"""AWOOOI priority work-order readback.

Loads the committed mainline priority snapshot so production can expose the
current P0/P1 order without consulting chat history, raw sessions, secrets, or
external SCM APIs.
"""

from __future__ import annotations

import json
import re
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo

from src.services.snapshot_paths import default_operations_dir

_DEFAULT_OPERATIONS_DIR = default_operations_dir(Path(__file__))
_SNAPSHOT_FILE = "awoooi-priority-work-order-readback.snapshot.json"
_SCHEMA_VERSION = "awoooi_priority_work_order_readback_v1"
_CONTROLLED_CD_LANE_LIVE_METRIC_SCHEMA_VERSION = (
    "controlled_cd_lane_live_metric_readback_v1"
)
_CONTROLLED_CD_LANE_NODE_EXPORTER_URL = "http://192.168.0.110:9100/metrics"
_CONTROLLED_CD_LANE_PROMETHEUS_QUERY_URL = "http://192.168.0.110:9090/api/v1/query"
_CONTROLLED_CD_LANE_ALLOWED_METRIC_NAMES = {
    "awoooi_host_gitea_actions_active_container_count",
    "awoooi_host_gitea_actions_active_process_count",
    "awoooi_host_load5_per_core",
    "awoooi_runner_failclosed_enforcer_active_job_containers",
    "awoooi_runner_failclosed_enforcer_apply_performed",
    "awoooi_runner_failclosed_enforcer_controlled_drain_active_allowed",
    "awoooi_runner_failclosed_enforcer_controlled_drain_staging_allowed",
    "awoooi_runner_failclosed_enforcer_lane_process_count",
    "awoooi_runner_failclosed_enforcer_last_run_timestamp",
    "awoooi_runner_failclosed_enforcer_root_restore_sources_left",
}
_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
_METRIC_LINE_RE = re.compile(
    r"^(?P<name>[a-zA-Z_:][a-zA-Z0-9_:]*)(?:\{[^}]*\})?\s+"
    r"(?P<value>[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?)$"
)
_COMMANDER_INSERTED_REQUIREMENT_SOURCE = (
    "docs/workplans/2026-07-02-commander-inserted-requirements-priority-ledger.md"
)
_STOCKPLATFORM_DATA_RETRY_READBACK_TIMES = [
    "19:12",
    "20:12",
    "21:12",
    "22:12",
    "22:47",
    "23:31",
]
_PARALLEL_MAINLINE_FORBIDDEN_ACTIONS = [
    "fake_stockplatform_freshness_marker",
    "manual_zero_fill_for_margin_short",
    "copy_previous_trading_day_data",
    "db_write_or_restore_from_this_wait_lane",
    "docker_or_host_restart_for_source_pending",
]
_AI_AUTOMATION_NODE_RECEIPT_SCHEMA_VERSION = "ai_automation_node_receipt_v1"
_AI_AUTOMATION_NODE_RECEIPT_REQUIRED_FIELDS = [
    "trace_id",
    "run_id",
    "work_item_id",
    "node_id",
    "node_status",
    "timestamp",
    "evidence_refs",
    "verifier_result",
    "rollback_result",
    "km_writeback_ref",
    "playbook_trust_writeback_ref",
]
_COMMANDER_INSERTED_REQUIREMENT_WORK_ITEMS: list[dict[str, Any]] = [
    {
        "id": "CIR-P0-001",
        "priority": "P0",
        "order": 1,
        "status": "in_progress",
        "lane": "mainline_order",
        "request": "不要偏離 / 只推進目前唯一目標 / 照順序推進",
        "normalized_work_item": "所有插入需求先歸入正式工作項，再依 P0/P1/P2/P3 排序。",
        "current_state": "台帳已建立；本 readback 將其產品化到 API 與前台。",
        "acceptance": "priority work-order API 與 work-items 前台可讀回完整排序。",
        "next_action": "每次推進固定回報 current P0 / action / evidence / next action。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-002",
        "priority": "P0",
        "order": 2,
        "status": "in_progress",
        "lane": "production_visible_result",
        "request": "我要看到實作結果，不能只有文件或長文字。",
        "normalized_work_item": "每個主線工作必須產出 commit、Gitea CD、production readback 或 verifier output。",
        "current_state": "Gitea/CD/readback 已有基準；本輪補前台可見的插入需求面板。",
        "acceptance": "正式環境 /zh-TW/awooop/work-items 可看到排序後工作項與 readback 計數。",
        "next_action": "正常 commit、push Gitea main，追 CD 與 production UI/API readback。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-003",
        "priority": "P0",
        "order": 3,
        "status": "done",
        "lane": "github_freeze",
        "request": "GitHub 申訴期間先做其他工作。",
        "normalized_work_item": "GitHub freeze 下，所有 GitHub 工作轉回 Gitea/local/production truth。",
        "current_state": "GitHub 停用有效；本輪未使用 GitHub、gh、GitHub API。",
        "acceptance": "GitHub 相關項目維持 stopped / do_not_use，且不阻擋 Gitea 主線。",
        "next_action": "只以 Gitea / Gitea SSH / production readback 作為 source-control truth。",
        "mapped_workplan_id": "P0-003A",
    },
    {
        "id": "CIR-P0-004",
        "priority": "P0",
        "order": 4,
        "status": "in_progress",
        "lane": "gitea_source_truth",
        "request": "全部專案推版與 repo truth 不能靠 GitHub。",
        "normalized_work_item": "全產品 source-control readiness 改以 Gitea repo identity、SSH heads、backup health 為準。",
        "current_state": "9 個 expected Gitea repos 已讀回 OK；跨產品 dev/prod CI baseline 仍需逐步補。",
        "acceptance": "product governance matrix 顯示 canonical repo、branch、backup evidence、private visibility。",
        "next_action": "把全產品 source truth 接到 product governance matrix。",
        "mapped_workplan_id": "P0-003",
    },
    {
        "id": "CIR-P0-005",
        "priority": "P0",
        "order": 5,
        "status": "done",
        "lane": "account_safety",
        "request": "說清楚 GitHub 帳號風險邊界。",
        "normalized_work_item": "建立 account safety 邊界：不碰 GitHub，不要求 token，不讀 suspension 細節。",
        "current_state": "freeze 已在 hard gates 與工作台帳中固定。",
        "acceptance": "沒有 GitHub read/write/API/gh 操作，且未要求使用者提供 GitHub token。",
        "next_action": "未來若要恢復 GitHub，先做風險評估與人工確認。",
        "mapped_workplan_id": "P0-003A",
    },
    {
        "id": "CIR-P0-006",
        "priority": "P0",
        "order": 6,
        "status": "blocked",
        "lane": "secret_safety",
        "request": "使用者貼入 runner token / 密碼類敏感值並授權直接操作。",
        "normalized_work_item": "敏感值不入檔、不重印、不保存；runner registration 改 hidden prompt 或 metadata verifier。",
        "current_state": "已遵守不保存、不讀 secret；secret exposure follow-up 不含明文。",
        "acceptance": "secret_value_read=false，並只輸出 rotate / revoke / hidden-prompt checklist。",
        "next_action": "需要 runner registration 時，只走 token-safe hidden prompt 或 non-secret verifier。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P0-007",
        "priority": "P0",
        "order": 7,
        "status": "in_progress",
        "lane": "runner_registration",
        "request": "我沒辦法複製貼上 token。",
        "normalized_work_item": "Runner 註冊需支援遠端 TTY hidden prompt，不要求把 token 貼給 Codex。",
        "current_state": "token-safe registration script 已有 source；live 110 lane metadata 仍需 verifier。",
        "acceptance": "不讀 `.runner` 內容，registration metadata 以 non-secret verifier 證明。",
        "next_action": "補 110 drain staging artifacts 後只跑 readiness verifier。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P0-008",
        "priority": "P0",
        "order": 8,
        "status": "done",
        "lane": "repo_identity",
        "request": "Gitea 恢復正常、所有專案儲存庫恢復、原本儲存庫不是新增。",
        "normalized_work_item": "repo recovery 以原 Gitea repo identity、SSH heads、backup health 為準，不建立替代 repo。",
        "current_state": "handoff truth 顯示 9 expected repos SSH heads OK、backup missing=0。",
        "acceptance": "private repo public 404 只標 visibility/auth，不宣稱 history 消失。",
        "next_action": "若再出現 404，先判斷 visibility/auth，再看 SSH heads 與 backup health。",
        "mapped_workplan_id": "P0-003",
    },
    {
        "id": "CIR-P0-009",
        "priority": "P0",
        "order": 9,
        "status": "in_progress",
        "lane": "gitea_cd",
        "request": "所有專案都沒辦法推版。",
        "normalized_work_item": "先保 AWOOOI Gitea CD mainline green，再逐產品恢復 dev/prod CI baseline。",
        "current_state": "AWOOOI Gitea CD 已恢復；跨產品 baseline 仍按 governance matrix 推進。",
        "acceptance": "Gitea queue / deploy marker / production readback 必須跟最新 main 對齊。",
        "next_action": "每個 production-visible 變更正常 push Gitea main 並追 CD。",
        "mapped_workplan_id": "P0-004",
    },
    {
        "id": "CIR-P0-010",
        "priority": "P0",
        "order": 10,
        "status": "in_progress",
        "lane": "runner_pressure",
        "request": "修復 Gitea、但不要開 legacy runner。",
        "normalized_work_item": "188 non-110 runner 為主 CD lane；110 legacy/generic runner 維持 fail-closed。",
        "current_state": "188 ready；110 live verifier 仍顯示 config / registration / staging blockers。",
        "acceptance": "不恢復 generic runner，不解除 pressure guard，不改成 warn-only。",
        "next_action": "補 110 drain staging artifacts 後只跑 readiness verifier。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P0-011",
        "priority": "P0",
        "order": 11,
        "status": "in_progress",
        "lane": "work_state_visibility",
        "request": "所有已開始、進行中、已完成工作全部看清楚。",
        "normalized_work_item": "工作狀態拆成 Done / In Progress / Blocked / Deferred，不再用單句完成度帶過。",
        "current_state": "本 readback 補完整 status 與 priority counts。",
        "acceptance": "API/UI 同時顯示總數、P0/P1/P2/P3、各工作狀態與 next action。",
        "next_action": "後續 LOGBOOK 與 UI 都沿用 status/evidence/next-action 結構。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P0-012",
        "priority": "P0",
        "order": 12,
        "status": "in_progress",
        "lane": "mainline_sequence",
        "request": "所有主線工作持續推進。",
        "normalized_work_item": "主線順序固定：Gitea source truth -> CD/runner -> production readback -> product governance -> KM/PlayBook/RAG。",
        "current_state": "目前仍在 Gitea/CD/production-visible readback 主線，不切 GitHub 或未授權 runtime 支線。",
        "acceptance": "每次下一步都能映射到此 sequence 的一個節點。",
        "next_action": "完成本面板 production readback 後回到下一個 P0 runtime closure item。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-013",
        "priority": "P0",
        "order": 13,
        "status": "in_progress",
        "lane": "gate_taxonomy",
        "request": "所有硬閘和 guard 全部打開。",
        "normalized_work_item": "非事故 gate 轉 evidence / ledger；事故級 secret、destructive、reboot、force-push 等仍 break-glass。",
        "current_state": "gate taxonomy 已整理；UI/API 需顯示可自動處理方式與不可越線項。",
        "acceptance": "readback 顯示 controlled apply 邊界，不把 0/false 當終局阻擋。",
        "next_action": "後續 P0 修復補 target selector、diff、dry-run、rollback、verifier、writeback。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-014",
        "priority": "P0",
        "order": 14,
        "status": "done",
        "lane": "approval_semantics",
        "request": "批准/繼續不能被誤解。",
        "normalized_work_item": "批准等於沿目前排序繼續，不等於開新支線或解除事故級 hard gate。",
        "current_state": "判讀規則已寫入台帳並由本 readback 對外顯示。",
        "acceptance": "簡短批准不會觸發 GitHub、secret、force push、reboot 或 destructive operation。",
        "next_action": "後續收到批准時，延續最新 P0 work item。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-015",
        "priority": "P0",
        "order": 15,
        "status": "in_progress",
        "lane": "context_convergence",
        "request": "為什麼搞成這麼亂。",
        "normalized_work_item": "多視窗、長上下文、重複 gate、GitHub freeze、Gitea recovery、runner pressure 收斂到同一台帳。",
        "current_state": "本 API/UI 成為收斂入口；不靠散落聊天句子。",
        "acceptance": "後續工作先看 work-order readback 與 LOGBOOK，不重讀 raw conversations。",
        "next_action": "把此 readback 作為 work-items 前台的主線優先序來源。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P0-AILOOP-001",
        "priority": "P0",
        "order": 16,
        "status": "in_progress",
        "lane": "ai_loop_agent_mainline",
        "request": "你現在有在往 AI Loop Agent 這個方向目標前進嗎？",
        "normalized_work_item": (
            "AI Loop Agent 北極星必須成為所有告警、工作項、Run、LOG 與前台的主線："
            "Sensor -> Normalizer -> AI Lane -> Candidate -> Gate -> Execution Boundary -> Verifier -> Learning/Writeback。"
        ),
        "current_state": "MASTER §1.4 已定義產品契約；本 work-order 將其升為 P0 可見工作項。",
        "acceptance": (
            "Work Items API/UI 可讀回 AI Loop Agent 主線，且每個後續 P0 都能映射到閉環節點。"
        ),
        "next_action": "把 Telegram、LOG、KM/RAG/MCP/PlayBook 與 UI 工作項都掛到 AI Loop Agent 節點。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-AILOOP-002",
        "priority": "P0",
        "order": 17,
        "status": "in_progress",
        "lane": "ai_automation_trace_nodes",
        "request": "所有 AI 自動化完整流程、節點必須完整且詳盡紀錄，作為持續學習與提升依據。",
        "normalized_work_item": (
            "每次 AI 自動化事件必須記錄 trace_id、run_id、work_item_id、節點狀態、timestamp、"
            "evidence refs、verifier result、rollback result 與 KM/PlayBook trust writeback refs。"
        ),
        "current_state": "現有 Run/Work Item/receipt 有部分證據；完整節點契約仍需補齊。",
        "acceptance": "API readback 能逐筆顯示 AI automation node coverage 與 missing node blockers。",
        "next_action": "建立 AI automation node receipt schema，先套用 Telegram alert 與 P0 runtime lanes。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P0-LOG-001",
        "priority": "P0",
        "order": 18,
        "status": "in_progress",
        "lane": "global_log_ingestion",
        "request": "把所有專案、產品、網站、服務、套件、工具等等的所有 LOG 都收進去。",
        "normalized_work_item": (
            "建立全域 LOG source registry 與 ingestion adapters，涵蓋 project/product/site/service/package/tool，"
            "並帶 redaction、retention、freshness、last_success 與 owner lane。"
        ),
        "current_state": "目前 observability/log/backup coverage 分散；尚未成為單一 AI Agent 可用資料層。",
        "acceptance": "source registry 顯示每類 LOG 的 adapter、freshness、缺口與安全邊界。",
        "next_action": "先做 metadata-only LOG source registry，不讀 secret/raw payload，再接 AI automation trace。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P0-LOG-002",
        "priority": "P0",
        "order": 19,
        "status": "pending",
        "lane": "log_tagging_classification_clustering",
        "request": "LOG 要依據專案、產品、網站、服務、套件、工具貼標，完整分類、分群，讓 AI Agent 可處理。",
        "normalized_work_item": (
            "LOG 必須自動貼上 product/project/site/service/package/tool、severity、lane、evidence confidence、"
            "AI route、cluster_id 與 dedup/fingerprint。"
        ),
        "current_state": "分類規則與群聚資料尚未統一；不能只靠 raw log 或 Telegram 文字。",
        "acceptance": "AI Agent 可按 tag/cluster 查詢相關 evidence，並產生候選修復與 verifier。",
        "next_action": "定義 tag taxonomy 與 clustering readback，先覆蓋 Telegram alert、CPU pressure、backup、freshness。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P0-TG-001",
        "priority": "P0",
        "order": 20,
        "status": "in_progress",
        "lane": "telegram_alert_ai_automation",
        "request": "所有發送到 Telegram 的監控告警是否全面清查、完整寫入 DB 或日誌、符合 AI Agent AI 自動化？不要一堆告警都要人工作業。",
        "normalized_work_item": (
            "每個 Telegram 告警都要映射到 DB/log receipt、AI route、controlled queue、work item、"
            "post verifier 與 learning writeback；direct send 或 manual default 都列缺口。"
        ),
        "current_state": (
            "Telegram alert AI automation matrix endpoint 已實作；channel_hub API direct sender 已改走 "
            "TelegramGateway / AwoooP outbound receipt path；scripts/ops 4 條 legacy direct Bot API fallback "
            "已改為 AWOOI API / TelegramGateway receipt path；目前明確讀回 workflow direct send 0、"
            "ops script direct gap 0、API direct gap 0；/runs/ai-alert-cards 已補 KM / PlayBook / RAG / MCP "
            "learning_writeback_refs read model，並投影 KM / PlayBook / RAG / MCP / verifier / AI Agent "
            "learning_registry consumer bindings；agent-log-controlled-writeback-consumer-readback 已把同一批 "
            "Telegram alert registry 轉成 AI Loop Agent consumer context receipt。"
        ),
        "acceptance": "Telegram alert matrix 顯示 total、DB receipt、AI route、controlled queue、manual/default gap、direct send gap、learning refs、registry readback 與 AI Loop consumer context receipt。",
        "next_action": "把 Telegram alert AI Loop context receipts 接 post-apply verifier，讓後續判斷可直接重用這些 receipt。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-IA-001",
        "priority": "P0",
        "order": 21,
        "status": "pending",
        "lane": "navigation_ia_recovery",
        "request": "AWOOOI 裡面的 IwoooS 被移除、導航列菜單被移除，且沒有把被移除頁面整合到相關頁面。",
        "normalized_work_item": (
            "建立 IA/nav removal recovery ledger：每個被移除 menu/route/page 必須有保留、合併、替代目的地、"
            "redirect、權限邊界與 desktop/mobile navigation smoke。"
        ),
        "current_state": "目前只在對話中被追問，尚未完整盤點成 route/menu/readback 表。",
        "acceptance": "IA recovery readback 顯示 IwoooS、AwoooP、OpenClaw、governance route 是否仍可被導覽或已合併。",
        "next_action": "盤點 navigation config、route list 與 removed-page destination，補 Work Items UI readback。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P1-001",
        "priority": "P1",
        "order": 16,
        "status": "pending",
        "lane": "km_playbook_rag_mcp",
        "request": "整合到 MCP、RAG、KM、PLAYBOOK、LOG。",
        "normalized_work_item": "治理資料要沉澱到 KM / PlayBook / RAG / MCP / log，不只存在對話。",
        "current_state": "已列入 P1；本輪先完成 API/UI readback。",
        "acceptance": "每個工作項帶 work_item_id、evidence source、verifier、rollback、trust writeback。",
        "next_action": "定義 work item schema 與 trust writeback 欄位。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P1-002",
        "priority": "P1",
        "order": 17,
        "status": "pending",
        "lane": "priority_matrix",
        "request": "所有工作的優先順序要清楚。",
        "normalized_work_item": "建立跨產品 priority matrix，區分 AWOOOI P0、Gitea/source-control P0、product governance P1、UI/UX P2。",
        "current_state": "scorecard 部分存在；本台帳補 current thread priority order。",
        "acceptance": "product runtime governance dashboard 能讀回 priority matrix。",
        "next_action": "把本台帳映射到 existing product runtime governance dashboard。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P1-003",
        "priority": "P1",
        "order": 18,
        "status": "in_progress",
        "lane": "repo_governance",
        "request": "所有儲存庫都不能被忽略。",
        "normalized_work_item": "repo identity / backup health / private visibility 成為 product governance 第一層。",
        "current_state": "Gitea P0 恢復 truth 已有 9 repos OK。",
        "acceptance": "全產品 source-control readback rows 顯示 canonical repo / branch / backup evidence。",
        "next_action": "補全產品 source-control readback rows。",
        "mapped_workplan_id": "P0-003",
    },
    {
        "id": "CIR-P1-004",
        "priority": "P1",
        "order": 19,
        "status": "pending",
        "lane": "gitea_auth_paths",
        "request": "Gitea 瀏覽器、API、SSH、runner token 的差別要清楚。",
        "normalized_work_item": "Gitea 操作區分 public HTML readback、API token readback、SSH git readback、runner token registration。",
        "current_state": "已區分 public HTML、API 401、SSH push 可用。",
        "acceptance": "runbook 說明何時需要 token、何時不需要、且不得要求貼 token。",
        "next_action": "建立 non-secret Gitea auth path runbook/readback。",
        "mapped_workplan_id": "P0-003",
    },
    {
        "id": "CIR-P1-005",
        "priority": "P1",
        "order": 20,
        "status": "deferred",
        "lane": "local_console",
        "request": "用 VMware Console 去 192.168.0.99 操作 110。",
        "normalized_work_item": "VMware console 屬 break-glass / local console lane，只在 control path 無法修復且目標明確時使用。",
        "current_state": "未作為本輪主線執行。",
        "acceptance": "若需要，只列 non-secret console checklist，不輸入或保存密碼。",
        "next_action": "保持 deferred，除非 SSH/Gitea control path 無法修復。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P1-006",
        "priority": "P1",
        "order": 21,
        "status": "pending",
        "lane": "sudo_auth_metadata",
        "request": "sudo 為什麼不能用密碼。",
        "normalized_work_item": "sudo/account/SSH auth 只做 metadata audit，不要求或記錄密碼。",
        "current_state": "未在本輪 runtime 修改。",
        "acceptance": "playbook 禁止收密碼，僅輸出 metadata check 與 authorized console SOP。",
        "next_action": "補 sudo/auth metadata check playbook。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P1-007",
        "priority": "P1",
        "order": 22,
        "status": "done",
        "lane": "blocked_lane_fallback",
        "request": "GitHub blocked 時先做其他工作。",
        "normalized_work_item": "GitHub blocked 不等待，改推 Gitea / CD / product governance / backup / KM mainline。",
        "current_state": "已照做：Gitea CD 已 success，且本輪續推 production-visible work item。",
        "acceptance": "不等待 GitHub appeal，不把 GitHub 當下一步。",
        "next_action": "下個 P0 仍照排序推進。",
        "mapped_workplan_id": "P0-004",
    },
    {
        "id": "CIR-P1-AUTO-001",
        "priority": "P1",
        "order": 23,
        "status": "in_progress",
        "lane": "parallel_mainline_scheduling",
        "request": "不能偏離不代表一定要每一個工作完成，才能進行下一個。",
        "normalized_work_item": (
            "建立主線並行推進規則：不離開 P0/P1 主線，但可在依賴允許時同時推進 API/UI、LOG、Telegram、"
            "KM/RAG/MCP/PlayBook 與 verifier。"
        ),
        "current_state": "目前 work-order 已按 priority 排序；仍需在回報和 UI 顯示 WIP lane。",
        "acceptance": "Work Items 顯示 next item、active lanes 與 blocked/deferred，不把單一 blocker 當全局停工。",
        "next_action": "讓後續回報以 active lane + evidence 更新，而不是等待單一項完全結束。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P1-UI-001",
        "priority": "P1",
        "order": 24,
        "status": "in_progress",
        "lane": "professional_product_ui_ux_mainline",
        "request": "UI/UX 工作項目不見了；整個前端頁面一大堆文字，要趕快優化成主流、專業網站、產品做法。",
        "normalized_work_item": (
            "UI/UX 成為主線工作項：first-viewport cockpit、可掃描 cards/flow rows、少文字牆、"
            "route/nav 一致、desktop/mobile visual smoke。"
        ),
        "current_state": "AwoooP Work Items 有初版面板；全站仍需系統性文字牆收斂與 IA 修復。",
        "acceptance": "AwoooP/Approvals/Runs/Work Items/Alerts/AI Loop 重要頁面都有專業 cockpit 與截圖 smoke。",
        "next_action": "先把新增 AI Loop/LOG/Telegram/IA 工作項顯示在 Work Items spotlight，再排 UI smoke。",
        "mapped_workplan_id": "P2-UX",
    },
    {
        "id": "CIR-P1-KM-002",
        "priority": "P1",
        "order": 25,
        "status": "pending",
        "lane": "log_km_mcp_rag_playbook_integration",
        "request": "所有服務日誌、LOG 要完整跟 KM、MCP、RAG、PLAYBOOK 整合，讓 AI Agent 利用起來。",
        "normalized_work_item": (
            "LOG ingestion 的每個 tag/cluster 必須能產生 RAG chunk、KM entry、MCP evidence pointer、"
            "PlayBook candidate、trust update 與 verifier/rollback learning。"
        ),
        "current_state": "writeback targets 分散存在；尚未形成 LOG -> AI Agent -> controlled action 的統一管線。",
        "acceptance": "readback 顯示 KM/RAG/MCP/PlayBook writeback target count、missing target 與 last_success。",
        "next_action": "把 LOG source registry 接到 KM/RAG/MCP/PlayBook writeback readback。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P2-001",
        "priority": "P2",
        "order": 23,
        "status": "in_progress",
        "lane": "reporting_cadence",
        "request": "為什麼會偏離工作目標。",
        "normalized_work_item": "每輪回報固定成 current P0 / action taken / evidence / next action。",
        "current_state": "本 readback 提供產品化依據；仍需持續執行。",
        "acceptance": "final / handoff 先列結果，再列下一步，不開旁支。",
        "next_action": "每次 production readback 後更新同一格式。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P2-002",
        "priority": "P2",
        "order": 24,
        "status": "deferred",
        "lane": "observability",
        "request": "production health readback degraded 要處理但不能亂重啟。",
        "normalized_work_item": "SignOz component down 分流到 Observability P2，不阻擋本次 CD success。",
        "current_state": "已觀察到 SignOz degraded；本輪不重啟服務。",
        "acceptance": "observability lane 有獨立 readback，不蓋過 Gitea/CD 主線。",
        "next_action": "排入 Observability P2，先補 readback 再決定 controlled action。",
        "mapped_workplan_id": "P2-OBSERVABILITY",
    },
    {
        "id": "CIR-P0-RBT-001",
        "priority": "P0",
        "order": 26,
        "status": "in_progress",
        "lane": "reboot_slo",
        "request": "主機重啟後 10 分鐘內全部恢復，且要自動判斷所有主機被重啟。",
        "normalized_work_item": "建立 99/110/111/112/120/121/188 reboot detector、10 分鐘 SLO scorecard 與固定 triage order。",
        "current_state": "部分已有 reboot recovery SLO alerts、scorecard、textfile；仍缺 fresh all-host reboot/drill proof。",
        "acceptance": "最新 reboot SLO scorecard 可讀回；缺 fresh event 時標 awaiting_next_reboot_or_approved_drill。",
        "next_action": "產生最新 reboot SLO scorecard readback，不宣稱未證明的 10 分鐘 SLA。",
        "mapped_workplan_id": "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD",
    },
    {
        "id": "CIR-P0-RBT-002",
        "priority": "P0",
        "order": 27,
        "status": "pending",
        "lane": "reboot_detection",
        "request": "沒有偵測到主機重啟。",
        "normalized_work_item": "boot_id、uptime、node exporter、Windows exporter、VMware VM power state 必須合併成 reboot event。",
        "current_state": "Prometheus rule 有缺口告警；99/VMware/Windows 來源仍未完整閉環。",
        "acceptance": "99/VMware/Windows probe source 與 textfile readback 存在，缺 99 時不得宣稱全主機 green。",
        "next_action": "補 99/VMware/Windows probe source 與 textfile readback。",
        "mapped_workplan_id": "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD",
    },
    {
        "id": "CIR-P0-RBT-003",
        "priority": "P0",
        "order": 28,
        "status": "pending",
        "lane": "vmware_autostart",
        "request": "192.168.0.99 VMware 要自動啟動，裡面 111/188/120/121/112 也自動啟動。",
        "normalized_work_item": "Windows 99 VMware host autostart、guest VM autostart contract、VM 開機順序與 readback。",
        "current_state": "尚未完成；不能用 Linux host green 代替。",
        "acceptance": "non-secret verifier 只讀 `.vmx`、autostart policy、VMware service 狀態，不讀 Windows 密碼。",
        "next_action": "建立 non-secret Windows/VMware autostart checklist 與 verifier。",
        "mapped_workplan_id": "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD",
    },
    {
        "id": "CIR-P0-RBT-004",
        "priority": "P0",
        "order": 29,
        "status": "pending",
        "lane": "windows_update_policy",
        "request": "192.168.0.99 不可因 Windows Update 無預警重開。",
        "normalized_work_item": "Windows Update reboot policy：active hours、no auto-restart、maintenance window、update notification audit。",
        "current_state": "尚未完成；屬 99 Windows policy lane。",
        "acceptance": "Windows Update policy verifier 可讀回；不得要求使用者貼密碼。",
        "next_action": "建立 Windows Update policy verifier，等待 99 console 或授權遠端管理通道。",
        "mapped_workplan_id": "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD",
    },
    {
        "id": "CIR-P0-RBT-005",
        "priority": "P0",
        "order": 30,
        "status": "pending",
        "lane": "maintenance_fallback",
        "request": "網站重啟後 502 嚴重影響體驗，要維護頁，外部雲端或專業做法。",
        "normalized_work_item": "Public maintenance fallback：Nginx / edge / external static maintenance page / status page / fail-open UX。",
        "current_state": "尚未完整落地；目前是需求缺口。",
        "acceptance": "先有 no-write decision record、rollback、smoke verifier；不直接切 DNS 或 edge route。",
        "next_action": "產生 public_maintenance_fallback decision record 與 no-write check-mode。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-RBT-006",
        "priority": "P0",
        "order": 31,
        "status": "in_progress",
        "lane": "telegram_reboot_alerts",
        "request": "所有主機關機立刻 Telegram 告警，重啟後也要告警，其他告警一併完整思考。",
        "normalized_work_item": "Down、shutdown suspected、reboot detected、reboot recovered、SLO missed、backup failed、CPU pressure 等告警矩陣。",
        "current_state": "部分已有 Alertmanager rule 與 Telegram receipt 補強；仍缺完整 shutdown/up E2E receipt。",
        "acceptance": "Alertmanager active/resolved 與 outbound receipt 能逐項讀回，不送測試 secret。",
        "next_action": "建立 Telegram alert matrix 與 receipt verifier。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-RBT-007",
        "priority": "P0",
        "order": 32,
        "status": "in_progress",
        "lane": "backup_observability",
        "request": "所有備份包含主機、DB、網站、服務、套件、工具、日誌都沒有監控告警。",
        "normalized_work_item": "Backup observability coverage：job inventory、last success、freshness、offsite、restore drill、Telegram receipt。",
        "current_state": "部分已有 backup health exporter / alert rules；全域 coverage 與 restore drill 未全綠。",
        "acceptance": "host/DB/site/service config/package/tool/log 每列都有 metric、alert、last_success、restore_verifier。",
        "next_action": "建立 backup coverage matrix 與 restore drill verifier。",
        "mapped_workplan_id": "P0-005",
    },
    {
        "id": "CIR-P0-RBT-008",
        "priority": "P0",
        "order": 33,
        "status": "in_progress",
        "lane": "reboot_runbook_fixed_order",
        "request": "每次重啟排查都不一樣，也不知道多久恢復，不符合 SLA。",
        "normalized_work_item": "固定化 reboot runbook：fixed triage order、ETA、active blocker、remaining seconds、owner lane、next command。",
        "current_state": "scorecard source / snapshot / API 已補 current_phase、eta_or_wait_reason、primary_blocker、next_safe_action；仍需 production deploy readback 與下一次 fresh reboot/drill 證明。",
        "acceptance": "SLO scorecard 強制輸出 current_phase、eta_or_wait_reason、active_blockers、next_safe_action。",
        "next_action": "推送後讀回 /api/v1/agents/reboot-auto-recovery-slo-scorecard，確認固定欄位在 production 可見；再接 99/VMware 與 fresh reboot/drill。",
        "mapped_workplan_id": "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD",
    },
    {
        "id": "CIR-P0-RBT-009",
        "priority": "P0",
        "order": 34,
        "status": "pending",
        "lane": "product_freshness_version",
        "request": "所有產品、網站都要是最新版本；版本和數據是否最新要驗證。",
        "normalized_work_item": "Product freshness/version matrix：source commit、deploy marker、runtime image、public health、data freshness、latest source availability。",
        "current_state": "AWOOOI / StockPlatform 部分已在做；全產品未統一。",
        "acceptance": "全產品表含 product、canonical repo、main SHA、deploy marker、public URL、data freshness、blocked reason。",
        "next_action": "建立全產品 freshness/version readback 表。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-GIT-001",
        "priority": "P0",
        "order": 35,
        "status": "done",
        "lane": "gitea_backup_restore",
        "request": "Gitea 儲存庫都不見了？Gitea 沒完整備份嗎？",
        "normalized_work_item": "Gitea repository identity、backup proof、restore drill 需比對 SSH heads、repo path、bundle backup、restore sample。",
        "current_state": (
            "2026-07-02 production Gitea bundle readback 已 ready："
            "9 expected repos present/ok、missing=0、failed=0、checksum_missing=0、"
            "bundle_fresh=true、all_expected_ok=true、sample_restore_dry_run_ok=true。"
            "本項關閉 repo bundle / restore dry-run 層；Gitea DB/settings/issues/packages/LFS "
            "全量 dump 仍歸 backup contract 另列追蹤。"
        ),
        "acceptance": "Gitea repo bundle backup readback 與 sample restore dry-run verifier 可讀回；禁止刪 repo / 改 visibility。",
        "next_action": (
            "維持每日 bundle backup + restore dry-run monitoring；另補 Gitea full dump / DB / issues / packages / LFS 備份 readback。"
        ),
        "mapped_workplan_id": "P0-003",
    },
    {
        "id": "CIR-P0-CPU-001",
        "priority": "P0",
        "order": 36,
        "status": "in_progress",
        "lane": "cpu_pressure_automation",
        "request": "110 / 188 CPU 負載持續過高，為什麼沒監控告警、沒主動修復。",
        "normalized_work_item": "Sustained CPU pressure automation：Alertmanager -> controller -> evidence -> service playbook -> verifier -> KM writeback。",
        "current_state": "110 已有 Host110SustainedModeratePressure、Gitea playbook、Stock/Postgres evidence；188 仍需同級 readback。",
        "acceptance": "Stock/Postgres playbook 與 188 equivalent readback 可讀回，不以單次下降結案。",
        "next_action": "接 postgres_hot_query_or_backup_export_playbook 並補 188 equivalent readback。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-CPU-002",
        "priority": "P0",
        "order": 37,
        "status": "in_progress",
        "lane": "alert_correlation",
        "request": "噪音會影響真問題，要整合一起做。",
        "normalized_work_item": "Alert noise / real issue correlation：backup aggregate noise、CPU pressure、Gitea queue、Stock freshness 分清主因與次因。",
        "current_state": "部分已在 SOP 註記；仍需統一 correlation scorecard。",
        "acceptance": "incident correlation readback 顯示 primary_blocker、secondary_noise、ignored_noise_reason、evidence_ref。",
        "next_action": "建立 incident correlation readback。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P0-CD-001",
        "priority": "P0",
        "order": 38,
        "status": "in_progress",
        "lane": "gitea_cd_baseline",
        "request": "所有專案都不能推版 / 要看到實作結果。",
        "normalized_work_item": "Gitea-only CD baseline：每次 main push 要有 visible run、deploy marker、production readback；GitHub 不作解法。",
        "current_state": "AWOOOI 最新 main 可推；全產品未全綠。",
        "acceptance": "product governance matrix 接入各產品 Gitea CD readiness，不只報 AWOOOI。",
        "next_action": "將 product governance matrix 接入各產品 Gitea CD readiness。",
        "mapped_workplan_id": "P0-004",
    },
    {
        "id": "CIR-P1-AI-001",
        "priority": "P1",
        "order": 39,
        "status": "in_progress",
        "lane": "ai_controlled_repair_loop",
        "request": "AI 專業在哪？要能主動發現、主動修復。",
        "normalized_work_item": "AI controlled repair loop：detect -> classify -> candidate -> check-mode -> controlled apply -> post verifier -> KM / PlayBook trust。",
        "current_state": "CPU / Gitea / Telegram receipt 已部分落地；全域 AI loop 未全部接上。",
        "acceptance": "每個 P0 runbook 都有 candidate_action、controlled_apply_allowed、post_verifier、trust_writeback。",
        "next_action": "將每個 P0 runbook 補齊 AI controlled repair loop 欄位。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P1-KM-001",
        "priority": "P1",
        "order": 40,
        "status": "in_progress",
        "lane": "sop_playbook_writeback",
        "request": "修復過程、經驗完整沉澱進 SOP，整合到目前版本。",
        "normalized_work_item": "所有 P0 修復必須同步 LOGBOOK、SOP、PlayBook、workplan ledger，不只留在對話。",
        "current_state": "本台帳、LOGBOOK、SOP 已開始補；仍需 API/UI read model。",
        "acceptance": "read-only API / governance UI row 顯示 last_updated / evidence_count。",
        "next_action": "把本台帳轉成 read-only API / governance UI row。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P1-WORK-001",
        "priority": "P1",
        "order": 41,
        "status": "in_progress",
        "lane": "work_state_inventory",
        "request": "所有已開始、進行中、已完成工作全部看清楚。",
        "normalized_work_item": "工作狀態盤點：Done / In Progress / Blocked / Deferred / Next Action + evidence。",
        "current_state": "本台帳已有初版；需納入 reboot/backup/VMware/maintenance/CPU。",
        "acceptance": "Done/In Progress/Blocked/Deferred 包含 reboot、backup、VMware、maintenance、CPU 全列。",
        "next_action": "更新工作狀態盤點並納入本節新 P0。",
        "mapped_workplan_id": "P0-010",
    },
    {
        "id": "CIR-P1-OPENCLAW-001",
        "priority": "P1",
        "order": 42,
        "status": "in_progress",
        "lane": "openclaw_live_ops_space",
        "request": "OpenClaw 要有像 Gather Town 的工作畫面，而且是持續動畫。",
        "normalized_work_item": "OpenClaw Live Ops Space：animated room、agent avatars、flow packets、work tokens、scene-state API、desktop/mobile smoke。",
        "current_state": "/zh-TW/openclaw/live-ops-space production route / scene API / desktop-mobile animation smoke 已讀回；AwoooP 導流仍可再前置。",
        "acceptance": "production smoke 證明動畫持續更新、scene API 可讀、desktop/mobile 無重疊；AwoooP 工作台可導向此視覺面。",
        "next_action": "將 AwoooP 工作台的 OpenClaw Live Ops 入口前置，保留 production smoke 截圖與動畫位移證據。",
        "mapped_workplan_id": "P1-006",
    },
    {
        "id": "CIR-P2-OBS-001",
        "priority": "P2",
        "order": 42,
        "status": "pending",
        "lane": "observability_coverage",
        "request": "其他還有哪些告警也要完整思考。",
        "normalized_work_item": "Observability coverage expansion：SignOz/Sentry/Langfuse/Harbor/Registry/K3s/DB/backup/freshness/route/TLS 告警。",
        "current_state": "多數 rule 分散存在；coverage matrix 不完整。",
        "acceptance": "alert coverage matrix 區分 P0 actionable 與 P2 observability debt。",
        "next_action": "建立 alert coverage matrix。",
        "mapped_workplan_id": "P2-OBSERVABILITY",
    },
    {
        "id": "CIR-P2-UX-001",
        "priority": "P2",
        "order": 43,
        "status": "pending",
        "lane": "maintenance_ux",
        "request": "維護頁外部雲端或其他專業做法評估。",
        "normalized_work_item": "Maintenance UX 可先做 design / decision record；實際 DNS/edge cutover 需 controlled apply。",
        "current_state": "尚未開始。",
        "acceptance": "no-write design / rollback / smoke verifier 完成；不直接切 DNS。",
        "next_action": "先出 no-write design / rollback / smoke verifier。",
        "mapped_workplan_id": "P0-006",
    },
    {
        "id": "CIR-P2-UX-002",
        "priority": "P2",
        "order": 44,
        "status": "in_progress",
        "lane": "ai_professional_workbench_ux",
        "request": "不要又是一大堆文字頁 / 文字牆，要像主流網站與專業 AI 產品。",
        "normalized_work_item": "AI professional UI：first-viewport cockpit、metrics/cards/flow rows、expandable technical detail、desktop/mobile screenshot smoke。",
        "current_state": "AwoooP 已有插入需求工作項面板；仍需把長文區塊持續收斂成可掃描 cockpit。",
        "acceptance": "desktop/mobile 第一視窗看得到狀態、優先序、下一步與證據；細節可展開但不形成文字牆。",
        "next_action": "針對 AwoooP / governance / OpenClaw live ops 做 visual smoke 與長文字區塊收斂。",
        "mapped_workplan_id": "P2-UX",
    },
    {
        "id": "CIR-P3-001",
        "priority": "P3",
        "order": 44,
        "status": "deferred",
        "lane": "github_future_recovery",
        "request": "GitHub appeal 後的未來恢復。",
        "normalized_work_item": "只有未來明確要求恢復 GitHub，才先做風險評估與人工確認。",
        "current_state": "等待外部狀態；freeze 仍有效。",
        "acceptance": "未確認前不做任何 GitHub 操作。",
        "next_action": "維持 stopped / do_not_use。",
        "mapped_workplan_id": "P0-003A",
    },
    {
        "id": "CIR-P3-NON-001",
        "priority": "P3",
        "order": 45,
        "status": "deferred",
        "lane": "non_awoooi_personal_note",
        "request": "隱形鐵窗 + 防霾捲紗（陽台最推薦）。",
        "normalized_work_item": "此插入內容已記錄為非 AWOOOI 產品/AI 自動化主線事項，不拿來改變 P0/P1 排序。",
        "current_state": "已歸檔為非產品主線 note，避免被誤當 AWOOOI 實作項。",
        "acceptance": "work-order 可見但 deferred，不阻擋 AWOOOI AI Loop Agent 主線。",
        "next_action": "不執行，除非使用者明確切換到家裝/陽台需求。",
        "mapped_workplan_id": "NON-AWOOOI",
    },
]


def load_latest_awoooi_priority_work_order_readback(
    operations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load and validate the committed AWOOOI priority work-order snapshot."""
    directory = operations_dir or _DEFAULT_OPERATIONS_DIR
    path = directory / _SNAPSHOT_FILE
    with path.open(encoding="utf-8") as handle:
        payload = json.load(handle)

    if not isinstance(payload, dict):
        raise ValueError(f"{path}: expected JSON object")
    _require_schema(payload, str(path))
    _require_operation_boundaries(payload, str(path))
    _require_mainline_consistency(payload, str(path))
    _enrich_from_current_readbacks(payload)
    _require_mainline_consistency(payload, str(path))
    _apply_commander_inserted_requirement_work_items(payload)
    _mark_runtime_generated_at(payload)
    apply_ai_automation_node_receipts(payload)
    return payload


def load_controlled_cd_lane_live_metric_readback(
    metrics_url: str = _CONTROLLED_CD_LANE_NODE_EXPORTER_URL,
    prometheus_query_url: str = _CONTROLLED_CD_LANE_PROMETHEUS_QUERY_URL,
    timeout_seconds: float = 3.0,
) -> dict[str, Any]:
    """Read 110 node_exporter text metrics for the controlled CD lane.

    This is a read-only HTTP metrics probe. It does not SSH, read runner
    registration contents, touch Docker/systemd, or perform runtime writes.
    """
    source = "node_exporter_text_metrics"
    error_class = ""
    try:
        request = urllib.request.Request(metrics_url, method="GET")
        with urllib.request.urlopen(request, timeout=timeout_seconds) as response:
            raw = response.read(2_000_000).decode("utf-8", errors="replace")
        metrics = _parse_prometheus_text_metrics(raw)
    except (OSError, TimeoutError, urllib.error.URLError) as exc:
        metrics, fallback_error_class = _load_prometheus_query_metrics(
            prometheus_query_url,
            timeout_seconds=timeout_seconds,
        )
        if fallback_error_class:
            return {
                "schema_version": _CONTROLLED_CD_LANE_LIVE_METRIC_SCHEMA_VERSION,
                "status": "controlled_cd_lane_live_metric_unavailable",
                "source": "node_exporter_text_metrics",
                "fallback_source": "prometheus_query_api",
                "metadata_only": True,
                "active_blockers": ["controlled_cd_lane_live_metric_unavailable"],
                "error_class": exc.__class__.__name__,
                "fallback_error_class": fallback_error_class,
                "readback": {
                    "enforcer_metric_present": False,
                    "controlled_drain_active_allowed": False,
                    "controlled_drain_staging_allowed": False,
                    "enforcer_last_run_fresh": False,
                },
            }
        source = "prometheus_query_api"
        error_class = exc.__class__.__name__

    readback = _build_controlled_cd_lane_metric_readback(metrics)
    active_blockers: list[str] = []
    if not readback["enforcer_metric_present"]:
        active_blockers.append("controlled_cd_lane_enforcer_metric_missing")
    if not readback["enforcer_last_run_fresh"]:
        active_blockers.append("controlled_cd_lane_enforcer_metric_stale")
    if not readback["controlled_drain_active_allowed"]:
        active_blockers.append("controlled_cd_lane_active_not_allowed_yet")
    if not readback["controlled_drain_staging_allowed"]:
        active_blockers.append("controlled_cd_lane_staging_not_allowed_yet")

    return {
        "schema_version": _CONTROLLED_CD_LANE_LIVE_METRIC_SCHEMA_VERSION,
        "status": (
            "controlled_cd_lane_live_metric_readback_ready"
            if readback["enforcer_metric_present"]
            else "controlled_cd_lane_live_metric_missing"
        ),
        "source": source,
        "metadata_only": True,
        "primary_error_class": error_class or None,
        "active_blockers": active_blockers,
        "readback": readback,
    }


def apply_controlled_cd_lane_live_metric_readback(
    payload: dict[str, Any],
    live_metric_readback: dict[str, Any],
) -> None:
    """Overlay live controlled CD lane metric truth onto P0-006 readback."""
    readback = _dict(live_metric_readback.get("readback"))
    state = _dict(payload.setdefault("mainline_execution_state", {}))
    active_blockers = _strings(live_metric_readback.get("active_blockers"))

    metric_fields = {
        "controlled_cd_lane_live_metric_status": str(
            live_metric_readback.get("status") or "unknown"
        ),
        "controlled_cd_lane_live_metric_source": str(
            live_metric_readback.get("source") or "node_exporter_text_metrics"
        ),
        "controlled_cd_lane_live_metric_metadata_only": bool(
            live_metric_readback.get("metadata_only") is True
        ),
        "controlled_cd_lane_live_enforcer_metric_present": bool(
            readback.get("enforcer_metric_present") is True
        ),
        "controlled_cd_lane_live_enforcer_last_run_timestamp": _float(
            readback.get("enforcer_last_run_timestamp")
        ),
        "controlled_cd_lane_live_enforcer_last_run_fresh": bool(
            readback.get("enforcer_last_run_fresh") is True
        ),
        "controlled_cd_lane_live_enforcer_apply_performed": _int(
            readback.get("enforcer_apply_performed")
        ),
        "controlled_cd_lane_live_active_job_containers": _int(
            readback.get("active_job_containers")
        ),
        "controlled_cd_lane_live_lane_process_count": _int(
            readback.get("lane_process_count")
        ),
        "controlled_cd_lane_live_root_restore_sources_left": _int(
            readback.get("root_restore_sources_left")
        ),
        "controlled_cd_lane_live_controlled_drain_active_allowed": bool(
            readback.get("controlled_drain_active_allowed") is True
        ),
        "controlled_cd_lane_live_controlled_drain_staging_allowed": bool(
            readback.get("controlled_drain_staging_allowed") is True
        ),
        "controlled_cd_lane_live_host_load5_per_core": _float(
            readback.get("host_load5_per_core")
        ),
        "controlled_cd_lane_live_gitea_actions_active_container_count": _int(
            readback.get("gitea_actions_active_container_count")
        ),
        "controlled_cd_lane_live_gitea_actions_active_process_count": _int(
            readback.get("gitea_actions_active_process_count")
        ),
        "controlled_cd_lane_live_metric_blockers": active_blockers,
    }
    state.update(metric_fields)

    rollups = _dict(payload.setdefault("rollups", {}))
    rollups.update(metric_fields)
    rollups["controlled_cd_lane_live_metric_blocker_count"] = len(active_blockers)

    summary = _dict(payload.setdefault("summary", {}))
    summary.update(metric_fields)
    summary["controlled_cd_lane_live_metric_blocker_count"] = len(active_blockers)

    for item in _list(payload.get("in_progress_or_blocked_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-006":
            continue
        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence.update(metric_fields)
        evidence["controlled_cd_lane_live_metric_blocker_count"] = len(
            active_blockers
        )

    _mark_runtime_generated_at(payload)
    apply_ai_automation_node_receipts(payload)


def apply_stockplatform_public_api_runtime_readback(
    payload: dict[str, Any],
    runtime_readback: dict[str, Any],
) -> None:
    """Overlay live StockPlatform public API truth onto the priority readback."""
    runtime_ready = runtime_readback.get("status") == (
        "stockplatform_public_api_runtime_ready"
    )
    runtime_blockers = _strings(runtime_readback.get("active_blockers"))
    runtime_rollups = _dict(runtime_readback.get("rollups"))
    runtime_readback_body = _dict(runtime_readback.get("readback"))
    data_readiness_readback = _dict(
        runtime_readback.get("data_readiness_control_readback")
    )
    source_contract_readback = _dict(
        runtime_readback.get("source_contract_control_readback")
    )
    data_dependency_classification = str(
        runtime_rollups.get("data_dependency_classification")
        or runtime_readback_body.get("data_dependency_classification")
        or "none"
    )
    postgres_not_ready = bool(
        runtime_rollups.get("postgres_not_ready") is True
        or runtime_readback_body.get("postgres_not_ready") is True
        or data_dependency_classification == "postgres_not_ready"
    )
    recovery_control_path = _dict(runtime_readback.get("recovery_control_path"))
    recovery_control_path_status = str(
        recovery_control_path.get("status") or "unknown"
    )
    recovery_control_path_blockers = _strings(
        recovery_control_path.get("active_blockers")
    )

    state = _dict(payload.setdefault("mainline_execution_state", {}))
    state["stockplatform_public_api_runtime_status"] = str(
        runtime_readback.get("status") or "unknown"
    )
    state["stockplatform_public_api_live_readback_state"] = (
        "ready" if runtime_ready else "blocked"
    )
    state["stockplatform_public_api_active_blockers"] = runtime_blockers
    state["stockplatform_public_api_live_drift_from_committed_scorecard"] = bool(
        runtime_readback.get("live_drift_from_committed_scorecard") is True
    )
    state["stockplatform_public_api_recovery_control_path_status"] = (
        recovery_control_path_status
    )
    state["stockplatform_public_api_recovery_control_path_active_blockers"] = (
        recovery_control_path_blockers
    )
    state["stockplatform_public_api_data_dependency_classification"] = (
        data_dependency_classification
    )
    state["stockplatform_freshness_status"] = str(
        runtime_readback_body.get("freshness_status") or "unknown"
    )
    state["stockplatform_ingestion_status"] = str(
        runtime_readback_body.get("ingestion_status") or "unknown"
    )
    state["stockplatform_latest_trading_date"] = str(
        runtime_readback_body.get("freshness_latest_trading_date") or ""
    )
    state["stockplatform_freshness_blockers"] = _strings(
        runtime_readback_body.get("freshness_blockers")
    )
    state["stockplatform_ingestion_blockers"] = _strings(
        runtime_readback_body.get("ingestion_blockers")
    )
    state["stockplatform_freshness_sla_source_count"] = _int(
        runtime_readback_body.get("freshness_sla_source_count")
    )
    state["stockplatform_freshness_source_count"] = _int(
        runtime_readback_body.get("freshness_source_count")
    )
    state["stockplatform_freshness_non_ok_source_count"] = _int(
        runtime_readback_body.get("freshness_non_ok_source_count")
    )
    state["stockplatform_public_api_postgres_not_ready"] = postgres_not_ready
    state["stockplatform_postgres_readiness_or_data_source_readback_status"] = str(
        data_readiness_readback.get("status") or "unknown"
    )
    state["stockplatform_postgres_readiness_or_data_source_readback_present"] = bool(
        data_readiness_readback.get("readback_present") is True
    )
    state["stockplatform_postgres_readiness_or_data_source_receipt_provided"] = bool(
        data_readiness_readback.get("receipt_provided") is True
    )
    state["stockplatform_postgres_readiness_or_data_source_postgres_ready"] = bool(
        data_readiness_readback.get("postgres_ready") is True
    )
    state["stockplatform_source_contract_readback_status"] = str(
        source_contract_readback.get("status") or "unknown"
    )
    state["stockplatform_source_contract_readback_present"] = bool(
        source_contract_readback.get("readback_present") is True
    )
    state["stockplatform_source_contract_receipt_provided"] = bool(
        source_contract_readback.get("receipt_provided") is True
    )
    state["stockplatform_source_contract_ready"] = bool(
        source_contract_readback.get("source_contract_ready") is True
    )
    state["stockplatform_source_contract_non_ok_source_count"] = _int(
        source_contract_readback.get("non_ok_source_count")
    )
    state["stockplatform_source_contract_blocking_sources"] = _list(
        source_contract_readback.get("blocking_sources")
    )

    for item in _list(payload.get("in_progress_or_blocked_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-006":
            continue
        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence["stockplatform_public_api_runtime_status"] = state[
            "stockplatform_public_api_runtime_status"
        ]
        evidence["stockplatform_public_api_runtime_ready"] = runtime_ready
        evidence["stockplatform_public_api_active_blockers"] = runtime_blockers
        evidence["stockplatform_public_api_http_502_count"] = _int(
            runtime_rollups.get("http_502_count")
        )
        evidence["stockplatform_public_api_live_drift_from_committed_scorecard"] = (
            state["stockplatform_public_api_live_drift_from_committed_scorecard"]
        )
        evidence["stockplatform_public_api_health_http_status"] = (
            runtime_readback_body.get("api_health_http_status")
        )
        evidence["stockplatform_freshness_http_status"] = (
            runtime_readback_body.get("freshness_http_status")
        )
        evidence["stockplatform_ingestion_http_status"] = (
            runtime_readback_body.get("ingestion_http_status")
        )
        evidence["stockplatform_data_dependency_classification"] = (
            data_dependency_classification
        )
        evidence["stockplatform_freshness_status"] = state[
            "stockplatform_freshness_status"
        ]
        evidence["stockplatform_ingestion_status"] = state[
            "stockplatform_ingestion_status"
        ]
        evidence["stock_latest_trading_date"] = state[
            "stockplatform_latest_trading_date"
        ]
        evidence["stock_blockers"] = state["stockplatform_freshness_blockers"]
        evidence["stock_ingestion_blockers"] = state[
            "stockplatform_ingestion_blockers"
        ]
        evidence["stockplatform_freshness_sla_source_count"] = state[
            "stockplatform_freshness_sla_source_count"
        ]
        evidence["stockplatform_freshness_source_count"] = state[
            "stockplatform_freshness_source_count"
        ]
        evidence["stockplatform_freshness_non_ok_source_count"] = state[
            "stockplatform_freshness_non_ok_source_count"
        ]
        evidence["stockplatform_postgres_not_ready"] = postgres_not_ready
        evidence[
            "stockplatform_postgres_readiness_or_data_source_readback_status"
        ] = state["stockplatform_postgres_readiness_or_data_source_readback_status"]
        evidence[
            "stockplatform_postgres_readiness_or_data_source_readback_present"
        ] = state["stockplatform_postgres_readiness_or_data_source_readback_present"]
        evidence[
            "stockplatform_postgres_readiness_or_data_source_receipt_provided"
        ] = state["stockplatform_postgres_readiness_or_data_source_receipt_provided"]
        evidence[
            "stockplatform_postgres_readiness_or_data_source_postgres_ready"
        ] = state["stockplatform_postgres_readiness_or_data_source_postgres_ready"]
        evidence["stockplatform_source_contract_readback_status"] = state[
            "stockplatform_source_contract_readback_status"
        ]
        evidence["stockplatform_source_contract_readback_present"] = state[
            "stockplatform_source_contract_readback_present"
        ]
        evidence["stockplatform_source_contract_receipt_provided"] = state[
            "stockplatform_source_contract_receipt_provided"
        ]
        evidence["stockplatform_source_contract_ready"] = state[
            "stockplatform_source_contract_ready"
        ]
        evidence["stockplatform_source_contract_non_ok_source_count"] = state[
            "stockplatform_source_contract_non_ok_source_count"
        ]
        evidence["stockplatform_source_contract_blocking_sources"] = state[
            "stockplatform_source_contract_blocking_sources"
        ]
        evidence["stockplatform_recovery_control_path_status"] = (
            recovery_control_path_status
        )
        evidence["stockplatform_recovery_control_path_active_blockers"] = (
            recovery_control_path_blockers
        )

        if runtime_ready:
            continue

        workplan["status"] = "blocked_stockplatform_public_api_runtime_drift"
        workplan["safe_next_step"] = str(
            runtime_readback.get("safe_next_step") or ""
        )
        workplan["reason"] = (
            _stockplatform_runtime_drift_reason(
                data_dependency_classification=data_dependency_classification,
                postgres_not_ready=postgres_not_ready,
            )
        )
        professional_fix = _dict(workplan.setdefault("professional_fix", {}))
        professional_fix["action"] = (
            _stockplatform_runtime_drift_action(
                data_dependency_classification=data_dependency_classification,
                postgres_not_ready=postgres_not_ready,
            )
        )
        professional_fix["owner"] = (
            "stockplatform public API runtime readback plus P0-006 reboot SLO lane"
        )

    if runtime_ready:
        _refresh_rollups_after_stockplatform_overlay(payload, state)
        return

    existing_blockers = _strings(state.get("active_p0_live_active_blockers"))
    state["active_p0_live_active_blockers"] = _unique_strings(
        existing_blockers
        + ["stockplatform_public_api_runtime_drift"]
        + runtime_blockers
        + recovery_control_path_blockers
    )
    state["active_p0_state"] = "blocked_stockplatform_public_api_runtime_drift"
    state["next_executable_mainline_workplan_id"] = (
        "P0-006-STOCKPLATFORM-PUBLIC-API-RUNTIME-READBACK"
    )
    state["next_executable_mainline_state"] = (
        _stockplatform_runtime_next_state(
            data_dependency_classification=data_dependency_classification,
            postgres_not_ready=postgres_not_ready,
        )
    )
    payload["status"] = "p0_006_blocked_stockplatform_public_api_runtime_drift"
    payload["next_execution_order"] = [
        _stockplatform_runtime_first_order(
            data_dependency_classification=data_dependency_classification,
            postgres_not_ready=postgres_not_ready,
        ),
        (
            "P0-006-STOCKPLATFORM-RECOVERY-CONTROL-PATH-RECEIPT: provide "
            "target selector, check-mode/dry-run, rollback, post-apply "
            "public API verifier, and KM/PlayBook/LOG writeback receipt before "
            "any runtime apply."
        ),
        (
            "P0-006: keep reboot SLO timer live, but do not claim final SLO "
            "closure while StockPlatform public API readback is blocked."
        ),
        (
            "P0-006-REBOOT-DRILL-PREFLIGHT-READBACK: preflight remains ready, "
            "but reboot remains break-glass and is not authorized by this lane."
        ),
        (
            "NEXT: after StockPlatform public API readback is green or a "
            "separate hard-blocker handoff is recorded, resume the next "
            "blocker-free priority item."
        ),
    ]
    _refresh_rollups_after_stockplatform_overlay(payload, state)


def apply_stockplatform_public_api_controlled_recovery_preflight(
    payload: dict[str, Any],
    recovery_preflight: dict[str, Any],
) -> None:
    """Overlay the packaged StockPlatform controlled recovery preflight."""
    status = str(recovery_preflight.get("status") or "unknown")
    if status == "stockplatform_public_api_recovery_preflight_not_required":
        return

    state = _dict(payload.setdefault("mainline_execution_state", {}))
    rollups = _dict(recovery_preflight.get("rollups"))
    source_diff = _dict(recovery_preflight.get("source_of_truth_diff"))
    target_selector = _dict(recovery_preflight.get("target_selector"))
    controlled_policy = _dict(recovery_preflight.get("controlled_apply_policy"))
    data_readiness_readback = _dict(
        recovery_preflight.get("data_readiness_control_readback")
    )
    source_contract_readback = _dict(
        recovery_preflight.get("source_contract_control_readback")
    )
    candidate_packaged = bool(
        rollups.get("controlled_recovery_candidate_packaged") is True
    )
    api_layer = str(
        recovery_preflight.get("api_layer_classification") or "unknown"
    )
    data_dependency_classification = str(
        recovery_preflight.get("data_dependency_classification") or "none"
    )

    state["stockplatform_public_api_controlled_recovery_preflight_status"] = status
    state["stockplatform_public_api_controlled_recovery_api_layer"] = api_layer
    state["stockplatform_public_api_controlled_recovery_data_dependency"] = (
        data_dependency_classification
    )
    state["stockplatform_postgres_readiness_or_data_source_readback_status"] = str(
        data_readiness_readback.get("status") or "unknown"
    )
    state["stockplatform_postgres_readiness_or_data_source_readback_present"] = bool(
        data_readiness_readback.get("readback_present") is True
    )
    state["stockplatform_postgres_readiness_or_data_source_receipt_provided"] = bool(
        data_readiness_readback.get("receipt_provided") is True
    )
    state["stockplatform_postgres_readiness_or_data_source_postgres_ready"] = bool(
        data_readiness_readback.get("postgres_ready") is True
    )
    state["stockplatform_source_contract_readback_status"] = str(
        source_contract_readback.get("status") or "unknown"
    )
    state["stockplatform_source_contract_readback_present"] = bool(
        source_contract_readback.get("readback_present") is True
    )
    state["stockplatform_source_contract_receipt_provided"] = bool(
        source_contract_readback.get("receipt_provided") is True
    )
    state["stockplatform_source_contract_ready"] = bool(
        source_contract_readback.get("source_contract_ready") is True
    )
    state["stockplatform_source_contract_non_ok_source_count"] = _int(
        source_contract_readback.get("non_ok_source_count")
    )
    state["stockplatform_source_contract_blocking_sources"] = _list(
        source_contract_readback.get("blocking_sources")
    )
    state["stockplatform_public_api_controlled_recovery_active_blockers"] = _strings(
        recovery_preflight.get("active_blockers")
    )
    state["active_p0_state"] = (
        "blocked_stockplatform_public_api_controlled_recovery_preflight"
    )
    state["next_executable_mainline_workplan_id"] = (
        "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT"
    )
    state["next_executable_mainline_state"] = _stockplatform_recovery_next_state(
        candidate_packaged=candidate_packaged,
        api_layer=api_layer,
        data_dependency_classification=data_dependency_classification,
    )

    existing_blockers = _strings(state.get("active_p0_live_active_blockers"))
    state["active_p0_live_active_blockers"] = _unique_strings(
        existing_blockers
        + ["stockplatform_public_api_controlled_recovery_preflight"]
        + _strings(recovery_preflight.get("active_blockers"))
    )

    for item in _list(payload.get("in_progress_or_blocked_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-006":
            continue

        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence["stockplatform_controlled_recovery_preflight_status"] = status
        evidence["stockplatform_controlled_recovery_api_layer"] = state[
            "stockplatform_public_api_controlled_recovery_api_layer"
        ]
        evidence["stockplatform_controlled_recovery_data_dependency"] = (
            data_dependency_classification
        )
        evidence["stockplatform_route_target_ready"] = bool(
            target_selector.get("route_target_ready") is True
        )
        evidence["stockplatform_source_of_truth_diff_status"] = str(
            source_diff.get("status") or ""
        )
        evidence[
            "stockplatform_postgres_readiness_or_data_source_readback_status"
        ] = state["stockplatform_postgres_readiness_or_data_source_readback_status"]
        evidence[
            "stockplatform_postgres_readiness_or_data_source_readback_present"
        ] = state["stockplatform_postgres_readiness_or_data_source_readback_present"]
        evidence[
            "stockplatform_postgres_readiness_or_data_source_receipt_provided"
        ] = state["stockplatform_postgres_readiness_or_data_source_receipt_provided"]
        evidence[
            "stockplatform_postgres_readiness_or_data_source_postgres_ready"
        ] = state["stockplatform_postgres_readiness_or_data_source_postgres_ready"]
        evidence["stockplatform_source_contract_readback_status"] = state[
            "stockplatform_source_contract_readback_status"
        ]
        evidence["stockplatform_source_contract_readback_present"] = state[
            "stockplatform_source_contract_readback_present"
        ]
        evidence["stockplatform_source_contract_receipt_provided"] = state[
            "stockplatform_source_contract_receipt_provided"
        ]
        evidence["stockplatform_source_contract_ready"] = state[
            "stockplatform_source_contract_ready"
        ]
        evidence["stockplatform_source_contract_non_ok_source_count"] = state[
            "stockplatform_source_contract_non_ok_source_count"
        ]
        evidence["stockplatform_source_contract_blocking_sources"] = state[
            "stockplatform_source_contract_blocking_sources"
        ]
        evidence["stockplatform_controlled_recovery_candidate_packaged"] = (
            candidate_packaged
        )
        evidence["stockplatform_host_control_path_readback_required"] = bool(
            rollups.get("host_control_path_readback_required") is True
        )
        evidence["stockplatform_controlled_work_item_count"] = _int(
            rollups.get("controlled_work_item_count")
        )
        evidence["stockplatform_post_apply_verifier_count"] = _int(
            rollups.get("post_apply_verifier_count")
        )
        evidence["stockplatform_learning_writeback_contract_count"] = _int(
            rollups.get("learning_writeback_contract_count")
        )
        evidence["stockplatform_current_apply_allowed"] = bool(
            controlled_policy.get("current_apply_allowed") is True
        )
        evidence["stockplatform_runtime_write_gate"] = str(
            controlled_policy.get("runtime_write_gate") or ""
        )

        workplan["status"] = (
            "blocked_stockplatform_public_api_controlled_recovery_preflight"
        )
        workplan["safe_next_step"] = str(
            recovery_preflight.get("safe_next_step") or ""
        )
        workplan["reason"] = (
            _stockplatform_recovery_reason(
                candidate_packaged=candidate_packaged,
                api_layer=api_layer,
                data_dependency_classification=data_dependency_classification,
            )
        )
        professional_fix = _dict(workplan.setdefault("professional_fix", {}))
        professional_fix["action"] = _stockplatform_recovery_action(
            api_layer=api_layer,
            data_dependency_classification=data_dependency_classification,
        )
        professional_fix["owner"] = (
            "StockPlatform API controlled recovery preflight plus P0-006 "
            "priority readback"
        )

    payload["status"] = (
        "p0_006_blocked_stockplatform_public_api_controlled_recovery_preflight"
    )
    payload["next_execution_order"] = [
        _stockplatform_recovery_first_order(
            api_layer=api_layer,
            data_dependency_classification=data_dependency_classification,
        ),
        (
            "P0-006-STOCKPLATFORM-PUBLIC-API-RUNTIME-READBACK: rerun public "
            "health/freshness/ingestion after the bounded reconcile candidate; "
            "public API must be green before returning to reboot-window proof."
        ),
        (
            "P0-006: keep reboot SLO timer live, but do not claim final SLO "
            "closure while StockPlatform public API readback is blocked."
        ),
        (
            "NEXT: after StockPlatform public API readback is green or a "
            "separate hard-blocker handoff is recorded, resume the next "
            "blocker-free priority item."
        ),
    ]
    _refresh_rollups_after_stockplatform_overlay(payload, state)
    summary = _dict(payload.setdefault("summary", {}))
    summary["stockplatform_public_api_controlled_recovery_preflight_status"] = status
    summary["stockplatform_public_api_controlled_recovery_api_layer"] = str(
        recovery_preflight.get("api_layer_classification") or "unknown"
    )
    summary["stockplatform_public_api_controlled_recovery_data_dependency"] = (
        data_dependency_classification
    )
    summary["stockplatform_public_api_controlled_recovery_candidate_packaged"] = bool(
        candidate_packaged
    )
    summary["stockplatform_public_api_host_control_path_readback_required"] = bool(
        rollups.get("host_control_path_readback_required") is True
    )
    summary["stockplatform_postgres_readiness_or_data_source_readback_status"] = str(
        state.get("stockplatform_postgres_readiness_or_data_source_readback_status")
        or "unknown"
    )
    summary["stockplatform_postgres_readiness_or_data_source_receipt_provided"] = bool(
        state.get("stockplatform_postgres_readiness_or_data_source_receipt_provided")
        is True
    )
    summary["stockplatform_source_contract_readback_status"] = str(
        state.get("stockplatform_source_contract_readback_status") or "unknown"
    )
    summary["stockplatform_source_contract_receipt_provided"] = bool(
        state.get("stockplatform_source_contract_receipt_provided") is True
    )
    summary["stockplatform_source_contract_non_ok_source_count"] = _int(
        state.get("stockplatform_source_contract_non_ok_source_count")
    )


def apply_harbor_registry_controlled_recovery_preflight(
    payload: dict[str, Any],
    recovery_preflight: dict[str, Any],
) -> None:
    """Overlay the packaged Harbor registry recovery preflight."""
    status = str(recovery_preflight.get("status") or "unknown")
    if status == "harbor_registry_ready":
        return

    state = _dict(payload.setdefault("mainline_execution_state", {}))
    rollups = _dict(recovery_preflight.get("rollups"))
    controlled_policy = _dict(recovery_preflight.get("controlled_apply_policy"))
    candidate_packaged = bool(
        rollups.get("controlled_recovery_candidate_packaged") is True
    )

    state["harbor_registry_controlled_recovery_preflight_status"] = status
    state["harbor_registry_controlled_recovery_active_blockers"] = _strings(
        recovery_preflight.get("active_blockers")
    )
    state["harbor_registry_controlled_recovery_candidate_packaged"] = (
        candidate_packaged
    )
    state["active_p0_state"] = "blocked_harbor_registry_controlled_recovery_preflight"
    state["next_executable_mainline_workplan_id"] = (
        "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT"
    )
    state["next_executable_mainline_state"] = _harbor_registry_next_state(
        status=status,
        candidate_packaged=candidate_packaged,
    )
    state["active_p0_live_active_blockers"] = _unique_strings(
        _strings(state.get("active_p0_live_active_blockers"))
        + ["harbor_registry_controlled_recovery_preflight"]
        + _strings(recovery_preflight.get("active_blockers"))
    )

    for item in _list(payload.get("in_progress_or_blocked_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-006":
            continue

        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence["harbor_registry_controlled_recovery_preflight_status"] = status
        evidence["harbor_registry_controlled_recovery_candidate_packaged"] = (
            candidate_packaged
        )
        evidence["harbor_registry_public_v2_ready"] = bool(
            rollups.get("public_registry_v2_ready") is True
        )
        evidence["harbor_registry_internal_v2_ready"] = bool(
            rollups.get("internal_110_registry_v2_ready") is True
        )
        evidence["harbor_registry_upstream_502_shape"] = bool(
            rollups.get("harbor_registry_upstream_502_shape") is True
        )
        evidence["harbor_registry_public_gateway_route_drift_shape"] = bool(
            rollups.get("public_gateway_route_drift_shape") is True
        )
        evidence["harbor_registry_watchdog_executor_ready"] = bool(
            rollups.get("watchdog_executor_ready") is True
        )
        evidence["harbor_registry_control_channel_readback_required"] = bool(
            rollups.get("control_channel_readback_required") is True
        )
        evidence["harbor_registry_awoooi_host_runner_required"] = bool(
            rollups.get("awoooi_host_runner_required") is True
        )
        evidence["harbor_registry_ssh_publickey_diagnosis_required"] = bool(
            rollups.get("ssh_publickey_diagnosis_required") is True
        )
        evidence["harbor_registry_controlled_work_item_count"] = _int(
            rollups.get("controlled_work_item_count")
        )
        evidence["harbor_registry_post_apply_verifier_count"] = _int(
            rollups.get("post_apply_verifier_count")
        )
        evidence["harbor_registry_learning_writeback_contract_count"] = _int(
            rollups.get("learning_writeback_contract_count")
        )
        evidence["harbor_registry_current_apply_allowed"] = bool(
            controlled_policy.get("current_apply_allowed") is True
        )
        evidence["harbor_registry_runtime_write_gate"] = str(
            controlled_policy.get("runtime_write_gate") or ""
        )

        workplan["status"] = "blocked_harbor_registry_controlled_recovery_preflight"
        workplan["safe_next_step"] = str(
            recovery_preflight.get("safe_next_step") or ""
        )
        workplan["reason"] = _harbor_registry_reason(
            status=status,
            candidate_packaged=candidate_packaged,
        )
        professional_fix = _dict(workplan.setdefault("professional_fix", {}))
        professional_fix["action"] = _harbor_registry_action(status=status)
        professional_fix["owner"] = (
            "Harbor registry controlled recovery preflight plus P0-006 deploy "
            "closure lane"
        )

    payload["status"] = "p0_006_blocked_harbor_registry_controlled_recovery_preflight"
    payload["next_execution_order"] = [
        _harbor_registry_first_order(status=status),
        (
            "P0-006-CD-DEPLOY-MARKER-READBACK: after registry /v2/ is 200/401, "
            "let the next Gitea CD run build/push/deploy and then verify "
            "delivery-closure-workbench, priority work order, and production "
            "marker advance."
        ),
        (
            "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT: "
            "resume StockPlatform API/data dependency recovery only after the "
            "AWOOOI API deploy marker can advance through Harbor."
        ),
        (
            "P0-006: keep reboot SLO timer live, but do not claim final SLO "
            "closure while deploy marker and StockPlatform readback are blocked."
        ),
    ]
    _refresh_rollups_after_stockplatform_overlay(payload, state)
    summary = _dict(payload.setdefault("summary", {}))
    summary["harbor_registry_controlled_recovery_preflight_status"] = status
    summary["harbor_registry_controlled_recovery_candidate_packaged"] = (
        candidate_packaged
    )
    summary["harbor_registry_public_v2_ready"] = bool(
        rollups.get("public_registry_v2_ready") is True
    )
    summary["harbor_registry_internal_v2_ready"] = bool(
        rollups.get("internal_110_registry_v2_ready") is True
    )
    summary["harbor_registry_watchdog_executor_ready"] = bool(
        rollups.get("watchdog_executor_ready") is True
    )
    summary["harbor_registry_control_channel_readback_required"] = bool(
        rollups.get("control_channel_readback_required") is True
    )
    summary["harbor_registry_awoooi_host_runner_required"] = bool(
        rollups.get("awoooi_host_runner_required") is True
    )
    summary["harbor_registry_ssh_publickey_diagnosis_required"] = bool(
        rollups.get("ssh_publickey_diagnosis_required") is True
    )


def apply_ai_loop_current_blocker_execution_queue(
    payload: dict[str, Any],
    executor_readback: dict[str, Any],
) -> None:
    """Overlay the AI Loop current blocker queue onto the ordered work board."""
    context = _dict(executor_readback.get("agent_consumption_context"))
    queue = list(_list(context.get("current_blocker_execution_queue")))
    if not queue:
        return

    first_item = _dict(queue[0])
    blocker_id = str(first_item.get("blocker_id") or "")
    registry_v2_ready = bool(first_item.get("registry_v2_ready") is True)
    registry_v2_status_classifier = str(
        first_item.get("registry_v2_status_classifier") or ""
    )
    deployment_closure_state = str(first_item.get("deployment_closure_state") or "")
    deploy_marker_readback_required = bool(
        first_item.get("deploy_marker_readback_required") is True
    )
    current_cd_run_id = str(first_item.get("current_cd_run_id") or "")
    current_cd_run_status = str(first_item.get("current_cd_run_status") or "")
    current_cd_commit_sha = str(first_item.get("current_cd_commit_sha") or "")
    cd_failed_after_registry_ready = bool(
        first_item.get("cd_failed_after_registry_ready") is True
    )
    harbor_110_repair_run_id = str(first_item.get("harbor_110_repair_run_id") or "")
    harbor_110_repair_run_status = str(
        first_item.get("harbor_110_repair_run_status") or ""
    )
    harbor_110_repair_failure_classifier = str(
        first_item.get("harbor_110_repair_failure_classifier") or ""
    )
    harbor_110_repair_failed_after_registry_ready = bool(
        first_item.get("harbor_110_repair_failed_after_registry_ready") is True
    )
    external_blocker = str(first_item.get("external_control_path_blocker") or "")
    pressure_blocker = str(first_item.get("control_path_pressure_blocker") or "")
    node_load_classifier = str(first_item.get("node_load_classifier") or "")

    state = _dict(payload.setdefault("mainline_execution_state", {}))
    current_head = _dict(payload.get("current_head"))
    production_readback_verified = bool(
        state.get("current_main_cd_run_status") == "production_readback_verified"
        and current_head.get("production_source_truth_available") is True
        and _is_sha(str(state.get("latest_successful_deployed_source_sha") or ""))
    )
    deploy_marker_resolved_by_production_readback = bool(
        production_readback_verified
        and (deploy_marker_readback_required or cd_failed_after_registry_ready)
    )
    controlled_cd_lane_guardrails_resolved_by_production_readback = bool(
        production_readback_verified
        and blocker_id == "controlled_cd_lane_guardrails_blocked"
        and registry_v2_ready
    )
    queue_resolved_by_production_readback = bool(
        production_readback_verified
        and registry_v2_ready
        and (
            deploy_marker_readback_required
            or cd_failed_after_registry_ready
            or harbor_110_repair_failed_after_registry_ready
            or controlled_cd_lane_guardrails_resolved_by_production_readback
        )
    )
    if queue_resolved_by_production_readback:
        _record_ai_loop_current_blocker_production_resolution(
            payload=payload,
            state=state,
            queue_count=len(queue),
            blocker_id=blocker_id,
            registry_v2_ready=registry_v2_ready,
            registry_v2_status_classifier=registry_v2_status_classifier,
            deployment_closure_state=deployment_closure_state,
            deploy_marker_readback_required=deploy_marker_readback_required,
            current_cd_run_id=current_cd_run_id,
            current_cd_run_status=current_cd_run_status,
            current_cd_commit_sha=current_cd_commit_sha,
            cd_failed_after_registry_ready=cd_failed_after_registry_ready,
            harbor_110_repair_run_id=harbor_110_repair_run_id,
            harbor_110_repair_run_status=harbor_110_repair_run_status,
            harbor_110_repair_failure_classifier=(
                harbor_110_repair_failure_classifier
            ),
            harbor_110_repair_failed_after_registry_ready=(
                harbor_110_repair_failed_after_registry_ready
            ),
            external_blocker=external_blocker,
            pressure_blocker=pressure_blocker,
            node_load_classifier=node_load_classifier,
        )
        apply_ai_automation_node_receipts(payload)
        return

    if not _ai_loop_current_blocker_can_override(
        status=str(payload.get("status") or ""),
        blocker_id=blocker_id,
        queue_item=first_item,
    ):
        return

    controlled_recovery_package = str(
        first_item.get("controlled_recovery_package") or ""
    )
    post_apply_verifier = str(first_item.get("post_apply_verifier") or "")
    learning_targets = _strings(first_item.get("learning_writeback_targets"))
    target_batches = _strings(first_item.get("target_batches"))
    local_console_plan = [
        _dict(item)
        for item in _list(first_item.get("controlled_local_console_execution_plan"))
    ]
    local_console_phase_ids = [
        str(item.get("phase_id") or "")
        for item in local_console_plan
        if item.get("phase_id")
    ]
    post_recovery_readback_commands = _strings(
        first_item.get("post_recovery_readback_commands")
    )
    harbor_recovery_receipt_inputs = [
        _dict(item)
        for item in _list(first_item.get("harbor_recovery_receipt_inputs"))
    ]
    harbor_recovery_receipt_input_ids = [
        str(item.get("input_id") or "")
        for item in harbor_recovery_receipt_inputs
        if item.get("input_id")
    ]
    harbor_recovery_receipt_output_contract = [
        _dict(item)
        for item in _list(first_item.get("harbor_recovery_receipt_output_contract"))
    ]
    harbor_recovery_receipt_output_ids = [
        str(item.get("output_id") or "")
        for item in harbor_recovery_receipt_output_contract
        if item.get("output_id")
    ]
    queue_readback_normalizer_contract = [
        _dict(item)
        for item in _list(first_item.get("queue_readback_normalizer_contract"))
    ]
    queue_readback_normalizer_field_ids = [
        str(item.get("field_id") or "")
        for item in queue_readback_normalizer_contract
        if item.get("field_id")
    ]
    log_source_tags = [
        _dict(item) for item in _list(first_item.get("log_source_tags"))
    ]
    log_source_tag_keys = [
        str(item.get("tag_key") or "")
        for item in log_source_tags
        if item.get("tag_key")
    ]
    log_source_grouping_keys = _strings(context.get("log_source_grouping_keys"))
    log_source_tagging_contract = [
        _dict(item) for item in _list(context.get("log_source_tagging_contract"))
    ]
    forbidden_runtime_actions = _strings(first_item.get("forbidden_runtime_actions"))
    runtime_write_gate = str(first_item.get("runtime_write_gate") or "")
    safe_next_action_id = str(first_item.get("safe_next_action_id") or "")
    safe_next_action_stage = str(first_item.get("safe_next_action_stage") or "")
    safe_next_action = str(first_item.get("safe_next_action") or "")
    safe_next_action_command = str(first_item.get("safe_next_action_command") or "")
    safe_next_action_post_verifier = str(
        first_item.get("safe_next_action_post_verifier") or ""
    )
    safe_next_action_requires_local_console = bool(
        first_item.get("safe_next_action_requires_local_console") is True
    )
    safe_next_action_blocker_fields = _strings(
        first_item.get("safe_next_action_blocker_fields")
    )
    active_deployment_closure_state = (
        "production_readback_verified"
        if deploy_marker_resolved_by_production_readback
        else deployment_closure_state
    )
    active_deploy_marker_readback_required = bool(
        deploy_marker_readback_required
        and not deploy_marker_resolved_by_production_readback
    )
    active_cd_failed_after_registry_ready = bool(
        cd_failed_after_registry_ready
        and not deploy_marker_resolved_by_production_readback
    )
    active_current_cd_run_id = (
        str(state.get("current_main_cd_run_id") or "")
        if deploy_marker_resolved_by_production_readback
        else current_cd_run_id
    )
    active_current_cd_run_status = (
        "production_readback_verified"
        if deploy_marker_resolved_by_production_readback
        else current_cd_run_status
    )
    active_current_cd_commit_sha = (
        str(state.get("latest_successful_deployed_source_sha") or "")
        if deploy_marker_resolved_by_production_readback
        else current_cd_commit_sha
    )
    state["active_p0_state"] = "blocked_ai_loop_current_blocker_execution_queue"
    state["next_executable_mainline_workplan_id"] = (
        "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE"
    )
    next_mainline_state = "ai_loop_current_blocker_queue_waiting_110_control_path_readback"
    if blocker_id == "controlled_cd_lane_guardrails_blocked":
        next_mainline_state = (
            "ai_loop_current_blocker_queue_waiting_controlled_cd_lane_guardrails_readback"
        )
    state["next_executable_mainline_state"] = next_mainline_state
    state["ai_loop_current_blocker_execution_queue_count"] = len(queue)
    state["ai_loop_current_blocker_id"] = blocker_id
    state["ai_loop_current_blocker_registry_v2_ready"] = registry_v2_ready
    state["ai_loop_current_blocker_registry_v2_status_classifier"] = (
        registry_v2_status_classifier
    )
    state["ai_loop_current_blocker_deployment_closure_state"] = (
        active_deployment_closure_state
    )
    state["ai_loop_current_blocker_deploy_marker_readback_required"] = (
        active_deploy_marker_readback_required
    )
    state["ai_loop_current_blocker_current_cd_run_id"] = active_current_cd_run_id
    state["ai_loop_current_blocker_current_cd_run_status"] = (
        active_current_cd_run_status
    )
    state["ai_loop_current_blocker_current_cd_commit_sha"] = (
        active_current_cd_commit_sha
    )
    state["ai_loop_current_blocker_cd_failed_after_registry_ready"] = (
        active_cd_failed_after_registry_ready
    )
    state["ai_loop_current_blocker_deploy_marker_resolved_by_production_readback"] = (
        deploy_marker_resolved_by_production_readback
    )
    state["ai_loop_current_blocker_historical_deployment_closure_state"] = (
        deployment_closure_state
    )
    state["ai_loop_current_blocker_historical_deploy_marker_readback_required"] = (
        deploy_marker_readback_required
    )
    state["ai_loop_current_blocker_historical_current_cd_run_id"] = current_cd_run_id
    state["ai_loop_current_blocker_historical_current_cd_run_status"] = (
        current_cd_run_status
    )
    state["ai_loop_current_blocker_historical_current_cd_commit_sha"] = (
        current_cd_commit_sha
    )
    state["ai_loop_current_blocker_historical_cd_failed_after_registry_ready"] = (
        cd_failed_after_registry_ready
    )
    state["ai_loop_current_blocker_harbor_110_repair_run_id"] = (
        harbor_110_repair_run_id
    )
    state["ai_loop_current_blocker_harbor_110_repair_run_status"] = (
        harbor_110_repair_run_status
    )
    state["ai_loop_current_blocker_harbor_110_repair_failure_classifier"] = (
        harbor_110_repair_failure_classifier
    )
    state[
        "ai_loop_current_blocker_harbor_110_repair_failed_after_registry_ready"
    ] = harbor_110_repair_failed_after_registry_ready
    state["ai_loop_current_blocker_control_path_blocker"] = external_blocker
    state["ai_loop_current_blocker_control_path_pressure_blocker"] = (
        pressure_blocker
    )
    state["ai_loop_current_blocker_node_load_classifier"] = node_load_classifier
    state["ai_loop_current_blocker_runtime_write_gate"] = runtime_write_gate
    state["ai_loop_current_blocker_safe_next_action_id"] = safe_next_action_id
    state["ai_loop_current_blocker_safe_next_action_stage"] = (
        safe_next_action_stage
    )
    state["ai_loop_current_blocker_safe_next_action_requires_local_console"] = (
        safe_next_action_requires_local_console
    )
    state["ai_loop_current_blocker_safe_next_action_blocker_fields"] = (
        safe_next_action_blocker_fields
    )
    state["ai_loop_current_blocker_learning_target_count"] = len(learning_targets)
    state["ai_loop_current_blocker_local_console_phase_count"] = len(
        local_console_plan
    )
    state["ai_loop_current_blocker_local_console_phase_ids"] = (
        local_console_phase_ids
    )
    state["ai_loop_current_blocker_post_recovery_readback_command_count"] = len(
        post_recovery_readback_commands
    )
    state["ai_loop_current_blocker_harbor_recovery_receipt_input_count"] = len(
        harbor_recovery_receipt_inputs
    )
    state["ai_loop_current_blocker_harbor_recovery_receipt_input_ids"] = (
        harbor_recovery_receipt_input_ids
    )
    state["ai_loop_current_blocker_harbor_recovery_receipt_output_contract_count"] = (
        len(harbor_recovery_receipt_output_contract)
    )
    state["ai_loop_current_blocker_harbor_recovery_receipt_output_ids"] = (
        harbor_recovery_receipt_output_ids
    )
    state["ai_loop_current_blocker_queue_readback_normalizer_contract_count"] = len(
        queue_readback_normalizer_contract
    )
    state["ai_loop_current_blocker_queue_readback_normalizer_field_ids"] = (
        queue_readback_normalizer_field_ids
    )
    state["ai_loop_current_blocker_log_source_tag_count"] = len(log_source_tags)
    state["ai_loop_current_blocker_log_source_tag_keys"] = log_source_tag_keys
    state["ai_loop_log_source_grouping_key_count"] = len(log_source_grouping_keys)
    state["ai_loop_log_source_grouping_keys"] = log_source_grouping_keys
    state["ai_loop_log_source_tagging_contract_count"] = len(
        log_source_tagging_contract
    )
    state["ai_loop_current_blocker_forbidden_runtime_action_count"] = len(
        forbidden_runtime_actions
    )
    state["active_p0_live_active_blockers"] = _unique_strings(
        _strings(state.get("active_p0_live_active_blockers"))
        + ["ai_loop_current_blocker_execution_queue"]
        + ([blocker_id] if blocker_id else [])
        + ([external_blocker] if external_blocker else [])
        + ([pressure_blocker] if pressure_blocker else [])
        + (
            ["deploy_marker_readback_required_after_registry_ready"]
            if active_deploy_marker_readback_required
            else []
        )
        + (
            ["current_cd_failure_after_registry_ready"]
            if active_cd_failed_after_registry_ready
            else []
        )
    )

    for item in _list(payload.get("in_progress_or_blocked_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-006":
            continue

        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence["ai_loop_current_blocker_execution_queue_count"] = len(queue)
        evidence["ai_loop_current_blocker_id"] = blocker_id
        evidence["ai_loop_current_blocker_queue_item_id"] = str(
            first_item.get("queue_item_id") or ""
        )
        evidence["ai_loop_current_blocker_runner_label"] = str(
            first_item.get("runner_label") or ""
        )
        evidence["ai_loop_current_blocker_registry_v2_status"] = first_item.get(
            "registry_v2_status"
        )
        evidence["ai_loop_current_blocker_registry_v2_ready"] = registry_v2_ready
        evidence["ai_loop_current_blocker_registry_v2_status_classifier"] = (
            registry_v2_status_classifier
        )
        evidence["ai_loop_current_blocker_deployment_closure_state"] = (
            active_deployment_closure_state
        )
        evidence["ai_loop_current_blocker_deploy_marker_readback_required"] = (
            active_deploy_marker_readback_required
        )
        evidence["ai_loop_current_blocker_current_cd_run_id"] = (
            active_current_cd_run_id
        )
        evidence["ai_loop_current_blocker_current_cd_run_status"] = (
            active_current_cd_run_status
        )
        evidence["ai_loop_current_blocker_current_cd_commit_sha"] = (
            active_current_cd_commit_sha
        )
        evidence["ai_loop_current_blocker_cd_failed_after_registry_ready"] = (
            active_cd_failed_after_registry_ready
        )
        evidence[
            "ai_loop_current_blocker_deploy_marker_resolved_by_production_readback"
        ] = deploy_marker_resolved_by_production_readback
        evidence["ai_loop_current_blocker_historical_deployment_closure_state"] = (
            deployment_closure_state
        )
        evidence[
            "ai_loop_current_blocker_historical_deploy_marker_readback_required"
        ] = deploy_marker_readback_required
        evidence["ai_loop_current_blocker_historical_current_cd_run_id"] = (
            current_cd_run_id
        )
        evidence["ai_loop_current_blocker_historical_current_cd_run_status"] = (
            current_cd_run_status
        )
        evidence["ai_loop_current_blocker_historical_current_cd_commit_sha"] = (
            current_cd_commit_sha
        )
        evidence[
            "ai_loop_current_blocker_historical_cd_failed_after_registry_ready"
        ] = (
            cd_failed_after_registry_ready
        )
        evidence["ai_loop_current_blocker_harbor_110_repair_run_id"] = (
            harbor_110_repair_run_id
        )
        evidence["ai_loop_current_blocker_harbor_110_repair_run_status"] = (
            harbor_110_repair_run_status
        )
        evidence["ai_loop_current_blocker_harbor_110_repair_failure_classifier"] = (
            harbor_110_repair_failure_classifier
        )
        evidence[
            "ai_loop_current_blocker_harbor_110_repair_failed_after_registry_ready"
        ] = harbor_110_repair_failed_after_registry_ready
        evidence["ai_loop_current_blocker_controlled_recovery_package"] = (
            controlled_recovery_package
        )
        evidence["ai_loop_current_blocker_post_apply_verifier"] = (
            post_apply_verifier
        )
        evidence["ai_loop_current_blocker_runtime_write_gate"] = runtime_write_gate
        evidence["ai_loop_current_blocker_safe_next_action_id"] = (
            safe_next_action_id
        )
        evidence["ai_loop_current_blocker_safe_next_action_stage"] = (
            safe_next_action_stage
        )
        evidence["ai_loop_current_blocker_safe_next_action"] = safe_next_action
        evidence["ai_loop_current_blocker_safe_next_action_command"] = (
            safe_next_action_command
        )
        evidence["ai_loop_current_blocker_safe_next_action_post_verifier"] = (
            safe_next_action_post_verifier
        )
        evidence["ai_loop_current_blocker_safe_next_action_requires_local_console"] = (
            safe_next_action_requires_local_console
        )
        evidence["ai_loop_current_blocker_safe_next_action_blocker_fields"] = (
            safe_next_action_blocker_fields
        )
        evidence["ai_loop_current_blocker_control_path_blocker"] = external_blocker
        evidence["ai_loop_current_blocker_control_path_pressure_blocker"] = (
            pressure_blocker
        )
        evidence["ai_loop_current_blocker_node_load_classifier"] = (
            node_load_classifier
        )
        evidence["ai_loop_current_blocker_learning_writeback_targets"] = (
            learning_targets
        )
        evidence["ai_loop_current_blocker_target_batches"] = target_batches
        evidence["ai_loop_current_blocker_local_console_phase_count"] = len(
            local_console_plan
        )
        evidence["ai_loop_current_blocker_local_console_phase_ids"] = (
            local_console_phase_ids
        )
        evidence["ai_loop_current_blocker_local_console_execution_plan"] = (
            local_console_plan
        )
        evidence["ai_loop_current_blocker_post_recovery_readback_commands"] = (
            post_recovery_readback_commands
        )
        evidence["ai_loop_current_blocker_harbor_recovery_receipt_endpoint"] = str(
            first_item.get("harbor_recovery_receipt_endpoint") or ""
        )
        evidence["ai_loop_current_blocker_harbor_recovery_receipt_input_count"] = len(
            harbor_recovery_receipt_inputs
        )
        evidence["ai_loop_current_blocker_harbor_recovery_receipt_input_ids"] = (
            harbor_recovery_receipt_input_ids
        )
        evidence["ai_loop_current_blocker_harbor_recovery_receipt_inputs"] = (
            harbor_recovery_receipt_inputs
        )
        evidence[
            "ai_loop_current_blocker_harbor_recovery_receipt_output_contract_count"
        ] = len(harbor_recovery_receipt_output_contract)
        evidence["ai_loop_current_blocker_harbor_recovery_receipt_output_ids"] = (
            harbor_recovery_receipt_output_ids
        )
        evidence["ai_loop_current_blocker_harbor_recovery_receipt_output_contract"] = (
            harbor_recovery_receipt_output_contract
        )
        evidence["ai_loop_current_blocker_queue_readback_normalizer_contract"] = (
            queue_readback_normalizer_contract
        )
        evidence["ai_loop_current_blocker_queue_readback_normalizer_field_ids"] = (
            queue_readback_normalizer_field_ids
        )
        evidence["ai_loop_current_blocker_log_source_tags"] = log_source_tags
        evidence["ai_loop_current_blocker_log_source_tag_keys"] = (
            log_source_tag_keys
        )
        evidence["ai_loop_log_source_grouping_keys"] = log_source_grouping_keys
        evidence["ai_loop_log_source_tagging_contract"] = (
            log_source_tagging_contract
        )
        evidence["ai_loop_current_blocker_forbidden_runtime_actions"] = (
            forbidden_runtime_actions
        )
        evidence["ai_loop_current_blocker_metadata_only_writeback_ready"] = bool(
            first_item.get("metadata_only_writeback_ready") is True
        )
        evidence["ai_loop_current_blocker_runtime_dispatch_performed"] = bool(
            first_item.get("runtime_dispatch_performed") is True
        )
        evidence["ai_loop_current_blocker_raw_payload_required"] = bool(
            first_item.get("raw_payload_required") is True
        )

        workplan["status"] = "blocked_ai_loop_current_blocker_execution_queue"
        workplan["safe_next_step"] = str(first_item.get("safe_next_step") or "")
        workplan["reason"] = (
            "The Harbor / 110 blocker is now visible as an AI Loop execution "
            "queue item with metadata-only KM/RAG/MCP/PlayBook/AI Agent "
            "writeback targets. The next action is not generic manual triage; "
            f"it is {blocker_id} through the bounded recovery package, ordered "
            "verifier phases, and post-apply verifier. Queue readback "
            "classifiers are normalized into explicit AI blockers before "
            "KM/RAG/MCP/PlayBook writeback."
        )
        professional_fix = _dict(workplan.setdefault("professional_fix", {}))
        professional_fix["action"] = (
            "Run the AI Loop current blocker package in order: "
            f"{', '.join(local_console_phase_ids)}, then rerun "
            "controlled CD lane / registry /v2/ / priority readbacks and write "
            "metadata-only KM/RAG/MCP/PlayBook receipts from normalized queue "
            "classifier fields. Do not restart Docker "
            "daemon, reboot hosts, drain nodes, switch registry provider, "
            "trigger workflows, or read runner tokens from this lane."
        )
        professional_fix["owner"] = (
            "AI Loop current blocker queue plus P0-006 Harbor/110 control path"
        )

    payload["status"] = "p0_006_blocked_ai_loop_current_blocker_execution_queue"
    if registry_v2_ready:
        payload["next_execution_order"] = [
            (
                "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE: registry /v2/ "
                f"is already {first_item.get('registry_v2_status')} "
                f"({registry_v2_status_classifier}); do not reopen Harbor 502 "
                f"as the main blocker. Execute {blocker_id} through the "
                "controlled CD lane guardrail verifier, registry readbacks, "
                "priority work-order readback, and metadata-only KM/RAG/MCP/"
                "PlayBook writeback."
            )
        ]
        if active_deploy_marker_readback_required or active_cd_failed_after_registry_ready:
            payload["next_execution_order"].append(
                "P0-006-CD-DEPLOY-MARKER-READBACK: close the latest visible CD "
                f"{active_current_cd_run_id or 'unknown'} status "
                f"{active_current_cd_run_status or 'unknown'} and verify deploy marker / "
                "production image / priority API before claiming runtime closure."
            )
        payload["next_execution_order"].append(
            "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT: only "
            "rerun Harbor watchdog repair if registry /v2/ regresses below "
            "200/401; otherwise keep focus on controlled CD lane guardrails."
        )
    else:
        payload["next_execution_order"] = [
            (
                "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE: execute the "
                f"{blocker_id} queue item through 110 control-path readback, "
                f"{len(local_console_plan)} ordered local-console phases, "
                "post-recovery readback commands, Harbor receipt inputs and "
                "outputs, and metadata-only KM/RAG/MCP/PlayBook writeback from "
                "normalized queue classifiers and control-path readiness "
                "classifiers."
            ),
            (
                "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT: after the "
                "AI Loop queue item verifies 110 control path, rerun Harbor "
                "watchdog check-mode / repair-once and registry /v2/ readback."
            )
        ]
        if active_deploy_marker_readback_required or active_cd_failed_after_registry_ready:
            payload["next_execution_order"].append(
                "P0-006-CD-DEPLOY-MARKER-READBACK: after registry /v2/ is "
                "200/401, let the next Gitea CD run build/push/deploy and then "
                "verify delivery-closure-workbench, priority work order, and "
                "production marker advance."
            )
    _refresh_rollups_after_stockplatform_overlay(payload, state)
    summary = _dict(payload.setdefault("summary", {}))
    summary["ai_loop_current_blocker_execution_queue_count"] = len(queue)
    summary["ai_loop_current_blocker_id"] = blocker_id
    summary["ai_loop_current_blocker_registry_v2_ready"] = registry_v2_ready
    summary["ai_loop_current_blocker_registry_v2_status_classifier"] = (
        registry_v2_status_classifier
    )
    summary["ai_loop_current_blocker_deployment_closure_state"] = (
        active_deployment_closure_state
    )
    summary["ai_loop_current_blocker_deploy_marker_readback_required"] = (
        active_deploy_marker_readback_required
    )
    summary["ai_loop_current_blocker_current_cd_run_status"] = (
        active_current_cd_run_status
    )
    summary["ai_loop_current_blocker_cd_failed_after_registry_ready"] = (
        active_cd_failed_after_registry_ready
    )
    summary["ai_loop_current_blocker_deploy_marker_resolved_by_production_readback"] = (
        deploy_marker_resolved_by_production_readback
    )
    summary["ai_loop_current_blocker_historical_current_cd_run_status"] = (
        current_cd_run_status
    )
    summary["ai_loop_current_blocker_harbor_110_repair_run_status"] = (
        harbor_110_repair_run_status
    )
    summary["ai_loop_current_blocker_harbor_110_repair_failure_classifier"] = (
        harbor_110_repair_failure_classifier
    )
    summary["ai_loop_current_blocker_control_path_blocker"] = external_blocker
    summary["ai_loop_current_blocker_control_path_pressure_blocker"] = (
        pressure_blocker
    )
    summary["ai_loop_current_blocker_node_load_classifier"] = node_load_classifier
    summary["ai_loop_current_blocker_controlled_recovery_package"] = (
        controlled_recovery_package
    )
    summary["ai_loop_current_blocker_post_apply_verifier"] = post_apply_verifier
    summary["ai_loop_current_blocker_safe_next_action_id"] = safe_next_action_id
    summary["ai_loop_current_blocker_safe_next_action_stage"] = (
        safe_next_action_stage
    )
    summary["ai_loop_current_blocker_safe_next_action"] = safe_next_action
    summary["ai_loop_current_blocker_safe_next_action_command"] = (
        safe_next_action_command
    )
    summary["ai_loop_current_blocker_safe_next_action_post_verifier"] = (
        safe_next_action_post_verifier
    )
    summary["ai_loop_current_blocker_safe_next_action_requires_local_console"] = (
        safe_next_action_requires_local_console
    )
    summary["ai_loop_current_blocker_safe_next_action_blocker_fields"] = (
        safe_next_action_blocker_fields
    )
    summary["ai_loop_current_blocker_learning_target_count"] = len(learning_targets)
    summary["ai_loop_current_blocker_local_console_phase_count"] = len(
        local_console_plan
    )
    summary["ai_loop_current_blocker_local_console_phase_ids"] = (
        local_console_phase_ids
    )
    summary["ai_loop_current_blocker_post_recovery_readback_command_count"] = len(
        post_recovery_readback_commands
    )
    summary["ai_loop_current_blocker_harbor_recovery_receipt_input_count"] = len(
        harbor_recovery_receipt_inputs
    )
    summary["ai_loop_current_blocker_harbor_recovery_receipt_input_ids"] = (
        harbor_recovery_receipt_input_ids
    )
    summary["ai_loop_current_blocker_harbor_recovery_receipt_output_contract_count"] = (
        len(harbor_recovery_receipt_output_contract)
    )
    summary["ai_loop_current_blocker_harbor_recovery_receipt_output_ids"] = (
        harbor_recovery_receipt_output_ids
    )
    summary["ai_loop_current_blocker_queue_readback_normalizer_contract_count"] = len(
        queue_readback_normalizer_contract
    )
    summary["ai_loop_current_blocker_queue_readback_normalizer_field_ids"] = (
        queue_readback_normalizer_field_ids
    )
    summary["ai_loop_current_blocker_log_source_tag_count"] = len(log_source_tags)
    summary["ai_loop_current_blocker_log_source_tag_keys"] = log_source_tag_keys
    summary["ai_loop_log_source_grouping_key_count"] = len(log_source_grouping_keys)
    summary["ai_loop_log_source_grouping_keys"] = log_source_grouping_keys
    summary["ai_loop_log_source_tagging_contract_count"] = len(
        log_source_tagging_contract
    )
    summary["ai_loop_current_blocker_forbidden_runtime_action_count"] = len(
        forbidden_runtime_actions
    )
    apply_ai_automation_node_receipts(payload)


def _record_ai_loop_current_blocker_production_resolution(
    *,
    payload: dict[str, Any],
    state: dict[str, Any],
    queue_count: int,
    blocker_id: str,
    registry_v2_ready: bool,
    registry_v2_status_classifier: str,
    deployment_closure_state: str,
    deploy_marker_readback_required: bool,
    current_cd_run_id: str,
    current_cd_run_status: str,
    current_cd_commit_sha: str,
    cd_failed_after_registry_ready: bool,
    harbor_110_repair_run_id: str,
    harbor_110_repair_run_status: str,
    harbor_110_repair_failure_classifier: str,
    harbor_110_repair_failed_after_registry_ready: bool,
    external_blocker: str,
    pressure_blocker: str,
    node_load_classifier: str,
) -> None:
    """Record a resolved AI-loop queue item without reopening active P0 state."""
    production_sha = str(state.get("latest_successful_deployed_source_sha") or "")
    production_run_id = str(state.get("current_main_cd_run_id") or "")
    production_run_status = str(state.get("current_main_cd_run_status") or "")
    resolved_fields: dict[str, Any] = {
        "ai_loop_current_blocker_execution_queue_count": queue_count,
        "ai_loop_current_blocker_id": blocker_id,
        "ai_loop_current_blocker_resolved_by_production_readback": True,
        "ai_loop_current_blocker_registry_v2_ready": registry_v2_ready,
        "ai_loop_current_blocker_registry_v2_status_classifier": (
            registry_v2_status_classifier
        ),
        "ai_loop_current_blocker_deployment_closure_state": (
            "production_readback_verified"
        ),
        "ai_loop_current_blocker_deploy_marker_resolved_by_production_readback": (
            True
        ),
        "ai_loop_current_blocker_deploy_marker_readback_required": False,
        "ai_loop_current_blocker_current_cd_run_id": production_run_id,
        "ai_loop_current_blocker_current_cd_run_status": production_run_status,
        "ai_loop_current_blocker_current_cd_commit_sha": production_sha,
        "ai_loop_current_blocker_cd_failed_after_registry_ready": False,
        "ai_loop_current_blocker_harbor_110_repair_failed_after_registry_ready": False,
        "ai_loop_current_blocker_control_path_blocker": "",
        "ai_loop_current_blocker_control_path_pressure_blocker": "",
        "ai_loop_current_blocker_safe_next_action": "",
        "ai_loop_current_blocker_safe_next_action_id": "",
        "ai_loop_current_blocker_safe_next_action_stage": "",
        "ai_loop_current_blocker_safe_next_action_command": "",
        "ai_loop_current_blocker_safe_next_action_post_verifier": "",
        "ai_loop_current_blocker_safe_next_action_requires_local_console": False,
        "ai_loop_current_blocker_safe_next_action_blocker_fields": [],
        "ai_loop_current_blocker_node_load_classifier": node_load_classifier,
        "ai_loop_current_blocker_historical_deployment_closure_state": (
            deployment_closure_state
        ),
        "ai_loop_current_blocker_historical_deploy_marker_readback_required": (
            deploy_marker_readback_required
        ),
        "ai_loop_current_blocker_historical_current_cd_run_id": current_cd_run_id,
        "ai_loop_current_blocker_historical_current_cd_run_status": (
            current_cd_run_status
        ),
        "ai_loop_current_blocker_historical_current_cd_commit_sha": (
            current_cd_commit_sha
        ),
        "ai_loop_current_blocker_historical_cd_failed_after_registry_ready": (
            cd_failed_after_registry_ready
        ),
        "ai_loop_current_blocker_historical_harbor_110_repair_run_id": (
            harbor_110_repair_run_id
        ),
        "ai_loop_current_blocker_historical_harbor_110_repair_run_status": (
            harbor_110_repair_run_status
        ),
        "ai_loop_current_blocker_historical_harbor_110_repair_failure_classifier": (
            harbor_110_repair_failure_classifier
        ),
        "ai_loop_current_blocker_historical_harbor_110_repair_failed_after_registry_ready": (
            harbor_110_repair_failed_after_registry_ready
        ),
        "ai_loop_current_blocker_historical_control_path_blocker": (
            external_blocker
        ),
        "ai_loop_current_blocker_historical_control_path_pressure_blocker": (
            pressure_blocker
        ),
    }
    state.update(resolved_fields)
    resolved_blockers = {
        blocker_id,
        external_blocker,
        pressure_blocker,
        "ai_loop_current_blocker_execution_queue",
        "deploy_marker_readback_required_after_registry_ready",
        "current_cd_failure_after_registry_ready",
    }
    state["active_p0_live_active_blockers"] = [
        blocker
        for blocker in _strings(state.get("active_p0_live_active_blockers"))
        if blocker and blocker not in resolved_blockers
    ]
    summary = _dict(payload.setdefault("summary", {}))
    summary.update(resolved_fields)
    summary["active_p0_live_active_blockers"] = list(
        state["active_p0_live_active_blockers"]
    )

    for item in _list(payload.get("in_progress_or_blocked_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-006":
            continue
        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence.update(resolved_fields)
        evidence["active_blockers"] = [
            blocker
            for blocker in _strings(evidence.get("active_blockers"))
            if blocker and blocker not in resolved_blockers
        ]
        break
    apply_ai_automation_node_receipts(payload)


def _ai_loop_current_blocker_can_override(
    *,
    status: str,
    blocker_id: str,
    queue_item: dict[str, Any],
) -> bool:
    ai_loop_blocker_ids = {
        "controlled_cd_lane_guardrails_blocked",
    }
    if status == "p0_006_blocked_harbor_registry_controlled_recovery_preflight":
        return True
    if status == "p0_006_blocked_stockplatform_public_api_runtime_drift":
        return blocker_id.startswith("harbor_110_") or blocker_id in ai_loop_blocker_ids
    if not blocker_id.startswith("harbor_110_") and blocker_id not in ai_loop_blocker_ids:
        return False
    if blocker_id in ai_loop_blocker_ids:
        return True
    return bool(
        queue_item.get("deploy_marker_readback_required") is True
        or queue_item.get("cd_failed_after_registry_ready") is True
        or queue_item.get("harbor_110_repair_failed_after_registry_ready") is True
    )


def _harbor_registry_next_state(*, status: str, candidate_packaged: bool) -> str:
    if candidate_packaged and "upstream_502" in status:
        return (
            "controlled_recovery_packaged_waiting_harbor_watchdog_check_mode_"
            "and_repair_once_receipt"
        )
    if candidate_packaged and "public_gateway_route_drift" in status:
        return (
            "controlled_recovery_packaged_waiting_188_registry_nginx_rendered_"
            "diff_and_nginx_t"
        )
    return "controlled_recovery_waiting_registry_v2_evidence_and_executor_contract"


def _harbor_registry_reason(*, status: str, candidate_packaged: bool) -> str:
    if candidate_packaged and "upstream_502" in status:
        return (
            "Current Gitea CD cannot deploy AWOOOI because Harbor registry /v2/ "
            "is returning 502 while the Harbor UI is reachable. The active "
            "mainline item is now a controlled Harbor watchdog check-mode / "
            "repair-once package with post-apply registry verifier and "
            "KM/RAG/MCP/PlayBook writeback. This is not a manual end state."
        )
    if candidate_packaged and "public_gateway_route_drift" in status:
        return (
            "Current Gitea CD cannot deploy AWOOOI because the public registry "
            "route is unhealthy while the internal registry /v2/ readback is "
            "healthy. The active mainline item is a controlled 188 Nginx "
            "rendered diff / nginx -t / route smoke package, not a manual end "
            "state."
        )
    return (
        "Harbor registry recovery is active and waiting for registry /v2/ "
        "shape evidence plus executor contract before any bounded apply; this "
        "is not a manual end state."
    )


def _harbor_registry_action(*, status: str) -> str:
    if "public_gateway_route_drift" in status:
        return (
            "Prepare the 188 registry public gateway controlled route diff, run "
            "rendered diff and nginx -t, keep rollback backup and route smoke "
            "receipts, then verify registry /v2/ and rerun CD marker readback. "
            "Do not switch registry provider, reload Nginx without check-mode, "
            "restart Docker daemon, reboot hosts, trigger workflows, or read "
            "secrets from this lane."
        )
    return (
        "Run Harbor registry controlled recovery in order: verify 110 control "
        "channel, execute harbor-watchdog.sh --check, run "
        "--repair-once only if check-mode proves /v2/ unhealthy, rerun public "
        "and internal registry /v2/ verifier, then allow CD marker readback and "
        "write metadata-only KM/RAG/MCP/PlayBook receipts. Do not restart "
        "Docker daemon, reboot hosts, drain nodes, reload Nginx, switch "
        "registry provider, trigger workflows, or read secrets from this lane."
    )


def _harbor_registry_first_order(*, status: str) -> str:
    if "public_gateway_route_drift" in status:
        return (
            "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT: registry "
            "public route drift is blocking AWOOOI deploy marker; run 188 "
            "rendered diff / nginx -t / route smoke controlled package first."
        )
    return (
        "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT: Harbor registry "
        "/v2/ 502 is blocking AWOOOI deploy marker; run watchdog check-mode, "
        "bounded repair-once, registry /v2/ verifier, and metadata writeback "
        "before retrying CD."
    )


def _stockplatform_recovery_next_state(
    *,
    candidate_packaged: bool,
    api_layer: str,
    data_dependency_classification: str,
) -> str:
    if data_dependency_classification == "postgres_not_ready":
        return (
            "controlled_recovery_preflight_waiting_stockplatform_production_"
            "migration_control_channel_readback_and_public_api_verifier"
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "controlled_recovery_preflight_waiting_stockplatform_ai_"
            "recommendation_pipeline_readback_and_public_api_verifier"
        )
    if api_layer == "api_live_data_dependency_not_ready":
        return (
            "controlled_recovery_preflight_waiting_stockplatform_data_dependency_"
            "readback_and_source_freshness_contract"
        )
    if candidate_packaged:
        return (
            "controlled_recovery_packaged_waiting_stockplatform_110_control_path_"
            "readback_and_read_only_container_inspection"
        )
    if api_layer == "public_edge_or_route_unavailable":
        return (
            "controlled_recovery_preflight_waiting_public_edge_or_188_to_110_"
            "upstream_reprobe_before_targeted_apply"
        )
    return "controlled_recovery_preflight_waiting_route_or_runtime_evidence"


def _stockplatform_recovery_reason(
    *,
    candidate_packaged: bool,
    api_layer: str,
    data_dependency_classification: str,
) -> str:
    if data_dependency_classification == "postgres_not_ready":
        return (
            "Live StockPlatform API health is reachable, but freshness and "
            "ingestion readbacks report postgres_not_ready. The active P0-006 "
            "item is now the production migration/control-channel path with "
            "target selector, dry-run, rollback, public API verifier, and "
            "KM/RAG/MCP/PlayBook writeback receipts. This is not a generic API "
            "container recovery task and not a manual end state."
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "Live StockPlatform API health is reachable and official core data "
            "readbacks have recovered, but AI recommendations remain stale. "
            "The P0-006 lane now points at the AI recommendation pipeline "
            "readback, public API verifier, and KM/RAG/MCP/PlayBook writeback "
            "receipts. This is not a generic DB/source repair task and not a "
            "manual end state."
        )
    if api_layer == "api_live_data_dependency_not_ready":
        return (
            "Live StockPlatform API health is reachable, but freshness and/or "
            "ingestion readbacks are not ok. The P0-006 lane now has a "
            "controlled data-dependency preflight with target selector, "
            "source-of-truth diff, data dependency work items, post-apply "
            "verifiers, and KM/RAG/MCP/PlayBook writeback contracts. The "
            "remaining blocker is data dependency/source freshness control-path "
            "readback, not a manual end state."
        )
    if candidate_packaged:
        return (
            "Live StockPlatform public web is reachable but public API routes "
            "return 502. The P0-006 lane now has a controlled recovery package "
            "with target selector, source-of-truth diff, bounded action "
            "candidates, post-apply verifiers, and KM/RAG/MCP/PlayBook "
            "writeback contracts. The remaining blocker is the StockPlatform "
            "110 control-path readback, not a manual end state."
        )
    if api_layer == "public_edge_or_route_unavailable":
        return (
            "Live StockPlatform public API recovery preflight is active, but "
            "the current public probe cannot prove the edge-alive/API-upstream "
            "502 shape. The next AI-controlled step is a bounded public-edge "
            "and 188-to-110 upstream reprobe before any targeted apply; this is "
            "not a manual end state."
        )
    return (
        "StockPlatform public API recovery preflight is active and waiting for "
        "route/runtime evidence before any bounded apply; this is not a manual "
        "end state."
    )


def _stockplatform_recovery_action(
    *,
    api_layer: str,
    data_dependency_classification: str,
) -> str:
    if data_dependency_classification == "postgres_not_ready":
        return (
            "Run the StockPlatform production migration controlled path in "
            "order: recover the non-secret 110 control-channel readback, verify "
            "the deployed source and migration target selector, run migration "
            "dry-run/check-mode where available, use the existing production "
            "migration path with rollback receipt, rerun public "
            "health/freshness/ingestion, and write metadata-only "
            "KM/RAG/MCP/PlayBook receipts. Do not restart Docker daemon, reboot "
            "hosts, reload Nginx, manually write DB rows, fake freshness, "
            "trigger unrelated workflows, or read secrets from this lane."
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "Run the StockPlatform AI recommendation pipeline controlled "
            "readback in order: verify core freshness and ingestion are still "
            "green, inspect the AI recommendation queue/pipeline receipt in "
            "read-only mode, use only the existing bounded pipeline path after "
            "dry-run if apply is needed, rerun public freshness/selection "
            "brief verifiers, and write metadata-only KM/RAG/MCP/PlayBook "
            "receipts. Do not restart Docker daemon, reboot hosts, reload "
            "Nginx, write DB rows, fake freshness, trigger unrelated "
            "workflows, or read secrets from this lane."
        )
    if api_layer == "api_live_data_dependency_not_ready":
        return (
            "Run the StockPlatform data dependency controlled preflight in order: "
            "restore/control the 110 host readback path, inspect freshness, "
            "ingestion, source freshness and Postgres contract status in read-only "
            "mode, apply only metadata/config contract repair after dry-run if "
            "needed, then rerun public health/freshness/ingestion and write "
            "metadata-only KM/RAG/MCP/PlayBook receipts. Do not restart Docker "
            "daemon, reboot hosts, reload Nginx, write DB rows, fake freshness, "
            "trigger workflows, or read secrets from this lane."
        )
    return (
        "Run the StockPlatform API controlled recovery preflight in order: "
        "restore/control the 110 host readback path, perform read-only API "
        "container inspection with redacted logs, reconcile only the API "
        "container if inspection proves it is missing/exited/unhealthy, then "
        "rerun public health/freshness/ingestion and write metadata-only "
        "KM/RAG/MCP/PlayBook receipts. Do not restart Docker daemon, reboot "
        "hosts, reload Nginx, write DB rows, trigger workflows, or read "
        "secrets from this lane."
    )


def _stockplatform_recovery_first_order(
    *,
    api_layer: str,
    data_dependency_classification: str,
) -> str:
    if data_dependency_classification == "postgres_not_ready":
        return (
            "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT: "
            "StockPlatform API is reachable and freshness/ingestion are blocked "
            "by postgres_not_ready, so the active mainline item is the "
            "production migration/control-channel path with rollback and public "
            "API verifier; do not manually DB-write or fake freshness."
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT: "
            "StockPlatform API and official core data are recovered, but AI "
            "recommendations are stale; run AI recommendation pipeline "
            "readback, public API verifier, and metadata writeback before "
            "claiming the lane is only reboot-window gated."
        )
    if api_layer == "api_live_data_dependency_not_ready":
        return (
            "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT: "
            "StockPlatform API health is reachable, so the active mainline item "
            "is data dependency/source freshness control-path readback, "
            "read-only contract inspection, verifier, and metadata writeback; "
            "do not DB-write or fake freshness from this lane."
        )
    return (
        "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT: "
        "controlled recovery package is now the active mainline item; "
        "restore/control the 110 readback path, inspect the API container, "
        "and only then allow a targeted API reconcile with verifier and "
        "metadata writeback."
    )


def _stockplatform_runtime_next_state(
    *,
    data_dependency_classification: str,
    postgres_not_ready: bool,
) -> str:
    if postgres_not_ready:
        return (
            "blocked_live_stockplatform_public_api_requires_production_"
            "migration_control_channel_readback"
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "blocked_live_stockplatform_public_api_requires_ai_recommendation_"
            "pipeline_readback"
        )
    if data_dependency_classification == "freshness_or_ingestion_not_ready":
        return (
            "blocked_live_stockplatform_public_api_requires_data_dependency_"
            "source_contract_readback"
        )
    return (
        "blocked_live_stockplatform_public_api_requires_separate_runtime_"
        "control_path_recovery_without_daemon_restart"
    )


def _stockplatform_runtime_drift_reason(
    *,
    data_dependency_classification: str,
    postgres_not_ready: bool,
) -> str:
    if postgres_not_ready:
        return (
            "StockPlatform public API health is now HTTP 200, but freshness and "
            "ingestion are blocked by postgres_not_ready. P0-006 must stay on "
            "the production migration/control-channel path before claiming the "
            "reboot SLO lane is only waiting on a fresh boot window."
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "StockPlatform public API health is now HTTP 200 and official core "
            "data readbacks are recovered, but AI recommendations are stale. "
            "P0-006 must stay on the AI recommendation pipeline readback and "
            "public verifier path before claiming the reboot SLO lane is only "
            "waiting on a fresh boot window."
        )
    if data_dependency_classification == "freshness_or_ingestion_not_ready":
        return (
            "StockPlatform public API health is now HTTP 200, but freshness and "
            "ingestion readbacks are not green. P0-006 must stay on the data "
            "dependency/source contract readback path before claiming the reboot "
            "SLO lane is only waiting on a fresh boot window."
        )
    return (
        "Committed P0-006 scorecard says StockPlatform freshness and ingestion "
        "are ok, but live public API readback is blocked. This must remain "
        "visible before claiming the reboot SLO lane is only waiting on a "
        "fresh boot window."
    )


def _stockplatform_runtime_drift_action(
    *,
    data_dependency_classification: str,
    postgres_not_ready: bool,
) -> str:
    if postgres_not_ready:
        return (
            "Recover the StockPlatform production migration/control channel "
            "with target selector, source-of-truth diff, dry-run/check-mode, "
            "rollback, and post-apply public API verifier, then rerun the "
            "public readback. Do not restart Docker daemon, reboot hosts, "
            "reload Nginx, manually write DB rows, fake freshness, trigger "
            "unrelated workflows, or read secrets from this lane."
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "Run the StockPlatform AI recommendation pipeline readback with "
            "target selector, source-of-truth diff, dry-run/check-mode, "
            "rollback, and public API verifier, then rerun the public "
            "readback. Do not restart Docker daemon, reboot hosts, reload "
            "Nginx, manually write DB rows, fake freshness, trigger unrelated "
            "workflows, or read secrets from this lane."
        )
    if data_dependency_classification == "freshness_or_ingestion_not_ready":
        return (
            "Run the StockPlatform data dependency/source contract readback "
            "with target selector, source-of-truth diff, dry-run/check-mode, "
            "rollback, and public API verifier, then rerun the public readback. "
            "Do not restart Docker daemon, reboot hosts, reload Nginx, manually "
            "write DB rows, fake freshness, trigger unrelated workflows, or read "
            "secrets from this lane."
        )
    return (
        "Recover the StockPlatform API container/runtime control path with a "
        "separate bounded plan, then rerun public API readback. Do not restart "
        "Docker daemon, reboot hosts, prune data, write DB rows, trigger "
        "workflows, or read secrets from this lane."
    )


def _stockplatform_runtime_first_order(
    *,
    data_dependency_classification: str,
    postgres_not_ready: bool,
) -> str:
    if postgres_not_ready:
        return (
            "P0-006-STOCKPLATFORM-PUBLIC-API-RUNTIME-READBACK: live public "
            "StockPlatform API health is 200 but freshness/ingestion report "
            "postgres_not_ready; run the production migration/control-channel "
            "path before claiming the lane is only reboot-window gated."
        )
    if _stockplatform_ai_recommendations_wait(data_dependency_classification):
        return (
            "P0-006-STOCKPLATFORM-PUBLIC-API-RUNTIME-READBACK: live public "
            "StockPlatform API health is 200 and official core data are "
            "recovered, but AI recommendations are stale; run AI recommendation "
            "pipeline readback and public verifier before claiming the lane is "
            "only reboot-window gated."
        )
    if data_dependency_classification == "freshness_or_ingestion_not_ready":
        return (
            "P0-006-STOCKPLATFORM-PUBLIC-API-RUNTIME-READBACK: live public "
            "StockPlatform API health is 200 but freshness/ingestion are not "
            "green; run the data dependency/source contract readback before "
            "claiming the lane is only reboot-window gated."
        )
    return (
        "P0-006-STOCKPLATFORM-PUBLIC-API-RUNTIME-READBACK: live public "
        "StockPlatform API is blocked while committed scorecard still says "
        "freshness/ingestion are ok; fix runtime control-path evidence before "
        "claiming the lane is only reboot-window gated."
    )


def _enrich_from_current_readbacks(payload: dict[str, Any]) -> None:
    from src.services.awoooi_gitea_onboarding_warning_step_runtime_enablement_gate import (
        load_latest_awoooi_gitea_onboarding_warning_step_runtime_enablement_gate,
    )
    from src.services.awoooi_gitea_onboarding_warning_step_template_copy_apply_gate import (
        load_latest_awoooi_gitea_onboarding_warning_step_template_copy_apply_gate,
    )
    from src.services.awoooi_gitea_onboarding_warning_step_template_copy_receipt import (
        load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt,
    )
    from src.services.delivery_closure_workbench import load_delivery_closure_workbench
    from src.services.reboot_auto_recovery_drill_preflight import (
        load_latest_reboot_auto_recovery_drill_preflight,
    )
    from src.services.reboot_auto_recovery_slo_scorecard import (
        load_latest_reboot_auto_recovery_slo_scorecard,
    )

    workbench = load_delivery_closure_workbench()
    workbench_summary = _dict(workbench.get("summary"))
    workbench_readback = _dict(workbench.get("readback"))
    template_apply_gate = load_latest_awoooi_gitea_onboarding_warning_step_template_copy_apply_gate()
    template_receipt = load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt()
    runtime_gate = load_latest_awoooi_gitea_onboarding_warning_step_runtime_enablement_gate()
    reboot_preflight = load_latest_reboot_auto_recovery_drill_preflight()
    reboot_slo = load_latest_reboot_auto_recovery_slo_scorecard()
    reboot_slo_rollups = _dict(reboot_slo.get("rollups"))
    reboot_stockplatform = _dict(reboot_slo.get("stockplatform_data_freshness"))
    reboot_service_data_backup = _dict(
        reboot_slo.get("controlled_service_data_backup_readback")
    )
    windows99_verify_collection = _dict(
        reboot_slo.get("windows99_verify_collection")
    )
    windows99_management = _dict(reboot_slo.get("windows99_management_channel"))
    windows99_ssh_batch = _dict(windows99_management.get("ssh_batch"))
    reboot_preflight_rollups = _dict(reboot_preflight.get("rollups"))
    reboot_preflight_target_selector = _dict(reboot_preflight.get("target_selector"))
    reboot_active_blockers = _strings(reboot_slo.get("active_blockers"))
    service_data_backup_readback_present = (
        reboot_service_data_backup.get("readback_present") is True
    )
    service_data_backup_blocking_fields = _strings(
        reboot_service_data_backup.get("blocking_fields")
    )
    windows99_verify_collection_blockers = _strings(
        windows99_verify_collection.get("collection_blockers")
    )
    p0_006_event_gated = bool(
        reboot_slo_rollups.get("blocked_by_fresh_reboot_window_only") is True
    )
    stock_freshness_status = str(
        reboot_slo_rollups.get("stockplatform_freshness_status")
        or reboot_stockplatform.get("freshness_status")
        or "unknown"
    )
    stock_ingestion_status = str(
        reboot_slo_rollups.get("stockplatform_ingestion_status")
        or reboot_stockplatform.get("ingestion_status")
        or "unknown"
    )
    stock_blockers = _strings(reboot_stockplatform.get("freshness_blockers"))
    stock_ingestion_blockers = _strings(
        reboot_stockplatform.get("ingestion_blockers")
    )

    state = _dict(payload.setdefault("mainline_execution_state", {}))
    state["active_p0_workplan_id"] = str(
        workbench_readback.get("current_p0_workplan_id") or "P0-006"
    )
    state["active_p0_state"] = (
        "event_gated_waiting_fresh_all_host_reboot_window"
        if p0_006_event_gated
        else "blocked_reboot_auto_recovery_slo_not_ready"
    )
    state["active_p0_immediate_apply_gap_count"] = 0
    state["active_p0_live_api_status"] = str(
        reboot_slo.get("status")
        or workbench_readback.get("current_p0_status")
        or "blocked_reboot_auto_recovery_slo_not_ready"
    )
    state["active_p0_live_active_blockers"] = reboot_active_blockers
    state["active_p0_readiness_percent"] = _int(
        reboot_slo.get("readiness_percent")
        or workbench_readback.get("current_p0_readiness_percent")
    )
    state["active_p0_can_claim_10_minute_recovery"] = bool(
        reboot_slo.get("can_claim_all_services_recovered_within_target") is True
    )
    state["controlled_service_data_backup_readback_present"] = (
        service_data_backup_readback_present
    )
    state["controlled_service_data_backup_readback_status"] = str(
        reboot_service_data_backup.get("status") or "unknown"
    )
    state["controlled_service_data_backup_blocker_count"] = len(
        service_data_backup_blocking_fields
    )
    state["controlled_service_data_backup_blocking_fields"] = (
        service_data_backup_blocking_fields
    )
    state["controlled_service_data_backup_can_clear_blockers"] = bool(
        reboot_service_data_backup.get("can_clear_service_data_backup_blockers")
        is True
    )
    state["controlled_service_data_backup_next_safe_action"] = str(
        reboot_service_data_backup.get("next_safe_action") or ""
    )
    state["windows99_verify_collection_status"] = str(
        windows99_verify_collection.get("status") or "unknown"
    )
    state["windows99_verify_collection_can_collect_no_secret"] = bool(
        windows99_verify_collection.get("can_collect_no_secret_verify") is True
    )
    state["windows99_verify_collection_blocker_count"] = len(
        windows99_verify_collection_blockers
    )
    state["windows99_verify_collection_blockers"] = (
        windows99_verify_collection_blockers
    )
    state["windows99_verify_collection_host99_reachable"] = bool(
        windows99_verify_collection.get("host99_reachable") is True
    )
    state["windows99_verify_collection_host99_uptime_known"] = bool(
        windows99_verify_collection.get("host99_uptime_known") is True
    )
    state["windows99_verify_collection_post_verifier"] = str(
        windows99_verify_collection.get("post_verifier") or ""
    )
    state["windows99_management_readback_present"] = bool(
        windows99_management.get("readback_present") is True
    )
    state["windows99_management_host_reachable"] = bool(
        windows99_management.get("host_reachable") is True
    )
    state["windows99_remote_execution_channel_ready"] = bool(
        windows99_management.get("remote_execution_channel_ready") is True
    )
    state["windows99_ssh_batch_status"] = str(
        windows99_ssh_batch.get("status") or "unknown"
    )
    state["windows99_rdp_console_reachable"] = bool(
        windows99_management.get("rdp_console_reachable") is True
    )
    state["windows99_hyperv_vmconnect_open"] = bool(
        windows99_management.get("hyperv_vmconnect_open") is True
    )
    state["windows99_local_console_channel_reachable"] = bool(
        windows99_management.get("local_console_channel_reachable") is True
    )
    state["windows99_console_collection_channels"] = _strings(
        windows99_management.get("console_collection_channels")
    )
    state["windows99_winrm_http_open"] = bool(
        windows99_management.get("winrm_http_open") is True
    )
    state["windows99_winrm_https_open"] = bool(
        windows99_management.get("winrm_https_open") is True
    )
    state["stale_snapshot_or_old_cd_runs_must_not_reopen_closed_work"] = True
    state["p0_004_template_copy_apply_gate_production_http_status"] = 200
    state["p0_004_template_copy_apply_gate_runtime_readback_state"] = (
        "ready"
        if template_apply_gate.get("status") == "controlled_template_copy_apply_gate_ready"
        else "blocked"
    )
    state["p0_004_template_copy_apply_gate_status"] = str(
        template_apply_gate.get("status") or ""
    )
    state["p0_004_template_copy_receipt_status"] = str(
        template_receipt.get("status") or ""
    )
    state["p0_004_runtime_enablement_status"] = str(runtime_gate.get("status") or "")
    state["p0_004_runtime_enablement_runtime_readback_state"] = (
        "ready"
        if runtime_gate.get("status") == "controlled_warning_step_runtime_enabled"
        else "blocked"
    )
    state["reboot_drill_preflight_production_http_status"] = 200
    state["reboot_drill_preflight_runtime_readback_state"] = (
        "ready"
        if reboot_preflight.get("status")
        == "ready_for_break_glass_reboot_drill_authorization"
        else "blocked"
    )
    state["reboot_drill_preflight_status"] = str(reboot_preflight.get("status") or "")
    state["next_executable_mainline_workplan_id"] = (
        "P0-006-REBOOT-DRILL-PREFLIGHT-READBACK"
        if p0_006_event_gated
        else "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD"
    )
    state["next_executable_mainline_state"] = (
        (
            "production_preflight_ready_wait_for_next_real_all_host_reboot_event_"
            "or_separate_break_glass_reboot_drill_authorization"
        )
        if p0_006_event_gated
        else (
            "blocked_reboot_slo_scorecard_service_data_backup_readback_present_"
            "blockers_open"
            if service_data_backup_readback_present
            else "blocked_reboot_slo_scorecard_requires_controlled_service_data_backup_readback"
        )
    )

    runtime_sha = str(
        workbench_summary.get("production_deploy_runtime_build_commit_sha") or ""
    ).strip().lower()
    runtime_short_sha = str(
        workbench_summary.get("production_deploy_runtime_build_commit_short_sha") or ""
    ).strip().lower()
    desired_short_sha = str(
        workbench_summary.get(
            "production_deploy_desired_main_api_image_tag_short_sha"
        )
        or ""
    ).strip().lower()
    current_head = _dict(payload.setdefault("current_head", {}))
    runtime_source_truth_available = _is_sha(runtime_sha)
    if runtime_source_truth_available:
        runtime_short_sha = runtime_short_sha or runtime_sha[:10]
        desired_short_sha = desired_short_sha or runtime_short_sha
        production_readback_id = f"production_readback:{desired_short_sha}"
        production_subject = f"production desired image tag {desired_short_sha}"

        current_head["gitea_main_sha"] = runtime_sha
        current_head["latest_fetched_gitea_main_subject"] = production_subject
        current_head["latest_source_readiness_cd_run_id"] = production_readback_id
        current_head["latest_verified_worktree_base_sha"] = runtime_short_sha
        current_head["latest_successful_deployed_source_sha"] = runtime_sha
        current_head["latest_successful_deploy_marker"] = production_subject
        current_head["latest_source_readiness_cd_run_status"] = (
            "production_readback_verified"
        )
        current_head["latest_source_readiness_commit_sha"] = runtime_sha

        state["updated_at"] = _taipei_now_iso()
        state["current_main_cd_run_id"] = production_readback_id
        state["current_main_cd_run_status"] = "production_readback_verified"
        state["current_main_latest_source_sha"] = runtime_sha
        state["latest_successful_deployed_source_sha"] = runtime_sha
        state["reboot_drill_preflight_source_status"] = "production_endpoint_ready"
        state["p0_004_template_copy_apply_gate_source_status"] = (
            "production_endpoint_ready"
        )

    current_head["production_source_truth_available"] = runtime_source_truth_available
    current_head["stale_current_head_metadata_normalized"] = (
        runtime_source_truth_available
    )
    current_head["no_matching_runner_visible"] = False
    current_head["source_readiness_ci_fix_required"] = False

    for item in _list(payload.get("completed_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-004":
            continue
        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence["production_deploy_status"] = "closure_verified"
        evidence["production_image_tag_matches_main"] = bool(
            workbench_summary.get("production_deploy_image_tag_matches_main") is True
        )
        evidence["production_runtime_build_commit_short_sha"] = runtime_short_sha
        evidence["production_desired_image_tag_short_sha"] = desired_short_sha
        closure_percent = workbench_summary.get(
            "production_deploy_non110_runner_cd_closure_ordered_completion_percent"
        )
        evidence["production_deploy_governance_fields_present"] = closure_percent == 100
        evidence["latest_cd_run_status"] = "Success"

    for item in _list(payload.get("in_progress_or_blocked_in_priority_order")):
        workplan = _dict(item)
        if workplan.get("workplan_id") != "P0-006":
            continue

        evidence = _dict(workplan.setdefault("evidence", {}))
        evidence["active_blockers"] = state["active_p0_live_active_blockers"]
        evidence["service_green"] = bool(reboot_slo.get("service_green") is True)
        evidence["product_data_green"] = bool(
            reboot_slo.get("product_data_green") is True
        )
        evidence["backup_core_green"] = bool(
            reboot_slo.get("backup_core_green") is True
        )
        evidence["host_188_service_green"] = bool(
            reboot_slo.get("host_188_service_green") is True
        )
        evidence["stock_freshness_status"] = stock_freshness_status
        evidence["stock_ingestion_status"] = stock_ingestion_status
        evidence["stock_blockers"] = stock_blockers
        evidence["stock_ingestion_blockers"] = stock_ingestion_blockers
        evidence["stockplatform_controlled_recovery_gate_required"] = bool(
            reboot_slo_rollups.get("stockplatform_controlled_recovery_gate_required")
            is True
        )
        evidence["controlled_service_data_backup_readback_present"] = (
            service_data_backup_readback_present
        )
        evidence["controlled_service_data_backup_readback_status"] = str(
            reboot_service_data_backup.get("status") or "unknown"
        )
        evidence["controlled_service_data_backup_blocker_count"] = len(
            service_data_backup_blocking_fields
        )
        evidence["controlled_service_data_backup_blocking_fields"] = (
            service_data_backup_blocking_fields
        )
        evidence["controlled_service_data_backup_can_clear_blockers"] = bool(
            reboot_service_data_backup.get(
                "can_clear_service_data_backup_blockers"
            )
            is True
        )
        evidence["controlled_service_data_backup_next_safe_action"] = str(
            reboot_service_data_backup.get("next_safe_action") or ""
        )
        evidence["windows99_verify_collection_status"] = str(
            windows99_verify_collection.get("status") or "unknown"
        )
        evidence["windows99_verify_collection_can_collect_no_secret"] = bool(
            windows99_verify_collection.get("can_collect_no_secret_verify") is True
        )
        evidence["windows99_verify_collection_blockers"] = (
            windows99_verify_collection_blockers
        )
        evidence["windows99_verify_collection_host99_reachable"] = bool(
            windows99_verify_collection.get("host99_reachable") is True
        )
        evidence["windows99_verify_collection_host99_uptime_known"] = bool(
            windows99_verify_collection.get("host99_uptime_known") is True
        )
        evidence["windows99_management_readback_present"] = state[
            "windows99_management_readback_present"
        ]
        evidence["windows99_management_host_reachable"] = state[
            "windows99_management_host_reachable"
        ]
        evidence["windows99_remote_execution_channel_ready"] = state[
            "windows99_remote_execution_channel_ready"
        ]
        evidence["windows99_ssh_batch_status"] = state[
            "windows99_ssh_batch_status"
        ]
        evidence["windows99_rdp_console_reachable"] = state[
            "windows99_rdp_console_reachable"
        ]
        evidence["windows99_hyperv_vmconnect_open"] = state[
            "windows99_hyperv_vmconnect_open"
        ]
        evidence["windows99_local_console_channel_reachable"] = state[
            "windows99_local_console_channel_reachable"
        ]
        evidence["windows99_console_collection_channels"] = state[
            "windows99_console_collection_channels"
        ]
        evidence["windows99_winrm_http_open"] = state["windows99_winrm_http_open"]
        evidence["windows99_winrm_https_open"] = state["windows99_winrm_https_open"]
        evidence["drill_preflight_status"] = str(reboot_preflight.get("status") or "")
        evidence["drill_preflight_ready"] = (
            reboot_preflight_rollups.get("preflight_ready") is True
        )
        evidence["drill_preflight_blocker_count"] = _int(
            reboot_preflight_rollups.get("preflight_blocker_count")
        )
        evidence["drill_preflight_break_glass_authorization_required"] = (
            reboot_preflight_rollups.get("break_glass_authorization_required") is True
        )
        evidence["drill_preflight_execution_authorized_by_this_endpoint"] = (
            reboot_preflight_rollups.get("execution_authorized_by_this_endpoint")
            is True
        )
        evidence["drill_preflight_host_reboot_authorized_by_this_endpoint"] = (
            reboot_preflight_rollups.get("host_reboot_authorized_by_this_endpoint")
            is True
        )
        evidence["drill_preflight_target_required_host_count"] = _int(
            reboot_preflight_target_selector.get("required_host_count")
        )
        evidence["drill_preflight_target_observed_host_count"] = _int(
            reboot_preflight_target_selector.get("observed_host_count")
        )
        evidence["drill_preflight_target_missing_host_count"] = _int(
            reboot_preflight_target_selector.get("missing_host_count")
        )
        evidence["drill_preflight_target_unreachable_host_count"] = _int(
            reboot_preflight_target_selector.get("unreachable_host_count")
        )

        professional_fix = _dict(workplan.setdefault("professional_fix", {}))
        if p0_006_event_gated:
            professional_fix["action"] = (
                "Keep the live boot-triggered SLO timer enabled. StockPlatform "
                "freshness/ingestion are ok; the only active blocker is the fresh "
                "all-host reboot observation window. Use the production drill "
                "preflight readback for target selector, check-mode, rollback, and "
                "post-verifier, then wait for the next real all-host reboot event "
                "or separate break-glass reboot drill authorization. Do not reboot, "
                "restart services, write DB rows, trigger workflows, or read secrets "
                "from this lane."
            )
            workplan["reason"] = (
                "Current readback shows service, product data, backup, and "
                "StockPlatform freshness/ingestion are green. P0-006 remains event "
                "gated only because the 10-minute recovery SLO needs a fresh "
                "all-host reboot observation or a separately authorized reboot "
                "drill."
            )
            workplan["safe_next_step"] = (
                "keep_timer_live_wait_for_next_all_host_reboot_event_or_separately_"
                "approved_reboot_drill_to_prove_10_minute_slo"
            )
            workplan["status"] = "blocked_waiting_fresh_all_host_reboot_window"
        else:
            professional_fix["action"] = (
                "Continue P0-006 from the reboot SLO scorecard truth: close the "
                "service, product-data, backup, 188 service, host reachability, "
                "disk, and Wazuh blockers in controlled lanes; keep the "
                "controlled service/data/backup readback visible as the source "
                "selector for these blockers. For Windows 99, use the "
                "windows99_verify_collection packet to collect no-secret Verify "
                "stdout, keep windows99_management_channel visible for the current "
                "remote execution blocker, and rerun the scorecard. For StockPlatform "
                "freshness/ingestion postgres_not_ready, use the production "
                "migration/control-channel path with target selector, dry-run, "
                "rollback, public API verifier, and KM/RAG/MCP/PlayBook writeback. "
                "Do not reboot, restart services, write DB rows, fake freshness, "
                "trigger workflows, or read secrets from this lane."
            )
            workplan["reason"] = (
                "The current reboot SLO scorecard is blocked, not merely waiting "
                "for a fresh reboot window. Controlled service/product-data/backup "
                "readback is present, but its blocker fields remain open and must "
                "stay visible in the priority readback until controlled recovery "
                "evidence closes."
            )
            workplan["safe_next_step"] = str(reboot_slo.get("safe_next_step") or "")
            workplan["status"] = "blocked_reboot_auto_recovery_slo_not_ready"
        professional_fix["owner"] = (
            "reboot auto-recovery lane plus drill preflight readback"
        )

    p0_004_ready = (
        state["p0_004_template_copy_apply_gate_runtime_readback_state"] == "ready"
        and state["p0_004_runtime_enablement_runtime_readback_state"] == "ready"
    )
    payload["status"] = (
        "p0_006_event_gated_all_immediate_apply_gaps_closed"
        if p0_004_ready and p0_006_event_gated
        else "p0_006_blocked_reboot_auto_recovery_slo_not_ready"
    )
    if p0_006_event_gated:
        payload["next_execution_order"] = [
            (
                "P0-006: service/data/backup/StockPlatform readback is green, but "
                "the 10-minute reboot SLO cannot be claimed until a fresh all-host "
                "reboot event or separately approved reboot drill; keep timer live "
                "and do not reboot/restart/DB-write from this lane."
            ),
            (
                "P0-006-REBOOT-DRILL-PREFLIGHT-READBACK: production endpoint is 200 "
                "and preflight is ready for separate break-glass reboot drill "
                "authorization; do not reboot from this lane without that explicit "
                "drill authorization."
            ),
            (
                "P0-004-TEMPLATE-COPY-APPLY-GATE-READBACK: production apply gate, "
                "template-copy receipt, and runtime enablement readbacks are ready; "
                "keep closed unless production readback regresses."
            ),
            (
                "NEXT: keep this priority-order API as the source of truth before "
                "opening the next blocker-free mainline item; stale snapshots, old "
                "failed CD runs, and retired GitHub lanes must not reorder closed work."
            ),
        ]
    else:
        payload["next_execution_order"] = [
            (
                "P0-006: reboot SLO scorecard is blocked; close the active "
                "service/product-data/backup/host/Wazuh blockers in controlled "
                "lanes, and keep StockPlatform postgres_not_ready on the "
                "production migration/control-channel path with verifier and "
                "metadata writeback."
            ),
            (
                "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT: "
                "freshness/ingestion are not_configured with postgres_not_ready; "
                "do not manually DB-write or fake freshness."
            ),
            (
                "P0-006-REBOOT-DRILL-PREFLIGHT-READBACK: drill preflight remains "
                "blocked until service/product-data/backup/host readiness turns "
                "green; reboot stays break-glass."
            ),
            (
                "NEXT: keep this priority-order API as the source of truth before "
                "opening the next blocker-free mainline item; stale snapshots, old "
                "failed CD runs, and retired GitHub lanes must not reorder closed work."
            ),
        ]
    _set_rollups_and_summary(
        payload=payload,
        current_head=current_head,
        state=state,
        p0_004_ready=p0_004_ready,
        p0_006_event_gated=p0_006_event_gated,
        runtime_source_truth_available=runtime_source_truth_available,
        runtime_sha=runtime_sha,
    )


def _refresh_rollups_after_stockplatform_overlay(
    payload: dict[str, Any],
    state: dict[str, Any],
) -> None:
    rollups = _dict(payload.setdefault("rollups", {}))
    active_blockers = _strings(state.get("active_p0_live_active_blockers"))
    stock_ready = state.get("stockplatform_public_api_live_readback_state") == "ready"
    stock_blocked = (
        state.get("stockplatform_public_api_live_readback_state") == "blocked"
    )
    rollups["stockplatform_public_api_runtime_ready"] = stock_ready
    rollups["stockplatform_public_api_runtime_blocked"] = stock_blocked
    rollups["stockplatform_public_api_live_drift_from_committed_scorecard"] = bool(
        state.get("stockplatform_public_api_live_drift_from_committed_scorecard")
        is True
    )
    recovery_control_path_blockers = _strings(
        state.get("stockplatform_public_api_recovery_control_path_active_blockers")
    )
    rollups["stockplatform_public_api_recovery_control_path_status"] = str(
        state.get("stockplatform_public_api_recovery_control_path_status") or "unknown"
    )
    rollups["stockplatform_public_api_recovery_control_path_blocked"] = bool(
        recovery_control_path_blockers
    )
    rollups["stockplatform_public_api_recovery_control_path_blocker_count"] = len(
        recovery_control_path_blockers
    )
    rollups["stockplatform_postgres_readiness_or_data_source_readback_present"] = bool(
        state.get("stockplatform_postgres_readiness_or_data_source_readback_present")
        is True
    )
    rollups["stockplatform_postgres_readiness_or_data_source_receipt_provided"] = bool(
        state.get("stockplatform_postgres_readiness_or_data_source_receipt_provided")
        is True
    )
    rollups["stockplatform_postgres_readiness_or_data_source_postgres_ready"] = bool(
        state.get("stockplatform_postgres_readiness_or_data_source_postgres_ready")
        is True
    )
    rollups["stockplatform_source_contract_readback_present"] = bool(
        state.get("stockplatform_source_contract_readback_present") is True
    )
    rollups["stockplatform_source_contract_receipt_provided"] = bool(
        state.get("stockplatform_source_contract_receipt_provided") is True
    )
    rollups["stockplatform_source_contract_ready"] = bool(
        state.get("stockplatform_source_contract_ready") is True
    )
    rollups["stockplatform_source_contract_non_ok_source_count"] = _int(
        state.get("stockplatform_source_contract_non_ok_source_count")
    )
    rollups["stockplatform_freshness_status"] = str(
        state.get("stockplatform_freshness_status") or "unknown"
    )
    rollups["stockplatform_ingestion_status"] = str(
        state.get("stockplatform_ingestion_status") or "unknown"
    )
    rollups["stockplatform_latest_trading_date"] = str(
        state.get("stockplatform_latest_trading_date") or ""
    )
    rollups["stockplatform_freshness_blockers"] = _strings(
        state.get("stockplatform_freshness_blockers")
    )
    rollups["stockplatform_ingestion_blockers"] = _strings(
        state.get("stockplatform_ingestion_blockers")
    )
    rollups["stockplatform_freshness_sla_source_count"] = _int(
        state.get("stockplatform_freshness_sla_source_count")
    )
    rollups["stockplatform_freshness_source_count"] = _int(
        state.get("stockplatform_freshness_source_count")
    )
    rollups["stockplatform_freshness_non_ok_source_count"] = _int(
        state.get("stockplatform_freshness_non_ok_source_count")
    )
    rollups["active_p0_live_active_blocker_count"] = len(active_blockers)
    rollups["active_p0_event_gated_by_fresh_reboot_window_only"] = (
        rollups.get("active_p0_event_gated_by_fresh_reboot_window_only") is True
        and not stock_blocked
    )

    summary = _dict(payload.setdefault("summary", {}))
    summary["status"] = str(payload.get("status") or "")
    summary["active_p0_state"] = str(state.get("active_p0_state") or "")
    summary["active_p0_live_active_blockers"] = active_blockers
    summary["stockplatform_public_api_runtime_status"] = str(
        state.get("stockplatform_public_api_runtime_status") or "unknown"
    )
    summary["stockplatform_public_api_runtime_ready"] = stock_ready
    summary["stockplatform_public_api_live_drift_from_committed_scorecard"] = bool(
        state.get("stockplatform_public_api_live_drift_from_committed_scorecard")
        is True
    )
    summary["stockplatform_public_api_recovery_control_path_status"] = str(
        state.get("stockplatform_public_api_recovery_control_path_status") or "unknown"
    )
    summary["stockplatform_public_api_recovery_control_path_blockers"] = (
        recovery_control_path_blockers
    )
    summary["stockplatform_postgres_readiness_or_data_source_readback_status"] = str(
        state.get("stockplatform_postgres_readiness_or_data_source_readback_status")
        or "unknown"
    )
    summary["stockplatform_postgres_readiness_or_data_source_receipt_provided"] = bool(
        state.get("stockplatform_postgres_readiness_or_data_source_receipt_provided")
        is True
    )
    summary["stockplatform_source_contract_readback_status"] = str(
        state.get("stockplatform_source_contract_readback_status") or "unknown"
    )
    summary["stockplatform_source_contract_receipt_provided"] = bool(
        state.get("stockplatform_source_contract_receipt_provided") is True
    )
    summary["stockplatform_source_contract_non_ok_source_count"] = _int(
        state.get("stockplatform_source_contract_non_ok_source_count")
    )
    summary["stockplatform_freshness_status"] = str(
        state.get("stockplatform_freshness_status") or "unknown"
    )
    summary["stockplatform_ingestion_status"] = str(
        state.get("stockplatform_ingestion_status") or "unknown"
    )
    summary["stockplatform_latest_trading_date"] = str(
        state.get("stockplatform_latest_trading_date") or ""
    )
    summary["stockplatform_freshness_blockers"] = _strings(
        state.get("stockplatform_freshness_blockers")
    )
    summary["stockplatform_ingestion_blockers"] = _strings(
        state.get("stockplatform_ingestion_blockers")
    )
    summary["stockplatform_freshness_sla_source_count"] = _int(
        state.get("stockplatform_freshness_sla_source_count")
    )
    summary["stockplatform_freshness_source_count"] = _int(
        state.get("stockplatform_freshness_source_count")
    )
    summary["stockplatform_freshness_non_ok_source_count"] = _int(
        state.get("stockplatform_freshness_non_ok_source_count")
    )
    summary["next_executable_mainline_workplan_id"] = str(
        state.get("next_executable_mainline_workplan_id") or ""
    )
    summary["next_executable_mainline_state"] = str(
        state.get("next_executable_mainline_state") or ""
    )
    _apply_parallel_mainline_execution_overlay(payload)


def _next_stockplatform_data_retry_readback_at(
    now: datetime | None = None,
) -> str:
    current = now or datetime.now(ZoneInfo("Asia/Taipei"))
    if current.tzinfo is None:
        current = current.replace(tzinfo=ZoneInfo("Asia/Taipei"))
    for retry_time in _STOCKPLATFORM_DATA_RETRY_READBACK_TIMES:
        hour, minute = retry_time.split(":", maxsplit=1)
        candidate = current.replace(
            hour=int(hour),
            minute=int(minute),
            second=0,
            microsecond=0,
        )
        if candidate > current:
            return candidate.isoformat()
    next_day = current.replace(
        hour=19,
        minute=12,
        second=0,
        microsecond=0,
    )
    next_day = next_day.replace(day=current.day) + timedelta(days=1)
    return next_day.isoformat()


def _stockplatform_external_data_wait_active(state: dict[str, Any]) -> bool:
    data_dependency = str(
        state.get("stockplatform_public_api_controlled_recovery_data_dependency")
        or state.get("stockplatform_public_api_data_dependency_classification")
        or ""
    )
    blockers = _strings(state.get("stockplatform_freshness_blockers")) + _strings(
        state.get("stockplatform_ingestion_blockers")
    )
    return (
        state.get("stockplatform_source_contract_readback_present") is True
        and state.get("stockplatform_source_contract_ready") is not True
        and data_dependency
        in {
            "freshness_or_ingestion_not_ready",
            "ai_recommendations_stale_after_core_recovered",
        }
        and any(
            blocker
            in {
                "core_margin_short_daily_missing",
                "ai_recommendations_stale",
                "core.margin_short_daily_incomplete",
            }
            for blocker in blockers
        )
    )


def _stockplatform_ai_recommendations_wait(
    data_dependency_classification: str,
) -> bool:
    return (
        data_dependency_classification
        == "ai_recommendations_stale_after_core_recovered"
    )


def _apply_parallel_mainline_execution_overlay(payload: dict[str, Any]) -> None:
    state = _dict(payload.setdefault("mainline_execution_state", {}))
    items = _list(payload.get("commander_inserted_requirement_work_items"))
    if not items:
        return
    next_item = next(
        (
            _dict(item)
            for item in items
            if item.get("status") in {"in_progress", "pending"}
            and str(item.get("priority") or "") == "P0"
            and str(item.get("id") or "") != "CIR-P0-006"
        ),
        _dict(items[0]),
    )
    external_wait_active = _stockplatform_external_data_wait_active(state)
    retry_readback_at = (
        _next_stockplatform_data_retry_readback_at()
        if external_wait_active
        else ""
    )
    overlay = {
        "enabled": external_wait_active,
        "policy": str(
            state.get("next_executable_mainline_policy")
            or "when_p0_has_external_gate_do_not_idle"
        ),
        "current_p0_workplan_id": str(state.get("active_p0_workplan_id") or ""),
        "current_p0_state": str(state.get("active_p0_state") or ""),
        "current_p0_wait_state": (
            "external_stockplatform_data_retry_wait"
            if external_wait_active
            else "active_p0_not_external_wait"
        ),
        "retry_readback_at": retry_readback_at,
        "parallel_work_item": {
            "id": str(next_item.get("id") or ""),
            "priority": str(next_item.get("priority") or ""),
            "lane": str(next_item.get("lane") or ""),
            "status": str(next_item.get("status") or ""),
            "mapped_workplan_id": str(next_item.get("mapped_workplan_id") or ""),
            "next_action": str(next_item.get("next_action") or ""),
        },
        "report_contract": {
            "current_p0": str(state.get("active_p0_workplan_id") or ""),
            "action": "advance_parallel_mainline_work_item_while_external_data_retry_waits",
            "evidence": "priority_readback.parallel_mainline_execution",
            "next_action": str(next_item.get("next_action") or ""),
        },
        "forbidden_actions": _PARALLEL_MAINLINE_FORBIDDEN_ACTIONS,
    }
    payload["mainline_parallel_execution"] = overlay

    state["parallel_mainline_execution_enabled"] = external_wait_active
    state["parallel_mainline_current_p0_wait_state"] = overlay[
        "current_p0_wait_state"
    ]
    state["parallel_mainline_retry_readback_at"] = retry_readback_at
    state["parallel_mainline_work_item_id"] = overlay["parallel_work_item"]["id"]
    state["parallel_mainline_work_item_priority"] = overlay["parallel_work_item"][
        "priority"
    ]
    state["parallel_mainline_work_item_lane"] = overlay["parallel_work_item"]["lane"]
    state["parallel_mainline_next_action"] = overlay["parallel_work_item"][
        "next_action"
    ]
    state["parallel_mainline_forbidden_actions"] = _PARALLEL_MAINLINE_FORBIDDEN_ACTIONS

    rollups = _dict(payload.setdefault("rollups", {}))
    rollups["parallel_mainline_execution_enabled"] = external_wait_active
    rollups["parallel_mainline_work_item_id"] = overlay["parallel_work_item"]["id"]
    rollups["parallel_mainline_retry_readback_at"] = retry_readback_at

    summary = _dict(payload.setdefault("summary", {}))
    summary["parallel_mainline_execution_enabled"] = external_wait_active
    summary["parallel_mainline_current_p0_wait_state"] = overlay[
        "current_p0_wait_state"
    ]
    summary["parallel_mainline_retry_readback_at"] = retry_readback_at
    summary["parallel_mainline_work_item_id"] = overlay["parallel_work_item"]["id"]
    summary["parallel_mainline_work_item_priority"] = overlay["parallel_work_item"][
        "priority"
    ]
    summary["parallel_mainline_work_item_lane"] = overlay["parallel_work_item"][
        "lane"
    ]
    summary["parallel_mainline_next_action"] = overlay["parallel_work_item"][
        "next_action"
    ]


def _set_rollups_and_summary(
    *,
    payload: dict[str, Any],
    current_head: dict[str, Any],
    state: dict[str, Any],
    p0_004_ready: bool,
    p0_006_event_gated: bool,
    runtime_source_truth_available: bool,
    runtime_sha: str,
) -> None:
    completed = _list(payload.get("completed_in_priority_order"))
    in_progress = _list(payload.get("in_progress_or_blocked_in_priority_order"))
    latest_source_sha = (
        runtime_sha
        if runtime_source_truth_available
        else str(current_head.get("latest_successful_deployed_source_sha") or "")
    )
    active_blockers = _strings(state.get("active_p0_live_active_blockers"))
    active_gap_count = _int(state.get("active_p0_immediate_apply_gap_count"))

    payload["rollups"] = {
        "completed_p0_count": len(completed),
        "in_progress_or_blocked_count": len(in_progress),
        "active_p0_immediate_apply_gap_count": active_gap_count,
        "active_p0_event_gated_by_fresh_reboot_window_only": p0_006_event_gated,
        "active_p0_live_active_blocker_count": len(active_blockers),
        "controlled_service_data_backup_readback_present": (
            state.get("controlled_service_data_backup_readback_present") is True
        ),
        "controlled_service_data_backup_blocker_count": _int(
            state.get("controlled_service_data_backup_blocker_count")
        ),
        "controlled_service_data_backup_can_clear_blockers": (
            state.get("controlled_service_data_backup_can_clear_blockers") is True
        ),
        "windows99_verify_collection_status": str(
            state.get("windows99_verify_collection_status") or "unknown"
        ),
        "windows99_verify_collection_can_collect_no_secret": (
            state.get("windows99_verify_collection_can_collect_no_secret") is True
        ),
        "windows99_verify_collection_blocker_count": _int(
            state.get("windows99_verify_collection_blocker_count")
        ),
        "windows99_verify_collection_host99_reachable": (
            state.get("windows99_verify_collection_host99_reachable") is True
        ),
        "windows99_verify_collection_host99_uptime_known": (
            state.get("windows99_verify_collection_host99_uptime_known") is True
        ),
        "windows99_management_readback_present": (
            state.get("windows99_management_readback_present") is True
        ),
        "windows99_remote_execution_channel_ready": (
            state.get("windows99_remote_execution_channel_ready") is True
        ),
        "windows99_ssh_batch_status": str(
            state.get("windows99_ssh_batch_status") or "unknown"
        ),
        "windows99_rdp_console_reachable": (
            state.get("windows99_rdp_console_reachable") is True
        ),
        "windows99_hyperv_vmconnect_open": (
            state.get("windows99_hyperv_vmconnect_open") is True
        ),
        "windows99_local_console_channel_reachable": (
            state.get("windows99_local_console_channel_reachable") is True
        ),
        "windows99_console_collection_channels": _strings(
            state.get("windows99_console_collection_channels")
        ),
        "p0_004_runtime_readback_ready": p0_004_ready,
        "reboot_drill_preflight_runtime_readback_ready": (
            state.get("reboot_drill_preflight_runtime_readback_state") == "ready"
        ),
        "production_source_truth_available": runtime_source_truth_available,
        "stale_current_head_metadata_normalized": runtime_source_truth_available,
        "stale_cd_runs_reopen_closed_work": False,
        "break_glass_reboot_drill_required": True,
    }
    payload["summary"] = {
        "status": str(payload.get("status") or ""),
        "active_p0_workplan_id": str(state.get("active_p0_workplan_id") or ""),
        "active_p0_state": str(state.get("active_p0_state") or ""),
        "active_p0_readiness_percent": _int(
            state.get("active_p0_readiness_percent")
        ),
        "active_p0_live_active_blockers": active_blockers,
        "controlled_service_data_backup_readback_present": (
            state.get("controlled_service_data_backup_readback_present") is True
        ),
        "controlled_service_data_backup_readback_status": str(
            state.get("controlled_service_data_backup_readback_status") or ""
        ),
        "controlled_service_data_backup_blocker_count": _int(
            state.get("controlled_service_data_backup_blocker_count")
        ),
        "controlled_service_data_backup_blocking_fields": _strings(
            state.get("controlled_service_data_backup_blocking_fields")
        ),
        "controlled_service_data_backup_can_clear_blockers": (
            state.get("controlled_service_data_backup_can_clear_blockers") is True
        ),
        "controlled_service_data_backup_next_safe_action": str(
            state.get("controlled_service_data_backup_next_safe_action") or ""
        ),
        "windows99_verify_collection_status": str(
            state.get("windows99_verify_collection_status") or "unknown"
        ),
        "windows99_verify_collection_can_collect_no_secret": (
            state.get("windows99_verify_collection_can_collect_no_secret") is True
        ),
        "windows99_verify_collection_blocker_count": _int(
            state.get("windows99_verify_collection_blocker_count")
        ),
        "windows99_verify_collection_blockers": _strings(
            state.get("windows99_verify_collection_blockers")
        ),
        "windows99_verify_collection_host99_reachable": (
            state.get("windows99_verify_collection_host99_reachable") is True
        ),
        "windows99_verify_collection_host99_uptime_known": (
            state.get("windows99_verify_collection_host99_uptime_known") is True
        ),
        "windows99_verify_collection_post_verifier": str(
            state.get("windows99_verify_collection_post_verifier") or ""
        ),
        "windows99_management_readback_present": (
            state.get("windows99_management_readback_present") is True
        ),
        "windows99_management_host_reachable": (
            state.get("windows99_management_host_reachable") is True
        ),
        "windows99_remote_execution_channel_ready": (
            state.get("windows99_remote_execution_channel_ready") is True
        ),
        "windows99_ssh_batch_status": str(
            state.get("windows99_ssh_batch_status") or "unknown"
        ),
        "windows99_rdp_console_reachable": (
            state.get("windows99_rdp_console_reachable") is True
        ),
        "windows99_hyperv_vmconnect_open": (
            state.get("windows99_hyperv_vmconnect_open") is True
        ),
        "windows99_local_console_channel_reachable": (
            state.get("windows99_local_console_channel_reachable") is True
        ),
        "windows99_console_collection_channels": _strings(
            state.get("windows99_console_collection_channels")
        ),
        "windows99_winrm_http_open": (
            state.get("windows99_winrm_http_open") is True
        ),
        "windows99_winrm_https_open": (
            state.get("windows99_winrm_https_open") is True
        ),
        "latest_successful_deployed_source_sha": latest_source_sha,
        "latest_successful_deployed_source_short_sha": latest_source_sha[:10],
        "latest_successful_deploy_marker": str(
            current_head.get("latest_successful_deploy_marker") or ""
        ),
        "next_executable_mainline_workplan_id": str(
            state.get("next_executable_mainline_workplan_id") or ""
        ),
        "next_executable_mainline_state": str(
            state.get("next_executable_mainline_state") or ""
        ),
        "production_source_truth_available": runtime_source_truth_available,
        "stale_current_head_metadata_normalized": runtime_source_truth_available,
    }


def _apply_commander_inserted_requirement_work_items(
    payload: dict[str, Any],
) -> None:
    priority_rank = {"P0": 0, "P1": 1, "P2": 2, "P3": 3}
    ordered_source_items = sorted(
        _COMMANDER_INSERTED_REQUIREMENT_WORK_ITEMS,
        key=lambda item: (
            priority_rank.get(str(item["priority"]), 99),
            _int(item.get("order")),
            str(item["id"]),
        ),
    )
    items = [
        {
            **item,
            "order": index,
            "source": _COMMANDER_INSERTED_REQUIREMENT_SOURCE,
            "visible_surface": "/zh-TW/awooop/work-items",
        }
        for index, item in enumerate(ordered_source_items, start=1)
    ]
    priority_counts = {
        priority: sum(1 for item in items if item["priority"] == priority)
        for priority in ("P0", "P1", "P2", "P3")
    }
    status_counts = {
        status: sum(1 for item in items if item["status"] == status)
        for status in ("done", "in_progress", "pending", "blocked", "deferred")
    }
    next_item = next(
        (
            item
            for item in items
            if item["status"] in {"in_progress", "pending", "blocked"}
        ),
        items[0],
    )

    payload["commander_inserted_requirement_work_items"] = items

    rollups = _dict(payload.setdefault("rollups", {}))
    rollups["commander_inserted_requirement_work_item_count"] = len(items)
    rollups["commander_inserted_requirement_p0_count"] = priority_counts["P0"]
    rollups["commander_inserted_requirement_p1_count"] = priority_counts["P1"]
    rollups["commander_inserted_requirement_p2_count"] = priority_counts["P2"]
    rollups["commander_inserted_requirement_p3_count"] = priority_counts["P3"]
    rollups["commander_inserted_requirement_done_count"] = status_counts["done"]
    rollups["commander_inserted_requirement_in_progress_count"] = status_counts[
        "in_progress"
    ]
    rollups["commander_inserted_requirement_pending_count"] = status_counts[
        "pending"
    ]
    rollups["commander_inserted_requirement_blocked_count"] = status_counts[
        "blocked"
    ]
    rollups["commander_inserted_requirement_deferred_count"] = status_counts[
        "deferred"
    ]

    summary = _dict(payload.setdefault("summary", {}))
    summary["commander_inserted_requirement_work_item_count"] = len(items)
    summary["commander_inserted_requirement_p0_count"] = priority_counts["P0"]
    summary["commander_inserted_requirement_p1_count"] = priority_counts["P1"]
    summary["commander_inserted_requirement_p2_count"] = priority_counts["P2"]
    summary["commander_inserted_requirement_p3_count"] = priority_counts["P3"]
    summary["commander_inserted_requirement_done_count"] = status_counts["done"]
    summary["commander_inserted_requirement_in_progress_count"] = status_counts[
        "in_progress"
    ]
    summary["commander_inserted_requirement_pending_count"] = status_counts[
        "pending"
    ]
    summary["commander_inserted_requirement_blocked_count"] = status_counts[
        "blocked"
    ]
    summary["commander_inserted_requirement_deferred_count"] = status_counts[
        "deferred"
    ]
    summary["commander_inserted_requirement_next_id"] = str(next_item["id"])
    summary["commander_inserted_requirement_next_priority"] = str(
        next_item["priority"]
    )
    summary["commander_inserted_requirement_next_action"] = str(
        next_item["next_action"]
    )
    summary["commander_inserted_requirement_source"] = (
        _COMMANDER_INSERTED_REQUIREMENT_SOURCE
    )
    _apply_parallel_mainline_execution_overlay(payload)


def apply_ai_automation_node_receipts(payload: dict[str, Any]) -> None:
    """Refresh metadata-only AI automation node receipts after live overlays."""
    _apply_ai_automation_node_receipts(payload)


def apply_ai_automation_live_closure_readbacks(
    payload: dict[str, Any],
    *,
    executor_readback: dict[str, Any] | None = None,
    verifier_readback: dict[str, Any] | None = None,
    consumer_readback: dict[str, Any] | None = None,
    telegram_alert_context_verifier_readback: dict[str, Any] | None = None,
) -> None:
    """Overlay live AI-loop executor/verifier/consumer readbacks onto receipts."""

    summary = _dict(payload.setdefault("summary", {}))
    rollups = _dict(payload.setdefault("rollups", {}))
    state = _dict(payload.setdefault("mainline_execution_state", {}))

    executor = _dict(executor_readback)
    executor_rollups = _dict(executor.get("rollups"))
    executor_active_blockers = _strings(executor.get("active_blockers"))
    if executor:
        summary["ai_automation_executor_status"] = str(executor.get("status") or "")
        summary["ai_automation_executor_ready_execution_batch_count"] = _int(
            executor_rollups.get("ready_execution_batch_count")
        )
        summary["ai_automation_executor_post_apply_verifier_ready_count"] = _int(
            executor_rollups.get("post_apply_verifier_ready_count")
        )
        summary["ai_automation_executor_log_source_grouping_key_count"] = _int(
            executor_rollups.get("log_source_grouping_key_count")
        )
        summary["ai_automation_executor_metadata_only_log_source_tagging_ready"] = bool(
            executor_rollups.get("metadata_only_log_source_tagging_ready") is True
        )
        summary["ai_automation_executor_controlled_dispatch_ready"] = bool(
            executor_rollups.get("controlled_executor_dispatch_ready") is True
        )
        summary["ai_automation_executor_runtime_dispatch_performed"] = bool(
            executor_rollups.get("runtime_dispatch_performed") is True
        )
        summary["ai_automation_executor_active_blockers"] = executor_active_blockers
        rollups["ai_automation_executor_active_blocker_count"] = len(
            executor_active_blockers
        )
        state["ai_automation_executor_controlled_dispatch_ready"] = summary[
            "ai_automation_executor_controlled_dispatch_ready"
        ]

    verifier = _dict(verifier_readback)
    verifier_rollups = _dict(verifier.get("rollups"))
    verifier_active_blockers = _strings(verifier.get("active_blockers"))
    if verifier:
        summary["ai_automation_post_write_verifier_status"] = str(
            verifier.get("status") or ""
        )
        summary["ai_automation_post_write_verifier_dry_run_ready"] = bool(
            verifier_rollups.get("dry_run_ready") is True
        )
        summary["ai_automation_post_write_verifier_passed_node_count"] = _int(
            verifier_rollups.get("passed_verifier_node_count")
        )
        summary["ai_automation_post_write_verifier_verified_target_count"] = _int(
            verifier_rollups.get("verified_target_count")
        )
        summary["ai_automation_post_write_verifier_verified_candidate_receipt_count"] = (
            _int(verifier_rollups.get("verified_candidate_receipt_count"))
        )
        summary["ai_automation_post_write_verifier_active_blockers"] = (
            verifier_active_blockers
        )
        rollups["ai_automation_post_write_verifier_active_blocker_count"] = len(
            verifier_active_blockers
        )
        state["ai_automation_post_write_verifier_dry_run_ready"] = summary[
            "ai_automation_post_write_verifier_dry_run_ready"
        ]

    consumer = _dict(consumer_readback)
    consumer_rollups = _dict(consumer.get("rollups"))
    consumer_control = _dict(consumer.get("controlled_consume"))
    telegram_context = _dict(consumer.get("telegram_alert_learning_context"))
    consumer_active_blockers = _strings(consumer.get("active_blockers"))
    if consumer:
        context_receipt_counts = {
            "km": _int(consumer_rollups.get("km_context_receipt_write_count")),
            "rag": _int(consumer_rollups.get("rag_context_receipt_write_count")),
            "playbook": _int(
                consumer_rollups.get("playbook_context_receipt_write_count")
            ),
            "mcp": _int(consumer_rollups.get("mcp_context_receipt_write_count")),
            "verifier": _int(
                consumer_rollups.get("verifier_context_receipt_write_count")
            ),
            "ai_agent": _int(
                consumer_rollups.get("ai_agent_context_receipt_write_count")
            ),
        }
        summary["ai_automation_consumer_status"] = str(consumer.get("status") or "")
        summary["ai_automation_consumer_readback_ready"] = bool(
            consumer_rollups.get("controlled_consumer_readback_ready") is True
        )
        summary["ai_automation_consumer_controlled_consume_allowed"] = bool(
            consumer_control.get("controlled_consume_allowed") is True
        )
        summary["ai_automation_consumer_runtime_target_write_performed"] = bool(
            consumer_rollups.get("runtime_target_write_performed") is True
            or consumer_control.get("runtime_target_write_performed") is True
        )
        summary["ai_automation_consumer_ready_target_count"] = _int(
            consumer_rollups.get("ready_target_count")
        )
        summary["ai_automation_consumer_target_context_receipt_write_count"] = _int(
            consumer_rollups.get("target_context_receipt_write_count")
        )
        summary["ai_automation_consumer_post_apply_verifier_ref_count"] = _int(
            consumer_rollups.get("post_apply_verifier_ref_count")
        )
        summary["ai_automation_consumer_context_receipt_counts"] = (
            context_receipt_counts
        )
        summary["ai_automation_consumer_apply_route"] = str(
            consumer_control.get("consumer_apply_route") or ""
        )
        summary["ai_automation_telegram_alert_context_status"] = str(
            telegram_context.get("status") or ""
        )
        summary["ai_automation_telegram_alert_context_readback_ready"] = bool(
            consumer_rollups.get("telegram_alert_learning_context_readback_ready")
            is True
        )
        summary["ai_automation_telegram_alert_context_receipt_count"] = _int(
            consumer_rollups.get("telegram_alert_learning_context_receipt_count")
        )
        summary["ai_automation_telegram_alert_ai_agent_context_receipt_count"] = _int(
            consumer_rollups.get(
                "telegram_alert_learning_ai_agent_context_receipt_count"
            )
        )
        summary["ai_automation_telegram_alert_context_ready_target_count"] = _int(
            consumer_rollups.get("telegram_alert_learning_ready_target_count")
        )
        summary["ai_automation_telegram_alert_context_target_count"] = _int(
            consumer_rollups.get("telegram_alert_learning_target_count")
        )
        summary["ai_automation_consumer_active_blockers"] = consumer_active_blockers
        rollups["ai_automation_consumer_active_blocker_count"] = len(
            consumer_active_blockers
        )
        rollups["ai_automation_consumer_ready_target_count"] = summary[
            "ai_automation_consumer_ready_target_count"
        ]
        rollups["ai_automation_consumer_target_context_receipt_write_count"] = (
            summary["ai_automation_consumer_target_context_receipt_write_count"]
        )
        rollups["ai_automation_telegram_alert_context_receipt_count"] = summary[
            "ai_automation_telegram_alert_context_receipt_count"
        ]
        rollups["ai_automation_telegram_alert_ai_agent_context_receipt_count"] = (
            summary["ai_automation_telegram_alert_ai_agent_context_receipt_count"]
        )
        state["ai_automation_consumer_readback_ready"] = summary[
            "ai_automation_consumer_readback_ready"
        ]
        state["ai_automation_consumer_runtime_target_write_performed"] = summary[
            "ai_automation_consumer_runtime_target_write_performed"
        ]

    telegram_verifier = _dict(telegram_alert_context_verifier_readback)
    telegram_verifier_rollups = _dict(telegram_verifier.get("rollups"))
    telegram_verifier_blockers = _strings(telegram_verifier.get("active_blockers"))
    if telegram_verifier:
        summary["ai_automation_telegram_alert_post_apply_verifier_status"] = str(
            telegram_verifier.get("status") or ""
        )
        summary["ai_automation_telegram_alert_post_apply_verifier_ready"] = bool(
            telegram_verifier_rollups.get(
                "telegram_alert_learning_context_post_apply_verifier_ready"
            )
            is True
        )
        summary[
            "ai_automation_telegram_alert_post_apply_verified_context_receipt_count"
        ] = _int(telegram_verifier_rollups.get("verified_context_receipt_count"))
        summary[
            "ai_automation_telegram_alert_post_apply_verified_target_count"
        ] = _int(telegram_verifier_rollups.get("verified_target_count"))
        summary[
            "ai_automation_telegram_alert_post_apply_verified_ai_agent_context_receipt_count"
        ] = _int(
            telegram_verifier_rollups.get("verified_ai_agent_context_receipt_count")
        )
        summary[
            "ai_automation_telegram_alert_post_apply_verifier_ref_count"
        ] = _int(telegram_verifier_rollups.get("post_apply_verifier_ref_count"))
        summary["ai_automation_telegram_alert_post_apply_verifier_active_blockers"] = (
            telegram_verifier_blockers
        )
        rollups["ai_automation_telegram_alert_post_apply_verifier_ready"] = summary[
            "ai_automation_telegram_alert_post_apply_verifier_ready"
        ]
        rollups[
            "ai_automation_telegram_alert_post_apply_verified_context_receipt_count"
        ] = summary[
            "ai_automation_telegram_alert_post_apply_verified_context_receipt_count"
        ]
        rollups[
            "ai_automation_telegram_alert_post_apply_verified_target_count"
        ] = summary["ai_automation_telegram_alert_post_apply_verified_target_count"]
        rollups[
            "ai_automation_telegram_alert_post_apply_verifier_active_blocker_count"
        ] = len(telegram_verifier_blockers)
        state["ai_automation_telegram_alert_post_apply_verifier_ready"] = summary[
            "ai_automation_telegram_alert_post_apply_verifier_ready"
        ]

    apply_ai_automation_node_receipts(payload)


def _apply_ai_automation_node_receipts(payload: dict[str, Any]) -> None:
    summary = _dict(payload.setdefault("summary", {}))
    rollups = _dict(payload.setdefault("rollups", {}))
    runtime_timestamp = str(
        payload.get("runtime_readback_generated_at")
        or summary.get("runtime_readback_generated_at")
        or payload.get("generated_at")
        or ""
    )
    source_sha = str(summary.get("latest_successful_deployed_source_short_sha") or "")
    cd_run_id = str(summary.get("ai_loop_current_blocker_current_cd_run_id") or "")
    cd_run_status = str(
        summary.get("ai_loop_current_blocker_current_cd_run_status") or ""
    )
    blocker_id = str(summary.get("ai_loop_current_blocker_id") or "")
    safe_next_action_id = str(
        summary.get("ai_loop_current_blocker_safe_next_action_id") or ""
    )
    safe_next_action_stage = str(
        summary.get("ai_loop_current_blocker_safe_next_action_stage") or ""
    )
    receipt_inputs = _strings(
        summary.get("ai_loop_current_blocker_harbor_recovery_receipt_input_ids")
    )
    receipt_outputs = _strings(
        summary.get("ai_loop_current_blocker_harbor_recovery_receipt_output_ids")
    )
    queue_fields = _strings(
        summary.get("ai_loop_current_blocker_queue_readback_normalizer_field_ids")
    )
    log_grouping_keys = _strings(summary.get("ai_loop_log_source_grouping_keys"))
    executor_metadata_tagging_ready = bool(
        summary.get("ai_automation_executor_metadata_only_log_source_tagging_ready")
        is True
    )
    executor_log_grouping_key_count = _int(
        summary.get("ai_automation_executor_log_source_grouping_key_count")
    )
    executor_dispatch_ready = bool(
        summary.get("ai_automation_executor_controlled_dispatch_ready") is True
    )
    executor_runtime_dispatch_performed = bool(
        summary.get("ai_automation_executor_runtime_dispatch_performed") is True
    )
    verifier_dry_run_ready = bool(
        summary.get("ai_automation_post_write_verifier_dry_run_ready") is True
    )
    verifier_passed_node_count = _int(
        summary.get("ai_automation_post_write_verifier_passed_node_count")
    )
    consumer_readback_ready = bool(
        summary.get("ai_automation_consumer_readback_ready") is True
    )
    consumer_runtime_target_write_performed = bool(
        summary.get("ai_automation_consumer_runtime_target_write_performed") is True
    )
    consumer_ready_target_count = _int(
        summary.get("ai_automation_consumer_ready_target_count")
    )
    consumer_context_receipt_write_count = _int(
        summary.get("ai_automation_consumer_target_context_receipt_write_count")
    )
    consumer_post_apply_verifier_ref_count = _int(
        summary.get("ai_automation_consumer_post_apply_verifier_ref_count")
    )
    consumer_context_counts = _dict(
        summary.get("ai_automation_consumer_context_receipt_counts")
    )
    telegram_alert_context_ready = bool(
        summary.get("ai_automation_telegram_alert_context_readback_ready") is True
    )
    telegram_alert_context_receipt_count = _int(
        summary.get("ai_automation_telegram_alert_context_receipt_count")
    )
    telegram_alert_ai_agent_context_receipt_count = _int(
        summary.get("ai_automation_telegram_alert_ai_agent_context_receipt_count")
    )
    telegram_alert_post_apply_verifier_ready = bool(
        summary.get("ai_automation_telegram_alert_post_apply_verifier_ready") is True
    )
    telegram_alert_post_apply_verified_context_receipt_count = _int(
        summary.get(
            "ai_automation_telegram_alert_post_apply_verified_context_receipt_count"
        )
    )
    telegram_alert_post_apply_verified_target_count = _int(
        summary.get("ai_automation_telegram_alert_post_apply_verified_target_count")
    )
    telegram_alert_post_apply_verifier_ref_count = _int(
        summary.get("ai_automation_telegram_alert_post_apply_verifier_ref_count")
    )
    consumer_apply_route = str(summary.get("ai_automation_consumer_apply_route") or "")
    normalizer_ready = bool(
        queue_fields
        or log_grouping_keys
        or executor_metadata_tagging_ready
        or executor_log_grouping_key_count > 0
    )
    candidate_ready = bool(safe_next_action_id or executor_dispatch_ready)
    execution_boundary_ready = bool(
        telegram_alert_context_ready
        or consumer_runtime_target_write_performed
        or executor_runtime_dispatch_performed
        or executor_dispatch_ready
    )
    post_verifier_ready = bool(
        receipt_outputs
        or verifier_dry_run_ready
        or telegram_alert_post_apply_verifier_ready
        or consumer_post_apply_verifier_ref_count > 0
    )
    learning_writeback_ready = bool(
        (
            consumer_readback_ready
            and consumer_context_receipt_write_count >= consumer_ready_target_count
            and consumer_ready_target_count > 0
        )
        or (
            telegram_alert_context_ready
            and telegram_alert_ai_agent_context_receipt_count > 0
        )
    )

    base_refs = [
        "awoooi-priority-work-order-readback",
        _COMMANDER_INSERTED_REQUIREMENT_SOURCE,
    ]
    if source_sha:
        base_refs.append(f"production_source:{source_sha}")
    if cd_run_id:
        base_refs.append(f"gitea_cd_run:{cd_run_id}:{cd_run_status or 'unknown'}")

    node_specs = [
        {
            "node_id": "sensor_evidence",
            "node_label": "Sensor / Evidence",
            "node_status": "ready",
            "work_item_id": "CIR-P0-AILOOP-001",
            "lane_id": "p0_runtime_lane",
            "evidence_refs": [*base_refs, *receipt_inputs[:3]],
            "verifier_result": "production_readback_present",
            "next_action": "keep source/CD/runtime readback attached to this trace",
        },
        {
            "node_id": "normalizer_log_tags",
            "node_label": "Normalizer / LOG tags",
            "node_status": "ready" if normalizer_ready else "queued",
            "work_item_id": "CIR-P0-LOG-002",
            "lane_id": "log_tagging_classification_clustering",
            "evidence_refs": [
                *queue_fields[:4],
                *log_grouping_keys[:4],
                f"executor_log_grouping_keys:{executor_log_grouping_key_count}",
                f"metadata_only_tagging_ready:{executor_metadata_tagging_ready}",
            ],
            "verifier_result": "queue_normalizer_fields_readback"
            if queue_fields
            else (
                "executor_log_source_tagging_readback"
                if normalizer_ready
                else "normalizer_contract_required"
            ),
            "next_action": "extend tag taxonomy to Telegram, CPU, backup, freshness",
        },
        {
            "node_id": "ai_lane_route",
            "node_label": "AI Lane",
            "node_status": "ready",
            "work_item_id": "CIR-P0-AILOOP-001",
            "lane_id": "ai_loop_agent_mainline",
            "evidence_refs": [blocker_id, safe_next_action_stage],
            "verifier_result": "ai_loop_current_blocker_routed",
            "next_action": "keep every alert/work item attached to an AI lane",
        },
        {
            "node_id": "candidate_action",
            "node_label": "Candidate",
            "node_status": "ready" if candidate_ready else "queued",
            "work_item_id": "CIR-P0-AILOOP-002",
            "lane_id": "p0_runtime_lane",
            "evidence_refs": [
                safe_next_action_id,
                safe_next_action_stage,
                f"controlled_executor_dispatch_ready:{executor_dispatch_ready}",
            ],
            "verifier_result": "safe_next_action_readback"
            if safe_next_action_id
            else (
                "controlled_executor_dispatch_ready"
                if executor_dispatch_ready
                else "candidate_action_required"
            ),
            "next_action": "emit candidate action with target selector and dry-run",
        },
        {
            "node_id": "gate_policy",
            "node_label": "Gate",
            "node_status": "ready",
            "work_item_id": "CIR-P0-013",
            "lane_id": "controlled_apply_gate_taxonomy",
            "evidence_refs": ["non_accident_gate_as_evidence", "break_glass_reserved"],
            "verifier_result": "controlled_apply_policy_readback",
            "next_action": "keep low/medium/high in controlled apply unless hard blocker",
        },
        {
            "node_id": "execution_boundary",
            "node_label": "Execution Boundary",
            "node_status": "ready" if execution_boundary_ready else "queued",
            "work_item_id": "CIR-P0-AILOOP-002",
            "lane_id": "telegram_alert_ai_automation",
            "evidence_refs": [
                "metadata_only",
                "no_secret_no_runtime_secret",
                f"consumer_ready_targets:{consumer_ready_target_count}",
                f"context_receipts:{consumer_context_receipt_write_count}",
                f"telegram_alert_context_receipts:{telegram_alert_context_receipt_count}",
                (
                    "telegram_alert_ai_agent_context_receipts:"
                    f"{telegram_alert_ai_agent_context_receipt_count}"
                ),
                f"consumer_apply_route:{consumer_apply_route}",
            ],
            "verifier_result": "controlled_consumer_context_receipt_readback"
            if consumer_runtime_target_write_performed or telegram_alert_context_ready
            else (
                "controlled_executor_dispatch_ready"
                if executor_dispatch_ready
                else "execution_receipt_required"
            ),
            "next_action": "attach Telegram alert receipt and controlled executor result",
            "telegram_receipt_ref": (
                f"controlled_consumer_readback:{consumer_context_receipt_write_count}"
                if consumer_runtime_target_write_performed
                else "metadata_only"
            ),
        },
        {
            "node_id": "post_verifier",
            "node_label": "Verifier",
            "node_status": "ready" if post_verifier_ready else "queued",
            "work_item_id": "CIR-P0-AILOOP-002",
            "lane_id": "p0_runtime_lane",
            "evidence_refs": [
                *receipt_outputs[:4],
                f"post_write_verifier_nodes:{verifier_passed_node_count}",
                f"consumer_post_apply_verifier_refs:{consumer_post_apply_verifier_ref_count}",
                (
                    "telegram_alert_post_apply_verified_context_receipts:"
                    f"{telegram_alert_post_apply_verified_context_receipt_count}"
                ),
                (
                    "telegram_alert_post_apply_verified_targets:"
                    f"{telegram_alert_post_apply_verified_target_count}"
                ),
                (
                    "telegram_alert_post_apply_verifier_refs:"
                    f"{telegram_alert_post_apply_verifier_ref_count}"
                ),
            ],
            "verifier_result": (
                "telegram_alert_learning_context_post_apply_verified"
                if telegram_alert_post_apply_verifier_ready
                else "post_verifier_receipt_readback"
                if receipt_outputs
                else (
                "post_write_verifier_dry_run_ready"
                if verifier_dry_run_ready
                else "post_verifier_required"
                )
            ),
            "next_action": "read back route/API/UI/verifier output before closing",
        },
        {
            "node_id": "learning_writeback",
            "node_label": "Learning / Writeback",
            "node_status": "ready" if learning_writeback_ready else "queued",
            "work_item_id": "CIR-P1-KM-002",
            "lane_id": "km_rag_mcp_playbook_integration",
            "evidence_refs": [
                f"context_receipts:{consumer_context_receipt_write_count}",
                f"km_context_receipt:{_int(consumer_context_counts.get('km'))}",
                f"rag_context_receipt:{_int(consumer_context_counts.get('rag'))}",
                f"playbook_context_receipt:{_int(consumer_context_counts.get('playbook'))}",
                f"mcp_context_receipt:{_int(consumer_context_counts.get('mcp'))}",
                f"telegram_alert_ai_agent_context_receipt:{telegram_alert_ai_agent_context_receipt_count}",
            ],
            "verifier_result": "consumer_context_receipt_writeback_ready"
            if learning_writeback_ready
            else "writeback_receipt_required",
            "next_action": "write KM/RAG/MCP/PlayBook trust refs after verifier",
            "km_writeback_ref": (
                f"context_receipt:km={_int(consumer_context_counts.get('km'))}"
                if learning_writeback_ready
                else "queued"
            ),
            "playbook_trust_writeback_ref": (
                "context_receipt:playbook="
                f"{_int(consumer_context_counts.get('playbook'))}"
                if learning_writeback_ready
                else "queued"
            ),
        },
    ]

    receipts = []
    for index, node in enumerate(node_specs, start=1):
        receipts.append(
            {
                "schema_version": _AI_AUTOMATION_NODE_RECEIPT_SCHEMA_VERSION,
                "trace_id": "trace:awoooi-ai-loop-current-p0",
                "run_id": cd_run_id or f"priority-readback:{source_sha or 'runtime'}",
                "node_order": index,
                "timestamp": runtime_timestamp,
                "metadata_only": True,
                "rollback_result": "not_started_no_runtime_write",
                "km_writeback_ref": ""
                if node["node_status"] != "queued"
                else "queued",
                "playbook_trust_writeback_ref": ""
                if node["node_status"] != "queued"
                else "queued",
                "mcp_evidence_ref": "metadata_registry",
                "telegram_receipt_ref": "metadata_only"
                if node["lane_id"] == "telegram_alert_ai_automation"
                else "",
                **node,
            }
        )

    status_counts = {
        status: sum(1 for item in receipts if item["node_status"] == status)
        for status in ("ready", "queued", "blocked")
    }
    lanes = sorted({str(item["lane_id"]) for item in receipts})
    work_items = sorted({str(item["work_item_id"]) for item in receipts})

    payload["ai_automation_node_receipt_schema"] = {
        "schema_version": _AI_AUTOMATION_NODE_RECEIPT_SCHEMA_VERSION,
        "required_fields": _AI_AUTOMATION_NODE_RECEIPT_REQUIRED_FIELDS,
        "metadata_only": True,
        "hard_blockers_preserved": [
            "secret_plaintext",
            "destructive_data_change",
            "reboot_or_node_drain",
            "force_push_or_repo_ref_delete",
            "paid_provider_route_change",
        ],
    }
    payload["ai_automation_node_receipts"] = receipts

    rollups["ai_automation_node_receipt_count"] = len(receipts)
    rollups["ai_automation_node_receipt_ready_count"] = status_counts["ready"]
    rollups["ai_automation_node_receipt_queued_count"] = status_counts["queued"]
    rollups["ai_automation_node_receipt_blocked_count"] = status_counts["blocked"]
    rollups["ai_automation_node_receipt_required_field_count"] = len(
        _AI_AUTOMATION_NODE_RECEIPT_REQUIRED_FIELDS
    )
    rollups["ai_automation_node_receipt_metadata_only"] = True
    rollups["ai_automation_node_receipt_lanes"] = lanes
    rollups["ai_automation_node_receipt_work_items"] = work_items

    summary["ai_automation_node_receipt_schema_version"] = (
        _AI_AUTOMATION_NODE_RECEIPT_SCHEMA_VERSION
    )
    summary["ai_automation_node_receipt_count"] = len(receipts)
    summary["ai_automation_node_receipt_ready_count"] = status_counts["ready"]
    summary["ai_automation_node_receipt_queued_count"] = status_counts["queued"]
    summary["ai_automation_node_receipt_blocked_count"] = status_counts["blocked"]
    summary["ai_automation_node_receipt_required_field_count"] = len(
        _AI_AUTOMATION_NODE_RECEIPT_REQUIRED_FIELDS
    )
    summary["ai_automation_node_receipt_metadata_only"] = True
    summary["ai_automation_node_receipt_lanes"] = lanes
    summary["ai_automation_node_receipt_work_items"] = work_items


def _mark_runtime_generated_at(payload: dict[str, Any]) -> None:
    snapshot_generated_at = str(
        payload.get("snapshot_generated_at") or payload.get("generated_at") or ""
    )
    runtime_generated_at = _taipei_now_iso()

    if snapshot_generated_at:
        payload["snapshot_generated_at"] = snapshot_generated_at
    payload["generated_at"] = runtime_generated_at
    payload["runtime_readback_generated_at"] = runtime_generated_at

    summary = _dict(payload.setdefault("summary", {}))
    if snapshot_generated_at:
        summary["snapshot_generated_at"] = snapshot_generated_at
    summary["generated_at"] = runtime_generated_at
    summary["runtime_readback_generated_at"] = runtime_generated_at

    rollups = _dict(payload.setdefault("rollups", {}))
    rollups["runtime_readback_generated_at_present"] = True


def _require_schema(payload: dict[str, Any], label: str) -> None:
    actual = payload.get("schema_version")
    if actual != _SCHEMA_VERSION:
        raise ValueError(
            f"{label}: expected schema_version={_SCHEMA_VERSION}, got {actual!r}"
        )


def _require_operation_boundaries(payload: dict[str, Any], label: str) -> None:
    boundaries = _dict(payload.get("operation_boundaries"))
    blocked_flags = {
        "credential_marker_written",
        "credential_secret_value_read",
        "database_write_or_restore_performed",
        "docker_restart_performed",
        "firewall_change_performed",
        "github_api_used",
        "github_cli_used",
        "host_write_performed",
        "k3s_restart_or_node_drain_performed",
        "nginx_restart_performed",
        "runner_registration_performed",
        "secret_or_runner_token_read",
        "workflow_dispatch_performed",
    }
    enabled = sorted(flag for flag in blocked_flags if boundaries.get(flag) is not False)
    if enabled:
        raise ValueError(f"{label}: operation boundaries must remain false: {enabled}")


def _require_mainline_consistency(payload: dict[str, Any], label: str) -> None:
    state = _dict(payload.get("mainline_execution_state"))
    active_workplan = str(state.get("active_p0_workplan_id") or "")
    if active_workplan != "P0-006":
        raise ValueError(f"{label}: active_p0_workplan_id must remain P0-006")

    if state.get("active_p0_immediate_apply_gap_count") != 0:
        raise ValueError(f"{label}: active P0 must not expose immediate apply gaps")

    if state.get("stale_snapshot_or_old_cd_runs_must_not_reopen_closed_work") is not True:
        raise ValueError(
            f"{label}: stale snapshots and old CD runs must not reopen closed work"
        )

    closed_ids = _strings(state.get("closed_p0_workplans_in_order"))
    completed_ids = [
        str(_dict(item).get("workplan_id") or "")
        for item in _list(payload.get("completed_in_priority_order"))
    ]
    if closed_ids != completed_ids:
        raise ValueError(f"{label}: closed P0 workplans must match completed order")

    in_progress = _list(payload.get("in_progress_or_blocked_in_priority_order"))
    if not in_progress:
        raise ValueError(f"{label}: in_progress_or_blocked_in_priority_order required")
    if _dict(in_progress[0]).get("workplan_id") != active_workplan:
        raise ValueError(f"{label}: first in-progress workplan must be active P0")

    next_order = _strings(payload.get("next_execution_order"))
    if not next_order or not next_order[0].startswith("P0-006:"):
        raise ValueError(f"{label}: next_execution_order must start with P0-006")


def _parse_prometheus_text_metrics(raw: str) -> dict[str, float]:
    metrics: dict[str, float] = {}
    for line in raw.splitlines():
        if not line or line.startswith("#"):
            continue
        match = _METRIC_LINE_RE.match(line.strip())
        if not match:
            continue
        name = match.group("name")
        if name not in _CONTROLLED_CD_LANE_ALLOWED_METRIC_NAMES:
            continue
        try:
            metrics[name] = float(match.group("value"))
        except ValueError:
            continue
    return metrics


def _load_prometheus_query_metrics(
    prometheus_query_url: str,
    *,
    timeout_seconds: float,
) -> tuple[dict[str, float], str]:
    metrics: dict[str, float] = {}
    try:
        for name in sorted(_CONTROLLED_CD_LANE_ALLOWED_METRIC_NAMES):
            query_url = (
                f"{prometheus_query_url}?"
                f"{urllib.parse.urlencode({'query': name})}"
            )
            request = urllib.request.Request(query_url, method="GET")
            with urllib.request.urlopen(request, timeout=timeout_seconds) as response:
                payload = json.loads(
                    response.read(1_000_000).decode("utf-8", errors="replace")
                )
            if not isinstance(payload, dict) or payload.get("status") != "success":
                return {}, "PrometheusQueryNotSuccessful"
            results = _list(_dict(payload.get("data")).get("result"))
            if not results:
                continue
            value_pair = _list(_dict(results[0]).get("value"))
            if len(value_pair) < 2:
                continue
            try:
                metrics[name] = float(value_pair[1])
            except (TypeError, ValueError):
                continue
    except (
        OSError,
        TimeoutError,
        urllib.error.URLError,
        json.JSONDecodeError,
        ValueError,
    ) as exc:
        return {}, exc.__class__.__name__
    return metrics, ""


def _build_controlled_cd_lane_metric_readback(
    metrics: dict[str, float],
) -> dict[str, Any]:
    last_run = metrics.get(
        "awoooi_runner_failclosed_enforcer_last_run_timestamp", 0.0
    )
    now_seconds = datetime.now(ZoneInfo("Asia/Taipei")).timestamp()
    enforcer_metric_present = (
        "awoooi_runner_failclosed_enforcer_last_run_timestamp" in metrics
    )
    return {
        "enforcer_metric_present": enforcer_metric_present,
        "enforcer_last_run_timestamp": last_run,
        "enforcer_last_run_age_seconds": max(0, int(now_seconds - last_run))
        if last_run
        else 0,
        "enforcer_last_run_fresh": bool(last_run and now_seconds - last_run <= 900),
        "enforcer_apply_performed": _int(
            metrics.get("awoooi_runner_failclosed_enforcer_apply_performed")
        ),
        "active_job_containers": _int(
            metrics.get("awoooi_runner_failclosed_enforcer_active_job_containers")
        ),
        "lane_process_count": _int(
            metrics.get("awoooi_runner_failclosed_enforcer_lane_process_count")
        ),
        "root_restore_sources_left": _int(
            metrics.get("awoooi_runner_failclosed_enforcer_root_restore_sources_left")
        ),
        "controlled_drain_active_allowed": _int(
            metrics.get(
                "awoooi_runner_failclosed_enforcer_controlled_drain_active_allowed"
            )
        )
        == 1,
        "controlled_drain_staging_allowed": _int(
            metrics.get(
                "awoooi_runner_failclosed_enforcer_controlled_drain_staging_allowed"
            )
        )
        == 1,
        "host_load5_per_core": _float(metrics.get("awoooi_host_load5_per_core")),
        "gitea_actions_active_container_count": _int(
            metrics.get("awoooi_host_gitea_actions_active_container_count")
        ),
        "gitea_actions_active_process_count": _int(
            metrics.get("awoooi_host_gitea_actions_active_process_count")
        ),
    }


def _dict(value: Any) -> dict[str, Any]:
    return value if isinstance(value, dict) else {}


def _list(value: Any) -> list[Any]:
    return value if isinstance(value, list) else []


def _int(value: Any) -> int:
    try:
        return int(str(value))
    except (TypeError, ValueError):
        return 0


def _float(value: Any) -> float:
    try:
        return float(str(value))
    except (TypeError, ValueError):
        return 0.0


def _strings(value: Any) -> list[str]:
    return [str(item) for item in _list(value)]


def _unique_strings(values: list[str]) -> list[str]:
    seen: set[str] = set()
    unique: list[str] = []
    for value in values:
        if value in seen:
            continue
        seen.add(value)
        unique.append(value)
    return unique


def _is_sha(value: str) -> bool:
    return bool(_SHA_RE.fullmatch(value))


def _taipei_now_iso() -> str:
    return datetime.now(ZoneInfo("Asia/Taipei")).isoformat(timespec="seconds")
