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,445 @@
1
+ """Bounded investigation records from recorded streams and explicit graph edges.
2
+
3
+ A graph edge can aggregate many messages. Native occurrence IDs, not aggregate
4
+ counts, pair send/receive and request/result observations here. This index never
5
+ reads provider bodies or workspace files, and never establishes task success.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import hashlib
11
+ import json
12
+ from itertools import islice
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import stat
17
+ from typing import Any
18
+
19
+ from .content_integrity import ArchiveReadError, _path_descriptor_stat, _reject_link, _signature
20
+
21
+ MAX_EVENTS = 100_000
22
+ MAX_OBSERVATIONS = 10_000
23
+ MAX_BYTES = 32 * 1024 * 1024
24
+ MAX_LINE_BYTES = 1024 * 1024
25
+ MAX_GRAPH_RECORDS = 100_000
26
+ _PATH = re.compile(r"content/sha256/([0-9a-f]{64})\.(?:txt|json|bin)")
27
+ _STREAMS = frozenset({"events.jsonl", "semantic.jsonl", "events.semantic.jsonl", "events.correlated.jsonl"})
28
+ _PHASES = {
29
+ "MESSAGE_SENT": ("message", "sent", "message_id"),
30
+ "MESSAGE_RECEIVED": ("message", "received", "message_id"),
31
+ "MESSAGE_UNROUTED": ("message", "unrouted", "message_id"),
32
+ "MODEL_REQUEST": ("model", "request", "model_call_id"),
33
+ "MODEL_RESPONSE": ("model", "response", "model_call_id"),
34
+ "MODEL_FAILURE": ("model", "failure", "model_call_id"),
35
+ "TOOL_CALL": ("tool", "request", "tool_call_id"),
36
+ "TOOL_RESULT": ("tool", "response", "tool_call_id"),
37
+ "TOOL_FAILURE": ("tool", "failure", "tool_call_id"),
38
+ }
39
+
40
+
41
+ def _obj(value: Any) -> dict[str, Any]:
42
+ return value if isinstance(value, dict) else {}
43
+
44
+
45
+ def _id(value: Any) -> str | None:
46
+ # Oversized IDs are rejected, never truncated into another identity.
47
+ return value if isinstance(value, str) and 0 < len(value) <= 2048 else None
48
+
49
+
50
+ def _native(value: dict[str, Any]) -> bool:
51
+ return all(part.get(key) is None or part.get(key) is False
52
+ for part in (value, _obj(value.get("attributes")))
53
+ for key in ("inferred", "viewer_only"))
54
+
55
+
56
+ def _unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
57
+ result = {}
58
+ for key, value in pairs:
59
+ if key in result:
60
+ raise ValueError("duplicate JSON key")
61
+ result[key] = value
62
+ return result
63
+
64
+
65
+ def _constant(value: str) -> None:
66
+ raise ValueError("nonfinite JSON")
67
+
68
+
69
+ def _scan(root: Path, names: list[str], session: str | None,
70
+ *, max_events: int, max_observations: int, max_bytes: int) -> dict[str, Any]:
71
+ report: dict[str, Any] = {
72
+ "state": "unavailable", "scanned_events": 0, "retained_observations": 0,
73
+ "scope_rejected": 0, "invalid_records": 0, "missing_occurrence_ids": 0,
74
+ "conflicting_event_ids": 0, "limit_reached": False, "streams": [],
75
+ "diagnostics": [],
76
+ }
77
+ records: dict[tuple[str, ...], dict[str, Any]] = {}
78
+ conflicts: set[tuple[str, ...]] = set()
79
+ used_bytes = 0
80
+
81
+ def diagnostic(code: str, stream: str) -> None:
82
+ if len(report["diagnostics"]) < 20:
83
+ report["diagnostics"].append({"code": code, "stream": stream})
84
+
85
+ for name in names:
86
+ file_records: dict[tuple[str, ...], dict[str, Any]] = {}
87
+ stream = {"name": name, "state": "unavailable", "bytes_read": 0}
88
+ report["streams"].append(stream)
89
+ descriptor = None
90
+ try:
91
+ _reject_link(root)
92
+ path = root / name
93
+ _reject_link(path)
94
+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0)
95
+ | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
96
+ before = os.fstat(descriptor)
97
+ if not stat.S_ISREG(before.st_mode):
98
+ raise ValueError("not_regular_file")
99
+ with os.fdopen(descriptor, "rb") as handle:
100
+ descriptor = None
101
+ line_no = 0
102
+ while True:
103
+ budget = max_bytes - used_bytes
104
+ if budget <= 0 or report["scanned_events"] >= max_events:
105
+ # An exact boundary is complete only at EOF.
106
+ if handle.read(1):
107
+ report["limit_reached"] = True
108
+ break
109
+ raw = handle.readline(min(MAX_LINE_BYTES + 1, budget + 1))
110
+ if not raw:
111
+ break
112
+ line_no += 1
113
+ used_bytes += len(raw)
114
+ stream["bytes_read"] += len(raw)
115
+ if len(raw) > MAX_LINE_BYTES or used_bytes > max_bytes:
116
+ report["limit_reached"] = True
117
+ diagnostic("line_or_byte_limit", name)
118
+ break
119
+ if not raw.strip():
120
+ continue
121
+ report["scanned_events"] += 1
122
+ try:
123
+ event = json.loads(raw.decode("utf-8-sig"), object_pairs_hook=_unique,
124
+ parse_constant=_constant)
125
+ if not isinstance(event, dict):
126
+ raise ValueError("event_not_object")
127
+ except (ValueError, RecursionError):
128
+ report["invalid_records"] += 1
129
+ diagnostic("invalid_event", name)
130
+ continue
131
+ phase = _PHASES.get(event.get("event_type")) if isinstance(event.get("event_type"), str) else None
132
+ if phase is None or not _native(event):
133
+ continue
134
+ a = _obj(event.get("attributes"))
135
+ declared = [part["session_id"] for part in (event, a) if "session_id" in part]
136
+ if not session or not declared or any(x != session for x in declared):
137
+ report["scope_rejected"] += 1
138
+ continue
139
+ source, target = _obj(event.get("source")), _obj(event.get("target"))
140
+ if not _native(source) or not _native(target):
141
+ report["invalid_records"] += 1
142
+ continue
143
+ framework = _id(a.get("framework")) or _id(_obj(source.get("attributes")).get("framework"))
144
+ # Canonical SDK events may declare user-defined framework names.
145
+ # Trust the native event/participant/scope checks above rather than
146
+ # a product-specific enum that rejects otherwise valid handoffs.
147
+ if framework is None:
148
+ report["invalid_records"] += 1
149
+ diagnostic("missing_canonical_emitter", name)
150
+ continue
151
+ kind, state, native_key = phase
152
+ native_id = _id(a.get(native_key))
153
+ event_id = _id(event.get("event_id"))
154
+ if not native_id:
155
+ report["missing_occurrence_ids"] += 1
156
+ owner = _id(source.get("id")) if source.get("type") in ("agent", "user") else None
157
+ target_id = _id(target.get("id")) if target.get("type") in ("agent", "user", "model", "tool") else None
158
+ if kind != "message" and source.get("type") != "agent":
159
+ owner = None
160
+ expected = a.get("sender_agent_id" if kind == "message" else "requesting_agent_id")
161
+ recipient = a.get("recipient_agent_id") if kind == "message" else None
162
+ if ((expected is not None and expected != owner) or
163
+ (recipient is not None and recipient != target_id)):
164
+ report["invalid_records"] += 1
165
+ diagnostic("conflicting_participants", name)
166
+ continue
167
+ key = (framework, "event", event_id) if event_id else (framework, "line", name, str(line_no))
168
+ item = {
169
+ "kind": kind, "phase": state, "framework": framework,
170
+ "namespace": _id(a.get("run_id")) or session,
171
+ "native_id": native_id, "event_id": event_id,
172
+ "owner_id": owner, "target_id": target_id,
173
+ "source_name": str(source.get("name") or owner or "Unknown sender")[:256],
174
+ "target_name": str(target.get("name") or target_id or "Unknown recipient")[:256],
175
+ "stream": name, "line": line_no, "timestamp": _id(event.get("timestamp")),
176
+ "reference": {"path": a.get("content_ref"), "sha256": a.get("content_sha256"),
177
+ "size_bytes": a.get("content_size_bytes"),
178
+ "content_kind": _id(a.get("content_kind")),
179
+ "complete_from_source": a.get("content_complete_from_source") if type(a.get("content_complete_from_source")) is bool else None},
180
+ "capture_mode": a.get("capture_mode") if isinstance(a.get("capture_mode"), str) and a.get("capture_mode") in {
181
+ "metadata_only", "content_ref_only", "prompt_only", "prompt_and_response"} else None,
182
+ "fingerprint": hashlib.sha256(raw).hexdigest(),
183
+ }
184
+ previous = file_records.get(key) or records.get(key)
185
+ if key in conflicts:
186
+ continue
187
+ if previous:
188
+ # Identical retries/replay are not additional deliveries.
189
+ left = {k: v for k, v in previous.items() if k not in {"stream", "line", "fingerprint"}}
190
+ right = {k: v for k, v in item.items() if k not in {"stream", "line", "fingerprint"}}
191
+ if left != right:
192
+ conflicts.add(key)
193
+ file_records.pop(key, None)
194
+ records.pop(key, None)
195
+ continue
196
+ if len(file_records) + len(records) >= max_observations:
197
+ report["limit_reached"] = True
198
+ break
199
+ file_records[key] = item
200
+ after = os.fstat(handle.fileno())
201
+ _reject_link(path)
202
+ if _signature(before) != _signature(after) or _signature(after) != _signature(_path_descriptor_stat(path)):
203
+ raise ValueError("stream_changed_during_scan")
204
+ records.update(file_records)
205
+ stream["state"] = "partial" if report["limit_reached"] else "scanned"
206
+ except (ArchiveReadError, OSError, RuntimeError, ValueError) as exc:
207
+ stream["state"] = "unavailable"
208
+ diagnostic(type(exc).__name__ + ":" + str(exc)[:120], name)
209
+ finally:
210
+ if descriptor is not None:
211
+ os.close(descriptor)
212
+ if report["limit_reached"]:
213
+ break
214
+ report["conflicting_event_ids"] = len(conflicts)
215
+ report["retained_observations"] = len(records)
216
+ if any(s["state"] == "scanned" for s in report["streams"]):
217
+ report["state"] = "scanned_selected_streams"
218
+ if (report["limit_reached"] or report["scope_rejected"] or report["invalid_records"] or conflicts or
219
+ any(s["state"] != "scanned" for s in report["streams"])):
220
+ report["state"] = "partial" if records else "unavailable"
221
+ return {"observations": list(records.values()), "inspection": report}
222
+
223
+
224
+ class InvestigationCache:
225
+ """One bounded stream snapshot per Live state; no process-global content cache."""
226
+
227
+ def __init__(self) -> None:
228
+ # Publish the key and value atomically; concurrent HTTP readers must
229
+ # never observe a new scope key paired with an older run's snapshot.
230
+ self.entry: tuple[object, dict[str, Any]] | None = None
231
+
232
+
233
+ def _graph_nodes(graph: dict[str, Any]) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]], bool]:
234
+ nodes: dict[str, dict[str, Any]] = {}
235
+ ambiguous: set[str] = set()
236
+ edges = []
237
+ containers = [graph]
238
+ clusters = _obj(_obj(graph.get("expansion")).get("clusters"))
239
+ containers.extend(v for v in islice(clusters.values(), 1000) if isinstance(v, dict))
240
+ remaining = MAX_GRAPH_RECORDS
241
+ partial = len(clusters) > 1000
242
+ for container in containers:
243
+ for kind in ("nodes", "edges"):
244
+ rows = container.get(kind, [])
245
+ if not isinstance(rows, list):
246
+ partial = True
247
+ continue
248
+ for row in rows:
249
+ if not remaining:
250
+ return {k: v for k, v in nodes.items() if k not in ambiguous}, edges, True
251
+ remaining -= 1
252
+ if not isinstance(row, dict):
253
+ partial = True
254
+ continue
255
+ if not _native(row):
256
+ continue
257
+ if kind == "edges":
258
+ edges.append(row)
259
+ elif _id(row.get("id")):
260
+ key = row["id"]
261
+ if key in nodes and nodes[key] != row:
262
+ ambiguous.add(key)
263
+ else:
264
+ nodes[key] = row
265
+ return {k: v for k, v in nodes.items() if k not in ambiguous}, edges, partial or bool(ambiguous)
266
+
267
+
268
+ def build_investigation_index(graph: dict[str, Any], run_root: str | Path, *,
269
+ cache: InvestigationCache | None = None,
270
+ max_events: int = MAX_EVENTS, max_observations: int = MAX_OBSERVATIONS,
271
+ max_bytes: int = MAX_BYTES) -> dict[str, Any]:
272
+ """Join only native occurrences in this run; reference bytes are never opened.
273
+
274
+ File names are a fixed allowlist under the supplied run folder. Original
275
+ absolute source paths are labels, not file access capabilities. Old archives
276
+ without streams still provide graph-backed roles and snapshot references.
277
+ """
278
+ if any(type(x) is not int or x < 0 for x in (max_events, max_observations, max_bytes)):
279
+ raise ValueError("inspection limits must be nonnegative integers")
280
+ root = Path(run_root).expanduser().absolute()
281
+ session = _id(graph.get("session_id"))
282
+ source = _id(graph.get("source_path"))
283
+ source_name = re.split(r"[/\\]", source or "")[-1]
284
+ names = [source_name] if source_name in _STREAMS and (root / source_name).exists() else []
285
+ if not names or names == ["events.jsonl"]:
286
+ if (root / "semantic.jsonl").exists():
287
+ names = ["semantic.jsonl"]
288
+ names = list(dict.fromkeys(names))
289
+ signatures = []
290
+ for name in names:
291
+ try:
292
+ _reject_link(root / name)
293
+ value = (root / name).stat()
294
+ signatures.append((name, _signature(value)))
295
+ except (ArchiveReadError, OSError, RuntimeError, ValueError):
296
+ signatures.append((name, None))
297
+ cache_key = (str(root), session, source, tuple(signatures), max_events, max_observations, max_bytes)
298
+ cached = cache.entry if cache is not None else None
299
+ if cached is not None and cached[0] == cache_key:
300
+ scanned = cached[1]
301
+ else:
302
+ scanned = _scan(root, names, session, max_events=max_events,
303
+ max_observations=max_observations, max_bytes=max_bytes)
304
+ # Do not cache an in-flight partial/mutating scan as a stable success.
305
+ if cache is not None:
306
+ cache.entry = (cache_key, scanned) if scanned["inspection"]["state"] == "scanned_selected_streams" else None
307
+ nodes, edges, graph_partial = _graph_nodes(graph)
308
+ declared: dict[tuple[str, str], list[dict[str, Any]]] = {}
309
+ for node in nodes.values():
310
+ a = _obj(node.get("attributes"))
311
+ if node.get("type") == "observed_content" and isinstance(a.get("path"), str) and isinstance(a.get("sha256"), str):
312
+ declared.setdefault((a["path"], a["sha256"]), []).append(a)
313
+
314
+ def registered(ref: dict[str, Any]) -> tuple[str, dict[str, Any] | None]:
315
+ path, digest = ref.get("path"), ref.get("sha256")
316
+ if path is None and digest is None:
317
+ return "not_recorded", None
318
+ match = _PATH.fullmatch(path) if isinstance(path, str) else None
319
+ if not match or match[1] != digest or type(ref.get("size_bytes")) is not int or ref["size_bytes"] < 0:
320
+ return "invalid_reference", None
321
+ matches = declared.get((path, digest), [])
322
+ if not matches or any(type(a.get("size_bytes")) is not int or a["size_bytes"] != ref["size_bytes"] for a in matches):
323
+ return "not_in_graph_inventory", None
324
+ # All references displayed here are also covered by the existing graph
325
+ # reference verifier. No hidden second class of archive references.
326
+ return "registered_not_read", {
327
+ "path": path, "sha256": digest, "size_bytes": ref["size_bytes"],
328
+ "content_kind": _id(ref.get("content_kind")),
329
+ "complete_from_source": ref.get("complete_from_source") if type(ref.get("complete_from_source")) is bool else None,
330
+ }
331
+
332
+ groups: dict[tuple[Any, ...], dict[str, Any]] = {}
333
+ for observation in scanned["observations"]:
334
+ o = observation
335
+ key = (o["namespace"], o["framework"], o["kind"],
336
+ o["native_id"] if o["native_id"] and o["owner_id"] and o["target_id"] else (o["stream"], o["line"]), o["owner_id"], o["target_id"])
337
+ row = groups.setdefault(key, {
338
+ "key": json.dumps(key, ensure_ascii=False, separators=(",", ":")),
339
+ "kind": o["kind"], "native_id": o["native_id"], "framework": o["framework"],
340
+ "owner_id": o["owner_id"], "target_id": o["target_id"],
341
+ "source_name": o["source_name"], "target_name": o["target_name"],
342
+ "identity_bound": bool(o["native_id"] and o["owner_id"] and o["target_id"]),
343
+ "observations": [], "references": [], "phases": [],
344
+ })
345
+ phase = o["phase"]
346
+ if phase not in row["phases"]:
347
+ row["phases"].append(phase)
348
+ state, reference = registered(o["reference"])
349
+ row["observations"].append({k: o[k] for k in ("phase", "event_id", "stream", "line", "timestamp", "capture_mode")})
350
+ # Keep each observed phase separate even if the bytes have equal hashes.
351
+ row["references"].append({"phase": phase, "state": state, "reference": reference,
352
+ "event_id": o["event_id"]})
353
+ rows = list(groups.values())
354
+ agents = [{"id": n["id"], "name": str(n.get("name") or n["id"])[:256],
355
+ "provider": str(_obj(n.get("attributes")).get("provider") or "unknown")[:80],
356
+ "role": str(_obj(n.get("attributes")).get("role") or _obj(n.get("attributes")).get("agent_role") or "")[:256]}
357
+ for n in nodes.values() if n.get("type") == "agent"]
358
+ files = []
359
+ outgoing: dict[str, list[dict[str, Any]]] = {}
360
+ incoming: dict[str, list[dict[str, Any]]] = {}
361
+ for edge in edges:
362
+ if _id(edge.get("source")) and _id(edge.get("target")):
363
+ outgoing.setdefault(edge["source"], []).append(edge)
364
+ incoming.setdefault(edge["target"], []).append(edge)
365
+ for n in nodes.values():
366
+ if n.get("type") not in ("file", "artifact"):
367
+ continue
368
+ snapshots = []
369
+ related_content = []
370
+ for e in outgoing.get(n["id"], []):
371
+ peer = nodes.get(e["target"], {})
372
+ if peer.get("type") != "observed_content":
373
+ continue
374
+ state, ref = registered(_obj(peer.get("attributes")))
375
+ record = {"relation": _id(e.get("relation")), "edge_id": _id(e.get("id")),
376
+ "timestamp": _id(e.get("first_seen")), "state": state, "reference": ref}
377
+ # Only the capture contract that explicitly records file bytes before
378
+ # a read establishes a file snapshot. An arbitrary associated payload
379
+ # is still inspectable, but is not silently promoted to file contents.
380
+ destination = snapshots if e.get("relation") == "OBSERVED_FILE_CONTENT_BEFORE_READ" else related_content
381
+ destination.append(record)
382
+ relations = [{"source": e.get("source"), "target": e.get("target"), "relation": e.get("relation"),
383
+ "edge_id": e.get("id"), "causal": e.get("causal")}
384
+ for e in incoming.get(n["id"], [])[:50]]
385
+ files.append({"id": n["id"], "name": str(n.get("name") or n["id"])[:512],
386
+ "snapshots": snapshots[:50], "snapshot_count": len(snapshots),
387
+ "related_content": related_content[:50], "related_content_count": len(related_content),
388
+ "relations": relations, "relation_count": len(incoming.get(n["id"], []))})
389
+ event_call_ids = {r["native_id"] for r in rows if r["kind"] != "message" and r["native_id"]}
390
+ call_relations = {"HAS_TOOL_INPUT": "request", "HAS_TOOL_OUTPUT": "response",
391
+ "OBSERVED_INFERENCE_REQUEST": "request", "OBSERVED_INFERENCE_RESPONSE": "response"}
392
+ owners = {"REQUESTED_TOOL_CALL", "REQUESTS_TOOL_CALL", "ISSUED_TOOL_CALL", "REQUESTS_MODEL_CALL"}
393
+ for n in nodes.values():
394
+ if n.get("type") not in ("tool_call", "model_call", "inference_request") or n["id"] in event_call_ids:
395
+ continue
396
+ # Framework call records use the event-stream contract above. Do not
397
+ # revive a rejected framework occurrence through its aggregate graph.
398
+ if _id(_obj(n.get("attributes")).get("framework")) in {"camel", "autogen", "metagpt"}:
399
+ continue
400
+ kind = "tool" if n["type"] == "tool_call" else "model"
401
+ candidates = sorted({e["source"] for e in incoming.get(n["id"], [])
402
+ if _id(e.get("relation")) in owners and nodes.get(e["source"], {}).get("type") == "agent"})
403
+ owner = candidates[0] if len(candidates) == 1 else None
404
+ target_type = "tool" if kind == "tool" else "model"
405
+ targets = sorted({e["target"] for e in outgoing.get(n["id"], [])
406
+ if _id(e.get("relation")) in {"USES_TOOL", "USED_MODEL"} and nodes.get(e["target"], {}).get("type") == target_type})
407
+ target = targets[0] if len(targets) == 1 else None
408
+ refs = []
409
+ phases = []
410
+ for e in outgoing.get(n["id"], []):
411
+ peer = nodes.get(e["target"], {})
412
+ if peer.get("type") != "observed_content":
413
+ continue
414
+ relation = _id(e.get("relation"))
415
+ phase = call_relations.get(relation, "supplemental_content")
416
+ if phase not in phases:
417
+ phases.append(phase)
418
+ state, ref = registered(_obj(peer.get("attributes")))
419
+ refs.append({"phase": phase, "relation": relation, "state": state, "reference": ref,
420
+ "edge_id": _id(e.get("id")), "event_ids": [_id(x) for x in e.get("event_ids", [])[:20]]
421
+ if isinstance(e.get("event_ids"), list) else []})
422
+ rows.append({"key": "graph:" + n["id"], "kind": kind, "native_id": n["id"],
423
+ "framework": _id(_obj(n.get("attributes")).get("provider")),
424
+ "owner_id": owner, "target_id": target,
425
+ "source_name": str(nodes.get(owner, {}).get("name") or owner or "Unknown owner")[:256],
426
+ "target_name": str(nodes.get(target, {}).get("name") or n.get("name") or n["id"])[:256],
427
+ "identity_bound": bool(owner and target), "observation_basis": "explicit_graph_call",
428
+ "owner_candidates": candidates[:20], "target_candidates": targets[:20],
429
+ "observations": [], "references": refs[:50], "reference_count": len(refs), "phases": phases})
430
+ inspection = copy.deepcopy(scanned["inspection"])
431
+ inspection["graph_inventory_partial"] = graph_partial or bool(graph.get("live_payload_compact")) or bool(graph.get("viewer_projection"))
432
+ inspection["agent_rows_omitted"] = max(0, len(agents) - 10_000)
433
+ inspection["call_rows_omitted"] = max(0, sum(r["kind"] != "message" for r in rows) - 10_000)
434
+ inspection["artifact_rows_omitted"] = max(0, len(files) - 10_000)
435
+ if inspection["agent_rows_omitted"] or inspection["artifact_rows_omitted"] or inspection["call_rows_omitted"]:
436
+ inspection["graph_inventory_partial"] = True
437
+ return {
438
+ "schema_version": "0.1", "scope": "recorded_event_investigation", "session_id": session,
439
+ "source_path": source, "inspection": inspection, "agents": agents[:10_000],
440
+ "messages": [r for r in rows if r["kind"] == "message"],
441
+ "calls": [r for r in rows if r["kind"] in {"tool", "model"}][:10_000], "artifacts": files[:10_000],
442
+ "limits": {"events": max_events, "observations": max_observations, "stream_bytes": max_bytes,
443
+ "agents": 10_000, "calls": 10_000, "artifacts": 10_000, "references_per_graph_row": 50},
444
+ "denominator_version": "observed-native-occurrences-v1",
445
+ }
@@ -0,0 +1,211 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from .content_store import FullFidelityContentStore
10
+ from .inference_gateway import (
11
+ append_gateway_records,
12
+ litellm_response_to_events,
13
+ sanitize_gateway_endpoint,
14
+ )
15
+ from .inference_gateway_full_fidelity import litellm_callback_to_content_events
16
+ from .privacy import full_content_capture_enabled
17
+
18
+ try:
19
+ from litellm.integrations.custom_logger import CustomLogger as _LiteLLMCustomLogger
20
+ except ImportError: # ExecWeave does not require LiteLLM unless this callback is loaded by it.
21
+ class _LiteLLMCustomLogger: # type: ignore[no-redef]
22
+ pass
23
+
24
+
25
+ _SEMANTIC_ENV = "EXECWEAVE_SEMANTIC_SIDECAR"
26
+ _ENDPOINT_ENV = "EXECWEAVE_LITELLM_ENDPOINT"
27
+ _DEFAULT_ENDPOINT = "http://localhost:4000"
28
+
29
+
30
+ def _mapping(value: object) -> dict[str, Any] | None:
31
+ if isinstance(value, dict):
32
+ return value
33
+ model_dump = getattr(value, "model_dump", None)
34
+ if callable(model_dump):
35
+ dumped = model_dump()
36
+ return dumped if isinstance(dumped, dict) else None
37
+ as_dict = getattr(value, "dict", None)
38
+ if callable(as_dict):
39
+ dumped = as_dict()
40
+ return dumped if isinstance(dumped, dict) else None
41
+ return None
42
+
43
+
44
+ def _text(value: object) -> str | None:
45
+ return value if isinstance(value, str) and value else None
46
+
47
+
48
+ def _number(value: object) -> int | float | None:
49
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
50
+ return None
51
+ return value
52
+
53
+
54
+ def _timestamp(value: object) -> str | None:
55
+ if isinstance(value, datetime):
56
+ observed = value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
57
+ return observed.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
58
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
59
+ try:
60
+ return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat().replace(
61
+ "+00:00", "Z"
62
+ )
63
+ except (OSError, OverflowError, ValueError):
64
+ return None
65
+ return None
66
+
67
+
68
+ def _now() -> str:
69
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
70
+
71
+
72
+ def _gateway_endpoint() -> str:
73
+ candidate = os.environ.get(_ENDPOINT_ENV) or os.environ.get("PROXY_BASE_URL") or _DEFAULT_ENDPOINT
74
+ try:
75
+ return sanitize_gateway_endpoint(candidate)
76
+ except ValueError:
77
+ return _DEFAULT_ENDPOINT
78
+
79
+
80
+ def standard_logging_to_events(
81
+ payload: dict[str, Any],
82
+ *,
83
+ endpoint: str | None = None,
84
+ timestamp: str | None = None,
85
+ ) -> list[dict[str, Any]]:
86
+ """Convert LiteLLM StandardLoggingPayload into privacy-safe gateway evidence.
87
+
88
+ The semantic summary intentionally stays limited to routing, usage, cost, cache, and
89
+ latency fields. Full request/response evidence is appended separately by the callback.
90
+ """
91
+ call_id = _text(payload.get("id"))
92
+ if call_id is None:
93
+ raise ValueError("LiteLLM standard logging payload requires id")
94
+
95
+ model = _text(payload.get("model"))
96
+ model_group = _text(payload.get("model_group"))
97
+ deployment_id = _text(payload.get("model_id"))
98
+
99
+ usage: dict[str, Any] = {}
100
+ for key in ("prompt_tokens", "completion_tokens", "total_tokens"):
101
+ value = payload.get(key)
102
+ if isinstance(value, int) and not isinstance(value, bool):
103
+ usage[key] = value
104
+ response_cost = _number(payload.get("response_cost"))
105
+ if response_cost is not None:
106
+ usage["cost"] = response_cost
107
+
108
+ response_payload: dict[str, Any] = {"id": call_id, "usage": usage}
109
+ if model is not None:
110
+ response_payload["model"] = model
111
+
112
+ records = litellm_response_to_events(
113
+ response_payload,
114
+ requested_model=model_group,
115
+ resolved_model=model,
116
+ deployment_id=deployment_id,
117
+ endpoint=sanitize_gateway_endpoint(endpoint or _gateway_endpoint()),
118
+ request_id=call_id,
119
+ timestamp=timestamp or _timestamp(payload.get("endTime")),
120
+ )
121
+
122
+ extra: dict[str, Any] = {"litellm_standard_logging": True}
123
+ call_type = _text(payload.get("call_type"))
124
+ if call_type is not None:
125
+ extra["call_type"] = call_type
126
+ response_time = _number(payload.get("response_time"))
127
+ if response_time is not None:
128
+ extra["response_time_seconds"] = float(response_time)
129
+ cache_hit = payload.get("cache_hit")
130
+ if isinstance(cache_hit, bool):
131
+ extra["cache_hit"] = cache_hit
132
+
133
+ for record in records:
134
+ attributes = record.get("attributes")
135
+ if isinstance(attributes, dict):
136
+ attributes.update(extra)
137
+ target = record.get("target")
138
+ if record.get("relation") == "SERVED_INFERENCE" and isinstance(target, dict):
139
+ target_attributes = target.get("attributes")
140
+ if isinstance(target_attributes, dict):
141
+ target_attributes.update(extra)
142
+ return records
143
+
144
+
145
+ class ExecWeaveLiteLLMCallback(_LiteLLMCustomLogger):
146
+ """LiteLLM callback that appends semantic summary then full source-exposed evidence."""
147
+
148
+ def _emit(self, kwargs: object, response_obj: object, end_time: object = None) -> None:
149
+ sidecar_value = os.environ.get(_SEMANTIC_ENV)
150
+ if not sidecar_value:
151
+ return
152
+ sidecar = Path(sidecar_value).expanduser().resolve()
153
+ try:
154
+ callback_kwargs = _mapping(kwargs)
155
+ if callback_kwargs is None:
156
+ return
157
+ standard = _mapping(callback_kwargs.get("standard_logging_object"))
158
+ if standard is None:
159
+ return
160
+ callback_kwargs = {**callback_kwargs, "standard_logging_object": standard}
161
+ observed_at = _timestamp(end_time) or _now()
162
+ records = standard_logging_to_events(standard, timestamp=observed_at)
163
+ append_gateway_records(sidecar, records)
164
+ except Exception:
165
+ # Observability must never alter the LiteLLM request outcome.
166
+ return
167
+
168
+ if not full_content_capture_enabled():
169
+ return
170
+
171
+ try:
172
+ mapped_response = _mapping(response_obj)
173
+ full_response: object = mapped_response if mapped_response is not None else response_obj
174
+ content_records = litellm_callback_to_content_events(
175
+ callback_kwargs,
176
+ full_response,
177
+ store=FullFidelityContentStore(sidecar.parent),
178
+ endpoint=_gateway_endpoint(),
179
+ timestamp=observed_at,
180
+ )
181
+ for record in content_records:
182
+ attributes = record.get("attributes")
183
+ if isinstance(attributes, dict):
184
+ attributes.setdefault("gateway", "litellm")
185
+ append_gateway_records(sidecar, content_records)
186
+ except Exception:
187
+ # Keep the already-written semantic summary if full-fidelity storage fails.
188
+ return
189
+
190
+ def log_success_event(
191
+ self,
192
+ kwargs: object,
193
+ response_obj: object,
194
+ start_time: object,
195
+ end_time: object,
196
+ ) -> None:
197
+ del start_time
198
+ self._emit(kwargs, response_obj, end_time)
199
+
200
+ async def async_log_success_event(
201
+ self,
202
+ kwargs: object,
203
+ response_obj: object,
204
+ start_time: object,
205
+ end_time: object,
206
+ ) -> None:
207
+ del start_time
208
+ await asyncio.to_thread(self._emit, kwargs, response_obj, end_time)
209
+
210
+
211
+ execweave_litellm_callback = ExecWeaveLiteLLMCallback()