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..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? | @@ -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