cendor-acttrace 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,534 @@
1
+ """cendor.acttrace — a tamper-evident, auto-populated audit log for AI decisions.
2
+
3
+ Construct an :class:`AuditLog` and it **subscribes** to ``cendor.core``'s event stream: every
4
+ instrumented model/tool call — and the context decisions ``contextkit`` and cost ``tokenguard``
5
+ ride on that same stream — becomes an audit entry with no per-call wiring. You add only the
6
+ explicit human-facing events (``decision``, ``human_oversight``).
7
+
8
+ Integrity comes from a **hash chain**, not a server: ``entry.hash = sha256(prev_hash +
9
+ canonical(entry))``, so editing any past entry breaks every entry after it. ``acttrace verify
10
+ file.jsonl`` re-walks the chain offline.
11
+
12
+ > This produces **evidence to support** compliance (e.g. EU AI Act record-keeping / human
13
+ > oversight). It is **not** legal advice and not a compliance guarantee. Control mappings are a
14
+ > starting template for your compliance team to adjust.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import hmac
21
+ import json
22
+ import re
23
+ import uuid
24
+ from collections import Counter
25
+ from collections.abc import Callable, Iterator
26
+ from contextlib import contextmanager
27
+ from contextvars import ContextVar
28
+ from dataclasses import dataclass
29
+ from datetime import UTC, datetime
30
+ from pathlib import Path
31
+ from typing import Any, Literal
32
+
33
+ from cendor.core import bus
34
+ from cendor.core.types import LLMCall, ToolCall
35
+
36
+ __all__ = ["AuditLog", "AuditEntry", "verify", "frameworks", "default_redactor", "GENESIS"]
37
+
38
+ GENESIS = "0" * 64
39
+
40
+ #: Recommended vocabularies for a policy flag (normalized to lowercase; other strings are allowed).
41
+ FlagAction = Literal["flagged", "redacted", "blocked"]
42
+ FlagSeverity = Literal["info", "warning", "critical"]
43
+
44
+ _active_decision: ContextVar[str | None] = ContextVar("cendor_acttrace_decision", default=None)
45
+
46
+ # Starting-template control mappings (NOT legal advice; adjust for your system). docs §5, §7.
47
+ # event type -> framework control IDs. Used by export(framework=...) to annotate the evidence pack.
48
+ # Control IDs reference the public framework texts (EU AI Act Reg. 2024/1689; NIST AI RMF 1.0;
49
+ # ISO/IEC 42001:2023 Annex A; GDPR Reg. 2016/679) — they map an event to the controls it provides
50
+ # *evidence for*, never a claim of compliance. Your compliance team owns the final mapping.
51
+ _CONTROLS: dict[str, dict[str, list[str]]] = {
52
+ "eu_ai_act": {
53
+ "audit_open": ["Art.12 record-keeping", "Art.19 automatically generated logs"],
54
+ "decision": ["Art.12 record-keeping", "Art.13 transparency"],
55
+ "decision_record": ["Art.12 record-keeping", "Art.13 transparency"],
56
+ "decision_end": ["Art.12 record-keeping"],
57
+ "llm_call": [
58
+ "Art.12 logging",
59
+ "Art.19 automatically generated logs",
60
+ "Art.72 post-market monitoring",
61
+ ],
62
+ "tool_call": ["Art.12 logging", "Art.19 automatically generated logs"],
63
+ "context_assembly": ["Art.12 logging", "Art.13 transparency"],
64
+ "human_oversight": ["Art.14 human oversight", "Art.26(5) deployer oversight"],
65
+ "policy_flag": ["Art.10 data governance", "Art.12 record-keeping"],
66
+ },
67
+ "nist_rmf": {
68
+ "audit_open": ["GOVERN-1.1"],
69
+ "decision": ["MAP-1.1", "MEASURE-2.1"],
70
+ "decision_record": ["MEASURE-2.1"],
71
+ "decision_end": ["MEASURE-2.1"],
72
+ "llm_call": ["MEASURE-2.1"],
73
+ "tool_call": ["MEASURE-2.1"],
74
+ "context_assembly": ["MEASURE-2.1"],
75
+ "human_oversight": ["MANAGE-2.1"],
76
+ "policy_flag": ["MANAGE-2.1", "MEASURE-2.1"],
77
+ },
78
+ "iso_42001": { # ISO/IEC 42001:2023 Annex A controls + management clauses
79
+ "audit_open": ["A.6.2.8 event logs"],
80
+ "decision": ["A.6.2.8 event logs", "A.5.2 AI system impact assessment"],
81
+ "decision_record": ["A.6.2.8 event logs"],
82
+ "decision_end": ["A.6.2.8 event logs"],
83
+ "llm_call": [
84
+ "A.6.2.8 event logs",
85
+ "A.6.2.6 operation & monitoring",
86
+ "Cl.9.1 monitoring & measurement",
87
+ ],
88
+ "tool_call": ["A.6.2.8 event logs", "A.6.2.6 operation & monitoring"],
89
+ "context_assembly": ["A.6.2.8 event logs", "A.6.2.6 operation & monitoring"],
90
+ "human_oversight": ["A.9.2 responsible use", "A.9.4 intended use"],
91
+ "policy_flag": ["A.7 data for AI systems", "A.6.2.8 event logs", "A.9.2 responsible use"],
92
+ },
93
+ "gdpr": { # automated decision-making + records of processing (Reg. 2016/679)
94
+ "audit_open": ["Art.30 records of processing", "Art.5(2) accountability"],
95
+ "decision": ["Art.22 automated decision-making", "Art.5(2) accountability"],
96
+ "decision_record": ["Art.22 automated decision-making"],
97
+ "decision_end": ["Art.30 records of processing"],
98
+ "llm_call": ["Art.30 records of processing"],
99
+ "tool_call": ["Art.30 records of processing"],
100
+ "context_assembly": ["Art.30 records of processing"],
101
+ "human_oversight": ["Art.22(3) right to human intervention"],
102
+ "policy_flag": [
103
+ "Art.9 special-category data",
104
+ "Art.5(1)(c) data minimisation",
105
+ "Art.30 records of processing",
106
+ ],
107
+ },
108
+ }
109
+
110
+
111
+ def frameworks() -> list[str]:
112
+ """Frameworks with a bundled (starting-template) control mapping for :meth:`AuditLog.export`."""
113
+ return sorted(_CONTROLS)
114
+
115
+
116
+ @dataclass
117
+ class AuditEntry:
118
+ """One link in the hash chain. docs/acttrace.md §5."""
119
+
120
+ seq: int
121
+ ts: str
122
+ type: str # decision | llm_call | tool_call | human_oversight | context_assembly | ...
123
+ payload: dict
124
+ prev_hash: str
125
+ hash: str
126
+ sig: str = "" # HMAC-SHA256 of `hash` under the signing key, if the log is signed
127
+
128
+
129
+ # Targeted PII/secret patterns (GDPR), each with a category label. Deliberately narrow — does NOT
130
+ # touch ids/hashes/uuids. The category labels are what an auto-emitted policy_flag records.
131
+ _REDACTION_CATEGORIES: list[tuple[str, re.Pattern[str]]] = [
132
+ ("email", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")),
133
+ ("api_key", re.compile(r"\bsk-[A-Za-z0-9]{8,}\b")), # openai-style keys
134
+ ("bearer_token", re.compile(r"\b[Bb]earer\s+[A-Za-z0-9._-]+\b")),
135
+ ]
136
+ _REDACTIONS = [pat for _, pat in _REDACTION_CATEGORIES]
137
+
138
+
139
+ def _redact(obj: Any) -> Any:
140
+ if isinstance(obj, str):
141
+ out = obj
142
+ for pat in _REDACTIONS:
143
+ out = pat.sub("<redacted>", out)
144
+ return out
145
+ if isinstance(obj, dict):
146
+ return {k: _redact(v) for k, v in obj.items()}
147
+ if isinstance(obj, list):
148
+ return [_redact(v) for v in obj]
149
+ return obj
150
+
151
+
152
+ def _scan_redactions(obj: Any) -> set[str]:
153
+ """Categories of sensitive data (``email`` / ``api_key`` / ``bearer_token``) present anywhere in
154
+ ``obj`` — what the built-in redactor would scrub. Drives the auto policy_flag on redaction."""
155
+ found: set[str] = set()
156
+
157
+ def walk(o: Any) -> None:
158
+ if isinstance(o, str):
159
+ for cat, pat in _REDACTION_CATEGORIES:
160
+ if pat.search(o):
161
+ found.add(cat)
162
+ elif isinstance(o, dict):
163
+ for v in o.values():
164
+ walk(v)
165
+ elif isinstance(o, list):
166
+ for v in o:
167
+ walk(v)
168
+
169
+ walk(obj)
170
+ return found
171
+
172
+
173
+ #: Entry types that carry caller-supplied content (where PII actually lands), so a redaction in one
174
+ #: of them is worth a follow-up flag. Excludes structural entries (audit_open / decision_end), the
175
+ #: flag itself (no recursion), and human_oversight (a reviewer's identity is legitimate audit data,
176
+ #: not PII to flag). Note: llm_call stores only metadata — messages are never recorded — so PII most
177
+ #: often surfaces in a decision's input or a tool_call's arguments.
178
+ _AUTO_REDACT_TYPES = frozenset(
179
+ {"decision", "decision_record", "llm_call", "tool_call", "context_assembly"}
180
+ )
181
+
182
+
183
+ #: The built-in redactor (emails / ``sk-`` keys / bearer tokens). Exposed so a custom ``redactor``
184
+ #: can compose it: ``AuditLog(redactor=lambda o: my_scrub(default_redactor(o)))``.
185
+ default_redactor = _redact
186
+
187
+
188
+ def _jsonable(obj: Any) -> Any:
189
+ if obj is None or isinstance(obj, (bool, int, float, str)):
190
+ return obj
191
+ if isinstance(obj, datetime):
192
+ return obj.isoformat()
193
+ if isinstance(obj, dict):
194
+ return {str(k): _jsonable(v) for k, v in obj.items()}
195
+ if isinstance(obj, (list, tuple)):
196
+ return [_jsonable(v) for v in obj]
197
+ if hasattr(obj, "amount") and hasattr(obj, "currency"): # Money
198
+ return f"{obj.amount} {obj.currency}"
199
+ if hasattr(obj, "__dict__"):
200
+ return _jsonable(vars(obj))
201
+ return str(obj)
202
+
203
+
204
+ def _canonical(payload: dict) -> str:
205
+ return json.dumps(_jsonable(payload), sort_keys=True, ensure_ascii=False, separators=(",", ":"))
206
+
207
+
208
+ def _chain_hash(prev_hash: str, seq: int, ts: str, etype: str, payload: dict) -> str:
209
+ body = _canonical({"seq": seq, "ts": ts, "type": etype, "payload": payload})
210
+ return hashlib.sha256((prev_hash + body).encode("utf-8")).hexdigest()
211
+
212
+
213
+ class AuditLog:
214
+ """A hash-chained, append-only, auto-populating audit log. docs/acttrace.md §3, §5."""
215
+
216
+ def __init__(
217
+ self,
218
+ system: str,
219
+ risk_tier: str = "limited",
220
+ path: str | None = None,
221
+ signing_key: str | bytes | None = None,
222
+ redact: bool = True,
223
+ redactor: Callable[[Any], Any] | None = None,
224
+ flag_on_redact: bool = True,
225
+ ) -> None:
226
+ """``redactor`` overrides the built-in scrubber: a ``payload -> payload`` callable applied
227
+ before each entry is chained/written (compose :data:`default_redactor` to extend it). Runs
228
+ only when ``redact=True``.
229
+
230
+ ``flag_on_redact`` (default ``True``): when the built-in redactor scrubs sensitive data from
231
+ an auto-captured entry, also append a ``policy_flag`` recording *what category* was redacted
232
+ — so "we removed PII" is itself in the tamper-evident chain, not silent. Only fires with the
233
+ built-in redactor (a custom ``redactor`` owns its own flagging)."""
234
+ self.system = system
235
+ self.risk_tier = risk_tier
236
+ self.path = Path(path) if path else None
237
+ self._signing_key = signing_key.encode() if isinstance(signing_key, str) else signing_key
238
+ self._redact = redact # scrub emails/keys/tokens from payloads (GDPR); on by default
239
+ self._redactor = redactor or _redact # the scrubber used when redaction is on
240
+ self._flag_on_redact = flag_on_redact
241
+ self.entries: list[AuditEntry] = []
242
+ self._head = GENESIS
243
+ if self.path is not None:
244
+ self.path.parent.mkdir(parents=True, exist_ok=True)
245
+ self.path.write_text("", encoding="utf-8")
246
+ self._append("audit_open", {"system": system, "risk_tier": risk_tier})
247
+ bus.subscribe(self._on_event)
248
+
249
+ @property
250
+ def head(self) -> str:
251
+ """The current chain head hash. Capture it to later assert completeness:
252
+ ``verify(path, expected_head=log.head)`` catches trailing entries being dropped."""
253
+ return self._head
254
+
255
+ def __enter__(self) -> AuditLog:
256
+ return self
257
+
258
+ def __exit__(self, *exc: object) -> None:
259
+ self.detach() # stop subscribing when the block exits, so logs don't leak onto the bus
260
+
261
+ # ------------------------------------------------------------------ chain
262
+
263
+ def _append(self, etype: str, payload: dict) -> AuditEntry:
264
+ seq = len(self.entries)
265
+ ts = datetime.now(UTC).isoformat()
266
+ safe = _jsonable(payload)
267
+ redacted_categories: set[str] = set()
268
+ if self._redact:
269
+ if self._redactor is _redact and etype in _AUTO_REDACT_TYPES:
270
+ redacted_categories = _scan_redactions(safe) # detect on the pre-scrub view
271
+ safe = self._redactor(safe) # scrub before hashing so the chain is consistent
272
+ h = _chain_hash(self._head, seq, ts, etype, safe)
273
+ sig = ""
274
+ if self._signing_key is not None:
275
+ sig = hmac.new(self._signing_key, h.encode("utf-8"), hashlib.sha256).hexdigest()
276
+ entry = AuditEntry(seq, ts, etype, safe, self._head, h, sig)
277
+ self.entries.append(entry)
278
+ self._head = h
279
+ if self.path is not None:
280
+ with self.path.open("a", encoding="utf-8") as fh:
281
+ fh.write(json.dumps(entry.__dict__, ensure_ascii=False) + "\n")
282
+ if redacted_categories and self._flag_on_redact:
283
+ # append a follow-up policy_flag so the redaction is itself in the chain. The flag's own
284
+ # _append carries etype="policy_flag" (not an auto type), so this never recurses.
285
+ cats = sorted(redacted_categories)
286
+ self.flag(
287
+ f"redacted {', '.join(cats)} from {etype}",
288
+ action="redacted",
289
+ severity="info",
290
+ data=cats,
291
+ auto=True,
292
+ )
293
+ return entry
294
+
295
+ # ------------------------------------------------------------------ auto-capture
296
+
297
+ def _on_event(self, event: Any) -> None:
298
+ did = _active_decision.get()
299
+ if isinstance(event, LLMCall):
300
+ self._append(
301
+ "llm_call",
302
+ {
303
+ "decision_id": did,
304
+ "provider": event.provider,
305
+ "model": event.model,
306
+ "usage": _jsonable(event.usage),
307
+ "cost": _jsonable(event.cost),
308
+ "latency_ms": event.latency_ms,
309
+ "replayed": event.metadata.get("replayed", False),
310
+ },
311
+ )
312
+ elif isinstance(event, ToolCall):
313
+ self._append(
314
+ "tool_call",
315
+ {"decision_id": did, "name": event.name, "arguments": _jsonable(event.arguments)},
316
+ )
317
+ elif hasattr(event, "decisions") and hasattr(event, "budget"): # contextkit AssemblyReport
318
+ self._append(
319
+ "context_assembly",
320
+ {
321
+ "decision_id": did,
322
+ "model": getattr(event, "model", None),
323
+ "budget": event.budget,
324
+ "used": getattr(event, "used", None),
325
+ "decisions": _jsonable(event.decisions),
326
+ },
327
+ )
328
+
329
+ def detach(self) -> None:
330
+ """Stop subscribing to the core event stream."""
331
+ bus.unsubscribe(self._on_event)
332
+
333
+ # ------------------------------------------------------------------ explicit events
334
+
335
+ @contextmanager
336
+ def decision(self, input: Any = None, actor: str = "agent") -> Iterator[Decision]:
337
+ """Group a unit of work. Auto-captured calls inside it are tagged with this decision."""
338
+ did = uuid.uuid4().hex
339
+ self._append("decision", {"decision_id": did, "input": _jsonable(input), "actor": actor})
340
+ token = _active_decision.set(did)
341
+ try:
342
+ yield Decision(self, did)
343
+ finally:
344
+ _active_decision.reset(token)
345
+ self._append("decision_end", {"decision_id": did})
346
+
347
+ def flag(
348
+ self,
349
+ reason: str,
350
+ *,
351
+ action: FlagAction = "flagged",
352
+ severity: FlagSeverity = "warning",
353
+ data: Any = None,
354
+ **fields: Any,
355
+ ) -> AuditEntry:
356
+ """Record a policy flag — e.g. input a guard decided should not be processed by the agent.
357
+
358
+ A tamper-evident record that a data/usage policy fired. ``action`` is what your guard did
359
+ (``"flagged"`` | ``"redacted"`` | ``"blocked"``), ``reason`` why, ``severity`` how serious
360
+ (``"info"`` | ``"warning"`` | ``"critical"``), and ``data`` a *summary/category* of the
361
+ offending content — pass a label, **never the raw sensitive value** (it is chained and
362
+ written; redaction still runs over it). ``action``/``severity`` are normalized to lowercase;
363
+ other strings are accepted, not rejected. Auto-tags the active :meth:`decision` span.
364
+
365
+ acttrace only *records* the flag; deciding and enforcing the policy is your guard's job —
366
+ typically a pre-flight ``core.add_interceptor`` that inspects the request and raises to
367
+ block it (see docs/acttrace.md). Recorder and enforcer stay separate by design.
368
+ """
369
+ return self._append(
370
+ "policy_flag",
371
+ {
372
+ "decision_id": _active_decision.get(),
373
+ "reason": reason,
374
+ "action": str(action).lower(),
375
+ "severity": str(severity).lower(),
376
+ "data": data,
377
+ **fields,
378
+ },
379
+ )
380
+
381
+ # ------------------------------------------------------------------ export
382
+
383
+ def _summary(self) -> dict:
384
+ """Substance counts for the evidence-pack header: how many decisions, calls, oversight
385
+ events and flags (broken down by action/severity) — what a reviewer scans first."""
386
+ types = Counter(e.type for e in self.entries)
387
+ flags = [e for e in self.entries if e.type == "policy_flag"]
388
+ return {
389
+ "decisions": types.get("decision", 0),
390
+ "llm_calls": types.get("llm_call", 0),
391
+ "tool_calls": types.get("tool_call", 0),
392
+ "context_assemblies": types.get("context_assembly", 0),
393
+ "human_oversight": types.get("human_oversight", 0),
394
+ "policy_flags": len(flags),
395
+ "flags_by_action": dict(Counter(e.payload.get("action") for e in flags)),
396
+ "flags_by_severity": dict(Counter(e.payload.get("severity") for e in flags)),
397
+ }
398
+
399
+ def export(self, path: str, framework: str | None = None) -> None:
400
+ """Write the chain as a JSONL evidence pack, optionally annotated with control IDs.
401
+
402
+ ``framework`` (e.g. ``"eu_ai_act"`` or ``"nist_rmf"``) annotates each entry with the
403
+ control IDs it provides evidence for, and the ``_meta`` header lists every control covered.
404
+ Mappings are starting templates, not legal advice. See :func:`frameworks`.
405
+ """
406
+ if framework and framework not in _CONTROLS:
407
+ raise ValueError(f"unknown framework {framework!r}; available: {frameworks()}")
408
+ controls = _CONTROLS.get(framework or "", {})
409
+ covered = sorted({c for e in self.entries for c in controls.get(e.type, [])})
410
+ out = Path(path)
411
+ out.parent.mkdir(parents=True, exist_ok=True)
412
+ with out.open("w", encoding="utf-8") as fh:
413
+ meta = {
414
+ "_meta": {
415
+ "system": self.system,
416
+ "risk_tier": self.risk_tier,
417
+ "framework": framework,
418
+ "controls_covered": covered,
419
+ "summary": self._summary(),
420
+ "head_hash": self._head,
421
+ "entries": len(self.entries),
422
+ "disclaimer": "Evidence to support compliance — not legal advice.",
423
+ }
424
+ }
425
+ fh.write(json.dumps(meta, ensure_ascii=False) + "\n")
426
+ for entry in self.entries:
427
+ row = dict(entry.__dict__)
428
+ if framework:
429
+ row["controls"] = controls.get(entry.type, [])
430
+ fh.write(json.dumps(row, ensure_ascii=False) + "\n")
431
+
432
+
433
+ @dataclass
434
+ class Decision:
435
+ """Handle for the active decision span (yielded by :meth:`AuditLog.decision`)."""
436
+
437
+ log: AuditLog
438
+ id: str
439
+
440
+ def record(self, **fields: Any) -> None:
441
+ """Record decision metadata (e.g. ``model``, ``prompt_id``)."""
442
+ self.log._append("decision_record", {"decision_id": self.id, **fields})
443
+
444
+ def human_oversight(self, reviewer: str, action: str, note: str = "") -> None:
445
+ """Record an Art. 14-style human-oversight event: who reviewed, what action, when."""
446
+ self.log._append(
447
+ "human_oversight",
448
+ {"decision_id": self.id, "reviewer": reviewer, "action": action, "note": note},
449
+ )
450
+
451
+ def flag(
452
+ self,
453
+ reason: str,
454
+ *,
455
+ action: FlagAction = "flagged",
456
+ severity: FlagSeverity = "warning",
457
+ data: Any = None,
458
+ **fields: Any,
459
+ ) -> AuditEntry:
460
+ """Record a policy flag tagged to this decision (see :meth:`AuditLog.flag`). Returns the
461
+ chained :class:`AuditEntry` (matching :meth:`AuditLog.flag`)."""
462
+ return self.log._append(
463
+ "policy_flag",
464
+ {
465
+ "decision_id": self.id,
466
+ "reason": reason,
467
+ "action": str(action).lower(),
468
+ "severity": str(severity).lower(),
469
+ "data": data,
470
+ **fields,
471
+ },
472
+ )
473
+
474
+
475
+ def verify(
476
+ path: str,
477
+ *,
478
+ key: str | bytes | None = None,
479
+ expected_head: str | None = None,
480
+ expect_entries: int | None = None,
481
+ ) -> tuple[bool, str]:
482
+ """Re-walk the hash chain in a JSONL file. Returns ``(ok, detail)``. docs/acttrace.md §5.
483
+
484
+ Detects edits and deletions, *including tail-truncation*: a hash chain alone can't catch
485
+ trailing entries being dropped, so completeness is checked against an expected head hash and/or
486
+ entry count. An exported pack's ``_meta`` header (``head_hash``/``entries``) is used
487
+ automatically; ``expected_head`` / ``expect_entries`` override it (capture :attr:`AuditLog.head`
488
+ for a raw log).
489
+
490
+ If ``key`` is given, also verify each entry's HMAC signature against it (proving the log was
491
+ produced by a holder of the key, not just internal consistency). Streams the file, so memory
492
+ stays flat on large logs.
493
+ """
494
+ key_bytes = key.encode() if isinstance(key, str) else key
495
+ prev = GENESIS
496
+ seen = 0
497
+ meta_head: str | None = None
498
+ meta_entries: int | None = None
499
+ # Iterate the file object: universal newlines split on the record separator only — NOT on the
500
+ # Unicode line separators (U+2028 / U+0085 / …) that str.splitlines() would break on.
501
+ with open(path, encoding="utf-8") as fh:
502
+ for raw in fh:
503
+ line = raw.strip()
504
+ if not line:
505
+ continue
506
+ row = json.loads(line)
507
+ if "_meta" in row: # export header, not a chain entry
508
+ meta_head = row["_meta"].get("head_hash")
509
+ meta_entries = row["_meta"].get("entries")
510
+ continue
511
+ expected = _chain_hash(prev, row["seq"], row["ts"], row["type"], row["payload"])
512
+ if row["prev_hash"] != prev:
513
+ return False, f"broken link at seq {row['seq']}: prev_hash mismatch"
514
+ if row["hash"] != expected:
515
+ return False, f"tampered entry at seq {row['seq']}: hash mismatch"
516
+ if key_bytes is not None:
517
+ want = hmac.new(key_bytes, row["hash"].encode("utf-8"), hashlib.sha256).hexdigest()
518
+ if not hmac.compare_digest(row.get("sig", ""), want):
519
+ return False, f"bad signature at seq {row['seq']}"
520
+ prev = row["hash"]
521
+ seen += 1
522
+
523
+ want_head = expected_head if expected_head is not None else meta_head
524
+ if want_head is not None and prev != want_head:
525
+ return False, (
526
+ f"incomplete log: head {prev[:12]}… != expected {want_head[:12]}… "
527
+ "(trailing entries removed?)"
528
+ )
529
+ want_n = expect_entries if expect_entries is not None else meta_entries
530
+ if want_n is not None and seen != want_n:
531
+ return False, f"incomplete log: found {seen} entries, expected {want_n} (entries removed?)"
532
+
533
+ suffix = " (signatures verified)" if key_bytes is not None else ""
534
+ return True, f"ok: {seen} entries, head {prev[:12]}…{suffix}"
cendor/acttrace/cli.py ADDED
@@ -0,0 +1,45 @@
1
+ """``acttrace`` CLI: an offline verifier for the hash chain. docs/acttrace.md §3.
2
+
3
+ acttrace verify evidence_q3.jsonl # exits non-zero if the chain is broken
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import sys
10
+ from collections.abc import Sequence
11
+
12
+ from . import verify
13
+
14
+
15
+ def main(argv: Sequence[str] | None = None) -> int:
16
+ """Entry point for the ``acttrace`` console script. Returns a process exit code."""
17
+ parser = argparse.ArgumentParser(prog="acttrace", description="Audit-log tools.")
18
+ sub = parser.add_subparsers(dest="command", required=True)
19
+ verify_cmd = sub.add_parser("verify", help="re-walk a JSONL log's hash chain")
20
+ verify_cmd.add_argument("path", help="path to the .jsonl audit/evidence file")
21
+ verify_cmd.add_argument(
22
+ "--key", default=None, help="HMAC signing key; also verifies entry signatures"
23
+ )
24
+ verify_cmd.add_argument(
25
+ "--expect-head", default=None, help="expected head hash; fails if trailing entries are gone"
26
+ )
27
+ verify_cmd.add_argument(
28
+ "--expect-entries", type=int, default=None, help="expected entry count (truncation check)"
29
+ )
30
+
31
+ args = parser.parse_args(argv)
32
+ if args.command == "verify":
33
+ ok, detail = verify(
34
+ args.path,
35
+ key=args.key,
36
+ expected_head=args.expect_head,
37
+ expect_entries=args.expect_entries,
38
+ )
39
+ print(detail)
40
+ return 0 if ok else 1
41
+ return 2
42
+
43
+
44
+ if __name__ == "__main__": # pragma: no cover
45
+ sys.exit(main())
File without changes
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: cendor-acttrace
3
+ Version: 0.7.0
4
+ Summary: Audit: a tamper-evident, hash-chained, auto-populated record of every AI decision — verifiable offline. Evidence, not a compliance guarantee.
5
+ Author: Raghav Mishra
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ License-File: NOTICE
9
+ Requires-Python: >=3.11
10
+ Requires-Dist: cendor-core<0.2,>=0.1.9
11
+ Description-Content-Type: text/markdown
12
+
13
+ # cendor-acttrace
14
+
15
+ A tamper-evident, append-only record of every AI decision — what model, what context, what it
16
+ cost, which tools, and who signed off — mapped to control templates and exportable as an evidence
17
+ pack. No database, no infra: integrity comes from a hash chain, not a server.
18
+
19
+ **Audit-ready evidence in 5 lines — and verifiable offline.**
20
+
21
+ ![PyPI](https://img.shields.io/pypi/v/cendor-acttrace) ![license](https://img.shields.io/badge/license-Apache_2.0-blue) · `pip install cendor-acttrace`
22
+
23
+ ```python
24
+ from cendor.core import instrument
25
+ from cendor.acttrace import AuditLog
26
+
27
+ client = instrument(OpenAI())
28
+ audit = AuditLog(system="loan_triage", risk_tier="high", signing_key="…") # auto-subscribes
29
+
30
+ with audit.decision(input=application, actor="agent") as d:
31
+ resp = client.chat.completions.create(model="gpt-4o", messages=msgs) # auto-logged
32
+ d.record(model="gpt-4o", prompt_id="triage@v3") # cost/context captured for free
33
+ d.human_oversight(reviewer="ops@bank", action="approved")
34
+
35
+ audit.export("evidence_q3.jsonl", framework="eu_ai_act") # evidence pack (also nist_rmf)
36
+ ```
37
+
38
+ ```bash
39
+ acttrace verify evidence_q3.jsonl --key "…" # re-walks the chain + checks signatures; non-zero if broken
40
+ ```
41
+
42
+ ## Highlights
43
+
44
+ - **Auto-populating** — construct an `AuditLog` and it subscribes to the bus: every LLM/tool call, plus cost (`tokenguard`) and context decisions (`contextkit`) on the same stream, becomes an entry — no per-call wiring.
45
+ - **Tamper-evident hash chain** — `verify()` catches edits, reordering, **and tail-truncation** (head + count travel in the evidence pack, or pass `expected_head=`); each entry optionally **HMAC-signed**.
46
+ - **Decisions & oversight** — `decision()` groups a unit of work; `d.record(...)` and `d.human_oversight(reviewer, action)` capture Art. 14-style sign-off.
47
+ - **Compliance evidence packs** — `export(framework=…)` annotates control IDs for **EU AI Act**, **ISO/IEC 42001**, **GDPR**, and **NIST AI RMF** (starting templates, not certified mappings), and a `_meta.summary` (counts of decisions, oversight, flags by action/severity) gives a reviewer the at-a-glance read first. PII redaction on by default (swap in `redactor=`).
48
+ - **Auto-flag on redaction** — when the built-in redactor scrubs PII (`email`, `api_key`, `bearer_token`) from an auto-captured entry, acttrace appends a `policy_flag` recording *which category* was removed — so "we removed PII" is in the hash chain, not silent (`flag_on_redact=True` by default; a custom `redactor=` owns its own flagging).
49
+ - **Policy flags (validation)** — `audit.flag(reason, action="blocked", …)` records a tamper-evident `policy_flag` (and **returns** the chained entry) when your pre-flight guard refuses input that shouldn't be processed — so the *refusal* is auditable, not just the calls that ran:
50
+
51
+ ```python
52
+ from cendor.core.instrument import add_interceptor, MISS
53
+
54
+ def guard(call): # your pre-flight policy guard
55
+ if my_policy_disallows(call): # YOUR rule
56
+ audit.flag("special-category data", action="blocked") # acttrace records the refusal
57
+ raise PolicyViolation("blocked") # your guard enforces it
58
+ return MISS
59
+
60
+ add_interceptor(guard) # the blocked call never reaches the bus — flag() is its only record
61
+ ```
62
+
63
+ > Produces **evidence to support** compliance — not legal advice, not a guarantee. Control
64
+ > mappings are starting templates for your compliance team.
65
+
66
+ See [`docs/acttrace.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/acttrace.md) · [CHANGELOG](https://github.com/PowerAI-Labs/Cendor/blob/main/packages/cendor-acttrace/CHANGELOG.md). *Part of the Cendor stack — [github.com/PowerAI-Labs/Cendor](https://github.com/PowerAI-Labs/Cendor). Powered by PowerAI Labs. Apache-2.0; provided "as is", without warranty — use at your own risk (LICENSE §7–8).*
@@ -0,0 +1,9 @@
1
+ cendor/acttrace/__init__.py,sha256=1DCm2FrwUgumuF_fZ8K2tK0TPe4n6-Hb3l9G_ap3UvE,23474
2
+ cendor/acttrace/cli.py,sha256=NnYXBSZ3MamLKRp2cDsAd2lPX3ExrzvYGFVg7UEc1wc,1522
3
+ cendor/acttrace/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ cendor_acttrace-0.7.0.dist-info/METADATA,sha256=YIkqUjnNvRVNV0g2IgHlRaqR5JjIHSrU1HbonrHo3Yw,4347
5
+ cendor_acttrace-0.7.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ cendor_acttrace-0.7.0.dist-info/entry_points.txt,sha256=j9KINyuxRPGLFT-9-a6EkCLc5WHICtmh2DL_O2kn7s0,54
7
+ cendor_acttrace-0.7.0.dist-info/licenses/LICENSE,sha256=rWd-5vQbNwLV-BXHAMGdYtO9C_qmH_CJRYguqs5VFew,11358
8
+ cendor_acttrace-0.7.0.dist-info/licenses/NOTICE,sha256=X9hofg62ar1nYcEJKv6QxqFj6_Yw_nYZEJ6ioOtznj0,222
9
+ cendor_acttrace-0.7.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ acttrace = cendor.acttrace.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Raghav Mishra (PowerAI Labs)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ PowerAI Labs
2
+ Copyright 2026 Raghav Mishra (PowerAI Labs)
3
+
4
+ This product includes software developed by Raghav Mishra (PowerAI Labs).
5
+
6
+ Licensed under the Apache License, Version 2.0. See the LICENSE file for the
7
+ full terms.