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/semantic.py ADDED
@@ -0,0 +1,453 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from copy import deepcopy
5
+ from dataclasses import asdict, dataclass
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any
9
+ from uuid import uuid4
10
+
11
+ from .private_io import write_private_text
12
+
13
+ from .schema import SCHEMA_VERSION
14
+ from .validate import validate_event_stream
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SemanticMergeResult:
19
+ runtime_event_count: int
20
+ semantic_event_count: int
21
+ merged_event_count: int
22
+ resolved_process_references: int
23
+ unresolved_process_references: int
24
+ session_id: str
25
+ output: str
26
+
27
+ def to_dict(self) -> dict[str, object]:
28
+ return asdict(self)
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class _ProcessCandidate:
33
+ pid: int
34
+ entity: dict[str, Any]
35
+ create_time: float | None
36
+
37
+
38
+ # Semantic sidecars are writable by the observed process in ordinary same-UID runs.
39
+ # Metadata supplied by a sidecar is a claim, never native sensor authority.
40
+ _NATIVE_ATTRIBUTIONS = {"syscall", "polling", "process_polling", "session_observation"}
41
+ _NATIVE_EFFECT_RELATIONS = {
42
+ "OPENED_READ", "OPENED_READ_WRITE", "OPENED_WRITE", "WROTE",
43
+ "CONNECTED_TO", "CONNECT_ATTEMPTED", "SPAWNED", "LAUNCHED",
44
+ }
45
+
46
+
47
+ def _parse_timestamp(value: object, *, context: str) -> datetime:
48
+ if not isinstance(value, str) or not value:
49
+ raise ValueError(f"{context}: timestamp must be a non-empty ISO-8601 string")
50
+ try:
51
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
52
+ except ValueError as exc:
53
+ raise ValueError(f"{context}: timestamp must be ISO-8601") from exc
54
+ if parsed.tzinfo is None:
55
+ parsed = parsed.replace(tzinfo=timezone.utc)
56
+ return parsed.astimezone(timezone.utc)
57
+
58
+
59
+ def _load_jsonl(path: Path, *, label: str) -> list[dict[str, Any]]:
60
+ if not path.exists():
61
+ raise ValueError(f"{label} does not exist: {path}")
62
+ records: list[dict[str, Any]] = []
63
+ for line_number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
64
+ if not raw.strip():
65
+ continue
66
+ try:
67
+ payload = json.loads(raw)
68
+ except json.JSONDecodeError as exc:
69
+ raise ValueError(f"{label} line {line_number}: invalid JSON: {exc.msg}") from exc
70
+ if not isinstance(payload, dict):
71
+ raise ValueError(f"{label} line {line_number}: record must be a JSON object")
72
+ records.append(payload)
73
+ return records
74
+
75
+
76
+ def _validate_entity(entity: object, *, context: str) -> None:
77
+ if entity is None:
78
+ return
79
+ if not isinstance(entity, dict):
80
+ raise ValueError(f"{context} must be an object or null")
81
+ for key in ("type", "id"):
82
+ value = entity.get(key)
83
+ if not isinstance(value, str) or not value:
84
+ raise ValueError(f"{context}.{key} must be a non-empty string")
85
+ attributes = entity.get("attributes", {})
86
+ if not isinstance(attributes, dict):
87
+ raise ValueError(f"{context}.attributes must be an object")
88
+
89
+
90
+ def _process_candidates(runtime_events: list[dict[str, Any]]) -> dict[int, list[_ProcessCandidate]]:
91
+ by_pid: dict[int, dict[str, _ProcessCandidate]] = {}
92
+ for event in runtime_events:
93
+ for entity in (event.get("source"), event.get("target")):
94
+ if not isinstance(entity, dict) or entity.get("type") != "process":
95
+ continue
96
+ entity_id = entity.get("id")
97
+ attributes = entity.get("attributes") or {}
98
+ if not isinstance(entity_id, str) or not isinstance(attributes, dict):
99
+ continue
100
+ pid = attributes.get("pid")
101
+ if not isinstance(pid, int) or isinstance(pid, bool):
102
+ continue
103
+ create_time_raw = attributes.get("create_time")
104
+ create_time = (
105
+ float(create_time_raw)
106
+ if isinstance(create_time_raw, (int, float)) and not isinstance(create_time_raw, bool)
107
+ else None
108
+ )
109
+ by_pid.setdefault(pid, {})[entity_id] = _ProcessCandidate(
110
+ pid=pid,
111
+ entity=deepcopy(entity),
112
+ create_time=create_time,
113
+ )
114
+ return {pid: list(candidates.values()) for pid, candidates in by_pid.items()}
115
+
116
+
117
+ def _resolve_process_reference(
118
+ entity: dict[str, Any],
119
+ *,
120
+ timestamp: datetime,
121
+ candidates: dict[int, list[_ProcessCandidate]],
122
+ ) -> tuple[dict[str, Any], bool]:
123
+ if entity.get("type") != "process_reference":
124
+ return deepcopy(entity), False
125
+ attributes = entity.get("attributes") or {}
126
+ pid = attributes.get("pid") if isinstance(attributes, dict) else None
127
+ if not isinstance(pid, int) or isinstance(pid, bool):
128
+ unresolved = deepcopy(entity)
129
+ unresolved.setdefault("attributes", {})["unresolved"] = True
130
+ return unresolved, False
131
+
132
+ options = candidates.get(pid, [])
133
+ if not options:
134
+ unresolved = deepcopy(entity)
135
+ unresolved.setdefault("attributes", {})["unresolved"] = True
136
+ return unresolved, False
137
+
138
+ unresolved = deepcopy(entity)
139
+ unresolved.setdefault("attributes", {})["unresolved"] = True
140
+ unresolved["attributes"]["candidate_process_ids"] = sorted(
141
+ candidate.entity["id"] for candidate in options if isinstance(candidate.entity.get("id"), str)
142
+ )
143
+ event_epoch = timestamp.timestamp()
144
+ explicit_create_time = attributes.get("create_time") if isinstance(attributes, dict) else None
145
+ if isinstance(explicit_create_time, (int, float)) and not isinstance(explicit_create_time, bool):
146
+ exact = [
147
+ candidate
148
+ for candidate in options
149
+ if candidate.create_time is not None
150
+ and abs(candidate.create_time - float(explicit_create_time)) < 0.001
151
+ ]
152
+ if len(exact) == 1 and exact[0].create_time <= event_epoch:
153
+ return deepcopy(exact[0].entity), True
154
+ # An explicit identity is evidence, not a hint that can be discarded in
155
+ # favour of a different process which happens to reuse the same PID.
156
+ return unresolved, False
157
+
158
+ if len(options) == 1:
159
+ if options[0].create_time is not None and options[0].create_time > event_epoch:
160
+ return unresolved, False
161
+ return deepcopy(options[0].entity), True
162
+
163
+ started = [
164
+ candidate
165
+ for candidate in options
166
+ if candidate.create_time is not None and candidate.create_time <= event_epoch
167
+ ]
168
+ if started:
169
+ latest = max(candidate.create_time or 0.0 for candidate in started)
170
+ nearest = [
171
+ candidate
172
+ for candidate in started
173
+ if candidate.create_time is not None and abs(candidate.create_time - latest) < 0.001
174
+ ]
175
+ if len(nearest) == 1:
176
+ return deepcopy(nearest[0].entity), True
177
+
178
+ return unresolved, False
179
+
180
+
181
+ def _normalize_semantic_record(
182
+ record: dict[str, Any],
183
+ *,
184
+ line_number: int,
185
+ session_id: str,
186
+ started_at: datetime,
187
+ finished_at: datetime | None,
188
+ candidates: dict[int, list[_ProcessCandidate]],
189
+ ) -> tuple[dict[str, Any], int, int]:
190
+ context = f"semantic sidecar line {line_number}"
191
+ timestamp = _parse_timestamp(record.get("timestamp"), context=context)
192
+ if timestamp < started_at:
193
+ raise ValueError(f"{context}: timestamp precedes the runtime session start")
194
+ if finished_at is not None and timestamp > finished_at:
195
+ raise ValueError(f"{context}: timestamp is outside the runtime session interval")
196
+
197
+ event_type = record.get("event_type")
198
+ relation = record.get("relation")
199
+ if not isinstance(event_type, str) or not event_type:
200
+ raise ValueError(f"{context}: event_type must be a non-empty string")
201
+ if not isinstance(relation, str) or not relation:
202
+ raise ValueError(f"{context}: relation must be a non-empty string")
203
+
204
+ source = record.get("source")
205
+ target = record.get("target")
206
+ _validate_entity(source, context=f"{context}.source")
207
+ _validate_entity(target, context=f"{context}.target")
208
+ attributes = record.get("attributes", {})
209
+ if not isinstance(attributes, dict):
210
+ raise ValueError(f"{context}: attributes must be an object")
211
+
212
+ resolved = 0
213
+ unresolved = 0
214
+ resolution_map: dict[str, str] = {}
215
+ normalized_entities: list[dict[str, Any] | None] = []
216
+ for entity in (source, target):
217
+ if entity is None:
218
+ normalized_entities.append(None)
219
+ continue
220
+ original_id = entity.get("id") if isinstance(entity, dict) else None
221
+ normalized, did_resolve = _resolve_process_reference(
222
+ entity,
223
+ timestamp=timestamp,
224
+ candidates=candidates,
225
+ )
226
+ if entity.get("type") == "process_reference":
227
+ if did_resolve:
228
+ resolved += 1
229
+ if isinstance(original_id, str) and isinstance(normalized.get("id"), str):
230
+ resolution_map[original_id] = normalized["id"]
231
+ else:
232
+ unresolved += 1
233
+ normalized_entities.append(normalized)
234
+
235
+ normalized_attributes = deepcopy(attributes)
236
+ # Sidecar-authored labels cannot impersonate the native OS collector.
237
+ # Preserve the declarations for audit, separately from authoritative fields.
238
+ claimed_backend = normalized_attributes.get("backend")
239
+ if isinstance(claimed_backend, str) and claimed_backend and claimed_backend != "semantic":
240
+ normalized_attributes["sidecar_claimed_backend"] = claimed_backend
241
+ normalized_attributes["backend"] = "semantic"
242
+ claimed_attribution = normalized_attributes.get("attribution")
243
+ if isinstance(claimed_attribution, str) and claimed_attribution in _NATIVE_ATTRIBUTIONS:
244
+ normalized_attributes["sidecar_claimed_attribution"] = claimed_attribution
245
+ normalized_attributes["attribution"] = "semantic_sidecar"
246
+ else:
247
+ normalized_attributes.setdefault("attribution", "semantic_sidecar")
248
+ # Preserve real semantic tool-call causality, but do not infer native OS
249
+ # file, network or process effects from an agent-writable sidecar claim.
250
+ if relation in _NATIVE_EFFECT_RELATIONS and normalized_attributes.get("causal") is True:
251
+ normalized_attributes["sidecar_claimed_causal"] = True
252
+ normalized_attributes["causal"] = False
253
+ if resolution_map:
254
+ normalized_attributes["resolved_process_references"] = resolution_map
255
+
256
+ event_id = record.get("event_id")
257
+ if not isinstance(event_id, str) or not event_id:
258
+ event_id = f"semantic:{uuid4()}"
259
+
260
+ return (
261
+ {
262
+ "schema_version": SCHEMA_VERSION,
263
+ "event_id": event_id,
264
+ "session_id": session_id,
265
+ "timestamp": record["timestamp"],
266
+ "event_type": event_type,
267
+ "relation": relation,
268
+ "source": normalized_entities[0],
269
+ "target": normalized_entities[1],
270
+ "sequence": None,
271
+ "attributes": normalized_attributes,
272
+ },
273
+ resolved,
274
+ unresolved,
275
+ )
276
+
277
+
278
+ class LiveSemanticNormalizer:
279
+ """Normalize append-only specialized records for disposable live graph state.
280
+
281
+ Live normalization is provisional: it resolves process references only against
282
+ process identities observed so far. The final artifact is rebuilt through
283
+ ``merge_semantic_sidecar`` after the runtime session closes.
284
+ """
285
+
286
+ def __init__(self, session_id: str) -> None:
287
+ self.session_id = session_id
288
+ self._started_at: datetime | None = None
289
+ self._candidates: dict[int, dict[str, _ProcessCandidate]] = {}
290
+
291
+ @property
292
+ def ready(self) -> bool:
293
+ return self._started_at is not None
294
+
295
+ def reset(self) -> None:
296
+ self._started_at = None
297
+ self._candidates.clear()
298
+
299
+ def observe_runtime_event(self, event: dict[str, Any]) -> None:
300
+ if event.get("event_type") == "session.started":
301
+ self._started_at = _parse_timestamp(
302
+ event.get("timestamp"),
303
+ context="live session.started",
304
+ )
305
+
306
+ for entity in (event.get("source"), event.get("target")):
307
+ if not isinstance(entity, dict) or entity.get("type") != "process":
308
+ continue
309
+ entity_id = entity.get("id")
310
+ attributes = entity.get("attributes") or {}
311
+ if not isinstance(entity_id, str) or not isinstance(attributes, dict):
312
+ continue
313
+ pid = attributes.get("pid")
314
+ if not isinstance(pid, int) or isinstance(pid, bool):
315
+ continue
316
+ create_time_raw = attributes.get("create_time")
317
+ create_time = (
318
+ float(create_time_raw)
319
+ if isinstance(create_time_raw, (int, float))
320
+ and not isinstance(create_time_raw, bool)
321
+ else None
322
+ )
323
+ self._candidates.setdefault(pid, {})[entity_id] = _ProcessCandidate(
324
+ pid=pid,
325
+ entity=deepcopy(entity),
326
+ create_time=create_time,
327
+ )
328
+
329
+ def normalize(
330
+ self,
331
+ record: dict[str, Any],
332
+ *,
333
+ line_number: int,
334
+ ) -> dict[str, Any] | None:
335
+ if self._started_at is None:
336
+ return None
337
+ candidates = {
338
+ pid: list(by_id.values()) for pid, by_id in self._candidates.items()
339
+ }
340
+ normalized, _, _ = _normalize_semantic_record(
341
+ record,
342
+ line_number=line_number,
343
+ session_id=self.session_id,
344
+ started_at=self._started_at,
345
+ finished_at=None,
346
+ candidates=candidates,
347
+ )
348
+ attributes = normalized.get("attributes")
349
+ if isinstance(attributes, dict):
350
+ attributes["live_normalization_provisional"] = True
351
+ return normalized
352
+
353
+
354
+ def merge_semantic_sidecar(
355
+ runtime_path: str | Path,
356
+ semantic_path: str | Path,
357
+ output_path: str | Path,
358
+ ) -> SemanticMergeResult:
359
+ runtime = Path(runtime_path).expanduser().resolve()
360
+ semantic = Path(semantic_path).expanduser().resolve()
361
+ raw_output = Path(output_path).expanduser()
362
+ raw_output.parent.mkdir(parents=True, exist_ok=True)
363
+ output = raw_output.parent.resolve() / raw_output.name
364
+ if output.exists() and output.stat().st_size > 0:
365
+ raise FileExistsError(f"ExecWeave merged event stream already exists: {output}")
366
+
367
+ validation = validate_event_stream(runtime, require_complete_session=True)
368
+ if not validation.valid:
369
+ raise ValueError("invalid runtime event stream: " + "; ".join(validation.errors))
370
+ runtime_events = _load_jsonl(runtime, label="runtime event stream")
371
+ sidecar_records = _load_jsonl(semantic, label="semantic sidecar")
372
+ if not sidecar_records:
373
+ raise ValueError("semantic sidecar contains no events")
374
+
375
+ starts = [event for event in runtime_events if event.get("event_type") == "session.started"]
376
+ finishes = [event for event in runtime_events if event.get("event_type") == "session.finished"]
377
+ if len(starts) != 1 or len(finishes) != 1:
378
+ raise ValueError("runtime event stream must contain exactly one session start and finish")
379
+ session_id = validation.session_ids[0]
380
+ started_at = _parse_timestamp(starts[0].get("timestamp"), context="session.started")
381
+ finished_at = _parse_timestamp(finishes[0].get("timestamp"), context="session.finished")
382
+ candidates = _process_candidates(runtime_events)
383
+
384
+ semantic_events: list[dict[str, Any]] = []
385
+ resolved_total = 0
386
+ unresolved_total = 0
387
+ for line_number, record in enumerate(sidecar_records, start=1):
388
+ normalized, resolved, unresolved = _normalize_semantic_record(
389
+ record,
390
+ line_number=line_number,
391
+ session_id=session_id,
392
+ started_at=started_at,
393
+ finished_at=finished_at,
394
+ candidates=candidates,
395
+ )
396
+ semantic_events.append(normalized)
397
+ resolved_total += resolved
398
+ unresolved_total += unresolved
399
+
400
+ runtime_body = [
401
+ deepcopy(event)
402
+ for event in runtime_events
403
+ if event.get("event_type") not in {"session.started", "session.finished"}
404
+ ]
405
+ decorated: list[tuple[datetime, int, int, dict[str, Any]]] = []
406
+ for index, event in enumerate(runtime_body):
407
+ decorated.append(
408
+ (
409
+ _parse_timestamp(event.get("timestamp"), context=f"runtime event {index + 1}"),
410
+ 0,
411
+ index,
412
+ event,
413
+ )
414
+ )
415
+ for index, event in enumerate(semantic_events):
416
+ decorated.append(
417
+ (
418
+ _parse_timestamp(event.get("timestamp"), context=f"semantic event {index + 1}"),
419
+ 1,
420
+ index,
421
+ event,
422
+ )
423
+ )
424
+ decorated.sort(key=lambda item: (item[0], item[1], item[2]))
425
+
426
+ merged = [deepcopy(starts[0]), *[item[3] for item in decorated], deepcopy(finishes[0])]
427
+ for sequence, event in enumerate(merged, start=1):
428
+ event["sequence"] = sequence
429
+
430
+ blob = "".join(
431
+ json.dumps(event, ensure_ascii=False, sort_keys=True) + "\n" for event in merged
432
+ )
433
+ validation_path = output.parent / f".{output.name}.validate-{uuid4().hex}.jsonl"
434
+ try:
435
+ write_private_text(validation_path, blob)
436
+ merged_validation = validate_event_stream(validation_path, require_complete_session=True)
437
+ if not merged_validation.valid:
438
+ raise ValueError(
439
+ "merged semantic event stream is invalid: " + "; ".join(merged_validation.errors)
440
+ )
441
+ write_private_text(output, blob)
442
+ finally:
443
+ validation_path.unlink(missing_ok=True)
444
+
445
+ return SemanticMergeResult(
446
+ runtime_event_count=len(runtime_events),
447
+ semantic_event_count=len(semantic_events),
448
+ merged_event_count=len(merged),
449
+ resolved_process_references=resolved_total,
450
+ unresolved_process_references=unresolved_total,
451
+ session_id=session_id,
452
+ output=str(output),
453
+ )
@@ -0,0 +1,159 @@
1
+ """Portable evidence counts and workload outcome derived from observed events.
2
+
3
+ Recorder completion is deliberately separate from workload success. Missing
4
+ terminal evidence is unknown, never a synthesized successful exit.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ from .observation import assess_observation
11
+
12
+
13
+ class SessionSummary:
14
+ def __init__(self) -> None:
15
+ self.counts = {"os_runtime": 0, "specialized": 0}
16
+ self.outcome: dict[str, Any] = {"state": "unknown", "return_code": None}
17
+ self.environment: dict[str, Any] = {}
18
+ self._unknown_files: set[str] = set()
19
+ self._missing_snapshots: set[str] = set()
20
+ self._warning_codes: set[str] = set()
21
+ self._short_lived_loss_possible: bool | None = None
22
+ self._filesystem_enabled: bool | None = None
23
+ # Bounded occurrence-level delivery telemetry; absence of a receive event
24
+ # is not proof that the recipient did not actually receive the message.
25
+ self._message_phases: dict[tuple[str, str, str], set[str]] = {}
26
+ self._message_overflow = False
27
+
28
+ @property
29
+ def observation(self) -> dict[str, Any]:
30
+ finished = self.outcome.get("recorder_finished") is True
31
+ unconfirmed = sorted(
32
+ (message_id, sender, recipient)
33
+ for (message_id, sender, recipient), phases in self._message_phases.items()
34
+ if "sent" in phases and "received" not in phases
35
+ )
36
+ warnings = set(self._warning_codes)
37
+ if finished and unconfirmed:
38
+ warnings.add("message_receive_not_observed")
39
+ if self._message_overflow:
40
+ warnings.add("message_delivery_inventory_truncated")
41
+ assessment = assess_observation(
42
+ specialized=self.counts["specialized"],
43
+ finished=finished,
44
+ unknown_files=len(self._unknown_files),
45
+ missing_snapshots=len(self._missing_snapshots),
46
+ short_lived_loss_possible=self._short_lived_loss_possible,
47
+ filesystem_enabled=self._filesystem_enabled,
48
+ warning_codes=warnings,
49
+ )
50
+ if self._message_phases or self._message_overflow:
51
+ assessment["message_delivery"] = {
52
+ "basis": "explicit_message_sent_and_received_events",
53
+ "unconfirmed_count": None if self._message_overflow else len(unconfirmed),
54
+ "unconfirmed_count_lower_bound": len(unconfirmed),
55
+ "inventory_truncated": self._message_overflow,
56
+ "unconfirmed": [
57
+ {"message_id": mid, "sender_id": sender,
58
+ "recipient_id": recipient, "state": "receive_not_observed"}
59
+ for mid, sender, recipient in unconfirmed[:20]
60
+ ],
61
+ "truncated": self._message_overflow or len(unconfirmed) > 20,
62
+ "diagnostics": [
63
+ {"kind": "message_receive_not_observed", "message_id": mid,
64
+ "sender_id": sender, "recipient_id": recipient,
65
+ "delivery_status": "receive_not_observed",
66
+ "delivery_failure_proven": False}
67
+ for mid, sender, recipient in unconfirmed[:20]
68
+ ] if finished else [],
69
+ "delivery_failure_proven": False,
70
+ }
71
+ return assessment
72
+
73
+ def observe(self, event: dict[str, Any]) -> None:
74
+ attributes = event.get("attributes")
75
+ attributes = attributes if isinstance(attributes, dict) else {}
76
+ kind = str(event.get("event_type") or "")
77
+ backend = attributes.get("backend")
78
+ semantic = (kind.startswith("semantic.")
79
+ or (isinstance(backend, str) and backend in {"semantic", "model_runtime"})
80
+ or attributes.get("attribution") == "semantic_sidecar")
81
+ self.counts["specialized" if semantic else "os_runtime"] += 1
82
+ if kind in {"MESSAGE_SENT", "MESSAGE_RECEIVED"}:
83
+ source, target = event.get("source"), event.get("target")
84
+ message_id = attributes.get("message_id")
85
+ # Inferred/viewer-only routing cannot establish a native send or
86
+ # receipt, even when it happens to carry an occurrence-like ID.
87
+ scopes = (event, attributes, source, target)
88
+ native = all(
89
+ scope.get(flag) is None or scope.get(flag) is False
90
+ for scope in scopes if isinstance(scope, dict)
91
+ for flag in ("inferred", "viewer_only")
92
+ )
93
+ for entity in (source, target):
94
+ entity_attributes = entity.get("attributes") if isinstance(entity, dict) else None
95
+ if isinstance(entity_attributes, dict):
96
+ native = native and all(
97
+ entity_attributes.get(flag) is None or entity_attributes.get(flag) is False
98
+ for flag in ("inferred", "viewer_only")
99
+ )
100
+ if (native and isinstance(message_id, str) and 0 < len(message_id) <= 2048
101
+ and isinstance(source, dict) and source.get("type") == "agent"
102
+ and isinstance(target, dict) and target.get("type") == "agent"):
103
+ sender, recipient = source.get("id"), target.get("id")
104
+ if (isinstance(sender, str) and 0 < len(sender) <= 2048
105
+ and isinstance(recipient, str) and 0 < len(recipient) <= 2048
106
+ and sender != recipient
107
+ and attributes.get("sender_agent_id", sender) == sender
108
+ and attributes.get("recipient_agent_id", recipient) == recipient
109
+ and attributes.get("session_id", event.get("session_id")) == event.get("session_id")
110
+ and not attributes.get("inferred") and not attributes.get("viewer_only")):
111
+ key = (message_id, sender, recipient)
112
+ if key in self._message_phases:
113
+ self._message_phases[key].add("sent" if kind == "MESSAGE_SENT" else "received")
114
+ elif len(self._message_phases) < 10_000:
115
+ self._message_phases[key] = {"sent" if kind == "MESSAGE_SENT" else "received"}
116
+ else:
117
+ self._message_overflow = True
118
+ if kind == "observation.warning":
119
+ reason = attributes.get("reason")
120
+ if isinstance(reason, str) and reason:
121
+ self._warning_codes.add(reason)
122
+ if kind in {"filesystem.created", "filesystem.modified", "filesystem.moved", "filesystem.deleted"} and attributes.get("is_directory") is not True:
123
+ target = event.get("target")
124
+ if isinstance(target, dict) and isinstance(target.get("id"), str):
125
+ if attributes.get("causal") is not True:
126
+ self._unknown_files.add(target["id"])
127
+ snapshot = attributes.get("snapshot_state")
128
+ if isinstance(snapshot, str) and snapshot in {"not_captured", "missing"}:
129
+ self._missing_snapshots.add(target["id"])
130
+ if kind in {"session.started", "session.finished"}:
131
+ value = attributes.get("short_lived_process_loss_possible")
132
+ if type(value) is bool:
133
+ self._short_lived_loss_possible = value
134
+ value = attributes.get("filesystem_collection_enabled")
135
+ if type(value) is bool:
136
+ self._filesystem_enabled = value
137
+ if kind == "session.started":
138
+ for key in ("execweave_version", "python_executable", "python_version", "package_path", "backend"):
139
+ value = attributes.get(key)
140
+ if isinstance(value, str):
141
+ self.environment[key] = value
142
+ if kind != "session.finished":
143
+ return
144
+ code = attributes.get("return_code")
145
+ if not isinstance(code, int) or isinstance(code, bool):
146
+ code = None
147
+ interrupted = attributes.get("interrupted") is True
148
+ collector_failed = attributes.get("collector_failed") is True
149
+ state = (
150
+ "collector_failed" if collector_failed else
151
+ "interrupted" if interrupted else
152
+ "succeeded" if code == 0 else
153
+ "failed" if code is not None else "unknown"
154
+ )
155
+ self.outcome = {
156
+ "state": state, "return_code": code, "interrupted": interrupted,
157
+ "collector_failed": collector_failed, "event_id": event.get("event_id"),
158
+ "timestamp": event.get("timestamp"), "recorder_finished": True,
159
+ }
execweave/sink.py ADDED
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import stat
6
+ import threading
7
+ from pathlib import Path
8
+
9
+ from .private_io import harden_private_file, private_file_security_state, write_private_text
10
+ from .schema import RuntimeEvent
11
+
12
+
13
+ def _protect_git_run_directory(path: Path) -> None:
14
+ """Keep default .execweave evidence out of accidental git add -A.
15
+
16
+ Never alter an existing ignore file. Git still tracks any already-tracked
17
+ evidence; users must untrack such files themselves.
18
+ """
19
+ for directory in path.parents:
20
+ if directory.name != ".execweave":
21
+ continue
22
+ ignore = directory / ".gitignore"
23
+ try:
24
+ write_private_text(ignore, "*\n")
25
+ except FileExistsError:
26
+ pass
27
+ return
28
+
29
+
30
+ class JsonlSink:
31
+ """Thread-safe local JSONL sink used by Phase 1 collectors.
32
+
33
+ One event file represents one ExecWeave session. Reusing a non-empty path is
34
+ rejected by default so event sequences and session identities cannot be
35
+ silently mixed by an accidental second run.
36
+ """
37
+
38
+ def __init__(self, path: str | Path) -> None:
39
+ original = Path(path).expanduser().absolute()
40
+ if original.is_symlink():
41
+ raise ValueError("event stream must not be a symlink")
42
+ self.path = original
43
+ self.path.parent.mkdir(parents=True, exist_ok=True)
44
+ _protect_git_run_directory(self.path)
45
+ if self.path.exists() and self.path.stat().st_size > 0:
46
+ raise FileExistsError(f"ExecWeave event stream already exists: {self.path}")
47
+ self._lock = threading.Lock()
48
+ self._sequence = 0
49
+
50
+ def emit(self, event: RuntimeEvent) -> None:
51
+ payload = event.to_dict()
52
+ with self._lock:
53
+ self._sequence += 1
54
+ payload["sequence"] = self._sequence
55
+ line = json.dumps(payload, ensure_ascii=False, sort_keys=True)
56
+ flags = (os.O_WRONLY | os.O_APPEND | os.O_CREAT
57
+ | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
58
+ fd = os.open(self.path, flags, 0o600)
59
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
60
+ info = os.fstat(handle.fileno())
61
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
62
+ raise ValueError("event stream must be a private regular file")
63
+ if os.name != "nt" and stat.S_IMODE(info.st_mode) != 0o600:
64
+ os.fchmod(handle.fileno(), 0o600)
65
+ if not harden_private_file(self.path):
66
+ raise OSError("unable to establish private event-stream permissions")
67
+ handle.write(line + "\n")
68
+ handle.flush()
69
+ os.fsync(handle.fileno())
70
+ if private_file_security_state(self.path) != "owner_only":
71
+ raise OSError("private event-stream permission verification failed")