ai-editor-tree-engine-dev 1.0.176__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,400 @@
1
+ """Safe declarative encoder/decoder for the versioned tree file (C-017).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the *bytes* side of the tree file whose data model is owned by the
7
+ sibling :mod:`tree_engine.storage.schema`; nothing declared there is redefined
8
+ here. This module adds three things, per {p086}/{p100}: a mapping between a
9
+ live common-model ``Document`` and the canonical payload body preserving
10
+ ``node_id`` (UUID4), ``short_id`` (positive int rendered 0x-prefixed hex per
11
+ {p097}), ``extended_type``, ``buffer_range`` and ``references``
12
+ (``NodeAddress``) exactly; a deterministic canonicalization
13
+ (:func:`canonical_bytes`) pinned by :data:`CODEC_VERSION`, over which
14
+ ``tree_payload_sha256`` is computed -- covering the payload section only, so
15
+ the service ``CHECKSUMS`` section and the checksum field itself are excluded by
16
+ construction; and the safe load path, bytes -> UTF-8 -> :func:`json.loads` ->
17
+ plain dict lookups and ``str``/``int``/``bool``/``float``/``UUID`` coercions,
18
+ with no ``eval``, ``exec``, ``pickle``, ``marshal``, dynamic import or any
19
+ other object-loading mechanism. The short_id map is never regenerated: a
20
+ caller-supplied ``ShortIdMap`` is carried verbatim and :func:`short_id_map_for`
21
+ reuses the values the document's own nodes carry. Non-goals: no file I/O, and
22
+ no ``source_sha256`` comparison -- per {p086} a storage-lifecycle concern; the
23
+ value is only carried in the envelope.
24
+ Source-of-truth labels: {p085}, {p086}, {p087}, {p092}, {p097}, {p100}.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import base64
30
+ import hashlib
31
+ import json
32
+ from dataclasses import dataclass
33
+ from types import MappingProxyType
34
+ from typing import Any, Callable, Dict, List, Mapping, Optional
35
+ from uuid import UUID
36
+
37
+ from tree_engine.core.identity import NodeAddress
38
+ from tree_engine.core.nodes import Document, Node, NodeKind, walk
39
+ from tree_engine.core.short_id import ShortIdError, ShortIdMap, from_hex, to_hex
40
+ from tree_engine.exceptions import ChecksumMismatch, TreePayloadInvalid, exception_for_code
41
+ from tree_engine.storage.schema import (
42
+ CURRENT_SCHEMA_VERSION, ChecksumsSection, TreeFile, TreeFileEnvelope,
43
+ TreeFilePayload, TreeFileSchemaError,
44
+ )
45
+
46
+ __all__ = [
47
+ "CODEC_VERSION", "DEFAULT_CORE_CONTRACT_VERSION", "UNSPECIFIED_VERSION",
48
+ "NO_SOURCE_SHA256", "DecodedTreeFile", "canonical_bytes", "tree_payload_sha256",
49
+ "short_id_map_for", "encode", "decode", "decode_document"]
50
+
51
+ #: Pins the tag vocabulary below and the JSON dialect of :func:`canonical_bytes`,
52
+ #: hence the exact bytes ``tree_payload_sha256`` covers ({p086}/{p100}).
53
+ CODEC_VERSION = "1"
54
+
55
+ #: Default envelope ``core_contract_version``: the core publishes no constant of
56
+ #: its own yet; this matches the ``contract_version`` the shipped plugins declare.
57
+ DEFAULT_CORE_CONTRACT_VERSION = "1.0.0"
58
+
59
+ #: Placeholder for a plugin version the caller did not supply; the schema
60
+ #: requires a non-empty string, and inventing a number would lie.
61
+ UNSPECIFIED_VERSION = "unspecified"
62
+
63
+ #: ``source_sha256`` placeholder (sha256 of empty content). Never compared here:
64
+ #: per {p086} that is the lifecycle layer's job, and it overwrites this field.
65
+ NO_SOURCE_SHA256 = hashlib.sha256(b"").hexdigest()
66
+
67
+ _NULL, _BOOL, _INT, _FLOAT, _STR, _BYTES, _NODE, _NODES = (
68
+ "null", "bool", "int", "float", "str", "bytes", "node", "nodes")
69
+ _SCALARS: Mapping[str, Any] = {_BOOL: bool, _INT: int, _FLOAT: (int, float), _STR: str, _BYTES: str}
70
+
71
+ @dataclass(frozen=True)
72
+ class DecodedTreeFile:
73
+ """Everything :func:`decode` recovers from a tree file's bytes."""
74
+
75
+ document: Document
76
+ short_id_map: ShortIdMap
77
+ envelope: TreeFileEnvelope
78
+ checksums: ChecksumsSection
79
+
80
+ def canonical_bytes(data: Mapping[str, Any]) -> bytes:
81
+ """Render ``data`` to canonical UTF-8 JSON -- sorted keys, fixed separators,
82
+ non-finite floats rejected -- so equal data always yields equal bytes."""
83
+
84
+ try:
85
+ text = json.dumps(
86
+ data, ensure_ascii=False, sort_keys=True, allow_nan=False, separators=(",", ":"))
87
+ except (TypeError, ValueError) as exc:
88
+ raise TreePayloadInvalid(f"payload is not canonically serializable: {exc}") from exc
89
+ return text.encode("utf-8")
90
+
91
+ def tree_payload_sha256(payload: TreeFilePayload) -> str:
92
+ """Hash the canonical bytes of the payload section only, per {p086}."""
93
+
94
+ return hashlib.sha256(canonical_bytes(payload.to_dict())).hexdigest()
95
+
96
+ def _schema(call: Callable[..., Any], *args: Any) -> Any:
97
+ """Map a schema constructor's ``TreeFileSchemaError`` onto the public
98
+ exception class for the ``ErrorCode`` it already carries."""
99
+
100
+ try:
101
+ return call(*args)
102
+ except TreeFileSchemaError as exc:
103
+ raise exception_for_code(exc.code)(str(exc)) from exc
104
+
105
+ def _as_uuid4(value: Any, label: str) -> UUID:
106
+ candidate = value if isinstance(value, UUID) else None
107
+ if candidate is None and isinstance(value, str):
108
+ try:
109
+ candidate = UUID(value)
110
+ except ValueError:
111
+ candidate = None
112
+ if candidate is None or candidate.version != 4:
113
+ raise TreePayloadInvalid(f"{label} must be a UUID4, got {value!r}")
114
+ return candidate
115
+
116
+ def _encode_short_id(value: Any) -> str:
117
+ try:
118
+ return to_hex(value)
119
+ except ValueError as exc:
120
+ raise TreePayloadInvalid(f"short_id must be a positive integer: {value!r}") from exc
121
+
122
+ def _decode_short_id(value: Any) -> int:
123
+ try:
124
+ return from_hex(value)
125
+ except ShortIdError as exc:
126
+ raise TreePayloadInvalid(f"short_id hex is malformed: {value!r}") from exc
127
+
128
+ def _bounds(value: Any) -> Optional[List[int]]:
129
+ """Validate a ``buffer_range`` int pair, normalized to a plain list."""
130
+ if value is None:
131
+ return None
132
+ if not isinstance(value, (tuple, list)) or len(value) != 2:
133
+ raise TreePayloadInvalid(f"buffer_range must be a (start, end) pair, got {value!r}")
134
+ if any(isinstance(bound, bool) or not isinstance(bound, int) for bound in value):
135
+ raise TreePayloadInvalid(f"buffer_range bounds must be ints, got {value!r}")
136
+ return [value[0], value[1]]
137
+
138
+ def _ext_type(value: Any) -> Optional[str]:
139
+ if value is not None and not isinstance(value, str):
140
+ raise TreePayloadInvalid(f"extended_type must be a str or null, got {value!r}")
141
+ return value
142
+
143
+ def _encode_address(address: Any) -> Dict[str, Any]:
144
+ if not isinstance(address, NodeAddress):
145
+ raise TreePayloadInvalid(f"reference must be a NodeAddress, got {type(address).__name__}")
146
+ doc_id = address.document_id
147
+ return {"node_id": str(_as_uuid4(address.node_id, "reference node_id")),
148
+ "document_id": None if doc_id is None
149
+ else str(_as_uuid4(doc_id, "reference document_id"))}
150
+
151
+ def _decode_address(data: Any) -> NodeAddress:
152
+ if not isinstance(data, dict):
153
+ raise TreePayloadInvalid(f"reference must be an object, got {type(data).__name__}")
154
+ doc_id = data.get("document_id")
155
+ return NodeAddress(node_id=_as_uuid4(data.get("node_id"), "reference node_id"),
156
+ document_id=None if doc_id is None
157
+ else _as_uuid4(doc_id, "reference document_id"))
158
+
159
+ def _encode_value(name: str, value: Any, memo: Dict[int, int]) -> List[Any]:
160
+ """Encode a ``Node.fields`` value as a ``[tag, payload]`` pair over the
161
+ ``FieldValue`` union; ``bool`` precedes ``int``, being its subclass."""
162
+
163
+ if value is None:
164
+ return [_NULL, None]
165
+ if isinstance(value, Node):
166
+ return [_NODE, _encode_node(value, memo)]
167
+ if isinstance(value, (tuple, list)):
168
+ return [_NODES, [_encode_node(item, memo) for item in value]]
169
+ if isinstance(value, bytes):
170
+ return [_BYTES, base64.b64encode(value).decode("ascii")]
171
+ for kind, tag in ((bool, _BOOL), (int, _INT), (float, _FLOAT), (str, _STR)):
172
+ if isinstance(value, kind):
173
+ return [tag, kind(value)]
174
+ raise TreePayloadInvalid(f"field {name!r} has unsupported value type {type(value).__name__}")
175
+
176
+ def _decode_value(name: str, entry: Any, memo: Dict[int, Node]) -> Any:
177
+ """Rebuild one ``Node.fields`` value from its ``[tag, payload]`` pair."""
178
+
179
+ if not isinstance(entry, list) or len(entry) != 2:
180
+ raise TreePayloadInvalid(f"field {name!r} must encode as a [tag, value] pair")
181
+ tag, raw = entry
182
+ if tag == _NODE:
183
+ return _decode_node(raw, memo)
184
+ if tag == _NODES:
185
+ if not isinstance(raw, list):
186
+ raise TreePayloadInvalid(f"field {name!r} tagged nodes holds {type(raw).__name__}")
187
+ return tuple(_decode_node(item, memo) for item in raw)
188
+ if tag == _NULL:
189
+ if raw is not None:
190
+ raise TreePayloadInvalid(f"field {name!r} tagged null holds {raw!r}")
191
+ return None
192
+ expected = _SCALARS.get(tag)
193
+ if expected is None:
194
+ raise TreePayloadInvalid(f"field {name!r} carries unknown value tag {tag!r}")
195
+ if not isinstance(raw, expected) or (tag != _BOOL and isinstance(raw, bool)):
196
+ raise TreePayloadInvalid(f"field {name!r} tagged {tag} holds {raw!r}")
197
+ if tag == _FLOAT:
198
+ return float(raw)
199
+ if tag == _BYTES:
200
+ try:
201
+ return base64.b64decode(raw.encode("ascii"), validate=True)
202
+ except (ValueError, UnicodeEncodeError) as exc:
203
+ raise TreePayloadInvalid(f"field {name!r} has malformed base64: {exc}") from exc
204
+ return raw
205
+
206
+ def _encode_node(node: Any, memo: Dict[int, int]) -> Dict[str, Any]:
207
+ """Encode a ``Node`` subtree into plain JSON-native data. ``fields`` and
208
+ ``children`` routinely hold the SAME node objects, so each is emitted once
209
+ under an ``"id"`` and every later occurrence becomes a ``{"ref": id}``
210
+ back-pointer -- without which a shared subtree would be duplicated once per
211
+ path and blow up exponentially with depth. ``fields`` is an ordered
212
+ ``[name, value]`` list so field order survives canonical key sorting."""
213
+
214
+ if not isinstance(node, Node):
215
+ raise TreePayloadInvalid(f"expected a Node, got {type(node).__name__}")
216
+ if id(node) in memo:
217
+ return {"ref": memo[id(node)]}
218
+ memo[id(node)] = index = len(memo)
219
+ return {
220
+ "id": index, "kind": str(node.kind), "extended_type": _ext_type(node.extended_type),
221
+ "node_id": None if node.node_id is None else str(_as_uuid4(node.node_id, "node_id")),
222
+ "short_id": None if node.short_id is None else _encode_short_id(node.short_id),
223
+ "buffer_range": _bounds(node.buffer_range),
224
+ "references": [_encode_address(item) for item in node.references],
225
+ "fields": [[name, _encode_value(name, val, memo)] for name, val in node.fields.items()],
226
+ "children": [_encode_node(child, memo) for child in node.children]}
227
+
228
+ def _decode_node(data: Any, memo: Dict[int, Node]) -> Node:
229
+ """Rebuild a ``Node``, resolving ``{"ref": id}`` back-pointers through ``memo``
230
+ so shared subtrees stay shared, shape-checking every value, then building the
231
+ frozen dataclass directly -- the documented path for a validated node."""
232
+
233
+ if not isinstance(data, dict):
234
+ raise TreePayloadInvalid(f"node must be an object, got {type(data).__name__}")
235
+ if "ref" in data:
236
+ shared = memo.get(data["ref"]) if isinstance(data["ref"], int) else None
237
+ if shared is None:
238
+ raise TreePayloadInvalid(f"node ref {data['ref']!r} precedes its definition")
239
+ return shared
240
+ kind = data.get("kind")
241
+ if not isinstance(kind, str) or not kind:
242
+ raise TreePayloadInvalid(f"node kind must be a non-empty str, got {kind!r}")
243
+ for key in ("fields", "children", "references"):
244
+ if not isinstance(data.get(key), list):
245
+ raise TreePayloadInvalid(
246
+ f"node {key} must be a list, got {type(data.get(key)).__name__}")
247
+ fields: Dict[str, Any] = {}
248
+ for entry in data["fields"]:
249
+ if (not isinstance(entry, list) or len(entry) != 2
250
+ or not isinstance(entry[0], str) or not entry[0]):
251
+ raise TreePayloadInvalid(f"node field must be a [name, value] pair, got {entry!r}")
252
+ fields[entry[0]] = _decode_value(entry[0], entry[1], memo)
253
+ bounds = _bounds(data.get("buffer_range"))
254
+ node_id, short_id, index = data.get("node_id"), data.get("short_id"), data.get("id")
255
+ node = Node(
256
+ kind=NodeKind(kind), fields=MappingProxyType(fields),
257
+ children=tuple(_decode_node(child, memo) for child in data["children"]),
258
+ node_id=None if node_id is None else _as_uuid4(node_id, "node_id"),
259
+ short_id=None if short_id is None else _decode_short_id(short_id),
260
+ extended_type=_ext_type(data.get("extended_type")),
261
+ buffer_range=None if bounds is None else (bounds[0], bounds[1]),
262
+ references=tuple(_decode_address(item) for item in data["references"]))
263
+ if isinstance(index, bool) or not isinstance(index, int) or index in memo:
264
+ raise TreePayloadInvalid(f"node id {index!r} is missing, malformed, or duplicated")
265
+ memo[index] = node
266
+ return node
267
+
268
+ def short_id_map_for(document: Document) -> ShortIdMap:
269
+ """Build the payload's short_id map from the document's own nodes, reusing the
270
+ exact ``short_id`` each carries -- never allocating a fresh one ({p097})."""
271
+
272
+ incoming: Dict[UUID, int] = {}
273
+ for node in walk(document.root):
274
+ if node.node_id is None or node.short_id is None:
275
+ continue
276
+ node_id = _as_uuid4(node.node_id, "node_id")
277
+ if node_id in incoming:
278
+ raise TreePayloadInvalid(f"duplicate node_id in the tree: {node_id}")
279
+ if isinstance(node.short_id, bool) or not isinstance(node.short_id, int) or node.short_id < 1:
280
+ raise TreePayloadInvalid(f"short_id must be a positive integer: {node.short_id!r}")
281
+ incoming[node_id] = node.short_id
282
+ result = ShortIdMap(next_short_id=1)
283
+ try:
284
+ result.merge_insert(incoming)
285
+ except ShortIdError as exc:
286
+ raise TreePayloadInvalid(f"short_id map cannot hold the document's ids: {exc}") from exc
287
+ return result
288
+
289
+ def _check_identity_consistency(root: Node, short_id_map: ShortIdMap) -> None:
290
+ """Reject a tree whose node ids duplicate or contradict the map ({p092})."""
291
+
292
+ seen = set()
293
+ for node in walk(root):
294
+ if node.node_id is None:
295
+ continue
296
+ node_id = _as_uuid4(node.node_id, "node_id")
297
+ if node_id in seen:
298
+ raise TreePayloadInvalid(f"duplicate node_id in the tree: {node_id}")
299
+ seen.add(node_id)
300
+ mapped = short_id_map.get_short_id(node_id)
301
+ if mapped is not None and node.short_id is not None and mapped != node.short_id:
302
+ raise TreePayloadInvalid(
303
+ f"short_id map says {mapped} for node {node_id}, tree says {node.short_id!r}")
304
+
305
+ def _derive_document_id(payload_dict: Mapping[str, Any]) -> UUID:
306
+ """Derive a stable version-4 document id from the canonical payload,
307
+ used only when neither caller nor document supplies one; being a pure
308
+ function of those bytes it keeps :func:`encode` deterministic."""
309
+
310
+ digest = bytearray(hashlib.sha256(canonical_bytes(payload_dict)).digest()[:16])
311
+ digest[6] = (digest[6] & 0x0F) | 0x40
312
+ digest[8] = (digest[8] & 0x3F) | 0x80
313
+ return UUID(bytes=bytes(digest))
314
+
315
+ def encode(
316
+ document: Document, *,
317
+ short_id_map: Optional[ShortIdMap] = None, document_id: Optional[Any] = None,
318
+ document_version: int = 0, source_sha256: Optional[str] = None,
319
+ core_contract_version: str = DEFAULT_CORE_CONTRACT_VERSION,
320
+ plugin_id: Optional[str] = None, plugin_version: str = UNSPECIFIED_VERSION,
321
+ plugin_contract_version: str = UNSPECIFIED_VERSION, encoding: str = "utf-8",
322
+ newline: str = "\n", trailing_newline: bool = True,
323
+ format_metadata: Optional[Mapping[str, Any]] = None,
324
+ ) -> bytes:
325
+ """Serialize ``document`` to the canonical tree-file bytes. Deterministic:
326
+ the same document and arguments always produce the same bytes.
327
+ ``tree_payload_sha256`` covers the payload's canonical bytes, excluding the
328
+ ``CHECKSUMS`` section and the checksum field itself ({p086});
329
+ ``source_sha256`` is carried, never compared. Raises ``TreePayloadInvalid``
330
+ for a tree the codec cannot express, or ``TreeSchemaUnsupported`` if the
331
+ schema gate rejects the envelope."""
332
+
333
+ if not isinstance(document, Document):
334
+ raise TreePayloadInvalid(f"document must be a Document, got {type(document).__name__}")
335
+ resolved_map = short_id_map if short_id_map is not None else short_id_map_for(document)
336
+ _check_identity_consistency(document.root, resolved_map)
337
+ payload = TreeFilePayload(short_id_map=resolved_map,
338
+ tree={"codec_version": CODEC_VERSION, "root": _encode_node(document.root, {})})
339
+ payload_dict = payload.to_dict()
340
+ given = document_id if document_id is not None else document.document_id
341
+ envelope_id = (_as_uuid4(given, "document_id") if given is not None
342
+ else _derive_document_id(payload_dict))
343
+ envelope = _schema(TreeFileEnvelope.from_dict, {
344
+ "schema_version": CURRENT_SCHEMA_VERSION, "document_id": str(envelope_id),
345
+ "core_contract_version": core_contract_version, "document_version": document_version,
346
+ "next_short_id": resolved_map.snapshot().next_short_id,
347
+ "representation_format_id": document.representation_format_id,
348
+ "source_format_id": document.source_format_id, "encoding": encoding,
349
+ "newline": newline, "trailing_newline": trailing_newline,
350
+ "plugin_id": plugin_id if plugin_id is not None else document.representation_format_id,
351
+ "plugin_version": plugin_version, "plugin_contract_version": plugin_contract_version,
352
+ "format_metadata": dict(format_metadata or {}),
353
+ })
354
+ checksums = _schema(ChecksumsSection.from_dict, {
355
+ "source_sha256": source_sha256 or NO_SOURCE_SHA256,
356
+ "tree_payload_sha256": hashlib.sha256(canonical_bytes(payload_dict)).hexdigest()})
357
+ return canonical_bytes(
358
+ TreeFile(envelope=envelope, payload=payload, checksums=checksums).to_dict())
359
+
360
+ def decode(data: bytes) -> DecodedTreeFile:
361
+ """Parse tree-file bytes back into document, map, envelope, checksums.
362
+ Gate order: JSON shape, then the schema module's version gate and explicit
363
+ minor migrations (an unknown major raises ``TreeSchemaUnsupported`` there,
364
+ per {p087}/{p100}), then the ``tree_payload_sha256`` recomputation, then the
365
+ tree body. Anything structurally unexpected raises ``TreePayloadInvalid``; a
366
+ checksum discrepancy raises ``ChecksumMismatch``. Nothing executes data."""
367
+
368
+ data = bytes(data) if isinstance(data, (bytearray, memoryview)) else data
369
+ if not isinstance(data, bytes):
370
+ raise TreePayloadInvalid(f"tree file must be bytes, got {type(data).__name__}")
371
+ try:
372
+ raw = json.loads(data.decode("utf-8"))
373
+ except (UnicodeDecodeError, ValueError) as exc:
374
+ raise TreePayloadInvalid(f"tree file is not valid UTF-8 JSON: {exc}") from exc
375
+ if not isinstance(raw, dict):
376
+ raise TreePayloadInvalid(f"tree file must be a JSON object, got {type(raw).__name__}")
377
+ tree_file = _schema(TreeFile.from_dict, raw)
378
+ recomputed = tree_payload_sha256(tree_file.payload)
379
+ if recomputed != tree_file.checksums.tree_payload_sha256:
380
+ raise ChecksumMismatch("tree_payload_sha256 does not match the canonical payload bytes",
381
+ expected=tree_file.checksums.tree_payload_sha256, recomputed=recomputed)
382
+ body = tree_file.payload.tree
383
+ if body.get("codec_version") != CODEC_VERSION:
384
+ raise TreePayloadInvalid(f"payload codec_version {body.get('codec_version')!r} is not 1")
385
+ root = _decode_node(body.get("root"), {})
386
+ short_id_map, envelope = tree_file.payload.short_id_map, tree_file.envelope
387
+ _check_identity_consistency(root, short_id_map)
388
+ stored_next = short_id_map.snapshot().next_short_id
389
+ if stored_next != envelope.next_short_id:
390
+ raise TreePayloadInvalid(f"envelope next_short_id != the map's {stored_next}")
391
+ document = Document(root=root, source_format_id=envelope.source_format_id,
392
+ representation_format_id=envelope.representation_format_id)
393
+ document.document_id = envelope.document_id
394
+ return DecodedTreeFile(document=document, short_id_map=short_id_map,
395
+ envelope=envelope, checksums=tree_file.checksums)
396
+
397
+ def decode_document(data: bytes) -> Document:
398
+ """Convenience wrapper returning only the document of :func:`decode`."""
399
+
400
+ return decode(data).document