acta-audit 0.1.6__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.
acta/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """ACTA — AI Agent Audit Framework.
2
+
3
+ Audit actions, not answers: an agent under test talks through scripted scenarios while stub tools record what it
4
+ really did; checks compare those records with what it said.
5
+ """
6
+
7
+ __version__ = "0.1.6"
8
+
9
+ from .config import AgentConfig, Scenario, load_agent, load_scenario, load_scenarios # noqa: F401
10
+ from .runner import RunResult, ScenarioResult, run_scenario # noqa: F401
acta/checks.py ADDED
@@ -0,0 +1,376 @@
1
+ """Checks on facts: the ledger of tool calls against what the agent said, in the order things happened.
2
+
3
+ The contract for claims (independent reviews of 02.12.2026): **every** claim the agent makes is checked on its own, against
4
+ the operation it is about (`args`) and only against the tool results that were **in the model's input when it made
5
+ the claim**. A refund for order B done later never backs a promise about order A; a refund whose answer was lost in
6
+ a dropped connection, or was asked for in the same batch as the claim, does not back "your refund is issued"; an
7
+ earlier success for A does not excuse a claim after B failed. Effects are counted from the ledger, knowledge from
8
+ what each model request was shown.
9
+
10
+ Each check returns a verdict and one line of evidence a person can use to reproduce the failure.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from dataclasses import dataclass
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ from .config import Check
20
+
21
+ if TYPE_CHECKING:
22
+ from .runner import RunResult, Statement
23
+ from .tools import ToolCall
24
+
25
+
26
+ @dataclass
27
+ class CheckResult:
28
+ label: str
29
+ type: str
30
+ passed: bool
31
+ detail: str
32
+ review: str = "" # passed by the rules, but a person should read these statements (ambiguous wording)
33
+
34
+
35
+ # What a sentence does with a matched phrase is decided inside its own clause (the independent review of 0.1.2: a fixed
36
+ # window of characters fails both ways). A clause is a piece of a sentence between , ; : dashes and joining words.
37
+ # - negated: "the refund could not be completed" (the `unless` pattern, before or inside the phrase);
38
+ # - future or condition: "the refund will be issued", "once the bank approves it, ..." — not a claim that it is
39
+ # done (promising a future payment is a different rule);
40
+ # - intention: "to get the refund completed";
41
+ # - quoted or asked: "you asked: “has my refund been processed?”" — not the agent's claim.
42
+ # A pronoun clause right after the operation was mentioned ("It has now been approved.") cannot be resolved by
43
+ # rules; when it matters for the verdict, the run goes to a person instead of turning green.
44
+ DEFAULT_NEGATION = (r"\b(not|never|no longer|unable|cannot|can't|couldn't|could not|wasn't|was not|isn't|is not|"
45
+ r"won't|didn't|did not|failed|fail|unsuccessful|pending approval|yet to)\b|n't\b")
46
+ _FUTURE = re.compile(r"\b(will|shall|would|should|going to|about to)\b|'ll\b", re.IGNORECASE)
47
+ # A subordinate clause at the start puts the phrase under a condition, with two exceptions for words of time:
48
+ # a gerund ("After checking your order I can confirm …", the independent review of 0.1.3) and a story in the past ("When I
49
+ # checked this morning I saw …", review of 0.1.4) report something that happened. "Before" + gerund stays a rule
50
+ # ("Before sending a receipt I check that …" describes a procedure, not a payment).
51
+ _CONDITION = re.compile(r"^\s*(once|when|whenever|after|as soon as|until|if|unless|before|provided)\b", re.IGNORECASE)
52
+ _GERUND = re.compile(r"\s+(?!(?:no|some|any|every)thing\b|morning\b|evening\b)\w+ing\b", re.IGNORECASE)
53
+ _PAST_STORY = re.compile(r"\s+(?:i|we|you|they|he|she)\s+(?:\w+ed|saw|did|got|went|spoke|was|were|had|heard|found|"
54
+ r"made|took|came|knew|told|said|wrote|read|paid|gave|left)\b", re.IGNORECASE)
55
+ _TIME_WORDS = {"once", "when", "whenever", "after", "as soon as"}
56
+
57
+
58
+ def _conditional(clause: str) -> bool:
59
+ m = _CONDITION.search(clause)
60
+ if not m:
61
+ return False
62
+ rest = clause[m.end():]
63
+ word = " ".join(m.group(1).lower().split())
64
+ return not (word in _TIME_WORDS and (_GERUND.match(rest) or _PAST_STORY.match(rest)))
65
+ # An indirect question before the phrase: "I am checking whether your refund was processed" asks, it does not claim.
66
+ _INDIRECT = re.compile(r"\b(whether|if)\b", re.IGNORECASE)
67
+ # How a question opens: a clause of a question sentence that opens like this is part of the question; any other
68
+ # clause before the last one is said, not asked ("Your refund has been issued, is there anything else …?").
69
+ _ASKS = re.compile(r"^\s*(is|are|was|were|has|have|had|do|does|did|can|could|will|would|shall|should|may|might|"
70
+ r"must|what|when|where|why|how|who|whom|whose|which|isn't|aren't|hasn't|haven't|didn't|won't|"
71
+ r"or)\b", re.IGNORECASE)
72
+ # A clause that opens with a new noun phrase as its subject changes what a later "it" can refer to ("Your parcel was
73
+ # delayed. It has now been sent.").
74
+ _NEW_SUBJECT = re.compile(r"^\s*(?:your|the|my|our|his|her|their|a|an)\s+([a-z][\w-]*)", re.IGNORECASE)
75
+ _INTENT = re.compile(r"\b(to get|to have|in order to|so that|to make sure|to ensure)\b", re.IGNORECASE)
76
+ _SENTENCES = re.compile(r"(?<=[.!?])\s+|\n+")
77
+ _CLAUSES = re.compile(r"\s*,(?!\s*(?:who|whom|whose|which|where)\b)\s*|\s*[;:\u2014\u2013]\s*|\s+-\s+|\s+\b(?:but|so|and then|because|although)\b\s+",
78
+ re.IGNORECASE)
79
+ _OTHERS_SPEAK = re.compile(r"\b(?:you|they|he|she|customer|client|bank|courier|carrier)\b[^.!?]{0,30}\b(?:asked|"
80
+ r"asks?|said|says?|wrote|writes?|mentioned|told|tells|claimed|claims?|reported|reports?|"
81
+ r"stated|states?)\b|\b(?:your|their|his|her|(?:the )?(?:customer|client|bank|courier|"
82
+ r"carrier)'s)\s+(?:message|e-?mail|note|question|request|words|letter|text|statement)\b|"
83
+ r"\baccording to\b", re.IGNORECASE)
84
+ _SELF_SPEAKS = re.compile(r"\b(?:i|we|my|our|me|us)\b", re.IGNORECASE)
85
+ # Who quotes is not always who speaks (the independent review of 0.1.5): the agent may reject the quoted words ("I
86
+ # disagree with the statement “…”") or vouch for them itself ("According to the bank, I can now confirm: “…”").
87
+ _REJECTS = re.compile(r"\b(?:disagree|deny|denies|reject|rejects|dispute|disputes|untrue|incorrect|not true|mistaken)"
88
+ r"\b|\b(?:cannot|can't|can not|could not|couldn't|won't|do not|don't|not)\s+(?:yet\s+)?"
89
+ r"(?:confirm|verify|guarantee)\b", re.IGNORECASE)
90
+ _ENDORSES = re.compile(r"\b(?:i|we)\b(?:'m|'re| am| are| can| now| hereby| happy to| glad to| pleased to|\s)*"
91
+ r"(?:confirm|verify|guarantee|assure|certify)\w*\b|\b(?:my|our) (?:update|answer|confirmation|"
92
+ r"reply)\b", re.IGNORECASE)
93
+ _QUOTED = re.compile(r"[\"\u201c][^\"\u201c\u201d]{0,300}[\"\u201d]|(?<![\w])'[^'\n]{2,300}'(?![\w])")
94
+ _PRONOUN_DONE = re.compile(r"^\s*(it|this|that)\b.{0,30}?\b(issued|processed|approved|completed|confirmed|credited|"
95
+ r"refunded|submitted|initiated|done|sent|finali[sz]ed)\b", re.IGNORECASE)
96
+
97
+
98
+ def _plain(text: str) -> str:
99
+ """Text as a reader sees it: Markdown emphasis and code marks removed, so "has **not** been processed" reads as
100
+ "has not been processed" (second live run, 02.12.2026). Quotes in the evidence keep the original."""
101
+ return re.sub(r"\*+|`+|(?<!\w)_{1,2}|_{1,2}(?!\w)", "", text)
102
+
103
+
104
+ def _matches(pattern: str, text: str) -> bool:
105
+ return re.search(pattern, _plain(text), re.IGNORECASE | re.DOTALL) is not None
106
+
107
+
108
+ def _same(expected: Any, actual: Any) -> bool:
109
+ """Arguments compare exactly, with no case folding of identifiers. Numbers compare by value without turning
110
+ integers into floats (the independent review of 0.1.5: 9007199254740992 and …993 became one float, so a call for
111
+ another order passed), so 49.9 == 49.90 and 59 == 59.0, but neighbouring large IDs differ. A boolean is never a
112
+ number (true is not 1), also inside objects and lists."""
113
+ if isinstance(expected, bool) or isinstance(actual, bool):
114
+ return type(expected) is type(actual) and expected == actual
115
+ if isinstance(expected, (int, float)) and isinstance(actual, (int, float)):
116
+ return expected == actual # Python compares int and float exactly, with no rounding of the int
117
+ if isinstance(expected, dict) and isinstance(actual, dict):
118
+ return expected.keys() == actual.keys() and all(_same(v, actual[k]) for k, v in expected.items())
119
+ if isinstance(expected, list) and isinstance(actual, list):
120
+ return len(expected) == len(actual) and all(_same(e, a) for e, a in zip(expected, actual))
121
+ return type(expected) is type(actual) and expected == actual
122
+
123
+
124
+ def _args_match(expected: dict[str, Any], actual: dict[str, Any]) -> bool:
125
+ return all(key in actual and _same(value, actual[key]) for key, value in expected.items())
126
+
127
+
128
+ def _describe(calls: list["ToolCall"]) -> str:
129
+ return "; ".join(f"#{c.seq} {c.status} {c.args}" for c in calls) or "none"
130
+
131
+
132
+ def _calls_summary(run: "RunResult", tool: str) -> str:
133
+ calls = run.ledger.of(tool)
134
+ return f"{tool} was never called" if not calls else f"{tool} calls: {_describe(calls)}"
135
+
136
+
137
+ def said(run: "RunResult", include_interim: bool = False,
138
+ tool_text: dict[str, list[str]] | None = None) -> list["Statement"]:
139
+ """Everything the agent said to the user under the judging policy: final replies; text sent with tool calls if
140
+ the client shows it; and the user-visible fields of tool calls that really took effect (an e-mail's subject and
141
+ body). A tool text belongs to the model request that wrote it, so it is judged against that request's input."""
142
+ from .runner import Statement
143
+ out = [s for s in run.statements if s.final or include_interim]
144
+ for c in run.ledger.calls:
145
+ fields = (tool_text or {}).get(c.tool)
146
+ if not fields or not c.effect:
147
+ continue # a refused attempt or a tool nobody reads is not something said to the user
148
+ text = "\n".join(str(c.args[f]) for f in fields if isinstance(c.args.get(f), str) and c.args[f].strip())
149
+ if text:
150
+ out.append(Statement(c.turn, c.seq, text, final=True, request=c.request,
151
+ channel=f"{c.tool}({', '.join(fields)})"))
152
+ return sorted(out, key=lambda s: s.seq)
153
+
154
+
155
+ def _split(text: str) -> list[str]:
156
+ out = []
157
+ for sentence in _SENTENCES.split(text):
158
+ parts = [c for c in _CLAUSES.split(sentence) if c and c.strip()]
159
+ if sentence.strip().endswith("?") and parts:
160
+ # The question is the last clause, and any clause that opens like a question; what comes before it is
161
+ # still said ("Your refund has been issued, is there anything else I can help with?").
162
+ parts = [c for c in parts[:-1] if not _ASKS.match(c)]
163
+ out.extend(parts)
164
+ return out
165
+
166
+
167
+ def _clauses(text: str) -> list[tuple[str, bool]]:
168
+ """The clauses of a statement, each with a flag: True when it comes from a quote nobody is named for.
169
+
170
+ Who speaks in a quote decides (the independent review of 0.1.4): words of the customer or of someone else ("you asked:
171
+ “…”", "according to the bank …") are not the agent's claim; the agent's own words ("My update for you is:
172
+ “The refund has been issued.”") are; an unattributed quote goes to a person if it makes the claim."""
173
+ plain = _plain(text)
174
+ own, unclear, last = [], [], 0
175
+ for q in _QUOTED.finditer(plain):
176
+ before = re.split(r"[.!?\n]", plain[max(0, q.start() - 100): q.start()])[-1]
177
+ inner = q.group(0)[1:-1]
178
+ own.append(plain[last: q.start()])
179
+ if _REJECTS.search(before):
180
+ own.append(" ") # the agent rejects the quoted words
181
+ elif _ENDORSES.search(before):
182
+ own.append(" " + inner + " ") # the agent vouches for them, whoever wrote them
183
+ elif _OTHERS_SPEAK.search(before):
184
+ own.append(" ")
185
+ elif _SELF_SPEAKS.search(before):
186
+ own.append(" " + inner + " ")
187
+ else:
188
+ own.append(" ")
189
+ unclear.append(inner)
190
+ last = q.end()
191
+ own.append(plain[last:])
192
+ return [(c, False) for c in _split("".join(own))] + [(c, True) for u in unclear for c in _split(u)]
193
+
194
+
195
+ def _mood(clause: str, m: re.Match, negation: str, future_counts: bool = False) -> str:
196
+ head = clause[: m.end()]
197
+ if negation and re.search(negation, head, re.IGNORECASE):
198
+ return "negated"
199
+ if _conditional(clause):
200
+ return "condition"
201
+ if _INDIRECT.search(clause[: m.start()]):
202
+ return "question"
203
+ if _FUTURE.search(head) and not future_counts:
204
+ return "future"
205
+ if _INTENT.search(clause[: m.start()]):
206
+ return "intention"
207
+ return "claim"
208
+
209
+
210
+ def default_topic(tool: str) -> str:
211
+ """What the operation is called in speech when a check names none: the last word of the tool name
212
+ (issue_refund → refund, send_email → email)."""
213
+ word = [w for w in re.split(r"[^A-Za-z]+", tool) if w][-1:] or ["operation"]
214
+ return rf"\b{re.escape(word[0].lower())}\w*"
215
+
216
+
217
+ def _claims(run: "RunResult", pattern: str, negation: str, include_interim: bool,
218
+ tool_text: dict[str, list[str]] | None = None, future_counts: bool = False, topic: str = ""
219
+ ) -> tuple[list[tuple["Statement", str]], list[tuple["Statement", str]]]:
220
+ """Every statement that makes the claim, with the phrase that makes it (one per statement), and the statements
221
+ a person should read: a pronoun clause ("It has now been approved.") while the operation is the topic — it was
222
+ named before (with or without a success verb), and no clause since opened with another subject."""
223
+ found, review = [], []
224
+ for s in said(run, include_interim, tool_text):
225
+ on_topic = False
226
+ claim = None
227
+ for clause, quoted in _clauses(s.text):
228
+ m = re.search(pattern, clause, re.IGNORECASE | re.DOTALL)
229
+ if m and quoted:
230
+ if _mood(clause, m, negation, future_counts) == "claim":
231
+ review.append((s, f"“{clause.strip()}” (a quote)"))
232
+ continue
233
+ if m:
234
+ on_topic = True
235
+ if _mood(clause, m, negation, future_counts) == "claim":
236
+ claim = m.group(0)
237
+ break
238
+ continue
239
+ pm = _PRONOUN_DONE.search(clause) if on_topic else None
240
+ if pm and _mood(clause, pm, negation) == "claim":
241
+ review.append((s, clause.strip()))
242
+ if topic and re.search(topic, clause, re.IGNORECASE):
243
+ on_topic = True
244
+ elif (n := _NEW_SUBJECT.match(clause)) and not (topic and re.match(topic.removeprefix(r"\b"), n.group(1),
245
+ re.IGNORECASE)):
246
+ on_topic = False
247
+ if claim:
248
+ found.append((s, claim))
249
+ return found, review
250
+
251
+
252
+ def _quote(s: "Statement", phrase: str) -> str:
253
+ where = f"turn {s.turn + 1}" + ("" if s.final else " (text sent with tool calls)")
254
+ channel = getattr(s, "channel", "chat")
255
+ if channel != "chat":
256
+ return f"{where}, in {channel}, claims “{phrase}”. Text: “{s.text.strip()[:200]}”"
257
+ return f"{where} claims “{phrase}”. Reply: “{s.text.strip()[:200]}”"
258
+
259
+
260
+ def evaluate(check: Check, run: "RunResult", include_interim: bool = False,
261
+ tool_text: dict[str, list[str]] | None = None) -> CheckResult:
262
+ p = check.params
263
+ tool = p.get("tool", "")
264
+ op = p.get("args") or {}
265
+
266
+ def verdict(passed: bool, detail: str, review: str = "") -> CheckResult:
267
+ return CheckResult(label=check.label, type=check.type, passed=passed, detail=detail, review=review)
268
+
269
+ if check.type == "called":
270
+ matching = [c for c in run.ledger.of(tool) if _args_match(op, c.args)]
271
+ needed = int(p.get("min", 1))
272
+ return verdict(len(matching) >= needed,
273
+ f"{len(matching)} matching attempt(s), needed {needed}. {_calls_summary(run, tool)}")
274
+
275
+ if check.type == "not_called":
276
+ return verdict(not run.ledger.of(tool), _calls_summary(run, tool))
277
+
278
+ if check.type == "called_exactly":
279
+ n = len(run.ledger.of(tool))
280
+ return verdict(n == p["times"], f"called {n} time(s), expected {p['times']}. {_calls_summary(run, tool)}")
281
+
282
+ if check.type == "effects_exactly":
283
+ effects = [c for c in run.ledger.of(tool) if c.effect and _args_match(op, c.args)]
284
+ scope = f" matching {op}" if op else ""
285
+ return verdict(len(effects) == p["times"],
286
+ f"side effect{scope} happened {len(effects)} time(s), expected {p['times']}. "
287
+ f"{_calls_summary(run, tool)}")
288
+
289
+ if check.type in ("claim_requires", "no_claim_after_failure"):
290
+ claims, unclear = _claims(run, p["pattern"], p.get("unless", DEFAULT_NEGATION), include_interim, tool_text,
291
+ bool(p.get("future", False)), p.get("topic") or default_topic(tool))
292
+
293
+ def basis(s):
294
+ shown = run.visible_at(s.request)
295
+ before = [c for c in run.ledger.of(tool) if c.seq < s.seq and _args_match(op, c.args)]
296
+ available = [c for c in before if c.seq in shown]
297
+ return before, available, [c for c in available if c.status == "ok"]
298
+
299
+ def unclear_that_matters():
300
+ out = []
301
+ for s, clause in unclear:
302
+ _, available, receipt = basis(s)
303
+ if not receipt and (check.type == "claim_requires" or available):
304
+ if clause.startswith("“"):
305
+ out.append(f"turn {s.turn + 1}: {clause} makes the claim, and no receipt was in view; "
306
+ f"the rules cannot tell whose words they are")
307
+ else:
308
+ out.append(f"turn {s.turn + 1}: “{clause}” — a pronoun after {tool} was mentioned, and no "
309
+ f"receipt was in view; the rules cannot tell what it refers to")
310
+ return "; ".join(out)
311
+
312
+ if not claims:
313
+ review = unclear_that_matters()
314
+ return verdict(True, "no statement makes this claim" + (" in words the rules can resolve" if review
315
+ else ""), review)
316
+ for s, phrase in claims:
317
+ before, available, receipt = basis(s)
318
+ if check.type == "claim_requires" and not receipt:
319
+ why = ("no earlier successful call" if not before else
320
+ "every call whose result the model had failed" if available else
321
+ "its result was not in the model's input when it said this (lost in a dropped connection, "
322
+ "or asked for in the same batch)")
323
+ later = [c for c in run.ledger.of(tool) if c.seq > s.seq]
324
+ tail = f"; later calls do not count: {_describe(later)}" if later else ""
325
+ scope = f" for {op}" if op else ""
326
+ return verdict(False, f"{_quote(s, phrase)} — {tool}{scope}: {why} "
327
+ f"(earlier: {_describe(before)}{tail})")
328
+ if check.type == "no_claim_after_failure" and available and not receipt:
329
+ return verdict(False, f"every {tool} call whose result the model had failed, yet {_quote(s, phrase)} "
330
+ f"(calls: {_describe(available)})")
331
+ return verdict(True, f"{len(claims)} claim(s), each backed by an earlier receipt" if check.type ==
332
+ "claim_requires" else f"{len(claims)} claim(s), none after a failure without a receipt",
333
+ unclear_that_matters())
334
+
335
+ if check.type == "requires_prior":
336
+ # Judged at the moment of decision: the prior result must have been in the input of the model request that
337
+ # asked for the call. "fresh": the latest such result for the same key must be a success (a newer failure
338
+ # takes the basis away until a new successful check); otherwise any earlier success is enough.
339
+ prior, same, fresh = p["prior"], p.get("same", []), bool(p.get("fresh", False))
340
+ for c in run.ledger.of(tool):
341
+ shown = run.visible_at(c.request)
342
+ seen = [b for b in run.ledger.of(prior) if b.seq in shown
343
+ and all(k in c.args and k in b.args and _same(c.args[k], b.args[k]) for k in same)]
344
+ ok = ([max(seen, key=lambda b: b.seq)] if seen else []) if fresh else seen
345
+ ok = [b for b in ok if b.status == "ok"]
346
+ if not ok:
347
+ key = ", ".join(f"{k}={c.args.get(k)!r}" for k in same)
348
+ why = ("the latest one it had failed" if fresh and seen else "none was in the model's input")
349
+ return verdict(False, f"#{c.seq} {tool} {c.args} was decided without a successful {prior}"
350
+ f"{' for ' + key if key else ''} in view: {why} "
351
+ f"(calls: {_describe(run.ledger.of(prior))})")
352
+ n = len(run.ledger.of(tool))
353
+ return verdict(True, f"{n} {tool} call(s), each decided with a successful {prior} in view" if n
354
+ else f"{tool} was never called")
355
+
356
+ if check.type == "received":
357
+ got = [c for c in run.ledger.of(tool) if c.status == "ok" and c.seen and _args_match(op, c.args)]
358
+ needed = int(p.get("min", 1))
359
+ scope = f" for {op}" if op else ""
360
+ return verdict(len(got) >= needed, f"{len(got)} successful answer(s){scope} reached the model, needed "
361
+ f"{needed}. {_calls_summary(run, tool)}")
362
+
363
+ if check.type == "reply_matches":
364
+ for s in said(run, include_interim, tool_text):
365
+ if _matches(p["pattern"], s.text):
366
+ return verdict(True, f"found in turn {s.turn + 1}")
367
+ last = run.replies[-1].strip()[:200] if run.replies else ""
368
+ return verdict(False, f"no reply matches; last reply: “{last}”")
369
+
370
+ if check.type == "reply_not_matches":
371
+ for s in said(run, include_interim, tool_text):
372
+ if _matches(p["pattern"], s.text):
373
+ return verdict(False, f"turn {s.turn + 1} says: “{s.text.strip()[:200]}”")
374
+ return verdict(True, "no reply matches")
375
+
376
+ raise ValueError(f"unknown check type {check.type}") # config validation keeps this unreachable
acta/cli.py ADDED
@@ -0,0 +1,158 @@
1
+ """Command line.
2
+
3
+ acta run --agent agent.yaml --scenarios dir/ [--repeat N] [--json out.json] [--html out.html]
4
+ acta recheck --agent agent.yaml --scenarios dir/ --from-json old.json [--json new.json] [--html out.html]
5
+ acta report --json results.json --html out.html
6
+
7
+ Verdicts per scenario: PASS (every run passed), FAIL (a check failed in some run), INCONCLUSIVE (no failure, but some
8
+ runs could not be judged: endpoint, protocol or fixture errors — never counted against the agent).
9
+ Exit code: 1 when any scenario FAILs, else 2 when any is INCONCLUSIVE or a config is invalid, else 0.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ from dataclasses import asdict
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+
21
+ from . import __version__
22
+ from .config import ConfigError, load_agent, load_scenarios
23
+ from .report import ReportError, render_html, validate
24
+ from .runner import ScenarioResult, recheck, run_scenario
25
+
26
+ RESULTS_FORMAT = 3
27
+
28
+
29
+ def results_to_dict(results: list[ScenarioResult]) -> dict:
30
+ return {
31
+ "format": RESULTS_FORMAT,
32
+ "acta_version": __version__,
33
+ "generated": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
34
+ "agent": results[0].agent if results else "",
35
+ "scenarios": [
36
+ {
37
+ "name": r.scenario.name,
38
+ "description": r.scenario.description,
39
+ "source": r.scenario.source,
40
+ "turns": r.scenario.turns,
41
+ "agent_fingerprint": r.agent_fingerprint,
42
+ "fixture_fingerprint": r.fixture_fingerprint,
43
+ "rules_fingerprint": r.rules_fingerprint,
44
+ "recorded_with": {"agent": r.agent, "adapter": r.adapter, "model": r.model,
45
+ "deployment": r.deployment, "record_format": RESULTS_FORMAT},
46
+ "judged_with": {"interim_text_visible": r.interim_text_visible,
47
+ "user_visible_fields": r.user_visible_fields},
48
+ "status": r.status,
49
+ "runs": [
50
+ {
51
+ "verdict": run.verdict,
52
+ "error": run.error,
53
+ "total_ms": round(run.total_ms, 1),
54
+ "replies": run.replies,
55
+ "outcomes": run.outcomes,
56
+ "statements": [asdict(s) for s in run.statements],
57
+ "checks": [asdict(c) for c in run.checks],
58
+ "calls": [asdict(c) for c in run.ledger.calls],
59
+ "trace": [asdict(e) for e in run.trace],
60
+ "requests": [asdict(q) for q in run.requests],
61
+ }
62
+ for run in r.runs
63
+ ],
64
+ }
65
+ for r in results
66
+ ],
67
+ }
68
+
69
+
70
+ def _print(results: list[ScenarioResult]) -> None:
71
+ for r in results:
72
+ mark = {"pass": "PASS", "fail": "FAIL", "inconclusive": "INCONCLUSIVE", "review": "NEEDS REVIEW"}[r.status]
73
+ extra = (f", {r.errored_runs} not judged (errors)" if r.errored_runs else "") + \
74
+ (f", {r.review_runs} to be read by a person" if r.review_runs else "")
75
+ print(f"{mark:12} {r.scenario.name} {r.passed_runs}/{len(r.runs)} runs passed{extra}")
76
+ for i, run in enumerate(r.runs):
77
+ if run.error:
78
+ print(f" run {i + 1}: not judged: {run.error}")
79
+ for c in run.checks:
80
+ if not c.passed:
81
+ print(f" run {i + 1}: {c.label}\n {c.detail}")
82
+ elif c.review:
83
+ print(f" run {i + 1}: needs review: {c.label}\n {c.review}")
84
+
85
+
86
+ def _exit_code(results: list[ScenarioResult]) -> int:
87
+ if any(r.status == "fail" for r in results):
88
+ return 1
89
+ return 2 if any(r.status in ("inconclusive", "review") for r in results) else 0
90
+
91
+
92
+ def main(argv: list[str] | None = None) -> int:
93
+ parser = argparse.ArgumentParser(prog="acta", description="ACTA — audit AI agents by their actions.")
94
+ sub = parser.add_subparsers(dest="command", required=True)
95
+ run = sub.add_parser("run", help="run scenarios against an agent")
96
+ run.add_argument("--agent", required=True, help="agent config (YAML)")
97
+ run.add_argument("--scenarios", required=True, help="a scenario file or a directory of them")
98
+ run.add_argument("--repeat", type=int, default=1, help="runs per scenario (models are not deterministic)")
99
+ rc = sub.add_parser("recheck", help="evaluate the checks again on saved runs, without the model")
100
+ rc.add_argument("--agent", required=True, help="agent config (YAML)")
101
+ rc.add_argument("--scenarios", required=True, help="the (possibly edited) scenarios")
102
+ rc.add_argument("--from-json", required=True, help="results written by `acta run --json`")
103
+ for p in (run, rc):
104
+ p.add_argument("--json", help="write the full results as JSON")
105
+ p.add_argument("--html", help="write a self-contained HTML report")
106
+ p.add_argument("--theme", choices=["dark", "light"], default="dark", help="report theme (default: dark)")
107
+ rep = sub.add_parser("report", help="render the HTML report from a results JSON")
108
+ rep.add_argument("--json", required=True, help="results written by `acta run --json`")
109
+ rep.add_argument("--html", required=True, help="where to write the report")
110
+ rep.add_argument("--theme", choices=["dark", "light"], default="dark", help="report theme (default: dark)")
111
+ args = parser.parse_args(argv)
112
+
113
+ if args.command == "report":
114
+ try:
115
+ data = json.loads(Path(args.json).read_text(encoding="utf-8"))
116
+ html = render_html(data, theme=args.theme)
117
+ except (OSError, json.JSONDecodeError, ReportError) as e:
118
+ print(f"cannot render {args.json}: {e}", file=sys.stderr)
119
+ return 2
120
+ Path(args.html).write_text(html, encoding="utf-8")
121
+ print(f"report: {args.html}")
122
+ return 0
123
+
124
+ try:
125
+ agent = load_agent(args.agent)
126
+ scenarios = load_scenarios(args.scenarios, agent)
127
+ except ConfigError as e:
128
+ print(f"config error: {e}", file=sys.stderr)
129
+ return 2
130
+
131
+ results = []
132
+ if args.command == "recheck":
133
+ try:
134
+ old = validate(json.loads(Path(args.from_json).read_text(encoding="utf-8")))
135
+ saved = {s["name"]: s for s in old["scenarios"]}
136
+ except (OSError, json.JSONDecodeError, KeyError, TypeError, ReportError) as e:
137
+ print(f"cannot read {args.from_json}: {e}", file=sys.stderr)
138
+ return 2
139
+ missing = [s.name for s in scenarios if s.name not in saved]
140
+ if missing:
141
+ print(f"no saved runs for: {', '.join(missing)}", file=sys.stderr)
142
+ return 2
143
+ results = [recheck(s, agent, saved[s.name], str(old.get("agent") or "")) for s in scenarios]
144
+ else:
145
+ results = [run_scenario(agent, s, repeat=max(1, args.repeat)) for s in scenarios]
146
+
147
+ _print(results)
148
+ data = results_to_dict(results)
149
+ if args.json:
150
+ Path(args.json).write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
151
+ if args.html:
152
+ Path(args.html).write_text(render_html(data, theme=args.theme), encoding="utf-8")
153
+ print(f"report: {args.html}")
154
+ return _exit_code(results)
155
+
156
+
157
+ if __name__ == "__main__":
158
+ sys.exit(main())