{
  "schema_version": "1.0.0",
  "bot_id": "2.2",
  "bot_name": "AntiToxicFill",
  "slug": "antitoxicfill",
  "layer": "Execution",
  "layer_key": "exec",
  "bot_class": "Execution Utility",
  "authority": [
    "Reshape"
  ],
  "status": "beta",
  "readiness": "Limited live",
  "flagship": false,
  "is_reference": false,
  "public_export": false,
  "identity": {
    "layer": "Execution",
    "bot_class": "Execution Utility",
    "authority": "Reshape",
    "runs_before": "Order signing and CLOB V2 submission",
    "runs_after": "SmartRouter (ExecutionPlan assembled) and ObservationReport ingestion",
    "applies_to": "Every pending ExecutionPlan where toxic-flow signals or adverse RiskVotes are present on the target market",
    "default_mode": "limited_live",
    "user_visible": "Advanced details only",
    "developer_owner": "Polytraders core \u2014 Execution pod"
  },
  "purpose": "AntiToxicFill detects toxic order-flow patterns on the target market immediately before order submission and reshapes or cancels the ExecutionPlan to avoid being adversely selected. It monitors three primary toxicity signals: one-sided sweeps through more than three book levels in the last 5 seconds, a cancel-storm on the opposite side, and realised post-fill drift over a rolling window. If an adverse news event is detected within \u00b130 seconds of a planned fill, the bot enters a cooldown. Depending on signal severity, AntiToxicFill either widens the limit price by requote_widen_bps, reduces the order size by downsize_factor, or cancels the order outright. It cannot alter the trade direction, market, or outcome leg.",
  "why_it_matters": [
    {
      "failure": "Toxic sweep not detected before submission",
      "consequence": "The system fills against an informed counterparty that has just swept the book on privileged news, resulting in immediate adverse mark-to-market on the filled position."
    },
    {
      "failure": "Cancel-storm ignored on opposite side",
      "consequence": "Mass cancellations on the opposite side of the book signal that the market is repricing. Submitting a resting order into this environment leads to a fill at a price that is immediately stale."
    },
    {
      "failure": "Post-fill drift not tracked across rolling window",
      "consequence": "Systematic adverse drift after fills indicates chronic toxic flow on the market. Without reshaping, the strategy will continue to be adversely selected until cumulative losses exceed risk limits."
    },
    {
      "failure": "News-window cooldown not applied",
      "consequence": "News events arriving within \u00b130 seconds of a fill represent the highest toxicity risk. Filling in this window without a cooldown leads to significant slippage on information-driven price moves."
    }
  ],
  "polymarket_inputs": [
    {
      "input": "CLOB V2 order book \u2014 top 10 levels both sides",
      "source": "clob_public",
      "required": true,
      "use": "Detect one-sided sweeps (>3 levels consumed in 5s) and cancel-storms on the opposite side."
    },
    {
      "input": "Recent trade tape (last 100 fills on market)",
      "source": "ws_market",
      "required": true,
      "use": "Compute realised post-fill drift over the rolling drift_window_s."
    },
    {
      "input": "Market metadata (tick size, neg-risk flag)",
      "source": "clob_public",
      "required": true,
      "use": "Tick-align the widened requote price after applying requote_widen_bps."
    }
  ],
  "internal_inputs": [
    {
      "input": "ObservationReport \u2014 toxic-flow signals",
      "source": "internal bus (polytraders.reports.execution)",
      "required": true,
      "use": "Receive structured toxic-flow observations: sweep_detected, cancel_storm_detected, drift_bps, news_event_at_ms."
    },
    {
      "input": "RiskVote \u2014 adverse risk signal from guardrail pipeline",
      "source": "risk guardrail pipeline",
      "required": true,
      "use": "If any RiskVote carries RESHAPE with a toxicity reason, apply downsize_factor to the order size."
    },
    {
      "input": "KillSwitch active flag",
      "source": "KillSwitch",
      "required": true,
      "use": "Abort order and emit no ExecutionReport if KillSwitch is active."
    },
    {
      "input": "NewsIngest adverse-event feed",
      "source": "internal NewsIngest service",
      "required": false,
      "use": "Detect news events within \u00b1news_window_s of the planned fill; enter cooldown_s pause if hit."
    }
  ],
  "raw_params": [
    "cooldown_s \u00b7 int",
    "requote_widen_bps \u00b7 int",
    "downsize_factor \u00b7 0\u20131",
    "news_window_s \u00b7 int"
  ],
  "parameters": [
    {
      "name": "cooldown_s",
      "default": 30,
      "warning": 60,
      "hard": 120,
      "controls": "Number of seconds to pause order submission after a toxic-flow event or news hit is detected. During cooldown, all ExecutionPlans for the affected market are held; no orders are submitted.",
      "why_default_matters": "A 30-second cooldown is long enough to let informed order flow resolve and the book to reprice, while short enough to avoid excessive missed opportunity cost on liquid markets.",
      "threshold_logic": [
        {
          "condition": "No toxic signal detected",
          "action": "No cooldown \u2014 proceed to submission"
        },
        {
          "condition": "Single signal (sweep OR cancel-storm OR drift) detected",
          "action": "Enter cooldown_s pause (default 30s)"
        },
        {
          "condition": "Multiple signals or news hit detected",
          "action": "Extend to warning threshold (60s)"
        },
        {
          "condition": "cooldown_s > 120 (hard)",
          "action": "Reject config change \u2014 PARAMETER_CHANGE_REQUIRES_APPROVAL"
        }
      ],
      "dev_check": "if cooldown_s > params.hard: raise ConfigError('PARAMETER_CHANGE_REQUIRES_APPROVAL')",
      "user_facing": "Trading on this market was briefly paused because unusual activity was detected that could affect your fill price."
    },
    {
      "name": "requote_widen_bps",
      "default": 20,
      "warning": 40,
      "hard": 100,
      "controls": "Number of basis points to widen the limit price on a RESHAPE action. For a BUY order the price is lowered by requote_widen_bps; for a SELL order the price is raised, creating a more protective limit.",
      "why_default_matters": "A 20 bps widen provides protection against short-lived adverse flow while still leaving the order competitive. More than 40 bps risks missing the trade entirely.",
      "threshold_logic": [
        {
          "condition": "No sweep, cancel-storm, or drift detected",
          "action": "No widen \u2014 original price used"
        },
        {
          "condition": "Mild signal: drift_bps < 30 or single cancel-storm",
          "action": "Widen by requote_widen_bps (default 20 bps)"
        },
        {
          "condition": "Strong signal: drift_bps >= 30 or sweep detected",
          "action": "Widen by warning threshold (40 bps)"
        },
        {
          "condition": "requote_widen_bps > 100 (hard)",
          "action": "Reject config \u2014 PARAMETER_CHANGE_REQUIRES_APPROVAL"
        }
      ],
      "dev_check": "widenedPrice = BUY ? price * (1 - requote_widen_bps/10000) : price * (1 + requote_widen_bps/10000)",
      "user_facing": "Your order price was adjusted slightly to protect against unfavourable market conditions detected just before submission."
    },
    {
      "name": "downsize_factor",
      "default": 0.5,
      "warning": 0.25,
      "hard": 0.1,
      "controls": "Multiplier (0 to 1) applied to the order size when a RESHAPE is triggered by a RiskVote or strong toxic signal. A factor of 0.5 halves the order; 0.1 reduces it to 10% of original.",
      "why_default_matters": "Halving the order on a toxic signal reduces adverse-selection exposure while still allowing partial participation. Factors below 0.25 leave very small residual orders that incur proportionally higher fees.",
      "threshold_logic": [
        {
          "condition": "No adverse RiskVote and no strong signal",
          "action": "No resize \u2014 original size used"
        },
        {
          "condition": "Adverse RiskVote RESHAPE or strong single signal",
          "action": "Apply downsize_factor (default 0.5)"
        },
        {
          "condition": "Multiple signals or news hit",
          "action": "Apply warning-level factor (0.25)"
        },
        {
          "condition": "downsize_factor < 0.1 (hard floor)",
          "action": "Clamp to 0.1 \u2014 ANTITOXICFILL_SIZE_FLOOR_APPLIED"
        }
      ],
      "dev_check": "finalSize = max(originalSize * downsize_factor, originalSize * 0.1)",
      "user_facing": "The size of your order was reduced because market conditions suggested a lower-risk position size was appropriate."
    },
    {
      "name": "news_window_s",
      "default": 30,
      "warning": 45,
      "hard": 60,
      "controls": "Symmetric window in seconds around the planned fill time within which an adverse news event triggers a cooldown. Events within [fill_time - news_window_s, fill_time + news_window_s] are treated as contemporaneous with the fill.",
      "why_default_matters": "A \u00b130-second window covers the typical latency between a news event and its full impact on the Polymarket CLOB order book, without being so wide that routine pre-trade news suppresses all activity.",
      "threshold_logic": [
        {
          "condition": "No news event within \u00b1news_window_s",
          "action": "No cooldown triggered by news"
        },
        {
          "condition": "News event within \u00b1news_window_s",
          "action": "Enter cooldown_s pause \u2014 ANTITOXICFILL_NEWS_COOLDOWN"
        },
        {
          "condition": "news_window_s > 60 (hard)",
          "action": "Reject config \u2014 PARAMETER_CHANGE_REQUIRES_APPROVAL"
        }
      ],
      "dev_check": "newsHit = any(abs(event.ts_ms - fill_planned_ms) <= news_window_s * 1000 for event in news_feed)",
      "user_facing": "A news event was detected close to your planned trade time, so the trade was briefly paused for safety."
    }
  ],
  "default_config": {
    "bot_id": "exec.antitoxicfill",
    "version": "2.0.0",
    "mode": "limited_live",
    "defaults": {
      "cooldown_s": 30,
      "requote_widen_bps": 20,
      "downsize_factor": 0.5,
      "news_window_s": 30
    },
    "locked": {
      "cooldown_s": {
        "max": 120
      },
      "requote_widen_bps": {
        "max": 100
      },
      "news_window_s": {
        "max": 60
      }
    }
  },
  "implementation_flow": [
    "Receive ExecutionPlan from SmartRouter; load associated ObservationReport and RiskVote from the internal bus.",
    "Check KillSwitch active flag; if active, discard the ExecutionPlan and emit no ExecutionReport.",
    "Check whether the market is in cooldown (cooldown state keyed by market_id in Redis); if in cooldown, hold the plan and re-evaluate after cooldown expires.",
    "Fetch CLOB V2 top-10 book snapshot from clob_public; subscribe to ws_market trade tape for the target market.",
    "Evaluate sweep signal: count book levels consumed on one side in the last 5 seconds using the ws_market trade tape. If > 3 levels consumed, set sweep_detected = true.",
    "Evaluate cancel-storm signal: count cancel events on the opposite side in the last 5 seconds from the ws_market feed. If cancel_count_5s > cancel_storm_threshold (default 10), set cancel_storm_detected = true.",
    "Evaluate post-fill drift: compute mean realised drift in bps over the last drift_window_s seconds using the recent fill tape. If drift_bps > drift_threshold_bps, set drift_detected = true.",
    "Check NewsIngest feed: if any adverse event timestamp falls within \u00b1news_window_s of the planned fill, set news_hit = true.",
    "Determine action: if news_hit or (sweep_detected AND cancel_storm_detected): enter cooldown, cancel order, emit ANTITOXICFILL_NEWS_COOLDOWN or ANTITOXICFILL_SWEEP_CANCEL_STORM. If single signal or adverse RiskVote: apply downsize_factor and requote_widen_bps, emit RESHAPE. If no signals: approve and pass ExecutionPlan through unchanged.",
    "On RESHAPE: compute widenedPrice (tick-aligned, using buildOrderTypedData metadata), apply downsize_factor to size, construct updated ExecutionPlan, forward to signing.",
    "Emit ExecutionReport to polytraders.reports.execution (partition by trace_id, WAL-then-retry, retention 7y) with verdict, reason_code, original and reshaped parameters, and all signal flags."
  ],
  "decision_logic": {
    "approve": "No toxic signals detected, no adverse RiskVote, no news hit, and market is not in cooldown. ExecutionPlan passes through unmodified. Emit ANTITOXICFILL_PASS.",
    "reshape_required": "One or more toxic signals (sweep, cancel-storm, or drift) detected, or an adverse RiskVote with toxicity reason received. Apply downsize_factor to size and widen price by requote_widen_bps. Emit ANTITOXICFILL_RESHAPE.",
    "reject": "News event detected within \u00b1news_window_s, or simultaneous sweep and cancel-storm signals, or KillSwitch active. Enter cooldown_s pause on the market, cancel the ExecutionPlan, emit no order. Emit ANTITOXICFILL_NEWS_COOLDOWN or ANTITOXICFILL_SWEEP_CANCEL_STORM.",
    "warning_only": "Post-fill drift is in the warning band (above warning threshold but below action threshold). WARN annotation attached to the ExecutionReport; plan proceeds unchanged."
  },
  "decision_output_schema": "ExecutionReport",
  "decision_output_example": {
    "report_id": "rep_a1b2c3d4e5f6a7b8",
    "trace_id": "trc_9f8e7d6c5b4a3f2e",
    "bot_id": "exec.antitoxicfill",
    "market_id": "0x3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e",
    "side": "BUY",
    "outcome": "YES",
    "verdict": "RESHAPE",
    "reason_code": "ANTITOXICFILL_RESHAPE",
    "original_price": 0.62,
    "reshaped_price": 0.608,
    "original_size_usd": 400,
    "reshaped_size_usd": 200,
    "widen_bps_applied": 20,
    "downsize_factor_applied": 0.5,
    "signals": {
      "sweep_detected": true,
      "cancel_storm_detected": false,
      "drift_detected": false,
      "news_hit": false,
      "drift_bps": 8
    },
    "collateral": "pUSD",
    "eip712_domain_version": "2",
    "evaluated_at_ms": 1746769800000
  },
  "developer_log": {
    "report_id": "rep_a1b2c3d4e5f6a7b8",
    "trace_id": "trc_9f8e7d6c5b4a3f2e",
    "bot_id": "exec.antitoxicfill",
    "market_id": "0x3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e",
    "sweep_levels_consumed": 4,
    "sweep_detected": true,
    "cancel_storm_count_5s": 3,
    "cancel_storm_detected": false,
    "drift_bps": 8,
    "drift_detected": false,
    "news_hit": false,
    "adverse_risk_vote": false,
    "cooldown_active": false,
    "verdict": "RESHAPE",
    "reason_code": "ANTITOXICFILL_RESHAPE",
    "original_price": 0.62,
    "reshaped_price": 0.608,
    "original_size_usd": 400,
    "reshaped_size_usd": 200,
    "requote_widen_bps": 20,
    "downsize_factor": 0.5,
    "tick_size": 0.01,
    "tick_aligned_reshaped_price": 0.61,
    "evaluated_at_ms": 1746769800000
  },
  "user_explanations": [
    {
      "situation": "Order price widened before submission",
      "message": "Unusual activity was detected on this market just before your order was submitted. The price was adjusted slightly to protect you from filling at a disadvantageous price."
    },
    {
      "situation": "Order size reduced before submission",
      "message": "Market conditions suggested an elevated risk of adverse fills. The order size was reduced to limit potential losses."
    },
    {
      "situation": "Order paused \u2014 news event nearby",
      "message": "A news event was detected close to the time of your planned trade. Trading was briefly paused to let the market adjust before your order was considered again."
    },
    {
      "situation": "Order cancelled \u2014 toxic flow detected",
      "message": "Significant one-sided activity and widespread order cancellations were detected simultaneously. The order was cancelled to protect you from being adversely selected."
    }
  ],
  "failure_modes": {
    "main_failure_mode": "Failing to detect a sweep because the ws_market feed is lagged or the CLOB book snapshot is stale, allowing a toxic order to be submitted without price widening or size reduction.",
    "false_positive_risk": "Triggering a cooldown on a momentary one-sided sweep that immediately reverses (e.g. large benign taker), causing missed opportunity cost. Over-sensitive cancel-storm detection may also fire on normal book refresh activity.",
    "false_negative_risk": "Missing a toxic news event because the NewsIngest feed has a latency spike, or because news_window_s is configured too tightly, leading to a fill against an informed counterparty.",
    "safe_fallback": "If ws_market feed or clob_public book snapshot is unavailable, apply conservative defaults: downsize_factor=0.5 and requote_widen_bps=40. If NewsIngest is unavailable, proceed without news check but log ANTITOXICFILL_NEWS_FEED_UNAVAILABLE. If KillSwitch status cannot be read, halt submission.",
    "required_dependencies": [
      "ws_market trade tape for target market",
      "clob_public top-10 book snapshot",
      "ObservationReport from internal bus",
      "RiskVote from guardrail pipeline",
      "KillSwitch active flag",
      "NewsIngest adverse-event feed (optional \u2014 graceful degradation if absent)"
    ]
  },
  "acceptance_tests": {
    "unit": [
      {
        "test": "PASS when no signals detected",
        "setup": "sweep_detected=false, cancel_storm_detected=false, drift_bps=5, news_hit=false, killswitch=false",
        "expected": "ExecutionReport.verdict=PASS, no price or size change"
      },
      {
        "test": "RESHAPE when sweep detected: price widened and size halved",
        "setup": "sweep_levels=4, sweep_detected=true, cancel_storm_detected=false, original_price=0.62, original_size_usd=400, requote_widen_bps=20, downsize_factor=0.5",
        "expected": "reshaped_price=0.608 (tick-aligned to 0.61), reshaped_size_usd=200, reason_code=ANTITOXICFILL_RESHAPE"
      },
      {
        "test": "CANCEL and cooldown when sweep + cancel-storm both detected",
        "setup": "sweep_detected=true, cancel_storm_detected=true, news_hit=false",
        "expected": "No order submitted; cooldown_s=30 applied on market_id; reason_code=ANTITOXICFILL_SWEEP_CANCEL_STORM"
      },
      {
        "test": "CANCEL and cooldown on news hit within news_window_s",
        "setup": "news_event_ts_ms = fill_planned_ms - 20000, news_window_s=30",
        "expected": "news_hit=true; order cancelled; cooldown applied; reason_code=ANTITOXICFILL_NEWS_COOLDOWN"
      },
      {
        "test": "HARD_REJECT when KillSwitch active",
        "setup": "killswitch.active=true",
        "expected": "No ExecutionReport emitted; reason_code=KILL_SWITCH_ACTIVE"
      },
      {
        "test": "RESHAPE on adverse RiskVote with toxicity reason",
        "setup": "risk_vote.verdict=RESHAPE, risk_vote.reason=ANTITOXICFILL_ADVERSE_FLOW, downsize_factor=0.5",
        "expected": "reshaped_size_usd = original_size_usd * 0.5; reason_code=ANTITOXICFILL_RESHAPE"
      }
    ],
    "integration": [
      {
        "test": "End-to-end: ObservationReport sweep signal \u2192 RESHAPE \u2192 reshaped ExecutionPlan forwarded to signing",
        "expected": "Reshaped order has tick-aligned widened price and halved size; ExecutionReport emitted to polytraders.reports.execution"
      },
      {
        "test": "News hit: NewsIngest event \u2192 cooldown applied \u2192 order held \u2192 re-evaluated after cooldown_s expires",
        "expected": "Order not submitted during cooldown; after cooldown expires and no further signals, order proceeds as PASS"
      },
      {
        "test": "Cooldown state survives bot restart (Redis TTL)",
        "expected": "After restart, market cooldown entry read from Redis; order still held until TTL expires"
      }
    ],
    "property": [
      {
        "property": "AntiToxicFill never alters the trade side, market_id, or outcome leg",
        "required": "Always true \u2014 only price, size, and submission timing are modified"
      },
      {
        "property": "Reshaped size is always >= original_size_usd * downsize_factor_hard_floor (0.1)",
        "required": "Always true \u2014 downsize_factor is clamped to 0.1 minimum"
      },
      {
        "property": "No order is submitted to CLOB V2 while a market is in cooldown",
        "required": "Always true \u2014 cooldown state checked before every ExecutionPlan evaluation"
      }
    ]
  },
  "checklist_overrides": {},
  "legacy_goal": "Avoid being run over right before bad news.",
  "legacy_pm_signals": [
    "One-sided sweeps through > 3 levels in last 5s",
    "Cancel-storm on the opposite side",
    "Realised post-fill drift over a rolling window"
  ],
  "legacy_external_feeds": [
    "NewsIngest adverse-event hits within \u00b130s of a fill"
  ],
  "reporting_groups": [
    "execution"
  ],
  "network": [
    "polygon"
  ],
  "api_surface": [
    "clob_public",
    "ws_market",
    "internal"
  ],
  "version": {
    "spec": "2.0.0",
    "implementation": "2.0.0",
    "schema": "2",
    "released": "2026-04-28"
  },
  "migration_history": [
    {
      "date": "2026-04-28",
      "from": "v1",
      "to": "v2",
      "reason": "CLOB V2 cutover",
      "action_taken": "Switched to py-clob-client-v2. Collateral denomination updated from USDC.e to pUSD in all ExecutionReport fields. Removed feeRateBps references from order-reshape logic (fees are now operator-set at match time by CTFExchangeV2). EIP-712 Exchange domain version updated from '1' to '2'. ObservationReport and RiskVote bus topics updated to V2 schema. Cooldown state store key updated to include bot_version=v2 prefix to avoid stale V1 entries."
    }
  ],
  "polymarket_v2_compat": {
    "clob_version": "v2",
    "collateral": "pUSD",
    "eip712_domain_version": "2",
    "builder_code_aware": false,
    "negrisk_aware": false,
    "multichain_ready": false,
    "sdk_used": "py-clob-client-v2",
    "settlement_contract": "CTFExchangeV2",
    "notes": "AntiToxicFill reshapes ExecutionPlans before order signing; it does not sign orders itself. All size and price amounts are denominated in pUSD. The widened price is tick-aligned using the V2 market metadata fetched from clob_public."
  },
  "reference_implementation": {
    "summary": "On each ExecutionPlan received from SmartRouter, AntiToxicFill evaluates three toxic-flow signals (sweep, cancel-storm, post-fill drift) and a news-event check, then either passes the plan unchanged, reshapes it (widen price, reduce size), or cancels it and enters a market-level cooldown. Emits ExecutionReport to polytraders.reports.execution.",
    "language_note": "Pseudocode is language-agnostic. FETCH = read input. EMIT = produce output. Translate to TS/Python/Go/Rust.",
    "pseudocode": "FUNCTION evaluatePlan(plan, observationReport, riskVotes):\n  // --- 0. KillSwitch gate ---\n  ks = FETCH internal.killswitch.status\n  IF ks.active:\n    EMIT ExecutionReport(plan, HARD_REJECT, KILL_SWITCH_ACTIVE)\n    RETURN\n\n  // --- 1. Cooldown check ---\n  cooldownKey = 'cooldown:' + plan.market_id\n  IF FETCH redis.GET(cooldownKey) IS NOT NULL:\n    EMIT ExecutionReport(plan, HOLD, ANTITOXICFILL_COOLDOWN_ACTIVE)\n    RETURN  // Re-evaluate after TTL\n\n  // --- 2. Fetch market book + trade tape ---\n  book = FETCH clob_public.GET('/book?market=' + plan.market_id + '&depth=10')\n  tape = FETCH ws_market.recent_fills(plan.market_id, last_n=100)\n  IF book IS NULL OR tape IS NULL:\n    // Safe fallback: apply conservative defaults\n    widenBps = params.requote_widen_bps * 2  // 40 bps default fallback\n    finalSize = plan.size_usd * params.downsize_factor\n    EMIT ExecutionReport(plan, RESHAPE, ANTITOXICFILL_FEED_UNAVAILABLE,\n                         reshaped_price=widenPrice(plan, widenBps),\n                         reshaped_size=finalSize)\n    RETURN\n\n  // --- 3. Evaluate sweep signal ---\n  // Count levels consumed on plan.side in last 5 seconds\n  recentTrades = [t FOR t IN tape IF now_ms() - t.ts_ms <= 5000\n                  AND t.aggressor_side == plan.side]\n  levelsConsumed = COUNT DISTINCT price levels in recentTrades\n  sweepDetected = (levelsConsumed > 3)\n\n  // --- 4. Evaluate cancel-storm signal ---\n  // Count cancels on opposite side in last 5 seconds\n  oppSide = 'SELL' IF plan.side == 'BUY' ELSE 'BUY'\n  recentCancels = FETCH ws_market.recent_cancels(plan.market_id, side=oppSide, window_ms=5000)\n  cancelStormDetected = (COUNT(recentCancels) > 10)\n\n  // --- 5. Evaluate post-fill drift ---\n  driftBps = computeRollingDrift(tape, window_s=params.drift_window_s)  // mean bps drift post-fill\n  driftDetected = (driftBps > params.drift_threshold_bps)  // default: 30 bps\n\n  // --- 6. Check news feed ---\n  newsEvents = FETCH internal.newsingest.recent(plan.market_id)\n  newsHit = ANY(abs(e.ts_ms - plan.planned_fill_ms) <= params.news_window_s * 1000\n                FOR e IN newsEvents)\n\n  // --- 7. Check adverse RiskVote ---\n  adverseVote = ANY(v.verdict == 'RESHAPE' AND 'toxicity' IN v.tags FOR v IN riskVotes)\n\n  // --- 8. Determine action ---\n  IF newsHit OR (sweepDetected AND cancelStormDetected):\n    // Hard cancel + cooldown\n    reason = ANTITOXICFILL_NEWS_COOLDOWN IF newsHit ELSE ANTITOXICFILL_SWEEP_CANCEL_STORM\n    redis.SET(cooldownKey, 1, EX=params.cooldown_s)\n    EMIT ExecutionReport(plan, HARD_REJECT, reason)\n    RETURN\n\n  IF sweepDetected OR cancelStormDetected OR driftDetected OR adverseVote:\n    // Reshape: widen price + downsize\n    signalStrength = COUNT([sweepDetected, cancelStormDetected, driftDetected, adverseVote])\n    widenBps = params.requote_widen_bps IF signalStrength == 1 ELSE params.requote_widen_bps_warning\n    newPrice = widenPrice(plan, widenBps)          // BUY: lower; SELL: raise\n    newPrice = tickAlign(newPrice, book.tick_size)  // snap to valid tick\n    newSize = max(plan.size_usd * params.downsize_factor,\n                  plan.size_usd * 0.1)             // clamp to hard floor\n    reshapedPlan = plan WITH price=newPrice, size_usd=newSize\n    EMIT ExecutionReport(reshapedPlan, RESHAPE, ANTITOXICFILL_RESHAPE,\n                         widen_bps_applied=widenBps,\n                         downsize_factor_applied=params.downsize_factor)\n    FORWARD reshapedPlan TO signing\n    RETURN\n\n  // --- 9. Pass through ---\n  EMIT ExecutionReport(plan, PASS, ANTITOXICFILL_PASS)\n  FORWARD plan TO signing",
    "helpers": [
      {
        "name": "widenPrice",
        "signature": "widenPrice(plan: ExecutionPlan, widenBps: int) -> float",
        "purpose": "Returns a more protective limit price: BUY orders get a lower price (plan.price * (1 - widenBps/10000)); SELL orders get a higher price."
      },
      {
        "name": "tickAlign",
        "signature": "tickAlign(price: float, tickSize: float) -> float",
        "purpose": "Rounds price to the nearest valid tick using floor for BUY and ceil for SELL to maintain the protective direction."
      },
      {
        "name": "computeRollingDrift",
        "signature": "computeRollingDrift(tape: List[Fill], window_s: int) -> float",
        "purpose": "Computes mean realised post-fill drift in basis points over a rolling window from the trade tape."
      },
      {
        "name": "fetchClobPublic",
        "signature": "fetchClobPublic(path: str) -> JSON",
        "purpose": "Unauthenticated GET against https://clob.polymarket.com; returns parsed JSON or null on error."
      }
    ],
    "sdk_calls": [
      "clob_public.GET('/book?market=' + plan.market_id + '&depth=10')",
      "ws_market.subscribe('last_trade_price', plan.market_id)",
      "ws_market.subscribe('book', plan.market_id)",
      "redis.GET('cooldown:' + plan.market_id)",
      "redis.SET('cooldown:' + plan.market_id, 1, EX=cooldown_s)"
    ],
    "complexity": "O(1) per ExecutionPlan evaluation; O(F) for rolling drift scan where F = recent fill count (capped at 100)"
  },
  "wire_examples": {
    "input": [
      {
        "label": "ExecutionPlan + ObservationReport with sweep signal",
        "source": "exec.smart_router + internal bus",
        "payload": {
          "intent_id": "int_3c4d5e6f7a8b9c0d",
          "trace_id": "trc_9f8e7d6c5b4a3f2e",
          "market_id": "0x3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e",
          "side": "BUY",
          "outcome": "YES",
          "price": 0.62,
          "size_usd": 400,
          "order_type": "GTC",
          "planned_fill_ms": 1746769800000,
          "observation_report": {
            "sweep_detected": true,
            "sweep_levels_consumed": 4,
            "cancel_storm_detected": false,
            "cancel_count_5s": 3,
            "drift_bps": 8,
            "news_hit": false
          },
          "risk_votes": [
            {
              "bot_id": "risk.portfolio_guard",
              "verdict": "PASS"
            }
          ]
        }
      }
    ],
    "output": [
      {
        "label": "ExecutionReport \u2014 RESHAPE (sweep detected, price widened, size halved)",
        "payload": {
          "report_id": "rep_a1b2c3d4e5f6a7b8",
          "trace_id": "trc_9f8e7d6c5b4a3f2e",
          "bot_id": "exec.antitoxicfill",
          "market_id": "0x3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e",
          "side": "BUY",
          "outcome": "YES",
          "verdict": "RESHAPE",
          "reason_code": "ANTITOXICFILL_RESHAPE",
          "original_price": 0.62,
          "reshaped_price": 0.61,
          "original_size_usd": 400,
          "reshaped_size_usd": 200,
          "widen_bps_applied": 20,
          "downsize_factor_applied": 0.5,
          "collateral": "pUSD",
          "eip712_domain_version": "2",
          "signals": {
            "sweep_detected": true,
            "cancel_storm_detected": false,
            "drift_detected": false,
            "news_hit": false,
            "drift_bps": 8
          },
          "evaluated_at_ms": 1746769800000
        }
      },
      {
        "label": "ExecutionReport \u2014 HARD_REJECT (news hit + cooldown applied)",
        "payload": {
          "report_id": "rep_b2c3d4e5f6a7b8c9",
          "trace_id": "trc_1a2b3c4d5e6f7a8b",
          "bot_id": "exec.antitoxicfill",
          "market_id": "0x3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e",
          "side": "SELL",
          "outcome": "NO",
          "verdict": "HARD_REJECT",
          "reason_code": "ANTITOXICFILL_NEWS_COOLDOWN",
          "original_price": 0.41,
          "reshaped_price": null,
          "original_size_usd": 300,
          "reshaped_size_usd": null,
          "collateral": "pUSD",
          "cooldown_s_applied": 30,
          "signals": {
            "sweep_detected": false,
            "cancel_storm_detected": false,
            "drift_detected": false,
            "news_hit": true,
            "news_event_delta_ms": -18000
          },
          "evaluated_at_ms": 1746769850000
        }
      }
    ]
  },
  "reason_codes": [
    {
      "code": "ANTITOXICFILL_PASS",
      "severity": "INFO",
      "meaning": "No toxic-flow signals detected; ExecutionPlan passes through unchanged.",
      "action": "Forward ExecutionPlan to signing without modification.",
      "user_message": ""
    },
    {
      "code": "ANTITOXICFILL_RESHAPE",
      "severity": "RESHAPE",
      "meaning": "One or more toxic-flow signals (sweep, cancel-storm, or drift) or an adverse RiskVote detected. Price widened by requote_widen_bps and size reduced by downsize_factor.",
      "action": "Apply widen and downsize to ExecutionPlan; forward reshaped plan to signing.",
      "user_message": "Your order was adjusted to protect against unusual market activity detected before submission."
    },
    {
      "code": "ANTITOXICFILL_NEWS_COOLDOWN",
      "severity": "HARD_REJECT",
      "meaning": "An adverse news event was detected within \u00b1news_window_s of the planned fill. Order cancelled; market enters cooldown.",
      "action": "Cancel ExecutionPlan; apply cooldown_s to market_id in Redis; emit no order.",
      "user_message": "Trading on this market was briefly paused because a news event was detected near your planned trade time."
    },
    {
      "code": "ANTITOXICFILL_SWEEP_CANCEL_STORM",
      "severity": "HARD_REJECT",
      "meaning": "Simultaneous one-sided sweep (>3 levels) and cancel-storm on the opposite side detected. Highest toxicity combination; order cancelled and market enters cooldown.",
      "action": "Cancel ExecutionPlan; apply cooldown_s to market_id; emit no order.",
      "user_message": "Significant one-sided activity was detected on this market. Your order was cancelled to avoid adverse fills."
    },
    {
      "code": "ANTITOXICFILL_COOLDOWN_ACTIVE",
      "severity": "EXPLAIN",
      "meaning": "This market is currently in a toxicity cooldown from a prior event. New ExecutionPlans are held until the cooldown expires.",
      "action": "Hold ExecutionPlan; re-evaluate after cooldown TTL expires.",
      "user_message": "Your order is waiting for unusual market activity to settle before it is submitted."
    },
    {
      "code": "ANTITOXICFILL_SIZE_FLOOR_APPLIED",
      "severity": "WARN",
      "meaning": "downsize_factor computation would have produced a size below the hard floor (10% of original). Size clamped to 10% of original.",
      "action": "Set reshaped_size_usd = original_size_usd * 0.1; log warning.",
      "user_message": ""
    },
    {
      "code": "ANTITOXICFILL_FEED_UNAVAILABLE",
      "severity": "WARN",
      "meaning": "ws_market or clob_public feed unavailable; conservative fallback defaults applied (widen 40 bps, downsize 0.5).",
      "action": "Apply fallback reshape parameters; do not block order entirely.",
      "user_message": ""
    },
    {
      "code": "KILL_SWITCH_ACTIVE",
      "severity": "HARD_REJECT",
      "meaning": "Global kill switch is active; no orders may proceed.",
      "action": "Discard ExecutionPlan; emit no order.",
      "user_message": "Trading is currently paused."
    },
    {
      "code": "MARKET_CLOSED",
      "severity": "HARD_REJECT",
      "meaning": "Target market is closed or resolved; ExecutionPlan is invalid.",
      "action": "Discard ExecutionPlan; log and emit no order.",
      "user_message": "The market for this order is no longer active."
    }
  ],
  "metrics": {
    "emitted": [
      {
        "name": "polytraders_exec_antitoxicfill_decisions_total",
        "type": "counter",
        "unit": "count",
        "labels": [
          "verdict",
          "reason_code"
        ],
        "meaning": "Total ExecutionReport records emitted per verdict (PASS/RESHAPE/HARD_REJECT) and reason code."
      },
      {
        "name": "polytraders_exec_antitoxicfill_cooldowns_active",
        "type": "gauge",
        "unit": "count",
        "labels": [],
        "meaning": "Number of markets currently in a toxicity cooldown. Rising count indicates sustained toxic-flow environment."
      },
      {
        "name": "polytraders_exec_antitoxicfill_drift_bps",
        "type": "histogram",
        "unit": "bps",
        "labels": [
          "market_id"
        ],
        "meaning": "Distribution of realised post-fill drift in basis points across evaluated ExecutionPlans."
      },
      {
        "name": "polytraders_exec_antitoxicfill_sweep_levels",
        "type": "histogram",
        "unit": "count",
        "labels": [
          "market_id"
        ],
        "meaning": "Distribution of sweep depth (levels consumed in 5s) at evaluation time; >3 triggers RESHAPE or HARD_REJECT."
      },
      {
        "name": "polytraders_exec_antitoxicfill_eval_latency_ms",
        "type": "histogram",
        "unit": "ms",
        "labels": [],
        "meaning": "Wall-clock latency from ExecutionPlan receipt to ExecutionReport emit."
      },
      {
        "name": "polytraders_exec_antitoxicfill_reshape_widen_bps",
        "type": "histogram",
        "unit": "bps",
        "labels": [],
        "meaning": "Distribution of price-widen bps actually applied on RESHAPE decisions."
      }
    ],
    "alerts": [
      {
        "name": "AntiToxicFillHighRejectRate",
        "condition": "rate(polytraders_exec_antitoxicfill_decisions_total{verdict='HARD_REJECT'}[5m]) / rate(polytraders_exec_antitoxicfill_decisions_total[5m]) > 0.3",
        "severity": "page",
        "runbook": "#runbook-antitoxicfill-high-reject-rate"
      },
      {
        "name": "AntiToxicFillCooldownsSpiking",
        "condition": "polytraders_exec_antitoxicfill_cooldowns_active > 5",
        "severity": "warn",
        "runbook": "#runbook-antitoxicfill-cooldowns-spiking"
      },
      {
        "name": "AntiToxicFillHighDrift",
        "condition": "histogram_quantile(0.95, rate(polytraders_exec_antitoxicfill_drift_bps_bucket[5m])) > 30",
        "severity": "warn",
        "runbook": "#runbook-antitoxicfill-high-drift"
      },
      {
        "name": "AntiToxicFillEvalLatencyHigh",
        "condition": "histogram_quantile(0.99, rate(polytraders_exec_antitoxicfill_eval_latency_ms_bucket[5m])) > 150",
        "severity": "warn",
        "runbook": "#runbook-antitoxicfill-latency"
      }
    ],
    "dashboards": [
      "Grafana \u2014 Execution / AntiToxicFill",
      "Grafana \u2014 Order quality / toxic-flow signals and cooldown history"
    ],
    "log_level": "info"
  },
  "state": {
    "store": "redis",
    "shape": "Market-level cooldown flags keyed by 'cooldown:{market_id}' with TTL = cooldown_s. Rolling drift cache keyed by 'drift:{market_id}' storing last 100 fill timestamps and prices with 5-minute TTL.",
    "ttl": "Cooldown entries: cooldown_s (default 30s). Drift cache entries: 300s.",
    "recovery": "On restart, cooldown entries are re-read from Redis. Any market with an active cooldown key continues in cooldown. Drift cache is rebuilt from ws_market fill replay on reconnect; first evaluation after restart may use conservative fallback if cache is empty.",
    "size_estimate": "~50 bytes per cooldown entry; ~8 KB per market drift cache (100 fills \u00d7 80 bytes each)"
  },
  "concurrency": {
    "execution_model": "single-threaded event loop",
    "max_in_flight": 50,
    "idempotency_key": "trace_id",
    "timeout_ms": 150,
    "backpressure": "Excess ExecutionPlans queued in memory ring buffer (max 50); oldest entry dropped if ring is full and WARN emitted",
    "locking": "Redis SETNX per market_id for cooldown write to prevent double-trigger during burst"
  },
  "dependencies": {
    "depends_on": [
      {
        "bot_id": "exec.smart_router",
        "why": "Provides the ExecutionPlan that AntiToxicFill evaluates and potentially reshapes.",
        "contract": "AntiToxicFill must not alter side, market_id, or outcome leg from the original ExecutionPlan."
      },
      {
        "bot_id": "risk.kill_switch",
        "why": "KillSwitch active flag is checked before any evaluation; active flag aborts all processing.",
        "contract": "No ExecutionReport is emitted while KillSwitch is active."
      },
      {
        "bot_id": "risk.portfolio_guard",
        "why": "Adverse RiskVotes from PortfolioGuard with toxicity tags trigger downsize_factor application.",
        "contract": "If RiskVote verdict is RESHAPE with toxicity reason, AntiToxicFill applies downsize_factor."
      }
    ],
    "emits_to": [
      {
        "bot_id": "gov.fill_quality_analyzer",
        "what": "ExecutionReport with verdict, reshaping details, and signal flags for fill quality analysis.",
        "contract": "ExecutionReport emitted to polytraders.reports.execution, partitioned by trace_id."
      }
    ],
    "sibling": [
      {
        "bot_id": "exec.queue_warden",
        "why": "QueueWarden manages resting order lifecycle post-submission; AntiToxicFill acts pre-submission. Both consume toxic-flow signals but at different lifecycle stages."
      }
    ],
    "external": [
      {
        "service": "Polymarket CLOB V2 (public)",
        "endpoint": "https://clob.polymarket.com",
        "sla": "99.9% / 200ms p99",
        "fallback": "If book snapshot unavailable, apply conservative fallback reshape (40 bps widen, 0.5 downsize)."
      },
      {
        "service": "Polymarket WebSocket \u2014 market feed",
        "endpoint": "wss://ws-subscriptions-clob.polymarket.com/ws/market",
        "sla": "best-effort",
        "fallback": "Falls back to REST recent-trades poll; conservative fallback if REST also unavailable."
      },
      {
        "service": "Internal NewsIngest service",
        "endpoint": "internal://newsingest",
        "sla": "99% / 100ms p99 (internal SLA)",
        "fallback": "Proceed without news check if unavailable; log ANTITOXICFILL_FEED_UNAVAILABLE."
      }
    ]
  },
  "security_surfaces": {
    "signs_orders": false,
    "private_key_access": "none",
    "abuse_vectors": [
      "Injecting a fabricated ObservationReport with sweep_detected=false to suppress reshaping and allow toxic-fill through at full size",
      "Flooding the cooldown Redis key with artificial expiry updates to prevent cooldown from being applied",
      "Replay of stale ObservationReport to trigger a false cooldown on a non-toxic market, causing missed trading opportunities"
    ],
    "mitigations": [
      "ObservationReport messages are HMAC-signed by the emitting bot; AntiToxicFill validates the signature before processing",
      "Redis cooldown keys use SETNX with TTL; they cannot be extended by external writers without Redis ACL access",
      "ObservationReport freshness check: reports older than 10 seconds are discarded with STALE_DATA reason code",
      "ws_market trade tape is fetched directly from Polymarket WebSocket \u2014 not from an internal cache that could be tampered with"
    ],
    "contract_calls": []
  },
  "failure_injection": [
    {
      "scenario": "WS_MARKET_FEED_STALE",
      "how_to_inject": "Disconnect ws_market subscription; leave last_seen > 10s",
      "expected_behaviour": "Bot emits WARN ANTITOXICFILL_FEED_UNAVAILABLE; applies conservative fallback reshape (40 bps widen, 0.5 downsize) on all ExecutionPlans until feed reconnects",
      "recovery": "Feed reconnects; bot reverts to live signal evaluation on next ExecutionPlan"
    },
    {
      "scenario": "NEWS_HIT_COOLDOWN",
      "how_to_inject": "Inject a NewsIngest event with ts_ms = now_ms() - 15000 (15s ago) for the target market; news_window_s=30",
      "expected_behaviour": "news_hit=true; ExecutionPlan cancelled; cooldown_s=30 applied to market in Redis; ANTITOXICFILL_NEWS_COOLDOWN emitted",
      "recovery": "After 30s, cooldown key expires; next ExecutionPlan evaluated without cooldown"
    },
    {
      "scenario": "SWEEP_AND_CANCEL_STORM_SIMULTANEOUS",
      "how_to_inject": "Inject mock ws_market tape with 5 levels consumed in 2s on BUY side + 15 cancel events on SELL side in 5s",
      "expected_behaviour": "sweep_detected=true; cancel_storm_detected=true; order cancelled; ANTITOXICFILL_SWEEP_CANCEL_STORM emitted; market enters cooldown",
      "recovery": "Automatic after cooldown_s expires"
    },
    {
      "scenario": "KILL_SWITCH_ON",
      "how_to_inject": "Set killswitch.active=true",
      "expected_behaviour": "All ExecutionPlans discarded immediately; no ExecutionReport emitted; KILL_SWITCH_ACTIVE logged",
      "recovery": "Returns to normal on manual KillSwitch reset"
    },
    {
      "scenario": "REDIS_COOLDOWN_STORE_DOWN",
      "how_to_inject": "Kill Redis connection during active cooldown period",
      "expected_behaviour": "Bot cannot read or write cooldown state; applies conservative fallback reshape on all plans (fail-safe: assume possible toxicity); emits WARN on each evaluation",
      "recovery": "Redis reconnects; cooldown state re-read; normal evaluation resumes"
    },
    {
      "scenario": "ADVERSE_RISK_VOTE_DOWNSIZE",
      "how_to_inject": "Inject RiskVote with verdict=RESHAPE and tags=['toxicity'] from mock portfolio_guard",
      "expected_behaviour": "downsize_factor=0.5 applied; price widens by requote_widen_bps; ANTITOXICFILL_RESHAPE emitted; reshaped plan forwarded to signing",
      "recovery": "Automatic; next plan evaluated fresh"
    }
  ],
  "runbook": {
    "summary": "AntiToxicFill incidents fall into two categories: sustained cooldowns causing trading pauses on multiple markets simultaneously (possible false-positive storm or genuine market crisis), and feed unavailability causing conservative fallback reshaping that may be overly restrictive.",
    "oncall_actions": [
      {
        "alert": "AntiToxicFillHighRejectRate",
        "first_step": "Check reason_code breakdown in Grafana. If ANTITOXICFILL_NEWS_COOLDOWN dominates, check NewsIngest feed for false positives. If ANTITOXICFILL_SWEEP_CANCEL_STORM dominates, check Polymarket market conditions.",
        "diagnosis": "Sustained HARD_REJECT > 30% indicates either a genuine market-wide toxic event, a false-positive signal loop, or a NewsIngest misconfiguration.",
        "mitigation": "If false positives: temporarily increase cooldown_s to reduce churn, or pause NewsIngest integration. If genuine event: let cooldowns run and alert Strategy pod.",
        "escalation": "Exec pod lead + Strategy pod if reject rate sustained > 5 minutes"
      },
      {
        "alert": "AntiToxicFillCooldownsSpiking",
        "first_step": "List active cooldown keys in Redis: redis-cli KEYS 'cooldown:*'. Cross-reference with Polymarket market status page.",
        "diagnosis": "More than 5 simultaneous market cooldowns suggests either a broad market event or a systematic false-positive in the sweep detector.",
        "mitigation": "If false positives: run polytraders bot flush-cooldowns exec.antitoxicfill --market <id>. If genuine: let cooldowns expire naturally.",
        "escalation": "Strategy pod lead for trading-pause decision"
      },
      {
        "alert": "AntiToxicFillHighDrift",
        "first_step": "Check drift_bps histogram in Grafana. High drift p95 > 30 bps indicates systematic adverse selection on active markets.",
        "diagnosis": "Chronic high drift may indicate the drift_threshold_bps parameter needs tuning, or that specific markets are structurally toxic.",
        "mitigation": "Lower drift_threshold_bps for affected markets. Consider blacklisting chronically toxic markets.",
        "escalation": "Strategy pod lead for market selection review"
      },
      {
        "alert": "AntiToxicFillEvalLatencyHigh",
        "first_step": "Check p99 eval latency. If > 150ms, check ws_market feed latency and Redis response times.",
        "diagnosis": "High latency means toxic signals arrive too late relative to order submission, reducing the effectiveness of reshaping.",
        "mitigation": "Check ws_market WebSocket connection health. Reduce max_in_flight if backpressure is the cause.",
        "escalation": "Infra on-call if latency sustained > 300ms"
      }
    ],
    "manual_overrides": [
      {
        "name": "flush_cooldown",
        "how": "polytraders bot flush-cooldowns exec.antitoxicfill --market <market_id>",
        "when": "False-positive cooldown is blocking trading on a market that is not actually toxic. Confirm with Exec pod lead before running."
      },
      {
        "name": "force_pass",
        "how": "Set config.force_verdict = pass for up to 60s via ops console",
        "when": "Emergency: AntiToxicFill is blocking all orders due to a feed misconfiguration. Use only under explicit Exec pod lead approval."
      }
    ],
    "healthcheck": "GET /internal/health/antitoxicfill \u2192 200 if ws_market feed connected and last message < 5s ago, Redis cooldown store reachable, NewsIngest feed responding, eval latency p99 < 150ms, cooldowns_active <= 3. RED if ws_market feed disconnected or stale > 10s, Redis unreachable, eval latency p99 > 300ms, or cooldowns_active > 10."
  },
  "promotion_gates": {
    "to_shadow": [
      {
        "gate": "All 6 acceptance_tests.unit cases pass",
        "how_measured": "CI test run",
        "threshold": "100% pass"
      },
      {
        "gate": "Side, market_id, and outcome invariants verified in property tests",
        "how_measured": "Property-based test: 1000 random ExecutionPlans, none with side/market_id/outcome altered",
        "threshold": "Zero violations"
      }
    ],
    "to_limited_live": [
      {
        "gate": "False-positive cooldown rate < 5% in 48h shadow run",
        "how_measured": "Compare cooldown triggers against post-event market price data; count cases where market price did not move adversely",
        "threshold": "False-positive rate < 5%"
      },
      {
        "gate": "p99 eval latency < 150ms over 24h",
        "how_measured": "polytraders_exec_antitoxicfill_eval_latency_ms histogram",
        "threshold": "p99 < 150ms"
      }
    ],
    "to_general_live": [
      {
        "gate": "7-day limited-live: mean post-fill drift on RESHAPE decisions < 10 bps",
        "how_measured": "Audit log comparing pre-reshape and post-fill prices on all RESHAPE decisions",
        "threshold": "Mean drift < 10 bps"
      },
      {
        "gate": "Zero false-positive HARD_REJECT cancellations on news events that did not materialise",
        "how_measured": "News event log vs. post-event price change; HARD_REJECT valid only if price moved > 20 bps within 60s",
        "threshold": "< 2% false-positive HARD_REJECT rate"
      }
    ]
  },
  "reporting": {
    "emits_kinds": [
      "ExecutionReport"
    ],
    "topics": [
      "polytraders.reports.execution"
    ],
    "partition_key": "trace_id",
    "cadence": "every-event",
    "retention_class": "7y",
    "sampling_rule": "emit-every",
    "bus_failure_action": "wal-then-retry",
    "user_visible": "summary-only",
    "consumes_kinds": [
      "ObservationReport",
      "RiskVote"
    ]
  },
  "capital_impact": "Direct",
  "mode_support": [
    "quarantine"
  ],
  "v3_status": {
    "phase": 5,
    "phase_name": "Execution rails",
    "docs": {
      "done": 27,
      "total": 27,
      "state": "done"
    },
    "impl": {
      "done": 0,
      "total": 15,
      "state": "pending"
    },
    "runtime": {
      "done": 0,
      "total": 8,
      "state": "pending"
    },
    "overall": "pending"
  }
}