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,927 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Iterable
|
|
14
|
+
|
|
15
|
+
from .auto_specialized import auto_specialized_launch
|
|
16
|
+
from .collector import infer_agent_name
|
|
17
|
+
from .command_privacy import public_command
|
|
18
|
+
from .schema import Entity, RuntimeEvent
|
|
19
|
+
from .private_io import write_private_text
|
|
20
|
+
from .sink import JsonlSink, _protect_git_run_directory
|
|
21
|
+
|
|
22
|
+
_TIMESTAMP_RE = re.compile(r"^(?P<ts>\d+(?:\.\d+)?)\s+(?P<body>.*)$")
|
|
23
|
+
_SYSCALL_RE = re.compile(r"^(?P<name>[a-zA-Z0-9_]+)\((?P<args>.*)\)\s+=\s+(?P<result>.*)$")
|
|
24
|
+
_CLONE_RESULT_RE = re.compile(r"^(?P<pid>\d+)(?:\s|$)")
|
|
25
|
+
_CONNECT_ERROR_RE = re.compile(r"^-1\s+(?P<errno>[A-Z0-9_]+)(?:\s|$)")
|
|
26
|
+
_EXIT_RE = re.compile(r"^\+\+\+ exited with (?P<code>-?\d+) \+\+\+$")
|
|
27
|
+
_KILLED_RE = re.compile(r"^\+\+\+ killed by (?P<signal>[A-Z0-9]+).*$")
|
|
28
|
+
_QUOTED_RE = re.compile(r'"((?:\\.|[^"\\])*)"')
|
|
29
|
+
_IPV4_RE = re.compile(
|
|
30
|
+
r'sin_port=htons\((?P<port>\d+)\).*sin_addr=inet_addr\("(?P<host>[^"]+)"\)'
|
|
31
|
+
)
|
|
32
|
+
_IPV6_RE = re.compile(
|
|
33
|
+
r'sin6_port=htons\((?P<port>\d+)\).*inet_pton\(AF_INET6, "(?P<host>[^"]+)"'
|
|
34
|
+
)
|
|
35
|
+
_UNIX_RE = re.compile(r'sun_path="(?P<path>[^"]+)"')
|
|
36
|
+
_DIRFD_RE = re.compile(r"^[^,]*<(?P<path>/[^>]*)>")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class TraceRecord:
|
|
41
|
+
timestamp: float
|
|
42
|
+
pid: int
|
|
43
|
+
body: str
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def strace_available() -> bool:
|
|
47
|
+
return sys.platform.startswith("linux") and shutil.which("strace") is not None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _iso_timestamp(value: float) -> str:
|
|
51
|
+
return datetime.fromtimestamp(value, timezone.utc).isoformat().replace("+00:00", "Z")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _decode_quoted(value: str) -> str:
|
|
55
|
+
# Synthetic Windows traces carry native drive paths with single
|
|
56
|
+
# backslashes (for example ``C:\\tmp``). Treating those as Python string
|
|
57
|
+
# escapes turns ``\\t`` into a tab and corrupts the observed path. Real
|
|
58
|
+
# Linux strace paths still use the normal C-style decoding below.
|
|
59
|
+
if re.match(r"^[A-Za-z]:[\\/]", value):
|
|
60
|
+
return value.replace(r'\"', '"').replace(r"\\", "\\")
|
|
61
|
+
try:
|
|
62
|
+
return str(ast.literal_eval(f'"{value}"'))
|
|
63
|
+
except (SyntaxError, ValueError):
|
|
64
|
+
return value
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _quoted_arguments(args: str) -> list[str]:
|
|
68
|
+
return [_decode_quoted(match.group(1)) for match in _QUOTED_RE.finditer(args)]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _pid_from_trace_path(path: Path) -> int | None:
|
|
72
|
+
suffix = path.name.rsplit(".", 1)[-1]
|
|
73
|
+
try:
|
|
74
|
+
return int(suffix)
|
|
75
|
+
except ValueError:
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _merge_unfinished(lines: Iterable[str]) -> list[str]:
|
|
80
|
+
merged: list[str] = []
|
|
81
|
+
pending: dict[str, str] = {}
|
|
82
|
+
for raw_line in lines:
|
|
83
|
+
line = raw_line.rstrip("\n")
|
|
84
|
+
timestamp_match = _TIMESTAMP_RE.match(line)
|
|
85
|
+
if timestamp_match is None:
|
|
86
|
+
merged.append(line)
|
|
87
|
+
continue
|
|
88
|
+
body = timestamp_match.group("body")
|
|
89
|
+
if body.endswith("<unfinished ...>"):
|
|
90
|
+
prefix = body[: -len("<unfinished ...>")].rstrip()
|
|
91
|
+
syscall = prefix.split("(", 1)[0]
|
|
92
|
+
pending[syscall] = f"{timestamp_match.group('ts')} {prefix}"
|
|
93
|
+
continue
|
|
94
|
+
resumed = re.match(
|
|
95
|
+
r"^<\.\.\. (?P<name>[a-zA-Z0-9_]+) resumed>(?P<rest>.*)$",
|
|
96
|
+
body,
|
|
97
|
+
)
|
|
98
|
+
if resumed is not None and resumed.group("name") in pending:
|
|
99
|
+
original = pending.pop(resumed.group("name"))
|
|
100
|
+
merged.append(original + resumed.group("rest"))
|
|
101
|
+
continue
|
|
102
|
+
merged.append(line)
|
|
103
|
+
merged.extend(pending.values())
|
|
104
|
+
return merged
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def read_trace_records(trace_dir: Path, prefix: str = "trace") -> list[TraceRecord]:
|
|
108
|
+
records: list[TraceRecord] = []
|
|
109
|
+
for path in sorted(trace_dir.glob(f"{prefix}.*")):
|
|
110
|
+
pid = _pid_from_trace_path(path)
|
|
111
|
+
if pid is None:
|
|
112
|
+
continue
|
|
113
|
+
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
114
|
+
for line in _merge_unfinished(lines):
|
|
115
|
+
match = _TIMESTAMP_RE.match(line)
|
|
116
|
+
if match is None:
|
|
117
|
+
continue
|
|
118
|
+
records.append(TraceRecord(float(match.group("ts")), pid, match.group("body")))
|
|
119
|
+
records.sort(key=lambda record: (record.timestamp, record.pid))
|
|
120
|
+
return records
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class StraceParser:
|
|
124
|
+
"""Convert Linux strace output into graph-ready runtime events.
|
|
125
|
+
|
|
126
|
+
This backend uses syscall evidence and therefore can attribute process creation,
|
|
127
|
+
file-open/mutation operations, and outbound connect() calls to a concrete PID.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
*,
|
|
133
|
+
session_id: str,
|
|
134
|
+
sink: JsonlSink,
|
|
135
|
+
watch_root: Path,
|
|
136
|
+
command: list[str],
|
|
137
|
+
) -> None:
|
|
138
|
+
self.session_id = session_id
|
|
139
|
+
self.sink = sink
|
|
140
|
+
self.watch_root = watch_root.expanduser().resolve()
|
|
141
|
+
self.command = command
|
|
142
|
+
self.session = Entity(
|
|
143
|
+
type="session",
|
|
144
|
+
id=f"session:{session_id}",
|
|
145
|
+
name=session_id,
|
|
146
|
+
attributes={
|
|
147
|
+
"command": public_command(command),
|
|
148
|
+
"argv_redacted": True,
|
|
149
|
+
"cwd": str(self.watch_root),
|
|
150
|
+
"backend": "strace",
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
self._known_processes: set[int] = set()
|
|
154
|
+
# Derive only the executable basename from execve; do not persist argv,
|
|
155
|
+
# which may contain passwords or tokens in ordinary agent commands.
|
|
156
|
+
self._executable_by_pid: dict[int, str] = {}
|
|
157
|
+
self._cwd_by_pid: dict[int, Path] = {}
|
|
158
|
+
self._parent_by_pid: dict[int, int] = {}
|
|
159
|
+
# strace -ff uses TIDs as trace-file suffixes; CLONE_THREAD does not
|
|
160
|
+
# create another process. Keep thread identity distinct from process.
|
|
161
|
+
# Identity mappings are lifetime-bounded: Linux may reuse a TID after
|
|
162
|
+
# a thread exits. An all-session TID map can misattribute later files
|
|
163
|
+
# and creates false grade-A native process edges.
|
|
164
|
+
self._thread_lifetimes: dict[int, list[tuple[float, float, int]]] = {}
|
|
165
|
+
self._uncertain_lifetimes: dict[int, list[tuple[float, float]]] = {}
|
|
166
|
+
self._record_timestamp = float("-inf")
|
|
167
|
+
self._spawn_origin_tid: dict[int, int] = {}
|
|
168
|
+
|
|
169
|
+
def _process_pid(self, tid: int, timestamp: float | None = None) -> int:
|
|
170
|
+
"""Resolve a TID to its TGID only within an observed thread lifetime."""
|
|
171
|
+
at = self._record_timestamp if timestamp is None else timestamp
|
|
172
|
+
seen: set[int] = set()
|
|
173
|
+
while tid not in seen:
|
|
174
|
+
seen.add(tid)
|
|
175
|
+
lifetimes = self._thread_lifetimes.get(tid, [])
|
|
176
|
+
active = [(born, parent) for born, until, parent in lifetimes
|
|
177
|
+
if born <= at <= until]
|
|
178
|
+
if len(active) != 1:
|
|
179
|
+
break
|
|
180
|
+
tid = active[0][1]
|
|
181
|
+
return tid
|
|
182
|
+
|
|
183
|
+
def _is_thread_at(self, tid: int, timestamp: float) -> bool:
|
|
184
|
+
return any(start <= timestamp <= end for start, end, _
|
|
185
|
+
in self._thread_lifetimes.get(tid, []))
|
|
186
|
+
|
|
187
|
+
def _is_uncertain_at(self, tid: int, timestamp: float) -> bool:
|
|
188
|
+
return any(start <= timestamp <= end for start, end
|
|
189
|
+
in self._uncertain_lifetimes.get(tid, []))
|
|
190
|
+
|
|
191
|
+
@staticmethod
|
|
192
|
+
def _clone_kind(name: str, args: str) -> str:
|
|
193
|
+
"""Return thread, process or unknown without assuming undocumented flags."""
|
|
194
|
+
if name in {"fork", "vfork"}:
|
|
195
|
+
return "process"
|
|
196
|
+
if name not in {"clone", "clone3"}:
|
|
197
|
+
return "unknown"
|
|
198
|
+
# strace normally renders flags symbolically, but numeric kernel flag
|
|
199
|
+
# words also occur. CLONE_THREAD is bit 0x10000 in Linux clone flags.
|
|
200
|
+
match = re.search(r"\bflags\s*=\s*([^,}\s)]+)", args)
|
|
201
|
+
if not match:
|
|
202
|
+
return "unknown"
|
|
203
|
+
flags = match.group(1)
|
|
204
|
+
bits = 0
|
|
205
|
+
parts = flags.split("|")
|
|
206
|
+
for part in parts:
|
|
207
|
+
if part == "CLONE_THREAD":
|
|
208
|
+
return "thread"
|
|
209
|
+
if part.startswith(("0x", "0X", "0o", "0O", "0b", "0B")) or part.isdigit():
|
|
210
|
+
try:
|
|
211
|
+
bits |= int(part, 0)
|
|
212
|
+
except ValueError:
|
|
213
|
+
return "unknown"
|
|
214
|
+
elif part.startswith(("CLONE_", "SIG")):
|
|
215
|
+
continue
|
|
216
|
+
else:
|
|
217
|
+
return "unknown"
|
|
218
|
+
return "thread" if bits & 0x10000 else "process"
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def _is_thread_clone(cls, name: str, args: str) -> bool:
|
|
222
|
+
return cls._clone_kind(name, args) == "thread"
|
|
223
|
+
|
|
224
|
+
def _uncertain_entity(self, tid: int) -> Entity:
|
|
225
|
+
return Entity(
|
|
226
|
+
type="unclassified_task",
|
|
227
|
+
id=f"unclassified-task:{self.session_id}:{tid}",
|
|
228
|
+
name=str(tid),
|
|
229
|
+
attributes={"tid": tid, "classification": "unknown",
|
|
230
|
+
"backend": "strace"},
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
def _thread_entity(self, tid: int) -> Entity:
|
|
234
|
+
leader = self._process_pid(tid)
|
|
235
|
+
return Entity(
|
|
236
|
+
type="thread", id=f"thread:{self.session_id}:{tid}", name=str(tid),
|
|
237
|
+
attributes={"tid": tid, "tgid": leader, "backend": "strace"},
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
def process_entity(self, pid: int) -> Entity:
|
|
241
|
+
if self._is_uncertain_at(pid, self._record_timestamp):
|
|
242
|
+
return self._uncertain_entity(pid)
|
|
243
|
+
pid = self._process_pid(pid)
|
|
244
|
+
return Entity(
|
|
245
|
+
type="process",
|
|
246
|
+
id=f"process:{self.session_id}:{pid}",
|
|
247
|
+
name=(f"{self._executable_by_pid[pid]} · {pid}"
|
|
248
|
+
if pid in self._executable_by_pid else str(pid)),
|
|
249
|
+
attributes={
|
|
250
|
+
"pid": pid,
|
|
251
|
+
"identity_scope": "session",
|
|
252
|
+
"backend": "strace",
|
|
253
|
+
},
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
def parse(self, records: Iterable[TraceRecord]) -> None:
|
|
257
|
+
materialized = list(records)
|
|
258
|
+
self._index_process_parents(materialized)
|
|
259
|
+
for record in materialized:
|
|
260
|
+
self._parse_record(record)
|
|
261
|
+
|
|
262
|
+
def _index_process_parents(self, records: Iterable[TraceRecord]) -> None:
|
|
263
|
+
"""Pre-index thread lifetimes and native parents before timestamp ties.
|
|
264
|
+
|
|
265
|
+
A traced TID can later be reused as a real child process. Time-bounded
|
|
266
|
+
identities prevent a stale thread map from claiming the new child.
|
|
267
|
+
"""
|
|
268
|
+
materialized = sorted(records, key=lambda r: (r.timestamp, r.pid))
|
|
269
|
+
births: dict[int, list[float]] = {}
|
|
270
|
+
thread_starts: list[tuple[int, float, int]] = []
|
|
271
|
+
uncertain_starts: list[tuple[int, float]] = []
|
|
272
|
+
real_starts: list[tuple[int, float, int]] = []
|
|
273
|
+
exits: dict[int, list[float]] = {}
|
|
274
|
+
for record in materialized:
|
|
275
|
+
if _EXIT_RE.match(record.body) or _KILLED_RE.match(record.body):
|
|
276
|
+
exits.setdefault(record.pid, []).append(record.timestamp)
|
|
277
|
+
continue
|
|
278
|
+
syscall = _SYSCALL_RE.match(record.body)
|
|
279
|
+
if syscall is None:
|
|
280
|
+
continue
|
|
281
|
+
name = syscall.group("name")
|
|
282
|
+
if name not in {"clone", "clone3", "fork", "vfork"}:
|
|
283
|
+
continue
|
|
284
|
+
child_match = _CLONE_RESULT_RE.match(syscall.group("result"))
|
|
285
|
+
if child_match is None:
|
|
286
|
+
continue
|
|
287
|
+
child = int(child_match.group("pid"))
|
|
288
|
+
births.setdefault(child, []).append(record.timestamp)
|
|
289
|
+
kind = self._clone_kind(name, syscall.group("args"))
|
|
290
|
+
if kind == "thread":
|
|
291
|
+
thread_starts.append((child, record.timestamp, record.pid))
|
|
292
|
+
elif kind == "process":
|
|
293
|
+
real_starts.append((child, record.timestamp, record.pid))
|
|
294
|
+
else:
|
|
295
|
+
uncertain_starts.append((child, record.timestamp))
|
|
296
|
+
|
|
297
|
+
def limit_for(tid: int, born: float) -> float:
|
|
298
|
+
# A later successful clone that returns the same TID proves the
|
|
299
|
+
# prior instance has ended even if its exit trace was lost.
|
|
300
|
+
future_births = [t for t in births.get(tid, []) if t > born]
|
|
301
|
+
cutoff = min(future_births) if future_births else float("inf")
|
|
302
|
+
possible_exits = [t for t in exits.get(tid, [])
|
|
303
|
+
if born <= t < cutoff]
|
|
304
|
+
if possible_exits:
|
|
305
|
+
return min(possible_exits)
|
|
306
|
+
if cutoff < float("inf"):
|
|
307
|
+
return math.nextafter(cutoff, float("-inf"))
|
|
308
|
+
return cutoff
|
|
309
|
+
|
|
310
|
+
for tid, born, parent_tid in thread_starts:
|
|
311
|
+
self._thread_lifetimes.setdefault(tid, []).append(
|
|
312
|
+
(born, limit_for(tid, born), parent_tid)
|
|
313
|
+
)
|
|
314
|
+
for tid, born in uncertain_starts:
|
|
315
|
+
self._uncertain_lifetimes.setdefault(tid, []).append(
|
|
316
|
+
(born, limit_for(tid, born))
|
|
317
|
+
)
|
|
318
|
+
for child, timestamp, parent_tid in real_starts:
|
|
319
|
+
self._parent_by_pid[child] = self._process_pid(parent_tid, timestamp)
|
|
320
|
+
self._spawn_origin_tid[child] = parent_tid
|
|
321
|
+
|
|
322
|
+
def _ensure_process(
|
|
323
|
+
self,
|
|
324
|
+
pid: int,
|
|
325
|
+
timestamp: float,
|
|
326
|
+
*,
|
|
327
|
+
parent_pid: int | None = None,
|
|
328
|
+
relation: str | None = None,
|
|
329
|
+
) -> None:
|
|
330
|
+
if self._is_uncertain_at(pid, timestamp):
|
|
331
|
+
return
|
|
332
|
+
pid = self._process_pid(pid, timestamp)
|
|
333
|
+
if parent_pid is not None:
|
|
334
|
+
parent_pid = self._process_pid(parent_pid)
|
|
335
|
+
if pid in self._known_processes:
|
|
336
|
+
return
|
|
337
|
+
if parent_pid is None:
|
|
338
|
+
parent_pid = self._parent_by_pid.get(pid)
|
|
339
|
+
self._known_processes.add(pid)
|
|
340
|
+
if parent_pid is not None:
|
|
341
|
+
self._cwd_by_pid[pid] = self._cwd_by_pid.get(parent_pid, self.watch_root)
|
|
342
|
+
else:
|
|
343
|
+
self._cwd_by_pid.setdefault(pid, self.watch_root)
|
|
344
|
+
source = self.session if parent_pid is None else self.process_entity(parent_pid)
|
|
345
|
+
relation = relation or ("LAUNCHED" if parent_pid is None else "SPAWNED")
|
|
346
|
+
self.sink.emit(
|
|
347
|
+
RuntimeEvent.create(
|
|
348
|
+
session_id=self.session_id,
|
|
349
|
+
event_type="process.started",
|
|
350
|
+
relation=relation,
|
|
351
|
+
source=source,
|
|
352
|
+
target=self.process_entity(pid),
|
|
353
|
+
timestamp=_iso_timestamp(timestamp),
|
|
354
|
+
attributes={
|
|
355
|
+
"attribution": "syscall",
|
|
356
|
+
"causal": True,
|
|
357
|
+
"backend": "strace",
|
|
358
|
+
"spawn_origin_tid": self._spawn_origin_tid.get(pid),
|
|
359
|
+
},
|
|
360
|
+
)
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
def _parse_record(self, record: TraceRecord) -> None:
|
|
364
|
+
self._record_timestamp = record.timestamp
|
|
365
|
+
exit_match = _EXIT_RE.match(record.body)
|
|
366
|
+
if exit_match is not None:
|
|
367
|
+
self._record_timestamp = record.timestamp
|
|
368
|
+
if self._is_uncertain_at(record.pid, record.timestamp):
|
|
369
|
+
self._emit_uncertain_exit(record)
|
|
370
|
+
return
|
|
371
|
+
if self._is_thread_at(record.pid, record.timestamp):
|
|
372
|
+
self._emit_thread_exit(record, exit_code=int(exit_match.group("code")))
|
|
373
|
+
return
|
|
374
|
+
self._ensure_process(record.pid, record.timestamp)
|
|
375
|
+
self.sink.emit(
|
|
376
|
+
RuntimeEvent.create(
|
|
377
|
+
session_id=self.session_id,
|
|
378
|
+
event_type="process.exited",
|
|
379
|
+
relation="EXITED",
|
|
380
|
+
source=self.process_entity(record.pid),
|
|
381
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
382
|
+
attributes={
|
|
383
|
+
"exit_code": int(exit_match.group("code")),
|
|
384
|
+
"backend": "strace",
|
|
385
|
+
},
|
|
386
|
+
)
|
|
387
|
+
)
|
|
388
|
+
return
|
|
389
|
+
|
|
390
|
+
killed_match = _KILLED_RE.match(record.body)
|
|
391
|
+
if killed_match is not None:
|
|
392
|
+
self._record_timestamp = record.timestamp
|
|
393
|
+
if self._is_uncertain_at(record.pid, record.timestamp):
|
|
394
|
+
self._emit_uncertain_exit(record)
|
|
395
|
+
return
|
|
396
|
+
if self._is_thread_at(record.pid, record.timestamp):
|
|
397
|
+
self._emit_thread_exit(record, signal=killed_match.group("signal"))
|
|
398
|
+
return
|
|
399
|
+
self._ensure_process(record.pid, record.timestamp)
|
|
400
|
+
self.sink.emit(
|
|
401
|
+
RuntimeEvent.create(
|
|
402
|
+
session_id=self.session_id,
|
|
403
|
+
event_type="process.exited",
|
|
404
|
+
relation="KILLED_BY",
|
|
405
|
+
source=self.process_entity(record.pid),
|
|
406
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
407
|
+
attributes={
|
|
408
|
+
"signal": killed_match.group("signal"),
|
|
409
|
+
"backend": "strace",
|
|
410
|
+
},
|
|
411
|
+
)
|
|
412
|
+
)
|
|
413
|
+
return
|
|
414
|
+
|
|
415
|
+
syscall = _SYSCALL_RE.match(record.body)
|
|
416
|
+
if syscall is None:
|
|
417
|
+
return
|
|
418
|
+
name = syscall.group("name")
|
|
419
|
+
args = syscall.group("args")
|
|
420
|
+
result = syscall.group("result")
|
|
421
|
+
self._ensure_process(record.pid, record.timestamp)
|
|
422
|
+
|
|
423
|
+
if name in {"clone", "clone3", "fork", "vfork"}:
|
|
424
|
+
self._parse_process_spawn(record, name, args, result)
|
|
425
|
+
elif name in {"execve", "execveat"}:
|
|
426
|
+
self._parse_exec(record, name, args, result)
|
|
427
|
+
elif name == "chdir":
|
|
428
|
+
self._parse_chdir(record, args, result)
|
|
429
|
+
elif name in {"open", "openat", "openat2", "creat"}:
|
|
430
|
+
self._parse_open(record, name, args, result)
|
|
431
|
+
elif name in {"unlink", "unlinkat", "rmdir"}:
|
|
432
|
+
self._parse_delete(record, name, args, result)
|
|
433
|
+
elif name in {"mkdir", "mkdirat"}:
|
|
434
|
+
self._parse_mkdir(record, name, args, result)
|
|
435
|
+
elif name in {"rename", "renameat", "renameat2"}:
|
|
436
|
+
self._parse_rename(record, name, args, result)
|
|
437
|
+
elif name == "connect":
|
|
438
|
+
self._parse_connect(record, args, result)
|
|
439
|
+
|
|
440
|
+
def _emit_uncertain_exit(self, record: TraceRecord) -> None:
|
|
441
|
+
self.sink.emit(RuntimeEvent.create(
|
|
442
|
+
session_id=self.session_id, event_type="task.exited",
|
|
443
|
+
relation="UNCLASSIFIED_TASK_EXITED",
|
|
444
|
+
source=self._uncertain_entity(record.pid),
|
|
445
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
446
|
+
attributes={"backend": "strace", "classification": "unknown",
|
|
447
|
+
"causal": False, "attribution": "syscall"},
|
|
448
|
+
))
|
|
449
|
+
|
|
450
|
+
def _emit_thread_exit(
|
|
451
|
+
self, record: TraceRecord, *, exit_code: int | None = None,
|
|
452
|
+
signal: str | None = None,
|
|
453
|
+
) -> None:
|
|
454
|
+
self.sink.emit(RuntimeEvent.create(
|
|
455
|
+
session_id=self.session_id, event_type="thread.exited",
|
|
456
|
+
relation="EXITED_THREAD" if signal is None else "THREAD_KILLED_BY",
|
|
457
|
+
source=self._thread_entity(record.pid),
|
|
458
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
459
|
+
attributes={"exit_code": exit_code, "signal": signal,
|
|
460
|
+
"attribution": "syscall", "backend": "strace"},
|
|
461
|
+
))
|
|
462
|
+
|
|
463
|
+
def _parse_process_spawn(
|
|
464
|
+
self, record: TraceRecord, name: str, args: str, result: str
|
|
465
|
+
) -> None:
|
|
466
|
+
child_match = _CLONE_RESULT_RE.match(result)
|
|
467
|
+
if child_match is None:
|
|
468
|
+
return
|
|
469
|
+
child_pid = int(child_match.group("pid"))
|
|
470
|
+
kind = self._clone_kind(name, args)
|
|
471
|
+
if kind == "unknown":
|
|
472
|
+
# The syscall return exposes a task ID, but without readable
|
|
473
|
+
# clone flags the OS has not established process-vs-thread kind.
|
|
474
|
+
# Do not emit a native process SPAWNED or an A-grade ancestry edge.
|
|
475
|
+
self.sink.emit(RuntimeEvent.create(
|
|
476
|
+
session_id=self.session_id, event_type="task.started",
|
|
477
|
+
relation="CLONE_KIND_UNRESOLVED",
|
|
478
|
+
source=self.process_entity(record.pid),
|
|
479
|
+
target=self._uncertain_entity(child_pid),
|
|
480
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
481
|
+
attributes={"syscall": name, "backend": "strace",
|
|
482
|
+
"attribution": "syscall", "causal": False,
|
|
483
|
+
"classification": "unknown"},
|
|
484
|
+
))
|
|
485
|
+
return
|
|
486
|
+
if kind == "thread":
|
|
487
|
+
# CLONE_THREAD creates a task/TID in the same thread group, not a
|
|
488
|
+
# new process. Retain the observed thread without inventing SPAWNED.
|
|
489
|
+
self.sink.emit(RuntimeEvent.create(
|
|
490
|
+
session_id=self.session_id, event_type="thread.started",
|
|
491
|
+
relation="STARTED_THREAD",
|
|
492
|
+
source=self.process_entity(record.pid),
|
|
493
|
+
target=self._thread_entity(child_pid),
|
|
494
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
495
|
+
attributes={"syscall": name, "attribution": "syscall",
|
|
496
|
+
"causal": True, "backend": "strace"},
|
|
497
|
+
))
|
|
498
|
+
return
|
|
499
|
+
self._ensure_process(
|
|
500
|
+
child_pid,
|
|
501
|
+
record.timestamp,
|
|
502
|
+
parent_pid=self._process_pid(record.pid),
|
|
503
|
+
relation="SPAWNED",
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
def _parse_exec(self, record: TraceRecord, name: str, args: str, result: str) -> None:
|
|
507
|
+
if not result.startswith("0"):
|
|
508
|
+
return
|
|
509
|
+
quoted = _quoted_arguments(args)
|
|
510
|
+
if not quoted:
|
|
511
|
+
return
|
|
512
|
+
executable = quoted[0]
|
|
513
|
+
target_path = self._resolve_path(record.pid, executable)
|
|
514
|
+
self._executable_by_pid[self._process_pid(record.pid)] = target_path.name
|
|
515
|
+
target = Entity(
|
|
516
|
+
type="executable",
|
|
517
|
+
id=f"executable:{target_path}",
|
|
518
|
+
name=target_path.name,
|
|
519
|
+
)
|
|
520
|
+
self.sink.emit(
|
|
521
|
+
RuntimeEvent.create(
|
|
522
|
+
session_id=self.session_id,
|
|
523
|
+
event_type="process.exec",
|
|
524
|
+
relation="EXECUTED",
|
|
525
|
+
source=self.process_entity(record.pid),
|
|
526
|
+
target=target,
|
|
527
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
528
|
+
attributes={
|
|
529
|
+
"syscall": name,
|
|
530
|
+
"argument_count": max(0, len(quoted) - 1),
|
|
531
|
+
"backend": "strace",
|
|
532
|
+
"attribution": "syscall",
|
|
533
|
+
"causal": True,
|
|
534
|
+
},
|
|
535
|
+
)
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
def _parse_chdir(self, record: TraceRecord, args: str, result: str) -> None:
|
|
539
|
+
if not result.startswith("0"):
|
|
540
|
+
return
|
|
541
|
+
quoted = _quoted_arguments(args)
|
|
542
|
+
if not quoted:
|
|
543
|
+
return
|
|
544
|
+
new_cwd = self._resolve_path(record.pid, quoted[0])
|
|
545
|
+
self._cwd_by_pid[self._process_pid(record.pid)] = new_cwd
|
|
546
|
+
target = Entity(
|
|
547
|
+
type="directory",
|
|
548
|
+
id=f"directory:{new_cwd}",
|
|
549
|
+
name=new_cwd.name,
|
|
550
|
+
)
|
|
551
|
+
self.sink.emit(
|
|
552
|
+
RuntimeEvent.create(
|
|
553
|
+
session_id=self.session_id,
|
|
554
|
+
event_type="filesystem.chdir",
|
|
555
|
+
relation="CHANGED_CWD_TO",
|
|
556
|
+
source=self.process_entity(record.pid),
|
|
557
|
+
target=target,
|
|
558
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
559
|
+
attributes={
|
|
560
|
+
"attribution": "syscall",
|
|
561
|
+
"causal": True,
|
|
562
|
+
"backend": "strace",
|
|
563
|
+
},
|
|
564
|
+
)
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
def _parse_open(self, record: TraceRecord, name: str, args: str, result: str) -> None:
|
|
568
|
+
if result.startswith("-1"):
|
|
569
|
+
return
|
|
570
|
+
quoted = _quoted_arguments(args)
|
|
571
|
+
if not quoted:
|
|
572
|
+
return
|
|
573
|
+
raw_path = quoted[0]
|
|
574
|
+
path = self._resolve_open_path(record.pid, name, args, raw_path)
|
|
575
|
+
flags = self._open_flags(name, args)
|
|
576
|
+
relation = self._open_relation(flags, name)
|
|
577
|
+
entity_type = "directory" if "O_DIRECTORY" in flags else "file"
|
|
578
|
+
target = Entity(
|
|
579
|
+
type=entity_type,
|
|
580
|
+
id=f"{entity_type}:{path}",
|
|
581
|
+
name=path.name,
|
|
582
|
+
)
|
|
583
|
+
self.sink.emit(
|
|
584
|
+
RuntimeEvent.create(
|
|
585
|
+
session_id=self.session_id,
|
|
586
|
+
event_type="filesystem.open",
|
|
587
|
+
relation=relation,
|
|
588
|
+
source=self.process_entity(record.pid),
|
|
589
|
+
target=target,
|
|
590
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
591
|
+
attributes={
|
|
592
|
+
"syscall": name,
|
|
593
|
+
"flags": flags,
|
|
594
|
+
"raw_path": raw_path,
|
|
595
|
+
"within_watch_root": self._within_watch_root(path),
|
|
596
|
+
"attribution": "syscall",
|
|
597
|
+
"causal": True,
|
|
598
|
+
"backend": "strace",
|
|
599
|
+
},
|
|
600
|
+
)
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
def _parse_delete(self, record: TraceRecord, name: str, args: str, result: str) -> None:
|
|
604
|
+
if not result.startswith("0"):
|
|
605
|
+
return
|
|
606
|
+
quoted = _quoted_arguments(args)
|
|
607
|
+
if not quoted:
|
|
608
|
+
return
|
|
609
|
+
path = self._resolve_open_path(record.pid, name, args, quoted[0])
|
|
610
|
+
entity_type = "directory" if name == "rmdir" else "file"
|
|
611
|
+
target = Entity(
|
|
612
|
+
type=entity_type,
|
|
613
|
+
id=f"{entity_type}:{path}",
|
|
614
|
+
name=path.name,
|
|
615
|
+
)
|
|
616
|
+
self.sink.emit(
|
|
617
|
+
RuntimeEvent.create(
|
|
618
|
+
session_id=self.session_id,
|
|
619
|
+
event_type="filesystem.delete",
|
|
620
|
+
relation="DELETED",
|
|
621
|
+
source=self.process_entity(record.pid),
|
|
622
|
+
target=target,
|
|
623
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
624
|
+
attributes={
|
|
625
|
+
"syscall": name,
|
|
626
|
+
"within_watch_root": self._within_watch_root(path),
|
|
627
|
+
"attribution": "syscall",
|
|
628
|
+
"causal": True,
|
|
629
|
+
"backend": "strace",
|
|
630
|
+
},
|
|
631
|
+
)
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
def _parse_mkdir(self, record: TraceRecord, name: str, args: str, result: str) -> None:
|
|
635
|
+
if not result.startswith("0"):
|
|
636
|
+
return
|
|
637
|
+
quoted = _quoted_arguments(args)
|
|
638
|
+
if not quoted:
|
|
639
|
+
return
|
|
640
|
+
path = self._resolve_open_path(record.pid, name, args, quoted[0])
|
|
641
|
+
target = Entity(
|
|
642
|
+
type="directory",
|
|
643
|
+
id=f"directory:{path}",
|
|
644
|
+
name=path.name,
|
|
645
|
+
)
|
|
646
|
+
self.sink.emit(
|
|
647
|
+
RuntimeEvent.create(
|
|
648
|
+
session_id=self.session_id,
|
|
649
|
+
event_type="filesystem.create",
|
|
650
|
+
relation="CREATED",
|
|
651
|
+
source=self.process_entity(record.pid),
|
|
652
|
+
target=target,
|
|
653
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
654
|
+
attributes={
|
|
655
|
+
"syscall": name,
|
|
656
|
+
"within_watch_root": self._within_watch_root(path),
|
|
657
|
+
"attribution": "syscall",
|
|
658
|
+
"causal": True,
|
|
659
|
+
"backend": "strace",
|
|
660
|
+
},
|
|
661
|
+
)
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
def _parse_rename(self, record: TraceRecord, name: str, args: str, result: str) -> None:
|
|
665
|
+
if not result.startswith("0"):
|
|
666
|
+
return
|
|
667
|
+
quoted = _quoted_arguments(args)
|
|
668
|
+
if len(quoted) < 2:
|
|
669
|
+
return
|
|
670
|
+
source_path = self._resolve_path(record.pid, quoted[-2])
|
|
671
|
+
destination_path = self._resolve_path(record.pid, quoted[-1])
|
|
672
|
+
target = Entity(
|
|
673
|
+
type="file",
|
|
674
|
+
id=f"file:{destination_path}",
|
|
675
|
+
name=destination_path.name,
|
|
676
|
+
)
|
|
677
|
+
self.sink.emit(
|
|
678
|
+
RuntimeEvent.create(
|
|
679
|
+
session_id=self.session_id,
|
|
680
|
+
event_type="filesystem.rename",
|
|
681
|
+
relation="RENAMED_TO",
|
|
682
|
+
source=self.process_entity(record.pid),
|
|
683
|
+
target=target,
|
|
684
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
685
|
+
attributes={
|
|
686
|
+
"syscall": name,
|
|
687
|
+
"source_path": str(source_path),
|
|
688
|
+
"destination_path": str(destination_path),
|
|
689
|
+
"within_watch_root": self._within_watch_root(destination_path),
|
|
690
|
+
"attribution": "syscall",
|
|
691
|
+
"causal": True,
|
|
692
|
+
"backend": "strace",
|
|
693
|
+
},
|
|
694
|
+
)
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
def _parse_connect(self, record: TraceRecord, args: str, result: str) -> None:
|
|
698
|
+
family: str | None = None
|
|
699
|
+
endpoint: str | None = None
|
|
700
|
+
ipv4 = _IPV4_RE.search(args)
|
|
701
|
+
if ipv4 is not None:
|
|
702
|
+
family = "AF_INET"
|
|
703
|
+
endpoint = f"{ipv4.group('host')}:{ipv4.group('port')}"
|
|
704
|
+
else:
|
|
705
|
+
ipv6 = _IPV6_RE.search(args)
|
|
706
|
+
if ipv6 is not None:
|
|
707
|
+
family = "AF_INET6"
|
|
708
|
+
endpoint = f"[{ipv6.group('host')}]:{ipv6.group('port')}"
|
|
709
|
+
else:
|
|
710
|
+
unix = _UNIX_RE.search(args)
|
|
711
|
+
if unix is not None:
|
|
712
|
+
family = "AF_UNIX"
|
|
713
|
+
endpoint = unix.group("path")
|
|
714
|
+
if endpoint is None:
|
|
715
|
+
return
|
|
716
|
+
|
|
717
|
+
error_match = _CONNECT_ERROR_RE.match(result)
|
|
718
|
+
connected = error_match is None and not result.startswith("-1")
|
|
719
|
+
relation = "CONNECTED_TO" if connected else "CONNECT_ATTEMPTED"
|
|
720
|
+
event_type = "network.connection" if connected else "network.connection_attempt"
|
|
721
|
+
errno = error_match.group("errno") if error_match is not None else None
|
|
722
|
+
|
|
723
|
+
target_type = "unix_socket" if family == "AF_UNIX" else "network_endpoint"
|
|
724
|
+
target = Entity(
|
|
725
|
+
type=target_type,
|
|
726
|
+
id=f"{target_type}:{endpoint}",
|
|
727
|
+
name=endpoint,
|
|
728
|
+
)
|
|
729
|
+
self.sink.emit(
|
|
730
|
+
RuntimeEvent.create(
|
|
731
|
+
session_id=self.session_id,
|
|
732
|
+
event_type=event_type,
|
|
733
|
+
relation=relation,
|
|
734
|
+
source=self.process_entity(record.pid),
|
|
735
|
+
target=target,
|
|
736
|
+
timestamp=_iso_timestamp(record.timestamp),
|
|
737
|
+
attributes={
|
|
738
|
+
"family": family,
|
|
739
|
+
"endpoint": endpoint,
|
|
740
|
+
"syscall": "connect",
|
|
741
|
+
"result": result,
|
|
742
|
+
"errno": errno,
|
|
743
|
+
"connected": connected,
|
|
744
|
+
"attribution": "syscall",
|
|
745
|
+
"causal": True,
|
|
746
|
+
"backend": "strace",
|
|
747
|
+
},
|
|
748
|
+
)
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
def _resolve_open_path(self, pid: int, syscall: str, args: str, raw_path: str) -> Path:
|
|
752
|
+
path = Path(raw_path).expanduser()
|
|
753
|
+
if path.is_absolute():
|
|
754
|
+
return path.resolve(strict=False)
|
|
755
|
+
if syscall in {"openat", "openat2", "unlinkat", "mkdirat"}:
|
|
756
|
+
dirfd_match = _DIRFD_RE.search(args)
|
|
757
|
+
if dirfd_match is not None:
|
|
758
|
+
return (Path(dirfd_match.group("path")) / path).resolve(strict=False)
|
|
759
|
+
return self._resolve_path(pid, raw_path)
|
|
760
|
+
|
|
761
|
+
def _resolve_path(self, pid: int, raw_path: str) -> Path:
|
|
762
|
+
path = Path(raw_path).expanduser()
|
|
763
|
+
if path.is_absolute():
|
|
764
|
+
return path.resolve(strict=False)
|
|
765
|
+
cwd = self._cwd_by_pid.get(self._process_pid(pid), self.watch_root)
|
|
766
|
+
return (cwd / path).resolve(strict=False)
|
|
767
|
+
|
|
768
|
+
def _within_watch_root(self, path: Path) -> bool:
|
|
769
|
+
return path == self.watch_root or self.watch_root in path.parents
|
|
770
|
+
|
|
771
|
+
@staticmethod
|
|
772
|
+
def _open_flags(syscall: str, args: str) -> str:
|
|
773
|
+
if syscall == "creat":
|
|
774
|
+
return "O_WRONLY|O_CREAT|O_TRUNC"
|
|
775
|
+
quoted = list(_QUOTED_RE.finditer(args))
|
|
776
|
+
if not quoted:
|
|
777
|
+
return ""
|
|
778
|
+
after_path = args[quoted[0].end() :].lstrip(", ")
|
|
779
|
+
return after_path.split(",", 1)[0].strip()
|
|
780
|
+
|
|
781
|
+
@staticmethod
|
|
782
|
+
def _open_relation(flags: str, syscall: str) -> str:
|
|
783
|
+
if syscall == "creat" or "O_CREAT" in flags:
|
|
784
|
+
return "OPENED_WRITE"
|
|
785
|
+
if "O_RDWR" in flags:
|
|
786
|
+
return "OPENED_READ_WRITE"
|
|
787
|
+
if any(flag in flags for flag in ("O_WRONLY", "O_TRUNC", "O_APPEND")):
|
|
788
|
+
return "OPENED_WRITE"
|
|
789
|
+
return "OPENED_READ"
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
class StraceRuntimeCollector:
|
|
793
|
+
"""Linux reference backend with syscall-attributed runtime evidence."""
|
|
794
|
+
|
|
795
|
+
backend_name = "strace"
|
|
796
|
+
|
|
797
|
+
def __init__(
|
|
798
|
+
self,
|
|
799
|
+
*,
|
|
800
|
+
session_id: str,
|
|
801
|
+
sink: JsonlSink,
|
|
802
|
+
watch_root: Path,
|
|
803
|
+
collect_filesystem: bool = True,
|
|
804
|
+
collect_network: bool = True,
|
|
805
|
+
trace_root: Path | None = None,
|
|
806
|
+
keep_raw_trace: bool = False,
|
|
807
|
+
) -> None:
|
|
808
|
+
self.session_id = session_id
|
|
809
|
+
self.sink = sink
|
|
810
|
+
self.watch_root = watch_root.expanduser().resolve()
|
|
811
|
+
self.collect_filesystem = collect_filesystem
|
|
812
|
+
self.collect_network = collect_network
|
|
813
|
+
self.trace_root = (
|
|
814
|
+
trace_root or (self.watch_root / ".execweave" / "traces" / session_id)
|
|
815
|
+
).resolve()
|
|
816
|
+
self.keep_raw_trace = keep_raw_trace
|
|
817
|
+
|
|
818
|
+
def _prepare_trace_directory(self) -> None:
|
|
819
|
+
"""Guard private, potentially secret-bearing native trace evidence."""
|
|
820
|
+
# Native syscall traces can include entire execve argv and are much more
|
|
821
|
+
# sensitive than projected event/graph evidence. Protect the dedicated
|
|
822
|
+
# directory even when the caller sends graph output elsewhere.
|
|
823
|
+
self.trace_root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
824
|
+
self.trace_root.chmod(0o700)
|
|
825
|
+
_protect_git_run_directory(self.trace_root / "trace")
|
|
826
|
+
raw_ignore = self.trace_root / ".gitignore"
|
|
827
|
+
try:
|
|
828
|
+
write_private_text(raw_ignore, "*\n")
|
|
829
|
+
except FileExistsError:
|
|
830
|
+
# A custom ignore file that does not protect the raw trace is
|
|
831
|
+
# insufficient: fail closed rather than retaining stageable argv.
|
|
832
|
+
if raw_ignore.read_text(encoding="utf-8") != "*\n":
|
|
833
|
+
raise ValueError("native strace directory must ignore all raw traces")
|
|
834
|
+
|
|
835
|
+
def run(self, command: list[str]) -> int:
|
|
836
|
+
if not command:
|
|
837
|
+
raise ValueError("command must not be empty")
|
|
838
|
+
executable = shutil.which("strace")
|
|
839
|
+
if not sys.platform.startswith("linux") or executable is None:
|
|
840
|
+
raise RuntimeError("The strace backend requires Linux and the strace executable")
|
|
841
|
+
|
|
842
|
+
self._prepare_trace_directory()
|
|
843
|
+
trace_prefix = self.trace_root / "trace"
|
|
844
|
+
agent_name = infer_agent_name(command)
|
|
845
|
+
agent = Entity(type="agent", id=f"agent:{agent_name}", name=agent_name)
|
|
846
|
+
session = Entity(
|
|
847
|
+
type="session",
|
|
848
|
+
id=f"session:{self.session_id}",
|
|
849
|
+
name=self.session_id,
|
|
850
|
+
attributes={
|
|
851
|
+
"command": public_command(command),
|
|
852
|
+
"argv_redacted": True,
|
|
853
|
+
"cwd": str(self.watch_root),
|
|
854
|
+
"backend": self.backend_name,
|
|
855
|
+
},
|
|
856
|
+
)
|
|
857
|
+
self.sink.emit(
|
|
858
|
+
RuntimeEvent.create(
|
|
859
|
+
session_id=self.session_id,
|
|
860
|
+
event_type="session.started",
|
|
861
|
+
relation="STARTED_SESSION",
|
|
862
|
+
source=agent,
|
|
863
|
+
target=session,
|
|
864
|
+
attributes={"collector_pid": os.getpid(), "backend": self.backend_name},
|
|
865
|
+
)
|
|
866
|
+
)
|
|
867
|
+
|
|
868
|
+
trace_expression = "%process"
|
|
869
|
+
if self.collect_filesystem:
|
|
870
|
+
trace_expression += ",%file"
|
|
871
|
+
if self.collect_network:
|
|
872
|
+
trace_expression += ",%network"
|
|
873
|
+
strace_command = [
|
|
874
|
+
executable,
|
|
875
|
+
"-ff",
|
|
876
|
+
"-ttt",
|
|
877
|
+
"-T",
|
|
878
|
+
"-yy",
|
|
879
|
+
"-s",
|
|
880
|
+
"256",
|
|
881
|
+
"-o",
|
|
882
|
+
str(trace_prefix),
|
|
883
|
+
"-e",
|
|
884
|
+
f"trace={trace_expression}",
|
|
885
|
+
"--",
|
|
886
|
+
*command,
|
|
887
|
+
]
|
|
888
|
+
return_code = 1
|
|
889
|
+
try:
|
|
890
|
+
with auto_specialized_launch(
|
|
891
|
+
command,
|
|
892
|
+
server_relay=True,
|
|
893
|
+
) as launch_environment:
|
|
894
|
+
completed = subprocess.run(
|
|
895
|
+
strace_command,
|
|
896
|
+
cwd=str(self.watch_root),
|
|
897
|
+
env=launch_environment,
|
|
898
|
+
check=False,
|
|
899
|
+
umask=0o077, # strace creates raw trace files mode 0600
|
|
900
|
+
)
|
|
901
|
+
return_code = int(completed.returncode)
|
|
902
|
+
records = read_trace_records(self.trace_root)
|
|
903
|
+
parser = StraceParser(
|
|
904
|
+
session_id=self.session_id,
|
|
905
|
+
sink=self.sink,
|
|
906
|
+
watch_root=self.watch_root,
|
|
907
|
+
command=command,
|
|
908
|
+
)
|
|
909
|
+
parser.parse(records)
|
|
910
|
+
return return_code
|
|
911
|
+
finally:
|
|
912
|
+
if not self.keep_raw_trace:
|
|
913
|
+
shutil.rmtree(self.trace_root, ignore_errors=True)
|
|
914
|
+
self.sink.emit(
|
|
915
|
+
RuntimeEvent.create(
|
|
916
|
+
session_id=self.session_id,
|
|
917
|
+
event_type="session.finished",
|
|
918
|
+
relation="FINISHED_SESSION",
|
|
919
|
+
source=session,
|
|
920
|
+
attributes={
|
|
921
|
+
"return_code": return_code,
|
|
922
|
+
"backend": self.backend_name,
|
|
923
|
+
"raw_trace_kept": self.keep_raw_trace,
|
|
924
|
+
"trace_directory": str(self.trace_root) if self.keep_raw_trace else None,
|
|
925
|
+
},
|
|
926
|
+
)
|
|
927
|
+
)
|