vitnify 0.0.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 (41) hide show
  1. vitnify-0.0.0/LICENSE +202 -0
  2. vitnify-0.0.0/NOTICE +14 -0
  3. vitnify-0.0.0/PKG-INFO +6 -0
  4. vitnify-0.0.0/README.md +132 -0
  5. vitnify-0.0.0/pyproject.toml +0 -0
  6. vitnify-0.0.0/setup.cfg +4 -0
  7. vitnify-0.0.0/src/vitnify/__init__.py +0 -0
  8. vitnify-0.0.0/src/vitnify/_vendor/__init__.py +0 -0
  9. vitnify-0.0.0/src/vitnify/_vendor/pck/__init__.py +0 -0
  10. vitnify-0.0.0/src/vitnify/_vendor/pck/cas.py +181 -0
  11. vitnify-0.0.0/src/vitnify/capability.py +77 -0
  12. vitnify-0.0.0/src/vitnify/certificate.py +388 -0
  13. vitnify-0.0.0/src/vitnify/deterministic_llm.py +64 -0
  14. vitnify-0.0.0/src/vitnify/engine.py +99 -0
  15. vitnify-0.0.0/src/vitnify/events.py +131 -0
  16. vitnify-0.0.0/src/vitnify/langgraph_adapter.py +120 -0
  17. vitnify-0.0.0/src/vitnify/mcp_adapter.py +120 -0
  18. vitnify-0.0.0/src/vitnify/react.py +93 -0
  19. vitnify-0.0.0/src/vitnify/redact.py +142 -0
  20. vitnify-0.0.0/src/vitnify/replayer.py +55 -0
  21. vitnify-0.0.0/src/vitnify/viewer.py +328 -0
  22. vitnify-0.0.0/src/vitnify.egg-info/PKG-INFO +6 -0
  23. vitnify-0.0.0/src/vitnify.egg-info/SOURCES.txt +39 -0
  24. vitnify-0.0.0/src/vitnify.egg-info/dependency_links.txt +1 -0
  25. vitnify-0.0.0/src/vitnify.egg-info/top_level.txt +1 -0
  26. vitnify-0.0.0/tests/test_adapters.py +161 -0
  27. vitnify-0.0.0/tests/test_attack_matrix.py +223 -0
  28. vitnify-0.0.0/tests/test_authority_program.py +95 -0
  29. vitnify-0.0.0/tests/test_capability.py +92 -0
  30. vitnify-0.0.0/tests/test_certificate.py +105 -0
  31. vitnify-0.0.0/tests/test_ed25519.py +61 -0
  32. vitnify-0.0.0/tests/test_engine_seam.py +91 -0
  33. vitnify-0.0.0/tests/test_events.py +80 -0
  34. vitnify-0.0.0/tests/test_l2_recompute.py +64 -0
  35. vitnify-0.0.0/tests/test_level2_verify.py +70 -0
  36. vitnify-0.0.0/tests/test_receipt_v2.py +132 -0
  37. vitnify-0.0.0/tests/test_redact.py +94 -0
  38. vitnify-0.0.0/tests/test_safe_defaults.py +83 -0
  39. vitnify-0.0.0/tests/test_verification.py +107 -0
  40. vitnify-0.0.0/tests/test_verify_hardening.py +156 -0
  41. vitnify-0.0.0/tests/test_viewer.py +177 -0
vitnify-0.0.0/LICENSE ADDED
@@ -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.
vitnify-0.0.0/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ vitnify
2
+ Copyright 2026 vitnify
3
+
4
+ This product includes software developed by vitnify (https://vitnify.com).
5
+
6
+ Portions of this software (the "vitni-tensor" deterministic inference engine and
7
+ the vitnify SDK) are licensed under the Apache License, Version 2.0. See the
8
+ LICENSE file.
9
+
10
+ "vitnify" and "vitnify-verified", and the vitnify logo, are trademarks of vitnify.
11
+ The Apache-2.0 license does not grant rights to use these marks. See TRADEMARKS.md.
12
+
13
+ Third-party components used by vitni-tensor include libm (deterministic math) and
14
+ BLAKE3 (hashing), each distributed under its own license.
vitnify-0.0.0/PKG-INFO ADDED
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.4
2
+ Name: vitnify
3
+ Version: 0.0.0
4
+ License-File: LICENSE
5
+ License-File: NOTICE
6
+ Dynamic: license-file
@@ -0,0 +1,132 @@
1
+ <h1 align="center">Vitnify your agents</h1>
2
+ <p align="center"><strong>Logs tell you what your agent did. Vitnify proves it</strong> — a cryptographic,
3
+ independently-reconstructable record of what an agent computed and did.</p>
4
+
5
+ Contain what an agent may do, deterministically reconstruct the model behind every
6
+ decision, and seal the whole run into one **bit-for-bit receipt** anyone can verify
7
+ offline — long after it happened.
8
+
9
+ > **vitnify** *(v.)* — to turn an agent run into a receipt anyone can reproduce and verify, offline.
10
+
11
+ vitnify isn't detection. It gives you the primitives to prove exactly what an agent
12
+ did: a `vitnify-receipt v2` binds the model's computation, the granted capabilities,
13
+ every tool call and result, the entropy, and the order into a single ed25519-signed,
14
+ self-verifying object.
15
+
16
+ ## Install
17
+
18
+ ```
19
+ pip install vitnify
20
+ ```
21
+
22
+ ## Quickstart
23
+
24
+ ```python
25
+ from vitnify.events import EventLog, Kind
26
+ from vitnify.engine import Engine, prompt_hash
27
+ from vitnify.certificate import issue_certificate, verify_authorized, gen_ed25519
28
+
29
+ eng = Engine("model.gguf", model_id="my-model") # deterministic backend
30
+ log = EventLog()
31
+
32
+ step = eng.run(prompt_tokens=[1, 2, 3], n_new=20) # a model step
33
+ log.append_llm_call(prompt_hash([1, 2, 3]), step["tokens"], seed=0,
34
+ model_digest=step["model_digest"], # bind the model computation
35
+ regime=step.get("regime"), # + regime and weights_hash: bound in the
36
+ weights_hash=step.get("weights_hash")) # digest, now readable in the receipt too
37
+ log.append(Kind.TOOL_CALL, {"tool": "read_docs", "decision": "allow"})
38
+ log.append(Kind.TOOL_CALL, {"tool": "send_email", "decision": "deny"}) # ungranted → blocked
39
+
40
+ priv, pub = gen_ed25519()
41
+ cert, _ = issue_certificate("program_hash", ["read_docs"], log, priv=priv)
42
+
43
+ checks = verify_authorized(cert, log, pinned_pubkeys=[pub]) # L1: offline, no model/secret; authorised signer
44
+ assert checks["ok"] # signed by a trusted key, unaltered, no ungranted tool ran
45
+ assert checks["containment_enforced"] # every tool call was GATED, not merely observed
46
+ # A receipt can be ok=True yet containment_enforced=False — a valid transcript from a
47
+ # watch-only integration proves what ran, not that anything was contained. A containment
48
+ # claim requires BOTH. (level 2: re-run each step through the engine; every model_digest
49
+ # reproduces bit-for-bit.)
50
+ ```
51
+
52
+ See the [receipt format spec](https://github.com/vitnify/vitnify-receipt-spec/blob/main/vitnify-receipt-v2.md)
53
+ (canonical — this repo does not vendor a copy, so the two can't drift), and
54
+ `examples/demo_receipt_e2e.py` for the full loop.
55
+
56
+ ## What you get
57
+
58
+ - **Capability containment** — ungranted tools are structurally unreachable.
59
+ - **Deterministic replay** — re-run a contested run and get the identical result, bit-for-bit.
60
+ - **Bit-for-bit receipts** — the model's exact computation, bound and signed.
61
+ - **Redaction by default** — the `Broker` commits *salted* hashes of tool payloads instead of cleartext, on allow **and** deny, so PHI/secrets never enter the receipt; cleartext stays in an org-held `Vault`, disclosed one event at a time with an inclusion proof (`vitnify.redact`). Pass `allow_cleartext=True` for the old behaviour (non-sensitive data only).
62
+ - **Offline verification** — anyone verifies a receipt's **integrity** (`integrity_ok`) with no model, network, or secret; **authority** (that an approved runtime signed it) is a separate verdict that needs a pinned trust root.
63
+ - **Drop-in** — wraps existing **LangGraph** and **MCP** agents (`pip install vitnify[langgraph]` / `[mcp]`).
64
+
65
+ **Two verification levels — and when to use each.** *Level 1 (integrity)* is offline,
66
+ instant, and needs no model — recompute the Merkle root and check the signature; this is
67
+ the default for every receipt, and it's what proves containment and tamper-evidence.
68
+ *Level 2 (recompute)* additionally re-runs the model to reproduce the committed output
69
+ tokens (per-op / activation records — a stronger commitment — are an available mode the
70
+ shipped binary does not emit).
71
+ It is the **dispute path** — run on a contested subset when someone challenges a specific
72
+ decision, **not** on every receipt inline. It is deliberately slow: the pinned-order
73
+ deterministic engine trades throughput for bit-exactness, roughly two orders of magnitude
74
+ below native inference (~0.45 tok/s vs ~58 for Mistral-7B Q4_K_M on the same Metal box).
75
+ Fleet throughput still scales the normal way — L2 is embarrassingly parallel across
76
+ receipts; a single recompute is simply not something you do on the hot path.
77
+
78
+ **The verdict is split** (0.4.1) — a receipt answers two different questions, and a
79
+ verifier reports them separately instead of collapsing them into one boolean:
80
+
81
+ - **`integrity_ok`** — is the transcript internally consistent and validly signed by
82
+ *whoever* signed it? Answerable by **anyone, offline, no secret**. Tampering, a forged
83
+ chain, an ungranted tool, a bad signature all set it `False`.
84
+ - **`authority_ok`** — was the signer an **approved runtime**? Needs a trust root, so it is
85
+ `True` / `False` / `None` (unestablished when no anchor is supplied — a stranger offline
86
+ can never answer it, and is *told so* rather than given a bare `False` that looks forged).
87
+ - **`ok`** = `integrity_ok` **and** an authorised signer. Pin the trusted key(s) —
88
+ `verify_authorized(cert, log, pinned_pubkeys=…)` is the production entry point; anchor it
89
+ in a TPM/enclave for the strongest form. Pass `require_authority=False` to make `ok` the
90
+ integrity-only verdict (the answer a stranger *can* compute offline).
91
+
92
+ **Program binding.** `program_hash` is caller-asserted unless you bind it. Pass
93
+ `derive_program_hash(paths_or_bytes)` at issue time and `verify_certificate(..., program=…)`
94
+ at verify time to make the receipt bind the *actual* program, not a label.
95
+
96
+ > ### ✅ Safe by default (0.4.0)
97
+ >
98
+ > The `Broker` **redacts** (no tool payload enters the receipt) and `verify_certificate`
99
+ > **requires signer authority** (a re-signed forgery can't verify without a trusted pin).
100
+ > Relax either only where appropriate, and do it explicitly:
101
+ >
102
+ > ```python
103
+ > broker = Broker(caps, tools, log, allow_cleartext=True) # record payloads in cleartext (non-sensitive only)
104
+ > verify_certificate(cert, log, require_authority=False) # integrity-only verdict (continuity, not authority)
105
+ > ```
106
+ >
107
+ > The production verify pins the trusted signer(s) and can bind the program:
108
+ >
109
+ > ```python
110
+ > from vitnify.certificate import verify_authorized, derive_program_hash
111
+ > cert, _ = issue_certificate(derive_program_hash(SRC), caps, log, priv=priv) # bind the real code
112
+ > checks = verify_authorized(cert, log, pinned_pubkeys=[trusted_key], program=SRC) # authority + binding
113
+ > ```
114
+
115
+ The deterministic engine is [`vitni-tensor`](https://github.com/vitnify/vitni-tensor);
116
+ the `vitni-receipt` binary is the model backend (point `VITNI_RECEIPT_BIN` at it).
117
+
118
+ ## License
119
+
120
+ Apache-2.0. **"vitnify"** and **"vitnify-verified"** are trademarks — see
121
+ [TRADEMARKS.md](TRADEMARKS.md). A fork may use the code, but not the name or issue
122
+ vitnify-verified receipts.
123
+
124
+ ## Part of Vitnify
125
+
126
+ This SDK is one of three open repos:
127
+
128
+ - **[vitni-tensor](https://github.com/vitnify/vitni-tensor)** — the deterministic,
129
+ `no_std` engine that produces the bit-identical model-computation digest this SDK binds.
130
+ - **[vitnify-receipt-spec](https://github.com/vitnify/vitnify-receipt-spec)** — the
131
+ canonical `vitnify-receipt v2` format the SDK implements.
132
+ - **[vitnify.com](https://vitnify.com)** — the project.
File without changes
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
File without changes
File without changes
@@ -0,0 +1,181 @@
1
+ """Content-addressed store + Merkle ledger — the provenance backbone of PCK.
2
+
3
+ Every source chunk is addressed by its cryptographic hash. A Merkle tree over those
4
+ hashes yields a single ``root`` that attests the whole corpus. Any single chunk can
5
+ then carry an *inclusion proof*: a short path of sibling hashes that recomputes the
6
+ root. The guarantees this buys, and why they matter for AI answers:
7
+
8
+ * **Tamper-evidence** — change one byte of one chunk and the root changes.
9
+ * **Independent verifiability** — anyone holding the root can check a chunk's proof
10
+ without trusting the party that produced it (no model, no server, no secret key).
11
+ * **Fabrication is uncredentialed** — a made-up "source" has no leaf in the tree, so
12
+ it cannot produce a valid proof. This is the cryptographic half of catching a
13
+ hallucination: a grounded claim points at a chunk with a valid proof; an invented
14
+ one cannot.
15
+
16
+ This mirrors the BLAKE3 + Merkle design of a native runtime's ``cas_store``; here we
17
+ keep a dependency-light pure-Python implementation over ``blake3``. BLAKE3 is a hard
18
+ dependency and DEFINES the wire format: a ``blake2b`` digest is a different value under
19
+ the same ``hash_name``, so there is NO silent stdlib fallback -- one would make honest
20
+ proofs indistinguishable from forgeries. A missing blake3 fails loudly (matching
21
+ ``events.py`` / ``certificate.py``), never silently downgrades.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass, field
26
+ from typing import Optional
27
+
28
+ import blake3 as _blake3
29
+
30
+ _HASH_NAME = "blake3"
31
+
32
+ def _digest(b: bytes) -> str:
33
+ return _blake3.blake3(b).hexdigest()
34
+
35
+
36
+ HASH_NAME = _HASH_NAME
37
+
38
+
39
+ def hash_bytes(b: bytes) -> str:
40
+ """Content address of raw bytes (hex)."""
41
+ return _digest(b)
42
+
43
+
44
+ def hash_text(s: str) -> str:
45
+ """Content address of a text chunk (UTF-8, hex)."""
46
+ return _digest(s.encode("utf-8"))
47
+
48
+
49
+ def _hash_pair(left: str, right: str) -> str:
50
+ """Internal Merkle node = hash of the concatenated child hex digests."""
51
+ return _digest((left + right).encode("utf-8"))
52
+
53
+
54
+ # --- inclusion proof -------------------------------------------------------------
55
+
56
+ @dataclass(frozen=True)
57
+ class ProofStep:
58
+ """One level of a Merkle inclusion path."""
59
+
60
+ sibling: str # hex digest of the sibling node
61
+ on_right: bool # True if the *current* node is the right child at this level
62
+
63
+ def to_json(self) -> dict:
64
+ return {"sibling": self.sibling, "on_right": self.on_right}
65
+
66
+ @staticmethod
67
+ def from_json(d: dict) -> "ProofStep":
68
+ return ProofStep(sibling=d["sibling"], on_right=bool(d["on_right"]))
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class InclusionProof:
73
+ """A self-contained proof that ``leaf`` is committed under ``root``.
74
+
75
+ Carries everything a third party needs to re-verify against a *published* root:
76
+ the leaf hash, the sibling path, and the index. No tree, server, or key required.
77
+ """
78
+
79
+ leaf: str
80
+ index: int
81
+ path: list[ProofStep]
82
+ hash_name: str = HASH_NAME
83
+
84
+ def verify(self, root: str) -> bool:
85
+ # A proof carries the hash suite it was built under. This module only speaks
86
+ # BLAKE3, so a proof committed under any other suite cannot be recomputed here
87
+ # -- reject rather than silently recompute under the wrong hash.
88
+ if self.hash_name != HASH_NAME:
89
+ return False
90
+ return verify_proof(self.leaf, self.path, root)
91
+
92
+ def to_json(self) -> dict:
93
+ return {
94
+ "leaf": self.leaf,
95
+ "index": self.index,
96
+ "hash": self.hash_name,
97
+ "path": [s.to_json() for s in self.path],
98
+ }
99
+
100
+ @staticmethod
101
+ def from_json(d: dict) -> "InclusionProof":
102
+ return InclusionProof(
103
+ leaf=d["leaf"],
104
+ index=int(d["index"]),
105
+ path=[ProofStep.from_json(s) for s in d["path"]],
106
+ hash_name=d.get("hash", HASH_NAME),
107
+ )
108
+
109
+
110
+ def verify_proof(leaf: str, path: list[ProofStep], root: str) -> bool:
111
+ """Recompute the root from ``leaf`` and ``path``; True iff it equals ``root``."""
112
+ h = leaf
113
+ for step in path:
114
+ h = _hash_pair(step.sibling, h) if step.on_right else _hash_pair(h, step.sibling)
115
+ return h == root
116
+
117
+
118
+ # --- the tree / store ------------------------------------------------------------
119
+
120
+ @dataclass
121
+ class MerkleCAS:
122
+ """Content-addressed store with a Merkle commitment over its chunks.
123
+
124
+ Odd layers duplicate the final node (Bitcoin-style), so a proof always exists for
125
+ every leaf. Construction is deterministic in the chunk order.
126
+ """
127
+
128
+ chunks: list[str]
129
+ leaves: list[str] = field(default_factory=list)
130
+ layers: list[list[str]] = field(default_factory=list)
131
+ _index_of_hash: dict[str, int] = field(default_factory=dict)
132
+
133
+ def __post_init__(self) -> None:
134
+ if not self.chunks:
135
+ raise ValueError("MerkleCAS requires at least one chunk")
136
+ self.leaves = [hash_text(c) for c in self.chunks]
137
+ # first occurrence wins if a chunk repeats
138
+ for i, h in enumerate(self.leaves):
139
+ self._index_of_hash.setdefault(h, i)
140
+ self.layers = self._build(self.leaves)
141
+
142
+ @staticmethod
143
+ def _build(leaves: list[str]) -> list[list[str]]:
144
+ layers = [leaves[:]]
145
+ while len(layers[-1]) > 1:
146
+ cur = layers[-1]
147
+ nxt = [
148
+ _hash_pair(cur[i], cur[i + 1] if i + 1 < len(cur) else cur[i])
149
+ for i in range(0, len(cur), 2)
150
+ ]
151
+ layers.append(nxt)
152
+ return layers
153
+
154
+ @property
155
+ def root(self) -> str:
156
+ return self.layers[-1][0]
157
+
158
+ def index_of(self, chunk_or_hash: str) -> Optional[int]:
159
+ """Index of a chunk by its raw text or by its hash; None if absent."""
160
+ if chunk_or_hash in self._index_of_hash:
161
+ return self._index_of_hash[chunk_or_hash]
162
+ return self._index_of_hash.get(hash_text(chunk_or_hash))
163
+
164
+ def contains(self, chunk_or_hash: str) -> bool:
165
+ return self.index_of(chunk_or_hash) is not None
166
+
167
+ def prove_index(self, idx: int) -> InclusionProof:
168
+ if not 0 <= idx < len(self.leaves):
169
+ raise IndexError(idx)
170
+ path: list[ProofStep] = []
171
+ i = idx
172
+ for layer in self.layers[:-1]:
173
+ sib = i ^ 1 if (i ^ 1) < len(layer) else i # duplicated node is its own sibling
174
+ path.append(ProofStep(sibling=layer[sib], on_right=bool(i & 1)))
175
+ i //= 2
176
+ return InclusionProof(leaf=self.leaves[idx], index=idx, path=path)
177
+
178
+ def prove(self, chunk_or_hash: str) -> Optional[InclusionProof]:
179
+ """Inclusion proof for a chunk (by text or hash); None if not in the corpus."""
180
+ idx = self.index_of(chunk_or_hash)
181
+ return None if idx is None else self.prove_index(idx)
@@ -0,0 +1,77 @@
1
+ """Userspace, kernel-free capability broker. Containment by construction: every
2
+ side-effecting tool call routes through here, and a tool the run wasn't granted is
3
+ simply unreachable -- a jailbreak that reaches an ungranted tool hits a wall, not a
4
+ classifier. Every call (allow or deny) is recorded to the event log.
5
+
6
+ SAFE BY DEFAULT (0.4.0). The broker **redacts**: it commits a SALTED hash of each
7
+ tool's args/results into the receipt and keeps the cleartext in an org-held
8
+ :class:`~vitnify.redact.Vault` (``broker.vault``), so PHI/secrets never enter the
9
+ signed record -- on allow AND deny. Disclose one event at a time with an inclusion
10
+ proof (see :mod:`vitnify.redact`).
11
+
12
+ Pass ``allow_cleartext=True`` to record payloads in cleartext instead (the pre-0.4.0
13
+ behaviour) -- ONLY where the arguments and results are not sensitive; a redacted log
14
+ is the safe choice for regulated data.
15
+ """
16
+ from __future__ import annotations
17
+ import hashlib
18
+ import os
19
+ from .events import EventLog, Kind
20
+
21
+
22
+ def _rh(x) -> str:
23
+ return hashlib.blake2b(repr(x).encode(), digest_size=16).hexdigest()
24
+
25
+
26
+ class Broker:
27
+ def __init__(self, capabilities, tools: dict, log: EventLog, *, vault=None,
28
+ allow_cleartext: bool = False, replay=None):
29
+ self.caps = set(capabilities)
30
+ self.tools = tools
31
+ self.log = log
32
+ self.replay = replay # if set: recorded ALLOW results to re-inject
33
+ self.allow_cleartext = allow_cleartext
34
+ if allow_cleartext:
35
+ self.vault = None
36
+ else:
37
+ from .redact import Vault # lazy: avoids an import cycle (redact imports Broker)
38
+ self.vault = vault if vault is not None else Vault()
39
+
40
+ def call(self, tool: str, *args):
41
+ args = list(args)
42
+ allowed = tool in self.caps
43
+
44
+ if self.allow_cleartext:
45
+ # OPT-OUT: record payloads in cleartext (only for non-sensitive data).
46
+ if not allowed:
47
+ self.log.append(Kind.TOOL_CALL, {"tool": tool, "args": args, "decision": "DENY"})
48
+ return False, None
49
+ result = self.replay.pop(0) if self.replay is not None else self.tools[tool](*args)
50
+ self.log.append(Kind.TOOL_CALL, {"tool": tool, "args": args, "decision": "ALLOW",
51
+ "result": result, "result_hash": _rh(result)})
52
+ return True, result
53
+
54
+ # SAFE DEFAULT: commit SALTED hashes; cleartext goes to the vault, not the receipt.
55
+ from .redact import _commit
56
+ idx = len(self.log)
57
+ asalt = os.urandom(16)
58
+ if not allowed:
59
+ self.log.append(Kind.TOOL_CALL,
60
+ {"tool": tool, "args_commit": _commit(asalt, args), "decision": "DENY"})
61
+ self.vault.put(idx, args_salt=asalt, args=args)
62
+ return False, None
63
+ result = self.replay.pop(0) if self.replay is not None else self.tools[tool](*args)
64
+ rsalt = os.urandom(16)
65
+ self.log.append(Kind.TOOL_CALL,
66
+ {"tool": tool, "args_commit": _commit(asalt, args),
67
+ "decision": "ALLOW", "result_commit": _commit(rsalt, result)})
68
+ self.vault.put(idx, args_salt=asalt, args=args, result_salt=rsalt, result=result)
69
+ return True, result
70
+
71
+
72
+ def recorded_tool_results(log: EventLog):
73
+ """ALLOW results for a replay, from a CLEARTEXT-mode log. For a redacted log the
74
+ results are in the vault -- use :func:`vitnify.redact.recorded_tool_results(log, vault)`."""
75
+ return [e.payload["result"] for e in log.events
76
+ if e.kind == Kind.TOOL_CALL.value and e.payload.get("decision") == "ALLOW"
77
+ and "result" in e.payload]