synth-code 0.0.1__py3-none-macosx_15_0_arm64.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 (110) hide show
  1. synth_code/__init__.py +0 -0
  2. synth_code/account.py +551 -0
  3. synth_code/account_http.py +86 -0
  4. synth_code/account_refusal.py +80 -0
  5. synth_code/accounting.py +148 -0
  6. synth_code/activity_grouping.py +149 -0
  7. synth_code/agent_panels.py +127 -0
  8. synth_code/approvals.py +397 -0
  9. synth_code/blobs.py +31 -0
  10. synth_code/cli.py +734 -0
  11. synth_code/client.py +413 -0
  12. synth_code/composer_delivery.py +139 -0
  13. synth_code/conversation.py +949 -0
  14. synth_code/daemon.py +34 -0
  15. synth_code/edition.py +306 -0
  16. synth_code/enrollment.py +304 -0
  17. synth_code/file_edit_facts.py +10 -0
  18. synth_code/freeze.py +234 -0
  19. synth_code/grant.py +59 -0
  20. synth_code/history.py +140 -0
  21. synth_code/history_generated.py +219 -0
  22. synth_code/history_wire.py +166 -0
  23. synth_code/image_input.py +109 -0
  24. synth_code/image_preview.py +105 -0
  25. synth_code/legacy_history.py +161 -0
  26. synth_code/live_turns.py +171 -0
  27. synth_code/model_picker.py +311 -0
  28. synth_code/native/manifest.json +1 -0
  29. synth_code/native/synth-code-runtime +0 -0
  30. synth_code/native.py +95 -0
  31. synth_code/oauth.py +284 -0
  32. synth_code/operator.py +116 -0
  33. synth_code/pack_source.py +65 -0
  34. synth_code/panel_request.py +291 -0
  35. synth_code/panels.py +40 -0
  36. synth_code/plugin_host.py +459 -0
  37. synth_code/protocol.py +35 -0
  38. synth_code/provider.py +313 -0
  39. synth_code/provider_fault.py +173 -0
  40. synth_code/provider_frames.py +571 -0
  41. synth_code/recommendation.py +324 -0
  42. synth_code/report.py +72 -0
  43. synth_code/research_events.py +44 -0
  44. synth_code/research_trace.py +449 -0
  45. synth_code/rex_view.py +58 -0
  46. synth_code/runtime_refusal.py +108 -0
  47. synth_code/schema/budgets.json +17 -0
  48. synth_code/schema/history-v2.json +1002 -0
  49. synth_code/session.py +291 -0
  50. synth_code/shoal.py +564 -0
  51. synth_code/side_panel.py +309 -0
  52. synth_code/skills.py +269 -0
  53. synth_code/slash.py +425 -0
  54. synth_code/source_view.py +135 -0
  55. synth_code/starter.json +13 -0
  56. synth_code/stdio.py +75 -0
  57. synth_code/stream.py +142 -0
  58. synth_code/subscriptions.py +267 -0
  59. synth_code/synth_authority.py +362 -0
  60. synth_code/synth_extra.py +32 -0
  61. synth_code/terminal.py +817 -0
  62. synth_code/terminal_journal.py +284 -0
  63. synth_code/terminal_layout.py +643 -0
  64. synth_code/terminal_surfaces.py +470 -0
  65. synth_code/terminal_viewport.py +125 -0
  66. synth_code/tool_render.py +86 -0
  67. synth_code/transcript_frames.py +212 -0
  68. synth_code/transcript_placement.py +63 -0
  69. synth_code/transcript_rows.py +456 -0
  70. synth_code/transport.py +243 -0
  71. synth_code/v001_history.py +468 -0
  72. synth_code/view.py +854 -0
  73. synth_code/views/__init__.py +93 -0
  74. synth_code/views/charts.py +196 -0
  75. synth_code/views/curses_adapter.py +116 -0
  76. synth_code/views/engine.py +170 -0
  77. synth_code/views/model.py +226 -0
  78. synth_code/views/primitives.py +270 -0
  79. synth_code/views/tiling.py +124 -0
  80. synth_code-0.0.1.dist-info/METADATA +50 -0
  81. synth_code-0.0.1.dist-info/RECORD +110 -0
  82. synth_code-0.0.1.dist-info/WHEEL +5 -0
  83. synth_code-0.0.1.dist-info/entry_points.txt +6 -0
  84. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
  85. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
  86. synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
  87. synth_code-0.0.1.dist-info/top_level.txt +2 -0
  88. synth_code_plugins/_sdk/__init__.py +19 -0
  89. synth_code_plugins/_sdk/callback_wire.py +240 -0
  90. synth_code_plugins/_sdk/callbacks.py +317 -0
  91. synth_code_plugins/_sdk/compliance.py +51 -0
  92. synth_code_plugins/_sdk/contracts.py +236 -0
  93. synth_code_plugins/_sdk/discovery.py +75 -0
  94. synth_code_plugins/_sdk/job_binding.py +71 -0
  95. synth_code_plugins/_sdk/lifecycle.py +50 -0
  96. synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
  97. synth_code_plugins/_sdk/manifest.py +269 -0
  98. synth_code_plugins/_sdk/pack.py +332 -0
  99. synth_code_plugins/_sdk/push.py +98 -0
  100. synth_code_plugins/_sdk/records.py +26 -0
  101. synth_code_plugins/_sdk/registry.py +491 -0
  102. synth_code_plugins/_sdk/schemas.py +210 -0
  103. synth_code_plugins/_sdk/sources.py +230 -0
  104. synth_code_plugins/_sdk/surfaces.py +54 -0
  105. synth_code_plugins/_sdk/tools.py +172 -0
  106. synth_code_plugins/_sdk/worker_memory.py +49 -0
  107. synth_code_plugins/core/SKILL.md +6 -0
  108. synth_code_plugins/core/__init__.py +21 -0
  109. synth_code_plugins/core/plugin.toml +44 -0
  110. synth_code_plugins/core/source.py +18 -0
@@ -0,0 +1,468 @@
1
+ """Convert a public v0.01 runtime store to the standalone, read-only transcript.
2
+
3
+ Public v0.01 (`synth-code` at 8b2265d, `crates/runtime/src/store.rs`) keeps one
4
+ private store directory:
5
+
6
+ * ``journal.sqlite`` (WAL, ``user_version=1``) with
7
+ ``streams(id TEXT PRIMARY KEY, head INTEGER)`` and
8
+ ``events(stream, sequence, body, digest)``. ``body`` is a serialized Temper
9
+ ``PersistenceEnvelope`` and ``digest`` is the SHA-256 hex of ``body``.
10
+ * ``artifacts/<sha256>``: immutable content-addressed payloads. Assistant replies
11
+ live here (``model_finish.display_ref``), not in the journal.
12
+ * ``owner.lock``: the runtime's exclusive flock. This reader never opens it.
13
+
14
+ The reader never opens the user's files for writing. It copies the database and
15
+ its WAL into a private temporary directory and reads the copy, so SQLite cannot
16
+ create ``-shm`` files or checkpoint inside the user's store. Integrity checks
17
+ mirror public ``SqliteStore::read_events``. Records this reader does not know are
18
+ shown as typed :class:`UnsupportedRecord` entries, never dropped.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ import json
25
+ import os
26
+ import shutil
27
+ import sqlite3
28
+ import tempfile
29
+ from collections import Counter
30
+ from collections.abc import Callable, Iterator, Mapping
31
+ from contextlib import closing
32
+ from dataclasses import dataclass, field
33
+ from enum import StrEnum
34
+ from pathlib import Path
35
+ from typing import TextIO
36
+
37
+ from .legacy_history import publish_archive, write_entry, write_header
38
+
39
+ __all__ = [
40
+ "ArtifactProblem",
41
+ "RecordKind",
42
+ "RefusalCode",
43
+ "UnsupportedReason",
44
+ "UnsupportedRecord",
45
+ "V001Conversion",
46
+ "V001Refusal",
47
+ "convert_v001",
48
+ ]
49
+
50
+ JOURNAL_STREAM = "local:Runtime:main"
51
+ EVENT_TYPE = "synth_code.event.v1"
52
+ _MAX_EVENT_BYTES = 64 * 1024
53
+ _MAX_EVENTS = 100_000
54
+ _MAX_ARTIFACT_BYTES = 8 * 1024 * 1024
55
+ _EVENT_COLUMNS = ("stream", "sequence", "body", "digest")
56
+ _STREAM_COLUMNS = ("id", "head")
57
+
58
+
59
+ class RecordKind(StrEnum):
60
+ """Every leaf record the public v0.01 runtime writes (domain.rs, turn.rs)."""
61
+
62
+ RECOVERED = "recovered"
63
+ CONFIGURE_PERMISSIONS = "configure_permissions"
64
+ CONFIGURE_INFERENCE = "configure_inference"
65
+ START = "start"
66
+ ADMIT = "admit"
67
+ ADMIT_EDIT = "admit_edit"
68
+ ADMIT_SHELL = "admit_shell"
69
+ AGENT_START = "agent.start"
70
+ AGENT_MODEL_BEGIN = "agent.model_begin"
71
+ AGENT_MODEL_FINISH = "agent.model_finish"
72
+ AGENT_TOOL_RESULT = "agent.tool_result"
73
+ AGENT_FINISH = "agent.finish"
74
+ APPROVE = "approve"
75
+ CANCEL = "cancel"
76
+ RECONCILE = "reconcile"
77
+ DISPATCH = "dispatch"
78
+ SETTLE = "settle"
79
+ MARK_UNKNOWN = "mark_unknown"
80
+
81
+
82
+ class RefusalCode(StrEnum):
83
+ STORE_MISSING = "store_missing"
84
+ NOT_V001_STORE = "not_v001_store"
85
+ UNSUPPORTED_SCHEMA = "unsupported_schema"
86
+ CORRUPT_DATABASE = "corrupt_database"
87
+ INTEGRITY_FAILURE = "integrity_failure"
88
+ OUTPUT_EXISTS = "output_exists"
89
+ OUTPUT_INSIDE_STORE = "output_inside_store"
90
+ OUTPUT_PARENT_MISSING = "output_parent_missing"
91
+
92
+
93
+ class UnsupportedReason(StrEnum):
94
+ UNKNOWN_STREAM = "unknown_stream"
95
+ UNKNOWN_EVENT_TYPE = "unknown_event_type"
96
+ UNKNOWN_EVENT = "unknown_event"
97
+ UNKNOWN_COMMAND = "unknown_command"
98
+ UNKNOWN_TURN_COMMAND = "unknown_turn_command"
99
+
100
+
101
+ class ArtifactProblem(StrEnum):
102
+ INVALID_REFERENCE = "invalid_reference"
103
+ MISSING = "missing"
104
+ INVALID_FILE = "invalid_file"
105
+ INTEGRITY_FAILURE = "integrity_failure"
106
+ NOT_TEXT = "not_text"
107
+
108
+
109
+ class V001Refusal(Exception):
110
+ """The store cannot be converted. No output file is left behind."""
111
+
112
+ def __init__(self, code: RefusalCode, detail: str) -> None:
113
+ super().__init__(f"{code.value}: {detail}")
114
+ self.code = code
115
+ self.detail = detail
116
+
117
+
118
+ @dataclass(frozen=True, slots=True)
119
+ class UnsupportedRecord:
120
+ stream: str
121
+ sequence: int
122
+ reason: UnsupportedReason
123
+ label: str
124
+
125
+
126
+ @dataclass(frozen=True, slots=True)
127
+ class V001Conversion:
128
+ rows: int
129
+ unreadable: int
130
+ unsupported: tuple[UnsupportedRecord, ...]
131
+ kinds: Mapping[RecordKind, int] = field(default_factory=dict)
132
+
133
+
134
+ class _Malformed(ValueError):
135
+ """A known record whose fields do not match the public schema."""
136
+
137
+
138
+ class _ArtifactUnreadable(Exception):
139
+ def __init__(self, problem: ArtifactProblem, reference: str) -> None:
140
+ super().__init__(f"{problem.value}: {reference}")
141
+ self.problem = problem
142
+
143
+
144
+ def _text(data: Mapping[str, object], key: str) -> str:
145
+ value = data.get(key)
146
+ if not isinstance(value, str):
147
+ raise _Malformed(f"invalid text field {key}")
148
+ return value
149
+
150
+
151
+ def _optional_text(data: Mapping[str, object], key: str) -> str | None:
152
+ value = data.get(key)
153
+ if value is not None and not isinstance(value, str):
154
+ raise _Malformed(f"invalid optional text field {key}")
155
+ return value
156
+
157
+
158
+ def _integer(data: Mapping[str, object], key: str) -> int:
159
+ value = data.get(key)
160
+ if not isinstance(value, int) or isinstance(value, bool):
161
+ raise _Malformed(f"invalid integer field {key}")
162
+ return value
163
+
164
+
165
+ def _flag(data: Mapping[str, object], key: str) -> bool:
166
+ value = data.get(key)
167
+ if not isinstance(value, bool):
168
+ raise _Malformed(f"invalid boolean field {key}")
169
+ return value
170
+
171
+
172
+ def _mapping(value: object, key: str) -> Mapping[str, object]:
173
+ if not isinstance(value, dict):
174
+ raise _Malformed(f"invalid object field {key}")
175
+ return value
176
+
177
+
178
+ class _Artifacts:
179
+ def __init__(self, root: Path) -> None:
180
+ self._root = root
181
+
182
+ def text(self, reference: str) -> str:
183
+ if len(reference) != 64 or any(c not in "0123456789abcdef" for c in reference):
184
+ raise _ArtifactUnreadable(ArtifactProblem.INVALID_REFERENCE, reference)
185
+ try:
186
+ descriptor = os.open(self._root / reference, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
187
+ except FileNotFoundError as error:
188
+ raise _ArtifactUnreadable(ArtifactProblem.MISSING, reference) from error
189
+ except OSError as error:
190
+ raise _ArtifactUnreadable(ArtifactProblem.INVALID_FILE, reference) from error
191
+ with os.fdopen(descriptor, "rb") as file:
192
+ status = os.fstat(file.fileno())
193
+ if not os.path.isfile(self._root / reference) or status.st_size > _MAX_ARTIFACT_BYTES:
194
+ raise _ArtifactUnreadable(ArtifactProblem.INVALID_FILE, reference)
195
+ data = file.read(_MAX_ARTIFACT_BYTES + 1)
196
+ if hashlib.sha256(data).hexdigest() != reference:
197
+ raise _ArtifactUnreadable(ArtifactProblem.INTEGRITY_FAILURE, reference)
198
+ try:
199
+ return data.decode("utf-8")
200
+ except UnicodeDecodeError as error:
201
+ raise _ArtifactUnreadable(ArtifactProblem.NOT_TEXT, reference) from error
202
+
203
+
204
+ _Entries = Iterator[tuple[str, str]]
205
+ _Renderer = Callable[[Mapping[str, object], _Artifacts], _Entries]
206
+
207
+
208
+ def _recovered(data: Mapping[str, object], _: _Artifacts) -> _Entries:
209
+ yield "Runtime recovered", f"epoch {_integer(data, 'epoch')}"
210
+
211
+
212
+ def _configure_permissions(data: Mapping[str, object], _: _Artifacts) -> _Entries:
213
+ _text(data, "session")
214
+ yield "Permissions", _text(data, "mode")
215
+
216
+
217
+ def _configure_inference(data: Mapping[str, object], _: _Artifacts) -> _Entries:
218
+ selection = _mapping(data.get("selection"), "selection")
219
+ provider, model, effort = (_text(selection, key) for key in ("provider", "model", "effort"))
220
+ yield "Model", f"{provider} / {model} · effort {effort}"
221
+
222
+
223
+ def _start(data: Mapping[str, object], _: _Artifacts) -> _Entries:
224
+ yield f"Session {_text(data, 'session')}", _text(data, "workspace")
225
+
226
+
227
+ def _admit(data: Mapping[str, object], _: _Artifacts) -> _Entries:
228
+ _text(data, "operation")
229
+ yield "Request", _text(data, "text")
230
+
231
+
232
+ def _admit_edit(data: Mapping[str, object], _: _Artifacts) -> _Entries:
233
+ request = _mapping(data.get("request"), "request")
234
+ yield "Edit requested", f"{_text(request, 'path')}\n{_text(request, 'content')}"
235
+
236
+
237
+ def _admit_shell(data: Mapping[str, object], _: _Artifacts) -> _Entries:
238
+ request = _mapping(data.get("request"), "request")
239
+ yield "Command requested", _text(request, "command")
240
+
241
+
242
+ def _agent_start(data: Mapping[str, object], _: _Artifacts) -> _Entries:
243
+ _text(data, "session")
244
+ yield "User", _text(data, "prompt")
245
+
246
+
247
+ def _bookkeeping(*fields: str) -> _Renderer:
248
+ """Known records that carry no transcript text; their fields are still checked."""
249
+
250
+ def render(data: Mapping[str, object], _: _Artifacts) -> _Entries:
251
+ for key in fields:
252
+ _text(data, key)
253
+ yield from ()
254
+
255
+ return render
256
+
257
+
258
+ def _agent_model_finish(data: Mapping[str, object], artifacts: _Artifacts) -> _Entries:
259
+ _text(data, "message_ref")
260
+ model = _optional_text(data, "provider_model")
261
+ yield (f"Assistant · {model}" if model else "Assistant"), artifacts.text(_text(data, "display_ref"))
262
+
263
+
264
+ def _agent_finish(data: Mapping[str, object], _: _Artifacts) -> _Entries:
265
+ phase = _text(data, "phase")
266
+ error = _optional_text(data, "error")
267
+ yield "Turn finished", phase if error is None else f"{phase}: {error}"
268
+
269
+
270
+ def _approve(data: Mapping[str, object], _: _Artifacts) -> _Entries:
271
+ verdict = "allowed" if _flag(data, "allow") else "denied"
272
+ yield "Approval", f"{verdict} {_text(data, 'operation')}"
273
+
274
+
275
+ def _cancel(data: Mapping[str, object], _: _Artifacts) -> _Entries:
276
+ yield "Canceled", _text(data, "operation")
277
+
278
+
279
+ def _reconcile(data: Mapping[str, object], _: _Artifacts) -> _Entries:
280
+ yield "Reconciled", _text(data, "observation")
281
+
282
+
283
+ def _settle(data: Mapping[str, object], _: _Artifacts) -> _Entries:
284
+ _text(data, "operation")
285
+ status = "succeeded" if _flag(data, "success") else "failed"
286
+ outcome = _mapping(data.get("outcome"), "outcome")
287
+ yield f"Operation {status}", json.dumps(outcome, indent=1, sort_keys=True, ensure_ascii=False)
288
+
289
+
290
+ def _mark_unknown(data: Mapping[str, object], _: _Artifacts) -> _Entries:
291
+ yield "Outcome unknown", _text(data, "reason")
292
+
293
+
294
+ _RENDER: Mapping[RecordKind, _Renderer] = {
295
+ RecordKind.RECOVERED: _recovered,
296
+ RecordKind.CONFIGURE_PERMISSIONS: _configure_permissions,
297
+ RecordKind.CONFIGURE_INFERENCE: _configure_inference,
298
+ RecordKind.START: _start,
299
+ RecordKind.ADMIT: _admit,
300
+ RecordKind.ADMIT_EDIT: _admit_edit,
301
+ RecordKind.ADMIT_SHELL: _admit_shell,
302
+ RecordKind.AGENT_START: _agent_start,
303
+ RecordKind.AGENT_MODEL_BEGIN: _bookkeeping("turn", "attempt", "request_ref"),
304
+ RecordKind.AGENT_MODEL_FINISH: _agent_model_finish,
305
+ RecordKind.AGENT_TOOL_RESULT: _bookkeeping("turn", "message_ref"),
306
+ RecordKind.AGENT_FINISH: _agent_finish,
307
+ RecordKind.APPROVE: _approve,
308
+ RecordKind.CANCEL: _cancel,
309
+ RecordKind.RECONCILE: _reconcile,
310
+ RecordKind.DISPATCH: _bookkeeping("operation"),
311
+ RecordKind.SETTLE: _settle,
312
+ RecordKind.MARK_UNKNOWN: _mark_unknown,
313
+ }
314
+ if set(_RENDER) != set(RecordKind): # pragma: no cover - import-time exhaustiveness guard
315
+ raise RuntimeError(f"v0.01 record kinds without a renderer: {sorted(set(RecordKind) - set(_RENDER))}")
316
+
317
+ _COMMANDS = {kind.value: kind for kind in RecordKind if "." not in kind.value and kind != RecordKind.RECOVERED}
318
+ _TURN_COMMANDS = {kind.value.removeprefix("agent."): kind for kind in RecordKind if kind.value.startswith("agent.")}
319
+
320
+
321
+ @dataclass(frozen=True, slots=True)
322
+ class _Known:
323
+ kind: RecordKind
324
+ data: Mapping[str, object]
325
+
326
+
327
+ def _classify(stream: str, sequence: int, envelope: Mapping[str, object]) -> _Known | UnsupportedRecord:
328
+ def unsupported(reason: UnsupportedReason, label: object) -> UnsupportedRecord:
329
+ return UnsupportedRecord(stream, sequence, reason, str(label))
330
+
331
+ if stream != JOURNAL_STREAM:
332
+ return unsupported(UnsupportedReason.UNKNOWN_STREAM, stream)
333
+ event_type = envelope.get("event_type")
334
+ if event_type != EVENT_TYPE:
335
+ return unsupported(UnsupportedReason.UNKNOWN_EVENT_TYPE, event_type)
336
+ event = _mapping(envelope.get("payload"), "payload")
337
+ tag = event.get("type")
338
+ if tag == RecordKind.RECOVERED.value:
339
+ return _Known(RecordKind.RECOVERED, event)
340
+ if tag != "accepted":
341
+ return unsupported(UnsupportedReason.UNKNOWN_EVENT, tag)
342
+ mutation = _mapping(event.get("mutation"), "mutation")
343
+ command = _mapping(mutation.get("command"), "command")
344
+ command_tag = command.get("type")
345
+ if command_tag == "agent":
346
+ request = _mapping(command.get("request"), "request")
347
+ turn_tag = request.get("type")
348
+ if not isinstance(turn_tag, str) or turn_tag not in _TURN_COMMANDS:
349
+ return unsupported(UnsupportedReason.UNKNOWN_TURN_COMMAND, f"agent.{turn_tag}")
350
+ return _Known(_TURN_COMMANDS[turn_tag], request)
351
+ if not isinstance(command_tag, str) or command_tag not in _COMMANDS:
352
+ return unsupported(UnsupportedReason.UNKNOWN_COMMAND, command_tag)
353
+ return _Known(_COMMANDS[command_tag], command)
354
+
355
+
356
+ @dataclass(frozen=True, slots=True)
357
+ class _Row:
358
+ stream: str
359
+ sequence: int
360
+ envelope: Mapping[str, object]
361
+
362
+
363
+ def _columns(db: sqlite3.Connection, table: str) -> tuple[str, ...]:
364
+ return tuple(row[1] for row in db.execute(f"PRAGMA table_info({table})"))
365
+
366
+
367
+ def _verified_rows(db: sqlite3.Connection) -> tuple[_Row, ...]:
368
+ """Mirror public `SqliteStore::read_events` for every stream in the store."""
369
+ (version,) = db.execute("PRAGMA user_version").fetchone()
370
+ events, streams = _columns(db, "events"), _columns(db, "streams")
371
+ if events != _EVENT_COLUMNS or streams != _STREAM_COLUMNS:
372
+ hint = "; a beta v1 journal converts with convert-v1-history" if "run" in events else ""
373
+ raise V001Refusal(RefusalCode.NOT_V001_STORE, f"events{events} streams{streams}{hint}")
374
+ if version != 1:
375
+ raise V001Refusal(RefusalCode.UNSUPPORTED_SCHEMA, f"user_version={version}")
376
+ heads = {stream: head for stream, head in db.execute("SELECT id, head FROM streams")}
377
+ rows: list[_Row] = []
378
+ counts: Counter[str] = Counter()
379
+ for stream, sequence, body, digest in db.execute(
380
+ "SELECT stream, sequence, body, digest FROM events ORDER BY stream, sequence"
381
+ ):
382
+ counts[stream] += 1
383
+ position = counts[stream]
384
+ if (
385
+ not isinstance(body, str)
386
+ or sequence != position
387
+ or position > _MAX_EVENTS
388
+ or len(body.encode()) > _MAX_EVENT_BYTES
389
+ or hashlib.sha256(body.encode()).hexdigest() != digest
390
+ ):
391
+ raise V001Refusal(RefusalCode.INTEGRITY_FAILURE, f"{stream} at sequence {sequence}")
392
+ try:
393
+ envelope = _mapping(json.loads(body), "envelope")
394
+ except ValueError as error:
395
+ raise V001Refusal(RefusalCode.INTEGRITY_FAILURE, f"{stream} at sequence {sequence}: {error}") from error
396
+ if envelope.get("sequence_nr") != sequence:
397
+ raise V001Refusal(RefusalCode.INTEGRITY_FAILURE, f"envelope sequence mismatch at {stream}:{sequence}")
398
+ rows.append(_Row(stream, sequence, envelope))
399
+ for stream in heads.keys() | counts.keys():
400
+ if heads.get(stream) != counts[stream]:
401
+ raise V001Refusal(RefusalCode.INTEGRITY_FAILURE, f"head mismatch for {stream}")
402
+ return tuple(rows)
403
+
404
+
405
+ def _render(rows: tuple[_Row, ...], artifacts: _Artifacts, title: str, output: TextIO) -> V001Conversion:
406
+ write_header(output, title)
407
+ written = unreadable = 0
408
+ unsupported: list[UnsupportedRecord] = []
409
+ kinds: Counter[RecordKind] = Counter()
410
+ for row in rows:
411
+ position = f"{row.stream}:{row.sequence}"
412
+ try:
413
+ known = _classify(row.stream, row.sequence, row.envelope)
414
+ if isinstance(known, UnsupportedRecord):
415
+ unsupported.append(known)
416
+ entries: tuple[tuple[str, str], ...] = (
417
+ (f"Unsupported record · {known.reason.value}", f"{known.label} at {position}"),
418
+ )
419
+ else:
420
+ entries = tuple(_RENDER[known.kind](known.data, artifacts))
421
+ kinds[known.kind] += 1
422
+ except _Malformed as error:
423
+ entries = (("Unreadable event", f"{position}: {error}"),)
424
+ unreadable += 1
425
+ except _ArtifactUnreadable as error:
426
+ entries = (("Unreadable artifact", f"{position}: {error}"),)
427
+ unreadable += 1
428
+ for speaker, body in entries:
429
+ write_entry(output, position, speaker, body)
430
+ written += 1
431
+ return V001Conversion(written, unreadable, tuple(unsupported), dict(kinds))
432
+
433
+
434
+ def _snapshot(journal: Path, workspace: Path) -> Path:
435
+ """Copy the database and its WAL so SQLite never touches the user's store."""
436
+ copy = workspace / "journal.sqlite"
437
+ shutil.copyfile(journal, copy)
438
+ wal = journal.with_name(journal.name + "-wal")
439
+ if wal.is_file():
440
+ shutil.copyfile(wal, workspace / "journal.sqlite-wal")
441
+ return copy
442
+
443
+
444
+ def convert_v001(store: Path, destination: Path) -> V001Conversion:
445
+ """Publish an owner-readable HTML transcript of a public v0.01 store."""
446
+ journal = store / "journal.sqlite"
447
+ if not store.is_dir() or not journal.is_file() or journal.is_symlink():
448
+ raise V001Refusal(RefusalCode.STORE_MISSING, str(store))
449
+ if os.path.lexists(destination):
450
+ raise V001Refusal(RefusalCode.OUTPUT_EXISTS, str(destination))
451
+ if not destination.parent.is_dir():
452
+ raise V001Refusal(RefusalCode.OUTPUT_PARENT_MISSING, str(destination.parent))
453
+ if destination.parent.resolve().is_relative_to(store.resolve()):
454
+ raise V001Refusal(RefusalCode.OUTPUT_INSIDE_STORE, str(destination))
455
+ with tempfile.TemporaryDirectory(prefix="v001-snapshot-") as workspace:
456
+ copy = _snapshot(journal, Path(workspace))
457
+ try:
458
+ with closing(sqlite3.connect(copy)) as db:
459
+ db.execute("PRAGMA query_only=1")
460
+ db.execute("BEGIN")
461
+ rows = _verified_rows(db)
462
+ except sqlite3.DatabaseError as error:
463
+ raise V001Refusal(RefusalCode.CORRUPT_DATABASE, str(error)) from error
464
+ artifacts = _Artifacts(store / "artifacts")
465
+ try:
466
+ return publish_archive(destination, lambda output: _render(rows, artifacts, store.name, output))
467
+ except FileExistsError as error:
468
+ raise V001Refusal(RefusalCode.OUTPUT_EXISTS, str(destination)) from error