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,403 @@
1
+ """Versioned tree-file envelope, payload layout, and schema version gate.
2
+
3
+ Scope (concept C-017, TreeSerializationSchema, narrowed to this atomic
4
+ step's target ``src/tree_engine/storage/schema.py``): the data model and
5
+ schema version gate for the persisted tree file, per {p085}/{p100}.
6
+
7
+ A tree file carries three sections: an *envelope* of schema/contract
8
+ versions, document identity/version, the short_id allocator state,
9
+ format ids, encoding/newline metadata, and plugin identity
10
+ (:class:`TreeFileEnvelope`); a *payload* of the canonical tree body and
11
+ the short_id-to-UUID4 map, the latter reusing
12
+ :class:`tree_engine.core.short_id.ShortIdMap` as-is
13
+ (:class:`TreeFilePayload`); and a service *CHECKSUMS* section holding
14
+ ``source_sha256``/``tree_payload_sha256`` (:class:`ChecksumsSection`).
15
+ :class:`TreeFile` composes the three. Per {p087}/{p100} this module also
16
+ implements the codec's version gate: an unknown major ``schema_version``
17
+ is rejected with ``TREE_SCHEMA_UNSUPPORTED``; compatible minor versions
18
+ migrate through the explicit registry :data:`MINOR_MIGRATIONS`.
19
+
20
+ Non-goals, per {p086}/{p092} and this step's acceptance criteria: no file
21
+ I/O, no bytes/JSON parsing, no canonical byte-serialization, and no
22
+ checksum computation -- those, plus the pinned codec version fixing
23
+ payload canonicalization per {p100}, belong to the sibling codec module.
24
+ Deep structural validation of the tree body (UUID4 uniqueness,
25
+ parent/child, reference cycles, ...) is the core's job per {p092}; this
26
+ module validates only *shape*, rejecting a mismatch with
27
+ ``TREE_PAYLOAD_INVALID``.
28
+
29
+ Deserialization here never executes code and never uses pickle-like
30
+ object loading: every conversion below is a plain dict lookup plus a
31
+ ``str``/``int``/``bool``/``uuid.UUID`` coercion -- no ``eval``, ``exec``,
32
+ ``pickle``, ``marshal``, or dynamic import appears in this file.
33
+
34
+ Source-of-truth labels honored here: {p085}, {p086}, {p087}, {p092}, {p100}.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ from dataclasses import dataclass, field
40
+ from types import MappingProxyType
41
+ from typing import Any, Callable, Dict, Mapping, Tuple
42
+ from uuid import UUID
43
+
44
+ from tree_engine.core.short_id import ShortIdMap
45
+ from tree_engine.errors import ErrorCode
46
+
47
+ __all__ = [
48
+ "TreeFileSchemaError",
49
+ "CURRENT_SCHEMA_MAJOR",
50
+ "CURRENT_SCHEMA_MINOR",
51
+ "CURRENT_SCHEMA_VERSION",
52
+ "SUPPORTED_SCHEMA_MAJOR_VERSIONS",
53
+ "MinorMigration",
54
+ "MINOR_MIGRATIONS",
55
+ "parse_schema_version",
56
+ "check_schema_major_supported",
57
+ "apply_minor_migrations",
58
+ "TreeFileEnvelope",
59
+ "TreeFilePayload",
60
+ "ChecksumsSection",
61
+ "TreeFile",
62
+ ]
63
+
64
+ # ---- Version gate ---------------------------------------------------------
65
+
66
+ CURRENT_SCHEMA_MAJOR = 1
67
+ CURRENT_SCHEMA_MINOR = 0
68
+ CURRENT_SCHEMA_VERSION = f"{CURRENT_SCHEMA_MAJOR}.{CURRENT_SCHEMA_MINOR}"
69
+
70
+ #: Major ``schema_version`` values readable at all; others are rejected
71
+ #: with ``TREE_SCHEMA_UNSUPPORTED`` before any migration, per {p087}.
72
+ SUPPORTED_SCHEMA_MAJOR_VERSIONS = frozenset({1})
73
+
74
+
75
+ class TreeFileSchemaError(Exception):
76
+ """Invalid tree-file envelope/payload/checksums dict.
77
+
78
+ Carries the originating ``ErrorCode`` as ``self.code``, mirroring
79
+ ``core.nodes.NodeSchemaError``: ``TREE_SCHEMA_UNSUPPORTED`` (unknown
80
+ major schema version) or ``TREE_PAYLOAD_INVALID`` (other mismatch).
81
+ """
82
+
83
+ def __init__(self, code: ErrorCode, message: str) -> None:
84
+ super().__init__(f"[{code.value}] {message}")
85
+ self.code = code
86
+
87
+
88
+ def parse_schema_version(value: Any) -> Tuple[int, int]:
89
+ """Parse ``"MAJOR.MINOR"`` into an ``(major, minor)`` int pair.
90
+
91
+ Raises ``TreeFileSchemaError`` (``TREE_PAYLOAD_INVALID``) if not a
92
+ str, or not exactly two dot-separated non-negative integers.
93
+ """
94
+
95
+ if not isinstance(value, str):
96
+ raise TreeFileSchemaError(ErrorCode.TREE_PAYLOAD_INVALID, f"schema_version must be a str, got {value!r}")
97
+ parts = value.split(".")
98
+ if len(parts) != 2 or not all(part.isdigit() for part in parts):
99
+ raise TreeFileSchemaError(
100
+ ErrorCode.TREE_PAYLOAD_INVALID,
101
+ f"schema_version must be 'MAJOR.MINOR' with non-negative integers, got {value!r}",
102
+ )
103
+ return int(parts[0]), int(parts[1])
104
+
105
+
106
+ def check_schema_major_supported(major: int) -> None:
107
+ """Raise ``TREE_SCHEMA_UNSUPPORTED`` if ``major`` is unreadable ({p087})."""
108
+
109
+ if major not in SUPPORTED_SCHEMA_MAJOR_VERSIONS:
110
+ raise TreeFileSchemaError(
111
+ ErrorCode.TREE_SCHEMA_UNSUPPORTED,
112
+ f"unsupported major schema_version: {major} (supported: {sorted(SUPPORTED_SCHEMA_MAJOR_VERSIONS)})",
113
+ )
114
+
115
+
116
+ #: Upgrades an envelope dict declaring ``"{major}.{minor}"`` to
117
+ #: ``"{major}.{minor + 1}"``, returning a new dict (input never mutated).
118
+ MinorMigration = Callable[[Dict[str, Any]], Dict[str, Any]]
119
+
120
+ #: Explicit registry of minor-version migrations, keyed by the
121
+ #: ``(major, minor)`` an envelope declares. Empty today: ``1.0`` is the
122
+ #: only minor version shipped under major version 1 so far; a future
123
+ #: compatible minor bump adds its migration here under its own key.
124
+ MINOR_MIGRATIONS: Mapping[Tuple[int, int], MinorMigration] = {}
125
+
126
+
127
+ def apply_minor_migrations(
128
+ data: Mapping[str, Any],
129
+ migrations: Mapping[Tuple[int, int], MinorMigration] = MINOR_MIGRATIONS,
130
+ ) -> Dict[str, Any]:
131
+ """Migrate an envelope dict through explicit, testable minor steps.
132
+
133
+ Rejects an unsupported major version, then repeatedly looks up
134
+ ``(major, minor)`` in ``migrations`` and applies the matching step
135
+ until none is registered; each result is re-validated the same way.
136
+ Raises ``TreeFileSchemaError`` (``TREE_PAYLOAD_INVALID``) on a cycle.
137
+ Returns a new dict; ``data`` is never mutated.
138
+ """
139
+
140
+ major, minor = parse_schema_version(data.get("schema_version"))
141
+ check_schema_major_supported(major)
142
+ migrated: Dict[str, Any] = dict(data)
143
+ seen = {(major, minor)}
144
+ while (major, minor) in migrations:
145
+ migrated = migrations[(major, minor)](migrated)
146
+ major, minor = parse_schema_version(migrated.get("schema_version"))
147
+ check_schema_major_supported(major)
148
+ if (major, minor) in seen:
149
+ raise TreeFileSchemaError(
150
+ ErrorCode.TREE_PAYLOAD_INVALID,
151
+ f"minor-version migration cycle detected at schema_version {major}.{minor}",
152
+ )
153
+ seen.add((major, minor))
154
+ migrated["schema_version"] = f"{major}.{minor}"
155
+ return migrated
156
+
157
+
158
+ # ---- Shape-validation helpers (no parsing, no I/O) -------------------------
159
+
160
+ def _require_str(data: Mapping[str, Any], key: str) -> str:
161
+ value = data.get(key)
162
+ if not isinstance(value, str) or not value:
163
+ raise TreeFileSchemaError(ErrorCode.TREE_PAYLOAD_INVALID, f"{key} must be a non-empty str, got {value!r}")
164
+ return value
165
+
166
+ def _require_int(data: Mapping[str, Any], key: str, *, minimum: int) -> int:
167
+ value = data.get(key)
168
+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
169
+ raise TreeFileSchemaError(ErrorCode.TREE_PAYLOAD_INVALID, f"{key} must be an int >= {minimum}, got {value!r}")
170
+ return value
171
+
172
+ def _require_bool(data: Mapping[str, Any], key: str) -> bool:
173
+ value = data.get(key)
174
+ if not isinstance(value, bool):
175
+ raise TreeFileSchemaError(ErrorCode.TREE_PAYLOAD_INVALID, f"{key} must be a bool, got {value!r}")
176
+ return value
177
+
178
+ def _require_uuid4(data: Mapping[str, Any], key: str) -> UUID:
179
+ value = data.get(key)
180
+ candidate = value if isinstance(value, UUID) else None
181
+ if candidate is None:
182
+ try:
183
+ candidate = UUID(str(value))
184
+ except (ValueError, AttributeError, TypeError):
185
+ candidate = None
186
+ if candidate is None or candidate.version != 4:
187
+ raise TreeFileSchemaError(ErrorCode.TREE_PAYLOAD_INVALID, f"{key} must be a UUID4, got {value!r}")
188
+ return candidate
189
+
190
+ def _require_mapping(data: Mapping[str, Any], key: str) -> Mapping[str, Any]:
191
+ value = data.get(key)
192
+ if not isinstance(value, Mapping):
193
+ raise TreeFileSchemaError(ErrorCode.TREE_PAYLOAD_INVALID, f"{key} must be a mapping, got {type(value).__name__}")
194
+ return value
195
+
196
+ _SHA256_HEX_DIGITS = frozenset("0123456789abcdefABCDEF")
197
+
198
+ def _require_sha256_hex(data: Mapping[str, Any], key: str) -> str:
199
+ value = data.get(key)
200
+ if not isinstance(value, str) or len(value) != 64 or not set(value) <= _SHA256_HEX_DIGITS:
201
+ raise TreeFileSchemaError(
202
+ ErrorCode.TREE_PAYLOAD_INVALID, f"{key} must be a 64-hex-digit sha256 string, got {value!r}"
203
+ )
204
+ return value.lower()
205
+
206
+
207
+ # ---- Envelope ---------------------------------------------------------------
208
+
209
+ @dataclass(frozen=True)
210
+ class TreeFileEnvelope:
211
+ """The tree file's envelope section, per {p085} and {p100}.
212
+
213
+ ``format_metadata`` is an open slot for other format metadata beyond
214
+ the named fields ({p100}); defaults to empty, round-trips verbatim.
215
+ """
216
+
217
+ schema_version: str
218
+ core_contract_version: str
219
+ document_id: UUID
220
+ document_version: int
221
+ next_short_id: int
222
+ representation_format_id: str
223
+ source_format_id: str
224
+ encoding: str
225
+ newline: str
226
+ trailing_newline: bool
227
+ plugin_id: str
228
+ plugin_version: str
229
+ plugin_contract_version: str
230
+ format_metadata: Mapping[str, Any] = field(default_factory=dict)
231
+
232
+ @classmethod
233
+ def from_dict(cls, data: Mapping[str, Any]) -> "TreeFileEnvelope":
234
+ """Validate and construct an envelope from a plain dict.
235
+
236
+ Applies the version gate first (:func:`apply_minor_migrations`),
237
+ then validates every other field. Raises ``TreeFileSchemaError``:
238
+ ``TREE_SCHEMA_UNSUPPORTED`` for an unknown major version,
239
+ ``TREE_PAYLOAD_INVALID`` for anything else malformed.
240
+ """
241
+
242
+ if not isinstance(data, Mapping):
243
+ raise TreeFileSchemaError(
244
+ ErrorCode.TREE_PAYLOAD_INVALID, f"envelope must be a mapping, got {type(data).__name__}"
245
+ )
246
+ migrated = apply_minor_migrations(data)
247
+ raw_metadata = migrated.get("format_metadata", {})
248
+ if not isinstance(raw_metadata, Mapping):
249
+ raise TreeFileSchemaError(
250
+ ErrorCode.TREE_PAYLOAD_INVALID,
251
+ f"format_metadata must be a mapping, got {type(raw_metadata).__name__}",
252
+ )
253
+ return cls(
254
+ schema_version=migrated["schema_version"],
255
+ core_contract_version=_require_str(migrated, "core_contract_version"),
256
+ document_id=_require_uuid4(migrated, "document_id"),
257
+ document_version=_require_int(migrated, "document_version", minimum=0),
258
+ next_short_id=_require_int(migrated, "next_short_id", minimum=1),
259
+ representation_format_id=_require_str(migrated, "representation_format_id"),
260
+ source_format_id=_require_str(migrated, "source_format_id"),
261
+ encoding=_require_str(migrated, "encoding"),
262
+ newline=_require_str(migrated, "newline"),
263
+ trailing_newline=_require_bool(migrated, "trailing_newline"),
264
+ plugin_id=_require_str(migrated, "plugin_id"),
265
+ plugin_version=_require_str(migrated, "plugin_version"),
266
+ plugin_contract_version=_require_str(migrated, "plugin_contract_version"),
267
+ format_metadata=MappingProxyType(dict(raw_metadata)),
268
+ )
269
+
270
+ def to_dict(self) -> Dict[str, Any]:
271
+ """Render to a dict; key order is fixed here, not by any input
272
+ dict's ordering, so equal envelopes always encode equal."""
273
+
274
+ return {
275
+ "schema_version": self.schema_version,
276
+ "core_contract_version": self.core_contract_version,
277
+ "document_id": str(self.document_id),
278
+ "document_version": self.document_version,
279
+ "next_short_id": self.next_short_id,
280
+ "representation_format_id": self.representation_format_id,
281
+ "source_format_id": self.source_format_id,
282
+ "encoding": self.encoding,
283
+ "newline": self.newline,
284
+ "trailing_newline": self.trailing_newline,
285
+ "plugin_id": self.plugin_id,
286
+ "plugin_version": self.plugin_version,
287
+ "plugin_contract_version": self.plugin_contract_version,
288
+ "format_metadata": dict(self.format_metadata),
289
+ }
290
+
291
+
292
+ # ---- Payload (tree body + short_id map) --------------------------------------
293
+
294
+ @dataclass(frozen=True)
295
+ class TreeFilePayload:
296
+ """The tree file's payload section: tree body plus short_id map.
297
+
298
+ ``tree`` is the opaque canonical tree body as a plain mapping; its
299
+ deep shape is owned by the core/codec, not here, per {p092} -- only
300
+ presence is checked. ``short_id_map`` reuses
301
+ :class:`tree_engine.core.short_id.ShortIdMap` as-is.
302
+ """
303
+
304
+ tree: Mapping[str, Any]
305
+ short_id_map: ShortIdMap
306
+
307
+ @classmethod
308
+ def from_dict(cls, data: Mapping[str, Any]) -> "TreeFilePayload":
309
+ if not isinstance(data, Mapping):
310
+ raise TreeFileSchemaError(
311
+ ErrorCode.TREE_PAYLOAD_INVALID, f"payload must be a mapping, got {type(data).__name__}"
312
+ )
313
+ tree = _require_mapping(data, "tree")
314
+ short_id_map_data = _require_mapping(data, "short_id_map")
315
+ try:
316
+ short_id_map = ShortIdMap.from_dict(dict(short_id_map_data))
317
+ # AttributeError belongs here too: a non-mapping ``entries`` makes
318
+ # ShortIdMap.from_dict call ``.items()`` on it, and a malformed field
319
+ # must surface as TREE_PAYLOAD_INVALID like every other one, never as
320
+ # a bare builtin escaping this boundary.
321
+ except (KeyError, ValueError, TypeError, AttributeError) as exc:
322
+ raise TreeFileSchemaError(
323
+ ErrorCode.TREE_PAYLOAD_INVALID, f"payload.short_id_map is malformed: {exc}"
324
+ ) from exc
325
+ return cls(tree=dict(tree), short_id_map=short_id_map)
326
+
327
+ def to_dict(self) -> Dict[str, Any]:
328
+ return {"tree": dict(self.tree), "short_id_map": self.short_id_map.to_dict()}
329
+
330
+
331
+ # ---- Checksums ----------------------------------------------------------------
332
+
333
+ @dataclass(frozen=True)
334
+ class ChecksumsSection:
335
+ """The tree file's service CHECKSUMS section, per {p085}.
336
+
337
+ ``source_sha256`` covers the exact source bytes; ``tree_payload_sha256``
338
+ covers the payload's canonical serialization. Neither is computed
339
+ here -- only checked as a well-formed 64-hex-digit string; computing
340
+ them from real bytes is the codec's job, per {p086}.
341
+ """
342
+
343
+ source_sha256: str
344
+ tree_payload_sha256: str
345
+
346
+ @classmethod
347
+ def from_dict(cls, data: Mapping[str, Any]) -> "ChecksumsSection":
348
+ if not isinstance(data, Mapping):
349
+ raise TreeFileSchemaError(
350
+ ErrorCode.TREE_PAYLOAD_INVALID, f"checksums must be a mapping, got {type(data).__name__}"
351
+ )
352
+ return cls(
353
+ source_sha256=_require_sha256_hex(data, "source_sha256"),
354
+ tree_payload_sha256=_require_sha256_hex(data, "tree_payload_sha256"),
355
+ )
356
+
357
+ def to_dict(self) -> Dict[str, str]:
358
+ return {
359
+ "source_sha256": self.source_sha256,
360
+ "tree_payload_sha256": self.tree_payload_sha256,
361
+ }
362
+
363
+
364
+ # ---- Whole tree file ------------------------------------------------------
365
+
366
+ @dataclass(frozen=True)
367
+ class TreeFile:
368
+ """The whole tree-file data model: envelope + payload + checksums."""
369
+
370
+ envelope: TreeFileEnvelope
371
+ payload: TreeFilePayload
372
+ checksums: ChecksumsSection
373
+
374
+ @classmethod
375
+ def from_dict(cls, data: Mapping[str, Any]) -> "TreeFile":
376
+ """Validate and construct a whole tree file from a plain dict.
377
+
378
+ ``data`` is assumed already parsed from bytes by the codec (this
379
+ module parses nothing of its own); it must map the three
380
+ top-level section names to their own mappings. Raises
381
+ ``TREE_SCHEMA_UNSUPPORTED`` for an unknown major schema version,
382
+ ``TREE_PAYLOAD_INVALID`` for any other malformed field.
383
+ """
384
+
385
+ if not isinstance(data, Mapping):
386
+ raise TreeFileSchemaError(
387
+ ErrorCode.TREE_PAYLOAD_INVALID, f"tree file must be a mapping, got {type(data).__name__}"
388
+ )
389
+ envelope = TreeFileEnvelope.from_dict(_require_mapping(data, "envelope"))
390
+ payload = TreeFilePayload.from_dict(_require_mapping(data, "payload"))
391
+ checksums = ChecksumsSection.from_dict(_require_mapping(data, "checksums"))
392
+ return cls(envelope=envelope, payload=payload, checksums=checksums)
393
+
394
+ def to_dict(self) -> Dict[str, Any]:
395
+ """Render to a dict; section/field order is fixed here and by the
396
+ section-level ``to_dict`` methods, not by any input dict's key
397
+ ordering, so equal data always renders to equal output."""
398
+
399
+ return {
400
+ "envelope": self.envelope.to_dict(),
401
+ "payload": self.payload.to_dict(),
402
+ "checksums": self.checksums.to_dict(),
403
+ }