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
@@ -0,0 +1,439 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ CURSOR_HOOKS_REFERENCE = "https://cursor.com/docs/hooks"
10
+
11
+ OFFICIAL_CURSOR_HOOK_EVENTS = frozenset(
12
+ {
13
+ "sessionStart",
14
+ "sessionEnd",
15
+ "preToolUse",
16
+ "postToolUse",
17
+ "postToolUseFailure",
18
+ "subagentStart",
19
+ "subagentStop",
20
+ "beforeShellExecution",
21
+ "afterShellExecution",
22
+ "beforeMCPExecution",
23
+ "afterMCPExecution",
24
+ "beforeReadFile",
25
+ "afterFileEdit",
26
+ "beforeSubmitPrompt",
27
+ "preCompact",
28
+ "stop",
29
+ "afterAgentResponse",
30
+ "afterAgentThought",
31
+ "beforeTabFileRead",
32
+ "afterTabFileEdit",
33
+ "workspaceOpen",
34
+ }
35
+ )
36
+
37
+ _ALREADY_PROJECTED_ELSEWHERE = frozenset(
38
+ {
39
+ "preToolUse",
40
+ "postToolUse",
41
+ "postToolUseFailure",
42
+ "subagentStart",
43
+ "subagentStop",
44
+ "beforeShellExecution",
45
+ "afterShellExecution",
46
+ "beforeMCPExecution",
47
+ "afterMCPExecution",
48
+ "beforeReadFile",
49
+ "afterFileEdit",
50
+ "beforeSubmitPrompt",
51
+ "afterAgentResponse",
52
+ "afterAgentThought",
53
+ "beforeTabFileRead",
54
+ "afterTabFileEdit",
55
+ }
56
+ )
57
+
58
+
59
+ def _now() -> str:
60
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
61
+
62
+
63
+ def _entity(
64
+ entity_type: str,
65
+ entity_id: str,
66
+ *,
67
+ name: str | None = None,
68
+ attributes: dict[str, Any] | None = None,
69
+ ) -> dict[str, Any]:
70
+ return {
71
+ "type": entity_type,
72
+ "id": entity_id,
73
+ "name": name,
74
+ "attributes": attributes or {},
75
+ }
76
+
77
+
78
+ def _root_agent() -> dict[str, Any]:
79
+ return _entity(
80
+ "agent",
81
+ "agent:Cursor",
82
+ name="Cursor",
83
+ attributes={"provider": "cursor"},
84
+ )
85
+
86
+
87
+ def _application() -> dict[str, Any]:
88
+ return _entity(
89
+ "provider_application",
90
+ "provider-application:cursor",
91
+ name="Cursor",
92
+ attributes={"provider": "cursor"},
93
+ )
94
+
95
+
96
+ def _event(
97
+ *,
98
+ timestamp: str,
99
+ event_type: str,
100
+ relation: str,
101
+ source: dict[str, Any],
102
+ target: dict[str, Any],
103
+ attributes: dict[str, Any] | None = None,
104
+ ) -> dict[str, Any]:
105
+ merged: dict[str, Any] = {
106
+ "backend": "semantic",
107
+ "provider": "cursor",
108
+ "evidence_source": "provider_hook",
109
+ "attribution": "cursor_official_hook_contract",
110
+ "causal": False,
111
+ "inferred": False,
112
+ "official_hook_contract": True,
113
+ "official_hook_reference": CURSOR_HOOKS_REFERENCE,
114
+ }
115
+ if attributes:
116
+ merged.update(attributes)
117
+ return {
118
+ "timestamp": timestamp,
119
+ "event_type": event_type,
120
+ "relation": relation,
121
+ "source": source,
122
+ "target": target,
123
+ "attributes": merged,
124
+ }
125
+
126
+
127
+ def _common(payload: dict[str, Any]) -> dict[str, Any]:
128
+ result: dict[str, Any] = {
129
+ "cursor_hook_event_name": payload.get("hook_event_name"),
130
+ }
131
+ for key in (
132
+ "conversation_id",
133
+ "generation_id",
134
+ "session_id",
135
+ "cursor_version",
136
+ "model",
137
+ "model_id",
138
+ ):
139
+ value = payload.get(key)
140
+ if isinstance(value, (str, int, float, bool)) and value != "":
141
+ result[f"cursor_{key}"] = value
142
+ roots = payload.get("workspace_roots")
143
+ if isinstance(roots, list):
144
+ result["cursor_workspace_root_count"] = len(roots)
145
+ return result
146
+
147
+
148
+ def _session(payload: dict[str, Any]) -> dict[str, Any]:
149
+ session_id = payload.get("session_id")
150
+ if not isinstance(session_id, str) or not session_id:
151
+ raise ValueError(f"{payload.get('hook_event_name')} requires session_id")
152
+ return _entity(
153
+ "provider_session",
154
+ f"provider-session:cursor:{session_id}",
155
+ name=session_id,
156
+ attributes={
157
+ "provider": "cursor",
158
+ "session_id": session_id,
159
+ "identity_semantics": "provider_session_id",
160
+ },
161
+ )
162
+
163
+
164
+ def _observation_id(payload: dict[str, Any], *, timestamp: str, phase: str) -> str:
165
+ stable = {
166
+ "conversation_id": payload.get("conversation_id"),
167
+ "generation_id": payload.get("generation_id"),
168
+ "session_id": payload.get("session_id"),
169
+ "hook_event_name": payload.get("hook_event_name"),
170
+ "phase": phase,
171
+ "timestamp": timestamp,
172
+ }
173
+ raw = json.dumps(stable, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
174
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:24]
175
+
176
+
177
+ def _observation(
178
+ payload: dict[str, Any],
179
+ *,
180
+ timestamp: str,
181
+ phase: str,
182
+ entity_type: str,
183
+ name: str,
184
+ attributes: dict[str, Any] | None = None,
185
+ ) -> dict[str, Any]:
186
+ ident = _observation_id(payload, timestamp=timestamp, phase=phase)
187
+ merged = {
188
+ "provider": "cursor",
189
+ "observation_phase": phase,
190
+ "identity_semantics": "provider_hook_observation_without_stable_stage_id",
191
+ }
192
+ if attributes:
193
+ merged.update(attributes)
194
+ return _entity(
195
+ entity_type,
196
+ f"{entity_type}:cursor:{ident}",
197
+ name=name,
198
+ attributes=merged,
199
+ )
200
+
201
+
202
+ def _workspace_roots(payload: dict[str, Any]) -> list[str]:
203
+ roots = payload.get("workspace_roots")
204
+ if not isinstance(roots, list):
205
+ raise ValueError("workspaceOpen requires workspace_roots")
206
+ normalized = [root for root in roots if isinstance(root, str) and root]
207
+ if not normalized:
208
+ raise ValueError("workspaceOpen requires at least one workspace root")
209
+ if len(normalized) != len(roots):
210
+ raise ValueError("workspaceOpen workspace_roots must contain only non-empty strings")
211
+ return normalized
212
+
213
+
214
+ def cursor_workspace_scope(payload: dict[str, Any]) -> tuple[str, Path]:
215
+ """Return a stable, non-session workspace scope from provider-exposed roots."""
216
+
217
+ roots = _workspace_roots(payload)
218
+ canonical = json.dumps(
219
+ sorted(roots),
220
+ ensure_ascii=False,
221
+ separators=(",", ":"),
222
+ )
223
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:24]
224
+ return digest, Path(roots[0]).expanduser()
225
+
226
+
227
+ def _workspace(payload: dict[str, Any]) -> dict[str, Any]:
228
+ digest, _root = cursor_workspace_scope(payload)
229
+ roots = _workspace_roots(payload)
230
+ return _entity(
231
+ "workspace",
232
+ f"workspace:cursor:{digest}",
233
+ name="Cursor workspace",
234
+ attributes={
235
+ "provider": "cursor",
236
+ "workspace_root_count": len(roots),
237
+ "identity_semantics": "sha256_of_sorted_provider_workspace_roots",
238
+ "outside_agent_session": True,
239
+ },
240
+ )
241
+
242
+
243
+ def cursor_official_hook_semantic_events(
244
+ payload: dict[str, Any],
245
+ *,
246
+ timestamp: str | None = None,
247
+ ) -> list[dict[str, Any]]:
248
+ """Project lifecycle semantics explicitly guaranteed by Cursor's hook contract."""
249
+
250
+ hook = payload.get("hook_event_name")
251
+ if not isinstance(hook, str) or not hook:
252
+ raise ValueError("Cursor hook payload requires hook_event_name")
253
+ if hook not in OFFICIAL_CURSOR_HOOK_EVENTS or hook in _ALREADY_PROJECTED_ELSEWHERE:
254
+ return []
255
+
256
+ observed_at = timestamp or _now()
257
+ common = _common(payload)
258
+
259
+ if hook == "sessionStart":
260
+ background = payload.get("is_background_agent")
261
+ if not isinstance(background, bool):
262
+ raise ValueError("sessionStart requires is_background_agent")
263
+ common.update(
264
+ {
265
+ "is_background_agent": background,
266
+ "fire_and_forget_hook": True,
267
+ "session_creation_blocked_by_hook_asserted": False,
268
+ }
269
+ )
270
+ mode = payload.get("composer_mode")
271
+ if isinstance(mode, str) and mode:
272
+ common["composer_mode"] = mode
273
+ return [
274
+ _event(
275
+ timestamp=observed_at,
276
+ event_type="semantic.cursor.session.started",
277
+ relation="STARTED_PROVIDER_SESSION",
278
+ source=_root_agent(),
279
+ target=_session(payload),
280
+ attributes=common,
281
+ )
282
+ ]
283
+
284
+ if hook == "sessionEnd":
285
+ reason = payload.get("reason")
286
+ if reason not in {"completed", "aborted", "error", "window_close", "user_close"}:
287
+ raise ValueError("sessionEnd requires a documented reason")
288
+ common["cursor_session_end_reason"] = reason
289
+ for key in ("duration_ms", "is_background_agent", "final_status"):
290
+ value = payload.get(key)
291
+ if isinstance(value, (str, int, float, bool)) and value != "":
292
+ common[key] = value
293
+ common.update(
294
+ {
295
+ "fire_and_forget_hook": True,
296
+ "flow_control_ignored_by_provider": True,
297
+ "error_message_stored_separately": isinstance(
298
+ payload.get("error_message"), str
299
+ ),
300
+ }
301
+ )
302
+ return [
303
+ _event(
304
+ timestamp=observed_at,
305
+ event_type="semantic.cursor.session.ended",
306
+ relation="OBSERVED_PROVIDER_SESSION_END",
307
+ source=_root_agent(),
308
+ target=_session(payload),
309
+ attributes=common,
310
+ )
311
+ ]
312
+
313
+ if hook == "preCompact":
314
+ trigger = payload.get("trigger")
315
+ if trigger not in {"auto", "manual"}:
316
+ raise ValueError("preCompact requires trigger auto or manual")
317
+ for key in (
318
+ "context_usage_percent",
319
+ "context_tokens",
320
+ "context_window_size",
321
+ "message_count",
322
+ "messages_to_compact",
323
+ "is_first_compaction",
324
+ ):
325
+ value = payload.get(key)
326
+ if isinstance(value, (int, float, bool)) and not (
327
+ isinstance(value, bool) and key != "is_first_compaction"
328
+ ):
329
+ common[key] = value
330
+ common.update(
331
+ {
332
+ "compaction_trigger": trigger,
333
+ "observational_hook": True,
334
+ "compaction_block_or_modify_supported": False,
335
+ "compaction_completion_asserted": False,
336
+ }
337
+ )
338
+ target = _observation(
339
+ payload,
340
+ timestamp=observed_at,
341
+ phase="pre_compact",
342
+ entity_type="context_compaction",
343
+ name="Cursor pre-compaction observation",
344
+ attributes={"trigger": trigger},
345
+ )
346
+ return [
347
+ _event(
348
+ timestamp=observed_at,
349
+ event_type="semantic.cursor.compaction.pre",
350
+ relation="OBSERVED_PRE_COMPACTION",
351
+ source=_root_agent(),
352
+ target=target,
353
+ attributes=common,
354
+ )
355
+ ]
356
+
357
+ if hook == "stop":
358
+ status = payload.get("status")
359
+ if status not in {"completed", "aborted", "error"}:
360
+ raise ValueError("stop requires status completed, aborted, or error")
361
+ loop_count = payload.get("loop_count")
362
+ if not isinstance(loop_count, int) or isinstance(loop_count, bool) or loop_count < 0:
363
+ raise ValueError("stop requires non-negative integer loop_count")
364
+ common.update(
365
+ {
366
+ "status": status,
367
+ "loop_count": loop_count,
368
+ "followup_message_supported": True,
369
+ "agent_loop_can_resume_via_followup": True,
370
+ "provider_session_end_asserted": False,
371
+ }
372
+ )
373
+ target = _observation(
374
+ payload,
375
+ timestamp=observed_at,
376
+ phase="stop",
377
+ entity_type="agent_turn_stop",
378
+ name="Cursor agent loop stop",
379
+ attributes={
380
+ "completion_semantics": "agent_loop_ended_before_optional_hook_followup"
381
+ },
382
+ )
383
+ return [
384
+ _event(
385
+ timestamp=observed_at,
386
+ event_type="semantic.cursor.turn.stop_observed",
387
+ relation="OBSERVED_TURN_STOP",
388
+ source=_root_agent(),
389
+ target=target,
390
+ attributes=common,
391
+ )
392
+ ]
393
+
394
+ if hook == "workspaceOpen":
395
+ roots = _workspace_roots(payload)
396
+ workspace = _workspace(payload)
397
+ common.update(
398
+ {
399
+ "outside_agent_session": True,
400
+ "conversation_identity_available": False,
401
+ "session_identity_available": False,
402
+ "fires_on_workspace_open_and_folder_change": True,
403
+ }
404
+ )
405
+ events = [
406
+ _event(
407
+ timestamp=observed_at,
408
+ event_type="semantic.cursor.workspace.open_observed",
409
+ relation="OBSERVED_WORKSPACE_OPEN",
410
+ source=_application(),
411
+ target=workspace,
412
+ attributes=common,
413
+ )
414
+ ]
415
+ for root in roots:
416
+ events.append(
417
+ _event(
418
+ timestamp=observed_at,
419
+ event_type="semantic.cursor.workspace.root_observed",
420
+ relation="WORKSPACE_HAS_ROOT",
421
+ source=workspace,
422
+ target=_entity(
423
+ "directory",
424
+ f"directory:cursor:{root}",
425
+ name=root,
426
+ attributes={
427
+ "provider": "cursor",
428
+ "absolute_path_from_provider": True,
429
+ },
430
+ ),
431
+ attributes={
432
+ **common,
433
+ "workspace_root_exact_from_provider": True,
434
+ },
435
+ )
436
+ )
437
+ return events
438
+
439
+ return []
@@ -0,0 +1,159 @@
1
+ """Attribution-safe Cursor GUI launcher hand-off helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any, Iterable
10
+
11
+ import psutil
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class CursorHandoff:
16
+ status: str
17
+ snapshot: Any | None = None
18
+ process: psutil.Process | None = None
19
+
20
+
21
+ def is_cursor_invocation(command: Iterable[str]) -> bool:
22
+ values = list(command)
23
+ if not values:
24
+ return False
25
+ name = Path(values[0]).name.lower()
26
+ for suffix in (".exe", ".cmd", ".bat", ".ps1"):
27
+ if name.endswith(suffix):
28
+ name = name[: -len(suffix)]
29
+ break
30
+ return name == "cursor"
31
+
32
+
33
+ def normalized_executable(value: str | None) -> str | None:
34
+ if not value:
35
+ return None
36
+ try:
37
+ return os.path.normcase(str(Path(value).expanduser().resolve(strict=False)))
38
+ except (OSError, RuntimeError, ValueError):
39
+ return os.path.normcase(str(value))
40
+
41
+
42
+ def process_identity(snapshot: Any) -> tuple[int, float]:
43
+ return snapshot.pid, snapshot.create_time
44
+
45
+
46
+ def process_baseline(executable: str | None) -> set[tuple[int, float]]:
47
+ """Return exact PID/create-time identities already using this executable."""
48
+ target = normalized_executable(executable)
49
+ if target is None:
50
+ return set()
51
+ identities: set[tuple[int, float]] = set()
52
+ try:
53
+ processes = psutil.process_iter(["pid", "create_time", "exe"])
54
+ except (OSError, RuntimeError):
55
+ return identities
56
+ for process in processes:
57
+ try:
58
+ info = process.info
59
+ if normalized_executable(info.get("exe")) == target:
60
+ create_time = info.get("create_time")
61
+ if isinstance(create_time, (int, float)):
62
+ identities.add((int(info["pid"]), float(create_time)))
63
+ except (KeyError, OSError, psutil.Error):
64
+ continue
65
+ return identities
66
+
67
+
68
+ def _descends_from(snapshot: Any, root_pid: int, snapshots: dict[int, Any]) -> bool:
69
+ current = snapshot
70
+ visited: set[int] = set()
71
+ while current.ppid > 0 and current.ppid not in visited:
72
+ if current.ppid == root_pid:
73
+ return True
74
+ visited.add(current.ppid)
75
+ parent = snapshots.get(current.ppid)
76
+ if parent is None:
77
+ return False
78
+ current = parent
79
+ return False
80
+
81
+
82
+ def select_handoff_candidate(
83
+ snapshots: Iterable[Any],
84
+ *,
85
+ root: Any,
86
+ executable: str | None,
87
+ baseline: set[tuple[int, float]],
88
+ ) -> CursorHandoff:
89
+ """Select exactly one newly-created descendant of the launcher.
90
+
91
+ The function intentionally abstains when process ancestry or identity is
92
+ ambiguous. It never searches by the string ``Cursor.exe`` alone.
93
+ """
94
+ target = normalized_executable(executable)
95
+ if target is None:
96
+ return CursorHandoff("unattributed_no_executable")
97
+ snapshot_map = {snapshot.pid: snapshot for snapshot in snapshots}
98
+ candidates = []
99
+ for snapshot in snapshot_map.values():
100
+ identity = process_identity(snapshot)
101
+ if identity == process_identity(root) or identity in baseline:
102
+ continue
103
+ if normalized_executable(snapshot.exe) != target:
104
+ continue
105
+ if snapshot.create_time < root.create_time:
106
+ continue
107
+ if not _descends_from(snapshot, root.pid, snapshot_map):
108
+ continue
109
+ try:
110
+ process = psutil.Process(snapshot.pid)
111
+ if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
112
+ candidates.append((snapshot, process))
113
+ except psutil.Error:
114
+ continue
115
+ if not candidates:
116
+ return CursorHandoff("no_attributed_candidate")
117
+ if len(candidates) != 1:
118
+ return CursorHandoff("ambiguous_candidates")
119
+ snapshot, process = candidates[0]
120
+ return CursorHandoff("handoff", snapshot=snapshot, process=process)
121
+
122
+
123
+ def run_cursor_handoff(
124
+ collector: Any,
125
+ *,
126
+ root_snapshot: Any,
127
+ executable: str,
128
+ baseline: set[tuple[int, float]],
129
+ ) -> None:
130
+ """Keep Live attached to one identity-safe GUI successor until it exits."""
131
+ snapshots = [
132
+ *collector._seen_processes.values(),
133
+ *collector._discovered_processes.values(),
134
+ root_snapshot,
135
+ ]
136
+ handoff = select_handoff_candidate(
137
+ snapshots,
138
+ root=root_snapshot,
139
+ executable=executable,
140
+ baseline=baseline,
141
+ )
142
+ collector._cursor_handoff_info["cursor_handoff_status"] = handoff.status
143
+ if handoff.status != "handoff" or handoff.process is None or handoff.snapshot is None:
144
+ return
145
+
146
+ collector._preserved_processes.add((handoff.snapshot.pid, handoff.snapshot.create_time))
147
+ collector._cursor_handoff_info.update(
148
+ {
149
+ "cursor_handoff_pid": handoff.snapshot.pid,
150
+ "cursor_handoff_create_time": handoff.snapshot.create_time,
151
+ "cursor_handoff_status": "active",
152
+ }
153
+ )
154
+ while collector._process_is_live(handoff.process):
155
+ collector._sample_process_tree(handoff.process)
156
+ time.sleep(collector.poll_interval)
157
+ collector._sample_process_tree(handoff.process)
158
+ collector._mark_disappeared_processes(set())
159
+ collector._cursor_handoff_info["cursor_handoff_status"] = "completed"
@@ -0,0 +1,96 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from .backends import BackendName
8
+ from .provider_record import ProviderRecordResult, record_provider_to_viewer
9
+
10
+ CursorRecordResult = ProviderRecordResult
11
+
12
+
13
+ def record_cursor_to_viewer(
14
+ command: list[str],
15
+ *,
16
+ watch_root: str | Path,
17
+ output_dir: str | Path | None = None,
18
+ backend: BackendName = "auto",
19
+ poll_interval: float = 0.10,
20
+ collect_filesystem: bool = True,
21
+ collect_network: bool = True,
22
+ keep_raw_trace: bool = False,
23
+ correlation_window_ms: int = 3000,
24
+ open_browser: bool = False,
25
+ ) -> CursorRecordResult:
26
+ return record_provider_to_viewer(
27
+ command,
28
+ provider_name="Cursor",
29
+ watch_root=watch_root,
30
+ output_dir=output_dir,
31
+ backend=backend,
32
+ poll_interval=poll_interval,
33
+ collect_filesystem=collect_filesystem,
34
+ collect_network=collect_network,
35
+ keep_raw_trace=keep_raw_trace,
36
+ correlation_window_ms=correlation_window_ms,
37
+ open_browser=open_browser,
38
+ )
39
+
40
+
41
+ def _clean_command(command: list[str]) -> list[str]:
42
+ result = list(command)
43
+ if result and result[0] == "--":
44
+ result = result[1:]
45
+ return result
46
+
47
+
48
+ def build_parser() -> argparse.ArgumentParser:
49
+ parser = argparse.ArgumentParser(
50
+ prog="execweave-cursor-record",
51
+ description=(
52
+ "Record runtime evidence, Cursor hook telemetry, and conservative "
53
+ "Tool-to-Process correlation in one local run."
54
+ ),
55
+ )
56
+ parser.add_argument("--watch-root", type=Path, default=None)
57
+ parser.add_argument("--output-dir", type=Path, default=None)
58
+ parser.add_argument("--interval", type=float, default=0.10)
59
+ parser.add_argument("--backend", choices=["auto", "portable", "strace"], default="auto")
60
+ parser.add_argument("--correlation-window-ms", type=int, default=3000)
61
+ parser.add_argument("--no-files", action="store_true")
62
+ parser.add_argument("--no-network", action="store_true")
63
+ parser.add_argument("--keep-native-trace", action="store_true")
64
+ parser.add_argument("--open", action="store_true", dest="open_browser")
65
+ parser.add_argument("command", nargs=argparse.REMAINDER)
66
+ return parser
67
+
68
+
69
+ def main(argv: list[str] | None = None) -> int:
70
+ parser = build_parser()
71
+ args = parser.parse_args(argv)
72
+ command = _clean_command(args.command)
73
+ if not command:
74
+ parser.error("a Cursor command is required, e.g. execweave-cursor-record --open -- cursor")
75
+ watch_root = (args.watch_root or Path.cwd()).expanduser().resolve()
76
+ try:
77
+ result = record_cursor_to_viewer(
78
+ command,
79
+ watch_root=watch_root,
80
+ output_dir=args.output_dir,
81
+ backend=args.backend,
82
+ poll_interval=args.interval,
83
+ collect_filesystem=not args.no_files,
84
+ collect_network=not args.no_network,
85
+ keep_raw_trace=args.keep_native_trace,
86
+ correlation_window_ms=args.correlation_window_ms,
87
+ open_browser=args.open_browser,
88
+ )
89
+ except (FileExistsError, RuntimeError, ValueError, OSError) as exc:
90
+ parser.error(str(exc))
91
+ print(json.dumps(result.to_dict(), indent=2, sort_keys=True))
92
+ return result.runtime.return_code
93
+
94
+
95
+ if __name__ == "__main__":
96
+ raise SystemExit(main())