agenttwin 0.1.1__tar.gz

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 (60) hide show
  1. agenttwin-0.1.1/CHANGELOG.md +45 -0
  2. agenttwin-0.1.1/LICENSE +202 -0
  3. agenttwin-0.1.1/MANIFEST.in +2 -0
  4. agenttwin-0.1.1/PKG-INFO +347 -0
  5. agenttwin-0.1.1/README.md +317 -0
  6. agenttwin-0.1.1/README.zh-CN.md +318 -0
  7. agenttwin-0.1.1/pyproject.toml +49 -0
  8. agenttwin-0.1.1/setup.cfg +4 -0
  9. agenttwin-0.1.1/src/agenttwin/__init__.py +73 -0
  10. agenttwin-0.1.1/src/agenttwin/__main__.py +14 -0
  11. agenttwin-0.1.1/src/agenttwin/adapters/__init__.py +22 -0
  12. agenttwin-0.1.1/src/agenttwin/adapters/base.py +96 -0
  13. agenttwin-0.1.1/src/agenttwin/adapters/openai_compatible.py +329 -0
  14. agenttwin-0.1.1/src/agenttwin/asserts.py +872 -0
  15. agenttwin-0.1.1/src/agenttwin/cli.py +655 -0
  16. agenttwin-0.1.1/src/agenttwin/diff.py +218 -0
  17. agenttwin-0.1.1/src/agenttwin/drift.py +94 -0
  18. agenttwin-0.1.1/src/agenttwin/env.py +369 -0
  19. agenttwin-0.1.1/src/agenttwin/fingerprint.py +114 -0
  20. agenttwin-0.1.1/src/agenttwin/fixtures/cleanup.jsonl +7 -0
  21. agenttwin-0.1.1/src/agenttwin/fixtures/cleanup_guarded.jsonl +5 -0
  22. agenttwin-0.1.1/src/agenttwin/fixtures/correct_shipping.jsonl +5 -0
  23. agenttwin-0.1.1/src/agenttwin/fixtures/deathloop.jsonl +22 -0
  24. agenttwin-0.1.1/src/agenttwin/fixtures/double_shipping.jsonl +7 -0
  25. agenttwin-0.1.1/src/agenttwin/fixtures/full_receipt.jsonl +5 -0
  26. agenttwin-0.1.1/src/agenttwin/fixtures/partial_receipt.jsonl +5 -0
  27. agenttwin-0.1.1/src/agenttwin/fixtures/repaired.jsonl +5 -0
  28. agenttwin-0.1.1/src/agenttwin/fixtures/search_first.jsonl +7 -0
  29. agenttwin-0.1.1/src/agenttwin/fixtures/write_first.jsonl +7 -0
  30. agenttwin-0.1.1/src/agenttwin/gallery.py +591 -0
  31. agenttwin-0.1.1/src/agenttwin/html/__init__.py +19 -0
  32. agenttwin-0.1.1/src/agenttwin/html/replayer.html +1468 -0
  33. agenttwin-0.1.1/src/agenttwin/proxy.py +431 -0
  34. agenttwin-0.1.1/src/agenttwin/record.py +104 -0
  35. agenttwin-0.1.1/src/agenttwin/redact.py +167 -0
  36. agenttwin-0.1.1/src/agenttwin/report.py +318 -0
  37. agenttwin-0.1.1/src/agenttwin/trace.py +391 -0
  38. agenttwin-0.1.1/src/agenttwin.egg-info/PKG-INFO +347 -0
  39. agenttwin-0.1.1/src/agenttwin.egg-info/SOURCES.txt +58 -0
  40. agenttwin-0.1.1/src/agenttwin.egg-info/dependency_links.txt +1 -0
  41. agenttwin-0.1.1/src/agenttwin.egg-info/entry_points.txt +2 -0
  42. agenttwin-0.1.1/src/agenttwin.egg-info/requires.txt +6 -0
  43. agenttwin-0.1.1/src/agenttwin.egg-info/top_level.txt +1 -0
  44. agenttwin-0.1.1/tests/test_adapters.py +486 -0
  45. agenttwin-0.1.1/tests/test_asserts.py +745 -0
  46. agenttwin-0.1.1/tests/test_cli.py +509 -0
  47. agenttwin-0.1.1/tests/test_diff.py +403 -0
  48. agenttwin-0.1.1/tests/test_drift.py +84 -0
  49. agenttwin-0.1.1/tests/test_env.py +369 -0
  50. agenttwin-0.1.1/tests/test_fingerprint.py +158 -0
  51. agenttwin-0.1.1/tests/test_gallery.py +402 -0
  52. agenttwin-0.1.1/tests/test_hero.py +55 -0
  53. agenttwin-0.1.1/tests/test_proxy.py +208 -0
  54. agenttwin-0.1.1/tests/test_readme.py +115 -0
  55. agenttwin-0.1.1/tests/test_record.py +113 -0
  56. agenttwin-0.1.1/tests/test_redact.py +305 -0
  57. agenttwin-0.1.1/tests/test_replayer_html.py +290 -0
  58. agenttwin-0.1.1/tests/test_report.py +401 -0
  59. agenttwin-0.1.1/tests/test_report_html.py +157 -0
  60. agenttwin-0.1.1/tests/test_trace.py +450 -0
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ Every release is tagged in git and published on PyPI. The tape format is
4
+ `schema 0.1` for all of them, so a tape recorded by an older release still
5
+ replays on a newer one: the package version in the fingerprint is compared
6
+ major.minor, so a patch release never invalidates a tape.
7
+
8
+ ## 0.1.1 — 2026-11-05
9
+
10
+ Documentation, one viewer fix and one change of meaning; the tape format is
11
+ untouched.
12
+
13
+ ### Added
14
+
15
+ - `examples/hero.py` and `assets/hero.gif`: one committed tape replayed twice —
16
+ faithful first (exit 1), then with a single policy key changed (exit 0). Both
17
+ README editions embed the animation and quote the same transcript, and
18
+ `tests/test_hero.py` keeps that transcript equal to a real run.
19
+ - A `Changelog` link in the package metadata.
20
+
21
+ ### Fixed
22
+
23
+ - The offline viewer's state-diff panel drew eighteen rows as ten-pixel slivers:
24
+ the list is a flex column with `overflow: auto`, so every row was shrinking to
25
+ fit instead of scrolling. Rows keep their height now.
26
+ - `README` installation instructions now lead with `pip install agenttwin`;
27
+ the `-e .` path is mentioned only for working on a checkout.
28
+
29
+ ### Changed
30
+
31
+ - A replay that carries a patch or an explicit `policy=` now reports
32
+ `mode: counterfactual`, and its divergence no longer forces exit code 2 — the
33
+ assertions decide. A faithful replay (neither supplied) still treats any
34
+ divergence as exit 2, which is the check that catches a controller that stopped
35
+ reproducing the recorded run.
36
+ - `fingerprint._DEFAULT_VERSION` no longer repeats the package version; the
37
+ single source of truth is `agenttwin.__version__`.
38
+
39
+ ## 0.1.0 — 2026-11-05
40
+
41
+ First public release: record / replay / counterfactual, the four drift classes,
42
+ nine assertion factories plus combinators and YAML loading, seq-aligned
43
+ `TraceDiff`, the single-file HTML viewer and report, the five `agenttwin`
44
+ commands, the openai-compatible adapter, and ten bundled fixtures in five
45
+ before/after pairs.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ include CHANGELOG.md
2
+ include README.zh-CN.md
@@ -0,0 +1,347 @@
1
+ Metadata-Version: 2.1
2
+ Name: agenttwin
3
+ Version: 0.1.1
4
+ Summary: Frozen-replay for LLM agents: record one JSONL tape, replay it deterministically, diff what changed.
5
+ Author: ravenkernel
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/ravenkernel/agenttwin
8
+ Project-URL: Source, https://github.com/ravenkernel/agenttwin
9
+ Project-URL: Issues, https://github.com/ravenkernel/agenttwin/issues
10
+ Project-URL: Changelog, https://github.com/ravenkernel/agenttwin/blob/main/CHANGELOG.md
11
+ Keywords: llm,agents,replay,record,determinism,testing
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Testing
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Provides-Extra: yaml
27
+ Requires-Dist: pyyaml; extra == "yaml"
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=7; extra == "dev"
30
+
31
+ [English](README.md) · [中文](README.zh-CN.md)
32
+
33
+ # AgentTwin
34
+
35
+ **The VCR for agents.** Record one agent run to a tape, replay it offline afterwards, and you have a unit test you can commit to CI.
36
+
37
+ Not a trace dashboard, not a monitoring platform: no service, no database, no dashboard, just one JSONL file and one ordinary assertion.
38
+
39
+ ![One failing tape, one policy change: the offline viewer, before and after](https://raw.githubusercontent.com/ravenkernel/agenttwin/main/assets/hero.gif)
40
+
41
+ *One committed tape, replayed twice with no model call: two assertions fail, one policy key changes, all three pass. What you are looking at is a single HTML file, opened from `file://`.*
42
+
43
+ The 30-second version:
44
+
45
+ 1. Recording calls the model and writes the request hash and the response into the tape;
46
+ 2. Replay calls no model and executes no real tool; it walks the tape event by event;
47
+ 3. A mismatch is a failure (not "run it again and see"); the assertion result ends up as a process exit code.
48
+
49
+ Every code block below was actually run against this repository. The Python and YAML blocks run in order on the tape recorded by the first one; the shell blocks only need the fixtures that ship inside the package. The output under a block is the output of that run.
50
+
51
+ ## 1. Record one run
52
+
53
+ `record_demo.py`
54
+
55
+ ```python
56
+ """Record one agent run to a JSONL tape. Run: python record_demo.py"""
57
+ import json
58
+
59
+ from agenttwin import Twin
60
+
61
+
62
+ def fake_llm(request): # stands in for your model client
63
+ return {"text": f"order {request['prompt']} is on its way"}
64
+
65
+
66
+ def lookup_order(order_id): # stands in for a real, side-effecting tool
67
+ return {"order_id": order_id, "status": "paid"}
68
+
69
+
70
+ def agent(llm, tools): # your agent: identical when replaying
71
+ reply = llm({"prompt": "A-1"})
72
+ order = tools["lookup_order"]("A-1")
73
+ return {"answer": reply["text"], "status": order["status"]}
74
+
75
+
76
+ with Twin.record("checkout", out="checkout.jsonl",
77
+ llm=fake_llm, tools={"lookup_order": lookup_order}) as rec:
78
+ rec.returned(agent(rec.llm, rec.tools())) # leaving the block writes the tape
79
+
80
+ lines = open("checkout.jsonl", encoding="utf-8").read().splitlines()
81
+ header = json.loads(lines[0])
82
+ print("header:", header["schema_version"], header["trace_id"], "seed=" + str(header["seed"]))
83
+ print("events:", " -> ".join(json.loads(line)["kind"] for line in lines[1:]))
84
+ print("line 2:", lines[1][:96] + " ...")
85
+ ```
86
+
87
+ Output:
88
+
89
+ ```text
90
+ header: 0.1 checkout seed=0
91
+ events: llm_call -> tool_call -> tool_result -> terminal
92
+ line 2: {"actor":"llm","kind":"llm_call","payload":{"prompt_hash":"1d783fcd9d8b565fc5b19532a4538139c2ab6 ...
93
+ ```
94
+
95
+ Only the last three lines do the recording: run the agent once inside `with Twin.record(...) as rec:`, keep the return value with `rec.returned(...)`, and the tape is written when the `with` block exits.
96
+
97
+ `checkout.jsonl` is plain JSONL: the first line is the header (`schema_version` / `trace_id` / `seed` / `env_fingerprint` / `redaction`), then one event per line; there are exactly 8 `kind`s: `llm_call`, `tool_call`, `tool_result`, `state_patch`, `decision`, `human_input`, `error`, `terminal`. Any text tool can read it.
98
+
99
+ ## 2. Replay offline, then assert
100
+
101
+ Keep going in the same directory:
102
+
103
+ `replay_demo.py`
104
+
105
+ ```python
106
+ """Replay the tape offline and assert on it. Run after record_demo.py, same dir."""
107
+ import sys
108
+
109
+ from agenttwin import Twin, asserts
110
+
111
+
112
+ def agent(llm, tools): # the same agent, character for character
113
+ reply = llm({"prompt": "A-1"})
114
+ order = tools["lookup_order"]("A-1")
115
+ return {"answer": reply["text"], "status": order["status"]}
116
+
117
+
118
+ report = Twin.load("checkout.jsonl").replay(agent) # note: no llm=, no tools=
119
+ report.assert_(
120
+ asserts.max_repeats("lookup_order", n=1),
121
+ asserts.never_calls("refund"),
122
+ asserts.terminates_within(10),
123
+ )
124
+
125
+ for result in report.results:
126
+ status = "SKIP" if result.passed is None else ("PASS" if result.passed else "FAIL")
127
+ print(f"{status} {result.name}")
128
+ page = report.html("report.html") # one self-contained file, opens from file://
129
+ print(f"html: {page.name} ({page.stat().st_size} bytes)")
130
+ print(f"divergent: {report.divergent}")
131
+ print(f"exit code: {report.exit_code}")
132
+ sys.exit(report.exit_code)
133
+ ```
134
+
135
+ Output:
136
+
137
+ ```text
138
+ PASS max_repeats(lookup_order, n=1)
139
+ PASS never_calls(refund)
140
+ PASS terminates_within(n=10)
141
+ html: report.html (56546 bytes)
142
+ divergent: False
143
+ exit code: 0
144
+ ```
145
+
146
+ Two things that are easy to miss:
147
+
148
+ - `Twin.load("checkout.jsonl").replay(agent)` takes no `llm=` and no `tools=`: both the model and the tools come from the tape. `llm(...)` returns the response as recorded, `tools["lookup_order"](...)` returns the result as recorded, and the real functions are never called.
149
+ - `sys.exit(report.exit_code)` turns the assertion result into an ordinary exit code that `pytest` or any CI consumes directly.
150
+
151
+ The same result in three shapes: `report.markdown()` (a table for humans), `report.json()` (for machines, with fixed top-level keys `schema_version` / `trace_id` / `mode` / `divergent` / `exit_code` / `results` / `misses` / `drifts` / `diff` / `header`), and `report.html("report.html")` (a single-file report, no external references, opens straight from `file://`; the byte count above varies a little with the tape and the environment). The viewer carries an English/Chinese switch in its header (the choice is remembered in `localStorage`); the recorded tape text itself is never translated.
152
+
153
+ ### The whole loop in one command
154
+
155
+ `examples/hero.py` is the animation at the top of this page: one tape from the fixtures that ship with the package, replayed twice, with one policy key changed between the two runs.
156
+
157
+ ```bash
158
+ PYTHONPATH=src python examples/hero.py
159
+ ```
160
+
161
+ Output:
162
+
163
+ ```text
164
+ tape: deathloop.jsonl (21 events)
165
+ no model call, no network, no API key: the tape is the whole environment
166
+
167
+ before mode=replay recorded (no policy passed)
168
+ exit code 1
169
+ FAIL max_repeats(shell, n=3) -- 6 calls of shell exceeds the limit of 3; first excess at seq 12 (seq 12)
170
+ FAIL budget_within(calls<=8) -- calls 13 > 8 (first excess at seq 12) (seq 12)
171
+ PASS never_calls(shell, args_contains='rm -rf') -- no call of shell matches
172
+
173
+ after mode=counterfactual policy={'max_attempts': 6, 'stop_on_failure': True}
174
+ exit code 0
175
+ PASS max_repeats(shell, n=3) -- 0 call(s) of shell (limit 3)
176
+ PASS budget_within(calls<=8) -- calls 2/8
177
+ PASS never_calls(shell, args_contains='rm -rf') -- no call of shell matches
178
+
179
+ first divergence: seq 3 (same tape, different trajectory)
180
+ reports: build/hero/before.html build/hero/after.html
181
+ ```
182
+
183
+ The word `counterfactual` in that banner is the point. A replay that carries a patch or its own policy is asking "what if", so the viewer labels it as one and its divergence is not a failure. A replay that carries neither has to reproduce the tape event for event, and divergence there is still exit code 2.
184
+
185
+ ## 3. A changed request is a hard failure
186
+
187
+ ```python
188
+ """A changed request is a hard failure, not a flaky test. Run after record_demo.py."""
189
+ from agenttwin import DriftError, Twin
190
+
191
+
192
+ def changed_agent(llm, tools):
193
+ llm({"prompt": "A-2"}) # one value changed in the request
194
+ tools["lookup_order"]("A-1")
195
+
196
+
197
+ try:
198
+ Twin.load("checkout.jsonl").replay(changed_agent)
199
+ except DriftError as exc: # PromptDrift / ArgsDrift / FingerprintDrift
200
+ detail = exc.message.replace(exc.expected, exc.expected[:8] + "...").replace(exc.actual, exc.actual[:8] + "...")
201
+ print(f"{type(exc).__name__}: {detail}")
202
+ raise SystemExit(2)
203
+ ```
204
+
205
+ Output:
206
+
207
+ ```text
208
+ PromptDrift: prompt_hash mismatch at seq 0: tape expects 1d783fcd..., controller sent 4250ccd5...
209
+ ```
210
+
211
+ Note that it raises instead of noting the mismatch and carrying on: the replay stops right there, and `SystemExit(2)` turns it into a red job in CI.
212
+
213
+ ## 4. Assertions can be data too (optional `[yaml]`)
214
+
215
+ `asserts.yaml`:
216
+
217
+ ```yaml
218
+ # The same three checks as replay_demo.py, kept as data.
219
+ - {spec: max_repeats, args: {tool: lookup_order, n: 1}}
220
+ - {spec: never_calls, args: {tool: refund}}
221
+ - {spec: terminates_within, args: {n: 10}}
222
+ ```
223
+
224
+ `yaml_demo.py`:
225
+
226
+ ```python
227
+ """The same three checks as data. Run after record_demo.py."""
228
+ from agenttwin import Twin, asserts
229
+
230
+
231
+ def agent(llm, tools):
232
+ reply = llm({"prompt": "A-1"})
233
+ order = tools["lookup_order"]("A-1")
234
+ return {"answer": reply["text"], "status": order["status"]}
235
+
236
+
237
+ report = Twin.load("checkout.jsonl").replay(agent)
238
+ report.assert_(*asserts.load_yaml("asserts.yaml")) # needs the [yaml] extra
239
+
240
+ for result in report.results:
241
+ print(f"{'PASS' if result.passed else 'FAIL'} {result.name}")
242
+ print("exit code:", report.exit_code)
243
+ ```
244
+
245
+ Output:
246
+
247
+ ```text
248
+ PASS max_repeats(lookup_order, n=1)
249
+ PASS never_calls(refund)
250
+ PASS terminates_within(n=10)
251
+ exit code: 0
252
+ ```
253
+
254
+ ## What this tape does not promise
255
+
256
+ This section sits on the second screen because the most common question is "why did nothing change when I changed the temperature".
257
+
258
+ - **What is frozen is the request and the response as recorded, not an inference pass you can run again.** The model is not called a second time during replay, so sampling parameters (temperature / top_p / seed) do not participate and do not affect the result. Conversely, if your agent puts temperature into the request dict, it is part of the request, it changes the `prompt_hash`, and it raises `PromptDrift`: a changed request is supposed to fail.
259
+ - **No real side effects.** A tool call during replay returns the `result` from the tape and the real function does not execute; there is no "call it for real while we are here" either, `Twin.load(..., allow_real=True)` raises `ValueError` outright.
260
+ - **No second model call.** No network requests, no token bill; as many `llm_call`s as the tape holds is as many replays as you get, and not one more appears out of nowhere.
261
+ - **All four drift kinds are hard failures.** `DriftError` and its three subclasses `PromptDrift` / `ArgsDrift` / `FingerprintDrift` are raised and stop the replay; `TapeMiss` (nothing recorded for that call) is not a drift and is not raised, but it also turns `exit_code` into 2.
262
+ - **Replay is not "run the agent again".** A tape hit does not re-execute the model or the tool, and a tape miss does not degrade into a real call.
263
+
264
+ ## What it does not do
265
+
266
+ | Not doing | Why |
267
+ | --- | --- |
268
+ | Calling the LLM again | Replay is worth exactly its determinism and its zero cost; for new results, record a new tape |
269
+ | Producing real side effects | Replay has to run in CI, on a machine with no network |
270
+ | Promising zero-config support for every framework | You write the agent as `agent(llm, tools)`, or as an object with `run(llm, tools)`; the tape knows nothing about your framework |
271
+ | SaaS / dashboard / database | The tape is a file and the report is a file; there is no backend to host |
272
+ | LLM-as-judge for pass or fail | The verdict has to be a deterministic assertion; asking a model to grade brings the uncertainty right back |
273
+
274
+ ## Install
275
+
276
+ ```bash
277
+ python -m pip install agenttwin
278
+ ```
279
+
280
+ Working on a clone of this repository instead, `python -m pip install -e .`.
281
+
282
+ An extra dependency is needed only to read and write YAML assertion files (`pyyaml` is imported lazily, inside `load_yaml()` only):
283
+
284
+ ```bash
285
+ python -m pip install "agenttwin[yaml]"
286
+ ```
287
+
288
+ Python 3.10+, zero third-party dependencies at runtime: `pyproject.toml` declares `dependencies = []`, and `import agenttwin` does not pull in `pyyaml`.
289
+
290
+ ### Exit codes
291
+
292
+ | code | meaning |
293
+ | --- | --- |
294
+ | 0 | everything PASSes (SKIP is not a failure) |
295
+ | 1 | an assertion FAILed |
296
+ | 2 | Drift / TapeMiss / SchemaError / incompatible schema |
297
+ | 3 | configuration or install error (missing tape, broken assertion file, missing dependency) |
298
+
299
+ `--strict` turns SKIP into 1, with precedence 3 > 2 > 1 > 0. `Report.exit_code` only ever produces 0 / 1 / 2; 3 comes from the CLI's usage and configuration layer (`EXIT_USAGE = 3` in `agenttwin.cli`: the tape does not exist, `--agent` is malformed, the assertion file cannot be read).
300
+
301
+ ### Command line
302
+
303
+ Once installed, `agenttwin` and `python -m agenttwin` are the same entry point (`agenttwin.cli:main`), with five subcommands: `record` / `replay` / `diff` / `doctor` / `gallery`. To see the ten fixtures shipped with the repo (five before/after pairs, one per assertion family), without recording a tape first:
304
+
305
+ ```bash
306
+ python -m agenttwin gallery list
307
+ python -m agenttwin gallery run deathloop
308
+ ```
309
+
310
+ Output (the second command prints the head of a report and its assertion table; the Diff / Fingerprint / Redaction sections in between are elided, `...` marks the gap):
311
+
312
+ ```text
313
+ deathloop Checkout retry loop
314
+ repaired Checkout that stops on the failed observation
315
+ cleanup Cleanup that deletes build/ with rm -rf
316
+ cleanup_guarded Cleanup that leaves the tree alone
317
+ write_first Release note written before the search
318
+ search_first Release note that cites what it found
319
+ partial_receipt Receipt without the charged total
320
+ full_receipt Receipt that carries the total it charged
321
+ double_shipping Order that pays shipping twice
322
+ correct_shipping Order priced once
323
+
324
+ # AgentTwin report: gallery-deathloop
325
+
326
+ verdict: FAIL (exit code 1)
327
+ mode: replay
328
+ divergent: no
329
+ strict: no
330
+ ...
331
+ | name | status | detail | first_offense_seq |
332
+ | --- | --- | --- | --- |
333
+ | max_repeats(shell, n=3) | FAIL | 6 calls of shell exceeds the limit of 3; first excess at seq 12 | 12 |
334
+ | budget_within(calls<=8) | FAIL | calls 13 > 8 (first excess at seq 12) | 12 |
335
+ | never_calls(shell, args_contains='rm -rf') | PASS | no call of shell matches | - |
336
+ ```
337
+
338
+ `gallery run deathloop` exits 1 and `gallery run repaired` exits 0: same assertion set, and the only difference is whether that agent repeats the same tool call a thirteenth time. The other four pairs are the same shape: `cleanup` / `cleanup_guarded` (`never_calls`), `write_first` / `search_first` (`call_order`), `partial_receipt` / `full_receipt` (`output_schema`), `double_shipping` / `correct_shipping` (`state_invariant`). `python -m agenttwin <command> --help` shows the arguments of each command.
339
+
340
+ ## Status
341
+
342
+ 0.1.1 is published: [agenttwin on PyPI](https://pypi.org/project/agenttwin/0.1.1/), Apache-2.0, Python 3.10+. What changed in each release: [CHANGELOG.md](CHANGELOG.md).
343
+
344
+ - Done and tested: the record/replay core (`Twin.record` / `Twin.load`), drift detection, 9 assertion factories plus the combinators and YAML loading, `TraceDiff`, `Report` (JSON / Markdown / single-file HTML), the five `agenttwin` subcommands, the openai-compatible adapter (duck-typed, no SDK import), and the ten bundled fixtures (five before/after pairs).
345
+ - Verified on GitHub: [CI](https://github.com/ravenkernel/agenttwin/actions) runs on every push to `main` — eight jobs: Python 3.10–3.13 on Ubuntu, 3.12 on macOS and Windows, and two stdlib-only import checks that uninstall PyYAML first, plus a console-script step in each. The first run failed on a fixture that used `platform: linux` and therefore matched the real `sys.platform` on the Ubuntu runners; that was a test bug, fixed in `6c5dae7`, and the suite has been green since.
346
+ - Verified from a clean install: `python -m pip install agenttwin` into an empty venv from the public index gives `agenttwin --version` → `agenttwin 0.1.1`, all ten fixtures from `agenttwin gallery list`, the bundled single-file HTML replayer, `gallery run repaired` → 0 and `gallery run deathloop` → 1. A record → offline replay → `.html()` loop run from an empty directory outside the repository produced a report with no unfilled placeholder and no external resource in it.
347
+ - Not done yet: a coverage gate, any hosted service or dashboard. The examples above run with `PYTHONPATH=src` so they work without installing anything.