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.
Files changed (46) hide show
  1. driftcatch/__init__.py +146 -0
  2. driftcatch/_name.py +12 -0
  3. driftcatch/agentio.py +246 -0
  4. driftcatch/bisect.py +160 -0
  5. driftcatch/cli.py +1035 -0
  6. driftcatch/config.py +166 -0
  7. driftcatch/contracts.py +508 -0
  8. driftcatch/coverage.py +165 -0
  9. driftcatch/determinism.py +282 -0
  10. driftcatch/errors.py +149 -0
  11. driftcatch/intercept/__init__.py +8 -0
  12. driftcatch/intercept/http.py +400 -0
  13. driftcatch/intercept/tools.py +187 -0
  14. driftcatch/invariants.py +646 -0
  15. driftcatch/match/__init__.py +60 -0
  16. driftcatch/match/base.py +161 -0
  17. driftcatch/match/keys.py +61 -0
  18. driftcatch/match/normalizers.py +130 -0
  19. driftcatch/match/registry.py +82 -0
  20. driftcatch/match/resolve.py +195 -0
  21. driftcatch/match/strategies.py +146 -0
  22. driftcatch/mcp_server.py +417 -0
  23. driftcatch/providers.py +227 -0
  24. driftcatch/py.typed +0 -0
  25. driftcatch/pytest_plugin.py +170 -0
  26. driftcatch/record.py +162 -0
  27. driftcatch/recording/__init__.py +57 -0
  28. driftcatch/recording/fingerprint.py +75 -0
  29. driftcatch/recording/io.py +257 -0
  30. driftcatch/recording/schema.py +261 -0
  31. driftcatch/redact.py +127 -0
  32. driftcatch/replay.py +152 -0
  33. driftcatch/review.py +102 -0
  34. driftcatch/session.py +126 -0
  35. driftcatch/suite.py +135 -0
  36. driftcatch/take.py +632 -0
  37. driftcatch/trajectory.py +208 -0
  38. driftcatch/ui/__init__.py +15 -0
  39. driftcatch/ui/server.py +245 -0
  40. driftcatch/ui/templates/app.html +346 -0
  41. driftcatch/whatif.py +65 -0
  42. driftcatch-0.1.0.dist-info/METADATA +456 -0
  43. driftcatch-0.1.0.dist-info/RECORD +46 -0
  44. driftcatch-0.1.0.dist-info/WHEEL +4 -0
  45. driftcatch-0.1.0.dist-info/entry_points.txt +5 -0
  46. driftcatch-0.1.0.dist-info/licenses/LICENSE +21 -0
driftcatch/__init__.py ADDED
@@ -0,0 +1,146 @@
1
+ """DriftCatch - catch the moment your AI agent's behaviour changes.
2
+
3
+ Quick start::
4
+
5
+ import driftcatch as drift
6
+
7
+ @drift.tool
8
+ def lookup_order(order_id: int) -> dict: ...
9
+
10
+ def test_refund_uses_the_database():
11
+ with drift.take("refund_1182") as take:
12
+ result = refund_agent("refund order 1182")
13
+ take.assert_tools().called("lookup_order").never("web_search")
14
+ take.assert_trajectory().matches_golden()
15
+
16
+ Everything users need is re-exported here; internal modules are free to move.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from driftcatch._name import CLI_NAME, NAME, RECORDING_VERSION
22
+ from driftcatch.bisect import bisect
23
+ from driftcatch.config import Config, config, get_config, reset_config
24
+ from driftcatch.contracts import FieldShape, ToolContract
25
+ from driftcatch.contracts import extract as extract_contracts
26
+ from driftcatch.coverage import CoverageReport
27
+ from driftcatch.coverage import analyse as analyse_coverage
28
+ from driftcatch.determinism import (
29
+ DeterminismReport,
30
+ LiveResult,
31
+ live_allowed,
32
+ live_check,
33
+ run_live,
34
+ )
35
+ from driftcatch.errors import (
36
+ AmbiguousMatchError,
37
+ ConfigError,
38
+ DriftCatchError,
39
+ DriftDetected,
40
+ DriftSignal,
41
+ DriftWarning,
42
+ InvalidRecordingName,
43
+ InvalidTransition,
44
+ LatencyNotMeasured,
45
+ NoMatchError,
46
+ PrunedRecording,
47
+ RecordedError,
48
+ RecordingNotApproved,
49
+ RecordingNotFound,
50
+ RecordingVersionError,
51
+ RedactionError,
52
+ )
53
+ from driftcatch.intercept import tool
54
+ from driftcatch.invariants import Invariant, InvariantKind, Violation
55
+ from driftcatch.invariants import check as check_invariants
56
+ from driftcatch.invariants import mine as mine_invariants
57
+ from driftcatch.match import chain, matcher, normalizer
58
+ from driftcatch.recording import (
59
+ ErrorInfo,
60
+ LLMEvent,
61
+ LLMRequest,
62
+ LLMResponse,
63
+ Outcome,
64
+ Recording,
65
+ Status,
66
+ Step,
67
+ ToolEvent,
68
+ Trajectory,
69
+ Usage,
70
+ list_recordings,
71
+ load_recording,
72
+ )
73
+ from driftcatch.review import approve, reject
74
+ from driftcatch.suite import Suite
75
+ from driftcatch.take import LatencyAssertion, OutputAssertion, Take, take
76
+ from driftcatch.trajectory import TOLERANCES
77
+
78
+ __version__ = "0.1.0"
79
+
80
+ __all__ = [
81
+ "CLI_NAME",
82
+ "NAME",
83
+ "RECORDING_VERSION",
84
+ "TOLERANCES",
85
+ "AmbiguousMatchError",
86
+ "Config",
87
+ "ConfigError",
88
+ "CoverageReport",
89
+ "DeterminismReport",
90
+ "DriftCatchError",
91
+ "DriftDetected",
92
+ "DriftSignal",
93
+ "DriftWarning",
94
+ "FieldShape",
95
+ "ToolContract",
96
+ "extract_contracts",
97
+ "LatencyAssertion",
98
+ "LatencyNotMeasured",
99
+ "OutputAssertion",
100
+ "ErrorInfo",
101
+ "InvalidRecordingName",
102
+ "InvalidTransition",
103
+ "mine_invariants",
104
+ "check_invariants",
105
+ "Violation",
106
+ "InvariantKind",
107
+ "Invariant",
108
+ "LLMEvent",
109
+ "LLMRequest",
110
+ "LLMResponse",
111
+ "LiveResult",
112
+ "NoMatchError",
113
+ "PrunedRecording",
114
+ "Outcome",
115
+ "RecordedError",
116
+ "Recording",
117
+ "RecordingNotApproved",
118
+ "RecordingNotFound",
119
+ "RecordingVersionError",
120
+ "RedactionError",
121
+ "Status",
122
+ "Step",
123
+ "Suite",
124
+ "Take",
125
+ "ToolEvent",
126
+ "Trajectory",
127
+ "Usage",
128
+ "__version__",
129
+ "analyse_coverage",
130
+ "approve",
131
+ "bisect",
132
+ "chain",
133
+ "config",
134
+ "get_config",
135
+ "list_recordings",
136
+ "live_allowed",
137
+ "live_check",
138
+ "load_recording",
139
+ "matcher",
140
+ "normalizer",
141
+ "reject",
142
+ "reset_config",
143
+ "run_live",
144
+ "take",
145
+ "tool",
146
+ ]
driftcatch/_name.py ADDED
@@ -0,0 +1,12 @@
1
+ """Single source of truth for the project's identity.
2
+
3
+ Everything that needs the package or CLI name imports it from here, so renaming
4
+ the project is a one-line change.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ NAME = "driftcatch"
10
+ CLI_NAME = "drift"
11
+ RECORDING_VERSION = 1
12
+ ENV_PREFIX = "DRIFTCATCH"
driftcatch/agentio.py ADDED
@@ -0,0 +1,246 @@
1
+ """Machine-readable output, for when the caller is a coding agent.
2
+
3
+ Cursor, Claude Code and friends drive tools by running shell commands and
4
+ reading stdout. A table drawn with box characters is good for a human and
5
+ hostile to a parser, so every read-only command can emit JSON instead.
6
+
7
+ The conventions here follow what the agent-CLI guidance has converged on:
8
+
9
+ * one uniform ``--json`` flag across every command, never a mix of spellings;
10
+ * results on **stdout**, diagnostics on **stderr**, so stdout is a clean contract;
11
+ * **errors are JSON too** in JSON mode - an agent should never have to parse a
12
+ stack trace to learn that a recording is missing;
13
+ * a **documented exit-code taxonomy**, so an agent can branch on the number
14
+ before it reads anything;
15
+ * nothing interactive, ever, when ``--json`` is set.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import sys
22
+ from enum import IntEnum
23
+ from typing import Any, NoReturn
24
+
25
+ __all__ = ["AGENTS_SECTION", "ExitCode", "capabilities", "emit", "fail", "payload"]
26
+
27
+
28
+ class ExitCode(IntEnum):
29
+ """What an agent can branch on without reading output at all."""
30
+
31
+ OK = 0
32
+ #: Something went wrong that isn't one of the specific cases below.
33
+ ERROR = 1
34
+ #: Reserved by the CLI framework for bad usage.
35
+ USAGE = 2
36
+ #: Behaviour changed: a trajectory diff or a learned invariant broke.
37
+ REGRESSION = 3
38
+ #: A quality gate failed, e.g. coverage below --fail-under.
39
+ GATE_FAILED = 4
40
+ #: Credential-shaped values were found in recordings.
41
+ SECRETS_FOUND = 5
42
+ #: The named recording does not exist.
43
+ NOT_FOUND = 6
44
+ #: A recording was used as golden without human approval.
45
+ NOT_APPROVED = 7
46
+
47
+
48
+ #: Written into the user's project by ``drift init`` so that any coding agent
49
+ #: working in that repo knows the workflow without being told.
50
+ AGENTS_SECTION = """\
51
+ ## Agent testing with DriftCatch
52
+
53
+ This project uses DriftCatch to pin agent behaviour. Read this before changing
54
+ any prompt, tool, or agent code.
55
+
56
+ ### The loop
57
+ 1. `pytest` - replays recorded runs. Free, offline, deterministic.
58
+ 2. If it fails with `NoMatchError`, behaviour changed.
59
+ **Do not re-record to make it pass.**
60
+ Read `changed_inputs` first and decide whether it is a bug.
61
+ 3. `drift bisect <name> --previous` - says which input caused the change.
62
+ 4. Only if the change is intended: `drift record --drift-update`, then
63
+ `drift approve <name> --by <who>`. The previous version is archived; undo
64
+ with `drift restore <name>`.
65
+
66
+ ### Rules
67
+ - Never edit files under the recordings directory by hand.
68
+ - Never approve a recording you have not inspected; approval means "this
69
+ behaviour is correct", and it is how wrong behaviour gets locked in.
70
+ - A changed **user question** is a NEW scenario - give it a new name. A changed
71
+ **system prompt, model, or tool schema** is drift - re-record that recording.
72
+ - Live runs cost money. Never add `DRIFTCATCH_ALLOW_LIVE=1` without being asked.
73
+ - `drift contracts` reports where a tool's declared schema and its real use
74
+ disagree. It is analysis, never a gate, and never fails a build.
75
+
76
+ ### Machine-readable output
77
+ Every read command takes `--json`. Prefer it; parse stdout, ignore stderr.
78
+
79
+ ```bash
80
+ drift status --json # recordings and their approval state
81
+ drift coverage --json # which behaviours were never tested
82
+ drift invariants --json # learned rules and whether they are enforced
83
+ drift contracts --json # declared tool schemas vs how they are really used
84
+ drift learn --json # mine rules from approved recordings
85
+ drift scan --json # credential audit
86
+ drift explain --json # this contract, as data
87
+ ```
88
+
89
+ `drift status --require-approved` exits 7 when any recording is still pending,
90
+ for use as a CI gate.
91
+
92
+ ### Exit codes
93
+ `0` ok · `1` error · `2` usage · `3` behaviour regression · `4` gate failed
94
+ (e.g. coverage) · `5` secrets found · `6` recording not found · `7` not approved
95
+ """
96
+
97
+
98
+ def payload(command: str, data: dict[str, Any], *, ok: bool = True) -> dict[str, Any]:
99
+ """Wrap a result in the envelope every JSON response shares.
100
+
101
+ A stable envelope means an agent can check ``ok`` and ``command`` without
102
+ knowing anything about the specific command it called.
103
+ """
104
+ return {"ok": ok, "command": command, **data}
105
+
106
+
107
+ def emit(data: dict[str, Any]) -> None:
108
+ """Write one JSON object to stdout and nothing else."""
109
+ sys.stdout.write(json.dumps(data, indent=2, default=str) + "\n")
110
+
111
+
112
+ def capabilities() -> dict[str, Any]:
113
+ """A self-describing manifest, so an agent needs no external docs.
114
+
115
+ This is the single discovery entrypoint: one call tells an agent what the
116
+ tool can do, which commands are safe to run unattended, what the exit codes
117
+ mean, and what the correct workflow is.
118
+ """
119
+ return {
120
+ "name": "driftcatch",
121
+ "purpose": (
122
+ "Behaviour regression testing for AI agents. Records agent runs, "
123
+ "replays them offline for free, detects when behaviour or its inputs "
124
+ "change, and learns the rules the agent always follows."
125
+ ),
126
+ "not_for": [
127
+ "production use - this is a test tool, never a response cache",
128
+ "scoring answer quality - that is evaluation, a different discipline",
129
+ "production monitoring - that is observability",
130
+ ],
131
+ "key_facts": [
132
+ "Replay is free and offline; it catches changes to YOUR prompt, "
133
+ "model id, tool schemas and code.",
134
+ "Replay CANNOT detect what the model would decide today, because the "
135
+ "model does not run. That needs a deliberate live check.",
136
+ "A recording is not trusted until a human approves it.",
137
+ "Live runs cost money and are refused unless DRIFTCATCH_ALLOW_LIVE=1.",
138
+ ],
139
+ "exit_codes": {int(c): c.name.lower() for c in ExitCode},
140
+ "commands": {
141
+ "status": {
142
+ "reads_only": True,
143
+ "json": True,
144
+ "purpose": "recordings and approval state",
145
+ },
146
+ "show": {"reads_only": True, "json": False, "purpose": "one recording in full"},
147
+ "coverage": {
148
+ "reads_only": True,
149
+ "json": True,
150
+ "purpose": "which behaviours were never tested",
151
+ "gate": "--fail-under N exits 4",
152
+ },
153
+ "suggest": {"reads_only": True, "json": False, "purpose": "scenarios worth adding"},
154
+ "learn": {
155
+ "reads_only": False,
156
+ "json": True,
157
+ "purpose": "mine rules from approved recordings",
158
+ "note": "mined rules are not enforced until --approve",
159
+ },
160
+ "invariants": {"reads_only": True, "json": True, "purpose": "learned rules"},
161
+ "diff": {"reads_only": True, "json": False, "purpose": "behaviour diff"},
162
+ "bisect": {
163
+ "reads_only": True,
164
+ "json": False,
165
+ "purpose": "which input caused a behaviour change",
166
+ },
167
+ "scan": {
168
+ "reads_only": True,
169
+ "json": True,
170
+ "purpose": "credential audit",
171
+ "gate": "exits 5 on findings",
172
+ },
173
+ "audit": {"reads_only": True, "json": False, "purpose": "how each request keys"},
174
+ "review": {
175
+ "reads_only": False,
176
+ "json": False,
177
+ "purpose": "approve or reject",
178
+ "warning": "approval means a human confirmed the behaviour is correct",
179
+ },
180
+ "record": {"reads_only": False, "json": False, "purpose": "re-record via pytest"},
181
+ "restore": {"reads_only": False, "json": False, "purpose": "undo a re-record"},
182
+ "check": {
183
+ "reads_only": False,
184
+ "json": False,
185
+ "purpose": "live verification",
186
+ "warning": "--live spends real money",
187
+ },
188
+ },
189
+ "workflows": {
190
+ "tests_failed_with_nomatch": [
191
+ "read changed_inputs on the take",
192
+ "drift bisect <name> --previous",
193
+ "decide: bug -> fix the code; intended -> drift record",
194
+ "drift approve <name> --by <who>",
195
+ ],
196
+ "improve_coverage": [
197
+ "drift coverage --json",
198
+ "drift suggest",
199
+ "add a what_if test for each uncovered error path",
200
+ ],
201
+ "adopt_in_a_new_project": [
202
+ "drift init",
203
+ "decorate tools with @drift.tool",
204
+ "wrap one test in `with drift.take(name) as take:`",
205
+ "pytest, then drift review",
206
+ ],
207
+ },
208
+ "cautions": [
209
+ "Never hand-edit recording files.",
210
+ "Never approve a recording without inspecting it.",
211
+ "Never re-record merely to make a failing test pass.",
212
+ "A changed user question is a new scenario, not drift.",
213
+ ],
214
+ }
215
+
216
+
217
+ def fail(
218
+ command: str,
219
+ message: str,
220
+ *,
221
+ code: ExitCode = ExitCode.ERROR,
222
+ json_mode: bool = False,
223
+ hint: str | None = None,
224
+ **extra: Any,
225
+ ) -> NoReturn:
226
+ """Exit with a structured error.
227
+
228
+ In JSON mode the error goes to stdout as data, because for an agent a
229
+ failure is a result like any other. ``hint`` carries the next command to
230
+ run, which is usually the only thing the agent actually needs.
231
+ """
232
+ import typer
233
+
234
+ if json_mode:
235
+ emit(
236
+ payload(
237
+ command,
238
+ {"error": message, "hint": hint, "exit_code": int(code), **extra},
239
+ ok=False,
240
+ )
241
+ )
242
+ else:
243
+ sys.stderr.write(f"error: {message}\n")
244
+ if hint:
245
+ sys.stderr.write(f"hint: {hint}\n")
246
+ raise typer.Exit(code=int(code))
driftcatch/bisect.py ADDED
@@ -0,0 +1,160 @@
1
+ """Behaviour bisect: attributing a change to the input that caused it.
2
+
3
+ Every other tool stops at "the behaviour differs". The question a developer
4
+ actually has is *why*. Because the fingerprint hashes each behaviour-determining
5
+ input separately, comparing two recordings isolates the candidates - and when
6
+ exactly one input moved, that is the root cause with certainty.
7
+
8
+ Scope note: this attributes by comparison, which needs no API spend. Proving
9
+ causation by reverting one input at a time and re-running live is a strictly
10
+ larger feature and is not claimed here.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import difflib
16
+
17
+ from pydantic import BaseModel, Field
18
+
19
+ from driftcatch.recording.fingerprint import compare as fp_compare
20
+ from driftcatch.recording.schema import LLMEvent, Recording
21
+ from driftcatch.trajectory import diff as trajectory_diff
22
+
23
+ __all__ = ["BisectReport", "bisect", "render"]
24
+
25
+ _COMPONENT_LABELS = {
26
+ "model_id": "the model version",
27
+ "prompt_hash": "the system prompt",
28
+ "tool_schema_hash": "the tool schemas",
29
+ "matcher_hash": "the matcher configuration",
30
+ }
31
+
32
+
33
+ class BisectReport(BaseModel):
34
+ name: str
35
+ behaviour_changed: bool = False
36
+ golden_path: str = ""
37
+ candidate_path: str = ""
38
+ changed_inputs: list[str] = Field(default_factory=list)
39
+ root_cause: str | None = None
40
+ confident: bool = False
41
+ prompt_diff: list[str] = Field(default_factory=list)
42
+ tool_diff: list[str] = Field(default_factory=list)
43
+
44
+
45
+ def _system_prompt(recording: Recording) -> str:
46
+ for event in recording.events:
47
+ if isinstance(event, LLMEvent):
48
+ return "\n".join(
49
+ str(message.get("content", ""))
50
+ for message in event.request.messages
51
+ if message.get("role") == "system"
52
+ )
53
+ return ""
54
+
55
+
56
+ def _tool_names(recording: Recording) -> list[str]:
57
+ for event in recording.events:
58
+ if isinstance(event, LLMEvent):
59
+ return [str(tool.get("name", "")) for tool in event.request.tools]
60
+ return []
61
+
62
+
63
+ def _word_diff(before: str, after: str) -> list[str]:
64
+ """A readable before/after of the prompt, the usual culprit."""
65
+ lines: list[str] = []
66
+ matcher = difflib.SequenceMatcher(None, before.split(), after.split())
67
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
68
+ if tag == "equal":
69
+ continue
70
+ removed = " ".join(before.split()[i1:i2])
71
+ added = " ".join(after.split()[j1:j2])
72
+ if removed:
73
+ lines.append(f"- {removed}")
74
+ if added:
75
+ lines.append(f"+ {added}")
76
+ return lines
77
+
78
+
79
+ def bisect(
80
+ golden: Recording, candidate: Recording, *, tolerance: str = "tools+order"
81
+ ) -> BisectReport:
82
+ """Attribute the behaviour difference between two recordings."""
83
+ report = BisectReport(
84
+ name=golden.name,
85
+ golden_path=" -> ".join(golden.trajectory.tools_called) or "(no tools)",
86
+ candidate_path=" -> ".join(candidate.trajectory.tools_called) or "(no tools)",
87
+ )
88
+
89
+ result = trajectory_diff(golden.trajectory, candidate.trajectory, tolerance)
90
+ report.behaviour_changed = not result.matched
91
+
92
+ if golden.fingerprint and candidate.fingerprint:
93
+ report.changed_inputs = fp_compare(golden.fingerprint, candidate.fingerprint)
94
+
95
+ # Exactly one changed input means the attribution is certain.
96
+ if len(report.changed_inputs) == 1:
97
+ component = report.changed_inputs[0]
98
+ report.root_cause = _COMPONENT_LABELS.get(component, component)
99
+ report.confident = True
100
+ elif len(report.changed_inputs) > 1:
101
+ report.root_cause = None
102
+ report.confident = False
103
+
104
+ if "prompt_hash" in report.changed_inputs:
105
+ report.prompt_diff = _word_diff(_system_prompt(golden), _system_prompt(candidate))
106
+
107
+ if "tool_schema_hash" in report.changed_inputs:
108
+ before, after = set(_tool_names(golden)), set(_tool_names(candidate))
109
+ report.tool_diff = [f"- {name}" for name in sorted(before - after)] + [
110
+ f"+ {name}" for name in sorted(after - before)
111
+ ]
112
+
113
+ return report
114
+
115
+
116
+ def render(report: BisectReport) -> str:
117
+ lines: list[str] = []
118
+
119
+ if not report.behaviour_changed:
120
+ lines.append(" behaviour is unchanged between these recordings")
121
+ else:
122
+ lines.extend(
123
+ [
124
+ " Behaviour changed:",
125
+ f" golden: {report.golden_path}",
126
+ f" candidate: {report.candidate_path}",
127
+ ]
128
+ )
129
+
130
+ lines.append("")
131
+ if not report.changed_inputs:
132
+ lines.append(" No behaviour-determining input changed.")
133
+ if report.behaviour_changed:
134
+ lines.append(" The difference is model non-determinism, not a code change.")
135
+ lines.append(" Measure it: drift determinism <recording> -n 20")
136
+ return "\n".join(lines)
137
+
138
+ labels = [_COMPONENT_LABELS.get(c, c) for c in report.changed_inputs]
139
+ lines.append(f" Changed inputs: {', '.join(labels)}")
140
+
141
+ if report.confident and report.root_cause:
142
+ lines.extend(["", f" ROOT CAUSE: {report.root_cause}."])
143
+ else:
144
+ lines.extend(
145
+ [
146
+ "",
147
+ " Several inputs changed, so the cause is not isolated.",
148
+ " Revert one at a time and re-record to narrow it down.",
149
+ ]
150
+ )
151
+
152
+ if report.prompt_diff:
153
+ lines.append("")
154
+ lines.extend(f" {line}" for line in report.prompt_diff)
155
+
156
+ if report.tool_diff:
157
+ lines.append("")
158
+ lines.extend(f" {line}" for line in report.tool_diff)
159
+
160
+ return "\n".join(lines)