From 1b3e4eb0a700a270c5b03736252657c8778d80a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:13:02 +0000 Subject: [PATCH 1/2] feat: export ledgers in the IETF Agent Audit Trail draft -11 format Adds am export-aat / am verify-aat and to_aat/export_aat/verify_aat. Targets draft-sharif-agent-audit-trail-11 (2026-11-21), an individual Internet-Draft, and records that revision in every exported record. Includes an RFC 8785 canonicaliser for the section 6.1 prev_hash chain. Refuses ledgers whose native chain fails verification. Fields the native ledger lacks are filled with documented defaults. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Aq8kkjQte1m3idCZFj8t8E --- CHANGELOG.md | 15 ++ README.md | 42 +++++- README_KO.md | 36 ++++- actmirror/__init__.py | 3 +- actmirror/aat.py | 331 ++++++++++++++++++++++++++++++++++++++++++ actmirror/am.py | 45 ++++++ tests/test_aat.py | 193 ++++++++++++++++++++++++ 7 files changed, 662 insertions(+), 3 deletions(-) create mode 100644 actmirror/aat.py create mode 100644 tests/test_aat.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d2ea840..0cd802f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [Unreleased] + +### Added +- **`am export-aat` / `am verify-aat`** (and `to_aat`, `export_aat`, `verify_aat`): export a + ledger in the record format of the IETF Internet-Draft + `draft-sharif-agent-audit-trail-11` (2026-11-21). The draft is an individual submission, + not a standard; only -11 is targeted and the revision is written into each record. + Includes an RFC 8785 (JCS) canonicaliser for the §6.1 `prev_hash` chain. A ledger whose + native chain fails verification is refused. AAT fields action-mirror does not record + (principal, agent_version, trust_level, outcome) are filled with documented defaults; + see the README section for every limitation. + +### Fixed +- README said "21 tests"; the suite had grown past that. The count is no longer hard-coded. + ## [0.4.0] — 2026-08-25 ### Changed diff --git a/README.md b/README.md index 5224dcd..59d20f1 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ am --ledger jebi.jsonl verify # my chain am --ledger seara.jsonl witness jebi.jsonl --name jebi # pin peer head am --ledger seara.jsonl verify-peer jebi.jsonl --name jebi # check peer am cross seara.jsonl jebi.jsonl --names seara jebi # mutual pin +am --ledger jebi.jsonl export-aat --out jebi.aat.jsonl # IETF AAT draft -11 ``` Demo (3-agent family, attack included): `PYTHONPATH=. python examples/demo_family.py` @@ -153,8 +154,47 @@ Demo (3-agent family, attack included): `PYTHONPATH=. python examples/demo_famil | `family_verify` | [Finding] | verify the whole family | | `verify_signatures` | [Finding] | verify the optional signed-identity layer | +| `to_aat` / `export_aat` / `verify_aat` | list / int / [Finding] | IETF AAT draft -11 export (see below) | + See the **[full Guide](docs/GUIDE.md)** for each function's signature and verdicts. +## Export to the IETF Agent Audit Trail format (draft) + +`am export-aat` writes the ledger as JSON Lines in the record format of +**[draft-sharif-agent-audit-trail-11](https://datatracker.ietf.org/doc/html/draft-sharif-agent-audit-trail-11)** +(2026-11-21). That is an individual Internet-Draft, not an IETF standard; it has changed +between revisions and may change again. The exporter targets **-11 only**, and writes the +revision into every record (`action_detail.export_profile.draft`). + +```bash +am --ledger jebi.jsonl export-aat --out jebi.aat.jsonl \ + --principal-type human --principal-id urn:user:operator --agent-version 1.0.0 +am verify-aat jebi.aat.jsonl # fields, enums and the §6.1 prev_hash chain +``` + +What you get: the §3.1 REQUIRED fields, `prev_hash = hex(SHA-256(JCS(previous record)))` +(RFC 8785), `null` on the genesis record, and the original action-mirror entry preserved +under `action_detail.action_mirror` so the export can be checked against the native ledger. +A ledger whose native chain fails `am verify` is **refused**, because re-chaining it would +produce a valid-looking AAT chain over tampered content. + +What it does not do: +- **No new evidence.** The export is derived from the native ledger; anyone holding that + ledger can regenerate it byte for byte. +- **Fields action-mirror does not record are filled with stated defaults**: `principal` + (the agent itself, self-asserted), `agent_version` `0.0.0`, `trust_level` `L0`, + `record_phase` `post_execution`, and `outcome` `success` unless `payload.exit` is an + integer. Here `success` means "recorded", not "verified to have succeeded". +- `record_id` / `session_id` are UUIDv4-formatted but derived from seals (so exports are + reproducible), not random. +- Native actions become `tool_call` (`tool_name` = the action string); witness entries + become `decision`. No other AAT action types are inferred. +- The optional Ed25519 `sig` signs the native seal, so it is **not** emitted as an AAT + `signature`. `verify-aat` does not check signatures, trust-level rules or §8 session + records, and cannot detect removal of the last record. +- The JCS implementation is tested against RFC 8785's number and key-ordering rules in + `tests/test_aat.py`, not against an external conformance suite. + --- ## Signed identity (optional) — making the *who* as hard as the *what* @@ -226,7 +266,7 @@ them up deliberately, not by default.) What's solid today: chain-sealed action records, content-hash attestation, position-pinned mutual witness with truncation/replacement detection — -21 tests, all passing, zero dependencies. +tested in CI on Linux and Windows, zero dependencies. --- diff --git a/README_KO.md b/README_KO.md index 9d52a8e..5134327 100644 --- a/README_KO.md +++ b/README_KO.md @@ -120,6 +120,7 @@ am --ledger jebi.jsonl verify # 내 체인 am --ledger seara.jsonl witness jebi.jsonl --name jebi # 동료 head 핀 am --ledger seara.jsonl verify-peer jebi.jsonl --name jebi # 동료 검사 am cross seara.jsonl jebi.jsonl --names seara jebi # 상호 핀 +am --ledger jebi.jsonl export-aat --out jebi.aat.jsonl # IETF AAT 초안 -11 ``` 데모 (3-에이전트 가족, 공격 포함): `PYTHONPATH=. python examples/demo_family.py` @@ -138,11 +139,44 @@ am cross seara.jsonl jebi.jsonl --names seara jebi # 상호 핀 | `family_round` | list | 전원이 전원을 핀 | | `family_verify` | [Finding] | 가족 전체 검증 | | `verify_signatures` | [Finding] | 선택적 서명-신원 레이어 검증 | +| `to_aat` / `export_aat` / `verify_aat` | list / int / [Finding] | IETF AAT 초안 -11 내보내기 (아래 참조) | 각 함수의 시그니처·판정은 **[완전 가이드](docs/GUIDE_KO.md)** 참조. --- +## IETF Agent Audit Trail 형식으로 내보내기 (초안) + +`am export-aat`는 원장을 +**[draft-sharif-agent-audit-trail-11](https://datatracker.ietf.org/doc/html/draft-sharif-agent-audit-trail-11)** +(2026-11-21)의 레코드 형식(JSON Lines)으로 씁니다. 이 문서는 개인 제출 인터넷 초안이고 +IETF 표준이 아닙니다. 판마다 바뀌어 왔고 앞으로도 바뀔 수 있습니다. 내보내기는 **-11판만** +기준으로 하며, 각 레코드의 `action_detail.export_profile.draft`에 판 번호를 기록합니다. + +```bash +am --ledger jebi.jsonl export-aat --out jebi.aat.jsonl \ + --principal-type human --principal-id urn:user:operator --agent-version 1.0.0 +am verify-aat jebi.aat.jsonl # 필드, 열거값, §6.1 prev_hash 체인 확인 +``` + +들어가는 것: §3.1 필수 필드, `prev_hash = hex(SHA-256(JCS(직전 레코드)))`(RFC 8785), +첫 레코드의 `null`, 그리고 `action_detail.action_mirror` 아래 원래 action-mirror 엔트리 +(원장과 대조용). 원장 체인이 `am verify`에서 실패하면 내보내기를 **거부**합니다. +변조된 내용 위에 멀쩡해 보이는 AAT 체인을 새로 만들게 되기 때문입니다. + +하지 않는 것: +- **새 증거를 만들지 않습니다.** 원장에서 파생된 것이라, 원장을 가진 사람은 똑같이 다시 만들 수 있습니다. +- action-mirror가 기록하지 않는 필드는 **명시된 기본값**으로 채웁니다: `principal`(에이전트 자신, 자기 주장), + `agent_version` `0.0.0`, `trust_level` `L0`, `record_phase` `post_execution`, `outcome`은 + `payload.exit`이 정수일 때만 계산하고 아니면 `success`. 여기서 `success`는 "기록됨"이지 "성공이 검증됨"이 아닙니다. +- `record_id`/`session_id`는 UUIDv4 형식이지만 봉인값에서 파생합니다(재현 가능). 무작위가 아닙니다. +- 원래 행동은 `tool_call`(`tool_name` = 행동 문자열), 증인 엔트리는 `decision`이 됩니다. 다른 AAT 유형은 추론하지 않습니다. +- 선택 기능인 Ed25519 `sig`는 원장 봉인값에 대한 서명이라 AAT `signature`로 **내보내지 않습니다**. + `verify-aat`는 서명, 신뢰 수준 규칙, §8 세션 레코드를 검사하지 않고, 마지막 레코드 삭제는 탐지하지 못합니다. +- JCS 구현은 `tests/test_aat.py`에서 RFC 8785의 숫자·키 정렬 규칙으로 시험했고, 외부 적합성 테스트 모음으로는 시험하지 않았습니다. + +--- + ## 서명 신원 (선택) — *누구*를 *무엇*만큼 단단하게 기본적으로 `agent` 필드는 **자기선언 라벨**입니다: 체인은 *엔트리*가 안 바뀌었음을 증명할 뿐, @@ -182,7 +216,7 @@ am verify-sig # 모든 서명 엔 무방비. 자주 핀하세요. 오늘 견고한 것: 체인봉인 행동 기록, 내용해시 입증, 위치고정 상호증인 + -절단/교체 탐지 — 21 테스트 통과, zero-dep. +절단/교체 탐지 — Linux·Windows CI에서 테스트, zero-dep. --- diff --git a/actmirror/__init__.py b/actmirror/__init__.py index 7a2646e..04c483b 100644 --- a/actmirror/__init__.py +++ b/actmirror/__init__.py @@ -4,10 +4,11 @@ witness_peer, verify_peer, cross_witness, family_round, family_verify, report, Finding, ) +from .aat import to_aat, export_aat, verify_aat __all__ = [ "record", "history", "attest", "verify_chain", "verify_signatures", "witness_peer", "verify_peer", "cross_witness", "family_round", "family_verify", - "report", "Finding", + "report", "Finding", "to_aat", "export_aat", "verify_aat", ] __version__ = "0.4.0" diff --git a/actmirror/aat.py b/actmirror/aat.py new file mode 100644 index 0000000..a80ec38 --- /dev/null +++ b/actmirror/aat.py @@ -0,0 +1,331 @@ +""" +Export an action-mirror ledger in the IETF *Agent Audit Trail* (AAT) record format. + +Target revision: draft-sharif-agent-audit-trail-11 (2026-11-21), an individual +Internet-Draft — NOT an IETF standard, NOT adopted by a working group, and still +changing between revisions. Field names, enums and the chaining rule below follow +-11 only. If a later revision changes them, this exporter must be updated; the +revision is written into every exported record's ``action_detail`` so a reader +can tell which one was used. + +What this does + * Converts each sealed action-mirror entry into one AAT JSON Lines record + (draft §10.1), with the §3.1 REQUIRED fields and the §6.1 chain: + prev_hash(N) = hex(SHA-256(JCS(record(N-1) with "batch" removed))) + and ``prev_hash: null`` on the genesis record. + * Preserves the original action-mirror entry (including ``seal``, ``prev_seal`` + and any ``sig``) under ``action_detail.action_mirror``, so the export can be + cross-checked against the native ledger. + * Refuses to export a ledger whose native chain does not verify: re-chaining a + tampered ledger into a fresh, internally valid AAT chain would launder the + tampering. + +What it does NOT do (read before relying on an export) + * It adds no new evidence. The AAT chain is derived from — and only as + trustworthy as — the native ledger. Anyone holding the native ledger can + regenerate the same export. + * Several AAT REQUIRED fields have no counterpart in action-mirror and are + filled with caller-supplied values or stated defaults: + principal default: the agent itself, principal_type "agent", + authority_ref null (self-asserted, not an authorization) + agent_version default "0.0.0" (unknown) + trust_level default "L0" + outcome "success"/"failure" only when payload.exit is an integer, + otherwise ``default_outcome`` (default "success", which here + means "recorded", not "verified to have succeeded") + record_phase "post_execution" (action-mirror records after the fact) + * ``record_id`` and ``session_id`` are UUIDv4-*formatted* values derived + deterministically from native seals (so re-exports are identical). They are + not random as §3.1's UUIDv4 implies. + * Every native action becomes ``action_type: "tool_call"`` (tool_name = the + native ``action`` string); ``peer_witness`` entries become ``"decision"``. + Native free-form action names are not mapped onto the other AAT types. + * action-mirror's Ed25519 ``sig`` signs the native seal, not the AAT record, so + it is NOT emitted as an AAT ``signature`` (which §6.2 defines as ES256 by + default over the AAT record). It stays available in the preserved entry. + * Timestamps keep the native one-second precision (§3.3 recommends ms). + * JCS (RFC 8785) is implemented here for the JSON values action-mirror + produces; it has not been tested against an external JCS conformance suite. +""" +from __future__ import annotations + +import hashlib +import json +import math +import re +import urllib.parse +from datetime import datetime +from decimal import Decimal + +from .am import Finding, _load_entries, verify_chain + +DRAFT = "draft-sharif-agent-audit-trail-11" +DRAFT_DATE = "2026-11-21" + +ACTION_TYPES = ("tool_call", "tool_response", "decision", "delegation", + "escalation", "error", "lifecycle") +OUTCOMES = ("success", "failure", "timeout", "denied", "escalated") +TRUST_LEVELS = ("L0", "L1", "L2", "L3", "L4") +PRINCIPAL_TYPES = ("human", "organization", "service", "agent") +RECORD_PHASES = ("pre_execution", "post_execution", "concurrent") +REQUIRED = ("record_id", "timestamp", "agent_id", "principal", "agent_version", + "session_id", "action_type", "action_detail", "outcome", "trust_level", + "parent_record_id", "prev_hash", "record_phase") + +_UUID4 = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$") +_HEX64 = re.compile(r"^[0-9a-f]{64}$") +_SEMVER = re.compile(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)" + r"(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$") +_RFC3339 = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$") + + +# ───────────────────────────────────────────────────────────── +# RFC 8785 JSON Canonicalization Scheme +# ───────────────────────────────────────────────────────────── +def _jcs_number(x) -> str: + if isinstance(x, bool): + return "true" if x else "false" + if isinstance(x, int): + if abs(x) > 2 ** 53: + raise ValueError(f"integer {x} is outside the IEEE-754 safe range (RFC 8785 §3.2.2.3)") + return str(x) + if not math.isfinite(x): + raise ValueError("NaN/Infinity are not valid JSON (RFC 8785 §3.2.2.2)") + if x == 0: + return "0" + # ECMAScript Number::toString on the shortest round-trip digits (Python repr). + sign = "-" if x < 0 else "" + t = Decimal(repr(abs(x))).as_tuple() + raw = "".join(map(str, t.digits)) + n = len(raw) + t.exponent # value = 0. × 10^n + digits = raw.rstrip("0") or "0" + k = len(digits) + if k <= n <= 21: + s = digits + "0" * (n - k) + elif 0 < n <= 21: + s = digits[:n] + "." + digits[n:] + elif -6 < n <= 0: + s = "0." + "0" * (-n) + digits + else: + e = n - 1 + s = digits[0] + ("." + digits[1:] if k > 1 else "") + "e" + ("+" if e >= 0 else "-") + str(abs(e)) + return sign + s + + +def _jcs(v) -> str: + if v is None: + return "null" + if isinstance(v, (bool, int, float)): + return _jcs_number(v) + if isinstance(v, str): + return json.dumps(v, ensure_ascii=False) + if isinstance(v, (list, tuple)): + return "[" + ",".join(_jcs(i) for i in v) + "]" + if isinstance(v, dict): + for key in v: + if not isinstance(key, str): + raise TypeError("JSON object keys must be strings") + keys = sorted(v, key=lambda s: s.encode("utf-16-be")) # UTF-16 code-unit order + return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + _jcs(v[k]) for k in keys) + "}" + raise TypeError(f"not JSON-serialisable: {type(v).__name__}") + + +def jcs(value) -> bytes: + """RFC 8785 canonical UTF-8 bytes of a JSON value.""" + return _jcs(value).encode("utf-8") + + +def record_hash(rec: dict) -> str: + """§6.1: hex(SHA-256(JCS(record with any "batch" object removed))).""" + return hashlib.sha256(jcs({k: v for k, v in rec.items() if k != "batch"})).hexdigest() + + +# ───────────────────────────────────────────────────────────── +# Export +# ───────────────────────────────────────────────────────────── +def _uuid4_from(label: str, seed: str) -> str: + b = bytearray(hashlib.sha256(f"{label}:{seed}".encode()).digest()[:16]) + b[6] = (b[6] & 0x0F) | 0x40 # version 4 + b[8] = (b[8] & 0x3F) | 0x80 # RFC 4122 variant + h = b.hex() + return f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:]}" + + +def _agent_uri(name: str) -> str: + return "urn:action-mirror:agent:" + urllib.parse.quote(str(name), safe="") + + +def to_aat(ledger_path: str, *, session_id: str | None = None, + agent_version: str = "0.0.0", trust_level: str = "L0", + principal: dict | None = None, default_outcome: str = "success") -> list[dict]: + """Convert a verified action-mirror ledger into AAT records (draft -11). + + Raises ValueError if the native chain does not verify, or an argument is not an + allowed -11 value. See the module docstring for every default and its meaning. + """ + chain = verify_chain(ledger_path) + if any(f.level == "FAIL" for f in chain): + raise ValueError("native chain does not verify — refusing to export " + f"(re-chaining would hide tampering): {chain[0].msg}") + if trust_level not in TRUST_LEVELS: + raise ValueError(f"trust_level must be one of {TRUST_LEVELS}") + if default_outcome not in OUTCOMES: + raise ValueError(f"default_outcome must be one of {OUTCOMES}") + if not _SEMVER.match(agent_version): + raise ValueError("agent_version must be SemVer (e.g. 1.2.3)") + if principal is not None: + if principal.get("principal_type") not in PRINCIPAL_TYPES: + raise ValueError(f"principal_type must be one of {PRINCIPAL_TYPES}") + if not principal.get("principal_id"): + raise ValueError("principal_id is required") + + entries = _load_entries(ledger_path) + if not entries: + return [] + if session_id is None: + session_id = _uuid4_from("session", str(entries[0].get("seal"))) + elif not _UUID4.match(session_id): + raise ValueError("session_id must be a lowercase UUIDv4") + + out: list[dict] = [] + prev: dict | None = None + for e in entries: + agent_id = _agent_uri(e.get("agent") or e.get("_type", "unknown")) + if e.get("_type") == "peer_witness": + action_type = "decision" + detail = {"decision_type": "action_mirror.peer_witness", + "peer": e.get("peer"), "peer_entries": e.get("peer_entries"), + "peer_head_seal": e.get("peer_head_seal")} + else: + action_type = "tool_call" + detail = {"tool_name": str(e.get("action")), + "parameters_hash": hashlib.sha256(jcs(e.get("payload", {}))).hexdigest()} + if "target" in e: + detail["target"] = e["target"] + detail["export_profile"] = {"draft": DRAFT, "draft_date": DRAFT_DATE, + "exporter": "action-mirror"} + detail["action_mirror"] = e # native entry, incl. seal / prev_seal / sig + + payload = e.get("payload") + exit_code = payload.get("exit") if isinstance(payload, dict) else None + if isinstance(exit_code, int) and not isinstance(exit_code, bool): + outcome = "success" if exit_code == 0 else "failure" + else: + outcome = default_outcome + + rec = { + "record_id": _uuid4_from("record", str(e.get("seal"))), + "timestamp": e.get("ts"), + "agent_id": agent_id, + "principal": dict(principal) if principal is not None else + {"principal_type": "agent", "principal_id": agent_id, + "authority_ref": None}, + "agent_version": agent_version, + "session_id": session_id, + "action_type": action_type, + "action_detail": detail, + "outcome": outcome, + "trust_level": trust_level, + "parent_record_id": prev["record_id"] if prev else None, + "prev_hash": record_hash(prev) if prev else None, + "record_phase": "post_execution", + } + rec["principal"].setdefault("authority_ref", None) + if "content_hash" in e and _HEX64.match(str(e["content_hash"])): + rec["output_hash"] = e["content_hash"] + out.append(rec) + prev = rec + return out + + +def export_aat(ledger_path: str, out_path: str, **kw) -> int: + """Write the AAT export as JSON Lines (UTF-8, no BOM, LF; draft §10.1). + Returns the number of records written.""" + recs = to_aat(ledger_path, **kw) + with open(out_path, "w", encoding="utf-8", newline="\n") as f: + for r in recs: + f.write(json.dumps(r, ensure_ascii=False) + "\n") + return len(recs) + + +def _instant(ts: str) -> datetime: + """RFC 3339 → aware datetime (fraction cut to µs; Python 3.10 has no 'Z').""" + m = re.match(r"^(.*T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$", ts) + frac = (m.group(2) or "")[:6].ljust(6, "0") + tz = "+00:00" if m.group(3) == "Z" else m.group(3) + return datetime.fromisoformat(f"{m.group(1)}.{frac}{tz}") + + +# ───────────────────────────────────────────────────────────── +# Structural verification of an AAT file (subset of -11) +# ───────────────────────────────────────────────────────────── +def verify_aat(path: str) -> list[Finding]: + """Check an AAT JSON Lines file against the parts of -11 this module implements: + REQUIRED fields and enums (§3.1), genesis nulls, §6.1 prev_hash chain, + parent_record_id linkage, one session_id, non-decreasing timestamps, unique + record_id. Signatures, trust-level rules, batching and §8 session records are + NOT checked. Passing means "structurally consistent", not "true".""" + recs: list[dict] = [] + with open(path, encoding="utf-8") as f: + for i, line in enumerate(f, 1): + if not line.strip(): + continue + try: + recs.append(json.loads(line)) + except json.JSONDecodeError: + return [Finding("📜 aat", "FAIL", f"Line {i} is not valid JSON.")] + if not recs: + return [Finding("📜 aat", "WARN", "No records.")] + seen: set[str] = set() + for i, r in enumerate(recs, 1): + missing = [k for k in REQUIRED if k not in r] + if missing: + return [Finding("📜 aat", "FAIL", f"Record {i}: missing REQUIRED {missing}.")] + bad = [] + if not _UUID4.match(str(r["record_id"])): + bad.append("record_id") + if not _UUID4.match(str(r["session_id"])): + bad.append("session_id") + if not isinstance(r["timestamp"], str) or not _RFC3339.match(r["timestamp"]): + bad.append("timestamp") + if r["action_type"] not in ACTION_TYPES: + bad.append("action_type") + if r["outcome"] not in OUTCOMES: + bad.append("outcome") + if r["trust_level"] not in TRUST_LEVELS: + bad.append("trust_level") + if r["record_phase"] not in RECORD_PHASES: + bad.append("record_phase") + if not isinstance(r["action_detail"], dict): + bad.append("action_detail") + p = r["principal"] + if not isinstance(p, dict) or p.get("principal_type") not in PRINCIPAL_TYPES \ + or not p.get("principal_id") or "authority_ref" not in p: + bad.append("principal") + if not isinstance(r["agent_version"], str) or not _SEMVER.match(r["agent_version"]): + bad.append("agent_version") + if bad: + return [Finding("📜 aat", "FAIL", f"Record {i}: invalid {bad}.")] + if r["record_id"] in seen: + return [Finding("📜 aat", "FAIL", f"Record {i}: duplicate record_id.")] + seen.add(r["record_id"]) + if i == 1: + if r["prev_hash"] is not None or r["parent_record_id"] is not None: + return [Finding("📜 aat", "FAIL", + "Record 1: genesis must have prev_hash and parent_record_id null.")] + continue + prev = recs[i - 2] + if r["prev_hash"] != record_hash(prev): + return [Finding("📜 aat", "FAIL", + f"Record {i}: prev_hash broken — record {i-1} modified, " + "or a record was inserted/deleted/reordered.")] + if r["parent_record_id"] != prev["record_id"]: + return [Finding("📜 aat", "FAIL", f"Record {i}: parent_record_id does not link.")] + if r["session_id"] != recs[0]["session_id"]: + return [Finding("📜 aat", "FAIL", f"Record {i}: session_id changes mid-file.")] + if _instant(r["timestamp"]) < _instant(prev["timestamp"]): + return [Finding("📜 aat", "FAIL", f"Record {i}: timestamp decreases.")] + return [Finding("📜 aat", "OK", + f"{len(recs)} records structurally consistent with {DRAFT} " + "(fields, enums, prev_hash chain). Signatures not checked; " + "the last record can be truncated without detection.")] diff --git a/actmirror/am.py b/actmirror/am.py index 967894a..15aea7e 100644 --- a/actmirror/am.py +++ b/actmirror/am.py @@ -531,7 +531,52 @@ def _cli() -> int: cr.add_argument("ledger_b") cr.add_argument("--names", nargs=2, required=True, metavar=("NAME_A", "NAME_B")) + ex = sub.add_parser("export-aat", + help="Export my ledger as IETF Agent Audit Trail JSONL " + "(draft-sharif-agent-audit-trail-11; an unratified draft)") + ex.add_argument("--out", required=True, help="Output .jsonl path") + ex.add_argument("--session-id", default=None, + help="UUIDv4 (default: derived from the genesis seal)") + ex.add_argument("--agent-version", default="0.0.0", + help="SemVer of the recorded agent (default 0.0.0 = unknown)") + ex.add_argument("--trust-level", default="L0", choices=["L0", "L1", "L2", "L3", "L4"]) + ex.add_argument("--principal-type", default=None, + choices=["human", "organization", "service", "agent"], + help="Who the agent acts for (default: the agent itself, self-asserted)") + ex.add_argument("--principal-id", default=None, help="Principal URI") + ex.add_argument("--authority-ref", default=None, help="Authorization evidence URI") + ex.add_argument("--default-outcome", default="success", + choices=["success", "failure", "timeout", "denied", "escalated"], + help="Outcome when payload.exit is absent (default success = 'recorded')") + + va = sub.add_parser("verify-aat", help="Structurally check an AAT JSONL file (draft -11 subset)") + va.add_argument("aat_file") + args = p.parse_args() + if args.cmd == "export-aat": + from . import aat + principal = None + if args.principal_type or args.principal_id or args.authority_ref: + if not (args.principal_type and args.principal_id): + print("🔴 --principal-type and --principal-id must be given together", file=sys.stderr) + return 2 + principal = {"principal_type": args.principal_type, + "principal_id": args.principal_id, + "authority_ref": args.authority_ref} + try: + n = aat.export_aat(args.ledger, args.out, session_id=args.session_id, + agent_version=args.agent_version, trust_level=args.trust_level, + principal=principal, default_outcome=args.default_outcome) + except ValueError as err: + print(f"🔴 export refused: {err}", file=sys.stderr) + return 1 + print(f"📜 Exported {n} records → {args.out} (format: {aat.DRAFT}, " + "derived from the native ledger — adds no new evidence)") + return 0 + if args.cmd == "verify-aat": + from . import aat + return 1 if report(f"AAT {args.aat_file}", + aat.verify_aat(args.aat_file)) == "FAIL" else 0 if args.cmd == "keygen": from . import identity pub = identity.generate(args.out) diff --git a/tests/test_aat.py b/tests/test_aat.py new file mode 100644 index 0000000..9a5a82f --- /dev/null +++ b/tests/test_aat.py @@ -0,0 +1,193 @@ +"""IETF Agent Audit Trail export (draft-sharif-agent-audit-trail-11).""" +from __future__ import annotations + +import hashlib +import json +import subprocess +import sys + +import pytest + +from actmirror import am, aat +from test_cli_exit_codes import _ENV + + +def _ledger(tmp_path): + l = str(tmp_path / "l.jsonl") + am.record(l, agent="jebi", action="eval_run", target="exp1.txt", + content=b"result", payload={"script": "eval.py", "exit": 0}) + am.record(l, agent="jebi", action="file_write", target="x.py", payload={"exit": 2}) + am.record(l, agent="seara", action="msg") + return l + + +def _read(path): + with open(path, encoding="utf-8") as f: + return [json.loads(x) for x in f if x.strip()] + + +# ─── RFC 8785 ──────────────────────────────────────────────── + +@pytest.mark.parametrize("x,want", [ + (1.0, "1"), (0.5, "0.5"), (1e21, "1e+21"), (1e20, "100000000000000000000"), + (1e-7, "1e-7"), (1e-6, "0.000001"), (-2.5e-10, "-2.5e-10"), (5e-324, "5e-324"), + (1.7976931348623157e308, "1.7976931348623157e+308"), (333333333.3333333, "333333333.3333333"), + (0.0, "0"), (-0.0, "0"), +]) +def test_jcs_numbers_follow_ecmascript(x, want): + assert aat.jcs(x).decode() == want + + +def test_jcs_sorts_keys_by_utf16_code_units(): + # RFC 8785 §3.2.3: U+1F600 (surrogate D83D) sorts before U+FB33. + out = aat.jcs({"דּ": 1, "\U0001F600": 2, "b": 3, "a": 4}).decode() + assert out == '{"a":4,"b":3,"\U0001F600":2,"דּ":1}' + + +def test_jcs_rejects_nan_and_unsafe_ints(): + with pytest.raises(ValueError): + aat.jcs(float("nan")) + with pytest.raises(ValueError): + aat.jcs(2 ** 60) + + +# ─── export ────────────────────────────────────────────────── + +def test_export_has_required_fields_and_chain(tmp_path): + recs = aat.to_aat(_ledger(tmp_path)) + assert len(recs) == 3 + for r in recs: + for k in aat.REQUIRED: + assert k in r + assert r["action_detail"]["export_profile"]["draft"] == "draft-sharif-agent-audit-trail-11" + assert recs[0]["prev_hash"] is None and recs[0]["parent_record_id"] is None + for prev, cur in zip(recs, recs[1:]): + expect = hashlib.sha256(aat.jcs(prev)).hexdigest() + assert cur["prev_hash"] == expect + assert cur["parent_record_id"] == prev["record_id"] + assert len({r["session_id"] for r in recs}) == 1 + + +def test_export_maps_outcome_and_hashes(tmp_path): + recs = aat.to_aat(_ledger(tmp_path)) + assert [r["outcome"] for r in recs] == ["success", "failure", "success"] + assert recs[0]["output_hash"] == hashlib.sha256(b"result").hexdigest() + assert recs[0]["action_detail"]["tool_name"] == "eval_run" + assert recs[0]["agent_id"] == "urn:action-mirror:agent:jebi" + # native entry preserved for cross-checking + assert recs[0]["action_detail"]["action_mirror"]["seal"] == am._load_entries( + str(tmp_path / "l.jsonl"))[0]["seal"] + + +def test_export_is_deterministic(tmp_path): + l = _ledger(tmp_path) + assert aat.to_aat(l) == aat.to_aat(l) + + +def test_peer_witness_becomes_decision(tmp_path): + a, b = str(tmp_path / "a.jsonl"), str(tmp_path / "b.jsonl") + am.record(b, agent="b", action="x") + am.witness_peer(a, b, peer_name="b") + r = aat.to_aat(a)[0] + assert r["action_type"] == "decision" + assert r["action_detail"]["decision_type"] == "action_mirror.peer_witness" + + +def test_export_refuses_tampered_native_ledger(tmp_path): + l = _ledger(tmp_path) + lines = open(l, encoding="utf-8").read().splitlines() + e = json.loads(lines[1]); e["target"] = "forged.py"; lines[1] = json.dumps(e) + open(l, "w", encoding="utf-8").write("\n".join(lines) + "\n") + with pytest.raises(ValueError, match="refusing to export"): + aat.to_aat(l) + + +def test_export_validates_arguments(tmp_path): + l = _ledger(tmp_path) + with pytest.raises(ValueError): + aat.to_aat(l, trust_level="L9") + with pytest.raises(ValueError): + aat.to_aat(l, agent_version="v1") + with pytest.raises(ValueError): + aat.to_aat(l, session_id="not-a-uuid") + with pytest.raises(ValueError): + aat.to_aat(l, principal={"principal_type": "robot", "principal_id": "urn:x"}) + + +def test_empty_ledger_exports_nothing(tmp_path): + assert aat.to_aat(str(tmp_path / "none.jsonl")) == [] + + +# ─── verify ────────────────────────────────────────────────── + +def test_verify_accepts_export(tmp_path): + out = str(tmp_path / "aat.jsonl") + assert aat.export_aat(_ledger(tmp_path), out) == 3 + assert aat.verify_aat(out)[0].level == "OK" + + +def test_verify_detects_modified_record(tmp_path): + out = str(tmp_path / "aat.jsonl") + aat.export_aat(_ledger(tmp_path), out) + recs = _read(out) + recs[0]["outcome"] = "failure" + with open(out, "w", encoding="utf-8") as f: + f.writelines(json.dumps(r) + "\n" for r in recs) + fs = aat.verify_aat(out) + assert fs[0].level == "FAIL" and "prev_hash" in fs[0].msg + + +def test_verify_detects_deletion_and_reorder(tmp_path): + out = str(tmp_path / "aat.jsonl") + aat.export_aat(_ledger(tmp_path), out) + recs = _read(out) + for mutated in (recs[:1] + recs[2:], [recs[0], recs[2], recs[1]]): + with open(out, "w", encoding="utf-8") as f: + f.writelines(json.dumps(r) + "\n" for r in mutated) + assert aat.verify_aat(out)[0].level == "FAIL" + + +def test_verify_rejects_bad_enum(tmp_path): + out = str(tmp_path / "aat.jsonl") + aat.export_aat(_ledger(tmp_path), out) + recs = _read(out) + recs[0]["action_type"] = "file_write" + with open(out, "w", encoding="utf-8") as f: + f.writelines(json.dumps(r) + "\n" for r in recs) + assert aat.verify_aat(out)[0].level == "FAIL" + + +def test_verify_compares_timestamps_as_instants(tmp_path): + out = str(tmp_path / "aat.jsonl") + aat.export_aat(_ledger(tmp_path), out) + recs = _read(out)[:1] + with open(out, "w", encoding="utf-8") as f: + f.writelines(json.dumps(r) + "\n" for r in recs) + assert aat.verify_aat(out)[0].level == "OK" + assert aat._instant("2026-01-01T00:00:00.5Z") > aat._instant("2026-01-01T00:00:00Z") + assert aat._instant("2026-01-01T09:00:00+09:00") == aat._instant("2026-01-01T00:00:00Z") + + +# ─── CLI ───────────────────────────────────────────────────── + +def _cli(*args): + return subprocess.run([sys.executable, "-m", "actmirror.am", *args], + capture_output=True, text=True, env=_ENV) + + +def test_cli_export_and_verify(tmp_path): + l, out = _ledger(tmp_path), str(tmp_path / "aat.jsonl") + r = _cli("--ledger", l, "export-aat", "--out", out, + "--principal-type", "human", "--principal-id", "urn:user:operator") + assert r.returncode == 0, r.stderr + assert _read(out)[0]["principal"] == {"principal_type": "human", + "principal_id": "urn:user:operator", + "authority_ref": None} + assert _cli("verify-aat", out).returncode == 0 + + +def test_cli_export_refusal_exits_nonzero(tmp_path): + l = _ledger(tmp_path) + with open(l, "a", encoding="utf-8") as f: + f.write("{not json\n") + assert _cli("--ledger", l, "export-aat", "--out", str(tmp_path / "o.jsonl")).returncode == 1 From 0a0a3c7551fc7314ede0b9684c1feb0432774711 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:14:30 +0000 Subject: [PATCH 2/2] docs: match provenance-mirror's row to the org profile wording The table said provenance-mirror proves origin; the org profile and its own verdicts say byte markers are unauthenticated hints (PROVENANCE-UNVERIFIED). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Aq8kkjQte1m3idCZFj8t8E --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 59d20f1..a2b73ae 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Third member of the mirror family — same DNA, new domain: | Tool | Audits | Question | |---|---|---| | 🪞 [measure-mirror](https://github.com/mirror-stack/measure-mirror) | AI evaluation claims | Is the **claim** honest? | -| 🔎 [provenance-mirror](https://github.com/mirror-stack/provenance-mirror) | Content authenticity | Is the **origin** proven? | +| 🔎 [provenance-mirror](https://github.com/mirror-stack/provenance-mirror) | Provenance signals | What origin hints are present? (not authenticated) | | 🪪 **action-mirror** (you are here) | Agent behaviour | **Who did what, provably?** | | 👁 [mirror-witness](https://github.com/mirror-stack/mirror-witness) | Cross-operator witness board | Who else **witnessed** it? |