Skip to content

fills_writer: recover client_order_id via posted_orders on Kalshi field drift - #12

Closed
ijlu wants to merge 90 commits into
thirdlayerinc:mainfrom
ijlu:claude/sleepy-hofstadter-1d66bc
Closed

ijlu wants to merge 90 commits into
thirdlayerinc:mainfrom
ijlu:claude/sleepy-hofstadter-1d66bc

Conversation

@ijlu

@ijlu ijlu commented May 12, 2026

Copy link
Copy Markdown

Summary

Second instance of the same Kalshi field-drift bug pattern that triggered the 2026-05-03 dual-format fix (commit 6a39dd7).

  • Kalshi's /portfolio/fills response stopped echoing back client_order_id around 2026-05-10. Confirmed against live API: the only identity fields are trade_id, fill_id, order_id, ticker.
  • Without client_order_id, default_source_tagger returns manual for every fill — silently breaking per-strategy attribution (weather_mm_shadow.live_pnl_cents back-fill matches zero rows, mm_promotion graduation never fires, backtest_comprehensive.py strategy slices are wrong).
  • 2026-05-12 audit found the bot logged 9 cross_bracket_live POSTED decisions on May 11 against 0 cross_bracket source rows in fills_ledger — all 12 corresponding fills collapsed into source='manual'. Real bot fills were indistinguishable from Josh's manual UI trades.

Recovery: every /portfolio/orders POST writes (order_id, client_order_id, source_hint) to posted_orders at post time. FillsWriter.ingest_page falls back to that lookup when Kalshi's payload omits client_order_id.

What changed

  • bot/db.py — posted_orders table definition. Existed on prod (30 historical rows from an aborted May 7–10 backfill) but was never tracked in the schema. CREATE TABLE IF NOT EXISTS is idempotent.
  • bot/daemon/fills_writer.py:
    • record_posted_order(conn, **kwargs) helper — idempotent via INSERT OR IGNORE, holds DB_WRITE_LOCK via db_write_ctx
    • ingest_page falls back to posted_orders lookup when fill.client_order_id is missing
    • Adds cross_bracket and cross_bracket_exit to ALLOWED_SOURCES
    • Routes mm_xb_* / mm_xb_exit_* prefixes in default_source_tagger (was collapsing to legacy)
  • bot/daemon/cross_bracket_shadow.py — call record_posted_order after successful api_post in _post_live_order
  • bot/daemon/cross_bracket_exit.py — same wiring + rename exit prefix mm_xbexit_ → mm_xb_exit_ so the tagger distinguishes exits from entries. has_pending_exit accepts both prefixes for in-flight orders.
  • tests/test_client_order_id_coverage.py — structural-invariant test now covers cross_bracket_shadow and cross_bracket_exit (was the silent gap that let this bug ship). Allowed prefixes expanded with mm_xb_exit_ and mm_xb_.
  • tests/test_posted_orders_fallback.py (new) — 12 tests pinning tagger routing, record_posted_order idempotence + partial-row refusal, end-to-end recovery, and external-fill fall-through to manual.

Follow-ups (out of scope here, see reports/INVESTIGATION_2026-05-12.md once drafted)

  • A.3 backfill — May 11+ fills_ledger rows still tag manual; need a one-time SQL operation to recover them from alpha_backtest decisions
  • A.4 alert — warn loudly when a manual fill lands within 10 min of a posted decision for the same ticker, so future Kalshi format drift surfaces immediately
  • B/C/D investigation — cross_bracket 0/42 win rate and the ensemble's ECE=0.26 calibration failure (separate from this attribution bug)

Test plan

  • pytest tests/ — 2327 passed, 2 skipped (cryptography ABI on local Mac + no_secrets_in_repo, both unrelated)
  • bash deploy/04_redeploy.sh 45.55.79.193 succeeded, daemon healthy after restart
  • After first cross_bracket_live POST post-deploy: confirm posted_orders row appears and the subsequent fill in fills_ledger tags cross_bracket rather than manual (background watcher is polling)
  • After 24h: confirm live_pnl_cents is populating on weather_mm_shadow again (was stuck at 0 matches since May 11)

🤖 Generated with Claude Code

ijlu and others added 30 commits April 16, 2026 08:10
Adds trade.py, bot/, and deploy/ — the core trading bot code.

Key additions in this commit:
- MM trade calibration: record_settlements() now inserts calibration
  records for market-maker trades using AVG(fair_value_cents)/100
  as estimated probability (previously only directional trades
  had calibration data)
- MM timing patterns: record_timing_data() now joins settlements
  with mm_orders to capture hour/day patterns for MM trades
  (previously only joined with trades table)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Both Open-Meteo and Tomorrow.io sources were using forecast_low instead
of forecast_high for "or below" HIGH-temperature markets. This caused
massive probability overestimation (e.g. 99.9% instead of 7.6%) because
the low temp is far below the threshold on most days.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…nsive backtest

Weather families caused 94% of losses ($375 of $400). Block all 11 weather
series from MM_TARGET_SERIES and add to blocklist as defense-in-depth.
Counterparties have real-time METAR/NWS and reprice faster than our 2-min cycle.

Fix opportunity_log: all 47K+ rows had NULL ensemble_prob/sources_json because
the log_opportunity call was in the selection phase (before ensemble computed).
Added logging in the actual quoting phase of trade.py's mm_run() with full
ensemble_prob, source_count, sources_json, and skip_reason.

Add backtest_comprehensive.py: 12-section analysis answering "do signals have
alpha?" with calibration curves, edge-vs-winrate, source accuracy, family P&L,
MM deep dive, loss classification, and statistical significance tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replaces the monolithic systemd-oneshot MM with a persistent daemon
architecture. Captures ~6 weeks of in-flight refactoring as a single
baseline so Phase 1 work can proceed on stable ground.

Architecture change
-------------------
- New bot/daemon/ package: supervisor (main.py), in-process CycleRunner
  (replaces forking trade.main() every 2 min), event-driven METARPoller
  on its own thread, Scheduler with periodic tasks, WAL DB connection
  under DB_WRITE_LOCK, WeatherQuoter + smart_gates ready for event-
  driven cancel-replace (on_result not yet wired).
- Old bot/market_maker/ package deleted (~2.3K lines): core, quotes,
  fills, inventory, liquidation, selection, adverse_selection,
  series_profitability, family_caps. Superseded by daemon-era equivalents.
- bot/orchestrator.py deleted; trade.py trimmed by ~2K lines (legacy
  MM phases removed; Safe Compounder gated on SC_ENABLED=off).
- bot/db.py, bot/api.py, bot/signals/ensemble.py now import locks from
  bot/daemon/locks to coordinate writes across poller/cycle threads.

New signal sources (Phase 2 weather stitching prep)
---------------------------------------------------
- bot/signals/sources/: nws_point, ndfd_nbm, madis, hrrr, afd, gdpnow,
  adp_nfp, commodity_futures
- bot/signals/weather_ensemble.py, family_routers.py
- bot/core/categorization.py

Backtest + analysis
-------------------
- backtest_comprehensive.py: 12-section analysis with per-family Brier,
  calibration curves, edge-vs-winrate, source accuracy, MM deep dive,
  loss classification, significance tests. Fixed the per-order-side
  fair_value_cents averaging bug that made v1 show Brier 0.50.
- reports/BACKTEST_APR17.md: Phase 0 go/no-go report — five weather
  families pass family-Brier gate by 4-8x; KXBTC/KXETH flagged for
  directional block; market-mid leg deferred to Phase 1 logging.

Deploy
------
- deploy/kalshi-daemon.service + kalshi-weather-daemon.service units.
- deploy/05_deploy_weather_daemon.sh, updated deploy/04_redeploy.sh
  with full daemon module import-check battery.

Tests
-----
- tests/daemon/: cycle_runner, scheduler, poller_base, smart_gates_trajectory
- tests/bot/: api_concurrency, db_wal
- tests/signals/: new source coverage
- tests/test_{weather_daemon,weather_quoter,smart_gates,money,fee_calc,
  fedwatch_parser,positions,settlement_certainty,db_schema}.py
- Removed tests/test_{adverse_selection_defenses,mm_opportunity_log}.py
  (covered legacy market_maker module)

Gitignore
---------
Expanded to block all forms of secrets (*.pem, *.key, .env*), DBs,
logs, local audit dumps (AUDIT_EXPORT*, REVIEW_V*, HEALTH_REPORT,
etc.), binary .docx, backup files (*.bak*, *.backup*, trade_v*_backup,
trade.py.bak*), and Claude tooling dirs.

What this commit does NOT do
----------------------------
- METARPoller.on_result is still None — event-driven requote not wired.
- Weather MM stays fully blocked (block list in config unchanged).
- Directional trading stays DRY_RUN.
- No alpha_backtest table yet, no Platt correction wired, no settlement-
  driven learning population. All Phase 1 follow-up items.

CLAUDE.md is intentionally committed as-is and will be rewritten in
the next commit to reflect the new daemon architecture.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Rewrites the project overview to match the post-refactor reality:
- Daemon supervisor (bot.daemon.main) with 60s cycle + event-driven
  pollers, replacing the systemd timer oneshot
- WAL + DB_WRITE_LOCK / API_LOCK concurrency model documented
- bot/market_maker/ removed from the file tree (deleted in 04ca78f);
  bot/daemon/ documented in full
- Expanded ensemble table with new sources (NWS/NBM/HRRR/MADIS/AFD/
  GDPNow/ADP-NFP/commodity futures)
- Current phase section: Phase 0 passed, Phase 1 is the current work,
  nothing trades live, weather MM re-enable is shadow-first
- Known Bug Patterns: added thirdlayerinc#13 (per-side fair_value normalization —
  the Apr 17 bug), thirdlayerinc#14 (DB_WRITE_LOCK), #15 (shared DB connection)
- Current Performance updated from the Apr 17 backtest: 922 fills /
  116 settlements / 11.2% WR / favorable +6.12¢ markout / per-family
  Brier showing weather alpha / catastrophic KXBTC/KXETH/KXHIGHDEN
- Audit History: Apr 14/16/17 entries added
- Phase 1 Work section: the 8-step plan now on record
- Critical Conventions: added fair_value_cents + ensemble_prob
  per-side rules that were only in the backtest report before

Preserves: Boil the ocean, Planning and qualifying questions, all
YES-equivalent math, bracket vs threshold, synthetic sell, graduated
exits, dynamic sizing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Phase 1 needs an auditable decision journal to evaluate the Phase 0 gate's
"ensemble beats market-mid by >=0.005" leg. This commit adds the table,
logger, and two hooks in trade.py's directional path.

- bot/db.py: alpha_backtest table (decision + raw market snapshot + settlement
  backfill fields) with 4 indexes including a partial pending-settle index.
  Raw yes_bid/ask/last/age/spread are stored alongside a canonical
  market_prob_yes + market_prob_source tag so analysis can re-evaluate the
  gate under multiple market-mid definitions without re-collecting data.
- bot/learning/alpha_log.py: atomic log_decision() + fill_settlement() under
  DB_WRITE_LOCK. resolve_market_prob() implements the mid/last/wide_mid/
  one_side/none fallback ladder. Never raises — logging must not break the
  trading loop.
- trade.py: log_decision() called alongside existing log_opportunity() at
  the two directional callsites (Kelly skip + shadow trade). Safe Compounder
  sites intentionally omitted — SC isn't ensemble-validated and would
  pollute the gate's analysis slice.
- tests/test_alpha_log.py: 40+ cases covering family extraction, Kalshi
  price coercion (incl. CLAUDE.md bug pattern #5), the full resolution
  ladder, log_decision round-trip, and fill_settlement idempotency.
- tests/test_db_schema.py: alpha_backtest added to expected-tables set.
Phase 1 step 4. The legacy learning writers (calibration, timing_patterns,
edge_convergence, loss_postmortems) read from `trades` + `mm_orders`. But
directional is DRY_RUN (empty `trades`) and MM was deleted (frozen
`mm_orders`), so today's cycle populates almost nothing — active_feedback
has no data to act on.

This commit adds alpha_backtest-driven writers that run alongside the
legacy ones, so directional shadow decisions feed the same downstream
analysis as live rows would.

- bot/learning/alpha_log.py: new fill_settlement_for_ticker() settles all
  open rows for a ticker in one UPDATE, computing per-row won_yes and
  counterfactual realized_pnl_cents (contracts * (100 - price_cents) on
  wins, -contracts * price_cents on losses).
- bot/db.py: add nullable alpha_id column + partial unique index (where
  alpha_id IS NOT NULL) to calibration, timing_patterns, edge_convergence,
  loss_postmortems. Legacy rows pass through as NULL.
- bot/learning/populate_from_alpha.py: one function per target table plus
  a populate_all() orchestrator. Each writer is idempotent via NOT EXISTS
  subquery on alpha_id. Never raises — instrumentation must not break the
  trading loop. Provenance tagged via source='alpha:shadow' or
  source='alpha:<decision_type>'.
- trade.py: record_settlements() now calls fill_settlement_for_ticker()
  per ticker; cycle body calls populate_all() right after.
- tests/test_alpha_log.py: covers fill_settlement_for_ticker's per-side
  win logic, counterfactual P&L, idempotency.
- tests/test_populate_from_alpha.py: 18 cases covering bucket assignment
  (YES uses p_yes, NO uses 1-p_yes), edge computation, convergence_pct
  math, loss classification (bad_source / efficient_market / adverse),
  provenance tags, and full populate_all idempotency.

All 498 tests pass.
Collapse the three duplicate calibration implementations (trade.py,
ensemble.py, bot/learning/calibration.py) into one Platt-scaling module
with label-smoothed Newton-Raphson fit, L2 ridge, per-family overrides,
shadow isotonic PAV for future promotion, and kv_cache persistence.
Fixes the latent shape-mismatch bug where the old flat {bucket: offset}
dict would crash ensemble.py's dict-of-dicts expectation once the
calibration table accumulated settlement rows. Ensemble now passes
ticker through both callsites so family-specific curves apply. 46 new
tests cover fit/apply/persist end-to-end.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Closes the Phase 1 step-6 gap: the METAR poller now fans temperature
changes into a shadow-by-default requote engine that persists proposed
quotes to the new weather_mm_shadow table. The step-9 gate will read
those rows to score event-driven MM on counterfactual P&L before the
WEATHER_MM_LIVE flip.

- New bot/daemon/forecast_cache.py extracts the Open-Meteo forecast
  cache from the legacy orchestrator with merge-on-failure semantics
  so one bad station doesn't wipe the others.
- New bot/daemon/weather_handler.py owns per-series cooldown, forecast
  fallback (running_high + 5°F), and the shadow-vs-live gate.
- WeatherQuoter gains shadow_requote_city / _shadow_requote_single +
  compute_quote_prices as a shared static to prevent live/shadow drift.
- weather_mm_shadow table captures FV, proposed bid/ask, market snap,
  smart-gate decision, latency, and live_mode for later analysis.
- bot/daemon/main.py now instantiates the handler, registers the
  forecast_refresh task, and rolls handler stats into health logs.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Phase 1 step 7. Pure evaluator at bot/learning/directional_shadow.py
runs per candidate: family blocklist → kelly_zero → below_edge (vs
YES-side market mid) → shadow_pass. Replaces the two inline
_alpha_log_decision sites in trade.py with one call-site that maps
outcomes to AlphaOutcome.DISCARDED / SHADOW_ONLY.

Blocks KXBTC, KXETH, KXHIGHDEN by default (Phase 0 catastrophic-
calibration findings), overridable via DIRECTIONAL_BLOCKLIST env.

Per-family live flag lives in kv_cache under directional_live:<FAMILY>
— primitive for step 9's shadow-to-live promotion job. should_go_live
is stubbed False until step 9 writes the alpha_backtest SQL.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Block weather MM, fix opportunity_log, add comprehensive backtest
Adds a per-family promotion state machine on top of the step-7 shadow
evaluator. Families start in SHADOW; a daily sweep auto-promotes to
LIVE_CANARY (0.5× Kelly) after ≥50 settled shadow decisions clear
edge_beat ≥ 0.005 on both the full window and the second-half OOS
slice, and auto-graduates canary → LIVE_FULL after 30 settled canary
decisions with non-negative P&L. A trifecta kill switch (P&L floor,
Brier regime shift, single-trade hard stop) demotes FULL → CANARY →
SHADOW; shadow demotion is terminal until an operator runs
manual_re_enable under a ratcheted 0.010 edge_beat gate. All
transitions are journaled to a new promotion_events table. trade.py
scales directional contract sizing by the family's Kelly multiplier
and only posts when the family is in a live state.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Phase 1 step 10: per-series promotion state machine (SHADOW → LIVE_CANARY → LIVE_FULL)
gated on shadow spread-capture evidence, with paired shadow-row logging on the live
path so the shadow-fill model can be continuously calibrated against realized fills.

- bot/learning/mm_promotion.py: LiveState enum, evaluate_mm_promotion (N≥80 settled
  shadow fills, mean pnl/fill ≥ 2¢, OOS second-half slice must also pass),
  evaluate_canary_graduation, evaluate_mm_kill_switch (single-trade hard stop +
  rolling floor), match_shadow_fills (trade-conservative crossing heuristic),
  annotate_shadow_pnl, run_mm_promotion_sweep daily driver
- bot/learning/threshold_tuner.py: T.8 weekly proposer — 3^4 grid search over the
  four promotion thresholds, objective = log-growth − λ·drawdown, writes to
  threshold_proposals only if best beats current by MIN_OBJECTIVE_DELTA_FOR_PROPOSAL
- bot/daemon/weather_quoter.py: requote_city accepts order_size_multiplier +
  old/new temp for T.6 paired logging; _post_quotes returns
  (n, bid_oid, ask_oid, bid_price, ask_price) so the handler can stamp a live-mode
  weather_mm_shadow row alongside the live orders
- bot/daemon/weather_handler.py: per-series gate reads mm_live:<SERIES> via
  is_mm_live / get_mm_order_size_multiplier; master WEATHER_MM_LIVE env still wins
- bot/daemon/main.py: three new scheduler tasks — mm_fill_match (5 min),
  mm_promotion_sweep (daily), threshold_tuner (weekly)
- trade.py record_settlements: on settle, call annotate_shadow_pnl so settled
  shadow rows become eligible for the promotion gate
- bot/db.py: weather_mm_shadow.order_size column migration
- tests/test_mm_promotion.py, test_threshold_tuner.py, test_mm_promotion_golden.py
  + tests/golden/mm_promotion_fixtures.json: T.7 CI regression harness that
  requires an explicit fixture update for any behavior change in the gate
- 722 tests pass

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The position_health_log schema has settlement_result + settlement_pnl_cents
columns described as "filled post-settlement for learning" — but nothing
ever filled them. Rows stayed NULL forever, starving the bandit that trains
on which health-band decisions held winners vs losers.

record_settlements now runs a scoped UPDATE per settled ticker so every
prior per-cycle health snapshot carries the eventual outcome. NULL-guard on
the WHERE clause keeps this idempotent across multiple settlements.

Audit note: the other four Phase 1 step #3 learning sinks (calibration,
timing_patterns, edge_convergence, loss_postmortems) are already fully
populated from alpha_backtest via bot/learning/populate_from_alpha.py and
from the legacy trade.py writers — no change needed there. Step #4 (Platt
in get_independent_estimate) and step #6 (directional shadow evaluator with
KXBTC/KXETH/KXHIGHDEN blocks) were likewise already wired. position_health
was the one real gap.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Kalshi families like KXFED-26MAY / KXFED-26JUN / KXFED-26JUL are one
rate-path bet, not three independent ones. Kelly-by-market sized each
independently; the Apr 17 book ended up 95% KXFED — one leveraged Fed
thesis, not a diversified book.

This cap limits aggregate correlated exposure (default 25% of equity)
without constraining per-market Kelly on genuinely independent bets. It
runs AFTER the 50% global cap so it's the tighter constraint that binds
for concentrated families.

- bot/core/exposure.py: family_from_ticker, compute_family_exposures
  (buckets Kalshi position rows), family_headroom_cents, and
  size_trade_against_family_cap which returns (allowed_contracts, skip_reason)
- bot/config.py: MAX_FAMILY_EXPOSURE_RATIO env var
- trade.py: fetches positions once per cycle, computes family_exposures,
  applies the cap per-candidate AFTER the global cap, mutates the
  accumulator so within-cycle accepts count against the next candidate
- tests/test_exposure.py: 22 tests — pass/reduce/reject paths, within-cycle
  accumulation, fallback ordering, cross-family isolation

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Code Structure tree: add bot/core/{exit_model,exposure,sizing}.py,
  bot/daemon/{dispatcher,fills_writer,forecast_cache,requote_triggers,weather_handler,__main__}.py,
  bot/learning/{alpha_log,bakeoff,directional_shadow,edge_convergence,mm_promotion,populate_from_alpha,self_modifier,shadow_promotion,shadow_testing}.py,
  bot/signals/regime.py, bot/scoring/four_factor.py, bot/observability/cost_tracker.py,
  bot/signals/sources/{_fomc_calendar,zq_futures}.py, expanded tests listing.
  Consolidate weather sources (weather.py now holds Open-Meteo + Tomorrow.io +
  NOAA) and economics sources (economics.py now holds FRED + BLS + Cleveland Fed).
  Update trade.py line count ~4.8K → ~7K.
- Cycle Flow: rewrite for current trade.main() — phase system, alpha-populate
  step, Platt fit per cycle, advanced learning loops, family/expiry exposure
  caps, graduated per-family sizing, directional shadow evaluator (already live,
  not "Phase 1 will log"). MM quoting step removed (legacy MM code deleted;
  weather MM is event-driven on WeatherQuoter path).
- Database Schema: add sessions, learned_config, decision_log, weather_mm_shadow,
  weather_source_weights, weather_forecast_snapshots, promotion_events,
  threshold_proposals, fills_ledger. Re-group by purpose. Move calibration /
  timing_patterns / edge_convergence out of "populated in Phase 1" — they're
  populated each cycle now.
- Source weights table: fix drifted weights (NBM 0.77→0.80, HRRR 0.72→0.85,
  MADIS 0.68→0.60, GDPNow 0.60→0.78, ADP/NFP 0.58→0.80). Add weather_ensemble
  (0.95), zq_futures (0.85), AFD (0.50).
- Env vars: SC_ENABLED default true (not false). Add FORCE_PHASE,
  DIRECTIONAL_BLOCKLIST, MAX_{PORTFOLIO,FAMILY,EXPIRY}_EXPOSURE_RATIO,
  EXIT_{EDGE_DECAY_RATIO,TIME_BACKSTOP_HOURS,TIME_BACKSTOP_EDGE_ABS,STALE_HOLD_HOURS},
  MM_SIZING_TARGET_EDGE_CENTS.
- Phase 1 Work: mark items 2–7 done (all have landed code paths); item 8
  (shadow-to-live gate) still in flight as graduated promotion; add item 9
  (T3 fills-ledger consumer migration, in flight).
- Current Phase: summarize landed vs. in-flight Phase 1 items.
The Apr-17 → Apr-21 data corruption (20,478 fake-filled rows on
fabricated zero-book data) took four days to surface because nothing
asserted that weather_mm_shadow.market_yes_bid had the shape Kalshi
actually returns. The B+D fix hardened _safe_cents and the MM promotion
gate, but a typo in any future parser would hit the same failure mode.

This adds three invariant checks that run every 10 min on a 1-hour
window — catches the Apr-17 class of bug within minutes of first
corrupt write:

  - Zero-price invariant (critical → Telegram alert): any row with
    market_yes_bid=0 or market_yes_ask=0. Kalshi never quotes below 1¢.
  - Blind-quote watchdog (warning): ≥20 gated-post rows but zero
    observed books — upstream parser is returning None for every
    market.
  - Stuck-book watchdog (info): ≥20 book observations with only 1
    distinct bid value in an hour.

scripts/shadow_status.py is the operator dashboard: per-series state +
shadow P&L table, integrity findings (reuses check_shadow_data_integrity
so the CLI can never disagree with the daemon monitor), and explicit
next-action hints per series against the CANARY and LIVE_FULL gates.

Wiring into the daemon scheduler (bot/daemon/main.py) and deploy-time
import assertions (deploy/04_redeploy.sh) land in the broader Phase 1
commit that follows.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- agent.py, agent-claude.py: pre-daemon orchestration scripts; the
  bot.daemon supervisor replaces both. Listed as deleted but
  never cleaned up.
- trade_audit_export.py, trade_v3_audit.py: stale one-shot export
  dumps (~14K lines between them). The current audit process uses
  backtest_comprehensive.py + reports/ markdown.
- bot/learning/threshold_tuner.py + test: never fired useful signal;
  proposed-thresholds table was read-only by design and the proposals
  were always ignored. Replaced by the shadow→canary→full graduated
  promotion gate which owns threshold evolution end-to-end.
- bot/observability/opportunity_log.py: DB-write was moved into
  trade.main long ago; this helper was dead.
- tests/golden/mm_promotion_fixtures.json + golden test: replaced
  by parameterised tests that drive the two-gate logic directly
  (tests/test_mm_promotion.py).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Before T1.1 there were five separate station registries (stations.py,
metar_observations.py, weather.py, madis.py, and a derived copy in
smart_gates.py). They disagreed on NYC resolution — the daemon polled
KJFK while signal sources polled KNYC, a 2–5°F systematic gap
depending on season.

Kalshi's KXHIGHNY settles against the NWS climatological record for
NYC, which has used Central Park (KNYC) since the 19th century. KJFK
is coastal and runs 2–5°F cooler in summer. Phase 0 backtest brier
scores (0.09–0.21 on weather families) were computed with signal
sources reading KNYC — switching them to KJFK would have invalidated
the validation.

This commit makes stations.py the single source of truth:
- KXHIGHNY primary station: KNYC (was KJFK)
- KJFK, KLGA, KEWR remain as backups (poller still cross-references;
  MADIS basket still spatially averages)
- ALL_STATION_IDS is the canonical URL driver for METARPoller
- New STATION_BY_SERIES dict provides the O(1) series→station lookup
  used by WeatherQuoter and smart_gates

Weather MM is currently blocked (WEATHER_MM_LIVE=false) so re-homing
the daemon primary has zero trading impact — it just aligns shadow-
mode readings with settlement for when we flip live.

tests/daemon/test_station_registry.py locks the KNYC primary + KJFK
backup invariant so no future refactor can silently demote KNYC.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Pre-T1.2 the weather MM quoter posted on METAR events only, and every
requote blocked the METAR poller thread for the duration of a Kalshi
cancel-replace round-trip (~500–1500 ms). A slow round-trip for one
city stalled observations for all six — and time-decay effects (sigma
shrink as we approach day-close) produced no requotes at all unless
a METAR happened to fire.

This commit ships three pieces:

1. AsyncEventDispatcher (dispatcher.py) — one worker thread per series.
   Same-series work is strictly serialised (invariant the quoter's
   cancel-replace logic depends on), but LAX's work never blocks NYC's.
   Stale pending events coalesce down to latest-state so a burst of
   METARs doesn't produce a queue of stale requotes.

2. TimeDecayDriver (requote_triggers.py) — ticks the cadence clock
   every 30 s. Fires synthetic requotes as sigma shrinks: 600 s
   cadence >8h out, tightening to 45 s in the final hour. Shares the
   same enqueue_synthetic path as METAR events so the quoter sees one
   event type, not three.

3. ForecastChangeDriver (requote_triggers.py) — captures pre/post
   Open-Meteo cache snapshots on every forecast_refresh. Fires a
   synthetic requote only when |Δfv| >= threshold AND the ticker is
   currently tradable — no-op refreshes produce no load.

Handler.on_fire is wired to time_decay_driver.note_external_fire so
a METAR event resets the cadence clock; otherwise a METAR at T+0
would be followed by a redundant time-decay fire at T+45s.

VALID_REASONS frozenset locks the trigger taxonomy to exactly 3 labels
(METAR_CHANGE, TIME_DECAY, FORECAST_CHANGE) — anything else is a typo.

tests/daemon/test_integration_cadence.py exercises the end-to-end
cadence shape (45 s → 600 s transition at the 8h boundary) so a
future driver refactor can't silently regress the late-day tightening.

orchestrator.py one-liner is a T1.1 follow-on (Station dataclass
attribute access replaces the pre-T1.1 dict access).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Adds the fills_ledger table as the T3 canonical append-only record of
every Kalshi fill, keyed by Kalshi's trade_id. Replaces the
mm_processed_fills table's role as the fills source of truth (though
mm_processed_fills stays writable during the T3.1→T3.3 transition).

Pieces:
- fills_ledger table + 4 indexes (ticker+ts, order_id, series+ts,
  family+ts) in bot/db.py. INSERT OR IGNORE on trade_id dedups so
  overlapping sync_since calls are free.
- FillsWriter (bot/daemon/fills_writer.py) — single writer of every
  ledger row. Two methods: ingest_page (one /portfolio/fills response
  page) and sync_since (drives pagination forward from a timestamp).
  Per writer-ownership rules, this is the ONLY path into fills_ledger.
- ValidationReport + compare_last_n_days / format_report
  (bot/learning/fills_validator.py) — dual-run divergence check
  comparing fills_ledger to mm_processed_fills over a 7-day window.
  is_meaningful gates alerting: one-sided (only one table populated)
  is the steady state during T3.1 bedding-in and logs info only;
  two-sided divergence is the signal T3.3 migration cares about.

Also in bot/db.py:
- db_write_ctx() context manager (T0.2 write discipline). Wraps
  SQLite writes in DB_WRITE_LOCK + BEGIN IMMEDIATE + commit/rollback
  so every writer respects the daemon's single-connection invariant.

Scoping doc: reports/T3_FILLS_LEDGER_SCOPING.md (lands with the
reports commit).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Two entangled changes that share mm_promotion.py and must land
together:

**B+D (two-gate shadow→canary→full promotion)**

The Apr-17 data-corruption incident exposed a single-criterion
promotion gate that auto-graduated two families on fabricated fills.
Plan B+D from the post-mortem:

- Step B: SHADOW → CANARY gate now requires sum(shadow_pnl) > 0 in
  addition to fill count (MM_CANARY_MIN_PNL_PER_FILL_CENTS = 1¢).
  Spurious 1¢-YES fills that always resolved NO can no longer pass.
- Step D: new CANARY → FULL graduation gate requires
  MM_GRADUATION_MIN_PAIRED_N (20) paired live/shadow rows AND
  sum(live_pnl) / sum(shadow_pnl) >= MM_GRADUATION_MIN_PNL_RATIO
  (0.5). Live must capture at least half the P&L the shadow model
  predicted before we scale up.

evaluate_mm_graduation(conn, series) is the new CANARY→FULL
evaluator. evaluate_mm_kill_switch unchanged (stateless two-day
drawdown rule on live_pnl alone).

**T3.3 (reader migration)**

_attribute_live_fills_to_shadow_rows populates weather_mm_shadow.
live_pnl_cents from fills_ledger at settlement time. Without this
the graduation gate's `live_pnl_cents IS NOT NULL` filter matches
zero rows forever and CANARY is a terminal state.

annotate_shadow_pnl now calls the attributor as part of its
settlement pass — idempotent via WHERE ts_settle_unix IS NULL.

Migrated readers:
- bot/signals/regime.py: detect_regime reads fills from fills_ledger
- backtest_comprehensive.py: per-fill aggregations join fills_ledger

mm_processed_fills stays writable during T3.1→T3.3 transition; the
dual-run validator (T3.1) watches for divergence.

**bot/config.py** carries the B+D knobs plus a broader config wave:
- MM_CANARY_MIN_PNL_PER_FILL_CENTS, MM_GRADUATION_MIN_PAIRED_N,
  MM_GRADUATION_MIN_PNL_RATIO (B+D)
- MAX_EXPIRY_EXPOSURE_RATIO (per-settlement cap, consumed by the
  exposure refactor that follows)
- EXIT_EDGE_DECAY_RATIO, EXIT_TIME_BACKSTOP_*, EXIT_STALE_HOLD_HOURS
  (consumed by bot/core/exit_model.py in the next commit)
- MM_SIZING_* (consumed by bot/core/sizing.py in the next commit)

All share the same bot/config.py file, so they land as a single
config addition even though consumers land across multiple commits.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Pulls three distinct concerns out of trade.py / manage_positions
into testable bot/core/ modules:

- bot/core/sizing.py: Thompson-sampled MM sizing. Replaces the
  3-step SHADOW/CANARY/FULL multiplier gate with a posterior draw
  over realised per-fill P&L. Below MM_SIZING_MIN_N (5 fills),
  multiplier = 0 (shadow-equivalent). Above the target edge
  (MM_SIZING_TARGET_EDGE_CENTS = 2¢), multiplier = 1.0 (full
  MM_ORDER_SIZE). Cached for MM_SIZING_CACHE_TTL_S (300s) so
  within-cycle quote bursts see a stable multiplier.

- bot/core/exit_model.py: Directional exit evaluator. Three signals:
  - edge_decay: remaining_edge < entry_edge × EXIT_EDGE_DECAY_RATIO
    (default 0.33 — exit when ⅔ of entry edge has eroded)
  - time_backstop: inside EXIT_TIME_BACKSTOP_HOURS (0.25h default)
    of expiry with |remaining_edge| < EXIT_TIME_BACKSTOP_EDGE_ABS
    (2c default) — catches frozen-ensemble positions
  - stale_hold: held past EXIT_STALE_HOLD_HOURS (24h) flat or
    deteriorating

- bot/core/exposure.py: per-expiry cap enforcement. New
  check_expiry_exposure() caps concentration on any single
  settlement date at MAX_EXPIRY_EXPOSURE_RATIO (7.5% equity). The
  family cap alone pooled KXFED-27APR with KXFED-26OCT — the
  expiry cap separates them so one surprise FOMC can't compound.

- bot/core/money.py: no functional change, minor docstring nits.

All three modules are called from trade.py (wiring lands in the
final commit of this series). Tests cover the edge cases:
  - test_sizing: MIN_N gate, cap multiplier, cache TTL, single-
    observation variance degeneracy.
  - test_exit_model: each signal fires independently; combined-
    signal priority; entry-metadata-missing graceful degrade.
  - test_exposure: per-expiry cap applied after family cap,
    stacks with portfolio cap, handles resting+filled correctly.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Batch of incremental signal and learning improvements that landed
alongside the T1/T3/B+D work. Grouped because they're small per-file
changes that share the same goal: tighten the settlement-driven
learning loop so promotion decisions have cleaner inputs.

Signal sources (bot/signals/):
- sources/metar_observations.py, sources/weather.py, sources/madis.py:
  reads now defer to bot/daemon/stations.STATION_BY_SERIES instead of
  holding parallel station maps. Same code change as T1.1 on the
  daemon side, completed on the source side.
- weather_ensemble.py: router accepts the new STATION_BY_SERIES shape;
  correlated-group weighting respects the canonical station list.
- ensemble.py: pipeline-health counters safe under concurrent reads
  via PIPELINE_STATS_LOCK (daemon requirement).
- scoring/four_factor.py: minor score-normalisation adjustment.

Learning loop (bot/learning/):
- alpha_log.py: settlement back-fill hardened against missing
  ts_settle_unix. Idempotent via WHERE settlement_unix IS NULL.
- calibration.py: Platt persistence via kv_cache read on hot path
  rather than per-cycle refit (_cal_fit_and_persist still fits on
  every cycle, but consumers read cached curve).
- edge_convergence.py: reads ensemble_prob with per-side
  normalisation (CASE WHEN side='yes' THEN ep ELSE 1-ep END) —
  the same convention flip the Apr-17 v2 backtest fix landed for
  mm_orders.fair_value_cents.
- populate_from_alpha.py: cascades settled alpha_backtest into
  calibration / timing_patterns / edge_convergence / postmortems.
  Called each cycle via _alpha_populate_all.
- postmortems.py: loss-classification tagger robust to None-valued
  avg_entry from legacy rows.
- self_modifier.py: learned_config persistence gate now checks
  n_samples not just improvement delta (prevents overfit-to-noise).
- shadow_promotion.py, shadow_testing.py: share the new
  mm_promotion.get_mm_live_state signature (returns LiveFlag dataclass
  with .state + .last_promotion_unix, not bare string).
- timing_patterns.py: hour-of-day and hour-to-expiry buckets now
  keyed on LST-adjusted hour for weather series.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Provides compute_bakeoff() + render_bakeoff_report() for head-to-head
evaluation of competing strategy variants against the same settlement
universe. Uses the same settlement back-fill path as the learning
loop, so a bakeoff is just an alternate aggregation over
alpha_backtest rows — no extra shadow-mode wiring required.

Will be called from the daemon's periodic sweep once we have two
competing strategies to compare. For Phase 1 this lands as dormant
infrastructure; first consumer is the post-Phase-1 directional-live
cutover comparing ensemble-with-Platt vs ensemble-without.

Tests cover the degenerate cases: empty universe, single-strategy
input, tied scoring, and the edge where one strategy had zero
fills (returns None for the comparison, not an error).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…rift)

A battery of boring-but-critical guard tests that catch the classes
of mistake the Apr-17 incident and earlier audits identified:

- test_writer_ownership (tests/ + tests/daemon/): scans every
  SQL-write callsite in bot/ and asserts each target table has
  exactly one writer module. Multi-writer tables are how Apr-17
  snuck in — two paths touched weather_mm_shadow with different
  contracts. Registry is explicit so new tables must declare
  ownership or the test fails.

- test_no_secrets_in_repo: walks tracked files for API key, RSA
  key, and Telegram token patterns. Fail-closed on match. Prevents
  the KALSHI_PRIVATE_KEY or .env leakage that gitignore alone can't
  guarantee.

- test_db_discipline: every direct sqlite3 write outside of
  db_write_ctx() is flagged. Enforces the daemon's single-connection
  invariant (see bug thirdlayerinc#14 in CLAUDE.md regression watchlist).

- test_config_no_drift: asserts bot/config.py constants referenced
  by assertions in deploy/04_redeploy.sh still exist with compatible
  types. Catches the class of failure where a config rename in a
  PR passes tests but breaks the deploy-time import gate.

- test_client_order_id_coverage: every code path that emits a
  client_order_id is test-covered for the "no periods" invariant
  (Kalshi rejects dotted IDs — regression bug #1 in CLAUDE.md).

- test_integration_row_shape (daemon): one-shot integration test
  that boots the daemon briefly, posts a fake METAR, and asserts
  the resulting weather_mm_shadow row has the exact post-B+D shape
  (market_yes_bid non-zero, gate_should_quote 0 or 1, no NULL
  fair_value, etc). Catches Apr-17-class row-shape regressions
  before they hit production.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Commits the five markdown reports generated during Phase 1 planning
and incident response, plus the CLAUDE.md drift audit that reflects
the post-incident architecture.

Reports:
- AUDIT_T1_2_2026-04-20.md: pre-ship code review of the event-
  driven requote drivers + dispatcher before the T1.2 commit.
- GO_LIVE_REVIEW_2026-04-20.md: pre-live readiness checklist;
  source of the "human-in-the-loop on first LIVE_CANARY flip"
  gate that shadow_status.py now exposes.
- POSTMORTEM_SHADOW_DATA_CORRUPTION_2026-04-21.md: the Apr-17 →
  Apr-21 data-corruption incident writeup. Source of the B+D plan
  and the post-mortem follow-on list (#2 = shadow integrity
  monitor, which landed as shadow_integrity.py in commit 0962096).
- T3_FILLS_LEDGER_SCOPING.md: scoping doc for the canonical fills
  ledger (T3.1–T3.4). Current status noted in CLAUDE.md: T3.1 +
  T3.3 complete, T3.4 trade.py fills-write freeze pending.
- T4_CANARY_GATES_DESIGN_2026-04-20.md: design of the two-gate
  shadow→canary→full promotion that B+D implements.

CLAUDE.md: audits the codebase-vs-docs drift accumulated during
Phase 1:
- Replaces the deleted bot/market_maker/ section with the new
  bot/daemon/ structure.
- Adds T3.1/T3.3/B+D status markers to Phase 1 Work.
- Corrects mm_orders.fair_value_cents convention section (per-YES
  storage, not per-side — source of the Apr 17 v1 Brier 0.50 bug
  and now in the regression watchlist as thirdlayerinc#13).
- Adds bug thirdlayerinc#14 (daemon pollers writing without DB_WRITE_LOCK)
  and #15 (process-local DB assumption) to the regression watchlist.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Final wiring commit that connects the Phase 1 modules landed in this
series into the running system.

**trade.py**:
- Immutable initial-config snapshot: apply_phase_limits() and the
  active-feedback block now derive from _INITIAL_* rather than
  current mutated globals. Long-running daemon cycles no longer
  compound multiplications that drove KELLY_FRACTION → 0 and
  MIN_EDGE → ∞ over process lifetime. Guard test:
  tests/test_config_no_drift.py.
- Consumes bot/core/sizing.py, bot/core/exit_model.py, and
  bot/core/exposure.py.check_expiry_exposure. manage_positions now
  routes through the extracted exit_model evaluator.
- Graduated per-family sizing multiplier reads from
  mm_promotion.evaluate_mm_promotion which now returns the B+D
  two-gate state.
- Directional shadow evaluator and block-list intact, no semantic
  change.

**bot/daemon/main.py**:
Wires every new scheduler task:
- shadow_integrity @ 600s — Apr-17 data-corruption monitor
- fills_sync @ 60s — FillsWriter.sync_since with 120s overlap
- fills_validator @ 24h — dual-run divergence report
- wx_time_decay @ 30s — TimeDecayDriver tick
- forecast_refresh wraps with ForecastChangeDriver.on_refresh for
  material-change requotes
- Handler.on_fire wired to time_decay_driver.note_external_fire so
  METAR events reset the cadence clock
- AsyncEventDispatcher per-series worker pool constructed once,
  drained on shutdown alongside pollers
- Removes the threshold_tuner registration (module deleted)
- Health log now covers the new subsystems: wx_dispatch worker
  health, wx_time_decay cadence stats, wx_forecast_change fire
  counts, wx_handler synthetic-enqueue + rejection counts

**deploy/04_redeploy.sh**:
- rsync filter includes scripts/ (shadow_status.py is now shipped
  to the VPS)
- Import-check battery expanded with assertions for every Phase 1
  module: STATION_BY_SERIES, VALID_REASONS, FillsWriter,
  ValidationReport, MM_CANARY_MIN_PNL_PER_FILL_CENTS,
  MM_GRADUATION_MIN_PAIRED_N, _attribute_live_fills_to_shadow_rows,
  detect_regime (fills_ledger switch), shadow_integrity module.
- Every assertion is tagged with its originating task (T1.1, T1.2,
  T3.1, T3.3, B+D, shadow_integrity) so a future failure points to
  the story it's guarding.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…egression tests

Latent bug in bot/signals/ensemble.py: a single source that sat in N
correlated groups (e.g. `fred` is in cpi/fed/nfp/gdp) was counted N times
toward n_effective, inflating the directional edge-threshold tier
(5%/7%/10% scaling). Replaced with `claim by first matching group`
semantics: a source contributes 1.0 to the first group that owns it and
0 to subsequent groups. Verified monotone — new n ≤ old n — so the fix
can only tighten the threshold, never loosen it.

Backtest replay against 521 sourced rows in opportunity_log on the VPS
DB: every row was `ensemble(fred)` (economics families). OLD impl
returned n=4 → 5% tier; NEW returns n=1 → 10% tier. Zero historical
flips because all rows were MM (which doesn't gate on n_effective) and
no directional decisions exist in the captured window — so the fix is
forward-looking insurance for when directional goes live.

Also pins the rest of the Known Bug Patterns watchlist (CLAUDE.md) with
explicit regression tests:

  #5  fixed-point parsing — tests/test_fixed_point_parsing.py
  #4  inventory-zero-without-settlement — tests/test_inventory_zero_settlement_only.py
  thirdlayerinc#8  Tomorrow.io >7-day horizon — tests/signals/test_tomorrow_horizon.py
       + clamp at bot/signals/sources/weather.py
  thirdlayerinc#9  correlated double-count — tests/signals/test_correlated_double_count.py
  thirdlayerinc#10 MM spread fee floor — tests/test_mm_spread_fee_floor.py
  thirdlayerinc#12 cache bounded — tests/test_cache_bounded.py
       + TTLCache(maxsize=4096, ttl=3600) replacing unbounded {} in trade.py
  thirdlayerinc#13 fair_value_cents reader handling — tests/test_fair_value_cents_readers.py
       + `# fv-mixed-side-ok` ack markers in trade.py + backtest_comprehensive.py

CLAUDE.md Known Bug Patterns updated with per-pattern test references.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Introduce a precision-weighted multi-source Gaussian combine
(weather_ensemble_v2.predict_v2) gated behind WEATHER_ENSEMBLE_V2 env
flag (default false, falls back to v1 on any error). Adds:

- bot/signals/weather_sources.py — canonical source-name registry
  preventing recurrence of the open_meteo/"weather" drift bug.
- bot/signals/weather_ensemble_v2.py — A1–A5 precision-weighted combine
  with per-source bias/sigma calibration and effective-N discount.
- bot/signals/weather_forecast.py — abstraction layer that lets each
  source emit its internal Gaussian without re-fetching.
- weather_gaussian_snapshots_backfill, weather_metar_hourly_backfill —
  retroactive archive tables (separate from live weather_forecast_snapshots
  because they carry observed_high_f and are populated out-of-band).
- WeatherQuoter._compute_fair_value_v2 routing in weather_quoter.py,
  clamped to [2, 98] with v1 fallback on any v2 failure.

Each weather source now exposes a Gaussian-emit contract used by v2.
Writer-ownership registry updated to allow weather_ensemble_v2 to write
to weather_forecast_snapshots (dual-write with v1 during shadow soak).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
ijlu and others added 26 commits May 5, 2026 16:51
Phase 3d/3e shipped the fast-path in weather_ensemble_v2.predict_v2's
combine flow (used by WeatherQuoter), but cross_bracket_shadow has
its own combine path that calls _collect_gaussians + combine_gaussian
directly without the fast-path.

Symptom (caught post-deploy 2026-05-05 23:08): WeatherQuoter logs show
'tag=metar_post_peak_override' for KXHIGHNY-26MAY05-* markets at LST
18+, but cross_bracket_shadow's same-cycle scoring was using the wide-σ
combined estimate — meaning the strategy was making decisions with the
old broken σ even though the fast-path was active in the MM path.

Fix: apply _apply_metar_post_peak_override to the cross-bracket combine
input, same as predict_v2 step 1b. Single line of code; the function
is already public-by-convention (underscored but imported).

Test suite: 1917 pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Phase 3e shipped a per-city LST+stability gate
(is_post_peak_safe / _is_in_lst_gate) as the new primary entry filter.
The legacy TTE 3-7h band stayed in place AND was checked first,
which had two problems:

1. Suppressing legitimate marine-layer-city opportunities. LAX
   always_arm@LST 14 = TTE ~9h, above the old 7h cap. Fast-peak
   cities lost 2-4h of trading window/day to a stale TTE upper bound.

2. Misleading skip messages. "tte_28.2h_outside_band" hid the actual
   reason (LST date mismatch) when both gates would have rejected.

This commit:
- Drops TTE band to MIN=0.5h (avoid posting at-settle), MAX=24h
  (sanity ceiling, redundant with LST gate's date check).
- Reorders the per-leg gate to check LST first, then TTE backstop,
  so skip messages reflect the actual reason.
- Updates docstrings, log line ("outside_band" → "outside_backstop"),
  and the test that pinned the old "tte must reject" contract.

Net effect on trading: marine-layer cities gain 3-4h of trading
window/day (LAX LST 14-21 vs old LST ~16-21). NY/CHI/MIA/DEN
unchanged — their LST gate kicks in around peak+2 ≈ TTE 7-8h
anyway.

Test suite: 1917 pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
City-expansion Layer 2 prereq. We need historical bid/ask + capacity
for candidate cities (PHX/SEA/HOU/...) BEFORE promoting them, but the
trading cycle only fetches TRADE_SERIES_ALLOWLIST so candidates have
zero history today. Standalone 60s poller persists every weather
series in WEATHER_SNAPSHOT_SERIES (16 entries: 6 traded + 10
candidates) into kalshi_market_snapshots.

Write rules: change-detection (bid/ask/last/volume/status diff),
5-minute heartbeat, full-payload sample on first observation +
status transition + every hour. NULL payload otherwise — schema-
evolution safety net at ~3 GB/yr extra.

Field-name parsing matches Kalshi's actual /markets shape:
- `*_dollars` strings → cents via _price_to_cents (smart 0-1 vs >1)
- `*_fp` decimal strings → int via _parse_fp
- ISO timestamps → unix via _iso_to_unix
- series_ticker derived from event_ticker (not in response)

Cleanup task wired but inert (TTL=NULL by default); flip via
kv_cache:market_snapshots_ttl_days.
Cumulative branch since 2026-04-17 — Phase 1 infra + fills ledger + weather v2 + calibration investigation + cross-bracket strategy. See PR description for workstream breakdown.
…ecard

Self-contained brief for a fresh agent session to build
tools/ensemble_market_evaluator.py once snapshotter has ≥14 days of
data. Spec is measurement-only — does not modify the ensemble itself.

Deliverable: per-market scorecard ranking the 40 weather markets by
ensemble-vs-market-mid Brier delta, with per-source attribution,
calibration curves, time-decay skill, and edge-net-of-fees analysis.

Output gates Phase 2 (single-market improvements) and Phase 3
(hierarchical cross-market model). Without it, every subsequent
ensemble change is a guess.

Spec includes scope discipline (read-only, don't fix what you find),
data prereqs (≥14d snapshotter, settlement coverage, no in-flight
ensemble code changes), and 6 open methodology questions for human
sign-off before implementation.
Trailing commits on mm-calibration-timing that weren't pushed to origin
when PR #2 was merged. Includes calibration investigation
(bounded-Newton Platt + bake-off + raw-prob logging), full
cross-bracket strategy work, and the Phase 1 ensemble eval spec.

Production VPS already runs this code (rsync'd via deploy/04_redeploy.sh).
This merge brings main into sync with what's deployed.
Adds bot/scoring/trading_caps.py with cap_trading_prob() + per-source
hit counters, applied at every callsite where a model probability
becomes a trading decision (edge gate, conviction, sizing, fair-value).
Logging and calibration paths see raw model output unchanged — the cap
is strictly a trading-layer risk control.

Sites capped:
- bracket_portfolio._decide_leg (cross-bracket, the live path)
- market_scorer.score_market info_edge + duplicate sub-strategies
- four_factor.score_four_factors (replaces _clamp on ensemble_prob)
- trade.py:score_market info_edge + 4 sub-strategy edge calcs
- trade.py:kelly_contracts entry (defense-in-depth)

Sites intentionally not capped: safe_compounder (probs are market-
derived, structurally bounded), weather_quoter (existing [0.02, 0.98]
clamps are stricter), prob_for_kelly fallback (kelly_contracts caps
at entry).

Hit counters surfaced via the daemon health-log task at 300s — sudden
spikes per source indicate the model is regularly bumping the cap,
which would signal Phase 1 σ-inflation has degraded.

See memory/project_layer_separation_model_vs_trading.md for the
architectural rationale: model output stays free to express extreme
probabilities for honest calibration; the cap is downstream of the
model and never feeds the Platt fit.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Adds bot/learning/calibration_alarm.py — a daily scheduler task that
computes per-TTE-bucket mean(|z|) from settled weather forecasts and
fires Telegram alerts when calibration drifts.

Two alarms per bucket:
- Drift: 3-day rolling mean(|z|) above bucket threshold
- Spike: single-day mean(|z|) above bucket threshold

v1 thresholds (deliberately loose; tighten after ~30 days of real data
per memory/project_calibration_alarm_thresholds.md):

  TTE bucket | drift | spike
  >48h       | 1.5   | 2.5
  12-48h     | 1.2   | 2.0
  <12h       | 0.8   | 1.5

The <12h bucket is the primary signal — METAR is supposed to anchor
the model in that window, so any |z| spike there indicates a pipeline
break (METAR not feeding predict_v2, σ floor too low, μ stale), not
honest tail.

Data path:
- Predicted (μ, σ): weather_forecast_snapshots WHERE source='combined_v2',
  deduped to one snapshot per (ticker, hours_out) — last recording wins.
- Actual high: weather_metar_hourly_backfill.daily_high_f
- z = (actual - μ) / σ, bucketed by hours_out

Scheduler: registered as 'calibration_alarm' at 13:00 UTC daily
(09:00 EDT, 06:00 PDT — pre-market start, after overnight METAR
backfill completes).

Empty-state and below-MIN_SETTLEMENTS handling: silently log + skip,
never fire on insufficient data.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Closes the architectural loop where weather v2 output short-circuited
before apply_calibration_correction, breaking the layer-separation
principle that Platt belongs at the ensemble integration boundary and
applies uniformly to all sources. See
memory/project_layer_separation_model_vs_trading.md.

Behavior: gated by new WEATHER_V2_PLATT_ENABLED flag, default false.
With default flag, behavior is unchanged from pre-Phase-2 (raw v2
output returned clamped). When flipped on, v2 output flows through
apply_calibration_correction respecting CALIBRATION_ENABLED.

Why default off: the persisted Platt curve was fit predominantly on
v1 ensemble outputs (96.5% v1-weather as of 2026-04-27 audit). Current
state on prod has weather-family A=0.5 uniformly, B in [-1.13, -0.66] —
which aggressively shrinks raw v2 predictions toward ~24% (e.g.
p=0.85 → ~0.43). That shrinkage was correct for the overconfident
v1 ensemble; whether it remains appropriate after Phase 1's σ-inflation
fix is unverified empirically. Refit calibration on v2-only data
(filter alpha_backtest by ts_decision > Phase-1 ship) before flipping
the flag.

Tests cover the full flag matrix:
  - WEATHER_V2_PLATT_ENABLED=false → raw passthrough (current behavior)
  - flag=true, no curve dict → raw passthrough (defensive)
  - flag=true, CALIBRATION_ENABLED=true, real curve → Platt fires
    (verified: 0.85 raw → 0.435 after A=0.5, B=-1.13)
  - flag=true, CALIBRATION_ENABLED=false → global gate dominates, raw
  - flag=true, identity curve → no-op
  - Family-router path unchanged (regression guard)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
When pytest runs from inside a worktree at
.claude/worktrees/<name>/, every file's absolute p.parts contains
".claude" → the rglob-and-filter sweep excludes everything → the
sanity assertions (len(files) > 10/20) fail. Two callers had the
same bug.

Switch the exclusion check to p.relative_to(REPO_ROOT).parts so
".claude" only matches truly-nested worktrees, not the worktree
that IS the REPO_ROOT.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 incident: a deploy invoked from a worktree silently
rsynced the main checkout (city-expansion + uncommitted WIP)
instead of the worktree's state, because BOT_DIR was pinned to
$HOME/autoagent. Same class of silent state-mismatch as the
2026-05-01 .env overwrite documented inline.

Resolve BOT_DIR via `git rev-parse --show-toplevel` of the cwd.
Worktrees resolve to themselves; the main checkout resolves to
itself; running from outside any git repo errors out instead of
silently picking a stale checkout. Operator gets a clear "from:
<path>" echo at the top of the deploy.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Intermittent SQLITE_MISUSE ("bad parameter or other API misuse")
and partial-row TypeError ("'>' not supported between NoneType
and float") were appearing in daemon.log at ~4/day, exclusively
from kv_get. Both symptoms reduce to the same root cause: the
daemon shares one sqlite3 connection across pollers + the cycle
runner, and Python's sqlite3 wrapper is not safe under concurrent
.execute() on a single connection (check_same_thread=False
removes the Python guard but adds no serialization).

kv_set and kv_cleanup already serialize through DB_WRITE_LOCK;
kv_get was the sole reader claiming "lock-free under WAL", which
holds at the SQLite level for separate connections but not for
one shared connection. Acquire the same lock briefly for the
SELECT — kv reads are microseconds so the cost is negligible.

Also defensively skip rows with expires_at IS NULL so the
shadow_cal_bridge_watermark pattern (intentional NULL TTL) can't
trigger a TypeError if it's ever read via kv_get.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Both tests asserted a non-None Gaussian for KXHIGHMIA but used
real datetime.now() — the production code's LST-11 gate
(lst_offset=-5 for Miami) returns None when called before 16:00
UTC. Tests passed afternoon-onward and silently failed in the
morning.

Apply the same _FixedDT monkeypatch the other LST-aware tests in
this file already use (test_morning_call_returns_none_lst_under_11,
test_post_lst_11_call_uses_today_running_max), pinning "now" to
18:00 UTC so the gate always opens.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…ixes

Phase 2 already-shipped items now reaching main:
- Item 4: trading-time p_yes humility cap [0.01, 0.99] (4be73a1)
- Item 3: daily |z| Telegram calibration alarm (5dc7ce4)
- Item 2: wire predict_v2 through apply_calibration (e502781)

Follow-up fixes from the 2026-05-10 wrap session:
- Worktree-path test exclusion bug (17402b8)
- Deploy script BOT_DIR from cwd git toplevel (227031e)
- kv_get serialized under DB_WRITE_LOCK (58c13e1, deployed + verified)
- test_nws_5min wall-clock flakiness (3e13275)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Both items were shipped but the section had not been updated.

Item 8 (shadow→canary→full MM promotion) is fully implemented in
bot/learning/mm_promotion.py (evaluate_mm_promotion,
evaluate_mm_graduation, evaluate_mm_kill_switch,
run_mm_promotion_sweep) and wired into the daily
mm_promotion_sweep daemon task at bot/daemon/main.py.

Item 9 (T3.4 trade.py fills-write freeze) is complete: zero
production writers to mm_processed_fills remain (verified via
grep). FillsWriter is the sole writer of fills_ledger;
mm_processed_fills is reader-only via the dual-run validator.

No code change.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…ld drift

The 2026-05-12 audit caught a second instance of the same Kalshi format-
drift pattern that triggered the 2026-05-03 dual-format fix (commit
6a39dd7). Kalshi's /portfolio/fills response stopped echoing back
``client_order_id`` around 2026-05-10:

    Old keys: action, count_fp, created_time, fee_cost, fill_id,
              is_taker, market_ticker, no_price_dollars, order_id,
              side, subaccount_number, ticker, trade_id, ts,
              yes_price_dollars
    Missing:  client_order_id

Without it, ``default_source_tagger`` returns ``manual`` for every fill,
silently breaking per-strategy attribution: ``weather_mm_shadow.live_
pnl_cents`` back-fill joins zero rows, ``mm_promotion`` graduation can
never fire (CANARY becomes terminal), and ``backtest_comprehensive.py``
strategy slices are wrong for everything since May 11. The 2026-05-12
audit found the bot had logged 9 cross_bracket_live POSTED decisions on
May 11 against 0 ``cross_bracket`` source rows in ``fills_ledger`` —
the 12 corresponding fills had all collapsed into ``source='manual'``.

Recovery: record ``(order_id, client_order_id, source_hint)`` at post
time in ``posted_orders``, fall back to that lookup at fill-ingest time
when Kalshi's payload omits client_order_id.

Changes:
* bot/db.py: ``posted_orders`` table definition with order_id PK and
  indexes on posted_ts_unix and client_order_id. The table existed on
  prod (30 historical rows from an aborted backfill on May 7–10) but
  was never tracked in the schema. CREATE TABLE IF NOT EXISTS is
  idempotent against the existing prod table.
* bot/daemon/fills_writer.py: ``record_posted_order(conn, **kwargs)``
  helper, idempotent via INSERT OR IGNORE on order_id, holds
  ``DB_WRITE_LOCK`` via db_write_ctx. ``ingest_page`` falls back to
  posted_orders lookup when fill.client_order_id is missing. Adds
  ``cross_bracket`` and ``cross_bracket_exit`` to ALLOWED_SOURCES and
  routes ``mm_xb_*`` / ``mm_xb_exit_*`` prefixes in default_source_tagger
  (was collapsing to ``legacy``).
* bot/daemon/cross_bracket_shadow.py: call record_posted_order after
  successful api_post in _post_live_order.
* bot/daemon/cross_bracket_exit.py: same wiring + rename exit prefix
  from ``mm_xbexit_`` to ``mm_xb_exit_`` so the tagger can distinguish
  exits from entries. has_pending_exit accepts both prefixes for
  in-flight orders.
* tests/test_client_order_id_coverage.py: structural-invariant test
  now covers cross_bracket_shadow and cross_bracket_exit (was missing
  them — which is why this bug shipped silently). Allowed prefixes
  expanded with ``mm_xb_exit_`` and ``mm_xb_``.
* tests/test_posted_orders_fallback.py: new — pins (a) tagger routing
  for both cross_bracket prefixes, (b) record_posted_order
  idempotence + partial-row refusal, (c) end-to-end recovery when
  Kalshi omits client_order_id from the fill payload, (d) external
  fills still fall through to ``manual`` correctly.

Going forward the daemon recovers attribution automatically. A
follow-up offline backfill is required to repair existing May 11+
``fills_ledger`` rows that already tagged ``manual`` (out of scope
here — the live trading path is fixed but historical data is not).

2327 tests passing (2 unrelated env-blocked: cryptography ABI on
local Mac, no_secrets_in_repo unrelated).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…ns 0

Third instance of the Kalshi field-drift pattern (after 2026-05-03
count_fp / *_price_dollars and 2026-05-12 client_order_id removal).

Kalshi's /portfolio/settlements endpoint has been intermittently
returning ``revenue=0`` for valid winning settlements since at least
2026-04-12, and as of 2026-05-12 returns 0 for every settlement.
Verified against live API on 2026-05-12: every settlement in the
500-row page reports ``revenue: 0`` regardless of contracts held or
market_result. The bot's record_settlements() used this field directly
in ``profit = revenue - cost - fees``, so:

* Pure winners with no hedge: profit = 0 - cost - fees (looks like a
  total loss). For directional buys at low prices this was a small
  rounding error, but for high-priced legs it understated profit.
* Hedged positions (cross_bracket_exit pattern: 1 YES + 1 NO on same
  ticker): the hedge GUARANTEES a $1 payout on the winning leg
  regardless of outcome. ``revenue=0`` made each hedge show as a
  ~$0.90 phantom loss when it was actually a ~$0.10 win. The
  2026-05-12 audit found 13 cross-bracket hedged positions all
  mis-reported this way; the strategy's headline -$13.39 P&L was
  actually closer to -$3.35 after correcting hedge accounting.

Fix: compute revenue locally via ``settlement_revenue_cents(yes_count,
no_count, market_result)`` in bot/core/money.py. The formula is the
canonical Kalshi binary contract: each winning-side contract pays $1.00,
losing-side contracts pay $0. Identical for pure and hedged positions.

This is BUG #5 in the test_money.py regression watchlist (added).

11 new tests covering: pure YES/NO winner+loser, balanced hedge under
both outcomes, asymmetric hedge, zero position, unknown result,
fractional-count rounding, and the exact record_settlements call
shape with a Kalshi payload that reports ``revenue=0``.

2339 tests passing (2 skipped: cryptography ABI on local Mac and
no_secrets_in_repo, both unrelated).

Going-forward correctness only — historical settlements in the DB
remain mis-reported (separate one-time backfill needed, out of scope
here). The fix kicks in for every settlement recorded after deploy.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 audit Phase C.3 finding: the combined-Gaussian σ for KXHIGHDEN
is 1.4–4.2°F across recent decisions, while actual high RMSE was 11–12°F
across 5 directional losses on May 6 (actual 38.5, model 49.5, σ=1.38) and
May 11 (actual 85.5, model 73.0, σ=4.23). Both are 3+σ misses; 5/5
KXHIGHDEN directional cross-bracket bets resolved against us.

KXHIGHDEN is already blocked in DIRECTIONAL_BLOCKLIST and MM_BLOCKED_SERIES
for the same reason (Brier 0.316 vs other weather families ≈ 0.10). The
cross-bracket loop was the remaining gap; this closes it.

Changes:
* bot/config.py: ``CROSS_BRACKET_BLOCKLIST`` (env-overridable, default
  ``KXHIGHDEN``) — frozenset of family prefixes that are hard-banned
  regardless of kv-cache toggles. Distinct from the canary kv toggle
  (``cross_bracket_live:<family>``): blocklist is for known-broken
  families, kv is for staged rollout / temporary pauses.
* bot/daemon/cross_bracket_shadow.py: ``_is_family_live`` consults the
  blocklist before the kv lookup. Short-circuits to False for
  KXHIGHDEN even if env=true and kv=true (defends against accidental
  re-arm).
* bot/daemon/main.py: ``_run_cross_bracket_rearm`` explicitly writes
  False for blocked families so a leftover True from a prior arm
  decays out immediately rather than waiting on the 24h TTL. Log
  message now reports ``armed=`` / ``blocked=`` lists.
* tests/test_cross_bracket_live_gates.py: two new regression tests
  (blocklist overrides kv-true; case-insensitive family compare).

VPS kv override applied alongside deploy:
  UPDATE kv_cache SET value='false', expires_at=now+86400
   WHERE key='cross_bracket_live:KXHIGHDEN'

Plan is to remove KXHIGHDEN from the blocklist once σ inflation lands
(Phase D.1 — per-family RMS-of-residuals as a floor on the Gaussian
σ used at cross-bracket decision time).

2341 tests passing (2 unrelated skipped).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Two companion scripts for the 2026-05-12 audit aftermath. Going-forward
correctness was landed in 433ceb7 (posted_orders writer) and b4bf869
(settlement_revenue_cents). These tools sweep up the historical data.

tools/backfill_hedge_settlements.py — recompute settlements rows
that were written before BUG #5 was fixed:
  - For every settlement, look up the bot's (yes_qty, no_qty, fees)
    from fills_ledger and the authoritative market_result from
    alpha_backtest.
  - Recompute revenue via settlement_revenue_cents, then profit and
    won. UPDATE only if any field differs.
  - Idempotent re-run via field-equality check.
  - Dry-run by default; --apply writes.
  - Applied live on VPS: 14 rows corrected. Net P&L correction
    +$14.00 on historical cross_bracket totals (the 13 hedged winners
    that were silently bleeding $1 each, plus one asymmetric hedge
    that goes from -$1.21 to -$0.21).

tools/backfill_fills_source.py — re-tag fills_ledger rows that
landed as ``source='manual'`` because posted_orders wasn't being
written during the May 11+ window:
  - Rule 1: match by (ticker, side, ts ±60s) against
    alpha_backtest cross_bracket_live posted decisions →
    ``source='cross_bracket'``.
  - Rule 2: YES buy at ≤15¢ following a same-ticker NO entry within
    12h → ``source='cross_bracket_exit'`` (heuristic; the exit code
    path doesn't log to alpha_backtest, but the price+timing is
    diagnostic).
  - Anything that doesn't match either rule stays as ``manual``.
  - Applied live on VPS: 26 cross_bracket + 5 cross_bracket_exit
    recovered. 3 left as manual (likely real human-placed fills).

7-test regression suite for the hedge-settlements backfill covering:
hedged winner correction, hedged loser with corrected (still-negative)
profit, pure winner, pure loser unchanged (rows already correct stay
that way), no-bot-fills rows skipped, dry-run writes nothing,
idempotent re-apply.

2348 tests passing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…decision

The 2026-05-12 audit's most insidious finding: Kalshi removed
client_order_id from /portfolio/fills around 2026-05-10, and the bot
silently tagged every cross_bracket fill as 'manual' for two days
before anyone noticed. Same class as the 2026-05-03 dual-format fix —
field drift on a "stable" Kalshi field, no warning, just attribution
quietly going dark.

This adds the canary that would have caught it on day one. When
FillsWriter tags a fill as 'manual', it checks alpha_backtest for a
posted decision on the same (ticker, side) within the last 10 minutes.
If found, log a loud DRIFT ALERT pointing at the audit Phase A so the
next instance of the same bug is visible the moment it lands.

Heuristic carefully tuned:
* Window: 600s — covers post→fill latency plus retries, narrow enough
  to avoid false positives from unrelated bot+human activity on the
  same ticker hours apart.
* Same-side match required — a fill on the opposite side could be a
  hedge exit or unrelated trade.
* decision_outcome='posted' filter — shadow decisions don't matter.
* Logged at WARNING with the exact phrase "DRIFT ALERT" so log greps
  and ops alerts can pattern-match without false-positive risk.
* Lookup wrapped in try/except — a broken alert must not break the
  writer.

3 new regression tests:
  - Fires when a posted decision sits within window of a manual fill
  - Silent for genuine external fills (no matching decision)
  - Silent for old decisions outside the 10-min window

2351 tests passing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 audit Phase D.1 finding: the combined-Gaussian σ that
cross_bracket scores brackets against collapses to ~1°F post-peak
(METAR fast-path tightens it once the daily high looks locked), but
the empirical actual-vs-predicted RMSE over the last 18 days is
much wider — 1.34–2.39°F across the five non-Denver weather families.

Per-family RMSE (tools/sigma_residuals.py, n=10–16 per family):
    LAX   1.34°F    MIA   1.73°F    NY    1.86°F
    AUS   1.95°F    CHI   2.39°F    DEN   6.55°F (blocked)

With σ collapsed to 1°F, cross_bracket's conviction gate
(p ≥ 0.65 either way) fires on any bracket >1.4°F from μ — but
the ACTUAL high routinely lands 1–2σ from μ at that scale. So the
strategy was confidently shorting NO on brackets that genuinely had
~30% YES probability, picking up 0/29 directional bets through the
audit window.

Fix: add ``CROSS_BRACKET_FAMILY_SIGMA_FLOORS`` (per-family table,
env-overridable), and clamp σ in ``_score_one_settlement`` to
``max(combined.sigma_f, family_floor, physical_floor)``. Wider σ →
flatter bracket probabilities → conviction gate fires only on
genuine model-market disagreements, not on routine variance the
model already knows about.

Concrete impact: with σ=2.0 instead of σ=1.0 for KXHIGHNY, a bracket
that previously scored p_yes=0.005 (the conviction-gate-passing
"definitely not this bracket") now scores ~0.04 — still skew, but
no longer triggering the strategy's "I'm certain" branch.

The σ inflation also changes shadow scoring (deliberate — future
calibration training sees the new regime), so the calibration table
will drift over the next few days as samples accumulate under the
new σ. Watch the per-family Brier in backtest_comprehensive.

KXHIGHDEN keeps its hard block in CROSS_BRACKET_BLOCKLIST: 6.5°F
empirical floor would essentially flatten every bracket probability,
preventing the strategy from firing anyway. Block is cleaner than
"infinite σ" as a way of saying "we don't trade this".

Companion tool: tools/sigma_residuals.py — recomputes the per-family
RMSE from weather_forecast_snapshots × alpha_backtest. Re-run
periodically; if the floors drift materially, update the constants
(test_cross_bracket_live_gates.py pins them and will fail loudly).

Test plan:
  - test_family_sigma_floors_table_defaults — pins the constants
  - test_family_sigma_floor_env_override — env var path works

2353 tests passing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The 2026-05-12 audit's deepest finding: the bot's ``metar`` source
isn't actually a METAR observation channel — its μ
(``expected_eventual_high``) blends running_high with the NWP-derived
forecast_high and a diurnal projection. On days when NWP misses (cold
fronts in DEN, heat domes in AUS), the blended μ carries a +5–15°F
bias, which the post-peak fast-path then locks in by collapsing σ to
1.0°F. Cross-bracket fires confidently against well-priced markets
and loses (5/5 KXHIGHDEN directional losses in the audit window).

Single concrete example — KXHIGHDEN-26MAY06 at decision time:
  actual METAR running max  = 38°F (cold front held the day's high)
  bot's `metar` source μ    = 48°F (NWP forecast was 54°F, blended in)
  bot's combined_v2 μ       = 48°F, σ = 1.0°F (fast-path locked)
  actual day's high         = 38°F → bracket B38.5 won
  bot bought NO at 5¢ on B38.5 thinking p_yes = 0.005, lost.

Josh's intuition for the fix: each source should represent ONE thing
and combine_gaussian should do the weighting. The METAR channel
should carry the running max with diurnal-RMSE σ; NWP feeds 5+ other
sources (nbm/hrrr/nws_point/ecmwf/gem/icon/etc) which the combine
already weights. Removing NWP from the METAR channel eliminates the
double-counting and lets the combine widen σ when NWP and obs
disagree.

Shipped behavior here is shadow-only:
* New side-channel ``_ALT_MU_RUNNING_HIGH`` stashes
  (μ=running_high, σ=diurnal_rmse_or_2.0°F_fallback) on every cycle
* Snapshot writer emits a parallel ``metar_running_only`` row in
  weather_forecast_snapshots alongside the existing ``metar`` row
* No change to the live Gaussian path (default flag off)
* Live cutover is gated by ``WEATHER_METAR_USE_RUNNING_HIGH_ONLY=true``
  — flip after ~1 week of shadow data confirms the alt is better-
  calibrated against settled outcomes
* When flag flips on, the existing D.1 per-family σ floors
  (commit 0985437) should probably come out — both target the same
  symptom; the F.4 cure is upstream and cleaner

The σ fallback (2.0°F when no diurnal fit) is wider than the existing
past-peak clamp (0.3°F) and the post-peak fast-path floor (1.0°F).
This is deliberate — claim less precision when only the running max
grounds μ, not more.

8 new regression tests pin:
- stash semantics (with/without diurnal fit, zero RMSE → fallback)
- pop semantics (prevents stale reads on a missed cycle)
- flag-off path: live μ uses blended forecast, alt still stashed
- flag-on path: live μ == running_high
- past-peak path: stashes the alt with the wider fallback σ
- default flag is False (regression guard against premature cutover)

2361 tests passing.

Follow-up plan (not landed yet):
  F.5 — analysis tool over weather_forecast_snapshots comparing the
        new ``metar_running_only`` rows vs ``metar`` rows against
        settled outcomes. Run after 7 days of shadow data.
  F.6 — once shadow validates, flip ``WEATHER_METAR_USE_RUNNING_HIGH_ONLY``
        and revert commit 0985437's D.1 per-family σ floors.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@ijlu

ijlu commented May 12, 2026

Copy link
Copy Markdown
Author

Re-homed to ijlu/autoagent — merged at ijlu#3. The cross-fork target was inadvertent; ijlu/autoagent is now the canonical home for this work.

@ijlu ijlu closed this May 12, 2026
@ijlu
ijlu deleted the claude/sleepy-hofstadter-1d66bc branch May 12, 2026 22:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant