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,622 @@
1
+ """Storage lifecycle orchestrator for the source/tree file pair (C-012).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Per {p085}-{p094}: the only place that owns a *pair* of files -- a source
7
+ document and the tree file beside it -- as an open/save/reparse lifecycle, and it
8
+ orchestrates rather than reimplements. ``schema``/``codec`` own the envelope, the
9
+ version gate and ``tree_payload_sha256``; ``session_guard`` owns both digests and
10
+ every external-modification verdict ({p089}); ``file_txn`` owns recoverable
11
+ publication ({p090}); ``validate_full_document`` owns the structural verdict
12
+ ({p092}); ``plugins.selection``/``registry``/``fallback`` resolve the plugin and
13
+ build the degraded tree ({p088}).
14
+
15
+ Open gates, in order ({p087}): journal recovery, source read, plugin resolution,
16
+ then a stored tree is accepted *without* ``parse_document`` only when
17
+ envelope/schema decoding, both SHAs, the plugin's availability and contract
18
+ compatibility, and full structural validation all pass. Two failures are raised
19
+ rather than rebuilt away, because they say the file came from an environment this
20
+ build cannot interpret: an unknown major schema (``TREE_SCHEMA_UNSUPPORTED``,
21
+ {p100}) and an absent or contract-incompatible plugin
22
+ (``FORMAT_PLUGIN_NOT_FOUND``/``FORMAT_PLUGIN_CONTRACT_ERROR``, never a fallback).
23
+ Everything else -- missing, corrupt or checksum-stale tree file, a compatible
24
+ plugin *version* change -- takes {p088}'s rebuild branch, which
25
+ :meth:`StorageLifecycle.reparse` also forces: parse (or, only on
26
+ ``FORMAT_CONTENT_PARSE_FAILED``, the fallback) -> encode -> atomic publication ->
27
+ reread -> that same branch, so no unvalidated in-memory tree is ever returned
28
+ ({p094}). Paths, digests, baselines and recovery reports live on
29
+ :class:`OpenedDocument`/``EditSession``, never on the tree ({p025}, {p093}).
30
+
31
+ Source-of-truth labels: {p006}, {p007}, {p025}, {p037}, {p052}, {p085}-{p094}, {p100}.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ from dataclasses import dataclass
38
+ from pathlib import Path
39
+ from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple, Union
40
+
41
+ from tree_engine.core.integrity_full import FullIntegrityError, validate_full_document
42
+ from tree_engine.core.nodes import Document, Node
43
+ from tree_engine.core.reference_cache import ReferenceIndex
44
+ from tree_engine.core.short_id import ShortIdMap
45
+ from tree_engine.errors import ErrorCode
46
+ from tree_engine.exceptions import (
47
+ ChecksumMismatch, ConcurrentTreeModification, StorageIOError, TreeEngineException, TreePayloadInvalid,
48
+ TreeSchemaUnsupported, exception_for_code)
49
+ from tree_engine.plugins.fallback import PLAIN_TEXT_FORMAT_ID, build_fallback_tree
50
+ from tree_engine.plugins.selection import build_extension_table, resolve_format_plugin
51
+ from tree_engine.storage.codec import (
52
+ DecodedTreeFile, canonical_bytes, decode, encode, short_id_map_for)
53
+ from tree_engine.storage.file_txn import (
54
+ FileWrite, PairLockBusy, PublishHook, RecoveryReport, pair_lock, publish, recover)
55
+ from tree_engine.storage.schema import TreeFile, TreeFileEnvelope, TreeFileSchemaError
56
+ from tree_engine.storage.session_guard import (
57
+ ConflictResolutionPolicy, EditSession, source_sha256, tree_payload_sha256)
58
+
59
+ __all__ = ["DEFAULT_TREE_SUFFIX", "DEFAULT_JOURNAL_SUFFIX", "OpenedDocument", "PublishedPair",
60
+ "StorageLifecycle", "TreeAcceptance", "canonical_tree_payload", "validate_structure"]
61
+
62
+ PathLike = Union[str, Path]
63
+
64
+ #: Appended to the source file's own name, so the pair is discoverable from
65
+ #: either side and two documents in one directory never collide.
66
+ DEFAULT_TREE_SUFFIX = ".tree.json"
67
+
68
+ #: The pair's file-transaction journal; its presence at open time is the single
69
+ #: fact that says a publication was interrupted ({p090}).
70
+ DEFAULT_JOURNAL_SUFFIX = ".storage-journal"
71
+
72
+ def canonical_tree_payload(raw_tree_file_bytes: bytes) -> bytes:
73
+ """Canonical payload bytes of a tree file, for the session guard's digest.
74
+ Pins :class:`EditSession` to the canonicalization ``codec`` itself uses, so a
75
+ session baseline and a tree file's ``CHECKSUMS`` entry are the same number
76
+ ({p086}); anything undecodable is ``TreePayloadInvalid``."""
77
+ try:
78
+ data = json.loads(raw_tree_file_bytes.decode("utf-8"))
79
+ except (UnicodeDecodeError, ValueError) as exc:
80
+ raise TreePayloadInvalid(f"tree file is not valid UTF-8 JSON: {exc}") from exc
81
+ if not isinstance(data, Mapping):
82
+ raise TreePayloadInvalid(f"tree file must be a JSON object, got {type(data).__name__}")
83
+ try:
84
+ tree_file = TreeFile.from_dict(data)
85
+ except TreeFileSchemaError as exc:
86
+ raise TreePayloadInvalid(str(exc)) from exc
87
+ return canonical_bytes(tree_file.payload.to_dict())
88
+
89
+ @dataclass(frozen=True)
90
+ class _DocumentView:
91
+ """The duck-typed shape :func:`validate_full_document` documents."""
92
+ root: Node
93
+ reference_index: ReferenceIndex
94
+
95
+ def validate_structure(document: Document) -> None:
96
+ """Run the core's full structural validation over ``document`` ({p092}).
97
+ Projects the node graph onto a fresh :class:`ReferenceIndex` -- parent/child
98
+ from ``children``, short_ids from each node's own ``short_id``, outgoing edges
99
+ from ``references`` -- for :func:`validate_full_document`, which owns every
100
+ actual check. A node with no ``node_id`` is unindexable and skipped, as that
101
+ validator also skips it; a violation is ``TREE_PAYLOAD_INVALID``."""
102
+ index = ReferenceIndex()
103
+ edges: List[Tuple[Any, Sequence[Any]]] = []
104
+ stack: List[Tuple[Node, Any]] = [(document.root, None)]
105
+ try:
106
+ while stack:
107
+ node, parent_id = stack.pop()
108
+ node_id = node.node_id
109
+ if node_id is not None:
110
+ index.register_node(node_id, node, parent_id=parent_id, short_id=node.short_id)
111
+ if node.references:
112
+ edges.append((node_id, node.references))
113
+ for child in node.children:
114
+ stack.append((child, node_id if node_id is not None else parent_id))
115
+ for node_id, references in edges:
116
+ index.update_references(node_id, (), references)
117
+ except (ValueError, TypeError, AttributeError) as exc:
118
+ raise TreePayloadInvalid(f"tree structure cannot be indexed: {exc}") from exc
119
+ try:
120
+ validate_full_document(_DocumentView(document.root, index))
121
+ except FullIntegrityError as exc:
122
+ raise TreePayloadInvalid(f"tree structure is invalid: {exc}") from exc
123
+
124
+ @dataclass(frozen=True)
125
+ class OpenedDocument:
126
+ """One open document: the tree plus every file fact the tree must not hold.
127
+ ``document``/``short_id_map``/``envelope`` come off the accepted tree file,
128
+ ``session`` guards the accepted digests, ``rebuilt`` says the tree file was
129
+ rewritten here, ``fallback`` that the representation is the degraded plain-text
130
+ one, ``recovery`` what an interrupted publication left -- storage state, never
131
+ on ``document`` ({p025}, {p088}, {p090}, {p093})."""
132
+ document: Document
133
+ short_id_map: ShortIdMap
134
+ envelope: TreeFileEnvelope
135
+ source_path: Path
136
+ tree_path: Path
137
+ journal_path: Path
138
+ session: EditSession
139
+ source_sha256: str
140
+ tree_payload_sha256: str
141
+ format_id: str
142
+ rebuilt: bool
143
+ fallback: bool
144
+ recovery: RecoveryReport
145
+
146
+ @dataclass(frozen=True)
147
+ class TreeAcceptance:
148
+ """Everything the {p087} gates establish about one tree file's bytes.
149
+
150
+ ``decoded`` is the tree file when EVERY gate passed, including that it records
151
+ this exact source -- the only case in which it may be used as the document.
152
+ ``stored`` is the tree file when every gate except that one passed: a usable
153
+ tree that describes DIFFERENT source bytes. The two are distinguished because
154
+ which of them wins is not storage's decision to take: before a file is open
155
+ the file is the truth and a mismatch means reparse, but while a session holds
156
+ it the tree is the truth and the same mismatch means keep the tree. Only the
157
+ caller knows which of those it is in. ``stored_source_sha256`` is the digest
158
+ the file records, present whenever it decoded at all, and ``refusal`` names
159
+ the gate that refused it, so "rebuilt" is never reported without a reason."""
160
+ decoded: Optional[DecodedTreeFile]
161
+ stored: Optional[DecodedTreeFile]
162
+ stored_source_sha256: Optional[str]
163
+ refusal: Optional[str]
164
+
165
+
166
+ @dataclass(frozen=True)
167
+ class PublishedPair:
168
+ """What one publication of the source/tree pair actually put on disk.
169
+
170
+ ``written_paths`` is the exact set of files this call created or replaced,
171
+ in publication order -- the output a caller needs to STAGE the result
172
+ somewhere else (the editor commits them to its own per-session git repo)
173
+ without having to reconstruct the tree-file naming convention. On success
174
+ ``file_txn.publish`` leaves no journal, backup or temp file behind, so these
175
+ paths are the whole of the change. ``source_bytes`` are the bytes written to
176
+ ``source_path`` and the two digests are the ones recorded in the tree file,
177
+ so a caller never has to re-read a file to learn what it now holds."""
178
+ source_path: Path
179
+ tree_path: Path
180
+ written_paths: Tuple[Path, ...]
181
+ source_bytes: bytes
182
+ tree_bytes: bytes
183
+ source_sha256: str
184
+ tree_payload_sha256: str
185
+ envelope: TreeFileEnvelope
186
+
187
+
188
+ def _code_of(exc: BaseException) -> Optional[ErrorCode]:
189
+ """The catalog code an exception carries, under either the typed
190
+ hierarchy's ``code`` or the plugin/registry/selection ``error_code``."""
191
+ for attribute in ("code", "error_code"):
192
+ candidate = getattr(exc, attribute, None)
193
+ if isinstance(candidate, ErrorCode):
194
+ return candidate
195
+ return None
196
+
197
+ def _typed(exc: BaseException) -> BaseException:
198
+ """Map a neighbouring layer's error onto the typed hierarchy by its code.
199
+ Already-typed errors pass through; everything else becomes the class
200
+ :func:`exception_for_code` fixes, so a caller sees only
201
+ ``tree_engine.exceptions`` types and ``file_txn``'s own same-named
202
+ ``StorageIOError`` arrives as the catalog's, ``phase``/``path`` kept."""
203
+ if isinstance(exc, TreeEngineException):
204
+ return exc
205
+ code = _code_of(exc)
206
+ if code is None:
207
+ return exc
208
+ details = {name: str(value) for name, value in (
209
+ ("path", getattr(exc, "path", None)), ("phase", getattr(exc, "phase", None)),
210
+ ("plugin_id", getattr(exc, "plugin_id", None))) if value is not None}
211
+ return exception_for_code(code)(str(exc), **details)
212
+
213
+ def _call(operation: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
214
+ """Run a neighbouring call, translating its error via :func:`_typed`.
215
+
216
+ Any unclassified exception (one without a .code attribute) is wrapped into
217
+ UNSUPPORTED_TRANSLATION with a message naming the real exception type, following
218
+ the same pattern as facade._typed. This ensures JSON-RPC clients never receive
219
+ raw -32603 errors from unclassified exceptions."""
220
+ try:
221
+ return operation(*args, **kwargs)
222
+ except TreeEngineException:
223
+ raise
224
+ except Exception as exc: # noqa: BLE001 - re-raised as a catalog-typed error
225
+ typed = _typed(exc)
226
+ if typed is exc:
227
+ # Unclassified exception: wrap it the same way facade._typed does
228
+ message = (
229
+ f"internal engine error (unclassified {type(exc).__name__}): "
230
+ f"{exc or 'no message'}"
231
+ )
232
+ raise exception_for_code(ErrorCode.UNSUPPORTED_TRANSLATION)(message) from exc
233
+ raise typed from exc
234
+
235
+ def _is_fallback(envelope: TreeFileEnvelope) -> bool:
236
+ """True for a plain-text representation of a non-plain-text document ({p088})."""
237
+ return (envelope.representation_format_id == PLAIN_TEXT_FORMAT_ID
238
+ and envelope.source_format_id != PLAIN_TEXT_FORMAT_ID)
239
+
240
+ class StorageLifecycle:
241
+ """Open/save/reparse for the linked source-file and tree-file pair ({p085}).
242
+ ``registry`` is any object exposing ``get_format_plugin(format_id)``, in
243
+ practice ``plugins.registry.FormatPluginRegistry``; the extension table for
244
+ path-based selection is rebuilt from its loaded plugins per call unless a
245
+ fixed ``extension_table`` is given, as an entry-point-only deployment must."""
246
+ def __init__(self, registry: Any, *, extension_table: Optional[Mapping[str, str]] = None,
247
+ tree_suffix: str = DEFAULT_TREE_SUFFIX,
248
+ journal_suffix: str = DEFAULT_JOURNAL_SUFFIX,
249
+ tree_publish_hook: Optional[PublishHook] = None,
250
+ cross_process_lock: bool = True) -> None:
251
+ self._publish_hook = tree_publish_hook
252
+ self._cross_process_lock = cross_process_lock
253
+ self._registry = registry
254
+ self._extension_table = extension_table
255
+ self._tree_suffix = tree_suffix
256
+ self._journal_suffix = journal_suffix
257
+
258
+ def tree_path_for(self, source_path: PathLike) -> Path:
259
+ """The serialized tree file paired with ``source_path`` ({p085})."""
260
+ return Path(str(source_path) + self._tree_suffix)
261
+
262
+ def _publish(self, source: Path, files: Sequence[FileWrite], journal: Path) -> None:
263
+ """Publish ``files`` through ``file_txn`` under the pair lock, calling the publish hook.
264
+
265
+ ``reference_path`` for the hook is the pair's existing source file, or its parent
266
+ directory when no source exists yet."""
267
+ reference = source if source.exists() else source.parent
268
+ hook = self._publish_hook
269
+ if not self._cross_process_lock:
270
+ _call(publish, files, journal, before_publish=hook, reference_path=reference)
271
+ return
272
+ try:
273
+ with pair_lock(source):
274
+ _call(publish, files, journal, before_publish=hook, reference_path=reference)
275
+ except PairLockBusy as exc:
276
+ raise ConcurrentTreeModification(
277
+ f"another process is publishing {source}", path=str(source)) from exc
278
+
279
+ def journal_path_for(self, source_path: PathLike) -> Path:
280
+ """The file-transaction journal for this pair ({p090})."""
281
+ return Path(str(source_path) + self._journal_suffix)
282
+
283
+ def open(self, source_path: PathLike, *, format_id: Optional[str] = None) -> OpenedDocument:
284
+ """Open the pair, accepting a valid tree file without ``parse_document``.
285
+ Recovers an interrupted publication first ({p090}), then runs the {p087}
286
+ gates; a stale or damaged tree file falls through to {p088}'s rebuild.
287
+ Raises ``TreeSchemaUnsupported``/``FormatPluginNotFound``/
288
+ ``FormatPluginContractError`` for a file this build must not reinterpret."""
289
+ return self._open(source_path, format_id, force_rebuild=False)
290
+
291
+ def reparse(self, source_path: PathLike, *, format_id: Optional[str] = None) -> OpenedDocument:
292
+ """Force the rebuild branch even over a fully valid tree file: {p037}'s
293
+ explicit reparse -- parse (or fallback), encode, publish atomically,
294
+ reread, revalidate through :meth:`open`'s own branch."""
295
+ return self._open(source_path, format_id, force_rebuild=True)
296
+
297
+ explicit_reparse = reparse # {p037}'s spelling of the same operation
298
+
299
+ def save(self, opened: OpenedDocument, document: Optional[Document] = None, *,
300
+ policy: ConflictResolutionPolicy = ConflictResolutionPolicy.REFUSE,
301
+ short_id_map: Optional[ShortIdMap] = None,
302
+ format_metadata: Optional[Mapping[str, Any]] = None,
303
+ ) -> OpenedDocument:
304
+ """Publish the edited pair as one recoverable transaction ({p090}, {p091}).
305
+ Validates the tree fully, renders source bytes and the canonical payload
306
+ (neither touches disk), re-verifies both files against the session
307
+ baselines -- refusing with ``CONCURRENT_SOURCE_MODIFICATION`` or
308
+ ``CONCURRENT_TREE_MODIFICATION`` unless ``policy`` names the overwrite --
309
+ publishes both atomically, rereads, re-verifies both digests, advances the
310
+ baselines, then re-runs the acceptance branch; a post-publication mismatch
311
+ runs recovery and is re-raised. ``short_id_map``/``format_metadata`` are
312
+ carried through to :meth:`_encode`, which documents why a caller holding a
313
+ live map must pass it."""
314
+ target = opened.document if document is None else document
315
+ validate_structure(target)
316
+ plugin = self._plugin(target.representation_format_id)
317
+ source_bytes = _call(plugin.render_document, target)
318
+ digest = source_sha256(source_bytes)
319
+ tree_bytes = self._encode(
320
+ target, source_bytes, digest, plugin, document_id=opened.envelope.document_id,
321
+ document_version=opened.envelope.document_version + 1,
322
+ short_id_map=short_id_map, format_metadata=format_metadata)
323
+ payload_digest = tree_payload_sha256(canonical_tree_payload(tree_bytes))
324
+ opened.session.check_before_write(policy=policy)
325
+ self._publish(opened.source_path, [FileWrite(opened.source_path, source_bytes),
326
+ FileWrite(opened.tree_path, tree_bytes)], opened.journal_path)
327
+ try:
328
+ opened.session.accept_publication(digest, payload_digest)
329
+ except ChecksumMismatch:
330
+ _call(recover, [opened.source_path, opened.tree_path], opened.journal_path)
331
+ raise
332
+ accepted = self._accept(opened.tree_path, digest, strict=True)
333
+ return self._opened(
334
+ accepted, opened.source_path, opened.tree_path, opened.journal_path,
335
+ opened.session, digest, opened.format_id, rebuilt=False,
336
+ fallback=_is_fallback(accepted.envelope), recovery=opened.recovery)
337
+
338
+ def _open(self, source_path: PathLike, format_id: Optional[str], *,
339
+ force_rebuild: bool) -> OpenedDocument:
340
+ source = Path(source_path)
341
+ tree = self.tree_path_for(source)
342
+ journal = self.journal_path_for(source)
343
+ recovery: RecoveryReport = _call(recover, [source, tree], journal)
344
+ source_bytes = self._read(source)
345
+ digest = source_sha256(source_bytes)
346
+ plugin = self._resolve(source, format_id)
347
+ fmt = plugin.metadata.format_id
348
+ accepted = None if force_rebuild else self._accept(tree, digest)
349
+ rebuilt = accepted is None
350
+ fallback = False
351
+ if rebuilt:
352
+ fallback = self._rebuild(tree, journal, source_bytes, digest, plugin, fmt, source)
353
+ accepted = self._accept(tree, digest, strict=True)
354
+ session = EditSession(
355
+ source, tree, base_source_sha256=digest,
356
+ base_tree_payload_sha256=accepted.checksums.tree_payload_sha256,
357
+ tree_canonicalizer=canonical_tree_payload)
358
+ return self._opened(
359
+ accepted, source, tree, journal, session, digest, fmt,
360
+ rebuilt=rebuilt, fallback=fallback or _is_fallback(accepted.envelope),
361
+ recovery=recovery)
362
+
363
+ def accept_tree_bytes(self, tree_bytes: bytes, source_digest: str, *, strict: bool = False,
364
+ tree_path: Optional[Path] = None) -> TreeAcceptance:
365
+ """The {p087} acceptance gates over tree-file BYTES, touching no disk.
366
+ The decision half of :meth:`open`, exposed on its own so a caller holding
367
+ both files' bytes -- an editor that fetched them from somewhere that is
368
+ not this filesystem -- takes the same decision without a path, and takes
369
+ it without writing anything. See :class:`TreeAcceptance` for what the four
370
+ reported facts mean; gate order is exactly :meth:`open`'s, so a stale tree
371
+ file is still reported stale before any plugin is asked about it. Raises,
372
+ never rebuilds, for a file this build must not reinterpret (unknown major
373
+ schema, and -- for a tree file that does record this source -- an absent or
374
+ contract-incompatible plugin), and under ``strict``, the post-publication
375
+ reread, for every other gate too."""
376
+ label = f" {tree_path}" if tree_path is not None else ""
377
+ try:
378
+ decoded = decode(tree_bytes)
379
+ except TreeSchemaUnsupported:
380
+ raise
381
+ except (TreePayloadInvalid, ChecksumMismatch) as exc:
382
+ if strict:
383
+ raise
384
+ return TreeAcceptance(None, None, None, f"stored tree file{label} does not decode: {exc}")
385
+ stored_digest = decoded.checksums.source_sha256
386
+ if stored_digest != source_digest:
387
+ if strict:
388
+ raise ChecksumMismatch(
389
+ f"published tree file{label} records a stale source_sha256",
390
+ path=None if tree_path is None else str(tree_path),
391
+ expected_source_sha256=source_digest, actual_source_sha256=stored_digest)
392
+ stale = (f"stored tree file{label} records source_sha256 {stored_digest}, "
393
+ f"the source hashes to {source_digest}")
394
+ try:
395
+ usable, refusal = self._plugin_and_structure_gates(decoded, label)
396
+ except TreeEngineException as exc:
397
+ return TreeAcceptance(None, None, stored_digest, f"{stale}, and {exc}")
398
+ return TreeAcceptance(None, usable, stored_digest,
399
+ stale if usable is not None else refusal)
400
+ usable, refusal = self._plugin_and_structure_gates(decoded, label, strict=strict)
401
+ if usable is None:
402
+ return TreeAcceptance(None, None, stored_digest, refusal)
403
+ return TreeAcceptance(decoded, decoded, stored_digest, None)
404
+
405
+ def _plugin_and_structure_gates(self, decoded: DecodedTreeFile, label: str, *,
406
+ strict: bool = False,
407
+ ) -> Tuple[Optional[DecodedTreeFile], Optional[str]]:
408
+ """The two {p087} gates that ask about the tree itself rather than about
409
+ the source it records: the representation plugin must be installed and
410
+ contract-compatible (raising, never rebuilding), at the version that wrote
411
+ the file, and the node graph must pass full structural validation."""
412
+ plugin = self._representation_plugin(decoded.envelope)
413
+ if not strict and plugin.metadata.plugin_version != decoded.envelope.plugin_version:
414
+ return None, (f"stored tree file{label} was written by {decoded.envelope.plugin_id} "
415
+ f"{decoded.envelope.plugin_version}, the installed plugin is "
416
+ f"{plugin.metadata.plugin_version}")
417
+ try:
418
+ validate_structure(decoded.document)
419
+ except TreePayloadInvalid as exc:
420
+ if strict:
421
+ raise
422
+ return None, f"stored tree file{label} fails structural validation: {exc}"
423
+ return decoded, None
424
+
425
+ def _accept(self, tree_path: Path, source_digest: str, *,
426
+ strict: bool = False) -> Optional[DecodedTreeFile]:
427
+ """:meth:`accept_tree_bytes` over the tree file at ``tree_path``; an
428
+ absent file is the rebuild branch, or ``StorageIOError`` under ``strict``."""
429
+ if not tree_path.exists():
430
+ if strict:
431
+ raise StorageIOError(f"published tree file {tree_path} is missing",
432
+ path=str(tree_path), phase="reread")
433
+ return None
434
+ return self.accept_tree_bytes(self._read(tree_path), source_digest, strict=strict,
435
+ tree_path=tree_path).decoded
436
+
437
+ def _representation_plugin(self, envelope: TreeFileEnvelope) -> Any:
438
+ """Plugin gate of {p087}: absent is ``FORMAT_PLUGIN_NOT_FOUND``, an
439
+ incompatible ``contract_version`` major ``FORMAT_PLUGIN_CONTRACT_ERROR``;
440
+ neither allows a fallback or a rebuild."""
441
+ plugin = self._plugin(envelope.plugin_id)
442
+ declared = plugin.metadata.contract_version
443
+ if declared.split(".", 1)[0] != envelope.plugin_contract_version.split(".", 1)[0]:
444
+ raise exception_for_code(ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR)(
445
+ f"tree file declares plugin_contract_version "
446
+ f"{envelope.plugin_contract_version!r}, but the installed "
447
+ f"{envelope.plugin_id!r} plugin declares {declared!r}",
448
+ plugin_id=envelope.plugin_id)
449
+ return plugin
450
+
451
+ def _rebuild(self, tree_path: Path, journal_path: Path, source_bytes: bytes,
452
+ digest: str, plugin: Any, format_id: str,
453
+ source_path: Optional[Path] = None) -> bool:
454
+ """Rebuild from source ({p088}) and publish the tree file atomically.
455
+ Only a classified ``FORMAT_CONTENT_PARSE_FAILED`` opens the C-013
456
+ sibling's fallback; any other diagnostic propagates."""
457
+ document, fallback = self._parse(plugin, source_bytes, format_id)
458
+ representation = self._plugin(PLAIN_TEXT_FORMAT_ID) if fallback else plugin
459
+ validate_structure(document)
460
+ tree_bytes = self._encode(document, source_bytes, digest, representation)
461
+ self._publish(source_path if source_path is not None else tree_path,
462
+ [FileWrite(tree_path, tree_bytes)], journal_path)
463
+ return fallback
464
+
465
+ def _parse(self, plugin: Any, source_bytes: bytes, format_id: str) -> Tuple[Document, bool]:
466
+ try:
467
+ return plugin.parse_document(source_bytes, source_format_id=format_id), False
468
+ except TreeEngineException as exc:
469
+ # A typed error is already classified, but "already typed" must not
470
+ # mean "never rescued": FormatContentParseFailed IS the fallback
471
+ # trigger, and plugins split across two exception carriers. Keying
472
+ # only on the older one left json/toml/yaml with no fallback at all.
473
+ if _code_of(exc) is not ErrorCode.FORMAT_CONTENT_PARSE_FAILED:
474
+ raise
475
+ return build_fallback_tree(source_bytes, exc, source_format_id=format_id).document, True
476
+ except Exception as exc: # noqa: BLE001 - classified below, never swallowed
477
+ if _code_of(exc) is not ErrorCode.FORMAT_CONTENT_PARSE_FAILED:
478
+ typed = _typed(exc)
479
+ if typed is exc:
480
+ raise
481
+ raise typed from exc
482
+ return build_fallback_tree(source_bytes, exc, source_format_id=format_id).document, True
483
+
484
+ def _encode(self, document: Document, source_bytes: bytes, digest: str, plugin: Any,
485
+ *, document_id: Optional[Any] = None, document_version: int = 0,
486
+ short_id_map: Optional[ShortIdMap] = None,
487
+ format_metadata: Optional[Mapping[str, Any]] = None) -> bytes:
488
+ """Serialize through the codec with the plugin identity the gate checks
489
+ and the ``source_sha256`` of these exact bytes ({p085}). ``short_id_map``
490
+ is the caller's LIVE map when it has one: deriving the map from the
491
+ document's own nodes recovers every issued short_id but not the monotonic
492
+ ``next_short_id`` counter above them, so a value released by a delete
493
+ would come back into circulation on the next reload -- the one thing
494
+ {p097} forbids. ``format_metadata`` rides in the envelope for facts that
495
+ belong to the representation rather than the tree, the plain-text
496
+ fallback's diagnostic being the one this build carries."""
497
+ metadata = plugin.metadata
498
+ return _call(
499
+ encode, document,
500
+ short_id_map=short_id_map if short_id_map is not None else short_id_map_for(document),
501
+ document_id=document_id, document_version=document_version,
502
+ source_sha256=digest, plugin_id=metadata.format_id,
503
+ plugin_version=metadata.plugin_version,
504
+ plugin_contract_version=metadata.contract_version,
505
+ trailing_newline=source_bytes.endswith(b"\n"),
506
+ format_metadata=dict(format_metadata or {}))
507
+
508
+ def publish_pair(self, source_path: PathLike, document: Document, *,
509
+ short_id_map: Optional[ShortIdMap] = None,
510
+ format_metadata: Optional[Mapping[str, Any]] = None,
511
+ document_version: int = 0) -> PublishedPair:
512
+ """Render ``document`` and publish the source/tree pair at ``source_path``
513
+ as one recoverable transaction ({p090}), reporting exactly what was
514
+ written. The unsessioned counterpart of :meth:`save`: it takes no
515
+ :class:`OpenedDocument` and checks no baseline, because it is the write a
516
+ caller performs when IT -- not this layer -- owns the concurrency story
517
+ (the editor holds the session and commits the result to its own git
518
+ repository). Everything else is :meth:`save`'s discipline unchanged:
519
+ structural validation first, both files published atomically, then the
520
+ published tree file reread and revalidated through the same strict
521
+ acceptance branch, so no unvalidated tree is ever reported as written."""
522
+ source = Path(source_path)
523
+ tree, journal = self.tree_path_for(source), self.journal_path_for(source)
524
+ validate_structure(document)
525
+ plugin = self._plugin(document.representation_format_id)
526
+ source_bytes = _call(plugin.render_document, document)
527
+ digest = source_sha256(source_bytes)
528
+ tree_bytes = self._encode(document, source_bytes, digest, plugin,
529
+ document_id=document.document_id,
530
+ document_version=document_version,
531
+ short_id_map=short_id_map, format_metadata=format_metadata)
532
+ accepted = self._publish_and_accept(source, tree, journal, source_bytes, tree_bytes, digest)
533
+ return PublishedPair(
534
+ source_path=source, tree_path=tree, written_paths=(source, tree),
535
+ source_bytes=source_bytes, tree_bytes=tree_bytes, source_sha256=digest,
536
+ tree_payload_sha256=accepted.checksums.tree_payload_sha256,
537
+ envelope=accepted.envelope)
538
+
539
+ def _publish_and_accept(self, source: Path, tree: Path, journal: Path, source_bytes: bytes,
540
+ tree_bytes: bytes, digest: str) -> DecodedTreeFile:
541
+ """Publish the pair and reread the tree strictly, both under one pair lock."""
542
+ reference = source if source.exists() else source.parent
543
+ files = [FileWrite(source, source_bytes), FileWrite(tree, tree_bytes)]
544
+ hook = self._publish_hook
545
+ if not self._cross_process_lock:
546
+ _call(publish, files, journal, before_publish=hook, reference_path=reference)
547
+ return self._accept(tree, digest, strict=True)
548
+ try:
549
+ with pair_lock(source):
550
+ _call(publish, files, journal, before_publish=hook, reference_path=reference)
551
+ return self._accept(tree, digest, strict=True)
552
+ except PairLockBusy as exc:
553
+ raise ConcurrentTreeModification(
554
+ f"another process is publishing {source}", path=str(source)) from exc
555
+
556
+ def encode_tree(self, document: Document, source_bytes: bytes, *,
557
+ short_id_map: Optional[ShortIdMap] = None,
558
+ format_metadata: Optional[Mapping[str, Any]] = None,
559
+ document_version: int = 0) -> bytes:
560
+ """Serialize the tree file for ``document`` over ``source_bytes``, writing NOTHING.
561
+
562
+ The tree file is a DERIVED artefact of a source this call must not alter, so the
563
+ ``source_sha256`` it records is the digest of ``source_bytes`` exactly as given -- never of
564
+ a re-render of the document. That is what lets the next open of those untouched bytes take
565
+ the checksum-match branch. It also means the caller owes one check before persisting the
566
+ result: a document whose render does NOT reproduce ``source_bytes`` would be stored under a
567
+ digest it does not correspond to, and reloading it would silently hand back a tree that is
568
+ not the file. :meth:`publish_pair` has no such duty, because there the source is written
569
+ from the same render."""
570
+ validate_structure(document)
571
+ plugin = self._plugin(document.representation_format_id)
572
+ return self._encode(document, source_bytes, source_sha256(source_bytes), plugin,
573
+ document_id=document.document_id, document_version=document_version,
574
+ short_id_map=short_id_map, format_metadata=format_metadata)
575
+
576
+ def publish_tree_only(self, source_path: PathLike, tree_bytes: bytes) -> Path:
577
+ """Publish the derived tree file beside ``source_path`` and NOT the source itself.
578
+
579
+ The source file is not in this transaction at all -- it is not read, not rewritten, not
580
+ normalised -- which is the guarantee an open has to make: opening a document may bring its
581
+ derived tree file into existence or up to date, and may never change the document. Returns
582
+ the tree path written."""
583
+ source = Path(source_path)
584
+ tree = self.tree_path_for(source)
585
+ self._publish(source, [FileWrite(tree, tree_bytes)], self.journal_path_for(source))
586
+ return tree
587
+
588
+ def publish_source_only(self, source_path: PathLike, source_bytes: bytes) -> Path:
589
+ """Publish the source file alone, with no tree file beside it ({p090}). The degraded write:
590
+ for a format whose plugin cannot be encoded into a tree file there is no second artefact to
591
+ publish, and writing one half of a pair is the honest outcome rather than a fabricated
592
+ tree. Returns the source path written."""
593
+ source = Path(source_path)
594
+ self._publish(source, [FileWrite(source, source_bytes)], self.journal_path_for(source))
595
+ return source
596
+
597
+ def _opened(self, accepted: DecodedTreeFile, source: Path, tree: Path, journal: Path,
598
+ session: EditSession, digest: str, format_id: str, *, rebuilt: bool,
599
+ fallback: bool, recovery: RecoveryReport) -> OpenedDocument:
600
+ return OpenedDocument(
601
+ document=accepted.document, short_id_map=accepted.short_id_map,
602
+ envelope=accepted.envelope, source_path=source, tree_path=tree,
603
+ journal_path=journal, session=session, source_sha256=digest,
604
+ tree_payload_sha256=accepted.checksums.tree_payload_sha256,
605
+ format_id=format_id, rebuilt=rebuilt, fallback=fallback, recovery=recovery)
606
+
607
+ def _plugin(self, format_id: str) -> Any:
608
+ return _call(self._registry.get_format_plugin, format_id)
609
+
610
+ def _resolve(self, source: Path, format_id: Optional[str]) -> Any:
611
+ table = self._extension_table
612
+ if table is None:
613
+ table = build_extension_table(_call(self._registry.list_format_plugins))
614
+ return _call(resolve_format_plugin, format_id=format_id, file_path=str(source),
615
+ registry=self._registry, extension_table=table)
616
+
617
+ def _read(self, path: Path) -> bytes:
618
+ try:
619
+ return path.read_bytes()
620
+ except OSError as exc:
621
+ raise StorageIOError(f"cannot read {path}: {exc}",
622
+ path=str(path), phase="read") from exc