#!/usr/bin/env python3
"""Independently verify the frozen GBPUSD Elder-Ray13 evidence from raw M1 ZIPs.

This standalone implementation does not import or execute the canonical engine.
It rebuilds source normalization, observed H4 candles, Decimal50 indicators,
strict decisions, minute execution phases and all eight collateral accounts.
Numpy stores exact source integers; no binary float participates in decisions.
"""
import argparse
import bisect
import calendar
import datetime as dt
from decimal import Decimal, getcontext, ROUND_CEILING, ROUND_FLOOR
import hashlib
import io
import json
from pathlib import Path
import statistics
import sys
import zipfile
from zoneinfo import ZoneInfo

import numpy as np


getcontext().prec = 50
D = Decimal
ZERO, ONE, HUNDRED = D(0), D(1), D(100)
SCALE, STEP = 1000000, 14400
UTC = dt.timezone.utc
NY = ZoneInfo("America/New_York")
# Reviewed protocol bytes frozen before the first canonical Elder calculation.
FROZEN = "dfde0e19fc89fb358dfd2c4ee3292fbaf8f4895077af63bae295ceda67b44dab"
PINS = {
    "GBPUSD-M1-2019.zip": "bc6d390e539d267fcd7856851db463fc098de5d7f7d732ddca75604f4a259bf2",
    "GBPUSD-M1-2020.zip": "07ad9524551d1b5bc617cd6971e5a6f38156f92e7046fa368abd22cbe7d9a044",
    "GBPUSD-M1-2021.zip": "5ce226e9e1cabcb8d3cab7d5c64135da2c864b0d79a559c8a08c6e1e3d47866e",
    "GBPUSD-M1-2022.zip": "6c3134133d24effe9ebae1ee02c7b0db3bff8f60f92bd9add846abc54d00a86e",
    "GBPUSD-M1-2023.zip": "4e7031d841a953ae76d1ba056780838bddd08e0d5eac62dd21c64b28b7b1a68b",
    "GBPUSD-M1-2024.zip": "030b05b4c670c7e152bf4aa4112488c96695d2dcc2b31ca13a3b4834b8431077",
    "GBPUSD-M1-2025.zip": "7b69c334eadd10568168634cff3ca37b06e5fb9057db4da9b590e2ef2034854e",
}

# Original local manifest bytes are embedded so the public checker is standalone.
MANIFEST_TEXT = r'''{
  "source": "HistData Generic ASCII M1 Bid",
  "timezone": "fixed EST UTC-05 without DST",
  "provider_published_hash": false,
  "reused_after_protocol_freeze": true,
  "files": [
    {
      "symbol": "GBPUSD",
      "period": "2019",
      "path": "data/eurusd-bb-squeeze/raw/GBPUSD-M1-2019.zip",
      "source_page": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/1-minute-bar-quotes/GBPUSD/2019",
      "download_endpoint": "https://www.histdata.com/get.php",
      "fetched_at_utc": "2026-11-04T14:35:50.071054+00:00",
      "http_status": 200,
      "content_type": "application/octet-stream",
      "bytes": 3411684,
      "sha256": "bc6d390e539d267fcd7856851db463fc098de5d7f7d732ddca75604f4a259bf2",
      "members": [
        {
          "name": "DAT_ASCII_GBPUSD_M1_2019.csv",
          "bytes": 20109384,
          "crc32": "160f03e9"
        },
        {
          "name": "DAT_ASCII_GBPUSD_M1_2019.txt",
          "bytes": 21130,
          "crc32": "e5e50bcf"
        }
      ],
      "status": "downloaded"
    },
    {
      "symbol": "GBPUSD",
      "period": "2020",
      "path": "data/eurusd-bb-squeeze/raw/GBPUSD-M1-2020.zip",
      "source_page": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/1-minute-bar-quotes/GBPUSD/2020",
      "download_endpoint": "https://www.histdata.com/get.php",
      "fetched_at_utc": "2026-11-04T14:35:50.189419+00:00",
      "http_status": 200,
      "content_type": "application/octet-stream",
      "bytes": 3625339,
      "sha256": "07ad9524551d1b5bc617cd6971e5a6f38156f92e7046fa368abd22cbe7d9a044",
      "members": [
        {
          "name": "DAT_ASCII_GBPUSD_M1_2020.csv",
          "bytes": 20145078,
          "crc32": "586ec6c6"
        },
        {
          "name": "DAT_ASCII_GBPUSD_M1_2020.txt",
          "bytes": 37763,
          "crc32": "d75d96b9"
        }
      ],
      "status": "downloaded"
    },
    {
      "symbol": "GBPUSD",
      "period": "2021",
      "path": "data/eurusd-bb-squeeze/raw/GBPUSD-M1-2021.zip",
      "source_page": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/1-minute-bar-quotes/GBPUSD/2021",
      "download_endpoint": "https://www.histdata.com/get.php",
      "fetched_at_utc": "2026-11-04T14:35:50.111823+00:00",
      "http_status": 200,
      "content_type": "application/octet-stream",
      "bytes": 3447415,
      "sha256": "5ce226e9e1cabcb8d3cab7d5c64135da2c864b0d79a559c8a08c6e1e3d47866e",
      "members": [
        {
          "name": "DAT_ASCII_GBPUSD_M1_2021.csv",
          "bytes": 20001492,
          "crc32": "968163bc"
        },
        {
          "name": "DAT_ASCII_GBPUSD_M1_2021.txt",
          "bytes": 232178,
          "crc32": "fd986272"
        }
      ],
      "status": "downloaded"
    },
    {
      "symbol": "GBPUSD",
      "period": "2022",
      "path": "data/eurusd-bb-squeeze/raw/GBPUSD-M1-2022.zip",
      "source_page": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/1-minute-bar-quotes/GBPUSD/2022",
      "download_endpoint": "https://www.histdata.com/get.php",
      "fetched_at_utc": "2026-11-04T14:36:02.561313+00:00",
      "http_status": 200,
      "content_type": "application/octet-stream",
      "bytes": 3670216,
      "sha256": "6c3134133d24effe9ebae1ee02c7b0db3bff8f60f92bd9add846abc54d00a86e",
      "members": [
        {
          "name": "DAT_ASCII_GBPUSD_M1_2022.csv",
          "bytes": 20114676,
          "crc32": "75949457"
        },
        {
          "name": "DAT_ASCII_GBPUSD_M1_2022.txt",
          "bytes": 105440,
          "crc32": "a2d68a50"
        }
      ],
      "status": "downloaded"
    },
    {
      "symbol": "GBPUSD",
      "period": "2023",
      "path": "data/eurusd-bb-squeeze/raw/GBPUSD-M1-2023.zip",
      "source_page": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/1-minute-bar-quotes/GBPUSD/2023",
      "download_endpoint": "https://www.histdata.com/get.php",
      "fetched_at_utc": "2026-11-04T14:36:02.570040+00:00",
      "http_status": 200,
      "content_type": "application/octet-stream",
      "bytes": 3049553,
      "sha256": "4e7031d841a953ae76d1ba056780838bddd08e0d5eac62dd21c64b28b7b1a68b",
      "members": [
        {
          "name": "DAT_ASCII_GBPUSD_M1_2023.csv",
          "bytes": 17413218,
          "crc32": "64c30dce"
        },
        {
          "name": "DAT_ASCII_GBPUSD_M1_2023.txt",
          "bytes": 118766,
          "crc32": "4872766c"
        }
      ],
      "status": "downloaded"
    },
    {
      "symbol": "GBPUSD",
      "period": "2024",
      "path": "data/eurusd-bb-squeeze/raw/GBPUSD-M1-2024.zip",
      "source_page": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/1-minute-bar-quotes/GBPUSD/2024",
      "download_endpoint": "https://www.histdata.com/get.php",
      "fetched_at_utc": "2026-11-04T14:36:02.448837+00:00",
      "http_status": 200,
      "content_type": "application/octet-stream",
      "bytes": 3375781,
      "sha256": "030b05b4c670c7e152bf4aa4112488c96695d2dcc2b31ca13a3b4834b8431077",
      "members": [
        {
          "name": "DAT_ASCII_GBPUSD_M1_2024.csv",
          "bytes": 20093778,
          "crc32": "67455607"
        },
        {
          "name": "DAT_ASCII_GBPUSD_M1_2024.txt",
          "bytes": 173828,
          "crc32": "cc315213"
        }
      ],
      "status": "downloaded"
    },
    {
      "symbol": "GBPUSD",
      "period": "2025",
      "path": "data/eurusd-bb-squeeze/raw/GBPUSD-M1-2025.zip",
      "source_page": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/1-minute-bar-quotes/GBPUSD/2025",
      "download_endpoint": "https://www.histdata.com/get.php",
      "fetched_at_utc": "2026-11-04T14:36:02.582415+00:00",
      "http_status": 200,
      "content_type": "application/octet-stream",
      "bytes": 3496823,
      "sha256": "7b69c334eadd10568168634cff3ca37b06e5fb9057db4da9b590e2ef2034854e",
      "members": [
        {
          "name": "DAT_ASCII_GBPUSD_M1_2025.csv",
          "bytes": 20038914,
          "crc32": "c230c60d"
        },
        {
          "name": "DAT_ASCII_GBPUSD_M1_2025.txt",
          "bytes": 153140,
          "crc32": "4f2d5df0"
        }
      ],
      "status": "downloaded"
    }
  ]
}
'''
MANIFEST_SHA256 = '2ae2ccdaaa1e727f8d2cf3f94284e31cdcc22362f428a597f8b86e691adff6fd'


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def decimal(value):
    return value if isinstance(value, D) else D(str(value))


def sign(value):
    return 1 if value > 0 else -1 if value < 0 else 0


def epoch(value):
    return int(dt.datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())


def iso(value):
    return dt.datetime.fromtimestamp(value, UTC).isoformat().replace("+00:00", "Z")


def digest(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def price_integer(text):
    fields = text.split(b".")
    require(len(fields) <= 2 and fields[0].isdigit(), "Malformed source price")
    fraction = fields[1] if len(fields) == 2 else b""
    require(not fraction or fraction.isdigit(), "Malformed source fraction")
    fraction = fraction.rstrip(b"0")
    require(len(fraction) <= 6, "Source price precision exceeds 1e-6")
    return int(fields[0])*SCALE + int((fraction+b"000000")[:6])


def original_minutes(folder, protocol, manifest):
    """Validate original archives and normalize source timestamps without filling."""
    listed = {Path(row["path"]).name: row for row in manifest["files"]}
    require(set(listed) == set(PINS), "Manifest must contain the seven original GBPUSD ZIPs")
    require(manifest.get("provider_published_hash") is False, "Misstated provider hash provenance")
    for name, pinned in PINS.items():
        row = listed[name]
        require(row["sha256"] == pinned and row["symbol"] == "GBPUSD", "Manifest pin identity changed")
        require(row["period"] == name[10:14], "Manifest year changed")
    first = epoch(protocol["warmup_start"])
    end = max(epoch(window[1]) for window in protocol["periods"].values())
    parts, records, duplicates, backward = [], [], [], []
    raw_rows = 0
    days = {}
    for name, pinned in sorted(PINS.items()):
        payload = (folder/name).read_bytes()
        meta = listed[name]
        require(hashlib.sha256(payload).hexdigest() == pinned, "Pinned ZIP changed: "+name)
        require(len(payload) == meta["bytes"], "Manifest ZIP byte size changed")
        with zipfile.ZipFile(io.BytesIO(payload)) as archive:
            require(archive.testzip() is None, "ZIP CRC check failed: "+name)
            require(set(archive.namelist()) == {m["name"] for m in meta["members"]}, "ZIP member identity changed")
            for member in meta["members"]:
                info = archive.getinfo(member["name"])
                require(info.file_size == member["bytes"] and format(info.CRC, "08x") == member["crc32"], "Pinned ZIP member metadata changed")
            csvs = [item for item in archive.namelist() if item.lower().endswith(".csv")]
            year = name[10:14]
            require(csvs == ["DAT_ASCII_GBPUSD_M1_"+year+".csv"], "Wrong source CSV identity")
            rows, seen = [], {}
            previous = None
            lines = archive.read(csvs[0]).splitlines(keepends=True)
            raw_rows += len(lines)
            for number, line in enumerate(lines, 1):
                fields = line.strip().split(b";")
                require(len(fields) == 6, "Expected timestamp, OHLC and placeholder volume")
                stamp = fields[0]
                require(len(stamp) == 15 and stamp[8:9] == b" " and stamp[:8].isdigit() and stamp[9:].isdigit(), "Malformed source timestamp")
                require(stamp[:4].decode() == year, "Timestamp outside its original annual source")
                if previous is not None and stamp < previous:
                    backward.append({"file":name,"row":number,"previous_stamp":previous.decode(),"stamp":stamp.decode()})
                previous = stamp
                if stamp in seen:
                    original_line, original_number = seen[stamp]
                    require(line == original_line, "Conflicting rows at an identical source timestamp")
                    duplicates.append({"file":name,"first_row":original_number,"duplicate_row":number,
                                       "source_stamp":stamp.decode(),"line_sha256":hashlib.sha256(line).hexdigest()})
                    continue
                seen[stamp] = (line, number)
                day = stamp[:8]
                if day not in days:
                    date = dt.date(int(day[:4]), int(day[4:6]), int(day[6:8]))
                    days[day] = calendar.timegm((date.year,date.month,date.day,0,0,0))
                hour, minute, second = int(stamp[9:11]), int(stamp[11:13]), int(stamp[13:15])
                require(hour < 24 and minute < 60 and second == 0, "Source timestamp is not a valid whole minute")
                timestamp = days[day]+hour*3600+minute*60+18000
                o,h,l,c = [price_integer(value) for value in fields[1:5]]
                require(0 < l <= min(o,c) <= max(o,c) <= h, "Invalid source OHLC")
                if first <= timestamp < end:
                    rows.append((timestamp,o,h,l,c))
            parts.append(np.asarray(rows,dtype=np.int64))
            records.append({"file":name,"sha256":pinned,"bytes":len(payload),"csv":csvs[0]})
    minutes = np.concatenate(parts)
    minutes = minutes[np.argsort(minutes[:,0],kind="stable")]
    require(len(minutes) > 0 and bool(np.all(np.diff(minutes[:,0]) > 0)), "UTC source minutes must be unique and ascending")
    return minutes, {"source_files":len(records),"sources":records,"rows":len(minutes),
                     "raw_rows_all_archives":raw_rows,"exact_duplicate_rows_removed":len(duplicates),
                     "duplicate_audit":duplicates,"source_backward_jumps":backward,
                     "invalid_count":0,"duplicate_count":0,"first_ts":int(minutes[0,0]),"last_ts":int(minutes[-1,0])}


def h4_observations(minutes):
    rows = []
    current = None
    for minute in minutes:
        timestamp = int(minute[0])
        anchor = timestamp//STEP*STEP
        if current is None or current["ts"] != anchor:
            if current is not None:
                rows.append(current)
            current = {"ts":anchor,"source_open_int":int(minute[1]),"source_high_int":int(minute[2]),
                       "source_low_int":int(minute[3]),"source_close_int":int(minute[4]),
                       "n":1,"first_ts":timestamp,"last_ts":timestamp}
        else:
            current["source_high_int"] = max(current["source_high_int"],int(minute[2]))
            current["source_low_int"] = min(current["source_low_int"],int(minute[3]))
            current["source_close_int"] = int(minute[4])
            current["n"] += 1
            current["last_ts"] = timestamp
    if current is not None:
        rows.append(current)
    for row in rows:
        for key in ("open","high","low","close"):
            row[key] = D(row["source_"+key+"_int"])/SCALE
    return rows


def raw_setups(rows, index):
    if index < 1:
        return False, False
    before, now = rows[index-1], rows[index]
    if now["ts"]-before["ts"] != STEP:
        return False, False
    if any(row.get(field) is None for row in (before,now) for field in ("ema13","bulls","bears")):
        return False, False
    return (now["bears"] < 0 and now["bears"] > before["bears"],
            now["bulls"] > 0 and now["bulls"] < before["bulls"])


def ema_slope(rows, index):
    if index < 1 or rows[index].get("ema13") is None or rows[index-1].get("ema13") is None:
        return 0
    return sign(rows[index]["ema13"]-rows[index-1]["ema13"])


def entry_direction(rows, index, variant):
    long_setup, short_setup = raw_setups(rows,index)
    # The common ambiguity rule is applied BEFORE the comparator's slope gate.
    if long_setup == short_setup:
        return 0
    atr = rows[index].get("atr14")
    if atr is None or not atr.is_finite() or atr <= 0:
        return 0
    direction = 1 if long_setup else -1
    return direction if variant == "no_slope" or ema_slope(rows,index) == direction else 0


def indicators(rows):
    ema, atr = None, None
    closes, ranges = [], []
    for index, row in enumerate(rows):
        closes.append(row["close"])
        if index == 12:
            ema = sum(closes,ZERO)/13
        elif index > 12:
            ema = (D(6)*ema+row["close"])/7
        tr = row["high"]-row["low"]
        if index:
            previous_close = rows[index-1]["close"]
            tr = max(tr,abs(row["high"]-previous_close),abs(row["low"]-previous_close))
        ranges.append(tr)
        if index == 13:
            atr = sum(ranges,ZERO)/14
        elif index > 13:
            atr = (D(13)*atr+tr)/14
        row.update(ema13=ema,bulls=None if ema is None else row["high"]-ema,
                   bears=None if ema is None else row["low"]-ema,atr14=atr)
        raw_long, raw_short = raw_setups(rows,index)
        row.update(raw_long=raw_long,raw_short=raw_short,setup_conflict=raw_long and raw_short,
                   ema_slope=ema_slope(rows,index))
        row["setup_direction"] = 1 if raw_long and not raw_short else -1 if raw_short and not raw_long else 0
        row["primary_direction"] = entry_direction(rows,index,"primary")
        row["no_slope_direction"] = entry_direction(rows,index,"no_slope")
    return rows


def calendar_events(start, end):
    rollovers, sessions, fridays = [], [], []
    day = dt.datetime.fromtimestamp(start,UTC).astimezone(NY).date()-dt.timedelta(days=8)
    finish = dt.datetime.fromtimestamp(end,UTC).astimezone(NY).date()+dt.timedelta(days=8)
    while day <= finish:
        cutoff = int(dt.datetime.combine(day,dt.time(17),NY).timestamp())
        if day.weekday() < 5:
            rollovers.append((cutoff,3 if day.weekday() == 2 else 1))
        if day.weekday() == 4:
            fridays.append(cutoff)
        if day.weekday() == 6:
            end_week = int(dt.datetime.combine(day+dt.timedelta(days=5),dt.time(17),NY).timestamp())
            sessions.append((cutoff,end_week))
        day += dt.timedelta(days=1)
    return rollovers,sessions,fridays


def inside_session(timestamp, sessions):
    index = bisect.bisect_right([item[0] for item in sessions],timestamp)-1
    return index >= 0 and sessions[index][0] <= timestamp < sessions[index][1]


def gap_quality(minutes, sessions):
    starts = [item[0] for item in sessions]
    gaps, missing = [], []
    outside = 0
    for index in np.flatnonzero(np.diff(minutes[:,0]) > 60):
        left, right = int(minutes[index,0]), int(minutes[index+1,0])
        count = (right-left)//60-1
        inside = 0
        session = max(0,bisect.bisect_right(starts,left+60)-1)
        while session < len(sessions) and sessions[session][0] < right:
            begin = max(left+60,sessions[session][0])
            end = min(right,sessions[session][1])
            if end > begin:
                inside += (end-begin)//60
                missing.extend(range(begin,end,60))
            session += 1
        outside += count-inside
        gaps.append({"left":left,"right":right,"missing_minutes":count,
                     "in_session_unobserved":inside,"outside_weekly_session":count-inside})
    return sorted(missing), {"gaps":gaps,"gap_count":len(gaps),"missing_minutes":len(missing)+outside,
                             "in_session_unobserved_minutes":len(missing),"outside_weekly_session_minutes":outside}


def verify_costs(protocol):
    require(decimal(protocol["pip_size"]) == D("0.0001"), "Frozen pip size changed")
    require(decimal(protocol["account"]["initial_cash"]) == D(10000), "Initial cash changed")
    require(decimal(protocol["account"]["risk_fraction"]) == D(".01"), "Risk fraction changed")
    for scenario, factor in (("baseline",ONE),("higher_cost",D(2)),("zero_cost",ZERO)):
        values = protocol["costs"][scenario]
        for field, value in (("spread_pips",D("1.5")),("slippage_pips_per_leg",D(".1")),
                             ("commission_usd_per_100000_gbp_per_leg",D("3.5")),
                             ("carry_pips_per_rollover_unit",D(".2"))):
            require(decimal(values[field]) == value*factor, "Frozen cost changed: "+scenario+"."+field)


def costs_for(protocol, variant):
    name = variant if variant in ("higher_cost","zero_cost") else "baseline"
    raw, pip = protocol["costs"][name], decimal(protocol["pip_size"])
    return {"scenario":name,"spread":decimal(raw["spread_pips"])*pip,
            "slip":decimal(raw["slippage_pips_per_leg"])*pip,
            "commission":decimal(raw["commission_usd_per_100000_gbp_per_leg"])/100000,
            "carry":decimal(raw["carry_pips_per_rollover_unit"])*pip}


def rollover_units(rollovers, entry, event, kind):
    return sum(units for cutoff,units in rollovers if entry < cutoff
               and (cutoff <= event if kind == "within_1m" else cutoff < event))


def already_flat(last, decision):
    return last is None or decision > last["exit_event_ts"] or (
        decision == last["exit_event_ts"] and last["exit_event_kind"] == "close")


def earliest_deadline(entry, end, fridays):
    friday = fridays[bisect.bisect_right(fridays,entry)]
    timestamp,_,reason = min((entry+30*STEP,0,"time"),(friday,1,"week_close"),(end,2,"period_end"))
    return timestamp,reason


def first_exit(minutes, entry_index, bars, direction, stop, costs, entry, deadline, deadline_reason, end):
    """At observed openings: stop gap, pending setup, deadline, then M1 range."""
    cutoffs = [row["ts"]+STEP for row in bars]
    next_cutoff = bisect.bisect_right(cutoffs,entry)
    pending = None
    # These integer thresholds are equivalent to exact comparisons with quoted
    # integer prices, including fractional-price stops and modeled short Ask.
    stop_bid = stop-(costs["spread"] if direction == -1 else ZERO)
    threshold = int((stop_bid*SCALE).to_integral_value(rounding=ROUND_FLOOR if direction == 1 else ROUND_CEILING))
    last_index = None
    for index in range(entry_index,len(minutes)):
        minute = minutes[index]
        timestamp = int(minute[0])
        if timestamp >= end:
            break
        while next_cutoff < len(bars) and cutoffs[next_cutoff] <= timestamp:
            row = bars[next_cutoff]
            trigger = row.get("raw_short",False) if direction == 1 else row.get("raw_long",False)
            if trigger and pending is None:
                pending = cutoffs[next_cutoff]
            next_cutoff += 1
        opening = int(minute[1])
        ref = D(opening)/SCALE+(costs["spread"] if direction == -1 else ZERO)
        crossed = opening <= threshold if direction == 1 else opening >= threshold
        if crossed:
            return {"index":index,"event_ts":timestamp,"kind":"open","ref":ref,"reason":"stop_gap","queue_ts":pending,"terminal_fallback":False}
        if pending is not None:
            return {"index":index,"event_ts":timestamp,"kind":"open","ref":ref,"reason":"signal_exit","queue_ts":pending,"terminal_fallback":False}
        if timestamp >= deadline:
            return {"index":index,"event_ts":timestamp,"kind":"open","ref":ref,"reason":deadline_reason,"queue_ts":pending,"terminal_fallback":False}
        edge = int(minute[3] if direction == 1 else minute[2])
        if (edge <= threshold if direction == 1 else edge >= threshold):
            return {"index":index,"event_ts":timestamp,"kind":"within_1m","ref":stop,"reason":"stop","queue_ts":pending,"terminal_fallback":False}
        last_index = index
        if timestamp+60 == deadline:
            ref = D(int(minute[4]))/SCALE+(costs["spread"] if direction == -1 else ZERO)
            return {"index":index,"event_ts":deadline,"kind":"close","ref":ref,"reason":deadline_reason,"queue_ts":pending,"terminal_fallback":False}
    require(last_index is not None,"No in-period quote following entry")
    minute = minutes[last_index]
    ref = D(int(minute[4]))/SCALE+(costs["spread"] if direction == -1 else ZERO)
    return {"index":last_index,"event_ts":int(minute[0])+60,"kind":"close","ref":ref,
            "reason":"period_end","queue_ts":pending,"terminal_fallback":True}


def replay(rows, minutes, protocol, variant, period, rollovers, sessions, fridays, missing):
    begin,end = [epoch(value) for value in protocol["periods"][period]]
    costs = costs_for(protocol,variant)
    initial = decimal(protocol["account"]["initial_cash"])
    cash = initial
    trades = []
    canceled = invalid = outside = capped = conflicts = invalid_atr = no_cash = no_quantity = slope_rejected = 0
    last = None
    times = minutes[:,0]
    by_anchor = {row["ts"]:row for row in rows}
    raw_exit_cutoffs = {
        1:[row["ts"]+STEP for row in rows if row.get("raw_short",False)],
        -1:[row["ts"]+STEP for row in rows if row.get("raw_long",False)]}
    for index,row in enumerate(rows):
        decision = row["ts"]+STEP
        if not begin <= decision < end or not already_flat(last,decision):
            continue
        raw_long, raw_short = raw_setups(rows,index)
        if raw_long and raw_short:
            conflicts += 1
            continue
        if raw_long != raw_short and (row.get("atr14") is None or not row["atr14"].is_finite() or row["atr14"] <= 0):
            invalid_atr += 1
            continue
        direction = entry_direction(rows,index,variant)
        if not direction:
            if raw_long != raw_short and row.get("atr14") is not None and row["atr14"] > 0 and variant != "no_slope":
                slope_rejected += 1
            continue
        if not cash.is_finite() or cash <= 0:
            no_cash += 1
            continue
        if not inside_session(decision,sessions):
            outside += 1
            continue
        entry_index = int(np.searchsorted(times,decision))
        if entry_index >= len(minutes) or int(times[entry_index]) != decision:
            canceled += 1
            continue
        bid = D(int(minutes[entry_index,1]))/SCALE
        fill = bid+(costs["spread"] if direction == 1 else ZERO)+direction*costs["slip"]
        distance = D(2)*row["atr14"]
        stop = fill-direction*distance
        exit_open_quote = bid+(costs["spread"] if direction == -1 else ZERO)
        if not stop.is_finite() or stop <= 0 or not (stop < exit_open_quote if direction == 1 else stop > exit_open_quote):
            invalid += 1
            continue
        lunit = distance+costs["slip"]+D(2)*costs["commission"]
        risk_quantity = decimal(protocol["account"]["risk_fraction"])*cash/lunit
        cap_quantity = cash/(abs(fill)+costs["commission"])
        quantity = min(risk_quantity,cap_quantity)
        if not quantity.is_finite() or quantity <= 0:
            no_quantity += 1
            continue
        is_capped = cap_quantity < risk_quantity
        capped += is_capped
        deadline,reason = earliest_deadline(decision,end,fridays)
        event = first_exit(minutes,entry_index,rows,direction,stop,costs,decision,deadline,reason,end)
        event_ts,kind = event["event_ts"],event["kind"]
        exit_fill = event["ref"]-direction*costs["slip"]
        units = rollover_units(rollovers,decision,event_ts,kind)
        # Compute the exact per-GBP net identity first: a truly flat trade stays
        # exactly zero and cannot acquire an artificial win/loss sign.
        net_unit = direction*(exit_fill-fill)-D(2)*costs["commission"]-costs["carry"]*units
        pnl = quantity*net_unit
        lo = bisect.bisect_right(missing,decision)
        hi = bisect.bisect_right(missing,event_ts) if kind == "within_1m" else bisect.bisect_left(missing,event_ts)
        source_minute = int(minutes[event["index"],0])
        exit_anchor = source_minute//STEP*STEP
        exit_row = by_anchor[exit_anchor]
        future = raw_exit_cutoffs[direction]
        future_index = bisect.bisect_right(future,decision)
        queued = future[future_index] if future_index < len(future) else None
        previous = rows[index-1]
        trade = {
            "number":len(trades)+1,"variant":variant,"period":period,
            "side":"long" if direction == 1 else "short","direction":direction,
            "signal_ts":row["ts"],"signal_bar_ts":row["ts"],"decision_ts":decision,"entry_ts":decision,
            "exit_event_ts":event_ts,"exit_event_kind":kind,
            "exit_event_precision":{"open":"at_open","close":"at_close","within_1m":"within_1m"}[kind],
            "exit_bar_ts":exit_anchor,"source_exit_minute_ts":source_minute,
            "entry":fill,"entry_ref":bid,"exit":exit_fill,"exit_ref":event["ref"],
            "exit_bid_ref":event["ref"]-(costs["spread"] if direction == -1 else ZERO),
            "stop":stop,"signal_atr":row["atr14"],"signal_ema13":row["ema13"],
            "signal_ema13_prev":previous["ema13"],"signal_bulls":row["bulls"],"signal_bears":row["bears"],
            "signal_bulls_prev":previous["bulls"],"signal_bears_prev":previous["bears"],
            "signal_ema_slope":ema_slope(rows,index),"signal_raw_long":raw_long,"signal_raw_short":raw_short,
            "signal_conflict":raw_long and raw_short,"quantity":quantity,"qty":quantity,
            "preentry_equity":cash,"risk_cash":quantity*lunit,"lunit":lunit,
            "notional":quantity*abs(fill),"notional_capped":is_capped,
            "pnl":pnl,"net_r":net_unit/lunit,"fees":D(2)*quantity*costs["commission"],
            "financing":quantity*costs["carry"]*units,"rollover_units":units,
            "spread_cost":quantity*costs["spread"],"slippage_cost":D(2)*quantity*costs["slip"],
            "cash_after":cash+pnl,"reason":event["reason"],"deadline":deadline,"deadline_reason":reason,
            "terminal_fallback":event["terminal_fallback"],"crosses_gap":hi>lo,"missing_open_minutes_crossed":hi-lo,
            "partial_signal":row["n"]<240,"partial_exit_bucket":exit_row["n"]<240,
            "stale_signal_close":row["last_ts"]+60 != decision,"queued_exit_ts":queued,
            "delayed_signal_exit":event["reason"] == "signal_exit" and queued is not None and event_ts > queued,
            "quote_side_exit":"Bid" if direction == 1 else "modeled Ask",
            "holding_bars":D(event_ts-decision)/STEP,"holding_h4_slots_lower":D(event_ts-decision)/STEP,
            "holding_h4_slots_upper":D(event_ts-decision+(60 if kind == "within_1m" else 0))/STEP}
        trades.append(trade)
        cash += pnl
        last = trade
    equity,settled,peak,position,occupied_count = [],initial,initial,0,0
    for row in rows:
        if not begin <= row["ts"] < end:
            continue
        cutoff = min(row["ts"]+STEP,end)
        while position < len(trades):
            trade = trades[position]
            if not (trade["exit_event_ts"] < cutoff or (trade["exit_event_ts"] == cutoff and trade["exit_event_kind"] == "close")):
                break
            settled = trade["cash_after"]
            position += 1
        value = settled
        if position < len(trades) and trades[position]["entry_ts"] < cutoff:
            trade = trades[position]
            kind = trade["exit_event_kind"] if trade["exit_event_ts"] == cutoff else "within_1m"
            units = rollover_units(rollovers,trade["entry_ts"],cutoff,kind)
            liquidation = row["close"]+(costs["spread"] if trade["direction"] == -1 else ZERO)-trade["direction"]*costs["slip"]
            unit_value = trade["direction"]*(liquidation-trade["entry"])-D(2)*costs["commission"]-costs["carry"]*units
            value = trade["preentry_equity"]+trade["quantity"]*unit_value
        occupied = any(trade["entry_ts"] < cutoff and (trade["exit_event_ts"] > row["ts"] or (
            trade["exit_event_ts"] == row["ts"] and trade["exit_event_kind"] == "within_1m")) for trade in trades)
        occupied_count += occupied
        peak = max(peak,value)
        equity.append({"ts":cutoff,"bar_ts":row["ts"],"equity":value,
                       "drawdown_pct":HUNDRED*(peak-value)/peak,"cash":settled,"occupied":occupied})
    profits,ratios = [trade["pnl"] for trade in trades],[trade["net_r"] for trade in trades]
    gain,loss = sum((value for value in profits if value > 0),ZERO),-sum((value for value in profits if value < 0),ZERO)
    cumulative,maximum_r,drawdown_r = ZERO,ZERO,ZERO
    for value in ratios:
        cumulative += value
        maximum_r = max(maximum_r,cumulative)
        drawdown_r = max(drawdown_r,maximum_r-cumulative)
    metrics = {
        "return_pct":HUNDRED*(cash/initial-ONE),"end_cash":cash,"trades":len(trades),
        "wins":sum(value>0 for value in profits),"losses":sum(value<0 for value in profits),
        "breakevens":sum(value==0 for value in profits),"profit_factor":gain/loss if loss else None,
        "mean_r":sum(ratios,ZERO)/len(ratios) if ratios else None,
        "median_r":statistics.median(ratios) if ratios else None,"sum_r":sum(ratios,ZERO),"drawdown_r":drawdown_r,
        "drawdown_pct":max((point["drawdown_pct"] for point in equity),default=ZERO),
        "fees":sum((trade["fees"] for trade in trades),ZERO),"financing":sum((trade["financing"] for trade in trades),ZERO),
        "rollover_units":sum(trade["rollover_units"] for trade in trades),
        "spread_cost":sum((trade["spread_cost"] for trade in trades),ZERO),
        "slippage_cost":sum((trade["slippage_cost"] for trade in trades),ZERO),
        "exposure_pct":HUNDRED*occupied_count/len(equity) if equity else ZERO,
        "notional_capped":capped,"cash_capped":capped,"canceled_missing_entry":canceled,
        "invalid_stop_entries":invalid,"outside_weekly_session_entries":outside,
        "ambiguous_entry_candidates":conflicts,"invalid_atr_candidates":invalid_atr,"slope_rejected_entries":slope_rejected,
        "nonpositive_cash_skips":no_cash,"invalid_quantity_entries":no_quantity,
        "gap_trades":sum(trade["crosses_gap"] for trade in trades),
        "partial_signal_trades":sum(trade["partial_signal"] for trade in trades),
        "stale_signal_trades":sum(trade["stale_signal_close"] for trade in trades),
        "partial_exit_trades":sum(trade["partial_exit_bucket"] for trade in trades),
        "delayed_signal_exits":sum(trade["delayed_signal_exit"] for trade in trades),
        "terminal_fallbacks":sum(trade["terminal_fallback"] for trade in trades),
        "long_trades":sum(trade["direction"]==1 for trade in trades),
        "short_trades":sum(trade["direction"]==-1 for trade in trades),
        "mean_holding":sum((trade["holding_bars"] for trade in trades),ZERO)/len(trades) if trades else None,
        "median_holding":statistics.median(trade["holding_bars"] for trade in trades) if trades else None}
    annual,groups,start_cash = [],{},initial
    for point in equity:
        groups[dt.datetime.fromtimestamp(point["bar_ts"],UTC).year] = point["equity"]
    for year,finish in sorted(groups.items()):
        annual.append({"year":year,"return_pct":HUNDRED*(finish/start_cash-ONE),"start_equity":start_cash,"end_equity":finish})
        start_cash = finish
    return {"variant":variant,"period":period,"start_ts":begin,"end_ts":end,
            "metrics":metrics,"trades":trades,"equity":equity,"annual":annual}


class Compare:
    MONEY = {"equity","cash","initial_cash","end_cash","cash_after","preentry_equity","risk_cash","pnl","fees",
             "financing","notional","spread_cost","slippage_cost","start_equity","end_equity","retained_ledger_pnl"}
    SIGNED = {"bulls","bears","signal_bulls","signal_bears","signal_bulls_prev","signal_bears_prev","pnl","net_r"}

    def __init__(self):
        self.numeric,self.exact,self.failures = 0,0,0
        self.samples,self.max_errors,self.max_locations,self.fields = [],{},{},set()

    def failure(self,path,expected,actual,tolerance=None):
        self.failures += 1
        if len(self.samples) < 40:
            self.samples.append({"path":path,"expected":str(expected),"actual":str(actual),
                                 "tolerance":str(tolerance) if tolerance is not None else None})

    def one(self,expected,actual,path):
        key = path.rsplit(".",1)[-1]
        self.fields.add(key)
        if isinstance(expected,(bool,str,int)) or expected is None:
            self.exact += 1
            if expected != actual or (isinstance(expected,bool) and not isinstance(actual,bool)):
                self.failure(path,expected,actual)
            return
        require(isinstance(expected,(D,float)),"Unsupported comparison type: "+type(expected).__name__)
        self.numeric += 1
        kind = "money_USD" if key in self.MONEY else "quantity_GBP" if key in ("quantity","qty") else "price_indicator_metric"
        tolerance = D(".000001") if kind == "money_USD" else D(".0000001") if kind == "quantity_GBP" else D(".00000001")
        if actual is None or isinstance(actual,bool):
            self.failure(path,expected,actual,tolerance)
            return
        x,y = decimal(expected),decimal(actual)
        if not x.is_finite() or not y.is_finite():
            self.failure(path,expected,actual,tolerance)
            return
        if key in self.SIGNED:
            self.exact += 1
            if sign(x) != sign(y):
                self.failure(path+".sign",sign(x),sign(y))
        error = abs(x-y)
        if error > self.max_errors.get(kind,ZERO):
            self.max_errors[kind],self.max_locations[kind] = error,path
        if error > tolerance:
            self.failure(path,expected,actual,tolerance)

    def published(self,expected,actual,path):
        """Every published field is covered; independent extra detail is allowed."""
        if isinstance(actual,dict):
            require(isinstance(expected,dict),path+" expected object")
            unknown = set(actual)-set(expected)
            require(not unknown,"Unverified published fields at "+path+": "+str(sorted(unknown)))
            for key,value in actual.items():
                self.published(expected[key],value,path+"."+key)
        elif isinstance(actual,list):
            require(isinstance(expected,list),path+" expected list")
            self.one(len(expected),len(actual),path+".length")
            for index,(x,y) in enumerate(zip(expected,actual)):
                self.published(x,y,path+"."+str(index))
        else:
            self.one(expected,actual,path)


def toy_rows(count=20,start=0):
    return [{"ts":start+index*STEP,"open":ONE,"high":D("1.01"),"low":D(".99"),"close":ONE,
             "n":240,"first_ts":start+index*STEP,"last_ts":start+(index+1)*STEP-60,
             "source_open_int":SCALE,"source_high_int":1010000,"source_low_int":990000,"source_close_int":SCALE}
            for index in range(count)]


def toy_protocol(start,end,cash=10000):
    return {"periods":{"full":[iso(start),iso(end)]},"pip_size":.0001,
            "account":{"initial_cash":cash,"risk_fraction":.01},
            "costs":{"baseline":{"spread_pips":1.5,"slippage_pips_per_leg":.1,
                "commission_usd_per_100000_gbp_per_leg":3.5,"carry_pips_per_rollover_unit":.2}}}


def synthetic_tests():
    tests = []
    def check(name,condition):
        require(condition,"Synthetic failure: "+name)
        tests.append({"name":name,"status":"passed"})
    rows = indicators(toy_rows())
    check("EMA13 seed index12 and ATR14 seed index13",next(i for i,r in enumerate(rows) if r["ema13"] is not None)==12 and next(i for i,r in enumerate(rows) if r["atr14"] is not None)==13)
    check("SMA13 seed and constant EMA stay exact",rows[12]["ema13"] == ONE and all(row["ema13"] == ONE for row in rows[12:]))
    check("Bulls and Bears use same EMA and their difference is H-L",all(row["bulls"]-row["bears"] == row["high"]-row["low"] for row in rows[12:]))
    check("equality is not rising or falling",all(not row["raw_long"] and not row["raw_short"] for row in rows))
    ramp = toy_rows(14)
    for i,row in enumerate(ramp):
        row["close"] = ONE+D(i)/100
        row["high"],row["low"] = row["close"]+D(".01"),row["close"]-D(".01")
    indicators(ramp)
    check("EMA13 arithmetic seed and alpha1/7 recursion",ramp[12]["ema13"]==D("1.06") and ramp[13]["ema13"]==D("1.07"))
    pair = toy_rows(2)
    pair[0].update(ema13=ONE,bulls=D(".002"),bears=D("-.002"),atr14=D(".001"))
    pair[1].update(ema13=D("1.001"),bulls=D(".001"),bears=D("-.001"),atr14=D(".001"))
    check("both strict raw setups are simultaneously possible",raw_setups(pair,1)==(True,True))
    check("common both-raw conflict precedes slope gate for primary and control",entry_direction(pair,1,"primary")==0 and entry_direction(pair,1,"no_slope")==0)
    pair[1]["bulls"] = pair[0]["bulls"]
    check("unchanged Bulls do not produce short setup",raw_setups(pair,1)==(True,False))
    pair[1]["bears"] = ZERO
    check("current zero Bears fail strict negative requirement",not raw_setups(pair,1)[0])
    pair[1].update(bears=D("-.001"),bulls=ZERO)
    check("current zero Bulls fail strict positive requirement",not raw_setups(pair,1)[1])
    pair[1]["ema13"] = ONE
    check("zero EMA slope fails primary while no_slope removes only gate",entry_direction(pair,1,"primary")==0 and entry_direction(pair,1,"no_slope")==1)
    pair[1]["atr14"] = None
    check("raw setup survives missing ATR while entry remains blocked",raw_setups(pair,1)==(True,False) and entry_direction(pair,1,"no_slope")==0)
    pair[1]["atr14"] = D(".001")
    pair[1]["bears"] = pair[0]["bears"]
    check("unchanged Bears do not produce long setup",raw_setups(pair,1)==(False,False))
    pair[1].update(bears=D("-.001"),ts=2*STEP)
    check("nonadjacent anchors suppress both raw setups",raw_setups(pair,1)==(False,False))
    gap = toy_rows(14)
    gap[-1].update(ts=20*STEP,close=D(2),high=D("2.01"),low=D("1.99"))
    indicators(gap)
    check("EMA continues over actual observations across gap",gap[-1]["ema13"]==D(8)/7)
    check("ATR uses previous observed close across gap",gap[-1]["atr14"]==(D(13)*D(".02")+D("1.01"))/14)
    start,end = epoch("2024-01-01T00:00:00Z"),epoch("2025-01-01T00:00:00Z")
    rolls,sessions,fridays = calendar_events(start,end)
    check("New York winter Friday17 is UTC22",epoch("2024-01-05T22:00:00Z") in fridays)
    check("New York summer Friday17 is UTC21",epoch("2024-07-05T21:00:00Z") in fridays)
    check("Sunday17 included and Friday17 excluded",inside_session(epoch("2024-07-07T21:00:00Z"),sessions) and not inside_session(epoch("2024-07-05T21:00:00Z"),sessions))
    check("DST Sunday session opening shifts in UTC",inside_session(epoch("2024-03-10T21:00:00Z"),sessions) and not inside_session(epoch("2024-03-10T20:59:00Z"),sessions))
    wednesday = epoch("2024-01-03T22:00:00Z")
    check("Wednesday intraminute exit includes triple rollover",rollover_units(rolls,wednesday-1,wednesday,"within_1m")==3)
    check("entry at rollover cutoff excludes debit",rollover_units(rolls,wednesday,wednesday+1,"within_1m")==0)
    check("opening and close exits at rollover cutoff exclude debit",rollover_units(rolls,wednesday-1,wednesday,"open")==0 and rollover_units(rolls,wednesday-1,wednesday,"close")==0)
    check("same opening and intraminute exits forbid reentry",all(not already_flat({"exit_event_ts":100,"exit_event_kind":kind},100) for kind in ("open","within_1m")))
    check("completed preceding minute close permits fresh decision",already_flat({"exit_event_ts":100,"exit_event_kind":"close"},100))
    check("deadline ties prefer time then week close then period end",earliest_deadline(0,30*STEP,[30*STEP])==(30*STEP,"time") and earliest_deadline(0,10*STEP,[10*STEP])==(10*STEP,"week_close"))
    costs = {"spread":D(".00015"),"slip":D(".00001"),"commission":D(".000035"),"carry":D(".00002")}
    both = [{"ts":0,"raw_long":False,"raw_short":False},
            {"ts":STEP,"raw_long":True,"raw_short":True,"atr14":None,"ema_slope":1}]
    minutes = np.array([[0,1000000,1000200,999800,1000000],[2*STEP,1000000,1000200,998000,1000000]],dtype=np.int64)
    event = first_exit(minutes,0,both,1,D(".999"),costs,0,10*STEP,"time",20*STEP)
    check("long exits on opposing raw despite BOTH setup conflict and absent ATR",event["reason"]=="signal_exit" and event["event_ts"]==2*STEP and event["kind"]=="open")
    event = first_exit(minutes,0,both,-1,D("1.002"),costs,0,10*STEP,"time",20*STEP)
    check("short exits on opposing raw despite nonconfirming EMA slope",event["reason"]=="signal_exit" and event["ref"]==D("1.00015"))
    minutes[1,0] += 60
    event = first_exit(minutes,0,both,1,D(".999"),costs,0,10*STEP,"time",20*STEP)
    check("missing exit opening keeps raw queue to first observed minute",event["queue_ts"]==2*STEP and event["event_ts"]==2*STEP+60)
    minutes[1,0] = 4*STEP
    event = first_exit(minutes,0,both,1,D(".999"),costs,0,3*STEP,"time",20*STEP)
    check("pending setup exit precedes overdue deadline after missing quotes",event["reason"]=="signal_exit")
    minutes[1,1] = 998000
    event = first_exit(minutes,0,both,1,D(".999"),costs,0,3*STEP,"time",20*STEP)
    check("opening stop gap precedes queued setup and overdue deadline",event["reason"]=="stop_gap" and event["ref"]==D(".998"))
    minutes = np.array([[0,1000000,1000200,999900,1000000]],dtype=np.int64)
    event = first_exit(minutes,0,[],-1,D("1.0003"),costs,0,10*STEP,"time",20*STEP)
    check("short barrier range uses modeled Ask high",event["reason"]=="stop" and event["ref"]==D("1.0003"))
    event = first_exit(minutes,0,[],-1,D("1.0001"),costs,0,10*STEP,"time",20*STEP)
    check("short opening gap triggers on Ask even when Bid is below stop",event["reason"]=="stop_gap" and event["ref"]==D("1.00015"))
    fractional = np.array([[0,1000000,1000150,999901,1000000]],dtype=np.int64)
    event = first_exit(fractional,0,[],1,D(".9999005"),costs,0,60,"period_end",60)
    check("fractional long stop never rounds up to an unhit source low",event["reason"]=="period_end")
    fractional[0,3] = 999900
    event = first_exit(fractional,0,[],1,D(".9999005"),costs,0,60,"period_end",60)
    check("fractional long stop triggers on the first integer below it",event["reason"]=="stop" and event["ref"]==D(".9999005"))
    event = first_exit(fractional,0,[],-1,D("1.0003005"),costs,0,60,"period_end",60)
    check("fractional short stop never rounds down to an unhit modeled Ask",event["reason"]=="period_end")
    fractional[0,2] = 1000151
    event = first_exit(fractional,0,[],-1,D("1.0003005"),costs,0,60,"period_end",60)
    check("fractional short stop triggers on the first integer Ask above it",event["reason"]=="stop")
    event = first_exit(minutes,0,[],1,D(".99995"),costs,0,60,"period_end",60)
    check("intraminute stop precedes exact deadline close",event["reason"]=="stop" and event["kind"]=="within_1m")
    event = first_exit(minutes,0,[],1,D(".999"),costs,0,60,"period_end",60)
    check("surviving exact deadline uses modeled minute close",event["kind"]=="close" and event["event_ts"]==60 and not event["terminal_fallback"])
    boundary = np.array([[0,1000000,1000200,999900,1000100],[120,900000,900000,800000,850000]],dtype=np.int64)
    event = first_exit(boundary,0,[],1,D(".999"),costs,0,120,"period_end",120)
    check("terminal fallback uses last in-period close and never later opening",event["event_ts"]==60 and event["ref"]==D("1.0001") and event["terminal_fallback"])
    elapsed = np.array([[0,1000000,1000200,999900,1000000],[30*STEP+60,1000000,1000200,999900,1000000]],dtype=np.int64)
    event = first_exit(elapsed,0,[],1,D(".999"),costs,0,30*STEP,"time",40*STEP)
    check("time deadline counts calendar H4 slots over data gaps",event["event_ts"]==30*STEP+60 and event["reason"]=="time" and event["kind"]=="open")
    check("exact per-unit PnL preserves mathematical breakeven",D("1.16222")-D("1.16215")-D(2)*D(".000035")==ZERO)
    at = epoch("2024-01-01T00:00:00Z")
    rs = toy_rows(4,at-STEP)
    for i,row in enumerate(rs):
        row.update(ema13=ONE+D(i)/10000,bulls=D(".003"),bears=D("-.003")+D(i)/10000,atr14=D(".001"))
        row["raw_long"],row["raw_short"] = raw_setups(rs,i)
    calendar_data = calendar_events(at,at+3*STEP)
    protocol = toy_protocol(at,at+3*STEP)
    mm = np.array([[at+STEP+60,1000000,1000200,999900,1000000]],dtype=np.int64)
    account = replay(rs,mm,protocol,"primary","full",*calendar_data,[])
    check("missing exact scheduled M1 opening cancels entry without late fill",account["metrics"]["canceled_missing_entry"]==2 and account["metrics"]["trades"]==0)
    mm = np.array([[at+STEP,1000000,1000200,999900,1000000]],dtype=np.int64)
    negative = toy_protocol(at,at+3*STEP,-1)
    account = replay(rs,mm,negative,"primary","full",*calendar_data,[])
    check("nonpositive collateral prevents negative quantity and new positions",account["metrics"]["nonpositive_cash_skips"]==2 and account["metrics"]["trades"]==0)
    # A real replay transition: entry on one completed setup, opposing setup
    # exits exactly on the next H4 opening, and would otherwise reverse there.
    for direction in (1,-1):
        rs = toy_rows(4,at-STEP)
        states = (("1",".003","-.003"),("1.0001",".003","-.0029"),("1",".002","-.003"),("1",".002","-.003")) if direction == 1 else (
            ("1.0003",".003","-.003"),("1.0002",".0029","-.003"),("1.0003",".003","-.0029"),("1.0003",".003","-.0029"))
        for i,(row,state) in enumerate(zip(rs,states)):
            row.update(ema13=D(state[0]),bulls=D(state[1]),bears=D(state[2]),atr14=D(".001"))
            row["raw_long"],row["raw_short"] = raw_setups(rs,i)
        exit_integer = SCALE+direction*240
        mm = np.array([[at+STEP,SCALE,SCALE+200,SCALE-100,SCALE+100],
                       [at+2*STEP,exit_integer,exit_integer+100,exit_integer-100,exit_integer]],dtype=np.int64)
        account = replay(rs,mm,protocol,"primary","full",*calendar_data,[])
        trade = account["trades"][0]
        expected_fill = ONE+(costs["spread"] if direction == 1 else ZERO)+direction*costs["slip"]
        expected_quantity = min(D(100)/D(".00208"),D(10000)/(abs(expected_fill)+costs["commission"]))
        label = "long" if direction == 1 else "short"
        check(label+" entry uses directional spread/slippage and collateral sizing",trade["entry"]==expected_fill and trade["quantity"]==expected_quantity and trade["stop"]==expected_fill-direction*D(".002"))
        check(label+" replay preserves exact breakeven after all 1.5-pip costs",trade["pnl"]==ZERO and account["metrics"]["breakevens"]==1 and account["metrics"]["wins"]==0 and account["metrics"]["losses"]==0)
        check(label+" exact opening exit forbids immediate reversal",len(account["trades"])==1 and trade["reason"]=="signal_exit" and trade["exit_event_ts"]==at+2*STEP)
        mark = next(point for point in account["equity"] if point["ts"]==at+2*STEP)
        liquidation = ONE+(costs["spread"] if direction == -1 else ZERO)-direction*costs["slip"]
        expected_value = D(10000)+expected_quantity*(direction*(liquidation-expected_fill)-D(2)*costs["commission"])
        check(label+" opening exit remains held in preceding cutoff equity mark",mark["cash"]==D(10000) and mark["equity"]==expected_value and mark["occupied"])
    return tests


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--protocol",type=Path,required=True)
    parser.add_argument("--evidence",type=Path)
    parser.add_argument("--raw-dir",type=Path)
    parser.add_argument("--report",type=Path,default=Path("reports/gbpusd-elder-cluster-20261114/independent-verification.json"))
    parser.add_argument("--synthetic-only",action="store_true")
    args = parser.parse_args()
    comparison = Compare()
    report = {"status":"failed","method":"Independent Decimal50 source, indicators and minute-phase account replay; no canonical-engine import or execution",
              "decimal_precision":50,"tolerances_absolute":{"money_USD":"0.000001","quantity_GBP":"0.0000001",
              "price_indicator_metric":"0.00000001","discrete_decisions_and_signs":"exact"}}
    try:
        protocol = json.loads(args.protocol.read_text())
        protocol_hash = digest(args.protocol)
        report.update(protocol_sha256=protocol_hash,checker_sha256=digest(Path(__file__)))
        if not args.synthetic_only:
            require(FROZEN is not None,"Methodology not frozen; performance verification is disabled")
            require(protocol_hash == FROZEN,"Frozen protocol SHA256 changed")
        verify_costs(protocol)
        report["synthetic_tests"] = synthetic_tests()
        if not args.synthetic_only:
            require(args.evidence is not None and args.raw_dir is not None,"Evidence and original raw directory are required")
            evidence = json.loads(args.evidence.read_text())
            report["evidence_sha256"] = digest(args.evidence)
            require(evidence["protocol"] == protocol,"Embedded protocol differs from frozen protocol bytes")
            comparison.published(protocol,evidence["protocol"],"protocol")
            comparison.one(FROZEN,evidence["protocol_sha256"],"protocol_sha256")
            for key,value in (("account_currency","USD"),("quantity_currency","GBP"),("price_units","USD per GBP")):
                comparison.one(value,evidence[key],key)
            manifest_sha = hashlib.sha256(MANIFEST_TEXT.encode()).hexdigest()
            require(manifest_sha == MANIFEST_SHA256, "Embedded original manifest bytes changed")
            manifest = json.loads(MANIFEST_TEXT)
            minutes,quality = original_minutes(args.raw_dir,protocol,manifest)
            rows = indicators(h4_observations(minutes))
            rolls,sessions,fridays = calendar_events(int(minutes[0,0]),max(epoch(window[1]) for window in protocol["periods"].values()))
            missing,gaps = gap_quality(minutes,sessions)
            quality.update(gaps)
            quality.update(h4_bars=len(rows),partial_h4_bars=sum(row["n"]<240 for row in rows),
                           stale_close_h4_bars=sum(row["last_ts"]+60 != row["ts"]+STEP for row in rows),
                           eval_bars={name:sum(epoch(window[0])<=row["ts"]<epoch(window[1]) for row in rows) for name,window in protocol["periods"].items()})
            report["source_verification"] = {"archives":len(PINS),"retained_minutes":len(minutes),"h4_buckets":len(rows),
                "raw_rows":quality["raw_rows_all_archives"],"identical_duplicate_rows_removed":quality["exact_duplicate_rows_removed"],
                "all_pinned_hashes_CRCs_and_manifest_members_passed":True,"manifest_sha256":manifest_sha}
            report["source_quality"] = {key:value for key,value in gaps.items() if key != "gaps"}
            bar_fields = {"ts","open","high","low","close","n","first_ts","last_ts","source_open_int",
                          "source_high_int","source_low_int","source_close_int","ema13","bulls","bears","atr14",
                          "raw_long","raw_short","ema_slope","setup_conflict","setup_direction"}
            for bar in evidence["bars"]:
                require(bar_fields <= set(bar),"Missing required published H4 field")
            comparison.published(rows,evidence["bars"],"bars")
            descriptions = {"normalization","quote_basis","volume_scope","source_sha_scope"}
            actual_quality = {key:value for key,value in evidence["data_quality"].items() if key not in descriptions}
            require(set(quality) <= set(actual_quality),"Missing required data-quality field")
            comparison.published(quality,actual_quality,"data_quality")
            rebuilt = {}
            require(set(evidence["runs"]) == set(protocol["runs"]),"Published account set differs from frozen eight runs")
            for name in protocol["runs"]:
                variant,period = name.rsplit("_",1)
                run = replay(rows,minutes,protocol,variant,period,rolls,sessions,fridays,missing)
                rebuilt[name] = run
                published = evidence["runs"][name]
                require(set(run) <= set(published),"Missing required account field: "+name)
                private_metrics = {"median_r","sum_r","drawdown_r","rollover_units","notional_capped","mean_holding",
                                   "median_holding","slope_rejected_entries","invalid_quantity_entries"}
                require(set(run["metrics"])-private_metrics <= set(published["metrics"]),"Missing required metric: "+name)
                private_trade = {"signal_ema13_prev","signal_bulls_prev","signal_bears_prev","signal_raw_long","signal_raw_short","signal_conflict"}
                for expected_trade,actual_trade in zip(run["trades"],published["trades"]):
                    require(set(expected_trade)-private_trade <= set(actual_trade),"Missing required trade field: "+name)
                for point in published["equity"]:
                    require({"ts","bar_ts","equity","drawdown_pct","cash","occupied"} <= set(point),"Missing required equity field")
                for point in published["annual"]:
                    require({"year","return_pct","start_equity","end_equity"} <= set(point),"Missing required annual field")
                comparison.published(run,published,"runs."+name)
            report["replayed_accounts"] = {name:{"trades":len(run["trades"]),"close_marks":len(run["equity"]),
                "end_cash_USD":str(run["metrics"]["end_cash"]),"cash_identity_error_USD":str(abs(run["metrics"]["end_cash"]-
                decimal(protocol["account"]["initial_cash"])-sum((trade["pnl"] for trade in run["trades"]),ZERO)))} for name,run in rebuilt.items()}
            initial = decimal(protocol["account"]["initial_cash"])
            comparison.published({"initial_cash":initial,"end_cash":initial,"return_pct":ZERO,"drawdown_pct":ZERO},evidence["cash_reference"],"cash_reference")
            exclusions = {}
            for name,run in rebuilt.items():
                retained = [trade for trade in run["trades"] if not trade["crosses_gap"]]
                exclusions[name] = {"original_trades":len(run["trades"]),"excluded_gap_trades":len(run["trades"])-len(retained),
                                    "retained_trades":len(retained),"retained_ledger_pnl":sum((trade["pnl"] for trade in retained),ZERO)}
            comparison.published(exclusions,evidence["gap_exclusion"],"gap_exclusion")
            early,later = rebuilt["primary_early"]["trades"],rebuilt["primary_later"]["trades"]
            chosen = {"early":early[0] if early else None,"later":later[0] if later else None}
            chosen["extra"] = next((trade for trade in later[1:] if trade["pnl"]*later[0]["pnl"] < 0),later[1] if len(later)>1 else None) if later else None
            by_anchor = {row["ts"]:row for row in rows}
            require(len(evidence["examples"]) == 3,"Gallery must disclose all three requested example slots")
            for index,example in enumerate(evidence["examples"]):
                tag = "extra" if example["tag"] == "opposite" else example["tag"]
                comparison.one(("early","later","extra")[index],tag,"examples."+str(index)+".tag")
                require(tag in chosen,"Unknown example selection tag")
                if chosen[tag] is None:
                    require(example.get("trade") is None,"Unavailable example must be explicit")
                    continue
                comparison.published(chosen[tag],example["trade"],"examples."+str(index)+".trade")
                anchors = [bar["ts"] for bar in example.get("bars",[])]
                require(anchors == sorted(set(anchors)),"Example candles are not unique and chronological")
                require(chosen[tag]["signal_bar_ts"] in anchors and chosen[tag]["exit_bar_ts"] in anchors,"Example omits its signal or exit H4 context")
                for offset,bar in enumerate(example.get("bars",[])):
                    require(bar["ts"] in by_anchor,"Example contains unknown H4 candle")
                    comparison.published(by_anchor[bar["ts"]],bar,"examples."+str(index)+".bars."+str(offset))
            report["additional_checks"] = {"selected_examples":len(evidence["examples"]),"source_manifest_pins":len(PINS),
                "annual_paths":"independently compared","all_published_numeric_discrete_trade_metric_bar_equity_fields":"independently reconstructed and compared",
                "cash_reference_and_gap_exclusion":"compared","comparison_field_names":sorted(comparison.fields)}
        report["status"] = "passed" if comparison.failures == 0 else "failed"
    except Exception as error:
        report["fatal_error"] = type(error).__name__+": "+str(error)
    report["comparison"] = {"numeric_values_compared":comparison.numeric,"exact_values_compared":comparison.exact,
        "failures":comparison.failures,"failure_samples":comparison.samples,
        "maximum_absolute_errors":{key:str(value) for key,value in comparison.max_errors.items()},"maximum_error_locations":comparison.max_locations}
    report["checked_at_utc"] = dt.datetime.now(UTC).isoformat()
    args.report.parent.mkdir(exist_ok=True,parents=True)
    args.report.write_text(json.dumps(report,indent=2,ensure_ascii=False)+"\n")
    print(json.dumps({"status":report["status"],"report":str(args.report),"comparison_failures":comparison.failures,
                      "fatal_error":report.get("fatal_error"),"synthetic_tests":len(report.get("synthetic_tests",[]))}))
    return 0 if report["status"] == "passed" else 1


if __name__ == "__main__":
    sys.exit(main())
