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/config.py ADDED
@@ -0,0 +1,166 @@
1
+ """Configuration.
2
+
3
+ The golden path uses no configuration at all. Everything here is progressive
4
+ disclosure: defaults that work, overridable per process, per project or per
5
+ recording, in that order of specificity.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import tomllib
12
+ from fnmatch import fnmatch
13
+ from pathlib import Path
14
+ from typing import Any, Literal
15
+
16
+ from pydantic import BaseModel, Field, ValidationError
17
+
18
+ from driftcatch._name import ENV_PREFIX
19
+ from driftcatch.errors import ConfigError
20
+
21
+ __all__ = ["Config", "config", "get_config", "reset_config"]
22
+
23
+ Mode = Literal["auto", "record", "replay", "live"]
24
+ DriftPolicy = Literal["warn", "fail", "ignore"]
25
+ StreamTiming = Literal["instant", "recorded"]
26
+
27
+ DEFAULT_NORMALIZERS = [
28
+ "drop_timestamps",
29
+ "mask_uuids",
30
+ "normalize_tool_call_ids",
31
+ ]
32
+
33
+
34
+ class Config(BaseModel):
35
+ """Resolved settings for a recording session."""
36
+
37
+ recordings_dir: Path = Path("tests/recordings")
38
+ matcher: str = "field"
39
+ normalizers: list[str] = Field(default_factory=lambda: list(DEFAULT_NORMALIZERS))
40
+ strict: bool = True
41
+ drift_policy: DriftPolicy = "warn"
42
+ require_approved: bool = False
43
+ record: list[str] = Field(default_factory=lambda: ["llm.*", "tools.*"])
44
+ passthrough: list[str] = Field(default_factory=list)
45
+ redactors: list[str] = Field(default_factory=lambda: ["default"])
46
+ stream_timing: StreamTiming = "instant"
47
+ max_recording_bytes: int = 2_000_000
48
+ default_tolerance: str = "tools+order"
49
+ #: What to do with a tool call that has no recorded match during a what-if
50
+ #: run. A counterfactual branch was never recorded, so there is nothing to
51
+ #: replay past the mutation point: ``execute`` runs the real tool (the
52
+ #: default, since the point of what-if is to explore that branch),
53
+ #: ``stub`` returns ``None`` to let control flow proceed without side
54
+ #: effects, and ``error`` refuses.
55
+ what_if_unmatched: Literal["execute", "stub", "error"] = "execute"
56
+
57
+ def should_record(self, target: str) -> bool:
58
+ """Whether a boundary should be captured.
59
+
60
+ ``target`` is a dotted name such as ``"llm.chat"`` or
61
+ ``"tools.get_time"``. ``passthrough`` wins over ``record``, so a single
62
+ noisy tool can be let through while everything else is pinned.
63
+ """
64
+ for pattern in self.passthrough:
65
+ if fnmatch(target, pattern):
66
+ return False
67
+ return any(fnmatch(target, pattern) for pattern in self.record)
68
+
69
+ def merged(self, **overrides: Any) -> Config:
70
+ """Return a copy with ``overrides`` applied, ignoring ``None`` values."""
71
+ clean = {key: value for key, value in overrides.items() if value is not None}
72
+ if not clean:
73
+ return self.model_copy(deep=True)
74
+ try:
75
+ return self.model_copy(deep=True).model_validate({**self.model_dump(), **clean})
76
+ except ValidationError as exc: # pragma: no cover - defensive
77
+ raise ConfigError(f"invalid configuration override: {exc}") from exc
78
+
79
+
80
+ _process_config: Config | None = None
81
+
82
+
83
+ def find_config_file(start: Path | None = None) -> Path | None:
84
+ """Locate ``driftcatch.toml`` or a ``pyproject.toml`` with our section."""
85
+ current = (start or Path.cwd()).resolve()
86
+ for directory in [current, *current.parents]:
87
+ standalone = directory / "driftcatch.toml"
88
+ if standalone.is_file():
89
+ return standalone
90
+ pyproject = directory / "pyproject.toml"
91
+ if pyproject.is_file():
92
+ try:
93
+ with pyproject.open("rb") as handle:
94
+ data = tomllib.load(handle)
95
+ except (OSError, tomllib.TOMLDecodeError):
96
+ return None
97
+ if isinstance(data.get("tool", {}).get("driftcatch"), dict):
98
+ return pyproject
99
+ return None
100
+ return None
101
+
102
+
103
+ def _from_pyproject(start: Path | None = None) -> dict[str, Any]:
104
+ """Read settings from ``driftcatch.toml`` or ``[tool.driftcatch]``.
105
+
106
+ A standalone ``driftcatch.toml`` is preferred and is what the UI writes, so
107
+ editing settings never has to rewrite a project's build file.
108
+ """
109
+ path = find_config_file(start)
110
+ if path is None:
111
+ return {}
112
+ try:
113
+ with path.open("rb") as handle:
114
+ data = tomllib.load(handle)
115
+ except (OSError, tomllib.TOMLDecodeError):
116
+ return {}
117
+ if path.name == "driftcatch.toml":
118
+ return {k: v for k, v in data.items() if not isinstance(v, dict)} or dict(data)
119
+ section = data.get("tool", {}).get("driftcatch", {})
120
+ return dict(section) if isinstance(section, dict) else {}
121
+
122
+
123
+ def _from_env() -> dict[str, Any]:
124
+ """Environment overrides, e.g. ``DRIFTCATCH_RECORDINGS_DIR``."""
125
+ env: dict[str, Any] = {}
126
+ mapping = {
127
+ f"{ENV_PREFIX}_RECORDINGS_DIR": "recordings_dir",
128
+ f"{ENV_PREFIX}_MATCHER": "matcher",
129
+ f"{ENV_PREFIX}_DRIFT_POLICY": "drift_policy",
130
+ }
131
+ for variable, field in mapping.items():
132
+ value = os.environ.get(variable)
133
+ if value:
134
+ env[field] = value
135
+ strict = os.environ.get(f"{ENV_PREFIX}_STRICT")
136
+ if strict is not None:
137
+ env["strict"] = strict.lower() not in {"0", "false", "no"}
138
+ return env
139
+
140
+
141
+ def config(**kwargs: Any) -> Config:
142
+ """Set the process-wide configuration and return it."""
143
+ global _process_config
144
+ base = Config(**_from_pyproject())
145
+ try:
146
+ _process_config = base.model_validate({**base.model_dump(), **kwargs})
147
+ except ValidationError as exc:
148
+ raise ConfigError(f"invalid configuration: {exc}") from exc
149
+ return _process_config
150
+
151
+
152
+ def get_config() -> Config:
153
+ """Resolve configuration: process override > pyproject > env > defaults."""
154
+ if _process_config is not None:
155
+ return _process_config.model_copy(deep=True)
156
+ data = {**_from_pyproject(), **_from_env()}
157
+ try:
158
+ return Config(**data)
159
+ except ValidationError as exc:
160
+ raise ConfigError(f"invalid [tool.driftcatch] configuration: {exc}") from exc
161
+
162
+
163
+ def reset_config() -> None:
164
+ """Forget any process-wide configuration. Used by tests."""
165
+ global _process_config
166
+ _process_config = None
@@ -0,0 +1,508 @@
1
+ """Tool contracts inferred from the approved corpus.
2
+
3
+ A tool has two descriptions. The one you *declare* to the model lives in the
4
+ JSON schema you send with every request. The one that is *real* is whatever the
5
+ model and your code actually did, run after run. They drift apart silently, and
6
+ neither your type checker nor your tests can see the gap, because the model is
7
+ the thing choosing which half of the schema to use.
8
+
9
+ This module reads the second description out of recordings that a human
10
+ approved, and puts the two side by side. Three things fall out of that
11
+ comparison, each of which costs something today:
12
+
13
+ * **Dead schema surface.** A parameter you declare and the model has never
14
+ once used is paid for on every single request, in tokens, forever.
15
+ * **Invented arguments.** A parameter the model passes that you never declared
16
+ is the model filling in a gap - usually a sign the schema is unclear, and
17
+ occasionally a sign your tool is silently ignoring input.
18
+ * **Shape instability.** A result whose keys differ between runs is a contract
19
+ your downstream code is relying on by luck.
20
+
21
+ Deliberately an *analysis* command, not a gate. ``drift invariants`` enforces;
22
+ this reports. Keeping the two apart means a contract report can be noisy and
23
+ exploratory without ever failing somebody's build.
24
+
25
+ Only approved recordings are read. Inferring a contract from runs nobody
26
+ confirmed were correct would describe a bug as if it were the specification -
27
+ the same reasoning that governs invariant mining.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ from collections import defaultdict
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ from pydantic import BaseModel, Field
38
+
39
+ from driftcatch.recording.schema import LLMEvent, Recording, ToolEvent
40
+
41
+ __all__ = [
42
+ "MIN_CORPUS_FOR_REMOVAL",
43
+ "FieldShape",
44
+ "ToolContract",
45
+ "extract",
46
+ "render",
47
+ "to_json",
48
+ ]
49
+
50
+ #: Below this many distinct values, a field is reported as an enumeration
51
+ #: rather than as a free type. Chosen so an obvious status field reads as
52
+ #: ``"pending" | "shipped"`` while a free-text field does not turn into an
53
+ #: unreadable wall of examples.
54
+ _ENUM_LIMIT = 8
55
+
56
+ #: How many example values to keep for a field that is not enum-like.
57
+ _EXAMPLES = 3
58
+
59
+ #: Findings that advise *removing* something need a corpus big enough for the
60
+ #: absence to mean anything. "This parameter was never used" across one run is
61
+ #: not evidence, it is a sample size of one, and acting on it deletes a working
62
+ #: parameter. Pinned to the same threshold invariant mining uses, for the same
63
+ #: reason: below it, absence of evidence is not evidence of absence.
64
+ MIN_CORPUS_FOR_REMOVAL = 5
65
+
66
+
67
+ def _type_name(value: Any) -> str:
68
+ """A stable, JSON-flavoured type name for a recorded value."""
69
+ if value is None:
70
+ return "null"
71
+ if isinstance(value, bool): # before int: bool is a subclass of int
72
+ return "boolean"
73
+ if isinstance(value, int):
74
+ return "integer"
75
+ if isinstance(value, float):
76
+ return "number"
77
+ if isinstance(value, str):
78
+ return "string"
79
+ if isinstance(value, list):
80
+ return "array"
81
+ if isinstance(value, dict):
82
+ return "object"
83
+ return type(value).__name__
84
+
85
+
86
+ class FieldShape(BaseModel):
87
+ """What one argument or result field has actually looked like."""
88
+
89
+ name: str
90
+ types: list[str] = Field(default_factory=list)
91
+ #: Calls in which this field was present.
92
+ present_in: int = 0
93
+ #: Calls observed in total, so optionality is a ratio not a guess.
94
+ total: int = 0
95
+ #: Distinct values, kept only while the field looks enum-like.
96
+ values: list[str] = Field(default_factory=list)
97
+ examples: list[str] = Field(default_factory=list)
98
+
99
+ @property
100
+ def required(self) -> bool:
101
+ """Present in every observed call."""
102
+ return self.total > 0 and self.present_in == self.total
103
+
104
+ @property
105
+ def is_enum(self) -> bool:
106
+ return bool(self.values)
107
+
108
+ @property
109
+ def summary(self) -> str:
110
+ """One line describing the field as it really behaves."""
111
+ kind = " | ".join(self.types) or "unknown"
112
+ if self.is_enum:
113
+ kind = " | ".join(repr(v) for v in self.values)
114
+ optional = "" if self.required else f" (optional, {self.present_in}/{self.total})"
115
+ return f"{self.name}: {kind}{optional}"
116
+
117
+
118
+ class ToolContract(BaseModel):
119
+ """The observed behaviour of one tool, next to what was declared."""
120
+
121
+ name: str
122
+ #: Calls seen across the corpus.
123
+ calls: int = 0
124
+ #: Runs in which the tool was called at least once.
125
+ runs: int = 0
126
+ #: Runs in which it was offered to the model.
127
+ offered_in: int = 0
128
+ arguments: list[FieldShape] = Field(default_factory=list)
129
+ result_type: list[str] = Field(default_factory=list)
130
+ result_fields: list[FieldShape] = Field(default_factory=list)
131
+ errors: int = 0
132
+ error_types: list[str] = Field(default_factory=list)
133
+ #: Parameters in the declared JSON schema.
134
+ declared_parameters: list[str] = Field(default_factory=list)
135
+ durations_ms: list[int] = Field(default_factory=list)
136
+
137
+ @property
138
+ def error_rate(self) -> float:
139
+ return self.errors / self.calls if self.calls else 0.0
140
+
141
+ @property
142
+ def unused_parameters(self) -> list[str]:
143
+ """Declared, but never once supplied.
144
+
145
+ Every request pays for these in prompt tokens. A parameter that has
146
+ survived an entire approved corpus without being used is either dead
147
+ or described badly enough that the model cannot tell when to use it.
148
+ """
149
+ used = {field.name for field in self.arguments}
150
+ return sorted(set(self.declared_parameters) - used)
151
+
152
+ @property
153
+ def undeclared_parameters(self) -> list[str]:
154
+ """Supplied, but never declared.
155
+
156
+ The model invented an argument name, or the schema sent at request time
157
+ disagrees with the function your code actually calls.
158
+ """
159
+ declared = set(self.declared_parameters)
160
+ if not declared:
161
+ return []
162
+ return sorted({f.name for f in self.arguments} - declared)
163
+
164
+ @property
165
+ def never_called(self) -> bool:
166
+ """Offered to the model in some run, and never chosen in any."""
167
+ return self.offered_in > 0 and self.calls == 0
168
+
169
+ @property
170
+ def unstable_result(self) -> list[str]:
171
+ """Result fields that appear in some calls and not others."""
172
+ return [f.name for f in self.result_fields if not f.required]
173
+
174
+ @property
175
+ def median_ms(self) -> int | None:
176
+ if not self.durations_ms:
177
+ return None
178
+ ordered = sorted(self.durations_ms)
179
+ return ordered[len(ordered) // 2]
180
+
181
+
182
+ class _ShapeBuilder:
183
+ """Accumulates one field's observed values across many calls."""
184
+
185
+ def __init__(self, name: str) -> None:
186
+ self.name = name
187
+ self.types: set[str] = set()
188
+ self.present = 0
189
+ self.values: set[str] = set()
190
+ self.enum_like = True
191
+
192
+ def observe(self, value: Any) -> None:
193
+ self.present += 1
194
+ self.types.add(_type_name(value))
195
+ if not self.enum_like:
196
+ return
197
+ if isinstance(value, (dict, list)):
198
+ # Containers are never reported as an enumeration: the rendering
199
+ # would be unreadable and the cardinality is unbounded.
200
+ self.enum_like = False
201
+ return
202
+ self.values.add(json.dumps(value, default=str))
203
+ if len(self.values) > _ENUM_LIMIT:
204
+ self.enum_like = False
205
+
206
+ def build(self, total: int) -> FieldShape:
207
+ decoded = sorted(json.loads(v) if v else v for v in self.values) if self.enum_like else []
208
+ rendered = [str(v) for v in decoded]
209
+ return FieldShape(
210
+ name=self.name,
211
+ types=sorted(self.types),
212
+ present_in=self.present,
213
+ total=total,
214
+ values=rendered if self.enum_like and len(rendered) > 1 else [],
215
+ examples=rendered[:_EXAMPLES],
216
+ )
217
+
218
+
219
+ def _tool_spec(declared: Any) -> dict[str, Any] | None:
220
+ """Unwrap a recorded tool entry down to the object holding its schema.
221
+
222
+ Three layers can be present, and all three must be peeled or the report is
223
+ silently empty:
224
+
225
+ 1. DriftCatch's own normalisation. ``parse_request`` rewrites every tool to
226
+ ``{"name": ..., "schema": <the original entry>}`` so the matcher and the
227
+ fingerprint see one shape. This is what is actually on disk, and missing
228
+ it was a real bug: the tools were found, every parameter was reported as
229
+ undeclared, and only a live run against a real SDK revealed it.
230
+ 2. The OpenAI envelope, ``{"type": "function", "function": {...}}``.
231
+ 3. The flat form, ``{"name": ..., "parameters": {...}}``, and Anthropic's
232
+ ``input_schema`` equivalent.
233
+ """
234
+ if not isinstance(declared, dict):
235
+ return None
236
+ inner = declared.get("schema")
237
+ if isinstance(inner, dict):
238
+ declared = inner
239
+ body = declared.get("function")
240
+ spec = body if isinstance(body, dict) else declared
241
+ return spec if isinstance(spec, dict) else None
242
+
243
+
244
+ def _declared_parameters(recordings: list[Recording]) -> dict[str, list[str]]:
245
+ """Parameter names from the tool schemas sent with each request."""
246
+ found: dict[str, set[str]] = defaultdict(set)
247
+ for recording in recordings:
248
+ for event in recording.events:
249
+ if not isinstance(event, LLMEvent):
250
+ continue
251
+ for declared in event.request.tools:
252
+ spec = _tool_spec(declared)
253
+ if spec is None:
254
+ continue
255
+ name = spec.get("name") or (
256
+ declared.get("name") if isinstance(declared, dict) else None
257
+ )
258
+ if not name:
259
+ continue
260
+ schema = spec.get("parameters") or spec.get("input_schema") or {}
261
+ properties = schema.get("properties") if isinstance(schema, dict) else None
262
+ if isinstance(properties, dict):
263
+ found[str(name)] |= set(properties)
264
+ else:
265
+ found[str(name)] |= set()
266
+ return {name: sorted(params) for name, params in found.items()}
267
+
268
+
269
+ def _offered_counts(recordings: list[Recording]) -> dict[str, int]:
270
+ """Runs in which each tool was offered to the model."""
271
+ counts: dict[str, int] = defaultdict(int)
272
+ for recording in recordings:
273
+ offered: set[str] = set()
274
+ for event in recording.events:
275
+ if not isinstance(event, LLMEvent):
276
+ continue
277
+ for declared in event.request.tools:
278
+ spec = _tool_spec(declared)
279
+ name = (spec or {}).get("name") or (
280
+ declared.get("name") if isinstance(declared, dict) else None
281
+ )
282
+ if name:
283
+ offered.add(str(name))
284
+ for name in offered:
285
+ counts[name] += 1
286
+ return counts
287
+
288
+
289
+ def extract(recordings: list[Recording]) -> list[ToolContract]:
290
+ """Infer a contract per tool from the approved recordings.
291
+
292
+ Unapproved runs are ignored, so a contract always describes behaviour a
293
+ human signed off on.
294
+ """
295
+ corpus = [r for r in recordings if r.is_golden]
296
+ if not corpus:
297
+ return []
298
+
299
+ declared = _declared_parameters(corpus)
300
+ offered = _offered_counts(corpus)
301
+
302
+ calls: dict[str, int] = defaultdict(int)
303
+ runs: dict[str, int] = defaultdict(int)
304
+ errors: dict[str, int] = defaultdict(int)
305
+ error_types: dict[str, set[str]] = defaultdict(set)
306
+ result_types: dict[str, set[str]] = defaultdict(set)
307
+ durations: dict[str, list[int]] = defaultdict(list)
308
+ arg_fields: dict[str, dict[str, _ShapeBuilder]] = defaultdict(dict)
309
+ result_fields: dict[str, dict[str, _ShapeBuilder]] = defaultdict(dict)
310
+ #: Calls whose result was an object, so result-field optionality is a
311
+ #: ratio over the calls where fields were even possible.
312
+ object_results: dict[str, int] = defaultdict(int)
313
+
314
+ for recording in corpus:
315
+ seen_here: set[str] = set()
316
+ for event in recording.events:
317
+ if not isinstance(event, ToolEvent):
318
+ continue
319
+ name = event.name
320
+ calls[name] += 1
321
+ seen_here.add(name)
322
+ if event.duration_ms is not None:
323
+ durations[name].append(event.duration_ms)
324
+
325
+ for key, value in (event.args or {}).items():
326
+ builder = arg_fields[name].setdefault(key, _ShapeBuilder(key))
327
+ builder.observe(value)
328
+
329
+ if event.error is not None:
330
+ errors[name] += 1
331
+ error_types[name].add(event.error.type)
332
+ continue
333
+
334
+ result_types[name].add(_type_name(event.result))
335
+ if isinstance(event.result, dict):
336
+ object_results[name] += 1
337
+ for key, value in event.result.items():
338
+ builder = result_fields[name].setdefault(key, _ShapeBuilder(key))
339
+ builder.observe(value)
340
+
341
+ for name in seen_here:
342
+ runs[name] += 1
343
+
344
+ contracts: list[ToolContract] = []
345
+ for name in sorted(set(calls) | set(offered)):
346
+ total_calls = calls[name]
347
+ # Argument optionality is measured over successful *and* failed calls,
348
+ # because a tool that raises still tells you what it was given.
349
+ contracts.append(
350
+ ToolContract(
351
+ name=name,
352
+ calls=total_calls,
353
+ runs=runs[name],
354
+ offered_in=offered.get(name, 0),
355
+ arguments=[b.build(total_calls) for b in arg_fields[name].values()],
356
+ result_type=sorted(result_types[name]),
357
+ result_fields=[b.build(object_results[name]) for b in result_fields[name].values()],
358
+ errors=errors[name],
359
+ error_types=sorted(error_types[name]),
360
+ declared_parameters=declared.get(name, []),
361
+ durations_ms=durations[name],
362
+ )
363
+ )
364
+ return contracts
365
+
366
+
367
+ # ------------------------------------------------------------- reporting
368
+
369
+
370
+ def _findings(contract: ToolContract, corpus: int = 0) -> list[str]:
371
+ """The lines worth acting on, in descending order of cost.
372
+
373
+ ``corpus`` gates the findings that recommend deleting something. With too
374
+ few recordings those are guesses dressed as advice, so they are withheld
375
+ rather than hedged - a report nobody can act on confidently is worse than a
376
+ shorter one.
377
+ """
378
+ notes: list[str] = []
379
+ enough = corpus >= MIN_CORPUS_FOR_REMOVAL
380
+
381
+ if contract.never_called and enough:
382
+ notes.append(
383
+ f"offered in {contract.offered_in} run(s) but never called - "
384
+ f"its schema costs tokens on every request"
385
+ )
386
+ if enough:
387
+ for param in contract.unused_parameters:
388
+ notes.append(f"parameter {param!r} is declared but was never supplied")
389
+ for param in contract.undeclared_parameters:
390
+ notes.append(f"parameter {param!r} was supplied but is not in the declared schema")
391
+ unstable = contract.unstable_result
392
+ if unstable:
393
+ notes.append(
394
+ f"result fields appear only sometimes: {', '.join(unstable)} - "
395
+ f"downstream code reading them is relying on luck"
396
+ )
397
+ if contract.errors:
398
+ notes.append(
399
+ f"failed {contract.errors}/{contract.calls} calls "
400
+ f"({contract.error_rate:.0%}): {', '.join(contract.error_types)}"
401
+ )
402
+ return notes
403
+
404
+
405
+ def render(contracts: list[ToolContract], *, corpus: int = 0) -> str:
406
+ """A human-readable contract report."""
407
+ if not contracts:
408
+ return (
409
+ "No tool contracts yet.\n\n"
410
+ "Contracts are read from approved recordings. Record a few runs, "
411
+ "approve them with 'drift approve <name>', then run this again."
412
+ )
413
+
414
+ lines: list[str] = []
415
+ if corpus:
416
+ lines.append(f"Tool contracts from {corpus} approved recording(s)\n")
417
+
418
+ total_findings = 0
419
+ for contract in contracts:
420
+ header = f"{contract.name} - {contract.calls} call(s) in {contract.runs} run(s)"
421
+ if contract.median_ms is not None:
422
+ header += f", median {contract.median_ms}ms"
423
+ lines.append(header)
424
+
425
+ if contract.arguments:
426
+ lines.append(" arguments:")
427
+ lines.extend(f" {field.summary}" for field in contract.arguments)
428
+ elif contract.calls:
429
+ lines.append(" arguments: (none)")
430
+
431
+ if contract.result_type:
432
+ lines.append(f" returns: {' | '.join(contract.result_type)}")
433
+ for field in contract.result_fields:
434
+ lines.append(f" {field.summary}")
435
+
436
+ notes = _findings(contract, corpus)
437
+ total_findings += len(notes)
438
+ lines.extend(f" ! {note}" for note in notes)
439
+ lines.append("")
440
+
441
+ withheld = bool(corpus) and corpus < MIN_CORPUS_FOR_REMOVAL
442
+
443
+ if total_findings:
444
+ lines.append(f"{total_findings} finding(s). These are observations, not failures.")
445
+ elif withheld:
446
+ # Saying "no findings" here would be a lie by omission: the findings
447
+ # that recommend deleting something were suppressed for lack of
448
+ # evidence, not evaluated and cleared.
449
+ lines.append("No findings from the evidence available.")
450
+ else:
451
+ lines.append("No findings: declared schemas and observed use agree.")
452
+
453
+ if withheld:
454
+ lines.append(
455
+ f"\n{corpus} approved recording(s) is too few to call anything unused. "
456
+ f"Findings that recommend removing a tool or a parameter need at least "
457
+ f"{MIN_CORPUS_FOR_REMOVAL} and are withheld until then - with this few runs, "
458
+ f"'never used' means 'not yet seen'. Record and approve more runs to see them."
459
+ )
460
+ return "\n".join(lines)
461
+
462
+
463
+ def to_json(contracts: list[ToolContract], *, corpus: int = 0) -> dict[str, Any]:
464
+ """The machine-readable form, for CI and for coding agents."""
465
+ return {
466
+ "corpus": corpus,
467
+ "removal_findings_enabled": corpus >= MIN_CORPUS_FOR_REMOVAL,
468
+ "min_corpus_for_removal": MIN_CORPUS_FOR_REMOVAL,
469
+ "tools": [
470
+ {
471
+ "name": c.name,
472
+ "calls": c.calls,
473
+ "runs": c.runs,
474
+ "offered_in": c.offered_in,
475
+ "never_called": c.never_called,
476
+ "error_rate": round(c.error_rate, 4),
477
+ "error_types": c.error_types,
478
+ "median_ms": c.median_ms,
479
+ "returns": c.result_type,
480
+ "arguments": [
481
+ {
482
+ "name": f.name,
483
+ "types": f.types,
484
+ "required": f.required,
485
+ "present_in": f.present_in,
486
+ "total": f.total,
487
+ "values": f.values,
488
+ }
489
+ for f in c.arguments
490
+ ],
491
+ "result_fields": [
492
+ {"name": f.name, "types": f.types, "required": f.required}
493
+ for f in c.result_fields
494
+ ],
495
+ "declared_parameters": c.declared_parameters,
496
+ "unused_parameters": c.unused_parameters,
497
+ "undeclared_parameters": c.undeclared_parameters,
498
+ "unstable_result_fields": c.unstable_result,
499
+ "findings": _findings(c, corpus),
500
+ }
501
+ for c in contracts
502
+ ],
503
+ }
504
+
505
+
506
+ def contracts_path(recordings_dir: Path) -> Path:
507
+ """Where a saved contract snapshot lives, beside the recordings."""
508
+ return Path(recordings_dir) / "contracts.json"