|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""TurtleTerm local SourceOS Agent Reliability status view. |
| 3 | +
|
| 4 | +Reads local SourceOS evidence artifacts and summarizes: |
| 5 | +- blocking guardrail decisions; |
| 6 | +- stop-gate outcomes; |
| 7 | +- guarded invocation outcomes; |
| 8 | +- pending governance queue items. |
| 9 | +
|
| 10 | +This tool is read-only. It does not modify policy, memory, git state, or queue |
| 11 | +artifacts. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import argparse |
| 17 | +import json |
| 18 | +from collections import Counter |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +BLOCKING_DECISIONS = {"deny", "quarantine", "defer", "escalate"} |
| 23 | +NEEDS_REVIEW_QUEUE_STATUSES = {"pending"} |
| 24 | + |
| 25 | + |
| 26 | +def load_json(path: Path) -> dict[str, Any] | None: |
| 27 | + try: |
| 28 | + data = json.loads(path.read_text(encoding="utf-8")) |
| 29 | + except (OSError, json.JSONDecodeError): |
| 30 | + return None |
| 31 | + return data if isinstance(data, dict) else None |
| 32 | + |
| 33 | + |
| 34 | +def load_jsonl(path: Path) -> list[dict[str, Any]]: |
| 35 | + if not path.exists(): |
| 36 | + return [] |
| 37 | + rows: list[dict[str, Any]] = [] |
| 38 | + try: |
| 39 | + for line in path.read_text(encoding="utf-8").splitlines(): |
| 40 | + if not line.strip(): |
| 41 | + continue |
| 42 | + try: |
| 43 | + data = json.loads(line) |
| 44 | + except json.JSONDecodeError: |
| 45 | + rows.append({"schema": "invalid-json", "decision": "invalid", "decisionId": f"{path}:invalid-json"}) |
| 46 | + continue |
| 47 | + if isinstance(data, dict): |
| 48 | + rows.append(data) |
| 49 | + except OSError: |
| 50 | + return [] |
| 51 | + return rows |
| 52 | + |
| 53 | + |
| 54 | +def unique_paths(paths: list[Path]) -> list[Path]: |
| 55 | + seen: set[str] = set() |
| 56 | + out: list[Path] = [] |
| 57 | + for path in paths: |
| 58 | + key = str(path.resolve()) |
| 59 | + if key not in seen: |
| 60 | + seen.add(key) |
| 61 | + out.append(path) |
| 62 | + return out |
| 63 | + |
| 64 | + |
| 65 | +def discover_json_artifacts(root: Path, filenames: set[str]) -> list[dict[str, Any]]: |
| 66 | + artifacts: list[dict[str, Any]] = [] |
| 67 | + paths: list[Path] = [] |
| 68 | + sourceos = root / ".sourceos" |
| 69 | + if sourceos.exists(): |
| 70 | + for name in filenames: |
| 71 | + paths.extend(sourceos.rglob(name)) |
| 72 | + for path in unique_paths(paths): |
| 73 | + data = load_json(path) |
| 74 | + if data is not None: |
| 75 | + data["_path"] = str(path) |
| 76 | + artifacts.append(data) |
| 77 | + return artifacts |
| 78 | + |
| 79 | + |
| 80 | +def discover_governance_queues(root: Path) -> list[dict[str, Any]]: |
| 81 | + queues: list[dict[str, Any]] = [] |
| 82 | + candidates: list[Path] = [] |
| 83 | + for base in [root / ".sourceos", root / "standards" / "agent-reliability"]: |
| 84 | + if base.exists(): |
| 85 | + candidates.extend(base.rglob("*governance-queue*.json")) |
| 86 | + for path in unique_paths(candidates): |
| 87 | + data = load_json(path) |
| 88 | + if data and data.get("kind") == "AgentReliabilityGovernanceQueue": |
| 89 | + data["_path"] = str(path) |
| 90 | + queues.append(data) |
| 91 | + return queues |
| 92 | + |
| 93 | + |
| 94 | +def summarize(root: Path) -> dict[str, Any]: |
| 95 | + decision_log = root / ".sourceos" / "logs" / "guardrail-decisions.jsonl" |
| 96 | + decisions = load_jsonl(decision_log) |
| 97 | + decision_counts = Counter(str(item.get("decision", "unknown")) for item in decisions) |
| 98 | + blocking = [item for item in decisions if str(item.get("decision", "")).lower() in BLOCKING_DECISIONS] |
| 99 | + redactions = [item for item in decisions if str(item.get("decision", "")).lower() == "redact"] |
| 100 | + |
| 101 | + stop_gates = discover_json_artifacts(root, {"stop-gate-artifact.json"}) |
| 102 | + stop_gate_counts = Counter(str(item.get("result", "unknown")) for item in stop_gates if item.get("kind") == "StopGateArtifact") |
| 103 | + failing_stop_gates = [item for item in stop_gates if item.get("kind") == "StopGateArtifact" and item.get("result") in {"fail", "needs_human"}] |
| 104 | + |
| 105 | + invocations = discover_json_artifacts(root, {"guarded-invocation-artifact.json"}) |
| 106 | + invocation_counts = Counter(str(item.get("result", "unknown")) for item in invocations if item.get("kind") == "GuardedInvocationArtifact") |
| 107 | + failed_invocations = [item for item in invocations if item.get("kind") == "GuardedInvocationArtifact" and item.get("result") in {"failure", "blocked", "needs_human"}] |
| 108 | + |
| 109 | + queues = discover_governance_queues(root) |
| 110 | + pending_queue_items: list[dict[str, Any]] = [] |
| 111 | + for queue in queues: |
| 112 | + for item in queue.get("items", []): |
| 113 | + if isinstance(item, dict) and item.get("status") in NEEDS_REVIEW_QUEUE_STATUSES: |
| 114 | + pending = dict(item) |
| 115 | + pending["queuePath"] = queue.get("_path") |
| 116 | + pending_queue_items.append(pending) |
| 117 | + |
| 118 | + status = "ready" |
| 119 | + if blocking or failing_stop_gates or failed_invocations: |
| 120 | + status = "blocked" |
| 121 | + elif pending_queue_items: |
| 122 | + status = "needs_review" |
| 123 | + elif not decisions and not stop_gates and not invocations and not queues: |
| 124 | + status = "no_artifacts" |
| 125 | + |
| 126 | + return { |
| 127 | + "schema": "sourceos.turtle.agent_status.v0", |
| 128 | + "root": str(root), |
| 129 | + "status": status, |
| 130 | + "guardrail": { |
| 131 | + "decisionLog": str(decision_log), |
| 132 | + "total": len(decisions), |
| 133 | + "counts": dict(decision_counts), |
| 134 | + "blocking": [item.get("decisionId") or item.get("policyId") for item in blocking], |
| 135 | + "redactions": [item.get("decisionId") or item.get("policyId") for item in redactions], |
| 136 | + }, |
| 137 | + "stopGates": { |
| 138 | + "total": len(stop_gates), |
| 139 | + "counts": dict(stop_gate_counts), |
| 140 | + "blocking": [item.get("gateId") or item.get("_path") for item in failing_stop_gates], |
| 141 | + }, |
| 142 | + "invocations": { |
| 143 | + "total": len(invocations), |
| 144 | + "counts": dict(invocation_counts), |
| 145 | + "blocking": [item.get("workcellArtifactRef") or item.get("_path") for item in failed_invocations], |
| 146 | + }, |
| 147 | + "governance": { |
| 148 | + "queues": len(queues), |
| 149 | + "pending": [ |
| 150 | + { |
| 151 | + "itemId": item.get("itemId"), |
| 152 | + "itemType": item.get("itemType"), |
| 153 | + "priority": item.get("priority"), |
| 154 | + "title": item.get("title"), |
| 155 | + "queuePath": item.get("queuePath"), |
| 156 | + } |
| 157 | + for item in pending_queue_items |
| 158 | + ], |
| 159 | + }, |
| 160 | + } |
| 161 | + |
| 162 | + |
| 163 | +def print_human(summary: dict[str, Any]) -> None: |
| 164 | + print(f"TurtleTerm Agent Status: {summary['status']}") |
| 165 | + print(f"root: {summary['root']}") |
| 166 | + print("") |
| 167 | + print("Guardrails") |
| 168 | + print(f" decisions: {summary['guardrail']['total']} {summary['guardrail']['counts']}") |
| 169 | + if summary["guardrail"]["blocking"]: |
| 170 | + print(f" blocking: {', '.join(str(x) for x in summary['guardrail']['blocking'])}") |
| 171 | + if summary["guardrail"]["redactions"]: |
| 172 | + print(f" redactions: {', '.join(str(x) for x in summary['guardrail']['redactions'])}") |
| 173 | + print("Stop gates") |
| 174 | + print(f" artifacts: {summary['stopGates']['total']} {summary['stopGates']['counts']}") |
| 175 | + if summary["stopGates"]["blocking"]: |
| 176 | + print(f" blocking: {', '.join(str(x) for x in summary['stopGates']['blocking'])}") |
| 177 | + print("Invocations") |
| 178 | + print(f" artifacts: {summary['invocations']['total']} {summary['invocations']['counts']}") |
| 179 | + if summary["invocations"]["blocking"]: |
| 180 | + print(f" blocking: {', '.join(str(x) for x in summary['invocations']['blocking'])}") |
| 181 | + print("Governance") |
| 182 | + print(f" queues: {summary['governance']['queues']}") |
| 183 | + print(f" pending review items: {len(summary['governance']['pending'])}") |
| 184 | + for item in summary["governance"]["pending"]: |
| 185 | + print(f" - [{item.get('priority')}] {item.get('itemType')}: {item.get('title')} ({item.get('itemId')})") |
| 186 | + |
| 187 | + |
| 188 | +def build_parser() -> argparse.ArgumentParser: |
| 189 | + parser = argparse.ArgumentParser(description="Read local SourceOS agent reliability artifacts and print TurtleTerm status.") |
| 190 | + parser.add_argument("--root", default=".", help="Workspace/repo root to inspect") |
| 191 | + parser.add_argument("--json", action="store_true", help="Emit JSON instead of human-readable text") |
| 192 | + return parser |
| 193 | + |
| 194 | + |
| 195 | +def main(argv: list[str] | None = None) -> int: |
| 196 | + args = build_parser().parse_args(argv) |
| 197 | + root = Path(args.root).resolve() |
| 198 | + summary = summarize(root) |
| 199 | + if args.json: |
| 200 | + print(json.dumps(summary, indent=2, sort_keys=True)) |
| 201 | + else: |
| 202 | + print_human(summary) |
| 203 | + return 0 if summary["status"] in {"ready", "no_artifacts"} else 2 |
| 204 | + |
| 205 | + |
| 206 | +if __name__ == "__main__": |
| 207 | + raise SystemExit(main()) |
0 commit comments