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
execweave/live_core.py
ADDED
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
import webbrowser
|
|
11
|
+
from collections import deque
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from functools import lru_cache
|
|
15
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
16
|
+
from http.cookies import SimpleCookie
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from socketserver import TCPServer
|
|
19
|
+
from urllib.parse import parse_qs, urlsplit
|
|
20
|
+
from uuid import uuid4
|
|
21
|
+
|
|
22
|
+
from .backends import create_collector
|
|
23
|
+
from .conversation_records import write_conversation_records
|
|
24
|
+
from .finalization import record_finalization
|
|
25
|
+
from .delivery_status import summarize_finalization
|
|
26
|
+
from .run_assessment import build_run_assessment
|
|
27
|
+
from .graph import GRAPH_SCHEMA_VERSION, GraphAccumulator, build_execution_graph, write_execution_graph
|
|
28
|
+
from .live_view import LIVE_HTML as _LIVE_HTML
|
|
29
|
+
from .semantic import LiveSemanticNormalizer, merge_semantic_sidecar
|
|
30
|
+
from .sink import JsonlSink
|
|
31
|
+
from .privacy import CONTENT_CAPTURE_ENV
|
|
32
|
+
from .validate import validate_event_stream
|
|
33
|
+
from .viewer_dashboard_clean import fold_budget_bootstrap, resolve_fold_budget
|
|
34
|
+
from .viewer_limits import resolve_viewer_limits, viewer_limits_bootstrap
|
|
35
|
+
from .viewer import (
|
|
36
|
+
VIEWER_MAX_DOM_ELEMENTS,
|
|
37
|
+
VIEWER_MAX_EDGES,
|
|
38
|
+
VIEWER_MAX_NODES,
|
|
39
|
+
render_graph_html,
|
|
40
|
+
write_graph_html,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
LIVE_DELTA_HISTORY = 256
|
|
44
|
+
LIVE_DELTA_HISTORY_BYTES = 8 * 1024 * 1024
|
|
45
|
+
_SEMANTIC_ENV = "EXECWEAVE_SEMANTIC_SIDECAR"
|
|
46
|
+
_RUN_ID_ENV = "EXECWEAVE_RUN_ID"
|
|
47
|
+
_SESSION_ID_ENV = "EXECWEAVE_SESSION_ID"
|
|
48
|
+
_LIVE_TOKEN_HEADER = "X-ExecWeave-Token"
|
|
49
|
+
|
|
50
|
+
_FINAL_THEME_CSS = """
|
|
51
|
+
:root[data-theme="light"]{color-scheme:light;--bg:#f7f9fc;--panel:#ffffff;--panel2:#eef3f8;--text:#172033;--muted:#617083;--border:#cbd5e1;--edge:#64748b;--causal:#15803d;--noncausal:#b45309;--inferred:#7e22ce;--identity:#0369a1;--selected:#2563eb;--accent:#2563eb}
|
|
52
|
+
#execweave-theme-toggle{position:fixed;right:14px;bottom:14px;z-index:9999;border:1px solid var(--border);background:var(--panel);color:var(--text);border-radius:8px;padding:7px 10px;cursor:pointer;box-shadow:0 4px 18px rgba(15,23,42,.12)}
|
|
53
|
+
#execweave-theme-toggle:hover{border-color:var(--selected,var(--accent))}
|
|
54
|
+
:root[data-theme="light"] .node text{fill:#f8fafc}:root[data-theme="light"] .node .node-type{fill:#cbd5e1}
|
|
55
|
+
""".strip()
|
|
56
|
+
|
|
57
|
+
_FINAL_THEME_CONTROLS = r"""
|
|
58
|
+
<button id="execweave-theme-toggle" type="button" aria-label="Switch to light theme" title="Switch to light theme">Light</button>
|
|
59
|
+
<script>
|
|
60
|
+
(()=>{const key='execweave-theme',button=document.getElementById('execweave-theme-toggle');function apply(theme,persist=false){const next=theme==='light'?'light':'dark';document.documentElement.dataset.theme=next;const light=next==='light';button.textContent=light?'Dark':'Light';button.setAttribute('aria-label',light?'Switch to dark theme':'Switch to light theme');button.title=light?'Switch to dark theme':'Switch to light theme';if(persist){try{localStorage.setItem(key,next)}catch(_){}}}let initial='dark';try{if(localStorage.getItem(key)==='light')initial='light'}catch(_){}apply(initial);button.onclick=()=>apply(document.documentElement.dataset.theme==='light'?'dark':'light',true)})();
|
|
61
|
+
</script>
|
|
62
|
+
""".strip()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _inject_final_theme(html: str) -> str:
|
|
66
|
+
if 'id="theme-toggle"' in html or 'id="execweave-theme-toggle"' in html:
|
|
67
|
+
return html
|
|
68
|
+
themed = html.replace("</style>", _FINAL_THEME_CSS + "\n</style>", 1)
|
|
69
|
+
return themed.replace("</body>", _FINAL_THEME_CONTROLS + "\n</body>", 1)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _inject_live_auth(html: str) -> str:
|
|
73
|
+
"""Keep browser authentication in an HttpOnly cookie, never page JavaScript."""
|
|
74
|
+
return html.replace(
|
|
75
|
+
"fetch(`/live.json?after=${liveSequence}`,{cache:'no-store'})",
|
|
76
|
+
"fetch(`/live.json?after=${liveSequence}`,{cache:'no-store',credentials:'same-origin'})",
|
|
77
|
+
1,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_PAIRING_HTML = """<!doctype html>
|
|
82
|
+
<meta charset="utf-8">
|
|
83
|
+
<meta name="referrer" content="no-referrer">
|
|
84
|
+
<title>ExecWeave live pairing</title>
|
|
85
|
+
<style>body{font:16px system-ui;max-width:34rem;margin:12vh auto;padding:2rem}input,button{font:inherit;padding:.6rem}input{width:100%;box-sizing:border-box;margin:.5rem 0 1rem}</style>
|
|
86
|
+
<h1>ExecWeave live pairing</h1>
|
|
87
|
+
<p>Enter the one-time pairing code shown in the terminal. The evidence credential is never placed in the URL.</p>
|
|
88
|
+
<form method="post" action="/pair"><label>Pairing code<input name="code" autocomplete="off" required></label><button type="submit">Open live graph</button></form>
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _PairingGate:
|
|
93
|
+
def __init__(self, code: str) -> None:
|
|
94
|
+
self._code = code
|
|
95
|
+
self._used = False
|
|
96
|
+
self._lock = threading.Lock()
|
|
97
|
+
|
|
98
|
+
def consume(self, candidate: str) -> bool:
|
|
99
|
+
with self._lock:
|
|
100
|
+
if self._used or not candidate or not hmac.compare_digest(candidate, self._code):
|
|
101
|
+
return False
|
|
102
|
+
self._used = True
|
|
103
|
+
self._code = ""
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
_AUTHENTICATED_LIVE_HTML = _inject_live_auth(_LIVE_HTML)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@lru_cache(maxsize=8)
|
|
111
|
+
def _live_page(html: str, budget: int) -> str:
|
|
112
|
+
"""The served page carries the fold budget this run was started with.
|
|
113
|
+
|
|
114
|
+
The shell is a module constant, so the budget cannot be baked in at import time —
|
|
115
|
+
the command line has not been read yet. It is spliced in per budget instead, and
|
|
116
|
+
cached, because a run resolves exactly one.
|
|
117
|
+
"""
|
|
118
|
+
limits = resolve_viewer_limits(
|
|
119
|
+
defaults=(VIEWER_MAX_NODES, VIEWER_MAX_EDGES, VIEWER_MAX_DOM_ELEMENTS)
|
|
120
|
+
)
|
|
121
|
+
bootstrap = (
|
|
122
|
+
f"<script>{fold_budget_bootstrap(budget)}"
|
|
123
|
+
f"{viewer_limits_bootstrap(limits)}</script>\n"
|
|
124
|
+
)
|
|
125
|
+
if "<script>" not in html:
|
|
126
|
+
return bootstrap + html
|
|
127
|
+
return html.replace("<script>", bootstrap + "<script>", 1)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True)
|
|
131
|
+
class LiveResult:
|
|
132
|
+
session_id: str
|
|
133
|
+
return_code: int
|
|
134
|
+
live_url: str
|
|
135
|
+
output_dir: Path
|
|
136
|
+
event_stream: Path
|
|
137
|
+
semantic_sidecar: Path
|
|
138
|
+
materialized_event_stream: Path
|
|
139
|
+
graph: Path
|
|
140
|
+
viewer: Path
|
|
141
|
+
|
|
142
|
+
def to_dict(self) -> dict[str, object]:
|
|
143
|
+
artifacts = {}
|
|
144
|
+
for key in ("event_stream", "semantic_sidecar", "materialized_event_stream", "graph", "viewer"):
|
|
145
|
+
path = getattr(self, key)
|
|
146
|
+
try:
|
|
147
|
+
info = path.stat()
|
|
148
|
+
status = "produced" if path.is_file() and info.st_size else "empty_or_not_regular"
|
|
149
|
+
except FileNotFoundError:
|
|
150
|
+
status = "not_produced"
|
|
151
|
+
except OSError:
|
|
152
|
+
status = "unreadable"
|
|
153
|
+
artifacts[key] = {"status": status, "path": str(path) if status == "produced" else None}
|
|
154
|
+
return {
|
|
155
|
+
"session_id": self.session_id,
|
|
156
|
+
"return_code": self.return_code,
|
|
157
|
+
"live_url": self.live_url,
|
|
158
|
+
"output_dir": str(self.output_dir),
|
|
159
|
+
**{key: value["path"] for key, value in artifacts.items()},
|
|
160
|
+
"semantic_sidecar_status": artifacts["semantic_sidecar"]["status"],
|
|
161
|
+
"artifacts": artifacts,
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _within_live_payload_budget(node_count: int, edge_count: int) -> bool:
|
|
166
|
+
estimated_dom = node_count * 4 + edge_count * 3
|
|
167
|
+
max_nodes, max_edges, max_dom_elements = resolve_viewer_limits(
|
|
168
|
+
defaults=(VIEWER_MAX_NODES, VIEWER_MAX_EDGES, VIEWER_MAX_DOM_ELEMENTS)
|
|
169
|
+
)
|
|
170
|
+
return (
|
|
171
|
+
node_count <= max_nodes
|
|
172
|
+
and edge_count <= max_edges
|
|
173
|
+
and estimated_dom <= max_dom_elements
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _compact_live_graph(graph: dict[str, object]) -> dict[str, object]:
|
|
178
|
+
return {
|
|
179
|
+
"graph_schema_version": graph.get("graph_schema_version", GRAPH_SCHEMA_VERSION),
|
|
180
|
+
"session_id": graph.get("session_id", "unknown"),
|
|
181
|
+
"source_path": graph.get("source_path"),
|
|
182
|
+
"source_schema_versions": graph.get("source_schema_versions", []),
|
|
183
|
+
"event_count": graph.get("event_count", 0),
|
|
184
|
+
"node_count": graph.get("node_count", 0),
|
|
185
|
+
"edge_count": graph.get("edge_count", 0),
|
|
186
|
+
"nodes": [],
|
|
187
|
+
"edges": [],
|
|
188
|
+
"live_payload_compact": True,
|
|
189
|
+
"evidence_counts": graph.get("evidence_counts"),
|
|
190
|
+
"session_outcome": graph.get("session_outcome"),
|
|
191
|
+
"observation_assessment": graph.get("observation_assessment"),
|
|
192
|
+
"runtime_environment": graph.get("runtime_environment"),
|
|
193
|
+
"run_assessment": graph.get("run_assessment"),
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _entity_id(entity: object) -> str | None:
|
|
198
|
+
if not isinstance(entity, dict):
|
|
199
|
+
return None
|
|
200
|
+
value = entity.get("id")
|
|
201
|
+
return value if isinstance(value, str) and value else None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _event_edge_key(event: dict[str, object]) -> tuple[str, str, str] | None:
|
|
205
|
+
source_id = _entity_id(event.get("source"))
|
|
206
|
+
target_id = _entity_id(event.get("target"))
|
|
207
|
+
relation = event.get("relation")
|
|
208
|
+
if source_id and target_id and isinstance(relation, str) and relation:
|
|
209
|
+
return (source_id, relation, target_id)
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@dataclass
|
|
214
|
+
class _JsonlTail:
|
|
215
|
+
path: Path
|
|
216
|
+
offset: int = 0
|
|
217
|
+
pending_bytes: bytes = b""
|
|
218
|
+
records_seen: int = 0
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class _LiveState:
|
|
222
|
+
def __init__(
|
|
223
|
+
self,
|
|
224
|
+
session_id: str,
|
|
225
|
+
event_path: Path,
|
|
226
|
+
semantic_path: Path | None = None,
|
|
227
|
+
) -> None:
|
|
228
|
+
self.session_id = session_id
|
|
229
|
+
self.event_path = event_path
|
|
230
|
+
self.semantic_path = semantic_path
|
|
231
|
+
self._lock = threading.Lock()
|
|
232
|
+
self._accumulator = GraphAccumulator(
|
|
233
|
+
session_id=session_id,
|
|
234
|
+
source_path=event_path,
|
|
235
|
+
retain_event_ids=False,
|
|
236
|
+
)
|
|
237
|
+
self._runtime_tail = _JsonlTail(event_path)
|
|
238
|
+
self._semantic_tail = _JsonlTail(semantic_path) if semantic_path is not None else None
|
|
239
|
+
self._semantic_normalizer = LiveSemanticNormalizer(session_id)
|
|
240
|
+
self._runtime_event_count = 0
|
|
241
|
+
self._specialized_event_count = 0
|
|
242
|
+
self._finished = False
|
|
243
|
+
self._final_graph: dict[str, object] | None = None
|
|
244
|
+
self._final_html: str | None = None
|
|
245
|
+
self._finalization_receipt = summarize_finalization(None)
|
|
246
|
+
self._update_sequence = 0
|
|
247
|
+
self._resync_floor = 0
|
|
248
|
+
self._updates: deque[dict[str, object]] = deque()
|
|
249
|
+
self._update_sizes: deque[int] = deque()
|
|
250
|
+
self._updates_bytes = 0
|
|
251
|
+
|
|
252
|
+
def _empty_graph(self) -> dict[str, object]:
|
|
253
|
+
return {
|
|
254
|
+
"graph_schema_version": GRAPH_SCHEMA_VERSION,
|
|
255
|
+
"session_id": self.session_id,
|
|
256
|
+
"source_path": str(self.event_path.resolve()),
|
|
257
|
+
"source_schema_versions": [],
|
|
258
|
+
"event_count": 0,
|
|
259
|
+
"node_count": 0,
|
|
260
|
+
"edge_count": 0,
|
|
261
|
+
"nodes": [],
|
|
262
|
+
"edges": [],
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
def _counts_locked(self) -> dict[str, object]:
|
|
266
|
+
if self._finished and self._final_graph is not None:
|
|
267
|
+
return {
|
|
268
|
+
"event_count": int(self._final_graph.get("event_count", 0) or 0),
|
|
269
|
+
"node_count": int(self._final_graph.get("node_count", 0) or 0),
|
|
270
|
+
"edge_count": int(self._final_graph.get("edge_count", 0) or 0),
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
"event_count": self._accumulator.event_count,
|
|
274
|
+
"node_count": self._accumulator.node_count,
|
|
275
|
+
"edge_count": self._accumulator.edge_count,
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
def _clear_update_history_locked(self) -> None:
|
|
279
|
+
self._updates.clear()
|
|
280
|
+
self._update_sizes.clear()
|
|
281
|
+
self._updates_bytes = 0
|
|
282
|
+
|
|
283
|
+
def _reset_incremental_state_locked(self) -> None:
|
|
284
|
+
self._accumulator = GraphAccumulator(
|
|
285
|
+
session_id=self.session_id,
|
|
286
|
+
source_path=self.event_path,
|
|
287
|
+
retain_event_ids=False,
|
|
288
|
+
)
|
|
289
|
+
tails = [self._runtime_tail]
|
|
290
|
+
if self._semantic_tail is not None:
|
|
291
|
+
tails.append(self._semantic_tail)
|
|
292
|
+
for tail in tails:
|
|
293
|
+
tail.offset = 0
|
|
294
|
+
tail.pending_bytes = b""
|
|
295
|
+
tail.records_seen = 0
|
|
296
|
+
self._semantic_normalizer.reset()
|
|
297
|
+
self._runtime_event_count = 0
|
|
298
|
+
self._specialized_event_count = 0
|
|
299
|
+
self._clear_update_history_locked()
|
|
300
|
+
self._update_sequence += 1
|
|
301
|
+
self._resync_floor = self._update_sequence
|
|
302
|
+
|
|
303
|
+
def _snapshot_from_accumulator_locked(self) -> dict[str, object]:
|
|
304
|
+
if self._finished and self._final_graph is not None:
|
|
305
|
+
graph = self._final_graph
|
|
306
|
+
node_count = int(graph.get("node_count", 0) or 0)
|
|
307
|
+
edge_count = int(graph.get("edge_count", 0) or 0)
|
|
308
|
+
return (
|
|
309
|
+
dict(graph)
|
|
310
|
+
if _within_live_payload_budget(node_count, edge_count)
|
|
311
|
+
else _compact_live_graph(graph)
|
|
312
|
+
)
|
|
313
|
+
if _within_live_payload_budget(
|
|
314
|
+
self._accumulator.node_count,
|
|
315
|
+
self._accumulator.edge_count,
|
|
316
|
+
):
|
|
317
|
+
return self._accumulator.to_dict()
|
|
318
|
+
return _compact_live_graph(
|
|
319
|
+
{
|
|
320
|
+
"graph_schema_version": GRAPH_SCHEMA_VERSION,
|
|
321
|
+
"session_id": self.session_id,
|
|
322
|
+
"source_path": self._accumulator.source_path,
|
|
323
|
+
"source_schema_versions": sorted(self._accumulator.source_schema_versions),
|
|
324
|
+
"event_count": self._accumulator.event_count,
|
|
325
|
+
"node_count": self._accumulator.node_count,
|
|
326
|
+
"edge_count": self._accumulator.edge_count,
|
|
327
|
+
}
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
def _append_update_locked(self, update: dict[str, object]) -> None:
|
|
331
|
+
self._update_sequence += 1
|
|
332
|
+
update["sequence"] = self._update_sequence
|
|
333
|
+
encoded_size = len(
|
|
334
|
+
json.dumps(update, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
335
|
+
)
|
|
336
|
+
self._updates.append(update)
|
|
337
|
+
self._update_sizes.append(encoded_size)
|
|
338
|
+
self._updates_bytes += encoded_size
|
|
339
|
+
while (
|
|
340
|
+
len(self._updates) > LIVE_DELTA_HISTORY
|
|
341
|
+
or self._updates_bytes > LIVE_DELTA_HISTORY_BYTES
|
|
342
|
+
):
|
|
343
|
+
evicted = self._updates.popleft()
|
|
344
|
+
self._updates_bytes -= self._update_sizes.popleft()
|
|
345
|
+
self._resync_floor = max(self._resync_floor, int(evicted["sequence"]))
|
|
346
|
+
|
|
347
|
+
def _tail_truncated_locked(self, tail: _JsonlTail) -> bool:
|
|
348
|
+
try:
|
|
349
|
+
return tail.path.stat().st_size < tail.offset
|
|
350
|
+
except OSError:
|
|
351
|
+
return False
|
|
352
|
+
|
|
353
|
+
def _read_tail_records_locked(
|
|
354
|
+
self,
|
|
355
|
+
tail: _JsonlTail,
|
|
356
|
+
) -> list[tuple[int, dict[str, object]]]:
|
|
357
|
+
try:
|
|
358
|
+
file_size = tail.path.stat().st_size
|
|
359
|
+
except OSError:
|
|
360
|
+
return []
|
|
361
|
+
if file_size <= tail.offset:
|
|
362
|
+
return []
|
|
363
|
+
try:
|
|
364
|
+
with tail.path.open("rb") as handle:
|
|
365
|
+
handle.seek(tail.offset)
|
|
366
|
+
chunk = handle.read()
|
|
367
|
+
except OSError:
|
|
368
|
+
return []
|
|
369
|
+
if not chunk:
|
|
370
|
+
return []
|
|
371
|
+
tail.offset += len(chunk)
|
|
372
|
+
buffered = tail.pending_bytes + chunk
|
|
373
|
+
lines = buffered.split(b"\n")
|
|
374
|
+
tail.pending_bytes = lines.pop()
|
|
375
|
+
records: list[tuple[int, dict[str, object]]] = []
|
|
376
|
+
for raw_line in lines:
|
|
377
|
+
if not raw_line.strip():
|
|
378
|
+
continue
|
|
379
|
+
tail.records_seen += 1
|
|
380
|
+
try:
|
|
381
|
+
payload = json.loads(raw_line.decode("utf-8"))
|
|
382
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
383
|
+
continue
|
|
384
|
+
if isinstance(payload, dict):
|
|
385
|
+
records.append((tail.records_seen, payload))
|
|
386
|
+
return records
|
|
387
|
+
|
|
388
|
+
def _apply_live_event_locked(
|
|
389
|
+
self,
|
|
390
|
+
event: dict[str, object],
|
|
391
|
+
*,
|
|
392
|
+
added_nodes: set[str],
|
|
393
|
+
updated_nodes: set[str],
|
|
394
|
+
added_edges: set[tuple[str, str, str]],
|
|
395
|
+
updated_edges: set[tuple[str, str, str]],
|
|
396
|
+
) -> bool:
|
|
397
|
+
source_id = _entity_id(event.get("source"))
|
|
398
|
+
target_id = _entity_id(event.get("target"))
|
|
399
|
+
node_ids = {value for value in (source_id, target_id) if value}
|
|
400
|
+
existing_nodes = {
|
|
401
|
+
node_id for node_id in node_ids if node_id in self._accumulator.nodes
|
|
402
|
+
}
|
|
403
|
+
edge_key = _event_edge_key(event)
|
|
404
|
+
edge_existed = edge_key in self._accumulator.edges if edge_key is not None else False
|
|
405
|
+
try:
|
|
406
|
+
self._accumulator.apply(event)
|
|
407
|
+
except (TypeError, ValueError):
|
|
408
|
+
return False
|
|
409
|
+
|
|
410
|
+
for node_id in node_ids:
|
|
411
|
+
if node_id in existing_nodes and node_id not in added_nodes:
|
|
412
|
+
updated_nodes.add(node_id)
|
|
413
|
+
else:
|
|
414
|
+
added_nodes.add(node_id)
|
|
415
|
+
updated_nodes.discard(node_id)
|
|
416
|
+
if edge_key is not None and edge_key in self._accumulator.edges:
|
|
417
|
+
if edge_existed and edge_key not in added_edges:
|
|
418
|
+
updated_edges.add(edge_key)
|
|
419
|
+
else:
|
|
420
|
+
added_edges.add(edge_key)
|
|
421
|
+
updated_edges.discard(edge_key)
|
|
422
|
+
return True
|
|
423
|
+
|
|
424
|
+
def _refresh_incremental_locked(self) -> None:
|
|
425
|
+
tails = [self._runtime_tail]
|
|
426
|
+
if self._semantic_tail is not None:
|
|
427
|
+
tails.append(self._semantic_tail)
|
|
428
|
+
if any(self._tail_truncated_locked(tail) for tail in tails):
|
|
429
|
+
self._reset_incremental_state_locked()
|
|
430
|
+
|
|
431
|
+
added_nodes: set[str] = set()
|
|
432
|
+
updated_nodes: set[str] = set()
|
|
433
|
+
added_edges: set[tuple[str, str, str]] = set()
|
|
434
|
+
updated_edges: set[tuple[str, str, str]] = set()
|
|
435
|
+
runtime_applied = 0
|
|
436
|
+
specialized_applied = 0
|
|
437
|
+
|
|
438
|
+
for _, event in self._read_tail_records_locked(self._runtime_tail):
|
|
439
|
+
if not self._apply_live_event_locked(
|
|
440
|
+
event,
|
|
441
|
+
added_nodes=added_nodes,
|
|
442
|
+
updated_nodes=updated_nodes,
|
|
443
|
+
added_edges=added_edges,
|
|
444
|
+
updated_edges=updated_edges,
|
|
445
|
+
):
|
|
446
|
+
continue
|
|
447
|
+
self._semantic_normalizer.observe_runtime_event(event)
|
|
448
|
+
self._runtime_event_count += 1
|
|
449
|
+
runtime_applied += 1
|
|
450
|
+
|
|
451
|
+
if self._semantic_tail is not None and self._semantic_normalizer.ready:
|
|
452
|
+
for line_number, record in self._read_tail_records_locked(self._semantic_tail):
|
|
453
|
+
try:
|
|
454
|
+
normalized = self._semantic_normalizer.normalize(
|
|
455
|
+
record,
|
|
456
|
+
line_number=line_number,
|
|
457
|
+
)
|
|
458
|
+
except ValueError:
|
|
459
|
+
continue
|
|
460
|
+
if normalized is None:
|
|
461
|
+
continue
|
|
462
|
+
if not self._apply_live_event_locked(
|
|
463
|
+
normalized,
|
|
464
|
+
added_nodes=added_nodes,
|
|
465
|
+
updated_nodes=updated_nodes,
|
|
466
|
+
added_edges=added_edges,
|
|
467
|
+
updated_edges=updated_edges,
|
|
468
|
+
):
|
|
469
|
+
continue
|
|
470
|
+
self._specialized_event_count += 1
|
|
471
|
+
specialized_applied += 1
|
|
472
|
+
|
|
473
|
+
applied_count = runtime_applied + specialized_applied
|
|
474
|
+
if not applied_count:
|
|
475
|
+
return
|
|
476
|
+
|
|
477
|
+
counts = self._counts_locked()
|
|
478
|
+
node_count = int(counts["node_count"])
|
|
479
|
+
edge_count = int(counts["edge_count"])
|
|
480
|
+
compact = not _within_live_payload_budget(node_count, edge_count)
|
|
481
|
+
update: dict[str, object] = {
|
|
482
|
+
**counts,
|
|
483
|
+
"event_count_delta": applied_count,
|
|
484
|
+
"evidence_event_count_delta": {
|
|
485
|
+
"os_runtime": runtime_applied,
|
|
486
|
+
"specialized": specialized_applied,
|
|
487
|
+
},
|
|
488
|
+
"nodes_added": [],
|
|
489
|
+
"nodes_updated": [],
|
|
490
|
+
"edges_added": [],
|
|
491
|
+
"edges_updated": [],
|
|
492
|
+
}
|
|
493
|
+
if compact:
|
|
494
|
+
update["live_payload_compact"] = True
|
|
495
|
+
else:
|
|
496
|
+
update["nodes_added"] = [
|
|
497
|
+
self._accumulator.nodes[node_id].to_dict()
|
|
498
|
+
for node_id in sorted(added_nodes)
|
|
499
|
+
if node_id in self._accumulator.nodes
|
|
500
|
+
]
|
|
501
|
+
update["nodes_updated"] = [
|
|
502
|
+
self._accumulator.nodes[node_id].to_dict()
|
|
503
|
+
for node_id in sorted(updated_nodes - added_nodes)
|
|
504
|
+
if node_id in self._accumulator.nodes
|
|
505
|
+
]
|
|
506
|
+
update["edges_added"] = [
|
|
507
|
+
self._accumulator.edges[key].to_dict()
|
|
508
|
+
for key in sorted(added_edges)
|
|
509
|
+
if key in self._accumulator.edges
|
|
510
|
+
]
|
|
511
|
+
update["edges_updated"] = [
|
|
512
|
+
self._accumulator.edges[key].to_dict()
|
|
513
|
+
for key in sorted(updated_edges - added_edges)
|
|
514
|
+
if key in self._accumulator.edges
|
|
515
|
+
]
|
|
516
|
+
self._append_update_locked(update)
|
|
517
|
+
|
|
518
|
+
def publish_finalization(self, report: dict[str, object]) -> None:
|
|
519
|
+
"""Publish a bounded receipt without rereading or rewriting the archive."""
|
|
520
|
+
receipt = summarize_finalization(report)
|
|
521
|
+
with self._lock:
|
|
522
|
+
self._finalization_receipt = receipt
|
|
523
|
+
|
|
524
|
+
def _evidence_metadata_locked(self) -> dict[str, object]:
|
|
525
|
+
# Cache metadata work per published sequence, including the terminal switch.
|
|
526
|
+
# No content files or provider bodies are opened by this assessment.
|
|
527
|
+
version = (self._update_sequence, self._finished)
|
|
528
|
+
if getattr(self, "_assessment_version", None) != version:
|
|
529
|
+
raw = self._final_graph if self._finished and self._final_graph is not None else self._accumulator.to_dict()
|
|
530
|
+
self._assessment_snapshot = build_run_assessment(raw)
|
|
531
|
+
self._assessment_version = version
|
|
532
|
+
return {
|
|
533
|
+
"run_assessment": self._assessment_snapshot,
|
|
534
|
+
"finalization_assessment": {
|
|
535
|
+
**self._finalization_receipt,
|
|
536
|
+
"session_id": self._assessment_snapshot.get("session_id"),
|
|
537
|
+
"source_path": self._assessment_snapshot.get("source_path"),
|
|
538
|
+
},
|
|
539
|
+
"live_evidence_counts": {
|
|
540
|
+
"os_runtime": self._runtime_event_count,
|
|
541
|
+
"specialized": self._specialized_event_count,
|
|
542
|
+
},
|
|
543
|
+
"live_specialized_provisional": (
|
|
544
|
+
self._specialized_event_count > 0 and not self._finished
|
|
545
|
+
),
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
def snapshot(self) -> dict[str, object]:
|
|
549
|
+
with self._lock:
|
|
550
|
+
if not self._finished:
|
|
551
|
+
self._refresh_incremental_locked()
|
|
552
|
+
payload = self._snapshot_from_accumulator_locked()
|
|
553
|
+
payload["live_finished"] = self._finished
|
|
554
|
+
payload.update(self._evidence_metadata_locked())
|
|
555
|
+
return payload
|
|
556
|
+
|
|
557
|
+
def live_update(self, after: int | None) -> dict[str, object]:
|
|
558
|
+
with self._lock:
|
|
559
|
+
if not self._finished:
|
|
560
|
+
self._refresh_incremental_locked()
|
|
561
|
+
if after is None or after < 0:
|
|
562
|
+
return {
|
|
563
|
+
"kind": "snapshot",
|
|
564
|
+
"sequence": self._update_sequence,
|
|
565
|
+
"graph": self._snapshot_from_accumulator_locked(),
|
|
566
|
+
**self._evidence_metadata_locked(),
|
|
567
|
+
"live_finished": self._finished,
|
|
568
|
+
}
|
|
569
|
+
oldest_sequence = (
|
|
570
|
+
int(self._updates[0]["sequence"]) if self._updates else self._update_sequence + 1
|
|
571
|
+
)
|
|
572
|
+
history_gap = after < self._resync_floor or (
|
|
573
|
+
self._updates and after < oldest_sequence - 1
|
|
574
|
+
)
|
|
575
|
+
if after > self._update_sequence or history_gap:
|
|
576
|
+
return {
|
|
577
|
+
"kind": "snapshot",
|
|
578
|
+
"sequence": self._update_sequence,
|
|
579
|
+
"graph": self._snapshot_from_accumulator_locked(),
|
|
580
|
+
**self._evidence_metadata_locked(),
|
|
581
|
+
"live_finished": self._finished,
|
|
582
|
+
"resync": True,
|
|
583
|
+
"resync_reason": "future_sequence" if after > self._update_sequence else "history_gap",
|
|
584
|
+
}
|
|
585
|
+
counts = self._counts_locked()
|
|
586
|
+
if after == self._update_sequence:
|
|
587
|
+
return {
|
|
588
|
+
"kind": "noop",
|
|
589
|
+
"sequence": self._update_sequence,
|
|
590
|
+
**counts,
|
|
591
|
+
**self._evidence_metadata_locked(),
|
|
592
|
+
"live_finished": self._finished,
|
|
593
|
+
}
|
|
594
|
+
updates = [dict(update) for update in self._updates if int(update["sequence"]) > after]
|
|
595
|
+
return {
|
|
596
|
+
"kind": "delta",
|
|
597
|
+
"base_sequence": after,
|
|
598
|
+
"sequence": self._update_sequence,
|
|
599
|
+
"updates": updates,
|
|
600
|
+
**counts,
|
|
601
|
+
**self._evidence_metadata_locked(),
|
|
602
|
+
"live_finished": self._finished,
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
def finish(self, graph: dict[str, object], *, final_html: str | None = None) -> None:
|
|
606
|
+
final_graph = dict(graph)
|
|
607
|
+
rendered_final = (
|
|
608
|
+
final_html
|
|
609
|
+
if isinstance(final_html, str)
|
|
610
|
+
else _inject_final_theme(render_graph_html(final_graph))
|
|
611
|
+
)
|
|
612
|
+
with self._lock:
|
|
613
|
+
# The last browser poll may precede the collector's final batch.
|
|
614
|
+
# Drain complete runtime/semantic records for raw-log and evidence
|
|
615
|
+
# counters before publishing FINISHED. The canonical graph below,
|
|
616
|
+
# not the provisional accumulator, remains the graph authority.
|
|
617
|
+
self._refresh_incremental_locked()
|
|
618
|
+
self._final_graph = final_graph
|
|
619
|
+
self._final_html = rendered_final
|
|
620
|
+
self._finished = True
|
|
621
|
+
counts = self._counts_locked()
|
|
622
|
+
node_count = int(counts["node_count"])
|
|
623
|
+
edge_count = int(counts["edge_count"])
|
|
624
|
+
terminal: dict[str, object] = {
|
|
625
|
+
**counts,
|
|
626
|
+
"event_count_delta": 0,
|
|
627
|
+
"nodes_added": [],
|
|
628
|
+
"nodes_updated": [],
|
|
629
|
+
"edges_added": [],
|
|
630
|
+
"edges_updated": [],
|
|
631
|
+
"terminal": True,
|
|
632
|
+
# A counts-only terminal delta loses unpolled nodes/edges and
|
|
633
|
+
# canonical identity/metadata changes. Reconcile in this same
|
|
634
|
+
# sequence-visible response, before the client stops polling.
|
|
635
|
+
# Use the normal projection and payload budget, as on reconnect.
|
|
636
|
+
"final_graph": self._snapshot_from_accumulator_locked(),
|
|
637
|
+
}
|
|
638
|
+
if not _within_live_payload_budget(node_count, edge_count):
|
|
639
|
+
terminal["live_payload_compact"] = True
|
|
640
|
+
self._append_update_locked(terminal)
|
|
641
|
+
|
|
642
|
+
def final_html(self) -> str | None:
|
|
643
|
+
with self._lock:
|
|
644
|
+
return self._final_html
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _handler_factory(
|
|
648
|
+
state: _LiveState, token: str, pairing: _PairingGate | None = None
|
|
649
|
+
):
|
|
650
|
+
pairing = pairing or _PairingGate(secrets.token_urlsafe(18))
|
|
651
|
+
cookie_name = "execweave_live"
|
|
652
|
+
|
|
653
|
+
class Handler(BaseHTTPRequestHandler):
|
|
654
|
+
def log_message(self, format: str, *args: object) -> None:
|
|
655
|
+
return
|
|
656
|
+
|
|
657
|
+
def _send(
|
|
658
|
+
self,
|
|
659
|
+
body: bytes,
|
|
660
|
+
content_type: str,
|
|
661
|
+
status: int = 200,
|
|
662
|
+
*,
|
|
663
|
+
headers: tuple[tuple[str, str], ...] = (),
|
|
664
|
+
) -> None:
|
|
665
|
+
try:
|
|
666
|
+
self.send_response(status)
|
|
667
|
+
self.send_header("Content-Type", content_type)
|
|
668
|
+
self.send_header("Content-Length", str(len(body)))
|
|
669
|
+
self.send_header("Cache-Control", "no-store")
|
|
670
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
671
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
672
|
+
self.send_header("Content-Security-Policy", "default-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'")
|
|
673
|
+
for name, value in headers:
|
|
674
|
+
self.send_header(name, value)
|
|
675
|
+
self.end_headers()
|
|
676
|
+
self.wfile.write(body)
|
|
677
|
+
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
|
|
678
|
+
self.close_connection = True
|
|
679
|
+
|
|
680
|
+
def _authorized(self, parsed) -> bool:
|
|
681
|
+
candidate = self.headers.get(_LIVE_TOKEN_HEADER)
|
|
682
|
+
if candidate is None:
|
|
683
|
+
raw_cookie = self.headers.get("Cookie", "")
|
|
684
|
+
try:
|
|
685
|
+
cookies = SimpleCookie()
|
|
686
|
+
cookies.load(raw_cookie)
|
|
687
|
+
morsel = cookies.get(cookie_name)
|
|
688
|
+
candidate = morsel.value if morsel is not None else None
|
|
689
|
+
except (KeyError, TypeError, ValueError):
|
|
690
|
+
candidate = None
|
|
691
|
+
# Query-string credentials are intentionally unsupported. A credential
|
|
692
|
+
# in a request target can leak through terminal output, browser history,
|
|
693
|
+
# proxies, crash reports and access logs.
|
|
694
|
+
return bool(candidate) and hmac.compare_digest(candidate, token)
|
|
695
|
+
|
|
696
|
+
def do_POST(self) -> None:
|
|
697
|
+
parsed = urlsplit(self.path)
|
|
698
|
+
if parsed.path != "/pair" or parsed.query or parsed.fragment:
|
|
699
|
+
self._send(b"Not found", "text/plain; charset=utf-8", 404)
|
|
700
|
+
return
|
|
701
|
+
try:
|
|
702
|
+
length = int(self.headers.get("Content-Length", "0"))
|
|
703
|
+
except ValueError:
|
|
704
|
+
length = -1
|
|
705
|
+
if length < 0 or length > 4096:
|
|
706
|
+
self._send(b"Invalid pairing request", "text/plain; charset=utf-8", 400)
|
|
707
|
+
return
|
|
708
|
+
raw = self.rfile.read(length)
|
|
709
|
+
try:
|
|
710
|
+
values = parse_qs(raw.decode("utf-8"), keep_blank_values=True).get("code", [])
|
|
711
|
+
except UnicodeDecodeError:
|
|
712
|
+
values = []
|
|
713
|
+
if len(values) != 1 or not pairing.consume(values[0]):
|
|
714
|
+
self._send(b"Pairing code rejected", "text/plain; charset=utf-8", 403)
|
|
715
|
+
return
|
|
716
|
+
self._send(
|
|
717
|
+
b"",
|
|
718
|
+
"text/plain; charset=utf-8",
|
|
719
|
+
303,
|
|
720
|
+
headers=(
|
|
721
|
+
("Set-Cookie", f"{cookie_name}={token}; HttpOnly; SameSite=Strict; Path=/"),
|
|
722
|
+
("Location", "/"),
|
|
723
|
+
),
|
|
724
|
+
)
|
|
725
|
+
|
|
726
|
+
def do_GET(self) -> None:
|
|
727
|
+
parsed = urlsplit(self.path)
|
|
728
|
+
path = parsed.path
|
|
729
|
+
if path == "/favicon.ico" and not parsed.query and not parsed.fragment:
|
|
730
|
+
# Browsers may request a favicon before pairing/authentication.
|
|
731
|
+
# Return no content so this cosmetic request cannot leak run evidence
|
|
732
|
+
# or create a misleading authentication error in the JS console.
|
|
733
|
+
self._send(b"", "image/x-icon", 204)
|
|
734
|
+
return
|
|
735
|
+
if path == "/" and not self._authorized(parsed):
|
|
736
|
+
# This page contains no run evidence and no authentication secret.
|
|
737
|
+
self._send(_PAIRING_HTML.encode("utf-8"), "text/html; charset=utf-8")
|
|
738
|
+
return
|
|
739
|
+
if not self._authorized(parsed):
|
|
740
|
+
self._send(b"Unauthorized", "text/plain; charset=utf-8", 401)
|
|
741
|
+
return
|
|
742
|
+
if path == "/":
|
|
743
|
+
page = _live_page(_AUTHENTICATED_LIVE_HTML, resolve_fold_budget())
|
|
744
|
+
self._send(page.encode("utf-8"), "text/html; charset=utf-8")
|
|
745
|
+
return
|
|
746
|
+
if path == "/graph.json":
|
|
747
|
+
payload = json.dumps(
|
|
748
|
+
state.snapshot(), ensure_ascii=False, separators=(",", ":")
|
|
749
|
+
).encode("utf-8")
|
|
750
|
+
self._send(payload, "application/json; charset=utf-8")
|
|
751
|
+
return
|
|
752
|
+
if path == "/live.json":
|
|
753
|
+
values = parse_qs(parsed.query).get("after", [])
|
|
754
|
+
try:
|
|
755
|
+
after = int(values[0]) if values else None
|
|
756
|
+
except (TypeError, ValueError):
|
|
757
|
+
self._send(b"Invalid after sequence", "text/plain; charset=utf-8", 400)
|
|
758
|
+
return
|
|
759
|
+
payload = json.dumps(
|
|
760
|
+
state.live_update(after), ensure_ascii=False, separators=(",", ":")
|
|
761
|
+
).encode("utf-8")
|
|
762
|
+
self._send(payload, "application/json; charset=utf-8")
|
|
763
|
+
return
|
|
764
|
+
if path == "/final":
|
|
765
|
+
final = state.final_html()
|
|
766
|
+
if final is None:
|
|
767
|
+
self._send(b"Final graph is not ready", "text/plain; charset=utf-8", 404)
|
|
768
|
+
else:
|
|
769
|
+
self._send(final.encode("utf-8"), "text/html; charset=utf-8")
|
|
770
|
+
return
|
|
771
|
+
self._send(b"Not found", "text/plain; charset=utf-8", 404)
|
|
772
|
+
|
|
773
|
+
return Handler
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
class _LocalThreadingHTTPServer(ThreadingHTTPServer):
|
|
777
|
+
"""Local HTTP server that skips HTTPServer's reverse-DNS lookup during bind."""
|
|
778
|
+
|
|
779
|
+
def server_bind(self) -> None:
|
|
780
|
+
TCPServer.server_bind(self)
|
|
781
|
+
host, port = self.server_address[:2]
|
|
782
|
+
self.server_name = str(host)
|
|
783
|
+
self.server_port = int(port)
|
|
784
|
+
|
|
785
|
+
def handle_error(self, request, client_address) -> None: # type: ignore[no-untyped-def]
|
|
786
|
+
"""Silence only expected browser disconnects at the handler lifecycle boundary."""
|
|
787
|
+
error = sys.exc_info()[1]
|
|
788
|
+
if isinstance(error, (BrokenPipeError, ConnectionResetError, ConnectionAbortedError)):
|
|
789
|
+
return
|
|
790
|
+
super().handle_error(request, client_address)
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def run_live(
|
|
794
|
+
command: list[str],
|
|
795
|
+
*,
|
|
796
|
+
watch_root: str | Path,
|
|
797
|
+
output_dir: str | Path | None = None,
|
|
798
|
+
poll_interval: float = 0.10,
|
|
799
|
+
collect_filesystem: bool = True,
|
|
800
|
+
collect_network: bool = True,
|
|
801
|
+
port: int = 0,
|
|
802
|
+
open_browser: bool = True,
|
|
803
|
+
linger_seconds: float = 2.0,
|
|
804
|
+
content_capture: str = "full",
|
|
805
|
+
announce: Callable[[str], None] | None = None,
|
|
806
|
+
announce_pairing_code: Callable[[str], None] | None = None,
|
|
807
|
+
announce_api_token: Callable[[str], None] | None = None,
|
|
808
|
+
) -> LiveResult:
|
|
809
|
+
"""Run a command with the portable collector and expose an authenticated localhost graph."""
|
|
810
|
+
if not command:
|
|
811
|
+
raise ValueError("command must not be empty")
|
|
812
|
+
if port < 0 or port > 65535:
|
|
813
|
+
raise ValueError("port must be between 0 and 65535")
|
|
814
|
+
if linger_seconds < 0:
|
|
815
|
+
raise ValueError("linger_seconds must be >= 0")
|
|
816
|
+
if content_capture not in {"metadata_only", "full"}:
|
|
817
|
+
raise ValueError("content_capture must be metadata_only or full")
|
|
818
|
+
|
|
819
|
+
session_id = uuid4().hex
|
|
820
|
+
live_token = secrets.token_urlsafe(32)
|
|
821
|
+
pairing_code = secrets.token_urlsafe(18)
|
|
822
|
+
pairing_gate = _PairingGate(pairing_code)
|
|
823
|
+
root = Path(watch_root).expanduser().resolve()
|
|
824
|
+
run_dir = (
|
|
825
|
+
Path(output_dir).expanduser().resolve()
|
|
826
|
+
if output_dir is not None
|
|
827
|
+
else root / ".execweave" / "runs" / session_id
|
|
828
|
+
)
|
|
829
|
+
run_dir.mkdir(parents=True, exist_ok=True)
|
|
830
|
+
event_path = run_dir / "events.jsonl"
|
|
831
|
+
semantic_path = run_dir / "semantic.jsonl"
|
|
832
|
+
merged_event_path = run_dir / "events.semantic.jsonl"
|
|
833
|
+
graph_path = run_dir / "graph.json"
|
|
834
|
+
viewer_path = run_dir / "viewer.html"
|
|
835
|
+
for artifact in (event_path, semantic_path, merged_event_path, graph_path, viewer_path):
|
|
836
|
+
if artifact.exists() and artifact.stat().st_size > 0:
|
|
837
|
+
raise FileExistsError(f"ExecWeave live artifact already exists: {artifact}")
|
|
838
|
+
|
|
839
|
+
recording_report = record_finalization(run_dir, state="recording")
|
|
840
|
+
sink = JsonlSink(event_path)
|
|
841
|
+
collector = create_collector(
|
|
842
|
+
backend="portable",
|
|
843
|
+
session_id=session_id,
|
|
844
|
+
sink=sink,
|
|
845
|
+
watch_root=root,
|
|
846
|
+
poll_interval=poll_interval,
|
|
847
|
+
collect_filesystem=collect_filesystem,
|
|
848
|
+
collect_network=collect_network,
|
|
849
|
+
)
|
|
850
|
+
|
|
851
|
+
state = _LiveState(session_id, event_path, semantic_path)
|
|
852
|
+
state.publish_finalization(recording_report)
|
|
853
|
+
server = _LocalThreadingHTTPServer(
|
|
854
|
+
("127.0.0.1", port), _handler_factory(state, live_token, pairing_gate)
|
|
855
|
+
)
|
|
856
|
+
server.daemon_threads = True
|
|
857
|
+
server_thread = threading.Thread(
|
|
858
|
+
target=server.serve_forever,
|
|
859
|
+
name="execweave-live",
|
|
860
|
+
daemon=True,
|
|
861
|
+
)
|
|
862
|
+
server_thread.start()
|
|
863
|
+
host, selected_port = server.server_address[:2]
|
|
864
|
+
live_url = f"http://{host}:{selected_port}/"
|
|
865
|
+
if announce is not None:
|
|
866
|
+
announce(live_url)
|
|
867
|
+
if announce_pairing_code is not None:
|
|
868
|
+
announce_pairing_code(pairing_code)
|
|
869
|
+
if announce_api_token is not None:
|
|
870
|
+
announce_api_token(live_token)
|
|
871
|
+
if open_browser:
|
|
872
|
+
webbrowser.open(live_url)
|
|
873
|
+
|
|
874
|
+
return_code = 1
|
|
875
|
+
environment_updates = {
|
|
876
|
+
_SEMANTIC_ENV: str(semantic_path),
|
|
877
|
+
_RUN_ID_ENV: session_id,
|
|
878
|
+
_SESSION_ID_ENV: session_id,
|
|
879
|
+
CONTENT_CAPTURE_ENV: content_capture,
|
|
880
|
+
}
|
|
881
|
+
previous_environment = {
|
|
882
|
+
key: os.environ.get(key) for key in environment_updates
|
|
883
|
+
}
|
|
884
|
+
os.environ.update(environment_updates)
|
|
885
|
+
collection_error: Exception | None = None
|
|
886
|
+
export_complete = False
|
|
887
|
+
try:
|
|
888
|
+
try:
|
|
889
|
+
return_code = collector.run(command)
|
|
890
|
+
except Exception as exc:
|
|
891
|
+
# The collector can have written a valid terminal stream before
|
|
892
|
+
# raising. Export it rather than leaving only raw evidence behind.
|
|
893
|
+
collection_error = exc
|
|
894
|
+
finally:
|
|
895
|
+
for key, value in previous_environment.items():
|
|
896
|
+
if value is None:
|
|
897
|
+
os.environ.pop(key, None)
|
|
898
|
+
else:
|
|
899
|
+
os.environ[key] = value
|
|
900
|
+
|
|
901
|
+
state.publish_finalization(record_finalization(run_dir, state="exporting", error=collection_error))
|
|
902
|
+
validation = validate_event_stream(event_path)
|
|
903
|
+
if not validation.valid:
|
|
904
|
+
details = "; ".join(validation.errors)
|
|
905
|
+
raise RuntimeError(f"live event stream failed validation: {details}")
|
|
906
|
+
|
|
907
|
+
materialized_event_path = event_path
|
|
908
|
+
if semantic_path.exists() and semantic_path.stat().st_size > 0:
|
|
909
|
+
merge_semantic_sidecar(event_path, semantic_path, merged_event_path)
|
|
910
|
+
materialized_event_path = merged_event_path
|
|
911
|
+
|
|
912
|
+
execution_graph = build_execution_graph(materialized_event_path)
|
|
913
|
+
graph_payload = execution_graph.to_dict()
|
|
914
|
+
write_execution_graph(execution_graph, graph_path)
|
|
915
|
+
# The extracted core must materialize the conversation index itself. The
|
|
916
|
+
# projected live wrapper also writes it, but direct live_core callers (and
|
|
917
|
+
# failure-path export) must not depend on that presentation monkeypatch.
|
|
918
|
+
write_conversation_records(graph_payload, run_dir)
|
|
919
|
+
write_graph_html(graph_payload, viewer_path, open_browser=False)
|
|
920
|
+
state.publish_finalization(record_finalization(run_dir, state="complete", error=collection_error))
|
|
921
|
+
export_complete = True
|
|
922
|
+
state.finish(graph_payload, final_html=viewer_path.read_text(encoding="utf-8"))
|
|
923
|
+
if linger_seconds:
|
|
924
|
+
time.sleep(linger_seconds)
|
|
925
|
+
|
|
926
|
+
if collection_error is not None:
|
|
927
|
+
raise collection_error
|
|
928
|
+
|
|
929
|
+
return LiveResult(
|
|
930
|
+
session_id=session_id,
|
|
931
|
+
return_code=return_code,
|
|
932
|
+
live_url=live_url,
|
|
933
|
+
output_dir=run_dir,
|
|
934
|
+
event_stream=event_path,
|
|
935
|
+
semantic_sidecar=semantic_path,
|
|
936
|
+
materialized_event_stream=materialized_event_path,
|
|
937
|
+
graph=graph_path,
|
|
938
|
+
viewer=viewer_path,
|
|
939
|
+
)
|
|
940
|
+
except Exception as exc:
|
|
941
|
+
# Export/finalization diagnostics are secondary to an already observed
|
|
942
|
+
# collector failure. Preserve the primary exception and attach later
|
|
943
|
+
# failures as notes rather than replacing the root cause.
|
|
944
|
+
primary_error = collection_error if collection_error is not None else exc
|
|
945
|
+
if collection_error is not None and exc is not collection_error:
|
|
946
|
+
try:
|
|
947
|
+
collection_error.add_note(
|
|
948
|
+
f"secondary export failure: {type(exc).__name__}: {exc}"
|
|
949
|
+
)
|
|
950
|
+
except AttributeError: # pragma: no cover - Python < 3.11 compatibility
|
|
951
|
+
pass
|
|
952
|
+
try:
|
|
953
|
+
state.publish_finalization(record_finalization(
|
|
954
|
+
run_dir,
|
|
955
|
+
state="complete" if export_complete else "failed",
|
|
956
|
+
error=primary_error,
|
|
957
|
+
))
|
|
958
|
+
except Exception as finalization_error:
|
|
959
|
+
try:
|
|
960
|
+
primary_error.add_note(
|
|
961
|
+
"secondary finalization diagnostic failure: "
|
|
962
|
+
f"{type(finalization_error).__name__}: {finalization_error}"
|
|
963
|
+
)
|
|
964
|
+
except AttributeError: # pragma: no cover - Python < 3.11 compatibility
|
|
965
|
+
pass
|
|
966
|
+
if primary_error is not exc:
|
|
967
|
+
raise primary_error from exc
|
|
968
|
+
raise
|
|
969
|
+
finally:
|
|
970
|
+
server.shutdown()
|
|
971
|
+
server.server_close()
|
|
972
|
+
server_thread.join(timeout=5)
|