agent-blackbox-cli 0.3.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.
Files changed (43) hide show
  1. agent_blackbox_cli-0.3.0.dist-info/METADATA +623 -0
  2. agent_blackbox_cli-0.3.0.dist-info/RECORD +43 -0
  3. agent_blackbox_cli-0.3.0.dist-info/WHEEL +5 -0
  4. agent_blackbox_cli-0.3.0.dist-info/entry_points.txt +2 -0
  5. agent_blackbox_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. agent_blackbox_cli-0.3.0.dist-info/top_level.txt +1 -0
  7. blackbox/__init__.py +61 -0
  8. blackbox/__main__.py +6 -0
  9. blackbox/adapters/__init__.py +0 -0
  10. blackbox/adapters/_linking.py +31 -0
  11. blackbox/adapters/base.py +38 -0
  12. blackbox/adapters/claude_code.py +341 -0
  13. blackbox/adapters/codex.py +318 -0
  14. blackbox/adapters/labelled_turns.py +371 -0
  15. blackbox/adapters/registry.py +30 -0
  16. blackbox/aggregate.py +119 -0
  17. blackbox/analysis.py +325 -0
  18. blackbox/bench.py +466 -0
  19. blackbox/cli.py +405 -0
  20. blackbox/cost.py +138 -0
  21. blackbox/describe.py +116 -0
  22. blackbox/detectors/__init__.py +32 -0
  23. blackbox/detectors/base.py +83 -0
  24. blackbox/detectors/context_bloat.py +137 -0
  25. blackbox/detectors/contradictions.py +180 -0
  26. blackbox/detectors/error_clusters.py +114 -0
  27. blackbox/detectors/retry_loops.py +98 -0
  28. blackbox/detectors/stalls.py +117 -0
  29. blackbox/detectors/thrash.py +86 -0
  30. blackbox/diff.py +123 -0
  31. blackbox/discover.py +189 -0
  32. blackbox/events.py +163 -0
  33. blackbox/graph.py +150 -0
  34. blackbox/guard.py +528 -0
  35. blackbox/guard_cli.py +349 -0
  36. blackbox/pricing.py +137 -0
  37. blackbox/py.typed +0 -0
  38. blackbox/replay.py +65 -0
  39. blackbox/report/__init__.py +0 -0
  40. blackbox/report/html.py +375 -0
  41. blackbox/report/text.py +287 -0
  42. blackbox/store.py +215 -0
  43. blackbox/toolinfo.py +336 -0
@@ -0,0 +1,83 @@
1
+ """Finding model and detector configuration.
2
+
3
+ Every detector is a pure function of the graph. No model calls, no network, no
4
+ clock reads -- which is what makes the whole report replayable (see
5
+ ``blackbox.replay``). A detector that needed an LLM to decide whether
6
+ something was a retry loop would make this tool unverifiable, and an
7
+ unverifiable analysis of an unverifiable agent is worth nothing.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ HIGH = "high"
16
+ MEDIUM = "medium"
17
+ LOW = "low"
18
+
19
+ _SEVERITY_RANK = {HIGH: 0, MEDIUM: 1, LOW: 2}
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Finding:
24
+ """One thing worth a human's attention, with the evidence to check it."""
25
+
26
+ detector: str
27
+ severity: str
28
+ title: str
29
+ detail: str
30
+ key: str
31
+ branch: str = "main"
32
+ count: int = 1
33
+ evidence: tuple[str, ...] = ()
34
+ metrics: dict[str, Any] = field(default_factory=dict)
35
+
36
+ @property
37
+ def rank(self) -> int:
38
+ return _SEVERITY_RANK.get(self.severity, 9)
39
+
40
+ def sort_key(self) -> tuple:
41
+ """Total order over findings, independent of discovery order."""
42
+ return (self.rank, self.detector, self.branch, self.key)
43
+
44
+ def to_dict(self) -> dict[str, Any]:
45
+ return {
46
+ "detector": self.detector,
47
+ "severity": self.severity,
48
+ "title": self.title,
49
+ "detail": self.detail,
50
+ "key": self.key,
51
+ "branch": self.branch,
52
+ "count": self.count,
53
+ "evidence": list(self.evidence),
54
+ "metrics": {k: self.metrics[k] for k in sorted(self.metrics)},
55
+ }
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Config:
60
+ """Detector thresholds. Everything tunable lives here, nothing is hidden."""
61
+
62
+ stall_seconds: float = 60.0
63
+ idle_seconds: float = 900.0
64
+ retry_min_repeats: int = 3
65
+ retry_window: int = 12
66
+ thrash_min_edits: int = 4
67
+ thrash_window: int = 25
68
+ error_cluster_min: int = 2
69
+ bloat_min_tokens: int = 4_000
70
+ bloat_min_usd: float = 0.50
71
+
72
+ def to_dict(self) -> dict[str, Any]:
73
+ return {
74
+ "stall_seconds": self.stall_seconds,
75
+ "idle_seconds": self.idle_seconds,
76
+ "retry_min_repeats": self.retry_min_repeats,
77
+ "retry_window": self.retry_window,
78
+ "thrash_min_edits": self.thrash_min_edits,
79
+ "thrash_window": self.thrash_window,
80
+ "error_cluster_min": self.error_cluster_min,
81
+ "bloat_min_tokens": self.bloat_min_tokens,
82
+ "bloat_min_usd": self.bloat_min_usd,
83
+ }
@@ -0,0 +1,137 @@
1
+ """Find the tool results that made the rest of the run expensive.
2
+
3
+ Agent cost compounds in a way that is almost invisible turn by turn. A tool
4
+ result is not paid for once: it sits in the context window and is re-sent with
5
+ every later turn. A 20,000-token log dumped at step 40 of a 400-turn session
6
+ is billed roughly 360 more times as cached input before the run ends.
7
+
8
+ So the expensive moment is rarely the expensive-looking turn. This detector
9
+ walks the graph for large tool results and estimates what each one cost
10
+ *downstream*: its size multiplied by the model turns that followed it in the
11
+ same branch, priced at the cache-read rate.
12
+
13
+ Two honesty constraints, both surfaced in the finding text:
14
+
15
+ * Token counts are **estimated** from character length (~4 chars/token). This
16
+ module does not tokenise, and a wrong-looking precise number would be worse
17
+ than an openly approximate one.
18
+ * Where a trace records a compaction boundary, counting stops there: a result
19
+ dumped before the context was summarised is not re-sent afterwards. Where a
20
+ trace records no such boundary, the figure is an upper bound on a context
21
+ that is never cleared, and silent context editing would lower it.
22
+
23
+ Each downstream turn is priced at **its own** model's cache-read rate, not at
24
+ one rate for the whole run. A run that hands reading to a cheap subagent and
25
+ reasons on an expensive model is exactly the case where a single blended rate
26
+ is wrong in both directions, and it is also the case where someone is most
27
+ likely to be looking.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ from collections import Counter
33
+
34
+ from blackbox.detectors.base import HIGH, LOW, MEDIUM, Config, Finding
35
+ from blackbox.events import ASSISTANT_MESSAGE, TOOL_RESULT
36
+ from blackbox.graph import Graph
37
+ from blackbox.pricing import lookup
38
+
39
+ NAME = "context_bloat"
40
+
41
+ CHARS_PER_TOKEN = 4
42
+
43
+
44
+ def _dominant_model(graph: Graph) -> str | None:
45
+ counts = Counter(e.model for e in graph.events if e.model and not e.usage.is_empty())
46
+ return counts.most_common(1)[0][0] if counts else None
47
+
48
+
49
+ def run(graph: Graph, config: Config) -> list[Finding]:
50
+ findings: list[Finding] = []
51
+
52
+ for branch in graph.branches:
53
+ branch_events = [e for e in graph.events if e.branch == branch.name]
54
+ # (seq, cache-read rate) for every billable turn in this branch. A turn
55
+ # on an unpriced model contributes nothing rather than a guessed rate,
56
+ # which makes the estimate a floor instead of a fiction.
57
+ turns: list[tuple[int, float]] = []
58
+ unpriced_turns = 0
59
+ compaction_seqs = sorted(
60
+ e.seq for e in branch_events if "compaction" in e.flags
61
+ )
62
+ for event in branch_events:
63
+ if event.kind != ASSISTANT_MESSAGE or event.usage.is_empty():
64
+ continue
65
+ price = lookup(event.model)
66
+ if price is None:
67
+ unpriced_turns += 1
68
+ continue
69
+ turns.append((event.seq, price.read_rate()))
70
+ if not turns:
71
+ continue
72
+
73
+ for ev in branch_events:
74
+ if ev.kind != TOOL_RESULT or not ev.tool_output:
75
+ continue
76
+ est_tokens = len(ev.tool_output) // CHARS_PER_TOKEN
77
+ if est_tokens < config.bloat_min_tokens:
78
+ continue
79
+
80
+ # A result stops being re-sent once the context is compacted.
81
+ horizon = next((s for s in compaction_seqs if s > ev.seq), None)
82
+ downstream = [
83
+ rate
84
+ for seq, rate in turns
85
+ if seq > ev.seq and (horizon is None or seq < horizon)
86
+ ]
87
+ downstream_turns = len(downstream)
88
+ if downstream_turns <= 0:
89
+ continue
90
+
91
+ # Each later turn re-reads this result at that turn's own rate.
92
+ est_usd = est_tokens / 1e6 * sum(downstream)
93
+ if est_usd < config.bloat_min_usd:
94
+ continue
95
+
96
+ call = graph.by_uid.get(ev.parent_uid) if ev.parent_uid else None
97
+ tool = call.tool_name if call is not None else "tool"
98
+
99
+ severity = HIGH if est_usd >= config.bloat_min_usd * 10 else (
100
+ MEDIUM if est_usd >= config.bloat_min_usd * 3 else LOW
101
+ )
102
+
103
+ findings.append(
104
+ Finding(
105
+ detector=NAME,
106
+ severity=severity,
107
+ title=(
108
+ f"{tool} result added ~{est_tokens:,} tokens to context, "
109
+ f"~${est_usd:,.2f} downstream"
110
+ ),
111
+ detail=(
112
+ f"This {tool} result is roughly {est_tokens:,} tokens and landed "
113
+ f"with {downstream_turns} model turns still to come, so it was "
114
+ f"re-sent as cached input about that many times — an estimated "
115
+ f"${est_usd:,.2f} after the fact, each turn priced at its own "
116
+ f"model's cache-read rate. Token counts are estimated from length, "
117
+ f"and context editing or compaction would lower the real figure, "
118
+ f"so treat this as an upper bound."
119
+ ),
120
+ key=f"{ev.seq:08d}",
121
+ branch=branch.name,
122
+ evidence=((call.uid,) if call is not None else ()) + (ev.uid,),
123
+ metrics={
124
+ "kind": "context_bloat",
125
+ "tool": tool,
126
+ "est_tokens": est_tokens,
127
+ "downstream_turns": downstream_turns,
128
+ "est_downstream_usd": round(est_usd, 4),
129
+ "unpriced_downstream_turns": unpriced_turns,
130
+ "compaction_bounded": horizon is not None,
131
+ "seq": ev.seq,
132
+ "estimated": True,
133
+ },
134
+ )
135
+ )
136
+
137
+ return findings
@@ -0,0 +1,180 @@
1
+ """Detect an agent acting on a stale or absent view of a file.
2
+
3
+ Two patterns, both of which produce confidently wrong edits:
4
+
5
+ * **Stale read** -- the same region of a file is read twice, the contents
6
+ differ, and nothing in the run wrote to it in between. Something outside the
7
+ agent moved under it (a build step, a formatter, another agent), so any
8
+ reasoning from the first read was already void.
9
+ * **Blind edit** -- a file is edited in place with no prior read *and no prior
10
+ write* in the same branch. The agent is changing text it has never seen.
11
+
12
+ Both rules were narrowed after running against real traces, where the naive
13
+ versions were wrong essentially every time:
14
+
15
+ * A ``Read`` can take ``offset`` and ``limit``. Reading lines 1-100 and then
16
+ 101-200 returns different bytes from an unchanged file, so comparisons are
17
+ keyed by the region read, never by path alone. Without this the detector
18
+ reports a file as changing underneath an agent that merely paged through it.
19
+ * ``Write`` establishes knowledge. An agent that created a file knows its
20
+ contents as surely as if it had read them, so a later in-place edit is not
21
+ blind. Without this, every file an agent builds from scratch and then tweaks
22
+ is reported as a blind edit.
23
+ * **Reading through the shell counts.** ``sed -n '1,200p' src/app.js`` is a
24
+ read. Ignoring it reported 84 of 84 Codex blind edits wrongly, because that
25
+ agent inspects files with shell commands rather than a file tool.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from dataclasses import dataclass
31
+
32
+ from blackbox.detectors.base import HIGH, MEDIUM, Config, Finding
33
+ from blackbox.events import TOOL_CALL
34
+ from blackbox.graph import Graph
35
+ from blackbox import toolinfo
36
+
37
+ NAME = "contradiction"
38
+
39
+ READ = toolinfo.READ
40
+ WRITE = toolinfo.WRITE
41
+ EDIT = toolinfo.EDIT
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class _Entry:
46
+ seq: int
47
+ kind: str
48
+ digest: str
49
+ uid: str
50
+ region: tuple[object, object]
51
+
52
+
53
+ def _region(tool_input: dict) -> tuple[object, object]:
54
+ """The slice of a file a read covers. ``(None, None)`` means the whole file."""
55
+ return (tool_input.get("offset"), tool_input.get("limit"))
56
+
57
+
58
+ def run(graph: Graph, config: Config) -> list[Finding]:
59
+ findings: list[Finding] = []
60
+
61
+ for branch in graph.branches:
62
+ history: dict[str, list[_Entry]] = {}
63
+ # (seq, path) for every file the agent inspected through a shell.
64
+ shell_seen: list[tuple[int, str]] = []
65
+
66
+ for ev in graph.events:
67
+ if ev.branch != branch.name or ev.kind != TOOL_CALL:
68
+ continue
69
+
70
+ for seen in toolinfo.shell_read_paths(ev.tool_name, ev.tool_input):
71
+ shell_seen.append((ev.seq, seen))
72
+
73
+ for path, kind in toolinfo.file_operations(ev.tool_name, ev.tool_input):
74
+ if kind == READ:
75
+ result = graph.result_for(ev)
76
+ if result is None:
77
+ continue
78
+ history.setdefault(path, []).append(
79
+ _Entry(ev.seq, READ, result.output_digest(), ev.uid, _region(ev.tool_input))
80
+ )
81
+ else:
82
+ history.setdefault(path, []).append(
83
+ _Entry(ev.seq, kind, "", ev.uid, (None, None))
84
+ )
85
+
86
+ for path in sorted(history):
87
+ entries = history[path]
88
+ findings.extend(_stale_reads(path, entries, branch.name))
89
+ findings.extend(_blind_edits(path, entries, branch.name, shell_seen))
90
+
91
+ return findings
92
+
93
+
94
+ def _stale_reads(path: str, entries: list[_Entry], branch: str) -> list[Finding]:
95
+ """A region re-read with different bytes, with no write in between."""
96
+ found: list[Finding] = []
97
+ last_read: dict[tuple[object, object], _Entry] = {}
98
+
99
+ for entry in entries:
100
+ if entry.kind in (WRITE, EDIT):
101
+ # The run changed the file, so a differing re-read is expected.
102
+ last_read.clear()
103
+ continue
104
+
105
+ previous = last_read.get(entry.region)
106
+ if previous is not None and previous.digest != entry.digest:
107
+ found.append(
108
+ Finding(
109
+ detector=NAME,
110
+ severity=HIGH,
111
+ title=f"{_short(path)} changed between two reads with no write",
112
+ detail=(
113
+ f"{path} was read at step {previous.seq} and again at step "
114
+ f"{entry.seq} — the same region, different contents, and the run "
115
+ f"never wrote to it in between. Something outside the agent "
116
+ f"changed the file, so anything concluded from the first read "
117
+ f"was already stale."
118
+ ),
119
+ key=f"stale:{path}:{entry.seq:08d}",
120
+ branch=branch,
121
+ evidence=(previous.uid, entry.uid),
122
+ metrics={
123
+ "path": path,
124
+ "kind": "stale_read",
125
+ "first_seq": previous.seq,
126
+ "second_seq": entry.seq,
127
+ "region_offset": entry.region[0],
128
+ "region_limit": entry.region[1],
129
+ },
130
+ )
131
+ )
132
+ last_read[entry.region] = entry
133
+
134
+ return found
135
+
136
+
137
+ def _blind_edits(
138
+ path: str,
139
+ entries: list[_Entry],
140
+ branch: str,
141
+ shell_seen: list[tuple[int, str]],
142
+ ) -> list[Finding]:
143
+ """An in-place edit of a file the agent has not seen by any route."""
144
+ knows = False
145
+ for entry in entries:
146
+ if not knows and any(
147
+ seq < entry.seq and toolinfo.paths_overlap(path, seen) for seq, seen in shell_seen
148
+ ):
149
+ knows = True
150
+ if entry.kind in (READ, WRITE):
151
+ # Reading it or having authored it both count as knowing it.
152
+ knows = True
153
+ continue
154
+ if entry.kind != EDIT:
155
+ continue
156
+ if knows:
157
+ return []
158
+ return [
159
+ Finding(
160
+ detector=NAME,
161
+ severity=MEDIUM,
162
+ title=f"{_short(path)} edited with no prior read",
163
+ detail=(
164
+ f"{path} was edited in place at step {entry.seq} without being read "
165
+ f"or written anywhere in this branch, so the agent changed content "
166
+ f"it has never seen. A read in an earlier session would not appear "
167
+ f"in this trace."
168
+ ),
169
+ key=f"blind:{path}:{entry.seq:08d}",
170
+ branch=branch,
171
+ evidence=(entry.uid,),
172
+ metrics={"path": path, "kind": "blind_write", "seq": entry.seq},
173
+ )
174
+ ]
175
+ return []
176
+
177
+
178
+ def _short(path: str, keep: int = 2) -> str:
179
+ parts = [p for p in path.split("/") if p]
180
+ return "/".join(parts[-keep:]) if parts else path
@@ -0,0 +1,114 @@
1
+ """Group failed tool calls by what actually went wrong.
2
+
3
+ A run with 88 failures is not 88 problems. Error text is normalised -- paths,
4
+ numbers, hex ids and quoted fragments removed -- so the same underlying failure
5
+ collapses into one cluster with a count, which is the form a human can act on.
6
+
7
+ Three rules keep the clusters meaningful, each added after the naive version
8
+ produced one useless bucket on real traces:
9
+
10
+ * **A bare exit-code line is not an error message.** Shell failures arrive as
11
+ ``Exit code 1`` followed by the real output. Taking line one collapses every
12
+ unrelated shell failure in the run into ``Exit code <n>``.
13
+ * **The error is usually at the end.** Output is scanned from the bottom for a
14
+ line that actually reads like a failure, falling back to the first content
15
+ line when nothing does.
16
+ * **What ran is part of the identity.** A ``pytest`` failure and an ``npm``
17
+ failure are different problems even when their text normalises the same, so
18
+ the program is part of the cluster key.
19
+
20
+ Declined tool calls -- a human saying no -- are excluded entirely. They are
21
+ not failures, and they are numerous enough to drown real ones.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import re
27
+
28
+ from blackbox.detectors.base import HIGH, LOW, MEDIUM, Config, Finding
29
+ from blackbox.events import TOOL_RESULT
30
+ from blackbox.graph import Graph
31
+ from blackbox.toolinfo import program_hint
32
+
33
+ NAME = "error_cluster"
34
+
35
+ _EXIT_CODE = re.compile(r"^(exit code|command exited with code|exit status)\s*\d+\s*$", re.I)
36
+ _ERRORISH = re.compile(
37
+ r"(error|exception|failed|failure|fatal|traceback|no such|not found|cannot|can't"
38
+ r"|unable|denied|refused|invalid|unexpected|missing|assert|bad |timed out)",
39
+ re.I,
40
+ )
41
+ _PATH = re.compile(r"(/[\w.\-]+){2,}")
42
+ _NUM = re.compile(r"\b\d+\b")
43
+ _HEX = re.compile(r"\b[0-9a-f]{8,}\b", re.I)
44
+ _QUOTED = re.compile(r"'[^']{0,80}'|\"[^\"]{0,80}\"")
45
+ _WS = re.compile(r"\s+")
46
+
47
+
48
+ def signature(text: str) -> str:
49
+ """Collapse an error message to its invariant shape."""
50
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
51
+ if not lines:
52
+ return "(empty error)"
53
+
54
+ start = 1 if _EXIT_CODE.match(lines[0]) else 0
55
+ body = lines[start:] or lines
56
+
57
+ # The useful line is usually the last one that reads like a failure.
58
+ chosen = body[0]
59
+ for line in reversed(body):
60
+ if _ERRORISH.search(line):
61
+ chosen = line
62
+ break
63
+
64
+ s = _QUOTED.sub("'_'", chosen)
65
+ s = _PATH.sub("<path>", s)
66
+ s = _HEX.sub("<hex>", s)
67
+ s = _NUM.sub("<n>", s)
68
+ s = _WS.sub(" ", s).strip()
69
+ return s[:120]
70
+
71
+
72
+ def run(graph: Graph, config: Config) -> list[Finding]:
73
+ clusters: dict[tuple[str, str, str], list[str]] = {}
74
+ seqs: dict[tuple[str, str, str], int] = {}
75
+
76
+ for ev in graph.events:
77
+ if ev.kind != TOOL_RESULT or ev.tool_ok is not False:
78
+ continue
79
+ if "declined" in ev.flags:
80
+ continue # a human said no; that is not a tool failure
81
+ parent = graph.by_uid.get(ev.parent_uid) if ev.parent_uid else None
82
+ tool_name = parent.tool_name if parent is not None else None
83
+ program = program_hint(tool_name, parent.tool_input if parent is not None else {})
84
+ label = f"{tool_name or '?'}({program})" if program else (tool_name or "?")
85
+ key = (ev.branch, label, signature(ev.tool_output))
86
+ clusters.setdefault(key, []).append(ev.uid)
87
+ seqs.setdefault(key, ev.seq)
88
+
89
+ findings: list[Finding] = []
90
+ for key in sorted(clusters):
91
+ branch, label, sig = key
92
+ uids = clusters[key]
93
+ if len(uids) < config.error_cluster_min:
94
+ continue
95
+ severity = HIGH if len(uids) >= 10 else MEDIUM if len(uids) >= 4 else LOW
96
+ findings.append(
97
+ Finding(
98
+ detector=NAME,
99
+ severity=severity,
100
+ title=f"{label} failed {len(uids)}x: {sig[:60]}",
101
+ detail=f"{len(uids)} {label} calls failed with the same error shape: {sig}",
102
+ key=f"{label}:{sig}",
103
+ branch=branch,
104
+ count=len(uids),
105
+ evidence=tuple(uids),
106
+ metrics={
107
+ "failures": len(uids),
108
+ "tool": label,
109
+ "signature": sig,
110
+ "first_seq": seqs[key],
111
+ },
112
+ )
113
+ )
114
+ return findings
@@ -0,0 +1,98 @@
1
+ """Detect an agent repeating the same call and getting nowhere.
2
+
3
+ Identical inputs are matched on a digest of the call's *meaningful* arguments,
4
+ so two `Bash` calls running the same command count as repeats even when their
5
+ prose descriptions differ. Repeats only count when they fall within a sliding
6
+ window of tool calls -- running the same test command at the start and end of
7
+ a long session is normal; running it four times in six calls is a loop.
8
+
9
+ Repeating a call is not always retrying. Taking the same screenshot eight
10
+ times is polling, and advancing a task list with the same payload ten times is
11
+ bookkeeping: in both the input is identical by design. Those are reported,
12
+ because the count is still worth seeing, but at low severity and never as
13
+ "the agent learned nothing".
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from blackbox.detectors.base import HIGH, LOW, MEDIUM, Config, Finding
19
+ from blackbox.graph import Graph
20
+ from blackbox.toolinfo import repeats_by_design
21
+
22
+ NAME = "retry_loop"
23
+
24
+
25
+ def run(graph: Graph, config: Config) -> list[Finding]:
26
+ findings: list[Finding] = []
27
+
28
+ for branch in graph.branches:
29
+ calls = graph.tool_calls(branch.name)
30
+ positions: dict[tuple[str, str], list[int]] = {}
31
+ for index, call in enumerate(calls):
32
+ key = (call.tool_name or "?", call.input_digest())
33
+ positions.setdefault(key, []).append(index)
34
+
35
+ for key in sorted(positions):
36
+ indices = positions[key]
37
+ if len(indices) < config.retry_min_repeats:
38
+ continue
39
+
40
+ # Split into clusters of repeats that are close together.
41
+ cluster = [indices[0]]
42
+ clusters = []
43
+ for idx in indices[1:]:
44
+ if idx - cluster[-1] <= config.retry_window:
45
+ cluster.append(idx)
46
+ else:
47
+ clusters.append(cluster)
48
+ cluster = [idx]
49
+ clusters.append(cluster)
50
+
51
+ tool_name, digest = key
52
+ for cluster in clusters:
53
+ if len(cluster) < config.retry_min_repeats:
54
+ continue
55
+ events = [calls[i] for i in cluster]
56
+ span = cluster[-1] - cluster[0] + 1
57
+ expected = repeats_by_design(tool_name, events[0].tool_input)
58
+
59
+ if expected:
60
+ severity = LOW
61
+ title = f"{tool_name} repeated {len(cluster)}x with identical input"
62
+ detail = (
63
+ f"The same {tool_name} call ran {len(cluster)} times within "
64
+ f"{span} tool calls. This tool either observes or records "
65
+ f"progress, so identical input is expected by design — it is "
66
+ f"not a retry loop."
67
+ )
68
+ else:
69
+ severity = HIGH if len(cluster) >= 5 else MEDIUM
70
+ title = f"{tool_name} called {len(cluster)}x with identical input"
71
+ detail = (
72
+ f"The same {tool_name} call ran {len(cluster)} times within "
73
+ f"{span} tool calls. Identical input means the agent learned "
74
+ f"nothing between attempts."
75
+ )
76
+
77
+ findings.append(
78
+ Finding(
79
+ detector=NAME,
80
+ severity=severity,
81
+ title=title,
82
+ detail=detail,
83
+ key=f"{tool_name}:{digest}:{events[0].seq}",
84
+ branch=branch.name,
85
+ count=len(cluster),
86
+ evidence=tuple(e.uid for e in events),
87
+ metrics={
88
+ "repeats": len(cluster),
89
+ "window_span": span,
90
+ "tool": tool_name,
91
+ "kind": "expected_repeat" if expected else "retry_loop",
92
+ "first_seq": events[0].seq,
93
+ "last_seq": events[-1].seq,
94
+ },
95
+ )
96
+ )
97
+
98
+ return findings