execweave 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. execweave/__init__.py +3 -0
  2. execweave/__main__.py +5 -0
  3. execweave/_conversation_records_core.py +902 -0
  4. execweave/_dashboard_shell_base.py +148 -0
  5. execweave/_http_proxy_base.py +565 -0
  6. execweave/_http_proxy_bounded.py +560 -0
  7. execweave/_http_proxy_stage.py +509 -0
  8. execweave/acceptance_output.py +19 -0
  9. execweave/agent_bootstrap.py +395 -0
  10. execweave/agent_topology.py +313 -0
  11. execweave/agent_trace.py +1162 -0
  12. execweave/agy_preview_sanitize.py +102 -0
  13. execweave/analysis.py +427 -0
  14. execweave/anthropic.py +228 -0
  15. execweave/anthropic_cli.py +171 -0
  16. execweave/anthropic_full_fidelity.py +385 -0
  17. execweave/antigravity_adapter.py +112 -0
  18. execweave/antigravity_adapter_base.py +479 -0
  19. execweave/antigravity_full_fidelity.py +656 -0
  20. execweave/antigravity_full_fidelity_base.py +172 -0
  21. execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
  22. execweave/antigravity_hook_cli.py +209 -0
  23. execweave/antigravity_record.py +96 -0
  24. execweave/antigravity_subagent_linkage.py +449 -0
  25. execweave/antigravity_trace_capability.py +39 -0
  26. execweave/auto_specialized.py +547 -0
  27. execweave/backends.py +102 -0
  28. execweave/benchmark.py +80 -0
  29. execweave/claude_adapter.py +517 -0
  30. execweave/claude_child_transcript.py +314 -0
  31. execweave/claude_delegation.py +136 -0
  32. execweave/claude_full_fidelity.py +396 -0
  33. execweave/claude_hook_cli.py +209 -0
  34. execweave/claude_hook_contract.py +943 -0
  35. execweave/claude_model_observer.py +353 -0
  36. execweave/claude_record.py +106 -0
  37. execweave/cli.py +629 -0
  38. execweave/codex_adapter.py +455 -0
  39. execweave/codex_conversation.py +621 -0
  40. execweave/codex_full_fidelity.py +287 -0
  41. execweave/codex_hook_cli.py +301 -0
  42. execweave/codex_hook_entry.py +207 -0
  43. execweave/codex_hook_lifecycle.py +363 -0
  44. execweave/codex_message_diagnostics.py +322 -0
  45. execweave/codex_message_transport_diagnostics.py +399 -0
  46. execweave/codex_record.py +199 -0
  47. execweave/codex_rollout_structures.py +402 -0
  48. execweave/codex_rollout_trace.py +56 -0
  49. execweave/codex_rollout_trace_base.py +1509 -0
  50. execweave/collector.py +768 -0
  51. execweave/command.py +157 -0
  52. execweave/command_privacy.py +20 -0
  53. execweave/content_evidence.py +101 -0
  54. execweave/content_integrity.py +289 -0
  55. execweave/content_store.py +273 -0
  56. execweave/controlled_checks.py +561 -0
  57. execweave/conversation_archive.py +338 -0
  58. execweave/conversation_message_identity.py +264 -0
  59. execweave/conversation_preview.py +66 -0
  60. execweave/conversation_preview_antigravity.py +32 -0
  61. execweave/conversation_preview_claude.py +31 -0
  62. execweave/conversation_preview_codex.py +107 -0
  63. execweave/conversation_preview_common.py +180 -0
  64. execweave/conversation_preview_generic.py +188 -0
  65. execweave/conversation_preview_lines.py +133 -0
  66. execweave/conversation_preview_transcript.py +121 -0
  67. execweave/conversation_records.py +349 -0
  68. execweave/conversation_records_antigravity.py +370 -0
  69. execweave/conversation_records_codex.py +83 -0
  70. execweave/conversation_records_common.py +17 -0
  71. execweave/conversation_records_ollama.py +39 -0
  72. execweave/correlation.py +818 -0
  73. execweave/cursor_adapter.py +349 -0
  74. execweave/cursor_delegation.py +87 -0
  75. execweave/cursor_delegation_base.py +220 -0
  76. execweave/cursor_full_fidelity.py +489 -0
  77. execweave/cursor_hook_cli.py +195 -0
  78. execweave/cursor_hook_contract.py +439 -0
  79. execweave/cursor_lifecycle.py +159 -0
  80. execweave/cursor_record.py +96 -0
  81. execweave/dashboard_shell.py +283 -0
  82. execweave/delivery_status.py +94 -0
  83. execweave/entry.py +98 -0
  84. execweave/evidence_availability.py +113 -0
  85. execweave/evidence_grade.py +166 -0
  86. execweave/fidelity.py +304 -0
  87. execweave/filesystem.py +327 -0
  88. execweave/finalization.py +92 -0
  89. execweave/focus.py +118 -0
  90. execweave/framework_adapters/__init__.py +34 -0
  91. execweave/framework_adapters/autogen.py +398 -0
  92. execweave/framework_adapters/base.py +580 -0
  93. execweave/framework_adapters/camel.py +270 -0
  94. execweave/framework_adapters/camel_channel.py +71 -0
  95. execweave/framework_adapters/metagpt.py +315 -0
  96. execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
  97. execweave/framework_adapters/metagpt_recording.py +342 -0
  98. execweave/framework_adapters/registry.py +90 -0
  99. execweave/graph.py +590 -0
  100. execweave/graph_ops.py +472 -0
  101. execweave/hook_command.py +32 -0
  102. execweave/hook_delivery.py +32 -0
  103. execweave/hook_input.py +16 -0
  104. execweave/http_proxy.py +187 -0
  105. execweave/http_proxy_cli.py +84 -0
  106. execweave/inference_gateway.py +476 -0
  107. execweave/inference_gateway_cli.py +211 -0
  108. execweave/inference_gateway_full_fidelity.py +613 -0
  109. execweave/inference_identity.py +76 -0
  110. execweave/inference_identity_cli.py +60 -0
  111. execweave/integrity.py +235 -0
  112. execweave/integrity_cli.py +55 -0
  113. execweave/investigation_index.py +445 -0
  114. execweave/litellm_callback.py +211 -0
  115. execweave/litellm_callback_cli.py +42 -0
  116. execweave/live.py +445 -0
  117. execweave/live_core.py +972 -0
  118. execweave/live_view.py +109 -0
  119. execweave/live_view_extra_style.py +11 -0
  120. execweave/live_view_markup.py +29 -0
  121. execweave/live_view_process_layout.py +650 -0
  122. execweave/live_view_readability.py +502 -0
  123. execweave/live_view_script_a.py +59 -0
  124. execweave/live_view_script_b.py +97 -0
  125. execweave/live_view_script_c.py +59 -0
  126. execweave/live_view_script_d.py +40 -0
  127. execweave/live_view_style.py +34 -0
  128. execweave/model_runtime.py +560 -0
  129. execweave/model_runtime_cli.py +265 -0
  130. execweave/model_runtime_full_fidelity.py +519 -0
  131. execweave/observation.py +53 -0
  132. execweave/observation_demo.py +69 -0
  133. execweave/openai_agents.py +267 -0
  134. execweave/openai_agents_sdk.py +453 -0
  135. execweave/openai_compatible.py +239 -0
  136. execweave/openai_compatible_cli.py +189 -0
  137. execweave/openai_compatible_full_fidelity.py +438 -0
  138. execweave/opencode_adapter.py +325 -0
  139. execweave/opencode_event_contract.py +734 -0
  140. execweave/opencode_full_fidelity.py +198 -0
  141. execweave/opencode_hook_cli.py +119 -0
  142. execweave/opencode_plugin_cli.py +150 -0
  143. execweave/opencode_record.py +96 -0
  144. execweave/opencode_task_linkage.py +225 -0
  145. execweave/overhead_benchmark.py +440 -0
  146. execweave/privacy.py +84 -0
  147. execweave/private_io.py +465 -0
  148. execweave/provider_capability.py +578 -0
  149. execweave/provider_lifecycle.py +282 -0
  150. execweave/provider_record.py +290 -0
  151. execweave/reader_identity.py +13 -0
  152. execweave/redacted_archive.py +906 -0
  153. execweave/risk.py +106 -0
  154. execweave/rule_pack.py +359 -0
  155. execweave/rule_pack_cli.py +57 -0
  156. execweave/run_assessment.py +200 -0
  157. execweave/runtime_endpoint_availability.py +44 -0
  158. execweave/scalability_benchmark.py +195 -0
  159. execweave/schema.py +62 -0
  160. execweave/scope.py +85 -0
  161. execweave/semantic.py +453 -0
  162. execweave/session_summary.py +159 -0
  163. execweave/sink.py +71 -0
  164. execweave/strace_backend.py +927 -0
  165. execweave/stream_assembly.py +363 -0
  166. execweave/task_artifacts.py +192 -0
  167. execweave/task_validation.py +317 -0
  168. execweave/theme.py +40 -0
  169. execweave/top.py +599 -0
  170. execweave/top_cli.py +150 -0
  171. execweave/validate.py +196 -0
  172. execweave/vendor/dagre.min.js +815 -0
  173. execweave/view_cli.py +49 -0
  174. execweave/viewer.py +474 -0
  175. execweave/viewer_agent_panel.py +630 -0
  176. execweave/viewer_agent_panel_antigravity.py +31 -0
  177. execweave/viewer_agent_panel_claude.py +9 -0
  178. execweave/viewer_agent_panel_codex.py +50 -0
  179. execweave/viewer_agent_panel_cursor.py +9 -0
  180. execweave/viewer_agent_panel_default.py +79 -0
  181. execweave/viewer_agent_panel_ollama.py +20 -0
  182. execweave/viewer_agent_panel_opencode.py +9 -0
  183. execweave/viewer_agent_panel_registry.py +20 -0
  184. execweave/viewer_archive_verifier.py +178 -0
  185. execweave/viewer_background_files.py +86 -0
  186. execweave/viewer_content_browser.py +307 -0
  187. execweave/viewer_content_health.py +208 -0
  188. execweave/viewer_content_inspector.py +309 -0
  189. execweave/viewer_controlled_checks.py +258 -0
  190. execweave/viewer_conversation_sync.py +115 -0
  191. execweave/viewer_dashboard_clean.py +405 -0
  192. execweave/viewer_dashboard_focus.py +127 -0
  193. execweave/viewer_dashboard_hardening.py +264 -0
  194. execweave/viewer_dashboard_hardening_v2.py +62 -0
  195. execweave/viewer_dashboard_projection.py +261 -0
  196. execweave/viewer_delivery_status.py +155 -0
  197. execweave/viewer_edge_decross.py +117 -0
  198. execweave/viewer_execution_flow.py +611 -0
  199. execweave/viewer_execution_flow_provider_normalization.py +107 -0
  200. execweave/viewer_execution_flow_safety.py +349 -0
  201. execweave/viewer_external_endpoints.py +307 -0
  202. execweave/viewer_flow_canvas.py +1140 -0
  203. execweave/viewer_flow_layout.py +922 -0
  204. execweave/viewer_fold_state.py +31 -0
  205. execweave/viewer_framework_flow.py +68 -0
  206. execweave/viewer_framework_model_output.py +133 -0
  207. execweave/viewer_gif.py +278 -0
  208. execweave/viewer_history_browser.py +225 -0
  209. execweave/viewer_investigation.py +268 -0
  210. execweave/viewer_layout_geometry.py +192 -0
  211. execweave/viewer_layout_v2.py +429 -0
  212. execweave/viewer_layout_v2_detached.py +25 -0
  213. execweave/viewer_limits.py +93 -0
  214. execweave/viewer_live_layout.py +61 -0
  215. execweave/viewer_message_handoffs.py +114 -0
  216. execweave/viewer_projection.py +488 -0
  217. execweave/viewer_projection_base.py +522 -0
  218. execweave/viewer_projection_bridges.py +214 -0
  219. execweave/viewer_recorded_sources.py +146 -0
  220. execweave/viewer_run_assessment.py +274 -0
  221. execweave/viewer_run_guide.py +175 -0
  222. execweave/viewer_runtime_evidence.py +258 -0
  223. execweave/viewer_semantic_projection.py +641 -0
  224. execweave/viewer_session_flow.py +491 -0
  225. execweave/viewer_structure_share.py +132 -0
  226. execweave/viewer_task_validation.py +241 -0
  227. execweave/viewer_tool_mirror_identity.py +75 -0
  228. execweave/viewer_workflow_mode.py +127 -0
  229. execweave/workflow.py +183 -0
  230. execweave-1.0.0.dist-info/METADATA +462 -0
  231. execweave-1.0.0.dist-info/RECORD +234 -0
  232. execweave-1.0.0.dist-info/WHEEL +4 -0
  233. execweave-1.0.0.dist-info/entry_points.txt +30 -0
  234. execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
@@ -0,0 +1,818 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from copy import deepcopy
7
+ from dataclasses import asdict, dataclass, field
8
+ from datetime import datetime, timedelta, timezone
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from uuid import uuid4
12
+
13
+ from .private_io import private_artifact_path, write_private_text
14
+ from .schema import SCHEMA_VERSION
15
+ from .validate import validate_event_stream
16
+
17
+ _RELATION = "CORRELATED_WITH_PROCESS"
18
+ _EVENT_TYPE = "inference.tool_process.correlation"
19
+ _BUILTINS = {
20
+ ".",
21
+ "[",
22
+ "alias",
23
+ "bg",
24
+ "break",
25
+ "cd",
26
+ "command",
27
+ "continue",
28
+ "echo",
29
+ "eval",
30
+ "exec",
31
+ "exit",
32
+ "export",
33
+ "false",
34
+ "fg",
35
+ "hash",
36
+ "jobs",
37
+ "printf",
38
+ "pwd",
39
+ "read",
40
+ "return",
41
+ "set",
42
+ "shift",
43
+ "source",
44
+ "test",
45
+ "trap",
46
+ "true",
47
+ "type",
48
+ "ulimit",
49
+ "umask",
50
+ "unalias",
51
+ "unset",
52
+ "wait",
53
+ }
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class CorrelationResult:
58
+ session_id: str
59
+ input_event_count: int
60
+ output_event_count: int
61
+ tool_calls_considered: int
62
+ correlated_tool_calls: int
63
+ skipped_unsupported: int
64
+ skipped_no_match: int
65
+ skipped_ambiguous: int
66
+ max_window_ms: int
67
+ output: str
68
+
69
+ def to_dict(self) -> dict[str, object]:
70
+ return asdict(self)
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class _Declaration:
75
+ event: dict[str, Any]
76
+ timestamp: datetime
77
+ tool_call: dict[str, Any]
78
+ command_entity: dict[str, Any]
79
+ command_token: str
80
+ command_head: str
81
+ command_argv: tuple[str, ...]
82
+
83
+
84
+ @dataclass
85
+ class _Candidate:
86
+ process: dict[str, Any]
87
+ latest_timestamp: datetime
88
+ latest_timestamp_text: str
89
+ supporting_event_ids: set[str] = field(default_factory=set)
90
+ has_exec_match: bool = False
91
+ has_process_exe_match: bool = False
92
+ has_cmdline_match: bool = False
93
+ has_argv_tail_match: bool = False
94
+
95
+ def observe(
96
+ self,
97
+ event: dict[str, Any],
98
+ *,
99
+ timestamp: datetime,
100
+ exec_match: bool = False,
101
+ process_exe_match: bool = False,
102
+ cmdline_match: bool = False,
103
+ argv_tail_match: bool = False,
104
+ ) -> None:
105
+ if timestamp >= self.latest_timestamp:
106
+ self.latest_timestamp = timestamp
107
+ self.latest_timestamp_text = str(event.get("timestamp"))
108
+ event_id = event.get("event_id")
109
+ if isinstance(event_id, str) and event_id:
110
+ self.supporting_event_ids.add(event_id)
111
+ self.has_exec_match = self.has_exec_match or exec_match
112
+ self.has_process_exe_match = self.has_process_exe_match or process_exe_match
113
+ self.has_cmdline_match = self.has_cmdline_match or cmdline_match
114
+ self.has_argv_tail_match = self.has_argv_tail_match or argv_tail_match
115
+
116
+ def method_and_confidence(self) -> tuple[str, float]:
117
+ if self.has_exec_match and self.has_cmdline_match:
118
+ return "unique_exec_and_cmdline_match", 0.95
119
+ if self.has_exec_match:
120
+ return "unique_exec_identity_match", 0.90
121
+ if self.has_process_exe_match and self.has_cmdline_match:
122
+ return "unique_process_exe_and_cmdline_match", 0.90
123
+ if self.has_process_exe_match:
124
+ return "unique_process_exe_match", 0.85
125
+ if self.has_cmdline_match:
126
+ return "unique_process_cmdline_match", 0.80
127
+ if self.has_argv_tail_match:
128
+ return "unique_process_argv_tail_match", 0.80
129
+ raise RuntimeError("correlation candidate has no matching evidence")
130
+
131
+
132
+ def _parse_timestamp(value: object, *, context: str) -> datetime:
133
+ if not isinstance(value, str) or not value:
134
+ raise ValueError(f"{context}: timestamp must be a non-empty ISO-8601 string")
135
+ try:
136
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
137
+ except ValueError as exc:
138
+ raise ValueError(f"{context}: timestamp must be ISO-8601") from exc
139
+ if parsed.tzinfo is None:
140
+ parsed = parsed.replace(tzinfo=timezone.utc)
141
+ return parsed.astimezone(timezone.utc)
142
+
143
+
144
+ def _load_jsonl(path: Path) -> list[dict[str, Any]]:
145
+ events: list[dict[str, Any]] = []
146
+ for line_number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
147
+ if not raw.strip():
148
+ continue
149
+ try:
150
+ payload = json.loads(raw)
151
+ except json.JSONDecodeError as exc:
152
+ raise ValueError(f"line {line_number}: invalid JSON: {exc.msg}") from exc
153
+ if not isinstance(payload, dict):
154
+ raise ValueError(f"line {line_number}: event must be an object")
155
+ events.append(payload)
156
+ return events
157
+
158
+
159
+ def _clean_executable(value: object) -> str | None:
160
+ if not isinstance(value, str) or not value.strip():
161
+ return None
162
+ return value.strip().strip('"').strip("'") or None
163
+
164
+
165
+ def _normalize_executable(value: object) -> str | None:
166
+ text = _clean_executable(value)
167
+ if text is None:
168
+ return None
169
+ name = text.replace("\\", "/").rsplit("/", 1)[-1].lower()
170
+ if name.endswith(".exe"):
171
+ name = name[:-4]
172
+ return name or None
173
+
174
+
175
+ def _canonical_executable_path(value: object) -> str | None:
176
+ text = _clean_executable(value)
177
+ if text is None:
178
+ return None
179
+ if "/" not in text and "\\" not in text and not Path(text).is_absolute():
180
+ return None
181
+ try:
182
+ resolved = Path(text).expanduser().resolve(strict=False)
183
+ except (OSError, RuntimeError, ValueError):
184
+ return None
185
+ return os.path.normcase(str(resolved))
186
+
187
+
188
+ def _same_executable_identity(candidate: object, declaration: _Declaration) -> bool:
189
+ if _normalize_executable(candidate) == declaration.command_head:
190
+ return True
191
+ declared_path = _canonical_executable_path(declaration.command_token)
192
+ candidate_path = _canonical_executable_path(candidate)
193
+ return declared_path is not None and candidate_path is not None and declared_path == candidate_path
194
+
195
+
196
+ def _has_shell_control(command: str) -> bool:
197
+ quote: str | None = None
198
+ escaped = False
199
+ index = 0
200
+ while index < len(command):
201
+ char = command[index]
202
+ if escaped:
203
+ escaped = False
204
+ index += 1
205
+ continue
206
+ if quote == "'":
207
+ if char == "'":
208
+ quote = None
209
+ index += 1
210
+ continue
211
+ if quote == '"':
212
+ if char == '"':
213
+ quote = None
214
+ elif char == "\\":
215
+ escaped = True
216
+ index += 1
217
+ continue
218
+ if char in {"'", '"'}:
219
+ quote = char
220
+ index += 1
221
+ continue
222
+ if char in "\r\n;&|<>`":
223
+ return True
224
+ if char == "$" and index + 1 < len(command) and command[index + 1] == "(":
225
+ return True
226
+ if char == "\\":
227
+ escaped = True
228
+ index += 1
229
+ return quote is not None
230
+
231
+
232
+ def _command_argv(command: str) -> tuple[str, ...] | None:
233
+ if _has_shell_control(command):
234
+ return None
235
+ tokens: list[str] = []
236
+ chars: list[str] = []
237
+ quote: str | None = None
238
+ token_started = False
239
+ index = 0
240
+ while index < len(command):
241
+ char = command[index]
242
+ if quote is not None:
243
+ if char == quote:
244
+ quote = None
245
+ token_started = True
246
+ elif (
247
+ quote == '"'
248
+ and char == "\\"
249
+ and index + 1 < len(command)
250
+ and command[index + 1] == '"'
251
+ ):
252
+ chars.append('"')
253
+ token_started = True
254
+ index += 1
255
+ else:
256
+ chars.append(char)
257
+ token_started = True
258
+ elif char.isspace():
259
+ if token_started:
260
+ tokens.append("".join(chars))
261
+ chars = []
262
+ token_started = False
263
+ elif char in {"'", '"'}:
264
+ quote = char
265
+ token_started = True
266
+ else:
267
+ chars.append(char)
268
+ token_started = True
269
+ index += 1
270
+ if quote is not None:
271
+ return None
272
+ if token_started:
273
+ tokens.append("".join(chars))
274
+ return tuple(tokens)
275
+
276
+
277
+ def _command_identity(command: str) -> tuple[str, str, tuple[str, ...]] | None:
278
+ argv = _command_argv(command)
279
+ if not argv:
280
+ return None
281
+ token = argv[0]
282
+ if "=" in token:
283
+ return None
284
+ head = _normalize_executable(token)
285
+ if head is None or head in _BUILTINS:
286
+ return None
287
+ return token, head, argv
288
+
289
+
290
+ def _declarations(events: list[dict[str, Any]]) -> list[_Declaration]:
291
+ result: list[_Declaration] = []
292
+ for index, event in enumerate(events, start=1):
293
+ if event.get("relation") != "DECLARED_COMMAND":
294
+ continue
295
+ source = event.get("source")
296
+ target = event.get("target")
297
+ if not isinstance(source, dict) or source.get("type") != "tool_call":
298
+ continue
299
+ if not isinstance(target, dict) or target.get("type") != "command":
300
+ continue
301
+ target_attributes = target.get("attributes") or {}
302
+ command = target_attributes.get("command") if isinstance(target_attributes, dict) else None
303
+ if not isinstance(command, str) or not command:
304
+ continue
305
+ identity = _command_identity(command)
306
+ if identity is None:
307
+ token, head, argv = "", "", ()
308
+ else:
309
+ token, head, argv = identity
310
+ result.append(
311
+ _Declaration(
312
+ event=event,
313
+ timestamp=_parse_timestamp(event.get("timestamp"), context=f"event {index}"),
314
+ tool_call=deepcopy(source),
315
+ command_entity=deepcopy(target),
316
+ command_token=token,
317
+ command_head=head,
318
+ command_argv=argv,
319
+ )
320
+ )
321
+ result.sort(key=lambda item: item.timestamp)
322
+ return result
323
+
324
+
325
+ def _result_times(events: list[dict[str, Any]]) -> dict[str, list[datetime]]:
326
+ result: dict[str, list[datetime]] = {}
327
+ for index, event in enumerate(events, start=1):
328
+ if event.get("relation") not in {"TOOL_CALL_SUCCEEDED", "TOOL_CALL_FAILED"}:
329
+ continue
330
+ source = event.get("source")
331
+ if not isinstance(source, dict):
332
+ continue
333
+ source_id = source.get("id")
334
+ if not isinstance(source_id, str) or not source_id:
335
+ continue
336
+ result.setdefault(source_id, []).append(
337
+ _parse_timestamp(event.get("timestamp"), context=f"event {index}")
338
+ )
339
+ for values in result.values():
340
+ values.sort()
341
+ return result
342
+
343
+
344
+ def _event_time(event: dict[str, Any], *, index: int) -> datetime:
345
+ return _parse_timestamp(event.get("timestamp"), context=f"event {index}")
346
+
347
+
348
+ def _candidate_processes(
349
+ events: list[dict[str, Any]],
350
+ *,
351
+ declaration: _Declaration,
352
+ start: datetime,
353
+ end: datetime,
354
+ ) -> dict[str, _Candidate]:
355
+ candidates: dict[str, _Candidate] = {}
356
+ for index, event in enumerate(events, start=1):
357
+ event_type = event.get("event_type")
358
+ relation = event.get("relation")
359
+ if event_type not in {"process.started", "process.exec"}:
360
+ continue
361
+ timestamp = _event_time(event, index=index)
362
+ if timestamp < start or timestamp > end:
363
+ continue
364
+
365
+ process: dict[str, Any] | None = None
366
+ exec_match = False
367
+ process_exe_match = False
368
+ cmdline_match = False
369
+ argv_tail_match = False
370
+ if event_type == "process.exec" and relation == "EXECUTED":
371
+ source = event.get("source")
372
+ target = event.get("target")
373
+ if not isinstance(source, dict) or source.get("type") != "process":
374
+ continue
375
+ if not isinstance(target, dict) or target.get("type") != "executable":
376
+ continue
377
+ executable_value: object = target.get("name")
378
+ executable_id = target.get("id")
379
+ if isinstance(executable_id, str) and executable_id.startswith("executable:"):
380
+ executable_value = executable_id[len("executable:") :]
381
+ if not _same_executable_identity(executable_value, declaration):
382
+ continue
383
+ process = deepcopy(source)
384
+ exec_match = True
385
+ elif event_type == "process.started":
386
+ target = event.get("target")
387
+ if not isinstance(target, dict) or target.get("type") != "process":
388
+ continue
389
+ attributes = target.get("attributes") or {}
390
+ if not isinstance(attributes, dict):
391
+ continue
392
+ process_exe_match = _same_executable_identity(attributes.get("exe"), declaration)
393
+ cmdline = attributes.get("cmdline")
394
+ if isinstance(cmdline, list) and cmdline and all(isinstance(item, str) for item in cmdline):
395
+ cmdline_match = _same_executable_identity(cmdline[0], declaration)
396
+ # A tail of option flags alone (``-v``, ``--help``) says nothing
397
+ # about which program ran, so it cannot establish compatibility.
398
+ argv_tail_match = (
399
+ len(declaration.command_argv) > 1
400
+ and len(cmdline) == len(declaration.command_argv)
401
+ and tuple(cmdline[1:]) == declaration.command_argv[1:]
402
+ and any(not token.startswith("-") for token in cmdline[1:])
403
+ )
404
+ if not process_exe_match and not cmdline_match and not argv_tail_match:
405
+ continue
406
+ process = deepcopy(target)
407
+ if process is None:
408
+ continue
409
+
410
+ process_id = process.get("id")
411
+ if not isinstance(process_id, str) or not process_id:
412
+ continue
413
+ candidate = candidates.get(process_id)
414
+ if candidate is None:
415
+ candidate = _Candidate(
416
+ process=process,
417
+ latest_timestamp=timestamp,
418
+ latest_timestamp_text=str(event.get("timestamp")),
419
+ )
420
+ candidates[process_id] = candidate
421
+ candidate.observe(
422
+ event,
423
+ timestamp=timestamp,
424
+ exec_match=exec_match,
425
+ process_exe_match=process_exe_match,
426
+ cmdline_match=cmdline_match,
427
+ argv_tail_match=argv_tail_match,
428
+ )
429
+ return candidates
430
+
431
+
432
+ def _derived_event(
433
+ declaration: _Declaration,
434
+ candidate: _Candidate,
435
+ *,
436
+ session_id: str,
437
+ max_window_ms: int,
438
+ ) -> dict[str, Any]:
439
+ method, confidence = candidate.method_and_confidence()
440
+ support = set(candidate.supporting_event_ids)
441
+ declaration_event_id = declaration.event.get("event_id")
442
+ if isinstance(declaration_event_id, str) and declaration_event_id:
443
+ support.add(declaration_event_id)
444
+
445
+ process_id = str(candidate.process.get("id"))
446
+ tool_call_id = str(declaration.tool_call.get("id"))
447
+ digest_source = "|".join(
448
+ [session_id, tool_call_id, process_id, method, *sorted(support)]
449
+ ).encode("utf-8", errors="replace")
450
+ digest = hashlib.sha256(digest_source).hexdigest()[:24]
451
+ delta_ms = max(
452
+ 0.0,
453
+ (candidate.latest_timestamp - declaration.timestamp).total_seconds() * 1000.0,
454
+ )
455
+ return {
456
+ "schema_version": SCHEMA_VERSION,
457
+ "event_id": f"inference:tool-process:{digest}",
458
+ "session_id": session_id,
459
+ "timestamp": candidate.latest_timestamp_text,
460
+ "event_type": _EVENT_TYPE,
461
+ "relation": _RELATION,
462
+ "source": deepcopy(declaration.tool_call),
463
+ "target": deepcopy(candidate.process),
464
+ "sequence": None,
465
+ "attributes": {
466
+ "backend": "inference",
467
+ "attribution": "execweave_correlation",
468
+ "evidence_source": "derived",
469
+ "causal": False,
470
+ "inferred": True,
471
+ "inference_method": method,
472
+ "confidence": confidence,
473
+ "confidence_semantics": "heuristic_score_not_probability",
474
+ "candidate_count": 1,
475
+ "declared_command_head": declaration.command_head,
476
+ "declared_command_token": declaration.command_token,
477
+ "tool_call_id": tool_call_id,
478
+ "command_entity_id": declaration.command_entity.get("id"),
479
+ "time_delta_ms": round(delta_ms, 3),
480
+ "max_window_ms": max_window_ms,
481
+ "supporting_event_ids": sorted(support),
482
+ },
483
+ }
484
+
485
+
486
+
487
+ def _sdk_native_spawn_correlations(
488
+ events: list[dict[str, Any]],
489
+ *,
490
+ session_id: str,
491
+ max_window_ms: int,
492
+ ) -> tuple[list[dict[str, Any]], int, int, int, int]:
493
+ """Infer *non-causal* SDK function-span/native-spawn links.
494
+
495
+ This is a deliberately weaker result than execution-context propagation:
496
+ SDK callback PID/timestamps originate in a same-UID process sidecar,
497
+ whereas the child spawn is independently observed by strace. A temporal
498
+ match is not proof that the tool caused the spawn. Never classify it as
499
+ syscall-attributed; ambiguity (including concurrent spans) abstains.
500
+ """
501
+ starts: dict[str, dict[str, Any]] = {}
502
+ # Retain even invalid/duplicated starts as competing declarations. Dropping
503
+ # them would let a different span claim an otherwise ambiguous native spawn.
504
+ all_starts: list[dict[str, Any]] = []
505
+ ends: dict[str, dict[str, Any]] = {}
506
+ spawns: list[dict[str, Any]] = []
507
+ for event in events:
508
+ attrs = event.get("attributes")
509
+ if not isinstance(attrs, dict):
510
+ continue
511
+ if (
512
+ event.get("event_type") == "process.started"
513
+ and event.get("relation") == "SPAWNED"
514
+ and attrs.get("backend") == "strace"
515
+ and attrs.get("attribution") == "syscall"
516
+ and isinstance(event.get("source"), dict)
517
+ and isinstance(event.get("target"), dict)
518
+ and event["source"].get("type") == "process"
519
+ and event["target"].get("type") == "process"
520
+ ):
521
+ spawns.append(event)
522
+ continue
523
+ if attrs.get("evidence_source") != "agents_sdk_tracing_callback":
524
+ continue
525
+ if attrs.get("framework") != "openai-agents-sdk":
526
+ continue
527
+ call_id = attrs.get("tool_call_id")
528
+ pid = attrs.get("sdk_host_pid")
529
+ if (
530
+ not isinstance(call_id, str) or not call_id
531
+ or not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0
532
+ or not isinstance(attrs.get("sdk_span_id"), str)
533
+ ):
534
+ continue
535
+ if event.get("event_type") == "TOOL_CALL" and event.get("relation") == "REQUESTS_TOOL_CALL":
536
+ all_starts.append(event)
537
+ if call_id in starts:
538
+ # A duplicate declaration is ambiguous; refuse to join.
539
+ starts[call_id] = {}
540
+ else:
541
+ starts[call_id] = event
542
+ elif event.get("event_type") in {"TOOL_RESULT", "TOOL_FAILURE"}:
543
+ if call_id in ends:
544
+ ends[call_id] = {}
545
+ else:
546
+ ends[call_id] = event
547
+
548
+ considered = len(starts)
549
+ skipped_no_match = 0
550
+ skipped_ambiguous = 0
551
+ candidates: list[tuple[dict[str, Any], dict[str, Any], dict[str, Any]]] = []
552
+ for call_id, start in starts.items():
553
+ end = ends.get(call_id)
554
+ if not start or not end:
555
+ skipped_no_match += 1
556
+ continue
557
+ start_attrs = start["attributes"]
558
+ end_attrs = end["attributes"]
559
+ if (
560
+ start_attrs["sdk_host_pid"] != end_attrs.get("sdk_host_pid")
561
+ or start_attrs["sdk_span_id"] != end_attrs.get("sdk_span_id")
562
+ or start_attrs.get("sdk_trace_id") != end_attrs.get("sdk_trace_id")
563
+ ):
564
+ skipped_ambiguous += 1
565
+ continue
566
+ begin = _event_time(start, index=1)
567
+ finish = _event_time(end, index=1)
568
+ if finish < begin:
569
+ skipped_no_match += 1
570
+ continue
571
+ # A time window cannot be stretched merely because a tool is slow.
572
+ limit = min(finish, begin + timedelta(milliseconds=max_window_ms))
573
+ matching = []
574
+ for spawn in spawns:
575
+ native_parent = (spawn.get("source") or {}).get("attributes") or {}
576
+ if native_parent.get("pid") != start_attrs["sdk_host_pid"]:
577
+ continue
578
+ when = _event_time(spawn, index=1)
579
+ if begin <= when < limit:
580
+ matching.append(spawn)
581
+ if len(matching) != 1:
582
+ if matching:
583
+ skipped_ambiguous += 1
584
+ else:
585
+ skipped_no_match += 1
586
+ continue
587
+ candidates.append((start, end, matching[0]))
588
+
589
+ # A span missing TOOL_RESULT still competes for a spawn in its bounded
590
+ # window. Ignoring incomplete spans could falsely attribute its child to
591
+ # a different, completed span. Never use absence of a callback as proof
592
+ # that a tool was not active.
593
+ process_claims: dict[str, int] = {}
594
+ for spawn in spawns:
595
+ parent = (spawn["source"].get("attributes") or {}).get("pid")
596
+ spawn_time = _event_time(spawn, index=1)
597
+ for start in all_starts:
598
+ if start["attributes"].get("sdk_host_pid") != parent:
599
+ continue
600
+ begin = _event_time(start, index=1)
601
+ limit = begin + timedelta(milliseconds=max_window_ms)
602
+ finish_event = ends.get(start["attributes"].get("tool_call_id"))
603
+ if finish_event:
604
+ finish_attrs = finish_event.get("attributes") or {}
605
+ if (
606
+ finish_attrs.get("sdk_host_pid") == parent
607
+ and finish_attrs.get("sdk_span_id") == start["attributes"].get("sdk_span_id")
608
+ and finish_attrs.get("sdk_trace_id") == start["attributes"].get("sdk_trace_id")
609
+ ):
610
+ limit = min(limit, _event_time(finish_event, index=1))
611
+ if begin <= spawn_time < limit:
612
+ pid_id = spawn["target"]["id"]
613
+ process_claims[pid_id] = process_claims.get(pid_id, 0) + 1
614
+ derived = []
615
+ for start, end, spawn in candidates:
616
+ target = spawn["target"]
617
+ if process_claims[target["id"]] != 1:
618
+ skipped_ambiguous += 1
619
+ continue
620
+ attrs = start["attributes"]
621
+ supporting = sorted({
622
+ value for value in (start.get("event_id"), end.get("event_id"), spawn.get("event_id"))
623
+ if isinstance(value, str) and value
624
+ })
625
+ call_id = attrs["tool_call_id"]
626
+ digest = hashlib.sha256(
627
+ "|".join([session_id, call_id, target["id"], *supporting]).encode()
628
+ ).hexdigest()[:24]
629
+ parent_tid = (spawn.get("attributes") or {}).get("spawn_origin_tid")
630
+ callback_tid = attrs.get("sdk_callback_tid")
631
+ derived.append({
632
+ "schema_version": SCHEMA_VERSION,
633
+ "event_id": f"inference:sdk-native-spawn:{digest}",
634
+ "session_id": session_id,
635
+ "timestamp": spawn["timestamp"],
636
+ "event_type": _EVENT_TYPE,
637
+ "relation": _RELATION,
638
+ "source": {
639
+ "type": "tool_call", "id": call_id,
640
+ "name": "SDK function span",
641
+ "attributes": {"sdk_trace_id": attrs.get("sdk_trace_id"),
642
+ "sdk_span_id": attrs["sdk_span_id"]},
643
+ },
644
+ "target": deepcopy(target),
645
+ "sequence": None,
646
+ "attributes": {
647
+ "backend": "inference",
648
+ "attribution": "execweave_correlation",
649
+ "evidence_source": "derived",
650
+ "inferred": True, "causal": False,
651
+ "process_effect_verified": False,
652
+ "inference_method": "unique_sdk_span_host_pid_native_spawn_window",
653
+ "confidence": 0.65,
654
+ "confidence_semantics": "heuristic_score_not_probability",
655
+ "candidate_count": 1,
656
+ "sdk_trace_id": attrs.get("sdk_trace_id"),
657
+ "sdk_span_id": attrs["sdk_span_id"],
658
+ "tool_call_id": call_id,
659
+ "sdk_host_pid": attrs["sdk_host_pid"],
660
+ "sdk_callback_tid": callback_tid,
661
+ "native_spawn_origin_tid": parent_tid,
662
+ "same_callback_and_spawn_tid": (
663
+ callback_tid == parent_tid
664
+ if isinstance(callback_tid, int) and isinstance(parent_tid, int)
665
+ else None
666
+ ),
667
+ "max_window_ms": max_window_ms,
668
+ "supporting_event_ids": supporting,
669
+ "limitation": "SDK callback PID/time window is a claim, not an OS-verified tool context",
670
+ },
671
+ })
672
+ return derived, considered, skipped_no_match, skipped_ambiguous, len(derived)
673
+
674
+
675
+ def correlate_tool_process(
676
+ input_path: str | Path,
677
+ output_path: str | Path,
678
+ *,
679
+ max_window_ms: int = 3000,
680
+ ) -> CorrelationResult:
681
+ if max_window_ms <= 0:
682
+ raise ValueError("max_window_ms must be greater than zero")
683
+ source = Path(input_path).expanduser().resolve()
684
+ output = private_artifact_path(output_path)
685
+ if output.exists() and output.stat().st_size > 0:
686
+ raise FileExistsError(f"ExecWeave correlation output already exists: {output}")
687
+
688
+ validation = validate_event_stream(source, require_complete_session=True)
689
+ if not validation.valid:
690
+ raise ValueError("invalid input event stream: " + "; ".join(validation.errors))
691
+ events = _load_jsonl(source)
692
+ session_id = validation.session_ids[0]
693
+ declarations = _declarations(events)
694
+ results = _result_times(events)
695
+ derived: list[dict[str, Any]] = []
696
+ skipped_unsupported = 0
697
+ skipped_no_match = 0
698
+ skipped_ambiguous = 0
699
+
700
+ candidate_sets: list[tuple[_Declaration, dict[str, _Candidate]]] = []
701
+ for position, declaration in enumerate(declarations):
702
+ if not declaration.command_head:
703
+ skipped_unsupported += 1
704
+ continue
705
+
706
+ window_end = declaration.timestamp + timedelta(milliseconds=max_window_ms)
707
+ tool_call_id = declaration.tool_call.get("id")
708
+ if isinstance(tool_call_id, str):
709
+ for result_time in results.get(tool_call_id, []):
710
+ if result_time >= declaration.timestamp:
711
+ window_end = min(window_end, result_time)
712
+ break
713
+ # Declarations sharing a timestamp do not bound each other; the next
714
+ # strictly later declaration still does.
715
+ for later in declarations[position + 1 :]:
716
+ if later.timestamp > declaration.timestamp:
717
+ window_end = min(window_end, later.timestamp)
718
+ break
719
+
720
+ candidate_sets.append(
721
+ (
722
+ declaration,
723
+ _candidate_processes(
724
+ events,
725
+ declaration=declaration,
726
+ start=declaration.timestamp,
727
+ end=window_end,
728
+ ),
729
+ )
730
+ )
731
+
732
+ # A process compatible with more than one declaration is ambiguous on the
733
+ # declaration side as well, so none of those declarations claims it.
734
+ claims: dict[str, int] = {}
735
+ for _, candidates in candidate_sets:
736
+ for process_id in candidates:
737
+ claims[process_id] = claims.get(process_id, 0) + 1
738
+
739
+ for declaration, candidates in candidate_sets:
740
+ if not candidates:
741
+ skipped_no_match += 1
742
+ continue
743
+ if len(candidates) != 1:
744
+ skipped_ambiguous += 1
745
+ continue
746
+ process_id, candidate = next(iter(candidates.items()))
747
+ if claims[process_id] != 1:
748
+ skipped_ambiguous += 1
749
+ continue
750
+ derived.append(
751
+ _derived_event(
752
+ declaration,
753
+ candidate,
754
+ session_id=session_id,
755
+ max_window_ms=max_window_ms,
756
+ )
757
+ )
758
+
759
+ sdk_derived, sdk_considered, sdk_missing, sdk_ambiguous, sdk_joined = (
760
+ _sdk_native_spawn_correlations(
761
+ events, session_id=session_id, max_window_ms=max_window_ms
762
+ )
763
+ )
764
+ derived.extend(sdk_derived)
765
+ skipped_no_match += sdk_missing
766
+ skipped_ambiguous += sdk_ambiguous
767
+
768
+ starts = [event for event in events if event.get("event_type") == "session.started"]
769
+ finishes = [event for event in events if event.get("event_type") == "session.finished"]
770
+ if len(starts) != 1 or len(finishes) != 1:
771
+ raise ValueError("input event stream must contain exactly one session start and finish")
772
+
773
+ body = [
774
+ deepcopy(event)
775
+ for event in events
776
+ if event.get("event_type") not in {"session.started", "session.finished"}
777
+ ]
778
+ decorated: list[tuple[datetime, int, int, dict[str, Any]]] = []
779
+ for index, event in enumerate(body):
780
+ decorated.append((_event_time(event, index=index + 1), 0, index, event))
781
+ for index, event in enumerate(derived):
782
+ decorated.append((_event_time(event, index=index + 1), 1, index, event))
783
+ decorated.sort(key=lambda item: (item[0], item[1], item[2]))
784
+
785
+ correlated = [deepcopy(starts[0]), *[item[3] for item in decorated], deepcopy(finishes[0])]
786
+ for sequence, event in enumerate(correlated, start=1):
787
+ event["sequence"] = sequence
788
+
789
+ blob = "".join(
790
+ json.dumps(event, ensure_ascii=False, sort_keys=True) + "\n" for event in correlated
791
+ )
792
+ validation_path = output.parent / f".{output.name}.validate-{uuid4().hex}.jsonl"
793
+ try:
794
+ write_private_text(validation_path, blob)
795
+ correlated_validation = validate_event_stream(
796
+ validation_path, require_complete_session=True
797
+ )
798
+ if not correlated_validation.valid:
799
+ raise ValueError(
800
+ "correlated event stream is invalid: "
801
+ + "; ".join(correlated_validation.errors)
802
+ )
803
+ write_private_text(output, blob)
804
+ finally:
805
+ validation_path.unlink(missing_ok=True)
806
+
807
+ return CorrelationResult(
808
+ session_id=session_id,
809
+ input_event_count=len(events),
810
+ output_event_count=len(correlated),
811
+ tool_calls_considered=len(declarations) + sdk_considered,
812
+ correlated_tool_calls=len(derived),
813
+ skipped_unsupported=skipped_unsupported,
814
+ skipped_no_match=skipped_no_match,
815
+ skipped_ambiguous=skipped_ambiguous,
816
+ max_window_ms=max_window_ms,
817
+ output=str(output),
818
+ )