feat(governance): 新增 runtime write gate review
Some checks failed
CD Pipeline / tests (push) Successful in 1m30s
Code Review / ai-code-review (push) Successful in 15s
CD Pipeline / build-and-deploy (push) Has been cancelled
CD Pipeline / post-deploy-checks (push) Has been cancelled

This commit is contained in:
Your Name
2026-06-12 00:39:10 +08:00
parent ac39e4fb2f
commit 7a7daa333e
21 changed files with 1017 additions and 56 deletions

View File

@@ -82,6 +82,9 @@ from src.services.ai_agent_proactive_operations_contract import (
from src.services.ai_agent_redis_dry_run_gate import (
load_latest_ai_agent_redis_dry_run_gate,
)
from src.services.ai_agent_runtime_write_gate_review import (
load_latest_ai_agent_runtime_write_gate_review,
)
from src.services.ai_agent_telegram_action_required_digest_policy import (
load_latest_ai_agent_telegram_action_required_digest_policy,
)
@@ -757,6 +760,34 @@ async def get_agent_owner_approved_learning_dry_run() -> dict[str, Any]:
) from exc
@router.get(
"/agent-runtime-write-gate-review",
response_model=dict[str, Any],
summary="取得 AI Agent runtime write gate review",
description=(
"讀取最新已提交的 runtime write gate review 契約;此端點只回傳雙重批准、"
"dry-run hash、post-write verifier 與 redaction 欄位檢查,"
"不寫 KM、不更新 PlayBook trust、不寫 timeline、不寫 replay score、不發 Telegram、"
"不啟動 runtime worker、不回傳未脫敏 payload。"
),
)
async def get_agent_runtime_write_gate_review() -> dict[str, Any]:
"""Return the latest read-only AI Agent runtime write gate review."""
try:
return await asyncio.to_thread(load_latest_ai_agent_runtime_write_gate_review)
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_runtime_write_gate_review_invalid", error=str(exc))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="AI Agent runtime write gate review 無效",
) from exc
@router.get(
"/agent-owner-approved-fixture-dry-run",
response_model=dict[str, Any],

View File

@@ -0,0 +1,147 @@
"""
AI Agent runtime write gate review snapshot.
Loads the latest committed P2-403G runtime write gate review contract. This
module never writes KM, PlayBook trust, timeline learning, replay scores, or
Telegram receipts.
"""
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_runtime_write_gate_review_*.json"
_SCHEMA_VERSION = "ai_agent_runtime_write_gate_review_v1"
def load_latest_ai_agent_runtime_write_gate_review(
evaluations_dir: Path | None = None,
) -> dict[str, Any]:
"""Load the newest committed AI Agent runtime write gate review contract."""
directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
if not candidates:
raise FileNotFoundError(f"no AI Agent runtime write gate review 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")
_require_schema(payload, str(latest))
_require_write_boundaries(payload, str(latest))
_require_review_contract(payload, str(latest))
_require_rollup_consistency(payload, str(latest))
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 {}
if status.get("read_only_mode") is not True:
raise ValueError(f"{label}: program_status.read_only_mode must be true")
if status.get("runtime_authority") != "write_gate_review_only_no_runtime_write":
raise ValueError(f"{label}: runtime_authority must remain write_gate_review_only_no_runtime_write")
def _require_write_boundaries(payload: dict[str, Any], label: str) -> None:
boundaries = payload.get("approval_boundaries") or {}
enabled = sorted(key for key, value in boundaries.items() if value is not False)
if enabled:
raise ValueError(f"{label}: approval boundaries must remain false: {enabled}")
truth = payload.get("runtime_write_truth") or {}
false_flags = {
"runtime_write_allowed",
"km_write_allowed",
"playbook_trust_write_allowed",
"timeline_learning_write_allowed",
"agent_replay_score_write_allowed",
"telegram_send_allowed",
}
unsafe = sorted(flag for flag in false_flags if truth.get(flag) is not False)
if unsafe:
raise ValueError(f"{label}: runtime write flags must remain false: {unsafe}")
required_true = {
"dual_approval_required",
"dry_run_hash_required",
"post_write_verifier_required",
}
missing = sorted(flag for flag in required_true if truth.get(flag) is not True)
if missing:
raise ValueError(f"{label}: required write gates must remain true: {missing}")
zero_counts = {
"dual_approval_received_count",
"dry_run_hash_verified_count",
"post_write_verifier_pass_count",
}
non_zero = sorted(key for key in zero_counts if truth.get(key) != 0)
if non_zero:
raise ValueError(f"{label}: write gate counts must remain zero: {non_zero}")
def _require_review_contract(payload: dict[str, Any], label: str) -> None:
review = payload.get("write_gate_review") or {}
required_fields = set(review.get("required_fields") or [])
required_minimum = {
"dual_approval_ids",
"dry_run_preview_hash",
"redacted_evidence_refs",
"target_write_surface",
"rollback_owner",
"post_write_verifier_ref",
}
missing = sorted(required_minimum - required_fields)
if missing:
raise ValueError(f"{label}: write gate review missing required fields: {missing}")
verification = payload.get("post_write_verification") or {}
if verification.get("verification_required") is not True:
raise ValueError(f"{label}: post-write verification must be required")
if verification.get("rollback_required") is not True:
raise ValueError(f"{label}: rollback must be required")
if not verification.get("verification_steps"):
raise ValueError(f"{label}: verification steps must not be empty")
redaction = payload.get("display_redaction_contract") or {}
if redaction.get("redaction_required") is not True:
raise ValueError(f"{label}: frontend redaction must be required")
for flag in ("raw_payload_display_allowed", "private_reasoning_display_allowed", "secret_value_display_allowed"):
if redaction.get(flag) is not False:
raise ValueError(f"{label}: {flag} must remain false")
def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
rollups = payload.get("rollups") or {}
targets = payload.get("write_targets") or []
gates = payload.get("approval_gates") or []
review = payload.get("write_gate_review") or {}
expected_counts = {
"write_target_count": len(targets),
"approval_gate_count": len(gates),
"blocked_runtime_action_count": len({gate.get("blocked_runtime_action") for gate in gates}),
"required_field_count": len(review.get("required_fields") or []),
"forbidden_field_count": len(review.get("forbidden_fields") or []),
}
mismatched = {
key: {"expected": expected, "actual": rollups.get(key)}
for key, expected in expected_counts.items()
if rollups.get(key) != expected
}
if mismatched:
raise ValueError(f"{label}: rollup counts must match payload sections: {mismatched}")
approval_required = sorted(gate.get("gate_id") for gate in gates if gate.get("status") == "approval_required")
if sorted(rollups.get("approval_required_gate_ids") or []) != approval_required:
raise ValueError(f"{label}: rollups.approval_required_gate_ids mismatch")
if rollups.get("live_write_count_total") != 0:
raise ValueError(f"{label}: live write count must remain zero")

View File

@@ -13,9 +13,9 @@ def test_load_latest_ai_agent_interaction_learning_proof_reads_committed_snapsho
data = load_latest_ai_agent_interaction_learning_proof()
assert data["schema_version"] == "ai_agent_interaction_learning_proof_v1"
assert data["program_status"]["overall_completion_percent"] == 88
assert data["program_status"]["current_task_id"] == "P2-403F"
assert data["program_status"]["next_task_id"] == "P2-403G"
assert data["program_status"]["overall_completion_percent"] == 94
assert data["program_status"]["current_task_id"] == "P2-403G"
assert data["program_status"]["next_task_id"] == "P2-403H"
assert data["program_status"]["read_only_mode"] is True
assert data["program_status"]["runtime_authority"] == "proof_surface_only_no_live_worker"
assert data["live_truth"]["runtime_loop_enabled"] is False

View File

@@ -16,9 +16,9 @@ def test_ai_agent_interaction_learning_proof_endpoint_returns_committed_snapshot
assert response.status_code == 200
data = response.json()
assert data["schema_version"] == "ai_agent_interaction_learning_proof_v1"
assert data["program_status"]["overall_completion_percent"] == 88
assert data["program_status"]["current_task_id"] == "P2-403F"
assert data["program_status"]["next_task_id"] == "P2-403G"
assert data["program_status"]["overall_completion_percent"] == 94
assert data["program_status"]["current_task_id"] == "P2-403G"
assert data["program_status"]["next_task_id"] == "P2-403H"
assert data["program_status"]["read_only_mode"] is True
assert data["live_truth"]["runtime_loop_enabled"] is False
assert data["live_truth"]["active_live_agent_sessions"] == 0

View File

@@ -14,8 +14,8 @@ def test_load_latest_ai_agent_proactive_operations_contract_reads_committed_snap
assert data["schema_version"] == "ai_agent_proactive_operations_contract_v1"
assert data["program_status"]["overall_completion_percent"] == 100
assert data["program_status"]["current_task_id"] == "P2-403F"
assert data["program_status"]["next_task_id"] == "P2-403G"
assert data["program_status"]["current_task_id"] == "P2-403G"
assert data["program_status"]["next_task_id"] == "P2-403H"
assert data["program_status"]["read_only_mode"] is True
assert data["program_status"]["runtime_authority"] == "contract_only_no_version_or_runtime_update"
assert data["approval_boundaries"]["runtime_version_update_allowed"] is False
@@ -25,7 +25,7 @@ def test_load_latest_ai_agent_proactive_operations_contract_reads_committed_snap
assert data["approval_boundaries"]["telegram_direct_send_allowed"] is False
assert data["rollups"]["version_domain_count"] == len(data["version_lifecycle_domains"]) == 12
assert data["rollups"]["delegable_capability_count"] == len(data["delegable_capabilities"]) == 24
assert data["rollups"]["rollout_task_count"] == len(data["rollout_tasks"]) == 13
assert data["rollups"]["rollout_task_count"] == len(data["rollout_tasks"]) == 14
assert data["rollups"]["auto_execute_allowed_count"] == 0
assert any(domain["domain_id"] == "ai_agents_models" for domain in data["version_lifecycle_domains"])
assert any(

View File

@@ -17,8 +17,8 @@ def test_ai_agent_proactive_operations_contract_endpoint_returns_committed_snaps
data = response.json()
assert data["schema_version"] == "ai_agent_proactive_operations_contract_v1"
assert data["program_status"]["overall_completion_percent"] == 100
assert data["program_status"]["current_task_id"] == "P2-403F"
assert data["program_status"]["next_task_id"] == "P2-403G"
assert data["program_status"]["current_task_id"] == "P2-403G"
assert data["program_status"]["next_task_id"] == "P2-403H"
assert data["program_status"]["read_only_mode"] is True
assert data["approval_boundaries"]["runtime_version_update_allowed"] is False
assert data["approval_boundaries"]["package_upgrade_allowed"] is False
@@ -26,7 +26,7 @@ def test_ai_agent_proactive_operations_contract_endpoint_returns_committed_snaps
assert data["approval_boundaries"]["telegram_direct_send_allowed"] is False
assert data["rollups"]["version_domain_count"] == 12
assert data["rollups"]["delegable_capability_count"] == 24
assert data["rollups"]["rollout_task_count"] == 13
assert data["rollups"]["rollout_task_count"] == 14
assert data["rollups"]["auto_execute_allowed_count"] == 0
assert any(domain["domain_id"] == "host_os_packages" for domain in data["version_lifecycle_domains"])
assert any(

View File

@@ -0,0 +1,74 @@
import copy
import json
import pytest
from src.services.ai_agent_runtime_write_gate_review import (
load_latest_ai_agent_runtime_write_gate_review,
)
def _write_snapshot(tmp_path, payload):
path = tmp_path / "ai_agent_runtime_write_gate_review_2026-06-12.json"
path.write_text(json.dumps(payload), encoding="utf-8")
return path
def test_load_latest_ai_agent_runtime_write_gate_review():
data = load_latest_ai_agent_runtime_write_gate_review()
assert data["schema_version"] == "ai_agent_runtime_write_gate_review_v1"
assert data["program_status"]["current_task_id"] == "P2-403G"
assert data["program_status"]["next_task_id"] == "P2-403H"
assert data["program_status"]["overall_completion_percent"] == 94
assert data["runtime_write_truth"]["runtime_write_allowed"] is False
assert data["runtime_write_truth"]["dual_approval_required"] is True
assert data["runtime_write_truth"]["dual_approval_received_count"] == 0
assert data["runtime_write_truth"]["dry_run_hash_verified_count"] == 0
assert data["runtime_write_truth"]["post_write_verifier_pass_count"] == 0
assert data["rollups"]["write_target_count"] == len(data["write_targets"])
assert data["rollups"]["approval_gate_count"] == len(data["approval_gates"])
assert data["rollups"]["live_write_count_total"] == 0
def test_rejects_runtime_write_enabled(tmp_path):
data = load_latest_ai_agent_runtime_write_gate_review()
bad = copy.deepcopy(data)
bad["runtime_write_truth"]["runtime_write_allowed"] = True
_write_snapshot(tmp_path, bad)
with pytest.raises(ValueError, match="runtime write flags"):
load_latest_ai_agent_runtime_write_gate_review(tmp_path)
def test_rejects_dual_approval_count_increment(tmp_path):
data = load_latest_ai_agent_runtime_write_gate_review()
bad = copy.deepcopy(data)
bad["runtime_write_truth"]["dual_approval_received_count"] = 1
_write_snapshot(tmp_path, bad)
with pytest.raises(ValueError, match="write gate counts"):
load_latest_ai_agent_runtime_write_gate_review(tmp_path)
def test_rejects_missing_required_review_field(tmp_path):
data = load_latest_ai_agent_runtime_write_gate_review()
bad = copy.deepcopy(data)
bad["write_gate_review"]["required_fields"] = [
field for field in bad["write_gate_review"]["required_fields"] if field != "dry_run_preview_hash"
]
bad["rollups"]["required_field_count"] = len(bad["write_gate_review"]["required_fields"])
_write_snapshot(tmp_path, bad)
with pytest.raises(ValueError, match="missing required fields"):
load_latest_ai_agent_runtime_write_gate_review(tmp_path)
def test_rejects_rollup_mismatch(tmp_path):
data = load_latest_ai_agent_runtime_write_gate_review()
bad = copy.deepcopy(data)
bad["rollups"]["approval_gate_count"] = 999
_write_snapshot(tmp_path, bad)
with pytest.raises(ValueError, match="rollup counts"):
load_latest_ai_agent_runtime_write_gate_review(tmp_path)

View File

@@ -0,0 +1,20 @@
from fastapi.testclient import TestClient
from src.main import app
def test_get_ai_agent_runtime_write_gate_review_api():
client = TestClient(app)
response = client.get("/api/v1/agents/agent-runtime-write-gate-review")
assert response.status_code == 200
data = response.json()
assert data["schema_version"] == "ai_agent_runtime_write_gate_review_v1"
assert data["program_status"]["current_task_id"] == "P2-403G"
assert data["program_status"]["next_task_id"] == "P2-403H"
assert data["program_status"]["overall_completion_percent"] == 94
assert data["runtime_write_truth"]["runtime_write_allowed"] is False
assert data["runtime_write_truth"]["dual_approval_received_count"] == 0
assert data["runtime_write_truth"]["dry_run_hash_verified_count"] == 0
assert data["runtime_write_truth"]["post_write_verifier_pass_count"] == 0
assert data["rollups"]["live_write_count_total"] == 0