feat(governance): 新增 result capture no-write readback
All checks were successful
Code Review / ai-code-review (push) Successful in 13s
CD Pipeline / tests (push) Successful in 1m27s
CD Pipeline / build-and-deploy (push) Successful in 4m11s
CD Pipeline / post-deploy-checks (push) Successful in 1m56s

This commit is contained in:
Your Name
2026-06-13 20:56:49 +08:00
parent 9ed913cd80
commit 69a536516e
10 changed files with 1642 additions and 1 deletions

View File

@@ -115,6 +115,9 @@ from src.services.ai_agent_redis_dry_run_gate import (
from src.services.ai_agent_reviewer_queue_no_write_readback import (
load_latest_ai_agent_reviewer_queue_no_write_readback,
)
from src.services.ai_agent_result_capture_no_write_readback import (
load_latest_ai_agent_result_capture_no_write_readback,
)
from src.services.ai_agent_runtime_readback_approval_package import (
load_latest_ai_agent_runtime_readback_approval_package,
)
@@ -1590,6 +1593,36 @@ async def get_agent_reviewer_queue_no_write_readback() -> dict[str, Any]:
) from exc
@router.get(
"/agent-result-capture-no-write-readback",
response_model=dict[str, Any],
summary="取得 AI Agent result capture no-write readback",
description=(
"讀取最新已提交的 P2-118 result capture no-write readback"
"此端點只回傳 result capture preview fixture、capture field mapping、no-write verifier、"
"blocked result capture write 與 operator handoff不寫 result capture、learning、"
"PlayBook trust、Gateway queue不送 Telegram、不呼叫 Bot API、不讀 canonical runtime target、"
"不讀 secret。"
),
)
async def get_agent_result_capture_no_write_readback() -> dict[str, Any]:
"""Return the latest read-only result capture no-write readback package."""
try:
payload = await asyncio.to_thread(load_latest_ai_agent_result_capture_no_write_readback)
return redact_public_lan_topology(payload)
except FileNotFoundError as exc:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=str(exc),
) from exc
except (json.JSONDecodeError, ValueError) as exc:
logger.error("ai_agent_result_capture_no_write_readback_invalid", error=str(exc))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="AI Agent result capture no-write readback 無效",
) from exc
@router.get(
"/agent-owner-approved-fixture-dry-run",
response_model=dict[str, Any],

View File

@@ -0,0 +1,361 @@
"""
AI Agent result capture no-write readback snapshot.
Loads the latest committed P2-118 result capture no-write readback package. This
module validates committed evidence only; it never writes result captures,
writes learning records, updates PlayBook trust, writes Gateway queues, sends
Telegram messages, reads canonical runtime targets, reads secrets, or performs
destructive operations.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from src.services.snapshot_paths import default_evaluations_dir
_DEFAULT_EVALUATIONS_DIR = default_evaluations_dir(Path(__file__))
_SNAPSHOT_PATTERN = "ai_agent_result_capture_no_write_readback_*.json"
_SCHEMA_VERSION = "ai_agent_result_capture_no_write_readback_v1"
_RUNTIME_AUTHORITY = "result_capture_no_write_readback_only_no_capture_or_learning_write"
_TARGET_CAPTURE = "result_capture_preview"
def load_latest_ai_agent_result_capture_no_write_readback(
evaluations_dir: Path | None = None,
) -> dict[str, Any]:
"""Load the newest committed result capture no-write readback package."""
directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
if not candidates:
raise FileNotFoundError(f"no AI Agent result capture no-write readback snapshots found in {directory}")
latest = candidates[-1]
with latest.open(encoding="utf-8") as handle:
payload = json.load(handle)
if not isinstance(payload, dict):
raise ValueError(f"{latest}: expected JSON object")
label = str(latest)
_require_schema(payload, label)
_require_prior(payload, label)
_require_truth(payload, label)
_require_result_capture_fixtures(payload, label)
_require_capture_mappings(payload, label)
_require_verifier_checks(payload, label)
_require_blockers(payload, label)
_require_actions(payload, label)
_require_display_redaction(payload, label)
_require_no_forbidden_display_terms(payload, label)
_require_rollup_consistency(payload, label)
return payload
def _require_schema(payload: dict[str, Any], label: str) -> None:
if payload.get("schema_version") != _SCHEMA_VERSION:
raise ValueError(f"{label}: expected schema_version={_SCHEMA_VERSION}")
status = payload.get("program_status") or {}
expected = {
"current_priority": "P2",
"current_task_id": "P2-118",
"next_task_id": "P2-119",
"read_only_mode": True,
"runtime_authority": _RUNTIME_AUTHORITY,
"overall_completion_percent": 100,
}
mismatches = _mismatches(status, expected)
if mismatches:
raise ValueError(f"{label}: program_status mismatch: {mismatches}")
if not status.get("status_note"):
raise ValueError(f"{label}: program_status.status_note is required")
def _require_prior(payload: dict[str, Any], label: str) -> None:
prior = payload.get("prior_reviewer_queue_readback") or {}
expected = {
"schema_version": "ai_agent_reviewer_queue_no_write_readback_v1",
"reviewer_queue_readback_fixture_count": 5,
"queue_item_mapping_count": 5,
"readback_verifier_check_count": 5,
"blocked_queue_write_count": 5,
"operator_action_count": 5,
"reviewer_queue_write_count": 0,
"gateway_queue_write_count": 0,
"telegram_send_count": 0,
"bot_api_call_count": 0,
"report_receipt_write_count": 0,
"result_capture_write_count": 0,
}
mismatches = _mismatches(prior, expected)
if mismatches:
raise ValueError(f"{label}: prior_reviewer_queue_readback mismatch: {mismatches}")
if not prior.get("readiness_note"):
raise ValueError(f"{label}: prior_reviewer_queue_readback.readiness_note is required")
def _require_truth(payload: dict[str, Any], label: str) -> None:
truth = payload.get("readback_truth") or {}
required_true = {
"p2_117_reviewer_queue_readback_loaded",
"result_capture_readback_package_ready",
"result_capture_fixture_ready",
"capture_field_mapping_ready",
"no_write_verifier_ready",
"operator_handoff_ready",
"learning_preview_ready",
}
missing = sorted(field for field in required_true if truth.get(field) is not True)
if missing:
raise ValueError(f"{label}: readback ready flags must remain true: {missing}")
if truth.get("owner_approval_received") is not False:
raise ValueError(f"{label}: owner approval must remain false before result capture write")
required_false = {
"canonical_runtime_target_read_enabled",
"live_query_enabled",
"reviewer_queue_write_enabled",
"gateway_queue_write_enabled",
"telegram_send_enabled",
"bot_api_call_enabled",
"report_receipt_write_enabled",
"result_capture_write_enabled",
"learning_write_enabled",
"playbook_trust_write_enabled",
"production_write_enabled",
"secret_read_enabled",
"destructive_operation_enabled",
}
unsafe = sorted(field for field in required_false if truth.get(field) is not False)
if unsafe:
raise ValueError(f"{label}: live read/send/write flags must remain false: {unsafe}")
zero_counts = {
"owner_approval_received_count",
"canonical_runtime_target_read_count",
"live_query_count",
"reviewer_queue_write_count",
"gateway_queue_write_count",
"telegram_send_count",
"bot_api_call_count",
"report_receipt_write_count",
"result_capture_write_count",
"learning_write_count",
"playbook_trust_write_count",
"production_write_count",
}
non_zero = sorted(field for field in zero_counts if truth.get(field) != 0)
if non_zero:
raise ValueError(f"{label}: result capture live counters must remain zero: {non_zero}")
if not truth.get("truth_note"):
raise ValueError(f"{label}: readback_truth.truth_note is required")
def _require_result_capture_fixtures(payload: dict[str, Any], label: str) -> None:
fixtures = payload.get("result_capture_readback_fixtures") or []
required = {
"result_capture_action_required_preview",
"result_capture_no_action_review",
"result_capture_verifier_degraded_hold",
"result_capture_route_lock_review",
"result_capture_owner_acceptance_pending",
}
fixture_ids = {fixture.get("fixture_id") for fixture in fixtures}
if fixture_ids != required:
raise ValueError(f"{label}: result capture fixtures must match {sorted(required)}")
for fixture in fixtures:
fixture_id = fixture.get("fixture_id")
if fixture.get("readback_mode") != "no_write_fixture":
raise ValueError(f"{label}: fixture {fixture_id} must remain no_write_fixture")
if fixture.get("result_capture_write_enabled") is not False:
raise ValueError(f"{label}: fixture {fixture_id} must not enable result capture write")
if fixture.get("status") not in {"ready_for_owner_review", "approval_required", "blocked_by_policy"}:
raise ValueError(f"{label}: fixture {fixture_id} status is invalid")
if not fixture.get("next_manual_action") or not fixture.get("capture_lane"):
raise ValueError(f"{label}: fixture {fixture_id} must include capture lane and next manual action")
if not _is_redacted_sha256(fixture.get("evidence_hash")):
raise ValueError(f"{label}: fixture {fixture_id} must expose redacted evidence_hash")
def _require_capture_mappings(payload: dict[str, Any], label: str) -> None:
mappings = payload.get("capture_field_mappings") or []
required = {
"incident_id_to_capture_key",
"repair_outcome_to_status",
"verifier_state_to_capture_verdict",
"manual_action_to_owner_note",
"learning_candidate_to_hold_reason",
}
mapping_ids = {mapping.get("mapping_id") for mapping in mappings}
if mapping_ids != required:
raise ValueError(f"{label}: capture field mappings must match {sorted(required)}")
for mapping in mappings:
mapping_id = mapping.get("mapping_id")
if mapping.get("target_capture") != _TARGET_CAPTURE:
raise ValueError(f"{label}: mapping {mapping_id} must target {_TARGET_CAPTURE}")
if mapping.get("capture_write_enabled") is not False:
raise ValueError(f"{label}: mapping {mapping_id} must not enable capture write")
if mapping.get("status") not in {"ready", "approval_required", "blocked_by_policy"}:
raise ValueError(f"{label}: mapping {mapping_id} status is invalid")
if not mapping.get("required_owner"):
raise ValueError(f"{label}: mapping {mapping_id} required_owner is required")
if not _is_redacted_sha256(mapping.get("evidence_hash")):
raise ValueError(f"{label}: mapping {mapping_id} must expose redacted evidence_hash")
def _require_verifier_checks(payload: dict[str, Any], label: str) -> None:
checks = payload.get("readback_verifier_checks") or []
required = {
"no_result_capture_write_verifier",
"no_learning_write_verifier",
"no_playbook_trust_write_verifier",
"no_gateway_queue_write_verifier",
"capture_redaction_completeness_verifier",
}
verifier_ids = {check.get("verifier_id") for check in checks}
if verifier_ids != required:
raise ValueError(f"{label}: readback verifier checks must match {sorted(required)}")
for check in checks:
verifier_id = check.get("verifier_id")
if check.get("live_execution_enabled") is not False:
raise ValueError(f"{label}: verifier {verifier_id} must not enable live execution")
if check.get("status") not in {"ready", "approval_required", "blocked_by_policy"}:
raise ValueError(f"{label}: verifier {verifier_id} status is invalid")
if not check.get("verifies") or not check.get("failure_if_missing"):
raise ValueError(f"{label}: verifier {verifier_id} must include verifies and failure_if_missing")
if not _is_redacted_sha256(check.get("evidence_hash")):
raise ValueError(f"{label}: verifier {verifier_id} must expose redacted evidence_hash")
def _require_blockers(payload: dict[str, Any], label: str) -> None:
blockers = payload.get("blocked_result_capture_writes") or []
required = {
"result_capture_writer_not_authorized",
"learning_write_not_authorized",
"playbook_trust_not_authorized",
"gateway_queue_not_authorized",
"production_write_not_authorized",
}
blocker_ids = {blocker.get("blocker_id") for blocker in blockers}
if blocker_ids != required:
raise ValueError(f"{label}: blocked result capture writes must match {sorted(required)}")
for blocker in blockers:
blocker_id = blocker.get("blocker_id")
if blocker.get("status") not in {"approval_required", "blocked_by_policy"}:
raise ValueError(f"{label}: blocker {blocker_id} status is invalid")
if blocker.get("severity") not in {"high", "critical"}:
raise ValueError(f"{label}: blocker {blocker_id} severity is invalid")
if not blocker.get("blocked_action") or not blocker.get("blocked_until"):
raise ValueError(f"{label}: blocker {blocker_id} must include blocked_action and blocked_until")
if not _is_redacted_sha256(blocker.get("evidence_hash")):
raise ValueError(f"{label}: blocker {blocker_id} must expose redacted evidence_hash")
def _require_actions(payload: dict[str, Any], label: str) -> None:
actions = payload.get("operator_actions") or []
required = {
"review_result_capture_preview",
"verify_capture_no_write_counts",
"confirm_owner_acceptance_fields",
"check_capture_redaction_contract",
"promote_to_p2_119",
}
action_ids = {action.get("action_id") for action in actions}
if action_ids != required:
raise ValueError(f"{label}: operator actions must match {sorted(required)}")
for action in actions:
action_id = action.get("action_id")
if action.get("runtime_capture_write_allowed") is not False:
raise ValueError(f"{label}: action {action_id} must not allow runtime capture write")
if not action.get("operator_instruction"):
raise ValueError(f"{label}: action {action_id} operator_instruction is required")
def _require_display_redaction(payload: dict[str, Any], label: str) -> None:
contract = payload.get("display_redaction_contract") or {}
expected = {
"redaction_required": True,
"raw_prompt_display_allowed": False,
"private_reasoning_display_allowed": False,
"secret_value_display_allowed": False,
"raw_runtime_payload_display_allowed": False,
"internal_collaboration_content_display_allowed": False,
}
mismatches = _mismatches(contract, expected)
if mismatches:
raise ValueError(f"{label}: display_redaction_contract mismatch: {mismatches}")
if not contract.get("frontend_display_policy"):
raise ValueError(f"{label}: display_redaction_contract.frontend_display_policy is required")
def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
rollups = payload.get("rollups") or {}
fixtures = payload.get("result_capture_readback_fixtures") or []
mappings = payload.get("capture_field_mappings") or []
verifiers = payload.get("readback_verifier_checks") or []
blockers = payload.get("blocked_result_capture_writes") or []
actions = payload.get("operator_actions") or []
expected = {
"result_capture_readback_fixture_count": len(fixtures),
"capture_field_mapping_count": len(mappings),
"readback_verifier_check_count": len(verifiers),
"blocked_result_capture_write_count": len(blockers),
"operator_action_count": len(actions),
"approval_required_fixture_count": sum(1 for item in fixtures if item.get("status") == "approval_required"),
"blocked_fixture_count": sum(1 for item in fixtures if item.get("status") == "blocked_by_policy"),
"approval_required_mapping_count": sum(1 for item in mappings if item.get("status") == "approval_required"),
"blocked_mapping_count": sum(1 for item in mappings if item.get("status") == "blocked_by_policy"),
"approval_required_verifier_count": sum(1 for item in verifiers if item.get("status") == "approval_required"),
"critical_blocker_count": sum(1 for item in blockers if item.get("severity") == "critical"),
"owner_approval_received_count": 0,
"canonical_runtime_target_read_count": 0,
"live_query_count": 0,
"reviewer_queue_write_count": 0,
"gateway_queue_write_count": 0,
"telegram_send_count": 0,
"bot_api_call_count": 0,
"report_receipt_write_count": 0,
"result_capture_write_count": 0,
"learning_write_count": 0,
"playbook_trust_write_count": 0,
"production_write_count": 0,
"secret_read_count": 0,
"destructive_operation_count": 0,
}
mismatches = _mismatches(rollups, expected)
if mismatches:
raise ValueError(f"{label}: rollup counts mismatch: {mismatches}")
def _require_no_forbidden_display_terms(payload: dict[str, Any], label: str) -> None:
serialized = json.dumps(payload, ensure_ascii=False)
forbidden = {
"work_window_transcript",
"session_id",
"browser_context",
"authorization_header",
"raw Telegram payload",
"private reasoning",
"raw prompt",
"chain-of-thought",
}
hits = sorted(term for term in forbidden if term in serialized)
if hits:
raise ValueError(f"{label}: forbidden display terms present: {hits}")
def _is_redacted_sha256(value: Any) -> bool:
if not isinstance(value, str) or not value.startswith("sha256:"):
return False
digest = value.removeprefix("sha256:")
return len(digest) == 64 and all(char in "0123456789abcdef" for char in digest)
def _mismatches(payload: dict[str, Any], expected: dict[str, Any]) -> dict[str, dict[str, Any]]:
return {
key: {"expected": value, "actual": payload.get(key)}
for key, value in expected.items()
if payload.get(key) != value
}

View File

@@ -0,0 +1,112 @@
import copy
import json
from pathlib import Path
import pytest
from src.services.ai_agent_result_capture_no_write_readback import (
load_latest_ai_agent_result_capture_no_write_readback,
)
REPO_ROOT = Path(__file__).resolve().parents[3]
FIXTURE = REPO_ROOT / "docs/evaluations/ai_agent_result_capture_no_write_readback_2026-06-13.json"
def test_load_latest_ai_agent_result_capture_no_write_readback_snapshot() -> None:
data = load_latest_ai_agent_result_capture_no_write_readback()
assert data["schema_version"] == "ai_agent_result_capture_no_write_readback_v1"
assert data["program_status"]["current_task_id"] == "P2-118"
assert data["program_status"]["next_task_id"] == "P2-119"
assert data["program_status"]["overall_completion_percent"] == 100
assert data["program_status"]["read_only_mode"] is True
rollups = data["rollups"]
assert rollups["result_capture_readback_fixture_count"] == 5
assert rollups["capture_field_mapping_count"] == 5
assert rollups["readback_verifier_check_count"] == 5
assert rollups["blocked_result_capture_write_count"] == 5
assert rollups["operator_action_count"] == 5
assert rollups["approval_required_fixture_count"] == 2
assert rollups["blocked_fixture_count"] == 2
assert rollups["approval_required_mapping_count"] == 1
assert rollups["blocked_mapping_count"] == 2
assert rollups["approval_required_verifier_count"] == 2
assert rollups["critical_blocker_count"] == 3
assert {mapping["target_capture"] for mapping in data["capture_field_mappings"]} == {
"result_capture_preview"
}
assert {fixture["readback_mode"] for fixture in data["result_capture_readback_fixtures"]} == {
"no_write_fixture"
}
zero_fields = [
"owner_approval_received_count",
"canonical_runtime_target_read_count",
"live_query_count",
"reviewer_queue_write_count",
"gateway_queue_write_count",
"telegram_send_count",
"bot_api_call_count",
"report_receipt_write_count",
"result_capture_write_count",
"learning_write_count",
"playbook_trust_write_count",
"production_write_count",
"secret_read_count",
"destructive_operation_count",
]
for field in zero_fields:
assert rollups[field] == 0
def test_result_capture_no_write_readback_rejects_capture_write_enabled(tmp_path: Path) -> None:
source = json.loads(FIXTURE.read_text(encoding="utf-8"))
source["result_capture_readback_fixtures"][0]["result_capture_write_enabled"] = True
target = tmp_path / "ai_agent_result_capture_no_write_readback_2026-06-13.json"
target.write_text(json.dumps(source), encoding="utf-8")
with pytest.raises(ValueError, match="must not enable result capture write"):
load_latest_ai_agent_result_capture_no_write_readback(tmp_path)
def test_result_capture_no_write_readback_rejects_truth_write_flag(tmp_path: Path) -> None:
source = json.loads(FIXTURE.read_text(encoding="utf-8"))
source["readback_truth"]["result_capture_write_enabled"] = True
target = tmp_path / "ai_agent_result_capture_no_write_readback_2026-06-13.json"
target.write_text(json.dumps(source), encoding="utf-8")
with pytest.raises(ValueError, match="live read/send/write flags"):
load_latest_ai_agent_result_capture_no_write_readback(tmp_path)
def test_result_capture_no_write_readback_rejects_target_capture_drift(tmp_path: Path) -> None:
source = json.loads(FIXTURE.read_text(encoding="utf-8"))
source["capture_field_mappings"][0]["target_capture"] = "live_result_capture"
target = tmp_path / "ai_agent_result_capture_no_write_readback_2026-06-13.json"
target.write_text(json.dumps(source), encoding="utf-8")
with pytest.raises(ValueError, match="must target result_capture_preview"):
load_latest_ai_agent_result_capture_no_write_readback(tmp_path)
def test_result_capture_no_write_readback_rejects_rollup_drift(tmp_path: Path) -> None:
source = json.loads(FIXTURE.read_text(encoding="utf-8"))
source["rollups"]["result_capture_readback_fixture_count"] = 4
target = tmp_path / "ai_agent_result_capture_no_write_readback_2026-06-13.json"
target.write_text(json.dumps(source), encoding="utf-8")
with pytest.raises(ValueError, match="rollup counts mismatch"):
load_latest_ai_agent_result_capture_no_write_readback(tmp_path)
def test_result_capture_no_write_readback_rejects_forbidden_display_terms(tmp_path: Path) -> None:
source = copy.deepcopy(json.loads(FIXTURE.read_text(encoding="utf-8")))
source["operator_actions"][0]["operator_instruction"] = "do not expose session_id"
target = tmp_path / "ai_agent_result_capture_no_write_readback_2026-06-13.json"
target.write_text(json.dumps(source), encoding="utf-8")
with pytest.raises(ValueError, match="forbidden display terms"):
load_latest_ai_agent_result_capture_no_write_readback(tmp_path)

View File

@@ -0,0 +1,45 @@
import pytest
from httpx import ASGITransport, AsyncClient
from src.main import app
@pytest.mark.asyncio
async def test_get_agent_result_capture_no_write_readback_api() -> None:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.get("/api/v1/agents/agent-result-capture-no-write-readback")
assert response.status_code == 200
data = response.json()
assert data["schema_version"] == "ai_agent_result_capture_no_write_readback_v1"
assert data["program_status"]["current_task_id"] == "P2-118"
assert data["program_status"]["next_task_id"] == "P2-119"
assert data["program_status"]["overall_completion_percent"] == 100
rollups = data["rollups"]
assert rollups["result_capture_readback_fixture_count"] == 5
assert rollups["capture_field_mapping_count"] == 5
assert rollups["readback_verifier_check_count"] == 5
assert rollups["blocked_result_capture_write_count"] == 5
assert rollups["operator_action_count"] == 5
assert rollups["critical_blocker_count"] == 3
assert rollups["owner_approval_received_count"] == 0
assert rollups["canonical_runtime_target_read_count"] == 0
assert rollups["live_query_count"] == 0
assert rollups["reviewer_queue_write_count"] == 0
assert rollups["gateway_queue_write_count"] == 0
assert rollups["telegram_send_count"] == 0
assert rollups["bot_api_call_count"] == 0
assert rollups["report_receipt_write_count"] == 0
assert rollups["result_capture_write_count"] == 0
assert rollups["learning_write_count"] == 0
assert rollups["playbook_trust_write_count"] == 0
assert rollups["production_write_count"] == 0
assert {mapping["target_capture"] for mapping in data["capture_field_mappings"]} == {
"result_capture_preview"
}
assert {fixture["result_capture_write_enabled"] for fixture in data["result_capture_readback_fixtures"]} == {
False
}