algovoi-keystone 0.4.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.
@@ -0,0 +1,201 @@
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 and Derivative Works thereof.
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 within 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 Derivative Works; 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 attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 AlgoVoi
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,9 @@
1
+ algovoi-keystone
2
+ Copyright 2026 AlgoVoi
3
+
4
+ This product includes software developed by AlgoVoi.
5
+ Licensed under the Apache License, Version 2.0.
6
+
7
+ An umbrella distribution over algovoi-keystone-connect and algovoi-keystone-agent,
8
+ plus the `keystone` command line. Built on the AlgoVoi substrate: RFC 8785 (JCS)
9
+ canonicalisation + SHA-256, producing content-addressed evidence recomputable offline.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: algovoi-keystone
3
+ Version: 0.4.0
4
+ Summary: The Keystone SDK umbrella -- one install for the whole bolt-on toolchain (connector builder + agentic behaviour layer) plus the `keystone` command line. Everything reduces to sha256 over RFC 8785 JCS (Apache-2.0)
5
+ Author-email: AlgoVoi <chopmob@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://www.algovoi.co.uk
8
+ Project-URL: Repository, https://github.com/chopmob-cloud/algovoi-keystone
9
+ Project-URL: Documentation, https://docs.algovoi.co.uk
10
+ Keywords: keystone,sdk,cli,bolt-on,connector,behaviour,execution_ref,jcs,rfc8785,agentic-payments,algovoi
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Classifier: Environment :: Console
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ License-File: NOTICE
22
+ Requires-Dist: algovoi-keystone-connect>=0.4.0
23
+ Requires-Dist: algovoi-keystone-agent>=0.4.0
24
+ Requires-Dist: algovoi-keystone-runtime>=0.4.0
25
+ Requires-Dist: algovoi-execution-ref>=0.4.0
26
+ Requires-Dist: rfc8785>=0.1.4
27
+ Provides-Extra: validate
28
+ Requires-Dist: algovoi-keystone-validate>=0.1.0; extra == "validate"
29
+ Provides-Extra: publish
30
+ Requires-Dist: build>=1.0; extra == "publish"
31
+ Requires-Dist: twine>=5.0; extra == "publish"
32
+ Dynamic: license-file
33
+
34
+ # algovoi-keystone
35
+
36
+ The Keystone SDK, in one install. `pip install algovoi-keystone` brings the whole bolt-on toolchain:
37
+ the connector builder ([keystone-connect](https://pypi.org/project/algovoi-keystone-connect/)), the
38
+ agentic behaviour layer ([keystone-agent](https://pypi.org/project/algovoi-keystone-agent/)) with its
39
+ ready-made behaviours, and the `keystone` command line. Everything still reduces to one primitive,
40
+ `ref = "sha256:" + SHA-256(RFC 8785 JCS(payload))`, with no AlgoVoi software in your trust base.
41
+ Apache-2.0.
42
+
43
+ ## One import surface
44
+
45
+ ```python
46
+ from algovoi_keystone import connector, rule, trigger, behaviour, Engine, keystone_ref, behaviours
47
+
48
+ keystone_s3 = connector("s3", writes={"put_object": ("put", lambda c: c.kwargs["Bucket"])})
49
+ engine = Engine([behaviours.cap_charges(500)], decision_ref=decision_ref)
50
+ ```
51
+
52
+ ## The `keystone` command line
53
+
54
+ ```
55
+ keystone new <name> --kind connector|behaviour|stage scaffold a publishable bolt-on
56
+ keystone test [path] run the bolt-on's test battery
57
+ keystone validate <records.json> verify emitted refs offline
58
+ keystone doctor check the environment
59
+ keystone info show installed pieces + the primitive
60
+ keystone publish [path] build the dist and check it (mirror-first)
61
+ ```
62
+
63
+ `keystone new` writes a complete package already wired to the conformance battery, so a bolt-on
64
+ goes from nothing to tested in one step:
65
+
66
+ ```
67
+ keystone new redis-stream --kind connector
68
+ cd redis-stream/python && keystone test # green: recompute, decision-bound, tamper-evident
69
+ ```
70
+
71
+ `keystone validate` verifies any emitted record offline, whether it is an `execution_ref` from a
72
+ connector or a `behaviour_ref` from the agent layer: it recomputes the reference from the recorded
73
+ fields and reports any that do not match, so a third party checks your evidence with a stock RFC 8785
74
+ implementation and standard SHA-256.
75
+
76
+ Install from the Keystone control panel (the integrity path, from the AlgoVoi index); new releases
77
+ land on the AlgoVoi index first, with PyPI mirrors following. Built on the AlgoVoi substrate
78
+ (RFC 8785 JCS + SHA-256).
@@ -0,0 +1,45 @@
1
+ # algovoi-keystone
2
+
3
+ The Keystone SDK, in one install. `pip install algovoi-keystone` brings the whole bolt-on toolchain:
4
+ the connector builder ([keystone-connect](https://pypi.org/project/algovoi-keystone-connect/)), the
5
+ agentic behaviour layer ([keystone-agent](https://pypi.org/project/algovoi-keystone-agent/)) with its
6
+ ready-made behaviours, and the `keystone` command line. Everything still reduces to one primitive,
7
+ `ref = "sha256:" + SHA-256(RFC 8785 JCS(payload))`, with no AlgoVoi software in your trust base.
8
+ Apache-2.0.
9
+
10
+ ## One import surface
11
+
12
+ ```python
13
+ from algovoi_keystone import connector, rule, trigger, behaviour, Engine, keystone_ref, behaviours
14
+
15
+ keystone_s3 = connector("s3", writes={"put_object": ("put", lambda c: c.kwargs["Bucket"])})
16
+ engine = Engine([behaviours.cap_charges(500)], decision_ref=decision_ref)
17
+ ```
18
+
19
+ ## The `keystone` command line
20
+
21
+ ```
22
+ keystone new <name> --kind connector|behaviour|stage scaffold a publishable bolt-on
23
+ keystone test [path] run the bolt-on's test battery
24
+ keystone validate <records.json> verify emitted refs offline
25
+ keystone doctor check the environment
26
+ keystone info show installed pieces + the primitive
27
+ keystone publish [path] build the dist and check it (mirror-first)
28
+ ```
29
+
30
+ `keystone new` writes a complete package already wired to the conformance battery, so a bolt-on
31
+ goes from nothing to tested in one step:
32
+
33
+ ```
34
+ keystone new redis-stream --kind connector
35
+ cd redis-stream/python && keystone test # green: recompute, decision-bound, tamper-evident
36
+ ```
37
+
38
+ `keystone validate` verifies any emitted record offline, whether it is an `execution_ref` from a
39
+ connector or a `behaviour_ref` from the agent layer: it recomputes the reference from the recorded
40
+ fields and reports any that do not match, so a third party checks your evidence with a stock RFC 8785
41
+ implementation and standard SHA-256.
42
+
43
+ Install from the Keystone control panel (the integrity path, from the AlgoVoi index); new releases
44
+ land on the AlgoVoi index first, with PyPI mirrors following. Built on the AlgoVoi substrate
45
+ (RFC 8785 JCS + SHA-256).
@@ -0,0 +1,47 @@
1
+ """algovoi-keystone -- the Keystone SDK umbrella.
2
+
3
+ One install brings the whole bolt-on toolchain:
4
+
5
+ pip install algovoi-keystone
6
+
7
+ and one import surface over it:
8
+
9
+ from algovoi_keystone import connector, behaviour, rule, trigger, Engine, keystone_ref
10
+
11
+ You get the connector builder (keystone-connect), the behaviour layer
12
+ (keystone-agent) with its ready-made `behaviours` library, and the `keystone`
13
+ command line. Everything still reduces to one primitive:
14
+
15
+ keystone_ref(payload) == "sha256:" + SHA-256(RFC 8785 JCS(payload))
16
+ """
17
+ __version__ = "0.4.0"
18
+
19
+ # The connector builder + conformance harness.
20
+ from algovoi_keystone_connect import ( # noqa: F401
21
+ Call, EXECUTION_OUTCOMES, Report, check_connector, check_ref_builder,
22
+ connector, execution_ref, keystone_ref, synth_ref,
23
+ )
24
+
25
+ # The agentic behaviour layer.
26
+ from algovoi_keystone_agent import ( # noqa: F401
27
+ Denied, Engine, Event, behaviour, check_behaviour, check_rule,
28
+ check_trigger, rule, synth_event, trigger,
29
+ )
30
+ # Ready-made behaviours: `from algovoi_keystone import behaviours; behaviours.cap_charges(500)`
31
+ from algovoi_keystone_agent import library as behaviours # noqa: F401
32
+
33
+ # The runtime: run a chain and keep the evidence in a tamper-evident journal.
34
+ from algovoi_keystone_runtime import Journal, Runtime, verify_record # noqa: F401
35
+
36
+ __all__ = [
37
+ "__version__",
38
+ # primitive + connectors
39
+ "keystone_ref", "synth_ref", "connector", "Call", "execution_ref",
40
+ "EXECUTION_OUTCOMES", "Report", "check_connector", "check_ref_builder",
41
+ # behaviour layer
42
+ "rule", "trigger", "behaviour", "Engine", "Denied", "Event",
43
+ "synth_event", "check_rule", "check_trigger", "check_behaviour",
44
+ "behaviours",
45
+ # runtime + journal
46
+ "Runtime", "Journal", "verify_record",
47
+ ]
@@ -0,0 +1,431 @@
1
+ """keystone -- the Keystone SDK command line.
2
+
3
+ One entry point over the bolt-on toolchain:
4
+
5
+ keystone new <name> --kind connector|behaviour|stage scaffold a publishable bolt-on
6
+ keystone test [path] run the bolt-on's test battery
7
+ keystone validate <records.json> verify emitted refs offline
8
+ keystone doctor check the environment
9
+ keystone info show installed pieces + the primitive
10
+ keystone journal <db> [--show] verify (and list) a runtime journal
11
+ keystone publish [path] build the dist and check it (mirror-first)
12
+
13
+ Everything reduces to one primitive:
14
+ keystone_ref(payload) == "sha256:" + SHA-256(RFC 8785 JCS(payload))
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import hashlib
20
+ import importlib.metadata as _im
21
+ import json
22
+ import os
23
+ import re
24
+ import subprocess
25
+ import sys
26
+ import urllib.request
27
+
28
+ MIRROR = "https://pip.algovoi.co.uk/simple/"
29
+ _FAMILY = [
30
+ "algovoi-keystone", "algovoi-keystone-connect", "algovoi-keystone-agent",
31
+ "algovoi-keystone-validate", "algovoi-execution-ref", "rfc8785",
32
+ ]
33
+
34
+
35
+ def _ok(msg): print(" [ok] " + msg)
36
+ def _bad(msg): print(" [FAIL] " + msg)
37
+ def _warn(msg): print(" [warn] " + msg)
38
+
39
+
40
+ def _keystone_ref(payload):
41
+ import rfc8785
42
+ return "sha256:" + hashlib.sha256(rfc8785.dumps(payload)).hexdigest()
43
+
44
+
45
+ def _version(dist):
46
+ try:
47
+ return _im.version(dist)
48
+ except _im.PackageNotFoundError:
49
+ return None
50
+
51
+
52
+ # --------------------------------------------------------------------------- #
53
+ # info / doctor
54
+ # --------------------------------------------------------------------------- #
55
+
56
+ def cmd_info(_args):
57
+ print("Keystone SDK -- installed pieces:")
58
+ for dist in _FAMILY:
59
+ v = _version(dist)
60
+ print(" %-26s %s" % (dist, v or "(not installed)"))
61
+ print("\nOne primitive:")
62
+ print(' keystone_ref(payload) == "sha256:" + SHA-256(RFC 8785 JCS(payload))')
63
+ print(" docs: https://docs.algovoi.co.uk/keystone")
64
+ return 0
65
+
66
+
67
+ def cmd_doctor(_args):
68
+ print("keystone doctor")
69
+ fails = 0
70
+
71
+ try:
72
+ import rfc8785 # noqa: F401
73
+ _ok("rfc8785 (RFC 8785 JCS) importable")
74
+ except Exception as exc:
75
+ _bad("rfc8785 not importable: %r" % exc); fails += 1
76
+
77
+ try:
78
+ a = _keystone_ref({"b": 1, "a": 2})
79
+ b = _keystone_ref({"a": 2, "b": 1})
80
+ if a == b and a.startswith("sha256:") and len(a) == 71:
81
+ _ok("keystone_ref canonical + deterministic (key order independent)")
82
+ else:
83
+ _bad("keystone_ref not canonical: %s vs %s" % (a, b)); fails += 1
84
+ except Exception as exc:
85
+ _bad("keystone_ref failed: %r" % exc); fails += 1
86
+
87
+ for mod, dist in [("algovoi_keystone_connect", "algovoi-keystone-connect"),
88
+ ("algovoi_keystone_agent", "algovoi-keystone-agent")]:
89
+ try:
90
+ __import__(mod)
91
+ _ok("%s importable (%s)" % (dist, _version(dist) or "?"))
92
+ except Exception as exc:
93
+ _bad("%s not importable: %r" % (dist, exc)); fails += 1
94
+
95
+ try:
96
+ req = urllib.request.Request(MIRROR, headers={"User-Agent": "keystone-cli"})
97
+ with urllib.request.urlopen(req, timeout=6) as r:
98
+ reachable = r.status == 200
99
+ _ok("AlgoVoi index reachable (%s)" % MIRROR) if reachable else _warn("index HTTP %s" % r.status)
100
+ except Exception as exc:
101
+ _warn("AlgoVoi index not reachable (offline is fine): %r" % exc)
102
+
103
+ print("\n=> %s" % ("PASS" if not fails else "FAIL (%d)" % fails))
104
+ return 1 if fails else 0
105
+
106
+
107
+ # --------------------------------------------------------------------------- #
108
+ # validate -- verify emitted refs offline
109
+ # --------------------------------------------------------------------------- #
110
+
111
+ def _verify_record(rec):
112
+ """(ok, ref_field, note) over the same strict rules the runtime journal uses.
113
+
114
+ Delegating to ``algovoi_keystone_runtime.verify_record`` keeps one definition of
115
+ "recomputes" across offline validation and the durable journal: a typed
116
+ ``execution_keystone`` wrapper is checked on every tier (decision, execution,
117
+ trust query, chain), and a fabricated ``*_ref`` field cannot stand in for a
118
+ real self-reference.
119
+ """
120
+ if not isinstance(rec, dict):
121
+ return (False, "?", "record is not a JSON object")
122
+ try:
123
+ from algovoi_keystone_runtime import verify_record
124
+ except Exception: # runtime absent: fall back to the local, stricter check
125
+ verify_record = None
126
+ if verify_record is not None:
127
+ try:
128
+ ok = verify_record(rec)
129
+ except Exception as exc:
130
+ return (False, "?", "cannot verify: %r" % exc)
131
+ field = next((k for k in ("execution_ref", "behaviour_ref", "stage_ref")
132
+ if k in rec), "?")
133
+ return (ok, field, "self-reference recomputes" if ok else "self-reference does not recompute")
134
+ if "execution_ref" in rec:
135
+ if not all(k in rec for k in
136
+ ("decision_ref", "action_type", "scope", "outcome", "executed_at_ms")):
137
+ return (False, "execution_ref", "incomplete execution record")
138
+ try:
139
+ from algovoi_execution_ref import execution_ref
140
+ want = execution_ref(rec["decision_ref"], rec["action_type"],
141
+ rec["scope"], rec["outcome"], rec["executed_at_ms"])
142
+ return (want == rec["execution_ref"], "execution_ref", "execution record")
143
+ except Exception as exc:
144
+ return (False, "execution_ref", "cannot recompute: %r" % exc)
145
+ self_refs = [k for k in ("behaviour_ref", "stage_ref") if k in rec]
146
+ if len(self_refs) != 1:
147
+ return (False, "?", "record must carry exactly one self-reference")
148
+ key = self_refs[0]
149
+ body = {k: v for k, v in rec.items() if k != key}
150
+ try:
151
+ ok = _keystone_ref(body) == rec[key]
152
+ except Exception as exc:
153
+ return (False, key, "cannot recompute: %r" % exc)
154
+ return (ok, key, "content-addressed" if ok else "does not recompute")
155
+
156
+
157
+
158
+ def _unique_object(pairs):
159
+ result = {}
160
+ for key, value in pairs:
161
+ if key in result:
162
+ raise ValueError("duplicate JSON member")
163
+ result[key] = value
164
+ return result
165
+
166
+
167
+ def cmd_validate(args):
168
+ try:
169
+ with open(args.file, "rb") as source:
170
+ raw = source.read(8 * 1024 * 1024 + 1)
171
+ if len(raw) > 8 * 1024 * 1024:
172
+ raise ValueError("evidence exceeds the 8 MiB input limit")
173
+ data = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object)
174
+ except Exception as exc:
175
+ _bad("cannot read %s: %r" % (args.file, exc)); return 2
176
+ records = data if isinstance(data, list) else [data]
177
+ if not records:
178
+ _bad("no records to validate"); return 1
179
+ print("keystone validate %s -- %d record(s)" % (args.file, len(records)))
180
+ fails = 0
181
+ for i, rec in enumerate(records):
182
+ ok, field, note = _verify_record(rec)
183
+ (_ok if ok else _bad)("record %d [%s] %s" % (i, field, note))
184
+ fails += 0 if ok else 1
185
+ print("\n=> %s" % ("PASS" if not fails else "FAIL (%d/%d)" % (fails, len(records))))
186
+ return 1 if fails else 0
187
+
188
+
189
+ # --------------------------------------------------------------------------- #
190
+ # new -- scaffold a publishable bolt-on
191
+ # --------------------------------------------------------------------------- #
192
+
193
+ def _slug(name):
194
+ s = re.sub(r"[^a-z0-9]+", "_", name.strip().lower()).strip("_")
195
+ if not s:
196
+ raise SystemExit("keystone new: name must contain a letter or digit")
197
+ return s
198
+
199
+
200
+ def _files_for(kind, name):
201
+ slug = _slug(name)
202
+ mod = "keystone_" + slug
203
+ dist = "keystone-" + slug.replace("_", "-")
204
+ common_pyproject = f"""[build-system]
205
+ requires = ["setuptools>=70", "wheel"]
206
+ build-backend = "setuptools.build_meta"
207
+
208
+ [project]
209
+ name = "{dist}"
210
+ version = "0.1.0"
211
+ description = "A Keystone bolt-on ({kind}) built with algovoi-keystone-connect"
212
+ readme = "README.md"
213
+ license = {{ text = "Apache-2.0" }}
214
+ requires-python = ">=3.10"
215
+ dependencies = ["algovoi-keystone-connect>=0.1.0", "algovoi-keystone-agent>=0.1.0"]
216
+
217
+ [tool.setuptools.packages.find]
218
+ where = ["."]
219
+ include = ["{mod}*"]
220
+ """
221
+ notice = f"{dist}\nCopyright 2026\n\nBuilt on the AlgoVoi Keystone substrate: RFC 8785 (JCS) + SHA-256.\n"
222
+ readme = f"# {dist}\n\nA Keystone bolt-on ({kind}). Test it with `keystone test`, publish it per\nhttps://docs.algovoi.co.uk/publishing-bolt-ons\n"
223
+
224
+ if kind == "connector":
225
+ init = f'''"""A Keystone {slug} connector: bind each write on a data plane to its decision_ref."""
226
+ from algovoi_keystone_connect import connector
227
+
228
+ # Map each write method to (action, scope_fn(call)). scope_fn reads call.kwargs /
229
+ # call.args for per-call values and call.client for fixed context.
230
+ keystone_{slug} = connector("{slug}", writes={{
231
+ "write": ("write", lambda call: str(call.kwargs.get("key", ""))),
232
+ "delete": ("delete", lambda call: str(call.kwargs.get("key", ""))),
233
+ }})
234
+ '''
235
+ test = f'''from algovoi_keystone_connect import check_connector
236
+ from {mod} import keystone_{slug}
237
+
238
+
239
+ class Fake:
240
+ def __init__(self): self.calls = []
241
+ def write(self, **kw): self.calls.append(("write", kw)); return {{}}
242
+ def delete(self, **kw): self.calls.append(("delete", kw)); return {{}}
243
+
244
+
245
+ def test_connector_conforms():
246
+ report = check_connector(keystone_{slug}, Fake(), [
247
+ ("write", {{"key": "k1"}}),
248
+ ("delete", {{"key": "k1"}}),
249
+ ])
250
+ assert report.ok, report
251
+ '''
252
+ elif kind == "behaviour":
253
+ init = f'''"""A Keystone {slug} behaviour: govern a stage of the chain."""
254
+ from algovoi_keystone_agent import behaviour, rule, trigger
255
+
256
+ # Edit the trigger (when it wakes) and the rule (ALLOW / FLAG / BLOCK).
257
+ {slug} = behaviour(
258
+ "{slug}",
259
+ on=trigger(stage="execution", where=lambda ev: ev.get("method") is not None),
260
+ rule=rule("{slug}_rule", lambda ev: "ALLOW"),
261
+ )
262
+ '''
263
+ test = f'''from algovoi_keystone_agent import check_behaviour, synth_event
264
+ from {mod} import {slug}
265
+
266
+
267
+ def test_behaviour_conforms():
268
+ report = check_behaviour({slug}, [synth_event("execution", method="write")])
269
+ assert report.ok, report
270
+ '''
271
+ elif kind == "stage":
272
+ init = f'''"""A Keystone {slug} stage: a content-addressed ref-builder over its payload."""
273
+ from algovoi_keystone_connect import keystone_ref
274
+
275
+
276
+ def {slug}_ref(payload):
277
+ # Bind to the upstream stage via a *_ref field inside `payload`.
278
+ return keystone_ref(payload)
279
+ '''
280
+ test = f'''from algovoi_keystone_connect import check_ref_builder, synth_ref
281
+ from {mod} import {slug}_ref
282
+
283
+
284
+ def test_stage_conforms():
285
+ report = check_ref_builder(
286
+ {slug}_ref,
287
+ {{"prev_ref": synth_ref("prev"), "field": "value"}},
288
+ prev_field="prev_ref",
289
+ )
290
+ assert report.ok, report
291
+ '''
292
+ else:
293
+ raise SystemExit("keystone new: --kind must be connector, behaviour, or stage")
294
+
295
+ root = os.path.join(name, "python")
296
+ return {
297
+ os.path.join(root, mod, "__init__.py"): init,
298
+ os.path.join(root, "tests", f"test_{mod}.py"): test,
299
+ os.path.join(root, "pyproject.toml"): common_pyproject,
300
+ os.path.join(root, "NOTICE"): notice,
301
+ os.path.join(root, "README.md"): readme,
302
+ }
303
+
304
+
305
+ def cmd_new(args):
306
+ if os.path.exists(args.name):
307
+ _bad("%s already exists" % args.name); return 2
308
+ files = _files_for(args.kind, args.name)
309
+ for path, content in files.items():
310
+ os.makedirs(os.path.dirname(path), exist_ok=True)
311
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
312
+ f.write(content)
313
+ print("scaffolded %s bolt-on %r:" % (args.kind, args.name))
314
+ for path in sorted(files):
315
+ print(" " + path)
316
+ print("\nnext:")
317
+ print(" cd %s/python && keystone test" % args.name)
318
+ print(" keystone publish # build + check, then publish per the docs")
319
+ return 0
320
+
321
+
322
+ # --------------------------------------------------------------------------- #
323
+ # journal -- verify / list a runtime journal
324
+ # --------------------------------------------------------------------------- #
325
+
326
+ def cmd_journal(args):
327
+ try:
328
+ from algovoi_keystone_runtime import Journal
329
+ except Exception as exc:
330
+ _bad("algovoi-keystone-runtime not installed: %r" % exc); return 2
331
+ if not os.path.exists(args.db):
332
+ _bad("journal not found: %s" % args.db); return 2
333
+ # Read-only first: a verification command must never create a database, write
334
+ # the schema, or mutate the evidence it is meant to inspect. Corrupt state then
335
+ # surfaces as a failed report rather than a traceback.
336
+ try:
337
+ j = Journal(args.db, read_only=True)
338
+ except Exception as exc:
339
+ _bad("cannot open %s: %r" % (args.db, exc)); return 2
340
+ try:
341
+ report = j.verify(expected_head=getattr(args, "expected_head", None))
342
+ print(report)
343
+ if not report.ok:
344
+ return 1
345
+ count = j.count()
346
+ print("keystone journal %s -- %d entries" % (args.db, count))
347
+ if args.show:
348
+ for rec in j.records():
349
+ ref = (rec.get("execution_ref") or rec.get("behaviour_ref")
350
+ or rec.get("stage_ref") or "?")
351
+ tag = rec.get("stage") or ("execution" if "execution_ref" in rec else "?")
352
+ note = rec.get("verdict", "")
353
+ print(" %-12s %s %s" % (tag, ref[:24] + "...", note))
354
+ return 0
355
+ except Exception as exc:
356
+ _bad("journal verification failed: %r" % exc); return 2
357
+ finally:
358
+ j.close()
359
+
360
+
361
+ # --------------------------------------------------------------------------- #
362
+ # test / publish
363
+ # --------------------------------------------------------------------------- #
364
+
365
+ def cmd_test(args):
366
+ path = args.path or "."
367
+ print("keystone test %s (pytest)" % path)
368
+ return subprocess.call([sys.executable, "-m", "pytest", "-q", path])
369
+
370
+
371
+ def cmd_publish(args):
372
+ path = args.path or "."
373
+ print("keystone publish %s -- build + check (does not push)" % path)
374
+ rc = subprocess.call([sys.executable, "-m", "build", path])
375
+ if rc != 0:
376
+ _bad("build failed"); return rc
377
+ dist = os.path.join(path, "dist")
378
+ rc = subprocess.call([sys.executable, "-m", "twine", "check", os.path.join(dist, "*")])
379
+ print("\nMirror-first cadence:")
380
+ print(" 1. publish the wheel to the AlgoVoi index first (validated, panel-installable)")
381
+ print(" 2. promote to PyPI once it is verified in place")
382
+ print(" docs: https://docs.algovoi.co.uk/publishing-bolt-ons")
383
+ return rc
384
+
385
+
386
+ # --------------------------------------------------------------------------- #
387
+
388
+ def build_parser():
389
+ p = argparse.ArgumentParser(prog="keystone", description="The Keystone SDK command line.")
390
+ sub = p.add_subparsers(dest="cmd")
391
+
392
+ sub.add_parser("info", help="show installed pieces + the primitive").set_defaults(fn=cmd_info)
393
+ sub.add_parser("doctor", help="check the environment").set_defaults(fn=cmd_doctor)
394
+
395
+ n = sub.add_parser("new", help="scaffold a publishable bolt-on")
396
+ n.add_argument("name")
397
+ n.add_argument("--kind", choices=["connector", "behaviour", "stage"], default="connector")
398
+ n.set_defaults(fn=cmd_new)
399
+
400
+ t = sub.add_parser("test", help="run the bolt-on's tests")
401
+ t.add_argument("path", nargs="?")
402
+ t.set_defaults(fn=cmd_test)
403
+
404
+ v = sub.add_parser("validate", help="verify emitted refs offline")
405
+ v.add_argument("file")
406
+ v.set_defaults(fn=cmd_validate)
407
+
408
+ jn = sub.add_parser("journal", help="verify (and list) a runtime journal")
409
+ jn.add_argument("db")
410
+ jn.add_argument("--show", action="store_true", help="list the entries")
411
+ jn.add_argument("--expected-head", dest="expected_head", default=None,
412
+ help="pin the journal head you independently trust")
413
+ jn.set_defaults(fn=cmd_journal)
414
+
415
+ pub = sub.add_parser("publish", help="build + check a bolt-on (mirror-first)")
416
+ pub.add_argument("path", nargs="?")
417
+ pub.set_defaults(fn=cmd_publish)
418
+
419
+ return p
420
+
421
+
422
+ def main(argv=None):
423
+ args = build_parser().parse_args(argv)
424
+ if not getattr(args, "fn", None):
425
+ build_parser().print_help()
426
+ return 0
427
+ return args.fn(args)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ raise SystemExit(main())
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: algovoi-keystone
3
+ Version: 0.4.0
4
+ Summary: The Keystone SDK umbrella -- one install for the whole bolt-on toolchain (connector builder + agentic behaviour layer) plus the `keystone` command line. Everything reduces to sha256 over RFC 8785 JCS (Apache-2.0)
5
+ Author-email: AlgoVoi <chopmob@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://www.algovoi.co.uk
8
+ Project-URL: Repository, https://github.com/chopmob-cloud/algovoi-keystone
9
+ Project-URL: Documentation, https://docs.algovoi.co.uk
10
+ Keywords: keystone,sdk,cli,bolt-on,connector,behaviour,execution_ref,jcs,rfc8785,agentic-payments,algovoi
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Classifier: Environment :: Console
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ License-File: NOTICE
22
+ Requires-Dist: algovoi-keystone-connect>=0.4.0
23
+ Requires-Dist: algovoi-keystone-agent>=0.4.0
24
+ Requires-Dist: algovoi-keystone-runtime>=0.4.0
25
+ Requires-Dist: algovoi-execution-ref>=0.4.0
26
+ Requires-Dist: rfc8785>=0.1.4
27
+ Provides-Extra: validate
28
+ Requires-Dist: algovoi-keystone-validate>=0.1.0; extra == "validate"
29
+ Provides-Extra: publish
30
+ Requires-Dist: build>=1.0; extra == "publish"
31
+ Requires-Dist: twine>=5.0; extra == "publish"
32
+ Dynamic: license-file
33
+
34
+ # algovoi-keystone
35
+
36
+ The Keystone SDK, in one install. `pip install algovoi-keystone` brings the whole bolt-on toolchain:
37
+ the connector builder ([keystone-connect](https://pypi.org/project/algovoi-keystone-connect/)), the
38
+ agentic behaviour layer ([keystone-agent](https://pypi.org/project/algovoi-keystone-agent/)) with its
39
+ ready-made behaviours, and the `keystone` command line. Everything still reduces to one primitive,
40
+ `ref = "sha256:" + SHA-256(RFC 8785 JCS(payload))`, with no AlgoVoi software in your trust base.
41
+ Apache-2.0.
42
+
43
+ ## One import surface
44
+
45
+ ```python
46
+ from algovoi_keystone import connector, rule, trigger, behaviour, Engine, keystone_ref, behaviours
47
+
48
+ keystone_s3 = connector("s3", writes={"put_object": ("put", lambda c: c.kwargs["Bucket"])})
49
+ engine = Engine([behaviours.cap_charges(500)], decision_ref=decision_ref)
50
+ ```
51
+
52
+ ## The `keystone` command line
53
+
54
+ ```
55
+ keystone new <name> --kind connector|behaviour|stage scaffold a publishable bolt-on
56
+ keystone test [path] run the bolt-on's test battery
57
+ keystone validate <records.json> verify emitted refs offline
58
+ keystone doctor check the environment
59
+ keystone info show installed pieces + the primitive
60
+ keystone publish [path] build the dist and check it (mirror-first)
61
+ ```
62
+
63
+ `keystone new` writes a complete package already wired to the conformance battery, so a bolt-on
64
+ goes from nothing to tested in one step:
65
+
66
+ ```
67
+ keystone new redis-stream --kind connector
68
+ cd redis-stream/python && keystone test # green: recompute, decision-bound, tamper-evident
69
+ ```
70
+
71
+ `keystone validate` verifies any emitted record offline, whether it is an `execution_ref` from a
72
+ connector or a `behaviour_ref` from the agent layer: it recomputes the reference from the recorded
73
+ fields and reports any that do not match, so a third party checks your evidence with a stock RFC 8785
74
+ implementation and standard SHA-256.
75
+
76
+ Install from the Keystone control panel (the integrity path, from the AlgoVoi index); new releases
77
+ land on the AlgoVoi index first, with PyPI mirrors following. Built on the AlgoVoi substrate
78
+ (RFC 8785 JCS + SHA-256).
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ algovoi_keystone/__init__.py
6
+ algovoi_keystone/cli.py
7
+ algovoi_keystone.egg-info/PKG-INFO
8
+ algovoi_keystone.egg-info/SOURCES.txt
9
+ algovoi_keystone.egg-info/dependency_links.txt
10
+ algovoi_keystone.egg-info/entry_points.txt
11
+ algovoi_keystone.egg-info/requires.txt
12
+ algovoi_keystone.egg-info/top_level.txt
13
+ tests/test_cli.py
14
+ tests/test_cli_security.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ keystone = algovoi_keystone.cli:main
@@ -0,0 +1,12 @@
1
+ algovoi-keystone-connect>=0.4.0
2
+ algovoi-keystone-agent>=0.4.0
3
+ algovoi-keystone-runtime>=0.4.0
4
+ algovoi-execution-ref>=0.4.0
5
+ rfc8785>=0.1.4
6
+
7
+ [publish]
8
+ build>=1.0
9
+ twine>=5.0
10
+
11
+ [validate]
12
+ algovoi-keystone-validate>=0.1.0
@@ -0,0 +1 @@
1
+ algovoi_keystone
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=70", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "algovoi-keystone"
7
+ version = "0.4.0"
8
+ description = "The Keystone SDK umbrella -- one install for the whole bolt-on toolchain (connector builder + agentic behaviour layer) plus the `keystone` command line. Everything reduces to sha256 over RFC 8785 JCS (Apache-2.0)"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ authors = [{ name = "AlgoVoi", email = "chopmob@gmail.com" }]
13
+ keywords = ["keystone", "sdk", "cli", "bolt-on", "connector", "behaviour", "execution_ref", "jcs", "rfc8785", "agentic-payments", "algovoi"]
14
+ requires-python = ">=3.10"
15
+ dependencies = [
16
+ "algovoi-keystone-connect>=0.4.0",
17
+ "algovoi-keystone-agent>=0.4.0",
18
+ "algovoi-keystone-runtime>=0.4.0",
19
+ "algovoi-execution-ref>=0.4.0",
20
+ "rfc8785>=0.1.4",
21
+ ]
22
+ classifiers = [
23
+ "Programming Language :: Python :: 3",
24
+ "Topic :: Software Development :: Libraries",
25
+ "Environment :: Console",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Programming Language :: Python :: 3.13",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ validate = ["algovoi-keystone-validate>=0.1.0"]
34
+ publish = ["build>=1.0", "twine>=5.0"]
35
+
36
+ [project.scripts]
37
+ keystone = "algovoi_keystone.cli:main"
38
+
39
+ [tool.setuptools.packages.find]
40
+ where = ["."]
41
+ include = ["algovoi_keystone*"]
42
+
43
+ [project.urls]
44
+ Homepage = "https://www.algovoi.co.uk"
45
+ Repository = "https://github.com/chopmob-cloud/algovoi-keystone"
46
+ Documentation = "https://docs.algovoi.co.uk"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,87 @@
1
+ """End-to-end tests for the algovoi-keystone umbrella + `keystone` CLI."""
2
+ import json
3
+ import os
4
+ import subprocess
5
+ import sys
6
+
7
+ import pytest
8
+
9
+ from algovoi_keystone import ( # umbrella import surface
10
+ Engine, behaviour, behaviours, connector, keystone_ref, rule, trigger,
11
+ )
12
+ from algovoi_keystone.cli import cmd_new, main
13
+
14
+
15
+ def test_umbrella_reexports_work():
16
+ # one import gives connectors + behaviours + the primitive
17
+ ks3 = connector("s3", writes={"put_object": ("put", lambda c: c.kwargs["Bucket"])})
18
+ eng = Engine([behaviours.cap_charges(500)], decision_ref=keystone_ref({"g": 1}), clock_ms=lambda: 1)
19
+ fired = eng.dispatch({"stage": "spend_decision", "amount": 900, "action_type": "charge"})
20
+ assert fired and fired[0]["verdict"] == "BLOCK"
21
+ assert callable(ks3) and callable(rule) and callable(trigger) and callable(behaviour)
22
+
23
+
24
+ def test_info_and_doctor(capsys):
25
+ assert main(["info"]) == 0
26
+ out = capsys.readouterr().out
27
+ assert "algovoi-keystone-connect" in out and "keystone_ref(payload)" in out
28
+ # doctor: connect + agent + rfc8785 all importable in this env
29
+ assert main(["doctor"]) == 0
30
+ assert "PASS" in capsys.readouterr().out
31
+
32
+
33
+ @pytest.mark.parametrize("kind", ["connector", "behaviour", "stage"])
34
+ def test_scaffold_then_test_is_green(tmp_path, kind, monkeypatch):
35
+ monkeypatch.chdir(tmp_path)
36
+ name = "acme-" + kind
37
+ rc = cmd_new(type("A", (), {"name": name, "kind": kind})())
38
+ assert rc == 0
39
+ pkgdir = tmp_path / name / "python"
40
+ assert (pkgdir / "pyproject.toml").exists()
41
+ assert (pkgdir / f"keystone_acme_{kind}" / "__init__.py").exists()
42
+ # the scaffolded bolt-on must pass its own wired-in conformance test
43
+ env = dict(os.environ)
44
+ env["PYTHONPATH"] = str(pkgdir) + os.pathsep + env.get("PYTHONPATH", "")
45
+ r = subprocess.run([sys.executable, "-m", "pytest", "-q", str(pkgdir / "tests")],
46
+ capture_output=True, text=True, env=env)
47
+ assert r.returncode == 0, r.stdout + r.stderr
48
+
49
+
50
+ def test_validate_behaviour_and_execution_records(tmp_path):
51
+ # a behaviour_ref record
52
+ eng = Engine([behaviours.cap_charges(500)], decision_ref=keystone_ref({"g": 1}), clock_ms=lambda: 1)
53
+ brec = eng.dispatch({"stage": "spend_decision", "amount": 900, "action_type": "charge"})[0]
54
+ # an execution_ref record from a real connector
55
+ ks3 = connector("s3", writes={"put_object": ("put", lambda c: c.kwargs["Bucket"] + "/" + c.kwargs["Key"])})
56
+
57
+ class Fake:
58
+ def put_object(self, **kw): return {}
59
+ client = ks3(Fake(), decision_ref=keystone_ref({"g": 1}))
60
+ client.put_object(Bucket="b", Key="k")
61
+ erec = client.executions[-1] if hasattr(client, "executions") else None
62
+
63
+ records = [brec] + ([erec] if erec else [])
64
+ f = tmp_path / "records.json"
65
+ f.write_text(json.dumps(records))
66
+ assert main(["validate", str(f)]) == 0
67
+
68
+
69
+ def test_runtime_reexport_and_journal_command(tmp_path, capsys):
70
+ from algovoi_keystone import Journal, Runtime, keystone_ref
71
+ db = str(tmp_path / "j.db")
72
+ rt = Runtime(Journal(db, clock_ms=lambda: 1), decision_ref=keystone_ref({"g": 1}),
73
+ clock_ms=lambda: 2)
74
+ rt.record_stage("passport", {"agent": "a7"})
75
+ rt.journal.close()
76
+ assert main(["journal", db, "--show"]) == 0
77
+ out = capsys.readouterr().out
78
+ assert "1 entries" in out and "passport" in out and "PASS" in out
79
+
80
+
81
+ def test_validate_catches_tamper(tmp_path):
82
+ eng = Engine([behaviours.cap_charges(500)], decision_ref=keystone_ref({"g": 1}), clock_ms=lambda: 1)
83
+ rec = dict(eng.dispatch({"stage": "spend_decision", "amount": 900, "action_type": "charge"})[0])
84
+ rec["verdict"] = "ALLOW" # tamper: was BLOCK, ref no longer recomputes
85
+ f = tmp_path / "bad.json"
86
+ f.write_text(json.dumps(rec))
87
+ assert main(["validate", str(f)]) == 1 # non-zero exit on failure
@@ -0,0 +1,135 @@
1
+ """Fail-closed regressions at the untrusted offline-evidence boundary."""
2
+ import json
3
+
4
+ from algovoi_keystone.cli import main
5
+ from algovoi_keystone_connect import keystone_ref
6
+
7
+
8
+ def test_incomplete_execution_cannot_fall_back_to_generic_hash(tmp_path):
9
+ record = {"execution_ref": "sha256:" + "0" * 64, "outcome": "COMMITTED"}
10
+ record["ref"] = keystone_ref(record)
11
+ path = tmp_path / "incomplete.json"
12
+ path.write_text(json.dumps(record), encoding="utf-8")
13
+ assert main(["validate", str(path)]) == 1
14
+
15
+
16
+ def test_incomplete_runtime_record_is_refused(tmp_path):
17
+ """Runtime append never stores a record whose fields do not recompute."""
18
+ from algovoi_keystone import Journal, Runtime
19
+
20
+ db = str(tmp_path / "j.db")
21
+ journal = Journal(db, clock_ms=lambda: 1)
22
+ rt = Runtime(journal, decision_ref="sha256:x", clock_ms=lambda: 2)
23
+ rec = {"decision_ref": "sha256:x", "action_type": "s3:put", "scope": "b",
24
+ "outcome": "COMMITTED", "executed_at_ms": 1}
25
+ rec["execution_ref"] = keystone_ref(rec)
26
+ try:
27
+ rt.journal.append(rec)
28
+ except ValueError:
29
+ refused = True
30
+ else:
31
+ refused = False
32
+ rt.journal.close()
33
+ assert refused is True
34
+
35
+
36
+
37
+ def test_empty_evidence_does_not_pass(tmp_path):
38
+ path = tmp_path / "empty.json"
39
+ path.write_text("[]", encoding="utf-8")
40
+ assert main(["validate", str(path)]) != 0
41
+
42
+
43
+ def test_duplicate_json_keys_are_rejected(tmp_path):
44
+ body = {"stage": "decision", "verdict": "ALLOW"}
45
+ body["stage_ref"] = keystone_ref(body)
46
+ text = json.dumps(body).replace('"verdict": "ALLOW"',
47
+ '"verdict": "BLOCK", "verdict": "ALLOW"')
48
+ path = tmp_path / "ambiguous.json"
49
+ path.write_text(text, encoding="utf-8")
50
+ assert main(["validate", str(path)]) == 2
51
+
52
+
53
+ def test_oversized_evidence_is_rejected(tmp_path):
54
+ body = {"payload": "x" * (8 * 1024 * 1024)}
55
+ body["stage_ref"] = keystone_ref(body)
56
+ path = tmp_path / "large.json"
57
+ path.write_text(json.dumps(body), encoding="utf-8")
58
+ assert main(["validate", str(path)]) == 2
59
+
60
+
61
+ def test_full_chain_wrapped_record_validates(tmp_path):
62
+ """A typed execution_keystone wrapper is still decision-bound and recomputes."""
63
+ from algovoi_execution_ref import bind_keystone
64
+
65
+ body = bind_keystone(
66
+ passport_ref=keystone_ref({"passport": 1}),
67
+ mandate_ref=keystone_ref({"mandate": 1}),
68
+ policy_bound_ref=keystone_ref({"policy": 1}), verdict="ALLOW",
69
+ action_type="s3:put", scope="receipts/r1", outcome="COMMITTED",
70
+ executed_at_ms=1700000000000, trust_outcome="TRUSTED")
71
+ path = tmp_path / "wrapped.json"
72
+ path.write_text(json.dumps(body), encoding="utf-8")
73
+ assert main(["validate", str(path)]) == 0
74
+
75
+
76
+ def test_tampered_full_chain_wrapper_is_rejected(tmp_path):
77
+ """CLI must not accept a wrapper whose decision/trust tiers were rewritten."""
78
+ from algovoi_execution_ref import bind_keystone
79
+
80
+ body = bind_keystone(
81
+ passport_ref=keystone_ref({"passport": 1}),
82
+ mandate_ref=keystone_ref({"mandate": 1}),
83
+ policy_bound_ref=keystone_ref({"policy": 1}), verdict="ALLOW",
84
+ action_type="s3:put", scope="receipts/r1", outcome="COMMITTED",
85
+ executed_at_ms=1700000000000, trust_outcome="TRUSTED")
86
+ body["trust_outcome"] = "UNTRUSTED"
87
+ path = tmp_path / "tampered.json"
88
+ path.write_text(json.dumps(body), encoding="utf-8")
89
+ assert main(["validate", str(path)]) == 1
90
+
91
+
92
+ def test_multi_self_reference_record_is_rejected(tmp_path):
93
+ body = {"stage": "mandate", "decision_ref": keystone_ref({"g": 1})}
94
+ body["stage_ref"] = keystone_ref(body)
95
+ body["behaviour_ref"] = "sha256:" + "a" * 64
96
+ path = tmp_path / "mixed.json"
97
+ path.write_text(json.dumps(body), encoding="utf-8")
98
+ assert main(["validate", str(path)]) == 1
99
+
100
+
101
+ def test_arbitrary_ref_field_cannot_prove_integrity(tmp_path):
102
+ """Only real self-references count; a fabricated *_ref must not pass."""
103
+ body = {"verdict": "ALLOW", "amount": 1}
104
+ body["settlement_ref"] = keystone_ref(body)
105
+ path = tmp_path / "fabricated.json"
106
+ path.write_text(json.dumps(body), encoding="utf-8")
107
+ assert main(["validate", str(path)]) == 1
108
+
109
+
110
+ def test_journal_missing_database_reports_failure_without_creating_it(tmp_path):
111
+ """A typo'd or absent journal path must not be silently created as empty."""
112
+ db = tmp_path / "absent.db"
113
+ assert main(["journal", str(db)]) != 0
114
+ assert not db.exists()
115
+
116
+
117
+ def test_journal_corrupt_database_reports_failure(tmp_path):
118
+ """Corrupt state must produce a failed report, not a traceback."""
119
+ db = tmp_path / "corrupt.db"
120
+ db.write_bytes(b"not a sqlite database at all" * 100)
121
+ assert main(["journal", str(db)]) != 0
122
+
123
+
124
+ def test_journal_expected_head_truncation_is_detected(tmp_path, capsys):
125
+ from algovoi_keystone import Journal, Runtime
126
+
127
+ db = str(tmp_path / "j.db")
128
+ journal = Journal(db, clock_ms=lambda: 1)
129
+ rt = Runtime(journal, decision_ref=keystone_ref({"grant": 1}), clock_ms=lambda: 2)
130
+ rt.record_stage("mandate", {"passport_ref": keystone_ref({"p": 1})})
131
+ rt.record_stage("mandate", {"passport_ref": keystone_ref({"p": 2})})
132
+ head = journal.head()
133
+ journal.close()
134
+ assert main(["journal", db, "--expected-head", head]) == 0
135
+ assert main(["journal", db, "--expected-head", "sha256:" + "b" * 64]) == 1