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
execweave/graph_ops.py ADDED
@@ -0,0 +1,472 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from collections import Counter, defaultdict, deque
6
+ from copy import deepcopy
7
+ from pathlib import Path, PurePosixPath
8
+ from typing import Any, Iterable
9
+
10
+ from .private_io import private_artifact_path, write_private_json
11
+
12
+ SUPPORTED_GRAPH_SCHEMA_VERSIONS = frozenset({"0.1", "0.2"})
13
+
14
+
15
+ def validate_graph_payload(
16
+ payload: Any,
17
+ *,
18
+ supported_versions: frozenset[str] = SUPPORTED_GRAPH_SCHEMA_VERSIONS,
19
+ ) -> dict[str, Any]:
20
+ if not isinstance(payload, dict):
21
+ raise ValueError("graph root must be a JSON object")
22
+ version = payload.get("graph_schema_version")
23
+ if not isinstance(version, str) or version not in supported_versions:
24
+ shown = version if isinstance(version, str) else "missing"
25
+ raise ValueError(f"unsupported graph schema version: {shown}")
26
+ # Reject graphs that explicitly declare a future/malformed source stream.
27
+ # Graph schema and event-stream schema are separate version namespaces.
28
+ source_versions = payload.get("source_schema_versions")
29
+ if source_versions is not None:
30
+ if not isinstance(source_versions, list) or any(
31
+ not isinstance(item, str) or item not in {"0.1", "0.2"}
32
+ for item in source_versions
33
+ ):
34
+ raise ValueError(
35
+ "unsupported_schema_version: graph declares an unsupported "
36
+ f"source event-stream schema {source_versions!r}; supported: 0.2"
37
+ )
38
+ if not isinstance(payload.get("nodes"), list) or not isinstance(payload.get("edges"), list):
39
+ raise ValueError("graph must contain nodes and edges arrays")
40
+ return payload
41
+
42
+
43
+
44
+ def load_graph(path: str | Path) -> dict[str, Any]:
45
+ graph_path = Path(path).expanduser().resolve()
46
+ try:
47
+ payload = json.loads(graph_path.read_text(encoding="utf-8"))
48
+ except FileNotFoundError as exc:
49
+ raise ValueError(f"graph does not exist: {graph_path}") from exc
50
+ except json.JSONDecodeError as exc:
51
+ raise ValueError(f"graph is not valid JSON: {exc.msg}") from exc
52
+ return validate_graph_payload(payload)
53
+
54
+
55
+ def write_graph_payload(graph: dict[str, Any], path: str | Path) -> Path:
56
+ output = private_artifact_path(path)
57
+ output.parent.mkdir(parents=True, exist_ok=True)
58
+ if output.exists() and output.stat().st_size > 0:
59
+ raise FileExistsError(f"ExecWeave graph output already exists: {output}")
60
+ write_private_json(output, graph)
61
+ return output
62
+
63
+
64
+ def graph_summary(graph: dict[str, Any]) -> dict[str, Any]:
65
+ nodes = [node for node in graph.get("nodes", []) if isinstance(node, dict)]
66
+ edges = [edge for edge in graph.get("edges", []) if isinstance(edge, dict)]
67
+ node_types = Counter(
68
+ node.get("type") for node in nodes if isinstance(node.get("type"), str)
69
+ )
70
+ relations = Counter(
71
+ edge.get("relation") for edge in edges if isinstance(edge.get("relation"), str)
72
+ )
73
+ causal_edges = sum(1 for edge in edges if edge.get("causal") is True)
74
+ noncausal_edges = sum(1 for edge in edges if edge.get("causal") is False)
75
+ mixed_edges = len(edges) - causal_edges - noncausal_edges
76
+ expansion = graph.get("expansion")
77
+ expansion_clusters = (
78
+ expansion.get("clusters", {})
79
+ if isinstance(expansion, dict) and isinstance(expansion.get("clusters"), dict)
80
+ else {}
81
+ )
82
+ return {
83
+ "session_id": graph.get("session_id"),
84
+ "event_count": graph.get("event_count"),
85
+ "node_count": len(nodes),
86
+ "edge_count": len(edges),
87
+ "node_types": dict(sorted(node_types.items())),
88
+ "relations": dict(sorted(relations.items())),
89
+ "causal_edges": causal_edges,
90
+ "noncausal_edges": noncausal_edges,
91
+ "mixed_or_unknown_causal_edges": mixed_edges,
92
+ "condensed": bool(graph.get("condensed")),
93
+ "expandable_cluster_count": len(expansion_clusters),
94
+ }
95
+
96
+
97
+ def filter_graph(
98
+ graph: dict[str, Any],
99
+ *,
100
+ node_types: Iterable[str] = (),
101
+ relations: Iterable[str] = (),
102
+ causal_only: bool = False,
103
+ backends: Iterable[str] = (),
104
+ ) -> dict[str, Any]:
105
+ requested_node_types = set(node_types)
106
+ requested_relations = set(relations)
107
+ requested_backends = set(backends)
108
+
109
+ nodes = [node for node in graph.get("nodes", []) if isinstance(node, dict)]
110
+ edges = [edge for edge in graph.get("edges", []) if isinstance(edge, dict)]
111
+
112
+ if requested_node_types:
113
+ selected_nodes = {
114
+ node.get("id")
115
+ for node in nodes
116
+ if node.get("type") in requested_node_types and isinstance(node.get("id"), str)
117
+ }
118
+ else:
119
+ selected_nodes = {
120
+ node.get("id") for node in nodes if isinstance(node.get("id"), str)
121
+ }
122
+
123
+ filtered_edges: list[dict[str, Any]] = []
124
+ for edge in edges:
125
+ source = edge.get("source")
126
+ target = edge.get("target")
127
+ if source not in selected_nodes or target not in selected_nodes:
128
+ continue
129
+ if requested_relations and edge.get("relation") not in requested_relations:
130
+ continue
131
+ if causal_only and edge.get("causal") is not True:
132
+ continue
133
+ edge_backends = set(edge.get("backends") or [])
134
+ if requested_backends and not requested_backends.intersection(edge_backends):
135
+ continue
136
+ filtered_edges.append(deepcopy(edge))
137
+
138
+ connected_nodes: set[str] = set()
139
+ for edge in filtered_edges:
140
+ source = edge.get("source")
141
+ target = edge.get("target")
142
+ if isinstance(source, str):
143
+ connected_nodes.add(source)
144
+ if isinstance(target, str):
145
+ connected_nodes.add(target)
146
+
147
+ keep_nodes = selected_nodes if requested_node_types else connected_nodes
148
+ filtered_nodes = [
149
+ deepcopy(node)
150
+ for node in nodes
151
+ if isinstance(node.get("id"), str) and node.get("id") in keep_nodes
152
+ ]
153
+
154
+ payload = deepcopy(graph)
155
+ payload["nodes"] = filtered_nodes
156
+ payload["edges"] = filtered_edges
157
+ payload["node_count"] = len(filtered_nodes)
158
+ payload["edge_count"] = len(filtered_edges)
159
+ payload["filter"] = {
160
+ "node_types": sorted(requested_node_types),
161
+ "relations": sorted(requested_relations),
162
+ "causal_only": causal_only,
163
+ "backends": sorted(requested_backends),
164
+ }
165
+ return payload
166
+
167
+
168
+ def _node_bucket(node: dict[str, Any]) -> str:
169
+ node_id = str(node.get("id") or "")
170
+ prefix, _, value = node_id.partition(":")
171
+ if prefix in {"file", "directory", "executable"} and value:
172
+ canonical = value.replace("\\", "/")
173
+ parent = str(PurePosixPath(canonical).parent)
174
+ return parent if parent != "." else "<relative>"
175
+ return "<unknown>"
176
+
177
+
178
+ def _cluster_id(parts: tuple[object, ...]) -> str:
179
+ raw = json.dumps(parts, ensure_ascii=False, separators=(",", ":"), sort_keys=False)
180
+ digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
181
+ return f"cluster:{digest}"
182
+
183
+
184
+ def condense_graph(
185
+ graph: dict[str, Any],
186
+ *,
187
+ threshold: int = 8,
188
+ sample_size: int = 8,
189
+ collapsible_types: Iterable[str] = ("file", "directory", "executable"),
190
+ include_expansion: bool = False,
191
+ ) -> dict[str, Any]:
192
+ """Collapse repetitive leaf resources while preserving runtime topology.
193
+
194
+ By default the result stays compact. When ``include_expansion`` is true, the
195
+ original member nodes and their incoming evidence edges are preserved under the
196
+ top-level ``expansion.clusters`` map so a viewer can materialize them on demand.
197
+ The expansion payload copies observed evidence; it does not infer new relations.
198
+ """
199
+ if threshold < 2:
200
+ raise ValueError("threshold must be >= 2")
201
+ if sample_size < 1:
202
+ raise ValueError("sample_size must be >= 1")
203
+
204
+ nodes = [deepcopy(node) for node in graph.get("nodes", []) if isinstance(node, dict)]
205
+ edges = [deepcopy(edge) for edge in graph.get("edges", []) if isinstance(edge, dict)]
206
+ node_by_id = {
207
+ node["id"]: node for node in nodes if isinstance(node.get("id"), str)
208
+ }
209
+ incoming: dict[str, list[dict[str, Any]]] = defaultdict(list)
210
+ outgoing: dict[str, list[dict[str, Any]]] = defaultdict(list)
211
+ for edge in edges:
212
+ source = edge.get("source")
213
+ target = edge.get("target")
214
+ if isinstance(source, str):
215
+ outgoing[source].append(edge)
216
+ if isinstance(target, str):
217
+ incoming[target].append(edge)
218
+
219
+ allowed_types = set(collapsible_types)
220
+ groups: dict[tuple[object, ...], list[tuple[dict[str, Any], dict[str, Any]]]] = defaultdict(list)
221
+ for node_id, node in node_by_id.items():
222
+ node_type = node.get("type")
223
+ if node_type not in allowed_types:
224
+ continue
225
+ if outgoing.get(node_id) or len(incoming.get(node_id, [])) != 1:
226
+ continue
227
+ edge = incoming[node_id][0]
228
+ source = edge.get("source")
229
+ relation = edge.get("relation")
230
+ if not isinstance(source, str) or not isinstance(relation, str):
231
+ continue
232
+ key = (
233
+ source,
234
+ relation,
235
+ node_type,
236
+ _node_bucket(node),
237
+ edge.get("causal"),
238
+ tuple(sorted(str(item) for item in (edge.get("backends") or []))),
239
+ )
240
+ groups[key].append((node, edge))
241
+
242
+ collapsed_node_ids: set[str] = set()
243
+ collapsed_edge_ids: set[str] = set()
244
+ cluster_nodes: list[dict[str, Any]] = []
245
+ cluster_edges: list[dict[str, Any]] = []
246
+ expansion_clusters: dict[str, dict[str, Any]] = {}
247
+ collapsed_groups = 0
248
+
249
+ for key, members in groups.items():
250
+ if len(members) < threshold:
251
+ continue
252
+ collapsed_groups += 1
253
+ source, relation, node_type, bucket, causal, backends = key
254
+ cluster_id = _cluster_id(key)
255
+ member_nodes = [node for node, _ in members]
256
+ member_edges = [edge for _, edge in members]
257
+ collapsed_node_ids.update(
258
+ node["id"] for node in member_nodes if isinstance(node.get("id"), str)
259
+ )
260
+ collapsed_edge_ids.update(
261
+ edge["id"] for edge in member_edges if isinstance(edge.get("id"), str)
262
+ )
263
+
264
+ names = [
265
+ str(node.get("name") or node.get("id"))
266
+ for node in member_nodes
267
+ if node.get("name") or node.get("id")
268
+ ]
269
+ first_seen_values = [
270
+ node.get("first_seen") for node in member_nodes if isinstance(node.get("first_seen"), str)
271
+ ]
272
+ last_seen_values = [
273
+ node.get("last_seen") for node in member_nodes if isinstance(node.get("last_seen"), str)
274
+ ]
275
+ first_seq_values = [
276
+ edge.get("first_sequence")
277
+ for edge in member_edges
278
+ if isinstance(edge.get("first_sequence"), int)
279
+ ]
280
+ last_seq_values = [
281
+ edge.get("last_sequence")
282
+ for edge in member_edges
283
+ if isinstance(edge.get("last_sequence"), int)
284
+ ]
285
+ event_ids = [
286
+ str(event_id)
287
+ for edge in member_edges
288
+ for event_id in (edge.get("event_ids") or [])
289
+ if isinstance(event_id, str)
290
+ ]
291
+ event_types = sorted(
292
+ {
293
+ str(event_type)
294
+ for edge in member_edges
295
+ for event_type in (edge.get("event_types") or [])
296
+ if isinstance(event_type, str)
297
+ }
298
+ )
299
+ attributions = sorted(
300
+ {
301
+ str(value)
302
+ for edge in member_edges
303
+ for value in (edge.get("attributions") or [])
304
+ if isinstance(value, str)
305
+ }
306
+ )
307
+
308
+ cluster_nodes.append(
309
+ {
310
+ "id": cluster_id,
311
+ "type": f"{node_type}_cluster",
312
+ "name": f"{len(member_nodes)} {node_type}s in {bucket}",
313
+ "attributes": {
314
+ "collapsed": True,
315
+ "member_count": len(member_nodes),
316
+ "member_type": node_type,
317
+ "directory_bucket": bucket,
318
+ "sample_members": names[:sample_size],
319
+ "sample_truncated": len(names) > sample_size,
320
+ "expandable": include_expansion,
321
+ },
322
+ "first_seen": min(first_seen_values) if first_seen_values else None,
323
+ "last_seen": max(last_seen_values) if last_seen_values else None,
324
+ "event_count": sum(
325
+ int(node.get("event_count") or 0) for node in member_nodes
326
+ ),
327
+ "event_types": event_types,
328
+ }
329
+ )
330
+ cluster_edge_id = f"{source}--{relation}-->{cluster_id}"
331
+ cluster_edges.append(
332
+ {
333
+ "id": cluster_edge_id,
334
+ "source": source,
335
+ "target": cluster_id,
336
+ "relation": relation,
337
+ "count": sum(int(edge.get("count") or 0) for edge in member_edges),
338
+ "first_seen": min(first_seen_values) if first_seen_values else None,
339
+ "last_seen": max(last_seen_values) if last_seen_values else None,
340
+ "first_sequence": min(first_seq_values) if first_seq_values else None,
341
+ "last_sequence": max(last_seq_values) if last_seq_values else None,
342
+ "event_ids": event_ids[:32],
343
+ "event_ids_truncated": len(event_ids) > 32,
344
+ "evidence_event_count": len(event_ids),
345
+ "event_types": event_types,
346
+ "backends": list(backends),
347
+ "attributions": attributions,
348
+ "causal": causal,
349
+ "collapsed_member_count": len(member_nodes),
350
+ }
351
+ )
352
+ if include_expansion:
353
+ expansion_clusters[cluster_id] = {
354
+ "cluster_node_id": cluster_id,
355
+ "cluster_edge_id": cluster_edge_id,
356
+ "nodes": deepcopy(member_nodes),
357
+ "edges": deepcopy(member_edges),
358
+ }
359
+
360
+ condensed_nodes = [
361
+ node for node in nodes if node.get("id") not in collapsed_node_ids
362
+ ] + cluster_nodes
363
+ condensed_edges = [
364
+ edge for edge in edges if edge.get("id") not in collapsed_edge_ids
365
+ ] + cluster_edges
366
+
367
+ payload = deepcopy(graph)
368
+ payload["nodes"] = sorted(
369
+ condensed_nodes,
370
+ key=lambda node: (str(node.get("type") or ""), str(node.get("id") or "")),
371
+ )
372
+ payload["edges"] = sorted(
373
+ condensed_edges,
374
+ key=lambda edge: (
375
+ str(edge.get("source") or ""),
376
+ str(edge.get("relation") or ""),
377
+ str(edge.get("target") or ""),
378
+ ),
379
+ )
380
+ payload["node_count"] = len(payload["nodes"])
381
+ payload["edge_count"] = len(payload["edges"])
382
+ payload["condensed"] = True
383
+ payload["condensation"] = {
384
+ "threshold": threshold,
385
+ "sample_size": sample_size,
386
+ "collapsible_types": sorted(allowed_types),
387
+ "original_node_count": len(nodes),
388
+ "original_edge_count": len(edges),
389
+ "collapsed_group_count": collapsed_groups,
390
+ "collapsed_node_count": len(collapsed_node_ids),
391
+ "result_node_count": len(payload["nodes"]),
392
+ "result_edge_count": len(payload["edges"]),
393
+ "expansion_embedded": include_expansion,
394
+ }
395
+ if include_expansion:
396
+ payload["expansion"] = {
397
+ "schema_version": "0.1",
398
+ "clusters": expansion_clusters,
399
+ }
400
+ else:
401
+ payload.pop("expansion", None)
402
+ return payload
403
+
404
+
405
+ def find_paths(
406
+ graph: dict[str, Any],
407
+ *,
408
+ source: str,
409
+ target: str,
410
+ max_depth: int = 6,
411
+ max_paths: int = 20,
412
+ relations: Iterable[str] = (),
413
+ causal_only: bool = False,
414
+ ) -> list[dict[str, Any]]:
415
+ if max_depth < 1:
416
+ raise ValueError("max_depth must be >= 1")
417
+ if max_paths < 1:
418
+ raise ValueError("max_paths must be >= 1")
419
+
420
+ nodes = {
421
+ node.get("id"): node
422
+ for node in graph.get("nodes", [])
423
+ if isinstance(node, dict) and isinstance(node.get("id"), str)
424
+ }
425
+ if source not in nodes:
426
+ raise ValueError(f"source node not found: {source}")
427
+ if target not in nodes:
428
+ raise ValueError(f"target node not found: {target}")
429
+
430
+ requested_relations = set(relations)
431
+ adjacency: dict[str, list[dict[str, Any]]] = {}
432
+ for edge in graph.get("edges", []):
433
+ if not isinstance(edge, dict):
434
+ continue
435
+ if requested_relations and edge.get("relation") not in requested_relations:
436
+ continue
437
+ if causal_only and edge.get("causal") is not True:
438
+ continue
439
+ edge_source = edge.get("source")
440
+ edge_target = edge.get("target")
441
+ if not isinstance(edge_source, str) or not isinstance(edge_target, str):
442
+ continue
443
+ adjacency.setdefault(edge_source, []).append(edge)
444
+
445
+ queue: deque[tuple[str, list[str], list[dict[str, Any]]]] = deque()
446
+ queue.append((source, [source], []))
447
+ results: list[dict[str, Any]] = []
448
+
449
+ while queue and len(results) < max_paths:
450
+ current, node_path, edge_path = queue.popleft()
451
+ if len(edge_path) >= max_depth:
452
+ continue
453
+ for edge in adjacency.get(current, []):
454
+ next_node = edge["target"]
455
+ if next_node in node_path:
456
+ continue
457
+ next_nodes = [*node_path, next_node]
458
+ next_edges = [*edge_path, edge]
459
+ if next_node == target:
460
+ results.append(
461
+ {
462
+ "nodes": next_nodes,
463
+ "relations": [item.get("relation") for item in next_edges],
464
+ "edges": deepcopy(next_edges),
465
+ }
466
+ )
467
+ if len(results) >= max_paths:
468
+ break
469
+ continue
470
+ queue.append((next_node, next_nodes, next_edges))
471
+
472
+ return results
@@ -0,0 +1,32 @@
1
+ """Rootless hooks tied to the installing interpreter, not an agent's PATH."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shlex
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ _MODULES = {
11
+ "claude": "execweave.claude_hook_cli",
12
+ "codex": "execweave.codex_hook_entry",
13
+ "antigravity": "execweave.antigravity_hook_cli",
14
+ "cursor": "execweave.cursor_hook_cli",
15
+ "opencode": "execweave.opencode_hook_cli",
16
+ }
17
+
18
+
19
+ def hook_argv(provider: str) -> list[str]:
20
+ # Do NOT resolve symlinks: a venv's python symlink must retain its venv path.
21
+ return [str(Path(sys.executable).absolute()), "-I", "-m", _MODULES[provider], "--auto"]
22
+
23
+
24
+ def hook_command(provider: str) -> str:
25
+ parts = hook_argv(provider)
26
+ return subprocess.list2cmdline(parts) if os.name == "nt" else shlex.join(parts)
27
+
28
+
29
+ def hook_markers(marker: str) -> tuple[str, ...]:
30
+ provider = marker.removeprefix("execweave-").removesuffix("-hook")
31
+ module = _MODULES.get(provider)
32
+ return (marker, module) if module else (marker,)
@@ -0,0 +1,32 @@
1
+ """Bounded, content-free delivery diagnostics for configured provider hooks."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+
9
+ def sidecar_delivery(path: str | None) -> dict[str, Any]:
10
+ if not path:
11
+ return {"state": "not_configured"}
12
+ try:
13
+ with Path(path).open("rb") as handle:
14
+ for _ in range(10000):
15
+ line = handle.readline(1024 * 1024 + 1)
16
+ if not line:
17
+ return {"state": "no_records"}
18
+ if len(line) > 1024 * 1024:
19
+ return {"state": "inspection_limit"}
20
+ if not line.strip():
21
+ continue
22
+ record = json.loads(line)
23
+ if (isinstance(record, dict) and isinstance(record.get("event_type"), str)
24
+ and record["event_type"] and isinstance(record.get("relation"), str)
25
+ and record["relation"]):
26
+ return {"state": "records_present", "semantic_validity": "not_verified"}
27
+ return {"state": "invalid_record"}
28
+ except FileNotFoundError:
29
+ return {"state": "not_produced"}
30
+ except (OSError, ValueError, UnicodeError):
31
+ return {"state": "unreadable_or_invalid"}
32
+ return {"state": "inspection_limit"}
@@ -0,0 +1,16 @@
1
+ """Read JSON hook transport as UTF-8, independently of the terminal code page."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+
7
+ def read_hook_text(source: Any) -> str:
8
+ binary = getattr(source, "buffer", None)
9
+ raw = binary.read() if binary is not None else source.read()
10
+ if isinstance(raw, bytes):
11
+ # Strict decoding avoids silently replacing evidence. Invalid input is
12
+ # reported by the existing fail-open hook boundary, not mis-recorded.
13
+ return raw.decode("utf-8-sig")
14
+ if not isinstance(raw, str):
15
+ raise ValueError("hook stdin must supply UTF-8 bytes or text")
16
+ return raw.lstrip("\ufeff")