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/command.py ADDED
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shutil
5
+ import sys
6
+ from pathlib import Path
7
+
8
+
9
+ def _looks_like_path(value: str) -> bool:
10
+ return (
11
+ Path(value).is_absolute()
12
+ or value.startswith((".", "~"))
13
+ or "/" in value
14
+ or "\\" in value
15
+ )
16
+
17
+
18
+ def _cursor_desktop_candidates() -> list[Path]:
19
+ home = Path.home()
20
+ if sys.platform == "darwin":
21
+ return [
22
+ home / "Applications" / "Cursor.app" / "Contents" / "MacOS" / "Cursor",
23
+ Path("/Applications/Cursor.app/Contents/MacOS/Cursor"),
24
+ ]
25
+ if os.name == "nt":
26
+ candidates: list[Path] = []
27
+ local_app_data = os.environ.get("LOCALAPPDATA")
28
+ program_files = os.environ.get("ProgramFiles")
29
+ program_files_x86 = os.environ.get("ProgramFiles(x86)")
30
+ if local_app_data:
31
+ candidates.append(Path(local_app_data) / "Programs" / "cursor" / "Cursor.exe")
32
+ if program_files:
33
+ candidates.append(Path(program_files) / "cursor" / "Cursor.exe")
34
+ if program_files_x86:
35
+ candidates.append(Path(program_files_x86) / "cursor" / "Cursor.exe")
36
+ return candidates
37
+ return []
38
+
39
+
40
+ def _prefer_cursor_desktop_launcher() -> bool:
41
+ return os.name == "nt"
42
+
43
+
44
+ def _cursor_desktop_from_launcher(launcher: str | None) -> str | None:
45
+ """Resolve Cursor.exe beside a VS Code-style PATH shim."""
46
+ if not launcher:
47
+ return None
48
+ path = Path(launcher).expanduser()
49
+ bin_dir = path.parent
50
+ app_dir = bin_dir.parent
51
+ resources_dir = app_dir.parent
52
+ install_root = resources_dir.parent
53
+ if (
54
+ bin_dir.name.lower() != "bin"
55
+ or app_dir.name.lower() != "app"
56
+ or resources_dir.name.lower() != "resources"
57
+ ):
58
+ return None
59
+ candidate = install_root / "Cursor.exe"
60
+ if candidate.is_file():
61
+ return str(candidate.resolve())
62
+ return None
63
+
64
+
65
+ def _resolve_cursor_desktop(*, path_launcher: str | None = None) -> str | None:
66
+ derived = _cursor_desktop_from_launcher(path_launcher)
67
+ if derived is not None:
68
+ return derived
69
+ for candidate in _cursor_desktop_candidates():
70
+ if candidate.is_file():
71
+ return str(candidate.resolve())
72
+ return None
73
+
74
+
75
+ def _resolve_executable(executable: str, *, path: str | None = None) -> str:
76
+ if not executable.strip():
77
+ raise ValueError("command executable must not be empty")
78
+
79
+ if _looks_like_path(executable):
80
+ candidate = Path(executable).expanduser()
81
+ if not candidate.is_file():
82
+ raise FileNotFoundError(f"command executable not found: {executable!r}")
83
+ # Keep the user-selected launcher path itself. In particular, a virtualenv
84
+ # Python executable is commonly a symlink to the base interpreter on POSIX;
85
+ # dereferencing it changes Python's prefix discovery and silently drops the
86
+ # virtualenv site-packages. ``abspath`` normalizes the argv path without
87
+ # resolving symlinks.
88
+ resolved = os.path.abspath(os.fspath(candidate))
89
+ else:
90
+ path_launcher = shutil.which(executable, path=path)
91
+ if executable.lower() == "cursor" and _prefer_cursor_desktop_launcher():
92
+ resolved = _resolve_cursor_desktop(path_launcher=path_launcher) or path_launcher
93
+ else:
94
+ resolved = path_launcher
95
+ if resolved is None and executable.lower() == "cursor":
96
+ resolved = _resolve_cursor_desktop()
97
+ if resolved is None and executable.lower() == "antigravity":
98
+ resolved = shutil.which("agy", path=path)
99
+ if resolved is None:
100
+ detail = ""
101
+ if executable.lower() == "cursor":
102
+ detail = (
103
+ "; ExecWeave also checked the Cursor desktop binary beside the PATH "
104
+ "launcher and the standard desktop-app install paths"
105
+ )
106
+ elif executable.lower() == "antigravity":
107
+ detail = "; the current Antigravity CLI executable is 'agy'"
108
+ raise FileNotFoundError(
109
+ f"command executable {executable!r} was not found on PATH{detail}; "
110
+ "install it or make its launcher available on PATH"
111
+ )
112
+
113
+ if os.name != "nt" and not os.access(resolved, os.X_OK):
114
+ raise PermissionError(f"command executable is not executable: {resolved!r}")
115
+ return resolved
116
+
117
+
118
+ def resolve_launch_command(command: list[str], *, path: str | None = None) -> list[str]:
119
+ """Resolve a user-facing command into an argv safe for ``subprocess``.
120
+
121
+ ExecWeave launches commands without ``shell=True``. Normal executables use PATH
122
+ lookup. On Windows, PATHEXT keeps npm-style ``.cmd``/``.bat`` launchers working.
123
+
124
+ Bare ``cursor`` on Windows prefers the desktop application binary. ExecWeave
125
+ first derives ``Cursor.exe`` from a VS Code-style PATH shim such as
126
+ ``<install>/resources/app/bin/cursor.cmd`` and then checks standard desktop
127
+ install paths. This keeps the GUI process and provider hooks in the ExecWeave
128
+ launch environment instead of treating a short-lived CLI shim as the observed
129
+ application lifetime. Explicit launcher paths are never rewritten.
130
+
131
+ ``antigravity`` is accepted as a friendly alias for Google's current
132
+ Antigravity CLI executable, ``agy``.
133
+
134
+ An explicitly supplied PowerShell ``.ps1`` file is launched through pwsh or
135
+ Windows PowerShell because CreateProcess cannot execute a PowerShell script by
136
+ itself. The caller's original command remains the evidence-facing value; this
137
+ function only returns the argv used to start the child process.
138
+ """
139
+ if not command:
140
+ raise ValueError("command must not be empty")
141
+
142
+ resolved = _resolve_executable(command[0], path=path)
143
+ arguments = list(command[1:])
144
+
145
+ if os.name == "nt" and Path(resolved).suffix.lower() == ".ps1":
146
+ search_path = path if path is not None else os.environ.get("PATH")
147
+ powershell = shutil.which("pwsh.exe", path=search_path) or shutil.which(
148
+ "powershell.exe", path=search_path
149
+ )
150
+ if powershell is None:
151
+ raise FileNotFoundError(
152
+ "PowerShell script requested, but neither pwsh.exe nor powershell.exe "
153
+ "was found on PATH"
154
+ )
155
+ return [powershell, "-NoLogo", "-NoProfile", "-File", resolved, *arguments]
156
+
157
+ return [resolved, *arguments]
@@ -0,0 +1,20 @@
1
+ """Deliberately metadata-only argv serialization for recorded OS processes.
2
+
3
+ An arbitrary Python argument may itself be a secret or full prompt; a denylist
4
+ of flag spellings cannot protect it. Keep only executable and script basename
5
+ when the script is an unambiguous .py path. Actual child argv is unchanged.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Iterable
11
+
12
+
13
+ def public_command(command: Iterable[str]) -> list[str]:
14
+ argv = list(command)
15
+ if not argv:
16
+ return []
17
+ display = [Path(argv[0]).name]
18
+ if len(argv) > 1 and argv[1].endswith(".py") and not argv[1].startswith("-"):
19
+ display.append(Path(argv[1]).name)
20
+ return display
@@ -0,0 +1,101 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from .content_store import ContentReference
6
+
7
+ _TRANSPORT_CREDENTIAL_KEYS = frozenset(
8
+ {
9
+ "authorization",
10
+ "proxy-authorization",
11
+ "cookie",
12
+ "set-cookie",
13
+ "x-api-key",
14
+ "api-key",
15
+ "api_key",
16
+ "apikey",
17
+ "access_token",
18
+ "refresh_token",
19
+ "client_secret",
20
+ "password",
21
+ }
22
+ )
23
+
24
+
25
+ def filter_transport_credentials(metadata: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
26
+ """Remove transport credentials from provider metadata only.
27
+
28
+ Do not apply this to prompts, completions, tool input/output, or file content.
29
+ Those are full-fidelity evidence and remain unredacted.
30
+ """
31
+
32
+ removed: list[str] = []
33
+
34
+ def walk(value: Any, path: str) -> Any:
35
+ if isinstance(value, dict):
36
+ result: dict[str, Any] = {}
37
+ for key, child in value.items():
38
+ key_text = str(key)
39
+ child_path = f"{path}.{key_text}" if path else key_text
40
+ if key_text.lower() in _TRANSPORT_CREDENTIAL_KEYS:
41
+ removed.append(child_path)
42
+ continue
43
+ result[key_text] = walk(child, child_path)
44
+ return result
45
+ if isinstance(value, list):
46
+ return [walk(item, f"{path}[{index}]") for index, item in enumerate(value)]
47
+ return value
48
+
49
+ return walk(metadata, ""), sorted(removed)
50
+
51
+
52
+ def content_entity(reference: ContentReference) -> dict[str, Any]:
53
+ kind = reference.content_kind.replace(" ", "_")
54
+ return {
55
+ "type": "observed_content",
56
+ "id": f"observed-content:{kind}:sha256:{reference.sha256}",
57
+ "name": reference.content_kind,
58
+ "attributes": reference.to_dict(),
59
+ }
60
+
61
+
62
+ def content_observation_event(
63
+ *,
64
+ timestamp: str,
65
+ provider: str,
66
+ source: dict[str, Any],
67
+ reference: ContentReference,
68
+ relation: str,
69
+ observed_field: str,
70
+ evidence_source: str,
71
+ attribution: str,
72
+ event_type: str | None = None,
73
+ attributes: dict[str, Any] | None = None,
74
+ ) -> dict[str, Any]:
75
+ """Create a graph-ready content edge without inflating evidence strength."""
76
+
77
+ merged: dict[str, Any] = {
78
+ "backend": "semantic",
79
+ "provider": provider,
80
+ "evidence_source": evidence_source,
81
+ "attribution": attribution,
82
+ "observed_field": observed_field,
83
+ "content_sha256": reference.sha256,
84
+ "content_path": reference.path,
85
+ "content_size_bytes": reference.size_bytes,
86
+ "content_media_type": reference.media_type,
87
+ "content_representation": reference.representation,
88
+ "content_complete_from_source": reference.complete_from_source,
89
+ "causal": False,
90
+ "inferred": False,
91
+ }
92
+ if attributes:
93
+ merged.update(attributes)
94
+ return {
95
+ "timestamp": timestamp,
96
+ "event_type": event_type or f"semantic.{provider}.content.observed",
97
+ "relation": relation,
98
+ "source": source,
99
+ "target": content_entity(reference),
100
+ "attributes": merged,
101
+ }
@@ -0,0 +1,289 @@
1
+ """Verify declared archive references without inspecting provider payload bodies.
2
+
3
+ The scope is the exported graph's observed_content nodes and conversation-index
4
+ entries, not provider recall or an adversary-resistant log. Payload JSON is a leaf:
5
+ strings/dictionaries supplied by agents never become additional filesystem paths.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import re
13
+ import stat
14
+ from contextlib import contextmanager
15
+ from pathlib import Path
16
+ from typing import Any, Iterator
17
+
18
+ CONTENT_PATH = re.compile(r"content/sha256/([0-9a-f]{64})\.(?:json|txt|bin)")
19
+ INDEXES = {"graph.json": "nodes", "conversations.json": "entries"}
20
+ EXPORTS = (*INDEXES, "viewer.html")
21
+ CHUNK = 1024 * 1024
22
+
23
+
24
+ class ArchiveReadError(Exception):
25
+ """A bounded, content-free archive diagnostic."""
26
+
27
+
28
+ def _signature(value: os.stat_result) -> tuple[int, ...]:
29
+ return (value.st_dev, value.st_ino, value.st_size, value.st_mtime_ns, value.st_ctime_ns)
30
+
31
+
32
+ def _reject_link(path: Path) -> None:
33
+ info = path.lstat()
34
+ if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
35
+ raise ArchiveReadError("unsafe_path") # Includes Windows reparse points.
36
+
37
+
38
+ def _path_descriptor_stat(path: Path) -> os.stat_result:
39
+ """Compare two open-file snapshots, not Windows stat/fstat timestamps.
40
+
41
+ Path-based stat and descriptor-based fstat need not expose the same ctime
42
+ semantics on supported Windows/Python versions. Reopening the recorded path
43
+ preserves the identity/size/time comparison without rounding timestamps or
44
+ ignoring changes. This handle is metadata-only and never reads payload bytes.
45
+ """
46
+ _reject_link(path)
47
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
48
+ flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
49
+ descriptor = os.open(path, flags)
50
+ try:
51
+ value = os.fstat(descriptor)
52
+ if not stat.S_ISREG(value.st_mode):
53
+ raise ArchiveReadError("not_regular_file")
54
+ return value
55
+ finally:
56
+ os.close(descriptor)
57
+
58
+
59
+ @contextmanager
60
+ def _open_regular(root: Path, relative: str) -> Iterator[Any]:
61
+ if relative not in EXPORTS and CONTENT_PATH.fullmatch(relative) is None:
62
+ raise ArchiveReadError("invalid_reference")
63
+ opened: list[int] = []
64
+ try:
65
+ parts = relative.split("/")
66
+ # Pin every directory on POSIX. O_NOFOLLOW prevents symlink traversal even
67
+ # when a directory entry is replaced between validation and opening.
68
+ if os.open in os.supports_dir_fd and hasattr(os, "O_NOFOLLOW"):
69
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
70
+ parent = os.open(root, flags)
71
+ opened.append(parent)
72
+ for part in parts[:-1]:
73
+ parent = os.open(part, flags, dir_fd=parent)
74
+ opened.append(parent)
75
+ fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
76
+ else:
77
+ path = root
78
+ _reject_link(path)
79
+ for part in parts:
80
+ path = path / part
81
+ _reject_link(path)
82
+ # Windows has no Python dir_fd/O_NOFOLLOW equivalent. Reject reparse
83
+ # points before and after reading; do not claim tamper-proof storage.
84
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0))
85
+ with os.fdopen(fd, "rb") as handle:
86
+ before = os.fstat(handle.fileno())
87
+ if not stat.S_ISREG(before.st_mode):
88
+ raise ArchiveReadError("not_regular_file")
89
+ yield handle
90
+ after = os.fstat(handle.fileno())
91
+ path = root
92
+ _reject_link(path)
93
+ for part in parts:
94
+ path = path / part
95
+ _reject_link(path)
96
+ if _signature(before) != _signature(after) or _signature(after) != _signature(_path_descriptor_stat(path)):
97
+ raise ArchiveReadError("changed_during_read")
98
+ except FileNotFoundError as exc:
99
+ raise ArchiveReadError("missing_file") from exc
100
+ except OSError as exc:
101
+ # Do not write raw exception messages: paths may contain private data.
102
+ raise ArchiveReadError("unreadable_or_unsafe_path") from exc
103
+ finally:
104
+ for fd in reversed(opened):
105
+ os.close(fd)
106
+
107
+
108
+ def _read(root: Path, relative: str, limit: int, *, collect: bool = False) -> tuple[dict[str, Any], bytes]:
109
+ chunks: list[bytes] = []
110
+ digest = hashlib.sha256()
111
+ size = 0
112
+ with _open_regular(root, relative) as handle:
113
+ if os.fstat(handle.fileno()).st_size > limit:
114
+ raise ArchiveReadError("verification_limit")
115
+ while True:
116
+ chunk = handle.read(min(CHUNK, max(1, limit - size + 1)))
117
+ if not chunk:
118
+ break
119
+ size += len(chunk)
120
+ if size > limit:
121
+ raise ArchiveReadError("verification_limit")
122
+ digest.update(chunk)
123
+ if collect:
124
+ chunks.append(chunk)
125
+ return {"sha256": digest.hexdigest(), "size_bytes": size}, b"".join(chunks)
126
+
127
+
128
+ def hash_export(root: Path, name: str) -> dict[str, Any]:
129
+ """Hash only a named, regular primary export, with bounded reads."""
130
+ if name not in EXPORTS:
131
+ raise ArchiveReadError("invalid_export")
132
+ return _read(root, name, 1024 * 1024 * 1024)[0]
133
+
134
+
135
+ def _unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
136
+ result: dict[str, Any] = {}
137
+ for key, value in pairs:
138
+ if key in result:
139
+ raise ValueError("duplicate JSON key")
140
+ result[key] = value
141
+ return result
142
+
143
+
144
+ def _constant(value: str) -> None:
145
+ raise ValueError("non-finite JSON value")
146
+
147
+
148
+ def audit_content_references(
149
+ run_root: str | Path,
150
+ *,
151
+ max_index_bytes: int = 64 * 1024 * 1024,
152
+ max_content_bytes: int = 1024 * 1024 * 1024,
153
+ max_references: int = 100_000,
154
+ ) -> dict[str, Any]:
155
+ """Verify registered references; limits and unknown sources never pass silently.
156
+
157
+ Missing size metadata on legacy references is accepted but not invented. Source
158
+ completeness is orthogonal: an intact blob of partial provider content can pass
159
+ byte-integrity verification without implying complete provider observation.
160
+ """
161
+ for limit in (max_index_bytes, max_content_bytes, max_references):
162
+ if type(limit) is not int or limit < 0:
163
+ raise ValueError("limits must be nonnegative integers")
164
+ root = Path(run_root).expanduser().absolute()
165
+ report: dict[str, Any] = {
166
+ "schema_version": "0.1",
167
+ "scope": "declared_graph_and_conversation_content",
168
+ "state": "incomplete",
169
+ "reference_count": 0,
170
+ "reference_count_truncated": False,
171
+ "unique_file_count": 0,
172
+ "verified_file_count": 0,
173
+ "error_count": 0,
174
+ "errors": [],
175
+ "errors_truncated": False,
176
+ "index_files": {},
177
+ "verified_files": {},
178
+ "limits": {"index_bytes": max_index_bytes, "content_bytes": max_content_bytes,
179
+ "references": max_references},
180
+ }
181
+
182
+ def fail(code: str, location: str) -> None:
183
+ report["error_count"] += 1
184
+ if len(report["errors"]) < 100:
185
+ report["errors"].append({"code": code, "location": location})
186
+ else:
187
+ report["errors_truncated"] = True
188
+
189
+ # None is an unknown legacy size, not zero. A duplicate declaration must agree
190
+ # with every known size; a later valid reference cannot erase a conflict.
191
+ references: dict[str, tuple[str, int | None, str]] = {}
192
+ conflicted: set[str] = set()
193
+ limit_hit = False
194
+
195
+ def register(value: Any, location: str) -> None:
196
+ nonlocal limit_hit
197
+ if limit_hit:
198
+ return
199
+ report["reference_count"] += 1
200
+ if report["reference_count"] > max_references:
201
+ limit_hit = True
202
+ report["reference_count_truncated"] = True
203
+ fail("reference_limit", location)
204
+ return
205
+ if not isinstance(value, dict):
206
+ fail("invalid_reference", location)
207
+ return
208
+ path, digest, size = value.get("path"), value.get("sha256"), value.get("size_bytes")
209
+ match = CONTENT_PATH.fullmatch(path) if isinstance(path, str) else None
210
+ if (match is None or match[1] != digest or
211
+ ("size_bytes" in value and (type(size) is not int or size < 0))):
212
+ fail("invalid_reference", location)
213
+ return
214
+ previous = references.get(path)
215
+ if previous and previous[1] is not None and size is not None and previous[1] != size:
216
+ conflicted.add(path)
217
+ fail("conflicting_reference", location)
218
+ return
219
+ if previous is None or previous[1] is None:
220
+ references[path] = (digest, size, location)
221
+
222
+ sessions: set[str] = set()
223
+ for name, key in INDEXES.items():
224
+ try:
225
+ fingerprint, raw = _read(root, name, max_index_bytes, collect=True)
226
+ report["index_files"][name] = fingerprint
227
+ data = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_keys, parse_constant=_constant)
228
+ if not isinstance(data, dict) or not isinstance(data.get(key), list):
229
+ raise ValueError("invalid index shape")
230
+ except ArchiveReadError as exc:
231
+ fail(str(exc), name)
232
+ continue
233
+ except (ValueError, RecursionError):
234
+ fail("invalid_index", name)
235
+ continue
236
+ session = data.get("session_id")
237
+ if isinstance(session, str) and session:
238
+ sessions.add(session)
239
+ for index, item in enumerate(data[key]):
240
+ location = f"{name}/{key}/{index}"
241
+ if not isinstance(item, dict):
242
+ fail("invalid_index_entry", location)
243
+ continue
244
+ if key == "nodes":
245
+ if item.get("type") == "observed_content":
246
+ register(item.get("attributes"), location)
247
+ else:
248
+ # Conversation entries are reference records. Do not walk preview
249
+ # messages, request objects, or arbitrary nested provider JSON.
250
+ if "path" in item or "sha256" in item:
251
+ register(item, location)
252
+ else:
253
+ fail("invalid_reference", location)
254
+ # A projected graph may retain hidden raw nodes under expansion.clusters.
255
+ if key == "nodes" and isinstance(data.get("expansion"), dict):
256
+ clusters = data["expansion"].get("clusters", {})
257
+ if not isinstance(clusters, dict):
258
+ fail("invalid_expansion", f"{name}/expansion/clusters")
259
+ continue
260
+ for cluster_index, cluster in enumerate(clusters.values()):
261
+ location = f"{name}/expansion/clusters/{cluster_index}"
262
+ if not isinstance(cluster, dict) or not isinstance(cluster.get("nodes"), list):
263
+ fail("invalid_expansion", location)
264
+ continue
265
+ for index, item in enumerate(cluster["nodes"]):
266
+ if isinstance(item, dict) and item.get("type") == "observed_content":
267
+ register(item.get("attributes"), f"{location}/nodes/{index}")
268
+ if len(sessions) > 1:
269
+ fail("index_session_mismatch", "graph.json/conversations.json")
270
+ report["unique_file_count"] = len(references)
271
+ budget = max_content_bytes
272
+ for path, (digest, size, location) in references.items():
273
+ if path in conflicted:
274
+ continue
275
+ try:
276
+ fingerprint, _ = _read(root, path, budget)
277
+ budget -= fingerprint["size_bytes"]
278
+ if fingerprint["sha256"] != digest:
279
+ raise ArchiveReadError("hash_mismatch")
280
+ if size is not None and fingerprint["size_bytes"] != size:
281
+ raise ArchiveReadError("size_mismatch")
282
+ report["verified_files"][path] = fingerprint
283
+ except ArchiveReadError as exc:
284
+ fail(str(exc), location)
285
+ report["verified_file_count"] = len(report["verified_files"])
286
+ report["completed_read_bytes"] = max_content_bytes - budget
287
+ if report["error_count"] == 0:
288
+ report["state"] = "complete"
289
+ return report