cacherift 0.2.0__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 (67) hide show
  1. cacherift-0.2.0/LICENSE +193 -0
  2. cacherift-0.2.0/PKG-INFO +177 -0
  3. cacherift-0.2.0/README.md +152 -0
  4. cacherift-0.2.0/pyproject.toml +75 -0
  5. cacherift-0.2.0/setup.cfg +4 -0
  6. cacherift-0.2.0/src/cacherift/__init__.py +5 -0
  7. cacherift-0.2.0/src/cacherift/capabilities/__init__.py +1 -0
  8. cacherift-0.2.0/src/cacherift/capabilities/registry.py +176 -0
  9. cacherift-0.2.0/src/cacherift/capabilities/tables/default_capabilities.toml +156 -0
  10. cacherift-0.2.0/src/cacherift/capabilities/tables/default_pricing.toml +232 -0
  11. cacherift-0.2.0/src/cacherift/check/__init__.py +1 -0
  12. cacherift-0.2.0/src/cacherift/check/cli.py +126 -0
  13. cacherift-0.2.0/src/cacherift/check/evaluator.py +158 -0
  14. cacherift-0.2.0/src/cacherift/check/policy.py +204 -0
  15. cacherift-0.2.0/src/cacherift/check/pytest_plugin.py +103 -0
  16. cacherift-0.2.0/src/cacherift/cli.py +383 -0
  17. cacherift-0.2.0/src/cacherift/core/__init__.py +1 -0
  18. cacherift-0.2.0/src/cacherift/core/diagnoser.py +441 -0
  19. cacherift-0.2.0/src/cacherift/core/diff.py +455 -0
  20. cacherift-0.2.0/src/cacherift/core/freeze.py +86 -0
  21. cacherift-0.2.0/src/cacherift/core/lineage.py +267 -0
  22. cacherift-0.2.0/src/cacherift/core/models.py +248 -0
  23. cacherift-0.2.0/src/cacherift/core/pricing.py +112 -0
  24. cacherift-0.2.0/src/cacherift/core/span.py +149 -0
  25. cacherift-0.2.0/src/cacherift/dialects/__init__.py +1 -0
  26. cacherift-0.2.0/src/cacherift/dialects/anthropic_messages.py +283 -0
  27. cacherift-0.2.0/src/cacherift/dialects/base.py +304 -0
  28. cacherift-0.2.0/src/cacherift/dialects/deepseek_chat.py +49 -0
  29. cacherift-0.2.0/src/cacherift/dialects/gemini_generate.py +144 -0
  30. cacherift-0.2.0/src/cacherift/dialects/openai_chat.py +139 -0
  31. cacherift-0.2.0/src/cacherift/dialects/openai_responses.py +265 -0
  32. cacherift-0.2.0/src/cacherift/io/__init__.py +1 -0
  33. cacherift-0.2.0/src/cacherift/io/capture.py +132 -0
  34. cacherift-0.2.0/src/cacherift/io/redact.py +94 -0
  35. cacherift-0.2.0/src/cacherift/probe/__init__.py +1 -0
  36. cacherift-0.2.0/src/cacherift/probe/budget.py +151 -0
  37. cacherift-0.2.0/src/cacherift/probe/cli.py +399 -0
  38. cacherift-0.2.0/src/cacherift/probe/runner.py +383 -0
  39. cacherift-0.2.0/src/cacherift/probe/scenarios.py +369 -0
  40. cacherift-0.2.0/src/cacherift/proxy/__init__.py +1 -0
  41. cacherift-0.2.0/src/cacherift/proxy/app.py +436 -0
  42. cacherift-0.2.0/src/cacherift/proxy/cli.py +130 -0
  43. cacherift-0.2.0/src/cacherift/proxy/recorder.py +95 -0
  44. cacherift-0.2.0/src/cacherift/proxy/sse.py +122 -0
  45. cacherift-0.2.0/src/cacherift/repair/__init__.py +1 -0
  46. cacherift-0.2.0/src/cacherift/repair/cli.py +177 -0
  47. cacherift-0.2.0/src/cacherift/repair/engine.py +174 -0
  48. cacherift-0.2.0/src/cacherift/repair/models.py +90 -0
  49. cacherift-0.2.0/src/cacherift/repair/rules.py +226 -0
  50. cacherift-0.2.0/src/cacherift.egg-info/PKG-INFO +177 -0
  51. cacherift-0.2.0/src/cacherift.egg-info/SOURCES.txt +65 -0
  52. cacherift-0.2.0/src/cacherift.egg-info/dependency_links.txt +1 -0
  53. cacherift-0.2.0/src/cacherift.egg-info/entry_points.txt +5 -0
  54. cacherift-0.2.0/src/cacherift.egg-info/requires.txt +19 -0
  55. cacherift-0.2.0/src/cacherift.egg-info/top_level.txt +1 -0
  56. cacherift-0.2.0/tests/test_check.py +612 -0
  57. cacherift-0.2.0/tests/test_cli_dispatch.py +179 -0
  58. cacherift-0.2.0/tests/test_diagnoser_counterexamples.py +787 -0
  59. cacherift-0.2.0/tests/test_dialects.py +763 -0
  60. cacherift-0.2.0/tests/test_diff_growth.py +255 -0
  61. cacherift-0.2.0/tests/test_lineage.py +184 -0
  62. cacherift-0.2.0/tests/test_probe.py +1220 -0
  63. cacherift-0.2.0/tests/test_proxy.py +1166 -0
  64. cacherift-0.2.0/tests/test_redact.py +53 -0
  65. cacherift-0.2.0/tests/test_repair.py +675 -0
  66. cacherift-0.2.0/tests/test_span_and_freeze.py +248 -0
  67. cacherift-0.2.0/tests/test_usage_and_pricing.py +261 -0
@@ -0,0 +1,193 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated into the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Work; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the NOTICE text file contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Work, in at least one of the
111
+ following places: within a NOTICE text file distributed
112
+ as part of the Work; within the Source form or
113
+ documentation, if provided along with the Work; or, within a
114
+ display generated by the Derivative Works, if and wherever such
115
+ third-party notices normally appear. The contents of the NOTICE
116
+ file are for informational purposes only and do not modify the
117
+ License. You may add Your own copyright notice to Your
118
+ Derivative Works and may provide additional or different
119
+ license terms and conditions for use, reproduction, or
120
+ distribution of Your Derivative Works, or for any such
121
+ Contribution, as a whole, provided Your use, reproduction, or
122
+ distribution of the Work otherwise complies with the conditions
123
+ stated in this License.
124
+
125
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
126
+ any Contribution intentionally submitted for inclusion in the Work
127
+ by You to the Licensor shall be under the terms and conditions of
128
+ this License, without any additional terms or conditions.
129
+ Notwithstanding the above, nothing herein shall supersede or modify
130
+ the terms of any separate license agreement you may have executed
131
+ with Licensor regarding such Contributions.
132
+
133
+ 6. Trademarks. This License does not grant permission to use the trade
134
+ names, trademarks, service marks, or product names of the Licensor,
135
+ except as required for reasonable and customary use in describing the
136
+ origin of the Work and reproducing the content of the NOTICE file.
137
+
138
+ 7. Disclaimer of Warranty. Unless required by applicable law or
139
+ agreed to in writing, Licensor provides the Work (and each
140
+ Contributor provides its Contributions) on an "AS IS" BASIS,
141
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
142
+ implied, including, without limitation, any warranties or conditions
143
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A
144
+ PARTICULAR PURPOSE. You are solely responsible for determining the
145
+ appropriateness of using or redistributing the Work and assume any
146
+ risks associated with Your exercise of permissions under this License.
147
+
148
+ 8. Limitation of Liability. In no event and under no theory of
149
+ liability, whether in contract, strict liability, or tort
150
+ (including negligence or otherwise) arising in any way out of the
151
+ use of the Work, even if advised of the possibility of such damages.
152
+ IN NO EVENT SHALL LICENSOR OR CONTRIBUTORS BE LIABLE FOR ANY DAMAGES
153
+ ARISING OUT OF THE USE OR OTHER LIABILITY, WHETHER IN CONTRACT,
154
+ TORT, OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
155
+ WORK OR THE USE OR OTHER DEALINGS IN THE WORK.
156
+
157
+ 9. Accepting Warranty or Additional Liability. While redistributing
158
+ the Work or Derivative Works thereof, You may choose to offer,
159
+ and charge a fee for, acceptance of support, warranty, indemnity,
160
+ or other liability obligations and/or rights consistent with this
161
+ License. However, in accepting such obligations, You may act only
162
+ on Your own behalf and on Your sole responsibility, not on behalf
163
+ of any other Contributor, and only if You agree to indemnify,
164
+ defend, and hold each Contributor harmless for any liability
165
+ incurred by, or claims asserted against, such Contributor by reason
166
+ of your accepting any such warranty or additional liability.
167
+
168
+ END OF TERMS AND CONDITIONS
169
+
170
+ APPENDIX: How to apply the Apache License to your work.
171
+
172
+ To apply the Apache License to your work, attach the following
173
+ boilerplate notice, with the fields enclosed by brackets "[]"
174
+ replaced with your own identifying information. (Don't include
175
+ the brackets!) The text should be enclosed in the appropriate
176
+ comment syntax for the file format. We also recommend that a
177
+ file or class name and description of purpose be included on the
178
+ same "printed page" as the copyright notice for easier
179
+ identification within third-party archives.
180
+
181
+ Copyright 2026 CacheRift Contributors
182
+
183
+ Licensed under the Apache License, Version 2.0 (the "License");
184
+ you may not use this file except in compliance with the License.
185
+ You may obtain a copy of the License at
186
+
187
+ http://www.apache.org/licenses/LICENSE-2.0
188
+
189
+ Unless required by applicable law or agreed to in writing, software
190
+ distributed under the License is distributed on an "AS IS" BASIS,
191
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
192
+ See the License for the specific language governing permissions and
193
+ limitations under the License.
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.4
2
+ Name: cacherift
3
+ Version: 0.2.0
4
+ Summary: An open-source Python toolkit for detecting, diagnosing, and repairing silent prompt cache failures in multi-turn AI agents.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: rich>=13.7
10
+ Provides-Extra: probe
11
+ Requires-Dist: httpx>=0.27; extra == "probe"
12
+ Provides-Extra: proxy
13
+ Requires-Dist: httpx>=0.27; extra == "proxy"
14
+ Requires-Dist: uvicorn>=0.30; extra == "proxy"
15
+ Provides-Extra: all
16
+ Requires-Dist: httpx>=0.27; extra == "all"
17
+ Requires-Dist: uvicorn>=0.30; extra == "all"
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8.0; extra == "dev"
20
+ Requires-Dist: ruff>=0.6; extra == "dev"
21
+ Requires-Dist: mypy>=1.11; extra == "dev"
22
+ Requires-Dist: httpx>=0.27; extra == "dev"
23
+ Requires-Dist: uvicorn>=0.30; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # CacheRift
27
+
28
+ **Prompt Cache Reliability for AI Agents**
29
+
30
+ **Find the break. Restore the cache.**
31
+
32
+ `cacherift` is an open-source Python toolkit for detecting, diagnosing, and repairing silent prompt cache failures in multi-turn AI agents.
33
+
34
+ ## Status
35
+
36
+ Five commands around one pure, offline diagnostic kernel:
37
+
38
+ | Command | What it does | Touches the disk |
39
+ |---|---|---|
40
+ | `analyze` | Diagnoses a JSONL capture turn by turn | Never |
41
+ | `probe` | Sends small, controlled probes to an upstream and captures what really comes back | Only with `--execute` |
42
+ | `proxy` | Local read-only proxy that captures real agent traffic | Appends to one capture file |
43
+ | `check` | Turns diagnoses into pass / fail; also a pytest plugin | Never |
44
+ | `repair` | Rewrites the few prefix defects that are provably equivalent for the model | Only with `--apply --output` |
45
+
46
+ ### What the kernel detects
47
+
48
+ - **Exact wire vs. structural diff**: Distinguishes JSON formatting/escaping differences (`WIRE_ONLY_DIFF`), normal multi-turn conversation growth (`NORMAL_APPEND`), upstream tool insertions (`INSERTED_BEFORE_TAIL`), object/array reordering (`REORDERED_EXISTING`), edits (`MUTATED_EXISTING`), deletions (`DELETED_EXISTING`), compaction (`COMPACTED_OR_TRUNCATED`), and parameter changes (`CONFIG_CHANGED`).
49
+ - **Two complete dialect pipelines**: OpenAI Responses (including `prompt_cache_diagnostics` and generation-specific ordering such as GPT-6.2 top-level `instructions`) and Anthropic Messages (including `diagnostics.previous_message_id`, tiered 5m/1h write buckets, and a non-overlapping `total_input` denominator).
50
+ - **Partial usage-only adapters**: OpenAI Chat Completions, DeepSeek Chat, and Gemini `generateContent`.
51
+ - **Evidence-graded diagnosis**: Local observations, provider-native diagnostics, lineage resolution (`NO_BASELINE` / `AMBIGUOUS` / `MATCHED`), capability metadata, and optional versioned pricing estimates, kept distinct. No cross-provider hit-rate thresholds.
52
+ - **Zero-snippet redaction by default**: Output carries `json_path`, byte spans, lengths, and SHA-256 fingerprints. Prompt text appears only with `--include-snippets`. Credential headers are replaced with `[REDACTED]` wherever a capture is stored.
53
+
54
+ ## Quick Start
55
+
56
+ Offline diagnosis of a capture:
57
+
58
+ ```bash
59
+ cacherift analyze path/to/captures.jsonl
60
+ ```
61
+
62
+ ```bash
63
+ cacherift analyze path/to/captures.jsonl --format json --pricing-table default-2026-11
64
+ ```
65
+
66
+ ### `probe`: measure what an upstream really does
67
+
68
+ Prints the plan and its worst-case cost; nothing is sent:
69
+
70
+ ```bash
71
+ cacherift probe --dialect openai_responses --base-url https://api.openai.com/v1 --model gpt-6.1-sol
72
+ ```
73
+
74
+ Send it, with the API key read from `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`), under a hard cap of 12 requests and $0.10 (use `--prefix-tokens` if an endpoint needs a different prefix size):
75
+
76
+ ```bash
77
+ cacherift probe --dialect openai_responses --base-url https://api.openai.com/v1 --model gpt-6.1-sol --execute --output probe.jsonl
78
+ ```
79
+
80
+ Scenarios are admitted as whole groups: a scenario whose worst-case cost does not fit the remaining budget is skipped and reported, never cut in half. A model with no pricing rule cannot be probed, because its cost cannot be bounded.
81
+
82
+ Everything that can be refused is refused before the first request goes out, including an output path that already exists or cannot be written. The capture file is written as each response arrives, so an interrupted run keeps what it paid for.
83
+
84
+ ### `proxy`: capture a real agent
85
+
86
+ ```bash
87
+ cacherift proxy --upstream https://api.openai.com --output session.jsonl --live
88
+ ```
89
+
90
+ Point the agent's base URL at `http://127.0.0.1:8787/v1`. Request bodies pass through byte for byte and are recorded as received. An optional `x-cacherift-session-id` header groups requests into a session; without it, lineage is resolved from the traffic itself.
91
+
92
+ Streamed responses (`text/event-stream`) are parsed for all five dialects. Chat Completions, DeepSeek and Gemini usage is taken from the last frame that carries it and never summed across frames; Anthropic usage is the final snapshot (`message_start` merged with the last `message_delta`); OpenAI Responses usage comes from the `response.completed` frame. Two shapes are not parsed: a Gemini `streamGenerateContent` call made without `alt=sse` answers with a JSON array, and a Gemini stream that closes early cannot be told from one that ended. A Chat Completions stream only contains usage when the client sets `stream_options.include_usage`; without it the turn is reported as missing usage, not as zero. `--live` keeps diagnosis state in memory, which grows with the traffic captured; for a long-running proxy, leave it off and run `cacherift analyze` on the capture file afterwards.
93
+
94
+ ### `check`: gate a build
95
+
96
+ ```bash
97
+ cacherift check session.jsonl --format github
98
+ ```
99
+
100
+ Exit `0` when no error-level rule is hit, `1` when one is, `2` when the capture or the policy cannot be read. Rules look at the shape of the prefix and at the usage report, never at the hit rate. Settings live in a `[check]` table of `cacherift.toml` or in `[tool.cacherift.check]` of `pyproject.toml`, and only override the rules they name:
101
+
102
+ ```toml
103
+ [check]
104
+ ignore = ["non_cacheable_top_level_instructions"]
105
+ ignore_paths = ["$.messages[*].content[*].cache_control"]
106
+ ```
107
+
108
+ In tests, check a prompt builder without any network:
109
+
110
+ ```python
111
+ def test_prompt_builder_keeps_its_prefix(cacherift_session):
112
+ for turn in range(1, 4):
113
+ cacherift_session.add(build_request(turn))
114
+ cacherift_session.assert_stable()
115
+ ```
116
+
117
+ ### `repair`: fix what is provably safe
118
+
119
+ ```bash
120
+ cacherift repair session.jsonl
121
+ ```
122
+
123
+ ```bash
124
+ cacherift repair session.jsonl --apply --output repaired.jsonl --audit-out audit.json
125
+ ```
126
+
127
+ Four rules only: tool key order aligned to the parent turn, tool array order restored with new tools last, static top-level `instructions` moved into a developer message, and stale Anthropic breakpoints removed. Free text is never rewritten. Records with ambiguous lineage, or on targets the capability table does not fully support, are refused and listed.
128
+
129
+ ## Integrating CacheRift
130
+
131
+ Pointing an agent at the proxy from the OpenAI SDK, the Anthropic SDK, Claude Code or LangChain, gating a GitHub Actions build with `check`, and using the pytest fixture are described in [docs/integrations.md](docs/integrations.md).
132
+
133
+ ## Installation
134
+
135
+ ```bash
136
+ pip install cacherift
137
+ ```
138
+
139
+ `analyze`, `check` and the pytest plugin need nothing beyond the core install. The two commands that talk to the network are optional extras:
140
+
141
+ ```bash
142
+ pip install 'cacherift[probe]'
143
+ ```
144
+
145
+ ```bash
146
+ pip install 'cacherift[proxy]'
147
+ ```
148
+
149
+ ### Core-only isolation
150
+
151
+ `analyze`, `check` and `repair` must keep working in an installation that has neither `httpx` nor `uvicorn`. CI checks this on every pull request and on every push to `main`. To run the same check on your machine, create a fresh virtual environment with Python 3.12 or newer, install only the core package and pytest into it, and run the verification script, all from the repository root:
152
+
153
+ ```bash
154
+ python3 -m venv /tmp/cacherift-core-only
155
+ ```
156
+
157
+ ```bash
158
+ /tmp/cacherift-core-only/bin/python -m pip install --upgrade pip
159
+ ```
160
+
161
+ ```bash
162
+ /tmp/cacherift-core-only/bin/python -m pip install . pytest
163
+ ```
164
+
165
+ ```bash
166
+ /tmp/cacherift-core-only/bin/python scripts/verify_install.py core-only
167
+ ```
168
+
169
+ The script checks that neither `httpx` nor `uvicorn` can be imported, that the help of every command works, that `probe` and `proxy` exit with a one-line install hint, that `analyze`, `check` and `repair` run on the captured fixtures, and that the tests pass without the two packages.
170
+
171
+ ## Changelog
172
+
173
+ Changes between versions are listed in [CHANGELOG.md](CHANGELOG.md).
174
+
175
+ ## License
176
+
177
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,152 @@
1
+ # CacheRift
2
+
3
+ **Prompt Cache Reliability for AI Agents**
4
+
5
+ **Find the break. Restore the cache.**
6
+
7
+ `cacherift` is an open-source Python toolkit for detecting, diagnosing, and repairing silent prompt cache failures in multi-turn AI agents.
8
+
9
+ ## Status
10
+
11
+ Five commands around one pure, offline diagnostic kernel:
12
+
13
+ | Command | What it does | Touches the disk |
14
+ |---|---|---|
15
+ | `analyze` | Diagnoses a JSONL capture turn by turn | Never |
16
+ | `probe` | Sends small, controlled probes to an upstream and captures what really comes back | Only with `--execute` |
17
+ | `proxy` | Local read-only proxy that captures real agent traffic | Appends to one capture file |
18
+ | `check` | Turns diagnoses into pass / fail; also a pytest plugin | Never |
19
+ | `repair` | Rewrites the few prefix defects that are provably equivalent for the model | Only with `--apply --output` |
20
+
21
+ ### What the kernel detects
22
+
23
+ - **Exact wire vs. structural diff**: Distinguishes JSON formatting/escaping differences (`WIRE_ONLY_DIFF`), normal multi-turn conversation growth (`NORMAL_APPEND`), upstream tool insertions (`INSERTED_BEFORE_TAIL`), object/array reordering (`REORDERED_EXISTING`), edits (`MUTATED_EXISTING`), deletions (`DELETED_EXISTING`), compaction (`COMPACTED_OR_TRUNCATED`), and parameter changes (`CONFIG_CHANGED`).
24
+ - **Two complete dialect pipelines**: OpenAI Responses (including `prompt_cache_diagnostics` and generation-specific ordering such as GPT-6.2 top-level `instructions`) and Anthropic Messages (including `diagnostics.previous_message_id`, tiered 5m/1h write buckets, and a non-overlapping `total_input` denominator).
25
+ - **Partial usage-only adapters**: OpenAI Chat Completions, DeepSeek Chat, and Gemini `generateContent`.
26
+ - **Evidence-graded diagnosis**: Local observations, provider-native diagnostics, lineage resolution (`NO_BASELINE` / `AMBIGUOUS` / `MATCHED`), capability metadata, and optional versioned pricing estimates, kept distinct. No cross-provider hit-rate thresholds.
27
+ - **Zero-snippet redaction by default**: Output carries `json_path`, byte spans, lengths, and SHA-256 fingerprints. Prompt text appears only with `--include-snippets`. Credential headers are replaced with `[REDACTED]` wherever a capture is stored.
28
+
29
+ ## Quick Start
30
+
31
+ Offline diagnosis of a capture:
32
+
33
+ ```bash
34
+ cacherift analyze path/to/captures.jsonl
35
+ ```
36
+
37
+ ```bash
38
+ cacherift analyze path/to/captures.jsonl --format json --pricing-table default-2026-11
39
+ ```
40
+
41
+ ### `probe`: measure what an upstream really does
42
+
43
+ Prints the plan and its worst-case cost; nothing is sent:
44
+
45
+ ```bash
46
+ cacherift probe --dialect openai_responses --base-url https://api.openai.com/v1 --model gpt-6.1-sol
47
+ ```
48
+
49
+ Send it, with the API key read from `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`), under a hard cap of 12 requests and $0.10 (use `--prefix-tokens` if an endpoint needs a different prefix size):
50
+
51
+ ```bash
52
+ cacherift probe --dialect openai_responses --base-url https://api.openai.com/v1 --model gpt-6.1-sol --execute --output probe.jsonl
53
+ ```
54
+
55
+ Scenarios are admitted as whole groups: a scenario whose worst-case cost does not fit the remaining budget is skipped and reported, never cut in half. A model with no pricing rule cannot be probed, because its cost cannot be bounded.
56
+
57
+ Everything that can be refused is refused before the first request goes out, including an output path that already exists or cannot be written. The capture file is written as each response arrives, so an interrupted run keeps what it paid for.
58
+
59
+ ### `proxy`: capture a real agent
60
+
61
+ ```bash
62
+ cacherift proxy --upstream https://api.openai.com --output session.jsonl --live
63
+ ```
64
+
65
+ Point the agent's base URL at `http://127.0.0.1:8787/v1`. Request bodies pass through byte for byte and are recorded as received. An optional `x-cacherift-session-id` header groups requests into a session; without it, lineage is resolved from the traffic itself.
66
+
67
+ Streamed responses (`text/event-stream`) are parsed for all five dialects. Chat Completions, DeepSeek and Gemini usage is taken from the last frame that carries it and never summed across frames; Anthropic usage is the final snapshot (`message_start` merged with the last `message_delta`); OpenAI Responses usage comes from the `response.completed` frame. Two shapes are not parsed: a Gemini `streamGenerateContent` call made without `alt=sse` answers with a JSON array, and a Gemini stream that closes early cannot be told from one that ended. A Chat Completions stream only contains usage when the client sets `stream_options.include_usage`; without it the turn is reported as missing usage, not as zero. `--live` keeps diagnosis state in memory, which grows with the traffic captured; for a long-running proxy, leave it off and run `cacherift analyze` on the capture file afterwards.
68
+
69
+ ### `check`: gate a build
70
+
71
+ ```bash
72
+ cacherift check session.jsonl --format github
73
+ ```
74
+
75
+ Exit `0` when no error-level rule is hit, `1` when one is, `2` when the capture or the policy cannot be read. Rules look at the shape of the prefix and at the usage report, never at the hit rate. Settings live in a `[check]` table of `cacherift.toml` or in `[tool.cacherift.check]` of `pyproject.toml`, and only override the rules they name:
76
+
77
+ ```toml
78
+ [check]
79
+ ignore = ["non_cacheable_top_level_instructions"]
80
+ ignore_paths = ["$.messages[*].content[*].cache_control"]
81
+ ```
82
+
83
+ In tests, check a prompt builder without any network:
84
+
85
+ ```python
86
+ def test_prompt_builder_keeps_its_prefix(cacherift_session):
87
+ for turn in range(1, 4):
88
+ cacherift_session.add(build_request(turn))
89
+ cacherift_session.assert_stable()
90
+ ```
91
+
92
+ ### `repair`: fix what is provably safe
93
+
94
+ ```bash
95
+ cacherift repair session.jsonl
96
+ ```
97
+
98
+ ```bash
99
+ cacherift repair session.jsonl --apply --output repaired.jsonl --audit-out audit.json
100
+ ```
101
+
102
+ Four rules only: tool key order aligned to the parent turn, tool array order restored with new tools last, static top-level `instructions` moved into a developer message, and stale Anthropic breakpoints removed. Free text is never rewritten. Records with ambiguous lineage, or on targets the capability table does not fully support, are refused and listed.
103
+
104
+ ## Integrating CacheRift
105
+
106
+ Pointing an agent at the proxy from the OpenAI SDK, the Anthropic SDK, Claude Code or LangChain, gating a GitHub Actions build with `check`, and using the pytest fixture are described in [docs/integrations.md](docs/integrations.md).
107
+
108
+ ## Installation
109
+
110
+ ```bash
111
+ pip install cacherift
112
+ ```
113
+
114
+ `analyze`, `check` and the pytest plugin need nothing beyond the core install. The two commands that talk to the network are optional extras:
115
+
116
+ ```bash
117
+ pip install 'cacherift[probe]'
118
+ ```
119
+
120
+ ```bash
121
+ pip install 'cacherift[proxy]'
122
+ ```
123
+
124
+ ### Core-only isolation
125
+
126
+ `analyze`, `check` and `repair` must keep working in an installation that has neither `httpx` nor `uvicorn`. CI checks this on every pull request and on every push to `main`. To run the same check on your machine, create a fresh virtual environment with Python 3.12 or newer, install only the core package and pytest into it, and run the verification script, all from the repository root:
127
+
128
+ ```bash
129
+ python3 -m venv /tmp/cacherift-core-only
130
+ ```
131
+
132
+ ```bash
133
+ /tmp/cacherift-core-only/bin/python -m pip install --upgrade pip
134
+ ```
135
+
136
+ ```bash
137
+ /tmp/cacherift-core-only/bin/python -m pip install . pytest
138
+ ```
139
+
140
+ ```bash
141
+ /tmp/cacherift-core-only/bin/python scripts/verify_install.py core-only
142
+ ```
143
+
144
+ The script checks that neither `httpx` nor `uvicorn` can be imported, that the help of every command works, that `probe` and `proxy` exit with a one-line install hint, that `analyze`, `check` and `repair` run on the captured fixtures, and that the tests pass without the two packages.
145
+
146
+ ## Changelog
147
+
148
+ Changes between versions are listed in [CHANGELOG.md](CHANGELOG.md).
149
+
150
+ ## License
151
+
152
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,75 @@
1
+ [build-system]
2
+ # The `license` expression and `license-files` below follow PEP 639, which setuptools 77 added.
3
+ requires = ["setuptools>=77"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [project]
7
+ name = "cacherift"
8
+ version = "0.2.0"
9
+ description = "An open-source Python toolkit for detecting, diagnosing, and repairing silent prompt cache failures in multi-turn AI agents."
10
+ readme = "README.md"
11
+ requires-python = ">=3.12"
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE"]
14
+ dependencies = [
15
+ "rich>=13.7",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ probe = [
20
+ "httpx>=0.27",
21
+ ]
22
+ proxy = [
23
+ "httpx>=0.27",
24
+ "uvicorn>=0.30",
25
+ ]
26
+ all = [
27
+ "httpx>=0.27",
28
+ "uvicorn>=0.30",
29
+ ]
30
+ dev = [
31
+ "pytest>=8.0",
32
+ "ruff>=0.6",
33
+ "mypy>=1.11",
34
+ "httpx>=0.27",
35
+ "uvicorn>=0.30",
36
+ ]
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "pytest>=8.0",
41
+ "ruff>=0.6",
42
+ "mypy>=1.11",
43
+ "httpx>=0.27",
44
+ "uvicorn>=0.30",
45
+ ]
46
+
47
+ [project.scripts]
48
+ cacherift = "cacherift.cli:main"
49
+
50
+ [project.entry-points."pytest11"]
51
+ cacherift = "cacherift.check.pytest_plugin"
52
+
53
+ [tool.setuptools.packages.find]
54
+ where = ["src"]
55
+
56
+ [tool.setuptools.package-data]
57
+ "cacherift.capabilities.tables" = ["*.toml"]
58
+
59
+ [tool.pytest.ini_options]
60
+ testpaths = ["tests"]
61
+ pythonpath = ["src"]
62
+
63
+ [tool.ruff]
64
+ target-version = "py312"
65
+ line-length = 100
66
+ src = ["src", "tests"]
67
+
68
+ [tool.ruff.lint]
69
+ select = ["E", "F", "I", "UP", "B", "SIM"]
70
+
71
+ [tool.mypy]
72
+ python_version = "3.12"
73
+ strict = true
74
+ warn_unused_configs = true
75
+ mypy_path = "src"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """CacheRift: Prompt Cache Reliability for AI Agents."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ __all__ = ["__version__"]
@@ -0,0 +1 @@
1
+ """Capability and pricing registries backed by versioned static TOML tables."""