diff --git a/.gitignore b/.gitignore index 5b02df8..08d5425 100644 --- a/.gitignore +++ b/.gitignore @@ -58,3 +58,4 @@ momentum-rebuilt.zip *.zip archive/ uv.lock +.firecrawl/ diff --git a/docs/ideation/2026-07-13-next-milestone-ideation.html b/docs/ideation/2026-07-13-next-milestone-ideation.html new file mode 100644 index 0000000..7fc5ae0 --- /dev/null +++ b/docs/ideation/2026-07-13-next-milestone-ideation.html @@ -0,0 +1,293 @@ + + + + + +Ideation: Next Enhancement Milestone — Momentum + + + +
+ +
Ideation · repo-grounded
+

Next Enhancement Milestone — Momentum

+ + +
+
48
raw ideas · 5 frames
+
14
merged candidates
+
14/14
verified sound (fresh-context spot-checks)
+
7
survivors · 5/5 axes covered
+
+ +

Grounding Context

+

Codebase context. Event-sourced small-cap momentum day-trading system (gap-and-go / opening-range breakout). Alpaca paper account over the SIP feed; single PostgreSQL datastore (append-only events table + projections, ~19M minute bars); production is a Docker Compose stack on TrueNAS SCALE (postgres 18, trading loop, dashboard :8765, admin :8767, telegram bot, nightly scheduler); 376 pytest tests against throwaway mem_* schemas. Solo owner-operator.

+

Grounding came from an 8-agent recon sweep (2026-07-13) that read every subsystem — live loop, strategy, storage, research/data, dashboard, ops/deploy, brokers, tests — and produced ~95 evidence-cited findings, plus the in-repo external research pass docs/research/entry_conversion_research.md (academic + backtest literature on breakout entry conversion, with a ranked experiment shortlist). A fresh-context verifier then spot-checked every load-bearing claim against HEAD with ~25 targeted reads; every checked citation matched.

+

Settled constraints honored throughout: the validated entry population stays ($2–20, static open gap 10–35%, real volume, ≥150%-gap & rvol≥5 squeeze exception); seven selection levers are refuted at year scale and are not re-proposed; scale-out partials and retest/pullback entries are refuted; the :8765 dashboard is the only UI to extend; the system's proven bottleneck is entry-conversion, not selection.

+ +

Topic Axes

+ + +

Ranked Ideas

+
+
Jump to
+
    +
  1. Experiment OS — pre-registered, auto-adjudicated counterfactual experiments over logged fires
  2. +
  3. Learning-flywheel resurrection — one population function + scheduled tune/replay
  4. +
  5. Entry-path unification + decision receipts
  6. +
  7. Money-path hardening — self-restart, positive-evidence contract, EOD cage count
  8. +
  9. Production safety rails — CI gate, dead-man's switch, automated backup
  10. +
  11. Operator control plane — dashboard repair, kill switch, effective-config panel
  12. +
  13. Dead-weight deletion sweep — every table names its reader or dies
  14. +
+
+ +
+

1. Experiment OS — pre-registered, auto-adjudicated counterfactual experiments over logged fires

+
entry-conversionConfidence 75%Complexity High
+
+
Description
+
One parametric experiment harness replacing the four hand-built shadow-track triples in research/labeler.py (vwap_reclaim / runner / liquid / premarket — ~1,467 lines of structurally near-identical build/report/validate code). An experiment becomes a config row: population, intervention (an entry or exit policy variant), pre-registered pass/fail bars, minimum n, and futility criteria. A replay engine runs every logged live fire counterfactually against its recorded bar path — the Tesla shadow-mode pattern — including a counterfactual exit ledger (every real trade re-run under each exit variant). A verdict engine auto-adjudicates at the pre-registered thresholds (the clinical-trial DSMB pattern, with futility stops) and emits PASS / FAIL / INCONCLUSIVE verdict events that flow to Telegram and a dashboard experiment-ledger panel. First cohort ships with the harness: the three literature-backed entry-conversion experiments (idea card behind them in docs/research/entry_conversion_research.md): time-boxed entries + 10-minute time-stop on unconfirmed positions, probe-then-add 0.5×+0.5× sizing, asymmetric exit (volatility-fractional stop with a spread floor, no target, trail to EOD) — plus the rank-concentration "one-bullet" counterfactual and an immediate adjudication of pm1.
+
Basis
+
direct: data/premarket_eval_history.tsv latest row (2026-07-09) shows pm1 at n=2377 with rate_1r=0.443 vs the pre-registered >0.50 bar and median_up_60m=0.0433 vs the ≥0.10 bar — failing 3 of 4 pre-registered criteria while the code's own docstring still frames it as "n=21 is far too small… watch n climb". Seven prior levers each required a human to notice a threshold crossing in a log file. external: the three first-cohort experiments carry academic + replicated-backtest support (Zarattini/Barbon/Aziz SSRN 4729284, Osler NY Fed SR150, Mesfin arXiv 2605.04004) per the in-repo research doc. Verifier confirmed none of the harness/experiment machinery exists yet.
+
Rationale
+
The system's bottleneck is proven to be entry-conversion, and the three highest-priority interventions are already researched, pre-registered, and testable for free against fires the system has already logged — zero live risk. The blocker is machinery, not ideas: every new experiment today costs a hand-built ~300-line triple plus a human reading a TSV. Build the machinery once and every future experiment (premarket module included) drops to a config row with an automatic verdict.
+
Downsides
+
Biggest build in the set; replay fidelity is a real risk (fills, spreads, halts must be modeled honestly — the tight-stop zero-slippage artifact has already fooled two shadow tracks here, so the harness must enforce adverse-fill floors by construction). Requires the population module from idea 2 to avoid baking look-ahead into every experiment.
+
+
+ + + + Logged fires + + recorded bar paths + + Experiment configs + population · policy · bars · n + + Replay engine + counterfactual P&L per fire + + Verdict engine + pre-registered bars · futility + + Telegram ping + PASS / FAIL / INCONCLUSIVE + + Ledger panel + :8765 dashboard + + + + + + +
Every logged fire becomes reusable evidence; every experiment becomes a config row with an automatic verdict.
+
+
+ +
+

2. Learning-flywheel resurrection — one population function + scheduled tune/replay

+
learning-flywheelConfidence 90%Complexity Medium
+
+
Description
+
Extract the live population gate into one shared pure module with an as-of-time contract (open-knowable inputs only: static open gap, price band, premarket-knowable volume, squeeze exception) and make every offline consumer — learn_params.py, the sweeps, eod_replay.py, the labeler — consume it instead of re-implementing it. Then actually schedule the flywheel in production: eod_replay after each close (unbiased whole-market dataset growth), nightly_tune after it (atomic tmp+rename write, staleness alert if learned_params.json ages past 2 days).
+
Basis
+
direct: verifier-confirmed at HEAD: the TrueNAS scheduler runs only research.premarket_eval; data/learned_params.json is stamped as_of 2026-06-17 — 26 days stale — while the boot log still claims self-tuning; learn_params.py:61,64 admits day-end day_rvol (outcome-time look-ahead); eod_replay.py:44-48 screens $1–5 under a "live verified config" comment while production trades $2–20 (truenas-compose.yml:105-106); eod_replay.sh points at a dead venv path; nightly_tune.py:91-92 writes non-atomically.
+
Rationale
+
The project memory says "nightly_tune self-tunes params, applied on boot" — that story is currently fiction in production, and the offline population drift means even a re-enabled tuner would fit a universe the bot doesn't trade. This is the data-integrity substrate under idea 1: experiments adjudicated against a look-ahead population are worthless. The owner has already been burned twice by exactly this class (the 2026-07-08 look-ahead correction).
+
Downsides
+
Population-module extraction touches the live gate — needs characterization tests before refactor. A deliberate alternative is to delete the tuner and stop claiming self-tuning; the wrong option is the current silent limbo.
+
+
+ + + TODAY: 5 diverging copies + live gate — $2–20, open gap + tuner — day-end rvol (look-ahead) + eod_replay — $1–5, no squeeze + sweeps · labeler — own filters + TARGET: one as-of-time module + + population.py + open-knowable inputs only + live gate + tuner + sweeps + eod_replay (scheduled) + labeler / Experiment OS + + + + + +
Every backtest, tune, and experiment verdict becomes trustworthy by construction when all consumers share the live gate.
+
+
+ +
+

3. Entry-path unification + decision receipts

+
money-path-correctnessConfidence 85%Complexity Medium
+
+
Description
+
Collapse the two drifted entry paths — slow auto-approval (request_approvals_for_ready_signals) and fast trigger (submit_breakout_now) — onto one shared pure gate function. Every gate evaluation emits a compact decision receipt event (gate name, inputs, pass/fail), so "why did/didn't it trade X?" becomes a query instead of a forensic session.
+
Basis
+
direct: verifier-confirmed: _population_reject/_outside_session/_anti_chase_skip are already shared by both paths, but the VWAP check exists only in the slow path (~trading_execution.py:938) and rank_risk_factor only in the fast path (:1228); the boot log itself warns "rank-concentration is enforced ONLY on the dead fast-trigger path, NOT the live auto-approval path" (run_live_paper.py:1026-1028). The daily-cap counted 44-vs-5 incident (fixed ac1ac50) was this same drift class.
+
Rationale
+
Half the convergence is already done — this finishes it so every future gate (including any Experiment-OS winner promoted to live) lands on both paths by construction. Receipts double as the raw material Experiment OS replays and the operator reads on the dashboard.
+
Downsides
+
Touches the live money path — needs the CI gate (idea 5) and characterization tests first. Receipt events add volume to the events table (bounded; they replace ad-hoc diagnostic events that retention already prunes).
+
+
+ +
+

4. Money-path hardening — self-restart, positive-evidence contract, EOD cage count

+
money-path-correctnessConfidence 95%Complexity Low
+
+
Description
+
Three small, high-severity fixes sharing one principle — never act on assumed state. (a) Daily self-restart: exit(0) after a successful EOD flatten and let compose's restart: unless-stopped resurrect a fresh process — the process is the trading session. (b) Positive-evidence contract: no destructive market action on an ambiguous broker read — the exit manager must distinguish "orders call failed / silently empty" from "position confirmed naked" before market-flattening, and a lost order-POST must reconcile via client_order_id lookup before journaling "cancelled". (c) EOD cage count: a nightly reconcile that diffs broker positions/orders/fills against event-store truth and alerts on any discrepancy, plus SIGTERM handled as clean shutdown (docker stop currently skips the shutdown path).
+
Basis
+
direct: verifier-confirmed: _eod_done/_catchup_done (run_live_paper.py:1064,1113) and _session_closed/_daily_loss_breach (trading_execution.py:398,612) never reset — an uninterrupted day-2 takes zero entries and has no EOD flatten, masked today only by frequent redeploys; exit_manager.py:71-72 returns None on any exception and treats it identically to "naked", flattening after ~24s grace; execution.py:124-129 journals lost POSTs as cancelled with no reconcile (no by_client_order_id method exists in the client); the 2026-07-06 duplicate-resting-order incident is corroborated by d54a2a9's own commit message; recovery-on-boot (_rebuild_daily_state) already exists and is tested.
+
Rationale
+
Highest severity-to-effort ratio in the whole set. (a) alone converts an entire recurring bug class (session gate, after-hours submissions, bench state — each patched separately before) into a non-issue by construction, in ~5 lines plus tests.
+
Downsides
+
Self-restart must fire only after a successful flatten (exit-on-failure would orphan positions — though broker-side stop legs keep them protected); the positive-evidence branch adds one more state to exit-manager logic that is already subtle.
+
+
+ +
+

5. Production safety rails — CI gate, dead-man's switch, automated backup

+
operability-deliveryConfidence 95%Complexity Low
+
+
Description
+
The "vacation test" bundle: (a) CI runs the 376-test suite (plus ruff check --select F for the untested script layer) before the image workflow pushes :latest to GHCR/Docker Hub; (b) the always-up qabot container gets a dead-man's switch — alert when the event-store heartbeat goes stale during market hours, plus a nightly OK-ping (the loop can't report its own death; the qabot is the independent observer); (c) a scheduled pg_dump (or documented ZFS snapshot task) — production currently has no automated backup.
+
Basis
+
direct: verifier-confirmed: .github/workflows/docker.yml has zero test step and ships on every master push; api/main.py at HEAD references os/hmac without importing them (AST-confirmed) — an untested regression that already shipped; loop-down currently means alerts-down (the notifier lives inside the loop process, run_live_paper.py:1034); pg_dump appears only in the one-time migration script.
+
Rationale
+
This is the lever that makes every other lever safe to ship. Every subsequent idea in this list lands as an image push; today each push is an untested bet against the production money path.
+
Downsides
+
CI needs a Postgres service container for the suite (~3–4 min per push). Dead-man thresholds need market-calendar awareness to avoid weekend false alarms — the holiday-aware calendar already exists in runtime/market_calendar.py.
+
+
+ +
+

6. Operator control plane — dashboard repair, kill switch, effective-config panel

+
operator-surfaceConfidence 85%Complexity Medium
+
+
Description
+
Make the production :8765 surface tell the truth and accept commands. Repairs: fix the POST NameError (unimported os/hmac); wire the research DB into the standalone dashboard so sparklines work in production; gate action buttons on the has_execution flag the API already ships; derive the LIVE badge from broker truth (it currently keys on a schwab_live literal the admin go-live flow never sets — it would read PAPER while trading real money). Capability: manual flatten (all / per-symbol) and pause-entries as guarded operator-command events through the store — the loop polls its own 5s guard cadence and executes with the existing cancel_protective_and_close helper; dashboard and qabot become thin command emitters. Efficiency: replace the per-client per-second fresh-connection + full-DDL + COUNT(*) SSE change detector with one shared cached signal. Visibility: an effective-config panel showing the merged config per service with per-key provenance (baked env → compose env → overrides.env → learned params) and drift-vs-inventory warnings.
+
Basis
+
direct: verifier-confirmed: telegram_bot.py:29 hard-refuses action words; dashboard_api.py:36 builds the production dashboard with execution_service=None — no manual flatten path exists anywhere in the production UI; dashboard.html:1061 keys LIVE on schwab_live while admin_api.py:276-295 only swaps Alpaca URL/keys; SSE poll confirmed at api/main.py:355; concurrency-gauge default drift (3 vs 6) confirmed at trading_execution.py:75 vs projections.py:869.
+
Rationale
+
The operator's two moments of need — "something is wrong, get me flat NOW" and "what is this thing actually running?" — both currently require shelling into a container. Command-as-event reuses the store as the bus (no new API surface into the loop) and leaves an audit trail by construction.
+
Downsides
+
A kill switch is a live-money control: needs HMAC/token guard, idempotency, and a test that a replayed or stale command cannot re-fire. Command latency is bounded by the 5s guard cadence (acceptable; broker stops remain the fast layer).
+
+
+ +
+

7. Dead-weight deletion sweep — every table names its reader or dies

+
operability-deliveryConfidence 90%Complexity Low
+
+
Description
+
Finish the deletion d54a2a9 claimed: schwab/ is still fully tracked (23 files) despite the commit message. Then the rest of the confirmed-dead surface: comprehensive_backtest.py (crashes on import — research/connection.py doesn't exist), strategy/regime.py, universe.py, backtest/outcomes.py, the ignition detector, the grafana/ stack (points at the decommissioned pre-migration DB with committed plaintext dev credentials), the telemetry/ husk, docker-publish.yml (fires on a nonexistent main branch, pushes a wrong image name), stale uv.lock, the empty test_alpaca_client.py, 12 zero-reference tables and 6 dead projections. Standing rule going forward: every table names its reader or dies — quote_snapshots gets retention or deletion; float_cache/dilution_events get wired into the labeler's features or stop being collected nightly.
+
Basis
+
direct: verifier-confirmed each item at HEAD, including git ls-files schwab/ (23 tracked files) vs d54a2a9's message, the import crash, the grafana datasource credentials, and grep-confirmed zero readers for the write-only tables.
+
Rationale
+
Every dead artifact taxes every future session ("which one is real?") and the grafana credentials are a small standing security smell. Deletion is the cheapest enhancement in the set and makes every subsequent plan smaller.
+
Downsides
+
The schwab/ decision should be explicit (its only non-delete rationale is the dormant human-vs-bot comparison); deleting tables needs a backup first (idea 5c) and a one-session soak.
+
+
+ +

Rejection Summary

+

Nothing was refuted: the fresh-context verifier confirmed all 14 merged candidates sound, and all 48 raw ideas were absorbed into the 7 survivors. The table records the merges and the judgment calls.

+
+ + + + + + + + + + + + + + +
#IdeaDisposition
1Daily self-restart (raw #1, 9, 18, 25, 33 — five frames converged independently)Merged into survivor 4a — strongest single convergence in the run
2Broker-ambiguity fixes / MCAS rule / "empty is not naked" (raw #2, 26, 37)Merged into survivor 4b as one shared contract
3EOD cage-count reconciliation (raw #27)Folded into survivor 4c — thinnest-sourced candidate (analogy + one past incident); kept as backstop, not standalone
4Verdict watchdog / DSMB / experiment ledger / experiment-as-config / Tesla shadow mode / counterfactual exit ledger (raw #4, 13, 22, 30, 34, 43, 44)Merged into survivor 1 (Experiment OS) — the run's flagship synthesis
5Entry-conversion shortlist experiments (raw #5, 38) and one-bullet rank counterfactual (raw #48)Merged into survivor 1 as the first experiment cohort
6Population parity / flywheel scheduling / "replay whole market nightly" (raw #3, 11, 12, 20, 21, 28, 35, 47)Merged into survivor 2
7Kill switch variants: qabot /flatten, fire handle, command-bus events (raw #8, 15, 32, 36)Merged into survivor 6 — command-as-event chosen as the unifying mechanism
8LISTEN/NOTIFY dashboard change signal (raw #16)Demoted to implementation option inside survivor 6 — shared cached signal may be enough (lazy option first)
9Effective-config panel (raw #46)Merged into survivor 6
10CI gate / vacation test / eye-in-the-sky (raw #6, 7, 17, 31, 41, 42)Merged into survivor 5
11Deletion sweeps (raw #14, 24, 39)Merged into survivor 7
—Axis coverageAll five axes have survivors; no recovery dispatch was needed
+
+ + +
+ + diff --git a/docs/ideation/momentum-architecture-current.drawio b/docs/ideation/momentum-architecture-current.drawio new file mode 100644 index 0000000..ed6796a --- /dev/null +++ b/docs/ideation/momentum-architecture-current.drawio @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/ideation/momentum-architecture-current.png b/docs/ideation/momentum-architecture-current.png new file mode 100644 index 0000000..a27feb5 Binary files /dev/null and b/docs/ideation/momentum-architecture-current.png differ diff --git a/docs/ideation/momentum-milestone-featureset.drawio b/docs/ideation/momentum-milestone-featureset.drawio new file mode 100644 index 0000000..6871cf4 --- /dev/null +++ b/docs/ideation/momentum-milestone-featureset.drawio @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/ideation/momentum-milestone-featureset.png b/docs/ideation/momentum-milestone-featureset.png new file mode 100644 index 0000000..8ac81af Binary files /dev/null and b/docs/ideation/momentum-milestone-featureset.png differ diff --git a/plans/001-production-safety-rails.md b/plans/001-production-safety-rails.md new file mode 100644 index 0000000..83eaae2 --- /dev/null +++ b/plans/001-production-safety-rails.md @@ -0,0 +1,209 @@ +# Plan 001: Gate every production image on the test suite, and make loop-death and data-loss impossible to miss + +> **Executor instructions**: Follow this plan step by step. Run every +> verification command and confirm the expected result before moving to the +> next step. If anything in the "STOP conditions" section occurs, stop and +> report — do not improvise. When done, update the status row for this plan +> in `plans/README.md`. +> +> **Drift check (run first)**: `git diff --stat d54a2a9..HEAD -- .github/workflows/ telegram_bot.py docker-compose.yml deploy/docker/truenas-compose.yml` +> If any in-scope file changed since this plan was written, compare the +> "Current state" excerpts against the live code before proceeding; on a +> mismatch, treat it as a STOP condition. + +## Status + +- **Priority**: P1 +- **Effort**: S +- **Risk**: LOW +- **Depends on**: none +- **Category**: dx / tests / ops +- **Planned at**: commit `d54a2a9`, 2026-07-13 + +## Why this matters + +Production is a Docker Compose stack on TrueNAS that pulls `:latest` from a registry. Today `.github/workflows/docker.yml` builds and pushes that image on **every master push with zero test run** — and the repo has 376 passing tests sitting unused in CI. This already bit: `api/main.py` at HEAD references `os` and `hmac` without importing them, so every dashboard POST endpoint crashes with `NameError` in production (fixed separately in plan 007). Additionally: if the trading loop dies, nothing notices (the Telegram alerter lives *inside* the loop process — loop-down means alerts-down), and the production Postgres has **no automated backup** (`pg_dump` appears only in the one-time migration script). This plan is the lever that makes every other plan safe to ship. + +## Current state + +- `.github/workflows/docker.yml` — builds + pushes `ghcr.io/fez5587/momentum-app:latest` and `fez5587/momentum-app:latest` on every master push. The `jobs:` block contains exactly one job (`build`) with checkout → two docker logins → `docker/build-push-action@v6`. **No test step exists.** +- `tests/` — 376 tests collected. They need a reachable Postgres and isolate via throwaway `mem_*` schemas (`tests/conftest.py` sweeps them at session end). Invocation per `README.md:112`: + ```bash + DATABASE_URL=postgresql://user:pass@host:5432/momentum python -m pytest + ``` +- `telegram_bot.py` — a **separate always-up container** (`docker-compose.yml:91-96`, service `qabot`; `restart: unless-stopped` inherited from the `x-app` anchor at `docker-compose.yml:27`) with its own EventStore access. It answers questions but never checks whether the loop is alive. `telegram_bot.py:219-220`: + ```python + def is_authorized(chat_id, allowed) -> bool: + return allowed is not None and str(chat_id) == str(allowed) + ``` +- The loop's own notifier is in-process: `run_live_paper.py:1033-1034` (`notifier = TelegramNotifier(rt["store"])`) — it cannot report the loop's own death. +- Heartbeat truth lives in the event store: `RUNBOOK.md:31` — `SELECT max(timestamp) FROM events;` should be < ~2 min old during any market hour. Timestamps are **ET-naive** (`RUNBOOK.md:34-36`) — compare against ET wall clock, not UTC. +- Market-hours awareness already exists: `runtime/market_calendar.py` (holiday-aware, hardcoded 2026/27 NYSE calendar). +- Backups: `grep -rn "pg_dump" --include="*.sh" --include="*.yml" .` → the one-time `deploy/docker/migrate_db.sh` plus one comment at `docker-compose.yml:9`. **The app image has NO pg_dump binary** (`Dockerfile` is `FROM python:3.13-slim` installing only runtime libs), and the server is `postgres:18` — a Debian-stock `postgresql-client` is an older major and `pg_dump` refuses to dump a newer server. So the backup must run with a version-matched client (the `postgres:18` image itself — step 3). The scheduler service (`docker-compose.yml:119-140` and `deploy/docker/truenas-compose.yml:~190`) is a `while true` shell loop that fires `python -m research.premarket_eval` at 20:00 ET Mon–Fri: + ```yaml + if [ "$$(date +%H:%M)" = "20:00" ] && [ "$$(date +%u)" -le 5 ]; then + echo "[scheduler] premarket_eval $$(date)" + python -m research.premarket_eval || echo "[scheduler] eval FAILED" + ``` +- Dead duplicate workflow: `.github/workflows/docker-publish.yml` triggers on branches `main` and `claude/kubernetes-image-package-kkdkom` — **the repo has no `main` branch** (`git branch -a` shows only `master`), and it pushes a different image name (`momentum-system`) referenced only by the parked helm chart. Deleting it is plan 002's job; do not touch it here. + +## Commands you will need + +| Purpose | Command | Expected on success | +|---|---|---| +| Run tests locally | `DATABASE_URL= python -m pytest -q` | `376 passed` (±environmental skips) | +| Lint (new) | `ruff check --select F .` | exit 0 after step 2 | +| Validate workflow YAML | `python3 -c "import yaml,sys;yaml.safe_load(open('.github/workflows/docker.yml'))"` | exit 0 | + +## Scope + +**In scope** (the only files you should modify): +- `.github/workflows/docker.yml` +- `telegram_bot.py` +- `docker-compose.yml` (new `db-backup` service + qabot env only) +- `deploy/docker/truenas-compose.yml` (same) +- `deploy/docker/backup_db.sh` (create) +- `tests/unit/test_qabot_deadman.py` (create) +- `.env.example` (document new keys) +- `plans/README.md` (status row only) + +**Out of scope** (do NOT touch, even though they look related): +- `.github/workflows/docker-publish.yml` — dead; deleted in plan 002. +- `api/main.py` POST NameError — plan 007. +- `run_live_paper.py` / the loop's in-process notifier — plan 003 territory. +- Any change to how tests connect to Postgres (`tests/conftest.py`). + +## Git workflow + +- Branch: `advisor/001-production-safety-rails` +- Commit style: short imperative lowercase summary like the repo's log (`admin: degrade gracefully when …`). One commit per step. +- Do NOT push or open a PR unless the operator instructed it. + +## Steps + +### Step 1: Add a test job that gates the image push + +In `.github/workflows/docker.yml`, add a `test` job before `build` and make `build` depend on it (`needs: test`). The test job needs a Postgres service container: + +```yaml +jobs: + test: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:18 + env: + POSTGRES_USER: momentum + POSTGRES_PASSWORD: momentum + POSTGRES_DB: momentum + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U momentum" --health-interval 5s + --health-timeout 5s --health-retries 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: { python-version: "3.13" } + - run: pip install -r requirements.txt && pip install pytest ruff + - run: ruff check --select F . + - run: python -m pytest -q + env: + DATABASE_URL: postgresql://momentum:momentum@localhost:5432/momentum + build: + needs: test + ...existing job unchanged... +``` + +The Dockerfile base is `FROM python:3.13-slim` (Dockerfile:8) — keep CI matched to it. If `requirements.txt` does not install `pytest`, keep the explicit `pip install pytest`. + +**Verify**: `python3 -c "import yaml;d=yaml.safe_load(open('.github/workflows/docker.yml'));assert d['jobs']['build']['needs']=='test';assert 'services' in d['jobs']['test']"` → exit 0. + +**Verify** (after push to a branch, if operator allows): the Actions run shows `test` before `build`. + +Note: `ruff check --select F .` may fail on pre-existing dead code (plan 002 deletes `comprehensive_backtest.py`, which crashes on import but is import-dead, not an F-level error necessarily). Run it locally first; if pre-existing F errors exist that this plan must not fix, scope ruff to the money path instead: `ruff check --select F run_live_paper.py trading_execution.py api/ alpaca_paper/ runtime/ storage/ strategy/ research/` and record the exclusions in the workflow comment. + +### Step 2: Dead-man's switch in the qabot + +In `telegram_bot.py`, add a background check to the existing poll loop (the bot already polls Telegram every few seconds and has an EventStore): every 120s, read `SELECT max(timestamp) FROM events` (use the existing EventStore/projection helper if one surfaces max timestamp; otherwise a raw query through its existing connection). Convert to ET-naive comparison (the column is ET-naive per RUNBOOK). Alert conditions: + +- **During regular market hours** (use `runtime/market_calendar.py` — reuse its is-open helpers; do NOT re-implement holidays): if `now_et - max_ts > DEADMAN_STALE_MIN` (env, default 5 minutes), send ONE Telegram message: `⚠️ DEAD-MAN: no events for N min during market hours — loop may be down.` Re-alert at most every 30 min (keep a `last_alerted` timestamp in memory). +- **Nightly OK-ping** (env `DEADMAN_DAILY_PING=1` default on): once per day at first check after 20:30 ET, send `✅ heartbeat: loop wrote events today; last event .` (Do NOT report the backup marker file here — the qabot container does not mount the backups path; backup failures surface in the db-backup service logs.) + +Config keys: `DEADMAN_STALE_MIN`, `DEADMAN_DAILY_PING`. Document both in `.env.example` with one-line whys. + +**Verify**: `DATABASE_URL= python -m pytest tests/unit/test_qabot_deadman.py -q` → new tests pass (see Test plan). + +### Step 3: Scheduled pg_dump — runs in a `postgres:18` container, NOT the app image + +The app image has no `pg_dump` (see Current state), so the backup gets its own tiny service using the SAME image as the database server (version-matched client for free). + +1. Create `deploy/docker/backup_db.sh` (mirror the style of `deploy/docker/migrate_db.sh`): `pg_dump "$DATABASE_URL" | gzip > "$BACKUP_DIR/momentum-$(date +%F).sql.gz"`, prune backups older than `BACKUP_KEEP_DAYS` (default 14), write `$BACKUP_DIR/last_backup_ok` marker with timestamp on success. +2. Add a `db-backup` service to BOTH compose files (root `docker-compose.yml` and `deploy/docker/truenas-compose.yml`), modeled on the scheduler's shell-loop pattern but on the postgres image: + +```yaml + db-backup: + image: postgres:18 + restart: unless-stopped + environment: + DATABASE_URL: ${DATABASE_URL} + BACKUP_DIR: /backups + BACKUP_KEEP_DAYS: "14" + volumes: + - ./deploy/docker/backup_db.sh:/backup_db.sh:ro + - /backups:/backups + command: + - /bin/sh + - -c + - | + echo "[backup] up; will fire 20:10 ET Mon-Fri" + while true; do + if [ "$$(date +%H:%M)" = "20:10" ] && [ "$$(date +%u)" -le 5 ]; then + sh /backup_db.sh || echo "[backup] FAILED" + sleep 120 + fi + sleep 20 + done +``` + +Match each file's existing conventions for the data volume/dataset path and TZ env (the scheduler block shows both). Do NOT add pg_dump to the app image or the scheduler block. Document `BACKUP_DIR`/`BACKUP_KEEP_DAYS` in `.env.example`. + +**Verify** (version-matched client): `docker compose run --rm db-backup pg_dump --version` → `pg_dump (PostgreSQL) 18.x`. + +**Verify** (end-to-end, dev DB): `docker compose run --rm -e BACKUP_DIR=/backups db-backup sh /backup_db.sh && ls /backups/` → one `momentum-*.sql.gz` + `last_backup_ok`; `gunzip -t /backups/momentum-*.sql.gz` → exit 0. + +## Test plan + +- `tests/unit/test_qabot_deadman.py` (create; model structure on any existing `tests/unit/test_*.py` that stubs the EventStore — `tests/unit/test_notifier*.py` if present, else the simplest unit test in `tests/unit/`): + 1. stale heartbeat during market hours → alert function called once; + 2. stale heartbeat repeated within 30 min → no second alert; + 3. fresh heartbeat → no alert; + 4. stale heartbeat outside market hours (weekend date) → no alert. + Inject the clock and the send function; do not hit Telegram or Postgres (stub the max-timestamp read). +- Verification: `DATABASE_URL= python -m pytest -q` → full suite green, 4 new tests included. + +## Done criteria + +- [ ] `.github/workflows/docker.yml` has a `test` job with a postgres service; `build` has `needs: test` +- [ ] `ruff check --select F ` exits 0 locally +- [ ] `DATABASE_URL=… python -m pytest -q` exits 0 with the 4 new dead-man tests +- [ ] `deploy/docker/backup_db.sh` exists; `docker compose run --rm db-backup pg_dump --version` → 18.x; end-to-end run produces a valid gzip and the marker file +- [ ] Both compose files define the `db-backup` service +- [ ] `.env.example` documents `DEADMAN_STALE_MIN`, `DEADMAN_DAILY_PING`, `BACKUP_DIR`, `BACKUP_KEEP_DAYS` +- [ ] `git status` shows no modified files outside the in-scope list (which includes `plans/README.md`) +- [ ] `plans/README.md` status row updated + +## STOP conditions + +Stop and report back (do not improvise) if: + +- `docker.yml` at HEAD no longer matches the "one build job, no test step" shape. +- The test suite does not pass locally BEFORE your changes (pre-existing red ≠ yours to fix here; report it). +- `ruff check --select F` reports more than ~10 pre-existing errors even after scoping — the lint step then needs a human decision, not silent exclusions. +- `telegram_bot.py` has no clean place to hook a periodic check (e.g. its poll loop is blocking with no timeout) — report the structure you found instead of restructuring the bot. + +## Maintenance notes + +- The CI Postgres pin (`postgres:18`) should track the production compose image; if production upgrades, update both. +- The dead-man threshold assumes the loop writes at least one event every ~2 min during market hours (RUNBOOK's own invariant). If a future change makes quiet periods legitimate, raise `DEADMAN_STALE_MIN` rather than silencing the alert. +- Backup restore path is documented nowhere — a follow-up worth 10 lines in RUNBOOK.md: `gunzip -c … | psql $DATABASE_URL`. +- Reviewer should scrutinize: the ET-naive vs aware comparison in the dead-man check (the classic 4-hour-stale artifact, RUNBOOK.md:34). diff --git a/plans/002-dead-weight-deletion.md b/plans/002-dead-weight-deletion.md new file mode 100644 index 0000000..c44269e --- /dev/null +++ b/plans/002-dead-weight-deletion.md @@ -0,0 +1,146 @@ +# Plan 002: Delete the confirmed-dead surface — every module and table names its reader or dies + +> **Executor instructions**: Follow this plan step by step. Run every +> verification command and confirm the expected result before moving to the +> next step. If anything in the "STOP conditions" section occurs, stop and +> report — do not improvise. When done, update the status row for this plan +> in `plans/README.md`. +> +> **Drift check (run first)**: `git diff --stat d54a2a9..HEAD -- schwab/ grafana/ telemetry/ comprehensive_backtest.py strategy/ storage/pg_schema.sql .github/workflows/docker-publish.yml uv.lock milestone3_verify.py docker-compose.yml .env.example` +> Diffs introduced by plan 001 (db-backup service, workflow test job) are EXPECTED — see plans/README.md "Expected drift". +> If any in-scope file changed since this plan was written, compare the +> "Current state" excerpts against the live code before proceeding; on a +> mismatch, treat it as a STOP condition. + +## Status + +- **Priority**: P2 +- **Effort**: S +- **Risk**: LOW (deletion of verified-dead code; every deletion is grep-gated) +- **Depends on**: 001 (CI gate should exist so the post-deletion image is test-verified) +- **Category**: tech-debt +- **Planned at**: commit `d54a2a9`, 2026-07-13 + +## Why this matters + +Commit `d54a2a9`'s message claims "delete 805MB dead weight" including `schwab/` — but `git ls-files schwab/ | wc -l` returns **23 tracked files** at HEAD; the commit deleted `core/`, `models/`, `controlroom/` but not `schwab/`. Beyond that, the repo carries: a backtest runner that crashes on import, a grafana stack pointing at the decommissioned pre-migration database **with committed plaintext dev credentials**, an empty `telemetry/` husk, a dead CI workflow that fires on a nonexistent branch, a stale `uv.lock` from the DuckDB era, and write-only tables collected nightly and read by nothing. Every dead artifact taxes every future session with "which one is real?"; the grafana credentials are a standing security smell. + +## Current state (verified at HEAD, each with its evidence) + +| Target | Evidence | +|---|---| +| `schwab/` (23 files) + `tests/unit/schwab/` + `milestone3_verify.py` | `git ls-files schwab/ | wc -l` → 23. d54a2a9's own `--stat` contains zero schwab/ entries despite the message. The only live consumer risk: grep before deleting (step 1). README.md:187 still lists it as a live subsystem. | +| `comprehensive_backtest.py` | line 12: `from research.connection import ResearchConnection` — `research/connection.py` does not exist; the script crashes on import. | +| `strategy/universe.py`, `strategy/backtest/outcomes.py` | zero references outside their own files (verify with the step-1 grep). NOTE: recon also listed `strategy/regime.py` — **already deleted at HEAD**; do not look for it. | +| ignition detector | **partially dead only**: `detect_momentum_ignition` in `strategy/evaluation/ignition.py` has no consumers, but `_last_higher_low` from the same file IS imported by `strategy/evaluation/runner.py:33`, `premarket_setup.py:32`, and `liquid_breakout.py:44` (live via research/labeler). Disposition: delete only `detect_momentum_ignition` (+ its tests) after moving `_last_higher_low` into a shared evaluation helper — or leave the whole file and log it. Do NOT `git rm` ignition.py wholesale. | +| `grafana/` | `grafana/provisioning/datasources/momentum.yaml` hardcodes `192.168.1.5:5432` (the OLD pre-migration instance) with committed plaintext credentials (user/password in the YAML — reference only, do not copy values anywhere). The compose stack has its own optional Grafana; this standalone stack is a pre-compose leftover. | +| `telemetry/` | contains only `__pycache__` (stale .pyc): `ls telemetry/` → `__pycache__`. | +| `.github/workflows/docker-publish.yml` | triggers on `main` (branch does not exist — only `master`) and the stale artifact branch `claude/kubernetes-image-package-kkdkom` (exists only as a dormant origin remote), plus `v*` tags (none cut). Pushes image name `momentum-system` referenced only by the parked helm chart. | +| `uv.lock` | stale DuckDB-era lockfile contradicting `pyproject.toml`; Docker installs from `requirements.txt` (the real manifest). | +| `tests/unit/test_alpaca_client.py` | 0-byte file squatting the name of the biggest untested money-path module (plan 003 fills it — here, just do not delete it; leave for 003). | +| Write-only tables | `quote_snapshots` (fed 24/7 incl. weekends, no retention, no readers), `float_cache` + `dilution_events` (written nightly by the scheduler's cache refresh, zero readers). ~12 zero-reference tables total in `storage/pg_schema.sql` (DuckDB grand-plan residue) — the authoritative list is derived by the step-4 grep procedure, not assumed. | +| Dead projections | 6 zero-consumer functions in `storage/projections.py` (one with a latent wrong-answer bug per recon) — identify by the step-4 grep procedure. | + +## Commands you will need + +| Purpose | Command | Expected on success | +|---|---|---| +| Tests | `DATABASE_URL= python -m pytest -q` | all pass | +| Reference check | `grep -rn "" --include="*.py" --include="*.yml" --include="*.sh" --include="*.html" . | grep -v ` | empty before deleting `` | +| Import sanity | `python -c "import run_live_paper"` (needs env; alternatively `python -m pytest -q` covers it) | exit 0 | + +## Scope + +**In scope**: +- Deletions listed above (schwab/, tests/unit/schwab/, milestone3_verify.py, comprehensive_backtest.py, strategy/universe.py, strategy/backtest/outcomes.py, `detect_momentum_ignition` only per the evidence table, grafana/, telemetry/, .github/workflows/docker-publish.yml, uv.lock) +- `docker-compose.yml` (grafana dashboards bind-mount path only) + `deploy/compose/grafana/dashboards/` (moved provisioning files) +- `storage/pg_schema.sql` (remove dead CREATE TABLEs), `storage/projections.py` (remove dead functions) +- `README.md` (remove schwab/grafana rows from the repo map; fix "~130 tests" → actual count) +- `.env.example` (remove the SCHWAB_* keys that die with schwab/) +- `pyproject.toml` (remove deps only schwab/deleted code used — verify by grep) +- A new short `plans/002-deletions.log` listing every deleted path + the grep that cleared it (executor-written receipt) +- `plans/README.md` (status row only) + +**Out of scope**: +- DROPping tables in the **production database** — this plan only removes DDL from `pg_schema.sql` and code references. Actual `DROP TABLE` statements go into a "for the operator" section of the deletions log for the owner to run after a backup exists (plan 001) and a one-session soak. +- `tests/unit/test_alpaca_client.py` (empty file — plan 003 fills it) +- `alpaca_paper/` — live money path +- The optional Grafana service inside `docker-compose.yml` (only the standalone `grafana/` directory dies; its dashboards bind-mount is re-pointed in step 2, nothing else in the service changes) + +## Git workflow + +- Branch: `advisor/002-dead-weight-deletion` +- One commit per target group (schwab, strategy-dead, grafana+telemetry, workflows+lock, schema+projections) so any single group can be reverted. +- Do NOT push or open a PR unless the operator instructed it. + +## Steps + +### Step 1: Grep-gate and delete the module-level dead weight + +For EACH of: `schwab`, `milestone3_verify`, `comprehensive_backtest`, `strategy.universe` / `strategy/universe`, `backtest.outcomes` / `backtest/outcomes`, the ignition detector module name: + +```bash +grep -rn "" --include="*.py" --include="*.yml" --include="*.sh" . | grep -v "" | grep -v "^plans/" | grep -v "^docs/" +``` + +If the grep is empty (or only hits tests that test the dead module itself, or README prose), delete the target (and its tests). If it hits LIVE code (anything imported by `run_live_paper.py`, `trading_execution.py`, `api/`, `research/` runtime paths), STOP for that target and record it in the deletions log as "kept — live reference at ". Record every grep result in `plans/002-deletions.log`. + +Known wrinkle: `schwab` appears in `README.md`, `.env.example`, and possibly `momentum_cli.py` (`milestone3_verify` walk-through). CLI subcommands that only invoke deleted modules get removed too — grep `momentum_cli.py` for the module names. + +**Verify**: `DATABASE_URL= python -m pytest -q` → suite passes with schwab tests gone (count drops from 376; record the new count). + +### Step 2: Delete grafana/, telemetry/, docker-publish.yml, uv.lock + +**First, un-break the live bind-mount**: `docker-compose.yml:178` mounts `./grafana/provisioning/dashboards` into the in-compose grafana service this plan keeps. Move that directory to `deploy/compose/grafana/dashboards/` (next to the datasources dir already mounted at line 177) and update line 178 to the new path. Then: + +```bash +git rm -r grafana/ telemetry/ .github/workflows/docker-publish.yml uv.lock +``` + +The credentials inside `grafana/provisioning/datasources/momentum.yaml` were committed — note in the deletions log: "grafana dev credentials were committed to history; owner should rotate that Postgres user's password if the old instance is still running" (do NOT write the credential values anywhere). + +**Verify**: `grep -n "\./grafana/" docker-compose.yml` → empty. `git ls-files grafana/ telemetry/ | wc -l` → 0. `ls .github/workflows/` → only `docker.yml` (+ any unrelated workflows present at HEAD). `ls deploy/compose/grafana/dashboards/` → the moved provisioning files. + +### Step 3: Prune README + pyproject + +- README repo map: remove the `schwab/` row (find with `grep -n "^schwab/" README.md`, currently line 183); update the tests line (`grep -n "~130 tests" README.md`, currently line 113 → the count from step 1). +- `pyproject.toml`: remove dependencies used ONLY by deleted code (grep each candidate dep name across remaining `*.py` first; keep anything still imported). Do not touch `requirements.txt` unless a removed dep is listed there AND unused elsewhere (same grep gate). + +**Verify**: `DATABASE_URL= python -m pytest -q` → passes; `grep -n "schwab" README.md` → no repo-map row (prose mentions in history/docs sections are fine to leave). + +### Step 4: Dead DDL and dead projections + +Procedure (mechanical, grep-driven): + +1. List tables: `grep -oE "CREATE TABLE IF NOT EXISTS [a-z_]+" storage/pg_schema.sql | awk '{print $NF}' | sort -u` +2. For each table name: `grep -rn "" --include="*.py" . | grep -v pg_schema` — zero hits → dead. Remove its `CREATE TABLE` (and its indexes) from `pg_schema.sql`; append `DROP TABLE IF EXISTS
;` to the "operator section" of `plans/002-deletions.log`. +3. `quote_snapshots`, `float_cache`, `dilution_events` are written but not read. These are **explicitly NOT deleted here** — plan 006 wires `float_cache`/`dilution_events` into the experiment features, and `quote_snapshots` gets retention there. Note: only `dilution_events` has DDL in `pg_schema.sql` (leave it); `quote_snapshots` and `float_cache` are created by code (`run_live_paper.py`, `research/ingestion/float_cache.py`) — there is nothing to leave in the schema file, just log all three as "write-only, disposition in plan 006". +4. Projections: for each `def query_*` / public function in `storage/projections.py`: `grep -rn "(" --include="*.py" --include="*.html" . | grep -v projections.py` — zero hits → delete the function. Record each in the log. + +**Verify**: `DATABASE_URL= python -m pytest -q` → passes. `python -c "import storage.projections"` → exit 0. + +## Test plan + +No new tests — this plan is deletion. The gate is the existing suite staying green after every step, plus the grep receipts in `plans/002-deletions.log`. + +## Done criteria + +- [ ] `git ls-files schwab/ | wc -l` → 0 +- [ ] `ls grafana/ telemetry/ 2>&1` → both "No such file or directory" +- [ ] `test -f comprehensive_backtest.py || echo gone` → gone (same for `strategy/universe.py`, `strategy/backtest/outcomes.py`, `milestone3_verify.py`, `uv.lock`, `.github/workflows/docker-publish.yml`) +- [ ] `DATABASE_URL=… python -m pytest -q` exits 0 +- [ ] `plans/002-deletions.log` exists with one line per deletion (grep receipt) + the operator DROP section +- [ ] `git status` clean outside in-scope paths +- [ ] `plans/README.md` status row updated + +## STOP conditions + +- Any step-1 grep shows a LIVE reference to a deletion target — keep that target, log it, continue with the rest. +- The suite fails after a deletion and the failure is not obviously "test of deleted module" — revert that group's commit and report. +- `pg_schema.sql` table names don't match the grep-derived list shape (schema file drifted) — re-derive, and if >20 tables look dead, stop and report (that's a sign the grep is wrong, not the schema). + +## Maintenance notes + +- The standing rule this plan establishes: **every table names its reader or dies** — enforceable at review time by requiring any new `CREATE TABLE` PR to name its consumer. +- The operator DROP section in the deletions log should be run only after plan 001's backup lands and one trading session soaks. +- If the human-vs-bot comparison (the one non-delete rationale for schwab/) is ever revived, it returns as a fresh integration against current Schwab APIs — the deleted code was dormant scaffolding, not a working head start. diff --git a/plans/003-money-path-hardening.md b/plans/003-money-path-hardening.md new file mode 100644 index 0000000..593da12 --- /dev/null +++ b/plans/003-money-path-hardening.md @@ -0,0 +1,191 @@ +# Plan 003: Money-path hardening — the process is the trading session, and no destructive action fires on assumed state + +> **Executor instructions**: Follow this plan step by step. Run every +> verification command and confirm the expected result before moving to the +> next step. If anything in the "STOP conditions" section occurs, stop and +> report — do not improvise. When done, update the status row for this plan +> in `plans/README.md`. +> +> **Drift check (run first)**: `git diff --stat d54a2a9..HEAD -- run_live_paper.py trading_execution.py runtime/exit_manager.py alpaca_paper/ docker-compose.yml deploy/docker/truenas-compose.yml` +> Diffs introduced by plans 001–002 are EXPECTED — see plans/README.md "Expected drift". +> If any in-scope file changed since this plan was written, compare the +> "Current state" excerpts against the live code before proceeding; on a +> mismatch, treat it as a STOP condition. + +## Status + +- **Priority**: P1 +- **Effort**: M (S per fix, but this is the live money path — tests dominate) +- **Risk**: MED (touches live trading; every change is behind a test) +- **Depends on**: 001 (CI gate — do not ship money-path changes on an untested image) +- **Category**: bug / correctness +- **Planned at**: commit `d54a2a9`, 2026-07-13 + +## Why this matters + +Three verified defects share one root: acting on assumed state. + +1. **The loop is a one-trading-day machine run as a forever service.** A dozen memory-only flags are set once and never reset on date rollover — an *uninterrupted* day 2 of uptime takes ZERO entries and never EOD-flattens. This is masked today only by frequent redeploy restarts. +2. **The exit manager reads a failed/empty broker orders call as "position is naked"** and market-flattens a healthy, protected book after two 12s passes. The owner's own ops notes document Alpaca returning silently-empty symbol-scoped order lists. +3. **A lost order-POST is journaled as "cancelled" with no reconcile**, though the submit already carries a `client_order_id` and Alpaca exposes `GET /v2/orders:by_client_order_id`. The 2026-07-06 crash-restart duplicate-order incident is this class. + +Fix shape: (a) exit(0) after a successful EOD flatten and let compose restart a fresh process — the recovery half (`_rebuild_daily_state`) already exists and is tested; (b) positive-evidence contract before destructive actions; (c) reconcile-by-client_order_id before emitting `cancelled`; plus SIGTERM as clean shutdown and a nightly broker-vs-event-store reconcile. + +## Current state + +- `run_live_paper.py:1064` — `_eod_done = {"v": False}` created once in `main()`; `step_eod_flatten` (1066–1106) sets `_eod_done["v"] = ok` after `close_session` succeeds; **nothing ever resets it**. Same for `_catchup_done = {"v": False}` at 1113. +- `trading_execution.py:398` — `self._session_closed = False` set once in `__init__`; `close_session()` sets it True; no reset. `trading_execution.py:612`: + ```python + if self._halted or self._session_closed: + return True + ``` + (`_daily_loss_breach` → permanently True after EOD flatten, for the life of the process.) +- Recovery on boot already exists: `trading_execution.py:406-458` — `_rebuild_daily_state()` restores fresh-entry cap, requested-symbol dedup, and loss benches from today's events ("the 2026-07-06 incident" comment at 407-409). +- `docker-compose.yml:27` and `:54` — loop service `restart: unless-stopped` (a clean `exit(0)` restarts the container). +- No SIGTERM handler: cleanup lives only in `main()`'s `finally:` (run_live_paper.py:~1259) — `docker stop` (SIGTERM) kills the process without running it. +- `runtime/exit_manager.py:64-72`: + ```python + def _all_orders(self, symbols=None): + try: + return self.client.get_orders(status="all", limit=500, nested=True, + symbols=list(symbols) if symbols else None) + except Exception: # noqa: BLE001 + return None + ``` + and `_stop_leg` (74–90) returns `(None, None)` for BOTH `orders is None` (call failed) and a genuinely-empty list — downstream naked-stop enforcement (grace `enforce_stop_grace_passes=2` at ~12s cadence) can market-flatten via `_flatten` (92–98) on a transient API failure. +- `alpaca_paper/execution.py:99-129` — both exception paths call `self._emit_cancelled(request, …)` with zero lookup, despite `client_order_id=request.order_id[:48]` being sent at line 116. +- `alpaca_paper/client.py` — has `get_orders` (line 186) and `submit_order` (line 230); **no order-lookup-by-client-order-id method exists** (grep `by_client` → nothing). +- Alpaca API (verified 2026-07-13 against docs.alpaca.markets): `GET /v2/orders:by_client_order_id?client_order_id=` exists on `paper-api.alpaca.markets`. `GET /v2/orders` supports `after`/`until` (exclusive timestamps), `symbols`, `limit` (max 500), `nested`, and cursor params `after_order_id`/`before_order_id` (mutually exclusive with `after`/`until`). +- Repo conventions: money-path mutations behind the `TradingExecutionService` RLock (`@_locked`); events emitted via typed pydantic events (`storage/event_schema.py`); tests stub the Alpaca client (see `tests/unit/test_exit_manager*.py`, `tests/unit/test_execution*.py` for the stub pattern). +- `tests/unit/test_alpaca_client.py` — exists but is **0 bytes** (accidental empty file). + +## Commands you will need + +| Purpose | Command | Expected on success | +|---|---|---| +| Full suite | `DATABASE_URL= python -m pytest -q` | all pass | +| Targeted | `DATABASE_URL= python -m pytest tests/unit/test_exit_manager*.py tests/unit/test_execution*.py tests/unit/test_alpaca_client.py -q` | all pass | + +## Scope + +**In scope**: +- `run_live_paper.py` (EOD-exit + SIGTERM only) +- `trading_execution.py` (`_rebuild_daily_state` boot detection of today's eod_flatten — step 1 only) +- `runtime/exit_manager.py` (orders-snapshot sanity gate) +- `alpaca_paper/client.py` (add `get_order_by_client_order_id`; optional `after=` passthrough on `get_orders`) +- `alpaca_paper/execution.py` (reconcile on failure path) +- `research/eod_reconcile.py` (create — nightly cage count, step 5) +- `docker-compose.yml` (scheduler `command:` block only) and `deploy/docker/truenas-compose.yml` (same block) +- `tests/unit/test_alpaca_client.py` (fill), `tests/unit/` additions +- `.env.example` (new keys) +- `plans/README.md` (status row only) + +**Out of scope**: +- The entry gates / entry-path unification (plan 005) +- The dashboard/qabot kill switch (plan 007) +- Any change to bracket construction, sizing, or exit *policy* (trail/BE/catastrophe logic stays byte-identical) +- Compose restart policies and everything else in the compose files beyond the scheduler `command:` block (already correct) + +## Git workflow + +- Branch: `advisor/003-money-path-hardening` +- One commit per step; message style: `loop: exit(0) after successful EOD flatten — the process is the session`. +- Do NOT push or open a PR. + +## Steps + +### Step 1: Daily self-restart + +In `run_live_paper.py` `step_eod_flatten` (1066–1106): after the success branch (post `notifier.send_eod_summary(...)` try/except, before `return f"{tag} closed [{closed}]"`), add a gated clean exit: + +- Gate on env `TRADING_EXIT_AFTER_EOD_FLATTEN` (default `"1"`; document in `.env.example`: "the process is one trading session; compose restarts it fresh"). +- Log + telegram: `♻️ EOD flatten complete — exiting for daily restart (compose brings the loop back fresh).` +- Set a module-level `_clean_exit_requested` flag consumed by the main scheduler loop (do NOT call `sys.exit()` from inside the task — the per-task `try/except` in the scheduler would swallow `SystemExit` or leave threads wedged; instead break the main loop so the existing `finally:` cleanup runs, then `sys.exit(0)`). +- Only on `ok` (`not res["errors"]`) — a failed flatten must keep retrying inside the window exactly as today. + +Also handle the "already flat, nothing to close" EOD case identically (it is a successful flatten). + +**Testability requirement**: `step_eod_flatten` and `_eod_done` are closures inside `main()`, so put the new logic in a MODULE-LEVEL helper `_request_exit_after_eod(ok: bool) -> bool` (reads `TRADING_EXIT_AFTER_EOD_FLATTEN`, sets a module-level `_clean_exit_requested` flag, returns whether exit was requested) called from the closure's success branch; make the SIGTERM handler (step 2) module-level too. Tests target these module-level pieces directly. + +**Restart-churn guard (required)**: the exit fires INSIDE the EOD window, compose restarts within seconds, and the fresh process has `_eod_done=False` / `_session_closed=False` — without a guard it flattens-nothing, exits again, and churns until the window closes, un-blocking fresh entries between restarts. Fix in the same step: `_rebuild_daily_state` (trading_execution.py:412-458) must also detect today's already-emitted eod_flatten event (`close_session` emits a `RiskRuleTriggeredEvent` with `rule_type="eod_flatten"` — read `close_session` at HEAD for the exact payload) and set `self._session_closed = True`; and the loop's boot path must set `_eod_done["v"] = True` when that event exists for today (query it where `build_runtime` wires the store, or expose a small `execution.session_closed_today()` check the closure reads). Result: a post-flatten restart neither re-exits nor re-enters. + +**Verify**: `DATABASE_URL= python -m pytest tests/unit/ -k "eod" -q` → existing EOD tests pass + new test (Test plan #1) passes. + +### Step 2: SIGTERM = clean shutdown + +In `run_live_paper.py` `main()`, register `signal.signal(signal.SIGTERM, handler)` where handler sets the same `_clean_exit_requested` flag (reuse step 1's mechanism). `docker stop` then drains through the existing `finally:` block instead of being killed. + +**Verify**: start `python run_live_paper.py --once` in background, `kill -TERM` it, exit code 0 and the shutdown log line appears. (If `--once` exits before the signal, use the new unit test instead — Test plan #2.) + +### Step 3: Positive-evidence gate in the exit manager + +In `runtime/exit_manager.py`: + +1. Make `_all_orders` failure distinguishable: return a sentinel (e.g. the string `"FETCH_FAILED"` or a module-level `_FETCH_FAILED = object()`) instead of `None` on exception. +2. In the pass loop, when the snapshot is `_FETCH_FAILED`: **skip naked-stop enforcement entirely for this pass** (log once per N passes: `orders fetch failed — skipping naked enforcement this pass`). The catastrophe stop still runs — but note it is NOT orders-free: `manage()` derives `cur_stop` from `_stop_leg(sym, orders)` and its flatten path passes the snapshot into `self._flatten(sym, orders)`. Required sentinel semantics: `_stop_leg` must return `(None, None)` when given the sentinel (guard at the top — never iterate it); `catastrophe_triggered` then evaluates on the price/pct path only; and a catastrophe flatten during a failed-fetch pass must call `_flatten(sym, orders=None)` so `cancel_protective_and_close` re-fetches instead of consuming the sentinel. Accepted tradeoff (state it in the code comment): a true catastrophe (−10%/1.5×R breach) still flattens even when the stop status is unknowable — a deep-drawdown position is worse than a duplicate cancel. +3. When the snapshot is a real empty list while positions exist: require a **second consecutive** empty-but-successful read on the NEXT pass before counting a grace pass (two independent confirmations ≥12s apart). Track `_empty_snapshot_streak`. +4. Keep everything else byte-identical — the grace-pass count, `_ACTIVE` states, `_stop_leg` logic. + +**Verify**: `DATABASE_URL= python -m pytest tests/unit/test_exit_manager*.py -q` → existing + 3 new tests pass (Test plan #3–5). + +### Step 4: Reconcile-by-client_order_id before emitting cancelled + +1. `alpaca_paper/client.py`: add + ```python + def get_order_by_client_order_id(self, client_order_id: str): + return self._trading("GET", "/orders:by_client_order_id", + params={"client_order_id": client_order_id}) + ``` + The module's helpers are `_request` (line 107) and `_trading` (line 152) — `_trading` already prefixes `/v2`, so the path here carries NO `/v2` (the literal `:` in the path is correct). Match `get_orders` (line 186) for params/error conventions; TTL cache OFF for this call. Confirm `_trading`'s actual signature at HEAD before pasting. +2. `alpaca_paper/execution.py` generic-`Exception` branch (124–129) — the lost-response case: before `_emit_cancelled`, call `get_order_by_client_order_id(request.order_id[:48])`. If an order comes back with a live status (`new/accepted/pending_new/partially_filled/filled/held`), do NOT emit cancelled — emit the normal submitted event path with the recovered broker order id and return `ok=True`. If the lookup 404s or errors, emit cancelled as today (with `reason="submit error (reconcile: not found)"`). +3. The `AlpacaApiError` branch (118–123) is a real broker rejection — leave it as-is. + +**Verify**: `DATABASE_URL= python -m pytest tests/unit/test_alpaca_client.py tests/unit/test_execution*.py -q` → new tests pass (Test plan #6–8). + +### Step 5: Nightly cage count (broker vs event store) + +Create `research/eod_reconcile.py` (standalone, callable as `python -m research.eod_reconcile`): after the close, fetch broker truth — positions, and orders via `get_orders`. NOTE: the client wrapper's signature is `get_orders(status="all", limit=500, nested=True, symbols=None)` — it has NO `after` param today; the raw REST API does. Extend the wrapper with an optional `after=None` passthrough (client.py is in scope; one param, one line in the query dict) and call `get_orders(status="all", after=)`. Diff against event-store truth (today's `order_submitted`/`order_filled`/`position_closed` events — reuse the payload-parsing idiom from `_rebuild_daily_state`, trading_execution.py:412-446). Emit one summary event (`reconcile_ok` / `reconcile_mismatch` with the diff) and, on mismatch, a Telegram alert via the existing send helper. Wire it into the scheduler command blocks (both compose files) after `premarket_eval` — same pattern as plan 001's backup line. Keep it read-only (report, never auto-fix). + +**Verify**: `DATABASE_URL= python -m research.eod_reconcile` against a dev DB → prints a summary and exits 0 (with a stubbed/paper client configured). + +## Test plan + +New tests (stub the Alpaca client exactly as `tests/unit/test_exit_manager*.py` does; no network, no real DB writes beyond the mem-schema store): + +1. `test_eod_exit_flag` — targets the module-level `_request_exit_after_eod`: `ok=True` + flag on → exit requested; `ok=False` → not; flag off → not (monkeypatch the env var). +2. `test_sigterm_clean_exit` — the module-level SIGTERM handler sets the exit flag. +2b. `test_boot_after_eod_flatten` — with today's `eod_flatten` risk event in the store, a fresh `TradingExecutionService` boots with `_session_closed=True` (no re-entry, no re-exit churn). +3. `test_exit_mgr_fetch_failed_skips_naked` — orders fetch raises → no naked-enforcement flatten; catastrophe check still runs; `_stop_leg` given the sentinel returns `(None, None)`; a catastrophe flatten in that pass calls `_flatten(sym, orders=None)` (never the sentinel). +4. `test_exit_mgr_empty_needs_two_reads` — empty snapshot once → no grace increment; twice consecutively → grace path proceeds. +5. `test_exit_mgr_real_naked_still_enforced` — genuinely naked position with successful snapshot → flatten after grace passes (regression guard: the gate must not weaken real enforcement). +6. `test_client_by_client_order_id` — request path/params correct; 404 → raises/returns per module convention. +7. `test_execute_lost_response_recovers` — submit raises socket-ish `Exception`, lookup returns live order → no cancelled event, ok=True with recovered id. +8. `test_execute_lost_response_not_found` — lookup 404 → cancelled emitted as today. + +File placement: 3–5 in `tests/unit/test_exit_manager_sanity.py` (new), 6–8 fill the empty `tests/unit/test_alpaca_client.py` + `tests/unit/test_execution_reconcile.py` (new). Model structure on the closest existing test in the same directory. + +- Verification: `DATABASE_URL= python -m pytest -q` → full suite green, 9 new tests. + +## Done criteria + +- [ ] Full suite green with the 9 new tests +- [ ] `grep -n "TRADING_EXIT_AFTER_EOD_FLATTEN" .env.example run_live_paper.py` → present in both +- [ ] `grep -n "SIGTERM\|signal.signal" run_live_paper.py` → handler registered +- [ ] `grep -n "FETCH_FAILED\|_fetch_failed" runtime/exit_manager.py` → sentinel path exists +- [ ] `grep -n "by_client_order_id" alpaca_paper/client.py alpaca_paper/execution.py` → method + call site +- [ ] Scheduler blocks in both compose files call `research.eod_reconcile` +- [ ] `git status` clean outside in-scope list; `plans/README.md` updated + +## STOP conditions + +- Excerpts in "Current state" don't match HEAD (drift) — stop. +- The scheduler main loop's structure makes a clean "break out and run finally" exit impossible without restructuring beyond ~20 lines — report the structure instead of restructuring. +- Any existing exit-manager test asserts the CURRENT behavior of flattening on a failed fetch (i.e. the bug is enshrined) — stop and report; that test encodes a decision the owner must reverse explicitly. +- `orders:by_client_order_id` returns 404 for a *known-submitted* order in paper testing — the reconcile assumption is wrong; stop. + +## Maintenance notes + +- After this lands, a mid-day `docker restart` remains safe (state rebuild) and a quiet multi-day run becomes safe (daily fresh process). If anyone later adds state that must survive *within* a day, it must go through events + `_rebuild_daily_state`, not module globals — that is now the architectural rule. +- The two-consecutive-empty-reads gate adds up to ~12s latency to REAL naked-stop enforcement (one extra pass). That is the accepted cost; do not "optimize" it away without re-reading this plan's Why. +- Reviewer scrutiny: step 4's recovered-order path must emit the same event sequence as a normal submit (no divergent event shapes for downstream projections). +- Deferred: reconcile for `cancel_entry` false-positives (`ok=True` on failed DELETE) — smaller blast radius, fold into a later pass. diff --git a/plans/004-learning-flywheel.md b/plans/004-learning-flywheel.md new file mode 100644 index 0000000..3f7f6a0 --- /dev/null +++ b/plans/004-learning-flywheel.md @@ -0,0 +1,187 @@ +# Plan 004: Resurrect the learning flywheel on one shared, look-ahead-free population + +> **Executor instructions**: Follow this plan step by step. Run every +> verification command and confirm the expected result before moving to the +> next step. If anything in the "STOP conditions" section occurs, stop and +> report — do not improvise. When done, update the status row for this plan +> in `plans/README.md`. +> +> **Drift check (run first)**: `git diff --stat d54a2a9..HEAD -- learn_params.py nightly_tune.py eod_replay.py trading_execution.py research/labeler.py docker-compose.yml deploy/docker/truenas-compose.yml` +> On any in-scope drift, compare "Current state" excerpts before proceeding; +> mismatch = STOP. Diffs introduced by plans 001–003 are EXPECTED — see +> plans/README.md "Expected drift". + +## Status + +- **Priority**: P1 +- **Effort**: M +- **Risk**: MED (extracting the live population gate needs characterization tests first) +- **Depends on**: 001 (CI gate), 002 recommended (smaller surface) +- **Category**: correctness / research-integrity +- **Planned at**: commit `d54a2a9`, 2026-07-13 + +## Why this matters + +The project's own memory claims "nightly_tune.py self-tunes params into learned_params.json, applied on boot." **In production that is currently fiction**: the TrueNAS scheduler runs only `research.premarket_eval` (verified — one `python -m research.premarket_eval` line in the scheduler loop, nothing else), `data/learned_params.json` is stamped `as_of` 2026-06-17 (26 days stale at plan time), and `eod_replay` — the job that grows the whole-market forward dataset — is also unscheduled, so dataset growth is selection-biased to the ~20 names watched live. Worse, the offline population diverges from the live gate: the tuner admits sessions on **day-end** volume (outcome-time look-ahead, the exact class the owner corrected on 2026-07-08), and `eod_replay` screens $1–5 under a comment saying "the live verified config" while production trades $2–20. Every backtest, tune, and (future) experiment verdict is untrustworthy until all consumers share the live gate through one module. + +## Current state + +- Live gate (authoritative): `trading_execution.py` — `_population_reject(gap_pct, cum_volume, price=…, rvol=…)` (used by BOTH entry paths; slow path at ~910, fast path at ~1222). **Unit contract: `gap_pct` is a FRACTION** (0.12 = 12% — the function formats `{g:.1%}` and compares against 0.35/1.50 literals). Gates: static open gap ≥ `min_entry_gap_pct` (env `TRADING_MIN_ENTRY_GAP_PCT`, **code default "0.0"** at trading_execution.py:291 — production sets 0.10; the ENTIRE gap logic is nested inside `if min_entry_gap_pct > 0`), **dead band `0.35 < g < 1.50` and squeeze `g >= 1.50 and rvol >= 5.0` are HARDCODED literals in the function** (trading_execution.py:~813-816) — the `TRIGGER_GAP_MAX`/`TRIGGER_GAP_SQUEEZE_*` env keys configure the SEPARATE ArmedTriggerBook watcher gate (runtime/triggers.py), not this function — plus price band (`TRADING_PRICE_MIN/MAX`, defaults 2.0/20.0) and day-volume floor (`TRADING_MIN_DAY_VOLUME`, default 0.0). Read the function at HEAD before extracting — the excerpt here is the *shape*, not the code. +- Tuner population, `learn_params.py:56-65` (look-ahead): + ```python + gap = (float(bars["open"].iloc[0]) - pc) / pc if pc else 0.0 + day_rvol = (float(bars["volume"].sum()) / adv) if adv else 0.0 # full-day sum = outcome-time + ... + if not (gap >= 0.03 or day_rvol >= 2.0): + continue + ``` +- Replay population, `eod_replay.py:43-48` (stale + look-ahead): + ```python + # the live verified config + PRICE_MIN = float(os.environ.get("WATCHER_PRICE_MIN", "1")) + PRICE_MAX = float(os.environ.get("WATCHER_PRICE_MAX", "5")) + GAP_MIN = float(os.environ.get("TRIGGER_GAP_MIN", "3")) + GAP_MAX = float(os.environ.get("TRIGGER_GAP_MAX", "60")) + ``` + and `_daily_gappers` (52–76) filters on `t_close` (day-end price — look-ahead) with `GAP_MIN <= gap <= GAP_MAX` (no squeeze exception; hard cap excludes the >150% names production explicitly re-admits). Production values (deploy/docker/truenas-compose.yml env block): `TRADING_PRICE_MIN=2`, `TRADING_PRICE_MAX=20`. +- Non-atomic write, `nightly_tune.py:89-92`: + ```python + path = os.path.join(os.environ.get("DATA_DIR", "./data"), "learned_params.json") + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + with open(path, "w") as f: + json.dump(out, f, indent=2) + ``` +- Stale artifact: `data/learned_params.json` `as_of: 2026-06-17…` (26 days before plan date). Boot loads it best-effort (`_load_learned` in `run_live_paper.py` returns `{}` on any exception — silent). +- Scheduler: root `docker-compose.yml:119-140` and `deploy/docker/truenas-compose.yml` (~line 190) — shell loop firing `python -m research.premarket_eval` at 20:00 ET Mon–Fri (plus `eod_reconcile` if plan 003 landed; plan 001 adds a separate db-backup service — expected drift, not a mismatch). +- `eod_replay.sh` points at a dead venv path (`/home/philip/.venvs/momentum`) — cron-era wrapper, unused by compose. +- Convention: pure strategy logic lives in `strategy/` (import-clean, no env reads at import time); env parsing happens at construction (`ExitConfig.from_env()` pattern, `strategy/exits.py`). + +## Commands you will need + +| Purpose | Command | Expected | +|---|---|---| +| Suite | `DATABASE_URL= python -m pytest -q` | all pass | +| Targeted | `DATABASE_URL= python -m pytest tests/unit/strategy/ tests/unit/test_population*.py -q` | all pass | +| Replay smoke | `DATABASE_URL= python eod_replay.py ` | runs; population line printed | +| Tune smoke | `DATABASE_URL= python nightly_tune.py` | writes learned_params.json atomically (needs stored minute_bars — on an empty dev DB it returns early without writing; use the atomic-write unit test instead) | + +## Scope + +**In scope**: +- `strategy/population.py` (create — the shared module) +- `trading_execution.py` (delegate `_population_reject` internals to the module; behavior byte-identical) +- `learn_params.py`, `eod_replay.py` (consume the module) +- `nightly_tune.py` (atomic write + as_of staleness) +- Both compose scheduler blocks (add eod_replay + nightly_tune lines) +- `run_live_paper.py` (ONLY the `_load_learned` staleness warning — nothing else) +- `eod_replay.sh` (delete — dead venv path; compose is the runner) +- tests as listed +- `.env.example` (any new keys) + +**Out of scope**: +- Changing ANY gate threshold or the population definition itself — this plan moves code, it does not retune. +- The entry-path unification (plan 005) — this plan touches only `_population_reject`'s internals, not the gate call sites. +- The experiment harness (plan 006) — it becomes the module's 5th consumer later. +- sweep_exits.py / sweep_filters.py population (fold-in later; log as deferred). + +## Git workflow + +- Branch: `advisor/004-learning-flywheel` +- Commits: characterization tests → module extraction → consumer switches (one each) → scheduler wiring. +- Do NOT push or open a PR. + +## Steps + +### Step 1: Characterization tests for the live gate (BEFORE any extraction) + +New `tests/unit/test_population_gate.py`: table-driven cases pinning CURRENT `_population_reject` behavior — **all gap values as FRACTIONS** — in-band pass ($2–20, gap_pct=0.12, volume ok), below-gap reject (0.05 with min 0.10), dead-band reject (gap_pct=0.40), squeeze-exception pass (gap_pct=1.60, rvol 6), squeeze-rvol-fail reject (gap_pct=1.60, rvol 3), price-band rejects (both sides), volume-floor reject, missing-data fail-open (None gap/volume ⇒ pass), unit-pin case (gap_pct=0.40 → dead-band reject proves fraction semantics; a percent-passing caller would see 40.0 → squeeze-unverified reject instead), and gap-gate-disabled case (min_entry_gap_pct=0 ⇒ all gap checks skipped — the nesting). Drive via a minimally-constructed `TradingExecutionService` or by calling the private method on an instance built the way existing execution tests do it (copy their fixture). + +**Verify**: targeted pytest → all characterization tests pass against UNMODIFIED code. + +### Step 2: Extract `strategy/population.py` + +Create a pure module: + +```python +@dataclass(frozen=True) +class PopulationConfig: + price_min: float = 2.0 + price_max: float = 20.0 + min_entry_gap_pct: float = 0.0 # FRACTION; env TRADING_MIN_ENTRY_GAP_PCT (code default 0.0 — gap logic disabled at 0, matching live) + min_day_volume: float = 0.0 # env TRADING_MIN_DAY_VOLUME + # Hardcoded in the live gate — module CONSTANTS, no env read (do NOT wire TRIGGER_* keys here; those belong to the watcher gate): + gap_dead_band_lo: float = 0.35 + gap_dead_band_hi: float = 1.50 + squeeze_rvol_min: float = 5.0 + @classmethod + def from_env(cls): ... # reads ONLY TRADING_MIN_ENTRY_GAP_PCT, TRADING_PRICE_MIN/MAX, TRADING_MIN_DAY_VOLUME — same keys+defaults as trading_execution today + +def population_reject(cfg, *, gap_pct, price, volume, rvol, as_of="open") -> str | None: + """Return None if inside the tradeable population, else the reject reason. + UNIT CONTRACT: gap_pct is a FRACTION (0.12 = 12%), matching the live call + site (signal.get("gap_pct")). CONTRACT: every input must be knowable at + evaluation time (as_of="open" = static open gap, premarket/at-entry + volume). Day-end fields are forbidden.""" +``` + +Move the logic verbatim from `trading_execution._population_reject`; the service keeps a thin wrapper calling the module (its settings → `PopulationConfig`). Fail-open semantics preserved exactly. **Offline consumers must pass production thresholds explicitly** (e.g. `PopulationConfig(min_entry_gap_pct=0.10, min_day_volume=)`) — a bare `from_env()` in a shell without the production env has `min_entry_gap_pct=0.0`, which disables the whole gap gate and admits everything. + +**Verify**: full suite + step-1 characterization tests still green (they now exercise the extracted path through the same public seam). + +### Step 3: Switch the offline consumers + +- `learn_params.py:56-65`: replace the `gap >= 0.03 or day_rvol >= 2.0` admit with `population_reject(cfg, gap_pct=gap, price=, volume=, rvol=None) is None`. **`gap` at learn_params.py:60 is already a FRACTION — pass it as-is, do NOT multiply by 100.** Delete the `day_rvol` full-day sum from the admission path (it may remain as a *reported metric*, never a filter). Use production thresholds (`min_entry_gap_pct=0.10`). +- `eod_replay.py`: delete the `PRICE_*/GAP_*/RVOL_MIN` constants (**lines 43–48 only — KEEP `RISK_PCT` at line 49**, it is position sizing used at line 132, not population) and rewrite `_daily_gappers` to (a) filter on **open** price not `t_close`, (b) call `population_reject` — NOTE its local `gap` at line 72 is computed in PERCENT (`*100`): divide by 100 (or compute as a fraction) before the call, (c) therefore inherit the squeeze exception. Keep the daily-bars-first cheap scan structure. +- `research/labeler.py`: **dropped from this plan.** The labeler tracks have no locatable price/gap admission screen (they label all sessions and stratify post-hoc), and the premarket track's pre-9:30 semantics arguably should not use the open-gap gate. The labeler becomes the module's consumer via plan 006 (experiment populations); log as deferred alongside sweep_exits/sweep_filters. + +**Verify**: `python eod_replay.py ` on a stored session → runs, and its printed population is consistent with production values (a $15 name with 12% open gap now qualifies; a $4 name with 45% gap does not unless ≥150%+rvol5). Full suite green. + +### Step 4: Atomic write + staleness + +- `nightly_tune.py:89-92` → write `path + ".tmp"`, `json.dump`, `f.flush()`+`os.fsync`, `os.replace(tmp, path)`. +- `run_live_paper.py` `_load_learned`: after successful load, if `as_of` is older than `LEARNED_PARAMS_MAX_AGE_DAYS` (default 3), log a WARNING and send one Telegram note ("learned_params is N days stale — tuner not running?"). Load anyway (never block boot). + +**Verify**: `python nightly_tune.py` (dev DB) → file replaced atomically (`.tmp` absent after); unit test for staleness warning passes. + +### Step 5: Schedule the flywheel + +In BOTH compose scheduler blocks, after the `premarket_eval` line (and after plan 001/003 additions if present), add: + +```sh +python eod_replay.py || echo "[scheduler] eod_replay FAILED" +python nightly_tune.py || echo "[scheduler] nightly_tune FAILED" +``` + +Order matters: replay grows the dataset first, tuner fits after. Delete `eod_replay.sh` (dead venv path). Note in the commit message that 20:00 ET is after close — replay of "today" is complete data by then, and this is NOT look-ahead because replay is a labeling job, not a live gate. + +**Verify**: `grep -n "eod_replay FAILED\|nightly_tune FAILED" docker-compose.yml deploy/docker/truenas-compose.yml` → 2 hits per file (the bare script names also appear in the root compose's on-demand job blocks at lines ~151/158 — grepping those would pass vacuously). + +## Test plan + +- `tests/unit/test_population_gate.py` (step 1, ~9 characterization cases) — the load-bearing file. +- `tests/unit/strategy/test_population_module.py`: module-level — `from_env` defaults match production keys; `as_of` contract docstring exists; day-end input rejection is by-convention (document, don't runtime-enforce). +- `tests/unit/test_nightly_tune_atomic.py`: tmp+replace write (tmp absent after; content valid JSON); staleness warning fires at >3 days (inject clock). +- Verification: `DATABASE_URL=… python -m pytest -q` → green, ~14 new tests. + +## Done criteria + +- [ ] `strategy/population.py` exists; `grep -n "population_reject" trading_execution.py learn_params.py eod_replay.py` → all three consume it +- [ ] `grep -n "volume.*sum()" learn_params.py` → not in the admission path +- [ ] `grep -n "WATCHER_PRICE_MIN\|TRIGGER_RVOL_MIN" eod_replay.py` → gone +- [ ] `grep -n "os.replace" nightly_tune.py` → atomic write present +- [ ] Both compose scheduler blocks run replay + tune; `test -f eod_replay.sh` → absent +- [ ] Full suite green including characterization tests +- [ ] `plans/README.md` updated + +## STOP conditions + +- `_population_reject` at HEAD contains logic not describable by the PopulationConfig fields above (the gate grew) — extend the characterization tests FIRST, then re-plan the extraction; report before proceeding. +- Characterization tests reveal the live gate's fail-open behavior differs from the recon description — pin actual behavior, report the difference, do not "fix" it here. +- The stored daily/minute data cannot supply an open-knowable volume proxy for the tuner admission — pass volume=None (fail-open) and REPORT it prominently; do not silently substitute day-end volume. +- eod_replay smoke run diverges wildly (e.g. 10x more qualifying names than the live day watched) — report the count delta before scheduling it. + +## Maintenance notes + +- `strategy/population.py` is now the ONLY place the tradeable population is defined. Any future lever test (plan 006 experiments) must consume it with an explicit `as_of` argument; a reviewer seeing a new day-end field flow into it should block the PR. +- sweep_exits.py / sweep_filters.py still carry their own session filters — deferred here to keep the diff reviewable; fold them in when next touched (they are research scripts, not verdict-producing jobs). +- If the tuner's fitted params shift materially after the population fix, that is EXPECTED (it was fitting a different universe) — compare `learned_params.json` before/after and let the owner decide whether to apply or re-baseline; the boot-load applies it automatically once written. diff --git a/plans/005-entry-path-unification.md b/plans/005-entry-path-unification.md new file mode 100644 index 0000000..7f2d904 --- /dev/null +++ b/plans/005-entry-path-unification.md @@ -0,0 +1,134 @@ +# Plan 005: One entry gate for both paths, with a decision receipt for every pass/fail + +> **Executor instructions**: Follow this plan step by step. Run every +> verification command and confirm the expected result before moving to the +> next step. If anything in the "STOP conditions" section occurs, stop and +> report — do not improvise. When done, update the status row for this plan +> in `plans/README.md`. +> +> **Drift check (run first)**: `git diff --stat d54a2a9..HEAD -- trading_execution.py run_live_paper.py storage/event_schema.py` +> On any in-scope drift, compare "Current state" excerpts before proceeding; +> mismatch = STOP. Diffs introduced by plans 001–004 are EXPECTED — see +> plans/README.md "Expected drift". + +## Status + +- **Priority**: P2 +- **Effort**: M +- **Risk**: MED-HIGH (live entry logic; mitigated by characterization tests + shadow parity mode) +- **Depends on**: 001 (CI gate), 003 (money-path hardening), 004 (population module — the first shared gate already extracted) +- **Category**: tech-debt / correctness +- **Planned at**: commit `d54a2a9`, 2026-07-13 + +## Why this matters + +Live entries flow through the SLOW auto-approval path (`request_approvals_for_ready_signals`); the FAST trigger path (`submit_breakout_now`) is architecturally alive but rarely used ("dead" per the boot log). The two paths have drifted: the VWAP gate and quality shadow exist only on the slow path; rank-concentration exists only on the fast path — and the boot log itself warns about it (run_live_paper.py:1026-1028: "rank-concentration is enforced ONLY on the dead fast-trigger path, NOT the live auto-approval path"). This drift class already produced the daily-cap 44-vs-5 incident (fixed in ac1ac50). Unifying onto one gate function means every future gate (including promoted Experiment-OS winners, plan 006) lands on both paths by construction — and emitting a compact *decision receipt* per evaluation turns "why didn't it trade X?" from a forensic session into a query. Receipts are also the raw material plan 006 replays. + +## Current state + +- SLOW path: `trading_execution.py` `request_approvals_for_ready_signals` — inline gate sequence per signal (~lines 860–1010): dedup/`_requested_symbols` → `_outside_session()` (~907) → `_population_reject(...)` (~910) → **VWAP gate** (~935: `if signal.get("above_vwap") is False:` — enforced when `settings.require_above_vwap`, else shadow-logged) → quality shadow → anti-chase/day-extension (`_anti_chase_skip`) → sizing → approval request. +- FAST path: `submit_breakout_now` (~1205–1290): `enabled` → `_daily_loss_breach()` → max-concurrent → `_late_confirmation` → `_outside_session()` (~1219) → `_population_reject` (~1222) → **`rank_risk_factor(rank, settings.concentrate_top_n)`** (~1228, fast-only) → daily fresh-entry cap → held/pending/`_requested_symbols` dedup → cooldown → `_exited_today` → dilution veto → price sanity → `_anti_chase_skip` (~1274) → sizing. **No VWAP gate, no quality gate.** +- Already-shared helpers: `_outside_session`, `_population_reject`, `_anti_chase_skip`, `_late_confirmation`, benches/dedup sets. The drift is only VWAP/quality (slow-only) vs rank (fast-only) plus ordering/structure. NOTE: on the slow path, anti-chase (~989) and the liquidity cap (~1023) are conditional on `settings.unified_entry` (`TRADING_UNIFIED_ENTRY`, default "1" — a documented rollback switch); the fast path runs anti-chase unconditionally. Step 2 preserves this flag semantics. +- Boot warning (run_live_paper.py:1024-1029) — delete it when rank runs on both paths. +- Events: typed pydantic events in `storage/event_schema.py`; risk skips today emit `RiskRuleTriggeredEvent` (see the population-reject emit at trading_execution.py:915-928). Convention: events carry `timestamp, mode, correlation_id, message` + structured fields. +- Retention: nightly job purges high-volume diagnostic event types older than 14 days (`research/premarket_eval.py` purge list) — receipts must be added to that list. + +## Commands you will need + +| Purpose | Command | Expected | +|---|---|---| +| Suite | `DATABASE_URL= python -m pytest -q` | all pass | +| Targeted | `DATABASE_URL= python -m pytest tests/unit/test_execution*.py tests/unit/test_trading_execution.py tests/unit/test_entry_gate*.py -q` | all pass (test_trading_execution.py is the main file for the refactored code — the `test_execution*` glob misses it) | +| Receipt query smoke | `./momentum inspect events` (after a dev-loop run) | `entry_gate_evaluated` events visible | + +## Scope + +**In scope**: +- `trading_execution.py` (the two path functions + a new `_evaluate_entry_gates` method) +- `storage/event_schema.py` (one new event type: `EntryGateEvaluatedEvent`) +- `research/premarket_eval.py` (add the receipt event-type STRING to the 14-day purge list) +- `run_live_paper.py` (rank-map handoff at the call site + remove the boot warning at 1024-1029 once true) +- `tests/unit/test_entry_gate_parity.py` (create) + adjustments to existing execution tests +- `.env.example` (`TRADING_GATE_RECEIPTS`, default on) + +**Out of scope**: +- Changing any gate's THRESHOLD or adding/removing gates (VWAP stays enforced-by-flag exactly as today; rank stays `concentrate_top_n`-gated; quality stays shadow) — this plan changes topology, not policy. +- The trigger book / arming logic in `run_live_paper.py` (rank is computed at arm time; it arrives as an argument). +- Dashboard rendering of receipts (plan 007 may surface them; not here). +- `strategy/population.py` internals (plan 004). + +## Git workflow + +- Branch: `advisor/005-entry-path-unification` +- Commits: characterization tests → shared gate function (parity mode) → path switches → receipts → boot-warning removal. +- Do NOT push or open a PR. + +## Steps + +### Step 1: Characterization tests for BOTH paths as they are + +`tests/unit/test_entry_gate_parity.py`: for a matrix of signals (in-population, below-VWAP, dead-band gap, ranked outside top-N, benched symbol, cooldown, session-closed, cap-reached), record the CURRENT decision of each path (slow: approval requested or skip reason via emitted events; fast: the `skipped` string). Pin them as expectations. This encodes today's asymmetries EXPLICITLY (e.g. below-VWAP: slow skips when enforced, fast proceeds — that is today's truth). + +**Verify**: targeted pytest green against unmodified code. + +### Step 2: Extract `_evaluate_entry_gates` + +One private method both paths call: + +```python +def _evaluate_entry_gates(self, ctx: EntryContext) -> GateDecision: + """Run the full ordered gate sequence; return first-reject or pass. + ctx carries: symbol, gap_pct, price/entry_ref, cum_volume, rvol, + above_vwap (None ok), rank (None on slow path today), trigger, stop, + day_open, halted, source ("auto"|"fast").""" +``` + +Order: session → late-confirmation (`_late_confirmation`, already on both paths at ~886/~1216) → population → VWAP (respect `require_above_vwap`; shadow-log below-VWAP exactly as the slow path does today) → quality (enforcement-flagged via `min_quality_score`; with the default `0.0` the fast-path decision is unchanged, so moving it into the shared gate is NOT a behavior closure) → rank (`rank_risk_factor`; **when `ctx.rank is None`, pass rank_factor=1.0 — see STOP #3**) → cap (**source=="fast" only** — the slow path's cap is enforced later in `approve_order` (trading_execution.py:1102-1108) and stays there untouched, as do both counter-increment sites; moving it to request time would be a third behavior change this plan does not make) → dedup/bench/cooldown/reentry → dilution veto → price sanity → anti-chase. Return `GateDecision(passed, reason, rank_factor, shadow_notes)`. Move code, don't rewrite it; each gate body is lifted verbatim from whichever path owns it today. + +**`unified_entry` flag fate**: the slow path's anti-chase and liquidity-cap are today conditional on `settings.unified_entry` (`TRADING_UNIFIED_ENTRY`, default "1"; documented rollback switch in `.env.example`). Keep that conditional INSIDE the shared gate for `source=="auto"` (fast stays unconditional, as today) — the rollback switch survives, behavior at flag=0 is unchanged. + +Wire BOTH paths to call it. Rank on the slow path: do NOT touch the watcher's signal payload or projections (the ready-signal payload is built in `runtime/watcher.py` from the detector's setup dict, which has no rank, and `query_ready_signals_snapshot` in `storage/projections.py` has a fixed field list — both out of scope). Instead pass a `{symbol: rank}` map from the trigger book into `request_approvals_for_ready_signals` at its call site in `run_live_paper.py` (the book computes rank at arm time; `t.rank` is visible in the trigger-thread code ~line 959 — expose the book's current ranks via a small accessor and hand the dict in as a new optional parameter). + +**Verify**: step-1 characterization tests — the ONLY acceptable diffs are the two documented asymmetries closing (fast now VWAP-gated; slow now rank-gated when rank present). Update exactly those expectations, cite this step in the test comment. Everything else stays pinned. + +### Step 3: Decision receipts + +New `EntryGateEvaluatedEvent` in `storage/event_schema.py` (match existing event conventions): `symbol, source, passed, reject_reason, gates: dict` (each gate → `{value, threshold, outcome}` — compact, one event per final decision, NOT one per gate). Emit from `_evaluate_entry_gates` behind `TRADING_GATE_RECEIPTS=1` (default on). Add the event-type **string** `"entry_gate_evaluated"` to the nightly 14-day purge tuple in `research/premarket_eval.py:96-97` (the `spam = ("module_tick", "criteria_evaluated", …)` tuple holds snake_case strings, not class names; diagnostic volume — order/fill events remain permanent). + +**Verify**: unit test asserts one receipt with full gate map on a reject and on a pass; suite green. + +### Step 4: Delete the boot warning + +Remove `run_live_paper.py:1024-1029` (the rank-concentration warning) — now false. Update the boot gate summary line (1018-1022) to include `rank top-N` state. + +**Verify**: `grep -n "enforced ONLY on the dead fast-trigger path" run_live_paper.py` → no matches. + +## Test plan + +- `tests/unit/test_entry_gate_parity.py` — the characterization matrix (~10 cases × 2 paths), then updated for the two closed asymmetries. +- Receipt tests (step 3): reject emits receipt with reason; pass emits receipt; `TRADING_GATE_RECEIPTS=0` emits nothing. +- Regression: existing `tests/unit/test_execution*.py` AND `tests/unit/test_trading_execution.py` (references `unified_entry`) untouched semantics must stay green — any other failure there means the extraction changed behavior beyond the two documented closures → STOP. +- Verification: `DATABASE_URL=… python -m pytest -q` green. + +## Done criteria + +- [ ] `grep -c "_population_reject" trading_execution.py` → 2 (the def + one call inside `_evaluate_entry_gates`; count is 3 at plan time) +- [ ] Both `request_approvals_for_ready_signals` and `submit_breakout_now` call `_evaluate_entry_gates` +- [ ] `grep -n "EntryGateEvaluatedEvent" storage/event_schema.py trading_execution.py` → defined + emitted; `grep -n "entry_gate_evaluated" research/premarket_eval.py storage/event_schema.py` → purge-listed + event-type registered +- [ ] Boot warning gone; boot summary shows rank state +- [ ] Full suite green; parity test documents exactly two behavior closures +- [ ] `plans/README.md` updated + +## STOP conditions + +- The slow path's gate sequence at HEAD contains gates not listed in "Current state" (drift/growth) — extend characterization first, report. +- Threading rank into the ready-signal payload requires touching more than `run_live_paper.py`'s arm/watch steps + the signal dict — report the actual data path instead of improvising. +- **Rank-on-slow-path decision**: if enabling rank on the live path would change today's LIVE behavior because `TRADING_CONCENTRATE_TOP_N > 0` is already set in production env — STOP and report: the owner must explicitly confirm turning rank concentration live (it was previously enforced nowhere that matters; making it real is a trading-behavior change, not a refactor). +- Any characterization diff beyond the two documented closures. + +## Maintenance notes + +- From now on a new entry gate is added in exactly one place. A PR adding a gate anywhere else in either path function should be blocked in review. +- Receipts are the substrate plan 006 replays; their `gates` map schema is now a soft contract — additive changes only. +- The `ctx.rank is None ⇒ factor 1.0` fail-open means signals with no rank are NOT concentration-limited; when plan 006's one-bullet experiment reports, the owner may want rank mandatory — that is a policy change to make deliberately, not here. +- Deferred: quality-grade gate promotion (currently shadow) — the runner-grade memory says the GRADE survives; promoting it to an enforced gate is an experiment for plan 006, not a refactor. diff --git a/plans/006-experiment-os.md b/plans/006-experiment-os.md new file mode 100644 index 0000000..9faa5d9 --- /dev/null +++ b/plans/006-experiment-os.md @@ -0,0 +1,229 @@ +# Plan 006: Experiment OS — pre-registered, auto-adjudicated counterfactual experiments over logged fires + +> **Executor instructions**: Follow this plan step by step. Run every +> verification command and confirm the expected result before moving to the +> next step. If anything in the "STOP conditions" section occurs, stop and +> report — do not improvise. When done, update the status row for this plan +> in `plans/README.md`. +> +> **Drift check (run first)**: `git diff --stat d54a2a9..HEAD -- research/labeler.py research/premarket_eval.py strategy/ storage/pg_schema.sql data/premarket_eval_history.tsv` +> On any in-scope drift, compare "Current state" excerpts before proceeding; +> mismatch = STOP. Diffs introduced by plans 001–005 are EXPECTED — see +> plans/README.md "Expected drift". + +## Status + +- **Priority**: P1 (flagship — attacks the proven entry-conversion bottleneck) +- **Effort**: L +- **Risk**: MED (all-shadow: zero live-trading changes; the risk is silent replay-fidelity bugs, mitigated by pre-registered fidelity checks) +- **Depends on**: 004 (population module — every experiment population MUST come from it), 005 recommended (receipts enrich replay inputs but bar-path replay works without them) +- **Category**: direction / research-infrastructure +- **Planned at**: commit `d54a2a9`, 2026-07-13 + +## Why this matters + +The system's bottleneck is proven to be ENTRY-CONVERSION (7 refuted selection levers; 76–84% of ORB fires poke-then-stop). The three most promising interventions are already researched with external evidence (`docs/research/entry_conversion_research.md`, ranked shortlist): (1) time-boxed entries + 10-min time-stop on unconfirmed positions, (2) probe-then-add 0.5×+0.5× sizing, (3) asymmetric exit (volatility-fractional stop with a spread floor, NO profit target, trail to EOD). All three are testable **for free** against fires already logged — zero live risk. What blocks them is machinery, not ideas: today each shadow track is a hand-built ~300-line build/report/validate triple in `research/labeler.py` (1,467 lines: `build_vwap_reclaim`:428, `build_runner`:630, `build_liquid`:870, `build_premarket`:1053), and verdicts rot in a TSV nobody reads — `data/premarket_eval_history.tsv`'s latest row (2026-07-09) shows pm1 at n=2377 with `rate_1r=0.443` vs the pre-registered `>0.50` bar and `median_up_60m=0.0433` vs `>=0.10`, `passed=False` — **failing 3 of 4 pre-registered criteria** while the code's docstring still frames it as underpowered. Build the harness once: experiment = config row; replay engine runs interventions counterfactually over logged fires; verdict engine auto-adjudicates at pre-registered thresholds and emits events → Telegram + dashboard. Every future experiment drops to a config row. + +**The owner provisions the Postgres database/tables once this plan is approved** — the DDL below is the deliverable for that. + +## Current state + +- Shadow-track pattern (to be superseded, not deleted yet): `research/labeler.py` — four structurally near-identical triples; pre-registered bars as module constants, e.g. lines 120–122: + ```python + PREMARKET_PROMO_MEDIAN_FWDMAX = 0.10 # (1) median max-upside (within pm) >= +10% + PREMARKET_PROMO_MEDIAN_ADVERSE = -0.06 # (2) median max-drawdown > -6% + PREMARKET_PROMO_MIN_1R = 0.50 # (3) +1R-before-(-1R) > 50% + ``` + `validate_premarket` (1132–1152) checks them; `research/premarket_eval.py` appends a TSV row nightly. +- Fire history: every live fire and its context is in the event store (`order_submitted`, `order_filled`, `position_closed`, `risk_rule_triggered`; plan 005 adds `entry_gate_evaluated` receipts). Minute bars for fired symbols/days are in `minute_bars` (~19M rows). `eod_replay.py` (plan 004 fixes its population) demonstrates the replay-from-bars idiom. +- Exit policy source of truth: `ExitConfig` (`strategy/exits.py`) — `eod_replay.py:79-84` shows `_exit_cfg()` construction from env. The live exit is `runtime/exit_manager.py`; `strategy/exits.py` has the simulation functions (`simulate_exit` family). KNOWN DIVERGENCE (recon): sweeps/replay exit variants have drifted from live exit behavior — the harness must simulate through ONE exit implementation and declare which (see step 2 fidelity rules). +- Wired-but-unread data feeds usable as experiment features: `float_cache`, `dilution_events` (written nightly, zero readers — plan 002 logged them as "disposition here"). +- Slippage honesty (non-negotiable, from the research doc): the tightest-stop-wins result is a documented zero-slippage artifact that already fooled two in-house tracks (vr1, liq1). Every experiment must apply `stop_width >= max(k_ATR × ATR14, m × spread_proxy)` floors and +1-tick adverse fills on entry AND stop, with the floor parameters recorded in the experiment row. +- Telegram: `runtime/notifier.py` `send_telegram` (used at run_live_paper.py:1037); the qabot is read-only — verdict pings go through the send helper from the nightly job. +- Population: `strategy/population.py` (plan 004) with `as_of` contract. +- Scheduler: both compose scheduler blocks (see plan 004 step 5 for the pattern). + +## Database DDL (the owner provisions this — also the executor's migration file) + +Create `storage/experiments_schema.sql` (applied by the harness on first run, same idiom as `pg_schema.sql`; ALSO handed to the owner to run manually if preferred): + +```sql +-- An experiment is a pre-registered, immutable contract. Rows are never +-- updated after registration except status/verdict fields. +CREATE TABLE IF NOT EXISTS experiments ( + id TEXT PRIMARY KEY, -- slug, e.g. 'time_stop_10m_v1' + registered_at TIMESTAMP NOT NULL, + hypothesis TEXT NOT NULL, -- one sentence, human-readable + population JSONB NOT NULL, -- PopulationConfig dump + extra filters + intervention JSONB NOT NULL, -- typed params, e.g. {"kind":"time_stop","minutes":10,"confirm":"new_high_or_0.5R"} + bars JSONB NOT NULL, -- pre-registered pass/fail criteria, e.g. {"expR_delta_min":0.05,"min_n":300,"p_max":0.05} + futility JSONB, -- early-kill rule, e.g. {"min_n":500,"expR_delta_max":-0.02} + fidelity JSONB NOT NULL, -- slippage floors: {"atr_frac":0.25,"spread_mult":3,"adverse_ticks":1} + status TEXT NOT NULL DEFAULT 'running', -- running|passed|failed|inconclusive|killed + verdict_at TIMESTAMP, + verdict_note TEXT +); + +-- One row per (experiment, replayed fire): the counterfactual outcome. +CREATE TABLE IF NOT EXISTS experiment_runs ( + experiment_id TEXT NOT NULL REFERENCES experiments(id), + fire_id TEXT NOT NULL, -- order_id / receipt correlation id + symbol TEXT NOT NULL, + session_date DATE NOT NULL, + baseline_r DOUBLE PRECISION, -- what actually happened (R units) + variant_r DOUBLE PRECISION, -- counterfactual outcome (R units) + detail JSONB, -- entry/exit stamps, fills, floor hits + computed_at TIMESTAMP NOT NULL, + PRIMARY KEY (experiment_id, fire_id) +); +CREATE INDEX IF NOT EXISTS idx_exp_runs_exp_date ON experiment_runs (experiment_id, session_date); + +-- Verdict history (append-only; the dashboard ledger reads this). +CREATE TABLE IF NOT EXISTS experiment_verdicts ( + experiment_id TEXT NOT NULL REFERENCES experiments(id), + as_of TIMESTAMP NOT NULL, + n INTEGER NOT NULL, + metrics JSONB NOT NULL, -- observed values vs each bar + verdict TEXT NOT NULL, -- PASS|FAIL|INCONCLUSIVE|KILLED + PRIMARY KEY (experiment_id, as_of) +); +``` + +## Commands you will need + +| Purpose | Command | Expected | +|---|---|---| +| Suite | `DATABASE_URL= python -m pytest -q` | all pass | +| Harness run | `DATABASE_URL= python -m research.experiments run` | replays new fires for all running experiments | +| Adjudicate | `DATABASE_URL= python -m research.experiments adjudicate` | prints/emits verdicts | +| Register | `DATABASE_URL= python -m research.experiments register experiments/time_stop_10m_v1.json` | row inserted, immutable | + +## Scope + +**In scope**: +- `research/experiments/` (new package: `__init__.py`, `registry.py`, `replay.py`, `adjudicate.py`, `cli.py` as `python -m research.experiments`) +- `storage/experiments_schema.sql` (the DDL above) +- `experiments/` (repo-root dir of experiment JSON definitions — the first cohort) +- `research/premarket_eval.py` (emit pm1's overdue verdict via the new adjudicator; keep the legacy TSV append until the owner retires it) +- Both compose scheduler blocks (add `python -m research.experiments run && … adjudicate` after eod_replay/nightly_tune) +- Tests as listed +- `docs/research/entry_conversion_research.md` — read-only input; do NOT edit + +**Out of scope**: +- ANY live-trading change. No experiment result may alter gates, sizing, or exits in this plan. Promotion of a PASS verdict to live behavior is a separate, owner-approved change (lands on plan 005's unified gate). +- Deleting the legacy labeler triples (follow-up after two clean harness cycles). +- The dashboard ledger panel UI (plan 007 renders `experiment_verdicts`; this plan only fills the tables). +- New market-data feeds. + +## Git workflow + +- Branch: `advisor/006-experiment-os` +- Commits: schema → registry/CLI → replay engine (+fidelity tests) → adjudicator → first cohort registrations → scheduler wiring. +- Do NOT push or open a PR. + +## Steps + +### Step 0: Precondition check (plan 004 must have landed) + +```bash +test -f strategy/population.py && grep -q "nightly_tune FAILED" docker-compose.yml deploy/docker/truenas-compose.yml && echo OK +``` + +If either check fails, plan 004 has not landed — STOP and report. (At the planned-at commit neither exists; this plan is unexecutable before 004.) + +### Step 1: Schema + registry + +`storage/experiments_schema.sql` as above; `registry.py` applies it idempotently (respect `PG_SKIP_SCHEMA=1`, mirroring `storage/db_pg.py:275-277` semantics) and implements `register(json_path)` (validates required keys incl. fidelity floors; refuses to overwrite an existing id — immutability), `list()`, `get(id)`. + +**Verify**: register a fixture experiment twice → first succeeds, second errors with "already registered". Tables exist (`\dt` or information_schema query). + +### Step 2: Replay engine + +`replay.py`: for each running experiment, find fires not yet in `experiment_runs` (source: `order_filled` buy events joined to their submits — the `_rebuild_daily_state` payload idiom, trading_execution.py:412-446 — plus `entry_gate_evaluated` receipts when present), filter through `strategy/population.py` with the experiment's population JSON, load that symbol/day's `minute_bars`, and compute: + +- `baseline_r`: what actually happened (from `position_closed` realized P&L in R units — the live truth, not a simulation). +- `variant_r`: the intervention applied counterfactually on the bar path. Intervention kinds for the first cohort, implemented as small pure functions in `replay.py`: + - `time_stop`: exit at market (next bar open, +adverse tick) if no new post-entry high AND < +0.5R within N minutes. + - `probe_add`: 0.5× at fill; add 0.5× at first new high above trigger-bar high within 10 min (fill at that bar's high + adverse tick); blended R. + - `asym_exit`: replace the live exit with stop = max(atr_frac × ATR14, spread_mult × spread_proxy), no target, trail to EOD close. Simulate via `strategy/exits.py` simulate functions ONLY (declare in `detail` which code simulated; never mix live-manager logic in). + - `rank_one_bullet`: portfolio-level — for each session, keep only the top-ranked fire. Rank source: plan 005's `entry_gate_evaluated` receipts ONLY — **no historical event payload carries rank** (the armed book is memory-only; do not hunt for an armed-book event type, it does not exist). Expect `detail.rank_missing=true` for effectively ALL fires predating plan 005; exclude those from n, register the experiment anyway, and report the starvation (its clock starts when receipts flow). +- FIDELITY RULES (hard-coded, not per-experiment-optional): +1-tick adverse fill on every counterfactual entry AND stop; spread_proxy from quiet-bar high-low as described in the research doc; a `fidelity` block recorded into `detail` per run. + +**Verify**: `python -m research.experiments run` over a dev DB with ≥1 registered experiment and stored fires → `experiment_runs` rows appear; re-run → zero new rows (idempotent); unit fidelity tests pass (Test plan #2–4). + +### Step 3: Adjudicator + +`adjudicate.py`: per running experiment, compute metrics over `experiment_runs` (n, mean/median R delta, +1R rate, win rate — whichever the experiment's `bars` reference), compare against `bars`/`futility`: + +- all bars met AND n ≥ min_n → `PASS` +- futility triggered → `KILLED` +- any bar decisively failed at n ≥ min_n → `FAIL` +- else → `INCONCLUSIVE` (recorded, no spam) + +Write `experiment_verdicts`, update `experiments.status` on terminal verdicts, emit an event (`experiment_verdict` type via EventStore) and Telegram ping on any TERMINAL verdict or status change only. + +Then pm1 through the engine — the explicit bridge (pm1's data lives in the labeler's `setup_events`/`outcome_labels` tables, not in fires): **backfill `experiment_runs` for `pm1_v1` from `outcome_labels` joined to `setup_events`** (one row per labeled premarket setup: `variant_r` = its reached-+1R-before-−1R outcome as ±1; `max_upside`/`max_drawdown` into `detail`; `baseline_r` NULL — pm1 is a detector track, not an intervention on fires), and extend the adjudicator's metric vocabulary to cover pm1's bars: `median_up_60m`, `median_dd_60m`, `rate_1r`, `big_gap_rate_1r`. Register `pm1_v1` with bars exactly from `research/labeler.py:120-122` + the validate function: `{"median_up_60m_min": 0.10, "median_dd_60m_min": -0.06, "rate_1r_min": 0.50, "big_gap_rate_1r_min": 0.50}`. Its FAIL verdict at n=2377 becomes the harness's first output. Keep the TSV append in `premarket_eval.py` for one release (dual-write). + +**Verify**: `python -m research.experiments adjudicate` on the dev DB → pm1_v1 verdict row `FAIL` (or the truth of the data at run time), one event emitted, no repeat ping on second run. + +### Step 4: First cohort registrations + +`experiments/*.json` — five files. **The bars below are pre-registered HERE, in this plan** (the research doc pre-registers the measures and fidelity floors, NOT numeric pass/fail thresholds — copy only the fidelity floors from it; `rank_one_bullet` does not appear in the doc at all). Use these bars verbatim: + +| id | intervention | bars (pass requires ALL) | futility (kill when) | +|---|---|---|---| +| `time_stop_10m_v1` | `{"kind":"time_stop","minutes":10,"confirm":"new_high_or_0.5R"}` | `{"expR_delta_min": 0.05, "min_n": 300}` | `{"min_n": 500, "expR_delta_max": -0.02}` | +| `probe_add_v1` | `{"kind":"probe_add","probe_frac":0.5,"confirm_minutes":10}` | `{"expR_delta_min": 0.05, "min_n": 300}` | `{"min_n": 500, "expR_delta_max": -0.02}` | +| `asym_exit_v1` | `{"kind":"asym_exit","atr_frac":0.25,"no_target":true,"trail":"eod"}` | `{"expR_delta_min": 0.10, "min_n": 300}` (higher bar — bigger structural change) | `{"min_n": 500, "expR_delta_max": -0.02}` | +| `rank_one_bullet_v1` | `{"kind":"rank_one_bullet","top_n":1}` | `{"expR_delta_min": 0.10, "min_n": 100}` (n = sessions with rank) | `{"min_n": 200, "expR_delta_max": -0.05}` | +| `pm1_v1` | (bridge — step 3) | `{"median_up_60m_min": 0.10, "median_dd_60m_min": -0.06, "rate_1r_min": 0.50, "big_gap_rate_1r_min": 0.50}` (from labeler.py:120-122) | none — adjudicate immediately at n=2377 | + +`expR_delta` = mean(variant_r − baseline_r) over runs. All five carry hypothesis text, population (production thresholds via `strategy/population.py` — see plan 004's "pass production values explicitly" note), and fidelity floors `{"atr_frac": 0.25, "spread_mult": 3, "adverse_ticks": 1}` (these ARE from the research doc). + +**Verify**: all five register; `run` + `adjudicate` complete end-to-end on stored history; verdicts land in the table. + +### Step 5: Schedule + +Add to both compose scheduler blocks after nightly_tune (plan 004's line): +```sh +python -m research.experiments run || echo "[scheduler] experiments run FAILED" +python -m research.experiments adjudicate || echo "[scheduler] experiments adjudicate FAILED" +``` + +**Verify**: `grep -n "research.experiments" docker-compose.yml deploy/docker/truenas-compose.yml` → both present, ordered after tune. + +## Test plan + +1. Registry: register/immutability/validation errors (missing fidelity → refuse). +2. Fidelity: a synthetic bar path where zero-slippage would profit but adverse-tick fills lose → variant_r reflects the loss (the anti-artifact regression test — this is the single most important test in the plan). +3. `time_stop` on a synthetic poke-then-die path → scratch loss smaller than full stop; on a confirm-then-run path → unchanged from baseline. +4. `probe_add` blended-R arithmetic on a known path (hand-computed expected value in the test). +5. Adjudicator: PASS/FAIL/KILLED/INCONCLUSIVE each from constructed run rows; terminal-verdict ping fires once. +6. Idempotency: `run` twice → no duplicate `experiment_runs` (PK holds). +Structure: model on `tests/unit/` conventions; synthetic bars built inline (see `tests/synthetic.py` helpers if applicable). +- Verification: `DATABASE_URL=… python -m pytest -q` green, ~12 new tests. + +## Done criteria + +- [ ] `storage/experiments_schema.sql` exists; three tables created idempotently; `PG_SKIP_SCHEMA` honored +- [ ] `python -m research.experiments register|run|adjudicate` all function end-to-end on a dev DB +- [ ] Five first-cohort experiments registered from `experiments/*.json` +- [ ] pm1 verdict emitted through the harness (event + verdict row) +- [ ] Fidelity floors hard-enforced (test #2 green) +- [ ] Scheduler wired in both compose files +- [ ] Full suite green; zero changes to live gates/sizing/exits (`git diff --stat` shows no trading_execution.py/runtime/ changes) +- [ ] `plans/README.md` updated + +## STOP conditions + +- Fire history proves insufficient to reconstruct entries (missing order events for a large share of fills) — report the coverage number (fires reconstructable / total) before building interventions. +- `strategy/exits.py` simulate functions cannot express the asym_exit variant without modifying live-shared code — report; do NOT fork exit logic silently. +- Rank is unavailable for >50% of historical fires (rank_one_bullet starves) — register it anyway but report; its clock starts when plan 005 receipts flow. +- Anything requires touching live gates/sizing/exits — hard stop; that is promotion, which is owner-gated. + +## Maintenance notes + +- The promotion path for a PASS verdict: owner reviews `experiment_verdicts` + detail distributions → implements the intervention behind a flag on plan 005's unified gate → ships as its own change. The harness NEVER auto-promotes. +- After two clean nightly cycles, the four legacy labeler triples (~1,200 lines) and the TSV append become deletable — log it as a follow-up in plans/README.md when reached. +- New experiment = one JSON file + (if a new intervention kind) one pure function in replay.py with its fidelity test. Review bar: no experiment registers without pre-registered bars and fidelity floors. +- `float_cache`/`dilution_events` become experiment FEATURES (population filters) — first use retires their "write-only" status from plan 002's log. diff --git a/plans/007-operator-control-plane.md b/plans/007-operator-control-plane.md new file mode 100644 index 0000000..e2bf897 --- /dev/null +++ b/plans/007-operator-control-plane.md @@ -0,0 +1,182 @@ +# Plan 007: Operator control plane — the dashboard tells the truth and accepts guarded commands + +> **Executor instructions**: Follow this plan step by step. Run every +> verification command and confirm the expected result before moving to the +> next step. If anything in the "STOP conditions" section occurs, stop and +> report — do not improvise. When done, update the status row for this plan +> in `plans/README.md`. +> +> **Drift check (run first)**: `git diff --stat d54a2a9..HEAD -- api/ dashboard_api.py admin_api.py telegram_bot.py run_live_paper.py trading_execution.py storage/event_schema.py deploy/ docker-compose.yml` +> Diffs introduced by plans 001–006 are EXPECTED — see plans/README.md "Expected drift". +> On any in-scope drift, compare "Current state" excerpts before proceeding; +> mismatch = STOP. + +## Status + +- **Priority**: P2 (except step 1, which is a P1 production bug fix) +- **Effort**: M +- **Risk**: MED (introduces a live kill switch; mitigated by HMAC guard, idempotency, and the loop consuming commands through its existing protective-close helper) +- **Depends on**: 001 (CI test gate), 003 (clean shutdown/flatten paths). The headless smoke test is CREATED in this plan (step 6) — it does not exist in 001. Ledger panel additionally wants 006's tables (render "no experiments yet" until then). +- **Category**: bug / dx / capability +- **Planned at**: commit `d54a2a9`, 2026-07-13 + +## Why this matters + +The production :8765 dashboard currently lies and cannot act: **every POST endpoint crashes** (`api/main.py:415-416` uses `os.environ` and `hmac.compare_digest` but the module imports at lines 24-30 include neither — `NameError` on any approve/reject/exit/watch action); the LIVE badge keys on `execution_mode === "schwab_live"` (dashboard.html:1061) while the admin go-live flow (admin_api.py:276-295) only swaps `ALPACA_BASE_URL`/keys and never touches `TRADING_EXECUTION_MODE` — the badge would read PAPER while trading real money; sparklines are permanently dead in production; the action UI renders in the read-only deployment even though `has_execution` is shipped (api/main.py:148) and never read; and **no manual flatten path exists anywhere in the production surface** (dashboard container runs `execution_service=None` — dashboard_api.py:36; the qabot hard-refuses action words — telegram_bot.py:29-30). The operator's two moments of need — "get me flat NOW" and "what is this thing actually running?" — both currently require shelling into a container. Additionally the SSE change detector opens a fresh Postgres connection (re-applying the 473-line schema unless `PG_SKIP_SCHEMA=1`) plus `COUNT(*)` every second per client. + +## Current state + +- `api/main.py:22-33` — imports: `json, threading, time, datetime/timezone, http.server, pathlib, urllib.parse, storage.*`. **No `os`, no `hmac`.** Lines 410-417: + ```python + def do_POST(self): # noqa: N802 + ... + _tok = os.environ.get("DASHBOARD_TOKEN") + if _tok and not hmac.compare_digest(self.headers.get("X-Dashboard-Token", ""), _tok): + ``` +- SSE loop `api/main.py:~350-365`: `count = self.state.event_count()` every ~1s tick; `event_count()` constructs work per call; `storage/db_pg.py:275-277` re-applies `pg_schema.sql` on connection unless `PG_SKIP_SCHEMA=1`; `storage/event_store.py:200` count = `COUNT(*)`. +- `has_execution` shipped in snapshots (`api/main.py:148`: `"has_execution": self.execution_service is not None`), zero uses in `api/static/dashboard.html` (grep). +- LIVE badge: `api/static/dashboard.html:419` `PAPER`; badge CSS at 89-94 (`.badge.paper` blue / `.badge.live` red); JS keys on the `schwab_live` literal (~line 1061). +- Admin go-live: `admin_api.py:276-295` — `/api/mode` writes `ALPACA_BASE_URL + live keys` to overrides; note `"restart the loop to apply"`. +- Standalone dashboard: `dashboard_api.py:36` — `DashboardState(db_path, execution_service=None, execution_mode=mode)`; docstring: "For approve/reject/exit buttons to act, run the full orchestrator". +- qabot: `telegram_bot.py:29-30` `_ACTION_WORDS = ("buy ", "sell ", "flatten", "close all", …)` — refusal list; `is_authorized` (220-221) = chat-id string equality. +- Loop guard cadence: 5s (`run_live_paper.py` guard task) — command pickup latency bound. Flatten primitive: `runtime/flatten.py:97` `cancel_protective_and_close(client, symbol, orders=None, …)`. +- Event conventions: typed events in `storage/event_schema.py`; the loop already polls the store on several cadences. +- Design system (from `api/static/dashboard.html`, verified): tokens at `:root` lines 8-27 (`--bg #080a10, --panel #111622, --border #232c41, --text #e3e8f2, --muted #7884a2, --accent #5ba3ff, --green #34d17e, --red #ff5a60, --amber #f7b13b, --mono` stack); panel convention at 137-169 — a new panel is `

Title …

`, span-6 grid cell (`.full` for span-12), collapth/persistence free via the `details.panel` classes; render via the shared helpers (`$(id)`, `fill()`, `table()`, `esc()` — keep the stricter global `esc` at ~line 590; `.pill/.count/.hint/.pos/.neg`); ALL numerics in the mono stack with `tabular-nums`; dark-only — use tokens, never hardcoded colors. +- Headless verification recipe exists (project memory): Playwright chrome-headless-shell renders the page to catch JS errors curl can't see. + +## Design contract (from the design-fit review — follow, don't re-design) + +- **Experiment ledger panel**: standard `details.panel` (span 6), columns `experiment · n · bar · observed · verdict`; verdict pill colors: PASS `--green`, FAIL `--red`, INCONCLUSIVE `--muted`, RUNNING/KILLED `--accent`/`--amber`; row-expand shows the pre-registered bars vs observed (mirror the Watch States expand pattern). Empty state: `No experiments registered — plan 006 fills this.` +- **Kill switch**: red **ghost** button `FLATTEN ALL` in the header right of the mode badge, visible only when `snapshot.has_execution || COMMAND_BUS_ENABLED`. Two-step: first click arms (button turns solid red, label `CONFIRM FLATTEN (3 positions) — 5s`, countdown auto-disarms); second click within 5s sends. Per-position `EXIT` ghost-red buttons in Open Positions rows, same two-step inline. `PAUSE ENTRIES` amber ghost toggle → solid amber + a thin amber banner while paused. **No keyboard shortcut for any destructive action.** Toast copy names the exact action: `Flatten command sent — loop executes within ~5s.` +- **LIVE badge**: derive from broker truth in the snapshot (step 4), tooltip = account + base-URL host; when live, the existing top shimmer line switches to red (one CSS rule off a `body.live-mode` class). +- **Effective-config panel** lives on ADMIN :8767 (its design system, its domain): per-key row `key · effective value · source` where source is a uniform-fill chip (`baked | compose | overrides.env | learned`); drift row highlighted when a required `.env.example` key is missing. Secrets masked (`***` + last 4). + +## Commands you will need + +| Purpose | Command | Expected | +|---|---|---| +| Suite | `DATABASE_URL= python -m pytest -q` | all pass | +| Dashboard API tests | `DATABASE_URL= python -m pytest tests/ -k "dashboard or api" -q` | pass (loopback bind failures on WSL hosts are environmental, not regressions) | +| Headless smoke | (new) `python tests/smoke_dashboard_headless.py` | exits 0, "0 JS errors" | + +## Scope + +**In scope**: +- `api/main.py` (imports fix; SSE cheapening; command + config endpoints; snapshot fields) +- `api/static/dashboard.html` (badge truth, has_execution gating, kill-switch UI, ledger panel, sparkline wiring) +- `dashboard_api.py` (env plumbed for research DB sparklines if that's the gap — see step 5) +- `storage/event_schema.py` (`OperatorCommandEvent`), `run_live_paper.py` (command consumer on the 5s guard), `trading_execution.py` ONLY if pause-entries needs a flag hook (keep minimal) +- `admin_api.py` (+ its static page) — effective-config endpoint + table +- `telegram_bot.py` (guarded `/flatten` command emitting the same event) +- `tests/` additions incl. `tests/smoke_dashboard_headless.py` +- `.env.example` (`DASHBOARD_TOKEN` documented as REQUIRED-when-commands-on, `COMMAND_BUS_ENABLED`) +- `deploy/docker/truenas-compose.yml` + `docker-compose.yml`: add `PG_SKIP_SCHEMA=1` + `DASHBOARD_TOKEN` to the dashboard service env + +**Out of scope**: +- Reviving NiceGUI controlroom (owner-rejected), any new UI framework/dependency, light theme. +- Approve/reject queue redesign; existing POST actions beyond making them not crash. +- Experiment tables themselves (plan 006). +- LISTEN/NOTIFY — explicitly deferred: the shared cached signal below is the lazy sufficient fix; NOTIFY is the upgrade path if it measurably falls short. + +## Git workflow + +- Branch: `advisor/007-operator-control-plane` +- Step 1 ships as its own first commit (it is a production bug fix candidates for cherry-pick). +- Do NOT push or open a PR. + +## Steps + +### Step 1: Fix the POST crash + token plumbing + +Add `import os` and `import hmac` to `api/main.py`'s imports. Add `DASHBOARD_TOKEN` to the deploy templates' dashboard-service env (empty default + comment). Write the missing regression test: a POST with no token configured → routes (asserting no `NameError`); with token configured → 401 without header, 200-path with correct header. + +**Verify**: `DATABASE_URL=… python -m pytest tests/ -k "dashboard" -q` → new POST tests pass. + +### Step 2: Cheapen the SSE change detector + +In `api/main.py`: one module-level cached signal shared by all SSE clients — a small `_ChangeSignal` holding `(stamp, checked_at)` refreshed at most once per second GLOBALLY (lock + monotonic stamp), using ONE long-lived EventStore connection created with schema application skipped (constructor arg or `PG_SKIP_SCHEMA` — mirror `storage/db_pg.py:275-277`). Freshness query: **`SELECT max(timestamp) FROM events`** — `events.id` is `VARCHAR PRIMARY KEY` (`storage/pg_schema.sql:18`), NOT serial, so `max(id)` would be lexicographic garbage; `idx_events_timestamp` exists (`pg_schema.sql:27`) so max(timestamp) is an index-tail seek. + +**Verify**: unit test — two fake clients, 10 ticks → underlying query runs ≤ ~10 times total (inject a counting stub); suite green. + +### Step 3: Operator command bus + +1. `storage/event_schema.py`: `OperatorCommandEvent` — `command` (`flatten_all|flatten_symbol|pause_entries|resume_entries`), `symbol` (nullable), `requested_by`, `nonce` (uuid), plus standard fields. +2. `api/main.py`: `POST /api/command` — REQUIRES `DASHBOARD_TOKEN` configured (503 with clear message if unset: commands never run unauthenticated), validates command against the enum, emits the event. Emitting is allowed even when `execution_service is None` — the standalone dashboard becomes a thin emitter; expose `command_bus: true` in snapshots when the token is set and `COMMAND_BUS_ENABLED=1`. +3. `run_live_paper.py`: in the 5s guard task, poll `operator_command` events newer than the last-consumed stamp (keep a consumed-nonce set for the session; also persist consumption as an emitted `operator_command_done` event so a restart doesn't re-execute — REPLAY SAFETY: on boot, ignore commands older than 10 minutes). Execute: `flatten_all` → `rt["execution"].close_session("operator_flatten")` — **decide deliberately**: `close_session` also blocks re-entry for the day (that is the kill-switch semantic the safety posture wants; document it in the button tooltip). **Interaction with plan 003's daily self-restart**: an operator flatten must NOT trigger the exit-after-EOD-flatten path — `_request_exit_after_eod` is called only from `step_eod_flatten`'s success branch, so route the operator command through `close_session` directly (never through `step_eod_flatten`) and add a test asserting no exit request fires on an operator flatten. `flatten_symbol` → `cancel_protective_and_close` for that symbol; `pause_entries`/`resume_entries` → a `_operator_paused` flag checked in `_evaluate_entry_gates` (plan 005) or, pre-005, at the top of BOTH `request_approvals_for_ready_signals` AND `submit_breakout_now` in `trading_execution.py` (miss one and pause silently fails on that path — the drift class plan 005 documents). +4. `telegram_bot.py`: `/flatten` and `/flatten SYM` commands — REMOVE `"flatten"` from `_ACTION_WORDS` refusals only for the slash-command path, keep prose refusals; authorized chat only (`is_authorized`); emits the same event; replies `Command sent — loop executes within ~5s.` +5. Dashboard UI per the design contract (two-step arm/confirm, gating, toasts). + +**Verify**: unit tests — command consumed once (nonce dedup), stale-on-boot ignored, pause blocks a would-pass entry, unauthorized qabot chat refused; suite green. + +### Step 4: Truthful LIVE badge (+ has_execution gating) + +Snapshot gains `broker` block (from env the services already have): `{"base_url_host": , "is_paper": host startswith "paper-api"}`. Dashboard JS: badge = `is_paper ? PAPER : LIVE` (drop the `schwab_live` keying; keep the badge classes), tooltip shows host; `body.live-mode` class flips the shimmer red (one CSS rule). Gate every action control (approve/reject/exit/inject + new commands) on `has_execution || command_bus`. + +**Verify**: unit test on the snapshot block (paper URL → is_paper true; live URL → false). Headless smoke (step 6) renders both states via a query stub if cheap, else at least default state with zero JS errors. + +### Step 5: Production sparklines + +`dashboard_api.py`/`api/main.py`: the standalone dashboard's bars/sparkline endpoints need the research DB connection the embedded mode has. Identify the exact gap by grepping `research_con` / bars queries in `api/main.py` — wire the standalone entrypoint to construct the same reader (read-only) the orchestrator passes. If the gap is env-only (DATABASE_URL already reaches it), fix the query path; report in the commit message what the actual missing wire was. + +**Verify**: run `python dashboard_api.py` against a dev DB → `curl -s "127.0.0.1:8765/api/bars?symbol=X"` returns HTTP 200 with a JSON array (rows when the dev DB has bars for X; an empty array on a bare DB is a PASS — the fix is the non-None reader, not the data). With bars present, headless smoke shows no fetch error. + +### Step 6: Headless smoke test + effective-config panel + +1. `tests/smoke_dashboard_headless.py` — NEW file; the recipe is not in the repo, so here it is in full: + - Setup (once per environment): `pip install playwright && python -m playwright install chrome-headless-shell`. On minimal Linux/WSL where the browser fails to launch with a libasound error, stub it: `mkdir -p ~/.lib-stubs && touch ~/.lib-stubs/libasound.so.2 && export LD_LIBRARY_PATH=~/.lib-stubs:$LD_LIBRARY_PATH` (the dashboard uses WebAudio only after user gesture; a dead stub is fine for rendering). + - Script shape (sync API): start the dashboard server on an ephemeral port against the test DB (reuse how `tests/` boot `create_server`), then: + ```python + from playwright.sync_api import sync_playwright + errors = [] + with sync_playwright() as p: + b = p.chromium.launch(channel="chrome-headless-shell", args=["--no-sandbox"]) + page = b.new_page() + page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) + page.on("pageerror", lambda e: errors.append(str(e))) + page.goto(f"http://127.0.0.1:{port}", wait_until="networkidle") + assert page.locator(".panel").count() >= 8, "panels missing" + assert page.locator("#mode-badge").count() == 1, "badge missing" + b.close() + assert not errors, f"JS errors: {errors}" + ``` + - If `channel="chrome-headless-shell"` is unsupported by the installed Playwright version, use `p.chromium.launch(headless=True)` after `python -m playwright install chromium`. + Wire into CI as a non-blocking step first (loopback binds can be flaky on WSL hosts), promote to blocking after one green week. +2. Admin effective-config: `admin_api.py` endpoint `GET /api/config/effective` — merge order baked-env < compose-env < `data/overrides.env` < `learned_params.json`-applied keys; return `{key: {value_masked, source}}`; static table per the design contract. Mask any key matching `(KEY|SECRET|TOKEN|PASSWORD)`. + +**Verify**: smoke test exits 0 locally; `curl -s :8767/api/config/effective | python -m json.tool` shows masked values + sources; admin tests (new, minimal: auth + masking) pass. + +## Test plan + +- POST regression (no-NameError), token 401/200 (step 1) +- SSE shared-signal query budget (step 2) +- Command bus: nonce dedup, boot-stale ignore, pause gate (blocks BOTH path functions), qabot auth, and operator flatten does NOT request the plan-003 daily-restart exit (step 3) +- Badge truth from base URL (step 4) +- Admin: effective-config masking + auth (step 6) +- `tests/smoke_dashboard_headless.py` — the JS-error net that would have caught the NameError's sibling class +- Verification: `DATABASE_URL=… python -m pytest -q` green (~12 new). + +## Done criteria + +- [ ] `grep -n "^import os\|^import hmac" api/main.py` → both present; POST works in tests +- [ ] SSE detector: one shared signal, `PG_SKIP_SCHEMA` honored, dashboard service env updated in both compose files +- [ ] `OperatorCommandEvent` end-to-end: dashboard button → event → loop executes → `operator_command_done`; qabot `/flatten` works for the authorized chat +- [ ] Badge reflects broker truth; action UI gated on `has_execution || command_bus` +- [ ] Standalone dashboard serves sparkline data +- [ ] Effective-config table live on :8767 with masked values + per-key source +- [ ] Headless smoke exits 0; full suite green +- [ ] No new colors outside `:root` tokens in dashboard.html diff +- [ ] `plans/README.md` updated + +## STOP conditions + +- `api/main.py` at HEAD already imports os/hmac (someone hotfixed) — skip step 1, continue. +- The events table lacks BOTH a serial id and an indexed timestamp usable for the cheap change signal — report before inventing a third scheme. +- `close_session` proves unusable as flatten_all (e.g. it exits the process after plan 003) — coordinate: the command consumer must flatten WITHOUT the daily self-restart exit; if the two plans' semantics collide, stop and report the interaction. +- Any step requires adding a JS dependency/framework — hard stop (zero-dependency page is a constraint, not a preference). + +## Maintenance notes + +- The command bus is deliberately minimal: enum commands, token-gated, nonce-deduped, 10-min staleness window. Adding parameterized commands (e.g. "resize position") should raise design review — the audit trail and replay-safety analysis must be redone per command. +- The two-step confirm's 5s disarm and the loop's 5s pickup are independent timers; total worst-case latency ~10s — acceptable because broker-side stops remain the fast protection layer. Do not "improve" by having the dashboard call the broker directly; the loop is the single execution authority. +- When plan 006's tables exist, add the ledger panel data key (`experiment_verdicts` latest per experiment) to `DashboardState.snapshots()` following the established pattern (filter on native timestamp column first — payload_json casts on the full events table time out; see the panel-adding convention). +- Reviewer scrutiny: XSS — every interpolated value in new panels goes through the global `esc()` (line ~590); the config panel doubly so (env values are attacker-influenced in principle). diff --git a/plans/README.md b/plans/README.md new file mode 100644 index 0000000..012113e --- /dev/null +++ b/plans/README.md @@ -0,0 +1,56 @@ +# Implementation Plans — next enhancement milestone + +Generated by the improve skill on 2026-07-13 at commit `d54a2a9`, from an +8-cluster recon sweep (~95 evidence-cited findings), a 5-frame ideation pass +(48 raw ideas → 14 merged candidates, all 14 verified sound by a fresh-context +spot-check against HEAD), and a design-fit review of the dashboard additions. +Companion design artifacts: `docs/ideation/2026-07-13-next-milestone-ideation.html` +(ranked ideas + bases), `docs/ideation/momentum-architecture-current.{drawio,png}`, +`docs/ideation/momentum-milestone-featureset.{drawio,png}`. + +Execute in the order below unless dependencies say otherwise. Each executor: +read the plan fully before starting, honor its STOP conditions, and update +your row when done. + +## Execution order & status + +| Plan | Title | Priority | Effort | Depends on | Status | +|------|-------|----------|--------|------------|--------| +| 001 | Production safety rails — CI test gate, dead-man's switch, pg_dump backup | P1 | S | — | TODO | +| 002 | Dead-weight deletion — schwab/, grafana/, dead modules/tables/projections | P2 | S | 001 | TODO | +| 003 | Money-path hardening — daily self-restart, positive-evidence contract, reconcile, cage count | P1 | M | 001 | TODO | +| 004 | Learning flywheel — one population module, scheduled eod_replay + nightly_tune, atomic writes | P1 | M | 001 (002 rec.) | TODO | +| 005 | Entry-path unification + decision receipts | P2 | M | 001, 003, 004 | TODO | +| 006 | Experiment OS — pre-registered counterfactual experiments over logged fires (flagship) | P1 | L | 004 (005 rec.) | TODO | +| 007 | Operator control plane — dashboard truth + kill switch + effective config (step 1 = prod bug fix, ship early) | P2 | M | 001, 003 (006 for ledger data) | TODO | + +Status values: TODO | IN PROGRESS | DONE | BLOCKED (with one-line reason) | REJECTED (with one-line rationale) + +## Expected drift (read before running any plan's drift check) + +Every plan stamps `d54a2a9` and its drift check diffs against that commit. Executed +in order, later plans WILL see diffs from earlier ones (compose scheduler/db-backup +blocks from 001/003/004/006, workflow test job from 001, trading_execution/ +run_live_paper changes from 003/004/005, telegram_bot from 001). That is EXPECTED +drift: verify only that the plan's quoted code excerpts still exist semantically +(line numbers may shift); STOP only on changes NOT attributable to a completed +plan in this series (check the status table above). + +## Dependency notes + +- **001 first, always**: it is the gate that makes every other plan's image push test-verified. 007's step 1 (the POST `NameError` import fix) is a production bug fix that may be cherry-picked ahead of everything. +- 002 before the refactor-heavy plans (004/005) so they diff against a smaller surface; its production `DROP TABLE` section runs only after 001's backup exists. +- 003 before 005/007: both build on its clean-shutdown/flatten semantics. Note the documented interaction: 007's `flatten_all` command must not trigger 003's daily-restart exit (see 007 STOP conditions). +- 004 before 006: every experiment population MUST come from `strategy/population.py` — running experiments against a look-ahead population re-creates the exact artifact class (vr1/liq1) this milestone exists to kill. +- 005 before 006 is recommended (receipts enrich replay + rank_one_bullet needs rank), but 006's bar-path replay works without it — the rank experiment just starts underpowered. +- **Postgres provisioning (owner)**: the only new DDL in the milestone is plan 006's `experiments` / `experiment_runs` / `experiment_verdicts` tables (full DDL in `plans/006-experiment-os.md`). Plans 001–005/007 add no tables. The owner said they will provision the database once the plan is solid — that means: apply 006's DDL (or let the harness's idempotent schema-apply do it on first run), and after 002 lands, optionally run its operator `DROP TABLE` list post-backup. + +## Findings considered and rejected (do not re-audit) + +- **Retest/pullback entry logic, scale-out partials, close-above-trigger confirmation from folklore** — refuted in `docs/research/entry_conversion_research.md` (external evidence + in-house tests); the research doc's "explicit do-nots". +- **Selection levers (confirmation-speed gate, float gating, liquidity floors, VWAP-reclaim promotion, liquid-breakout, leading-gainer detector, premarket-volume slices)** — refuted at year scale per project memory; the validated population stays as-is. +- **Reviving the NiceGUI controlroom** — owner preference: :8765 is the dashboard. +- **LISTEN/NOTIFY for dashboard change detection** — deferred, not rejected: the shared cached signal (007 step 2) is the sufficient lazy fix; NOTIFY is the named upgrade path. +- **TimescaleDB / pg extensions** — not required at current scale (README's own assessment); revisit only if event/bar volume grows past what the hot-path index handles. +- **`strategy/regime.py` deletion** — already deleted at HEAD; recon reference was stale. +- **Schwab account sync revival for human-vs-bot comparison** — the only non-delete rationale for schwab/; owner may veto 002's schwab deletion if that comparison is still wanted (plan 002 grep-gates it either way).