assaystone 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. assaystone/__init__.py +24 -0
  2. assaystone/__main__.py +4 -0
  3. assaystone/adapters/__init__.py +16 -0
  4. assaystone/adapters/messages.py +254 -0
  5. assaystone/audit.py +534 -0
  6. assaystone/backtest.py +90 -0
  7. assaystone/cli.py +491 -0
  8. assaystone/contract.py +69 -0
  9. assaystone/demo.py +201 -0
  10. assaystone/demo_data/audit/README.md +13 -0
  11. assaystone/demo_data/audit/baseline/README.md +5 -0
  12. assaystone/demo_data/audit/baseline/ci/build.yml +3 -0
  13. assaystone/demo_data/audit/baseline/pricing/__init__.py +1 -0
  14. assaystone/demo_data/audit/baseline/pricing/discounts.py +16 -0
  15. assaystone/demo_data/audit/baseline/tests/__init__.py +0 -0
  16. assaystone/demo_data/audit/baseline/tests/test_discounts.py +40 -0
  17. assaystone/demo_data/audit/transcript.jsonl +13 -0
  18. assaystone/demo_data/code_agent/baseline/README.md +5 -0
  19. assaystone/demo_data/code_agent/baseline/ci/build.yml +3 -0
  20. assaystone/demo_data/code_agent/baseline/pricing/__init__.py +1 -0
  21. assaystone/demo_data/code_agent/baseline/pricing/discounts.py +16 -0
  22. assaystone/demo_data/code_agent/baseline/tests/__init__.py +0 -0
  23. assaystone/demo_data/code_agent/baseline/tests/test_discounts.py +40 -0
  24. assaystone/demo_data/code_agent/contracts/hardened.json +18 -0
  25. assaystone/demo_data/code_agent/contracts/naive.json +11 -0
  26. assaystone/demo_data/code_agent/traces/t01-correct.json +49 -0
  27. assaystone/demo_data/code_agent/traces/t02-regression.json +49 -0
  28. assaystone/demo_data/code_agent/traces/t03-test-tampering.json +62 -0
  29. assaystone/demo_data/code_agent/traces/t04-forbidden-path.json +62 -0
  30. assaystone/demo_data/code_agent/traces/t05-debug-print.json +49 -0
  31. assaystone/demo_data/code_agent/traces/t06-clean-noisy.json +49 -0
  32. assaystone/demo_data/importers/README.md +20 -0
  33. assaystone/demo_data/importers/langfuse_trace.json +60 -0
  34. assaystone/demo_data/importers/langsmith_runs.json +70 -0
  35. assaystone/demo_data/importers/otel_trace.json +228 -0
  36. assaystone/demo_data/ops_agent/baseline/README.md +5 -0
  37. assaystone/demo_data/ops_agent/baseline/orders.json +32 -0
  38. assaystone/demo_data/ops_agent/baseline/policy.json +4 -0
  39. assaystone/demo_data/ops_agent/contracts/amount_only.json +11 -0
  40. assaystone/demo_data/ops_agent/contracts/hardened.json +15 -0
  41. assaystone/demo_data/ops_agent/traces/t01-correct.json +60 -0
  42. assaystone/demo_data/ops_agent/traces/t02-over-limit.json +60 -0
  43. assaystone/demo_data/ops_agent/traces/t03-double-refund.json +60 -0
  44. assaystone/demo_data/ops_agent/traces/t04-missing-approval.json +49 -0
  45. assaystone/demo_data/ops_agent/traces/t05-bad-status.json +60 -0
  46. assaystone/demo_data/ops_agent/traces/t06-clean-noisy.json +60 -0
  47. assaystone/hooks/__init__.py +1 -0
  48. assaystone/hooks/claude_code.py +236 -0
  49. assaystone/importers/__init__.py +45 -0
  50. assaystone/importers/common.py +100 -0
  51. assaystone/importers/langfuse.py +123 -0
  52. assaystone/importers/langsmith.py +140 -0
  53. assaystone/importers/otel.py +191 -0
  54. assaystone/init.py +138 -0
  55. assaystone/model.py +192 -0
  56. assaystone/mutate.py +352 -0
  57. assaystone/packs/__init__.py +8 -0
  58. assaystone/packs/ops.py +180 -0
  59. assaystone/pytest_plugin.py +109 -0
  60. assaystone/replay.py +274 -0
  61. assaystone/reports.py +180 -0
  62. assaystone/runner.py +87 -0
  63. assaystone/runtime.py +225 -0
  64. assaystone/scorecard.py +163 -0
  65. assaystone/verifiers.py +318 -0
  66. assaystone/workspace.py +73 -0
  67. assaystone-0.3.0.dist-info/METADATA +417 -0
  68. assaystone-0.3.0.dist-info/RECORD +72 -0
  69. assaystone-0.3.0.dist-info/WHEEL +5 -0
  70. assaystone-0.3.0.dist-info/entry_points.txt +5 -0
  71. assaystone-0.3.0.dist-info/licenses/LICENSE +202 -0
  72. assaystone-0.3.0.dist-info/top_level.txt +1 -0
assaystone/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """Assaystone — the assay stone for AI agents."""
2
+
3
+ __version__ = "0.3.0"
4
+
5
+ from .contract import Contract
6
+ from .model import Artifact, Label, Step, Trace, Verdict
7
+ from .runner import run_contract
8
+ from .verifiers import REGISTRY, Verifier, load_external_verifiers, register
9
+ from . import packs as _packs # noqa: F401 (registers built-in domain packs)
10
+
11
+ load_external_verifiers()
12
+
13
+ __all__ = [
14
+ "Artifact",
15
+ "Contract",
16
+ "Label",
17
+ "REGISTRY",
18
+ "Step",
19
+ "Trace",
20
+ "Verdict",
21
+ "Verifier",
22
+ "register",
23
+ "run_contract",
24
+ ]
assaystone/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,16 @@
1
+ """Trace adapters for popular agent frameworks."""
2
+ from .messages import (
3
+ artifacts_from_git,
4
+ from_claude_agent,
5
+ from_langgraph,
6
+ from_messages,
7
+ from_openai_agents,
8
+ )
9
+
10
+ __all__ = [
11
+ "artifacts_from_git",
12
+ "from_claude_agent",
13
+ "from_langgraph",
14
+ "from_messages",
15
+ "from_openai_agents",
16
+ ]
@@ -0,0 +1,254 @@
1
+ """Turn framework message lists into Assaystone traces.
2
+
3
+ The adapter is intentionally duck-typed: it accepts dicts or SDK objects from
4
+ the Claude Agent SDK, OpenAI-style chat/tool messages, and most LangGraph
5
+ message states. It never imports a framework.
6
+
7
+ from assaystone.adapters import from_claude_agent
8
+ trace = from_claude_agent(messages, artifacts=artifacts, task="fix the bug")
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import subprocess
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any, Iterable, Sequence
17
+
18
+ from ..model import Artifact, Step, Trace
19
+
20
+
21
+ def _get(obj: Any, key: str, default: Any = None) -> Any:
22
+ if isinstance(obj, dict):
23
+ return obj.get(key, default)
24
+ return getattr(obj, key, default)
25
+
26
+
27
+ def _as_args(value: Any) -> dict[str, Any]:
28
+ if isinstance(value, dict):
29
+ return dict(value)
30
+ if isinstance(value, str):
31
+ try:
32
+ parsed = json.loads(value)
33
+ except json.JSONDecodeError:
34
+ return {"raw": value}
35
+ return parsed if isinstance(parsed, dict) else {"value": parsed}
36
+ return {"value": value} if value is not None else {}
37
+
38
+
39
+ def _stringify(content: Any) -> str:
40
+ if content is None:
41
+ return ""
42
+ if isinstance(content, str):
43
+ return content
44
+ if isinstance(content, list):
45
+ parts: list[str] = []
46
+ for item in content:
47
+ if isinstance(item, str):
48
+ parts.append(item)
49
+ elif isinstance(item, dict):
50
+ if item.get("type") == "text":
51
+ parts.append(str(item.get("text", "")))
52
+ else:
53
+ parts.append(json.dumps(item, ensure_ascii=False))
54
+ else:
55
+ text = getattr(item, "text", None)
56
+ parts.append(str(text) if text is not None else repr(item))
57
+ return "\n".join(part for part in parts if part)
58
+ return str(content)
59
+
60
+
61
+ def _blocks(content: Any) -> list[Any]:
62
+ if isinstance(content, str):
63
+ return [{"type": "text", "text": content}]
64
+ if isinstance(content, list):
65
+ return content
66
+ if content is None:
67
+ return []
68
+ return [content]
69
+
70
+
71
+ _BLOCK_TYPES = {
72
+ "textblock": "text",
73
+ "tooluseblock": "tool_use",
74
+ "toolresultblock": "tool_result",
75
+ "thinkingblock": "thinking",
76
+ }
77
+
78
+
79
+ def _block_type(block: Any) -> str:
80
+ explicit = _get(block, "type")
81
+ if explicit:
82
+ return str(explicit)
83
+ name = type(block).__name__.lower()
84
+ return _BLOCK_TYPES.get(name, name)
85
+
86
+
87
+ def from_messages(
88
+ messages: Sequence[Any],
89
+ *,
90
+ artifacts: Iterable[Artifact] | None = None,
91
+ task: str = "",
92
+ agent: str = "agent",
93
+ trace_id: str | None = None,
94
+ evidence: dict[str, Any] | None = None,
95
+ ) -> Trace:
96
+ """Build a Trace from a list of framework messages."""
97
+ steps: list[Step] = []
98
+ pending: dict[str, int] = {}
99
+ assistant_text: list[str] = []
100
+ input_text = ""
101
+ final_message = ""
102
+ result_meta: dict[str, Any] = {}
103
+ session_id = ""
104
+
105
+ for message in messages:
106
+ message_type = str(_get(message, "type") or _get(message, "role") or "").lower()
107
+ content = _get(message, "content")
108
+
109
+ if message_type == "result":
110
+ final_message = _stringify(_get(message, "result") or content)
111
+ for key in (
112
+ "subtype",
113
+ "is_error",
114
+ "duration_ms",
115
+ "duration_api_ms",
116
+ "num_turns",
117
+ "total_cost_usd",
118
+ "session_id",
119
+ ):
120
+ value = _get(message, key)
121
+ if value is not None:
122
+ result_meta[key] = value
123
+ session_id = str(_get(message, "session_id") or session_id)
124
+ continue
125
+
126
+ if message_type in ("system",):
127
+ continue
128
+
129
+ if message_type in ("assistant", "ai", "model"):
130
+ for call in _get(message, "tool_calls") or []:
131
+ function = _get(call, "function") or {}
132
+ name = _get(function, "name") or _get(call, "name") or "tool"
133
+ raw_args = _get(function, "arguments")
134
+ if raw_args is None:
135
+ raw_args = _get(call, "args") # LangChain / LangGraph shape
136
+ step = Step(tool=str(name), args=_as_args(raw_args), result="", ok=True)
137
+ steps.append(step)
138
+ call_id = _get(call, "id")
139
+ if call_id:
140
+ pending[str(call_id)] = len(steps) - 1
141
+
142
+ for block in _blocks(content):
143
+ block_type = _block_type(block)
144
+ if block_type == "text":
145
+ text = _stringify(_get(block, "text"))
146
+ if text:
147
+ assistant_text.append(text)
148
+ elif block_type == "tool_use":
149
+ name = _get(block, "name") or "tool"
150
+ step = Step(tool=str(name), args=_as_args(_get(block, "input")), result="", ok=True)
151
+ steps.append(step)
152
+ call_id = _get(block, "id")
153
+ if call_id:
154
+ pending[str(call_id)] = len(steps) - 1
155
+ continue
156
+
157
+ if message_type in ("user", "human"):
158
+ for block in _blocks(content):
159
+ block_type = _block_type(block)
160
+ if block_type == "tool_result":
161
+ call_id = _get(block, "tool_use_id") or _get(block, "tool_call_id")
162
+ output = _stringify(_get(block, "content"))
163
+ is_error = bool(_get(block, "is_error", False))
164
+ if call_id and str(call_id) in pending:
165
+ step = steps[pending[str(call_id)]]
166
+ step.result = output
167
+ step.ok = not is_error
168
+ elif block_type == "text":
169
+ text = _stringify(_get(block, "text"))
170
+ if text and not input_text:
171
+ input_text = text
172
+ continue
173
+
174
+ if message_type == "tool":
175
+ call_id = _get(message, "tool_call_id")
176
+ output = _stringify(content)
177
+ is_error = bool(_get(message, "is_error", False))
178
+ if call_id and str(call_id) in pending:
179
+ step = steps[pending[str(call_id)]]
180
+ step.result = output
181
+ step.ok = not is_error
182
+
183
+ if not final_message:
184
+ final_message = assistant_text[-1] if assistant_text else ""
185
+
186
+ trace_evidence = dict(evidence or {})
187
+ if result_meta:
188
+ trace_evidence["agent_result"] = result_meta
189
+
190
+ return Trace(
191
+ id=trace_id or session_id or f"trace-{int(time.time() * 1000)}",
192
+ task=task,
193
+ agent=agent,
194
+ input=input_text,
195
+ steps=steps,
196
+ artifacts=list(artifacts or []),
197
+ final_message=final_message,
198
+ evidence=trace_evidence,
199
+ )
200
+
201
+
202
+ def from_claude_agent(messages: Sequence[Any], **kwargs: Any) -> Trace:
203
+ """Adapter for Claude Agent SDK message streams."""
204
+ kwargs.setdefault("agent", "claude-agent-sdk")
205
+ return from_messages(messages, **kwargs)
206
+
207
+
208
+ def from_openai_agents(messages: Sequence[Any], **kwargs: Any) -> Trace:
209
+ """Adapter for OpenAI-style chat, tool-call, and tool-result messages."""
210
+ kwargs.setdefault("agent", "openai-agents")
211
+ return from_messages(messages, **kwargs)
212
+
213
+
214
+ def from_langgraph(state: Any, **kwargs: Any) -> Trace:
215
+ """Adapter for a LangGraph state dict (or a bare message list)."""
216
+ messages = state.get("messages", state) if isinstance(state, dict) else state
217
+ kwargs.setdefault("agent", "langgraph")
218
+ return from_messages(messages, **kwargs)
219
+
220
+
221
+ def artifacts_from_git(repo: str | Path, base: str = "HEAD") -> list[Artifact]:
222
+ """Collect tracked changes vs ``base`` plus untracked files as artifacts."""
223
+
224
+ root = Path(repo)
225
+
226
+ def run(*args: str) -> subprocess.CompletedProcess[str]:
227
+ return subprocess.run(
228
+ ["git", "-C", str(root), *args],
229
+ capture_output=True,
230
+ text=True,
231
+ )
232
+
233
+ diff = run("diff", "--name-only", base)
234
+ if diff.returncode != 0:
235
+ return []
236
+ paths = {line.strip() for line in diff.stdout.splitlines() if line.strip()}
237
+
238
+ untracked = run("ls-files", "--others", "--exclude-standard")
239
+ if untracked.returncode == 0:
240
+ paths.update(line.strip() for line in untracked.stdout.splitlines() if line.strip())
241
+
242
+ artifacts: list[Artifact] = []
243
+ for relative in sorted(paths):
244
+ path = root / relative
245
+ if not path.exists():
246
+ artifacts.append(Artifact(relative, "", "deleted"))
247
+ continue
248
+ try:
249
+ content = path.read_text(encoding="utf-8")
250
+ except (UnicodeDecodeError, OSError):
251
+ continue
252
+ in_base = run("cat-file", "-e", f"{base}:{relative}").returncode == 0
253
+ artifacts.append(Artifact(relative, content, "modified" if in_base else "added"))
254
+ return artifacts