driftcatch 0.1.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.
- driftcatch/__init__.py +146 -0
- driftcatch/_name.py +12 -0
- driftcatch/agentio.py +246 -0
- driftcatch/bisect.py +160 -0
- driftcatch/cli.py +1035 -0
- driftcatch/config.py +166 -0
- driftcatch/contracts.py +508 -0
- driftcatch/coverage.py +165 -0
- driftcatch/determinism.py +282 -0
- driftcatch/errors.py +149 -0
- driftcatch/intercept/__init__.py +8 -0
- driftcatch/intercept/http.py +400 -0
- driftcatch/intercept/tools.py +187 -0
- driftcatch/invariants.py +646 -0
- driftcatch/match/__init__.py +60 -0
- driftcatch/match/base.py +161 -0
- driftcatch/match/keys.py +61 -0
- driftcatch/match/normalizers.py +130 -0
- driftcatch/match/registry.py +82 -0
- driftcatch/match/resolve.py +195 -0
- driftcatch/match/strategies.py +146 -0
- driftcatch/mcp_server.py +417 -0
- driftcatch/providers.py +227 -0
- driftcatch/py.typed +0 -0
- driftcatch/pytest_plugin.py +170 -0
- driftcatch/record.py +162 -0
- driftcatch/recording/__init__.py +57 -0
- driftcatch/recording/fingerprint.py +75 -0
- driftcatch/recording/io.py +257 -0
- driftcatch/recording/schema.py +261 -0
- driftcatch/redact.py +127 -0
- driftcatch/replay.py +152 -0
- driftcatch/review.py +102 -0
- driftcatch/session.py +126 -0
- driftcatch/suite.py +135 -0
- driftcatch/take.py +632 -0
- driftcatch/trajectory.py +208 -0
- driftcatch/ui/__init__.py +15 -0
- driftcatch/ui/server.py +245 -0
- driftcatch/ui/templates/app.html +346 -0
- driftcatch/whatif.py +65 -0
- driftcatch-0.1.0.dist-info/METADATA +456 -0
- driftcatch-0.1.0.dist-info/RECORD +46 -0
- driftcatch-0.1.0.dist-info/WHEEL +4 -0
- driftcatch-0.1.0.dist-info/entry_points.txt +5 -0
- driftcatch-0.1.0.dist-info/licenses/LICENSE +21 -0
driftcatch/cli.py
ADDED
|
@@ -0,0 +1,1035 @@
|
|
|
1
|
+
"""The ``drift`` command line interface.
|
|
2
|
+
|
|
3
|
+
Commands split into two groups, and the difference is honest rather than hidden:
|
|
4
|
+
|
|
5
|
+
* **Read-only commands** (``status``, ``coverage``, ``diff``, ``bisect``,
|
|
6
|
+
``audit``, ``scan``, ``review``) work entirely on recording files.
|
|
7
|
+
* **Commands that need to run your agent** (``record``, ``check``) delegate to
|
|
8
|
+
pytest, because the agent lives in your test code - the CLI has no way to call
|
|
9
|
+
it directly, and pretending otherwise would just produce a broken command.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import typer
|
|
20
|
+
from rich.console import Console
|
|
21
|
+
from rich.panel import Panel
|
|
22
|
+
from rich.syntax import Syntax
|
|
23
|
+
from rich.table import Table
|
|
24
|
+
|
|
25
|
+
from driftcatch._name import CLI_NAME, ENV_PREFIX
|
|
26
|
+
from driftcatch.agentio import (
|
|
27
|
+
AGENTS_SECTION,
|
|
28
|
+
ExitCode,
|
|
29
|
+
capabilities,
|
|
30
|
+
emit,
|
|
31
|
+
fail,
|
|
32
|
+
payload,
|
|
33
|
+
)
|
|
34
|
+
from driftcatch.bisect import bisect as run_bisect
|
|
35
|
+
from driftcatch.bisect import render as render_bisect
|
|
36
|
+
from driftcatch.config import Config, get_config
|
|
37
|
+
from driftcatch.contracts import extract as extract_contracts
|
|
38
|
+
from driftcatch.contracts import render as render_contracts
|
|
39
|
+
from driftcatch.contracts import to_json as contracts_to_json
|
|
40
|
+
from driftcatch.coverage import analyse as analyse_coverage
|
|
41
|
+
from driftcatch.coverage import render as render_coverage
|
|
42
|
+
from driftcatch.errors import DriftCatchError, RecordingNotApproved, RecordingNotFound
|
|
43
|
+
from driftcatch.invariants import (
|
|
44
|
+
DEFAULT_MIN_SUPPORT,
|
|
45
|
+
invariants_path,
|
|
46
|
+
load_invariants,
|
|
47
|
+
save_invariants,
|
|
48
|
+
)
|
|
49
|
+
from driftcatch.invariants import merge as merge_invariants
|
|
50
|
+
from driftcatch.invariants import mine as mine_invariants
|
|
51
|
+
from driftcatch.invariants import render as render_invariants
|
|
52
|
+
from driftcatch.match.keys import event_payload, key_for
|
|
53
|
+
from driftcatch.match.normalizers import apply_normalizers
|
|
54
|
+
from driftcatch.recording.io import (
|
|
55
|
+
list_recordings,
|
|
56
|
+
load_recording,
|
|
57
|
+
previous_path,
|
|
58
|
+
recording_path,
|
|
59
|
+
restore_previous,
|
|
60
|
+
save_recording,
|
|
61
|
+
)
|
|
62
|
+
from driftcatch.recording.schema import LLMEvent, Recording, Status, ToolEvent
|
|
63
|
+
from driftcatch.redact import find_secrets
|
|
64
|
+
from driftcatch.review import approve as approve_recording
|
|
65
|
+
from driftcatch.review import reject as reject_recording
|
|
66
|
+
from driftcatch.trajectory import diff as diff_trajectory
|
|
67
|
+
from driftcatch.trajectory import render as render_trajectory
|
|
68
|
+
|
|
69
|
+
app = typer.Typer(
|
|
70
|
+
name=CLI_NAME,
|
|
71
|
+
help="Catch the moment your AI agent's behaviour changes.",
|
|
72
|
+
no_args_is_help=True,
|
|
73
|
+
add_completion=False,
|
|
74
|
+
)
|
|
75
|
+
console = Console()
|
|
76
|
+
|
|
77
|
+
_STATUS_STYLE = {
|
|
78
|
+
Status.APPROVED: "green",
|
|
79
|
+
Status.PENDING: "yellow",
|
|
80
|
+
Status.REJECTED: "red",
|
|
81
|
+
Status.STALE: "magenta",
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
DirOption = typer.Option(None, "--recordings-dir", "-d", help="Directory of recording files.")
|
|
85
|
+
JsonOption = typer.Option(
|
|
86
|
+
False,
|
|
87
|
+
"--json",
|
|
88
|
+
help="Emit machine-readable JSON on stdout. For coding agents and CI.",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _config(recordings_dir: Path | None) -> Config:
|
|
93
|
+
cfg = get_config()
|
|
94
|
+
if recordings_dir is not None:
|
|
95
|
+
cfg = cfg.merged(recordings_dir=recordings_dir)
|
|
96
|
+
return cfg
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _load(name: str, cfg: Config) -> Recording:
|
|
100
|
+
return load_recording(recording_path(name, cfg.recordings_dir))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
#: Exceptions whose exit code the CLI documents. Mapping here rather than at
|
|
104
|
+
#: each call site is what keeps the contract consistent: every command that
|
|
105
|
+
#: funnels a DriftCatchError through `_die` gets the right code for free, and
|
|
106
|
+
#: a command cannot quietly report "not found" as a generic error.
|
|
107
|
+
_EXIT_FOR: dict[type[BaseException], ExitCode] = {
|
|
108
|
+
RecordingNotFound: ExitCode.NOT_FOUND,
|
|
109
|
+
RecordingNotApproved: ExitCode.NOT_APPROVED,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _exit_code_for(exc: BaseException) -> ExitCode:
|
|
114
|
+
for kind, code in _EXIT_FOR.items():
|
|
115
|
+
if isinstance(exc, kind):
|
|
116
|
+
return code
|
|
117
|
+
return ExitCode.ERROR
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _die(message: str, *, code: ExitCode = ExitCode.ERROR) -> None:
|
|
121
|
+
console.print(f"[red]error[/red] {message}")
|
|
122
|
+
raise typer.Exit(code=int(code))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _die_from(exc: BaseException) -> None:
|
|
126
|
+
"""Report a library error with the exit code its type promises."""
|
|
127
|
+
_die(str(exc), code=_exit_code_for(exc))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# --------------------------------------------------------------- version
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@app.command()
|
|
134
|
+
def version() -> None:
|
|
135
|
+
"""Print the installed version."""
|
|
136
|
+
from driftcatch import __version__
|
|
137
|
+
|
|
138
|
+
console.print(f"{CLI_NAME} {__version__}")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@app.command()
|
|
142
|
+
def explain(as_json: bool = JsonOption) -> None:
|
|
143
|
+
"""Describe this tool to a coding agent: commands, exit codes, workflows.
|
|
144
|
+
|
|
145
|
+
A single discovery entrypoint, so an agent can work correctly without
|
|
146
|
+
having read any documentation.
|
|
147
|
+
"""
|
|
148
|
+
manifest = capabilities()
|
|
149
|
+
if as_json:
|
|
150
|
+
emit(payload("explain", manifest))
|
|
151
|
+
return
|
|
152
|
+
|
|
153
|
+
console.print(f"[bold]{manifest['name']}[/bold] - {manifest['purpose']}\n")
|
|
154
|
+
console.print("[bold]Key facts[/bold]")
|
|
155
|
+
for fact in manifest["key_facts"]:
|
|
156
|
+
console.print(f" - {fact}")
|
|
157
|
+
console.print("\n[bold]Not for[/bold]")
|
|
158
|
+
for item in manifest["not_for"]:
|
|
159
|
+
console.print(f" - {item}")
|
|
160
|
+
console.print("\n[bold]Cautions[/bold]")
|
|
161
|
+
for caution in manifest["cautions"]:
|
|
162
|
+
console.print(f" [yellow]![/yellow] {caution}")
|
|
163
|
+
console.print(
|
|
164
|
+
f"\nRun [bold]{CLI_NAME} explain --json[/bold] for the full machine-readable manifest."
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@app.command()
|
|
169
|
+
def mcp(recordings_dir: Path | None = DirOption) -> None:
|
|
170
|
+
"""Run as an MCP server, so a coding agent can call DriftCatch as tools.
|
|
171
|
+
|
|
172
|
+
Exposes reading and analysis only. Approving recordings, re-recording and
|
|
173
|
+
live runs are deliberately not available to an agent - approval means a
|
|
174
|
+
human confirmed the behaviour is correct, and that judgement is theirs.
|
|
175
|
+
"""
|
|
176
|
+
cfg = _config(recordings_dir)
|
|
177
|
+
try:
|
|
178
|
+
from driftcatch.mcp_server import serve as serve_mcp
|
|
179
|
+
except ImportError:
|
|
180
|
+
fail(
|
|
181
|
+
"mcp",
|
|
182
|
+
'the MCP server needs extra packages: pip install "driftcatch[mcp]"',
|
|
183
|
+
code=ExitCode.ERROR,
|
|
184
|
+
hint='pip install "driftcatch[mcp]"',
|
|
185
|
+
)
|
|
186
|
+
serve_mcp(str(cfg.recordings_dir))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@app.command()
|
|
190
|
+
def init(recordings_dir: Path | None = DirOption) -> None:
|
|
191
|
+
"""Set up DriftCatch in this project and print a starter test."""
|
|
192
|
+
cfg = _config(recordings_dir)
|
|
193
|
+
cfg.recordings_dir.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
|
|
195
|
+
gitignore = cfg.recordings_dir / ".gitignore"
|
|
196
|
+
if not gitignore.exists():
|
|
197
|
+
gitignore.write_text(
|
|
198
|
+
"# The archived copy of a re-recorded golden is a local safety net,\n"
|
|
199
|
+
"# not something to commit. Recordings themselves SHOULD be committed.\n"
|
|
200
|
+
".previous/\n",
|
|
201
|
+
encoding="utf-8",
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
# Teach whatever coding agent works in this repo how to use the tool.
|
|
205
|
+
# AGENTS.md is read by Cursor, Claude Code, Codex and others; appending
|
|
206
|
+
# rather than overwriting means an existing file is never clobbered.
|
|
207
|
+
agents_file = Path.cwd() / "AGENTS.md"
|
|
208
|
+
existing = agents_file.read_text(encoding="utf-8") if agents_file.exists() else ""
|
|
209
|
+
if "DriftCatch" not in existing:
|
|
210
|
+
separator = "\n\n" if existing.strip() else ""
|
|
211
|
+
agents_file.write_text(existing + separator + AGENTS_SECTION, encoding="utf-8")
|
|
212
|
+
console.print(f"[green]wrote[/green] agent instructions to {agents_file}")
|
|
213
|
+
else:
|
|
214
|
+
console.print("[dim]AGENTS.md already mentions DriftCatch, left alone[/dim]")
|
|
215
|
+
|
|
216
|
+
console.print(f"[green]ready[/green] recordings will live in {cfg.recordings_dir}\n")
|
|
217
|
+
snippet = """import driftcatch as drift
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@drift.tool # one line per tool you want captured
|
|
221
|
+
def lookup_order(order_id: int) -> dict:
|
|
222
|
+
return {"id": order_id, "total": 40}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def test_my_agent():
|
|
226
|
+
with drift.take("first_scenario") as take:
|
|
227
|
+
result = my_agent("do the thing")
|
|
228
|
+
|
|
229
|
+
take.assert_tools().called("lookup_order")
|
|
230
|
+
take.assert_trajectory().matches_golden()
|
|
231
|
+
"""
|
|
232
|
+
console.print(Panel(Syntax(snippet, "python", theme="ansi_dark"), expand=False))
|
|
233
|
+
console.print("Then:")
|
|
234
|
+
console.print(" 1. [bold]pytest[/bold] records a pending recording")
|
|
235
|
+
console.print(f" 2. [bold]{CLI_NAME} review[/bold] approve it -> golden")
|
|
236
|
+
console.print(" 3. [bold]pytest[/bold] replays: free, offline, deterministic")
|
|
237
|
+
console.print(f" 4. [bold]{CLI_NAME} coverage[/bold] see which behaviours are untested")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# ---------------------------------------------------------------- status
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@app.command()
|
|
244
|
+
def status(
|
|
245
|
+
recordings_dir: Path | None = DirOption,
|
|
246
|
+
as_json: bool = JsonOption,
|
|
247
|
+
require_approved: bool = typer.Option(
|
|
248
|
+
False,
|
|
249
|
+
"--require-approved",
|
|
250
|
+
help="Exit 7 if any recording is still pending. For CI.",
|
|
251
|
+
),
|
|
252
|
+
) -> None:
|
|
253
|
+
"""List every recording with its approval status and drift state."""
|
|
254
|
+
cfg = _config(recordings_dir)
|
|
255
|
+
recordings = list_recordings(cfg.recordings_dir)
|
|
256
|
+
pending = [r.name for r in recordings if r.status is Status.PENDING]
|
|
257
|
+
|
|
258
|
+
if as_json:
|
|
259
|
+
emit(
|
|
260
|
+
payload(
|
|
261
|
+
"status",
|
|
262
|
+
{
|
|
263
|
+
"recordings_dir": str(cfg.recordings_dir),
|
|
264
|
+
"total": len(recordings),
|
|
265
|
+
"counts": {
|
|
266
|
+
st.value: sum(1 for r in recordings if r.status is st) for st in Status
|
|
267
|
+
},
|
|
268
|
+
"pending": pending,
|
|
269
|
+
"recordings": [
|
|
270
|
+
{
|
|
271
|
+
"name": r.name,
|
|
272
|
+
"status": r.status.value,
|
|
273
|
+
"trajectory": r.trajectory.tools_called,
|
|
274
|
+
"events": len(r.events),
|
|
275
|
+
"tokens": r.meta.usage.total_tokens,
|
|
276
|
+
"approved_by": r.approved_by,
|
|
277
|
+
}
|
|
278
|
+
for r in recordings
|
|
279
|
+
],
|
|
280
|
+
},
|
|
281
|
+
)
|
|
282
|
+
)
|
|
283
|
+
if require_approved and pending:
|
|
284
|
+
raise typer.Exit(code=int(ExitCode.NOT_APPROVED))
|
|
285
|
+
return
|
|
286
|
+
|
|
287
|
+
if not recordings:
|
|
288
|
+
console.print(f"No recordings in [cyan]{cfg.recordings_dir}[/cyan].")
|
|
289
|
+
console.print(f"Record one by running your tests: [bold]{CLI_NAME} record[/bold]")
|
|
290
|
+
return
|
|
291
|
+
|
|
292
|
+
table = Table(title=f"Recordings in {cfg.recordings_dir}")
|
|
293
|
+
table.add_column("NAME")
|
|
294
|
+
table.add_column("STATUS")
|
|
295
|
+
table.add_column("BEHAVIOUR")
|
|
296
|
+
table.add_column("EVENTS", justify="right")
|
|
297
|
+
table.add_column("TOKENS", justify="right")
|
|
298
|
+
table.add_column("APPROVED BY")
|
|
299
|
+
|
|
300
|
+
for recording in recordings:
|
|
301
|
+
style = _STATUS_STYLE.get(recording.status, "white")
|
|
302
|
+
table.add_row(
|
|
303
|
+
recording.name,
|
|
304
|
+
f"[{style}]{recording.status.value}[/{style}]",
|
|
305
|
+
" -> ".join(recording.trajectory.tools_called) or "-",
|
|
306
|
+
str(len(recording.events)),
|
|
307
|
+
str(recording.meta.usage.total_tokens),
|
|
308
|
+
recording.approved_by or "-",
|
|
309
|
+
)
|
|
310
|
+
console.print(table)
|
|
311
|
+
|
|
312
|
+
stale = [r for r in recordings if r.status is Status.STALE]
|
|
313
|
+
if pending:
|
|
314
|
+
console.print(
|
|
315
|
+
f"\n[yellow]{len(pending)} recording(s) awaiting approval.[/yellow] "
|
|
316
|
+
f"Review them: [bold]{CLI_NAME} review[/bold]"
|
|
317
|
+
)
|
|
318
|
+
if stale:
|
|
319
|
+
console.print(
|
|
320
|
+
f"[magenta]{len(stale)} recording(s) stale.[/magenta] "
|
|
321
|
+
f"Re-verify: [bold]{CLI_NAME} check --live <name>[/bold]"
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
if require_approved and pending:
|
|
325
|
+
console.print(
|
|
326
|
+
f"\n[red]{len(pending)} recording(s) have not been approved: {', '.join(pending)}[/red]"
|
|
327
|
+
)
|
|
328
|
+
raise typer.Exit(code=int(ExitCode.NOT_APPROVED))
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# ------------------------------------------------------------------ show
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@app.command()
|
|
335
|
+
def show(name: str, recordings_dir: Path | None = DirOption) -> None:
|
|
336
|
+
"""Print a recording: its trajectory, then every event in order."""
|
|
337
|
+
cfg = _config(recordings_dir)
|
|
338
|
+
try:
|
|
339
|
+
recording = _load(name, cfg)
|
|
340
|
+
except DriftCatchError as exc:
|
|
341
|
+
_die_from(exc)
|
|
342
|
+
return
|
|
343
|
+
|
|
344
|
+
style = _STATUS_STYLE.get(recording.status, "white")
|
|
345
|
+
header = [
|
|
346
|
+
f"status: [{style}]{recording.status.value}[/{style}]",
|
|
347
|
+
f"recorded: {recording.created_at:%Y-%m-%d %H:%M}",
|
|
348
|
+
f"approved: {recording.approved_by or '-'}",
|
|
349
|
+
f"trajectory: {' -> '.join(recording.trajectory.tools_called) or '(no tools)'}",
|
|
350
|
+
f"usage: {recording.meta.usage.total_tokens} tokens",
|
|
351
|
+
]
|
|
352
|
+
console.print(Panel("\n".join(header), title=f"recording: {name}", expand=False))
|
|
353
|
+
|
|
354
|
+
for event in recording.events:
|
|
355
|
+
if isinstance(event, LLMEvent):
|
|
356
|
+
decided = ", ".join(event.decided) or "(text reply)"
|
|
357
|
+
console.print(f" [cyan]#{event.index} llm[/cyan] -> {decided}")
|
|
358
|
+
for message in event.request.messages:
|
|
359
|
+
role = str(message.get("role", "?"))
|
|
360
|
+
content = str(message.get("content", ""))[:100]
|
|
361
|
+
console.print(f" {role:<9} {content}")
|
|
362
|
+
if event.response and event.response.content:
|
|
363
|
+
console.print(f" [dim]reply[/dim] {event.response.content[:100]}")
|
|
364
|
+
elif isinstance(event, ToolEvent):
|
|
365
|
+
outcome = "[red]error[/red]" if event.error else "[green]ok[/green]"
|
|
366
|
+
console.print(f" [magenta]#{event.index} tool[/magenta] {event.name} {outcome}")
|
|
367
|
+
console.print(f" args {event.args}")
|
|
368
|
+
if event.error:
|
|
369
|
+
console.print(f" error {event.error.type}: {event.error.message}")
|
|
370
|
+
else:
|
|
371
|
+
console.print(f" result {str(event.result)[:100]}")
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
# ---------------------------------------------------------------- review
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
@app.command()
|
|
378
|
+
def review(
|
|
379
|
+
name: str | None = typer.Argument(None, help="Recording to review; omit for all pending."),
|
|
380
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Approve without prompting (CI)."),
|
|
381
|
+
by: str = typer.Option("cli", "--by", help="Who is approving."),
|
|
382
|
+
recordings_dir: Path | None = DirOption,
|
|
383
|
+
) -> None:
|
|
384
|
+
"""Inspect recordings and approve or reject them.
|
|
385
|
+
|
|
386
|
+
Nothing becomes golden without passing through here: recording states what
|
|
387
|
+
happened, a human states what is correct.
|
|
388
|
+
"""
|
|
389
|
+
cfg = _config(recordings_dir)
|
|
390
|
+
if name:
|
|
391
|
+
targets = [_load(name, cfg)]
|
|
392
|
+
else:
|
|
393
|
+
targets = [
|
|
394
|
+
r
|
|
395
|
+
for r in list_recordings(cfg.recordings_dir)
|
|
396
|
+
if r.status in {Status.PENDING, Status.STALE}
|
|
397
|
+
]
|
|
398
|
+
|
|
399
|
+
if not targets:
|
|
400
|
+
console.print("Nothing to review. Every recording is approved or rejected.")
|
|
401
|
+
return
|
|
402
|
+
|
|
403
|
+
for recording in targets:
|
|
404
|
+
show(recording.name, cfg.recordings_dir)
|
|
405
|
+
if yes:
|
|
406
|
+
approve_recording(recording.name, by=by, config=cfg)
|
|
407
|
+
console.print(f"[green]approved[/green] {recording.name}\n")
|
|
408
|
+
continue
|
|
409
|
+
|
|
410
|
+
choice = (
|
|
411
|
+
typer.prompt(f"[{recording.name}] (a)pprove / (r)eject / (s)kip", default="s")
|
|
412
|
+
.strip()
|
|
413
|
+
.lower()
|
|
414
|
+
)
|
|
415
|
+
if choice.startswith("a"):
|
|
416
|
+
approve_recording(recording.name, by=by, config=cfg)
|
|
417
|
+
console.print(f"[green]approved[/green] {recording.name}\n")
|
|
418
|
+
elif choice.startswith("r"):
|
|
419
|
+
reject_recording(recording.name, config=cfg)
|
|
420
|
+
console.print(f"[red]rejected[/red] {recording.name} - fix the agent, then re-record\n")
|
|
421
|
+
else:
|
|
422
|
+
console.print(f"[dim]skipped[/dim] {recording.name}\n")
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
# ------------------------------------------------------------------ diff
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
@app.command()
|
|
429
|
+
def diff(
|
|
430
|
+
name: str,
|
|
431
|
+
against: str | None = typer.Option(None, "--against", help="Compare with another recording."),
|
|
432
|
+
tolerance: str = typer.Option("tools+order", "--tolerance", "-t"),
|
|
433
|
+
recordings_dir: Path | None = DirOption,
|
|
434
|
+
) -> None:
|
|
435
|
+
"""Show the behaviour difference between two recordings."""
|
|
436
|
+
cfg = _config(recordings_dir)
|
|
437
|
+
try:
|
|
438
|
+
golden = _load(name, cfg)
|
|
439
|
+
except DriftCatchError as exc:
|
|
440
|
+
_die_from(exc)
|
|
441
|
+
return
|
|
442
|
+
|
|
443
|
+
if against is None:
|
|
444
|
+
console.print(
|
|
445
|
+
Panel(
|
|
446
|
+
" -> ".join(golden.trajectory.tools_called) or "(no tools)",
|
|
447
|
+
title=f"{name} behaviour",
|
|
448
|
+
expand=False,
|
|
449
|
+
)
|
|
450
|
+
)
|
|
451
|
+
console.print("Pass --against <other> to compare two recordings.")
|
|
452
|
+
return
|
|
453
|
+
|
|
454
|
+
candidate = _load(against, cfg)
|
|
455
|
+
result = diff_trajectory(golden.trajectory, candidate.trajectory, tolerance)
|
|
456
|
+
console.print(render_trajectory(result))
|
|
457
|
+
if not result.matched:
|
|
458
|
+
raise typer.Exit(code=1)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
# -------------------------------------------------------------- coverage
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
@app.command()
|
|
465
|
+
def coverage(
|
|
466
|
+
fail_under: float | None = typer.Option(
|
|
467
|
+
None, "--fail-under", help="Exit non-zero below this percentage (CI gate)."
|
|
468
|
+
),
|
|
469
|
+
badge: bool = typer.Option(False, "--badge", help="Print a README badge instead."),
|
|
470
|
+
recordings_dir: Path | None = DirOption,
|
|
471
|
+
as_json: bool = JsonOption,
|
|
472
|
+
) -> None:
|
|
473
|
+
"""Behaviour coverage: which of the agent's paths were ever tested."""
|
|
474
|
+
cfg = _config(recordings_dir)
|
|
475
|
+
recordings = list_recordings(cfg.recordings_dir)
|
|
476
|
+
if not recordings:
|
|
477
|
+
fail(
|
|
478
|
+
"coverage",
|
|
479
|
+
f"no recordings in {cfg.recordings_dir}",
|
|
480
|
+
code=ExitCode.NOT_FOUND,
|
|
481
|
+
json_mode=as_json,
|
|
482
|
+
hint=f"{CLI_NAME} record",
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
report = analyse_coverage(recordings)
|
|
486
|
+
|
|
487
|
+
if as_json:
|
|
488
|
+
passed = fail_under is None or report.percent >= fail_under
|
|
489
|
+
emit(
|
|
490
|
+
payload(
|
|
491
|
+
"coverage",
|
|
492
|
+
{
|
|
493
|
+
**report.model_dump(mode="json"),
|
|
494
|
+
"fail_under": fail_under,
|
|
495
|
+
"passed": passed,
|
|
496
|
+
},
|
|
497
|
+
ok=passed,
|
|
498
|
+
)
|
|
499
|
+
)
|
|
500
|
+
raise typer.Exit(code=0 if passed else int(ExitCode.GATE_FAILED))
|
|
501
|
+
|
|
502
|
+
if badge:
|
|
503
|
+
colour = (
|
|
504
|
+
"brightgreen" if report.percent >= 80 else "yellow" if report.percent >= 50 else "red"
|
|
505
|
+
)
|
|
506
|
+
label = "behaviour%20coverage"
|
|
507
|
+
url = f"https://img.shields.io/badge/{label}-{report.percent:.0f}%25-{colour}"
|
|
508
|
+
console.print(f"")
|
|
509
|
+
return
|
|
510
|
+
|
|
511
|
+
console.print(render_coverage(report))
|
|
512
|
+
|
|
513
|
+
if fail_under is not None and report.percent < fail_under:
|
|
514
|
+
console.print(
|
|
515
|
+
f"\n[red]coverage {report.percent:.1f}% is below the required {fail_under:.1f}%[/red]"
|
|
516
|
+
)
|
|
517
|
+
raise typer.Exit(code=int(ExitCode.GATE_FAILED))
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
@app.command()
|
|
521
|
+
def suggest(recordings_dir: Path | None = DirOption) -> None:
|
|
522
|
+
"""Propose scenarios that would close the biggest coverage gaps."""
|
|
523
|
+
cfg = _config(recordings_dir)
|
|
524
|
+
recordings = list_recordings(cfg.recordings_dir)
|
|
525
|
+
if not recordings:
|
|
526
|
+
_die(f"no recordings in {cfg.recordings_dir}")
|
|
527
|
+
return
|
|
528
|
+
|
|
529
|
+
report = analyse_coverage(recordings)
|
|
530
|
+
if not report.uncovered:
|
|
531
|
+
console.print("[green]Every declared behaviour already has coverage.[/green]")
|
|
532
|
+
return
|
|
533
|
+
|
|
534
|
+
example = recordings[0].name
|
|
535
|
+
console.print("[bold]Suggested next scenarios[/bold]\n")
|
|
536
|
+
for tool_name, tool in sorted(report.tools.items()):
|
|
537
|
+
if not tool.covered:
|
|
538
|
+
console.print(f" [yellow]{tool_name}[/yellow] has never been called.")
|
|
539
|
+
console.print(" Write a scenario that makes the agent choose it, then record it.\n")
|
|
540
|
+
elif not tool.error_path_covered:
|
|
541
|
+
console.print(f" [yellow]{tool_name}[/yellow] has never failed in a test.")
|
|
542
|
+
console.print(
|
|
543
|
+
f" No re-recording needed:\n"
|
|
544
|
+
f" [bold]{CLI_NAME} what-if {example} --fail-tool {tool_name}[/bold]\n"
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
# -------------------------------------------------------------- what-if
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
@app.command(name="what-if")
|
|
552
|
+
def what_if(
|
|
553
|
+
name: str,
|
|
554
|
+
fail_tool: str | None = typer.Option(None, "--fail-tool", help="Make this tool raise."),
|
|
555
|
+
recordings_dir: Path | None = DirOption,
|
|
556
|
+
) -> None:
|
|
557
|
+
"""Explain how to run a counterfactual against a recording.
|
|
558
|
+
|
|
559
|
+
The mutation has to run inside your test, because only your test knows how
|
|
560
|
+
to invoke the agent. This prints the snippet to drop in.
|
|
561
|
+
"""
|
|
562
|
+
cfg = _config(recordings_dir)
|
|
563
|
+
try:
|
|
564
|
+
_load(name, cfg)
|
|
565
|
+
except DriftCatchError as exc:
|
|
566
|
+
_die_from(exc)
|
|
567
|
+
return
|
|
568
|
+
|
|
569
|
+
tool_name = fail_tool or "<tool>"
|
|
570
|
+
snippet = f'''import driftcatch as drift
|
|
571
|
+
|
|
572
|
+
def test_{name}_handles_{tool_name}_failure():
|
|
573
|
+
with drift.take("{name}").what_if(
|
|
574
|
+
tool="{tool_name}", raises="TimeoutError"
|
|
575
|
+
) as take:
|
|
576
|
+
run_my_agent(...)
|
|
577
|
+
|
|
578
|
+
# assert the agent handled it, e.g.
|
|
579
|
+
take.assert_tools().called("escalate_to_human")
|
|
580
|
+
'''
|
|
581
|
+
console.print(
|
|
582
|
+
Panel(Syntax(snippet, "python", theme="ansi_dark"), title="what-if", expand=False)
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
# --------------------------------------------------------------- bisect
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
@app.command()
|
|
590
|
+
def bisect(
|
|
591
|
+
golden: str,
|
|
592
|
+
candidate: str | None = typer.Argument(None, help="Recording to compare against."),
|
|
593
|
+
previous: bool = typer.Option(
|
|
594
|
+
False, "--previous", help="Compare against the version replaced by the last re-record."
|
|
595
|
+
),
|
|
596
|
+
recordings_dir: Path | None = DirOption,
|
|
597
|
+
) -> None:
|
|
598
|
+
"""Attribute a behaviour change to the input that caused it."""
|
|
599
|
+
cfg = _config(recordings_dir)
|
|
600
|
+
|
|
601
|
+
if previous:
|
|
602
|
+
archived = previous_path(golden, cfg.recordings_dir)
|
|
603
|
+
if not archived.exists():
|
|
604
|
+
_die(
|
|
605
|
+
f"no previous version of {golden!r}. One is kept only after a re-record "
|
|
606
|
+
f"replaces an existing recording."
|
|
607
|
+
)
|
|
608
|
+
return
|
|
609
|
+
try:
|
|
610
|
+
# The archived copy is the old golden; the file on disk is the new take.
|
|
611
|
+
left = load_recording(archived)
|
|
612
|
+
right = _load(golden, cfg)
|
|
613
|
+
except DriftCatchError as exc:
|
|
614
|
+
_die_from(exc)
|
|
615
|
+
return
|
|
616
|
+
elif candidate is None:
|
|
617
|
+
_die("pass a second recording name, or use --previous")
|
|
618
|
+
return
|
|
619
|
+
else:
|
|
620
|
+
try:
|
|
621
|
+
left = _load(golden, cfg)
|
|
622
|
+
right = _load(candidate, cfg)
|
|
623
|
+
except DriftCatchError as exc:
|
|
624
|
+
_die_from(exc)
|
|
625
|
+
return
|
|
626
|
+
|
|
627
|
+
console.print(render_bisect(run_bisect(left, right)))
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
@app.command()
|
|
631
|
+
def learn(
|
|
632
|
+
approve: bool = typer.Option(False, "--approve", help="Enforce every mined invariant."),
|
|
633
|
+
min_support: int = typer.Option(
|
|
634
|
+
DEFAULT_MIN_SUPPORT, "--min-support", help="Runs a pattern needs before it counts."
|
|
635
|
+
),
|
|
636
|
+
recordings_dir: Path | None = DirOption,
|
|
637
|
+
as_json: bool = JsonOption,
|
|
638
|
+
) -> None:
|
|
639
|
+
"""Learn the rules your agent always follows, from approved recordings.
|
|
640
|
+
|
|
641
|
+
Mined rules are evidence, not truth - Daikon's own evaluation found about a
|
|
642
|
+
third of inferred invariants were wrong or irrelevant - so nothing is
|
|
643
|
+
enforced until a human approves it.
|
|
644
|
+
"""
|
|
645
|
+
cfg = _config(recordings_dir)
|
|
646
|
+
recordings = list_recordings(cfg.recordings_dir)
|
|
647
|
+
golden = [r for r in recordings if r.is_golden]
|
|
648
|
+
|
|
649
|
+
mined = mine_invariants(recordings, min_support=min_support)
|
|
650
|
+
path = invariants_path(cfg.recordings_dir)
|
|
651
|
+
mined = merge_invariants(mined, load_invariants(path))
|
|
652
|
+
|
|
653
|
+
if approve:
|
|
654
|
+
for invariant in mined:
|
|
655
|
+
invariant.approved = True
|
|
656
|
+
|
|
657
|
+
if mined:
|
|
658
|
+
save_invariants(mined, path)
|
|
659
|
+
|
|
660
|
+
if as_json:
|
|
661
|
+
emit(
|
|
662
|
+
payload(
|
|
663
|
+
"learn",
|
|
664
|
+
{
|
|
665
|
+
"corpus": len(golden),
|
|
666
|
+
"mined": len(mined),
|
|
667
|
+
"enforced": sum(1 for i in mined if i.approved),
|
|
668
|
+
"path": str(path),
|
|
669
|
+
"invariants": [
|
|
670
|
+
{
|
|
671
|
+
"key": i.key,
|
|
672
|
+
"kind": i.kind.value,
|
|
673
|
+
"description": i.description,
|
|
674
|
+
"support": i.support,
|
|
675
|
+
"applicable": i.applicable,
|
|
676
|
+
"confidence": round(i.confidence, 4),
|
|
677
|
+
"approved": i.approved,
|
|
678
|
+
}
|
|
679
|
+
for i in mined
|
|
680
|
+
],
|
|
681
|
+
},
|
|
682
|
+
)
|
|
683
|
+
)
|
|
684
|
+
return
|
|
685
|
+
|
|
686
|
+
console.print(render_invariants(mined, corpus=len(golden)))
|
|
687
|
+
if mined and not approve:
|
|
688
|
+
console.print(f"\n saved to [cyan]{path}[/cyan]")
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
@app.command()
|
|
692
|
+
def invariants(
|
|
693
|
+
recordings_dir: Path | None = DirOption,
|
|
694
|
+
as_json: bool = JsonOption,
|
|
695
|
+
) -> None:
|
|
696
|
+
"""Show the learned rules and whether they are enforced."""
|
|
697
|
+
cfg = _config(recordings_dir)
|
|
698
|
+
learned = load_invariants(invariants_path(cfg.recordings_dir))
|
|
699
|
+
|
|
700
|
+
if as_json:
|
|
701
|
+
emit(
|
|
702
|
+
payload(
|
|
703
|
+
"invariants",
|
|
704
|
+
{
|
|
705
|
+
"total": len(learned),
|
|
706
|
+
"enforced": sum(1 for i in learned if i.approved),
|
|
707
|
+
"invariants": [
|
|
708
|
+
{
|
|
709
|
+
"key": i.key,
|
|
710
|
+
"kind": i.kind.value,
|
|
711
|
+
"description": i.description,
|
|
712
|
+
"support": i.support,
|
|
713
|
+
"applicable": i.applicable,
|
|
714
|
+
"confidence": round(i.confidence, 4),
|
|
715
|
+
"approved": i.approved,
|
|
716
|
+
}
|
|
717
|
+
for i in learned
|
|
718
|
+
],
|
|
719
|
+
},
|
|
720
|
+
)
|
|
721
|
+
)
|
|
722
|
+
return
|
|
723
|
+
|
|
724
|
+
if not learned:
|
|
725
|
+
console.print(f"No invariants learned yet. Run [bold]{CLI_NAME} learn[/bold].")
|
|
726
|
+
return
|
|
727
|
+
|
|
728
|
+
table = Table(title="learned invariants")
|
|
729
|
+
table.add_column("ENFORCED")
|
|
730
|
+
table.add_column("RULE")
|
|
731
|
+
table.add_column("EVIDENCE", justify="right")
|
|
732
|
+
table.add_column("CONF", justify="right")
|
|
733
|
+
for invariant in learned:
|
|
734
|
+
table.add_row(
|
|
735
|
+
"[green]yes[/green]" if invariant.approved else "[yellow]no[/yellow]",
|
|
736
|
+
invariant.description,
|
|
737
|
+
f"{invariant.support}/{invariant.applicable}",
|
|
738
|
+
f"{invariant.confidence:.2f}",
|
|
739
|
+
)
|
|
740
|
+
console.print(table)
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
@app.command()
|
|
744
|
+
def contracts(
|
|
745
|
+
recordings_dir: Path | None = DirOption,
|
|
746
|
+
as_json: bool = JsonOption,
|
|
747
|
+
) -> None:
|
|
748
|
+
"""Compare each tool's declared schema with how it is really used.
|
|
749
|
+
|
|
750
|
+
Reports dead schema surface, invented arguments and unstable result shapes.
|
|
751
|
+
This never fails a build: it is an analysis of the approved corpus, while
|
|
752
|
+
'drift invariants' is the gate.
|
|
753
|
+
"""
|
|
754
|
+
cfg = _config(recordings_dir)
|
|
755
|
+
recordings = list_recordings(cfg.recordings_dir)
|
|
756
|
+
approved = [r for r in recordings if r.is_golden]
|
|
757
|
+
found = extract_contracts(recordings)
|
|
758
|
+
|
|
759
|
+
if as_json:
|
|
760
|
+
emit(payload("contracts", contracts_to_json(found, corpus=len(approved))))
|
|
761
|
+
return
|
|
762
|
+
|
|
763
|
+
console.print(render_contracts(found, corpus=len(approved)))
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
@app.command()
|
|
767
|
+
def approve(
|
|
768
|
+
name: str,
|
|
769
|
+
by: str = typer.Option("cli", "--by", help="Who is approving."),
|
|
770
|
+
recordings_dir: Path | None = DirOption,
|
|
771
|
+
) -> None:
|
|
772
|
+
"""Approve a recording, making it the golden for that scenario.
|
|
773
|
+
|
|
774
|
+
The non-interactive half of `drift review`. Both exist because approving a
|
|
775
|
+
known-good recording in a script and walking the pending queue by hand are
|
|
776
|
+
different jobs, and making the scripted one go through a prompt is how
|
|
777
|
+
people end up piping `yes` into it.
|
|
778
|
+
"""
|
|
779
|
+
cfg = _config(recordings_dir)
|
|
780
|
+
try:
|
|
781
|
+
approve_recording(name, by=by, config=cfg)
|
|
782
|
+
except RecordingNotFound as exc:
|
|
783
|
+
fail("approve", str(exc), code=ExitCode.NOT_FOUND, hint=f"{CLI_NAME} status")
|
|
784
|
+
return
|
|
785
|
+
except DriftCatchError as exc:
|
|
786
|
+
_die_from(exc)
|
|
787
|
+
return
|
|
788
|
+
console.print(f"[green]approved[/green] [cyan]{name}[/cyan] by {by}")
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
@app.command()
|
|
792
|
+
def reject(
|
|
793
|
+
name: str,
|
|
794
|
+
by: str = typer.Option("cli", "--by", help="Who is rejecting."),
|
|
795
|
+
recordings_dir: Path | None = DirOption,
|
|
796
|
+
) -> None:
|
|
797
|
+
"""Reject a recording, so it is never used as a golden."""
|
|
798
|
+
cfg = _config(recordings_dir)
|
|
799
|
+
try:
|
|
800
|
+
reject_recording(name, config=cfg)
|
|
801
|
+
except RecordingNotFound as exc:
|
|
802
|
+
fail("reject", str(exc), code=ExitCode.NOT_FOUND, hint=f"{CLI_NAME} status")
|
|
803
|
+
return
|
|
804
|
+
except DriftCatchError as exc:
|
|
805
|
+
_die_from(exc)
|
|
806
|
+
return
|
|
807
|
+
console.print(
|
|
808
|
+
f"[yellow]rejected[/yellow] [cyan]{name}[/cyan] by {by} - fix the agent, then re-record"
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
@app.command()
|
|
813
|
+
def restore(name: str, recordings_dir: Path | None = DirOption) -> None:
|
|
814
|
+
"""Undo a re-record, putting the previous version back."""
|
|
815
|
+
cfg = _config(recordings_dir)
|
|
816
|
+
try:
|
|
817
|
+
target = restore_previous(name, cfg.recordings_dir)
|
|
818
|
+
except DriftCatchError as exc:
|
|
819
|
+
_die_from(exc)
|
|
820
|
+
return
|
|
821
|
+
recording = load_recording(target)
|
|
822
|
+
console.print(
|
|
823
|
+
f"restored [cyan]{name}[/cyan] -> status [green]{recording.status.value}[/green], "
|
|
824
|
+
f"behaviour: {' -> '.join(recording.trajectory.tools_called) or '-'}"
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
# ---------------------------------------------------------------- audit
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
@app.command()
|
|
832
|
+
def audit(name: str, recordings_dir: Path | None = DirOption) -> None:
|
|
833
|
+
"""Show how each recorded request keys, so a loose matcher is visible."""
|
|
834
|
+
cfg = _config(recordings_dir)
|
|
835
|
+
try:
|
|
836
|
+
recording = _load(name, cfg)
|
|
837
|
+
except DriftCatchError as exc:
|
|
838
|
+
_die_from(exc)
|
|
839
|
+
return
|
|
840
|
+
|
|
841
|
+
table = Table(title=f"match keys for {name} (matcher: {cfg.matcher})")
|
|
842
|
+
table.add_column("#", justify="right")
|
|
843
|
+
table.add_column("KIND")
|
|
844
|
+
table.add_column("WHAT")
|
|
845
|
+
table.add_column("KEY")
|
|
846
|
+
|
|
847
|
+
keys: dict[str, list[int]] = {}
|
|
848
|
+
for event in recording.events:
|
|
849
|
+
payload = apply_normalizers(event_payload(event), cfg.normalizers)
|
|
850
|
+
key = key_for(payload)
|
|
851
|
+
keys.setdefault(key, []).append(event.index)
|
|
852
|
+
what = event.name if isinstance(event, ToolEvent) else event.request.model
|
|
853
|
+
table.add_row(str(event.index), event.type, what, key[7:19])
|
|
854
|
+
|
|
855
|
+
console.print(table)
|
|
856
|
+
|
|
857
|
+
duplicates = {key: indices for key, indices in keys.items() if len(indices) > 1}
|
|
858
|
+
if duplicates:
|
|
859
|
+
console.print(
|
|
860
|
+
"\n[yellow]Identical keys found.[/yellow] These are served in order, which is "
|
|
861
|
+
"what makes retries and polling work - but if they were meant to be distinct, "
|
|
862
|
+
"tighten the matcher or reduce the normalizer set."
|
|
863
|
+
)
|
|
864
|
+
for key, indices in duplicates.items():
|
|
865
|
+
console.print(f" {key[7:19]} events {indices}")
|
|
866
|
+
else:
|
|
867
|
+
console.print("\n[green]Every request keys uniquely.[/green]")
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
# ----------------------------------------------------------------- scan
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
@app.command()
|
|
874
|
+
def scan(
|
|
875
|
+
recordings_dir: Path | None = DirOption,
|
|
876
|
+
as_json: bool = JsonOption,
|
|
877
|
+
) -> None:
|
|
878
|
+
"""Audit recordings for credential-shaped values. Pre-commit friendly."""
|
|
879
|
+
cfg = _config(recordings_dir)
|
|
880
|
+
recordings = list_recordings(cfg.recordings_dir)
|
|
881
|
+
if not recordings:
|
|
882
|
+
console.print(f"No recordings in {cfg.recordings_dir}.")
|
|
883
|
+
return
|
|
884
|
+
|
|
885
|
+
offenders: dict[str, list[str]] = {}
|
|
886
|
+
for recording in recordings:
|
|
887
|
+
found = find_secrets([e.model_dump(mode="json") for e in recording.events])
|
|
888
|
+
if found:
|
|
889
|
+
offenders[recording.name] = found
|
|
890
|
+
|
|
891
|
+
if as_json:
|
|
892
|
+
emit(
|
|
893
|
+
payload(
|
|
894
|
+
"scan",
|
|
895
|
+
{"scanned": len(recordings), "offenders": offenders},
|
|
896
|
+
ok=not offenders,
|
|
897
|
+
)
|
|
898
|
+
)
|
|
899
|
+
raise typer.Exit(code=0 if not offenders else int(ExitCode.SECRETS_FOUND))
|
|
900
|
+
|
|
901
|
+
if not offenders:
|
|
902
|
+
console.print(f"[green]clean[/green] - scanned {len(recordings)} recording(s).")
|
|
903
|
+
return
|
|
904
|
+
|
|
905
|
+
for name, paths in offenders.items():
|
|
906
|
+
console.print(f"[red]{name}[/red]")
|
|
907
|
+
for path in paths:
|
|
908
|
+
console.print(f" {path}")
|
|
909
|
+
console.print(f"\n[red]{len(offenders)} recording(s) contain secrets.[/red]")
|
|
910
|
+
raise typer.Exit(code=int(ExitCode.SECRETS_FOUND))
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
# ---------------------------------------------------------------- prune
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
@app.command()
|
|
917
|
+
def prune(name: str, recordings_dir: Path | None = DirOption) -> None:
|
|
918
|
+
"""Drop raw response bodies, keeping the trajectory for behaviour tests."""
|
|
919
|
+
cfg = _config(recordings_dir)
|
|
920
|
+
path = recording_path(name, cfg.recordings_dir)
|
|
921
|
+
try:
|
|
922
|
+
recording = load_recording(path)
|
|
923
|
+
except DriftCatchError as exc:
|
|
924
|
+
_die_from(exc)
|
|
925
|
+
return
|
|
926
|
+
|
|
927
|
+
before = path.stat().st_size
|
|
928
|
+
for event in recording.events:
|
|
929
|
+
if isinstance(event, LLMEvent):
|
|
930
|
+
event.raw_response = None
|
|
931
|
+
event.stream_chunks = None
|
|
932
|
+
save_recording(recording, path)
|
|
933
|
+
after = path.stat().st_size
|
|
934
|
+
console.print(
|
|
935
|
+
f"pruned {name}: {before / 1024:.1f} KB -> {after / 1024:.1f} KB "
|
|
936
|
+
f"(behaviour preserved, replay of raw bodies no longer possible)"
|
|
937
|
+
)
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
# ----------------------------------------- commands that run your agent
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
#: pytest's own exit codes, translated into the ones this CLI documents so an
|
|
944
|
+
#: agent or a CI step can branch without parsing output. Two of these matter
|
|
945
|
+
#: more than the rest:
|
|
946
|
+
#:
|
|
947
|
+
#: * ``1`` (tests failed) becomes REGRESSION during a check, because that is
|
|
948
|
+
#: what a failing behaviour replay means.
|
|
949
|
+
#: * ``5`` (no tests collected) must never become 0. "Verified nothing" and
|
|
950
|
+
#: "verified everything" are the same exit code otherwise, which is the
|
|
951
|
+
#: silent false green this project exists to prevent.
|
|
952
|
+
_PYTEST_FAILED = 1
|
|
953
|
+
_PYTEST_INTERRUPTED = 2
|
|
954
|
+
_PYTEST_INTERNAL_ERROR = 3
|
|
955
|
+
_PYTEST_USAGE_ERROR = 4
|
|
956
|
+
_PYTEST_NO_TESTS = 5
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def _pytest(extra: list[str]) -> int:
|
|
960
|
+
console.print(f"[dim]$ pytest {' '.join(extra)}[/dim]")
|
|
961
|
+
return subprocess.call([sys.executable, "-m", "pytest", *extra])
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def _translate_pytest(code: int, *, failure_means_regression: bool) -> int:
|
|
965
|
+
"""Map a pytest exit code onto this CLI's documented contract."""
|
|
966
|
+
if code == 0:
|
|
967
|
+
return int(ExitCode.OK)
|
|
968
|
+
if code == _PYTEST_FAILED:
|
|
969
|
+
return int(ExitCode.REGRESSION if failure_means_regression else ExitCode.ERROR)
|
|
970
|
+
if code == _PYTEST_NO_TESTS:
|
|
971
|
+
console.print(
|
|
972
|
+
"[red]No tests were collected, so no behaviour was verified.[/red]\n"
|
|
973
|
+
"This is reported as an error on purpose: exiting 0 here would be "
|
|
974
|
+
"indistinguishable from a passing run."
|
|
975
|
+
)
|
|
976
|
+
return int(ExitCode.ERROR)
|
|
977
|
+
if code == _PYTEST_USAGE_ERROR:
|
|
978
|
+
return int(ExitCode.USAGE)
|
|
979
|
+
if code in (_PYTEST_INTERRUPTED, _PYTEST_INTERNAL_ERROR):
|
|
980
|
+
return int(ExitCode.ERROR)
|
|
981
|
+
return code
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
@app.command(context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
|
|
985
|
+
def record(ctx: typer.Context) -> None:
|
|
986
|
+
"""Record by running your tests. Extra arguments go to pytest."""
|
|
987
|
+
code = _pytest(["--drift-mode=record", *ctx.args])
|
|
988
|
+
# A failing test while recording is a failing test, not a regression:
|
|
989
|
+
# there is no golden yet for the behaviour to have regressed from.
|
|
990
|
+
raise typer.Exit(code=_translate_pytest(code, failure_means_regression=False))
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
@app.command(context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
|
|
994
|
+
def check(
|
|
995
|
+
ctx: typer.Context,
|
|
996
|
+
live: bool = typer.Option(False, "--live", help="Run against the real model."),
|
|
997
|
+
) -> None:
|
|
998
|
+
"""Re-verify behaviour against the golden. Use --live for Tier 2 (costs money)."""
|
|
999
|
+
if not live:
|
|
1000
|
+
code = _pytest(["--drift-mode=replay", *ctx.args])
|
|
1001
|
+
raise typer.Exit(code=_translate_pytest(code, failure_means_regression=True))
|
|
1002
|
+
console.print(
|
|
1003
|
+
f"[yellow]Live runs make real API calls.[/yellow] "
|
|
1004
|
+
f"Set {ENV_PREFIX}_ALLOW_LIVE=1 to permit them in CI."
|
|
1005
|
+
)
|
|
1006
|
+
code = _pytest(["--drift-mode=live", *ctx.args])
|
|
1007
|
+
raise typer.Exit(code=_translate_pytest(code, failure_means_regression=True))
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
# -------------------------------------------------------------------- ui
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
@app.command()
|
|
1014
|
+
def ui(
|
|
1015
|
+
port: int = typer.Option(7777, "--port", "-p"),
|
|
1016
|
+
host: str = typer.Option("127.0.0.1", "--host"),
|
|
1017
|
+
recordings_dir: Path | None = DirOption,
|
|
1018
|
+
) -> None:
|
|
1019
|
+
"""Launch the local web UI."""
|
|
1020
|
+
cfg = _config(recordings_dir)
|
|
1021
|
+
try:
|
|
1022
|
+
from driftcatch.ui.server import serve
|
|
1023
|
+
except ImportError:
|
|
1024
|
+
_die('the UI needs extra packages. Install them with:\n pip install "driftcatch[ui]"')
|
|
1025
|
+
return
|
|
1026
|
+
serve(cfg, host=host, port=port)
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def main() -> Any:
|
|
1030
|
+
"""Console-script entry point."""
|
|
1031
|
+
return app()
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
if __name__ == "__main__": # pragma: no cover
|
|
1035
|
+
main()
|