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,902 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections import Counter
5
+ from pathlib import Path
6
+ from typing import Any
7
+ from .content_store import _filesystem_path
8
+ from .private_io import write_private_json, write_private_text
9
+
10
+ from .agent_topology import (
11
+ COMPLETENESS_ROUTING_ONLY,
12
+ EVIDENCE_CROSS_AGENT_ROUTING,
13
+ PATH_PROVIDER_DECLARED,
14
+ ROOT_PATH,
15
+ THREAD_ID_PROVIDER_NATIVE,
16
+ TOPOLOGY_OBSERVED,
17
+ strongest_completeness,
18
+ )
19
+ from .conversation_preview import conversation_preview
20
+
21
+ _CONVERSATION_PATH_RE = re.compile(
22
+ r"^content/sha256/(?P<sha256>[0-9a-f]{64})\.(?P<suffix>json|txt|bin)$"
23
+ )
24
+ _CONVERSATION_TOKENS = (
25
+ "conversation_transcript",
26
+ "conversation_item",
27
+ "agent_message",
28
+ "user_message",
29
+ "user_prompt",
30
+ "assistant_display",
31
+ "assistant_response",
32
+ "assistant_final_response",
33
+ "assistant_messages",
34
+ "assistant_content_blocks",
35
+ "response_object",
36
+ "standard_logging_response",
37
+ "completed_text",
38
+ "agent_response_candidate",
39
+ "subtask_prompt",
40
+ "subtask_description",
41
+ "subagent_task",
42
+ "subagent_description",
43
+ "subagent_summary",
44
+ "subagent_final_response",
45
+ "prompt_submission_candidate",
46
+ "inference_message",
47
+ "request_messages",
48
+ "request_prompt",
49
+ "request_input",
50
+ "model_context_messages",
51
+ "model_request",
52
+ "model_response",
53
+ "model_failure",
54
+ )
55
+
56
+
57
+ def is_conversation_content_kind(content_kind: str) -> bool:
58
+ """Return whether one stored value belongs in the user-facing conversation index."""
59
+ if not isinstance(content_kind, str) or not content_kind:
60
+ return False
61
+ value = content_kind.lower()
62
+ if value == "inference_gateway.openrouter.response":
63
+ return True
64
+ return any(token in value for token in _CONVERSATION_TOKENS)
65
+
66
+
67
+ def _safe_content_reference(node: dict[str, Any]) -> dict[str, Any] | None:
68
+ if node.get("type") != "observed_content":
69
+ return None
70
+ attributes = node.get("attributes")
71
+ if not isinstance(attributes, dict):
72
+ return None
73
+ path = attributes.get("path")
74
+ sha256 = attributes.get("sha256")
75
+ content_kind = attributes.get("content_kind")
76
+ if not all(isinstance(value, str) and value for value in (path, sha256, content_kind)):
77
+ return None
78
+ if not is_conversation_content_kind(content_kind):
79
+ return None
80
+ match = _CONVERSATION_PATH_RE.fullmatch(path)
81
+ if match is None or match.group("sha256") != sha256:
82
+ return None
83
+ size_bytes = attributes.get("size_bytes")
84
+ if not isinstance(size_bytes, int) or isinstance(size_bytes, bool) or size_bytes < 0:
85
+ return None
86
+ return {
87
+ "path": path,
88
+ "sha256": sha256,
89
+ "size_bytes": size_bytes,
90
+ "content_kind": content_kind,
91
+ "media_type": attributes.get("media_type"),
92
+ "representation": attributes.get("representation"),
93
+ "complete_from_source": attributes.get("complete_from_source"),
94
+ }
95
+
96
+
97
+ def _provider(source: dict[str, Any] | None, content_kind: str) -> str:
98
+ if isinstance(source, dict):
99
+ attributes = source.get("attributes")
100
+ if isinstance(attributes, dict):
101
+ for key in ("provider", "provider_name"):
102
+ value = attributes.get(key)
103
+ if isinstance(value, str) and value:
104
+ return value
105
+ parts = content_kind.split(".")
106
+ if len(parts) > 1 and parts[0] == "inference_gateway":
107
+ return parts[1]
108
+ if parts and parts[0] == "openai_compatible":
109
+ return "openai-compatible"
110
+ prefix = parts[0] if parts else ""
111
+ return prefix if prefix else "unknown"
112
+
113
+
114
+ def _run_local_path(root: Path, relative: str) -> Path | None:
115
+ try:
116
+ root_fs = _filesystem_path(root)
117
+ candidate = (root_fs / relative).resolve(strict=False)
118
+ candidate.relative_to(root_fs)
119
+ except (OSError, RuntimeError, ValueError):
120
+ return None
121
+ return candidate if candidate.is_file() else None
122
+
123
+
124
+ def _conversation_preview(
125
+ root: Path | None,
126
+ reference: dict[str, Any],
127
+ *,
128
+ provider: str,
129
+ source: dict[str, Any] | None,
130
+ timestamp: object,
131
+ ordinal: object,
132
+ ) -> dict[str, Any] | None:
133
+ if root is None:
134
+ return None
135
+ relative = reference.get("path")
136
+ content_kind = reference.get("content_kind")
137
+ if not isinstance(relative, str) or not isinstance(content_kind, str):
138
+ return None
139
+ path = _run_local_path(root, relative)
140
+ if path is None:
141
+ return None
142
+ return conversation_preview(
143
+ path,
144
+ content_kind=content_kind,
145
+ provider=provider,
146
+ source=source,
147
+ timestamp=timestamp,
148
+ ordinal=ordinal,
149
+ )
150
+
151
+
152
+ def _entry_rank(entry: dict[str, Any]) -> tuple[int, int, str]:
153
+ last_sequence = entry.get("last_sequence")
154
+ sequence = last_sequence if isinstance(last_sequence, int) else -1
155
+ size = entry.get("size_bytes")
156
+ size_bytes = size if isinstance(size, int) else -1
157
+ return sequence, size_bytes, str(entry.get("path") or "")
158
+
159
+
160
+ def _message_key(message: dict[str, Any]) -> tuple[object, ...]:
161
+ return (
162
+ message.get("ordinal"),
163
+ message.get("kind"),
164
+ message.get("sender"),
165
+ message.get("recipient"),
166
+ message.get("text"),
167
+ message.get("content_state"),
168
+ message.get("phase"),
169
+ message.get("task_name"),
170
+ )
171
+
172
+
173
+ def _message_sort_key(message: dict[str, Any], index: int) -> tuple[object, ...]:
174
+ ordinal = message.get("ordinal")
175
+ return (
176
+ 0 if isinstance(ordinal, int) else 1,
177
+ ordinal if isinstance(ordinal, int) else 2**63 - 1,
178
+ str(message.get("timestamp") or ""),
179
+ index,
180
+ )
181
+
182
+
183
+ def _cross_source_message_sort_key(message: dict[str, Any], index: int) -> tuple[object, ...]:
184
+ """Order a thread assembled from several transcripts by observation time.
185
+
186
+ Ordinals are positions within one transcript, so they do not compare across
187
+ transcripts. A thread whose evidence spans more than one stored blob orders by
188
+ timestamp instead, and keeps the ordinal only as a tiebreak within one source.
189
+ """
190
+ timestamp = message.get("timestamp")
191
+ ordinal = message.get("ordinal")
192
+ return (
193
+ 0 if isinstance(timestamp, str) and timestamp else 1,
194
+ str(timestamp or ""),
195
+ ordinal if isinstance(ordinal, int) else 2**63 - 1,
196
+ index,
197
+ )
198
+
199
+
200
+ def _conversation_identity_keys(
201
+ entry: dict[str, Any],
202
+ preview: dict[str, Any],
203
+ ) -> tuple[str, str, set[tuple[str, str]]]:
204
+ """Return the positive evidence that identifies this record's agent execution.
205
+
206
+ Two records may be merged only when evidence establishes they describe the *same*
207
+ execution. Two kinds of positive evidence qualify:
208
+
209
+ ``graph_agent``
210
+ The same graph agent node. That id already encodes the provider-native
211
+ identity it was built from (``agent:codex:<session>:subagent:<agent_id>``), so
212
+ sharing it is a provider-grounded statement that this is one execution.
213
+
214
+ ``provider_thread``
215
+ The same raw thread identity, which is how incremental provider content for one
216
+ conversation has always been recognized.
217
+
218
+ Matching labels, nicknames, similar-looking thread ids, or both being children of
219
+ ``/root`` are deliberately absent: none of them establishes shared identity. The
220
+ agent path is carried in every key rather than being a key itself, so records for
221
+ two different agents can never merge no matter what else they share.
222
+ """
223
+ provider = str(entry.get("provider") or "unknown").lower()
224
+ agent_path = preview.get("agent_path")
225
+ agent_scope = (
226
+ str(agent_path)
227
+ if isinstance(agent_path, str) and agent_path
228
+ else str(entry.get("source_id") or "unknown")
229
+ )
230
+ keys: set[tuple[str, str]] = set()
231
+ source_id = entry.get("source_id")
232
+ if isinstance(source_id, str) and source_id:
233
+ keys.add(("graph_agent", source_id))
234
+ thread_id = preview.get("thread_id")
235
+ if isinstance(thread_id, str) and thread_id:
236
+ keys.add(("provider_thread", thread_id))
237
+ if not keys:
238
+ keys.add(("unidentified", str(id(entry))))
239
+ return provider, agent_scope, keys
240
+
241
+
242
+ def _canonical_thread_id(previews: list[dict[str, Any]]) -> tuple[str | None, list[str]]:
243
+ """Pick the preferred thread id for one execution and keep every contributing id.
244
+
245
+ A provider-native id wins over an ExecWeave-synthesized one, so merging never
246
+ downgrades an identity the provider actually published, and a provider that exposes
247
+ no thread of its own keeps the synthesized id it has always had. Selection is
248
+ deterministic: sorted within each class.
249
+ """
250
+ native: set[str] = set()
251
+ derived: set[str] = set()
252
+ for preview in previews:
253
+ thread_id = preview.get("thread_id")
254
+ if not isinstance(thread_id, str) or not thread_id:
255
+ continue
256
+ if preview.get("thread_id_source") == THREAD_ID_PROVIDER_NATIVE:
257
+ native.add(thread_id)
258
+ else:
259
+ derived.add(thread_id)
260
+ evidence = sorted(native | derived)
261
+ if native:
262
+ return sorted(native)[0], evidence
263
+ if derived:
264
+ return sorted(derived)[0], evidence
265
+ return None, evidence
266
+
267
+
268
+ def _parent_agent_path(agent_path: object) -> str | None:
269
+ if not isinstance(agent_path, str) or not agent_path.startswith("/root/"):
270
+ return None
271
+ parent = agent_path.rsplit("/", 1)[0]
272
+ return parent or "/root"
273
+
274
+
275
+ def _merge_conversation_previews(entries: list[dict[str, Any]]) -> None:
276
+ """Merge evidence describing one agent execution, without crossing identities.
277
+
278
+ One execution can be observed through several kinds of evidence that name its
279
+ thread differently — a provider-native Codex rollout id on one record and a
280
+ synthesized ``<provider>:root`` on another. Grouping by raw thread alone published
281
+ those as two conversations for the same agent. Records are therefore grouped by the
282
+ transitive closure of positive identity evidence (see
283
+ :func:`_conversation_identity_keys`), which merges those records while still
284
+ keeping genuinely distinct agents and distinct conversations apart.
285
+ """
286
+ indexed_entries: list[dict[str, Any]] = [
287
+ entry for entry in entries if isinstance(entry.get("conversation_preview"), dict)
288
+ ]
289
+ if not indexed_entries:
290
+ return
291
+
292
+ parents = list(range(len(indexed_entries)))
293
+
294
+ def find(node: int) -> int:
295
+ while parents[node] != node:
296
+ parents[node] = parents[parents[node]]
297
+ node = parents[node]
298
+ return node
299
+
300
+ def union(left: int, right: int) -> None:
301
+ left_root, right_root = find(left), find(right)
302
+ if left_root != right_root:
303
+ parents[max(left_root, right_root)] = min(left_root, right_root)
304
+
305
+ scopes: list[tuple[str, str]] = []
306
+ first_seen: dict[tuple[str, str, str, str], int] = {}
307
+ for index, entry in enumerate(indexed_entries):
308
+ provider, agent_scope, keys = _conversation_identity_keys(
309
+ entry, entry["conversation_preview"]
310
+ )
311
+ scopes.append((provider, agent_scope))
312
+ for kind, value in keys:
313
+ # The agent scope is part of every key, so evidence can never join records
314
+ # that belong to two different agents.
315
+ slot = (provider, agent_scope, kind, value)
316
+ union(index, first_seen.setdefault(slot, index))
317
+
318
+ components: dict[int, list[int]] = {}
319
+ for index in range(len(indexed_entries)):
320
+ components.setdefault(find(index), []).append(index)
321
+
322
+ # A provider can reuse one thread id across agents. Detect that before publishing,
323
+ # so a reused id still cannot fold Agent 1 into Agent 2.
324
+ canonical_owners: dict[tuple[str, str], set[str]] = {}
325
+ resolved: dict[int, tuple[str | None, list[str]]] = {}
326
+ for root, members in components.items():
327
+ previews = [indexed_entries[i]["conversation_preview"] for i in members]
328
+ canonical, evidence = _canonical_thread_id(previews)
329
+ resolved[root] = (canonical, evidence)
330
+ if canonical is not None:
331
+ provider, agent_scope = scopes[members[0]]
332
+ canonical_owners.setdefault((provider, canonical), set()).add(agent_scope)
333
+
334
+ thread_alias: dict[tuple[str, str, str], str] = {}
335
+ merged_by_root: dict[int, dict[str, Any]] = {}
336
+ for root, members in components.items():
337
+ group = [indexed_entries[i] for i in members]
338
+ provider, agent_scope = scopes[members[0]]
339
+ previews = [entry["conversation_preview"] for entry in group]
340
+ canonical, evidence_thread_ids = resolved[root]
341
+
342
+ published = canonical if canonical is not None else agent_scope
343
+ if canonical is not None and len(canonical_owners[(provider, canonical)]) > 1:
344
+ published = f"{canonical}::agent={agent_scope}"
345
+
346
+ merged_messages: list[dict[str, Any]] = []
347
+ for preview in previews:
348
+ for message in preview.get("messages") or []:
349
+ if isinstance(message, dict):
350
+ merged_messages.append(dict(message))
351
+ sources = {str(entry.get("sha256") or "") for entry in group}
352
+ sort_key = _cross_source_message_sort_key if len(sources) > 1 else _message_sort_key
353
+ indexed = list(enumerate(merged_messages))
354
+ indexed.sort(key=lambda pair: sort_key(pair[1], pair[0]))
355
+ seen: set[tuple[object, ...]] = set()
356
+ deduped: list[dict[str, Any]] = []
357
+ for _, message in indexed:
358
+ key = _message_key(message)
359
+ if key in seen:
360
+ continue
361
+ seen.add(key)
362
+ deduped.append(message)
363
+
364
+ truncated = len(deduped) > 80
365
+ if truncated:
366
+ deduped = deduped[:10] + deduped[-70:]
367
+
368
+ representative = max(group, key=_entry_rank)
369
+ canonical_preview = next(
370
+ (preview for preview in previews if preview.get("thread_id") == canonical),
371
+ None,
372
+ )
373
+ # The record that owns the canonical thread describes this agent directly, so
374
+ # its identity fields are preferred over one that inherited them from a parent.
375
+ search_order = [canonical_preview] if canonical_preview is not None else []
376
+ search_order += list(reversed(previews))
377
+
378
+ merged_preview: dict[str, Any] = {}
379
+ carried = (
380
+ "parent_thread_id",
381
+ "agent_path",
382
+ "agent_label",
383
+ "provider_label",
384
+ "agent_nickname",
385
+ "is_root",
386
+ "agent_path_source",
387
+ "topology_state",
388
+ "topology_evidence",
389
+ "parent_agent_path",
390
+ "parent_relation_source",
391
+ "provider_native_id",
392
+ "thread_id_source",
393
+ )
394
+ for field in carried:
395
+ for preview in search_order:
396
+ value = preview.get(field)
397
+ if value is not None and value != "":
398
+ merged_preview[field] = value
399
+ break
400
+ for field in carried:
401
+ merged_preview.setdefault(field, representative["conversation_preview"].get(field))
402
+ merged_preview["conversation_completeness"] = strongest_completeness(
403
+ [str(preview.get("conversation_completeness") or "") for preview in previews]
404
+ )
405
+ merged_preview["thread_id"] = published
406
+ merged_preview["evidence_thread_ids"] = evidence_thread_ids
407
+ merged_preview["message_count"] = len(deduped)
408
+ merged_preview["messages_truncated"] = truncated or any(
409
+ bool(preview.get("messages_truncated")) for preview in previews
410
+ )
411
+ merged_preview["messages"] = deduped
412
+
413
+ for raw_thread_id in evidence_thread_ids:
414
+ thread_alias[(provider, raw_thread_id, agent_scope)] = published
415
+
416
+ for entry in group:
417
+ entry.pop("conversation_preview", None)
418
+ representative["conversation_preview"] = merged_preview
419
+ merged_by_root[root] = merged_preview
420
+
421
+ # Parent links were recorded against a contributing thread id, which may not be the
422
+ # one published. Re-point them at the parent's canonical thread.
423
+ for root, preview in merged_by_root.items():
424
+ parent_thread_id = preview.get("parent_thread_id")
425
+ parent_path = preview.get("parent_agent_path") or _parent_agent_path(
426
+ preview.get("agent_path")
427
+ )
428
+ if not isinstance(parent_thread_id, str) or not parent_thread_id:
429
+ continue
430
+ if not isinstance(parent_path, str) or not parent_path:
431
+ continue
432
+ provider = scopes[components[root][0]][0]
433
+ alias = thread_alias.get((provider, parent_thread_id, parent_path))
434
+ if alias is not None:
435
+ preview["parent_thread_id"] = alias
436
+
437
+
438
+ def _derived_agent_entry_source_id(entry: dict[str, Any], preview: dict[str, Any]) -> str:
439
+ """Address a derived thread by the provider agent identity the graph also uses."""
440
+ provider = str(entry.get("provider") or "provider").lower()
441
+ agent_id = preview.get("agent_id")
442
+ parent_thread_id = preview.get("parent_thread_id")
443
+ if isinstance(agent_id, str) and agent_id and isinstance(parent_thread_id, str):
444
+ return f"agent:{provider}:{parent_thread_id}:subagent:{agent_id}"
445
+ return f"agent:{provider}:{preview.get('agent_path') or 'agent'}"
446
+
447
+
448
+ def _derived_agent_entries(
449
+ entry: dict[str, Any],
450
+ previews: list[Any],
451
+ ) -> list[dict[str, Any]]:
452
+ """Materialize agent-local threads a transcript carries routing evidence about.
453
+
454
+ One provider transcript can be the only observable evidence for another agent's
455
+ conversation. Those records are published under that agent's own identity so a
456
+ parent thread never stands in for its children, while still referencing the same
457
+ stored evidence blob.
458
+ """
459
+ results: list[dict[str, Any]] = []
460
+ for preview in previews:
461
+ if not isinstance(preview, dict) or not preview.get("messages"):
462
+ continue
463
+ agent_path = preview.get("agent_path")
464
+ if not isinstance(agent_path, str) or not agent_path:
465
+ continue
466
+ preview.setdefault("agent_path_source", PATH_PROVIDER_DECLARED)
467
+ preview.setdefault("topology_state", TOPOLOGY_OBSERVED)
468
+ preview.setdefault("topology_evidence", EVIDENCE_CROSS_AGENT_ROUTING)
469
+ preview.setdefault("parent_agent_path", ROOT_PATH)
470
+ preview.setdefault("parent_relation_source", EVIDENCE_CROSS_AGENT_ROUTING)
471
+ preview.setdefault("conversation_completeness", COMPLETENESS_ROUTING_ONLY)
472
+ derived_entry = dict(entry)
473
+ derived_entry.pop("conversation_preview", None)
474
+ derived_entry["source_id"] = _derived_agent_entry_source_id(entry, preview)
475
+ derived_entry["source_name"] = preview.get("agent_label") or agent_path
476
+ derived_entry["source_type"] = "agent"
477
+ derived_entry["conversation_preview"] = preview
478
+ results.append(derived_entry)
479
+ return results
480
+
481
+
482
+ def conversation_record_entries(
483
+ graph: dict[str, Any],
484
+ run_root: str | Path | None = None,
485
+ ) -> list[dict[str, Any]]:
486
+ """Build stable run-relative conversation references and provider-neutral visible previews."""
487
+ root = Path(run_root).expanduser().resolve() if run_root is not None else None
488
+ nodes = [node for node in graph.get("nodes", []) if isinstance(node, dict)]
489
+ edges = [edge for edge in graph.get("edges", []) if isinstance(edge, dict)]
490
+ node_by_id = {
491
+ str(node["id"]): node
492
+ for node in nodes
493
+ if isinstance(node.get("id"), str) and node.get("id")
494
+ }
495
+ source_counts = Counter(node.get("id") for node in nodes if isinstance(node.get("id"), str))
496
+ entries: list[dict[str, Any]] = []
497
+ for edge in edges:
498
+ target_id = edge.get("target")
499
+ if not isinstance(target_id, str):
500
+ continue
501
+ target = node_by_id.get(target_id)
502
+ if target is None:
503
+ continue
504
+ reference = _safe_content_reference(target)
505
+ if reference is None:
506
+ continue
507
+ source_id = edge.get("source")
508
+ source = node_by_id.get(source_id) if isinstance(source_id, str) else None
509
+ provider = _provider(source, str(reference["content_kind"]))
510
+ preview = _conversation_preview(
511
+ root,
512
+ reference,
513
+ provider=provider,
514
+ source=source,
515
+ timestamp=edge.get("first_seen"),
516
+ ordinal=edge.get("first_sequence"),
517
+ )
518
+ source_name = source.get("name") if isinstance(source, dict) else None
519
+ if isinstance(preview, dict):
520
+ agent_label = preview.get("agent_label")
521
+ agent_path = preview.get("agent_path")
522
+ if isinstance(agent_label, str) and agent_label:
523
+ source_name = agent_label
524
+ elif isinstance(agent_path, str) and agent_path:
525
+ source_name = agent_path
526
+ entry = {
527
+ "provider": provider,
528
+ "relation": edge.get("relation"),
529
+ "source_id": source_id,
530
+ "source_name": source_name,
531
+ "source_type": source.get("type") if isinstance(source, dict) else None,
532
+ "content_kind": reference["content_kind"],
533
+ "path": reference["path"],
534
+ "sha256": reference["sha256"],
535
+ "size_bytes": reference["size_bytes"],
536
+ "media_type": reference["media_type"],
537
+ "representation": reference["representation"],
538
+ "complete_from_source": reference["complete_from_source"],
539
+ "first_sequence": edge.get("first_sequence"),
540
+ "last_sequence": edge.get("last_sequence"),
541
+ "first_seen": edge.get("first_seen"),
542
+ "last_seen": edge.get("last_seen"),
543
+ }
544
+ derived = preview.pop("derived_agent_previews", None) if isinstance(preview, dict) else None
545
+ if preview is not None:
546
+ entry["conversation_preview"] = preview
547
+ # Keep each framework model response attached to its own content reference.
548
+ # Conversation merging publishes only one aggregate preview and can otherwise
549
+ # leave the actual model bodies behind a later control/status message.
550
+ source_attrs = source.get("attributes") if isinstance(source, dict) else None
551
+ if (
552
+ isinstance(source_attrs, dict)
553
+ and source.get("type") == "agent"
554
+ and source_counts[source_id] == 1
555
+ and source_attrs.get("conversation_scope") == "framework_agent"
556
+ and reference["content_kind"] in {
557
+ "metagpt.model_response", "autogen.model_response", "camel.model_response"
558
+ }
559
+ and edge.get("relation") == "HAS_MODEL_CONTENT"
560
+ and all(
561
+ record.get(flag) is None or record.get(flag) is False
562
+ for record in (edge, edge.get("attributes") if isinstance(edge.get("attributes"), dict) else {})
563
+ for flag in ("inferred", "viewer_only")
564
+ )
565
+ and isinstance(preview, dict)
566
+ ):
567
+ agent_path = preview.get("agent_path")
568
+ entry["model_response_preview"] = {
569
+ "schema_version": "1",
570
+ "source_id": source_id,
571
+ "agent_path": agent_path,
572
+ "messages": [dict(message) for message in preview.get("messages", [])
573
+ if isinstance(message, dict) and agent_path
574
+ and message.get("sender") == agent_path],
575
+ "messages_truncated": bool(preview.get("messages_truncated")),
576
+ }
577
+ entries.append(entry)
578
+ if isinstance(derived, list):
579
+ entries.extend(_derived_agent_entries(entry, derived))
580
+
581
+ entries.sort(
582
+ key=lambda entry: (
583
+ entry["first_sequence"]
584
+ if isinstance(entry.get("first_sequence"), int)
585
+ else 2**63 - 1,
586
+ str(entry.get("first_seen") or ""),
587
+ str(entry.get("provider") or ""),
588
+ str(entry.get("source_id") or ""),
589
+ str(entry.get("path") or ""),
590
+ )
591
+ )
592
+ _merge_conversation_previews(entries)
593
+ return entries
594
+
595
+
596
+ def _markdown_text(value: object) -> str:
597
+ text = str(value) if value not in (None, "") else "unknown"
598
+ return text.replace("|", "\\|").replace("\n", " ")
599
+
600
+
601
+ def _markdown_message_text(value: object) -> str:
602
+ if not isinstance(value, str) or not value:
603
+ return ""
604
+ return (
605
+ value.replace("&", "&amp;")
606
+ .replace("<", "&lt;")
607
+ .replace(">", "&gt;")
608
+ .replace("\r", "")
609
+ .replace("\n", " \n")
610
+ )
611
+
612
+
613
+ def _preview_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
614
+ rich = [entry for entry in entries if isinstance(entry.get("conversation_preview"), dict)]
615
+ return sorted(
616
+ rich,
617
+ key=lambda entry: (
618
+ 0 if (entry.get("conversation_preview") or {}).get("is_root") else 1,
619
+ str((entry.get("conversation_preview") or {}).get("agent_path") or ""),
620
+ str(entry.get("provider") or ""),
621
+ str(entry.get("source_id") or ""),
622
+ ),
623
+ )
624
+
625
+
626
+ def _render_markdown(entries: list[dict[str, Any]]) -> str:
627
+ lines = [
628
+ "# ExecWeave Conversation Records",
629
+ "",
630
+ "This index uses run-local, content-addressed evidence and a provider-neutral visible conversation projection. Provider-specific cache folders are not required for inspection.",
631
+ "",
632
+ f"Records: **{len(entries)}**",
633
+ "",
634
+ ]
635
+ if not entries:
636
+ lines.extend(
637
+ [
638
+ "No run-local conversation record was captured for this run.",
639
+ "",
640
+ ]
641
+ )
642
+ return "\n".join(lines)
643
+
644
+ lines.extend(
645
+ [
646
+ "| # | Provider | Source | Relation | Content | Bytes | Stored copy |",
647
+ "| ---: | --- | --- | --- | --- | ---: | --- |",
648
+ ]
649
+ )
650
+ for index, entry in enumerate(entries, start=1):
651
+ path = str(entry["path"])
652
+ lines.append(
653
+ "| "
654
+ + " | ".join(
655
+ [
656
+ str(index),
657
+ _markdown_text(entry.get("provider")),
658
+ _markdown_text(entry.get("source_name") or entry.get("source_id")),
659
+ _markdown_text(entry.get("relation")),
660
+ _markdown_text(entry.get("content_kind")),
661
+ str(entry.get("size_bytes") or 0),
662
+ f"[Open]({path})",
663
+ ]
664
+ )
665
+ + " |"
666
+ )
667
+
668
+ rich_entries = _preview_entries(entries)
669
+ if rich_entries:
670
+ lines.extend(["", "## Visible conversation timeline", ""])
671
+ for entry in rich_entries:
672
+ preview = entry.get("conversation_preview") or {}
673
+ agent_label = (
674
+ preview.get("agent_label")
675
+ or preview.get("agent_path")
676
+ or entry.get("source_name")
677
+ or entry.get("source_id")
678
+ )
679
+ provider_label = preview.get("provider_label") or entry.get("provider")
680
+ # Lead with the agent path. A provider nickname is often unrelated to the task
681
+ # the agent was given ("OpenAI Codex · Avicenna" for /root/ci_agent), so heading
682
+ # every section with provider plus nickname made six agents indistinguishable.
683
+ agent_path = preview.get("agent_path")
684
+ identity = (
685
+ agent_path if isinstance(agent_path, str) and agent_path else agent_label
686
+ )
687
+ heading = f"### {_markdown_text(identity)} · {_markdown_text(provider_label)}"
688
+ for annotation in (agent_label, preview.get("agent_nickname")):
689
+ if (
690
+ isinstance(annotation, str)
691
+ and annotation
692
+ and annotation != identity
693
+ and annotation != provider_label
694
+ and f"({_markdown_text(annotation)})" not in heading
695
+ ):
696
+ heading += f" ({_markdown_text(annotation)})"
697
+ lines.extend([heading, ""])
698
+
699
+ messages = preview.get("messages")
700
+ if not isinstance(messages, list) or not messages:
701
+ lines.extend(["No user-visible messages were projected from this evidence.", ""])
702
+ continue
703
+ for message in messages:
704
+ if not isinstance(message, dict):
705
+ continue
706
+ sender = message.get("sender") or agent_label
707
+ recipient = message.get("recipient")
708
+ direction = str(sender)
709
+ if isinstance(recipient, str) and recipient:
710
+ direction += f" → {recipient}"
711
+ kind = str(message.get("kind") or "message")
712
+ phase = message.get("phase")
713
+ label = f"**{_markdown_text(kind)}**"
714
+ if isinstance(phase, str) and phase:
715
+ label += f" / {_markdown_text(phase)}"
716
+ timestamp = message.get("timestamp")
717
+ prefix = f"- `{_markdown_text(timestamp)}` {direction} · {label}: "
718
+ if message.get("content_state") == "provider_encrypted":
719
+ lines.append(
720
+ prefix
721
+ + "*provider-encrypted payload; plaintext is not exposed by the observed provider surface*"
722
+ )
723
+ else:
724
+ text = _markdown_message_text(message.get("text"))
725
+ lines.append(prefix + (text or "*(no plaintext body exposed)*"))
726
+ lines.append("")
727
+
728
+ lines.extend(
729
+ [
730
+ "Paths above are SHA-256-addressed copies inside this ExecWeave run. External provider cache paths are intentionally not required for inspection.",
731
+ "",
732
+ ]
733
+ )
734
+ return "\n".join(lines)
735
+
736
+
737
+ # A provider may prepend the same block to every subagent it spawns — Codex sends a
738
+ # plugin catalogue and an environment context, several kilobytes of it, recorded in the
739
+ # rollout exactly where that agent's own assignment belongs. Read literally, every
740
+ # sibling was handed an identical multi-kilobyte task and the panel shows four agents
741
+ # that look the same.
742
+ #
743
+ # Nothing about the provider needs to be recognised to see that this is wrong. A text
744
+ # handed to two or more agents is, by that fact alone, not any one agent's own
745
+ # assignment. It is marked here, once, in the index both viewers read, so neither has to
746
+ # detect it and they cannot disagree about it.
747
+ #
748
+ # The rule reaches inbound messages only. A child reports its answer back to its parent,
749
+ # so that answer appears both in the child's record and in the parent's; judged on
750
+ # repetition alone it looked like a shared preamble and the child lost its own answer.
751
+ SHARED_INJECTED_CONTEXT = "shared_injected_context"
752
+ _MIN_SHARED_CONTEXT_LENGTH = 400
753
+
754
+
755
+ def _inbound_assignment_text(message: object, agent_path: str) -> str | None:
756
+ """Return the text of a message handed *to* this agent, if it is long enough.
757
+
758
+ Only what an agent was handed can be a shared preamble. What the agent wrote is
759
+ its own, however often it is repeated elsewhere in the run.
760
+ """
761
+ if not isinstance(message, dict):
762
+ return None
763
+ if str(message.get("recipient") or "") != agent_path:
764
+ return None
765
+ if str(message.get("sender") or "") == agent_path:
766
+ return None
767
+ text = message.get("text")
768
+ if not isinstance(text, str) or len(text) < _MIN_SHARED_CONTEXT_LENGTH:
769
+ return None
770
+ return text
771
+
772
+
773
+ def _mark_shared_injected_context(entries: list[dict[str, Any]]) -> None:
774
+ agents_by_text: dict[str, set[str]] = {}
775
+ for entry in entries:
776
+ preview = entry.get("conversation_preview")
777
+ if not isinstance(preview, dict):
778
+ continue
779
+ agent_path = preview.get("agent_path")
780
+ if not isinstance(agent_path, str) or not agent_path:
781
+ continue
782
+ for message in preview.get("messages") or []:
783
+ text = _inbound_assignment_text(message, agent_path)
784
+ if text is not None:
785
+ agents_by_text.setdefault(text, set()).add(agent_path)
786
+
787
+ shared = {text for text, agents in agents_by_text.items() if len(agents) > 1}
788
+ if not shared:
789
+ return
790
+ for entry in entries:
791
+ preview = entry.get("conversation_preview")
792
+ if not isinstance(preview, dict):
793
+ continue
794
+ agent_path = preview.get("agent_path")
795
+ if not isinstance(agent_path, str) or not agent_path:
796
+ continue
797
+ for message in preview.get("messages") or []:
798
+ if _inbound_assignment_text(message, agent_path) in shared:
799
+ message["content_role"] = SHARED_INJECTED_CONTEXT
800
+
801
+
802
+ # One rollout can be the evidence for several agents: Codex records a delegation and
803
+ # the return it receives in the parent's file, so a child's turns are read from the
804
+ # parent's record rather than from one of its own. Every agent then cited that file as
805
+ # its own raw evidence, and the link inside a child's section opened the whole run.
806
+ #
807
+ # The file is still the evidence and has to stay inspectable, so it is attributed
808
+ # instead of hidden: the agent highest in the path hierarchy among those citing it owns
809
+ # it, and the others say whose record their turns were read from.
810
+ EVIDENCE_SHARED_WITH_OWNER = "evidence_shared_with_owner"
811
+
812
+
813
+ def _mark_shared_evidence(entries: list[dict[str, Any]]) -> None:
814
+ agents_by_path: dict[str, set[str]] = {}
815
+ for entry in entries:
816
+ preview = entry.get("conversation_preview")
817
+ relative = entry.get("path")
818
+ if not isinstance(preview, dict) or not isinstance(relative, str) or not relative:
819
+ continue
820
+ agent_path = preview.get("agent_path")
821
+ if isinstance(agent_path, str) and agent_path:
822
+ agents_by_path.setdefault(relative, set()).add(agent_path)
823
+
824
+ owners = {
825
+ relative: min(agents, key=lambda path: (path.count("/"), len(path), path))
826
+ for relative, agents in agents_by_path.items()
827
+ if len(agents) > 1
828
+ }
829
+ if not owners:
830
+ return
831
+ for entry in entries:
832
+ preview = entry.get("conversation_preview")
833
+ relative = entry.get("path")
834
+ if not isinstance(preview, dict) or not isinstance(relative, str):
835
+ continue
836
+ owner = owners.get(relative)
837
+ if owner is None or preview.get("agent_path") == owner:
838
+ continue
839
+ entry[EVIDENCE_SHARED_WITH_OWNER] = owner
840
+
841
+
842
+ def conversation_index_payload(
843
+ graph: dict[str, Any],
844
+ run_root: str | Path,
845
+ *,
846
+ investigation_cache=None,
847
+ include_investigation: bool = False,
848
+ ) -> dict[str, Any]:
849
+ """Build the shared conversation projection, with opt-in investigation.
850
+
851
+ The default is the historical, lightweight conversation contract used by
852
+ ordinary Live polling. Event-stream inspection is requested explicitly by
853
+ the investigation reader and offline exporters. Both modes publish exactly
854
+ the same conversation entries; the extended mode only adds an index.
855
+ """
856
+ from .investigation_index import build_investigation_index
857
+
858
+ root = Path(run_root).expanduser().resolve()
859
+ entries = conversation_record_entries(graph, root)
860
+ _mark_shared_injected_context(entries)
861
+ _mark_shared_evidence(entries)
862
+ visible_message_count = sum(
863
+ len(preview.get("messages") or [])
864
+ for entry in entries
865
+ if isinstance((preview := entry.get("conversation_preview")), dict)
866
+ )
867
+ return {
868
+ "schema_version": "0.3",
869
+ "scope": "run_local_provider_neutral_conversation_projection",
870
+ "session_id": graph.get("session_id") if isinstance(graph.get("session_id"), str) else None,
871
+ "source_path": graph.get("source_path") if isinstance(graph.get("source_path"), str) else None,
872
+ **({"investigation": build_investigation_index(graph, root, cache=investigation_cache)}
873
+ if include_investigation else {}),
874
+ "entry_count": len(entries),
875
+ "visible_message_count": visible_message_count,
876
+ "external_provider_folder_lookup_required": False,
877
+ "entries": entries,
878
+ }
879
+
880
+
881
+ def write_conversation_records(
882
+ graph: dict[str, Any],
883
+ run_root: str | Path,
884
+ *,
885
+ payload: dict[str, Any] | None = None,
886
+ ) -> tuple[Path, Path]:
887
+ """Write deterministic JSON + Markdown indexes beside the viewer artifacts.
888
+
889
+ A caller that already built the index passes it in rather than letting a second
890
+ projection run: the standalone viewer embeds these same entries, and a viewer
891
+ built from its own projection is free to disagree with the file beside it.
892
+ """
893
+ root = Path(run_root).expanduser().resolve()
894
+ root.mkdir(parents=True, exist_ok=True)
895
+ if payload is None:
896
+ payload = conversation_index_payload(graph, root, include_investigation=True)
897
+ entries = payload["entries"]
898
+ json_path = root / "conversations.json"
899
+ markdown_path = root / "conversations.md"
900
+ write_private_json(json_path, payload, replace=json_path.exists())
901
+ write_private_text(markdown_path, _render_markdown(entries), replace=markdown_path.exists())
902
+ return json_path, markdown_path