execweave 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. execweave/__init__.py +3 -0
  2. execweave/__main__.py +5 -0
  3. execweave/_conversation_records_core.py +902 -0
  4. execweave/_dashboard_shell_base.py +148 -0
  5. execweave/_http_proxy_base.py +565 -0
  6. execweave/_http_proxy_bounded.py +560 -0
  7. execweave/_http_proxy_stage.py +509 -0
  8. execweave/acceptance_output.py +19 -0
  9. execweave/agent_bootstrap.py +395 -0
  10. execweave/agent_topology.py +313 -0
  11. execweave/agent_trace.py +1162 -0
  12. execweave/agy_preview_sanitize.py +102 -0
  13. execweave/analysis.py +427 -0
  14. execweave/anthropic.py +228 -0
  15. execweave/anthropic_cli.py +171 -0
  16. execweave/anthropic_full_fidelity.py +385 -0
  17. execweave/antigravity_adapter.py +112 -0
  18. execweave/antigravity_adapter_base.py +479 -0
  19. execweave/antigravity_full_fidelity.py +656 -0
  20. execweave/antigravity_full_fidelity_base.py +172 -0
  21. execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
  22. execweave/antigravity_hook_cli.py +209 -0
  23. execweave/antigravity_record.py +96 -0
  24. execweave/antigravity_subagent_linkage.py +449 -0
  25. execweave/antigravity_trace_capability.py +39 -0
  26. execweave/auto_specialized.py +547 -0
  27. execweave/backends.py +102 -0
  28. execweave/benchmark.py +80 -0
  29. execweave/claude_adapter.py +517 -0
  30. execweave/claude_child_transcript.py +314 -0
  31. execweave/claude_delegation.py +136 -0
  32. execweave/claude_full_fidelity.py +396 -0
  33. execweave/claude_hook_cli.py +209 -0
  34. execweave/claude_hook_contract.py +943 -0
  35. execweave/claude_model_observer.py +353 -0
  36. execweave/claude_record.py +106 -0
  37. execweave/cli.py +629 -0
  38. execweave/codex_adapter.py +455 -0
  39. execweave/codex_conversation.py +621 -0
  40. execweave/codex_full_fidelity.py +287 -0
  41. execweave/codex_hook_cli.py +301 -0
  42. execweave/codex_hook_entry.py +207 -0
  43. execweave/codex_hook_lifecycle.py +363 -0
  44. execweave/codex_message_diagnostics.py +322 -0
  45. execweave/codex_message_transport_diagnostics.py +399 -0
  46. execweave/codex_record.py +199 -0
  47. execweave/codex_rollout_structures.py +402 -0
  48. execweave/codex_rollout_trace.py +56 -0
  49. execweave/codex_rollout_trace_base.py +1509 -0
  50. execweave/collector.py +768 -0
  51. execweave/command.py +157 -0
  52. execweave/command_privacy.py +20 -0
  53. execweave/content_evidence.py +101 -0
  54. execweave/content_integrity.py +289 -0
  55. execweave/content_store.py +273 -0
  56. execweave/controlled_checks.py +561 -0
  57. execweave/conversation_archive.py +338 -0
  58. execweave/conversation_message_identity.py +264 -0
  59. execweave/conversation_preview.py +66 -0
  60. execweave/conversation_preview_antigravity.py +32 -0
  61. execweave/conversation_preview_claude.py +31 -0
  62. execweave/conversation_preview_codex.py +107 -0
  63. execweave/conversation_preview_common.py +180 -0
  64. execweave/conversation_preview_generic.py +188 -0
  65. execweave/conversation_preview_lines.py +133 -0
  66. execweave/conversation_preview_transcript.py +121 -0
  67. execweave/conversation_records.py +349 -0
  68. execweave/conversation_records_antigravity.py +370 -0
  69. execweave/conversation_records_codex.py +83 -0
  70. execweave/conversation_records_common.py +17 -0
  71. execweave/conversation_records_ollama.py +39 -0
  72. execweave/correlation.py +818 -0
  73. execweave/cursor_adapter.py +349 -0
  74. execweave/cursor_delegation.py +87 -0
  75. execweave/cursor_delegation_base.py +220 -0
  76. execweave/cursor_full_fidelity.py +489 -0
  77. execweave/cursor_hook_cli.py +195 -0
  78. execweave/cursor_hook_contract.py +439 -0
  79. execweave/cursor_lifecycle.py +159 -0
  80. execweave/cursor_record.py +96 -0
  81. execweave/dashboard_shell.py +283 -0
  82. execweave/delivery_status.py +94 -0
  83. execweave/entry.py +98 -0
  84. execweave/evidence_availability.py +113 -0
  85. execweave/evidence_grade.py +166 -0
  86. execweave/fidelity.py +304 -0
  87. execweave/filesystem.py +327 -0
  88. execweave/finalization.py +92 -0
  89. execweave/focus.py +118 -0
  90. execweave/framework_adapters/__init__.py +34 -0
  91. execweave/framework_adapters/autogen.py +398 -0
  92. execweave/framework_adapters/base.py +580 -0
  93. execweave/framework_adapters/camel.py +270 -0
  94. execweave/framework_adapters/camel_channel.py +71 -0
  95. execweave/framework_adapters/metagpt.py +315 -0
  96. execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
  97. execweave/framework_adapters/metagpt_recording.py +342 -0
  98. execweave/framework_adapters/registry.py +90 -0
  99. execweave/graph.py +590 -0
  100. execweave/graph_ops.py +472 -0
  101. execweave/hook_command.py +32 -0
  102. execweave/hook_delivery.py +32 -0
  103. execweave/hook_input.py +16 -0
  104. execweave/http_proxy.py +187 -0
  105. execweave/http_proxy_cli.py +84 -0
  106. execweave/inference_gateway.py +476 -0
  107. execweave/inference_gateway_cli.py +211 -0
  108. execweave/inference_gateway_full_fidelity.py +613 -0
  109. execweave/inference_identity.py +76 -0
  110. execweave/inference_identity_cli.py +60 -0
  111. execweave/integrity.py +235 -0
  112. execweave/integrity_cli.py +55 -0
  113. execweave/investigation_index.py +445 -0
  114. execweave/litellm_callback.py +211 -0
  115. execweave/litellm_callback_cli.py +42 -0
  116. execweave/live.py +445 -0
  117. execweave/live_core.py +972 -0
  118. execweave/live_view.py +109 -0
  119. execweave/live_view_extra_style.py +11 -0
  120. execweave/live_view_markup.py +29 -0
  121. execweave/live_view_process_layout.py +650 -0
  122. execweave/live_view_readability.py +502 -0
  123. execweave/live_view_script_a.py +59 -0
  124. execweave/live_view_script_b.py +97 -0
  125. execweave/live_view_script_c.py +59 -0
  126. execweave/live_view_script_d.py +40 -0
  127. execweave/live_view_style.py +34 -0
  128. execweave/model_runtime.py +560 -0
  129. execweave/model_runtime_cli.py +265 -0
  130. execweave/model_runtime_full_fidelity.py +519 -0
  131. execweave/observation.py +53 -0
  132. execweave/observation_demo.py +69 -0
  133. execweave/openai_agents.py +267 -0
  134. execweave/openai_agents_sdk.py +453 -0
  135. execweave/openai_compatible.py +239 -0
  136. execweave/openai_compatible_cli.py +189 -0
  137. execweave/openai_compatible_full_fidelity.py +438 -0
  138. execweave/opencode_adapter.py +325 -0
  139. execweave/opencode_event_contract.py +734 -0
  140. execweave/opencode_full_fidelity.py +198 -0
  141. execweave/opencode_hook_cli.py +119 -0
  142. execweave/opencode_plugin_cli.py +150 -0
  143. execweave/opencode_record.py +96 -0
  144. execweave/opencode_task_linkage.py +225 -0
  145. execweave/overhead_benchmark.py +440 -0
  146. execweave/privacy.py +84 -0
  147. execweave/private_io.py +465 -0
  148. execweave/provider_capability.py +578 -0
  149. execweave/provider_lifecycle.py +282 -0
  150. execweave/provider_record.py +290 -0
  151. execweave/reader_identity.py +13 -0
  152. execweave/redacted_archive.py +906 -0
  153. execweave/risk.py +106 -0
  154. execweave/rule_pack.py +359 -0
  155. execweave/rule_pack_cli.py +57 -0
  156. execweave/run_assessment.py +200 -0
  157. execweave/runtime_endpoint_availability.py +44 -0
  158. execweave/scalability_benchmark.py +195 -0
  159. execweave/schema.py +62 -0
  160. execweave/scope.py +85 -0
  161. execweave/semantic.py +453 -0
  162. execweave/session_summary.py +159 -0
  163. execweave/sink.py +71 -0
  164. execweave/strace_backend.py +927 -0
  165. execweave/stream_assembly.py +363 -0
  166. execweave/task_artifacts.py +192 -0
  167. execweave/task_validation.py +317 -0
  168. execweave/theme.py +40 -0
  169. execweave/top.py +599 -0
  170. execweave/top_cli.py +150 -0
  171. execweave/validate.py +196 -0
  172. execweave/vendor/dagre.min.js +815 -0
  173. execweave/view_cli.py +49 -0
  174. execweave/viewer.py +474 -0
  175. execweave/viewer_agent_panel.py +630 -0
  176. execweave/viewer_agent_panel_antigravity.py +31 -0
  177. execweave/viewer_agent_panel_claude.py +9 -0
  178. execweave/viewer_agent_panel_codex.py +50 -0
  179. execweave/viewer_agent_panel_cursor.py +9 -0
  180. execweave/viewer_agent_panel_default.py +79 -0
  181. execweave/viewer_agent_panel_ollama.py +20 -0
  182. execweave/viewer_agent_panel_opencode.py +9 -0
  183. execweave/viewer_agent_panel_registry.py +20 -0
  184. execweave/viewer_archive_verifier.py +178 -0
  185. execweave/viewer_background_files.py +86 -0
  186. execweave/viewer_content_browser.py +307 -0
  187. execweave/viewer_content_health.py +208 -0
  188. execweave/viewer_content_inspector.py +309 -0
  189. execweave/viewer_controlled_checks.py +258 -0
  190. execweave/viewer_conversation_sync.py +115 -0
  191. execweave/viewer_dashboard_clean.py +405 -0
  192. execweave/viewer_dashboard_focus.py +127 -0
  193. execweave/viewer_dashboard_hardening.py +264 -0
  194. execweave/viewer_dashboard_hardening_v2.py +62 -0
  195. execweave/viewer_dashboard_projection.py +261 -0
  196. execweave/viewer_delivery_status.py +155 -0
  197. execweave/viewer_edge_decross.py +117 -0
  198. execweave/viewer_execution_flow.py +611 -0
  199. execweave/viewer_execution_flow_provider_normalization.py +107 -0
  200. execweave/viewer_execution_flow_safety.py +349 -0
  201. execweave/viewer_external_endpoints.py +307 -0
  202. execweave/viewer_flow_canvas.py +1140 -0
  203. execweave/viewer_flow_layout.py +922 -0
  204. execweave/viewer_fold_state.py +31 -0
  205. execweave/viewer_framework_flow.py +68 -0
  206. execweave/viewer_framework_model_output.py +133 -0
  207. execweave/viewer_gif.py +278 -0
  208. execweave/viewer_history_browser.py +225 -0
  209. execweave/viewer_investigation.py +268 -0
  210. execweave/viewer_layout_geometry.py +192 -0
  211. execweave/viewer_layout_v2.py +429 -0
  212. execweave/viewer_layout_v2_detached.py +25 -0
  213. execweave/viewer_limits.py +93 -0
  214. execweave/viewer_live_layout.py +61 -0
  215. execweave/viewer_message_handoffs.py +114 -0
  216. execweave/viewer_projection.py +488 -0
  217. execweave/viewer_projection_base.py +522 -0
  218. execweave/viewer_projection_bridges.py +214 -0
  219. execweave/viewer_recorded_sources.py +146 -0
  220. execweave/viewer_run_assessment.py +274 -0
  221. execweave/viewer_run_guide.py +175 -0
  222. execweave/viewer_runtime_evidence.py +258 -0
  223. execweave/viewer_semantic_projection.py +641 -0
  224. execweave/viewer_session_flow.py +491 -0
  225. execweave/viewer_structure_share.py +132 -0
  226. execweave/viewer_task_validation.py +241 -0
  227. execweave/viewer_tool_mirror_identity.py +75 -0
  228. execweave/viewer_workflow_mode.py +127 -0
  229. execweave/workflow.py +183 -0
  230. execweave-1.0.0.dist-info/METADATA +462 -0
  231. execweave-1.0.0.dist-info/RECORD +234 -0
  232. execweave-1.0.0.dist-info/WHEEL +4 -0
  233. execweave-1.0.0.dist-info/entry_points.txt +30 -0
  234. execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
execweave/risk.py ADDED
@@ -0,0 +1,106 @@
1
+ """Conservative risk classification for observations, never enforcement claims."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import sys
6
+ from pathlib import Path, PurePath, PureWindowsPath
7
+ from typing import Mapping, Sequence
8
+
9
+ _PRIVILEGE_LAUNCHERS = frozenset({"sudo", "doas", "pkexec", "su", "runas"})
10
+ _POSIX_SYSTEM_PREFIXES = (
11
+ ("/etc", "system_configuration"),
12
+ ("/usr", "system_software"),
13
+ ("/bin", "system_software"),
14
+ ("/sbin", "system_software"),
15
+ ("/lib", "system_software"),
16
+ ("/lib64", "system_software"),
17
+ ("/boot", "boot_configuration"),
18
+ ("/System", "macos_system"),
19
+ ("/Library", "macos_system_library"),
20
+ )
21
+
22
+
23
+ def _command_basename(value: str) -> str:
24
+ name = Path(value).name.lower()
25
+ for suffix in (".exe", ".cmd", ".bat", ".ps1"):
26
+ if name.endswith(suffix):
27
+ name = name[: -len(suffix)]
28
+ break
29
+ return name
30
+
31
+
32
+ def privilege_process_trigger(
33
+ *,
34
+ name: str,
35
+ cmdline: Sequence[str],
36
+ exe: str | None = None,
37
+ ) -> str | None:
38
+ candidates = [name, exe or "", cmdline[0] if cmdline else ""]
39
+ for value in candidates:
40
+ if value and _command_basename(value) in _PRIVILEGE_LAUNCHERS:
41
+ return _command_basename(value)
42
+ lowered = [part.lower() for part in cmdline]
43
+ executable = _command_basename(candidates[-1] or name)
44
+ if executable in {"powershell", "pwsh"}:
45
+ for index, part in enumerate(lowered[:-1]):
46
+ if part in {"-verb", "/verb"} and lowered[index + 1] == "runas":
47
+ return "powershell_runas"
48
+ return None
49
+
50
+
51
+ def system_path_category(
52
+ path: str | Path,
53
+ *,
54
+ os_name: str | None = None,
55
+ environment: Mapping[str, str] | None = None,
56
+ ) -> str | None:
57
+ platform = os.name if os_name is None else os_name
58
+ if platform == "nt":
59
+ env = os.environ if environment is None else environment
60
+ candidate = str(PureWindowsPath(str(path))).casefold().rstrip("\\/")
61
+ roots = []
62
+ for key, category in (
63
+ ("SystemRoot", "windows_system"),
64
+ ("ProgramFiles", "installed_programs"),
65
+ ("ProgramFiles(x86)", "installed_programs"),
66
+ ("ProgramData", "system_program_data"),
67
+ ):
68
+ raw = env.get(key)
69
+ if raw:
70
+ roots.append((str(PureWindowsPath(raw)).casefold().rstrip("\\/"), category))
71
+ # Standard roots remain covered even in deliberately sparse environments.
72
+ roots.extend(((r"c:\windows", "windows_system"),
73
+ (r"c:\program files", "installed_programs"),
74
+ (r"c:\program files (x86)", "installed_programs"),
75
+ (r"c:\programdata", "system_program_data")))
76
+ for root, category in roots:
77
+ if candidate == root or candidate.startswith(root + "\\"):
78
+ return category
79
+ return None
80
+
81
+ # POSIX semantics were selected, so the verdict must not depend on the host's
82
+ # Path flavour: a host-native WindowsPath renders "/etc/x" as "\etc\x".
83
+ # Strings are already logical POSIX paths and stay verbatim.
84
+ candidate = path.as_posix() if isinstance(path, PurePath) else str(path)
85
+ if sys.platform == "darwin":
86
+ # macOS resolves /etc through /private/etc. Preserve the system-config
87
+ # classification after canonical path resolution without treating
88
+ # /private/etc as a Linux system root.
89
+ if candidate == "/private/etc" or candidate.startswith("/private/etc/"):
90
+ return "system_configuration"
91
+ for prefix, category in _POSIX_SYSTEM_PREFIXES:
92
+ if candidate == prefix or candidate.startswith(prefix + "/"):
93
+ return category
94
+ return None
95
+
96
+
97
+ def risk_attributes(kind: str, trigger: str, **details: object) -> dict[str, object]:
98
+ return {
99
+ "risk_kind": kind,
100
+ "trigger": trigger,
101
+ "severity": "high",
102
+ "default_decision": "deny",
103
+ "enforced": False,
104
+ "control_state": "observation_only",
105
+ **details,
106
+ }
execweave/rule_pack.py ADDED
@@ -0,0 +1,359 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections import Counter
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from string import ascii_letters, digits
8
+ from typing import Any, Sequence
9
+
10
+ RULE_PACK_SCHEMA_VERSION = "0.1"
11
+
12
+ _MAX_PACK_BYTES = 256 * 1024
13
+ _MAX_RULES = 128
14
+ _MAX_MATCH_VALUES = 16
15
+ _MAX_MATCH_VALUE_CHARS = 160
16
+ _MAX_ID_CHARS = 80
17
+
18
+ _ID_CHARS = frozenset(ascii_letters + digits + "._-")
19
+ _ALLOWED_SEVERITIES = {"high", "medium", "low", "info"}
20
+ _ALLOWED_TOP_KEYS = {"rule_pack_schema_version", "id", "rules"}
21
+ _ALLOWED_RULE_KEYS = {"id", "severity", "match"}
22
+ _LIST_MATCH_KEYS = {
23
+ "relations",
24
+ "source_types",
25
+ "target_types",
26
+ "source_id_contains",
27
+ "target_id_contains",
28
+ "source_name_contains",
29
+ "target_name_contains",
30
+ "backends",
31
+ "attributions",
32
+ }
33
+ _ALLOWED_MATCH_KEYS = {*_LIST_MATCH_KEYS, "causal"}
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class RulePackRule:
38
+ rule_id: str
39
+ severity: str
40
+ match: dict[str, Any]
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class RulePack:
45
+ pack_id: str
46
+ rules: tuple[RulePackRule, ...]
47
+
48
+ def metadata(self) -> dict[str, Any]:
49
+ return {
50
+ "id": self.pack_id,
51
+ "rule_count": len(self.rules),
52
+ "schema_version": RULE_PACK_SCHEMA_VERSION,
53
+ }
54
+
55
+
56
+ def _identifier(value: object, *, label: str) -> str:
57
+ if not isinstance(value, str) or not value:
58
+ raise ValueError(f"{label} must be a non-empty string")
59
+ if len(value) > _MAX_ID_CHARS:
60
+ raise ValueError(f"{label} exceeds {_MAX_ID_CHARS} characters")
61
+ if any(character not in _ID_CHARS for character in value):
62
+ raise ValueError(f"{label} may contain only letters, digits, '.', '_', and '-'")
63
+ return value
64
+
65
+
66
+ def _validate_keys(payload: dict[str, Any], allowed: set[str], *, label: str) -> None:
67
+ unknown = sorted(set(payload) - allowed)
68
+ if unknown:
69
+ raise ValueError(f"{label} contains unsupported keys: {', '.join(unknown)}")
70
+
71
+
72
+ def _match_values(value: object, *, label: str) -> tuple[str, ...]:
73
+ if not isinstance(value, list) or not value:
74
+ raise ValueError(f"{label} must be a non-empty list of strings")
75
+ if len(value) > _MAX_MATCH_VALUES:
76
+ raise ValueError(f"{label} exceeds {_MAX_MATCH_VALUES} values")
77
+ result: list[str] = []
78
+ for item in value:
79
+ if not isinstance(item, str) or not item:
80
+ raise ValueError(f"{label} must contain only non-empty strings")
81
+ if len(item) > _MAX_MATCH_VALUE_CHARS:
82
+ raise ValueError(
83
+ f"{label} contains a value longer than {_MAX_MATCH_VALUE_CHARS} characters"
84
+ )
85
+ result.append(item)
86
+ return tuple(result)
87
+
88
+
89
+ def _parse_rule(payload: object, *, pack_id: str, index: int) -> RulePackRule:
90
+ if not isinstance(payload, dict):
91
+ raise ValueError(f"rule {index} in {pack_id} must be an object")
92
+ _validate_keys(payload, _ALLOWED_RULE_KEYS, label=f"rule {index} in {pack_id}")
93
+
94
+ rule_id = _identifier(payload.get("id"), label=f"rule {index} id")
95
+ severity = payload.get("severity")
96
+ if severity not in _ALLOWED_SEVERITIES:
97
+ raise ValueError(
98
+ f"rule {pack_id}/{rule_id} severity must be one of: "
99
+ + ", ".join(sorted(_ALLOWED_SEVERITIES))
100
+ )
101
+
102
+ raw_match = payload.get("match")
103
+ if not isinstance(raw_match, dict) or not raw_match:
104
+ raise ValueError(f"rule {pack_id}/{rule_id} match must be a non-empty object")
105
+ _validate_keys(
106
+ raw_match,
107
+ _ALLOWED_MATCH_KEYS,
108
+ label=f"rule {pack_id}/{rule_id} match",
109
+ )
110
+
111
+ match: dict[str, Any] = {}
112
+ for key in sorted(_LIST_MATCH_KEYS):
113
+ if key in raw_match:
114
+ match[key] = _match_values(
115
+ raw_match[key],
116
+ label=f"rule {pack_id}/{rule_id} match.{key}",
117
+ )
118
+ if "causal" in raw_match:
119
+ if not isinstance(raw_match["causal"], bool):
120
+ raise ValueError(f"rule {pack_id}/{rule_id} match.causal must be boolean")
121
+ match["causal"] = raw_match["causal"]
122
+ return RulePackRule(rule_id=rule_id, severity=str(severity), match=match)
123
+
124
+
125
+ def load_rule_pack(path: Path) -> RulePack:
126
+ source = Path(path).expanduser().resolve()
127
+ try:
128
+ size = source.stat().st_size
129
+ except OSError as exc:
130
+ raise ValueError(f"cannot read rule pack {source}: {exc}") from exc
131
+ if size > _MAX_PACK_BYTES:
132
+ raise ValueError(f"rule pack exceeds {_MAX_PACK_BYTES} bytes: {source}")
133
+ try:
134
+ payload = json.loads(source.read_text(encoding="utf-8"))
135
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
136
+ raise ValueError(f"invalid rule pack {source}: {exc}") from exc
137
+ if not isinstance(payload, dict):
138
+ raise ValueError("rule pack root must be an object")
139
+ _validate_keys(payload, _ALLOWED_TOP_KEYS, label="rule pack")
140
+
141
+ schema_version = payload.get("rule_pack_schema_version")
142
+ if schema_version != RULE_PACK_SCHEMA_VERSION:
143
+ raise ValueError(
144
+ "unsupported rule_pack_schema_version "
145
+ f"{schema_version!r}; expected {RULE_PACK_SCHEMA_VERSION!r}"
146
+ )
147
+ pack_id = _identifier(payload.get("id"), label="rule pack id")
148
+ raw_rules = payload.get("rules")
149
+ if not isinstance(raw_rules, list) or not raw_rules:
150
+ raise ValueError(f"rule pack {pack_id} rules must be a non-empty list")
151
+ if len(raw_rules) > _MAX_RULES:
152
+ raise ValueError(f"rule pack {pack_id} exceeds {_MAX_RULES} rules")
153
+
154
+ rules = tuple(
155
+ _parse_rule(rule, pack_id=pack_id, index=index)
156
+ for index, rule in enumerate(raw_rules, start=1)
157
+ )
158
+ rule_ids = [rule.rule_id for rule in rules]
159
+ if len(rule_ids) != len(set(rule_ids)):
160
+ raise ValueError(f"rule pack {pack_id} contains duplicate rule ids")
161
+ return RulePack(pack_id=pack_id, rules=rules)
162
+
163
+
164
+ def _node_map(graph: dict[str, Any]) -> dict[str, dict[str, Any]]:
165
+ return {
166
+ node["id"]: node
167
+ for node in graph.get("nodes", [])
168
+ if isinstance(node, dict) and isinstance(node.get("id"), str)
169
+ }
170
+
171
+
172
+ def _edge_values(edge: dict[str, Any], key: str) -> set[str]:
173
+ value = edge.get(key)
174
+ if isinstance(value, str):
175
+ return {value}
176
+ if isinstance(value, list):
177
+ return {item for item in value if isinstance(item, str)}
178
+ return set()
179
+
180
+
181
+ def _matches_any_contains(text: str, values: Sequence[str]) -> bool:
182
+ normalized = text.casefold()
183
+ return any(value.casefold() in normalized for value in values)
184
+
185
+
186
+ def _rule_matches(
187
+ rule: RulePackRule,
188
+ *,
189
+ edge: dict[str, Any],
190
+ source: dict[str, Any] | None,
191
+ target: dict[str, Any] | None,
192
+ ) -> bool:
193
+ match = rule.match
194
+ relation = edge.get("relation")
195
+ source_id = edge.get("source")
196
+ target_id = edge.get("target")
197
+
198
+ exact_checks = (
199
+ ("relations", relation),
200
+ ("source_types", source.get("type") if source else None),
201
+ ("target_types", target.get("type") if target else None),
202
+ )
203
+ for key, value in exact_checks:
204
+ allowed = match.get(key)
205
+ if allowed is not None and value not in allowed:
206
+ return False
207
+
208
+ contains_checks = (
209
+ ("source_id_contains", str(source_id or "")),
210
+ ("target_id_contains", str(target_id or "")),
211
+ ("source_name_contains", str(source.get("name") or "") if source else ""),
212
+ ("target_name_contains", str(target.get("name") or "") if target else ""),
213
+ )
214
+ for key, text in contains_checks:
215
+ values = match.get(key)
216
+ if values is not None and not _matches_any_contains(text, values):
217
+ return False
218
+
219
+ for key in ("backends", "attributions"):
220
+ required = match.get(key)
221
+ if required is not None and not _edge_values(edge, key).intersection(required):
222
+ return False
223
+
224
+ if "causal" in match and edge.get("causal") is not match["causal"]:
225
+ return False
226
+ return True
227
+
228
+
229
+ def _event_ids(edge: dict[str, Any], limit: int = 24) -> list[str]:
230
+ values = edge.get("event_ids") or []
231
+ return [str(value) for value in values if isinstance(value, str)][:limit]
232
+
233
+
234
+ def _validate_pack_set(rule_packs: Sequence[RulePack]) -> None:
235
+ pack_ids = [pack.pack_id for pack in rule_packs]
236
+ if len(pack_ids) != len(set(pack_ids)):
237
+ raise ValueError("rule pack ids must be unique within one analysis invocation")
238
+
239
+
240
+ def rule_pack_metadata(rule_packs: Sequence[RulePack]) -> list[dict[str, Any]]:
241
+ _validate_pack_set(rule_packs)
242
+ return [pack.metadata() for pack in rule_packs]
243
+
244
+
245
+ def evaluate_rule_packs(
246
+ graph: dict[str, Any],
247
+ rule_packs: Sequence[RulePack],
248
+ ) -> list[dict[str, Any]]:
249
+ _validate_pack_set(rule_packs)
250
+ nodes = _node_map(graph)
251
+ matches: list[dict[str, Any]] = []
252
+
253
+ for edge in graph.get("edges", []):
254
+ if not isinstance(edge, dict):
255
+ continue
256
+ edge_id = edge.get("id")
257
+ source_id = edge.get("source")
258
+ target_id = edge.get("target")
259
+ relation = edge.get("relation")
260
+ if not all(
261
+ isinstance(value, str) and value
262
+ for value in (edge_id, source_id, target_id, relation)
263
+ ):
264
+ continue
265
+ source = nodes.get(source_id)
266
+ target = nodes.get(target_id)
267
+
268
+ for pack in rule_packs:
269
+ for rule in pack.rules:
270
+ if not _rule_matches(rule, edge=edge, source=source, target=target):
271
+ continue
272
+ matches.append(
273
+ {
274
+ "rule_id": f"rule-pack:{pack.pack_id}:{rule.rule_id}",
275
+ "severity": rule.severity,
276
+ "title": "Rule-pack observation matched",
277
+ "summary": (
278
+ f"Rule pack {pack.pack_id}/{rule.rule_id} matched observed graph "
279
+ f"edge {edge_id}: {source_id} --{relation}--> {target_id}. "
280
+ "This records an observation match only; ExecWeave has not proven "
281
+ "byte-level data flow or exfiltration."
282
+ ),
283
+ "node_ids": [source_id, target_id],
284
+ "edge_ids": [edge_id],
285
+ "evidence_event_ids": _event_ids(edge),
286
+ "attributes": {
287
+ "rule_pack_schema_version": RULE_PACK_SCHEMA_VERSION,
288
+ "rule_pack_id": pack.pack_id,
289
+ "rule_pack_rule_id": rule.rule_id,
290
+ "relation": relation,
291
+ "causal": edge.get("causal"),
292
+ "observation_only": True,
293
+ "data_flow_proven": False,
294
+ "exfiltration_proven": False,
295
+ },
296
+ }
297
+ )
298
+ return matches
299
+
300
+
301
+ _SEVERITY_ORDER = {"high": 0, "medium": 1, "low": 2, "info": 3}
302
+
303
+
304
+ def analyze_graph_with_rule_packs(
305
+ graph: dict[str, Any],
306
+ rule_packs: Sequence[RulePack],
307
+ ) -> dict[str, Any]:
308
+ from .analysis import analyze_graph
309
+ from .evidence_grade import EVIDENCE_GRADES, annotate_finding
310
+
311
+ _validate_pack_set(rule_packs)
312
+ report = analyze_graph(graph)
313
+ edges_by_id = {
314
+ edge_id: edge
315
+ for edge in graph.get("edges", [])
316
+ if isinstance(edge, dict)
317
+ and isinstance((edge_id := edge.get("id")), str)
318
+ and edge_id
319
+ }
320
+ custom_findings = [
321
+ annotate_finding(finding, edges_by_id)
322
+ for finding in evaluate_rule_packs(graph, rule_packs)
323
+ ]
324
+ findings = [*report.get("findings", []), *custom_findings]
325
+ findings.sort(
326
+ key=lambda finding: (
327
+ _SEVERITY_ORDER.get(str(finding.get("severity") or ""), 99),
328
+ str(finding.get("rule_id") or ""),
329
+ list(finding.get("node_ids") or []),
330
+ )
331
+ )
332
+
333
+ severity_counts = Counter(str(finding.get("severity") or "") for finding in findings)
334
+ grade_counts = Counter(str(finding.get("evidence_grade") or "U") for finding in findings)
335
+ limitations = list(report.get("limitations") or [])
336
+ limitation = (
337
+ "Rule-pack findings are single-edge observation matches; they do not prove "
338
+ "byte-level data flow or exfiltration."
339
+ )
340
+ if limitation not in limitations:
341
+ limitations.append(limitation)
342
+
343
+ return {
344
+ **report,
345
+ "analysis_schema_version": "0.4",
346
+ "rule_pack_schema_version": RULE_PACK_SCHEMA_VERSION,
347
+ "rule_packs": rule_pack_metadata(rule_packs),
348
+ "finding_count": len(findings),
349
+ "severity_counts": {
350
+ severity: severity_counts.get(severity, 0)
351
+ for severity in ("high", "medium", "low", "info")
352
+ },
353
+ "evidence_grade_counts": {
354
+ grade: grade_counts.get(grade, 0)
355
+ for grade in EVIDENCE_GRADES
356
+ },
357
+ "limitations": limitations,
358
+ "findings": findings,
359
+ }
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from .graph_ops import load_graph
8
+ from .rule_pack import analyze_graph_with_rule_packs, load_rule_pack
9
+
10
+
11
+ def build_parser() -> argparse.ArgumentParser:
12
+ parser = argparse.ArgumentParser(
13
+ prog="execweave-rule-pack",
14
+ description="Run bounded observation rule packs over an ExecWeave execution graph.",
15
+ )
16
+ parser.add_argument("graph", type=Path, help="Path to a graph JSON file")
17
+ parser.add_argument(
18
+ "--rule-pack",
19
+ dest="rule_packs",
20
+ action="append",
21
+ type=Path,
22
+ required=True,
23
+ help="JSON rule-pack path. Repeat to load multiple packs.",
24
+ )
25
+ parser.add_argument(
26
+ "--output",
27
+ type=Path,
28
+ default=None,
29
+ help="Optional JSON report output path; the report is always printed to stdout",
30
+ )
31
+ return parser
32
+
33
+
34
+ def main(argv: list[str] | None = None) -> int:
35
+ parser = build_parser()
36
+ args = parser.parse_args(argv)
37
+ try:
38
+ graph = load_graph(args.graph)
39
+ packs = [load_rule_pack(path) for path in args.rule_packs]
40
+ report = analyze_graph_with_rule_packs(graph, packs)
41
+ if args.output is not None:
42
+ output = args.output.expanduser().resolve()
43
+ output.parent.mkdir(parents=True, exist_ok=True)
44
+ if output.exists() and output.stat().st_size > 0:
45
+ raise FileExistsError(f"ExecWeave rule-pack output already exists: {output}")
46
+ output.write_text(
47
+ json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
48
+ encoding="utf-8",
49
+ )
50
+ except (FileExistsError, ValueError) as exc:
51
+ parser.error(str(exc))
52
+ print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
53
+ return 0
54
+
55
+
56
+ if __name__ == "__main__":
57
+ raise SystemExit(main())