execweave 1.0.0__py3-none-any.whl

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 (234) hide show
  1. execweave/__init__.py +3 -0
  2. execweave/__main__.py +5 -0
  3. execweave/_conversation_records_core.py +902 -0
  4. execweave/_dashboard_shell_base.py +148 -0
  5. execweave/_http_proxy_base.py +565 -0
  6. execweave/_http_proxy_bounded.py +560 -0
  7. execweave/_http_proxy_stage.py +509 -0
  8. execweave/acceptance_output.py +19 -0
  9. execweave/agent_bootstrap.py +395 -0
  10. execweave/agent_topology.py +313 -0
  11. execweave/agent_trace.py +1162 -0
  12. execweave/agy_preview_sanitize.py +102 -0
  13. execweave/analysis.py +427 -0
  14. execweave/anthropic.py +228 -0
  15. execweave/anthropic_cli.py +171 -0
  16. execweave/anthropic_full_fidelity.py +385 -0
  17. execweave/antigravity_adapter.py +112 -0
  18. execweave/antigravity_adapter_base.py +479 -0
  19. execweave/antigravity_full_fidelity.py +656 -0
  20. execweave/antigravity_full_fidelity_base.py +172 -0
  21. execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
  22. execweave/antigravity_hook_cli.py +209 -0
  23. execweave/antigravity_record.py +96 -0
  24. execweave/antigravity_subagent_linkage.py +449 -0
  25. execweave/antigravity_trace_capability.py +39 -0
  26. execweave/auto_specialized.py +547 -0
  27. execweave/backends.py +102 -0
  28. execweave/benchmark.py +80 -0
  29. execweave/claude_adapter.py +517 -0
  30. execweave/claude_child_transcript.py +314 -0
  31. execweave/claude_delegation.py +136 -0
  32. execweave/claude_full_fidelity.py +396 -0
  33. execweave/claude_hook_cli.py +209 -0
  34. execweave/claude_hook_contract.py +943 -0
  35. execweave/claude_model_observer.py +353 -0
  36. execweave/claude_record.py +106 -0
  37. execweave/cli.py +629 -0
  38. execweave/codex_adapter.py +455 -0
  39. execweave/codex_conversation.py +621 -0
  40. execweave/codex_full_fidelity.py +287 -0
  41. execweave/codex_hook_cli.py +301 -0
  42. execweave/codex_hook_entry.py +207 -0
  43. execweave/codex_hook_lifecycle.py +363 -0
  44. execweave/codex_message_diagnostics.py +322 -0
  45. execweave/codex_message_transport_diagnostics.py +399 -0
  46. execweave/codex_record.py +199 -0
  47. execweave/codex_rollout_structures.py +402 -0
  48. execweave/codex_rollout_trace.py +56 -0
  49. execweave/codex_rollout_trace_base.py +1509 -0
  50. execweave/collector.py +768 -0
  51. execweave/command.py +157 -0
  52. execweave/command_privacy.py +20 -0
  53. execweave/content_evidence.py +101 -0
  54. execweave/content_integrity.py +289 -0
  55. execweave/content_store.py +273 -0
  56. execweave/controlled_checks.py +561 -0
  57. execweave/conversation_archive.py +338 -0
  58. execweave/conversation_message_identity.py +264 -0
  59. execweave/conversation_preview.py +66 -0
  60. execweave/conversation_preview_antigravity.py +32 -0
  61. execweave/conversation_preview_claude.py +31 -0
  62. execweave/conversation_preview_codex.py +107 -0
  63. execweave/conversation_preview_common.py +180 -0
  64. execweave/conversation_preview_generic.py +188 -0
  65. execweave/conversation_preview_lines.py +133 -0
  66. execweave/conversation_preview_transcript.py +121 -0
  67. execweave/conversation_records.py +349 -0
  68. execweave/conversation_records_antigravity.py +370 -0
  69. execweave/conversation_records_codex.py +83 -0
  70. execweave/conversation_records_common.py +17 -0
  71. execweave/conversation_records_ollama.py +39 -0
  72. execweave/correlation.py +818 -0
  73. execweave/cursor_adapter.py +349 -0
  74. execweave/cursor_delegation.py +87 -0
  75. execweave/cursor_delegation_base.py +220 -0
  76. execweave/cursor_full_fidelity.py +489 -0
  77. execweave/cursor_hook_cli.py +195 -0
  78. execweave/cursor_hook_contract.py +439 -0
  79. execweave/cursor_lifecycle.py +159 -0
  80. execweave/cursor_record.py +96 -0
  81. execweave/dashboard_shell.py +283 -0
  82. execweave/delivery_status.py +94 -0
  83. execweave/entry.py +98 -0
  84. execweave/evidence_availability.py +113 -0
  85. execweave/evidence_grade.py +166 -0
  86. execweave/fidelity.py +304 -0
  87. execweave/filesystem.py +327 -0
  88. execweave/finalization.py +92 -0
  89. execweave/focus.py +118 -0
  90. execweave/framework_adapters/__init__.py +34 -0
  91. execweave/framework_adapters/autogen.py +398 -0
  92. execweave/framework_adapters/base.py +580 -0
  93. execweave/framework_adapters/camel.py +270 -0
  94. execweave/framework_adapters/camel_channel.py +71 -0
  95. execweave/framework_adapters/metagpt.py +315 -0
  96. execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
  97. execweave/framework_adapters/metagpt_recording.py +342 -0
  98. execweave/framework_adapters/registry.py +90 -0
  99. execweave/graph.py +590 -0
  100. execweave/graph_ops.py +472 -0
  101. execweave/hook_command.py +32 -0
  102. execweave/hook_delivery.py +32 -0
  103. execweave/hook_input.py +16 -0
  104. execweave/http_proxy.py +187 -0
  105. execweave/http_proxy_cli.py +84 -0
  106. execweave/inference_gateway.py +476 -0
  107. execweave/inference_gateway_cli.py +211 -0
  108. execweave/inference_gateway_full_fidelity.py +613 -0
  109. execweave/inference_identity.py +76 -0
  110. execweave/inference_identity_cli.py +60 -0
  111. execweave/integrity.py +235 -0
  112. execweave/integrity_cli.py +55 -0
  113. execweave/investigation_index.py +445 -0
  114. execweave/litellm_callback.py +211 -0
  115. execweave/litellm_callback_cli.py +42 -0
  116. execweave/live.py +445 -0
  117. execweave/live_core.py +972 -0
  118. execweave/live_view.py +109 -0
  119. execweave/live_view_extra_style.py +11 -0
  120. execweave/live_view_markup.py +29 -0
  121. execweave/live_view_process_layout.py +650 -0
  122. execweave/live_view_readability.py +502 -0
  123. execweave/live_view_script_a.py +59 -0
  124. execweave/live_view_script_b.py +97 -0
  125. execweave/live_view_script_c.py +59 -0
  126. execweave/live_view_script_d.py +40 -0
  127. execweave/live_view_style.py +34 -0
  128. execweave/model_runtime.py +560 -0
  129. execweave/model_runtime_cli.py +265 -0
  130. execweave/model_runtime_full_fidelity.py +519 -0
  131. execweave/observation.py +53 -0
  132. execweave/observation_demo.py +69 -0
  133. execweave/openai_agents.py +267 -0
  134. execweave/openai_agents_sdk.py +453 -0
  135. execweave/openai_compatible.py +239 -0
  136. execweave/openai_compatible_cli.py +189 -0
  137. execweave/openai_compatible_full_fidelity.py +438 -0
  138. execweave/opencode_adapter.py +325 -0
  139. execweave/opencode_event_contract.py +734 -0
  140. execweave/opencode_full_fidelity.py +198 -0
  141. execweave/opencode_hook_cli.py +119 -0
  142. execweave/opencode_plugin_cli.py +150 -0
  143. execweave/opencode_record.py +96 -0
  144. execweave/opencode_task_linkage.py +225 -0
  145. execweave/overhead_benchmark.py +440 -0
  146. execweave/privacy.py +84 -0
  147. execweave/private_io.py +465 -0
  148. execweave/provider_capability.py +578 -0
  149. execweave/provider_lifecycle.py +282 -0
  150. execweave/provider_record.py +290 -0
  151. execweave/reader_identity.py +13 -0
  152. execweave/redacted_archive.py +906 -0
  153. execweave/risk.py +106 -0
  154. execweave/rule_pack.py +359 -0
  155. execweave/rule_pack_cli.py +57 -0
  156. execweave/run_assessment.py +200 -0
  157. execweave/runtime_endpoint_availability.py +44 -0
  158. execweave/scalability_benchmark.py +195 -0
  159. execweave/schema.py +62 -0
  160. execweave/scope.py +85 -0
  161. execweave/semantic.py +453 -0
  162. execweave/session_summary.py +159 -0
  163. execweave/sink.py +71 -0
  164. execweave/strace_backend.py +927 -0
  165. execweave/stream_assembly.py +363 -0
  166. execweave/task_artifacts.py +192 -0
  167. execweave/task_validation.py +317 -0
  168. execweave/theme.py +40 -0
  169. execweave/top.py +599 -0
  170. execweave/top_cli.py +150 -0
  171. execweave/validate.py +196 -0
  172. execweave/vendor/dagre.min.js +815 -0
  173. execweave/view_cli.py +49 -0
  174. execweave/viewer.py +474 -0
  175. execweave/viewer_agent_panel.py +630 -0
  176. execweave/viewer_agent_panel_antigravity.py +31 -0
  177. execweave/viewer_agent_panel_claude.py +9 -0
  178. execweave/viewer_agent_panel_codex.py +50 -0
  179. execweave/viewer_agent_panel_cursor.py +9 -0
  180. execweave/viewer_agent_panel_default.py +79 -0
  181. execweave/viewer_agent_panel_ollama.py +20 -0
  182. execweave/viewer_agent_panel_opencode.py +9 -0
  183. execweave/viewer_agent_panel_registry.py +20 -0
  184. execweave/viewer_archive_verifier.py +178 -0
  185. execweave/viewer_background_files.py +86 -0
  186. execweave/viewer_content_browser.py +307 -0
  187. execweave/viewer_content_health.py +208 -0
  188. execweave/viewer_content_inspector.py +309 -0
  189. execweave/viewer_controlled_checks.py +258 -0
  190. execweave/viewer_conversation_sync.py +115 -0
  191. execweave/viewer_dashboard_clean.py +405 -0
  192. execweave/viewer_dashboard_focus.py +127 -0
  193. execweave/viewer_dashboard_hardening.py +264 -0
  194. execweave/viewer_dashboard_hardening_v2.py +62 -0
  195. execweave/viewer_dashboard_projection.py +261 -0
  196. execweave/viewer_delivery_status.py +155 -0
  197. execweave/viewer_edge_decross.py +117 -0
  198. execweave/viewer_execution_flow.py +611 -0
  199. execweave/viewer_execution_flow_provider_normalization.py +107 -0
  200. execweave/viewer_execution_flow_safety.py +349 -0
  201. execweave/viewer_external_endpoints.py +307 -0
  202. execweave/viewer_flow_canvas.py +1140 -0
  203. execweave/viewer_flow_layout.py +922 -0
  204. execweave/viewer_fold_state.py +31 -0
  205. execweave/viewer_framework_flow.py +68 -0
  206. execweave/viewer_framework_model_output.py +133 -0
  207. execweave/viewer_gif.py +278 -0
  208. execweave/viewer_history_browser.py +225 -0
  209. execweave/viewer_investigation.py +268 -0
  210. execweave/viewer_layout_geometry.py +192 -0
  211. execweave/viewer_layout_v2.py +429 -0
  212. execweave/viewer_layout_v2_detached.py +25 -0
  213. execweave/viewer_limits.py +93 -0
  214. execweave/viewer_live_layout.py +61 -0
  215. execweave/viewer_message_handoffs.py +114 -0
  216. execweave/viewer_projection.py +488 -0
  217. execweave/viewer_projection_base.py +522 -0
  218. execweave/viewer_projection_bridges.py +214 -0
  219. execweave/viewer_recorded_sources.py +146 -0
  220. execweave/viewer_run_assessment.py +274 -0
  221. execweave/viewer_run_guide.py +175 -0
  222. execweave/viewer_runtime_evidence.py +258 -0
  223. execweave/viewer_semantic_projection.py +641 -0
  224. execweave/viewer_session_flow.py +491 -0
  225. execweave/viewer_structure_share.py +132 -0
  226. execweave/viewer_task_validation.py +241 -0
  227. execweave/viewer_tool_mirror_identity.py +75 -0
  228. execweave/viewer_workflow_mode.py +127 -0
  229. execweave/workflow.py +183 -0
  230. execweave-1.0.0.dist-info/METADATA +462 -0
  231. execweave-1.0.0.dist-info/RECORD +234 -0
  232. execweave-1.0.0.dist-info/WHEEL +4 -0
  233. execweave-1.0.0.dist-info/entry_points.txt +30 -0
  234. execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
@@ -0,0 +1,561 @@
1
+ """Execute fixed acceptance predicates on captured bytes and sign the result.
2
+
3
+ Only explicit CLI selections authorize reads. No artifact code, report command,
4
+ plugin, regular expression or external URL is executed. Trust in a signature
5
+ requires an independently selected verifier profile and its approved policy hash.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import base64
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import sys
17
+ import uuid
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from .task_artifacts import (
23
+ FORMAT as ARTIFACT_FORMAT,
24
+ MAX_FILE_BYTES,
25
+ MAX_TOTAL_BYTES,
26
+ _read_selected,
27
+ artifact_name,
28
+ manifest_bytes,
29
+ validate_manifest,
30
+ )
31
+ from .task_validation import _pairs, _read, _text, task_subject
32
+
33
+ POLICY_FORMAT = "execweave.fixed-check-policy.v1"
34
+ PROFILE_FORMAT = "execweave.verifier-profile.v1"
35
+ RECEIPT_FORMAT = "execweave.controlled-checks.v1"
36
+ PAYLOAD_FORMAT = "execweave.fixed-check-execution.v1"
37
+ DOMAIN = b"ExecWeave fixed checks v1\x00"
38
+ MAX_POLICY = 128 * 1024
39
+ MAX_RECEIPT = 2 * 1024 * 1024
40
+ MAX_CHECKS = 100
41
+ HEX = re.compile(r"[0-9a-f]{64}\Z")
42
+ IDENTIFIER = re.compile(r"[A-Za-z0-9_.-]{1,96}\Z")
43
+ LIMITATION = (
44
+ "Only approved fixed predicates on the listed captured byte buffers were evaluated. "
45
+ "No program behavior, complete task correctness, whole directory, dependencies, "
46
+ "atomic filesystem snapshot or hardware attestation is certified. Trust requires "
47
+ "the verifier host and separately pinned signing key to remain under trusted control."
48
+ )
49
+
50
+
51
+ def _bad_constant(_value):
52
+ raise ValueError("nonfinite JSON is not supported")
53
+
54
+
55
+ def strict_json(value: str | bytes, limit: int = MAX_RECEIPT, *, safe_numbers: bool = True) -> Any:
56
+ raw = value.encode("utf-8") if isinstance(value, str) else value
57
+ if not isinstance(raw, bytes) or len(raw) > limit:
58
+ raise ValueError("JSON exceeds its byte limit")
59
+ result = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs, parse_constant=_bad_constant)
60
+
61
+ # Bound recursion and numeric semantics identically to browser JSON.
62
+ def check(v, depth=0):
63
+ if depth > 32:
64
+ raise ValueError("JSON nesting exceeds 32")
65
+ if safe_numbers and (isinstance(v, float) or (type(v) is int and abs(v) > 2**53 - 1)):
66
+ raise ValueError("only safe JSON integers are supported")
67
+ if isinstance(v, str):
68
+ v.encode("utf-8") # Refuse unpaired surrogates.
69
+ elif isinstance(v, list):
70
+ for item in v:
71
+ check(item, depth + 1)
72
+ elif isinstance(v, dict):
73
+ for k, item in v.items():
74
+ check(k, depth + 1)
75
+ check(item, depth + 1)
76
+
77
+ check(result)
78
+ return result
79
+
80
+
81
+ def _fields(value: Any, names: set[str], what: str) -> dict:
82
+ if not isinstance(value, dict) or set(value) != names:
83
+ raise ValueError(f"invalid {what} fields")
84
+ return value
85
+
86
+
87
+ def encoded(value: Any) -> bytes:
88
+ return json.dumps(
89
+ value, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(",", ":")
90
+ ).encode("utf-8")
91
+
92
+
93
+ def digest(value: bytes) -> str:
94
+ return hashlib.sha256(value).hexdigest()
95
+
96
+
97
+ def _hex(value: Any) -> bool:
98
+ return isinstance(value, str) and HEX.fullmatch(value) is not None
99
+
100
+
101
+ def _pointer(value: Any) -> list[str]:
102
+ if not isinstance(value, str) or len(value) > 2048 or (value and not value.startswith("/")):
103
+ raise ValueError("invalid JSON pointer")
104
+ if re.search(r"~(?![01])", value):
105
+ raise ValueError("invalid JSON pointer escape")
106
+ parts = [] if not value else value[1:].split("/")
107
+ if len(parts) > 32:
108
+ raise ValueError("JSON pointer exceeds 32 steps")
109
+ return [p.replace("~1", "/").replace("~0", "~") for p in parts]
110
+
111
+
112
+ def policy_document(raw: str | bytes) -> dict:
113
+ policy = strict_json(raw, MAX_POLICY)
114
+ _fields(policy, {"format", "name", "checks"}, "policy")
115
+ if policy["format"] != POLICY_FORMAT:
116
+ raise ValueError("unsupported fixed-check policy")
117
+ _text(policy["name"], "policy name", 256)
118
+ rows = policy["checks"]
119
+ if not isinstance(rows, list) or not 1 <= len(rows) <= MAX_CHECKS:
120
+ raise ValueError("policy requires 1 to 100 checks; empty checks cannot pass")
121
+ seen, paths = set(), {}
122
+ for row in rows:
123
+ if not isinstance(row, dict):
124
+ raise ValueError("invalid check")
125
+ op = row.get("op")
126
+ expected_fields = {"id", "path", "op", "expected"}
127
+ if op == "json_pointer_equals":
128
+ expected_fields.add("pointer")
129
+ _fields(row, expected_fields, "check")
130
+ if (
131
+ not isinstance(row["id"], str)
132
+ or not IDENTIFIER.fullmatch(row["id"])
133
+ or row["id"] in seen
134
+ ):
135
+ raise ValueError("check IDs must be unique portable identifiers")
136
+ seen.add(row["id"])
137
+ name = artifact_name(row["path"])
138
+ if name.lower() in paths and paths[name.lower()] != name:
139
+ raise ValueError("case-colliding policy paths")
140
+ paths[name.lower()] = name
141
+ expected = row["expected"]
142
+ if op == "sha256_equals":
143
+ if not _hex(expected):
144
+ raise ValueError("invalid expected SHA-256")
145
+ elif op == "utf8_contains":
146
+ _text(expected, "expected text", 65536)
147
+ elif op == "json_pointer_equals":
148
+ _pointer(row["pointer"])
149
+ if expected is not None and type(expected) not in (str, int, bool):
150
+ raise ValueError("JSON comparison requires a scalar expected value")
151
+ if isinstance(expected, str) and len(expected) > 65536:
152
+ raise ValueError("expected scalar exceeds limit")
153
+ else:
154
+ raise ValueError("unsupported check operation; executable tests are not accepted")
155
+ return policy
156
+
157
+
158
+ def _binding(graph: dict, task_id: str) -> tuple[dict, dict, str]:
159
+ from .run_assessment import build_run_assessment
160
+
161
+ assessment = build_run_assessment(graph)
162
+ if assessment["inspection"]["state"] != "declared_graph":
163
+ raise ValueError("complete unambiguous raw graph metadata is required")
164
+ session = _text(graph.get("session_id"), "session ID")
165
+ subjects = assessment["task_validation"]["external_report_subjects"]
166
+ nodes = [n for n in graph.get("nodes", []) if isinstance(n, dict) and n.get("id") == task_id]
167
+ if len(nodes) != 1 or sum(s["task_id"] == task_id for s in subjects) != 1:
168
+ raise ValueError("exact native task is missing, ambiguous or outside the budget")
169
+ subject = task_subject(nodes[0])
170
+ scope = {"session_id": session}
171
+ for name in ("run_id", "source_path"):
172
+ value = graph.get(name)
173
+ if value is not None:
174
+ _text(value, name)
175
+ scope[name] = value
176
+ return scope, subject, encoded(nodes[0]).decode("utf-8")
177
+
178
+
179
+ def _crypto():
180
+ try:
181
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
182
+ Ed25519PrivateKey,
183
+ Ed25519PublicKey,
184
+ )
185
+ from cryptography.hazmat.primitives import serialization
186
+ except ImportError as exc:
187
+ raise ValueError("signing requires the optional execweave[validation] extra") from exc
188
+ return Ed25519PrivateKey, Ed25519PublicKey, serialization
189
+
190
+
191
+ def _b64(value: bytes) -> str:
192
+ return base64.b64encode(value).decode("ascii")
193
+
194
+
195
+ def _unb64(value: Any, size: int) -> bytes:
196
+ if not isinstance(value, str) or len(value) != 4 * ((size + 2) // 3):
197
+ raise ValueError("invalid encoded key or signature")
198
+ raw = base64.b64decode(value, validate=True)
199
+ if len(raw) != size or _b64(raw) != value:
200
+ raise ValueError("noncanonical encoded key or signature")
201
+ return raw
202
+
203
+
204
+ def make_profile(public: bytes, policy_raw: bytes, label: str) -> dict:
205
+ policy_document(policy_raw)
206
+ if len(public) != 32:
207
+ raise ValueError("an Ed25519 public key is required")
208
+ return {
209
+ "format": PROFILE_FORMAT,
210
+ "label": _text(label, "verifier label", 256),
211
+ "key_id": digest(public),
212
+ "public_key_b64": _b64(public),
213
+ "policy_sha256": digest(policy_raw),
214
+ }
215
+
216
+
217
+ def validate_profile(profile: Any) -> bytes:
218
+ _fields(profile, {"format", "label", "key_id", "public_key_b64", "policy_sha256"}, "profile")
219
+ public = _unb64(profile["public_key_b64"], 32)
220
+ if (
221
+ profile["format"] != PROFILE_FORMAT
222
+ or profile["key_id"] != digest(public)
223
+ or not _hex(profile["policy_sha256"])
224
+ ):
225
+ raise ValueError("invalid pinned verifier profile")
226
+ _text(profile["label"], "verifier label", 256)
227
+ return public
228
+
229
+
230
+ def _predicate(row: dict, raw: bytes) -> tuple[str, str]:
231
+ if row["op"] == "sha256_equals":
232
+ equal = digest(raw) == row["expected"]
233
+ else:
234
+ try:
235
+ text = raw.decode("utf-8")
236
+ except UnicodeError:
237
+ return "error", "invalid_utf8"
238
+ if row["op"] == "utf8_contains":
239
+ equal = row["expected"] in text
240
+ else:
241
+ try:
242
+ value = strict_json(raw, MAX_FILE_BYTES)
243
+ except (ValueError, RecursionError, UnicodeError):
244
+ return "error", "invalid_json"
245
+ try:
246
+ for part in _pointer(row["pointer"]):
247
+ if isinstance(value, list) and re.fullmatch(r"0|[1-9][0-9]*", part):
248
+ value = value[int(part)]
249
+ elif isinstance(value, dict):
250
+ value = value[part]
251
+ else:
252
+ raise KeyError(part)
253
+ except (KeyError, IndexError, ValueError):
254
+ return "failed", "pointer_missing"
255
+ equal = type(value) is type(row["expected"]) and value == row["expected"]
256
+ return ("passed", "predicate_true") if equal else ("failed", "predicate_false")
257
+
258
+
259
+ def execute_checks(
260
+ graph: dict, task_id: str, policy_raw: bytes, selections: list[str], key
261
+ ) -> dict:
262
+ """Evaluate only in-memory immutable bytes, then sign their hashes and outcomes."""
263
+ policy = policy_document(policy_raw)
264
+ scope, subject, task_json = _binding(graph, task_id)
265
+ expected = {r["path"] for r in policy["checks"]}
266
+ if not 1 <= len(selections) <= 100:
267
+ raise ValueError("select 1 to 100 files explicitly")
268
+ paths = {}
269
+ for spec in selections:
270
+ if not isinstance(spec, str) or "=" not in spec:
271
+ raise ValueError("use RELATIVE_NAME=LOCAL_FILE selections")
272
+ name, path = spec.split("=", 1)
273
+ artifact_name(name)
274
+ if not path or name in paths:
275
+ raise ValueError("duplicate or empty file selection")
276
+ paths[name] = path
277
+ if set(paths) != expected:
278
+ raise ValueError("explicit file selections must exactly match the approved policy paths")
279
+ buffers, total = {}, 0
280
+ for name, path in paths.items():
281
+ raw = _read_selected(path)
282
+ total += len(raw)
283
+ if total > MAX_TOTAL_BYTES:
284
+ raise ValueError("selected input bytes exceed 64 MiB")
285
+ buffers[name] = raw
286
+ # Hashes, checks and manifest derive from these same byte objects. There is
287
+ # no subprocess, artifact import, shell, plugin, later reread or test report.
288
+ entries = [
289
+ {"path": name, "size_bytes": len(raw), "sha256": digest(raw)}
290
+ for name, raw in sorted(buffers.items(), key=lambda item: item[0].encode("utf-8"))
291
+ ]
292
+ artifacts = {
293
+ "format": ARTIFACT_FORMAT,
294
+ "entries": entries,
295
+ "manifest_sha256": digest(manifest_bytes(entries)),
296
+ }
297
+ results = []
298
+ for row in policy["checks"]:
299
+ outcome, reason = _predicate(row, buffers[row["path"]])
300
+ results.append(
301
+ {
302
+ "id": row["id"],
303
+ "path": row["path"],
304
+ "op": row["op"],
305
+ "artifact_sha256": digest(buffers[row["path"]]),
306
+ "outcome": outcome,
307
+ "reason": reason,
308
+ }
309
+ )
310
+ payload = {
311
+ "format": PAYLOAD_FORMAT,
312
+ "scope": scope,
313
+ "subject": subject,
314
+ "task_snapshot_json": task_json,
315
+ "policy_json": policy_raw.decode("utf-8"),
316
+ "policy_sha256": digest(policy_raw),
317
+ "artifacts": artifacts,
318
+ "results": results,
319
+ "execution_id": uuid.uuid4().hex,
320
+ "recorded_at": datetime.now(timezone.utc).isoformat(),
321
+ "task_success_implied": False,
322
+ "limitation": LIMITATION,
323
+ }
324
+ encoded_payload = encoded(payload)
325
+ if len(encoded_payload) > MAX_RECEIPT // 2:
326
+ raise ValueError("signed payload exceeds its limit")
327
+ private_class, _, serialization = _crypto()
328
+ if not isinstance(key, private_class):
329
+ raise ValueError("Ed25519 signer required")
330
+ public = key.public_key().public_bytes(
331
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
332
+ )
333
+ return {
334
+ "format": RECEIPT_FORMAT,
335
+ "key_id": digest(public),
336
+ "payload": encoded_payload.decode("utf-8"),
337
+ "signature_b64": _b64(key.sign(DOMAIN + encoded_payload)),
338
+ }
339
+
340
+
341
+ def inspect_payload(payload: Any, profile: dict) -> dict:
342
+ """Validate coverage and derive results; never trust a supplied summary."""
343
+ _fields(
344
+ payload,
345
+ {
346
+ "format",
347
+ "scope",
348
+ "subject",
349
+ "task_snapshot_json",
350
+ "policy_json",
351
+ "policy_sha256",
352
+ "artifacts",
353
+ "results",
354
+ "execution_id",
355
+ "recorded_at",
356
+ "task_success_implied",
357
+ "limitation",
358
+ },
359
+ "signed payload",
360
+ )
361
+ if (
362
+ payload["format"] != PAYLOAD_FORMAT
363
+ or payload["task_success_implied"] is not False
364
+ or payload["limitation"] != LIMITATION
365
+ ):
366
+ raise ValueError("unsupported execution semantics")
367
+ _fields(payload["scope"], {"session_id", "run_id", "source_path"}, "scope")
368
+ _text(payload["scope"]["session_id"], "session ID")
369
+ for field in ("run_id", "source_path"):
370
+ if payload["scope"][field] is not None:
371
+ _text(payload["scope"][field], field)
372
+ _fields(payload["subject"], {"task_id", "task_snapshot_sha256"}, "subject")
373
+ task_raw = payload["task_snapshot_json"]
374
+ node = strict_json(task_raw, 1024 * 1024, safe_numbers=False)
375
+ if (
376
+ task_subject(node) != payload["subject"]
377
+ or digest(task_raw.encode("utf-8")) != payload["subject"]["task_snapshot_sha256"]
378
+ ):
379
+ raise ValueError("signed task snapshot mismatch")
380
+ raw = payload["policy_json"].encode("utf-8")
381
+ policy = policy_document(raw)
382
+ if digest(raw) != payload["policy_sha256"] or digest(raw) != profile["policy_sha256"]:
383
+ raise ValueError("policy was not independently approved by this profile")
384
+ _text(payload["recorded_at"], "recorded time", 64)
385
+ if not isinstance(payload["execution_id"], str) or not re.fullmatch(
386
+ "[0-9a-f]{32}", payload["execution_id"]
387
+ ):
388
+ raise ValueError("invalid execution identity")
389
+ _fields(payload["artifacts"], {"format", "entries", "manifest_sha256"}, "artifact manifest")
390
+ manifest = validate_manifest(payload["artifacts"])
391
+ for entry in payload["artifacts"]["entries"]:
392
+ _fields(entry, {"path", "size_bytes", "sha256"}, "artifact entry")
393
+ by_path = {item["path"]: item for item in manifest["entries"]}
394
+ if set(by_path) != {row["path"] for row in policy["checks"]}:
395
+ raise ValueError("signed artifacts do not cover exactly the approved policy")
396
+ results = payload["results"]
397
+ if not isinstance(results, list) or len(results) != len(policy["checks"]):
398
+ raise ValueError("missing or additional executed checks")
399
+ counts = {"passed": 0, "failed": 0, "error": 0}
400
+ reasons = {
401
+ "passed": {"predicate_true"},
402
+ "failed": {"predicate_false", "pointer_missing"},
403
+ "error": {"invalid_utf8", "invalid_json"},
404
+ }
405
+ for planned, result in zip(policy["checks"], results):
406
+ _fields(result, {"id", "path", "op", "artifact_sha256", "outcome", "reason"}, "result")
407
+ if (
408
+ any(result[k] != planned[k] for k in ("id", "path", "op"))
409
+ or result["artifact_sha256"] != by_path[planned["path"]]["sha256"]
410
+ ):
411
+ raise ValueError("executed check identity or byte binding mismatch")
412
+ outcome = result["outcome"]
413
+ if (
414
+ not isinstance(outcome, str)
415
+ or outcome not in counts
416
+ or result["reason"] not in reasons[outcome]
417
+ ):
418
+ raise ValueError("invalid executed check outcome")
419
+ counts[outcome] += 1
420
+ return {
421
+ "state": "checks_passed" if counts["passed"] == len(results) else "checks_failed",
422
+ "counts": counts,
423
+ "policy_name": policy["name"],
424
+ "payload": payload,
425
+ "whole_task_verified": False,
426
+ }
427
+
428
+
429
+ def verify_receipt(envelope: Any, profile: dict, graph: dict, task_id: str) -> dict:
430
+ public = validate_profile(profile)
431
+ _fields(envelope, {"format", "key_id", "payload", "signature_b64"}, "receipt")
432
+ if envelope["format"] != RECEIPT_FORMAT or envelope["key_id"] != profile["key_id"]:
433
+ raise ValueError("receipt does not match the independently pinned key")
434
+ raw = envelope["payload"].encode("utf-8")
435
+ if len(raw) > MAX_RECEIPT // 2:
436
+ raise ValueError("signed payload exceeds limit")
437
+ _, public_class, _ = _crypto()
438
+ from cryptography.exceptions import InvalidSignature
439
+
440
+ try:
441
+ public_class.from_public_bytes(public).verify(
442
+ _unb64(envelope["signature_b64"], 64), DOMAIN + raw
443
+ )
444
+ except InvalidSignature as exc:
445
+ raise ValueError("signature verification failed") from exc
446
+ payload = strict_json(raw)
447
+ result = inspect_payload(payload, profile)
448
+ scope, subject, _ = _binding(graph, task_id)
449
+ if payload["scope"] != scope or payload["subject"] != subject:
450
+ raise ValueError("signed result belongs to a different execution or task snapshot")
451
+ result["signature_verified"] = True
452
+ return result
453
+
454
+
455
+ def _write_new(path: str, raw: bytes, mode: int = 0o600) -> None:
456
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0), mode)
457
+ with os.fdopen(fd, "wb") as stream:
458
+ stream.write(raw)
459
+ stream.flush()
460
+ os.fsync(stream.fileno())
461
+
462
+
463
+ def main(argv: list[str] | None = None) -> int:
464
+ parser = argparse.ArgumentParser(
465
+ description="Execute fixed byte predicates, sign results, or verify using an independently pinned profile. Never executes supplied code."
466
+ )
467
+ sub = parser.add_subparsers(dest="action", required=True)
468
+ keygen = sub.add_parser(
469
+ "keygen",
470
+ help="Create a private signing key and a policy-pinned public profile; protect the private file.",
471
+ )
472
+ for name in ("private-key", "profile", "policy", "label"):
473
+ keygen.add_argument("--" + name, required=True)
474
+ run = sub.add_parser("run")
475
+ for name in ("graph", "task-id", "policy", "private-key", "output"):
476
+ run.add_argument("--" + name, required=True)
477
+ run.add_argument("--artifact", action="append", required=True, metavar="NAME=FILE")
478
+ verify = sub.add_parser("verify")
479
+ for name in ("graph", "task-id", "receipt", "profile"):
480
+ verify.add_argument("--" + name, required=True)
481
+ args = parser.parse_args(argv)
482
+ try:
483
+ private_class, _, serialization = _crypto()
484
+ if args.action == "keygen":
485
+ policy_raw = _read(args.policy, MAX_POLICY)
486
+ policy_document(policy_raw)
487
+ if (
488
+ Path(args.private_key).exists()
489
+ or Path(args.profile).exists()
490
+ or Path(args.private_key).resolve() == Path(args.profile).resolve()
491
+ ):
492
+ raise ValueError("key/profile outputs must be different new files")
493
+ key = private_class.generate()
494
+ public = key.public_key().public_bytes(
495
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
496
+ )
497
+ profile = make_profile(public, policy_raw, args.label)
498
+ pem = key.private_bytes(
499
+ serialization.Encoding.PEM,
500
+ serialization.PrivateFormat.PKCS8,
501
+ serialization.NoEncryption(),
502
+ )
503
+ _write_new(args.private_key, pem)
504
+ _write_new(args.profile, encoded(profile) + b"\n")
505
+ print(
506
+ json.dumps(
507
+ {
508
+ "key_id": profile["key_id"],
509
+ "policy_sha256": profile["policy_sha256"],
510
+ "note": "Trust the public profile through a separate approved channel; protect the private key.",
511
+ }
512
+ )
513
+ )
514
+ return 0
515
+ graph = strict_json(
516
+ _read(args.graph, 64 * 1024 * 1024), 64 * 1024 * 1024, safe_numbers=False
517
+ )
518
+ if args.action == "verify":
519
+ profile = strict_json(_read(args.profile, MAX_POLICY), MAX_POLICY)
520
+ result = verify_receipt(
521
+ strict_json(_read(args.receipt, MAX_RECEIPT)), profile, graph, args.task_id
522
+ )
523
+ else:
524
+ if os.name == "posix" and os.lstat(args.private_key).st_mode & 0o077:
525
+ raise ValueError("private key permissions must exclude group and other users")
526
+ policy_raw = _read(args.policy, MAX_POLICY)
527
+ key = serialization.load_pem_private_key(_read(args.private_key, 4096), password=None)
528
+ for spec in args.artifact:
529
+ if "=" in spec and os.path.samefile(spec.split("=", 1)[1], args.private_key):
530
+ raise ValueError("private key cannot be an artifact input")
531
+ envelope = execute_checks(graph, args.task_id, policy_raw, args.artifact, key)
532
+ public = key.public_key().public_bytes(
533
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
534
+ )
535
+ profile = make_profile(public, policy_raw, "local signer")
536
+ result = verify_receipt(envelope, profile, graph, args.task_id)
537
+ _write_new(args.output, encoded(envelope) + b"\n")
538
+ print(
539
+ json.dumps(
540
+ {
541
+ k: result[k]
542
+ for k in ("state", "counts", "signature_verified", "whole_task_verified")
543
+ }
544
+ )
545
+ )
546
+ return 0 if result["state"] == "checks_passed" else 1
547
+ except (
548
+ OSError,
549
+ ValueError,
550
+ TypeError,
551
+ KeyError,
552
+ AttributeError,
553
+ UnicodeError,
554
+ RecursionError,
555
+ ) as exc:
556
+ print(f"Controlled checks not accepted: {exc}", file=sys.stderr)
557
+ return 2
558
+
559
+
560
+ if __name__ == "__main__":
561
+ raise SystemExit(main())