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,115 @@
1
+ """Explicit, run-scoped state for the existing final conversation synchronization."""
2
+ from __future__ import annotations
3
+
4
+ SYNC_STATE_JS = """let selectedNode=null,refreshing=false,conversationPollingFinished=false,conversationFinishSynchronized=false,conversationFinishing=false,conversationRefreshController=null,conversationRefreshTimer=null,conversationRefreshPromise=Promise.resolve(false),conversationFinishPromise=Promise.resolve(false),selectedConversationSignature='',conversationScopeKey=null,conversationSyncGeneration=0,conversationResponseScoped=false;"""
5
+
6
+ SYNC_REFRESH_JS = r"""
7
+ function conversationScope(){
8
+ const g=window.__execweaveCore?.getGraph?.()||window.__execweaveStaticGraph||{};
9
+ return {session_id:g.session_id||null,source_path:g.source_path||null};
10
+ }
11
+ function synchronizationStatus(){
12
+ const scope=conversationScope(),stale=conversationScopeKey!==null&&conversationScopeKey!==JSON.stringify(scope);
13
+ return {...scope,state:stale?'unknown':window.__execweaveStaticMode?'embedded':
14
+ conversationFinishing?'syncing':conversationPollingFinished?
15
+ (conversationFinishSynchronized?'synced':'failed'):'live',
16
+ response_session_checked:!stale&&conversationResponseScoped};
17
+ }
18
+ function notifyConversationSync(){
19
+ window.dispatchEvent(new CustomEvent('execweave:conversation-sync'));
20
+ }
21
+ function ensureConversationScope(){
22
+ const next=JSON.stringify(conversationScope());
23
+ if(conversationScopeKey===null){conversationScopeKey=next;return}
24
+ if(next===conversationScopeKey)return;
25
+ conversationScopeKey=next;conversationSyncGeneration++;
26
+ conversationRefreshController?.abort();conversationRefreshController=null;
27
+ refreshing=false;conversationPollingFinished=false;conversationFinishSynchronized=false;
28
+ conversationFinishing=false;conversationResponseScoped=false;
29
+ conversationRefreshPromise=Promise.resolve(false);conversationFinishPromise=Promise.resolve(false);
30
+ document.getElementById('conversation-sync-status')?.remove();setEntries([]);
31
+ if(!window.__execweaveStaticMode&&conversationRefreshTimer===null){
32
+ conversationRefreshTimer=setInterval(()=>{if(selectedNode&&!conversationFinishing&&!conversationPollingFinished)refresh()},800);
33
+ }
34
+ notifyConversationSync();
35
+ }
36
+ function publishConversationIndex(payload){
37
+ try{setEntries(payload.entries);if(payload.investigation!==undefined)window.__execweaveInvestigation?.setIndex(payload.investigation);return true}catch(_){return false}
38
+ }
39
+ async function refresh({allowDuringFinish=false,includeInvestigation=false}={}){
40
+ ensureConversationScope();
41
+ if(window.__execweaveStaticMode||(conversationPollingFinished&&!allowDuringFinish)||
42
+ (conversationFinishing&&!allowDuringFinish))return false;
43
+ if(refreshing){
44
+ const epoch=conversationSyncGeneration,scope=conversationScopeKey,pending=conversationRefreshPromise;
45
+ const result=await pending;
46
+ if(includeInvestigation&&epoch===conversationSyncGeneration&&scope===JSON.stringify(conversationScope()))
47
+ return refresh({allowDuringFinish,includeInvestigation:true});
48
+ return result;
49
+ }
50
+ refreshing=true;const epoch=conversationSyncGeneration,scope=conversationScopeKey;
51
+ const controller=new AbortController();conversationRefreshController=controller;
52
+ const timeout=setTimeout(()=>controller.abort(),5000);
53
+ const task=(async()=>{try{
54
+ const headers={};if(window.__execweaveToken)headers['X-ExecWeave-Token']=window.__execweaveToken;
55
+ const response=includeInvestigation?
56
+ await fetch('/conversations.json?investigation=1',{cache:'no-store',headers,signal:controller.signal}):
57
+ await fetch('/conversations.json',{cache:'no-store',headers,signal:controller.signal});
58
+ if(!response.ok)return false;
59
+ if(response.status!==undefined&&response.status!==200)return false;
60
+ const payload=await response.json();
61
+ if(controller.signal.aborted||epoch!==conversationSyncGeneration||scope!==JSON.stringify(conversationScope()))return false;
62
+ if(!Array.isArray(payload?.entries)||payload.entries.some(e=>!e||typeof e!=='object'||Array.isArray(e)))return false;
63
+ const session=conversationScope().session_id;
64
+ if(payload.session_id!==undefined&&payload.session_id!==session)return false;
65
+ if(payload.source_path!==undefined&&(payload.source_path||null)!==conversationScope().source_path)return false;
66
+ conversationResponseScoped=typeof session==='string'&&payload.session_id===session;
67
+ return publishConversationIndex(payload);
68
+ }catch(_){return false}finally{
69
+ clearTimeout(timeout);
70
+ if(conversationRefreshController===controller){conversationRefreshController=null;refreshing=false}
71
+ }})();conversationRefreshPromise=task;return await task;
72
+ }
73
+ """.strip()
74
+
75
+ SYNC_LIFECYCLE_JS = r"""
76
+ function reportFinalConversationSync(ok){
77
+ let notice=document.getElementById('conversation-sync-status');
78
+ if(ok){notice?.remove();return}if(notice)return;
79
+ notice=document.createElement('div');notice.id='conversation-sync-status';notice.setAttribute('role','status');
80
+ notice.style.cssText='position:fixed;right:18px;bottom:18px;z-index:100;max-width:360px;padding:12px;background:#2b2118;color:#fff;border:1px solid #e5ad63;border-radius:8px';
81
+ notice.append(document.createTextNode('Conversation history may be incomplete. Final synchronization failed. '));
82
+ const retry=document.createElement('button');retry.type='button';retry.textContent='Retry sync';
83
+ retry.onclick=async()=>{retry.disabled=true;try{await finishConversationPolling()}finally{retry.disabled=false}};
84
+ notice.append(retry);document.body.append(notice);
85
+ }
86
+ async function finishConversationPolling(){
87
+ ensureConversationScope();
88
+ if(conversationPollingFinished&&conversationFinishSynchronized)return true;
89
+ if(conversationFinishing)return conversationFinishPromise;
90
+ const epoch=conversationSyncGeneration,scope=conversationScopeKey;
91
+ conversationFinishing=true;notifyConversationSync();
92
+ if(conversationRefreshTimer!==null){clearInterval(conversationRefreshTimer);conversationRefreshTimer=null}
93
+ conversationFinishPromise=(async()=>{
94
+ await conversationRefreshPromise;
95
+ if(epoch!==conversationSyncGeneration||scope!==JSON.stringify(conversationScope()))return false;
96
+ if(window.__execweaveStaticMode)return true;
97
+ return await refresh({allowDuringFinish:true,includeInvestigation:true});
98
+ })().catch(()=>false).then(synchronized=>{
99
+ if(epoch!==conversationSyncGeneration||scope!==JSON.stringify(conversationScope()))return false;
100
+ conversationFinishSynchronized=Boolean(synchronized);reportFinalConversationSync(conversationFinishSynchronized);
101
+ return conversationFinishSynchronized;
102
+ }).finally(()=>{
103
+ if(epoch!==conversationSyncGeneration||scope!==JSON.stringify(conversationScope()))return;
104
+ conversationPollingFinished=true;conversationFinishing=false;
105
+ if(conversationRefreshController!==null){conversationRefreshController.abort();conversationRefreshController=null}
106
+ notifyConversationSync();
107
+ });return await conversationFinishPromise;
108
+ }
109
+ const stopConversationPolling=finishConversationPolling;
110
+ const previous=window.__execweaveDashboard||{};
111
+ window.__execweaveDashboard={...previous,
112
+ onPayload(data){previous.onPayload?.(data);ensureConversationScope();if(selectedNode&&!data?.live_finished&&!conversationFinishing&&!conversationPollingFinished)refresh()},
113
+ onFinished(){previous.onFinished?.();void finishConversationPolling()}
114
+ };
115
+ """.strip()
@@ -0,0 +1,405 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+
6
+ # How many nodes of one foldable type stay drawn before the older ones collapse.
7
+ # Twelve is a starting point, not a measurement: the runs this was built against
8
+ # touch a handful of files. A deployment that writes hundreds will want its own
9
+ # number, so the value is a setting rather than a constant.
10
+ DEFAULT_FOLD_BUDGET = 12
11
+ FOLD_BUDGET_ENV = "EXECWEAVE_FOLD_BUDGET"
12
+
13
+
14
+ def resolve_fold_budget(raw: str | None = None) -> int:
15
+ """Read the budget a run was started with, falling back to the default.
16
+
17
+ The command line validates its own value and refuses a bad one there, where the
18
+ user can see it. This function is called while rendering, often at the end of a
19
+ long run, so an unusable environment value falls back rather than costing the
20
+ reader the viewer.
21
+ """
22
+ value = os.environ.get(FOLD_BUDGET_ENV) if raw is None else raw
23
+ if value is None:
24
+ return DEFAULT_FOLD_BUDGET
25
+ try:
26
+ budget = int(str(value).strip())
27
+ except ValueError:
28
+ return DEFAULT_FOLD_BUDGET
29
+ return budget if budget >= 1 else DEFAULT_FOLD_BUDGET
30
+
31
+
32
+ def fold_budget_option(value: str) -> int:
33
+ """Parse --fold-budget, refusing a value the reader would not understand."""
34
+ try:
35
+ budget = int(str(value).strip())
36
+ except ValueError:
37
+ raise argparse.ArgumentTypeError(
38
+ f"fold budget must be a whole number, not {value!r}"
39
+ ) from None
40
+ if budget < 1:
41
+ raise argparse.ArgumentTypeError(
42
+ f"fold budget must be at least 1, not {budget}; a large value effectively "
43
+ "turns folding off"
44
+ )
45
+ return budget
46
+
47
+
48
+ def add_fold_budget_argument(parser: argparse.ArgumentParser) -> None:
49
+ """Offer the budget on any command that renders a dashboard."""
50
+ parser.add_argument(
51
+ "--fold-budget",
52
+ type=fold_budget_option,
53
+ default=None,
54
+ metavar="N",
55
+ help=(
56
+ "How many nodes of one crowded type stay drawn before the older ones "
57
+ f"collapse into a single node that still lists them (default: "
58
+ f"{DEFAULT_FOLD_BUDGET}). Set it high to effectively turn folding off. "
59
+ f"Also readable from {FOLD_BUDGET_ENV}."
60
+ ),
61
+ )
62
+
63
+
64
+ def apply_fold_budget(budget: int | None) -> None:
65
+ """Publish the chosen budget so every renderer in this run agrees on it.
66
+
67
+ The value travels in the environment rather than through each render call: a run
68
+ resolves one budget, the renderers are reached from several entry points, and top
69
+ launches the live server as a child process that has to agree with its parent.
70
+ """
71
+ if budget is not None:
72
+ os.environ[FOLD_BUDGET_ENV] = str(int(budget))
73
+
74
+
75
+ def fold_budget_bootstrap(budget: int | None = None) -> str:
76
+ """The one statement a rendered page needs so its fold budget is the run's."""
77
+ resolved = resolve_fold_budget() if budget is None else budget
78
+ return f"window.__execweaveFoldBudget={int(resolved)};"
79
+
80
+
81
+ _DASHBOARD_JS = r"""
82
+ function execweaveDashboardGraph(data){
83
+ const allNodes=Array.isArray(data?.nodes)?data.nodes:[],allEdges=Array.isArray(data?.edges)?data.edges:[];
84
+ const allById=new Map(allNodes.filter(node=>node&&node.id).map(node=>[node.id,node]));
85
+ const hiddenTypes=new Set(['agent_execution','observed_content','tool_call','agent_turn','tool_call_observation','conversation_item','provider_session','permission_request','context_compaction','agent_turn_stop','compaction','compaction_request','terminal_operation']);
86
+ const hiddenDetailIds=new Set(allNodes.filter(node=>node&&hiddenTypes.has(String(node.type||''))).map(node=>node.id).filter(Boolean));
87
+ const internalStaging=node=>{
88
+ const type=String(node?.type||'');
89
+ if(type!=='file'&&type!=='directory')return false;
90
+ const attrs=node?.attributes||{},values=[node?.id,node?.name,attrs.path,attrs.file_path,attrs.source_path,attrs.target_path,attrs.real_path];
91
+ return values.some(value=>{
92
+ const path=String(value||'');
93
+ return /(^|[\\/])\.execweave-content-[^\\/]+$/.test(path)||
94
+ /(^|[\\/])\.execweave[\\/](?:runs|traces)(?:[\\/]|$)/.test(path)||
95
+ /(^|[\\/])\.execweave[\\/]\.gitignore$/.test(path);
96
+ });
97
+ };
98
+ const internalStagingIds=new Set(allNodes.filter(node=>node&&internalStaging(node)).map(node=>node.id).filter(Boolean));
99
+ const hiddenIds=new Set([...hiddenDetailIds,...internalStagingIds]);
100
+ const incoming=new Map(),outgoing=new Map();
101
+ for(const edge of allEdges){
102
+ if(!edge)continue;
103
+ if(!incoming.has(edge.target))incoming.set(edge.target,[]);
104
+ if(!outgoing.has(edge.source))outgoing.set(edge.source,[]);
105
+ incoming.get(edge.target).push(edge);outgoing.get(edge.source).push(edge);
106
+ }
107
+ const fileDisplayMode=String(globalThis.__execweaveFileDisplayMode||'changed');
108
+ const fileTypes=new Set(['file','directory']);
109
+ const fileMutationEvents=new Set(['filesystem.created','filesystem.modified','filesystem.moved','filesystem.deleted']);
110
+ const fileMutationRelation=relation=>/(^|_)(WROTE|WRITE|WRITES|CREATE|CREATED|UPDATE|UPDATED|EDIT|EDITED|DELETE|DELETED|MOVE|MOVED|RENAME|RENAMED|PATCH|REPLACE|REPLACED|SAVE|SAVED|MODIFY|MODIFIED)($|_)/.test(String(relation||'').toUpperCase());
111
+ const fileReadRelation=relation=>/(^|_)(READ|OPEN|SCAN|LIST|STAT|INSPECT|OBSERVE|OBSERVED)($|_)/.test(String(relation||'').toUpperCase());
112
+ const fileActivity=node=>{
113
+ if(!fileTypes.has(String(node?.type||'')))return'other';
114
+ const eventTypes=Array.isArray(node?.event_types)?node.event_types:[];
115
+ const related=[...(incoming.get(node.id)||[]),...(outgoing.get(node.id)||[])];
116
+ const relatedEventTypes=related.flatMap(edge=>Array.isArray(edge?.event_types)?edge.event_types:[]);
117
+ const allEventTypes=[...eventTypes,...relatedEventTypes].map(String);
118
+ if(allEventTypes.some(value=>fileMutationEvents.has(value)))return'changed';
119
+ if(related.some(edge=>fileMutationRelation(edge?.relation)))return'changed';
120
+ const observedEvents=allEventTypes.some(value=>value.startsWith('filesystem.'));
121
+ if(observedEvents||related.some(edge=>fileReadRelation(edge?.relation)))return'observed';
122
+ return'unknown';
123
+ };
124
+ const fileVisible=node=>{const activity=fileActivity(node);if(activity==='other')return true;if(fileDisplayMode==='hide')return false;if(fileDisplayMode==='all')return true;return activity!=='observed'};
125
+ const provider=node=>String(node?.attributes?.provider||'unknown').toLowerCase();
126
+ const toolName=node=>String(node?.attributes?.tool_name||node?.attributes?.native_name||node?.name||'tool');
127
+ const toolKey=node=>`${provider(node)}\u0000${toolName(node).trim().toLowerCase()}`;
128
+ const toolNodesByKey=new Map();
129
+ for(const node of allNodes){
130
+ if(node?.type!=='tool'||!node.id)continue;
131
+ const key=toolKey(node);if(!toolNodesByKey.has(key))toolNodesByKey.set(key,[]);toolNodesByKey.get(key).push(node);
132
+ }
133
+ const toolCanonicalId=new Map(),toolRepresentativeByKey=new Map(),toolMembersByRepresentative=new Map();
134
+ for(const [key,members] of toolNodesByKey){
135
+ members.sort((a,b)=>String(a.id).localeCompare(String(b.id)));
136
+ const representative=members[0];toolRepresentativeByKey.set(key,representative.id);toolMembersByRepresentative.set(representative.id,members);
137
+ for(const member of members)toolCanonicalId.set(member.id,representative.id);
138
+ }
139
+ const attrsOf=node=>node&&typeof node.attributes==='object'&&node.attributes?node.attributes:{};
140
+ const callConversation=call=>{
141
+ const attrs=attrsOf(call),direct=attrs.conversation_id||attrs.antigravity_conversation_id||attrs.session_id||attrs.provider_session_id;
142
+ if(direct!==null&&direct!==undefined&&String(direct).trim())return String(direct).trim();
143
+ const match=String(call?.id||'').match(/^tool-call(?:-observation)?:antigravity:([^:]+):/i);
144
+ return match?match[1]:'';
145
+ };
146
+ function ownerFor(call){
147
+ const edges=incoming.get(call.id)||[];
148
+ for(const edge of edges){const source=allById.get(edge.source);if(source?.type==='agent')return edge.source}
149
+ for(const edge of edges){
150
+ const turn=allById.get(edge.source);if(turn?.type!=='agent_turn')continue;
151
+ for(const parent of incoming.get(edge.source)||[]){const source=allById.get(parent.source);if(source?.type==='agent')return parent.source}
152
+ }
153
+ const conversation=callConversation(call);
154
+ if(conversation){
155
+ const exact=`agent:antigravity:conversation:${conversation}`;
156
+ if(allById.has(exact))return exact;
157
+ }
158
+ for(const edge of edges){
159
+ const source=allById.get(edge.source);
160
+ if(source&&!hiddenTypes.has(String(source.type||''))&&source.type!=='tool')return edge.source;
161
+ }
162
+ return null;
163
+ }
164
+ function toolFor(call){
165
+ for(const edge of outgoing.get(call.id)||[]){
166
+ const target=allById.get(edge.target);
167
+ if(target?.type==='tool')return toolCanonicalId.get(target.id)||target.id;
168
+ }
169
+ return toolRepresentativeByKey.get(toolKey(call))||null;
170
+ }
171
+ const seq=(edge,key)=>Number.isInteger(edge?.[key])?edge[key]:null;
172
+ const earlier=(a,b)=>!a?b:!b?a:(String(a)<=String(b)?a:b);
173
+ const later=(a,b)=>!a?b:!b?a:(String(a)>=String(b)?a:b);
174
+ const firstValue=(attrs,keys)=>{for(const key of keys){if(attrs[key]!==undefined&&attrs[key]!==null)return attrs[key]}return null};
175
+ const callIdentity=call=>{
176
+ const attrs=attrsOf(call),native=firstValue(attrs,['tool_use_id','tool_call_id','call_id','provider_call_id','invocation_id']);
177
+ if(native!==null&&String(native).trim())return `${provider(call)}\u0000native\u0000${String(native)}`;
178
+ const conversation=callConversation(call),step=firstValue(attrs,['step_index','antigravity_step_index','stepIdx']);
179
+ if(conversation&&step!==null&&step!==undefined)return `${provider(call)}\u0000conversation-step\u0000${conversation}\u0000${step}\u0000${toolName(call).toLowerCase()}`;
180
+ return `${provider(call)}\u0000id\u0000${call.id}`;
181
+ };
182
+ const adjacentContent=call=>{
183
+ const rows=[];
184
+ for(const edge of [...(incoming.get(call.id)||[]),...(outgoing.get(call.id)||[])]){
185
+ const otherId=edge.source===call.id?edge.target:edge.source,other=allById.get(otherId);
186
+ if(other?.type!=='observed_content')continue;
187
+ const attrs=attrsOf(other);
188
+ rows.push({relation:edge.relation||null,content_kind:attrs.content_kind||other.name||null,sha256:attrs.sha256||attrs.content_sha256||null,path:attrs.path||attrs.content_path||null,size_bytes:attrs.size_bytes??attrs.content_size_bytes??null,media_type:attrs.media_type||attrs.content_media_type||null});
189
+ }
190
+ return rows;
191
+ };
192
+ const toolCallToTool=new Map(),invocationMap=new Map();
193
+ for(const call of allNodes){
194
+ if(!['tool_call','tool_call_observation'].includes(String(call?.type||''))||!call.id)continue;
195
+ const owner=ownerFor(call),tool=toolFor(call);if(!owner||!tool)continue;
196
+ toolCallToTool.set(call.id,tool);
197
+ const key=`${owner}\u0000${tool}\u0000${callIdentity(call)}`,attrs=attrsOf(call),evidence=[...(incoming.get(call.id)||[]),...(outgoing.get(call.id)||[])];
198
+ let occurrence=invocationMap.get(key);
199
+ if(!occurrence){
200
+ occurrence={invocation_id:callIdentity(call),owner_id:owner,tool_id:tool,call_ids:[],first_sequence:null,last_sequence:null,first_seen:call.first_seen||null,last_seen:call.last_seen||null,input:null,output:null,content_references:[]};
201
+ invocationMap.set(key,occurrence);
202
+ }
203
+ if(!occurrence.call_ids.includes(call.id))occurrence.call_ids.push(call.id);
204
+ occurrence.first_seen=earlier(occurrence.first_seen,call.first_seen);occurrence.last_seen=later(occurrence.last_seen,call.last_seen);
205
+ if(occurrence.input===null)occurrence.input=firstValue(attrs,['arguments','args','tool_input','input','parameters','request']);
206
+ if(occurrence.output===null)occurrence.output=firstValue(attrs,['output','result','tool_output','response']);
207
+ for(const edge of evidence){
208
+ const first=seq(edge,'first_sequence'),last=seq(edge,'last_sequence');
209
+ if(first!==null)occurrence.first_sequence=occurrence.first_sequence===null?first:Math.min(occurrence.first_sequence,first);
210
+ if(last!==null)occurrence.last_sequence=occurrence.last_sequence===null?last:Math.max(occurrence.last_sequence,last);
211
+ occurrence.first_seen=earlier(occurrence.first_seen,edge.first_seen);occurrence.last_seen=later(occurrence.last_seen,edge.last_seen);
212
+ }
213
+ for(const ref of adjacentContent(call))if(!occurrence.content_references.some(item=>JSON.stringify(item)===JSON.stringify(ref)))occurrence.content_references.push(ref);
214
+ }
215
+ const groups=new Map(),toolOccurrences=new Map();
216
+ for(const occurrence of invocationMap.values()){
217
+ const key=`${occurrence.owner_id}\u0000${occurrence.tool_id}`;
218
+ let group=groups.get(key);if(!group){group={owner:occurrence.owner_id,tool:occurrence.tool_id,count:0,first_sequence:null,last_sequence:null,first_seen:null,last_seen:null,occurrences:[]};groups.set(key,group)}
219
+ group.occurrences.push(occurrence);group.count+=1;
220
+ if(occurrence.first_sequence!==null)group.first_sequence=group.first_sequence===null?occurrence.first_sequence:Math.min(group.first_sequence,occurrence.first_sequence);
221
+ if(occurrence.last_sequence!==null)group.last_sequence=group.last_sequence===null?occurrence.last_sequence:Math.max(group.last_sequence,occurrence.last_sequence);
222
+ group.first_seen=earlier(group.first_seen,occurrence.first_seen);group.last_seen=later(group.last_seen,occurrence.last_seen);
223
+ if(!toolOccurrences.has(occurrence.tool_id))toolOccurrences.set(occurrence.tool_id,[]);toolOccurrences.get(occurrence.tool_id).push(occurrence);
224
+ }
225
+ const occurrenceOrder=(a,b)=>{
226
+ if(a.first_sequence!==null&&b.first_sequence!==null&&a.first_sequence!==b.first_sequence)return a.first_sequence-b.first_sequence;
227
+ const byTime=String(a.first_seen||'').localeCompare(String(b.first_seen||''));return byTime||String(a.invocation_id).localeCompare(String(b.invocation_id));
228
+ };
229
+ for(const group of groups.values())group.occurrences.sort(occurrenceOrder);
230
+ for(const list of toolOccurrences.values())list.sort(occurrenceOrder);
231
+ const candidateNodes=allNodes.filter(node=>node&&node.id&&!hiddenIds.has(node.id)).filter(node=>node.type!=='tool'||toolCanonicalId.get(node.id)===node.id);
232
+ const hiddenFileObservationCount=candidateNodes.filter(node=>fileTypes.has(String(node?.type||''))&&!fileVisible(node)).length;
233
+ let visibleNodes=candidateNodes.filter(node=>fileVisible(node)).map(node=>{
234
+ if(fileTypes.has(String(node?.type||'')))return{...node,attributes:{...attrsOf(node),viewer_file_activity:fileActivity(node)}};
235
+ if(node.type!=='tool')return node;
236
+ const occurrences=toolOccurrences.get(node.id)||[],members=toolMembersByRepresentative.get(node.id)||[node];
237
+ if(!occurrences.length&&members.length===1)return node;
238
+ const firstSeen=members.reduce((value,item)=>earlier(value,item.first_seen),node.first_seen||null),lastSeen=members.reduce((value,item)=>later(value,item.last_seen),node.last_seen||null);
239
+ return{...node,first_seen:firstSeen||node.first_seen,last_seen:lastSeen||node.last_seen,attributes:{...(node.attributes||{}),viewer_canonicalized:members.length>1||undefined,viewer_occurrence_count:occurrences.length,viewer_occurrence_ids:occurrences.map(item=>item.invocation_id),viewer_occurrences:occurrences,viewer_tool_call_occurrences:occurrences,viewer_aggregated_tool_call_count:occurrences.length,viewer_tool_entity_ids:members.map(item=>item.id)}};
240
+ });
241
+
242
+ const canonicalTypes=new Set(['process','file']);
243
+ const foldableTypes=new Set(['process','file','directory','network_endpoint']);
244
+ const foldType=node=>{const type=String(node?.type||'');return type==='file'||type==='directory'?'filesystem':type};
245
+ const declaredBudget=Number(globalThis.__execweaveFoldBudget);
246
+ const FOLD_BUDGET=Number.isFinite(declaredBudget)&&declaredBudget>=1?Math.floor(declaredBudget):12;
247
+ const canonicalGroups=new Map();
248
+ const canonicalKey=node=>{
249
+ const type=String(node?.type||'');
250
+ if(!canonicalTypes.has(type))return `id\u0000${node.id}`;
251
+ const name=String(node?.name||'').trim().toLowerCase();
252
+ return name?`${type}\u0000${name}`:`id\u0000${node.id}`;
253
+ };
254
+ for(const node of visibleNodes){const key=canonicalKey(node);if(!canonicalGroups.has(key))canonicalGroups.set(key,[]);canonicalGroups.get(key).push(node)}
255
+ const canonicalId=new Map(toolCanonicalId);
256
+ const nodes=[];
257
+ let canonicalizedProcessOccurrenceCount=0;
258
+ for(const group of canonicalGroups.values()){
259
+ group.sort((a,b)=>String(a.first_seen||'').localeCompare(String(b.first_seen||''))||String(a.id).localeCompare(String(b.id)));
260
+ const base=group[0];
261
+ for(const item of group)canonicalId.set(item.id,base.id);
262
+ if(group.length===1){nodes.push(base);continue}
263
+ canonicalizedProcessOccurrenceCount+=group.length-1;
264
+ const occurrenceRows=group.map(item=>{
265
+ const attrs=item.attributes||{};
266
+ return{id:item.id,first_seen:item.first_seen||null,last_seen:item.last_seen||null,pid:attrs.pid??attrs.process_id??null,ppid:attrs.ppid??attrs.parent_pid??null};
267
+ });
268
+ const pids=[...new Set(occurrenceRows.map(item=>item.pid).filter(value=>value!==null&&value!==undefined))];
269
+ const ppids=[...new Set(occurrenceRows.map(item=>item.ppid).filter(value=>value!==null&&value!==undefined))];
270
+ const firstSeen=group.reduce((value,item)=>earlier(value,item.first_seen),null),lastSeen=group.reduce((value,item)=>later(value,item.last_seen),null);
271
+ nodes.push({...base,first_seen:firstSeen||base.first_seen,last_seen:lastSeen||base.last_seen,attributes:{...(base.attributes||{}),viewer_canonicalized:true,viewer_occurrence_count:group.length,viewer_occurrence_ids:group.map(item=>item.id),viewer_occurrences:occurrenceRows,viewer_pids:pids,viewer_ppids:ppids}});
272
+ }
273
+
274
+ let foldedNodeCount=0;
275
+ const byType=new Map();
276
+ for(const node of nodes){const rawType=String(node?.type||'');if(!foldableTypes.has(rawType))continue;const type=foldType(node);if(!byType.has(type))byType.set(type,[]);byType.get(type).push(node)}
277
+ const folds=[];
278
+ for(const[type,members]of byType){
279
+ if(members.length<=FOLD_BUDGET)continue;
280
+ const recency=node=>String(node?.last_seen||node?.first_seen||'');
281
+ const ordered=[...members].sort((a,b)=>recency(b).localeCompare(recency(a)));
282
+ const older=ordered.slice(FOLD_BUDGET);if(!older.length)continue;
283
+ const removeIds=new Set(older.map(node=>node.id));
284
+ const foldId=`viewer:folded:${type}`;
285
+ for(const node of older)canonicalId.set(node.id,foldId);
286
+ foldedNodeCount+=older.length;
287
+ const foldedType=type==='filesystem'?'file_cluster':type,foldedName=type==='filesystem'?`${older.length} earlier files / directories`:`${older.length} earlier ${type.replace(/_/g,' ')}${older.length===1?'':'s'}`;
288
+ const activities=[...new Set(older.map(node=>node?.attributes?.viewer_file_activity).filter(Boolean))];
289
+ folds.push({id:foldId,type:foldedType,name:foldedName,first_seen:older.reduce((value,node)=>earlier(value,node.first_seen),null),last_seen:older.reduce((value,node)=>later(value,node.last_seen),null),attributes:{viewer_folded:true,viewer_folded_type:type,viewer_folded_count:older.length,viewer_file_activity:type==='filesystem'?(activities.length===1?activities[0]:'mixed'):undefined,viewer_folded_members:older.map(node=>({id:node.id,type:node.type,name:node.name||node.id,activity:node?.attributes?.viewer_file_activity||null,first_seen:node.first_seen||null,last_seen:node.last_seen||null}))}});
290
+ for(let index=nodes.length-1;index>=0;index--)if(removeIds.has(nodes[index].id))nodes.splice(index,1);
291
+ }
292
+ nodes.push(...folds);
293
+
294
+ let nodeIds=new Set(nodes.map(node=>node.id));
295
+ let edges=allEdges.map(edge=>{
296
+ if(!edge)return null;
297
+ const declaredTool=edge.relation==='DECLARED_TARGET'?toolCallToTool.get(edge.source):null;
298
+ const rawSource=declaredTool||edge.source;
299
+ const source=canonicalId.get(rawSource)||rawSource,target=canonicalId.get(edge.target)||edge.target;
300
+ if(!nodeIds.has(source)||!nodeIds.has(target))return null;
301
+ if(source===edge.source&&target===edge.target)return edge;
302
+ return{...edge,source,target,viewer_canonicalized:true,viewer_original_source:edge.source,viewer_original_target:edge.target,viewer_reanchored_from_tool_call:rawSource!==edge.source||undefined};
303
+ }).filter(Boolean);
304
+ for(const group of groups.values()){
305
+ const owner=canonicalId.get(group.owner)||group.owner,tool=canonicalId.get(group.tool)||group.tool;
306
+ if(!nodeIds.has(owner)||!nodeIds.has(tool))continue;
307
+ edges.push({id:`viewer:${owner}--CALLED_TOOL-->${tool}`,source:owner,target:tool,relation:'CALLED_TOOL',count:group.count,first_sequence:group.first_sequence,last_sequence:group.last_sequence,first_seen:group.first_seen,last_seen:group.last_seen,causal:null,inferred:false,viewer_only:true,attributions:['viewer_tool_call_aggregation'],evidence_call_count:group.count,viewer_tool_call_occurrences:group.occurrences});
308
+ }
309
+ const incident=new Set();for(const edge of edges){incident.add(edge.source);incident.add(edge.target)}
310
+ visibleNodes=nodes.filter(node=>node.type!=='tool'||incident.has(node.id));
311
+ nodeIds=new Set(visibleNodes.map(node=>node.id));edges=edges.filter(edge=>nodeIds.has(edge.source)&&nodeIds.has(edge.target));
312
+ return{...data,nodes:visibleNodes,edges,node_count:visibleNodes.length,edge_count:edges.length,dashboard_projection:{hidden_detail_node_count:hiddenDetailIds.size,hidden_internal_staging_node_count:internalStagingIds.size,canonicalized_process_occurrence_count:canonicalizedProcessOccurrenceCount,canonicalized_tool_entity_count:[...toolMembersByRepresentative.values()].reduce((sum,members)=>sum+Math.max(0,members.length-1),0),folded_node_count:foldedNodeCount,collapsed_tool_call_count:invocationMap.size,raw_tool_call_detail_count:allNodes.filter(node=>['tool_call','tool_call_observation'].includes(String(node?.type||''))).length,file_display_mode:fileDisplayMode,hidden_file_observation_node_count:hiddenFileObservationCount}};
313
+ }
314
+ """.strip()
315
+
316
+ _STATIC_MATERIALIZED = """function materializedGraph(){
317
+ const hiddenClusterEdges=new Set();
318
+ expandedClusters.forEach(id=>{const entry=expansionClusters[id];if(entry&&entry.cluster_edge_id)hiddenClusterEdges.add(entry.cluster_edge_id)});
319
+ let nodes=baseNodes.filter(node=>!expandedClusters.has(node.id));
320
+ let edges=baseEdges.filter(edge=>!hiddenClusterEdges.has(edge.id));
321
+ expandedClusters.forEach(id=>{const entry=expansionClusters[id];if(!entry)return;nodes=nodes.concat(entry.nodes||[]);edges=edges.concat(entry.edges||[])});
322
+ return{nodes:uniqueById(nodes),edges:uniqueById(edges)};
323
+ }"""
324
+
325
+ _STATIC_MATERIALIZED_CLEAN = """function materializedGraph(){
326
+ const hiddenClusterEdges=new Set();
327
+ expandedClusters.forEach(id=>{const entry=expansionClusters[id];if(entry&&entry.cluster_edge_id)hiddenClusterEdges.add(entry.cluster_edge_id)});
328
+ let nodes=baseNodes.filter(node=>!expandedClusters.has(node.id));
329
+ let edges=baseEdges.filter(edge=>!hiddenClusterEdges.has(edge.id));
330
+ expandedClusters.forEach(id=>{const entry=expansionClusters[id];if(!entry)return;nodes=nodes.concat(entry.nodes||[]);edges=edges.concat(entry.edges||[])});
331
+ return execweaveDashboardGraph({nodes:uniqueById(nodes),edges:uniqueById(edges)});
332
+ }"""
333
+
334
+ _STATIC_TYPE_OPTIONS = "[...new Set(possibleNodes.map(n=>n.type).filter(Boolean))].sort().forEach(v=>option(typeFilter,v));\n[...new Set(possibleEdges.map(e=>e.relation).filter(Boolean))].sort().forEach(v=>option(relationFilter,v));"
335
+ _STATIC_TYPE_OPTIONS_CLEAN = "const execweavePossibleGraph=execweaveDashboardGraph({nodes:possibleNodes,edges:possibleEdges});\n[...new Set(execweavePossibleGraph.nodes.map(n=>n.type).filter(Boolean))].sort().forEach(v=>option(typeFilter,v));\n[...new Set(execweavePossibleGraph.edges.map(e=>e.relation).filter(Boolean))].sort().forEach(v=>option(relationFilter,v));"
336
+
337
+ _LIVE_SET_SNAPSHOT_CLEAN = "function setSnapshot(data){const signature=`${data.node_count||0}:${data.edge_count||0}`;lastSignature=signature;graph=data;const display=execweaveDashboardGraph(data);nodeById=new Map((display.nodes||[]).map(n=>[n.id,n]));edgeById=new Map((display.edges||[]).map(e=>[edgeId(e),e]));rebuildAdjacency();updateStats({...data,node_count:display.node_count,edge_count:display.edge_count});if(!withinRenderBudget(display)){enterProtectiveMode(display);return}renderSnapshot();seedActivities();const sortedEdges=[...edgeById.values()].sort((a,b)=>String(a.last_seen||'').localeCompare(String(b.last_seen||''))),sortedNodes=[...nodeById.values()].sort((a,b)=>String(a.last_seen||'').localeCompare(String(b.last_seen||''))),lastEdge=sortedEdges.length?sortedEdges[sortedEdges.length-1]:null,lastNode=sortedNodes.length?sortedNodes[sortedNodes.length-1]:null;markLatest(lastEdge?.target||lastNode?.id||null,lastEdge?edgeId(lastEdge):null);if(!hasFitted&&positions.size){fit(false);hasFitted=true}else scheduleCamera(true)}"
338
+
339
+ _LIVE_APPLY_DELTA_CLEAN = "function applyDelta(update){if(update.live_payload_compact){updateStats(update);enterProtectiveMode(update);return}const rawNodes=new Map((graph.nodes||[]).map(n=>[n.id,n])),rawEdges=new Map((graph.edges||[]).map(e=>[edgeId(e),e]));for(const node of [...(update.nodes_added||[]),...(update.nodes_updated||[])])if(node?.id)rawNodes.set(node.id,node);for(const edge of [...(update.edges_added||[]),...(update.edges_updated||[])])rawEdges.set(edgeId(edge),edge);graph={...graph,event_count:update.event_count,node_count:update.node_count,edge_count:update.edge_count,nodes:[...rawNodes.values()],edges:[...rawEdges.values()]};const display=execweaveDashboardGraph(graph);updateStats({...update,node_count:display.node_count,edge_count:display.edge_count});if(!withinRenderBudget(display)){enterProtectiveMode(display);return}if(protectedMode)leaveProtectiveMode();nodeById=new Map((display.nodes||[]).map(n=>[n.id,n]));edgeById=new Map((display.edges||[]).map(e=>[edgeId(e),e]));rebuildAdjacency();renderSnapshot();seedActivities();const sortedEdges=[...edgeById.values()].sort((a,b)=>String(a.last_seen||'').localeCompare(String(b.last_seen||''))),sortedNodes=[...nodeById.values()].sort((a,b)=>String(a.last_seen||'').localeCompare(String(b.last_seen||''))),lastEdge=sortedEdges.length?sortedEdges[sortedEdges.length-1]:null,lastNode=sortedNodes.length?sortedNodes[sortedNodes.length-1]:null;markLatest(lastEdge?.target||lastNode?.id||null,lastEdge?edgeId(lastEdge):null);scheduleCamera(false);if(!hasFitted&&positions.size){fit(false);hasFitted=true}}"
340
+
341
+ _LIVE_CORE_EXPORT = "window.__execweaveCore={getActivities:()=>activities.slice(),getGraph:()=>graph,getPositions:()=>new Map(positions),selectEdge,selectNode,focusNode,markLatest,setCameraMode};"
342
+ _LIVE_CORE_EXPORT_CLEAN = "const execweaveFileGraphFilter=document.getElementById('file-graph-filter');globalThis.__execweaveFileDisplayMode=execweaveFileGraphFilter?.value||'changed';if(execweaveFileGraphFilter)execweaveFileGraphFilter.addEventListener('change',()=>{globalThis.__execweaveFileDisplayMode=execweaveFileGraphFilter.value||'changed';setSnapshot(graph)});window.__execweaveCore={getActivities:()=>activities.slice(),getGraph:()=>graph,getDisplayGraph:()=>({...graph,nodes:[...nodeById.values()],edges:[...edgeById.values()],node_count:nodeById.size,edge_count:edgeById.size}),getPositions:()=>new Map(positions),selectEdge,selectNode,focusNode,markLatest,setCameraMode};"
343
+
344
+ _LIVE_NOOP_STATS = "else if(data.kind==='noop'){liveSequence=Number(data.sequence)||liveSequence;updateStats(data);}"
345
+ _LIVE_NOOP_STATS_CLEAN = "else if(data.kind==='noop'){liveSequence=Number(data.sequence)||liveSequence;updateStats(protectedMode?data:{...data,node_count:nodeById.size,edge_count:edgeById.size});}"
346
+
347
+
348
+ def _replace_function(html: str, start: str, following: str, replacement: str) -> str:
349
+ begin = html.find(start)
350
+ if begin < 0:
351
+ return html
352
+ end = html.find(following, begin)
353
+ if end < 0:
354
+ return html
355
+ return html[:begin] + replacement + html[end:]
356
+
357
+
358
+ def inject_standalone_dashboard_clean(html: str) -> str:
359
+ """Keep full evidence embedded while simplifying only the SVG canvas graph."""
360
+ marker = "function uniqueById(values){"
361
+ if "function execweaveDashboardGraph(data){" not in html and marker in html:
362
+ html = html.replace(marker, _DASHBOARD_JS + "\n" + marker, 1)
363
+ html = html.replace(_STATIC_MATERIALIZED, _STATIC_MATERIALIZED_CLEAN, 1)
364
+ html = html.replace(_STATIC_TYPE_OPTIONS, _STATIC_TYPE_OPTIONS_CLEAN, 1)
365
+ return html.replace("execweavePreferAgentView();", "", 1)
366
+
367
+
368
+ def inject_live_dashboard_clean(html: str) -> str:
369
+ """Simplify only the browser canvas; the live JSON protocol remains unchanged."""
370
+ control_seam = '<div class="panel-spacer"></div>\n <div class="segmented" aria-label="Camera mode">'
371
+ control = '<div class="panel-spacer"></div>\n <label class="graph-file-filter" title="Choose which file and directory nodes appear in the graph"><span>Files</span><select id="file-graph-filter"><option value="changed" selected>Changed only</option><option value="all">All observed</option><option value="hide">Hidden</option></select></label>\n <div class="segmented" aria-label="Camera mode">'
372
+ if html.count(control_seam) != 1:
373
+ raise RuntimeError("file graph filter control seam changed")
374
+ html = html.replace(control_seam, control, 1)
375
+ marker = "function renderSnapshot(){"
376
+ if "function execweaveDashboardGraph(data){" not in html and marker in html:
377
+ html = html.replace(marker, _DASHBOARD_JS + "\n" + marker, 1)
378
+ html = _replace_function(
379
+ html,
380
+ "function setSnapshot(data){",
381
+ "function mergeById(",
382
+ _LIVE_SET_SNAPSHOT_CLEAN + "\n",
383
+ )
384
+ html = _replace_function(
385
+ html,
386
+ "function applyDelta(update){",
387
+ "function applyTransform(){",
388
+ _LIVE_APPLY_DELTA_CLEAN + "\n",
389
+ )
390
+ # Static viewer deltas rerender the graph, but an incoming upstream node
391
+ # must not vertically re-pack unrelated existing nodes. Preserve their Y
392
+ # coordinates while allowing semantic lane X shifts.
393
+ html = html.replace(
394
+ "if(protectedMode)leaveProtectiveMode();nodeById=new Map((display.nodes||[]).map(n=>[n.id,n]));",
395
+ "if(protectedMode)leaveProtectiveMode();const priorY=new Map([...positions].map(([id,p])=>[id,p.y]));nodeById=new Map((display.nodes||[]).map(n=>[n.id,n]));",
396
+ 1,
397
+ )
398
+ render_marker = "renderSnapshot();seedActivities();const sortedEdges="
399
+ render_replacement = "renderSnapshot();for(const [id,y] of priorY){const p=positions.get(id);if(p&&Number.isFinite(y))p.y=y}if(typeof execweaveSeparateOverlappingNodes==='function')execweaveSeparateOverlappingNodes({spec:positions});for(const [id,p] of positions){const group=nodeElements.get(id);if(group)group.setAttribute('transform',`translate(${p.x} ${p.y})`)}for(const e of edgeById.values())updateEdgeElement(e);seedActivities();const sortedEdges="
400
+ render_index = html.rfind(render_marker)
401
+ if render_index >= 0:
402
+ html = html[:render_index] + html[render_index:].replace(render_marker, render_replacement, 1)
403
+ html = html.replace(_LIVE_CORE_EXPORT, _LIVE_CORE_EXPORT_CLEAN, 1)
404
+ html = html.replace(_LIVE_NOOP_STATS, _LIVE_NOOP_STATS_CLEAN, 1)
405
+ return html