execweave 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- execweave/__init__.py +3 -0
- execweave/__main__.py +5 -0
- execweave/_conversation_records_core.py +902 -0
- execweave/_dashboard_shell_base.py +148 -0
- execweave/_http_proxy_base.py +565 -0
- execweave/_http_proxy_bounded.py +560 -0
- execweave/_http_proxy_stage.py +509 -0
- execweave/acceptance_output.py +19 -0
- execweave/agent_bootstrap.py +395 -0
- execweave/agent_topology.py +313 -0
- execweave/agent_trace.py +1162 -0
- execweave/agy_preview_sanitize.py +102 -0
- execweave/analysis.py +427 -0
- execweave/anthropic.py +228 -0
- execweave/anthropic_cli.py +171 -0
- execweave/anthropic_full_fidelity.py +385 -0
- execweave/antigravity_adapter.py +112 -0
- execweave/antigravity_adapter_base.py +479 -0
- execweave/antigravity_full_fidelity.py +656 -0
- execweave/antigravity_full_fidelity_base.py +172 -0
- execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
- execweave/antigravity_hook_cli.py +209 -0
- execweave/antigravity_record.py +96 -0
- execweave/antigravity_subagent_linkage.py +449 -0
- execweave/antigravity_trace_capability.py +39 -0
- execweave/auto_specialized.py +547 -0
- execweave/backends.py +102 -0
- execweave/benchmark.py +80 -0
- execweave/claude_adapter.py +517 -0
- execweave/claude_child_transcript.py +314 -0
- execweave/claude_delegation.py +136 -0
- execweave/claude_full_fidelity.py +396 -0
- execweave/claude_hook_cli.py +209 -0
- execweave/claude_hook_contract.py +943 -0
- execweave/claude_model_observer.py +353 -0
- execweave/claude_record.py +106 -0
- execweave/cli.py +629 -0
- execweave/codex_adapter.py +455 -0
- execweave/codex_conversation.py +621 -0
- execweave/codex_full_fidelity.py +287 -0
- execweave/codex_hook_cli.py +301 -0
- execweave/codex_hook_entry.py +207 -0
- execweave/codex_hook_lifecycle.py +363 -0
- execweave/codex_message_diagnostics.py +322 -0
- execweave/codex_message_transport_diagnostics.py +399 -0
- execweave/codex_record.py +199 -0
- execweave/codex_rollout_structures.py +402 -0
- execweave/codex_rollout_trace.py +56 -0
- execweave/codex_rollout_trace_base.py +1509 -0
- execweave/collector.py +768 -0
- execweave/command.py +157 -0
- execweave/command_privacy.py +20 -0
- execweave/content_evidence.py +101 -0
- execweave/content_integrity.py +289 -0
- execweave/content_store.py +273 -0
- execweave/controlled_checks.py +561 -0
- execweave/conversation_archive.py +338 -0
- execweave/conversation_message_identity.py +264 -0
- execweave/conversation_preview.py +66 -0
- execweave/conversation_preview_antigravity.py +32 -0
- execweave/conversation_preview_claude.py +31 -0
- execweave/conversation_preview_codex.py +107 -0
- execweave/conversation_preview_common.py +180 -0
- execweave/conversation_preview_generic.py +188 -0
- execweave/conversation_preview_lines.py +133 -0
- execweave/conversation_preview_transcript.py +121 -0
- execweave/conversation_records.py +349 -0
- execweave/conversation_records_antigravity.py +370 -0
- execweave/conversation_records_codex.py +83 -0
- execweave/conversation_records_common.py +17 -0
- execweave/conversation_records_ollama.py +39 -0
- execweave/correlation.py +818 -0
- execweave/cursor_adapter.py +349 -0
- execweave/cursor_delegation.py +87 -0
- execweave/cursor_delegation_base.py +220 -0
- execweave/cursor_full_fidelity.py +489 -0
- execweave/cursor_hook_cli.py +195 -0
- execweave/cursor_hook_contract.py +439 -0
- execweave/cursor_lifecycle.py +159 -0
- execweave/cursor_record.py +96 -0
- execweave/dashboard_shell.py +283 -0
- execweave/delivery_status.py +94 -0
- execweave/entry.py +98 -0
- execweave/evidence_availability.py +113 -0
- execweave/evidence_grade.py +166 -0
- execweave/fidelity.py +304 -0
- execweave/filesystem.py +327 -0
- execweave/finalization.py +92 -0
- execweave/focus.py +118 -0
- execweave/framework_adapters/__init__.py +34 -0
- execweave/framework_adapters/autogen.py +398 -0
- execweave/framework_adapters/base.py +580 -0
- execweave/framework_adapters/camel.py +270 -0
- execweave/framework_adapters/camel_channel.py +71 -0
- execweave/framework_adapters/metagpt.py +315 -0
- execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
- execweave/framework_adapters/metagpt_recording.py +342 -0
- execweave/framework_adapters/registry.py +90 -0
- execweave/graph.py +590 -0
- execweave/graph_ops.py +472 -0
- execweave/hook_command.py +32 -0
- execweave/hook_delivery.py +32 -0
- execweave/hook_input.py +16 -0
- execweave/http_proxy.py +187 -0
- execweave/http_proxy_cli.py +84 -0
- execweave/inference_gateway.py +476 -0
- execweave/inference_gateway_cli.py +211 -0
- execweave/inference_gateway_full_fidelity.py +613 -0
- execweave/inference_identity.py +76 -0
- execweave/inference_identity_cli.py +60 -0
- execweave/integrity.py +235 -0
- execweave/integrity_cli.py +55 -0
- execweave/investigation_index.py +445 -0
- execweave/litellm_callback.py +211 -0
- execweave/litellm_callback_cli.py +42 -0
- execweave/live.py +445 -0
- execweave/live_core.py +972 -0
- execweave/live_view.py +109 -0
- execweave/live_view_extra_style.py +11 -0
- execweave/live_view_markup.py +29 -0
- execweave/live_view_process_layout.py +650 -0
- execweave/live_view_readability.py +502 -0
- execweave/live_view_script_a.py +59 -0
- execweave/live_view_script_b.py +97 -0
- execweave/live_view_script_c.py +59 -0
- execweave/live_view_script_d.py +40 -0
- execweave/live_view_style.py +34 -0
- execweave/model_runtime.py +560 -0
- execweave/model_runtime_cli.py +265 -0
- execweave/model_runtime_full_fidelity.py +519 -0
- execweave/observation.py +53 -0
- execweave/observation_demo.py +69 -0
- execweave/openai_agents.py +267 -0
- execweave/openai_agents_sdk.py +453 -0
- execweave/openai_compatible.py +239 -0
- execweave/openai_compatible_cli.py +189 -0
- execweave/openai_compatible_full_fidelity.py +438 -0
- execweave/opencode_adapter.py +325 -0
- execweave/opencode_event_contract.py +734 -0
- execweave/opencode_full_fidelity.py +198 -0
- execweave/opencode_hook_cli.py +119 -0
- execweave/opencode_plugin_cli.py +150 -0
- execweave/opencode_record.py +96 -0
- execweave/opencode_task_linkage.py +225 -0
- execweave/overhead_benchmark.py +440 -0
- execweave/privacy.py +84 -0
- execweave/private_io.py +465 -0
- execweave/provider_capability.py +578 -0
- execweave/provider_lifecycle.py +282 -0
- execweave/provider_record.py +290 -0
- execweave/reader_identity.py +13 -0
- execweave/redacted_archive.py +906 -0
- execweave/risk.py +106 -0
- execweave/rule_pack.py +359 -0
- execweave/rule_pack_cli.py +57 -0
- execweave/run_assessment.py +200 -0
- execweave/runtime_endpoint_availability.py +44 -0
- execweave/scalability_benchmark.py +195 -0
- execweave/schema.py +62 -0
- execweave/scope.py +85 -0
- execweave/semantic.py +453 -0
- execweave/session_summary.py +159 -0
- execweave/sink.py +71 -0
- execweave/strace_backend.py +927 -0
- execweave/stream_assembly.py +363 -0
- execweave/task_artifacts.py +192 -0
- execweave/task_validation.py +317 -0
- execweave/theme.py +40 -0
- execweave/top.py +599 -0
- execweave/top_cli.py +150 -0
- execweave/validate.py +196 -0
- execweave/vendor/dagre.min.js +815 -0
- execweave/view_cli.py +49 -0
- execweave/viewer.py +474 -0
- execweave/viewer_agent_panel.py +630 -0
- execweave/viewer_agent_panel_antigravity.py +31 -0
- execweave/viewer_agent_panel_claude.py +9 -0
- execweave/viewer_agent_panel_codex.py +50 -0
- execweave/viewer_agent_panel_cursor.py +9 -0
- execweave/viewer_agent_panel_default.py +79 -0
- execweave/viewer_agent_panel_ollama.py +20 -0
- execweave/viewer_agent_panel_opencode.py +9 -0
- execweave/viewer_agent_panel_registry.py +20 -0
- execweave/viewer_archive_verifier.py +178 -0
- execweave/viewer_background_files.py +86 -0
- execweave/viewer_content_browser.py +307 -0
- execweave/viewer_content_health.py +208 -0
- execweave/viewer_content_inspector.py +309 -0
- execweave/viewer_controlled_checks.py +258 -0
- execweave/viewer_conversation_sync.py +115 -0
- execweave/viewer_dashboard_clean.py +405 -0
- execweave/viewer_dashboard_focus.py +127 -0
- execweave/viewer_dashboard_hardening.py +264 -0
- execweave/viewer_dashboard_hardening_v2.py +62 -0
- execweave/viewer_dashboard_projection.py +261 -0
- execweave/viewer_delivery_status.py +155 -0
- execweave/viewer_edge_decross.py +117 -0
- execweave/viewer_execution_flow.py +611 -0
- execweave/viewer_execution_flow_provider_normalization.py +107 -0
- execweave/viewer_execution_flow_safety.py +349 -0
- execweave/viewer_external_endpoints.py +307 -0
- execweave/viewer_flow_canvas.py +1140 -0
- execweave/viewer_flow_layout.py +922 -0
- execweave/viewer_fold_state.py +31 -0
- execweave/viewer_framework_flow.py +68 -0
- execweave/viewer_framework_model_output.py +133 -0
- execweave/viewer_gif.py +278 -0
- execweave/viewer_history_browser.py +225 -0
- execweave/viewer_investigation.py +268 -0
- execweave/viewer_layout_geometry.py +192 -0
- execweave/viewer_layout_v2.py +429 -0
- execweave/viewer_layout_v2_detached.py +25 -0
- execweave/viewer_limits.py +93 -0
- execweave/viewer_live_layout.py +61 -0
- execweave/viewer_message_handoffs.py +114 -0
- execweave/viewer_projection.py +488 -0
- execweave/viewer_projection_base.py +522 -0
- execweave/viewer_projection_bridges.py +214 -0
- execweave/viewer_recorded_sources.py +146 -0
- execweave/viewer_run_assessment.py +274 -0
- execweave/viewer_run_guide.py +175 -0
- execweave/viewer_runtime_evidence.py +258 -0
- execweave/viewer_semantic_projection.py +641 -0
- execweave/viewer_session_flow.py +491 -0
- execweave/viewer_structure_share.py +132 -0
- execweave/viewer_task_validation.py +241 -0
- execweave/viewer_tool_mirror_identity.py +75 -0
- execweave/viewer_workflow_mode.py +127 -0
- execweave/workflow.py +183 -0
- execweave-1.0.0.dist-info/METADATA +462 -0
- execweave-1.0.0.dist-info/RECORD +234 -0
- execweave-1.0.0.dist-info/WHEEL +4 -0
- execweave-1.0.0.dist-info/entry_points.txt +30 -0
- execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
|
@@ -0,0 +1,906 @@
|
|
|
1
|
+
"""Create and verify content-aware redacted derivative run archives.
|
|
2
|
+
|
|
3
|
+
The source archive is never modified. A derivative receives new content hashes,
|
|
4
|
+
new primary-export hashes and an explicit lineage manifest. The policy is hashed
|
|
5
|
+
but not copied into the derivative because literal redaction terms can themselves
|
|
6
|
+
be sensitive. This is a sharing derivative, not an anonymity guarantee or a
|
|
7
|
+
cryptographically authenticated audit log.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import shutil
|
|
18
|
+
import stat
|
|
19
|
+
import tempfile
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from .content_integrity import (
|
|
24
|
+
ArchiveReadError,
|
|
25
|
+
CONTENT_PATH,
|
|
26
|
+
_path_descriptor_stat,
|
|
27
|
+
_read as _integrity_read,
|
|
28
|
+
audit_content_references,
|
|
29
|
+
hash_export,
|
|
30
|
+
)
|
|
31
|
+
from .content_store import FullFidelityContentStore
|
|
32
|
+
from .dashboard_shell import render_static_dashboard_html
|
|
33
|
+
from .delivery_status import summarize_finalization
|
|
34
|
+
from .finalization import REQUIRED_EXPORTS, record_finalization
|
|
35
|
+
|
|
36
|
+
POLICY_FORMAT = "execweave.redaction-policy.v1"
|
|
37
|
+
LINEAGE_FORMAT = "execweave.redacted-lineage.v1"
|
|
38
|
+
DERIVATIVE_FORMAT = "execweave.redacted-archive.v1"
|
|
39
|
+
MAX_POLICY_BYTES = 128 * 1024
|
|
40
|
+
MAX_FINALIZATION_BYTES = 16 * 1024 * 1024
|
|
41
|
+
MAX_LINEAGE_BYTES = 32 * 1024 * 1024
|
|
42
|
+
MAX_INDEX_BYTES = 64 * 1024 * 1024
|
|
43
|
+
MAX_CONTENT_BYTES = 1024 * 1024 * 1024
|
|
44
|
+
MAX_DERIVATIVE_FILE_BYTES = 64 * 1024 * 1024
|
|
45
|
+
MAX_DERIVATIVE_TOTAL_BYTES = 256 * 1024 * 1024
|
|
46
|
+
MAX_RULES = 100
|
|
47
|
+
MAX_STRING_BYTES = 4096
|
|
48
|
+
_HASH = re.compile(r"[0-9a-f]{64}\Z")
|
|
49
|
+
_KEY = re.compile(r"[A-Za-z0-9_.-]{1,128}\Z")
|
|
50
|
+
_RESERVED_REDACT_KEYS = frozenset(
|
|
51
|
+
{
|
|
52
|
+
"id",
|
|
53
|
+
"type",
|
|
54
|
+
"relation",
|
|
55
|
+
"event_type",
|
|
56
|
+
"graph_schema_version",
|
|
57
|
+
"schema_version",
|
|
58
|
+
"sha256",
|
|
59
|
+
"path",
|
|
60
|
+
"session_id",
|
|
61
|
+
"source_path",
|
|
62
|
+
"content_kind",
|
|
63
|
+
"media_type",
|
|
64
|
+
"representation",
|
|
65
|
+
"provider",
|
|
66
|
+
"backend",
|
|
67
|
+
"evidence_source",
|
|
68
|
+
"attribution",
|
|
69
|
+
"observed_field",
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
_CONTROL_STRING_KEYS = frozenset(
|
|
73
|
+
{
|
|
74
|
+
"type",
|
|
75
|
+
"relation",
|
|
76
|
+
"event_type",
|
|
77
|
+
"graph_schema_version",
|
|
78
|
+
"schema_version",
|
|
79
|
+
"content_kind",
|
|
80
|
+
"media_type",
|
|
81
|
+
"representation",
|
|
82
|
+
"provider",
|
|
83
|
+
"backend",
|
|
84
|
+
"evidence_source",
|
|
85
|
+
"attribution",
|
|
86
|
+
"observed_field",
|
|
87
|
+
"sha256",
|
|
88
|
+
"path",
|
|
89
|
+
}
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class RedactedArchiveError(Exception):
|
|
94
|
+
"""Bounded derivative-archive diagnostic without private file paths."""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
98
|
+
result: dict[str, Any] = {}
|
|
99
|
+
for key, value in pairs:
|
|
100
|
+
if key in result:
|
|
101
|
+
raise ValueError("duplicate JSON key")
|
|
102
|
+
result[key] = value
|
|
103
|
+
return result
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _bad_constant(_value: str) -> None:
|
|
107
|
+
raise ValueError("nonfinite JSON value")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _strict_json(raw: bytes, limit: int) -> Any:
|
|
111
|
+
if not isinstance(raw, bytes) or len(raw) > limit:
|
|
112
|
+
raise ValueError("JSON exceeds its byte limit")
|
|
113
|
+
return json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs, parse_constant=_bad_constant)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _canonical(value: Any, *, newline: bool = True) -> bytes:
|
|
117
|
+
raw = json.dumps(
|
|
118
|
+
value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False
|
|
119
|
+
).encode("utf-8")
|
|
120
|
+
return raw + (b"\n" if newline else b"")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _fingerprint(raw: bytes) -> dict[str, Any]:
|
|
124
|
+
return {"sha256": hashlib.sha256(raw).hexdigest(), "size_bytes": len(raw)}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _validate_fingerprint(value: Any) -> bool:
|
|
128
|
+
return (
|
|
129
|
+
isinstance(value, dict)
|
|
130
|
+
and set(value) == {"sha256", "size_bytes"}
|
|
131
|
+
and isinstance(value.get("sha256"), str)
|
|
132
|
+
and _HASH.fullmatch(value["sha256"]) is not None
|
|
133
|
+
and type(value.get("size_bytes")) is int
|
|
134
|
+
and value["size_bytes"] >= 0
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _read_named_regular(root: Path, name: str, limit: int) -> bytes:
|
|
139
|
+
"""Read one fixed top-level metadata file without following links/reparse points."""
|
|
140
|
+
if name not in {"finalization.json", "lineage.json"}:
|
|
141
|
+
raise RedactedArchiveError("invalid_metadata_file")
|
|
142
|
+
path = root / name
|
|
143
|
+
try:
|
|
144
|
+
info = path.lstat()
|
|
145
|
+
if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
|
|
146
|
+
raise RedactedArchiveError("unsafe_metadata_file")
|
|
147
|
+
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
|
148
|
+
flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
149
|
+
fd = os.open(path, flags)
|
|
150
|
+
try:
|
|
151
|
+
before = os.fstat(fd)
|
|
152
|
+
if not stat.S_ISREG(before.st_mode) or before.st_size > limit:
|
|
153
|
+
raise RedactedArchiveError("metadata_file_limit")
|
|
154
|
+
chunks: list[bytes] = []
|
|
155
|
+
size = 0
|
|
156
|
+
while True:
|
|
157
|
+
chunk = os.read(fd, min(1024 * 1024, max(1, limit - size + 1)))
|
|
158
|
+
if not chunk:
|
|
159
|
+
break
|
|
160
|
+
size += len(chunk)
|
|
161
|
+
if size > limit:
|
|
162
|
+
raise RedactedArchiveError("metadata_file_limit")
|
|
163
|
+
chunks.append(chunk)
|
|
164
|
+
after = os.fstat(fd)
|
|
165
|
+
finally:
|
|
166
|
+
os.close(fd)
|
|
167
|
+
try:
|
|
168
|
+
final = _path_descriptor_stat(path)
|
|
169
|
+
except ArchiveReadError as exc:
|
|
170
|
+
raise RedactedArchiveError("unsafe_metadata_file") from exc
|
|
171
|
+
|
|
172
|
+
def signature(value):
|
|
173
|
+
return (value.st_dev, value.st_ino, value.st_size, value.st_mtime_ns, value.st_ctime_ns)
|
|
174
|
+
|
|
175
|
+
if signature(before) != signature(after) or signature(after) != signature(final):
|
|
176
|
+
raise RedactedArchiveError("metadata_changed_during_read")
|
|
177
|
+
return b"".join(chunks)
|
|
178
|
+
except FileNotFoundError as exc:
|
|
179
|
+
raise RedactedArchiveError("missing_metadata_file") from exc
|
|
180
|
+
except RedactedArchiveError:
|
|
181
|
+
raise
|
|
182
|
+
except OSError as exc:
|
|
183
|
+
raise RedactedArchiveError("unreadable_metadata_file") from exc
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _read_policy(path: Path) -> bytes:
|
|
187
|
+
"""Bound a policy before materializing it in memory."""
|
|
188
|
+
try:
|
|
189
|
+
info = path.lstat()
|
|
190
|
+
if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
|
|
191
|
+
raise RedactedArchiveError("unsafe_policy")
|
|
192
|
+
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_POLICY_BYTES:
|
|
193
|
+
raise RedactedArchiveError("policy_limit")
|
|
194
|
+
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
|
195
|
+
flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
196
|
+
fd = os.open(path, flags)
|
|
197
|
+
try:
|
|
198
|
+
before = os.fstat(fd)
|
|
199
|
+
chunks: list[bytes] = []
|
|
200
|
+
size = 0
|
|
201
|
+
while True:
|
|
202
|
+
chunk = os.read(fd, min(64 * 1024, max(1, MAX_POLICY_BYTES - size + 1)))
|
|
203
|
+
if not chunk:
|
|
204
|
+
break
|
|
205
|
+
size += len(chunk)
|
|
206
|
+
if size > MAX_POLICY_BYTES:
|
|
207
|
+
raise RedactedArchiveError("policy_limit")
|
|
208
|
+
chunks.append(chunk)
|
|
209
|
+
after = os.fstat(fd)
|
|
210
|
+
finally:
|
|
211
|
+
os.close(fd)
|
|
212
|
+
if (
|
|
213
|
+
before.st_dev,
|
|
214
|
+
before.st_ino,
|
|
215
|
+
before.st_size,
|
|
216
|
+
before.st_mtime_ns,
|
|
217
|
+
before.st_ctime_ns,
|
|
218
|
+
) != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns):
|
|
219
|
+
raise RedactedArchiveError("policy_changed_during_read")
|
|
220
|
+
return b"".join(chunks)
|
|
221
|
+
except RedactedArchiveError:
|
|
222
|
+
raise
|
|
223
|
+
except (FileNotFoundError, OSError) as exc:
|
|
224
|
+
raise RedactedArchiveError("unreadable_policy") from exc
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _pointer(value: str) -> list[str]:
|
|
228
|
+
if not isinstance(value, str) or len(value.encode("utf-8")) > MAX_STRING_BYTES:
|
|
229
|
+
raise ValueError("invalid JSON pointer")
|
|
230
|
+
if value and not value.startswith("/"):
|
|
231
|
+
raise ValueError("invalid JSON pointer")
|
|
232
|
+
if re.search(r"~(?![01])", value):
|
|
233
|
+
raise ValueError("invalid JSON pointer escape")
|
|
234
|
+
parts = [] if not value else value[1:].split("/")
|
|
235
|
+
if len(parts) > 32:
|
|
236
|
+
raise ValueError("JSON pointer exceeds 32 steps")
|
|
237
|
+
return [p.replace("~1", "/").replace("~0", "~") for p in parts]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def policy_document(raw: bytes) -> tuple[dict[str, Any], bytes, str]:
|
|
241
|
+
try:
|
|
242
|
+
value = _strict_json(raw, MAX_POLICY_BYTES)
|
|
243
|
+
except (ValueError, UnicodeError, RecursionError) as exc:
|
|
244
|
+
raise RedactedArchiveError("invalid_policy") from exc
|
|
245
|
+
fields = {"format", "name", "replacement", "literals", "json_pointers", "redact_keys", "binary"}
|
|
246
|
+
if not isinstance(value, dict) or set(value) != fields or value.get("format") != POLICY_FORMAT:
|
|
247
|
+
raise RedactedArchiveError("invalid_policy")
|
|
248
|
+
for field in ("name", "replacement"):
|
|
249
|
+
item = value[field]
|
|
250
|
+
if not isinstance(item, str) or not item or len(item.encode("utf-8")) > MAX_STRING_BYTES:
|
|
251
|
+
raise RedactedArchiveError("invalid_policy")
|
|
252
|
+
for field in ("literals", "json_pointers", "redact_keys"):
|
|
253
|
+
if not isinstance(value[field], list) or len(value[field]) > MAX_RULES:
|
|
254
|
+
raise RedactedArchiveError("invalid_policy")
|
|
255
|
+
if len(set(value[field])) != len(value[field]):
|
|
256
|
+
raise RedactedArchiveError("invalid_policy")
|
|
257
|
+
for literal in value["literals"]:
|
|
258
|
+
if not isinstance(literal, str) or not literal or len(literal.encode("utf-8")) > 1024:
|
|
259
|
+
raise RedactedArchiveError("invalid_policy")
|
|
260
|
+
try:
|
|
261
|
+
for pointer in value["json_pointers"]:
|
|
262
|
+
_pointer(pointer)
|
|
263
|
+
except ValueError as exc:
|
|
264
|
+
raise RedactedArchiveError("invalid_policy") from exc
|
|
265
|
+
for key in value["redact_keys"]:
|
|
266
|
+
if (
|
|
267
|
+
not isinstance(key, str)
|
|
268
|
+
or _KEY.fullmatch(key) is None
|
|
269
|
+
or key.lower() in _RESERVED_REDACT_KEYS
|
|
270
|
+
):
|
|
271
|
+
raise RedactedArchiveError("invalid_policy")
|
|
272
|
+
if value["binary"] != "drop":
|
|
273
|
+
raise RedactedArchiveError("invalid_policy")
|
|
274
|
+
canonical = _canonical(value, newline=False)
|
|
275
|
+
return value, canonical, hashlib.sha256(canonical).hexdigest()
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _replace_literals(text: str, policy: dict[str, Any]) -> tuple[str, int]:
|
|
279
|
+
count = 0
|
|
280
|
+
for literal in policy["literals"]:
|
|
281
|
+
occurrences = text.count(literal)
|
|
282
|
+
if occurrences:
|
|
283
|
+
text = text.replace(literal, policy["replacement"])
|
|
284
|
+
count += occurrences
|
|
285
|
+
return text, count
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _set_pointer(document: Any, pointer: str, replacement: str) -> bool:
|
|
289
|
+
parts = _pointer(pointer)
|
|
290
|
+
if not parts:
|
|
291
|
+
return False # Replacing the entire document would destroy its type/shape.
|
|
292
|
+
current = document
|
|
293
|
+
for part in parts[:-1]:
|
|
294
|
+
if isinstance(current, dict) and part in current:
|
|
295
|
+
current = current[part]
|
|
296
|
+
elif isinstance(current, list) and part.isdigit() and int(part) < len(current):
|
|
297
|
+
current = current[int(part)]
|
|
298
|
+
else:
|
|
299
|
+
return False
|
|
300
|
+
leaf = parts[-1]
|
|
301
|
+
if isinstance(current, dict) and leaf in current:
|
|
302
|
+
current[leaf] = replacement
|
|
303
|
+
return True
|
|
304
|
+
if isinstance(current, list) and leaf.isdigit() and int(leaf) < len(current):
|
|
305
|
+
current[int(leaf)] = replacement
|
|
306
|
+
return True
|
|
307
|
+
return False
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _redact_json_value(
|
|
311
|
+
value: Any, policy: dict[str, Any], *, key: str | None = None
|
|
312
|
+
) -> tuple[Any, int]:
|
|
313
|
+
if key is not None and key.lower() in {k.lower() for k in policy["redact_keys"]}:
|
|
314
|
+
return policy["replacement"], 1
|
|
315
|
+
if isinstance(value, str):
|
|
316
|
+
return _replace_literals(value, policy)
|
|
317
|
+
if isinstance(value, list):
|
|
318
|
+
result, count = [], 0
|
|
319
|
+
for item in value:
|
|
320
|
+
transformed, used = _redact_json_value(item, policy)
|
|
321
|
+
result.append(transformed)
|
|
322
|
+
count += used
|
|
323
|
+
return result, count
|
|
324
|
+
if isinstance(value, dict):
|
|
325
|
+
result: dict[str, Any] = {}
|
|
326
|
+
count = 0
|
|
327
|
+
for child_key, child in value.items():
|
|
328
|
+
transformed, used = _redact_json_value(child, policy, key=child_key)
|
|
329
|
+
result[child_key] = transformed
|
|
330
|
+
count += used
|
|
331
|
+
return result, count
|
|
332
|
+
return value, 0
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _redact_content(
|
|
336
|
+
raw: bytes, suffix: str, media_type: str, policy: dict[str, Any]
|
|
337
|
+
) -> tuple[bytes, str, list[str]]:
|
|
338
|
+
actions: list[str] = []
|
|
339
|
+
if suffix == ".json" or media_type.lower().startswith("application/json"):
|
|
340
|
+
try:
|
|
341
|
+
document = _strict_json(raw, MAX_CONTENT_BYTES)
|
|
342
|
+
except (ValueError, UnicodeError, RecursionError) as exc:
|
|
343
|
+
raise RedactedArchiveError("invalid_json_content") from exc
|
|
344
|
+
document, count = _redact_json_value(document, policy)
|
|
345
|
+
if count:
|
|
346
|
+
actions.append(f"literal_or_key_replacements:{count}")
|
|
347
|
+
pointer_count = 0
|
|
348
|
+
for pointer in policy["json_pointers"]:
|
|
349
|
+
if _set_pointer(document, pointer, policy["replacement"]):
|
|
350
|
+
pointer_count += 1
|
|
351
|
+
if pointer_count:
|
|
352
|
+
actions.append(f"json_pointer_replacements:{pointer_count}")
|
|
353
|
+
return (
|
|
354
|
+
_canonical(document, newline=False),
|
|
355
|
+
"application/json",
|
|
356
|
+
actions or ["canonicalized_json"],
|
|
357
|
+
)
|
|
358
|
+
if suffix == ".txt" or media_type.lower().startswith("text/"):
|
|
359
|
+
try:
|
|
360
|
+
text = raw.decode("utf-8")
|
|
361
|
+
except UnicodeDecodeError as exc:
|
|
362
|
+
raise RedactedArchiveError("invalid_utf8_text_content") from exc
|
|
363
|
+
text, count = _replace_literals(text, policy)
|
|
364
|
+
if count:
|
|
365
|
+
actions.append(f"literal_replacements:{count}")
|
|
366
|
+
return (
|
|
367
|
+
text.encode("utf-8"),
|
|
368
|
+
media_type or "text/plain; charset=utf-8",
|
|
369
|
+
actions or ["text_unchanged"],
|
|
370
|
+
)
|
|
371
|
+
# V1 never copies opaque binary into a sharing derivative.
|
|
372
|
+
return b"", "application/octet-stream", ["binary_dropped"]
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _source_reference_map(
|
|
376
|
+
graph: dict[str, Any], conversations: dict[str, Any]
|
|
377
|
+
) -> dict[str, dict[str, Any]]:
|
|
378
|
+
refs: dict[str, dict[str, Any]] = {}
|
|
379
|
+
|
|
380
|
+
def register(value: Any) -> None:
|
|
381
|
+
if not isinstance(value, dict):
|
|
382
|
+
return
|
|
383
|
+
path, digest = value.get("path"), value.get("sha256")
|
|
384
|
+
if isinstance(path, str) and isinstance(digest, str) and CONTENT_PATH.fullmatch(path):
|
|
385
|
+
refs.setdefault(path, value)
|
|
386
|
+
|
|
387
|
+
def nodes(items: Any) -> None:
|
|
388
|
+
if isinstance(items, list):
|
|
389
|
+
for item in items:
|
|
390
|
+
if isinstance(item, dict) and item.get("type") == "observed_content":
|
|
391
|
+
register(item.get("attributes"))
|
|
392
|
+
|
|
393
|
+
nodes(graph.get("nodes"))
|
|
394
|
+
expansion = graph.get("expansion")
|
|
395
|
+
if isinstance(expansion, dict) and isinstance(expansion.get("clusters"), dict):
|
|
396
|
+
for cluster in expansion["clusters"].values():
|
|
397
|
+
if isinstance(cluster, dict):
|
|
398
|
+
nodes(cluster.get("nodes"))
|
|
399
|
+
for entry in (
|
|
400
|
+
conversations.get("entries", []) if isinstance(conversations.get("entries"), list) else []
|
|
401
|
+
):
|
|
402
|
+
register(entry)
|
|
403
|
+
return refs
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _rewrite_index(
|
|
407
|
+
value: Any,
|
|
408
|
+
*,
|
|
409
|
+
policy: dict[str, Any],
|
|
410
|
+
refs: dict[str, dict[str, Any]],
|
|
411
|
+
id_map: dict[str, str],
|
|
412
|
+
parent_key: str | None = None,
|
|
413
|
+
) -> Any:
|
|
414
|
+
if isinstance(value, list):
|
|
415
|
+
return [
|
|
416
|
+
_rewrite_index(item, policy=policy, refs=refs, id_map=id_map, parent_key=parent_key)
|
|
417
|
+
for item in value
|
|
418
|
+
]
|
|
419
|
+
if isinstance(value, dict):
|
|
420
|
+
if isinstance(value.get("path"), str) and value["path"] in refs and value.get("sha256"):
|
|
421
|
+
replacement = dict(value)
|
|
422
|
+
derived = refs[value["path"]]
|
|
423
|
+
replacement.update(derived)
|
|
424
|
+
replacement["redacted_derivative"] = True
|
|
425
|
+
replacement["complete_from_source"] = value.get("complete_from_source", True)
|
|
426
|
+
return replacement
|
|
427
|
+
result: dict[str, Any] = {}
|
|
428
|
+
redact_keys = {k.lower() for k in policy["redact_keys"]}
|
|
429
|
+
for key, child in value.items():
|
|
430
|
+
if key == "source_path":
|
|
431
|
+
result[key] = None
|
|
432
|
+
elif key == "session_id" and isinstance(child, str):
|
|
433
|
+
result[key] = id_map.get(child, child)
|
|
434
|
+
elif key == "id" and isinstance(child, str):
|
|
435
|
+
result[key] = id_map.get(child, child)
|
|
436
|
+
elif key in ("source", "target") and isinstance(child, str):
|
|
437
|
+
result[key] = id_map.get(child, child)
|
|
438
|
+
elif key.lower() in redact_keys and key.lower() not in _RESERVED_REDACT_KEYS:
|
|
439
|
+
result[key] = policy["replacement"]
|
|
440
|
+
else:
|
|
441
|
+
result[key] = _rewrite_index(
|
|
442
|
+
child, policy=policy, refs=refs, id_map=id_map, parent_key=key
|
|
443
|
+
)
|
|
444
|
+
return result
|
|
445
|
+
if isinstance(value, str):
|
|
446
|
+
if value in id_map:
|
|
447
|
+
return id_map[value]
|
|
448
|
+
if parent_key in _CONTROL_STRING_KEYS:
|
|
449
|
+
return value
|
|
450
|
+
return _replace_literals(value, policy)[0]
|
|
451
|
+
return value
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _identity_map(
|
|
455
|
+
graph: dict[str, Any],
|
|
456
|
+
conversations: dict[str, Any],
|
|
457
|
+
policy: dict[str, Any],
|
|
458
|
+
derived_session: str,
|
|
459
|
+
) -> dict[str, str]:
|
|
460
|
+
mapping: dict[str, str] = {}
|
|
461
|
+
source_session = graph.get("session_id")
|
|
462
|
+
if isinstance(source_session, str) and source_session:
|
|
463
|
+
mapping[source_session] = derived_session
|
|
464
|
+
identities: set[str] = set()
|
|
465
|
+
|
|
466
|
+
def collect(value: Any) -> None:
|
|
467
|
+
if isinstance(value, list):
|
|
468
|
+
for item in value:
|
|
469
|
+
collect(item)
|
|
470
|
+
return
|
|
471
|
+
if not isinstance(value, dict):
|
|
472
|
+
return
|
|
473
|
+
for key, child in value.items():
|
|
474
|
+
if key in {"id", "source", "target"} and isinstance(child, str) and child:
|
|
475
|
+
identities.add(child)
|
|
476
|
+
else:
|
|
477
|
+
collect(child)
|
|
478
|
+
|
|
479
|
+
collect(graph)
|
|
480
|
+
collect(conversations)
|
|
481
|
+
transformed: dict[str, str] = {}
|
|
482
|
+
for identity in sorted(identities):
|
|
483
|
+
new = _replace_literals(identity, policy)[0]
|
|
484
|
+
transformed[identity] = new
|
|
485
|
+
reverse: dict[str, str] = {}
|
|
486
|
+
for old, new in transformed.items():
|
|
487
|
+
previous = reverse.get(new)
|
|
488
|
+
if previous is not None and previous != old:
|
|
489
|
+
raise RedactedArchiveError("identity_collision")
|
|
490
|
+
reverse[new] = old
|
|
491
|
+
if old != new:
|
|
492
|
+
mapping[old] = new
|
|
493
|
+
return mapping
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _load_source(
|
|
497
|
+
root: Path,
|
|
498
|
+
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any], bytes, dict[str, Any]]:
|
|
499
|
+
integrity = audit_content_references(
|
|
500
|
+
root, max_index_bytes=MAX_INDEX_BYTES, max_content_bytes=MAX_CONTENT_BYTES
|
|
501
|
+
)
|
|
502
|
+
if integrity.get("state") != "complete":
|
|
503
|
+
raise RedactedArchiveError("source_archive_incomplete")
|
|
504
|
+
final_raw = _read_named_regular(root, "finalization.json", MAX_FINALIZATION_BYTES)
|
|
505
|
+
try:
|
|
506
|
+
report = _strict_json(final_raw, MAX_FINALIZATION_BYTES)
|
|
507
|
+
except (ValueError, UnicodeError, RecursionError) as exc:
|
|
508
|
+
raise RedactedArchiveError("invalid_source_finalization") from exc
|
|
509
|
+
if summarize_finalization(report).get("state") != "complete":
|
|
510
|
+
raise RedactedArchiveError("source_finalization_incomplete")
|
|
511
|
+
for name in REQUIRED_EXPORTS:
|
|
512
|
+
if hash_export(root, name) != report.get("artifacts", {}).get(name):
|
|
513
|
+
raise RedactedArchiveError("source_primary_changed")
|
|
514
|
+
try:
|
|
515
|
+
graph_fp, graph_raw = _integrity_read(root, "graph.json", MAX_INDEX_BYTES, collect=True)
|
|
516
|
+
conversations_fp, conversations_raw = _integrity_read(
|
|
517
|
+
root, "conversations.json", MAX_INDEX_BYTES, collect=True
|
|
518
|
+
)
|
|
519
|
+
if graph_fp != report.get("artifacts", {}).get(
|
|
520
|
+
"graph.json"
|
|
521
|
+
) or conversations_fp != report.get("artifacts", {}).get("conversations.json"):
|
|
522
|
+
raise RedactedArchiveError("source_primary_changed")
|
|
523
|
+
graph = _strict_json(graph_raw, MAX_INDEX_BYTES)
|
|
524
|
+
conversations = _strict_json(conversations_raw, MAX_INDEX_BYTES)
|
|
525
|
+
except RedactedArchiveError:
|
|
526
|
+
raise
|
|
527
|
+
except (ArchiveReadError, ValueError, UnicodeError, RecursionError) as exc:
|
|
528
|
+
raise RedactedArchiveError("invalid_source_index") from exc
|
|
529
|
+
if not isinstance(graph, dict) or not isinstance(graph.get("nodes"), list):
|
|
530
|
+
raise RedactedArchiveError("invalid_source_index")
|
|
531
|
+
if not isinstance(conversations, dict) or not isinstance(conversations.get("entries"), list):
|
|
532
|
+
raise RedactedArchiveError("invalid_source_index")
|
|
533
|
+
return graph, conversations, report, final_raw, integrity
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _write_bytes(path: Path, raw: bytes) -> None:
|
|
537
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
538
|
+
fd, tmp = tempfile.mkstemp(prefix=".execweave-redacted-", dir=path.parent)
|
|
539
|
+
tmp_path = Path(tmp)
|
|
540
|
+
try:
|
|
541
|
+
with os.fdopen(fd, "wb") as handle:
|
|
542
|
+
handle.write(raw)
|
|
543
|
+
handle.flush()
|
|
544
|
+
os.fsync(handle.fileno())
|
|
545
|
+
os.replace(tmp_path, path)
|
|
546
|
+
finally:
|
|
547
|
+
tmp_path.unlink(missing_ok=True)
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def create_redacted_archive(
|
|
551
|
+
source: str | Path, destination: str | Path, policy_path: str | Path
|
|
552
|
+
) -> dict[str, Any]:
|
|
553
|
+
source_root = Path(source).expanduser().absolute()
|
|
554
|
+
destination = Path(destination).expanduser().absolute()
|
|
555
|
+
if destination.exists():
|
|
556
|
+
raise RedactedArchiveError("destination_exists")
|
|
557
|
+
policy_raw = _read_policy(Path(policy_path).expanduser().absolute())
|
|
558
|
+
policy, _policy_canonical, policy_sha = policy_document(policy_raw)
|
|
559
|
+
graph, conversations, source_report, source_final_raw, source_integrity = _load_source(
|
|
560
|
+
source_root
|
|
561
|
+
)
|
|
562
|
+
source_primary = {name: hash_export(source_root, name) for name in REQUIRED_EXPORTS}
|
|
563
|
+
source_graph_sha = source_primary["graph.json"]["sha256"]
|
|
564
|
+
derived_session = "redacted-" + source_graph_sha[:24]
|
|
565
|
+
identity_map = _identity_map(graph, conversations, policy, derived_session)
|
|
566
|
+
source_refs = _source_reference_map(graph, conversations)
|
|
567
|
+
|
|
568
|
+
parent = destination.parent
|
|
569
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
570
|
+
temporary = Path(tempfile.mkdtemp(prefix=".execweave-redacted-", dir=parent))
|
|
571
|
+
store = FullFidelityContentStore(temporary)
|
|
572
|
+
mapped: dict[str, dict[str, Any]] = {}
|
|
573
|
+
lineage_rows: list[dict[str, Any]] = []
|
|
574
|
+
try:
|
|
575
|
+
completed_source_bytes = 0
|
|
576
|
+
for path in sorted(source_refs):
|
|
577
|
+
ref = source_refs[path]
|
|
578
|
+
remaining = MAX_DERIVATIVE_TOTAL_BYTES - completed_source_bytes
|
|
579
|
+
if remaining < 0:
|
|
580
|
+
raise RedactedArchiveError("derivative_content_limit")
|
|
581
|
+
try:
|
|
582
|
+
fp, raw = _integrity_read(
|
|
583
|
+
source_root, path, min(MAX_DERIVATIVE_FILE_BYTES, remaining), collect=True
|
|
584
|
+
)
|
|
585
|
+
except ArchiveReadError as exc:
|
|
586
|
+
raise RedactedArchiveError("source_content_unreadable") from exc
|
|
587
|
+
completed_source_bytes += len(raw)
|
|
588
|
+
if fp.get("sha256") != ref.get("sha256") or (
|
|
589
|
+
"size_bytes" in ref
|
|
590
|
+
and ref.get("size_bytes") is not None
|
|
591
|
+
and fp.get("size_bytes") != ref.get("size_bytes")
|
|
592
|
+
):
|
|
593
|
+
raise RedactedArchiveError("source_content_changed")
|
|
594
|
+
suffix = Path(path).suffix
|
|
595
|
+
media = (
|
|
596
|
+
ref.get("media_type")
|
|
597
|
+
if isinstance(ref.get("media_type"), str)
|
|
598
|
+
else (
|
|
599
|
+
"application/json"
|
|
600
|
+
if suffix == ".json"
|
|
601
|
+
else "text/plain; charset=utf-8"
|
|
602
|
+
if suffix == ".txt"
|
|
603
|
+
else "application/octet-stream"
|
|
604
|
+
)
|
|
605
|
+
)
|
|
606
|
+
payload, derived_media, actions = _redact_content(raw, suffix, media, policy)
|
|
607
|
+
content_kind = (
|
|
608
|
+
ref.get("content_kind")
|
|
609
|
+
if isinstance(ref.get("content_kind"), str) and ref.get("content_kind")
|
|
610
|
+
else "redacted_content"
|
|
611
|
+
)
|
|
612
|
+
derived = store.put_bytes(
|
|
613
|
+
payload,
|
|
614
|
+
content_kind=content_kind,
|
|
615
|
+
media_type=derived_media,
|
|
616
|
+
representation="redacted_derivative",
|
|
617
|
+
).to_dict()
|
|
618
|
+
mapped[path] = derived
|
|
619
|
+
lineage_rows.append(
|
|
620
|
+
{
|
|
621
|
+
"source": {"path": path, "sha256": ref["sha256"], "size_bytes": len(raw)},
|
|
622
|
+
"derived": {
|
|
623
|
+
"path": derived["path"],
|
|
624
|
+
"sha256": derived["sha256"],
|
|
625
|
+
"size_bytes": derived["size_bytes"],
|
|
626
|
+
},
|
|
627
|
+
"actions": actions,
|
|
628
|
+
"changed": raw != payload,
|
|
629
|
+
}
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
new_graph = _rewrite_index(graph, policy=policy, refs=mapped, id_map=identity_map)
|
|
633
|
+
new_conversations = _rewrite_index(
|
|
634
|
+
conversations, policy=policy, refs=mapped, id_map=identity_map
|
|
635
|
+
)
|
|
636
|
+
derivative_meta = {
|
|
637
|
+
"format": DERIVATIVE_FORMAT,
|
|
638
|
+
"policy_sha256": policy_sha,
|
|
639
|
+
"source_graph_sha256": source_graph_sha,
|
|
640
|
+
"lineage_file": "lineage.json",
|
|
641
|
+
"limitation": "Redaction follows the approved explicit policy; this is not an anonymity guarantee or proof that no other sensitive values remain.",
|
|
642
|
+
}
|
|
643
|
+
new_graph["redacted_derivative"] = derivative_meta
|
|
644
|
+
new_conversations["redacted_derivative"] = derivative_meta
|
|
645
|
+
graph_raw = _canonical(new_graph)
|
|
646
|
+
conversations_raw = _canonical(new_conversations)
|
|
647
|
+
_write_bytes(temporary / "graph.json", graph_raw)
|
|
648
|
+
_write_bytes(temporary / "conversations.json", conversations_raw)
|
|
649
|
+
viewer = render_static_dashboard_html(
|
|
650
|
+
new_graph, conversation_entries=new_conversations["entries"]
|
|
651
|
+
)
|
|
652
|
+
_write_bytes(temporary / "viewer.html", viewer.encode("utf-8"))
|
|
653
|
+
derived_primary = {name: hash_export(temporary, name) for name in REQUIRED_EXPORTS}
|
|
654
|
+
lineage = {
|
|
655
|
+
"format": LINEAGE_FORMAT,
|
|
656
|
+
"policy": {"name": policy["name"], "sha256": policy_sha},
|
|
657
|
+
"source": {
|
|
658
|
+
"finalization": _fingerprint(source_final_raw),
|
|
659
|
+
"artifacts": source_primary,
|
|
660
|
+
"content_file_count": source_integrity["verified_file_count"],
|
|
661
|
+
},
|
|
662
|
+
"derived": {
|
|
663
|
+
"session_id": derived_session,
|
|
664
|
+
"artifacts": derived_primary,
|
|
665
|
+
"content_file_count": len({row["derived"]["path"] for row in lineage_rows}),
|
|
666
|
+
},
|
|
667
|
+
"mappings": lineage_rows,
|
|
668
|
+
"limitations": [
|
|
669
|
+
"Source archive bytes are not included solely for lineage verification.",
|
|
670
|
+
"The policy body is not included because redaction terms can themselves be sensitive.",
|
|
671
|
+
"A complete derivative integrity check does not prove anonymization, source authenticity, provider recall, or task correctness.",
|
|
672
|
+
],
|
|
673
|
+
}
|
|
674
|
+
lineage_raw = _canonical(lineage)
|
|
675
|
+
_write_bytes(temporary / "lineage.json", lineage_raw)
|
|
676
|
+
report = record_finalization(temporary, state="complete")
|
|
677
|
+
report["derivation"] = {
|
|
678
|
+
"format": DERIVATIVE_FORMAT,
|
|
679
|
+
"lineage": _fingerprint(lineage_raw),
|
|
680
|
+
"policy_sha256": policy_sha,
|
|
681
|
+
"source_finalization_sha256": hashlib.sha256(source_final_raw).hexdigest(),
|
|
682
|
+
}
|
|
683
|
+
_write_bytes(
|
|
684
|
+
temporary / "finalization.json",
|
|
685
|
+
json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
|
|
686
|
+
+ b"\n",
|
|
687
|
+
)
|
|
688
|
+
verified = verify_redacted_archive(temporary, source_root=source_root)
|
|
689
|
+
if verified["state"] != "complete" or verified["source_state"] != "complete":
|
|
690
|
+
raise RedactedArchiveError("derivative_verification_failed")
|
|
691
|
+
os.replace(temporary, destination)
|
|
692
|
+
return verified
|
|
693
|
+
except Exception:
|
|
694
|
+
shutil.rmtree(temporary, ignore_errors=True)
|
|
695
|
+
raise
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _validate_lineage(value: Any) -> dict[str, Any]:
|
|
699
|
+
if not isinstance(value, dict) or set(value) != {
|
|
700
|
+
"format",
|
|
701
|
+
"policy",
|
|
702
|
+
"source",
|
|
703
|
+
"derived",
|
|
704
|
+
"mappings",
|
|
705
|
+
"limitations",
|
|
706
|
+
}:
|
|
707
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
708
|
+
if value.get("format") != LINEAGE_FORMAT:
|
|
709
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
710
|
+
policy = value.get("policy")
|
|
711
|
+
if (
|
|
712
|
+
not isinstance(policy, dict)
|
|
713
|
+
or set(policy) != {"name", "sha256"}
|
|
714
|
+
or not isinstance(policy["name"], str)
|
|
715
|
+
or _HASH.fullmatch(str(policy["sha256"])) is None
|
|
716
|
+
):
|
|
717
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
718
|
+
for side in ("source", "derived"):
|
|
719
|
+
item = value.get(side)
|
|
720
|
+
if not isinstance(item, dict) or not isinstance(item.get("artifacts"), dict):
|
|
721
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
722
|
+
for name in REQUIRED_EXPORTS:
|
|
723
|
+
if not _validate_fingerprint(item["artifacts"].get(name)):
|
|
724
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
725
|
+
source = value["source"]
|
|
726
|
+
if (
|
|
727
|
+
not _validate_fingerprint(source.get("finalization"))
|
|
728
|
+
or type(source.get("content_file_count")) is not int
|
|
729
|
+
or source["content_file_count"] < 0
|
|
730
|
+
):
|
|
731
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
732
|
+
derived = value["derived"]
|
|
733
|
+
if (
|
|
734
|
+
not isinstance(derived.get("session_id"), str)
|
|
735
|
+
or not derived["session_id"]
|
|
736
|
+
or type(derived.get("content_file_count")) is not int
|
|
737
|
+
or derived["content_file_count"] < 0
|
|
738
|
+
):
|
|
739
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
740
|
+
mappings = value.get("mappings")
|
|
741
|
+
if not isinstance(mappings, list) or len(mappings) > 100_000:
|
|
742
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
743
|
+
seen_source: set[str] = set()
|
|
744
|
+
for row in mappings:
|
|
745
|
+
if not isinstance(row, dict) or set(row) != {"source", "derived", "actions", "changed"}:
|
|
746
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
747
|
+
if (
|
|
748
|
+
type(row["changed"]) is not bool
|
|
749
|
+
or not isinstance(row["actions"], list)
|
|
750
|
+
or not all(isinstance(x, str) for x in row["actions"])
|
|
751
|
+
):
|
|
752
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
753
|
+
for side in ("source", "derived"):
|
|
754
|
+
ref = row[side]
|
|
755
|
+
if not isinstance(ref, dict) or set(ref) != {"path", "sha256", "size_bytes"}:
|
|
756
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
757
|
+
if (
|
|
758
|
+
not isinstance(ref["path"], str)
|
|
759
|
+
or CONTENT_PATH.fullmatch(ref["path"]) is None
|
|
760
|
+
or _HASH.fullmatch(str(ref["sha256"])) is None
|
|
761
|
+
or type(ref["size_bytes"]) is not int
|
|
762
|
+
or ref["size_bytes"] < 0
|
|
763
|
+
):
|
|
764
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
765
|
+
if CONTENT_PATH.fullmatch(ref["path"])[1] != ref["sha256"]:
|
|
766
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
767
|
+
if row["source"]["path"] in seen_source:
|
|
768
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
769
|
+
seen_source.add(row["source"]["path"])
|
|
770
|
+
if not isinstance(value["limitations"], list) or not all(
|
|
771
|
+
isinstance(x, str) for x in value["limitations"]
|
|
772
|
+
):
|
|
773
|
+
raise RedactedArchiveError("invalid_lineage")
|
|
774
|
+
return value
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def verify_redacted_archive(
|
|
778
|
+
derived_root: str | Path, *, source_root: str | Path | None = None
|
|
779
|
+
) -> dict[str, Any]:
|
|
780
|
+
root = Path(derived_root).expanduser().absolute()
|
|
781
|
+
try:
|
|
782
|
+
report_raw = _read_named_regular(root, "finalization.json", MAX_FINALIZATION_BYTES)
|
|
783
|
+
report = _strict_json(report_raw, MAX_FINALIZATION_BYTES)
|
|
784
|
+
except (ValueError, UnicodeError, RecursionError) as exc:
|
|
785
|
+
raise RedactedArchiveError("invalid_finalization") from exc
|
|
786
|
+
if summarize_finalization(report).get("state") != "complete":
|
|
787
|
+
raise RedactedArchiveError("derivative_incomplete")
|
|
788
|
+
integrity = audit_content_references(
|
|
789
|
+
root, max_index_bytes=MAX_INDEX_BYTES, max_content_bytes=MAX_CONTENT_BYTES
|
|
790
|
+
)
|
|
791
|
+
if integrity.get("state") != "complete":
|
|
792
|
+
raise RedactedArchiveError("derivative_incomplete")
|
|
793
|
+
for name in REQUIRED_EXPORTS:
|
|
794
|
+
if hash_export(root, name) != report.get("artifacts", {}).get(name):
|
|
795
|
+
raise RedactedArchiveError("derivative_primary_changed")
|
|
796
|
+
derivation = report.get("derivation")
|
|
797
|
+
if (
|
|
798
|
+
not isinstance(derivation, dict)
|
|
799
|
+
or set(derivation) != {"format", "lineage", "policy_sha256", "source_finalization_sha256"}
|
|
800
|
+
or derivation.get("format") != DERIVATIVE_FORMAT
|
|
801
|
+
or not _validate_fingerprint(derivation.get("lineage"))
|
|
802
|
+
or _HASH.fullmatch(str(derivation.get("policy_sha256"))) is None
|
|
803
|
+
or _HASH.fullmatch(str(derivation.get("source_finalization_sha256"))) is None
|
|
804
|
+
):
|
|
805
|
+
raise RedactedArchiveError("invalid_derivation_receipt")
|
|
806
|
+
lineage_raw = _read_named_regular(root, "lineage.json", MAX_LINEAGE_BYTES)
|
|
807
|
+
if _fingerprint(lineage_raw) != derivation["lineage"]:
|
|
808
|
+
raise RedactedArchiveError("lineage_hash_mismatch")
|
|
809
|
+
try:
|
|
810
|
+
lineage = _validate_lineage(_strict_json(lineage_raw, MAX_LINEAGE_BYTES))
|
|
811
|
+
except (ValueError, UnicodeError, RecursionError) as exc:
|
|
812
|
+
raise RedactedArchiveError("invalid_lineage") from exc
|
|
813
|
+
if lineage["policy"]["sha256"] != derivation["policy_sha256"]:
|
|
814
|
+
raise RedactedArchiveError("lineage_policy_mismatch")
|
|
815
|
+
current_primary = {name: hash_export(root, name) for name in REQUIRED_EXPORTS}
|
|
816
|
+
if lineage["derived"]["artifacts"] != current_primary:
|
|
817
|
+
raise RedactedArchiveError("lineage_derived_mismatch")
|
|
818
|
+
try:
|
|
819
|
+
_graph_fp, graph_raw = _integrity_read(root, "graph.json", MAX_INDEX_BYTES, collect=True)
|
|
820
|
+
graph = _strict_json(graph_raw, MAX_INDEX_BYTES)
|
|
821
|
+
except (ArchiveReadError, ValueError, UnicodeError, RecursionError) as exc:
|
|
822
|
+
raise RedactedArchiveError("invalid_derivative_index") from exc
|
|
823
|
+
marker = graph.get("redacted_derivative") if isinstance(graph, dict) else None
|
|
824
|
+
if (
|
|
825
|
+
not isinstance(marker, dict)
|
|
826
|
+
or marker.get("format") != DERIVATIVE_FORMAT
|
|
827
|
+
or marker.get("policy_sha256") != derivation["policy_sha256"]
|
|
828
|
+
or marker.get("lineage_file") != "lineage.json"
|
|
829
|
+
):
|
|
830
|
+
raise RedactedArchiveError("lineage_graph_marker_mismatch")
|
|
831
|
+
mapping_paths = set()
|
|
832
|
+
for row in lineage["mappings"]:
|
|
833
|
+
d = row["derived"]
|
|
834
|
+
fingerprint = integrity["verified_files"].get(d["path"])
|
|
835
|
+
if fingerprint != {"sha256": d["sha256"], "size_bytes": d["size_bytes"]}:
|
|
836
|
+
raise RedactedArchiveError("lineage_content_mismatch")
|
|
837
|
+
mapping_paths.add(d["path"])
|
|
838
|
+
if mapping_paths != set(integrity["verified_files"]):
|
|
839
|
+
raise RedactedArchiveError("lineage_content_inventory_mismatch")
|
|
840
|
+
if lineage["derived"]["content_file_count"] != len(mapping_paths):
|
|
841
|
+
raise RedactedArchiveError("lineage_content_inventory_mismatch")
|
|
842
|
+
|
|
843
|
+
source_state = "not_checked"
|
|
844
|
+
if source_root is not None:
|
|
845
|
+
source_path = Path(source_root).expanduser().absolute()
|
|
846
|
+
source_graph, source_conversations, source_report, source_final_raw, source_integrity = (
|
|
847
|
+
_load_source(source_path)
|
|
848
|
+
)
|
|
849
|
+
del source_graph, source_conversations, source_report
|
|
850
|
+
if (
|
|
851
|
+
_fingerprint(source_final_raw) != lineage["source"]["finalization"]
|
|
852
|
+
or hashlib.sha256(source_final_raw).hexdigest()
|
|
853
|
+
!= derivation["source_finalization_sha256"]
|
|
854
|
+
):
|
|
855
|
+
raise RedactedArchiveError("lineage_source_finalization_mismatch")
|
|
856
|
+
source_primary = {name: hash_export(source_path, name) for name in REQUIRED_EXPORTS}
|
|
857
|
+
if source_primary != lineage["source"]["artifacts"]:
|
|
858
|
+
raise RedactedArchiveError("lineage_source_artifact_mismatch")
|
|
859
|
+
if source_integrity["verified_file_count"] != lineage["source"]["content_file_count"]:
|
|
860
|
+
raise RedactedArchiveError("lineage_source_inventory_mismatch")
|
|
861
|
+
for row in lineage["mappings"]:
|
|
862
|
+
s = row["source"]
|
|
863
|
+
if source_integrity["verified_files"].get(s["path"]) != {
|
|
864
|
+
"sha256": s["sha256"],
|
|
865
|
+
"size_bytes": s["size_bytes"],
|
|
866
|
+
}:
|
|
867
|
+
raise RedactedArchiveError("lineage_source_content_mismatch")
|
|
868
|
+
source_state = "complete"
|
|
869
|
+
return {
|
|
870
|
+
"state": "complete",
|
|
871
|
+
"source_state": source_state,
|
|
872
|
+
"policy_sha256": derivation["policy_sha256"],
|
|
873
|
+
"mapping_count": len(lineage["mappings"]),
|
|
874
|
+
"derived_content_file_count": len(mapping_paths),
|
|
875
|
+
"lineage": derivation["lineage"],
|
|
876
|
+
"limitation": "Derivative integrity and lineage declarations are verified; anonymization, source authenticity and task correctness are not established.",
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def _main(argv: list[str] | None = None) -> int:
|
|
881
|
+
parser = argparse.ArgumentParser(
|
|
882
|
+
description="Create or verify a redacted ExecWeave derivative archive"
|
|
883
|
+
)
|
|
884
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
885
|
+
create = sub.add_parser("create")
|
|
886
|
+
create.add_argument("source")
|
|
887
|
+
create.add_argument("destination")
|
|
888
|
+
create.add_argument("--policy", required=True)
|
|
889
|
+
verify = sub.add_parser("verify")
|
|
890
|
+
verify.add_argument("derived")
|
|
891
|
+
verify.add_argument("--source")
|
|
892
|
+
args = parser.parse_args(argv)
|
|
893
|
+
try:
|
|
894
|
+
if args.command == "create":
|
|
895
|
+
result = create_redacted_archive(args.source, args.destination, args.policy)
|
|
896
|
+
else:
|
|
897
|
+
result = verify_redacted_archive(args.derived, source_root=args.source)
|
|
898
|
+
print(json.dumps(result, indent=2, sort_keys=True))
|
|
899
|
+
return 0
|
|
900
|
+
except (RedactedArchiveError, ArchiveReadError, ValueError, OSError) as exc:
|
|
901
|
+
print(json.dumps({"state": "failed", "code": str(exc)}), file=os.sys.stderr)
|
|
902
|
+
return 2
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
if __name__ == "__main__":
|
|
906
|
+
raise SystemExit(_main())
|