consequence-gate 0.1.1__tar.gz → 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 (54) hide show
  1. consequence_gate-0.2.0/LICENSE +202 -0
  2. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/PKG-INFO +66 -24
  3. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/README.md +59 -22
  4. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/__init__.py +1 -1
  5. consequence_gate-0.2.0/consequence_gate/backtest/harness.py +62 -0
  6. consequence_gate-0.2.0/consequence_gate/backtest/reporter.py +29 -0
  7. consequence_gate-0.2.0/consequence_gate/cli.py +166 -0
  8. consequence_gate-0.2.0/consequence_gate/core/approval.py +16 -0
  9. consequence_gate-0.2.0/consequence_gate/core/circuit_breaker.py +91 -0
  10. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/core/evaluator.py +5 -5
  11. consequence_gate-0.2.0/consequence_gate/core/evidence.py +172 -0
  12. consequence_gate-0.2.0/consequence_gate/core/models.py +37 -0
  13. consequence_gate-0.2.0/consequence_gate/core/store.py +140 -0
  14. consequence_gate-0.2.0/consequence_gate/core/thresholds.py +5 -0
  15. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/integrations/examples/run_langgraph.py +4 -2
  16. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/integrations/examples/run_mcp_proxy.py +11 -6
  17. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/integrations/langgraph_hook.py +54 -20
  18. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/integrations/mcp_proxy.py +127 -35
  19. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/integrations/strands_hook.py +48 -18
  20. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/simulators/communications.py +89 -31
  21. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/simulators/database.py +92 -28
  22. consequence_gate-0.2.0/consequence_gate/simulators/financial.py +164 -0
  23. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate.egg-info/PKG-INFO +66 -24
  24. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate.egg-info/SOURCES.txt +9 -0
  25. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate.egg-info/requires.txt +3 -0
  26. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/pyproject.toml +9 -3
  27. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/tests/test_circuit_breaker.py +10 -7
  28. consequence_gate-0.2.0/tests/test_circuit_breaker_strict.py +68 -0
  29. consequence_gate-0.2.0/tests/test_cli.py +45 -0
  30. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/tests/test_communications_sim.py +23 -10
  31. consequence_gate-0.2.0/tests/test_database_explain_fixture.py +307 -0
  32. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/tests/test_database_sim.py +1 -1
  33. consequence_gate-0.2.0/tests/test_evidence_envelope.py +123 -0
  34. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/tests/test_financial_sim.py +6 -3
  35. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/tests/test_langgraph_hook.py +133 -32
  36. consequence_gate-0.2.0/tests/test_mcp_proxy.py +455 -0
  37. consequence_gate-0.2.0/tests/test_sqlite_store.py +210 -0
  38. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/tests/test_strands_hook.py +72 -8
  39. consequence_gate-0.1.1/consequence_gate/backtest/harness.py +0 -43
  40. consequence_gate-0.1.1/consequence_gate/backtest/reporter.py +0 -20
  41. consequence_gate-0.1.1/consequence_gate/cli.py +0 -75
  42. consequence_gate-0.1.1/consequence_gate/core/circuit_breaker.py +0 -56
  43. consequence_gate-0.1.1/consequence_gate/core/models.py +0 -35
  44. consequence_gate-0.1.1/consequence_gate/simulators/financial.py +0 -102
  45. consequence_gate-0.1.1/tests/test_cli.py +0 -34
  46. consequence_gate-0.1.1/tests/test_mcp_proxy.py +0 -198
  47. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/backtest/__init__.py +0 -0
  48. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/core/__init__.py +0 -0
  49. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/integrations/__init__.py +0 -0
  50. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate/simulators/__init__.py +0 -0
  51. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate.egg-info/dependency_links.txt +0 -0
  52. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate.egg-info/entry_points.txt +0 -0
  53. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/consequence_gate.egg-info/top_level.txt +0 -0
  54. {consequence_gate-0.1.1 → consequence_gate-0.2.0}/setup.cfg +0 -0
@@ -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.
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: consequence-gate
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Speculative outcome-simulation layer for AI agent tool calls — predicts consequence (blast radius, irreversibility, velocity) before execution and steers agents toward safer alternatives.
5
- Author-email: Anandkrishnan Shnn <anandkrshnn@gmail.com>
5
+ Author-email: Anandkrishnan Shnn <anandkrshnn@outlook.com>
6
6
  License: Apache-2.0
7
7
  Project-URL: Homepage, https://github.com/anandkrshnn-ai/consequence-gate
8
8
  Project-URL: Documentation, https://github.com/anandkrshnn-ai/consequence-gate#readme
@@ -21,11 +21,15 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
21
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
22
  Requires-Python: >=3.10
23
23
  Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: pydantic>=2.5.0
26
+ Requires-Dist: cryptography>=42.0.0
24
27
  Provides-Extra: dev
25
28
  Requires-Dist: pytest>=7.0; extra == "dev"
26
29
  Requires-Dist: pytest-cov>=4.0; extra == "dev"
27
30
  Requires-Dist: black>=23.0; extra == "dev"
28
31
  Requires-Dist: ruff>=0.1.0; extra == "dev"
32
+ Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
29
33
  Provides-Extra: mcp
30
34
  Provides-Extra: langgraph
31
35
  Requires-Dist: langgraph>=0.2.0; extra == "langgraph"
@@ -33,22 +37,31 @@ Requires-Dist: langchain-core>=0.3.0; extra == "langgraph"
33
37
  Provides-Extra: langchain
34
38
  Requires-Dist: langchain>=0.3.0; extra == "langchain"
35
39
  Requires-Dist: langchain-core>=0.3.0; extra == "langchain"
40
+ Dynamic: license-file
36
41
 
37
42
  # consequence-gate
38
43
 
44
+ [![CI](https://github.com/anandkrshnn-ai/consequence-gate/actions/workflows/ci.yml/badge.svg)](https://github.com/anandkrshnn-ai/consequence-gate/actions/workflows/ci.yml)
45
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](https://pypi.org/project/consequence-gate/)
46
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
47
+ [![Tests](https://img.shields.io/badge/tests-30%20passed-success.svg)](tests/)
48
+ [![Coverage](https://img.shields.io/badge/coverage-core%2090%25%2B-brightgreen.svg)](tests/)
49
+
50
+ **[Try the interactive demo ⚡](https://consequence-gate-demo-mu.vercel.app/)**
51
+
39
52
  A speculative outcome-simulation layer for AI agent tool calls. It sits
40
53
  **upstream** of static runtime access gates (AgentWall, AWS Strands
41
54
  `BeforeToolCallEvent`, MCP proxies, Prisma AIRS) and asks a different
42
55
  question than they do.
43
56
 
44
- Static gates ask: *does this call match an allowed pattern?*
57
+ Static gates ask: *does this call match an allowed pattern or schema?*
45
58
  `consequence-gate` asks: *what will this call actually do, and is that
46
59
  outcome safe?*
47
60
 
48
61
  ## Why this exists
49
62
 
50
63
  Static runtime gates are fast (sub-millisecond) and effective at schema
51
- validation, RBAC, and pattern matching -- but a schema-valid,
64
+ validation, RBAC, and pattern matching — but a schema-valid,
52
65
  policy-compliant call can still be consequence-catastrophic. A
53
66
  `process_claim(amount=50000)` call can pass every static check while
54
67
  pushing an account over its daily velocity limit via an irreversible
@@ -59,8 +72,8 @@ either passes it through, asks a human, denies it outright, or steers
59
72
  the agent toward a pre-vetted safer alternative.
60
73
 
61
74
  This is explicitly **not** a replacement for AgentWall / Strands / MCP
62
- proxies -- it's a prediction layer that runs before them, in the same
63
- pipeline.
75
+ proxies — it is an outcome prediction layer that runs upstream of them in the same pipeline.
76
+
64
77
 
65
78
  ## Core contracts
66
79
 
@@ -221,34 +234,63 @@ agent = Agent(hooks=[hook])
221
234
  ## Decision Matrix
222
235
 
223
236
  | Decision | Strands | MCP | LangGraph |
224
- |----------|---------|-----|-----------|
237
+ |---|---|---|---|
225
238
  | `ALLOW` | Executes normally | Forwarded to downstream MCP server | Tool executes via handler(request) |
226
239
  | `DENY` | `BLOCKED: <reason>` | JSON-RPC error (code=-32603) | Raises `ValueError("BLOCKED: ...")` |
227
240
  | `ASK` | `ESCALATION_REQUIRED: <reason>` | `isError=true` tool result | Raises `ValueError("ESCALATION_REQUIRED: ...")` |
228
241
  | `STEER` | `STEER_GUIDANCE: <guidance>\nSuggested alternative...` | `isError=true` + guidance | `ToolMessage(content="STEER_GUIDANCE: ...", status="error")` |
229
242
 
230
- ## Backtest Workflow
243
+ ## Trust Model & Failure Modes
244
+
245
+ `consequence-gate` evaluates consequence by combining tool invocation parameters with runtime state returned from your `context_provider` callback (e.g. `account_rolling_24h_spend`, `kyc_verified`, `table_metadata`).
246
+
247
+ ### Critical Failure Modes & Mitigations
248
+
249
+ | Failure Mode | Risk | Mitigation in Consequence-Gate |
250
+ |---|---|---|
251
+ | **Stale Context / Cache Lag** | Context provider returns yesterday's spend balance, potentially missing velocity breaches. | If context is unverified or confidence drops below `0.8`, the gate **always defaults to `ASK` (human escalation)**. It never grants a speculative `ALLOW`. |
252
+ | **Missing Context Provider** | Tool is invoked without any environment or database connection. | The simulator scores confidence as `0.0` or `0.5` and raises an escalation requirement (`ASK`). |
253
+ | **Agent Steering Thrashing** | The agent repeatedly submits non-compliant alternative calls in response to guidance. | The `SteerCircuitBreaker` enforces a hard retry cap (default: 2 retries) before terminating the loop and escalating to human review. |
254
+ | **Replay / Network Retries** | Network timeout causes agent runtime to resubmit the identical tool call. | Idempotency tokens are deterministically keyed to the entity's natural business key, guaranteeing identical evaluation without incrementing velocity counters twice. |
255
+
256
+ See [SECURITY.md](SECURITY.md) for full trust boundary documentation.
257
+
258
+ ## Offline Backtest Benchmark
259
+
260
+ Before deploying to production, run an offline backtest against historical execution traces to measure the four-quadrant FP/FN/TN breakdown:
231
261
 
232
- Before deploying to production, run an offline backtest against historical
233
- execution traces:
262
+ ```bash
263
+ # Run backtest on the bundled 500-trace synthetic benchmark dataset
264
+ consequence-gate backtest examples/benchmark_traces.jsonl
265
+ ```
266
+
267
+ ### Empirical Benchmark Summary (500 Synthetic Traces)
268
+
269
+ *(Note: Evaluated on a synthetically generated trace corpus `examples/benchmark_traces.jsonl` to validate harness mechanics end-to-end; see [BACKTEST_RESULTS.md](BACKTEST_RESULTS.md) for disclosure)*
234
270
 
235
- 1. Export 1,000-5,000 tool-call traces as JSONL (see `examples/backtest_sample_traces.jsonl`)
236
- 2. Run `python examples/run_backtest_demo.py` against your traces
237
- 3. Review the four-quadrant breakdown:
238
- - True Negative: correctly allowed benign operations
239
- - False Negative Caught: schema-valid calls that would have breached limits
240
- - False Positive Relieved: over-blocking that the simulator would have avoided
241
- - Steer Recovery Rate: percentage of blocked turns that could have completed via guidance
271
+ - **Benign Pass-Through (True Negatives):** 252 (50.4%) — Benign operations passed through.
272
+ - **Downstream Hazards Intercepted:** 129 (25.8%) — Schema-valid hazards caught before execution.
273
+ - **Over-Blocked Operations Relieved:** 35 (7.0%) — Benign calls over-blocked by naive regex gates safely enabled.
274
+ - **Ambiguous Escalations:** 84 (16.8%) — Low-confidence/unrecognized calls routed to `ASK`.
242
275
 
243
- ## Status
276
+ Detailed breakdown and reproduction steps: [BACKTEST_RESULTS.md](BACKTEST_RESULTS.md) | [BACKTEST_METHODOLOGY.md](BACKTEST_METHODOLOGY.md)
244
277
 
245
- - **Financial simulator**: functional with unit tests
246
- - **Database simulator**: functional with unit tests (EXPLAIN-based row estimation, recursive FK cascade walk)
247
- - **Communications simulator**: functional with unit tests (blast radius, unsubscribe compliance, canary cohorts, reputation impact)
248
- - **Strands integration**: functional with unit tests (full `ALLOW`/`DENY`/`ASK`/`STEER` lifecycle)
249
- - **MCP integration**: functional with unit tests (stdio transport, JSON-RPC error handling)
250
- - **LangGraph integration**: functional with unit tests (`@wrap_tool_call` middleware pattern)
278
+ ## Status & Test Coverage
279
+
280
+ - **Financial simulator**: functional with unit tests (`tests/test_financial_sim.py`, 96% coverage)
281
+ - **Database simulator**: functional with unit tests (`tests/test_database_sim.py`), plus real-PostgreSQL EXPLAIN fixture validation (`tests/test_database_explain_fixture.py`, runs in CI via a `postgres:16` service container; skips locally when no database is reachable)
282
+ - **Communications simulator**: functional with unit tests (`tests/test_communications_sim.py`, 90% coverage)
283
+ - **Circuit breaker & natural-key idempotency**: functional with unit tests (`tests/test_circuit_breaker.py`, 95% coverage)
284
+ - **Strands integration**: functional with unit tests (`tests/test_strands_hook.py`, 91% coverage)
285
+ - **MCP integration**: functional with unit tests (`tests/test_mcp_proxy.py`)
286
+ - **LangGraph integration**: functional with unit tests (`tests/test_langgraph_hook.py`)
287
+ - **CLI & Backtesting**: functional with unit tests (`tests/test_cli.py`)
288
+
289
+ ## Contributing
290
+
291
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for architecture guidelines, coding conventions, and instructions on creating new consequence simulators.
251
292
 
252
293
  ## License
253
294
 
254
295
  Apache-2.0
296
+
@@ -1,18 +1,26 @@
1
1
  # consequence-gate
2
2
 
3
+ [![CI](https://github.com/anandkrshnn-ai/consequence-gate/actions/workflows/ci.yml/badge.svg)](https://github.com/anandkrshnn-ai/consequence-gate/actions/workflows/ci.yml)
4
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](https://pypi.org/project/consequence-gate/)
5
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
6
+ [![Tests](https://img.shields.io/badge/tests-30%20passed-success.svg)](tests/)
7
+ [![Coverage](https://img.shields.io/badge/coverage-core%2090%25%2B-brightgreen.svg)](tests/)
8
+
9
+ **[Try the interactive demo ⚡](https://consequence-gate-demo-mu.vercel.app/)**
10
+
3
11
  A speculative outcome-simulation layer for AI agent tool calls. It sits
4
12
  **upstream** of static runtime access gates (AgentWall, AWS Strands
5
13
  `BeforeToolCallEvent`, MCP proxies, Prisma AIRS) and asks a different
6
14
  question than they do.
7
15
 
8
- Static gates ask: *does this call match an allowed pattern?*
16
+ Static gates ask: *does this call match an allowed pattern or schema?*
9
17
  `consequence-gate` asks: *what will this call actually do, and is that
10
18
  outcome safe?*
11
19
 
12
20
  ## Why this exists
13
21
 
14
22
  Static runtime gates are fast (sub-millisecond) and effective at schema
15
- validation, RBAC, and pattern matching -- but a schema-valid,
23
+ validation, RBAC, and pattern matching — but a schema-valid,
16
24
  policy-compliant call can still be consequence-catastrophic. A
17
25
  `process_claim(amount=50000)` call can pass every static check while
18
26
  pushing an account over its daily velocity limit via an irreversible
@@ -23,8 +31,8 @@ either passes it through, asks a human, denies it outright, or steers
23
31
  the agent toward a pre-vetted safer alternative.
24
32
 
25
33
  This is explicitly **not** a replacement for AgentWall / Strands / MCP
26
- proxies -- it's a prediction layer that runs before them, in the same
27
- pipeline.
34
+ proxies — it is an outcome prediction layer that runs upstream of them in the same pipeline.
35
+
28
36
 
29
37
  ## Core contracts
30
38
 
@@ -185,34 +193,63 @@ agent = Agent(hooks=[hook])
185
193
  ## Decision Matrix
186
194
 
187
195
  | Decision | Strands | MCP | LangGraph |
188
- |----------|---------|-----|-----------|
196
+ |---|---|---|---|
189
197
  | `ALLOW` | Executes normally | Forwarded to downstream MCP server | Tool executes via handler(request) |
190
198
  | `DENY` | `BLOCKED: <reason>` | JSON-RPC error (code=-32603) | Raises `ValueError("BLOCKED: ...")` |
191
199
  | `ASK` | `ESCALATION_REQUIRED: <reason>` | `isError=true` tool result | Raises `ValueError("ESCALATION_REQUIRED: ...")` |
192
200
  | `STEER` | `STEER_GUIDANCE: <guidance>\nSuggested alternative...` | `isError=true` + guidance | `ToolMessage(content="STEER_GUIDANCE: ...", status="error")` |
193
201
 
194
- ## Backtest Workflow
202
+ ## Trust Model & Failure Modes
203
+
204
+ `consequence-gate` evaluates consequence by combining tool invocation parameters with runtime state returned from your `context_provider` callback (e.g. `account_rolling_24h_spend`, `kyc_verified`, `table_metadata`).
205
+
206
+ ### Critical Failure Modes & Mitigations
207
+
208
+ | Failure Mode | Risk | Mitigation in Consequence-Gate |
209
+ |---|---|---|
210
+ | **Stale Context / Cache Lag** | Context provider returns yesterday's spend balance, potentially missing velocity breaches. | If context is unverified or confidence drops below `0.8`, the gate **always defaults to `ASK` (human escalation)**. It never grants a speculative `ALLOW`. |
211
+ | **Missing Context Provider** | Tool is invoked without any environment or database connection. | The simulator scores confidence as `0.0` or `0.5` and raises an escalation requirement (`ASK`). |
212
+ | **Agent Steering Thrashing** | The agent repeatedly submits non-compliant alternative calls in response to guidance. | The `SteerCircuitBreaker` enforces a hard retry cap (default: 2 retries) before terminating the loop and escalating to human review. |
213
+ | **Replay / Network Retries** | Network timeout causes agent runtime to resubmit the identical tool call. | Idempotency tokens are deterministically keyed to the entity's natural business key, guaranteeing identical evaluation without incrementing velocity counters twice. |
214
+
215
+ See [SECURITY.md](SECURITY.md) for full trust boundary documentation.
216
+
217
+ ## Offline Backtest Benchmark
218
+
219
+ Before deploying to production, run an offline backtest against historical execution traces to measure the four-quadrant FP/FN/TN breakdown:
195
220
 
196
- Before deploying to production, run an offline backtest against historical
197
- execution traces:
221
+ ```bash
222
+ # Run backtest on the bundled 500-trace synthetic benchmark dataset
223
+ consequence-gate backtest examples/benchmark_traces.jsonl
224
+ ```
225
+
226
+ ### Empirical Benchmark Summary (500 Synthetic Traces)
227
+
228
+ *(Note: Evaluated on a synthetically generated trace corpus `examples/benchmark_traces.jsonl` to validate harness mechanics end-to-end; see [BACKTEST_RESULTS.md](BACKTEST_RESULTS.md) for disclosure)*
198
229
 
199
- 1. Export 1,000-5,000 tool-call traces as JSONL (see `examples/backtest_sample_traces.jsonl`)
200
- 2. Run `python examples/run_backtest_demo.py` against your traces
201
- 3. Review the four-quadrant breakdown:
202
- - True Negative: correctly allowed benign operations
203
- - False Negative Caught: schema-valid calls that would have breached limits
204
- - False Positive Relieved: over-blocking that the simulator would have avoided
205
- - Steer Recovery Rate: percentage of blocked turns that could have completed via guidance
230
+ - **Benign Pass-Through (True Negatives):** 252 (50.4%) — Benign operations passed through.
231
+ - **Downstream Hazards Intercepted:** 129 (25.8%) — Schema-valid hazards caught before execution.
232
+ - **Over-Blocked Operations Relieved:** 35 (7.0%) — Benign calls over-blocked by naive regex gates safely enabled.
233
+ - **Ambiguous Escalations:** 84 (16.8%) — Low-confidence/unrecognized calls routed to `ASK`.
206
234
 
207
- ## Status
235
+ Detailed breakdown and reproduction steps: [BACKTEST_RESULTS.md](BACKTEST_RESULTS.md) | [BACKTEST_METHODOLOGY.md](BACKTEST_METHODOLOGY.md)
208
236
 
209
- - **Financial simulator**: functional with unit tests
210
- - **Database simulator**: functional with unit tests (EXPLAIN-based row estimation, recursive FK cascade walk)
211
- - **Communications simulator**: functional with unit tests (blast radius, unsubscribe compliance, canary cohorts, reputation impact)
212
- - **Strands integration**: functional with unit tests (full `ALLOW`/`DENY`/`ASK`/`STEER` lifecycle)
213
- - **MCP integration**: functional with unit tests (stdio transport, JSON-RPC error handling)
214
- - **LangGraph integration**: functional with unit tests (`@wrap_tool_call` middleware pattern)
237
+ ## Status & Test Coverage
238
+
239
+ - **Financial simulator**: functional with unit tests (`tests/test_financial_sim.py`, 96% coverage)
240
+ - **Database simulator**: functional with unit tests (`tests/test_database_sim.py`), plus real-PostgreSQL EXPLAIN fixture validation (`tests/test_database_explain_fixture.py`, runs in CI via a `postgres:16` service container; skips locally when no database is reachable)
241
+ - **Communications simulator**: functional with unit tests (`tests/test_communications_sim.py`, 90% coverage)
242
+ - **Circuit breaker & natural-key idempotency**: functional with unit tests (`tests/test_circuit_breaker.py`, 95% coverage)
243
+ - **Strands integration**: functional with unit tests (`tests/test_strands_hook.py`, 91% coverage)
244
+ - **MCP integration**: functional with unit tests (`tests/test_mcp_proxy.py`)
245
+ - **LangGraph integration**: functional with unit tests (`tests/test_langgraph_hook.py`)
246
+ - **CLI & Backtesting**: functional with unit tests (`tests/test_cli.py`)
247
+
248
+ ## Contributing
249
+
250
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for architecture guidelines, coding conventions, and instructions on creating new consequence simulators.
215
251
 
216
252
  ## License
217
253
 
218
254
  Apache-2.0
255
+
@@ -1,3 +1,3 @@
1
1
  """consequence-gate: speculative outcome-simulation layer for AI agent tool calls."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "0.2.0"
@@ -0,0 +1,62 @@
1
+ """
2
+ Offline backtest harness: replays historical JSONL tool-call traces
3
+ through a simulator + evaluator, WITHOUT re-executing anything, to
4
+ measure the four-quadrant FP/FN/TN/steer-recovery breakdown against
5
+ the trace's recorded existing_gate_decision and actual_execution_status.
6
+ """
7
+
8
+ import json
9
+ from collections.abc import Callable, Iterable
10
+
11
+
12
+ def load_traces(path: str) -> list[dict]:
13
+ traces = []
14
+ with open(path) as f:
15
+ for line in f:
16
+ line = line.strip()
17
+ if line:
18
+ traces.append(json.loads(line))
19
+ return traces
20
+
21
+
22
+ def run_backtest(
23
+ traces: Iterable[dict], simulate_and_evaluate: Callable[[dict], str]
24
+ ) -> list[dict]:
25
+ """
26
+ simulate_and_evaluate: function(trace) -> decision string ("ALLOW"/"DENY"/"ASK"/"STEER")
27
+ Returns per-trace records annotated with quadrant classification.
28
+ """
29
+ results = []
30
+ for trace in traces:
31
+ new_decision = simulate_and_evaluate(trace)
32
+ gt = trace.get("ground_truth_consequence")
33
+
34
+ if gt == "UNSAFE":
35
+ if new_decision in ("DENY", "STEER", "ASK"):
36
+ quadrant = "FALSE_NEGATIVE_CAUGHT" # TP: Hazard Intercepted
37
+ else:
38
+ quadrant = "OTHER" # FN: Missed Hazard
39
+ elif gt == "SAFE":
40
+ if new_decision == "ALLOW":
41
+ quadrant = "TRUE_NEGATIVE" # TN: Benign Pass-Through
42
+ else:
43
+ quadrant = "FALSE_POSITIVE" # FP: Over-blocked
44
+ else:
45
+ # Fallback for traces lacking ground_truth_consequence
46
+ old_decision = trace.get("existing_gate_decision", "ALLOW")
47
+ outcome = trace.get("actual_execution_status", "UNKNOWN")
48
+ if (
49
+ old_decision == "ALLOW"
50
+ and new_decision in ("DENY", "STEER", "ASK")
51
+ and outcome != "SUCCESS"
52
+ ):
53
+ quadrant = "FALSE_NEGATIVE_CAUGHT"
54
+ elif old_decision in ("DENY", "ASK") and new_decision == "ALLOW":
55
+ quadrant = "FALSE_POSITIVE_RELIEVED"
56
+ elif old_decision == "ALLOW" and new_decision == "ALLOW":
57
+ quadrant = "TRUE_NEGATIVE"
58
+ else:
59
+ quadrant = "OTHER"
60
+
61
+ results.append({**trace, "simulated_decision": new_decision, "quadrant": quadrant})
62
+ return results
@@ -0,0 +1,29 @@
1
+ """
2
+ Generates the four-quadrant FP/FN breakdown report from backtest results.
3
+ """
4
+
5
+ from collections import Counter
6
+
7
+
8
+ def generate_report(results: list[dict]) -> dict:
9
+ counts = Counter(r["quadrant"] for r in results)
10
+ total = len(results)
11
+ fn_caught = counts.get("FALSE_NEGATIVE_CAUGHT", 0)
12
+ fp_relieved = counts.get("FALSE_POSITIVE_RELIEVED", 0)
13
+ fp_caused = counts.get("FALSE_POSITIVE", 0)
14
+ return {
15
+ "total_traces": total,
16
+ "true_negative": counts.get("TRUE_NEGATIVE", 0),
17
+ "hazards_intercepted": fn_caught,
18
+ "overblocked_relieved": fp_relieved,
19
+ "false_positives_caused": fp_caused,
20
+ "other": counts.get("OTHER", 0),
21
+ "hazard_interception_rate": fn_caught / total if total else 0.0,
22
+ "overblock_relief_rate": fp_relieved / total if total else 0.0,
23
+ "false_positive_rate": fp_caused / total if total else 0.0,
24
+ # Backward-compatibility aliases
25
+ "false_negative_caught": fn_caught,
26
+ "false_positive_relieved": fp_relieved,
27
+ "false_negative_rate": fn_caught / total if total else 0.0,
28
+ "false_positive_relief_rate": fp_relieved / total if total else 0.0,
29
+ }