abyXsmart commited on
Commit
5f776b1
Β·
verified Β·
1 Parent(s): 71fe8ee

Upload 20 files

Browse files
Files changed (2) hide show
  1. IMPLEMENTATION_PLAN_v7.5.md +266 -445
  2. Log.md +113 -0
IMPLEMENTATION_PLAN_v7.5.md CHANGED
@@ -1,477 +1,298 @@
1
- # FVG-Delta Crypto Signal Core β€” v7.5 Implementation Plan (Build Handover)
2
 
3
- > Author: Session 13 (diagnosis agent). Reader: the build agent who will implement.
4
- > Status of THIS file: PLAN ONLY. No engine code was changed in Session 13.
5
- > Golden rules: single-file/flat layout (phone uploads one file at a time). Do NOT touch
6
- > the UI/layout or Stage 0–3 logic β€” they work. Bump version to **7.5** everywhere.
7
- > Casing: Title Case for short labels/phrases; Sentence case for full sentences.
 
8
 
9
  ---
10
 
11
- ## 0. What is already PROVEN (do not re-investigate β€” wastes credit)
12
-
13
- All verified live by Session 13 from the box against the user's real proxy + MEXC:
14
-
15
- 1. **Telegram transport is FINE.** A real matplotlib PNG sent through the user's Deno proxy
16
- (`https://fvg-delta-telegram-proxy.profitxpilot.deno.net`) returned `ok:true`,
17
- message_id 292, delivered to channel `-1002017507364`. The proxy, multipart format,
18
- token and chat-id all work. **Any photo bug is app-side, not transport.**
19
- 2. **MEXC data facts** (public, no key):
20
- - `/contract/deals/{sym}` caps at **100 rows** (code requests 200; ignored). 100 deals
21
- span ~8.6s on BTC, ~71s PEPE, ~247s DOGE. The current "CVD" is an ~8-second snapshot
22
- grabbed once per cycle, UNANCHORED to the zone β†’ this is the math root of chip jitter.
23
- - **No historical OI endpoint** (all paths 404). Only a live snapshot `holdVol` on
24
- `/contract/ticker` (918-symbol universe, one call) + `fundingRate` + `indexPrice`.
25
- - **1-minute klines EXIST**: `/contract/kline/{sym}?interval=Min1` β†’ fields
26
- time/open/close/high/low/vol/amount(+real*). 15 Min1 bars per 15m candle.
27
- 3. **Index drift is already fixed** via `_rebase_indices` (ts→idx each cycle). Do not "fix" it.
28
- 4. **draw_chart already closes figures** (`plt.close(fig)`), so no figure leak.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  ---
31
 
32
- ## 1. SCOPE (the six workstreams). Implement in this order.
33
 
34
- - **WS-1** Telegram entry-alert bug (highest ROI, smallest change).
35
- - **WS-2** Chart window so locked BoS/impulse stay in frame + screenshot never degrades.
36
- - **WS-3** Single dynamic structural TP (remove TP2 everywhere; keep leverage dynamic).
37
- - **WS-4** Real, zone-anchored order flow (the footprint) + persisted OI.
38
- - **WS-5** Stage-4 predictive promotion = confluence STATE recognition (not a blended score).
39
- - **WS-6** Stage-5 Guardian = Trade Thesis Ledger (kill the permanent terminal latch).
40
 
41
- Each workstream below: ROOT CAUSE (file:line) β†’ CHANGE β†’ TEST β†’ DONE-WHEN.
 
42
 
43
- ---
44
-
45
- ## WS-1 β€” Telegram: Stage-5 entry alert never sends (photo AND text)
46
-
47
- **ROOT CAUSE (definitive, code-verified).** `_send_stage4()` (app.py L4470) starts with
48
- `if not st.setup or st.stage != 4: return False`. It is called ONLY from the
49
- `if st.stage == 5 ...` block (L4507 β†’ L4511). `process_symbol` promotes 4β†’5 BEFORE
50
- `maybe_send_stage_alerts` runs (L4855), so at call time `st.stage == 5` β†’ the guard returns
51
- False IMMEDIATELY. No `send_photo`, no `send_text`, nothing logged β†’ the Recent-Alerts row
52
- reads **"Failed: photo or text"** forever (re-fires every cycle because `st.stage4_alerted`
53
- only latches on success L4512). This matches the user's screenshot exactly. Received TP1/SL/
54
- TP2/BE/test texts come from OTHER functions (`send_trade_event_alert` L4522, `telegram_selftest`
55
- L4644) which call `send_text` directly β€” that is why "text works but the chart never arrives."
56
-
57
- **CHANGE.**
58
- 1. In `_send_stage4` change the guard to accept the promoted stage:
59
- `if not st.setup or st.stage not in (4, 5): return False`.
60
- 2. Rename `_send_stage4` β†’ `_send_entry_alert` (update call site L4511 + the `_ = _send_stage3`
61
- comment). Keep behaviour otherwise identical.
62
- 3. Capture the photo result so the badge is honest:
63
- `photo_ok = await TG.send_photo(...)` then `text_ok = await TG.send_text(...)`;
64
- delivery = "Ok" if text_ok else "Failed"; if `text_ok and not photo_ok` β†’ "Sent (No Chart)".
65
- Latch `st.stage4_alerted = True` when `text_ok` (stops re-firing even if chart fails).
66
- 4. **Test button parity:** `telegram_selftest` (L4612) sends TEXT ONLY. Add a tiny `send_photo`
67
- (small BTC `draw_chart` or a 1-bar placeholder PNG) and report `photo_ok` separately in the
68
- returned dict + Recent-Alerts badge, so photo health is visible. This is why the user trusted
69
- a green test while photos were dead.
70
-
71
- **TEST.** Force a synthetic Stage-5 (or temporarily call `_send_entry_alert` from the test
72
- route) β†’ confirm BOTH chart and levels arrive and the badge says "Ok"; confirm no per-cycle spam.
73
-
74
- **DONE-WHEN.** A real verified entry delivers chart + text once; badge "Ok"; no repeat rows.
75
-
76
- ---
77
-
78
- ## WS-2 β€” Chart: locked BoS/impulse leave frame; long trades degrade the screenshot
79
-
80
- **ROOT CAUSE.** `draw_chart` (L2789) uses a FIXED `view = bars[-120:]`. When a setup is older
81
- than 120 candles, the impulse leg (L2827-2836) and the locked BoS anchor→break segment fall
82
- outside the window, so the impulse is omitted and the BoS drops to a full-width `axhline` (the
83
- "line stretches to current price" the user sees). No y-axis clamp β†’ a big move squashes candles
84
- into a thin band ("broken" screenshot). `_rebase_indices` already keeps the INDICES correct β€”
85
- the bug is purely the drawing WINDOW, not drift.
86
-
87
- **CHANGE (only `draw_chart`; leave `draw_trade_chart` alone β€” history snapshots are fine).**
88
- 1. Replace `bars[-120:]` with a **setup-anchored dynamic window**:
89
- - `anchor = min(z.impulse_start_idx, st.first_seen_bos_anchor_idx or z.impulse_start_idx)`.
90
- - `left = max(0, anchor - 5)`; `view = bars[left:]`; `start_idx = left`.
91
- - Width cap: `CHART_MAX_VIEW = _i("CHART_MAX_VIEW", 220)`. If the window would exceed it,
92
- prefer keeping the anchor visible (`left = max(0, anchor - 5)`) even if wider β€” never drop
93
- the anchor. Goal: impulse + FVG + BoS anchor→break + entry + current price all in frame.
94
- 2. **Keep the locked BoS as a SEGMENT** (anchor x β†’ break x) with the diamond/arrow markers β€”
95
- never the full-width fallback (the anchor now stays in view).
96
- 3. **Y-bounds guard:** compute y-range from candle highs/lows AND the level lines
97
- (entry/sl/tp), then `ax.set_ylim(lo - pad, hi + pad)`, `pad β‰ˆ 0.04*(hi-lo)`, so nothing is
98
- clipped and candles stay readable on long moves.
99
-
100
- **TEST.** Render `draw_chart` for (a) fresh setup, (b) synthetic anchor 300 candles back,
101
- (c) synthetic big-move trade. Assert PNG > 0 bytes, BoS is a segment (not edge-to-edge),
102
- candles not squashed. Use a local Agg harness.
103
-
104
- **DONE-WHEN.** BoS/impulse stay locked + visible at any trade age; no degraded/clipped charts.
105
 
106
  ---
107
 
108
- ## WS-3 β€” One dynamic structural TP (remove TP1/TP2 split)
109
-
110
- **USER INTENT.** A single, ACHIEVABLE, structurally-placed TP (next opposing liquidity:
111
- opposing FVG edge / swing H-L / equal-H/L pool / range EQ), leverage STILL dynamic
112
- (`_auto_leverage(stop_pct)` unchanged β†’ SL β‰ˆ -40/-60% margin). Remove TP2 from engine, tables,
113
- trade history, metrics, Telegram, settings, charts.
114
-
115
- **PERSISTENCE β€” DO NOT BREAK /data (verified safe path).** SQLite `trades` has FIXED columns
116
- `(...entry, sl, tp1, tp2, stop_pct, data)` with `INSERT OR REPLACE` + a JSON `data` catch-all
117
- (app.py L929/960; same schema duplicated in start.sh L43). Rules:
118
- - **NEVER drop/recreate the table** (WAL + mid-write = corruption).
119
- - **ADDITIVE only:** `ALTER TABLE trades ADD COLUMN tp REAL` inside try/except (column-exists is
120
- fine), guarded by the existing `CREATE TABLE IF NOT EXISTS`. Back up `trades.db`β†’`.bak` first.
121
- - New trades write `tp`, leave `tp2` NULL. **Read back-compat:** trades.html `rOf` (L145-160)
122
- must branch: if `tp` present β†’ single-TP math (TP=+R, SL=-1R, manual=realized); else old
123
- 0.5*R1+0.5*R2 path so the existing ~17 trades still render right.
124
-
125
- **CHANGE.**
126
- - `build_trade_levels` (L2170): compute ONE `tp` = nearest valid opposing-liquidity level beyond
127
- entry (reuse `_nearest_opposing_zone` L3741 / `_nearest_swing_target`) with an RR floor so it
128
- isn't sub-1R. Return `tp` (drop tp1/tp2/tp3; keep rr, risk_unit, stop_pct, leverage,
129
- target_source).
130
- - `_trade_outcome` (L1084) + `_trade_lifecycle` (L1128): collapse to SL / TP / (optional BE).
131
- **RECOMMENDED (tell user):** keep a Break-Even mechanic (SLβ†’BE after β‰₯1R or an intermediate
132
- structure tap), CFG toggle `single_tp_breakeven_enabled` (default on) β€” at 33% win-rate,
133
- losing the only loss-protection can push expectancy negative.
134
- - `_pre_entry_resolution` (L3428): same semantics, reads `tp` not `tp2`.
135
- - `_send_entry_alert` (L4476) + `send_trade_event_alert` (L4522): one TP line; outcomes
136
- "TP Hit"/"SL Hit"/"Break-Even".
137
- - `draw_chart` + `draw_trade_chart`: one TP line.
138
- - `trades.html`: m-tp1/m-tp2 cards β†’ one "TP Hits" card; TP1/TP2 cols β†’ one TP col; fix
139
- `cls()`/`outLabel()`/`computeMetrics` for single TP (keep old-row back-compat).
140
- - `settings_schema.json`+settings: remove `TP2_RR` or repurpose as `TP_MIN_RR`. `market.js`:
141
- tp1/tp2 NOTIFY/SOUND β†’ single `tp`.
142
- - Phase labels `advancing_tp1/at_tp1/advancing_tp2/at_tp2` β†’ `advancing_tp/at_tp`.
143
-
144
- **TEST.** Migration on a COPY of trades.db (old rows intact + render); new single-TP trade writes
145
- `tp`; node-check trades.html metrics for old(2-TP)+new(1-TP) rows; py_compile.
146
-
147
- **DONE-WHEN.** No TP2 anywhere; old history still correct; /data intact.
148
 
149
  ---
150
 
151
- ## WS-4 β€” Real zone-anchored order flow (the footprint) + persisted OI
152
-
153
- **ROOT CAUSE of "random chips/verdict".** `load_cvd` (L3675) = ~8s rolling snapshot, refetched
154
- each cycle, not anchored to the zone; `_cvd_proxy` (L3699) = candle close-location = price
155
- relabeled as flow (circular); OI history (`g_oi_hist`) is in-memory, wiped on restart, <2
156
- samples early β†’ defaults then flips. Averaging these (`_g_wavg`) pins Drive/Risk near 50 and
157
- twitches. The 8s sample of an hours-long battle, fresh each cycle, IS the oscillation.
158
-
159
- **CHANGE β€” make flow a WINDOW measurement, anchored at zone entry, persisted to /data.**
160
- 1. **Footprint buffer per active symbol**, started when price first enters the FVG (Stage 3β†’4),
161
- persisted to /data (JSON, atomic write like the icon map L1355). Per cycle accumulate:
162
- - **Signed delta** from `/contract/deals` (cap 100; sign by `T`: 1=buy, 2=sell) appended to a
163
- cumulative running total for THIS zone window (NOT reset each cycle).
164
- - **Min1-bar delta backbone** (always-on, robust): pull `/contract/kline?interval=Min1` for
165
- the zone-interaction window, sign each Min1 `vol` by close-location, net it. This is the
166
- dependable signal; the deals tape is a higher-fidelity overlay for liquid pairs.
167
- - **OI delta:** snapshot `holdVol` from the per-cycle `/contract/ticker` (already fetched β€”
168
- `refresh_oi_funding` L4370) into a PERSISTED per-symbol series in /data (replace in-memory
169
- `g_oi_hist`). Compute Ξ” over the window.
170
- 2. **Derived reads** (feed WS-5/WS-6):
171
- - `absorption` = delta turning POSITIVE while price HOLDS a discount FVG (long) / mirror.
172
- - `distribution` = delta negative + OI rising against while price stalls.
173
- - `flow_side` = sign of cumulative window delta.
174
- 3. Persist + restore on boot; clear when the trade closes / setup invalidates.
175
-
176
- **TEST.** Live probe (shown working) that deals + Min1 + ticker return usable data; unit-test the
177
- signing + accumulation; restart and confirm the footprint survives.
178
-
179
- **DONE-WHEN.** "Who's dominating in the FVG" is a real cumulative measurement that survives
180
- restart and does not reset each cycle.
 
 
 
 
 
 
 
 
 
181
 
182
  ---
183
 
184
- ## WS-5 β€” Stage-4 promotion: confluence STATE recognition (predictive, not averaged)
185
-
186
- **ROOT CAUSE.** `evaluate_pre_entry_conviction` (L3463) blends 8 signals via `_g_wavg` (L3610).
187
- The biggest weight `c_w_align=22` (E1) is `_trend_of` EMA = the LAGGING gate the user removed β€”
188
- green only AFTER price moves, so promotion is late and price tags TP in Stage 4. E6 reads
189
- `bars[-1]` (FORMING candle) β†’ intrabar flips. Leading signals (sweep-reclaim E8 weight 10,
190
- premium/discount, displacement) are underweighted. Empirically (user's extended-test log)
191
- conviction was ANTI-correlated with outcome (winners scored lower than the SL loser).
192
-
193
- **CHANGE β€” replace the blended score with a CONFLUENCE STACK (count of discrete aligned facts).**
194
- 1. Build LEADING preconditions, each a hard boolean:
195
- - HTF **location** permission: price in discount(long)/premium(short) of HTF range (use swing
196
- structure / range, NOT EMA trend).
197
- - **Liquidity swept + reclaimed** (E8 logic β€” the crown jewel).
198
- - **OB + FVG overlap** at the zone.
199
- - **Displacement origin** (impulse moved β‰₯ N ATR β€” commitment).
200
- - **Footprint side = our side** (WS-4).
201
- - **BTC not actively opposing** (keep the single-candle veto L3490-3501 as PERMISSION).
202
- - **Clear path to TP** (no opposing zone between entry and target).
203
- 2. **Promotion = N-of-M met** (e.g. β‰₯5 of 7, `conviction_min_confluence`), NOT a weighted
204
- average. Counting discrete facts kills "too many unqualified" promotions (averaging lets one
205
- strong input mask four weak ones).
206
- 3. **Adaptive confirmation** (fixes "TP hit in Stage 4 before promotion"):
207
- - Strong stack β†’ promote on the TRIGGER event (sweep-reclaim / absorption flip) β€” enter at
208
- the base, before the move.
209
- - Medium stack β†’ wait for the confirmation candle (current behaviour).
210
- - Weak stack β†’ do not promote.
211
- 4. Replace E1's EMA reading with location/permission. Fix E6 to read the LAST CLOSED candle
212
- (`bars[-2]`), never `bars[-1]`.
213
- 5. Keep `evaluate_entry_filters` as the disabled legacy fallback.
214
-
215
- **TEST.** Replay the user's logged setups (winners should stack higher than the SL loser);
216
- confirm no `bars[-1]` reads remain in the promotion path; py_compile.
217
-
218
- **DONE-WHEN.** Promotion is a discrete, leading, restart-stable decision that fires before the
219
- move and rejects low-confluence setups.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  ---
222
 
223
- ## WS-6 β€” Stage-5 Guardian: Trade Thesis Ledger (kill the permanent terminal latch)
224
-
225
- **ROOT CAUSE.** `evaluate_trade_guardian` builds Drive/Risk via `_g_wavg` (L4183/4271) β†’ pinned
226
- near 50, twitchy. The terminal latch (L4302-4312) sets `st.g_terminal=True` PERMANENTLY;
227
- L4335-4344 then RETURNS the frozen "Close Trade Before Reversal" forever, BEFORE the verdict
228
- machine runs. One transient concurrence latches it; recovery can't clear it. The live ENS
229
- screenshot proves it: Drive 56 > Risk 34, all green chips, yet verdict "Close … 90%". Verdict
230
- also fires terminal-exit on IN-PROFIT, still-rising trades (Drive>Risk) β†’ cuts winners (user's
231
- closed trades: MFE 1.68R/1.8R cut early). `_commit_verdict` debounce only makes the WRONG signal
232
- stable.
233
-
234
- **CHANGE β€” state recognition, not scoring; advisory must be LIVE + REVERSIBLE.**
235
- 1. **Freeze a thesis CONTRACT at entry** (stable by construction): swept liquidity, origin
236
- FVG/OB, structural INVALIDATION level, target liquidity pool.
237
- 2. **Three structural questions** (replace the 12 jittery chips as the DRIVER; chips may stay as
238
- cosmetic detail but must DERIVE from these so they can never contradict the verdict):
239
- - (a) Is the structural invalidation level intact? β†’ Hold / Exit.
240
- - (b) Has price reached the target pool and reacted there? β†’ Scale / Trail.
241
- - (c) Is the footprint (WS-4) still on our side post-entry? β†’ Conviction.
242
- 3. **Retrace-vs-reversal done right** (existing `healthy_retrace` guard L4296 is the right shape
243
- but fed the 8s snapshot β†’ misfires): HOLD a healthy pullback (low vol + FVG holds + no LTF
244
- CHoCH against + footprint neutral/with); EXIT only on a STRUCTURAL reversal (expanding vol +
245
- close THROUGH the FVG + LTF CHoCH against + footprint flip). Feed it the real footprint.
246
- 4. **KILL the permanent freeze.** The exit recommendation must be LIVE + REVERSIBLE β€” withdraw it
247
- if structure reclaims. Remove the `st.g_terminal` permanent-return path (L4335-4344); replace
248
- with a derived, debounced-but-reversible verdict. Keep ONE one-shot Telegram alert when an exit
249
- FIRST becomes recommended, but allow it to clear.
250
- 5. **Give-back stop logic** (mechanical, not a "verdict"; MFE/MAE already at L4095): on
251
- `single_tp_breakeven_enabled`, SLβ†’BE after β‰₯1R; optional trail to the next STRUCTURAL level
252
- (not a fixed %). Protects winners without the Guardian cutting them.
253
- 6. All LTF/guardian inputs must use CLOSED candles (`_ltf_structure` already slices `bars[:-1]` β€”
254
- verify the rest do too; no `bars[-1]` decisions).
255
-
256
- **TEST.** Replay ENS-like state (Drive>Risk, green) β†’ verdict Hold, not Close. Replay a real
257
- reversal β†’ Exit, and confirm it CLEARS when structure reclaims. Confirm in-profit rising trades
258
- are not exited.
259
-
260
- **DONE-WHEN.** Verdict tracks structure, never contradicts its own chips, doesn't cut winners,
261
- recovers from a transient scare.
262
 
263
  ---
264
 
265
- ## 2. Cross-cutting requirements (the build agent MUST do all of these)
266
-
267
- - **Version to 7.5 everywhere:** `ENGINE_VERSION` (app.py L54, currently "7.0"), SKILL.md
268
- (`version: 7.5.0` + title), README.md, AGENT.md, STRATEGY_DETAILED_SPEC (add a v7.5 section),
269
- Log.md, and the export zip name. Reconcile all `7.0`/`v7.0` references to 7.5.
270
- - **Casing convention:** Title Case for short labels / buttons / phrases (e.g. "TP Hit",
271
- "Holding Entry Zone"); Sentence case for full sentences in messages and docs.
272
- - **Do NOT touch:** UI layout/CSS, Stage 0-3 detection logic, `_rebase_indices` (drift already
273
- fixed), HF README metadata header, the Deno proxy worker (it works).
274
- - **Persistence discipline:** every /data write must be additive + atomic + restart-safe; never
275
- drop/recreate the trades table; back up `trades.db` before the WS-3 migration.
276
- - **No `bars[-1]` decisions:** all stage/guardian/promotion logic decides on the last CLOSED
277
- candle (`bars[-2]`); `bars[-1]` (forming) is for display only.
278
-
279
- ## 3. Dockerfile (ensure `web/Dockerfile` exists and is correct)
280
-
281
- For the Hugging Face Docker SDK:
282
- - Base `python:3.11-slim`; install `libfreetype6 libpng16-16` (matplotlib Agg runtime).
283
- - `pip install -r requirements.txt` (fastapi, uvicorn[standard], aiohttp, numpy, matplotlib,
284
- python-dotenv, brotli).
285
- - `/data` writable; `ENV MPLCONFIGDIR=/data/mplconfig`.
286
- - `EXPOSE 7860`; CMD runs `preflight_check.py` then
287
- `uvicorn app:app --host 0.0.0.0 --port 7860` (or `start.sh`).
288
- - For apt-list cleanup use a `find ... -delete` style command (the box safety filter rejects
289
- recursive force-delete on apt lists).
290
-
291
- ## 4. Suggested build order & checkpoints
292
-
293
- 1. WS-1 (Telegram) - smallest, unblocks live verification of everything else.
294
- 2. WS-2 (chart window) - so screenshots are usable while testing.
295
- 3. WS-4 (footprint + persisted OI) - the data foundation for WS-5 & WS-6.
296
- 4. WS-5 (Stage-4 confluence promotion).
297
- 5. WS-6 (Stage-5 Thesis Ledger).
298
- 6. WS-3 (single TP) - touches the widest surface; do with full attention + DB backup.
299
-
300
- After EACH workstream: `python -m py_compile app.py`, `node --check market.js`, TestClient boot
301
- (`SCAN_ENABLED=false`) so `/ /api/state /trades /settings` all return 200, then paste the file
302
- path in chat (per the user's modular rule). Re-export the zip only at the end.
303
-
304
- ## 5. Test matrix (must all be green before export)
305
-
306
- - py_compile app.py; node --check market.js + trades.html embedded JS.
307
- - TestClient boot: /, /api/state, /trades, /settings, /api/trades, /market.js, /settings.js β†’ 200.
308
- - WS-1: synthetic Stage-5 gives chart + text delivered once; badge "Ok"; no per-cycle repeat.
309
- - WS-2: draw_chart for fresh / old-anchor / big-move setups β†’ BoS is a segment, candles readable.
310
- - WS-3: trades.db migration on a copy β†’ old rows render; new trade writes `tp`; metrics correct.
311
- - WS-4: live deals + Min1 + ticker return data; footprint survives a restart.
312
- - WS-5: logged winners stack higher than the SL loser; no `bars[-1]` in promotion path.
313
- - WS-6: ENS-like (Drive>Risk green) β†’ Hold; real reversal β†’ Exit that CLEARS on reclaim.
314
-
315
- ## 6. Export
316
-
317
- When all green, rebuild **`FVG-Delta Crypto Signal Core v7.5.zip`** with every flat file in
318
- `web/` (engine, dashboards, settings, market.js, proxy worker, Dockerfile, start.sh,
319
- run_one_shot.sh, preflight_check.py, requirements.txt, AGENT.md, STRATEGY_DETAILED_SPEC,
320
- VARIABLES_AND_SECRETS_GUIDE, README, SKILL.md, Log.md, this plan) - excluding screenshots and
321
- the uploads folder. Update Log.md with a Session-14 completion entry.
322
 
323
- ---
324
- _End of v7.5 implementation plan. Diagnosis evidence lives in Log.md Session 13._
 
 
 
 
 
 
325
 
326
  ---
327
 
328
- ## WS-7 β€” Entry-Model Recognition & Human-Like Conviction (Stage 4 brain + Stage 5 print)
329
-
330
- **GOAL.** Make Stage 4 reason like an experienced SMC trader: recognise WHICH entry model is
331
- playing out, score the trade with dynamic, model-specific logic, and only promote when the model
332
- is genuinely valid. On promotion, Stage 5 prints the exact position details for THAT model. Every
333
- segment must adapt to the live market, not run one rigid rule.
334
-
335
- **WHY (ties together WS-4/WS-5/WS-6).** A single averaged score cannot tell a wick-rejection from
336
- an impulse reclaim from a failed tap β€” yet those need different entries, SLs and conviction. The
337
- footprint (WS-4) tells us WHO is winning; the entry-model classifier tells us HOW the move is
338
- starting. Together they are the "human read."
339
-
340
- ### 7.1 Entry-Model Classifier (new, runs on the Stage-4 setup each cycle)
341
- Classify the live FVG interaction into ONE primary model (closed-candle reads only, `bars[-2]`):
342
-
343
- 1. **Wick Rejection / Liquidity Sweep** β€” price wicks into (or just past) the zone / sweeps a
344
- liquidity pool, then CLOSES back inside on a long rejection wick. Tell: wick β‰₯ ~1.5Γ— body into
345
- zone, close back on our side, footprint flips to our side on the rejection candle.
346
- 2. **Impulse Reclaim / Displacement** β€” a strong-bodied candle closes back through the zone edge
347
- in our direction (displacement). Tell: body β‰₯ NΓ—ATR, small opposing wick, footprint surge.
348
- 3. **FVG Mitigation Tap** β€” price taps the FVG midpoint/equilibrium and turns WITHOUT a deep
349
- sweep. Tell: shallow interaction, defended, OB confluence present.
350
- 4. **Inside-Zone Consolidation Break** β€” price coils inside the FVG then breaks out (micro-BoS on
351
- LTF) in our direction. Tell: β‰₯3 small-range candles inside zone, then expansion candle.
352
- 5. **Failed-Then-Reclaim (Spring)** β€” price closes against us through the zone (looks invalid)
353
- then reclaims within a few candles. Tell: brief breach + strong reclaim + footprint flip.
354
- 6. **No Clear Model** β€” none of the above β†’ do NOT promote (this kills "unqualified" entries).
355
-
356
- Expose the chosen model as `st.entry_model` + a human phrase (e.g. "Wick Rejection Off Discount
357
- FVG"). Show it in the Stage-4 dashboard row and the Stage-5 alert.
358
-
359
- ### 7.2 Model-Specific Validation (dynamic filters per model β€” the "is this a good trade?" brain)
360
- Each model carries its OWN preconditions + its OWN SL/entry rule (NOT one global rule):
361
- - **Wick Rejection:** entry = close of rejection candle; SL = beyond the rejection wick + buffer;
362
- require swept liquidity + footprint flip. Tightest, highest-conviction model.
363
- - **Impulse Reclaim:** entry = close of displacement candle; SL = beyond the origin of the
364
- displacement / FVG far edge; require bodyβ‰₯NΒ·ATR + footprint surge.
365
- - **FVG Mitigation Tap:** entry = confirmation candle close; SL = beyond FVG far edge; require OB
366
- confluence + discount/premium location.
367
- - **Consolidation Break:** entry = breakout candle close; SL = other side of the coil; require LTF
368
- micro-BoS in our direction.
369
- - **Failed-Then-Reclaim:** entry = reclaim candle close; SL = beyond the failed-breach extreme;
370
- require fast reclaim (≀K candles) + footprint flip. Highest risk β†’ require the strongest
371
- confluence stack.
372
-
373
- Feed these into the WS-5 confluence stack: promotion requires (model recognised) AND (model's own
374
- preconditions met) AND (N-of-M global confluence). This is the dynamic, human-like gate.
375
-
376
- ### 7.3 Conviction Read (so the user trades with confidence)
377
- Produce a single, stable, human-readable conviction per setup, DERIVED from discrete facts (never
378
- a twitchy average):
379
- - **Grade A (High Conviction):** strong model (wick rejection / impulse reclaim) + footprint on
380
- our side + HTF location + swept liquidity + clear path to TP.
381
- - **Grade B (Valid):** model recognised + most preconditions, one soft miss.
382
- - **Grade C (Watch):** model forming, confluence incomplete β†’ stay in Stage 4, do not promote.
383
- Print the grade + the 2-3 reasons that drive it (e.g. "Swept Sell-Side, Reclaimed, Buyers
384
- Absorbing") so the user understands WHY, like a desk analyst would say it.
385
-
386
- ### 7.4 Stage-5 Position Print (model-aware)
387
- On promotion, the Stage-5 alert (Telegram + dashboard) prints details for the RECOGNISED model:
388
- - Direction, Entry, SL, single structural TP (WS-3), Leverage (dynamic), Stop %, RR.
389
- - **Entry Model** + **Conviction Grade** + the reason line.
390
- - The structural invalidation level and the target liquidity pool (the thesis contract, WS-6).
391
- Use Title Case for the labels, Sentence case for any explanation line.
392
-
393
- ### 7.5 Make every segment market-adaptive
394
- - Thresholds (wick ratio, bodyΒ·ATR, coil count, reclaim window) live in CFG + settings so they
395
- tune without code edits; default sensibly.
396
- - All model reads use CLOSED candles; LTF reads via Min1 footprint (WS-4).
397
- - The classifier must be deterministic + restart-safe (re-derivable from candles + persisted
398
- footprint), so a restart never changes a live setup's model/grade.
399
-
400
- **TEST.** Build fixtures for each of the 6 models (synthetic candle sets) β†’ classifier picks the
401
- right one; wrong/ambiguous sets β†’ "No Clear Model" (no promotion). Verify each model's SL/entry
402
- rule. Verify Stage-5 print shows the model + grade + reasons. py_compile + node-check.
403
-
404
- **DONE-WHEN.** Stage 4 names the entry model + grades conviction from real structure/flow,
405
- promotes only valid models, and Stage 5 prints model-aware position details the user can act on
406
- with confidence.
407
-
408
- > BUILD-ORDER NOTE: implement WS-7 AFTER WS-4 (needs the footprint) and alongside WS-5 (it feeds
409
- > the confluence stack) and WS-6 (it sets the thesis contract). Update Β§4 order accordingly:
410
- > WS-1 β†’ WS-2 β†’ WS-4 β†’ (WS-5 + WS-7 together) β†’ WS-6 β†’ WS-3.
411
 
412
  ---
413
 
414
- ## WS-8 β€” Optimal Enhancements (analyst-recommended, BEYOND user spec)
415
-
416
- These are not from the user's observations β€” they are the highest-leverage additions a quant desk
417
- would insist on for an SMC perp scanner to actually SURVIVE. Ordered by survival impact. Each is
418
- CFG-toggleable so the user can adopt incrementally. Do not let these bloat Stage 0-3.
419
-
420
- ### 8.1 Cost-Aware Expectancy (the single biggest survival gap)
421
- Today every R is computed from price levels only β€” no taker fees, funding, or slippage. At dynamic
422
- high leverage on alts, these turn a paper "+R" into breakeven-or-loss.
423
- - Add CFG: `fee_taker_pct` (default 0.04% per side), `slippage_pct` (default ~0.03%, larger for
424
- low-turnover pairs), and use live `fundingRate` (already fetched, `refresh_oi_funding` L4370).
425
- - Compute NET R on every closed trade: gross R βˆ’ entry/exit fees βˆ’ funding accrued over hold βˆ’ a
426
- slippage haircut. Store both gross and net on the history row + JSON `data`.
427
- - Trades.html metrics (win-rate, net R, profit factor, expectancy) show NET as primary, gross as
428
- secondary. This is what makes the dashboard honest.
429
- - **Pre-trade screen:** reject a setup whose structural TP gives < `min_net_rr` (default ~1.3R)
430
- AFTER costs β€” kills marginal trades the gross-R view would have taken.
431
-
432
- ### 8.2 Feature-Vector Outcome Log + Calibration Loop (turn vibes into evidence)
433
- The user keeps Stage-5 outcomes (Trade History) but not the WHY. Extend each saved trade row (JSON
434
- `data`, additive β€” no schema change) with the full decision vector: entry_model, conviction_grade,
435
- the confluence members that were TRUE, footprint side at entry, HTF location, session, ATR
436
- percentile, BTC alignment, net R.
437
- - Add a read-only `/api/calibration` + a small dashboard panel computing PER-FEATURE hit-rate and
438
- avg net R once N trades exist (e.g. "Wick Rejection: 61% / +0.7R", "Counter-BTC: 28% / -0.4R").
439
- - This is how WS-5's confluence requirement and WS-7's grades stop being guesses. Later, optionally
440
- auto-tune `conviction_min_confluence` from the data (gated behind a CFG flag, off by default).
441
-
442
- ### 8.3 SMT Divergence (the user mentioned SMT β€” implement it properly)
443
- Smart-Money-Technique divergence is a genuinely LEADING confirmation: when a pair makes a new
444
- low/high but its correlated peer/leader does NOT, the move is likely a stop-grab about to reverse.
445
- - For an alt long: check that BTC (or the pair's sector leader) did NOT confirm the same new low
446
- (bullish SMT). Mirror for shorts. Use closed 15m + the HTF swing map.
447
- - Add as a confluence member in WS-5 and a tell in WS-7's wick-rejection/spring models. High
448
- predictive value, cheap (data already loaded for BTC).
449
-
450
- ### 8.4 Session & Volatility Regime Awareness (trade when it pays)
451
- - **Killzones:** weight/permit setups during London + New York opens; down-weight the low-liquidity
452
- Asian range and the funding-flip windows. CFG `session_filter_enabled`, UTC ranges in settings.
453
- - **Volatility regime:** compute ATR percentile vs its own history; SKIP dead regimes (no follow-
454
- through) and be stricter in hyper-volatile spikes (stops get wicked). Adapts WS-7 thresholds.
455
-
456
- ### 8.5 Portfolio Heat / Correlation Throttle (don't die on one BTC candle)
457
- The scanner can promote many correlated alt longs at once β€” one adverse BTC move then hits them all.
458
- - Track concurrent live Stage-5 trades; cap total open risk (`max_concurrent_trades`,
459
- `max_aligned_direction`) and refuse a new entry that is highly correlated/same-direction with
460
- existing exposure (especially counter-BTC clusters). Surface "Portfolio Heat" on the dashboard.
461
-
462
- ### 8.6 Adaptive Per-Symbol Cooldown (stop re-entering a failing structure)
463
- After an SL on a symbol, apply a cooldown before that symbol can re-promote on the SAME structure
464
- (`symbol_cooldown_minutes`), and never re-arm the identical invalidated zone. Prevents the
465
- "stopped, re-enters, stopped again" bleed.
466
-
467
- **TEST.** Unit-test net-R math (fees+funding+slippage) vs hand calc; calibration panel renders with
468
- β‰₯N synthetic rows; SMT divergence fixture (pair new-low, leader not) flags correctly; session +
469
- ATR-percentile gates; portfolio-heat cap blocks an over-exposed entry; cooldown blocks re-entry.
470
-
471
- **DONE-WHEN.** The system measures NET expectancy, learns from its own outcomes, uses SMT + session
472
- + volatility as leading context, and protects itself from correlated blow-ups β€” i.e. it has a
473
- realistic chance of surviving live, not just looking good in screenshots.
474
-
475
- > ADOPTION NOTE for the user: 8.1 (cost-aware) and 8.2 (calibration) are the two that most change
476
- > whether this is profitable vs. merely pretty β€” recommend enabling both from day one. The rest are
477
- > safety/edge multipliers that can be switched on as confidence grows.
 
1
+ # FVG-Delta Crypto Signal Core β€” IMPLEMENTATION PLAN (Stage-0 Lock-In Permanent Fix)
2
 
3
+ > Author: Session 20 (diagnosis agent). Reader: the build agent who implements this.
4
+ > Status of THIS file: PLAN ONLY. No engine code changed while writing it.
5
+ > The PREVIOUS contents (v7.5 WS-1…WS-8 build plan) are DONE + logged in Log.md β€” cleared.
6
+ > Golden rules: single-file/flat layout (phone uploads one file at a time). Do NOT touch the
7
+ > UI/layout or the Stage 1–5 detection math. Casing: Title Case for labels, Sentence case for
8
+ > sentences. Co-author trailer on commits: `Co-authored-by: Starchild <noreply@iamstarchild.com>`.
9
 
10
  ---
11
 
12
+ ## 0. THE PROBLEM THIS PLAN FIXES (already diagnosed β€” do NOT re-diagnose, it wastes credit)
13
+
14
+ **Symptom:** the engine runs fine after a restart, then after a variable number of hours the
15
+ funnel FREEZES β€” the same pairs sit in Stage 1 (and maybe 1 in Stage 2), no new pairs sort in,
16
+ nothing reaches Stage 3/4/5. Scanner + every function still runs; container logs read HTTP 200.
17
+ A restart heals it temporarily, then it re-freezes.
18
+
19
+ **Root cause (PROVEN with live HF run-log data, Session 20 β€” see Log.md "ISSUE #1 RESOLVED VIA
20
+ LIVE DATA"):** STAGE-0 ZONE LOCK-IN β†’ SLOT EXHAUSTION.
21
+ - Live evidence line (stable across 30 cycles / 16 min while frozen):
22
+ `[DIAG] cyc=370 elapsed=5s states=602 s0z=290 stg[1:46 2:1 3:0 4:0 5:0] shard=72 active=339
23
+ picks=368 api_ok+=280 api_err+=0 thin+=228 zones+=4`
24
+ - `api_err+=0` every cycle β†’ NOT throttling/rate-limit. `elapsedβ‰ˆ4s`, RSS 20 MB β†’ NOT memory.
25
+ `zones+β‰ˆ4/cyc` β†’ detection is alive. ALL three earlier theories are DEAD (logged as rejected).
26
+ - `s0z=290` = 290 symbols each holding a **Stage-0 zone** (a bare FVG detected, but Stage-1
27
+ first-liquidity+BoS never locked). They dominate `active=339` (the per-cycle re-check set).
28
+
29
+ **Why a Stage-0 zone holder is effectively IMMORTAL (up to 24h) β€” four closed exits:**
30
+ 1. Cannot be re-sorted to a better zone β€” acquisition is gated `if st.zone is None` (app.py
31
+ ~L2897). Once any candidate zone is locked, the symbol is married to THAT zone.
32
+ 2. Cannot close-through invalidate β€” invalidation requires `st.stage >= 1` (L2972). At Stage 0
33
+ there is no kill path.
34
+ 3. Not covered by the 6h forming-eviction β€” that targets only `s.stage in (1,2)` (L5897-5899).
35
+ 4. Not covered by the 2h idle-prune β€” needs a stale `last_update_ts` (L5889-5890), but Stage-0
36
+ zone holders are in `active_picks` and refreshed every cycle β†’ never idle.
37
+ Its ONLY exits: advance to Stage 1, or the 24h `zone_ttl`/`max_zone_age` ceiling (L2956).
38
+
39
+ **Consequence:** most candidate FVG zones never mature to Stage 1 (normal SMC base rate). Each
40
+ detected zone nonetheless LOCKS its symbol's single slot for up to 24h doing nothing. Over hours
41
+ the universe saturates β†’ the funnel freezes. Restart clears every lock β†’ refills β†’ re-saturates.
42
+
43
+ **User's framing (correct, and the design intent):** Stage 0 is a BACKGROUND probe β€” it is NOT a
44
+ "physical" stage. It is NOT shown in the dashboard stage tables, and NOT persisted (`_save_state`
45
+ only saves `stage >= 1`, L1789). The zombie class should not exist at all. A bare FVG is not a
46
+ commitment; the symbol should not be married to it.
47
+
48
+ **Secondary (chronic waste, NOT the freeze trigger):** `thin+β‰ˆ230/cycle` β‰ˆ 62% of picks return
49
+ `<80 bars` and are skipped. With `api_err=0` these are newly-listed perps lacking 80 candles of
50
+ HISTORY (a history problem, not a liquidity problem). They bloat `states` and waste fetches but
51
+ are present after a restart too, so they do not cause the freeze. (NOTE: `universe_top_n` is the
52
+ WRONG lever for this β€” it ranks by turnover/liquidity, so it can both miss thin new listings AND
53
+ drop good full-history low-cap pairs that qualify. Do not use it to chase thin-skips.)
54
 
55
  ---
56
 
57
+ ## 1. TWO ROUTES TO A PERMANENT FIX
58
 
59
+ Both target the same root cause (the Stage-0 marriage). They are mutually exclusive β€” pick ONE.
 
 
 
 
 
60
 
61
+ - **Option B β€” Re-sort on a better zone** (keep the Stage-0 store, but make it replaceable).
62
+ - **Option C β€” Never lock at Stage 0** (don't store a zone until it earns Stage 1). ← RECOMMENDED.
63
 
64
+ Section 2 = how the machine works today (shared context). Section 3 = Option B. Section 4 =
65
+ Option C. Section 5 = impact/blast-radius comparison. Section 6 = the optional thin-skip cleanup.
66
+ Section 7 = test matrix. Section 8 = rollout + flags.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  ---
69
 
70
+ ## 2. HOW THE MACHINE WORKS TODAY (read this before B or C β€” grounded in app.py)
71
+
72
+ Per symbol, per cycle, `process_symbol` (L5563) does:
73
+ 1. `load_bars` (15m window, ~500 candles) β†’ `st.bars`.
74
+ 2. `_rebase_indices` (L5595) β€” re-pin every locked TIMESTAMP to its current index (drift fix).
75
+ 3. `evaluate_stages(st)` (L2877) β†’ `_run_machine` (L2935).
76
+ 4. footprint / filters / promotion / alerts.
77
+
78
+ `evaluate_stages` β†’ `_run_machine`:
79
+ - **Zone acquisition (L2891-2916):** `if st.zone is None:` β€” probe several candidate zones via
80
+ `detect_candidate_zones` (L2346) + `_probe_zone_stage` (L2922), adopt the one valid at the most
81
+ advanced stage, `_reset_state`, set `st.zone`, `st.stage = 0`. **This is the marriage.**
82
+ - **`_run_machine` (L2935+) re-derives the FULL stage from the locked zone EVERY cycle:**
83
+ - TTL/age expiry (stage<3 only, L2956).
84
+ - Close-through invalidation (stage 1–4, L2970-2982).
85
+ - Committed floor: `if st.stage >= 4: return None` (L2995) β€” no regression once committed.
86
+ - Otherwise it RE-COMPUTES from scratch each cycle: `_lock_first_liquidity`, Stage-1 BoS loop
87
+ (L3021), Stage-2 sweep loop (L3050), Stage-3 FVG interaction, Stage-4 confirm β†’ sets
88
+ `desired_stage` (L3115) and finally `st.stage = final_stage` (L3156).
89
+
90
+ **KEY INSIGHT for both fixes:** Stages 1–3 are already RE-DERIVED every cycle from the zone +
91
+ locked timestamps; the machine is effectively idempotent given a zone (proven by `_probe_zone_stage`
92
+ running the exact same machine on a throwaway scratch state, L2922-2930). The "locked" cross-cycle
93
+ fields (`bos_break_idx`, `stage2_break_idx`, `first_seen_liquidity_*`, etc.) are all set lock-once
94
+ INSIDE the machine and are re-pinned by `_rebase_indices`. **At Stage 0, NONE of these are set yet**
95
+ β€” so re-probing a Stage-0 symbol from scratch each cycle costs nothing and loses nothing. This is
96
+ exactly why Option C is safe.
97
+
98
+ **What persists / shows (so we know UI/restart blast radius):**
99
+ - `_save_state` persists only `stage >= 1` (L1789). Stage-0 zones are already NOT persisted.
100
+ - Dashboard stage tables + `trades.html` + `market.js` reference stages 1–5 only (grep: no
101
+ `stage0` consumers). `counts_by_stage.stage0` (L6461) feeds the "Symbols" metric card only.
102
+ - `STATS.zones_found` increments on acquisition (L2913).
 
 
 
 
 
 
 
103
 
104
  ---
105
 
106
+ ## 3. OPTION B β€” RE-SORT ON A BETTER ZONE (keep Stage-0 store, make it replaceable)
107
+
108
+ ### 3.1 Idea
109
+ Keep storing a zone at Stage 0, but DROP the absolute `if st.zone is None` marriage. Each cycle,
110
+ if the symbol is still at Stage 0 (uncommitted) AND its stored zone is stale, re-probe candidate
111
+ zones; if a probe finds a MORE-ADVANCED or NEWER zone, swap to it. Committed setups (Stage β‰₯1, and
112
+ especially the Stage β‰₯4 floor) are never disturbed.
113
+
114
+ ### 3.2 Exact changes (app.py)
115
+ 1. **`_run_machine` zone block (L2891-2916):** change the guard from
116
+ `if st.zone is None:` to:
117
+ `if st.zone is None or _stage0_zone_is_replaceable(st, bars, a, now_ts):`
118
+ where the new helper returns True ONLY when `st.stage == 0` (never for stage β‰₯1) AND
119
+ (current stored zone is older than `stage0_resort_min_age_candles`) AND a fresh probe yields a
120
+ zone whose `_probe_zone_stage` β‰₯ current OR whose `impulse_ts` is newer. On True, fall through
121
+ to the existing acquisition path (which already `_reset_state`s and re-locks).
122
+ 2. **New helper `_stage0_zone_is_replaceable(st, bars, a, now_ts) -> bool`** (place next to
123
+ `_probe_zone_stage`). Must be CHEAP: only probe when `st.stage == 0`; reuse `detect_candidate_zones`
124
+ already computed if possible (or accept one extra in-memory probe β€” no network; bars already loaded).
125
+ 3. **New CFG knobs** (near L105): `stage0_resort_enabled` (default True),
126
+ `stage0_resort_min_age_candles` (default 8 = 2h) β€” so a fresh zone isn't thrashed every cycle.
127
+ 4. **Settings + schema:** add both knobs to `settings_schema.json` (toggle + int) so they're tunable.
128
+ 5. **Eviction safety net (recommended alongside B):** extend the existing forming-eviction in
129
+ `_prune_states` (L5894-5899) to ALSO drop a Stage-0 zone holder that has sat `> forming_stale_ttl`
130
+ without advancing β€” so a symbol with NO better zone available still frees eventually.
131
+
132
+ ### 3.3 What is affected
133
+ - ONLY the Stage-0 acquisition guard + a new helper + 2 knobs + `_prune_states`. The detection
134
+ math (Stage 1–5), `_rebase_indices`, alerts, footprints, persistence, UI: UNTOUCHED.
135
+
136
+ ### 3.4 Consequences / risks
137
+ - βœ… No timer-guessing for the core fix β€” a slot is freed/replaced as soon as a better zone exists.
138
+ - ⚠️ Re-probing at Stage 0 each cycle adds CPU (in-memory only; `elapsed` headroom is large at 4s).
139
+ Mitigate with `stage0_resort_min_age_candles` + only-when-stage0 guard.
140
+ - ⚠️ Subtle thrash risk: zone A↔B flip-flop if the "better" test isn't strictly monotonic. The
141
+ min-age gate + "β‰₯ current stage OR strictly newer impulse_ts" rule prevents it.
142
+ - ⚠️ Still keeps the Stage-0 store concept alive β€” i.e. it MANAGES the zombie class rather than
143
+ eliminating it. Lower conceptual purity than C.
144
+ - **Impact level: MEDIUM-LOW.** ~1 helper + 1 guard line + 2 knobs + 1 prune extension.
145
 
146
  ---
147
 
148
+ ## 4. OPTION C β€” NEVER LOCK AT STAGE 0 (RECOMMENDED β€” eliminates the zombie class by design)
149
+
150
+ ### 4.1 Idea (matches the user's mental model + the strategy)
151
+ Stage 0 stops being a STORED state. A bare FVG is a background candidate, re-evaluated fresh every
152
+ cycle, and is NEVER married to the symbol. The symbol only acquires/stores a zone the moment the
153
+ probe shows it qualifies for **Stage 1** (first liquidity + BoS = the first real commitment). Below
154
+ Stage 1, `st.zone` stays `None`, so the four immortality paths simply cannot exist β€” there is
155
+ nothing to evict because there was never a lock.
156
+
157
+ ### 4.2 Exact changes (app.py)
158
+ 1. **Zone acquisition block (`_run_machine`, L2891-2916):** today it adopts the best zone whenever
159
+ `reached >= 0`. CHANGE the adoption threshold: only `_reset_state` + lock `st.zone` + set the
160
+ stage when the best probe reaches **`best_stage >= 1`**. If the best candidate only reaches
161
+ Stage 0, leave `st.zone = None`, `st.stage = 0`, and `return None` (nothing stored).
162
+ - Concretely: keep the `for z_cand in detect_candidate_zones(...)` ranking loop, but after it:
163
+ `if best_zone is None or best_stage < 1: return None` (replaces `if best_zone is None: return None`),
164
+ then lock as today and set `st.stage = best_stage` (NOT hard 0) so it enters at its true stage.
165
+ 2. **Direct entry at true stage:** when locking, set `st.stage = best_stage` and
166
+ `st.stage_since_ts = now_ts` so a symbol that probes straight to Stage 2/3/4 is placed there (the
167
+ existing multi-stage sorter already computes `best_stage`; today it overwrites to 0 at L2913 then
168
+ re-derives β€” under C we trust `best_stage` and let `_run_machine`'s body refine it the same cycle).
169
+ 3. **Re-probe every cycle while uncommitted:** because nothing is stored below Stage 1, a symbol at
170
+ Stage 0 re-runs the acquisition probe each cycle automatically (its `st.zone` is `None`). This is
171
+ the same per-cycle probe the engine already does for never-seen symbols β€” proven cheap.
172
+ 4. **`detect_candidate_zones` / `_probe_zone_stage`:** UNCHANGED. They already run the full machine
173
+ on a scratch state, so "what stage would this zone reach now" is already available.
174
+ 5. **Persistence:** already saves `stage >= 1` only (L1789) β€” so C requires NO persistence change;
175
+ it actually makes the on-disk model and the in-memory model finally agree.
176
+ 6. **`STATS.zones_found`:** move/keep the increment so it counts Stage-1 acquisitions (a "found
177
+ zone" now means a committed one). Optional: add `STATS.zone0_probes` for visibility.
178
+ 7. **Eviction:** the 6h forming-eviction (stage 1–2) and 2h idle-prune (stage 0, no-zone) remain
179
+ correct and are now SUFFICIENT β€” there are no Stage-0 zone holders left to leak.
180
+
181
+ ### 4.3 What is affected
182
+ - The acquisition block in `_run_machine` (adoption threshold + entry stage). That's the core.
183
+ - `STATS` counters (cosmetic). Everything else β€” Stage 1–5 math, `_rebase_indices`, invalidation,
184
+ committed floor, alerts, footprints, filters, promotion, persistence, ALL UI β€” UNTOUCHED.
185
+ - The "Symbols at Stage 0" metric card will now read ~0 (correct: Stage 0 is no longer a resident
186
+ state). If the dashboard shows a "Stage 0 / Forming" count, relabel or let it reflect probes.
187
+
188
+ ### 4.4 Consequences / risks
189
+ - βœ… ELIMINATES the zombie class structurally β€” the freeze cannot recur (no Stage-0 lock to exhaust).
190
+ - βœ… Conceptually correct + matches user intent: a bare FVG is a probe, not a commitment.
191
+ - βœ… Self-cleaning: `active_picks` shrinks dramatically (no ~290 Stage-0 residents) β†’ the per-cycle
192
+ re-check set is small and always has room β†’ funnel breathes 24/7. `states` stops bloating.
193
+ - βœ… Makes in-memory and persisted models consistent (both = stage β‰₯1).
194
+ - ⚠️ Behavioral nuance: today a Stage-0 zone is "remembered" so the SAME zone is tracked as it
195
+ matures. Under C, the zone is RE-DERIVED each cycle until it hits Stage 1. Because the machine is
196
+ already idempotent (it re-derives 1–3 every cycle anyway and re-pins via timestamps), the SAME
197
+ structural zone is re-found deterministically from the same bars β€” so maturation tracking is
198
+ preserved IN PRACTICE. RISK to verify: `detect_candidate_zones` must return the same zone
199
+ stably across cycles for a given window (it ranks by recency/structure β€” confirm determinism in
200
+ tests 7.x). If a zone could be dropped from the candidate list before reaching Stage 1, we'd lose
201
+ nothing tradeable (it wasn't committed), but verify no flicker in the Stage-1 entry moment.
202
+ - ⚠️ One-time: the "Symbols at Stage 0" card semantics change (see 4.3). Pure cosmetic.
203
+ - **Impact level: LOW-MEDIUM, but CONCENTRATED + clean.** Essentially one changed condition
204
+ (`best_stage >= 1` to adopt) + trust `best_stage` as the entry stage. Smaller code delta than B,
205
+ higher conceptual payoff, but it changes a core invariant so it needs the full test matrix (Β§7).
206
+
207
+ ### 4.5 Why C is recommended over B
208
+ B manages the symptom (replaceable zombie); C removes the cause (no Stage-0 lock). C is a SMALLER
209
+ diff, makes persistence consistent, and structurally guarantees the freeze cannot return. B keeps a
210
+ re-sort mechanism that itself needs tuning (min-age, thrash guards) and still leaves Stage-0
211
+ residents in `active_picks`. Build C unless live testing of C surfaces a maturation-tracking flicker
212
+ that B's "remember the zone" behavior would avoid β€” in which case fall back to B.
213
 
214
  ---
215
 
216
+ ## 5. IMPACT / BLAST-RADIUS COMPARISON (at a glance)
217
+
218
+ | Dimension | Option B (re-sort) | Option C (no Stage-0 lock) β˜… |
219
+ |---|---|---|
220
+ | Fixes the freeze permanently | Yes (manages) | Yes (eliminates by design) |
221
+ | Core code touched | acquisition guard + new helper + prune ext | acquisition adoption threshold + entry stage |
222
+ | New CFG knobs | 2 (resort enabled + min-age) | 0 required (1 optional stat) |
223
+ | Detection math (Stage 1–5) | Untouched | Untouched |
224
+ | `_rebase_indices` / invalidation / committed floor | Untouched | Untouched |
225
+ | Persistence | Untouched | Untouched (now consistent) |
226
+ | UI | Untouched | "Stage 0" metric card semantics change (cosmetic) |
227
+ | `active_picks` size after fix | Smaller (stale zones replaced) | Much smaller (no Stage-0 residents) |
228
+ | New tuning surface / thrash risk | Yes (min-age, flip-flop guard) | No |
229
+ | Conceptual correctness | Medium | High (matches strategy + user model) |
230
+ | Risk profile | More moving parts, lower per-part risk | Fewer parts, changes one core invariant |
231
+ | Recommended | Fallback | **PRIMARY** |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
  ---
234
 
235
+ ## 6. OPTIONAL β€” THIN-SKIP CLEANUP (throughput only; NOT the freeze; do AFTER B or C)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
+ Independent of the freeze fix. Eliminates the ~62%/cycle wasted `<80 bars` re-fetches WITHOUT
238
+ dropping any qualifying pair (so NOT `universe_top_n`).
239
+ - In `process_symbol`, when a symbol returns `<80 bars`, stamp `st.thin_until = now + thin_skip_ttl`
240
+ (default 1800s) and skip re-fetching it until then; on expiry, retry once (so a newly-listed perp
241
+ rejoins automatically once it has accumulated β‰₯80 candles).
242
+ - New CFG `thin_skip_ttl_seconds` (default 1800) + schema entry. Keep the `STATS.thin_skips` DIAG
243
+ counter to confirm the drop after deploy.
244
+ - Impact: LOW. Pure throughput; coverage-neutral. Build only after the freeze fix is verified.
245
 
246
  ---
247
 
248
+ ## 7. TEST MATRIX (run BEFORE export; the box has no `zip` binary β€” use Python zipfile)
249
+
250
+ Static:
251
+ - `python3 -m py_compile app.py` β†’ OK.
252
+ - `python3 -c "import json;json.load(open('settings_schema.json'))"` β†’ OK.
253
+ - `node --check market.js` and inline JS in `trades.html` / dashboard β†’ OK.
254
+
255
+ Boot (TestClient or `uvicorn app:app` with `SCAN_ENABLED=false`):
256
+ - `/`, `/api/state`, `/trades`, `/settings`, `/market.js`, `/settings.js` β†’ 200.
257
+ - `/api/state` still exposes the stage tables + counts_by_stage without KeyError.
258
+
259
+ Behavioral (synthetic bars fixtures, no network):
260
+ - **B:** a Stage-0 zone older than min-age + a fresher higher-stage candidate β†’ symbol SWAPS;
261
+ a Stage-1+ setup is NEVER swapped; flip-flop does not occur across 10 cycles on static bars.
262
+ - **C (critical):** (a) a window whose best candidate only reaches Stage 0 β†’ `st.zone is None`,
263
+ `st.stage == 0`, nothing stored, symbol re-probes next cycle. (b) a window that qualifies to
264
+ Stage 1/2/3 β†’ zone locked, entered at the correct stage, identical to current behavior. (c)
265
+ DETERMINISM: same window over 10 consecutive cycles re-derives the SAME zone + SAME stage (no
266
+ flicker at the Stage-1 entry moment). (d) committed Stage 4/5 floor still never regresses. (e)
267
+ close-through invalidation still fires at Stage 1–4.
268
+ - **Both:** restart (state.json) restores Stage β‰₯1 setups unchanged; `_rebase_indices` still pins.
269
+
270
+ Live smoke (HF, with the S20 DIAG line ON β€” `DIAG_CYCLE_LOG=true`):
271
+ - After deploy, watch `[DIAG]`: `s0z` should fall toward ~0 (C) or stay bounded (B); `active`
272
+ should drop and STOP climbing over hours; `stg[...]` should keep CHANGING (new pairs flowing);
273
+ pairs should reach Stage 3/4/5 again. Capture a multi-hour stretch to confirm NO re-freeze.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
 
275
  ---
276
 
277
+ ## 8. ROLLOUT + FLAGS + GUARDRAILS
278
+
279
+ - Keep the S20 DIAG instrument IN for this fix's verification; turn it OFF (Settings β†’ "Diagnostic
280
+ Cycle Log", or `DIAG_CYCLE_LOG=false`) once a multi-hour no-freeze run is confirmed.
281
+ - Ship behind a flag for safe rollback:
282
+ - B: `stage0_resort_enabled` (default True).
283
+ - C: `stage0_require_stage1_to_lock` (default True) β€” when False, reverts to legacy Stage-0
284
+ locking, so the change is instantly reversible without a redeploy.
285
+ - Do NOT touch: Stage 1–5 detection math, `_rebase_indices`, committed-stage floor (L2995),
286
+ invalidation, entry/SL/TP/BE math, footprints, filters/promotion, alerts, README HF metadata,
287
+ flat-file layout. Bump nothing except a point note in `AGENT.md` changelog.
288
+ - After implementing, UPDATE Log.md with: which option was built, the exact line edits, test
289
+ results, and the live `[DIAG]` before/after so the NEXT agent has the full trail.
290
+
291
+ ## 9. SUGGESTED BUILD ORDER
292
+ 1. Implement **Option C** behind `stage0_require_stage1_to_lock` (default True).
293
+ 2. Run the full Β§7 test matrix (esp. C-determinism 7.c).
294
+ 3. Export, deploy to HF with DIAG ON, watch `[DIAG]` for a multi-hour no-freeze confirmation.
295
+ 4. If C shows a maturation flicker, flip the flag off (instant revert) and implement **Option B**.
296
+ 5. Once stable, add the Β§6 thin-skip cleanup. Then turn DIAG OFF.
297
+ 6. (Later, separate) revisit Issue #2 (TP-hit trades logged as Stage-4 invalidation) and E1
298
+ (Sweep-Reclaim Re-Entry blueprint in Log.md) β€” NOT part of this plan.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Log.md CHANGED
@@ -2387,3 +2387,116 @@ NEXT: user runs this build on HF until it freezes once, copies the [DIAG] lines
2387
  logs (a healthy stretch + the frozen stretch) back here. Then we read the pattern and the cause
2388
  stops being a hypothesis. STILL PENDING separately: Issue #2 (TP-hit trades logged as Stage-4
2389
  invalidation).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2387
  logs (a healthy stretch + the frozen stretch) back here. Then we read the pattern and the cause
2388
  stops being a hypothesis. STILL PENDING separately: Issue #2 (TP-hit trades logged as Stage-4
2389
  invalidation).
2390
+
2391
+
2392
+ ## SESSION 20 β€” ISSUE #1 *RESOLVED VIA LIVE DATA* (HF run-logs, cyc 359-388, 2026-06-24 19:40-19:56Z)
2393
+ The DIAG instrument worked. Real per-cycle line (representative; stable across all 30 cycles):
2394
+ [DIAG] cyc=370 elapsed=5s states=602 s0z=290 stg[1:46 2:1 3:0 4:0 5:0]
2395
+ shard=72 active=339 picks=368 api_ok+=280 api_err+=0 thin+=228 zones+=4
2396
+ Resource sidecar: peak RSS 20.5 MB, CPU 1.3%, 80% mem free.
2397
+
2398
+ WHAT THE DATA PROVES (no longer hypothesis):
2399
+ 1. NOT throttle/starvation. api_err+ = 0 EVERY cycle. REQUEST_SEM(20)+MEXC are NOT rate-limiting.
2400
+ => my S20 "forming-backlog throttle starvation" PRIMARY HYPOTHESIS is REJECTED BY DATA.
2401
+ Recorded as WRONG so no future agent re-chases it.
2402
+ 2. NOT memory/slowdown. elapsed flat 3-5s, RSS 20.5 MB, CPU ~1%. No leak, no degradation in loop
2403
+ time. Earlier "matplotlib leak / slowdown" branch also dead.
2404
+ 3. Zone DISCOVERY is alive: zones+ = 2-9 every cycle (~4 avg => ~120 zones found over the window).
2405
+ So detection is NOT broken either.
2406
+
2407
+ THE ACTUAL ROOT CAUSE (data-confirmed) = STAGE-0 ZONE LOCK-IN -> SLOT-EXHAUSTION SATURATION:
2408
+ - s0z = 290 = number of symbols holding a STAGE-0 zone (zone detected, but Stage-1 first-liquidity
2409
+ + BoS not yet locked). active=339 = these 290 + the 46 stage1 + 1 stage2 + a couple. So the
2410
+ per-cycle re-check set is DOMINATED by ~290 stage-0 zone holders.
2411
+ - A stage-0 zone holder is effectively IMMORTAL for up to 24h. Proof from code:
2412
+ * It can NOT be re-sorted to a better zone: zone acquisition is gated `if st.zone is None`
2413
+ (L2897). Once any candidate zone is locked, the symbol is married to THAT zone.
2414
+ * It can NOT close-through invalidate: invalidation requires `st.stage >= 1` (L2970). At
2415
+ stage 0 there is NO invalidation path.
2416
+ * It is NOT covered by the 6h forming-eviction: that targets only `s.stage in (1,2)`
2417
+ (L5897-5899). Stage-0-with-zone is excluded.
2418
+ * It is NOT covered by the 2h idle-prune: that needs a STALE last_update_ts (L5889-5890), but
2419
+ these are in active_picks and refreshed EVERY cycle -> never idle.
2420
+ * Its ONLY exit is advancing to Stage 1, or the 24h zone_ttl/max_zone_age ceiling (L2956).
2421
+ - CONSEQUENCE: most candidate zones never mature to Stage 1 (normal SMC base rate). Each one that
2422
+ is detected LOCKS its symbol's single slot for up to 24h doing nothing. Over hours the universe
2423
+ saturates: stg[1:46 2:1] sits FROZEN (identical for all 30 cycles = 16 min), nothing reaches
2424
+ Stage 3/4/5, and the same pairs recycle. New, genuinely promotable setups on those 290 symbols
2425
+ are INVISIBLE because the slot is taken by a dead stage-0 zone. EXACT match to the user report.
2426
+ - RESTART HEALS because it clears every locked zone -> all symbols free -> fresh multi-stage sort
2427
+ fills the funnel -> then re-saturates with stage-0 zombies -> re-freezes. Time-to-freeze varies
2428
+ with how fast zones get detected = market-dependent ("rarely lasts 24h").
2429
+
2430
+ SECONDARY (chronic waste, not the freeze trigger but amplifies it): thin+ = ~228/cycle. ~62% of
2431
+ every cycle's ~370 picks return <80 bars and are skipped (STATS.thin_skips). With api_err=0 these
2432
+ are NOT failed fetches -> they are genuinely low-history / illiquid perps in the UNCAPPED universe
2433
+ (max_symbols=0, universe_top_n=0 -> entire ~700-800 MEXC USDT-perp list). They can never sort,
2434
+ yet are re-fetched every cycle. They don't cause the freeze (present after restart too) but they
2435
+ waste ~62% of scan throughput and bloat `states` toward the prune cap, leaving fewer effective
2436
+ slots for real setups.
2437
+
2438
+ FIX DIRECTIONS (data-driven; NOT yet implemented, awaiting user go-ahead):
2439
+ PRIMARY (the freeze). Give STAGE-0-WITH-ZONE a bounded dwell + re-sort, the bucket that is
2440
+ currently the least-guarded and largest:
2441
+ (a) Extend the existing forming-eviction to stage 0-with-zone: if a symbol has held a
2442
+ stage-0 zone for > forming_stale_ttl (or a dedicated stage0_zone_ttl) without advancing
2443
+ to Stage 1, free the slot so the symbol re-sorts from scratch. AND/OR
2444
+ (b) Relax the `if st.zone is None` lock so a symbol holding a STALE/low-stage zone can be
2445
+ RE-SORTED when a probe finds a more-advanced fresh zone (never disturb Stage >=3).
2446
+ Either directly drains the 290-deep stage-0 reservoir and keeps the funnel breathing 24/7.
2447
+ SECONDARY (throughput + slot pressure). Cap the universe to liquid pairs: set universe_top_n
2448
+ (e.g. 150-250) β€” SETTINGS-ONLY, zero code. Kills most of the 228/cycle thin skips, shrinks the
2449
+ active set, concentrates compute on tradeable majors. Immediate, reversible, testable.
2450
+ NOTE: F3 (rebase drift) is NOT implicated here β€” bars_per_symbol=500 => ~125h window >> 24h
2451
+ zone_ttl, so locked timestamps never scroll off. Drift is not the cause; do not spend on it.
2452
+ NOTE: F4 (SONIC stage3->4 geometry) is a SEPARATE, lower-priority tuning item; with the funnel
2453
+ unclogged we can re-observe whether clean rejections still under-trigger.
2454
+
2455
+ CONFIDENCE: HIGH for "not throttle/not memory" (direct counters) and for "stage-0 lock-in
2456
+ saturation" (s0z=290 dominating active + the four code-proven immortality paths). The stage-1->2
2457
+ stall (stg[1] frozen at 46) is consistent with the same slot-saturation but a longer DIAG capture
2458
+ (or stage-transition counters) would confirm whether 1->2 transitions are truly ~0. STATUS:
2459
+ diagnosis complete; awaiting user decision on PRIMARY vs SECONDARY (or both) before any code.
2460
+
2461
+ ## SESSION 20 β€” SESSION OPERATIONS SUMMARY (so the next agent does NOT re-diagnose / re-test)
2462
+ WHAT WE DID THIS SESSION (diagnosis only on the engine; one additive DIAG instrument shipped):
2463
+ 1. Read fully: Log.md (S1-S19), SKILL.md, IMPLEMENTATION_PLAN_v7.5 (old), and grounded v7.5 in
2464
+ live app.py (ENGINE_VERSION=7.5; WS-1..WS-8 confirmed present; E1 confirmed NOT built).
2465
+ 2. Issue #1 ("stuck after hours") β€” iterated through THREE diagnoses, two REJECTED BY EVIDENCE:
2466
+ (a) REJECTED: "immortal Stage-3/4 zombies clog funnel" β€” user counter-evidence: freezes even
2467
+ with Stage 3/4 empty.
2468
+ (b) REJECTED: "forming-backlog THROTTLE starvation" β€” killed by live data: api_err+=0 every
2469
+ cycle (no rate-limit). Also corrected a factual error: forming-eviction (stage 1-2) is ON
2470
+ by default (6h), not OFF (user was right).
2471
+ (c) CONFIRMED by live data: STAGE-0 ZONE LOCK-IN -> slot exhaustion (s0z=290 dominating
2472
+ active=339; four code-proven immortality paths). See "ISSUE #1 RESOLVED VIA LIVE DATA".
2473
+ 3. Built the S20 DIAG instrument (additive, default-on, zero extra API calls): Stats.thin_skips
2474
+ counter; per-cycle stdout `[DIAG]` line in scanner_loop; CFG diag_cycle_log + DIAG_CYCLE_LOG
2475
+ schema toggle. KEY discovery enabling this: engine log() writes only to the in-memory EVENTS
2476
+ deque (dashboard), NEVER to stdout β€” so container logs only ever showed uvicorn 200s, which is
2477
+ why the user always saw "everything OK." DIAG prints to stdout so it shows in HF container logs.
2478
+ 4. TEST CARRIED OUT (real, do not repeat): pulled HF run-logs via
2479
+ `curl -N -H "Authorization: Bearer $HF_TOKEN"
2480
+ https://huggingface.co/api/spaces/abyXsmart/FVG-Delta-Crypto-Core/logs/run`
2481
+ (HF Space: abyXsmart/FVG-Delta-Crypto-Core). Captured cyc 359-388 (2026-06-24 ~19:40-19:56Z),
2482
+ frozen state stg[1:46 2:1 3:0 4:0 5:0], s0z~291, api_err+=0, thin+~230, elapsed~4s, RSS 20MB.
2483
+ The build log endpoint variant (.../logs/build) also exists. NOTE the per-cycle DIAG fields:
2484
+ states / s0z / stg[1..5] / shard / active / picks / api_ok+ / api_err+ / thin+ / zones+.
2485
+ 5. Clarified the SECONDARY (thin+=230): newly-listed perps with <80 candles of HISTORY in the
2486
+ UNCAPPED universe (max_symbols=0, universe_top_n=0). NOT a liquidity problem -> universe_top_n
2487
+ is the WRONG fix (would drop good low-cap pairs, user correctly objected). Correct cheap fix =
2488
+ thin-skip TTL cache (see plan Β§6). This is throughput, NOT the freeze.
2489
+ 6. WROTE the new IMPLEMENTATION_PLAN_v7.5.md (cleared old, now Stage-0 Lock-In fix): full plans
2490
+ for Option B (re-sort on better zone) and Option C (never lock at Stage 0 β€” RECOMMENDED),
2491
+ with code-grounded change lists, consequences, impact-level table, test matrix, rollout flags,
2492
+ and a build order. Verified code facts used in the plan: zone acquisition guard `if st.zone is
2493
+ None` (L2897); stages 1-3 re-derived every cycle (idempotent, proven by _probe_zone_stage);
2494
+ committed floor `if st.stage>=4: return None` (L2995); persistence saves stage>=1 only (L1789);
2495
+ no stage0 consumers in trades.html/market.js; counts_by_stage.stage0 feeds the Symbols card.
2496
+
2497
+ STATE AFTER SESSION 20: diagnosis COMPLETE + proven; DIAG instrument shipped (leave ON until the
2498
+ freeze fix is verified, then turn OFF); fix NOT yet built (user out of credits). NEXT AGENT: build
2499
+ Option C behind flag `stage0_require_stage1_to_lock` (default True) per IMPLEMENTATION_PLAN_v7.5.md
2500
+ Β§4 + Β§9, run test matrix Β§7, deploy with DIAG ON, confirm s0z->~0 and no re-freeze over hours.
2501
+ Do NOT re-diagnose Issue #1 β€” it is solved. Open items remain: Issue #2 (TP-hit logged as Stage-4
2502
+ invalidation) and E1 (Sweep-Reclaim Re-Entry blueprint).