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.
- execweave/__init__.py +3 -0
- execweave/__main__.py +5 -0
- execweave/_conversation_records_core.py +902 -0
- execweave/_dashboard_shell_base.py +148 -0
- execweave/_http_proxy_base.py +565 -0
- execweave/_http_proxy_bounded.py +560 -0
- execweave/_http_proxy_stage.py +509 -0
- execweave/acceptance_output.py +19 -0
- execweave/agent_bootstrap.py +395 -0
- execweave/agent_topology.py +313 -0
- execweave/agent_trace.py +1162 -0
- execweave/agy_preview_sanitize.py +102 -0
- execweave/analysis.py +427 -0
- execweave/anthropic.py +228 -0
- execweave/anthropic_cli.py +171 -0
- execweave/anthropic_full_fidelity.py +385 -0
- execweave/antigravity_adapter.py +112 -0
- execweave/antigravity_adapter_base.py +479 -0
- execweave/antigravity_full_fidelity.py +656 -0
- execweave/antigravity_full_fidelity_base.py +172 -0
- execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
- execweave/antigravity_hook_cli.py +209 -0
- execweave/antigravity_record.py +96 -0
- execweave/antigravity_subagent_linkage.py +449 -0
- execweave/antigravity_trace_capability.py +39 -0
- execweave/auto_specialized.py +547 -0
- execweave/backends.py +102 -0
- execweave/benchmark.py +80 -0
- execweave/claude_adapter.py +517 -0
- execweave/claude_child_transcript.py +314 -0
- execweave/claude_delegation.py +136 -0
- execweave/claude_full_fidelity.py +396 -0
- execweave/claude_hook_cli.py +209 -0
- execweave/claude_hook_contract.py +943 -0
- execweave/claude_model_observer.py +353 -0
- execweave/claude_record.py +106 -0
- execweave/cli.py +629 -0
- execweave/codex_adapter.py +455 -0
- execweave/codex_conversation.py +621 -0
- execweave/codex_full_fidelity.py +287 -0
- execweave/codex_hook_cli.py +301 -0
- execweave/codex_hook_entry.py +207 -0
- execweave/codex_hook_lifecycle.py +363 -0
- execweave/codex_message_diagnostics.py +322 -0
- execweave/codex_message_transport_diagnostics.py +399 -0
- execweave/codex_record.py +199 -0
- execweave/codex_rollout_structures.py +402 -0
- execweave/codex_rollout_trace.py +56 -0
- execweave/codex_rollout_trace_base.py +1509 -0
- execweave/collector.py +768 -0
- execweave/command.py +157 -0
- execweave/command_privacy.py +20 -0
- execweave/content_evidence.py +101 -0
- execweave/content_integrity.py +289 -0
- execweave/content_store.py +273 -0
- execweave/controlled_checks.py +561 -0
- execweave/conversation_archive.py +338 -0
- execweave/conversation_message_identity.py +264 -0
- execweave/conversation_preview.py +66 -0
- execweave/conversation_preview_antigravity.py +32 -0
- execweave/conversation_preview_claude.py +31 -0
- execweave/conversation_preview_codex.py +107 -0
- execweave/conversation_preview_common.py +180 -0
- execweave/conversation_preview_generic.py +188 -0
- execweave/conversation_preview_lines.py +133 -0
- execweave/conversation_preview_transcript.py +121 -0
- execweave/conversation_records.py +349 -0
- execweave/conversation_records_antigravity.py +370 -0
- execweave/conversation_records_codex.py +83 -0
- execweave/conversation_records_common.py +17 -0
- execweave/conversation_records_ollama.py +39 -0
- execweave/correlation.py +818 -0
- execweave/cursor_adapter.py +349 -0
- execweave/cursor_delegation.py +87 -0
- execweave/cursor_delegation_base.py +220 -0
- execweave/cursor_full_fidelity.py +489 -0
- execweave/cursor_hook_cli.py +195 -0
- execweave/cursor_hook_contract.py +439 -0
- execweave/cursor_lifecycle.py +159 -0
- execweave/cursor_record.py +96 -0
- execweave/dashboard_shell.py +283 -0
- execweave/delivery_status.py +94 -0
- execweave/entry.py +98 -0
- execweave/evidence_availability.py +113 -0
- execweave/evidence_grade.py +166 -0
- execweave/fidelity.py +304 -0
- execweave/filesystem.py +327 -0
- execweave/finalization.py +92 -0
- execweave/focus.py +118 -0
- execweave/framework_adapters/__init__.py +34 -0
- execweave/framework_adapters/autogen.py +398 -0
- execweave/framework_adapters/base.py +580 -0
- execweave/framework_adapters/camel.py +270 -0
- execweave/framework_adapters/camel_channel.py +71 -0
- execweave/framework_adapters/metagpt.py +315 -0
- execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
- execweave/framework_adapters/metagpt_recording.py +342 -0
- execweave/framework_adapters/registry.py +90 -0
- execweave/graph.py +590 -0
- execweave/graph_ops.py +472 -0
- execweave/hook_command.py +32 -0
- execweave/hook_delivery.py +32 -0
- execweave/hook_input.py +16 -0
- execweave/http_proxy.py +187 -0
- execweave/http_proxy_cli.py +84 -0
- execweave/inference_gateway.py +476 -0
- execweave/inference_gateway_cli.py +211 -0
- execweave/inference_gateway_full_fidelity.py +613 -0
- execweave/inference_identity.py +76 -0
- execweave/inference_identity_cli.py +60 -0
- execweave/integrity.py +235 -0
- execweave/integrity_cli.py +55 -0
- execweave/investigation_index.py +445 -0
- execweave/litellm_callback.py +211 -0
- execweave/litellm_callback_cli.py +42 -0
- execweave/live.py +445 -0
- execweave/live_core.py +972 -0
- execweave/live_view.py +109 -0
- execweave/live_view_extra_style.py +11 -0
- execweave/live_view_markup.py +29 -0
- execweave/live_view_process_layout.py +650 -0
- execweave/live_view_readability.py +502 -0
- execweave/live_view_script_a.py +59 -0
- execweave/live_view_script_b.py +97 -0
- execweave/live_view_script_c.py +59 -0
- execweave/live_view_script_d.py +40 -0
- execweave/live_view_style.py +34 -0
- execweave/model_runtime.py +560 -0
- execweave/model_runtime_cli.py +265 -0
- execweave/model_runtime_full_fidelity.py +519 -0
- execweave/observation.py +53 -0
- execweave/observation_demo.py +69 -0
- execweave/openai_agents.py +267 -0
- execweave/openai_agents_sdk.py +453 -0
- execweave/openai_compatible.py +239 -0
- execweave/openai_compatible_cli.py +189 -0
- execweave/openai_compatible_full_fidelity.py +438 -0
- execweave/opencode_adapter.py +325 -0
- execweave/opencode_event_contract.py +734 -0
- execweave/opencode_full_fidelity.py +198 -0
- execweave/opencode_hook_cli.py +119 -0
- execweave/opencode_plugin_cli.py +150 -0
- execweave/opencode_record.py +96 -0
- execweave/opencode_task_linkage.py +225 -0
- execweave/overhead_benchmark.py +440 -0
- execweave/privacy.py +84 -0
- execweave/private_io.py +465 -0
- execweave/provider_capability.py +578 -0
- execweave/provider_lifecycle.py +282 -0
- execweave/provider_record.py +290 -0
- execweave/reader_identity.py +13 -0
- execweave/redacted_archive.py +906 -0
- execweave/risk.py +106 -0
- execweave/rule_pack.py +359 -0
- execweave/rule_pack_cli.py +57 -0
- execweave/run_assessment.py +200 -0
- execweave/runtime_endpoint_availability.py +44 -0
- execweave/scalability_benchmark.py +195 -0
- execweave/schema.py +62 -0
- execweave/scope.py +85 -0
- execweave/semantic.py +453 -0
- execweave/session_summary.py +159 -0
- execweave/sink.py +71 -0
- execweave/strace_backend.py +927 -0
- execweave/stream_assembly.py +363 -0
- execweave/task_artifacts.py +192 -0
- execweave/task_validation.py +317 -0
- execweave/theme.py +40 -0
- execweave/top.py +599 -0
- execweave/top_cli.py +150 -0
- execweave/validate.py +196 -0
- execweave/vendor/dagre.min.js +815 -0
- execweave/view_cli.py +49 -0
- execweave/viewer.py +474 -0
- execweave/viewer_agent_panel.py +630 -0
- execweave/viewer_agent_panel_antigravity.py +31 -0
- execweave/viewer_agent_panel_claude.py +9 -0
- execweave/viewer_agent_panel_codex.py +50 -0
- execweave/viewer_agent_panel_cursor.py +9 -0
- execweave/viewer_agent_panel_default.py +79 -0
- execweave/viewer_agent_panel_ollama.py +20 -0
- execweave/viewer_agent_panel_opencode.py +9 -0
- execweave/viewer_agent_panel_registry.py +20 -0
- execweave/viewer_archive_verifier.py +178 -0
- execweave/viewer_background_files.py +86 -0
- execweave/viewer_content_browser.py +307 -0
- execweave/viewer_content_health.py +208 -0
- execweave/viewer_content_inspector.py +309 -0
- execweave/viewer_controlled_checks.py +258 -0
- execweave/viewer_conversation_sync.py +115 -0
- execweave/viewer_dashboard_clean.py +405 -0
- execweave/viewer_dashboard_focus.py +127 -0
- execweave/viewer_dashboard_hardening.py +264 -0
- execweave/viewer_dashboard_hardening_v2.py +62 -0
- execweave/viewer_dashboard_projection.py +261 -0
- execweave/viewer_delivery_status.py +155 -0
- execweave/viewer_edge_decross.py +117 -0
- execweave/viewer_execution_flow.py +611 -0
- execweave/viewer_execution_flow_provider_normalization.py +107 -0
- execweave/viewer_execution_flow_safety.py +349 -0
- execweave/viewer_external_endpoints.py +307 -0
- execweave/viewer_flow_canvas.py +1140 -0
- execweave/viewer_flow_layout.py +922 -0
- execweave/viewer_fold_state.py +31 -0
- execweave/viewer_framework_flow.py +68 -0
- execweave/viewer_framework_model_output.py +133 -0
- execweave/viewer_gif.py +278 -0
- execweave/viewer_history_browser.py +225 -0
- execweave/viewer_investigation.py +268 -0
- execweave/viewer_layout_geometry.py +192 -0
- execweave/viewer_layout_v2.py +429 -0
- execweave/viewer_layout_v2_detached.py +25 -0
- execweave/viewer_limits.py +93 -0
- execweave/viewer_live_layout.py +61 -0
- execweave/viewer_message_handoffs.py +114 -0
- execweave/viewer_projection.py +488 -0
- execweave/viewer_projection_base.py +522 -0
- execweave/viewer_projection_bridges.py +214 -0
- execweave/viewer_recorded_sources.py +146 -0
- execweave/viewer_run_assessment.py +274 -0
- execweave/viewer_run_guide.py +175 -0
- execweave/viewer_runtime_evidence.py +258 -0
- execweave/viewer_semantic_projection.py +641 -0
- execweave/viewer_session_flow.py +491 -0
- execweave/viewer_structure_share.py +132 -0
- execweave/viewer_task_validation.py +241 -0
- execweave/viewer_tool_mirror_identity.py +75 -0
- execweave/viewer_workflow_mode.py +127 -0
- execweave/workflow.py +183 -0
- execweave-1.0.0.dist-info/METADATA +462 -0
- execweave-1.0.0.dist-info/RECORD +234 -0
- execweave-1.0.0.dist-info/WHEEL +4 -0
- execweave-1.0.0.dist-info/entry_points.txt +30 -0
- execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
|
@@ -0,0 +1,922 @@
|
|
|
1
|
+
"""Flow-ordered viewer layout: fold per-event bookkeeping, then layer by execution order.
|
|
2
|
+
|
|
3
|
+
Two things happen here, both provider-neutral. Nothing below reads a provider name, an
|
|
4
|
+
adapter, or an event type; the rules are written against node type, edge direction and
|
|
5
|
+
the relation vocabulary every adapter already emits.
|
|
6
|
+
|
|
7
|
+
**Folding** removes nodes that carry no flow of their own. A content leaf is evidence
|
|
8
|
+
about the entity it hangs off, not a step; a ``tool_call`` is one occurrence of the tool
|
|
9
|
+
that defines it. Every folded node keeps its identity in ``viewer_member_ids`` and its span
|
|
10
|
+
in ``viewer_folded_members``, the same contract the existing endpoint and file clusters
|
|
11
|
+
use, so raw-log inspection, conversation ownership and time ranges all still resolve.
|
|
12
|
+
|
|
13
|
+
A path the OS watcher saw change is not folded, even when no actor touched it. It is a
|
|
14
|
+
change on the user's disk during the run, which is what the reader came to see, and the
|
|
15
|
+
canvas draws it; folding it as well listed the same file both as a box and as a member of
|
|
16
|
+
the session that observed it.
|
|
17
|
+
|
|
18
|
+
**Layering** replaces lane-by-node-type with longest-path layering over the graph itself.
|
|
19
|
+
Because a node's column is one past its furthest predecessor, every edge points right by
|
|
20
|
+
construction: there is no arrangement of a layered DAG that produces a backward edge.
|
|
21
|
+
Feedback edges are reversed before layering so the layering is defined even on a cyclic
|
|
22
|
+
graph. A previously assigned column acts as a floor, which is what keeps a live run from
|
|
23
|
+
ever pulling a node that is already on screen back to the left.
|
|
24
|
+
|
|
25
|
+
Raw evidence is never touched. This is a view over the graph, and the graph is itself a
|
|
26
|
+
materialized view over events.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from collections import Counter, defaultdict, deque
|
|
32
|
+
from copy import deepcopy
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from ._conversation_records_core import _safe_content_reference
|
|
36
|
+
|
|
37
|
+
# A content node is evidence about something else. It has no flow of its own.
|
|
38
|
+
CONTENT_TYPES = frozenset({"observed_content"})
|
|
39
|
+
|
|
40
|
+
# One occurrence of an entity that exists independently of the occurrence. Folding these
|
|
41
|
+
# turns "six calls to list_dir" from six boxes into one box that says six.
|
|
42
|
+
OCCURRENCE_TYPES = frozenset({
|
|
43
|
+
"tool_call",
|
|
44
|
+
"tool_call_observation",
|
|
45
|
+
"agent_execution",
|
|
46
|
+
"agent_turn",
|
|
47
|
+
"agent_turn_interrupt",
|
|
48
|
+
"agent_message",
|
|
49
|
+
"agent_message_transport_diagnostic",
|
|
50
|
+
"command",
|
|
51
|
+
"context_compaction",
|
|
52
|
+
"conversation_item",
|
|
53
|
+
"inference_request",
|
|
54
|
+
# the remainder of the set the dashboard display filter already withholds, kept here
|
|
55
|
+
# so the layout is computed over precisely the nodes a canvas ends up drawing
|
|
56
|
+
"provider_session",
|
|
57
|
+
"permission_request",
|
|
58
|
+
"agent_turn_stop",
|
|
59
|
+
"compaction",
|
|
60
|
+
"compaction_request",
|
|
61
|
+
"terminal_operation",
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
# The relation an occurrence uses to name the entity that defines it.
|
|
65
|
+
DEFINING_RELATIONS = frozenset({
|
|
66
|
+
"USES_TOOL",
|
|
67
|
+
"EXECUTED_TOOL_CALL",
|
|
68
|
+
"SERVED_BY_MODEL",
|
|
69
|
+
"ROUTED_TO_MODEL",
|
|
70
|
+
"USED_MODEL",
|
|
71
|
+
"REQUESTED_MODEL",
|
|
72
|
+
"VIA_MCP",
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
# Types the dashboard withholds from its canvas. Anything left here after folding is
|
|
76
|
+
# still a node of the graph and still reachable from every panel, but it takes no column,
|
|
77
|
+
# and edges route through it, so the ordering is solved against the set that is really
|
|
78
|
+
# drawn. Keeping the list here rather than only in the browser is what stops the two
|
|
79
|
+
# from disagreeing about which nodes exist to be ordered.
|
|
80
|
+
NOT_DRAWN_TYPES = frozenset({
|
|
81
|
+
"agent_execution",
|
|
82
|
+
"agent_turn",
|
|
83
|
+
"agent_turn_stop",
|
|
84
|
+
"compaction",
|
|
85
|
+
"compaction_request",
|
|
86
|
+
"context_compaction",
|
|
87
|
+
"conversation_item",
|
|
88
|
+
"observed_content",
|
|
89
|
+
"permission_request",
|
|
90
|
+
"provider_session",
|
|
91
|
+
"terminal_operation",
|
|
92
|
+
"tool_call",
|
|
93
|
+
"tool_call_observation",
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
# Only these can stand in for an occurrence. A file, endpoint or content node is a thing
|
|
97
|
+
# the occurrence acted on, never the thing that defines it.
|
|
98
|
+
DEFINER_TYPES = frozenset({
|
|
99
|
+
"agent",
|
|
100
|
+
"model",
|
|
101
|
+
"subtask",
|
|
102
|
+
"tool",
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
# Attribute keys that name an entity, used to rejoin an observation that lost its edges.
|
|
106
|
+
IDENTITY_NAME_KEYS = ("tool_name", "native_name", "model_name")
|
|
107
|
+
IDENTITY_SCOPE_KEYS = ("provider",)
|
|
108
|
+
|
|
109
|
+
MIN_TWIN_GROUP = 3
|
|
110
|
+
DEFAULT_ORDER_SWEEPS = 16
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# --------------------------------------------------------------------------- helpers
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _attrs(node: dict[str, Any]) -> dict[str, Any]:
|
|
117
|
+
value = node.get("attributes")
|
|
118
|
+
return value if isinstance(value, dict) else {}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _relation(edge: dict[str, Any]) -> str:
|
|
122
|
+
return str(edge.get("relation") or "").upper()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _min_stamp(*values: Any) -> str | None:
|
|
126
|
+
present = sorted(str(v) for v in values if isinstance(v, str) and v)
|
|
127
|
+
return present[0] if present else None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _max_stamp(*values: Any) -> str | None:
|
|
131
|
+
present = sorted(str(v) for v in values if isinstance(v, str) and v)
|
|
132
|
+
return present[-1] if present else None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _min_int(*values: Any) -> int | None:
|
|
136
|
+
present = [v for v in values if isinstance(v, int) and not isinstance(v, bool)]
|
|
137
|
+
return min(present) if present else None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _max_int(*values: Any) -> int | None:
|
|
141
|
+
present = [v for v in values if isinstance(v, int) and not isinstance(v, bool)]
|
|
142
|
+
return max(present) if present else None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _merge_lists(a: Any, b: Any) -> list[str]:
|
|
146
|
+
out: list[str] = []
|
|
147
|
+
seen: set[str] = set()
|
|
148
|
+
for source in (a, b):
|
|
149
|
+
if not isinstance(source, list):
|
|
150
|
+
continue
|
|
151
|
+
for value in source:
|
|
152
|
+
text = str(value)
|
|
153
|
+
if text and text not in seen:
|
|
154
|
+
seen.add(text)
|
|
155
|
+
out.append(text)
|
|
156
|
+
return out
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class _Folder:
|
|
160
|
+
"""Accumulates folds while preserving identity, span and provenance."""
|
|
161
|
+
|
|
162
|
+
def __init__(self, graph: dict[str, Any]) -> None:
|
|
163
|
+
self.nodes: dict[str, dict[str, Any]] = {}
|
|
164
|
+
for node in graph.get("nodes", []) or []:
|
|
165
|
+
if isinstance(node, dict) and isinstance(node.get("id"), str) and node["id"]:
|
|
166
|
+
self.nodes[node["id"]] = deepcopy(node)
|
|
167
|
+
self.edges: list[dict[str, Any]] = [
|
|
168
|
+
deepcopy(edge)
|
|
169
|
+
for edge in (graph.get("edges", []) or [])
|
|
170
|
+
if isinstance(edge, dict)
|
|
171
|
+
and isinstance(edge.get("source"), str)
|
|
172
|
+
and isinstance(edge.get("target"), str)
|
|
173
|
+
]
|
|
174
|
+
self.removed: Counter[str] = Counter()
|
|
175
|
+
|
|
176
|
+
# -- adjacency -------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
def outgoing(self) -> dict[str, list[dict[str, Any]]]:
|
|
179
|
+
out: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
180
|
+
for edge in self.edges:
|
|
181
|
+
out[edge["source"]].append(edge)
|
|
182
|
+
return out
|
|
183
|
+
|
|
184
|
+
def incoming(self) -> dict[str, list[dict[str, Any]]]:
|
|
185
|
+
out: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
186
|
+
for edge in self.edges:
|
|
187
|
+
out[edge["target"]].append(edge)
|
|
188
|
+
return out
|
|
189
|
+
|
|
190
|
+
def degree(self) -> Counter[str]:
|
|
191
|
+
deg: Counter[str] = Counter()
|
|
192
|
+
for edge in self.edges:
|
|
193
|
+
deg[edge["source"]] += 1
|
|
194
|
+
deg[edge["target"]] += 1
|
|
195
|
+
return deg
|
|
196
|
+
|
|
197
|
+
# -- protection ------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
def conversation_sources(self) -> set[str]:
|
|
200
|
+
"""Nodes a conversation entry names as its owner.
|
|
201
|
+
|
|
202
|
+
``conversation_record_entries`` walks every edge whose target passes
|
|
203
|
+
``_safe_content_reference`` and reports the *source* as ``source_id``. The agent
|
|
204
|
+
panel then selects content by that id, so folding such a node away would leave an
|
|
205
|
+
entry no box can open. The same predicate is used deliberately: a looser one
|
|
206
|
+
freezes nodes that own nothing, a tighter one drops an owner the panel needs.
|
|
207
|
+
"""
|
|
208
|
+
protected: set[str] = set()
|
|
209
|
+
for edge in self.edges:
|
|
210
|
+
target = self.nodes.get(edge["target"])
|
|
211
|
+
if target is not None and _safe_content_reference(target) is not None:
|
|
212
|
+
protected.add(edge["source"])
|
|
213
|
+
return protected
|
|
214
|
+
|
|
215
|
+
# -- mutation --------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
def absorb(self, survivor_id: str, victim_id: str, reason: str) -> None:
|
|
218
|
+
survivor = self.nodes.get(survivor_id)
|
|
219
|
+
victim = self.nodes.get(victim_id)
|
|
220
|
+
if survivor is None or victim is None or survivor_id == victim_id:
|
|
221
|
+
return
|
|
222
|
+
attributes = dict(_attrs(survivor))
|
|
223
|
+
victim_attrs = _attrs(victim)
|
|
224
|
+
|
|
225
|
+
members = list(attributes.get("viewer_folded_members") or [])
|
|
226
|
+
members.append({
|
|
227
|
+
"id": victim_id,
|
|
228
|
+
"type": victim.get("type"),
|
|
229
|
+
"name": victim.get("name") or victim_id,
|
|
230
|
+
"first_seen": victim.get("first_seen"),
|
|
231
|
+
"last_seen": victim.get("last_seen"),
|
|
232
|
+
"reason": reason,
|
|
233
|
+
})
|
|
234
|
+
# a victim that had already absorbed others hands those on, so nothing is lost
|
|
235
|
+
members.extend(victim_attrs.get("viewer_folded_members") or [])
|
|
236
|
+
|
|
237
|
+
member_ids = _merge_lists(
|
|
238
|
+
attributes.get("viewer_member_ids"),
|
|
239
|
+
[victim_id, *(victim_attrs.get("viewer_member_ids") or [])],
|
|
240
|
+
)
|
|
241
|
+
attributes["viewer_member_ids"] = member_ids
|
|
242
|
+
# Not ``viewer_folded``: that marks a node whose whole purpose is to stand for
|
|
243
|
+
# others, and the panel replaces such a node's cards with a list of what it
|
|
244
|
+
# holds. This survivor is a real node with a panel of its own to keep, so it
|
|
245
|
+
# says it absorbed members and the panel adds them rather than replacing.
|
|
246
|
+
attributes["viewer_absorbed"] = True
|
|
247
|
+
attributes["viewer_folded_members"] = members
|
|
248
|
+
attributes["viewer_folded_count"] = len(members)
|
|
249
|
+
attributes["viewer_folded_type"] = victim.get("type")
|
|
250
|
+
reasons = Counter(attributes.get("viewer_fold_reasons") or {})
|
|
251
|
+
reasons[reason] += 1
|
|
252
|
+
for key, value in Counter(victim_attrs.get("viewer_fold_reasons") or {}).items():
|
|
253
|
+
reasons[key] += value
|
|
254
|
+
attributes["viewer_fold_reasons"] = dict(reasons)
|
|
255
|
+
|
|
256
|
+
# an agent-shaped victim also aliases conversation ownership onto the survivor
|
|
257
|
+
if victim.get("type") in {"agent", "agent_execution", "subtask", "provider_session"}:
|
|
258
|
+
attributes["viewer_agent_member_ids"] = _merge_lists(
|
|
259
|
+
attributes.get("viewer_agent_member_ids"),
|
|
260
|
+
[victim_id, *(victim_attrs.get("viewer_agent_member_ids") or [])],
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
survivor["attributes"] = attributes
|
|
264
|
+
survivor["first_seen"] = _min_stamp(survivor.get("first_seen"), victim.get("first_seen"))
|
|
265
|
+
survivor["last_seen"] = _max_stamp(survivor.get("last_seen"), victim.get("last_seen"))
|
|
266
|
+
self.removed[reason] += 1
|
|
267
|
+
|
|
268
|
+
def drop(self, victim_ids: set[str], reason: str) -> None:
|
|
269
|
+
for victim_id in victim_ids:
|
|
270
|
+
if self.nodes.pop(victim_id, None) is not None:
|
|
271
|
+
self.removed[reason] += 1
|
|
272
|
+
self._rewrite({})
|
|
273
|
+
|
|
274
|
+
def _rewrite(self, remap: dict[str, str]) -> None:
|
|
275
|
+
"""Apply a remap, then merge edges that became parallel."""
|
|
276
|
+
resolved: dict[str, str] = {}
|
|
277
|
+
for key in remap:
|
|
278
|
+
seen: set[str] = set()
|
|
279
|
+
value = key
|
|
280
|
+
while value in remap and remap[value] not in seen:
|
|
281
|
+
seen.add(remap[value])
|
|
282
|
+
value = remap[value]
|
|
283
|
+
resolved[key] = value
|
|
284
|
+
|
|
285
|
+
merged: dict[tuple[str, str, str], dict[str, Any]] = {}
|
|
286
|
+
for edge in self.edges:
|
|
287
|
+
source = resolved.get(edge["source"], edge["source"])
|
|
288
|
+
target = resolved.get(edge["target"], edge["target"])
|
|
289
|
+
if source not in self.nodes or target not in self.nodes or source == target:
|
|
290
|
+
continue
|
|
291
|
+
key = (source, _relation(edge), target)
|
|
292
|
+
candidate = dict(edge)
|
|
293
|
+
candidate["source"] = source
|
|
294
|
+
candidate["target"] = target
|
|
295
|
+
existing = merged.get(key)
|
|
296
|
+
if existing is None:
|
|
297
|
+
merged[key] = candidate
|
|
298
|
+
continue
|
|
299
|
+
existing["first_seen"] = _min_stamp(
|
|
300
|
+
existing.get("first_seen"), candidate.get("first_seen")
|
|
301
|
+
)
|
|
302
|
+
existing["last_seen"] = _max_stamp(
|
|
303
|
+
existing.get("last_seen"), candidate.get("last_seen")
|
|
304
|
+
)
|
|
305
|
+
existing["first_sequence"] = _min_int(
|
|
306
|
+
existing.get("first_sequence"), candidate.get("first_sequence")
|
|
307
|
+
)
|
|
308
|
+
existing["last_sequence"] = _max_int(
|
|
309
|
+
existing.get("last_sequence"), candidate.get("last_sequence")
|
|
310
|
+
)
|
|
311
|
+
for key_name in ("event_ids", "event_types", "backends", "attributions"):
|
|
312
|
+
combined = _merge_lists(existing.get(key_name), candidate.get(key_name))
|
|
313
|
+
if combined:
|
|
314
|
+
existing[key_name] = combined
|
|
315
|
+
self.edges = list(merged.values())
|
|
316
|
+
|
|
317
|
+
def collapse(self, remap: dict[str, str], reason: str) -> None:
|
|
318
|
+
for victim_id, survivor_id in remap.items():
|
|
319
|
+
self.absorb(survivor_id, victim_id, reason)
|
|
320
|
+
for victim_id in remap:
|
|
321
|
+
self.nodes.pop(victim_id, None)
|
|
322
|
+
self._rewrite(remap)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
# ----------------------------------------------------------------------- the rules
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _rule_content_leaves(folder: _Folder, protected: set[str]) -> None:
|
|
329
|
+
"""A content node holding a single edge folds into the entity it describes."""
|
|
330
|
+
out, inc = folder.outgoing(), folder.incoming()
|
|
331
|
+
deg = folder.degree()
|
|
332
|
+
remap: dict[str, str] = {}
|
|
333
|
+
for node_id, node in folder.nodes.items():
|
|
334
|
+
if node_id in protected or node.get("type") not in CONTENT_TYPES:
|
|
335
|
+
continue
|
|
336
|
+
if deg[node_id] != 1:
|
|
337
|
+
continue
|
|
338
|
+
edge = (out[node_id] + inc[node_id])[0]
|
|
339
|
+
anchor = edge["target"] if edge["source"] == node_id else edge["source"]
|
|
340
|
+
if anchor != node_id and anchor in folder.nodes:
|
|
341
|
+
remap[node_id] = anchor
|
|
342
|
+
if remap:
|
|
343
|
+
folder.collapse(remap, "content_leaf")
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _rule_occurrences(folder: _Folder, protected: set[str]) -> None:
|
|
347
|
+
"""An occurrence folds into the entity that defines it, repeatedly until stable."""
|
|
348
|
+
while True:
|
|
349
|
+
out, inc = folder.outgoing(), folder.incoming()
|
|
350
|
+
remap: dict[str, str] = {}
|
|
351
|
+
for node_id, node in folder.nodes.items():
|
|
352
|
+
if node_id in protected or node.get("type") not in OCCURRENCE_TYPES:
|
|
353
|
+
continue
|
|
354
|
+
owner: str | None = None
|
|
355
|
+
for edge in out[node_id]:
|
|
356
|
+
if _relation(edge) in DEFINING_RELATIONS and edge["target"] in folder.nodes:
|
|
357
|
+
owner = edge["target"]
|
|
358
|
+
break
|
|
359
|
+
if owner is None:
|
|
360
|
+
peers = {
|
|
361
|
+
(edge["target"] if edge["source"] == node_id else edge["source"])
|
|
362
|
+
for edge in (*out[node_id], *inc[node_id])
|
|
363
|
+
}
|
|
364
|
+
peers.discard(node_id)
|
|
365
|
+
peers = {
|
|
366
|
+
peer for peer in peers
|
|
367
|
+
if peer in folder.nodes
|
|
368
|
+
and folder.nodes[peer].get("type") in DEFINER_TYPES
|
|
369
|
+
}
|
|
370
|
+
if len(peers) == 1:
|
|
371
|
+
owner = peers.pop()
|
|
372
|
+
if owner and owner != node_id and owner not in remap:
|
|
373
|
+
remap[node_id] = owner
|
|
374
|
+
if not remap:
|
|
375
|
+
return
|
|
376
|
+
folder.collapse(remap, "occurrence")
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _identity(node: dict[str, Any]) -> tuple[tuple[str, ...], str]:
|
|
380
|
+
a = _attrs(node)
|
|
381
|
+
name = next(
|
|
382
|
+
(str(a[key]).lower() for key in IDENTITY_NAME_KEYS if isinstance(a.get(key), str) and a[key]),
|
|
383
|
+
str(node.get("name") or "").lower(),
|
|
384
|
+
)
|
|
385
|
+
scope = tuple(str(a.get(key) or "").lower() for key in IDENTITY_SCOPE_KEYS)
|
|
386
|
+
return scope, name
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _rule_mirror_identity(folder: _Folder, protected: set[str]) -> None:
|
|
390
|
+
"""An observation left with no edges rejoins the entity sharing its scope and name.
|
|
391
|
+
|
|
392
|
+
This is the presentation half of ``mirrorWitness``: a mirrored observation is not a
|
|
393
|
+
second invocation, so it must not sit on the canvas as an unattached twin of the call
|
|
394
|
+
it mirrors. A node with no identity to match keeps its own box.
|
|
395
|
+
"""
|
|
396
|
+
out, inc = folder.outgoing(), folder.incoming()
|
|
397
|
+
attached: dict[tuple[tuple[str, ...], str], list[str]] = defaultdict(list)
|
|
398
|
+
for node_id, node in folder.nodes.items():
|
|
399
|
+
if out[node_id] or inc[node_id]:
|
|
400
|
+
attached[_identity(node)].append(node_id)
|
|
401
|
+
remap: dict[str, str] = {}
|
|
402
|
+
for node_id, node in folder.nodes.items():
|
|
403
|
+
if node_id in protected or out[node_id] or inc[node_id]:
|
|
404
|
+
continue
|
|
405
|
+
candidates = [c for c in attached.get(_identity(node), []) if c != node_id]
|
|
406
|
+
if candidates:
|
|
407
|
+
remap[node_id] = sorted(candidates)[0]
|
|
408
|
+
if remap:
|
|
409
|
+
folder.collapse(remap, "mirror_identity")
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _rule_structural_twins(folder: _Folder, protected: set[str]) -> None:
|
|
413
|
+
"""Same type, same neighbours, same relations: one box instead of many."""
|
|
414
|
+
out, inc = folder.outgoing(), folder.incoming()
|
|
415
|
+
groups: dict[tuple[Any, ...], list[str]] = defaultdict(list)
|
|
416
|
+
for node_id, node in folder.nodes.items():
|
|
417
|
+
if node_id in protected:
|
|
418
|
+
continue
|
|
419
|
+
edges = (*out[node_id], *inc[node_id])
|
|
420
|
+
if not edges:
|
|
421
|
+
continue
|
|
422
|
+
peers = tuple(sorted(
|
|
423
|
+
{(e["target"] if e["source"] == node_id else e["source"]) for e in edges} - {node_id}
|
|
424
|
+
))
|
|
425
|
+
relations = tuple(sorted({_relation(e) for e in edges}))
|
|
426
|
+
if peers:
|
|
427
|
+
groups[(node.get("type"), peers, relations)].append(node_id)
|
|
428
|
+
remap: dict[str, str] = {}
|
|
429
|
+
renames: dict[str, tuple[str, str, int]] = {}
|
|
430
|
+
for (node_type, _peers, _relations), group in groups.items():
|
|
431
|
+
if len(group) < MIN_TWIN_GROUP:
|
|
432
|
+
continue
|
|
433
|
+
group.sort()
|
|
434
|
+
keep = group[0]
|
|
435
|
+
base = str(node_type or "node")
|
|
436
|
+
renames[keep] = (
|
|
437
|
+
base if base.endswith("_cluster") else base + "_cluster",
|
|
438
|
+
f"{len(group)} {base.replace('_', ' ')}s",
|
|
439
|
+
len(group),
|
|
440
|
+
)
|
|
441
|
+
for victim in group[1:]:
|
|
442
|
+
remap[victim] = keep
|
|
443
|
+
if not remap:
|
|
444
|
+
return
|
|
445
|
+
folder.collapse(remap, "structural_twin")
|
|
446
|
+
for keep, (node_type, name, count) in renames.items():
|
|
447
|
+
node = folder.nodes.get(keep)
|
|
448
|
+
if node is None:
|
|
449
|
+
continue
|
|
450
|
+
node["type"] = node_type
|
|
451
|
+
node["name"] = name
|
|
452
|
+
attributes = dict(_attrs(node))
|
|
453
|
+
attributes["viewer_cluster"] = True
|
|
454
|
+
attributes["member_count"] = count
|
|
455
|
+
node["attributes"] = attributes
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _rule_bypass_undrawn(folder: _Folder) -> None:
|
|
459
|
+
"""Route edges through the types a canvas withholds, so they take no column.
|
|
460
|
+
|
|
461
|
+
These are not folded into anything: no single node stands in for them, and each keeps
|
|
462
|
+
its own entry in the graph and its own panel. They simply stop being an obstacle the
|
|
463
|
+
ordering has to place, and their neighbours are joined directly so the flow through
|
|
464
|
+
them survives. Solving the order against any other set is what leaves a drawn edge
|
|
465
|
+
crossing another for no reason a reader can see.
|
|
466
|
+
"""
|
|
467
|
+
for _ in range(len(NOT_DRAWN_TYPES) + 1):
|
|
468
|
+
out, inc = folder.outgoing(), folder.incoming()
|
|
469
|
+
victims = [
|
|
470
|
+
node_id for node_id, node in folder.nodes.items()
|
|
471
|
+
if node.get("type") in NOT_DRAWN_TYPES
|
|
472
|
+
]
|
|
473
|
+
if not victims:
|
|
474
|
+
return
|
|
475
|
+
bridged: list[dict[str, Any]] = []
|
|
476
|
+
for node_id in victims:
|
|
477
|
+
for before in inc[node_id]:
|
|
478
|
+
for after in out[node_id]:
|
|
479
|
+
source, target = before["source"], after["target"]
|
|
480
|
+
if source == node_id or target == node_id or source == target:
|
|
481
|
+
continue
|
|
482
|
+
bridged.append({
|
|
483
|
+
"source": source,
|
|
484
|
+
"target": target,
|
|
485
|
+
# the bridged edge describes what the bypassed node did next, so
|
|
486
|
+
# it carries the outgoing relation. Taking the incoming one made an
|
|
487
|
+
# agent's INVOKES_MODEL edge read as OBSERVED_PROVIDER_SESSION.
|
|
488
|
+
"relation": after.get("relation") or before.get("relation"),
|
|
489
|
+
"first_seen": _min_stamp(before.get("first_seen"), after.get("first_seen")),
|
|
490
|
+
"last_seen": _max_stamp(before.get("last_seen"), after.get("last_seen")),
|
|
491
|
+
"viewer_bridged_through": node_id,
|
|
492
|
+
})
|
|
493
|
+
for node_id in victims:
|
|
494
|
+
folder.nodes.pop(node_id, None)
|
|
495
|
+
folder.edges.extend(bridged)
|
|
496
|
+
folder._rewrite({})
|
|
497
|
+
folder.removed["not_drawn"] += len(victims)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
# -------------------------------------------------------------------------- layering
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _feedback_edges(node_ids: list[str], adjacency: dict[str, list[str]]) -> set[tuple[str, str]]:
|
|
504
|
+
"""Edges that close a cycle, found by an iterative colouring DFS."""
|
|
505
|
+
WHITE, GREY, BLACK = 0, 1, 2
|
|
506
|
+
colour = dict.fromkeys(node_ids, WHITE)
|
|
507
|
+
feedback: set[tuple[str, str]] = set()
|
|
508
|
+
for root in node_ids:
|
|
509
|
+
if colour[root] != WHITE:
|
|
510
|
+
continue
|
|
511
|
+
colour[root] = GREY
|
|
512
|
+
stack: list[tuple[str, Any]] = [(root, iter(adjacency.get(root, ())))]
|
|
513
|
+
while stack:
|
|
514
|
+
node, children = stack[-1]
|
|
515
|
+
advanced = False
|
|
516
|
+
for child in children:
|
|
517
|
+
if colour.get(child) == GREY:
|
|
518
|
+
feedback.add((node, child))
|
|
519
|
+
continue
|
|
520
|
+
if colour.get(child) == WHITE:
|
|
521
|
+
colour[child] = GREY
|
|
522
|
+
stack.append((child, iter(adjacency.get(child, ()))))
|
|
523
|
+
advanced = True
|
|
524
|
+
break
|
|
525
|
+
if not advanced:
|
|
526
|
+
colour[node] = BLACK
|
|
527
|
+
stack.pop()
|
|
528
|
+
return feedback
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def assign_layers(
|
|
532
|
+
node_ids: list[str],
|
|
533
|
+
edges: list[dict[str, Any]],
|
|
534
|
+
previous: dict[str, int] | None = None,
|
|
535
|
+
) -> dict[str, int]:
|
|
536
|
+
"""Longest-path layering with a per-node floor.
|
|
537
|
+
|
|
538
|
+
Every edge of the resulting layering points strictly right. ``previous`` supplies the
|
|
539
|
+
floor that makes a live run monotonic: a node already placed can be pushed further
|
|
540
|
+
right by new evidence, never pulled back.
|
|
541
|
+
"""
|
|
542
|
+
present = set(node_ids)
|
|
543
|
+
adjacency: dict[str, list[str]] = defaultdict(list)
|
|
544
|
+
seen: set[tuple[str, str]] = set()
|
|
545
|
+
for edge in edges:
|
|
546
|
+
source, target = edge.get("source"), edge.get("target")
|
|
547
|
+
if source in present and target in present and source != target:
|
|
548
|
+
if (source, target) not in seen:
|
|
549
|
+
seen.add((source, target))
|
|
550
|
+
adjacency[source].append(target)
|
|
551
|
+
|
|
552
|
+
feedback = _feedback_edges(node_ids, adjacency)
|
|
553
|
+
forward: dict[str, list[str]] = defaultdict(list)
|
|
554
|
+
indegree: Counter[str] = Counter(dict.fromkeys(node_ids, 0))
|
|
555
|
+
for source, targets in adjacency.items():
|
|
556
|
+
for target in targets:
|
|
557
|
+
a, b = (target, source) if (source, target) in feedback else (source, target)
|
|
558
|
+
if a == b:
|
|
559
|
+
continue
|
|
560
|
+
forward[a].append(b)
|
|
561
|
+
indegree[b] += 1
|
|
562
|
+
|
|
563
|
+
floor = previous or {}
|
|
564
|
+
layer = {node_id: max(0, int(floor.get(node_id, 0))) for node_id in node_ids}
|
|
565
|
+
queue = deque(sorted(n for n in node_ids if indegree[n] == 0))
|
|
566
|
+
settled = 0
|
|
567
|
+
while queue:
|
|
568
|
+
node = queue.popleft()
|
|
569
|
+
settled += 1
|
|
570
|
+
for child in forward[node]:
|
|
571
|
+
if layer[child] < layer[node] + 1:
|
|
572
|
+
layer[child] = layer[node] + 1
|
|
573
|
+
indegree[child] -= 1
|
|
574
|
+
if indegree[child] == 0:
|
|
575
|
+
queue.append(child)
|
|
576
|
+
if settled < len(node_ids):
|
|
577
|
+
# a cycle the reversal missed; park the remainder to the right of everything placed
|
|
578
|
+
rest = max(layer.values(), default=0) + 1
|
|
579
|
+
for node_id in node_ids:
|
|
580
|
+
if indegree[node_id] > 0:
|
|
581
|
+
layer[node_id] = max(layer[node_id], rest)
|
|
582
|
+
return layer
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _count_crossings(
|
|
586
|
+
edges: list[dict[str, Any]],
|
|
587
|
+
layer: dict[str, int],
|
|
588
|
+
order: dict[str, int],
|
|
589
|
+
) -> int:
|
|
590
|
+
by_layer: dict[int, list[tuple[int, int]]] = defaultdict(list)
|
|
591
|
+
for edge in edges:
|
|
592
|
+
source, target = edge.get("source"), edge.get("target")
|
|
593
|
+
if source in layer and target in layer and layer[target] == layer[source] + 1:
|
|
594
|
+
by_layer[layer[source]].append((order[source], order[target]))
|
|
595
|
+
total = 0
|
|
596
|
+
for pairs in by_layer.values():
|
|
597
|
+
for i in range(len(pairs)):
|
|
598
|
+
a = pairs[i]
|
|
599
|
+
for j in range(i + 1, len(pairs)):
|
|
600
|
+
b = pairs[j]
|
|
601
|
+
if (a[0] - b[0]) * (a[1] - b[1]) < 0:
|
|
602
|
+
total += 1
|
|
603
|
+
return total
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _with_virtual_chain(
|
|
607
|
+
edges: list[dict[str, Any]],
|
|
608
|
+
layer: dict[str, int],
|
|
609
|
+
) -> tuple[list[tuple[str, str]], dict[str, int]]:
|
|
610
|
+
"""Break every edge into single-column steps, inventing a node for each one crossed.
|
|
611
|
+
|
|
612
|
+
An edge spanning three columns occupies a row in the two columns between its ends,
|
|
613
|
+
but with nothing standing in those columns the ordering cannot see it and places
|
|
614
|
+
other nodes straight through its path. Giving it a placeholder per column is what
|
|
615
|
+
lets a barycentre sweep route around it; the placeholders are discarded afterwards
|
|
616
|
+
and never reach the canvas.
|
|
617
|
+
"""
|
|
618
|
+
steps: list[tuple[str, str]] = []
|
|
619
|
+
virtual: dict[str, int] = {}
|
|
620
|
+
for edge in edges:
|
|
621
|
+
source, target = edge.get("source"), edge.get("target")
|
|
622
|
+
if source not in layer or target not in layer or source == target:
|
|
623
|
+
continue
|
|
624
|
+
start, end = layer[source], layer[target]
|
|
625
|
+
if end <= start:
|
|
626
|
+
continue
|
|
627
|
+
if end == start + 1:
|
|
628
|
+
steps.append((source, target))
|
|
629
|
+
continue
|
|
630
|
+
previous = source
|
|
631
|
+
for column in range(start + 1, end):
|
|
632
|
+
placeholder = f"\0virtual\0{source}\0{target}\0{column}"
|
|
633
|
+
virtual[placeholder] = column
|
|
634
|
+
steps.append((previous, placeholder))
|
|
635
|
+
previous = placeholder
|
|
636
|
+
steps.append((previous, target))
|
|
637
|
+
return steps, virtual
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def assign_order(
|
|
641
|
+
nodes: dict[str, dict[str, Any]],
|
|
642
|
+
edges: list[dict[str, Any]],
|
|
643
|
+
layer: dict[str, int],
|
|
644
|
+
sweeps: int = DEFAULT_ORDER_SWEEPS,
|
|
645
|
+
) -> dict[str, int]:
|
|
646
|
+
"""Barycentre sweeps over the real nodes plus a placeholder per column an edge crosses."""
|
|
647
|
+
steps, virtual = _with_virtual_chain(edges, layer)
|
|
648
|
+
placed = dict(layer)
|
|
649
|
+
placed.update(virtual)
|
|
650
|
+
|
|
651
|
+
columns: dict[int, list[str]] = defaultdict(list)
|
|
652
|
+
for node_id in nodes:
|
|
653
|
+
columns[layer[node_id]].append(node_id)
|
|
654
|
+
for node_id, column in virtual.items():
|
|
655
|
+
columns[column].append(node_id)
|
|
656
|
+
for column in columns.values():
|
|
657
|
+
column.sort(key=lambda n: (
|
|
658
|
+
str((nodes.get(n) or {}).get("type") or "~"),
|
|
659
|
+
str((nodes.get(n) or {}).get("name") or "~"),
|
|
660
|
+
n,
|
|
661
|
+
))
|
|
662
|
+
order = {n: i for column in columns.values() for i, n in enumerate(column)}
|
|
663
|
+
|
|
664
|
+
predecessors: dict[str, list[str]] = defaultdict(list)
|
|
665
|
+
successors: dict[str, list[str]] = defaultdict(list)
|
|
666
|
+
for source, target in steps:
|
|
667
|
+
predecessors[target].append(source)
|
|
668
|
+
successors[source].append(target)
|
|
669
|
+
|
|
670
|
+
def crossings(current: dict[str, int]) -> int:
|
|
671
|
+
by_layer: dict[int, list[tuple[int, int]]] = defaultdict(list)
|
|
672
|
+
for source, target in steps:
|
|
673
|
+
by_layer[placed[source]].append((current[source], current[target]))
|
|
674
|
+
total = 0
|
|
675
|
+
for pairs in by_layer.values():
|
|
676
|
+
for i in range(len(pairs)):
|
|
677
|
+
a = pairs[i]
|
|
678
|
+
for j in range(i + 1, len(pairs)):
|
|
679
|
+
b = pairs[j]
|
|
680
|
+
if (a[0] - b[0]) * (a[1] - b[1]) < 0:
|
|
681
|
+
total += 1
|
|
682
|
+
return total
|
|
683
|
+
|
|
684
|
+
best_score = crossings(order)
|
|
685
|
+
best_order = dict(order)
|
|
686
|
+
for sweep in range(sweeps):
|
|
687
|
+
downward = sweep % 2 == 0
|
|
688
|
+
neighbours = predecessors if downward else successors
|
|
689
|
+
for index in sorted(columns, reverse=not downward):
|
|
690
|
+
column = columns[index]
|
|
691
|
+
|
|
692
|
+
def barycentre(node_id: str) -> float:
|
|
693
|
+
positions = [order[n] for n in neighbours[node_id] if n in order]
|
|
694
|
+
return sum(positions) / len(positions) if positions else float(order[node_id])
|
|
695
|
+
|
|
696
|
+
column.sort(key=lambda n: (barycentre(n), n))
|
|
697
|
+
for position, node_id in enumerate(column):
|
|
698
|
+
order[node_id] = position
|
|
699
|
+
score = crossings(order)
|
|
700
|
+
if score < best_score:
|
|
701
|
+
best_score = score
|
|
702
|
+
best_order = dict(order)
|
|
703
|
+
|
|
704
|
+
# discard the placeholders and close the gaps they left in each column
|
|
705
|
+
final: dict[str, int] = {}
|
|
706
|
+
for index, column in columns.items():
|
|
707
|
+
real = sorted((n for n in column if n in nodes), key=lambda n: best_order[n])
|
|
708
|
+
for position, node_id in enumerate(real):
|
|
709
|
+
final[node_id] = position
|
|
710
|
+
return final
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def _isotonic(desired: list[float], separation: float = 1.0) -> list[float]:
|
|
714
|
+
"""Closest values to ``desired`` that keep every neighbour ``separation`` apart.
|
|
715
|
+
|
|
716
|
+
Substituting ``u_i = y_i - i*separation`` turns the spacing constraint into "u must
|
|
717
|
+
not decrease", which pool-adjacent-violators solves exactly by averaging each run
|
|
718
|
+
that breaks the order. So a column lands as near its preferred rows as the spacing
|
|
719
|
+
allows, rather than being pushed down one slot at a time from the top.
|
|
720
|
+
"""
|
|
721
|
+
shifted = [value - index * separation for index, value in enumerate(desired)]
|
|
722
|
+
weights: list[float] = []
|
|
723
|
+
means: list[float] = []
|
|
724
|
+
for value in shifted:
|
|
725
|
+
weights.append(1.0)
|
|
726
|
+
means.append(value)
|
|
727
|
+
while len(means) > 1 and means[-2] > means[-1]:
|
|
728
|
+
weight = weights[-2] + weights[-1]
|
|
729
|
+
mean = (means[-2] * weights[-2] + means[-1] * weights[-1]) / weight
|
|
730
|
+
means[-2:] = [mean]
|
|
731
|
+
weights[-2:] = [weight]
|
|
732
|
+
flat: list[float] = []
|
|
733
|
+
for weight, mean in zip(weights, means):
|
|
734
|
+
flat.extend([mean] * int(round(weight)))
|
|
735
|
+
return [value + index * separation for index, value in enumerate(flat)]
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def assign_rows(
|
|
739
|
+
nodes: dict[str, dict[str, Any]],
|
|
740
|
+
edges: list[dict[str, Any]],
|
|
741
|
+
layer: dict[str, int],
|
|
742
|
+
order: dict[str, int],
|
|
743
|
+
sweeps: int = 8,
|
|
744
|
+
) -> dict[str, float]:
|
|
745
|
+
"""Turn the column order into actual rows, pulling each node level with its neighbours.
|
|
746
|
+
|
|
747
|
+
Ordering decides who is above whom; this decides how far apart they sit. Without it
|
|
748
|
+
every column starts at the top and counts downwards, which leaves a column holding
|
|
749
|
+
one node stranded level with the top of a column holding eight, and makes the edges
|
|
750
|
+
between them long diagonals for no reason in the data.
|
|
751
|
+
"""
|
|
752
|
+
columns: dict[int, list[str]] = defaultdict(list)
|
|
753
|
+
for node_id in nodes:
|
|
754
|
+
columns[layer[node_id]].append(node_id)
|
|
755
|
+
for column in columns.values():
|
|
756
|
+
column.sort(key=lambda n: order[n])
|
|
757
|
+
|
|
758
|
+
row: dict[str, float] = {n: float(order[n]) for n in nodes}
|
|
759
|
+
predecessors: dict[str, list[str]] = defaultdict(list)
|
|
760
|
+
successors: dict[str, list[str]] = defaultdict(list)
|
|
761
|
+
for edge in edges:
|
|
762
|
+
source, target = edge.get("source"), edge.get("target")
|
|
763
|
+
if source in layer and target in layer and layer[target] > layer[source]:
|
|
764
|
+
predecessors[target].append(source)
|
|
765
|
+
successors[source].append(target)
|
|
766
|
+
|
|
767
|
+
for sweep in range(sweeps):
|
|
768
|
+
downward = sweep % 2 == 0
|
|
769
|
+
neighbours = predecessors if downward else successors
|
|
770
|
+
for index in sorted(columns, reverse=not downward):
|
|
771
|
+
column = columns[index]
|
|
772
|
+
desired = []
|
|
773
|
+
for node_id in column:
|
|
774
|
+
values = sorted(row[n] for n in neighbours[node_id] if n in row)
|
|
775
|
+
if values:
|
|
776
|
+
middle = len(values) // 2
|
|
777
|
+
centre = (values[middle] if len(values) % 2
|
|
778
|
+
else (values[middle - 1] + values[middle]) / 2)
|
|
779
|
+
else:
|
|
780
|
+
centre = row[node_id]
|
|
781
|
+
desired.append(centre)
|
|
782
|
+
for node_id, value in zip(column, _isotonic(desired)):
|
|
783
|
+
row[node_id] = value
|
|
784
|
+
|
|
785
|
+
lowest = min(row.values(), default=0.0)
|
|
786
|
+
return {node_id: value - lowest for node_id, value in row.items()}
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
# ------------------------------------------------------------------------ entry point
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def flow_layout_graph(
|
|
793
|
+
graph: dict[str, Any],
|
|
794
|
+
previous_layers: dict[str, int] | None = None,
|
|
795
|
+
) -> dict[str, Any]:
|
|
796
|
+
"""Describe a canvas over the graph without removing anything from the graph.
|
|
797
|
+
|
|
798
|
+
``nodes`` and ``edges`` come back with exactly the members they went in with. The
|
|
799
|
+
node panel, the content inspector, delegation and execution payload lookups,
|
|
800
|
+
conversation ownership and the raw-event log all read those arrays, and every one of
|
|
801
|
+
them is entitled to find a ``tool_call`` or a payload edge that this layout chooses
|
|
802
|
+
not to draw. What is added is a description of the canvas:
|
|
803
|
+
|
|
804
|
+
* each node gains ``viewer_layer`` and ``viewer_order``; a node that is drawn in
|
|
805
|
+
another node's place also gains ``viewer_collapsed_into``, naming its stand-in;
|
|
806
|
+
* the stand-in gains the usual ``viewer_member_ids`` / ``viewer_folded_members``, so
|
|
807
|
+
a folded member is still listed, with its span, on the panel that replaced it;
|
|
808
|
+
* ``viewer_flow`` lists exactly what to draw, with folded endpoints already remapped.
|
|
809
|
+
|
|
810
|
+
A renderer draws ``viewer_flow``. Everything else keeps reading the full graph.
|
|
811
|
+
"""
|
|
812
|
+
if not isinstance(graph, dict):
|
|
813
|
+
return graph
|
|
814
|
+
folder = _Folder(graph)
|
|
815
|
+
if not folder.nodes:
|
|
816
|
+
return graph
|
|
817
|
+
original_ids = list(folder.nodes)
|
|
818
|
+
|
|
819
|
+
protected = folder.conversation_sources()
|
|
820
|
+
_rule_content_leaves(folder, protected)
|
|
821
|
+
_rule_occurrences(folder, protected)
|
|
822
|
+
_rule_mirror_identity(folder, protected)
|
|
823
|
+
_rule_structural_twins(folder, protected)
|
|
824
|
+
_rule_bypass_undrawn(folder)
|
|
825
|
+
|
|
826
|
+
# Keep the graph's stable insertion order for cycle breaking. Sorting IDs here can
|
|
827
|
+
# make a child appear before its parent, so the DFS would choose the forward
|
|
828
|
+
# SPAWNED_AGENT edge as the feedback edge and put that child in the wrong layer.
|
|
829
|
+
drawn_ids = list(folder.nodes)
|
|
830
|
+
layer = assign_layers(drawn_ids, folder.edges, previous_layers)
|
|
831
|
+
order = assign_order(folder.nodes, folder.edges, layer)
|
|
832
|
+
row = assign_rows(folder.nodes, folder.edges, layer, order)
|
|
833
|
+
|
|
834
|
+
# where each folded node ended up, so an undrawn node can still be pointed at a box
|
|
835
|
+
stand_in: dict[str, str] = {}
|
|
836
|
+
for survivor_id, node in folder.nodes.items():
|
|
837
|
+
for member in _attrs(node).get("viewer_member_ids") or []:
|
|
838
|
+
stand_in[str(member)] = survivor_id
|
|
839
|
+
|
|
840
|
+
annotations: dict[str, dict[str, Any]] = {}
|
|
841
|
+
for node_id, node in folder.nodes.items():
|
|
842
|
+
extra = dict(_attrs(node))
|
|
843
|
+
extra["viewer_layer"] = int(layer[node_id])
|
|
844
|
+
extra["viewer_order"] = int(order[node_id])
|
|
845
|
+
extra["viewer_row"] = round(float(row[node_id]), 3)
|
|
846
|
+
annotations[node_id] = extra
|
|
847
|
+
for node_id in original_ids:
|
|
848
|
+
if node_id in annotations:
|
|
849
|
+
continue
|
|
850
|
+
target = stand_in.get(node_id)
|
|
851
|
+
if target is None:
|
|
852
|
+
continue
|
|
853
|
+
annotations[node_id] = {
|
|
854
|
+
"viewer_collapsed_into": target,
|
|
855
|
+
"viewer_layer": int(layer.get(target, 0)),
|
|
856
|
+
"viewer_order": int(order.get(target, 0)),
|
|
857
|
+
"viewer_row": round(float(row.get(target, 0.0)), 3),
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
nodes: list[dict[str, Any]] = []
|
|
861
|
+
for node in graph.get("nodes", []) or []:
|
|
862
|
+
if not isinstance(node, dict) or not isinstance(node.get("id"), str):
|
|
863
|
+
nodes.append(node)
|
|
864
|
+
continue
|
|
865
|
+
extra = annotations.get(node["id"])
|
|
866
|
+
if extra is None:
|
|
867
|
+
nodes.append(node)
|
|
868
|
+
continue
|
|
869
|
+
merged = dict(node)
|
|
870
|
+
merged["attributes"] = {**_attrs(node), **extra}
|
|
871
|
+
nodes.append(merged)
|
|
872
|
+
|
|
873
|
+
result = dict(graph)
|
|
874
|
+
result["nodes"] = nodes
|
|
875
|
+
result["node_count"] = len(nodes)
|
|
876
|
+
result["viewer_flow"] = {
|
|
877
|
+
"schema_version": "0.1",
|
|
878
|
+
"layer_count": (max(layer.values()) + 1) if layer else 0,
|
|
879
|
+
"nodes": [
|
|
880
|
+
{
|
|
881
|
+
"id": node_id,
|
|
882
|
+
"layer": int(layer[node_id]),
|
|
883
|
+
"order": int(order[node_id]),
|
|
884
|
+
"row": round(float(row[node_id]), 3),
|
|
885
|
+
}
|
|
886
|
+
for node_id in drawn_ids
|
|
887
|
+
],
|
|
888
|
+
"edges": [
|
|
889
|
+
{
|
|
890
|
+
"source": edge["source"],
|
|
891
|
+
"target": edge["target"],
|
|
892
|
+
"relation": edge.get("relation"),
|
|
893
|
+
}
|
|
894
|
+
for edge in folder.edges
|
|
895
|
+
],
|
|
896
|
+
"collapsed": {
|
|
897
|
+
member: survivor
|
|
898
|
+
for member, survivor in sorted(stand_in.items())
|
|
899
|
+
},
|
|
900
|
+
"folded": dict(folder.removed),
|
|
901
|
+
"crossings": _count_crossings(folder.edges, layer, order),
|
|
902
|
+
}
|
|
903
|
+
# ``viewer_projection`` is deliberately left alone. live_update reads that key to
|
|
904
|
+
# decide a delta can no longer describe the view, because the projections that set it
|
|
905
|
+
# rewrite node identity. This one does not: every node and edge is still present and
|
|
906
|
+
# still itself. What changed is only which of them a canvas draws, and that travels
|
|
907
|
+
# with a delta as ``viewer_flow`` rather than costing the run its incremental updates.
|
|
908
|
+
return result
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def layers_of(graph: dict[str, Any]) -> dict[str, int]:
|
|
912
|
+
"""Read back the assigned columns, to feed the next tick's floor."""
|
|
913
|
+
flow = graph.get("viewer_flow")
|
|
914
|
+
if isinstance(flow, dict):
|
|
915
|
+
return {
|
|
916
|
+
str(entry["id"]): int(entry["layer"])
|
|
917
|
+
for entry in (flow.get("nodes") or [])
|
|
918
|
+
if isinstance(entry, dict)
|
|
919
|
+
and isinstance(entry.get("id"), str)
|
|
920
|
+
and isinstance(entry.get("layer"), int)
|
|
921
|
+
}
|
|
922
|
+
return {}
|