"""市場情報 MCP fetch candidate queue writer run receipt review preview。

本模組只審核 operator shell writer run 後貼回的 receipt 摘要；API/UI
不讀 receipt 原文、不讀 approval token、不執行 CLI、不開 DB、不寫 queue、
不做 post-write query、不掛 scheduler。
"""

from copy import deepcopy

from services.market_intel.mcp_fetch_candidate_queue_writer_preflight import TARGET_TABLE
from services.market_intel.mcp_fetch_candidate_queue_writer_run_readiness import (
    ARTIFACT_PREFIX,
    BACKUP_PREFIX,
    build_mcp_fetch_candidate_queue_writer_run_readiness_preview,
)


MAX_RECEIPT_ROWS = 80
_SAMPLE_RUN_RECEIPT_REVIEW_PACKAGE = None

FORBIDDEN_SECRET_KEYS = (
    "approval_token",
    "approval-token",
    "api_key",
    "authorization",
    "bearer",
    "client_secret",
    "cookie",
    "password",
    "secret",
    "session_cookie",
    "token",
)

SAFE_SECRET_METADATA_KEYS = {
    "approval_token_shell_only_required",
    "no_approval_token_payload",
    "operator_confirmed_no_approval_token_payload",
    "operator_confirmed_one_time_token_shell_only",
    "token_not_logged",
}

_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_execution",
    "allow_cli_execution",
    "allow_database_write",
    "allow_external_network_in_api",
    "allow_scheduler_attach",
    "api_execution_allowed",
    "api_executed_cli",
    "api_executes",
    "api_executes_cli",
    "api_opens_database_connection",
    "api_reads_approval_token",
    "api_uses_external_network",
    "api_writes_database",
    "api_writes_file",
    "apply_real_write",
    "attach_scheduler",
    "candidate_queue_created_by_api",
    "candidate_queue_persisted_by_api",
    "candidate_review_state_updated",
    "cli_executed_by_api",
    "command_executed_by_api",
    "database_commit_executed",
    "database_connection_opened",
    "database_session_created",
    "database_write_executed_by_api",
    "execute_requested",
    "external_network_executed_by_api",
    "file_written",
    "network_request_allowed",
    "opens_database_connection",
    "package_artifact_created",
    "payload_persisted",
    "postwrite_query_executed_by_api",
    "ready_for_api_database_write",
    "ready_for_real_write",
    "real_write_allowed_by_api",
    "receipt_file_written",
    "receipt_persisted",
    "review_state_update_executed",
    "run_receipt_file_written",
    "run_receipt_persisted",
    "scheduler_attach",
    "scheduler_attached",
    "write_database",
    "writes_database",
    "writes_executed",
    "would_write_database",
)


def _as_dict(value):
    return value if isinstance(value, dict) else {}


def _as_list(value):
    if value is None:
        return []
    if isinstance(value, (list, tuple, set)):
        return list(value)
    return [value]


def _safe_int(value):
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def _safe_text(value, limit=500):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _safe_path(value, *, prefixes, suffixes):
    if not isinstance(value, str):
        return False
    normalized = value.strip().replace("\\", "/")
    if not normalized or normalized.startswith("/"):
        return False
    parts = [part for part in normalized.split("/") if part]
    if any(part in (".", "..") for part in parts):
        return False
    return normalized.startswith(prefixes) and normalized.endswith(suffixes)


def _contains_forbidden_key(value, forbidden_keys, *, safe_keys=None):
    safe_keys = safe_keys or set()
    if isinstance(value, dict):
        for key, nested in value.items():
            normalized_key = str(key).lower()
            if normalized_key in safe_keys and isinstance(nested, bool):
                continue
            if any(forbidden_key in normalized_key for forbidden_key in forbidden_keys):
                return True
            if _contains_forbidden_key(nested, forbidden_keys, safe_keys=safe_keys):
                return True
    elif isinstance(value, list):
        return any(
            _contains_forbidden_key(item, forbidden_keys, safe_keys=safe_keys)
            for item in value
        )
    return False


def _blocked_side_effects(payload):
    found = []

    def visit(value, path):
        if isinstance(value, dict):
            for key, item in value.items():
                normalized_key = str(key).lower()
                key_path = f"{path}.{key}" if path else key
                if normalized_key in _BLOCKED_SIDE_EFFECT_KEYS and bool(item):
                    found.append(key_path)
                visit(item, key_path)
        elif isinstance(value, list):
            for index, item in enumerate(value):
                visit(item, f"{path}[{index}]")

    visit(payload, "")
    return found


def _run_readiness_from_inputs(readiness_package, readiness_result, phase):
    if isinstance(readiness_result, dict) and readiness_result:
        return readiness_result

    readiness_package = _as_dict(readiness_package)
    return build_mcp_fetch_candidate_queue_writer_run_readiness_preview(
        writer_run_package_review_package=(
            readiness_package.get("writer_run_package_review_package")
            or readiness_package.get("candidate_queue_writer_run_package_review")
            or readiness_package.get("writer_run_package_review")
            or readiness_package.get("run_package_review_package")
            or {}
        ),
        writer_run_package_review_result=(
            readiness_package.get("writer_run_package_review_result")
            or readiness_package.get(
                "mcp_fetch_candidate_queue_writer_run_package_review"
            )
        ),
        operator_readiness=(
            readiness_package.get("operator_readiness")
            or readiness_package.get("writer_run_readiness")
            or readiness_package.get("candidate_queue_writer_run_readiness")
            or readiness_package.get("readiness_payload")
        ),
        phase=phase,
    )


def _sample_run_receipt_review_package():
    global _SAMPLE_RUN_RECEIPT_REVIEW_PACKAGE
    if _SAMPLE_RUN_RECEIPT_REVIEW_PACKAGE is not None:
        return deepcopy(_SAMPLE_RUN_RECEIPT_REVIEW_PACKAGE)

    sample_candidate_keys = [
        "momo:momo_edm:sample-campaign",
        "momo-momo_edm-sample-product",
    ]
    sample_dedupe_keys = [
        "campaign::momo::momo_edm::momo:momo_edm:sample-campaign",
        "product::momo::momo_edm::momo-momo_edm-sample-product",
    ]
    run_package_id = "market-intel-candidate-writer-run-package-sample"
    readiness_package = {
        "writer_run_package_review_package": {
            "run_package_id": run_package_id,
            "target_table": TARGET_TABLE,
        },
        "operator_readiness": {
            "run_readiness_artifact_path": (
                ARTIFACT_PREFIX + "candidate-queue-writer-run-readiness-sample.json"
            ),
            "reviewed_sample_json_path": (
                ARTIFACT_PREFIX + "candidate-queue-reviewed-sample.json"
            ),
            "backup_artifact_path": (
                BACKUP_PREFIX + "momo_pro_system_backup_sample.zip"
            ),
            "read_only_preflight_output_path": (
                ARTIFACT_PREFIX + "candidate-queue-writer-preflight-sample.json"
            ),
        },
    }
    readiness_result = {
        "mode": "mcp_fetch_candidate_queue_writer_run_readiness_review",
        "mcp_fetch_candidate_queue_writer_run_readiness_accepted": True,
        "ready_for_candidate_queue_writer_operator_run": True,
        "ready_for_candidate_queue_writer_run_receipt_review": True,
        "network_request_allowed": False,
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_writes_file": False,
        "api_uses_external_network": False,
        "database_write_executed": False,
        "cli_executed": False,
        "file_written": False,
        "scheduler_attached": False,
        "candidate_queue_created": False,
        "candidate_queue_persisted": False,
        "blocked_reasons": [],
        "writer_run_package_review_summary": {
            "run_package_id": run_package_id,
            "target_table": TARGET_TABLE,
            "payload_row_count": len(sample_candidate_keys),
            "candidate_keys": sample_candidate_keys,
            "dedupe_keys": sample_dedupe_keys,
        },
    }
    package_summary = _run_readiness_summary(readiness_result)
    writer_run_receipt = {
        "receipt_id": "market-intel-candidate-writer-run-receipt-sample",
        "run_package_id": package_summary["run_package_id"],
        "target_table": TARGET_TABLE,
        "payload_row_count": package_summary["payload_row_count"],
        "candidate_keys": package_summary["candidate_keys"],
        "dedupe_keys": package_summary["dedupe_keys"],
        "writer_output_path": (
            ARTIFACT_PREFIX + "candidate-queue-writer-output-sample.json"
        ),
        "postwrite_smoke_result_path": (
            ARTIFACT_PREFIX + "candidate-queue-writer-postwrite-smoke-sample.json"
        ),
        "backup_artifact_path": BACKUP_PREFIX + "momo_pro_system_backup_sample.zip",
        "writer_exit_code": 0,
        "inserted_row_count": package_summary["payload_row_count"],
        "skipped_duplicate_count": 0,
        "error_count": 0,
        "operator_shell_cli_executed": True,
        "api_executed_cli": False,
        "database_write_executed_by_api": False,
        "postwrite_query_executed_by_api": False,
        "postwrite_smoke": {
            "read_only_smoke_executed_by_operator": True,
            "expected_rows_found": True,
            "row_count_matches_payload": True,
            "target_table": TARGET_TABLE,
        },
        "operator_confirmations": {
            "receipt_redacted": True,
            "token_not_logged": True,
            "no_approval_token_payload": True,
            "no_api_cli_execution": True,
            "no_api_database_write": True,
            "no_api_file_write": True,
            "no_api_postwrite_query": True,
            "no_scheduler_attach": True,
        },
        "api_execution_allowed": False,
        "real_write_allowed_by_api": False,
    }
    _SAMPLE_RUN_RECEIPT_REVIEW_PACKAGE = {
        "writer_run_readiness_package": readiness_package,
        "writer_run_readiness_result": readiness_result,
        "writer_run_receipt": writer_run_receipt,
    }
    return deepcopy(_SAMPLE_RUN_RECEIPT_REVIEW_PACKAGE)


def _run_readiness_summary(readiness_result):
    readiness_result = _as_dict(readiness_result)
    package = _as_dict(readiness_result.get("writer_run_package_review_summary"))
    side_effects_clear = bool(
        not readiness_result.get("network_request_allowed")
        and not readiness_result.get("api_executes_cli")
        and not readiness_result.get("api_reads_approval_token")
        and not readiness_result.get("api_opens_database_connection")
        and not readiness_result.get("api_writes_database")
        and not readiness_result.get("api_writes_file")
        and not readiness_result.get("api_uses_external_network")
        and not readiness_result.get("database_write_executed")
        and not readiness_result.get("cli_executed")
        and not readiness_result.get("file_written")
        and not readiness_result.get("scheduler_attached")
        and not readiness_result.get("candidate_queue_created")
        and not readiness_result.get("candidate_queue_persisted")
    )
    return {
        "mode": readiness_result.get("mode"),
        "accepted": bool(
            readiness_result.get(
                "mcp_fetch_candidate_queue_writer_run_readiness_accepted"
            )
        ),
        "ready_for_operator_run": bool(
            readiness_result.get("ready_for_candidate_queue_writer_operator_run")
        ),
        "ready_for_run_receipt_review": bool(
            readiness_result.get(
                "ready_for_candidate_queue_writer_run_receipt_review"
            )
        ),
        "run_package_id": _safe_text(package.get("run_package_id"), 160),
        "target_table": _safe_text(package.get("target_table"), 160),
        "payload_row_count": _safe_int(package.get("payload_row_count")),
        "candidate_keys": sorted(
            key for key in _as_list(package.get("candidate_keys")) if key
        ),
        "dedupe_keys": sorted(
            key for key in _as_list(package.get("dedupe_keys")) if key
        ),
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": readiness_result.get("blocked_reasons", []),
    }


def _receipt_summary(receipt):
    receipt = _as_dict(receipt)
    smoke = _as_dict(receipt.get("postwrite_smoke"))
    confirmations = _as_dict(receipt.get("operator_confirmations"))
    candidate_keys = sorted(key for key in _as_list(receipt.get("candidate_keys")) if key)
    dedupe_keys = sorted(key for key in _as_list(receipt.get("dedupe_keys")) if key)
    return {
        "provided_keys": sorted(receipt.keys()),
        "receipt_id": _safe_text(receipt.get("receipt_id"), 160),
        "run_package_id": _safe_text(receipt.get("run_package_id"), 160),
        "target_table": _safe_text(receipt.get("target_table"), 160),
        "payload_row_count": _safe_int(receipt.get("payload_row_count")),
        "candidate_keys": candidate_keys,
        "dedupe_keys": dedupe_keys,
        "writer_output_path": _safe_text(receipt.get("writer_output_path")),
        "postwrite_smoke_result_path": _safe_text(
            receipt.get("postwrite_smoke_result_path")
        ),
        "backup_artifact_path": _safe_text(receipt.get("backup_artifact_path")),
        "writer_output_path_safe": _safe_path(
            receipt.get("writer_output_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "postwrite_smoke_result_path_safe": _safe_path(
            receipt.get("postwrite_smoke_result_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "backup_artifact_path_safe": _safe_path(
            receipt.get("backup_artifact_path"),
            prefixes=(BACKUP_PREFIX,),
            suffixes=(".zip", ".tar.gz"),
        ),
        "writer_exit_code": _safe_int(receipt.get("writer_exit_code")),
        "inserted_row_count": _safe_int(receipt.get("inserted_row_count")),
        "skipped_duplicate_count": _safe_int(receipt.get("skipped_duplicate_count")),
        "error_count": _safe_int(receipt.get("error_count")),
        "operator_shell_cli_executed": bool(
            receipt.get("operator_shell_cli_executed")
        ),
        "api_executed_cli": bool(receipt.get("api_executed_cli")),
        "database_write_executed_by_api": bool(
            receipt.get("database_write_executed_by_api")
        ),
        "postwrite_query_executed_by_api": bool(
            receipt.get("postwrite_query_executed_by_api")
        ),
        "postwrite_smoke_read_only_by_operator": bool(
            smoke.get("read_only_smoke_executed_by_operator")
        ),
        "postwrite_smoke_expected_rows_found": bool(
            smoke.get("expected_rows_found")
        ),
        "postwrite_smoke_row_count_matches_payload": bool(
            smoke.get("row_count_matches_payload")
        ),
        "postwrite_smoke_target_table": _safe_text(smoke.get("target_table"), 160),
        "receipt_redacted": bool(confirmations.get("receipt_redacted")),
        "token_not_logged": bool(confirmations.get("token_not_logged")),
        "no_approval_token_payload": bool(
            confirmations.get("no_approval_token_payload")
        ),
        "no_api_cli_execution": bool(confirmations.get("no_api_cli_execution")),
        "no_api_database_write": bool(
            confirmations.get("no_api_database_write")
        ),
        "no_api_file_write": bool(confirmations.get("no_api_file_write")),
        "no_api_postwrite_query": bool(
            confirmations.get("no_api_postwrite_query")
        ),
        "no_scheduler_attach": bool(confirmations.get("no_scheduler_attach")),
        "api_execution_allowed": bool(receipt.get("api_execution_allowed")),
        "real_write_allowed_by_api": bool(receipt.get("real_write_allowed_by_api")),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            receipt,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_side_effects(receipt),
    }


def _receipt_gates(*, readiness_received, receipt_received, readiness, receipt):
    readiness_candidate_keys = set(readiness["candidate_keys"])
    receipt_candidate_keys = set(receipt["candidate_keys"])
    readiness_dedupe_keys = set(readiness["dedupe_keys"])
    receipt_dedupe_keys = set(receipt["dedupe_keys"])
    operator_confirmed_boundaries = bool(
        receipt["receipt_redacted"]
        and receipt["token_not_logged"]
        and receipt["no_approval_token_payload"]
        and receipt["no_api_cli_execution"]
        and receipt["no_api_database_write"]
        and receipt["no_api_file_write"]
        and receipt["no_api_postwrite_query"]
        and receipt["no_scheduler_attach"]
    )
    return [
        {
            "key": "writer_run_readiness_payload_or_result_received",
            "label": "已提供 writer run readiness package 或已審核結果",
            "passed": readiness_received,
        },
        {
            "key": "writer_run_readiness_accepted",
            "label": "writer run readiness gate 必須已通過",
            "passed": readiness["accepted"],
        },
        {
            "key": "writer_run_readiness_ready_for_receipt_review",
            "label": "run readiness 必須只放行到 receipt review",
            "passed": readiness["ready_for_run_receipt_review"],
        },
        {
            "key": "writer_run_readiness_side_effect_free",
            "label": "run readiness 未顯示 API 執行、寫 DB 或掛 scheduler",
            "passed": readiness["side_effects_clear"],
        },
        {
            "key": "writer_run_receipt_payload_received",
            "label": "已提供 writer run receipt 摘要",
            "passed": receipt_received,
        },
        {
            "key": "writer_run_receipt_identity_recorded",
            "label": "receipt 必須記錄 receipt_id 與 run_package_id",
            "passed": bool(receipt["receipt_id"] and receipt["run_package_id"]),
        },
        {
            "key": "writer_run_receipt_run_package_matches",
            "label": "receipt run_package_id 必須對齊 readiness",
            "passed": bool(
                receipt["run_package_id"]
                and receipt["run_package_id"] == readiness["run_package_id"]
            ),
        },
        {
            "key": "writer_run_receipt_target_table_safe",
            "label": "target table 必須是 market_alert_review_queue",
            "passed": receipt["target_table"] == TARGET_TABLE,
        },
        {
            "key": "writer_run_receipt_payload_count_matches_readiness",
            "label": "receipt row count 必須對齊 readiness payload",
            "passed": bool(
                0 < receipt["payload_row_count"] <= MAX_RECEIPT_ROWS
                and receipt["payload_row_count"] == readiness["payload_row_count"]
            ),
        },
        {
            "key": "writer_run_receipt_candidate_keys_match_readiness",
            "label": "receipt candidate keys 必須完全對齊 readiness",
            "passed": bool(
                readiness_candidate_keys
                and receipt_candidate_keys == readiness_candidate_keys
            ),
        },
        {
            "key": "writer_run_receipt_dedupe_keys_match_readiness",
            "label": "receipt dedupe keys 必須完全對齊 readiness",
            "passed": bool(
                readiness_dedupe_keys
                and receipt_dedupe_keys == readiness_dedupe_keys
            ),
        },
        {
            "key": "writer_run_receipt_artifact_paths_safe",
            "label": "writer output、post-write smoke 與 backup paths 必須安全",
            "passed": bool(
                receipt["writer_output_path_safe"]
                and receipt["postwrite_smoke_result_path_safe"]
                and receipt["backup_artifact_path_safe"]
            ),
        },
        {
            "key": "writer_run_receipt_operator_cli_executed",
            "label": "receipt 必須標明 CLI 由操作員 shell 執行",
            "passed": receipt["operator_shell_cli_executed"],
        },
        {
            "key": "writer_run_receipt_cli_success",
            "label": "writer exit code 必須為 0 且 error_count 為 0",
            "passed": bool(
                receipt["writer_exit_code"] == 0 and receipt["error_count"] == 0
            ),
        },
        {
            "key": "writer_run_receipt_insert_count_matches_payload",
            "label": "inserted rows 必須對齊 payload rows",
            "passed": receipt["inserted_row_count"] == readiness["payload_row_count"],
        },
        {
            "key": "writer_run_receipt_postwrite_smoke_passed",
            "label": "post-write smoke 必須由操作員只讀執行且 row count 對齊",
            "passed": bool(
                receipt["postwrite_smoke_read_only_by_operator"]
                and receipt["postwrite_smoke_expected_rows_found"]
                and receipt["postwrite_smoke_row_count_matches_payload"]
                and receipt["postwrite_smoke_target_table"] == TARGET_TABLE
            ),
        },
        {
            "key": "writer_run_receipt_operator_boundaries_confirmed",
            "label": "操作員確認 receipt 已遮罩 token，且 API 未執行 CLI/DB/file/scheduler",
            "passed": operator_confirmed_boundaries,
        },
        {
            "key": "writer_run_receipt_no_api_execution_or_real_write",
            "label": "receipt payload 不得允許 API execution 或 real write",
            "passed": bool(
                not receipt["api_execution_allowed"]
                and not receipt["real_write_allowed_by_api"]
                and not receipt["api_executed_cli"]
                and not receipt["database_write_executed_by_api"]
                and not receipt["postwrite_query_executed_by_api"]
            ),
        },
        {
            "key": "writer_run_receipt_no_secret_or_token_key",
            "label": "receipt payload 不得包含 secret、cookie、password 或 token key",
            "passed": not receipt["secret_or_token_submitted_to_api"],
        },
        {
            "key": "writer_run_receipt_side_effect_free",
            "label": "receipt payload 不得要求 API 寫檔、執行、寫 DB 或掛 scheduler",
            "passed": not receipt["blocked_side_effects"],
        },
    ]


def build_mcp_fetch_candidate_queue_writer_run_receipt_review_preview(
    *,
    writer_run_readiness_package=None,
    writer_run_readiness_result=None,
    writer_run_receipt=None,
    phase=None,
):
    """建立 fetch candidate queue writer run receipt review；不執行查詢或寫入。"""
    writer_run_readiness_package = _as_dict(writer_run_readiness_package)
    readiness_result_received = bool(
        isinstance(writer_run_readiness_result, dict) and writer_run_readiness_result
    )
    receipt_valid_object = (
        isinstance(writer_run_receipt, dict) if writer_run_receipt is not None else True
    )
    receipt_payload = _as_dict(writer_run_receipt)
    readiness_result = _run_readiness_from_inputs(
        writer_run_readiness_package,
        writer_run_readiness_result,
        phase,
    )
    readiness_received = bool(
        writer_run_readiness_package or readiness_result_received
    )
    payload_received = bool(
        readiness_received or receipt_payload or writer_run_receipt is not None
    )
    receipt_received = bool(receipt_payload)
    readiness = _run_readiness_summary(readiness_result)
    receipt = _receipt_summary(receipt_payload)
    gates = _receipt_gates(
        readiness_received=readiness_received,
        receipt_received=receipt_received and receipt_valid_object,
        readiness=readiness,
        receipt=receipt,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    if not receipt_valid_object:
        blocked_reasons.append("writer_run_receipt_payload_valid_object")
    accepted = bool(payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_candidate_queue_writer_run_receipt_review"
            if payload_received
            else "mcp_fetch_candidate_queue_writer_run_receipt_review_preview"
        ),
        "phase": phase,
        "writer_run_receipt_review_payload_received": payload_received,
        "writer_run_readiness_received": readiness_received,
        "writer_run_receipt_received": receipt_received,
        "writer_run_receipt_valid_object": receipt_valid_object,
        "writer_run_readiness_accepted": readiness["accepted"],
        "mcp_fetch_candidate_queue_writer_run_receipt_review_accepted": accepted,
        "candidate_queue_writer_run_receipt_review_ready": accepted,
        "ready_for_candidate_queue_writer_run_closeout_review": accepted,
        "ready_for_api_database_write": False,
        "ready_for_real_write": False,
        "ready_for_scheduler_attach": False,
        "network_request_allowed": False,
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_writes_file": False,
        "api_uses_external_network": False,
        "postwrite_query_executed_by_api": False,
        "payload_row_count": receipt["payload_row_count"],
        "gate_count": len(gates),
        "passed_gate_count": sum(1 for gate in gates if gate["passed"]),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "writer_run_readiness_summary": readiness,
        "writer_run_receipt_summary": receipt,
        "sample_writer_run_receipt_review_package": (
            _sample_run_receipt_review_package()
        ),
        "next_operator_steps": [
            "Receipt review 通過後，只代表可進入 closeout review",
            "API/UI 仍不得回放 receipt 原文、執行 CLI、讀 token、開 DB 或寫 queue",
            "後續 closeout 必須確認 artifact 保存、rollback note 與排程仍未掛載",
        ],
        "payload_persisted": False,
        "run_receipt_review_persisted": False,
        "run_receipt_persisted": False,
        "run_receipt_file_written": False,
        "receipt_file_written": False,
        "package_artifact_created": False,
        "database_session_created": False,
        "database_commit_executed": False,
        "database_write_executed": False,
        "external_network_executed": False,
        "cli_executed": False,
        "file_written": False,
        "writes_executed": False,
        "would_write_database": False,
        "scheduler_attached": False,
        "candidate_queue_created": False,
        "candidate_queue_persisted": False,
        "candidate_review_state_updated": False,
    }
