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.py ADDED
@@ -0,0 +1,590 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from dataclasses import asdict, dataclass, field
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .session_summary import SessionSummary
11
+ from .observation import session_outcome as assessed_session_outcome
12
+ from .fidelity import FidelityAccumulator
13
+ from .provider_lifecycle import ProviderLifecycleAnnotation, provider_lifecycle_annotation
14
+ from .validate import validate_event_stream
15
+ from .private_io import private_artifact_path, write_private_json
16
+
17
+ GRAPH_SCHEMA_VERSION = "0.2"
18
+
19
+
20
+ def logical_event_key(event: dict[str, Any]) -> str | None:
21
+ """Return a replay key only when the event exposes occurrence identity.
22
+
23
+ A semantic sidecar can replay one transcript occurrence many times, but equal
24
+ endpoints do *not* prove equal occurrences. Model invocations are the important
25
+ counterexample: one provider session legitimately invokes the same model more than
26
+ once. We therefore fold only events that carry a provider occurrence discriminator
27
+ or point at an occurrence-shaped entity whose stable ID supplies that discriminator.
28
+ """
29
+ if not isinstance(event, dict):
30
+ return None
31
+ event_type = event.get("event_type")
32
+ attributes = event.get("attributes")
33
+ semantic = (
34
+ isinstance(event_type, str)
35
+ and event_type.startswith("semantic.")
36
+ ) or (
37
+ isinstance(attributes, dict)
38
+ and attributes.get("backend") == "semantic"
39
+ )
40
+ event_id = event.get("event_id")
41
+ if not semantic and isinstance(event_id, str) and event_id:
42
+ return f"event_id:{event_id}"
43
+ if not semantic:
44
+ return None
45
+ def endpoint_identity(value: object) -> dict[str, str] | None:
46
+ if not isinstance(value, dict):
47
+ return None
48
+ identity = {
49
+ key: value[key]
50
+ for key in ("id", "type")
51
+ if isinstance(value.get(key), str) and value[key]
52
+ }
53
+ return identity or None
54
+
55
+ source = endpoint_identity(event.get("source"))
56
+ target = endpoint_identity(event.get("target"))
57
+ occurrence_entity_types = {
58
+ "agent_operation",
59
+ "agent_turn",
60
+ "command",
61
+ "context_compaction",
62
+ "conversation_item",
63
+ "observed_content",
64
+ "permission_request",
65
+ "subtask",
66
+ "terminal_operation",
67
+ "tool_call",
68
+ "tool_call_observation",
69
+ "tool_result",
70
+ }
71
+ endpoint_occurrence = any(
72
+ endpoint is not None and endpoint.get("type") in occurrence_entity_types
73
+ for endpoint in (source, target)
74
+ )
75
+
76
+ occurrence_keys = (
77
+ "tool_use_id",
78
+ "tool_call_id",
79
+ "call_id",
80
+ "provider_call_id",
81
+ "invocation_id",
82
+ "request_id",
83
+ "response_id",
84
+ "message_id",
85
+ "item_id",
86
+ "turn_id",
87
+ "step_index",
88
+ "stepIdx",
89
+ "antigravity_step_index",
90
+ "invocation_number",
91
+ "antigravity_invocation_number",
92
+ "initial_num_steps",
93
+ "antigravity_initial_num_steps",
94
+ "transcript_record_ordinal",
95
+ "transcript_tool_call_index",
96
+ )
97
+
98
+ occurrence: dict[str, Any] = {}
99
+ if not endpoint_occurrence:
100
+ for scope, value in (
101
+ ("event", event.get("attributes")),
102
+ (
103
+ "source",
104
+ (event.get("source") or {}).get("attributes")
105
+ if isinstance(event.get("source"), dict)
106
+ else None,
107
+ ),
108
+ (
109
+ "target",
110
+ (event.get("target") or {}).get("attributes")
111
+ if isinstance(event.get("target"), dict)
112
+ else None,
113
+ ),
114
+ ):
115
+ if not isinstance(value, dict):
116
+ continue
117
+ selected = {
118
+ key: value[key]
119
+ for key in occurrence_keys
120
+ if value.get(key) is not None
121
+ }
122
+ if selected:
123
+ occurrence[scope] = selected
124
+
125
+ if not endpoint_occurrence and not occurrence:
126
+ return None
127
+
128
+ stable = {
129
+ "event_type": event.get("event_type"),
130
+ "relation": event.get("relation"),
131
+ "source": source,
132
+ "target": target,
133
+ "occurrence": occurrence,
134
+ }
135
+ encoded = json.dumps(
136
+ stable,
137
+ ensure_ascii=False,
138
+ sort_keys=True,
139
+ separators=(",", ":"),
140
+ )
141
+ return "semantic:" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()
142
+
143
+
144
+ @dataclass
145
+ class GraphNode:
146
+ id: str
147
+ type: str
148
+ name: str | None = None
149
+ attributes: dict[str, Any] = field(default_factory=dict)
150
+ first_seen: str | None = None
151
+ last_seen: str | None = None
152
+ event_count: int = 0
153
+ evidence_event_count: int = 0
154
+ event_types: set[str] = field(default_factory=set)
155
+
156
+ def observe(
157
+ self,
158
+ entity: dict[str, Any],
159
+ event: dict[str, Any],
160
+ *,
161
+ logical: bool = True,
162
+ ) -> None:
163
+ incoming_name = entity.get("name")
164
+ self.name = self.name or incoming_name
165
+ # Strace sees a PID at spawn time, and the executable only at execve.
166
+ # Upgrade this PID-only display name when syscall evidence arrives.
167
+ if (
168
+ self.type == "process"
169
+ and isinstance(self.name, str) and self.name.isdecimal()
170
+ and isinstance(incoming_name, str) and incoming_name != self.name
171
+ and incoming_name.endswith(" · " + self.name)
172
+ ):
173
+ self.name = incoming_name
174
+ incoming = entity.get("attributes") or {}
175
+ if isinstance(incoming, dict):
176
+ for key, value in incoming.items():
177
+ # First non-null wins. A key written with None by an early event used
178
+ # to block the real value a later event carried, which silently froze
179
+ # agent identity at "unknown".
180
+ if value is None:
181
+ self.attributes.setdefault(key, None)
182
+ elif self.attributes.get(key) is None:
183
+ self.attributes[key] = value
184
+ # Event-level exit status belongs to the *exiting process*, never to
185
+ # the run-level session outcome and never to an unrelated target node.
186
+ if (
187
+ self.type == "process"
188
+ and event.get("event_type") == "process.exited"
189
+ and isinstance(event.get("source"), dict)
190
+ and event["source"].get("id") == self.id
191
+ ):
192
+ exit_fields = event.get("attributes")
193
+ if isinstance(exit_fields, dict):
194
+ code = exit_fields.get("exit_code")
195
+ if type(code) is int:
196
+ self.attributes["exit_code"] = code
197
+ self.attributes["return_code"] = code
198
+ signal = exit_fields.get("signal")
199
+ if isinstance(signal, str) and signal:
200
+ self.attributes["exit_signal"] = signal
201
+ if type(code) is int or (isinstance(signal, str) and signal):
202
+ self.attributes["exit_observed"] = True
203
+ when = event.get("timestamp")
204
+ if isinstance(when, str):
205
+ self.attributes["exit_observed_at"] = when
206
+ timestamp = event.get("timestamp")
207
+ if isinstance(timestamp, str):
208
+ self.first_seen = min(self.first_seen, timestamp) if self.first_seen else timestamp
209
+ self.last_seen = max(self.last_seen, timestamp) if self.last_seen else timestamp
210
+ self.evidence_event_count += 1
211
+ if logical:
212
+ self.event_count += 1
213
+ event_type = event.get("event_type")
214
+ if isinstance(event_type, str):
215
+ self.event_types.add(event_type)
216
+
217
+ def to_dict(self) -> dict[str, Any]:
218
+ payload = asdict(self)
219
+ payload["event_types"] = sorted(self.event_types)
220
+ return payload
221
+
222
+
223
+ @dataclass
224
+ class GraphEdge:
225
+ id: str
226
+ source: str
227
+ target: str
228
+ relation: str
229
+ count: int = 0
230
+ evidence_event_count: int = 0
231
+ first_seen: str | None = None
232
+ last_seen: str | None = None
233
+ first_sequence: int | None = None
234
+ last_sequence: int | None = None
235
+ event_ids: list[str] = field(default_factory=list)
236
+ event_types: set[str] = field(default_factory=set)
237
+ backends: set[str] = field(default_factory=set)
238
+ attributions: set[str] = field(default_factory=set)
239
+ causal_values: set[bool] = field(default_factory=set)
240
+ inferred_values: set[bool] = field(default_factory=set)
241
+ inference_methods: set[str] = field(default_factory=set)
242
+ # Observations that omit a flag are ignored by the Boolean sets above, so
243
+ # count them separately; evidence grading must not treat them as covered.
244
+ causal_unannotated_count: int = 0
245
+ attribution_unannotated_count: int = 0
246
+ identity_exact_values: set[bool] = field(default_factory=set)
247
+ identity_methods: set[str] = field(default_factory=set)
248
+ identity_hashes: set[str] = field(default_factory=set)
249
+ confidence_values: list[float] = field(default_factory=list)
250
+ confidence_semantics: set[str] = field(default_factory=set)
251
+ supporting_event_ids: set[str] = field(default_factory=set)
252
+ provider_lifecycle: set[ProviderLifecycleAnnotation] = field(default_factory=set)
253
+
254
+ def observe(
255
+ self,
256
+ event: dict[str, Any],
257
+ *,
258
+ retain_event_id: bool = True,
259
+ logical: bool = True,
260
+ ) -> None:
261
+ self.evidence_event_count += 1
262
+ if logical:
263
+ self.count += 1
264
+ timestamp = event.get("timestamp")
265
+ if isinstance(timestamp, str):
266
+ self.first_seen = min(self.first_seen, timestamp) if self.first_seen else timestamp
267
+ self.last_seen = max(self.last_seen, timestamp) if self.last_seen else timestamp
268
+ sequence = event.get("sequence")
269
+ if isinstance(sequence, int) and not isinstance(sequence, bool):
270
+ self.first_sequence = (
271
+ min(self.first_sequence, sequence) if self.first_sequence is not None else sequence
272
+ )
273
+ self.last_sequence = (
274
+ max(self.last_sequence, sequence) if self.last_sequence is not None else sequence
275
+ )
276
+ event_id = event.get("event_id")
277
+ if retain_event_id and isinstance(event_id, str):
278
+ self.event_ids.append(event_id)
279
+ event_type = event.get("event_type")
280
+ if isinstance(event_type, str):
281
+ self.event_types.add(event_type)
282
+ attributes = event.get("attributes") or {}
283
+ if not isinstance(attributes, dict) or not isinstance(attributes.get("causal"), bool):
284
+ self.causal_unannotated_count += 1
285
+ if not isinstance(attributes, dict) or not isinstance(attributes.get("attribution"), str):
286
+ self.attribution_unannotated_count += 1
287
+ if isinstance(attributes, dict):
288
+ backend = attributes.get("backend")
289
+ if isinstance(backend, str):
290
+ self.backends.add(backend)
291
+ attribution = attributes.get("attribution")
292
+ if isinstance(attribution, str):
293
+ self.attributions.add(attribution)
294
+ causal = attributes.get("causal")
295
+ if isinstance(causal, bool):
296
+ self.causal_values.add(causal)
297
+ inferred = attributes.get("inferred")
298
+ if isinstance(inferred, bool):
299
+ self.inferred_values.add(inferred)
300
+ method = attributes.get("inference_method")
301
+ if isinstance(method, str) and method:
302
+ self.inference_methods.add(method)
303
+ identity_exact = attributes.get("identity_exact")
304
+ if isinstance(identity_exact, bool):
305
+ self.identity_exact_values.add(identity_exact)
306
+ identity_method = attributes.get("identity_method")
307
+ if isinstance(identity_method, str) and identity_method:
308
+ self.identity_methods.add(identity_method)
309
+ identity_hash = attributes.get("shared_request_id_hash")
310
+ if isinstance(identity_hash, str) and identity_hash:
311
+ self.identity_hashes.add(identity_hash)
312
+ confidence = attributes.get("confidence")
313
+ if isinstance(confidence, (int, float)) and not isinstance(confidence, bool):
314
+ self.confidence_values.append(float(confidence))
315
+ semantics = attributes.get("confidence_semantics")
316
+ if isinstance(semantics, str) and semantics:
317
+ self.confidence_semantics.add(semantics)
318
+ supporting = attributes.get("supporting_event_ids")
319
+ if isinstance(supporting, list):
320
+ self.supporting_event_ids.update(
321
+ value for value in supporting if isinstance(value, str) and value
322
+ )
323
+ lifecycle = provider_lifecycle_annotation(event)
324
+ if lifecycle is not None:
325
+ self.provider_lifecycle.add(lifecycle)
326
+
327
+ def to_dict(self) -> dict[str, Any]:
328
+ if self.causal_values == {True}:
329
+ causal: bool | None = True
330
+ elif self.causal_values == {False}:
331
+ causal = False
332
+ else:
333
+ causal = None
334
+ if self.inferred_values == {True}:
335
+ inferred: bool | None = True
336
+ elif self.inferred_values == {False}:
337
+ inferred = False
338
+ else:
339
+ inferred = None
340
+ if self.identity_exact_values == {True}:
341
+ identity_exact: bool | None = True
342
+ elif self.identity_exact_values == {False}:
343
+ identity_exact = False
344
+ else:
345
+ identity_exact = None
346
+ payload: dict[str, Any] = {
347
+ "id": self.id,
348
+ "source": self.source,
349
+ "target": self.target,
350
+ "relation": self.relation,
351
+ "count": self.count,
352
+ "evidence_event_count": self.evidence_event_count,
353
+ "first_seen": self.first_seen,
354
+ "last_seen": self.last_seen,
355
+ "first_sequence": self.first_sequence,
356
+ "last_sequence": self.last_sequence,
357
+ "event_ids": self.event_ids,
358
+ "event_types": sorted(self.event_types),
359
+ "backends": sorted(self.backends),
360
+ "attributions": sorted(self.attributions),
361
+ "causal": causal,
362
+ "causal_unannotated_count": self.causal_unannotated_count,
363
+ "attribution_unannotated_count": self.attribution_unannotated_count,
364
+ "inferred": inferred,
365
+ "inference_methods": sorted(self.inference_methods),
366
+ "identity_exact": identity_exact,
367
+ "identity_methods": sorted(self.identity_methods),
368
+ "identity_hashes": sorted(self.identity_hashes),
369
+ "confidence_min": min(self.confidence_values) if self.confidence_values else None,
370
+ "confidence_max": max(self.confidence_values) if self.confidence_values else None,
371
+ "confidence_semantics": sorted(self.confidence_semantics),
372
+ "supporting_event_ids": sorted(self.supporting_event_ids),
373
+ }
374
+ if self.provider_lifecycle:
375
+ payload["provider_lifecycle"] = [
376
+ annotation.to_dict() for annotation in sorted(self.provider_lifecycle)
377
+ ]
378
+ return payload
379
+
380
+
381
+ @dataclass
382
+ class ExecutionGraph:
383
+ session_id: str
384
+ source_path: str
385
+ source_schema_versions: list[str]
386
+ event_count: int
387
+ nodes: list[GraphNode]
388
+ edges: list[GraphEdge]
389
+ fidelity: dict[str, Any] = field(default_factory=dict)
390
+ built_at: str = field(
391
+ default_factory=lambda: datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
392
+ )
393
+
394
+ evidence_counts: dict[str, int] = field(default_factory=dict)
395
+ session_outcome: dict[str, Any] = field(default_factory=dict)
396
+ runtime_environment: dict[str, Any] = field(default_factory=dict)
397
+ observation_assessment: dict[str, Any] = field(default_factory=dict)
398
+
399
+ def to_dict(self) -> dict[str, Any]:
400
+ return {
401
+ "graph_schema_version": GRAPH_SCHEMA_VERSION,
402
+ "session_id": self.session_id,
403
+ "source_path": self.source_path,
404
+ "source_schema_versions": self.source_schema_versions,
405
+ "event_count": self.event_count,
406
+ "node_count": len(self.nodes),
407
+ "edge_count": len(self.edges),
408
+ "built_at": self.built_at,
409
+ "fidelity": self.fidelity,
410
+ "evidence_counts": dict(self.evidence_counts),
411
+ "session_outcome": dict(self.session_outcome),
412
+ "runtime_environment": dict(self.runtime_environment),
413
+ "observation_assessment": dict(self.observation_assessment),
414
+ "nodes": [node.to_dict() for node in self.nodes],
415
+ "edges": [edge.to_dict() for edge in self.edges],
416
+ }
417
+
418
+
419
+ def _edge_id(source: str, relation: str, target: str) -> str:
420
+ return f"{source}--{relation}-->{target}"
421
+
422
+
423
+ class GraphAccumulator:
424
+ """Incrementally materialize graph state without retaining raw event objects.
425
+
426
+ This is intentionally a small, replaceable seam for live graph maintenance.
427
+ The canonical final graph builder still validates and materializes the complete
428
+ event stream independently. ``retain_event_ids=False`` is therefore suitable
429
+ for disposable live/browser state while preserving explicit inferred support
430
+ and exact-identity justification fields.
431
+ """
432
+
433
+ def __init__(
434
+ self,
435
+ *,
436
+ session_id: str,
437
+ source_path: str | Path,
438
+ retain_event_ids: bool = True,
439
+ ) -> None:
440
+ self.session_id = session_id
441
+ self.source_path = str(Path(source_path).expanduser().resolve())
442
+ self.retain_event_ids = retain_event_ids
443
+ self.source_schema_versions: set[str] = set()
444
+ self.event_count = 0
445
+ self.nodes: dict[str, GraphNode] = {}
446
+ self.edges: dict[tuple[str, str, str], GraphEdge] = {}
447
+ self._fidelity = FidelityAccumulator()
448
+ self._session_summary = SessionSummary()
449
+ self._seen_logical_events: set[str] = set()
450
+
451
+ @property
452
+ def node_count(self) -> int:
453
+ return len(self.nodes)
454
+
455
+ @property
456
+ def edge_count(self) -> int:
457
+ return len(self.edges)
458
+
459
+ def apply(self, event: dict[str, Any]) -> None:
460
+ if not isinstance(event, dict):
461
+ raise TypeError("event must be a dictionary")
462
+ event_session = event.get("session_id")
463
+ if isinstance(event_session, str) and event_session != self.session_id:
464
+ raise ValueError(
465
+ f"event session_id {event_session!r} does not match accumulator {self.session_id!r}"
466
+ )
467
+
468
+ schema_version = event.get("schema_version")
469
+ if isinstance(schema_version, str) and schema_version:
470
+ self.source_schema_versions.add(schema_version)
471
+ self.event_count += 1
472
+ self._fidelity.observe(event)
473
+ self._session_summary.observe(event)
474
+ logical_key = logical_event_key(event)
475
+ logical = logical_key not in self._seen_logical_events
476
+ if logical_key is not None:
477
+ self._seen_logical_events.add(logical_key)
478
+
479
+ source = event.get("source")
480
+ target = event.get("target")
481
+ for entity in (source, target):
482
+ if not isinstance(entity, dict):
483
+ continue
484
+ entity_id = entity.get("id")
485
+ entity_type = entity.get("type")
486
+ if not isinstance(entity_id, str) or not isinstance(entity_type, str):
487
+ continue
488
+ node = self.nodes.get(entity_id)
489
+ if node is None:
490
+ node = GraphNode(
491
+ id=entity_id,
492
+ type=entity_type,
493
+ name=entity.get("name") if isinstance(entity.get("name"), str) else None,
494
+ )
495
+ self.nodes[entity_id] = node
496
+ node.observe(entity, event, logical=logical)
497
+
498
+ if not isinstance(source, dict) or not isinstance(target, dict):
499
+ return
500
+ source_id = source.get("id")
501
+ target_id = target.get("id")
502
+ relation = event.get("relation")
503
+ if not all(isinstance(value, str) and value for value in (source_id, target_id, relation)):
504
+ return
505
+ key = (source_id, relation, target_id)
506
+ edge = self.edges.get(key)
507
+ if edge is None:
508
+ edge = GraphEdge(
509
+ id=_edge_id(source_id, relation, target_id),
510
+ source=source_id,
511
+ target=target_id,
512
+ relation=relation,
513
+ )
514
+ self.edges[key] = edge
515
+ edge.observe(
516
+ event,
517
+ retain_event_id=self.retain_event_ids,
518
+ logical=logical,
519
+ )
520
+
521
+ def to_execution_graph(self) -> ExecutionGraph:
522
+ return ExecutionGraph(
523
+ session_id=self.session_id,
524
+ source_path=self.source_path,
525
+ source_schema_versions=sorted(self.source_schema_versions),
526
+ event_count=self.event_count,
527
+ nodes=sorted(self.nodes.values(), key=lambda node: (node.type, node.id)),
528
+ edges=sorted(
529
+ self.edges.values(), key=lambda edge: (edge.source, edge.relation, edge.target)
530
+ ),
531
+ fidelity=self._fidelity.to_dict(),
532
+ evidence_counts=dict(self._session_summary.counts),
533
+ session_outcome=assessed_session_outcome(
534
+ self._session_summary.outcome, self._session_summary.observation
535
+ ),
536
+ observation_assessment=self._session_summary.observation,
537
+ runtime_environment=dict(self._session_summary.environment),
538
+ )
539
+
540
+ def to_dict(self) -> dict[str, Any]:
541
+ return self.to_execution_graph().to_dict()
542
+
543
+
544
+ def _load_events(path: Path) -> list[dict[str, Any]]:
545
+ return [
546
+ json.loads(line)
547
+ for line in path.read_text(encoding="utf-8").splitlines()
548
+ if line.strip()
549
+ ]
550
+
551
+
552
+ def build_execution_graph(
553
+ path: str | Path,
554
+ *,
555
+ allow_incomplete: bool = False,
556
+ ) -> ExecutionGraph:
557
+ source_path = Path(path).expanduser().resolve()
558
+ validation = validate_event_stream(
559
+ source_path,
560
+ require_complete_session=not allow_incomplete,
561
+ )
562
+ if not validation.valid:
563
+ details = "; ".join(validation.errors)
564
+ raise ValueError(f"invalid ExecWeave event stream: {details}")
565
+
566
+ events = _load_events(source_path)
567
+ session_id = validation.session_ids[0] if validation.session_ids else "unknown"
568
+ accumulator = GraphAccumulator(session_id=session_id, source_path=source_path)
569
+ for event in events:
570
+ accumulator.apply(event)
571
+ graph = accumulator.to_execution_graph()
572
+ graph.source_schema_versions = validation.schema_versions
573
+ return graph
574
+
575
+
576
+ def write_execution_graph(
577
+ graph: ExecutionGraph,
578
+ path: str | Path,
579
+ *,
580
+ metadata: dict[str, Any] | None = None,
581
+ ) -> Path:
582
+ output = private_artifact_path(path)
583
+ output.parent.mkdir(parents=True, exist_ok=True)
584
+ if output.exists() and output.stat().st_size > 0:
585
+ raise FileExistsError(f"ExecWeave graph output already exists: {output}")
586
+ payload = graph.to_dict()
587
+ if metadata is not None:
588
+ payload["metadata"] = metadata
589
+ write_private_json(output, payload)
590
+ return output