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/filesystem.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import errno
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import warnings
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Iterable
|
|
9
|
+
|
|
10
|
+
from watchdog.events import FileSystemEvent, FileSystemEventHandler, FileCreatedEvent, FileModifiedEvent, FileDeletedEvent
|
|
11
|
+
from watchdog.observers import Observer
|
|
12
|
+
from watchdog.observers.polling import PollingObserver
|
|
13
|
+
|
|
14
|
+
from .schema import Entity, RuntimeEvent
|
|
15
|
+
from .sink import JsonlSink
|
|
16
|
+
from .risk import risk_attributes, system_path_category
|
|
17
|
+
|
|
18
|
+
LINUX_INOTIFY_MIN_SAFE_DIRS = 2048
|
|
19
|
+
LINUX_INOTIFY_MAX_SAFE_DIRS = 32768
|
|
20
|
+
_LINUX_INOTIFY_LIMIT = Path("/proc/sys/fs/inotify/max_user_watches")
|
|
21
|
+
_INOTIFY_RESOURCE_ERRNOS = {errno.ENOSPC, errno.EMFILE}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _linux_inotify_directory_budget() -> int | None:
|
|
25
|
+
"""Return a conservative per-session directory budget on Linux.
|
|
26
|
+
|
|
27
|
+
watchdog's recursive inotify observer consumes approximately one kernel watch
|
|
28
|
+
per directory. ExecWeave does not know how many watches editors, language
|
|
29
|
+
servers, containers, or other processes already consume, so it deliberately
|
|
30
|
+
reserves most of the kernel limit for the rest of the system. The returned
|
|
31
|
+
budget never exceeds one quarter of the configured per-user watch limit.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
if not sys.platform.startswith("linux"):
|
|
35
|
+
return None
|
|
36
|
+
try:
|
|
37
|
+
configured = int(_LINUX_INOTIFY_LIMIT.read_text(encoding="utf-8").strip())
|
|
38
|
+
except (OSError, ValueError):
|
|
39
|
+
configured = 32768
|
|
40
|
+
|
|
41
|
+
quarter = max(1, configured // 4)
|
|
42
|
+
if quarter < LINUX_INOTIFY_MIN_SAFE_DIRS:
|
|
43
|
+
return quarter
|
|
44
|
+
return min(LINUX_INOTIFY_MAX_SAFE_DIRS, quarter)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _tree_exceeds_directory_budget(root: Path, budget: int) -> bool:
|
|
48
|
+
"""Boundedly count directories without following symlinks.
|
|
49
|
+
|
|
50
|
+
Count the tree watchdog's recursive native observer would have to watch,
|
|
51
|
+
including directories whose *events* are later filtered. This intentionally
|
|
52
|
+
avoids underestimating kernel pressure from large internal/cache trees.
|
|
53
|
+
Traversal stops as soon as the budget is exceeded.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
count = 1
|
|
57
|
+
stack = [root]
|
|
58
|
+
while stack:
|
|
59
|
+
current = stack.pop()
|
|
60
|
+
try:
|
|
61
|
+
iterator = os.scandir(current)
|
|
62
|
+
except OSError:
|
|
63
|
+
continue
|
|
64
|
+
with iterator:
|
|
65
|
+
for entry in iterator:
|
|
66
|
+
try:
|
|
67
|
+
is_directory = entry.is_dir(follow_symlinks=False)
|
|
68
|
+
except OSError:
|
|
69
|
+
continue
|
|
70
|
+
if not is_directory:
|
|
71
|
+
continue
|
|
72
|
+
count += 1
|
|
73
|
+
if count > budget:
|
|
74
|
+
return True
|
|
75
|
+
stack.append(Path(entry.path))
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _prefer_polling_on_linux(root: Path) -> tuple[bool, int | None]:
|
|
80
|
+
budget = _linux_inotify_directory_budget()
|
|
81
|
+
if budget is None:
|
|
82
|
+
return False, None
|
|
83
|
+
return _tree_exceeds_directory_budget(root, budget), budget
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _is_linux_inotify_resource_error(exc: OSError) -> bool:
|
|
87
|
+
"""Return whether watchdog failed because Linux inotify resources are exhausted."""
|
|
88
|
+
|
|
89
|
+
return sys.platform.startswith("linux") and exc.errno in _INOTIFY_RESOURCE_ERRNOS
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class SessionFileEventHandler(FileSystemEventHandler):
|
|
93
|
+
"""Record filesystem changes observed inside a watched session directory.
|
|
94
|
+
|
|
95
|
+
Phase 1 intentionally records these as session-level observations. A filesystem
|
|
96
|
+
change is not attributed to a specific process until a lower-level collector
|
|
97
|
+
(for example eBPF/ETW) can prove that relationship.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
*,
|
|
103
|
+
session_id: str,
|
|
104
|
+
session_entity: Entity,
|
|
105
|
+
sink: JsonlSink,
|
|
106
|
+
excluded_roots: Iterable[Path] = (),
|
|
107
|
+
) -> None:
|
|
108
|
+
super().__init__()
|
|
109
|
+
self.session_id = session_id
|
|
110
|
+
self.session_entity = session_entity
|
|
111
|
+
self.sink = sink
|
|
112
|
+
self.excluded_roots = tuple(path.resolve() for path in excluded_roots)
|
|
113
|
+
# watchdog emits a parent DirModifiedEvent when an internal file closes.
|
|
114
|
+
# Recording that event writes the sink again, producing an infinite loop.
|
|
115
|
+
# Suppress only aggregate directory-modified hints along recorder paths;
|
|
116
|
+
# concrete user file changes and directory create/move/delete remain visible.
|
|
117
|
+
sink_path = getattr(self.sink, "path", None)
|
|
118
|
+
internal = (*self.excluded_roots, *((sink_path.resolve(),) if isinstance(sink_path, Path) else ()))
|
|
119
|
+
self._internal_parents = {parent for path in internal for parent in path.parents}
|
|
120
|
+
|
|
121
|
+
def _excluded(self, path: str) -> bool:
|
|
122
|
+
candidate = Path(path).expanduser().resolve()
|
|
123
|
+
return any(candidate == root or root in candidate.parents for root in self.excluded_roots)
|
|
124
|
+
|
|
125
|
+
def _emit(self, event: FileSystemEvent) -> None:
|
|
126
|
+
if self._excluded(event.src_path):
|
|
127
|
+
return
|
|
128
|
+
|
|
129
|
+
src = Path(event.src_path).expanduser().resolve()
|
|
130
|
+
if event.is_directory and event.event_type == "modified" and src in self._internal_parents:
|
|
131
|
+
return
|
|
132
|
+
target_path = src
|
|
133
|
+
attributes: dict[str, object] = {
|
|
134
|
+
"filesystem_event": event.event_type,
|
|
135
|
+
"is_directory": event.is_directory,
|
|
136
|
+
"attribution": "session_observation",
|
|
137
|
+
"causal": False,
|
|
138
|
+
"writer_identity": "unknown",
|
|
139
|
+
"snapshot_state": "not_captured",
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
destination = getattr(event, "dest_path", None)
|
|
143
|
+
if destination:
|
|
144
|
+
dest = Path(destination).expanduser().resolve()
|
|
145
|
+
if self._excluded(str(dest)):
|
|
146
|
+
return
|
|
147
|
+
attributes["source_path"] = str(src)
|
|
148
|
+
attributes["destination_path"] = str(dest)
|
|
149
|
+
target_path = dest
|
|
150
|
+
|
|
151
|
+
entity_type = "directory" if event.is_directory else "file"
|
|
152
|
+
target = Entity(
|
|
153
|
+
type=entity_type, id=f"{entity_type}:{target_path}", name=target_path.name,
|
|
154
|
+
attributes={"path": str(target_path), "writer_identity": "unknown",
|
|
155
|
+
"snapshot_state": "not_captured"},
|
|
156
|
+
)
|
|
157
|
+
self.sink.emit(
|
|
158
|
+
RuntimeEvent.create(
|
|
159
|
+
session_id=self.session_id,
|
|
160
|
+
event_type=f"filesystem.{event.event_type}",
|
|
161
|
+
relation="OBSERVED_FILE_CHANGE",
|
|
162
|
+
source=self.session_entity,
|
|
163
|
+
target=target,
|
|
164
|
+
attributes=attributes,
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
category = system_path_category(target_path)
|
|
168
|
+
if category is not None and event.event_type in {"created", "modified", "deleted", "moved"}:
|
|
169
|
+
risk = Entity(
|
|
170
|
+
type="risk_record",
|
|
171
|
+
id=f"risk:{self.session_id}:system_path:{target_path}",
|
|
172
|
+
name="sensitive system path change observed",
|
|
173
|
+
)
|
|
174
|
+
self.sink.emit(RuntimeEvent.create(
|
|
175
|
+
session_id=self.session_id, event_type="risk.system_path_change",
|
|
176
|
+
relation="HAS_RISK", source=self.session_entity, target=risk,
|
|
177
|
+
attributes=risk_attributes(
|
|
178
|
+
"system_path_change", category, path=str(target_path),
|
|
179
|
+
operation=event.event_type, writer_identity="unknown",
|
|
180
|
+
),
|
|
181
|
+
))
|
|
182
|
+
|
|
183
|
+
def on_any_event(self, event: FileSystemEvent) -> None:
|
|
184
|
+
self._emit(event)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class FileWatcher:
|
|
188
|
+
"""Filesystem observation with resource-safe Linux fallbacks.
|
|
189
|
+
|
|
190
|
+
Native OS notifications remain the default. On Linux, large recursive trees
|
|
191
|
+
are preflighted before allocating inotify watches. If a tree exceeds the
|
|
192
|
+
conservative session budget, or if the kernel still returns ENOSPC/EMFILE
|
|
193
|
+
because other programs already consumed the watch/instance pool, ExecWeave
|
|
194
|
+
falls back to watchdog's polling observer instead of aborting the run.
|
|
195
|
+
|
|
196
|
+
The observation semantics stay session-level and non-causal. Only the
|
|
197
|
+
collection mechanism and detection latency change.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
*,
|
|
203
|
+
root: Path,
|
|
204
|
+
session_id: str,
|
|
205
|
+
session_entity: Entity,
|
|
206
|
+
sink: JsonlSink,
|
|
207
|
+
excluded_roots: Iterable[Path] = (),
|
|
208
|
+
) -> None:
|
|
209
|
+
self.root = root.expanduser().resolve()
|
|
210
|
+
self.handler = SessionFileEventHandler(
|
|
211
|
+
session_id=session_id,
|
|
212
|
+
session_entity=session_entity,
|
|
213
|
+
sink=sink,
|
|
214
|
+
excluded_roots=excluded_roots,
|
|
215
|
+
)
|
|
216
|
+
prefer_polling, budget = _prefer_polling_on_linux(self.root)
|
|
217
|
+
self.observer_kind = "polling" if prefer_polling else "native"
|
|
218
|
+
self.observer = PollingObserver(timeout=1.0) if prefer_polling else Observer()
|
|
219
|
+
self.fallback_reason: str | None = None
|
|
220
|
+
self._started = False
|
|
221
|
+
self._baseline: dict[str, tuple[int, int, int, int]] | None = None
|
|
222
|
+
self._inventory_limited = False
|
|
223
|
+
if prefer_polling:
|
|
224
|
+
self.fallback_reason = (
|
|
225
|
+
"ExecWeave selected polling filesystem observation because this Linux "
|
|
226
|
+
f"workspace exceeds the conservative recursive inotify budget ({budget} "
|
|
227
|
+
"directories). File-change semantics are preserved, but detection may "
|
|
228
|
+
"be less immediate."
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
def _schedule_and_start(self) -> None:
|
|
232
|
+
try:
|
|
233
|
+
self.observer.schedule(self.handler, str(self.root), recursive=True)
|
|
234
|
+
self.observer.start()
|
|
235
|
+
except BaseException:
|
|
236
|
+
# Observer.start() can allocate threads/resources before raising. Always
|
|
237
|
+
# tear down the partially initialized observer before propagating the
|
|
238
|
+
# failure or switching to the polling fallback.
|
|
239
|
+
self._shutdown_observer(timeout=1)
|
|
240
|
+
raise
|
|
241
|
+
self._started = True
|
|
242
|
+
|
|
243
|
+
def _shutdown_observer(self, timeout: float) -> None:
|
|
244
|
+
try:
|
|
245
|
+
self.observer.unschedule_all()
|
|
246
|
+
except (AttributeError, RuntimeError):
|
|
247
|
+
pass
|
|
248
|
+
try:
|
|
249
|
+
self.observer.stop()
|
|
250
|
+
except RuntimeError:
|
|
251
|
+
pass
|
|
252
|
+
try:
|
|
253
|
+
self.observer.join(timeout=timeout)
|
|
254
|
+
except RuntimeError:
|
|
255
|
+
pass
|
|
256
|
+
self._started = False
|
|
257
|
+
|
|
258
|
+
def _inventory(self) -> dict[str, tuple[int, int, int, int]]:
|
|
259
|
+
found: dict[str, tuple[int, int, int, int]] = {}
|
|
260
|
+
budget = 100000
|
|
261
|
+
def failed(_error: OSError) -> None:
|
|
262
|
+
self._inventory_limited = True
|
|
263
|
+
for base, directories, files in os.walk(self.root, followlinks=False, onerror=failed):
|
|
264
|
+
directories[:] = [name for name in directories
|
|
265
|
+
if not self.handler._excluded(str(Path(base) / name))]
|
|
266
|
+
budget -= 1
|
|
267
|
+
for name in files:
|
|
268
|
+
budget -= 1
|
|
269
|
+
if budget < 0:
|
|
270
|
+
self._inventory_limited = True
|
|
271
|
+
return found
|
|
272
|
+
path = Path(base) / name
|
|
273
|
+
if self.handler._excluded(str(path)):
|
|
274
|
+
continue
|
|
275
|
+
try:
|
|
276
|
+
info = path.lstat()
|
|
277
|
+
found[str(path)] = (info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_ino)
|
|
278
|
+
except OSError:
|
|
279
|
+
self._inventory_limited = True
|
|
280
|
+
if budget < 0:
|
|
281
|
+
self._inventory_limited = True
|
|
282
|
+
break
|
|
283
|
+
return found
|
|
284
|
+
|
|
285
|
+
def start(self) -> None:
|
|
286
|
+
self._baseline = self._inventory()
|
|
287
|
+
if self.fallback_reason is not None:
|
|
288
|
+
warnings.warn(self.fallback_reason, RuntimeWarning, stacklevel=2)
|
|
289
|
+
try:
|
|
290
|
+
self._schedule_and_start()
|
|
291
|
+
except OSError as exc:
|
|
292
|
+
if not _is_linux_inotify_resource_error(exc) or self.observer_kind == "polling":
|
|
293
|
+
raise
|
|
294
|
+
self.fallback_reason = (
|
|
295
|
+
"Linux inotify watch or instance capacity was exhausted; ExecWeave is "
|
|
296
|
+
"using polling filesystem observation for this session. File-change "
|
|
297
|
+
"semantics are preserved, but detection may be less immediate."
|
|
298
|
+
)
|
|
299
|
+
warnings.warn(self.fallback_reason, RuntimeWarning, stacklevel=2)
|
|
300
|
+
self.observer_kind = "polling"
|
|
301
|
+
self.observer = PollingObserver(timeout=1.0)
|
|
302
|
+
self._schedule_and_start()
|
|
303
|
+
|
|
304
|
+
def stop(self) -> None:
|
|
305
|
+
# This is intentionally idempotent and also safe after a failed start. A
|
|
306
|
+
# watchdog backend may have partially initialized before raising even when
|
|
307
|
+
# _started never became true.
|
|
308
|
+
self._shutdown_observer(timeout=5)
|
|
309
|
+
before, self._baseline = self._baseline, None
|
|
310
|
+
if before is None:
|
|
311
|
+
return
|
|
312
|
+
after = self._inventory()
|
|
313
|
+
# A final metadata difference is independent observation, not a process edge.
|
|
314
|
+
for path, signature in after.items():
|
|
315
|
+
if path not in before:
|
|
316
|
+
self.handler._emit(FileCreatedEvent(path))
|
|
317
|
+
elif before[path] != signature:
|
|
318
|
+
self.handler._emit(FileModifiedEvent(path))
|
|
319
|
+
if not self._inventory_limited:
|
|
320
|
+
for path in before.keys() - after.keys():
|
|
321
|
+
self.handler._emit(FileDeletedEvent(path))
|
|
322
|
+
if self._inventory_limited:
|
|
323
|
+
self.handler.sink.emit(RuntimeEvent.create(
|
|
324
|
+
session_id=self.handler.session_id, event_type="observation.warning",
|
|
325
|
+
relation="HAS_OBSERVATION_WARNING", source=self.handler.session_entity,
|
|
326
|
+
attributes={"reason": "filesystem_inventory_incomplete", "severity": "warning"},
|
|
327
|
+
))
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Durable export status, including the content referenced by exported indexes."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .content_integrity import ArchiveReadError, audit_content_references, hash_export, _read
|
|
9
|
+
from .private_io import write_private_json
|
|
10
|
+
from .run_assessment import build_run_assessment
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
REQUIRED_EXPORTS = ("graph.json", "viewer.html", "conversations.json")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def record_finalization(
|
|
17
|
+
run_dir: Path, *, state: str, error: BaseException | None = None,
|
|
18
|
+
) -> dict[str, Any]:
|
|
19
|
+
run_dir = Path(run_dir).absolute()
|
|
20
|
+
files: dict[str, Any] = {}
|
|
21
|
+
artifact_errors: dict[str, str] = {}
|
|
22
|
+
for name in REQUIRED_EXPORTS:
|
|
23
|
+
try:
|
|
24
|
+
files[name] = hash_export(run_dir, name)
|
|
25
|
+
except ArchiveReadError as exc:
|
|
26
|
+
artifact_errors[name] = str(exc)
|
|
27
|
+
missing = [name for name in REQUIRED_EXPORTS if not files.get(name, {}).get("size_bytes")]
|
|
28
|
+
integrity: dict[str, Any] = {"state": "not_checked", "reason": "export_not_terminal"}
|
|
29
|
+
if state != "recording":
|
|
30
|
+
integrity = audit_content_references(run_dir)
|
|
31
|
+
# An index must be the same version as the primary export we hashed. This
|
|
32
|
+
# does not claim that a writable archive cannot change after verification.
|
|
33
|
+
for name, fingerprint in integrity["index_files"].items():
|
|
34
|
+
if fingerprint != files.get(name):
|
|
35
|
+
artifact_errors[name] = "changed_during_finalization"
|
|
36
|
+
complete = not missing and not artifact_errors and integrity["state"] == "complete"
|
|
37
|
+
payload = {
|
|
38
|
+
"schema_version": "0.2", "state": state, "artifacts": files,
|
|
39
|
+
"missing": missing, "error_type": type(error).__name__ if error else None,
|
|
40
|
+
"artifact_errors": artifact_errors, "content_integrity": integrity,
|
|
41
|
+
}
|
|
42
|
+
if state == "complete" and not complete:
|
|
43
|
+
payload["state"] = "incomplete"
|
|
44
|
+
payload["observation_assessment"] = {
|
|
45
|
+
"state": "not_verified", "reasons": ["graph_assessment_unavailable"],
|
|
46
|
+
}
|
|
47
|
+
payload["run_assessment"] = {
|
|
48
|
+
"schema_version": "0.1",
|
|
49
|
+
"scope": "unavailable",
|
|
50
|
+
"reason": "graph_assessment_unavailable",
|
|
51
|
+
}
|
|
52
|
+
payload["run_assessment_binding"] = None
|
|
53
|
+
if state != "recording" and "graph.json" in files:
|
|
54
|
+
try:
|
|
55
|
+
fingerprint, raw = _read(run_dir, "graph.json", 64 * 1024 * 1024, collect=True)
|
|
56
|
+
graph = json.loads(raw)
|
|
57
|
+
if fingerprint != files["graph.json"] or not isinstance(graph, dict):
|
|
58
|
+
raise ValueError("inconsistent_graph")
|
|
59
|
+
assessment = graph.get("observation_assessment")
|
|
60
|
+
if assessment is not None:
|
|
61
|
+
if not (isinstance(assessment, dict) and assessment.get("schema_version") == "0.1"
|
|
62
|
+
and isinstance(assessment.get("state"), str)
|
|
63
|
+
and assessment["state"] in {"not_verified", "observation_incomplete"}):
|
|
64
|
+
raise ValueError("invalid_observation_assessment")
|
|
65
|
+
payload["observation_assessment"] = assessment
|
|
66
|
+
outcome = graph.get("session_outcome")
|
|
67
|
+
if isinstance(outcome, dict):
|
|
68
|
+
payload["session_outcome"] = outcome
|
|
69
|
+
payload["run_assessment"] = build_run_assessment(graph)
|
|
70
|
+
payload["run_assessment_binding"] = {
|
|
71
|
+
"graph": dict(files["graph.json"]),
|
|
72
|
+
"assessment_schema_version": payload["run_assessment"].get("schema_version"),
|
|
73
|
+
"derivation": "execweave.run_assessment.build_run_assessment",
|
|
74
|
+
}
|
|
75
|
+
except (ArchiveReadError, ValueError, UnicodeError):
|
|
76
|
+
payload["observation_assessment"] = {
|
|
77
|
+
"state": "observation_incomplete", "reasons": ["graph_assessment_unreadable"],
|
|
78
|
+
}
|
|
79
|
+
payload["run_assessment"] = {
|
|
80
|
+
"schema_version": "0.1", "scope": "unavailable",
|
|
81
|
+
"reason": "graph_assessment_unreadable",
|
|
82
|
+
}
|
|
83
|
+
payload["run_assessment_binding"] = None
|
|
84
|
+
# state=complete is retained as the archive/export axis for older readers.
|
|
85
|
+
# Overall session_status must not claim success merely because bytes were exported.
|
|
86
|
+
payload["session_status"] = payload["observation_assessment"]["state"]
|
|
87
|
+
write_private_json(run_dir / "finalization.json", payload, replace=True)
|
|
88
|
+
if state == "complete" and not complete and error is None:
|
|
89
|
+
detail = ", ".join(missing) if missing else "declared content or export verification failed"
|
|
90
|
+
raise RuntimeError("Final export is incomplete: " + detail)
|
|
91
|
+
# A collector failure stays primary, even when the archive is incomplete.
|
|
92
|
+
return payload
|
execweave/focus.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict, deque
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
from typing import Any, Iterable, Literal
|
|
6
|
+
|
|
7
|
+
FocusDirection = Literal["both", "in", "out"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def focus_graph(
|
|
11
|
+
graph: dict[str, Any],
|
|
12
|
+
*,
|
|
13
|
+
anchors: Iterable[str],
|
|
14
|
+
hops: int = 1,
|
|
15
|
+
direction: FocusDirection = "both",
|
|
16
|
+
relations: Iterable[str] = (),
|
|
17
|
+
causal_only: bool = False,
|
|
18
|
+
) -> dict[str, Any]:
|
|
19
|
+
"""Return an evidence-preserving neighborhood around one or more graph nodes.
|
|
20
|
+
|
|
21
|
+
Traversal only follows edges already present in the input graph. The operation
|
|
22
|
+
never creates inferred edges. ``direction`` controls traversal relative to edge
|
|
23
|
+
direction, while the returned payload contains the induced set of eligible edges
|
|
24
|
+
between all selected nodes.
|
|
25
|
+
"""
|
|
26
|
+
if hops < 0:
|
|
27
|
+
raise ValueError("hops must be >= 0")
|
|
28
|
+
if direction not in {"both", "in", "out"}:
|
|
29
|
+
raise ValueError("direction must be one of: both, in, out")
|
|
30
|
+
|
|
31
|
+
requested_anchors = list(dict.fromkeys(str(anchor) for anchor in anchors if str(anchor)))
|
|
32
|
+
if not requested_anchors:
|
|
33
|
+
raise ValueError("at least one anchor node ID is required")
|
|
34
|
+
|
|
35
|
+
nodes = [node for node in graph.get("nodes", []) if isinstance(node, dict)]
|
|
36
|
+
edges = [edge for edge in graph.get("edges", []) if isinstance(edge, dict)]
|
|
37
|
+
node_by_id = {
|
|
38
|
+
node["id"]: node for node in nodes if isinstance(node.get("id"), str)
|
|
39
|
+
}
|
|
40
|
+
missing = [anchor for anchor in requested_anchors if anchor not in node_by_id]
|
|
41
|
+
if missing:
|
|
42
|
+
raise ValueError(f"anchor node not found: {missing[0]}")
|
|
43
|
+
|
|
44
|
+
requested_relations = set(relations)
|
|
45
|
+
eligible_edges: list[dict[str, Any]] = []
|
|
46
|
+
outgoing: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
47
|
+
incoming: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
48
|
+
|
|
49
|
+
for edge in edges:
|
|
50
|
+
source = edge.get("source")
|
|
51
|
+
target = edge.get("target")
|
|
52
|
+
relation = edge.get("relation")
|
|
53
|
+
if not isinstance(source, str) or not isinstance(target, str):
|
|
54
|
+
continue
|
|
55
|
+
if source not in node_by_id or target not in node_by_id:
|
|
56
|
+
continue
|
|
57
|
+
if requested_relations and relation not in requested_relations:
|
|
58
|
+
continue
|
|
59
|
+
if causal_only and edge.get("causal") is not True:
|
|
60
|
+
continue
|
|
61
|
+
eligible_edges.append(edge)
|
|
62
|
+
outgoing[source].append(edge)
|
|
63
|
+
incoming[target].append(edge)
|
|
64
|
+
|
|
65
|
+
selected: set[str] = set(requested_anchors)
|
|
66
|
+
queue: deque[tuple[str, int]] = deque((anchor, 0) for anchor in requested_anchors)
|
|
67
|
+
best_depth = {anchor: 0 for anchor in requested_anchors}
|
|
68
|
+
|
|
69
|
+
while queue:
|
|
70
|
+
current, depth = queue.popleft()
|
|
71
|
+
if depth >= hops:
|
|
72
|
+
continue
|
|
73
|
+
|
|
74
|
+
candidates: list[tuple[str, dict[str, Any]]] = []
|
|
75
|
+
if direction in {"both", "out"}:
|
|
76
|
+
candidates.extend((edge["target"], edge) for edge in outgoing.get(current, []))
|
|
77
|
+
if direction in {"both", "in"}:
|
|
78
|
+
candidates.extend((edge["source"], edge) for edge in incoming.get(current, []))
|
|
79
|
+
|
|
80
|
+
for neighbor, _edge in candidates:
|
|
81
|
+
next_depth = depth + 1
|
|
82
|
+
selected.add(neighbor)
|
|
83
|
+
previous = best_depth.get(neighbor)
|
|
84
|
+
if previous is None or next_depth < previous:
|
|
85
|
+
best_depth[neighbor] = next_depth
|
|
86
|
+
queue.append((neighbor, next_depth))
|
|
87
|
+
|
|
88
|
+
focused_nodes = [deepcopy(node) for node in nodes if node.get("id") in selected]
|
|
89
|
+
focused_edges = [
|
|
90
|
+
deepcopy(edge)
|
|
91
|
+
for edge in eligible_edges
|
|
92
|
+
if edge.get("source") in selected and edge.get("target") in selected
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
payload = deepcopy(graph)
|
|
96
|
+
payload["nodes"] = focused_nodes
|
|
97
|
+
payload["edges"] = focused_edges
|
|
98
|
+
payload["node_count"] = len(focused_nodes)
|
|
99
|
+
payload["edge_count"] = len(focused_edges)
|
|
100
|
+
payload["focus"] = {
|
|
101
|
+
"anchors": requested_anchors,
|
|
102
|
+
"hops": hops,
|
|
103
|
+
"direction": direction,
|
|
104
|
+
"relations": sorted(requested_relations),
|
|
105
|
+
"causal_only": causal_only,
|
|
106
|
+
"source_node_count": len(nodes),
|
|
107
|
+
"source_edge_count": len(edges),
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
expansion = payload.get("expansion")
|
|
111
|
+
if isinstance(expansion, dict) and isinstance(expansion.get("clusters"), dict):
|
|
112
|
+
expansion["clusters"] = {
|
|
113
|
+
cluster_id: value
|
|
114
|
+
for cluster_id, value in expansion["clusters"].items()
|
|
115
|
+
if cluster_id in selected
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return payload
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Stable public API for third-party framework semantic adapters."""
|
|
2
|
+
|
|
3
|
+
from .autogen import AutoGenAdapter
|
|
4
|
+
from .base import (
|
|
5
|
+
CANONICAL_EVENT_TYPES,
|
|
6
|
+
AdapterCapabilities,
|
|
7
|
+
AdapterContext,
|
|
8
|
+
AgentRecord,
|
|
9
|
+
CaptureMode,
|
|
10
|
+
ContentCapturePolicy,
|
|
11
|
+
ContentWriter,
|
|
12
|
+
EntityRef,
|
|
13
|
+
FrameworkAdapter,
|
|
14
|
+
FrameworkCompatibility,
|
|
15
|
+
MessageRecord,
|
|
16
|
+
ModelCallRecord,
|
|
17
|
+
ProcessRef,
|
|
18
|
+
SemanticWriter,
|
|
19
|
+
TaskRecord,
|
|
20
|
+
ToolCallRecord,
|
|
21
|
+
stable_id,
|
|
22
|
+
)
|
|
23
|
+
from .camel import CAMELAdapter
|
|
24
|
+
from .metagpt import MetaGPTAdapter
|
|
25
|
+
from .registry import AdapterDescriptor, FrameworkAdapterRegistry, default_registry
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"AdapterCapabilities", "AdapterContext", "AdapterDescriptor", "AgentRecord",
|
|
29
|
+
"AutoGenAdapter", "CAMELAdapter", "CANONICAL_EVENT_TYPES", "CaptureMode",
|
|
30
|
+
"ContentCapturePolicy", "ContentWriter", "EntityRef", "FrameworkAdapter",
|
|
31
|
+
"FrameworkAdapterRegistry", "FrameworkCompatibility", "MessageRecord",
|
|
32
|
+
"MetaGPTAdapter", "ModelCallRecord", "ProcessRef", "SemanticWriter",
|
|
33
|
+
"TaskRecord", "ToolCallRecord", "default_registry", "stable_id",
|
|
34
|
+
]
|