from __future__ import annotations

import json
import urllib.error
from pathlib import Path

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1 import agents
from src.api.v1.agents import router
from src.services import awoooi_priority_work_order_readback as priority_service
from src.services.ai_agent_log_controlled_writeback_executor_readback import (
    load_latest_ai_agent_log_controlled_writeback_executor_readback,
)
from src.services.ai_agent_log_post_write_verifier_dry_run import (
    load_latest_ai_agent_log_post_write_verifier_dry_run,
)
from src.services.awoooi_priority_work_order_readback import (
    apply_ai_automation_live_closure_readbacks,
    apply_ai_loop_current_blocker_execution_queue,
    apply_controlled_cd_lane_live_metric_readback,
    apply_harbor_registry_controlled_recovery_preflight,
    apply_stockplatform_public_api_controlled_recovery_preflight,
    apply_stockplatform_public_api_runtime_readback,
    load_controlled_cd_lane_live_metric_readback,
    load_latest_awoooi_priority_work_order_readback,
)
from src.services.harbor_registry_controlled_recovery_preflight import (
    load_latest_harbor_registry_controlled_recovery_preflight,
)
from src.services.telegram_alert_learning_context_post_apply_verifier import (
    build_telegram_alert_learning_context_post_apply_verifier,
)
from src.services.stockplatform_public_api_controlled_recovery_preflight import (
    load_latest_stockplatform_public_api_controlled_recovery_preflight,
)

_REPO_ROOT = Path(__file__).resolve().parents[3]
_SNAPSHOT_PATH = (
    _REPO_ROOT
    / "docs"
    / "operations"
    / "awoooi-priority-work-order-readback.snapshot.json"
)


def test_awoooi_priority_work_order_readback_loader_returns_mainline_order():
    payload = load_latest_awoooi_priority_work_order_readback()

    assert payload["schema_version"] == "awoooi_priority_work_order_readback_v1"
    assert payload["snapshot_generated_at"] == "2026-06-29T23:50:52+08:00"
    assert payload["generated_at"] != payload["snapshot_generated_at"]
    assert payload["generated_at"].endswith("+08:00")
    assert payload["runtime_readback_generated_at"] == payload["generated_at"]
    assert payload["status"] == "p0_006_blocked_reboot_auto_recovery_slo_not_ready"
    assert payload["mainline_execution_state"]["active_p0_workplan_id"] == "P0-006"
    assert payload["mainline_execution_state"]["active_p0_state"] == (
        "blocked_reboot_auto_recovery_slo_not_ready"
    )
    assert payload["mainline_execution_state"][
        "next_executable_mainline_workplan_id"
    ] == "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD"
    assert payload["mainline_execution_state"][
        "next_executable_mainline_state"
    ] == (
        "blocked_reboot_slo_scorecard_service_data_backup_readback_present_"
        "blockers_open"
    )
    assert payload["mainline_execution_state"]["active_p0_immediate_apply_gap_count"] == 0
    assert payload["mainline_execution_state"]["active_p0_readiness_percent"] == 47
    assert (
        payload["mainline_execution_state"][
            "controlled_service_data_backup_readback_present"
        ]
        is True
    )
    assert (
        payload["mainline_execution_state"][
            "controlled_service_data_backup_readback_status"
        ]
        == "blocked_service_data_backup_readback_not_green"
    )
    assert (
        payload["mainline_execution_state"][
            "controlled_service_data_backup_blocker_count"
        ]
        == 4
    )
    assert payload["mainline_execution_state"][
        "controlled_service_data_backup_blocking_fields"
    ] == [
        "service_green",
        "post_start_blocked",
        "backup_core_green",
        "wazuh_dashboard_degraded",
    ]
    assert (
        payload["mainline_execution_state"][
            "controlled_service_data_backup_can_clear_blockers"
        ]
        is False
    )
    assert payload["mainline_execution_state"][
        "stale_snapshot_or_old_cd_runs_must_not_reopen_closed_work"
    ] is True
    assert payload["mainline_execution_state"][
        "windows99_verify_collection_status"
    ] == "blocked_windows99_verify_output_missing_host_reachable"
    assert (
        payload["mainline_execution_state"][
            "windows99_verify_collection_can_collect_no_secret"
        ]
        is True
    )
    assert payload["mainline_execution_state"][
        "windows99_verify_collection_blocker_count"
    ] == 2
    assert payload["mainline_execution_state"][
        "windows99_verify_collection_blockers"
    ] == [
        "windows99_vmware_autostart_readback_missing",
        "windows99_uptime_unknown",
    ]
    assert (
        payload["mainline_execution_state"][
            "windows99_verify_collection_host99_reachable"
        ]
        is True
    )
    assert (
        payload["mainline_execution_state"][
            "windows99_verify_collection_host99_uptime_known"
        ]
        is False
    )
    assert (
        payload["mainline_execution_state"]["windows99_management_readback_present"]
        is True
    )
    assert (
        payload["mainline_execution_state"][
            "windows99_remote_execution_channel_ready"
        ]
        is False
    )
    assert (
        payload["mainline_execution_state"]["windows99_ssh_batch_status"]
        == "permission_denied"
    )
    assert (
        payload["mainline_execution_state"]["windows99_rdp_console_reachable"]
        is True
    )
    assert (
        payload["mainline_execution_state"]["windows99_hyperv_vmconnect_open"]
        is True
    )
    assert (
        payload["mainline_execution_state"][
            "windows99_local_console_channel_reachable"
        ]
        is True
    )
    assert payload["mainline_execution_state"][
        "windows99_console_collection_channels"
    ] == ["rdp_console", "hyperv_vmconnect"]
    assert payload["next_execution_order"][0].startswith("P0-006:")
    in_progress = payload["in_progress_or_blocked_in_priority_order"][0]
    assert in_progress["workplan_id"] == "P0-006"
    assert in_progress["status"] == "blocked_reboot_auto_recovery_slo_not_ready"
    assert in_progress["evidence"]["service_green"] is False
    assert in_progress["evidence"]["product_data_green"] is True
    assert in_progress["evidence"]["backup_core_green"] is False
    assert in_progress["evidence"]["host_188_service_green"] is True
    assert in_progress["evidence"]["stock_freshness_status"] == "ok"
    assert in_progress["evidence"]["stock_ingestion_status"] == "ok"
    assert in_progress["evidence"]["stock_blockers"] == []
    assert in_progress["evidence"]["stock_ingestion_blockers"] == []
    assert (
        in_progress["evidence"][
            "controlled_service_data_backup_readback_present"
        ]
        is True
    )
    assert in_progress["evidence"][
        "controlled_service_data_backup_readback_status"
    ] == "blocked_service_data_backup_readback_not_green"
    assert in_progress["evidence"][
        "controlled_service_data_backup_blocker_count"
    ] == 4
    assert in_progress["evidence"][
        "controlled_service_data_backup_blocking_fields"
    ] == [
        "service_green",
        "post_start_blocked",
        "backup_core_green",
        "wazuh_dashboard_degraded",
    ]
    assert in_progress["evidence"]["windows99_verify_collection_status"] == (
        "blocked_windows99_verify_output_missing_host_reachable"
    )
    assert (
        in_progress["evidence"][
            "windows99_verify_collection_can_collect_no_secret"
        ]
        is True
    )
    assert in_progress["evidence"]["windows99_verify_collection_blockers"] == [
        "windows99_vmware_autostart_readback_missing",
        "windows99_uptime_unknown",
    ]
    assert (
        in_progress["evidence"]["windows99_verify_collection_host99_reachable"]
        is True
    )
    assert (
        in_progress["evidence"]["windows99_verify_collection_host99_uptime_known"]
        is False
    )
    assert in_progress["evidence"]["windows99_management_readback_present"] is True
    assert in_progress["evidence"]["windows99_management_host_reachable"] is True
    assert (
        in_progress["evidence"]["windows99_remote_execution_channel_ready"]
        is False
    )
    assert in_progress["evidence"]["windows99_ssh_batch_status"] == (
        "permission_denied"
    )
    assert in_progress["evidence"]["windows99_rdp_console_reachable"] is True
    assert in_progress["evidence"]["windows99_hyperv_vmconnect_open"] is True
    assert (
        in_progress["evidence"]["windows99_local_console_channel_reachable"]
        is True
    )
    assert in_progress["evidence"]["windows99_console_collection_channels"] == [
        "rdp_console",
        "hyperv_vmconnect",
    ]
    assert (
        in_progress["evidence"][
            "controlled_service_data_backup_can_clear_blockers"
        ]
        is False
    )
    assert in_progress["evidence"]["drill_preflight_ready"] is False
    assert in_progress["evidence"]["drill_preflight_blocker_count"] == 5
    assert (
        in_progress["evidence"][
            "drill_preflight_execution_authorized_by_this_endpoint"
        ]
        is False
    )
    assert "reboot SLO scorecard truth" in in_progress[
        "professional_fix"
    ]["action"]
    assert "controlled service/data/backup readback visible" in in_progress[
        "professional_fix"
    ]["action"]
    assert "windows99_verify_collection packet" in in_progress[
        "professional_fix"
    ]["action"]
    assert "windows99_management_channel visible" in in_progress[
        "professional_fix"
    ]["action"]
    assert "production migration/control-channel" in in_progress[
        "professional_fix"
    ]["action"]
    assert "StockPlatform freshness/ingestion are ok" not in in_progress[
        "professional_fix"
    ]["action"]
    assert "readback is present" in in_progress["reason"]
    assert "not merely waiting for a fresh reboot window" in in_progress["reason"]
    assert (
        payload["rollups"]["controlled_service_data_backup_readback_present"]
        is True
    )
    assert payload["rollups"]["controlled_service_data_backup_blocker_count"] == 4
    assert (
        payload["summary"]["controlled_service_data_backup_readback_present"]
        is True
    )
    assert payload["summary"]["snapshot_generated_at"] == payload[
        "snapshot_generated_at"
    ]
    assert payload["summary"]["runtime_readback_generated_at"] == payload[
        "runtime_readback_generated_at"
    ]
    assert payload["summary"]["controlled_service_data_backup_blocker_count"] == 4
    assert payload["summary"][
        "controlled_service_data_backup_next_safe_action"
    ] == (
        "collect_public_service_data_backup_readback_and_refresh_reboot_slo_"
        "scorecard_no_reboot_no_db_write"
    )
    assert payload["summary"]["windows99_verify_collection_status"] == (
        "blocked_windows99_verify_output_missing_host_reachable"
    )
    assert (
        payload["summary"]["windows99_verify_collection_can_collect_no_secret"]
        is True
    )
    assert payload["summary"]["windows99_verify_collection_blocker_count"] == 2
    assert payload["summary"]["windows99_verify_collection_blockers"] == [
        "windows99_vmware_autostart_readback_missing",
        "windows99_uptime_unknown",
    ]
    assert payload["rollups"]["windows99_verify_collection_blocker_count"] == 2
    assert (
        payload["rollups"]["windows99_verify_collection_host99_reachable"]
        is True
    )
    assert payload["rollups"]["windows99_management_readback_present"] is True
    assert payload["rollups"]["windows99_remote_execution_channel_ready"] is False
    assert payload["rollups"]["windows99_ssh_batch_status"] == "permission_denied"
    assert payload["rollups"]["windows99_hyperv_vmconnect_open"] is True
    assert payload["rollups"]["windows99_rdp_console_reachable"] is True
    assert (
        payload["rollups"]["windows99_local_console_channel_reachable"]
        is True
    )
    assert payload["rollups"]["windows99_console_collection_channels"] == [
        "rdp_console",
        "hyperv_vmconnect",
    ]
    assert payload["summary"]["windows99_management_readback_present"] is True
    assert payload["summary"]["windows99_management_host_reachable"] is True
    assert payload["summary"]["windows99_remote_execution_channel_ready"] is False
    assert payload["summary"]["windows99_ssh_batch_status"] == "permission_denied"
    assert payload["summary"]["windows99_hyperv_vmconnect_open"] is True
    assert payload["summary"]["windows99_rdp_console_reachable"] is True
    assert (
        payload["summary"]["windows99_local_console_channel_reachable"]
        is True
    )
    assert payload["summary"]["windows99_console_collection_channels"] == [
        "rdp_console",
        "hyperv_vmconnect",
    ]
    assert payload["operation_boundaries"]["github_api_used"] is False
    assert payload["operation_boundaries"]["github_cli_used"] is False
    assert payload["operation_boundaries"]["secret_or_runner_token_read"] is False
    assert payload["operation_boundaries"]["workflow_dispatch_performed"] is False
    assert payload["operation_boundaries"]["host_write_performed"] is False
    inserted_items = payload["commander_inserted_requirement_work_items"]
    assert len(inserted_items) == 55
    assert inserted_items[0]["id"] == "CIR-P0-001"
    assert inserted_items[-1]["id"] == "CIR-P3-NON-001"
    assert [item["order"] for item in inserted_items] == list(range(1, 56))
    assert all(item["acceptance"] for item in inserted_items)
    assert payload["summary"]["commander_inserted_requirement_work_item_count"] == 55
    assert payload["summary"]["commander_inserted_requirement_p0_count"] == 34
    assert payload["summary"]["commander_inserted_requirement_p1_count"] == 14
    assert payload["summary"]["commander_inserted_requirement_p2_count"] == 5
    assert payload["summary"]["commander_inserted_requirement_p3_count"] == 2
    assert payload["summary"]["commander_inserted_requirement_next_id"] == "CIR-P0-001"
    assert payload["rollups"]["commander_inserted_requirement_blocked_count"] == 1
    inserted_by_id = {item["id"]: item for item in inserted_items}
    assert inserted_by_id["CIR-P0-AILOOP-001"]["lane"] == (
        "ai_loop_agent_mainline"
    )
    assert "AI Loop Agent" in inserted_by_id["CIR-P0-AILOOP-001"]["request"]
    assert "Sensor -> Normalizer" in inserted_by_id[
        "CIR-P0-AILOOP-001"
    ]["normalized_work_item"]
    assert inserted_by_id["CIR-P0-AILOOP-002"]["lane"] == (
        "ai_automation_trace_nodes"
    )
    assert "trace_id" in inserted_by_id["CIR-P0-AILOOP-002"][
        "normalized_work_item"
    ]
    assert inserted_by_id["CIR-P0-LOG-001"]["lane"] == "global_log_ingestion"
    assert "專案、產品、網站、服務、套件、工具" in inserted_by_id[
        "CIR-P0-LOG-001"
    ]["request"]
    assert inserted_by_id["CIR-P0-LOG-002"]["lane"] == (
        "log_tagging_classification_clustering"
    )
    assert inserted_by_id["CIR-P0-TG-001"]["lane"] == (
        "telegram_alert_ai_automation"
    )
    assert "manual/default" in inserted_by_id["CIR-P0-TG-001"]["acceptance"]
    assert inserted_by_id["CIR-P0-IA-001"]["lane"] == "navigation_ia_recovery"
    assert "IwoooS" in inserted_by_id["CIR-P0-IA-001"]["request"]
    assert inserted_by_id["CIR-P1-AUTO-001"]["lane"] == (
        "parallel_mainline_scheduling"
    )
    assert inserted_by_id["CIR-P1-UI-001"]["lane"] == (
        "professional_product_ui_ux_mainline"
    )
    assert inserted_by_id["CIR-P1-KM-002"]["lane"] == (
        "log_km_mcp_rag_playbook_integration"
    )
    assert inserted_by_id["CIR-P1-OPENCLAW-001"]["lane"] == (
        "openclaw_live_ops_space"
    )
    assert "Gather Town" in inserted_by_id["CIR-P1-OPENCLAW-001"]["request"]
    assert "desktop-mobile animation smoke 已讀回" in inserted_by_id[
        "CIR-P1-OPENCLAW-001"
    ]["current_state"]
    assert inserted_by_id["CIR-P2-UX-002"]["lane"] == (
        "ai_professional_workbench_ux"
    )
    assert "文字牆" in inserted_by_id["CIR-P2-UX-002"]["request"]
    assert inserted_by_id["CIR-P3-NON-001"]["status"] == "deferred"
    assert inserted_by_id["CIR-P3-NON-001"]["lane"] == "non_awoooi_personal_note"
    expected_node_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",
    ]
    receipt_schema = payload["ai_automation_node_receipt_schema"]
    assert receipt_schema["schema_version"] == "ai_automation_node_receipt_v1"
    assert receipt_schema["required_fields"] == expected_node_required_fields
    assert receipt_schema["metadata_only"] is True
    assert receipt_schema["hard_blockers_preserved"] == [
        "secret_plaintext",
        "destructive_data_change",
        "reboot_or_node_drain",
        "force_push_or_repo_ref_delete",
        "paid_provider_route_change",
    ]
    receipts = payload["ai_automation_node_receipts"]
    assert [item["node_id"] for item in receipts] == [
        "sensor_evidence",
        "normalizer_log_tags",
        "ai_lane_route",
        "candidate_action",
        "gate_policy",
        "execution_boundary",
        "post_verifier",
        "learning_writeback",
    ]
    assert all(item["schema_version"] == "ai_automation_node_receipt_v1" for item in receipts)
    assert all(item["metadata_only"] is True for item in receipts)
    assert all(item["rollback_result"] == "not_started_no_runtime_write" for item in receipts)
    receipts_by_id = {item["node_id"]: item for item in receipts}
    assert receipts_by_id["sensor_evidence"]["work_item_id"] == "CIR-P0-AILOOP-001"
    assert receipts_by_id["execution_boundary"]["lane_id"] == (
        "telegram_alert_ai_automation"
    )
    assert receipts_by_id["execution_boundary"]["telegram_receipt_ref"] == (
        "metadata_only"
    )
    assert receipts_by_id["learning_writeback"]["work_item_id"] == "CIR-P1-KM-002"
    assert receipts_by_id["learning_writeback"]["km_writeback_ref"] == "queued"
    assert payload["summary"]["ai_automation_node_receipt_schema_version"] == (
        "ai_automation_node_receipt_v1"
    )
    assert payload["summary"]["ai_automation_node_receipt_count"] == 8
    assert payload["summary"]["ai_automation_node_receipt_ready_count"] == 3
    assert payload["summary"]["ai_automation_node_receipt_queued_count"] == 5
    assert payload["summary"]["ai_automation_node_receipt_blocked_count"] == 0
    assert payload["summary"]["ai_automation_node_receipt_required_field_count"] == 11
    assert payload["summary"]["ai_automation_node_receipt_metadata_only"] is True
    assert "p0_runtime_lane" in payload["summary"]["ai_automation_node_receipt_lanes"]
    assert "CIR-P0-AILOOP-002" in payload["summary"][
        "ai_automation_node_receipt_work_items"
    ]


def test_ai_automation_live_closure_readbacks_close_node_receipts():
    payload = load_latest_awoooi_priority_work_order_readback()
    executor = load_latest_ai_agent_log_controlled_writeback_executor_readback()
    verifier = load_latest_ai_agent_log_post_write_verifier_dry_run()

    apply_ai_automation_live_closure_readbacks(
        payload,
        executor_readback=executor,
        verifier_readback=verifier,
        consumer_readback=_consumer_readback_ready(),
        telegram_alert_context_verifier_readback=_telegram_alert_context_verifier_ready(),
    )

    receipts_by_id = {
        item["node_id"]: item for item in payload["ai_automation_node_receipts"]
    }
    assert payload["summary"]["ai_automation_node_receipt_count"] == 8
    assert payload["summary"]["ai_automation_node_receipt_ready_count"] == 8
    assert payload["summary"]["ai_automation_node_receipt_queued_count"] == 0
    assert payload["summary"]["ai_automation_node_receipt_blocked_count"] == 0
    assert receipts_by_id["normalizer_log_tags"]["node_status"] == "ready"
    assert receipts_by_id["candidate_action"]["node_status"] == "ready"
    assert receipts_by_id["execution_boundary"]["node_status"] == "ready"
    assert receipts_by_id["post_verifier"]["node_status"] == "ready"
    assert receipts_by_id["learning_writeback"]["node_status"] == "ready"
    assert receipts_by_id["execution_boundary"]["verifier_result"] == (
        "controlled_consumer_context_receipt_readback"
    )
    assert receipts_by_id["post_verifier"]["verifier_result"] == (
        "telegram_alert_learning_context_post_apply_verified"
    )
    assert receipts_by_id["learning_writeback"]["verifier_result"] == (
        "consumer_context_receipt_writeback_ready"
    )
    assert receipts_by_id["learning_writeback"]["km_writeback_ref"] == (
        "context_receipt:km=1"
    )
    assert receipts_by_id["learning_writeback"]["playbook_trust_writeback_ref"] == (
        "context_receipt:playbook=1"
    )
    assert payload["summary"][
        "ai_automation_consumer_runtime_target_write_performed"
    ] is True
    assert payload["summary"]["ai_automation_consumer_ready_target_count"] == 6
    assert payload["summary"][
        "ai_automation_consumer_target_context_receipt_write_count"
    ] == 6
    assert payload["summary"][
        "ai_automation_telegram_alert_post_apply_verifier_ready"
    ] is True
    assert payload["summary"][
        "ai_automation_telegram_alert_post_apply_verified_context_receipt_count"
    ] == 6


def test_awoooi_priority_work_order_readback_endpoint_returns_snapshot(
    monkeypatch: pytest.MonkeyPatch,
):
    monkeypatch.setattr(
        agents,
        "load_latest_stockplatform_public_api_runtime_readback",
        _stockplatform_runtime_ready,
    )
    monkeypatch.setattr(
        agents,
        "load_latest_harbor_registry_controlled_recovery_preflight",
        _harbor_registry_ready,
    )
    monkeypatch.setattr(
        agents,
        "load_controlled_cd_lane_live_metric_readback",
        _controlled_cd_lane_live_metrics,
    )
    monkeypatch.setattr(
        agents,
        "load_latest_ai_agent_log_controlled_writeback_consumer_readback",
        _consumer_readback_ready_async,
    )
    monkeypatch.setattr(
        agents,
        "load_latest_telegram_alert_learning_context_post_apply_verifier",
        _telegram_alert_context_verifier_ready_async,
    )
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.get("/api/v1/agents/awoooi-priority-work-order-readback")

    assert response.status_code == 200
    data = response.json()
    assert data["snapshot_generated_at"] == "2026-06-29T23:50:52+08:00"
    assert data["generated_at"] != data["snapshot_generated_at"]
    assert data["runtime_readback_generated_at"] == data["generated_at"]
    assert data["summary"]["runtime_readback_generated_at"] == data["generated_at"]
    assert data["status"] == "p0_006_blocked_ai_loop_current_blocker_execution_queue"
    assert data["mainline_execution_state"]["active_p0_workplan_id"] == "P0-006"
    assert data["mainline_execution_state"]["active_p0_state"] == (
        "blocked_ai_loop_current_blocker_execution_queue"
    )
    assert data["mainline_execution_state"][
        "next_executable_mainline_workplan_id"
    ] == "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE"
    assert (
        data["mainline_execution_state"]["ai_loop_current_blocker_registry_v2_ready"]
        is True
    )
    assert (
        data["mainline_execution_state"][
            "controlled_cd_lane_live_enforcer_metric_present"
        ]
        is True
    )
    assert (
        data["mainline_execution_state"][
            "controlled_cd_lane_live_enforcer_last_run_fresh"
        ]
        is True
    )
    assert (
        data["mainline_execution_state"][
            "controlled_cd_lane_live_controlled_drain_active_allowed"
        ]
        is False
    )
    assert data["summary"]["controlled_cd_lane_live_metric_status"] == (
        "controlled_cd_lane_live_metric_readback_ready"
    )
    assert data["summary"]["controlled_cd_lane_live_metric_metadata_only"] is True
    assert data["mainline_execution_state"][
        "ai_loop_current_blocker_deploy_marker_readback_required"
    ] is False
    assert data["mainline_execution_state"]["p0_004_template_copy_apply_gate_runtime_readback_state"] == "ready"
    assert data["mainline_execution_state"]["reboot_drill_preflight_runtime_readback_state"] == "blocked"
    assert data["rollups"]["stockplatform_public_api_runtime_ready"] is True
    assert data["next_execution_order"][0].startswith(
        "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE"
    )
    assert "do not reopen Harbor 502" in data["next_execution_order"][0]
    assert data["summary"]["commander_inserted_requirement_work_item_count"] == 55
    assert data["summary"]["commander_inserted_requirement_next_id"] == "CIR-P0-001"
    assert data["commander_inserted_requirement_work_items"][1]["id"] == (
        "CIR-P0-002"
    )
    assert data["commander_inserted_requirement_work_items"][1]["priority"] == "P0"
    assert data["commander_inserted_requirement_work_items"][1]["visible_surface"] == (
        "/zh-TW/awooop/work-items"
    )
    assert data["summary"]["ai_automation_node_receipt_schema_version"] == (
        "ai_automation_node_receipt_v1"
    )
    assert data["summary"]["ai_automation_node_receipt_count"] == 8
    assert data["summary"]["ai_automation_node_receipt_ready_count"] == 8
    assert data["summary"]["ai_automation_node_receipt_queued_count"] == 0
    assert data["summary"]["ai_automation_node_receipt_blocked_count"] == 0
    assert [item["node_id"] for item in data["ai_automation_node_receipts"]] == [
        "sensor_evidence",
        "normalizer_log_tags",
        "ai_lane_route",
        "candidate_action",
        "gate_policy",
        "execution_boundary",
        "post_verifier",
        "learning_writeback",
    ]
    endpoint_receipts = {
        item["node_id"]: item for item in data["ai_automation_node_receipts"]
    }
    assert endpoint_receipts["candidate_action"]["work_item_id"] == (
        "CIR-P0-AILOOP-002"
    )
    assert endpoint_receipts["execution_boundary"]["lane_id"] == (
        "telegram_alert_ai_automation"
    )
    assert endpoint_receipts["execution_boundary"]["node_status"] == "ready"
    assert endpoint_receipts["post_verifier"]["node_status"] == "ready"
    assert endpoint_receipts["post_verifier"]["verifier_result"] == (
        "telegram_alert_learning_context_post_apply_verified"
    )
    assert endpoint_receipts["learning_writeback"]["node_status"] == "ready"
    assert endpoint_receipts["learning_writeback"]["km_writeback_ref"] == (
        "context_receipt:km=1"
    )


def test_controlled_cd_lane_live_metric_readback_falls_back_to_prometheus(
    monkeypatch: pytest.MonkeyPatch,
):
    values = {
        "awoooi_runner_failclosed_enforcer_last_run_timestamp": "1782968690",
        "awoooi_runner_failclosed_enforcer_apply_performed": "0",
        "awoooi_runner_failclosed_enforcer_active_job_containers": "0",
        "awoooi_runner_failclosed_enforcer_lane_process_count": "0",
        "awoooi_runner_failclosed_enforcer_root_restore_sources_left": "0",
        "awoooi_runner_failclosed_enforcer_controlled_drain_active_allowed": "0",
        "awoooi_runner_failclosed_enforcer_controlled_drain_staging_allowed": "0",
        "awoooi_host_load5_per_core": "0.64",
        "awoooi_host_gitea_actions_active_container_count": "0",
        "awoooi_host_gitea_actions_active_process_count": "0",
    }

    class _Response:
        def __init__(self, body: bytes):
            self.body = body

        def __enter__(self):
            return self

        def __exit__(self, *_args):
            return False

        def read(self, _limit: int = -1) -> bytes:
            return self.body

    def _urlopen(request, timeout):  # noqa: ARG001
        url = getattr(request, "full_url", str(request))
        if url.endswith("/metrics"):
            raise urllib.error.URLError("node exporter unavailable")
        metric_name = next((name for name in values if name in url), "")
        result = []
        if metric_name:
            result = [
                {
                    "metric": {"__name__": metric_name, "host": "110"},
                    "value": [1782968699.0, values[metric_name]],
                }
            ]
        return _Response(
            json.dumps(
                {"status": "success", "data": {"result": result}},
                separators=(",", ":"),
            ).encode("utf-8")
        )

    monkeypatch.setattr(priority_service.urllib.request, "urlopen", _urlopen)

    readback = load_controlled_cd_lane_live_metric_readback(
        metrics_url="http://node-exporter.invalid/metrics",
        prometheus_query_url="http://prometheus.invalid/api/v1/query",
    )

    assert readback["status"] == "controlled_cd_lane_live_metric_readback_ready"
    assert readback["source"] == "prometheus_query_api"
    assert readback["metadata_only"] is True
    assert readback["readback"]["enforcer_metric_present"] is True
    assert readback["readback"]["host_load5_per_core"] == 0.64
    serialized = json.dumps(readback)
    assert "node-exporter.invalid" not in serialized
    assert "prometheus.invalid" not in serialized


def test_awoooi_priority_work_order_readback_endpoint_redacts_ai_loop_queue(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
):
    monkeypatch.setattr(
        agents,
        "load_latest_stockplatform_public_api_runtime_readback",
        _stockplatform_runtime_ready,
    )

    def _harbor_registry_upstream_502() -> dict:
        return load_latest_harbor_registry_controlled_recovery_preflight(
            route_source_path=_harbor_route_source(tmp_path),
            watchdog_source_path=_harbor_watchdog_source(tmp_path),
            probe=_harbor_upstream_502_probe,
        )

    monkeypatch.setattr(
        agents,
        "load_latest_harbor_registry_controlled_recovery_preflight",
        _harbor_registry_upstream_502,
    )
    monkeypatch.setattr(
        agents,
        "load_controlled_cd_lane_live_metric_readback",
        _controlled_cd_lane_live_metrics,
    )
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.get("/api/v1/agents/awoooi-priority-work-order-readback")

    assert response.status_code == 200
    assert "192.168.0.110" not in response.text
    data = response.json()
    in_progress = data["in_progress_or_blocked_in_priority_order"][0]
    evidence = in_progress["evidence"]
    assert data["status"] == (
        "p0_006_blocked_ai_loop_current_blocker_execution_queue"
    )
    assert evidence["ai_loop_current_blocker_post_recovery_readback_commands"] == [
        "check-awoooi-110-controlled-cd-lane-readiness.sh",
        "curl -k https://registry.wooo.work/v2/",
        "curl host:public-gateway/registry/v2/",
    ]
    assert len(
        evidence["ai_loop_current_blocker_local_console_execution_plan"]
    ) == 3
    assert "read_runner_registration_token_or_runner_file" in evidence[
        "ai_loop_current_blocker_forbidden_runtime_actions"
    ]


def test_awoooi_priority_work_order_readback_overlays_harbor_deploy_blocker(
    tmp_path: Path,
):
    payload = load_latest_awoooi_priority_work_order_readback()
    recovery = load_latest_harbor_registry_controlled_recovery_preflight(
        route_source_path=_harbor_route_source(tmp_path),
        watchdog_source_path=_harbor_watchdog_source(tmp_path),
        probe=_harbor_upstream_502_probe,
    )

    apply_harbor_registry_controlled_recovery_preflight(payload, recovery)

    state = payload["mainline_execution_state"]
    in_progress = payload["in_progress_or_blocked_in_priority_order"][0]
    evidence = in_progress["evidence"]
    assert payload["status"] == (
        "p0_006_blocked_harbor_registry_controlled_recovery_preflight"
    )
    assert state["active_p0_state"] == (
        "blocked_harbor_registry_controlled_recovery_preflight"
    )
    assert state["next_executable_mainline_workplan_id"] == (
        "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT"
    )
    assert evidence["harbor_registry_controlled_recovery_candidate_packaged"] is True
    assert evidence["harbor_registry_upstream_502_shape"] is True
    assert evidence["harbor_registry_watchdog_executor_ready"] is True
    assert evidence["harbor_registry_control_channel_readback_required"] is True
    assert evidence["harbor_registry_awoooi_host_runner_required"] is True
    assert evidence["harbor_registry_ssh_publickey_diagnosis_required"] is True
    assert evidence["harbor_registry_runtime_write_gate"] == "controlled_after_preflight"
    assert evidence["harbor_registry_current_apply_allowed"] is False
    assert "not a manual end state" in in_progress["reason"]
    assert "harbor-watchdog.sh --check" in in_progress["professional_fix"][
        "action"
    ]
    assert "Do not restart Docker daemon" in in_progress["professional_fix"]["action"]
    assert payload["summary"][
        "harbor_registry_controlled_recovery_candidate_packaged"
    ] is True
    assert (
        payload["summary"]["harbor_registry_control_channel_readback_required"]
        is True
    )
    assert payload["summary"]["harbor_registry_awoooi_host_runner_required"] is True
    assert (
        payload["summary"]["harbor_registry_ssh_publickey_diagnosis_required"]
        is True
    )
    assert payload["next_execution_order"][0].startswith(
        "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT"
    )


def test_awoooi_priority_work_order_readback_overlays_ai_loop_current_blocker_queue(
    tmp_path: Path,
):
    payload = load_latest_awoooi_priority_work_order_readback()
    recovery = load_latest_harbor_registry_controlled_recovery_preflight(
        route_source_path=_harbor_route_source(tmp_path),
        watchdog_source_path=_harbor_watchdog_source(tmp_path),
        probe=_harbor_upstream_502_probe,
    )
    executor = load_latest_ai_agent_log_controlled_writeback_executor_readback()

    apply_harbor_registry_controlled_recovery_preflight(payload, recovery)
    apply_ai_loop_current_blocker_execution_queue(payload, executor)

    state = payload["mainline_execution_state"]
    in_progress = payload["in_progress_or_blocked_in_priority_order"][0]
    evidence = in_progress["evidence"]
    assert payload["status"] == (
        "p0_006_blocked_ai_loop_current_blocker_execution_queue"
    )
    assert state["active_p0_state"] == (
        "blocked_ai_loop_current_blocker_execution_queue"
    )
    assert state["next_executable_mainline_workplan_id"] == (
        "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE"
    )
    assert state["ai_loop_current_blocker_execution_queue_count"] == 1
    assert state["ai_loop_current_blocker_id"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert state["ai_loop_current_blocker_control_path_blocker"] == ""
    assert state["ai_loop_current_blocker_control_path_pressure_blocker"] == ""
    assert state["ai_loop_current_blocker_node_load_classifier"] == "load_not_high"
    assert state["ai_loop_current_blocker_registry_v2_ready"] is True
    assert state["ai_loop_current_blocker_registry_v2_status_classifier"] == (
        "ready_auth_required_http_401"
    )
    assert state["ai_loop_current_blocker_deployment_closure_state"] == (
        "blocked_controlled_cd_lane_guardrails_after_ssh_and_harbor_ready"
    )
    assert state["ai_loop_current_blocker_deploy_marker_readback_required"] is False
    assert state["ai_loop_current_blocker_current_cd_run_id"] == "4293"
    assert (
        state["ai_loop_current_blocker_current_cd_run_status"]
        == "production_readback_verified"
    )
    assert state["ai_loop_current_blocker_cd_failed_after_registry_ready"] is False
    assert state["ai_loop_current_blocker_harbor_110_repair_run_id"] == "4255"
    assert state["ai_loop_current_blocker_harbor_110_repair_run_status"] == (
        "Failure"
    )
    assert state["ai_loop_current_blocker_harbor_110_repair_failure_classifier"] == (
        "controlled_cd_lane_guardrails_blocked_after_ssh_and_harbor_ready"
    )
    assert evidence["ai_loop_current_blocker_execution_queue_count"] == 1
    assert evidence["ai_loop_current_blocker_id"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert evidence["ai_loop_current_blocker_runner_label"] == "awoooi-non110-host"
    assert evidence["ai_loop_current_blocker_registry_v2_status"] == 401
    assert evidence["ai_loop_current_blocker_registry_v2_ready"] is True
    assert evidence["ai_loop_current_blocker_registry_v2_status_classifier"] == (
        "ready_auth_required_http_401"
    )
    assert evidence["ai_loop_current_blocker_deployment_closure_state"] == (
        "blocked_controlled_cd_lane_guardrails_after_ssh_and_harbor_ready"
    )
    assert (
        evidence["ai_loop_current_blocker_deploy_marker_readback_required"]
        is False
    )
    assert evidence["ai_loop_current_blocker_current_cd_run_id"] == "4293"
    assert (
        evidence["ai_loop_current_blocker_current_cd_run_status"]
        == "production_readback_verified"
    )
    assert (
        evidence["ai_loop_current_blocker_current_cd_commit_sha"]
        == "87512d32f5a73849b2d8090092677a745c85f9a8"
    )
    assert evidence["ai_loop_current_blocker_cd_failed_after_registry_ready"] is False
    assert evidence["ai_loop_current_blocker_harbor_110_repair_run_id"] == "4255"
    assert evidence["ai_loop_current_blocker_harbor_110_repair_run_status"] == (
        "Failure"
    )
    assert evidence["ai_loop_current_blocker_harbor_110_repair_failure_classifier"] == (
        "controlled_cd_lane_guardrails_blocked_after_ssh_and_harbor_ready"
    )
    assert (
        evidence[
            "ai_loop_current_blocker_harbor_110_repair_failed_after_registry_ready"
        ]
        is False
    )
    assert evidence["ai_loop_current_blocker_controlled_recovery_package"] == (
        "check-awoooi-110-controlled-cd-lane-readiness.sh"
    )
    assert evidence["ai_loop_current_blocker_post_apply_verifier"] == (
        "harbor-registry-controlled-recovery-receipt validator"
    )
    assert evidence["ai_loop_current_blocker_runtime_write_gate"] == (
        "controlled_after_110_local_console_preflight"
    )
    assert evidence["ai_loop_current_blocker_control_path_blocker"] == ""
    assert evidence["ai_loop_current_blocker_control_path_pressure_blocker"] == ""
    assert evidence["ai_loop_current_blocker_node_load_classifier"] == "load_not_high"
    assert set(evidence["ai_loop_current_blocker_learning_writeback_targets"]) == {
        "km",
        "rag",
        "playbook",
        "mcp",
        "verifier",
        "ai_agent",
    }
    assert len(evidence["ai_loop_current_blocker_target_batches"]) == 6
    assert evidence["ai_loop_current_blocker_local_console_phase_count"] == 3
    assert evidence["ai_loop_current_blocker_local_console_phase_ids"] == [
        "verify_ssh_control_path_restored",
        "verify_harbor_v2_ready",
        "verify_controlled_cd_lane_guardrails",
    ]
    assert evidence["ai_loop_current_blocker_local_console_execution_plan"][0][
        "mode"
    ] == "read_only"
    assert evidence["ai_loop_current_blocker_local_console_execution_plan"][2][
        "command"
    ] == "check-awoooi-110-controlled-cd-lane-readiness.sh"
    assert "check-awoooi-110-controlled-cd-lane-readiness.sh" in evidence[
        "ai_loop_current_blocker_post_recovery_readback_commands"
    ]
    assert "restart_docker_daemon" in evidence[
        "ai_loop_current_blocker_forbidden_runtime_actions"
    ]
    assert evidence["ai_loop_current_blocker_metadata_only_writeback_ready"] is True
    assert evidence["ai_loop_current_blocker_runtime_dispatch_performed"] is False
    assert evidence["ai_loop_current_blocker_raw_payload_required"] is False
    assert evidence["ai_loop_current_blocker_post_recovery_readback_commands"] == [
        "check-awoooi-110-controlled-cd-lane-readiness.sh",
        "curl -k https://registry.wooo.work/v2/",
        "curl http://192.168.0.110:5000/v2/",
    ]
    assert evidence["ai_loop_current_blocker_harbor_recovery_receipt_endpoint"] == (
        "/api/v1/agents/harbor-registry-controlled-recovery-receipt"
    )
    assert evidence["ai_loop_current_blocker_harbor_recovery_receipt_input_count"] == 11
    assert evidence["ai_loop_current_blocker_harbor_recovery_receipt_input_ids"] == [
        "gitea_actions_queue_readback",
        "remote_control_channel_readback",
        "ssh_local_repair_output",
        "local_console_recovery_output",
        "watchdog_check_output",
        "watchdog_repair_output",
        "controlled_cd_lane_readiness_output",
        "non110_runner_readiness_output",
        "public_registry_v2_http_status",
        "internal_registry_v2_http_status",
        "deploy_marker_readback",
    ]
    assert evidence["ai_loop_current_blocker_harbor_recovery_receipt_inputs"][-1][
        "expected_schema"
    ] == "awoooi_production_deploy_readback_blocker_v1"
    assert (
        evidence[
            "ai_loop_current_blocker_harbor_recovery_receipt_output_contract_count"
        ]
        == 8
    )
    assert evidence["ai_loop_current_blocker_harbor_recovery_receipt_output_ids"] == [
        "control_path_readiness",
        "ssh_local_repair",
        "controlled_cd_lane_readiness",
        "non110_runner_readiness",
        "gitea_actions_queue",
        "local_console_phase_readback",
        "post_apply_verifier",
        "deploy_marker",
    ]
    assert evidence["ai_loop_current_blocker_harbor_recovery_receipt_output_contract"][
        0
    ]["writeback_targets"] == ["km", "rag", "playbook", "mcp", "verifier", "ai_agent"]
    assert evidence["ai_loop_current_blocker_safe_next_action_id"] == (
        "restore_controlled_cd_lane_guardrails_then_rerun_readiness_receipt"
    )
    assert evidence["ai_loop_current_blocker_safe_next_action_stage"] == (
        "controlled_cd_lane_guardrails_receipt_required"
    )
    assert (
        evidence[
            "ai_loop_current_blocker_safe_next_action_requires_local_console"
        ]
        is False
    )
    assert evidence["ai_loop_current_blocker_safe_next_action_command"] == (
        "check-awoooi-110-controlled-cd-lane-readiness.sh"
    )
    assert evidence["ai_loop_current_blocker_queue_readback_normalizer_field_ids"] == [
        "cd_run_jobs_payload_classifier",
        "harbor_110_repair_jobs_payload_classifier",
        "latest_visible_harbor_110_repair_no_matching_runner_label",
        "latest_visible_harbor_110_repair_remote_control_channel_unavailable",
        "latest_visible_harbor_110_repair_remote_ssh_publickey_auth_stalled",
        "latest_visible_harbor_110_repair_remote_ssh_publickey_offer_timeout",
        "latest_visible_harbor_110_repair_remote_ssh_server_accepts_key_then_session_timeout",
        "current_cd_workflow_runner_readiness",
        "current_cd_deploy_marker_closure",
        "registry_v2_ready_state",
        "harbor_110_repair_failure_after_registry_ready",
        "harbor_110_repair_visible_running_jobs_api_stale",
        "current_cd_waiting_behind_harbor_110_repair_running",
        "safe_next_action_id",
        "controlled_profile_no_matching_runner_labels",
    ]
    assert evidence["ai_loop_current_blocker_queue_readback_normalizer_contract"][0][
        "writes_blockers"
    ] == [
        "gitea_queue_cd_jobs_head_sha_mismatch",
        "gitea_queue_cd_jobs_run_id_mismatch",
        "gitea_queue_cd_jobs_stale_or_mismatched",
    ]
    assert evidence["ai_loop_current_blocker_log_source_tag_keys"] == [
        "project_id",
        "product",
        "site_or_route",
        "service",
        "package",
        "tool",
        "source_system",
        "runtime_component",
        "signal_lane",
        "evidence_boundary",
    ]
    source_tags = {
        item["tag_key"]: item
        for item in evidence["ai_loop_current_blocker_log_source_tags"]
    }
    assert source_tags["project_id"]["tag_value"] == "awoooi"
    assert source_tags["service"]["tag_value"] == "awoooi-110-control-path"
    assert source_tags["tool"]["tag_value"] == (
        "read_public_gitea_queue_and_remote_control_classifier"
    )
    assert source_tags["signal_lane"]["tag_value"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert evidence["ai_loop_log_source_grouping_keys"] == [
        "project_id",
        "product",
        "site_or_route",
        "service",
        "package",
        "tool",
        "source_system",
        "runtime_component",
        "signal_lane",
        "evidence_boundary",
    ]
    assert len(evidence["ai_loop_log_source_tagging_contract"]) == 10
    assert all(
        item["metadata_only"] is True
        and item["raw_output_allowed"] is False
        and item["secret_value_allowed"] is False
        for item in evidence["ai_loop_current_blocker_harbor_recovery_receipt_inputs"]
    )
    assert "workflow_dispatch_from_this_endpoint" in evidence[
        "ai_loop_current_blocker_forbidden_runtime_actions"
    ]
    assert "not generic manual triage" in in_progress["reason"]
    assert "Do not restart Docker daemon" in in_progress["professional_fix"]["action"]
    assert payload["summary"]["ai_loop_current_blocker_execution_queue_count"] == 1
    assert payload["summary"]["ai_loop_current_blocker_id"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert payload["summary"]["ai_loop_current_blocker_registry_v2_ready"] is True
    assert payload["summary"]["ai_loop_current_blocker_deployment_closure_state"] == (
        "blocked_controlled_cd_lane_guardrails_after_ssh_and_harbor_ready"
    )
    assert (
        payload["summary"][
            "ai_loop_current_blocker_deploy_marker_readback_required"
        ]
        is False
    )
    assert payload["summary"]["ai_loop_current_blocker_current_cd_run_status"] == (
        "production_readback_verified"
    )
    assert (
        payload["summary"]["ai_loop_current_blocker_cd_failed_after_registry_ready"]
        is False
    )
    assert payload["summary"][
        "ai_loop_current_blocker_harbor_110_repair_failure_classifier"
    ] == "controlled_cd_lane_guardrails_blocked_after_ssh_and_harbor_ready"
    assert payload["summary"]["ai_loop_current_blocker_control_path_pressure_blocker"] == ""
    assert payload["summary"]["ai_loop_current_blocker_node_load_classifier"] == (
        "load_not_high"
    )
    assert payload["summary"]["ai_loop_current_blocker_local_console_phase_count"] == 3
    assert payload["summary"]["ai_loop_current_blocker_safe_next_action_id"] == (
        "restore_controlled_cd_lane_guardrails_then_rerun_readiness_receipt"
    )
    assert payload["summary"]["ai_loop_current_blocker_safe_next_action_command"] == (
        "check-awoooi-110-controlled-cd-lane-readiness.sh"
    )
    assert "harbor-registry-controlled-recovery-receipt validator" in payload["summary"][
        "ai_loop_current_blocker_safe_next_action_post_verifier"
    ]
    assert payload["summary"][
        "ai_loop_current_blocker_safe_next_action_requires_local_console"
    ] is False
    assert payload["summary"][
        "ai_loop_current_blocker_post_recovery_readback_command_count"
    ] == 3
    assert (
        payload["summary"][
            "ai_loop_current_blocker_harbor_recovery_receipt_input_count"
        ]
        == 11
    )
    assert payload["summary"][
        "ai_loop_current_blocker_harbor_recovery_receipt_input_ids"
    ][0] == "gitea_actions_queue_readback"
    assert payload["summary"][
        "ai_loop_current_blocker_harbor_recovery_receipt_input_ids"
    ][-1] == "deploy_marker_readback"
    assert (
        payload["summary"][
            "ai_loop_current_blocker_harbor_recovery_receipt_output_contract_count"
        ]
        == 8
    )
    assert payload["summary"][
        "ai_loop_current_blocker_harbor_recovery_receipt_output_ids"
    ][0] == "control_path_readiness"
    assert (
        payload["summary"][
            "ai_loop_current_blocker_queue_readback_normalizer_contract_count"
        ]
        == 15
    )
    assert payload["summary"][
        "ai_loop_current_blocker_queue_readback_normalizer_field_ids"
    ][0] == "cd_run_jobs_payload_classifier"
    assert payload["summary"]["ai_loop_current_blocker_log_source_tag_count"] == 10
    assert payload["summary"]["ai_loop_current_blocker_log_source_tag_keys"][0] == (
        "project_id"
    )
    assert payload["summary"]["ai_loop_log_source_grouping_key_count"] == 10
    assert payload["summary"]["ai_loop_log_source_tagging_contract_count"] == 10
    assert payload["summary"][
        "ai_loop_current_blocker_forbidden_runtime_action_count"
    ] == 6
    assert payload["next_execution_order"][0].startswith(
        "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE"
    )
    assert "already 401" in payload["next_execution_order"][0]
    assert "do not reopen Harbor 502" in payload["next_execution_order"][0]
    assert "P0-006-HARBOR-REGISTRY-CONTROLLED-RECOVERY-PREFLIGHT" in payload[
        "next_execution_order"
    ][1]


def test_awoooi_priority_work_order_readback_overlays_live_stockplatform_drift():
    payload = load_latest_awoooi_priority_work_order_readback()

    apply_stockplatform_public_api_runtime_readback(
        payload,
        _stockplatform_runtime_blocked(),
    )

    state = payload["mainline_execution_state"]
    in_progress = payload["in_progress_or_blocked_in_priority_order"][0]
    evidence = in_progress["evidence"]
    assert payload["status"] == "p0_006_blocked_stockplatform_public_api_runtime_drift"
    assert state["active_p0_state"] == "blocked_stockplatform_public_api_runtime_drift"
    assert state["stockplatform_public_api_live_readback_state"] == "blocked"
    assert "stockplatform_public_api_runtime_drift" in state[
        "active_p0_live_active_blockers"
    ]
    assert evidence["stockplatform_public_api_runtime_ready"] is False
    assert evidence["stockplatform_public_api_http_502_count"] == 3
    assert evidence["stockplatform_public_api_health_http_status"] == 502
    assert (
        evidence["stockplatform_recovery_control_path_status"]
        == "api_upstream_recovered_data_readiness_not_green"
    )
    assert "stockplatform_post_apply_public_api_verifier_not_green" in evidence[
        "stockplatform_recovery_control_path_active_blockers"
    ]
    assert in_progress["status"] == "blocked_stockplatform_public_api_runtime_drift"
    assert "Do not restart Docker daemon" in in_progress["professional_fix"]["action"]
    assert payload["rollups"]["stockplatform_public_api_runtime_blocked"] is True
    assert (
        payload["rollups"][
            "stockplatform_public_api_recovery_control_path_status"
        ]
        == "api_upstream_recovered_data_readiness_not_green"
    )
    assert (
        payload["rollups"][
            "stockplatform_public_api_recovery_control_path_blocker_count"
        ]
        == 2
    )
    assert (
        payload["rollups"]["active_p0_event_gated_by_fresh_reboot_window_only"]
        is False
    )
    assert payload["next_execution_order"][0].startswith(
        "P0-006-STOCKPLATFORM-PUBLIC-API-RUNTIME-READBACK"
    )


def test_awoooi_priority_work_order_ai_loop_overrides_stockplatform_drift_for_current_ai_loop_blocker():
    payload = load_latest_awoooi_priority_work_order_readback()
    executor = load_latest_ai_agent_log_controlled_writeback_executor_readback()

    apply_stockplatform_public_api_runtime_readback(
        payload,
        _stockplatform_runtime_blocked(),
    )
    apply_ai_loop_current_blocker_execution_queue(payload, executor)

    state = payload["mainline_execution_state"]
    assert payload["status"] == (
        "p0_006_blocked_ai_loop_current_blocker_execution_queue"
    )
    assert state["active_p0_state"] == (
        "blocked_ai_loop_current_blocker_execution_queue"
    )
    assert state["next_executable_mainline_workplan_id"] == (
        "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE"
    )
    assert state["stockplatform_public_api_live_readback_state"] == "blocked"
    assert state["ai_loop_current_blocker_id"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert state["ai_loop_current_blocker_control_path_blocker"] == ""
    assert payload["summary"]["ai_loop_current_blocker_id"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert payload["next_execution_order"][0].startswith(
        "P0-006-AI-LOOP-CURRENT-BLOCKER-EXECUTION-QUEUE"
    )


def test_awoooi_priority_work_order_readback_overlays_controlled_recovery_preflight():
    payload = load_latest_awoooi_priority_work_order_readback()
    runtime = _stockplatform_runtime_blocked()
    preflight = load_latest_stockplatform_public_api_controlled_recovery_preflight(
        runtime_readback=runtime
    )

    apply_stockplatform_public_api_runtime_readback(payload, runtime)
    apply_stockplatform_public_api_controlled_recovery_preflight(payload, preflight)

    state = payload["mainline_execution_state"]
    in_progress = payload["in_progress_or_blocked_in_priority_order"][0]
    evidence = in_progress["evidence"]
    assert payload["status"] == (
        "p0_006_blocked_stockplatform_public_api_controlled_recovery_preflight"
    )
    assert state["active_p0_state"] == (
        "blocked_stockplatform_public_api_controlled_recovery_preflight"
    )
    assert state["next_executable_mainline_workplan_id"] == (
        "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT"
    )
    assert evidence["stockplatform_controlled_recovery_preflight_status"] == (
        "controlled_recovery_preflight_packaged_waiting_control_path_readback"
    )
    assert evidence["stockplatform_controlled_recovery_candidate_packaged"] is True
    assert evidence["stockplatform_host_control_path_readback_required"] is True
    assert evidence["stockplatform_controlled_work_item_count"] == 5
    assert evidence["stockplatform_post_apply_verifier_count"] == 4
    assert evidence["stockplatform_learning_writeback_contract_count"] == 6
    assert evidence["stockplatform_current_apply_allowed"] is False
    assert evidence["stockplatform_runtime_write_gate"] == "controlled_after_preflight"
    assert "not a manual end state" in in_progress["reason"]
    assert "Do not restart Docker daemon" in in_progress["professional_fix"]["action"]
    assert payload["summary"][
        "stockplatform_public_api_controlled_recovery_candidate_packaged"
    ] is True
    assert payload["next_execution_order"][0].startswith(
        "P0-006-STOCKPLATFORM-PUBLIC-API-CONTROLLED-RECOVERY-PREFLIGHT"
    )


def test_awoooi_priority_work_order_readback_routes_stockplatform_data_dependency():
    payload = load_latest_awoooi_priority_work_order_readback()
    runtime = _stockplatform_runtime_data_dependency_blocked()
    preflight = load_latest_stockplatform_public_api_controlled_recovery_preflight(
        runtime_readback=runtime
    )

    apply_stockplatform_public_api_runtime_readback(payload, runtime)
    apply_stockplatform_public_api_controlled_recovery_preflight(payload, preflight)

    state = payload["mainline_execution_state"]
    in_progress = payload["in_progress_or_blocked_in_priority_order"][0]
    evidence = in_progress["evidence"]
    assert evidence["stockplatform_controlled_recovery_preflight_status"] == (
        "controlled_data_dependency_preflight_packaged_waiting_control_path_readback"
    )
    assert evidence["stockplatform_controlled_recovery_api_layer"] == (
        "api_live_data_dependency_not_ready"
    )
    assert state["next_executable_mainline_state"] == (
        "controlled_recovery_preflight_waiting_stockplatform_production_"
        "migration_control_channel_readback_and_public_api_verifier"
    )
    assert "postgres_not_ready" in in_progress["reason"]
    assert evidence["stockplatform_controlled_recovery_data_dependency"] == (
        "postgres_not_ready"
    )
    assert evidence["stockplatform_freshness_status"] == "blocked"
    assert evidence["stockplatform_ingestion_status"] == "blocked"
    assert evidence["stock_latest_trading_date"] == "2026-07-02"
    assert evidence["stock_blockers"] == ["core_margin_short_daily_missing"]
    assert evidence["stock_ingestion_blockers"] == [
        "core.margin_short_daily_incomplete"
    ]
    assert evidence["stockplatform_freshness_sla_source_count"] == 9
    assert payload["summary"]["stockplatform_latest_trading_date"] == "2026-07-02"
    assert payload["summary"]["stockplatform_freshness_status"] == "blocked"
    assert payload["summary"]["stockplatform_freshness_sla_source_count"] == 9
    assert payload["rollups"]["stockplatform_latest_trading_date"] == "2026-07-02"
    assert evidence[
        "stockplatform_postgres_readiness_or_data_source_readback_status"
    ] == "blocked_stockplatform_postgres_not_ready"
    assert evidence[
        "stockplatform_postgres_readiness_or_data_source_readback_present"
    ] is True
    assert evidence[
        "stockplatform_postgres_readiness_or_data_source_receipt_provided"
    ] is True
    assert evidence[
        "stockplatform_postgres_readiness_or_data_source_postgres_ready"
    ] is False
    assert evidence["stockplatform_source_contract_readback_status"] == (
        "stockplatform_source_contract_not_required_postgres_path"
    )
    assert evidence["stockplatform_source_contract_receipt_provided"] is True
    assert evidence["stockplatform_source_contract_non_ok_source_count"] == 2
    assert payload["rollups"]["stockplatform_source_contract_receipt_provided"] is True
    assert payload["summary"]["stockplatform_source_contract_non_ok_source_count"] == 2
    assert payload["rollups"][
        "stockplatform_postgres_readiness_or_data_source_readback_present"
    ] is True
    assert payload["rollups"][
        "stockplatform_postgres_readiness_or_data_source_receipt_provided"
    ] is True
    assert payload["summary"][
        "stockplatform_postgres_readiness_or_data_source_receipt_provided"
    ] is True
    assert "production migration" in in_progress["professional_fix"]["action"]
    assert "Do not restart Docker daemon" in in_progress["professional_fix"]["action"]
    assert "manually write DB rows" in in_progress["professional_fix"]["action"]
    assert "production migration/control-channel" in payload["next_execution_order"][0]
    assert "do not manually DB-write or fake freshness" in payload[
        "next_execution_order"
    ][0]


def test_awoooi_priority_work_order_readback_allows_parallel_mainline_on_stockplatform_external_wait():
    payload = load_latest_awoooi_priority_work_order_readback()
    runtime = _stockplatform_runtime_source_contract_blocked()
    preflight = load_latest_stockplatform_public_api_controlled_recovery_preflight(
        runtime_readback=runtime
    )

    apply_stockplatform_public_api_runtime_readback(payload, runtime)
    apply_stockplatform_public_api_controlled_recovery_preflight(payload, preflight)

    parallel = payload["mainline_parallel_execution"]
    state = payload["mainline_execution_state"]
    assert parallel["enabled"] is True
    assert parallel["current_p0_wait_state"] == (
        "external_stockplatform_data_retry_wait"
    )
    assert parallel["retry_readback_at"]
    assert parallel["parallel_work_item"]["id"] == "CIR-P0-001"
    assert parallel["parallel_work_item"]["priority"] == "P0"
    assert parallel["report_contract"]["current_p0"] == "P0-006"
    assert "fake_stockplatform_freshness_marker" in parallel["forbidden_actions"]
    assert "db_write_or_restore_from_this_wait_lane" in parallel["forbidden_actions"]
    assert state["parallel_mainline_execution_enabled"] is True
    assert state["parallel_mainline_work_item_id"] == "CIR-P0-001"
    assert payload["summary"]["parallel_mainline_execution_enabled"] is True
    assert payload["summary"]["parallel_mainline_work_item_id"] == "CIR-P0-001"
    assert payload["summary"]["parallel_mainline_work_item_priority"] == "P0"
    assert payload["rollups"]["parallel_mainline_execution_enabled"] is True
    assert payload["rollups"]["parallel_mainline_work_item_id"] == "CIR-P0-001"


def test_awoooi_priority_work_order_readback_routes_stockplatform_ai_recommendations():
    payload = load_latest_awoooi_priority_work_order_readback()
    runtime = _stockplatform_runtime_ai_recommendations_stale_after_core_recovered()
    preflight = load_latest_stockplatform_public_api_controlled_recovery_preflight(
        runtime_readback=runtime
    )

    apply_stockplatform_public_api_runtime_readback(payload, runtime)
    apply_stockplatform_public_api_controlled_recovery_preflight(payload, preflight)

    state = payload["mainline_execution_state"]
    in_progress = payload["in_progress_or_blocked_in_priority_order"][0]
    evidence = in_progress["evidence"]
    assert state["stockplatform_public_api_data_dependency_classification"] == (
        "ai_recommendations_stale_after_core_recovered"
    )
    assert state["next_executable_mainline_state"] == (
        "controlled_recovery_preflight_waiting_stockplatform_ai_"
        "recommendation_pipeline_readback_and_public_api_verifier"
    )
    assert evidence["stockplatform_freshness_status"] == "blocked"
    assert evidence["stockplatform_ingestion_status"] == "ok"
    assert evidence["stock_blockers"] == ["ai_recommendations_stale"]
    assert evidence["stock_ingestion_blockers"] == []
    assert evidence["stockplatform_source_contract_readback_status"] == (
        "stockplatform_source_contract_core_ready_ai_recommendations_stale"
    )
    assert "AI recommendation pipeline" in in_progress["professional_fix"]["action"]
    assert "AI recommendations are stale" in payload["next_execution_order"][0]
    assert payload["mainline_parallel_execution"]["enabled"] is True
    assert payload["mainline_parallel_execution"]["current_p0_wait_state"] == (
        "external_stockplatform_data_retry_wait"
    )


def test_awoooi_priority_work_order_readback_normalizes_runtime_source_truth(
    monkeypatch: pytest.MonkeyPatch,
):
    runtime_sha = "b4dc407ce05c68a3908b993437a61b869d83810f"
    runtime_short_sha = runtime_sha[:10]
    monkeypatch.setenv("AWOOOI_BUILD_COMMIT_SHA", runtime_sha)
    monkeypatch.setenv("AWOOOI_DESIRED_API_IMAGE_TAG", runtime_sha)

    payload = load_latest_awoooi_priority_work_order_readback()

    current_head = payload["current_head"]
    state = payload["mainline_execution_state"]
    assert current_head["gitea_main_sha"] == runtime_sha
    assert current_head["latest_source_readiness_commit_sha"] == runtime_sha
    assert current_head["latest_source_readiness_cd_run_id"] == (
        f"production_readback:{runtime_short_sha}"
    )
    assert current_head["latest_fetched_gitea_main_subject"] == (
        f"production desired image tag {runtime_short_sha}"
    )
    assert current_head["stale_current_head_metadata_normalized"] is True
    assert state["current_main_latest_source_sha"] == runtime_sha
    assert state["latest_successful_deployed_source_sha"] == runtime_sha
    assert state["current_main_cd_run_status"] == "production_readback_verified"
    assert state["p0_004_template_copy_apply_gate_source_status"] == (
        "production_endpoint_ready"
    )
    assert state["reboot_drill_preflight_source_status"] == "production_endpoint_ready"
    assert payload["rollups"]["stale_current_head_metadata_normalized"] is True
    assert payload["summary"]["latest_successful_deployed_source_sha"] == runtime_sha

    current_truth = json.dumps(
        {
            "current_head": current_head,
            "mainline_execution_state": state,
        },
        ensure_ascii=False,
        sort_keys=True,
    )
    assert "3973" not in current_truth
    assert "49637ee7" not in current_truth
    assert "f426522" not in current_truth


def test_awoooi_priority_work_order_readback_does_not_reopen_stale_cd_failure_after_production_readback(
    monkeypatch: pytest.MonkeyPatch,
):
    runtime_sha = "b4dc407ce05c68a3908b993437a61b869d83810f"
    runtime_short_sha = runtime_sha[:10]
    monkeypatch.setenv("AWOOOI_BUILD_COMMIT_SHA", runtime_sha)
    monkeypatch.setenv("AWOOOI_DESIRED_API_IMAGE_TAG", runtime_sha)

    payload = load_latest_awoooi_priority_work_order_readback()
    apply_harbor_registry_controlled_recovery_preflight(
        payload,
        _harbor_registry_ready(),
    )
    executor = json.loads(
        json.dumps(load_latest_ai_agent_log_controlled_writeback_executor_readback())
    )
    executor["agent_consumption_context"]["current_blocker_execution_queue"][0].update(
        {
            "deployment_closure_state": (
                "blocked_latest_visible_cd_failure_after_registry_ready"
            ),
            "deploy_marker_readback_required": True,
            "current_cd_run_id": "4258",
            "current_cd_run_status": "Failure",
            "current_cd_commit_sha": "06819ea96c058e7987811e853242390eaced7f91",
            "cd_failed_after_registry_ready": True,
        }
    )
    apply_ai_loop_current_blocker_execution_queue(
        payload,
        executor,
    )

    state = payload["mainline_execution_state"]
    evidence = payload["in_progress_or_blocked_in_priority_order"][0]["evidence"]
    blockers = state["active_p0_live_active_blockers"]
    assert payload["status"] == "p0_006_blocked_reboot_auto_recovery_slo_not_ready"
    assert state["active_p0_state"] == "blocked_reboot_auto_recovery_slo_not_ready"
    assert state["next_executable_mainline_workplan_id"] == (
        "P0-006-REBOOT-AUTO-RECOVERY-SLO-SCORECARD"
    )
    assert state["current_main_cd_run_status"] == "production_readback_verified"
    assert state["ai_loop_current_blocker_resolved_by_production_readback"] is True
    assert state["ai_loop_current_blocker_deploy_marker_readback_required"] is False
    assert state["ai_loop_current_blocker_cd_failed_after_registry_ready"] is False
    assert (
        state["ai_loop_current_blocker_deploy_marker_resolved_by_production_readback"]
        is True
    )
    assert state["ai_loop_current_blocker_current_cd_run_status"] == (
        "production_readback_verified"
    )
    assert state["ai_loop_current_blocker_current_cd_run_id"] == (
        f"production_readback:{runtime_short_sha}"
    )
    assert state["ai_loop_current_blocker_control_path_blocker"] == ""
    assert state["ai_loop_current_blocker_historical_control_path_blocker"] == ""
    assert state["ai_loop_current_blocker_historical_current_cd_run_id"] == "4258"
    assert state["ai_loop_current_blocker_historical_current_cd_run_status"] == (
        "Failure"
    )
    assert "deploy_marker_readback_required_after_registry_ready" not in blockers
    assert "current_cd_failure_after_registry_ready" not in blockers
    assert "remote_ssh_publickey_offer_timeout" not in blockers
    assert evidence["ai_loop_current_blocker_resolved_by_production_readback"] is True
    assert evidence["ai_loop_current_blocker_deploy_marker_readback_required"] is False
    assert evidence["ai_loop_current_blocker_cd_failed_after_registry_ready"] is False
    assert evidence["ai_loop_current_blocker_control_path_blocker"] == ""
    assert evidence["ai_loop_current_blocker_historical_control_path_blocker"] == ""
    assert evidence[
        "ai_loop_current_blocker_historical_deploy_marker_readback_required"
    ] is True
    assert evidence["ai_loop_current_blocker_historical_current_cd_run_status"] == (
        "Failure"
    )
    assert payload["summary"][
        "ai_loop_current_blocker_deploy_marker_resolved_by_production_readback"
    ] is True
    assert payload["summary"]["ai_loop_current_blocker_current_cd_run_status"] == (
        "production_readback_verified"
    )
    assert payload["summary"]["ai_loop_current_blocker_control_path_blocker"] == ""
    assert payload["summary"][
        "ai_loop_current_blocker_historical_control_path_blocker"
    ] == ""
    assert all(
        "P0-006-CD-DEPLOY-MARKER-READBACK" not in item
        for item in payload["next_execution_order"]
    )


def test_awoooi_priority_work_order_readback_does_not_reopen_resolved_controlled_cd_lane_guardrails(
    monkeypatch: pytest.MonkeyPatch,
):
    runtime_sha = "ec563465e7890f365f367c8faf6e99228bd19f91"
    runtime_short_sha = runtime_sha[:10]
    monkeypatch.setenv("AWOOOI_BUILD_COMMIT_SHA", runtime_sha)
    monkeypatch.setenv("AWOOOI_DESIRED_API_IMAGE_TAG", runtime_sha)

    payload = load_latest_awoooi_priority_work_order_readback()
    apply_harbor_registry_controlled_recovery_preflight(
        payload,
        _harbor_registry_ready(),
    )
    executor = json.loads(
        json.dumps(load_latest_ai_agent_log_controlled_writeback_executor_readback())
    )

    apply_ai_loop_current_blocker_execution_queue(payload, executor)

    state = payload["mainline_execution_state"]
    evidence = payload["in_progress_or_blocked_in_priority_order"][0]["evidence"]
    blockers = state["active_p0_live_active_blockers"]
    assert payload["status"] == "p0_006_blocked_reboot_auto_recovery_slo_not_ready"
    assert state["active_p0_state"] == "blocked_reboot_auto_recovery_slo_not_ready"
    assert state["ai_loop_current_blocker_id"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert state["ai_loop_current_blocker_resolved_by_production_readback"] is True
    assert state["ai_loop_current_blocker_deployment_closure_state"] == (
        "production_readback_verified"
    )
    assert state["ai_loop_current_blocker_current_cd_run_id"] == (
        f"production_readback:{runtime_short_sha}"
    )
    assert state["ai_loop_current_blocker_current_cd_run_status"] == (
        "production_readback_verified"
    )
    assert state["ai_loop_current_blocker_safe_next_action_id"] == ""
    assert "ai_loop_current_blocker_execution_queue" not in blockers
    assert "controlled_cd_lane_guardrails_blocked" not in blockers
    assert evidence["ai_loop_current_blocker_resolved_by_production_readback"] is True
    assert evidence["ai_loop_current_blocker_deployment_closure_state"] == (
        "production_readback_verified"
    )
    assert payload["summary"][
        "ai_loop_current_blocker_resolved_by_production_readback"
    ] is True
    assert payload["summary"]["ai_loop_current_blocker_safe_next_action_id"] == ""


def test_awoooi_priority_work_order_readback_rejects_reordered_active_p0(tmp_path):
    operations_dir = tmp_path / "docs" / "operations"
    operations_dir.mkdir(parents=True)
    payload = json.loads(_SNAPSHOT_PATH.read_text(encoding="utf-8"))
    payload["mainline_execution_state"]["active_p0_workplan_id"] = "P1-OPENCLAW"
    (operations_dir / _SNAPSHOT_PATH.name).write_text(
        json.dumps(payload),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="active_p0_workplan_id"):
        load_latest_awoooi_priority_work_order_readback(operations_dir)


def _stockplatform_runtime_ready() -> dict:
    return {
        "schema_version": "stockplatform_public_api_runtime_readback_v1",
        "status": "stockplatform_public_api_runtime_ready",
        "safe_next_step": "stockplatform_public_api_ready_keep_p0_006_reboot_window_gate",
        "active_blockers": [],
        "runtime_ready": True,
        "live_drift_from_committed_scorecard": False,
        "readback": {
            "api_health_http_status": 200,
            "freshness_http_status": 200,
            "ingestion_http_status": 200,
        },
        "rollups": {
            "http_502_count": 0,
        },
    }


def _controlled_cd_lane_live_metrics() -> dict:
    return {
        "schema_version": "controlled_cd_lane_live_metric_readback_v1",
        "status": "controlled_cd_lane_live_metric_readback_ready",
        "source": "node_exporter_text_metrics",
        "metadata_only": True,
        "active_blockers": [
            "controlled_cd_lane_active_not_allowed_yet",
            "controlled_cd_lane_staging_not_allowed_yet",
        ],
        "readback": {
            "enforcer_metric_present": True,
            "enforcer_last_run_timestamp": 1782961969.0,
            "enforcer_last_run_fresh": True,
            "enforcer_apply_performed": 1,
            "active_job_containers": 0,
            "lane_process_count": 0,
            "root_restore_sources_left": 0,
            "controlled_drain_active_allowed": False,
            "controlled_drain_staging_allowed": False,
            "host_load5_per_core": 0.64,
            "gitea_actions_active_container_count": 0,
            "gitea_actions_active_process_count": 0,
        },
    }


async def _consumer_readback_ready_async() -> dict:
    return _consumer_readback_ready()


async def _telegram_alert_context_verifier_ready_async() -> dict:
    return _telegram_alert_context_verifier_ready()


def _telegram_alert_context_verifier_ready() -> dict:
    return build_telegram_alert_learning_context_post_apply_verifier(
        consumer_readback=_consumer_readback_ready()
    )


def _telegram_context_receipts() -> list[dict]:
    targets = [
        ("km", "knowledge_memory_context"),
        ("rag", "rag_index_candidate_context"),
        ("playbook", "playbook_trust_candidate_context"),
        ("mcp", "mcp_audit_feedback_context"),
        ("verifier", "post_apply_verifier_feedback_context"),
        ("ai_agent", "autonomous_runtime_decision_context"),
    ]
    return [
        {
            "receipt_id": f"telegram_alert_learning_context::msg-telegram-1::{target}",
            "source_receipt_id": "msg-telegram-1",
            "source_run_id": "run-telegram-1",
            "source_message_id": "msg-telegram-1",
            "work_item_id": "CIR-P0-TG-001",
            "target": target,
            "consumer_surface": surface,
            "source_ref": f"{target}://awoooi/telegram-alert/msg-telegram-1",
            "ai_agent_context_ref": (
                "ai-agent://awoooi/telegram-alert-learning-context/"
                "run-telegram-1/msg-telegram-1"
            ),
            "status": "ready_for_ai_loop_context",
            "metadata_only": True,
            "target_write_performed": False,
            "raw_payload_included": False,
            "target_selector": {
                "project_id": "awoooi",
                "run_id": "run-telegram-1",
                "message_id": "msg-telegram-1",
                "target": target,
                "source_ref": f"{target}://awoooi/telegram-alert/msg-telegram-1",
            },
            "source_of_truth_diff": {
                "current_state": "telegram_alert_learning_registry_readable",
                "desired_state": "ai_loop_agent_context_receipt_available",
                "delta_kind": f"telegram_alert_{target}_context_binding",
                "raw_payload_included": False,
            },
            "check_mode": {
                "enabled": True,
                "checks": [
                    "ai_alert_card_delivery_receipt_present",
                    "learning_registry_binding_ready",
                    "metadata_only_raw_payload_absent",
                    "ai_agent_context_ref_present",
                ],
            },
            "rollback": {
                "required": True,
                "rollback_ref": (
                    "rollback://telegram-alert-learning-context/"
                    f"msg-telegram-1/{target}"
                ),
            },
            "post_apply_verifier": {
                "required": True,
                "verifier_refs": [
                    "verifier://awoooi/telegram-alert-delivery-receipt/run-telegram-1",
                    f"{target}://awoooi/telegram-alert/msg-telegram-1",
                ],
            },
        }
        for target, surface in targets
    ]


def _consumer_readback_ready() -> dict:
    return {
        "schema_version": "ai_agent_log_controlled_writeback_consumer_readback_v1",
        "status": "controlled_writeback_consumer_readback_ready",
        "controlled_consume": {
            "mode": "controlled_consumer_readback_ready",
            "controlled_consume_allowed": True,
            "owner_review_required_for_low_medium_high": False,
            "critical_break_glass_required": True,
            "target_selector_required": True,
            "source_of_truth_diff_required": True,
            "check_mode_required": True,
            "rollback_required": True,
            "post_apply_verifier_required": True,
            "runtime_target_write_performed": True,
            "consumer_apply_route": (
                "/api/v1/agents/agent-log-controlled-writeback-consumer-apply"
            ),
        },
        "rollups": {
            "target_count": 6,
            "dispatch_ledger_row_count": 6,
            "consumer_apply_receipt_row_count": 6,
            "consumer_binding_count": 6,
            "ready_consumer_binding_count": 6,
            "ready_target_count": 6,
            "metadata_only_receipt_count": 6,
            "post_apply_verifier_ref_count": 12,
            "controlled_consumer_readback_ready": True,
            "km_consumer_binding_count": 1,
            "rag_consumer_binding_count": 1,
            "playbook_consumer_binding_count": 1,
            "mcp_consumer_binding_count": 1,
            "verifier_consumer_binding_count": 1,
            "ai_agent_consumer_binding_count": 1,
            "target_context_receipt_write_count": 6,
            "km_context_receipt_write_count": 1,
            "rag_context_receipt_write_count": 1,
            "playbook_context_receipt_write_count": 1,
            "mcp_context_receipt_write_count": 1,
            "verifier_context_receipt_write_count": 1,
            "ai_agent_context_receipt_write_count": 1,
            "runtime_target_write_performed": True,
            "telegram_alert_learning_context_readback_ready": True,
            "telegram_alert_learning_context_receipt_count": 6,
            "telegram_alert_learning_ai_agent_context_receipt_count": 1,
            "telegram_alert_learning_ready_target_count": 6,
            "telegram_alert_learning_target_count": 6,
        },
        "telegram_alert_learning_context": {
            "schema_version": "telegram_alert_ai_loop_consumer_context_readback_v1",
            "status": "ai_loop_agent_context_receipt_ready",
            "priority_work_item_id": "CIR-P0-TG-001",
            "project_id": "awoooi",
            "source_endpoint": "/api/v1/platform/runs/ai-alert-cards",
            "source_registry_status": "learning_registry_ready",
            "consumer_context_route": "ai_loop_agent.telegram_alert_learning_context",
            "target_count": 6,
            "ready_target_count": 6,
            "context_receipt_count": 6,
            "ai_agent_context_receipt_count": 1,
            "next_action": (
                "verify_telegram_alert_learning_context_receipts_with_ai_loop_post_apply_verifier"
            ),
            "context_receipts": _telegram_context_receipts(),
            "active_blockers": [],
            "operation_boundaries": {
                "metadata_read_performed": True,
                "db_or_log_receipt_read_performed": True,
                "runtime_target_write_performed": False,
                "km_write_performed": False,
                "rag_index_write_performed": False,
                "playbook_trust_write_performed": False,
                "mcp_tool_call_performed": False,
                "agent_runtime_action_performed": False,
                "telegram_send_performed": False,
                "raw_payload_included": False,
                "secret_value_collection_allowed": False,
                "github_api_used": False,
            },
        },
        "active_blockers": [],
    }


def _stockplatform_runtime_blocked() -> dict:
    return {
        "schema_version": "stockplatform_public_api_runtime_readback_v1",
        "status": "blocked_stockplatform_public_api_runtime_drift",
        "safe_next_step": (
            "recover_stockplatform_api_container_runtime_or_docker_control_path_"
            "without_daemon_restart_then_rerun_public_api_readback"
        ),
        "active_blockers": [
            "stockplatform_public_api_healthz_http_502",
            "stockplatform_freshness_http_502",
            "stockplatform_ingestion_http_502",
            "stockplatform_postgres_not_ready",
            "stockplatform_post_apply_public_api_verifier_not_green",
        ],
        "runtime_ready": False,
        "live_drift_from_committed_scorecard": True,
        "readback": {
            "web_health_http_status": 200,
            "api_health_http_status": 502,
            "freshness_http_status": 502,
            "ingestion_http_status": 502,
        },
        "rollups": {
            "http_502_count": 3,
        },
        "recovery_control_path": {
            "status": "api_upstream_recovered_data_readiness_not_green",
            "active_blockers": [
                "stockplatform_postgres_not_ready",
                "stockplatform_post_apply_public_api_verifier_not_green",
            ],
        },
    }


def _stockplatform_runtime_data_dependency_blocked() -> dict:
    return {
        "schema_version": "stockplatform_public_api_runtime_readback_v1",
        "status": "blocked_stockplatform_public_api_runtime_drift",
        "safe_next_step": (
            "run_stockplatform_production_migration_path_after_control_channel_"
            "readback_then_rerun_public_api_readback"
        ),
        "active_blockers": [
            "stockplatform_freshness_postgres_not_ready",
            "stockplatform_ingestion_postgres_not_ready",
            "stockplatform_recovery_control_path_receipt_missing",
            "stockplatform_controlled_deploy_or_ssh_readback_required",
        ],
        "runtime_ready": False,
        "live_drift_from_committed_scorecard": True,
        "readback": {
            "web_health_http_status": 200,
            "api_health_http_status": 200,
            "freshness_http_status": 200,
            "ingestion_http_status": 200,
            "freshness_status": "blocked",
            "ingestion_status": "blocked",
            "freshness_latest_trading_date": "2026-07-02",
            "freshness_blockers": ["core_margin_short_daily_missing"],
            "ingestion_blockers": ["core.margin_short_daily_incomplete"],
            "freshness_sla_source_count": 9,
            "freshness_source_count": 9,
            "freshness_non_ok_source_count": 3,
            "data_dependency_classification": "postgres_not_ready",
            "postgres_not_ready": True,
        },
        "rollups": {
            "http_502_count": 0,
            "data_dependency_classification": "postgres_not_ready",
            "postgres_not_ready": True,
        },
        "recovery_control_path": {
            "status": "blocked_recovery_control_path_receipt_missing",
            "active_blockers": [
                "stockplatform_recovery_control_path_receipt_missing",
                "stockplatform_controlled_deploy_or_ssh_readback_required",
            ],
        },
        "data_readiness_control_readback": {
            "schema_version": (
                "stockplatform_postgres_readiness_or_data_source_readback_v1"
            ),
            "receipt_key": "stockplatform_postgres_readiness_or_data_source_readback",
            "status": "blocked_stockplatform_postgres_not_ready",
            "readback_present": True,
            "receipt_provided": True,
            "postgres_ready": False,
            "postgres_not_ready": True,
        },
        "source_contract_control_readback": {
            "schema_version": "stockplatform_source_contract_control_readback_v1",
            "receipt_key": "stockplatform_source_contract_readback",
            "status": "stockplatform_source_contract_not_required_postgres_path",
            "readback_present": True,
            "receipt_provided": True,
            "source_contract_ready": False,
            "non_ok_source_count": 2,
            "blocking_sources": [
                {
                    "source": "postgres_not_ready",
                    "category": "freshness",
                    "status": "blocked",
                },
                {
                    "source": "postgres_not_ready",
                    "category": "ingestion",
                    "status": "blocked",
                },
            ],
        },
    }


def _stockplatform_runtime_source_contract_blocked() -> dict:
    payload = _stockplatform_runtime_data_dependency_blocked()
    payload["safe_next_step"] = (
        "run_stockplatform_data_dependency_source_contract_readback_then_"
        "rerun_public_api_verifier"
    )
    payload["active_blockers"] = [
        "stockplatform_freshness_core_margin_short_daily_missing",
        "stockplatform_freshness_ai_recommendations_stale",
        "stockplatform_ingestion_core.margin_short_daily_incomplete",
        "stockplatform_post_apply_public_api_verifier_not_green",
    ]
    payload["readback"]["data_dependency_classification"] = (
        "freshness_or_ingestion_not_ready"
    )
    payload["readback"]["postgres_not_ready"] = False
    payload["rollups"]["data_dependency_classification"] = (
        "freshness_or_ingestion_not_ready"
    )
    payload["rollups"]["postgres_not_ready"] = False
    payload["data_readiness_control_readback"] = {
        "schema_version": "stockplatform_postgres_readiness_or_data_source_readback_v1",
        "receipt_key": "stockplatform_postgres_readiness_or_data_source_readback",
        "status": "blocked_stockplatform_data_dependency_not_ready",
        "readback_present": True,
        "receipt_provided": True,
        "postgres_ready": False,
        "postgres_not_ready": False,
    }
    payload["source_contract_control_readback"] = {
        "schema_version": "stockplatform_source_contract_control_readback_v1",
        "receipt_key": "stockplatform_source_contract_readback",
        "status": "blocked_stockplatform_source_contract_not_ready",
        "readback_present": True,
        "receipt_provided": True,
        "source_contract_ready": False,
        "non_ok_source_count": 3,
        "active_blockers": [
            "stockplatform_freshness_core_margin_short_daily_missing",
            "stockplatform_freshness_ai_recommendations_stale",
            "stockplatform_ingestion_core.margin_short_daily_incomplete",
        ],
        "blocking_sources": [
            {
                "source": "raw.source_quality_observations.unit_sanity",
                "category": "freshness",
                "status": "warning",
                "classification": "freshness_source_non_ok",
            },
            {
                "source": "core.margin_short_daily",
                "category": "freshness",
                "status": "missing",
                "classification": "freshness_source_non_ok",
            },
            {
                "source": "ai.recommendations",
                "category": "freshness",
                "status": "stale",
                "classification": "freshness_source_non_ok",
            },
        ],
    }
    return payload


def _stockplatform_runtime_ai_recommendations_stale_after_core_recovered() -> dict:
    payload = _stockplatform_runtime_source_contract_blocked()
    payload["safe_next_step"] = (
        "run_stockplatform_ai_recommendation_pipeline_readback_then_rerun_"
        "public_api_verifier"
    )
    payload["active_blockers"] = [
        "stockplatform_freshness_ai_recommendations_stale",
        "stockplatform_post_apply_public_api_verifier_not_green",
    ]
    payload["readback"].update(
        {
            "freshness_status": "blocked",
            "ingestion_status": "ok",
            "freshness_blockers": ["ai_recommendations_stale"],
            "ingestion_blockers": [],
            "data_dependency_classification": (
                "ai_recommendations_stale_after_core_recovered"
            ),
            "postgres_not_ready": False,
        }
    )
    payload["rollups"]["data_dependency_classification"] = (
        "ai_recommendations_stale_after_core_recovered"
    )
    payload["rollups"]["postgres_not_ready"] = False
    payload["data_readiness_control_readback"]["status"] = (
        "blocked_stockplatform_ai_recommendations_stale_after_core_recovered"
    )
    payload["data_readiness_control_readback"]["postgres_not_ready"] = False
    payload["source_contract_control_readback"]["status"] = (
        "stockplatform_source_contract_core_ready_ai_recommendations_stale"
    )
    payload["source_contract_control_readback"]["non_ok_source_count"] = 1
    payload["source_contract_control_readback"]["active_blockers"] = [
        "stockplatform_freshness_ai_recommendations_stale"
    ]
    payload["source_contract_control_readback"]["blocking_sources"] = [
        {
            "source": "ai.recommendations",
            "category": "freshness",
            "status": "stale",
            "classification": "freshness_source_non_ok",
        },
    ]
    return payload


def _harbor_registry_ready() -> dict:
    return {
        "schema_version": "harbor_registry_controlled_recovery_preflight_v1",
        "priority": "P0-006",
        "scope": "harbor_registry_controlled_recovery_preflight",
        "status": "harbor_registry_ready",
        "safe_next_step": "rerun_gitea_cd_and_verify_deploy_marker",
        "active_blockers": [],
        "rollups": {
            "registry_ready": True,
            "public_registry_v2_ready": True,
            "internal_110_registry_v2_ready": True,
            "controlled_recovery_candidate_packaged": False,
        },
    }


def _harbor_route_source(tmp_path: Path) -> Path:
    path = tmp_path / "188-internal-tools-https.conf.j2"
    path.write_text(
        """
server {
    listen 443 ssl http2;
    server_name harbor.wooo.work;
    location / {
        proxy_pass http://192.168.0.110:5000;
    }
}
server {
    listen 443 ssl http2;
    server_name registry.wooo.work;
    location / {
        proxy_pass http://192.168.0.110:5000;
    }
}
""",
        encoding="utf-8",
    )
    return path


def _harbor_watchdog_source(tmp_path: Path) -> Path:
    path = tmp_path / "harbor-watchdog.sh"
    path.write_text(
        """
harbor_is_healthy() {
  curl -s --max-time 5 -o /dev/null -w "%{http_code}" http://127.0.0.1:5000/v2/
}
case "${1:-}" in
  --check) echo AWOOOI_HARBOR_WATCHDOG_CHECK ;;
  --repair-once) echo HARBOR_REPAIR_PERFORMED=1 ;;
esac
docker compose up -d harbor-log
docker compose up -d
""",
        encoding="utf-8",
    )
    return path


def _harbor_upstream_502_probe(url: str, _timeout_seconds: float) -> dict:
    if "/v2/" in url:
        return {"http_status": 502}
    return {"http_status": 200}
