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,166 @@
1
+ """Validate authority and sequence boundaries of the generated history contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from functools import cache
8
+ from importlib.resources import files
9
+ from typing import cast
10
+
11
+ from jsonschema import Draft7Validator, ValidationError
12
+
13
+ from .blobs import read_blob
14
+ from .history_generated import SCHEMA_SHA256, DurableEvent, HistorySnapshot, InputPart
15
+
16
+ __all__ = ["input_text", "message_text", "read_event", "read_history", "read_scoped_event"]
17
+
18
+
19
+ def input_text(parts: list[InputPart]) -> str:
20
+ """Render text parts and show attachment size without fetching attachment contents."""
21
+ return "\n".join(
22
+ part["text"] if part["type"] == "text" else f"[Text attachment: {part['bytes']} bytes]"
23
+ for part in parts
24
+ )
25
+
26
+
27
+ def message_text(client, payload: dict) -> str:
28
+ """Resolve one durable message's inline text or run-scoped content reference."""
29
+ text = payload.get("text")
30
+ if isinstance(text, str):
31
+ return text
32
+ reference = payload["text_ref"]
33
+ if type(reference["bytes"]) is not int or not 0 < reference["bytes"] <= 1_048_576:
34
+ raise ValueError("Message text reference exceeds the Engine v2 text budget")
35
+ return read_blob(client, reference).decode("utf-8")
36
+
37
+
38
+ def _event_envelope(raw: object, run: str) -> dict:
39
+ if not isinstance(raw, dict):
40
+ raise ConnectionError("Invalid durable journal event")
41
+ sequence = raw.get("seq")
42
+ if (
43
+ raw.get("schema") != "synth-code.v2"
44
+ or raw.get("version") != 2
45
+ or raw.get("run") != run
46
+ or type(sequence) is not int
47
+ or sequence < 1
48
+ or raw.get("id") != f"{run}/{sequence}"
49
+ or raw.get("event_id") != raw["id"]
50
+ or not isinstance(raw.get("kind"), str)
51
+ or not isinstance(raw.get("payload"), dict)
52
+ ):
53
+ raise ConnectionError(f"Invalid Engine v2 journal event for run {run} at {sequence}")
54
+ return raw
55
+
56
+
57
+ def read_scoped_event(raw: object, run: str) -> dict:
58
+ """Read a run-scoped projection without accepting owner metadata."""
59
+ event = _event_envelope(raw, run)
60
+ if (
61
+ any(name not in event or event[name] is not None for name in ("actor", "turn", "operation"))
62
+ or any(
63
+ name in event
64
+ for name in ("actor_ref", "subject", "cause_ref", "links", "history_change")
65
+ )
66
+ ):
67
+ raise ConnectionError(f"Invalid scoped journal event for run {run} at {event['seq']}")
68
+ return event
69
+
70
+
71
+ def read_event(raw: object, run: str) -> DurableEvent:
72
+ event = _event_envelope(raw, run)
73
+ sequence = event["seq"]
74
+ if (
75
+ not isinstance(event.get("actor"), str)
76
+ or not isinstance(event.get("actor_ref"), dict)
77
+ or not isinstance(event.get("subject"), dict)
78
+ or not isinstance(event.get("cause_ref"), dict)
79
+ ):
80
+ raise ConnectionError(f"Invalid Engine v2 journal event for run {run} at {sequence}")
81
+ change = event.get("history_change")
82
+ if change is not None and (not isinstance(change, dict) or change.get("cursor") != sequence):
83
+ raise ConnectionError(f"Invalid history change for run {run} at {sequence}")
84
+ return cast(DurableEvent, event)
85
+
86
+
87
+ @cache
88
+ def _snapshot_schema() -> Draft7Validator:
89
+ data = files("synth_code").joinpath("schema/history-v2.json").read_bytes()
90
+ if hashlib.sha256(data).hexdigest() != SCHEMA_SHA256:
91
+ raise ConnectionError("Engine v2 history schema and models disagree")
92
+ return Draft7Validator(json.loads(data))
93
+
94
+
95
+ def read_history(
96
+ raw: object,
97
+ run: str,
98
+ *,
99
+ at: int | None = None,
100
+ before: int | None = None,
101
+ ) -> HistorySnapshot:
102
+ try:
103
+ _snapshot_schema().validate(raw)
104
+ except ValidationError as error:
105
+ location = ".".join(map(str, error.absolute_path))
106
+ raise ConnectionError(
107
+ f"Invalid Engine v2 history snapshot for run {run} at {location}"
108
+ ) from error
109
+ if not isinstance(raw, dict) or raw["run"] != run:
110
+ raise ConnectionError(f"Engine v2 history snapshot belongs to a different run than {run}")
111
+ cursor = raw.get("cursor")
112
+ if type(cursor) is not int or cursor < 0 or (at is not None and at != cursor):
113
+ raise ConnectionError(f"Invalid history snapshot cursor for run {run}")
114
+ upper = cursor if before is None else min(cursor, before - 1)
115
+ for collection in ("rows", "active_turns", "approvals", "transcript", "open_tools"):
116
+ rows = raw.get(collection)
117
+ if not isinstance(rows, list):
118
+ raise ConnectionError(f"Invalid history snapshot {collection} for run {run}")
119
+ previous = 0
120
+ for row in rows:
121
+ if collection in ("rows", "active_turns", "approvals"):
122
+ read_event(row, run)
123
+ if not isinstance(row, dict) or type(row.get("seq")) is not int:
124
+ raise ConnectionError(f"Invalid history row in {collection} for run {run}")
125
+ limit = upper if collection in ("rows", "transcript") else cursor
126
+ if not previous < row["seq"] <= limit:
127
+ raise ConnectionError(f"Out-of-order history row in {collection} for run {run}")
128
+ previous = row["seq"]
129
+ anchors = {
130
+ row["seq"]: row["kind"]
131
+ for row in raw["rows"]
132
+ if row["kind"]
133
+ in ("input.received", "message.completed", "tool.started", "reasoning.summary")
134
+ }
135
+ transcript = {
136
+ block["seq"]: {
137
+ "input": "input.received",
138
+ "message": "message.completed",
139
+ "tool": "tool.started",
140
+ "reasoning": "reasoning.summary",
141
+ }[block["kind"]]
142
+ for block in raw["transcript"]
143
+ }
144
+ if anchors != transcript:
145
+ raise ConnectionError(f"Transcript anchors disagree with the history page for run {run}")
146
+ older = raw.get("before")
147
+ if older is not None and (
148
+ type(older) is not int or not raw["rows"] or older != raw["rows"][0]["seq"]
149
+ ):
150
+ raise ConnectionError(f"Invalid history pagination cursor for run {run}")
151
+ return cast(HistorySnapshot, raw)
152
+
153
+
154
+ def steering_request(event):
155
+ payload = event["payload"]
156
+ return event["kind"] == "core.steer.requested" or (
157
+ event["kind"] == "input.received" and payload.get("delivery") == "turn_only"
158
+ )
159
+
160
+
161
+ def steering_receipt(event):
162
+ payload = event["payload"]
163
+ return event["kind"] == "core.steer.receipt" or (
164
+ event["kind"] in {"input.steered", "input.not_delivered", "input.quarantined"}
165
+ and payload.get("delivery") == "turn_only"
166
+ )
@@ -0,0 +1,109 @@
1
+ """Attach a local image to a Core turn without putting its bytes in the journal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import stat
9
+ from pathlib import Path
10
+ from tempfile import NamedTemporaryFile
11
+
12
+ from .panel_request import STATE_ENV
13
+
14
+ __all__ = ["image_draft", "is_slash_command", "retain_image", "turn_image"]
15
+
16
+ MAX_IMAGE_BYTES = 10 * 1024 * 1024
17
+ IMAGE_FORMATS = (".jpeg", ".jpg", ".png", ".webp")
18
+ IMAGE_PATH = re.compile(
19
+ r"""(?<!\S)(['"]?)(?P<path>(?:/|~/|\./)[^\r\n]*?\.(?:jpe?g|png|webp))(?!/)\1""",
20
+ re.IGNORECASE,
21
+ )
22
+
23
+
24
+ def image_draft(text: str) -> tuple[Path, str] | None:
25
+ match = IMAGE_PATH.search(text)
26
+ if match is None:
27
+ return None
28
+ raw_path = match["path"]
29
+ if not match[1]:
30
+ raw_path = re.sub(r"\\(.)", r"\1", raw_path)
31
+ caption = " ".join(
32
+ part
33
+ for part in (text[: match.start()].rstrip(), text[match.end() :].lstrip())
34
+ if part
35
+ )
36
+ return Path(raw_path).expanduser(), caption
37
+
38
+
39
+ def is_slash_command(text: str) -> bool:
40
+ if not text.startswith("/"):
41
+ return False
42
+ head = text.split(maxsplit=1)[0]
43
+ return "/" not in head[1:] and IMAGE_PATH.match(head) is None
44
+
45
+
46
+ def _image_key(run: str, turn: str) -> str:
47
+ return hashlib.sha256(f"{run}\0{turn}".encode()).hexdigest()
48
+
49
+
50
+ def _image_bytes(source: Path) -> bytes:
51
+ fd = os.open(source, os.O_RDONLY | os.O_NONBLOCK)
52
+ with os.fdopen(fd, "rb") as handle:
53
+ if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
54
+ raise ValueError("Image attachment must be a regular file")
55
+ data = handle.read(MAX_IMAGE_BYTES + 1)
56
+ if len(data) > MAX_IMAGE_BYTES:
57
+ raise ValueError("Image attachment exceeds 10 MiB")
58
+ signatures = {
59
+ ".png": data.startswith(b"\x89PNG\r\n\x1a\n"),
60
+ ".jpg": data.startswith(b"\xff\xd8\xff"),
61
+ ".jpeg": data.startswith(b"\xff\xd8\xff"),
62
+ ".webp": data.startswith(b"RIFF") and data[8:12] == b"WEBP",
63
+ }
64
+ if not signatures[source.suffix.lower()]:
65
+ raise ValueError("Image contents do not match the file extension")
66
+ return data
67
+
68
+
69
+ def retain_image(state: Path, run: str, turn: str, source: Path) -> None:
70
+ try:
71
+ data = _image_bytes(source)
72
+ except OSError as error:
73
+ raise ValueError(
74
+ f"Cannot read image {source.name}: {error.strerror}"
75
+ ) from error
76
+ directory = state / "attachments"
77
+ directory.mkdir(mode=0o700, exist_ok=True)
78
+ key = _image_key(run, turn)
79
+ target = directory / (key + source.suffix.lower())
80
+ with NamedTemporaryFile(dir=directory) as staging:
81
+ staging.write(data)
82
+ staging.flush()
83
+ try:
84
+ os.link(staging.name, target)
85
+ except FileExistsError:
86
+ if _image_bytes(target) != data:
87
+ raise ValueError(
88
+ "This pending message already has a different image"
89
+ ) from None
90
+
91
+
92
+ def turn_image(request: dict) -> Path | None:
93
+ state = os.environ.get(STATE_ENV)
94
+ if not state or request.get("role") != "core":
95
+ return None
96
+ identity = request["identity"].rsplit("/", 3)
97
+ if len(identity) != 4 or identity[1] != "core":
98
+ return None
99
+ run, _, turn, _ = identity
100
+ directory = Path(state) / "attachments"
101
+ key = _image_key(run, turn)
102
+ return next(
103
+ (
104
+ path
105
+ for suffix in IMAGE_FORMATS
106
+ if (path := directory / (key + suffix)).is_file()
107
+ ),
108
+ None,
109
+ )
@@ -0,0 +1,105 @@
1
+ """Show a bounded preview of a local image before sending it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import stat
6
+ import struct
7
+ import subprocess
8
+ from functools import lru_cache
9
+ from pathlib import Path
10
+ from tempfile import TemporaryDirectory
11
+
12
+ from .image_input import IMAGE_PATH, MAX_IMAGE_BYTES, image_draft, is_slash_command
13
+
14
+ __all__ = ["IMAGE_LABEL", "draft_image_span", "preview_draft"]
15
+
16
+ IMAGE_LABEL = "[Image #1]"
17
+ PREVIEW_WIDTH = 24
18
+ PREVIEW_HEIGHT = 8
19
+ SIPS = Path("/usr/bin/sips")
20
+
21
+
22
+ def draft_image_span(draft: str) -> tuple[int, int] | None:
23
+ match = IMAGE_PATH.search(draft)
24
+ return match.span() if match and not is_slash_command(draft) else None
25
+
26
+
27
+ def preview_draft(
28
+ draft: str, caret: int, state: Path, rows: int
29
+ ) -> tuple[str, int, tuple[tuple[int, ...], ...]]:
30
+ span = draft_image_span(draft)
31
+ if span is None:
32
+ return draft, caret, ()
33
+ attachment = image_draft(draft)
34
+ assert attachment is not None
35
+ source, _ = attachment
36
+ start, end = span
37
+ spacer = " " if draft[end:] and not draft[end].isspace() else ""
38
+ label = IMAGE_LABEL + spacer
39
+ if caret > end:
40
+ caret += len(label) - (end - start)
41
+ elif caret > start:
42
+ caret = start + len(label)
43
+ display = draft[:start] + label + draft[end:]
44
+ return display, caret, _preview(source, state)[:rows] if rows else ()
45
+
46
+
47
+ def _preview(source: Path, state: Path) -> tuple[tuple[int, ...], ...]:
48
+ if not SIPS.is_file():
49
+ return ()
50
+ try:
51
+ info = source.stat()
52
+ except OSError:
53
+ return ()
54
+ if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_IMAGE_BYTES:
55
+ return ()
56
+ return _raster(source.absolute(), state, info.st_mtime_ns, info.st_size)
57
+
58
+
59
+ @lru_cache(maxsize=16)
60
+ def _raster(
61
+ source: Path, state: Path, modified: int, size: int
62
+ ) -> tuple[tuple[int, ...], ...]:
63
+ try:
64
+ with TemporaryDirectory(dir=state) as directory:
65
+ bitmap = Path(directory) / "thumbnail.bmp"
66
+ subprocess.run(
67
+ [SIPS, "-Z", "48", "-s", "format", "bmp", source, "--out", bitmap],
68
+ stdout=subprocess.DEVNULL,
69
+ stderr=subprocess.DEVNULL,
70
+ timeout=1,
71
+ check=True,
72
+ )
73
+ return _cells(bitmap.read_bytes())
74
+ except (OSError, subprocess.SubprocessError, ValueError):
75
+ return ()
76
+
77
+
78
+ def _cells(bitmap: bytes) -> tuple[tuple[int, ...], ...]:
79
+ if len(bitmap) < 54 or bitmap[:2] != b"BM":
80
+ raise ValueError("Invalid thumbnail bitmap")
81
+ offset = struct.unpack_from("<I", bitmap, 10)[0]
82
+ width, height, _, bits, compression = struct.unpack_from("<iiHHI", bitmap, 18)
83
+ if not (0 < width <= 48 and 0 < abs(height) <= 48 and bits in (24, 32)):
84
+ raise ValueError("Invalid thumbnail dimensions or depth")
85
+ if compression not in (0, 3):
86
+ raise ValueError("Unsupported thumbnail encoding")
87
+ bytes_per_pixel = bits // 8
88
+ stride = (width * bytes_per_pixel + 3) & ~3
89
+ if offset < 54 or offset + abs(height) * stride > len(bitmap):
90
+ raise ValueError("Truncated thumbnail bitmap")
91
+ columns = min(PREVIEW_WIDTH, width)
92
+ rows = max(1, min(PREVIEW_HEIGHT, round(abs(height) * columns / (2 * width))))
93
+ preview = []
94
+ for row in range(rows):
95
+ y = min(abs(height) - 1, (2 * row + 1) * abs(height) // (2 * rows))
96
+ if height > 0:
97
+ y = height - 1 - y
98
+ cells = []
99
+ for col in range(columns):
100
+ x = min(width - 1, (2 * col + 1) * width // (2 * columns))
101
+ position = offset + y * stride + x * bytes_per_pixel
102
+ blue, green, red = bitmap[position : position + 3]
103
+ cells.append((21 * red + 72 * green + 7 * blue) * 23 // 25500)
104
+ preview.append(tuple(cells))
105
+ return tuple(preview)
@@ -0,0 +1,161 @@
1
+ """Convert v1 journal history to a standalone, read-only transcript (§14)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sqlite3
8
+ import tempfile
9
+ from collections.abc import Callable, Iterator
10
+ from contextlib import closing
11
+ from dataclasses import dataclass
12
+ from html import escape
13
+ from pathlib import Path
14
+ from typing import TextIO, TypeVar
15
+
16
+ __all__ = ["Conversion", "convert", "publish_archive", "write_entry", "write_header"]
17
+
18
+ _Result = TypeVar("_Result")
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class Conversion:
23
+ rows: int
24
+ unreadable: int
25
+
26
+
27
+ def _string(value: object, field: str) -> str:
28
+ if not isinstance(value, str):
29
+ raise TypeError(f"invalid text field {field}")
30
+ return value
31
+
32
+
33
+ def _object(value: object, field: str) -> dict:
34
+ if not isinstance(value, dict):
35
+ raise TypeError(f"invalid object field {field}")
36
+ return value
37
+
38
+
39
+ # The v1 daemon migrated these names on writable open (src/role_migration.rs).
40
+ # An archive reader can encounter both generations, including a live WAL.
41
+ _ROLES = {"horst": "core", "hengis": "side"}
42
+ _DISPLAY_KINDS = (
43
+ "user.message", "user.steer", "core.turn.activity", "core.turn.complete",
44
+ "core.turn.unresolved", "core.turn.output", "side.recommendation",
45
+ )
46
+ _LEGACY_KINDS = tuple(
47
+ first + kind[len(current):]
48
+ for first, current in _ROLES.items()
49
+ for kind in _DISPLAY_KINDS
50
+ if kind.startswith(current + ".")
51
+ )
52
+ _KIND_MARKERS = ",".join("?" for _ in (*_DISPLAY_KINDS, *_LEGACY_KINDS))
53
+
54
+
55
+ def _canonical_kind(kind: str) -> str:
56
+ role, dot, rest = kind.partition(".")
57
+ return _ROLES.get(role, role) + dot + rest
58
+
59
+
60
+ def _messages(data: dict) -> tuple[str, ...]:
61
+ result = _object(data.get("result"), "result")
62
+ messages = result.get("messages")
63
+ if not isinstance(messages, list):
64
+ raise TypeError("invalid message list")
65
+ return tuple(_string(_object(item, "message").get("text"), "text") for item in messages)
66
+
67
+
68
+ def _display(kind: str, data: dict, settled: set[str]) -> Iterator[tuple[str, str]]:
69
+ if kind in {"user.message", "user.steer"}:
70
+ yield "User", _string(data.get("summary"), "summary")
71
+ elif kind == "side.recommendation":
72
+ yield "Side recommendation", _string(data.get("summary"), "summary")
73
+ elif kind == "core.turn.activity":
74
+ if "tool" in data:
75
+ tool = _object(data["tool"], "tool")
76
+ state = _string(tool.get("state"), "state")
77
+ target = _string(tool.get("target"), "target")
78
+ preview = tool.get("preview", [])
79
+ if not isinstance(preview, list):
80
+ raise TypeError("invalid tool preview")
81
+ yield f"Tool · {state}", "\n".join([target, *(_string(s, "preview") for s in preview)])
82
+ elif kind == "core.turn.complete":
83
+ role = _string(data.get("role"), "role")
84
+ _string(data.get("id"), "id")
85
+ for text in _messages(data):
86
+ yield _ROLES.get(role, role), text
87
+ elif kind == "core.turn.output" and _string(data.get("id"), "id") not in settled:
88
+ yield "Partial reply", _string(data.get("text"), "text")
89
+ elif kind == "core.turn.unresolved":
90
+ yield "Turn stopped", _string(data.get("reason"), "reason")
91
+
92
+
93
+ def _read(db: sqlite3.Connection, run: str, output: TextIO) -> Conversion:
94
+ # Hold the same SQLite snapshot across both scans, including a live WAL.
95
+ db.execute("BEGIN")
96
+ (version,) = db.execute("PRAGMA user_version").fetchone()
97
+ if version not in (0, 1):
98
+ raise ValueError(f"Unsupported legacy journal user_version={version}")
99
+ if db.execute("SELECT 1 FROM runs WHERE run = ?", (run,)).fetchone() is None:
100
+ raise ValueError(f"unknown legacy run {run!r}")
101
+ settled: set[str] = set()
102
+ for (raw,) in db.execute(
103
+ "SELECT payload FROM events WHERE run = ? AND kind IN ('core.turn.complete','horst.turn.complete')", (run,)
104
+ ):
105
+ try:
106
+ data = _object(json.loads(raw), "payload")
107
+ if any(_messages(data)):
108
+ _string(data.get("role"), "role")
109
+ settled.add(_string(data.get("id"), "id"))
110
+ except (TypeError, ValueError):
111
+ # The ordered scan reports the corrupt receipt and keeps its streamed text.
112
+ continue
113
+ write_header(output, run)
114
+ rows = unreadable = 0
115
+ for seq, kind, raw in db.execute(
116
+ "SELECT seq, kind, payload FROM events WHERE run = ? "
117
+ f"AND kind IN ({_KIND_MARKERS}) ORDER BY seq", (run, *_DISPLAY_KINDS, *_LEGACY_KINDS)
118
+ ):
119
+ try:
120
+ entries = tuple(_display(_canonical_kind(kind), _object(json.loads(raw), "payload"), settled))
121
+ except (TypeError, ValueError) as error:
122
+ entries = (("Unreadable event", f"{kind} at sequence {seq}: {error}"),)
123
+ unreadable += 1
124
+ for speaker, body in entries:
125
+ write_entry(output, str(seq), speaker, body)
126
+ rows += 1
127
+ return Conversion(rows, unreadable)
128
+
129
+
130
+ def write_header(output: TextIO, title: str) -> None:
131
+ """Start the shared standalone archive page used by every legacy converter."""
132
+ output.write('<!doctype html><meta charset="utf-8"><title>Archived session</title>\n')
133
+ output.write(f"<h1>{escape(title)}</h1>\n")
134
+
135
+
136
+ def write_entry(output: TextIO, position: str, speaker: str, body: str) -> None:
137
+ output.write(f'<section data-seq="{escape(position)}"><h2>{escape(speaker)}</h2>')
138
+ output.write(f"<pre>{escape(body)}</pre></section>\n")
139
+
140
+
141
+ def publish_archive(destination: Path, render: Callable[[TextIO], _Result]) -> _Result:
142
+ """Render into a private temporary file, then link it into place without clobbering."""
143
+ with tempfile.NamedTemporaryFile(
144
+ mode="w", encoding="utf-8", dir=destination.parent, delete=False
145
+ ) as output:
146
+ pending = Path(output.name)
147
+ try:
148
+ result = render(output)
149
+ output.flush()
150
+ os.fsync(output.fileno())
151
+ os.link(pending, destination) # Atomic publication, including the no-clobber check.
152
+ finally:
153
+ pending.unlink()
154
+ return result
155
+
156
+
157
+ def convert(journal: Path, run: str, destination: Path) -> Conversion:
158
+ """Publish an owner-readable HTML file only after a successful read-only scan."""
159
+ uri = journal.resolve(strict=True).as_uri() + "?mode=ro"
160
+ with closing(sqlite3.connect(uri, uri=True)) as db:
161
+ return publish_archive(destination, lambda output: _read(db, run, output))