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,579 @@
1
+ """The join between the stored source/tree pair and the MUTABLE working tree.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the one seam the storage layer and the mutation layer never had. ``storage/lifecycle.py``
7
+ and ``storage/codec.py`` speak the IMMUTABLE ``core.nodes.Document``; every mutating operation --
8
+ and therefore every facade command -- speaks the MUTABLE ``core.live_tree.TreeDocument``. With no
9
+ converter between them the facade's ``load``/``save`` could not route through storage at all, which
10
+ is why their docstrings said so verbatim, and why node identity was not in fact persisted anywhere:
11
+ a reopened document reparsed its source and ``reindex()`` minted a brand-new short_id map. Identity
12
+ that is not persisted is not identity. This module supplies both directions --
13
+ :func:`to_tree_document`, :func:`to_frozen_document` -- and SEEDS the live document's
14
+ ``short_id_map`` from the stored one, which is the whole point: without the seed the reload keeps
15
+ the ``node_id`` and loses the ``short_id``, and the frozen editor API addresses nodes by short_id.
16
+
17
+ **The open decision, and why it is four branches and not two.** The owner's rule is that on OPEN
18
+ the source file is the truth and on WRITE the tree is; on reopen the recorded ``source_sha256``
19
+ decides between them. But a mismatch means two different things depending on one fact this layer
20
+ cannot know -- whether some session currently holds the file open. Before a file is opened the
21
+ bytes on disk are the truth and a mismatch means reparse with fresh identity; while a session holds
22
+ it the tree is the truth and the same mismatch means keep the stored tree, because the source on
23
+ disk is the stale one. So :class:`OpenBranch` carries all four cases under the names the editor's
24
+ own ``sha_sync_policy.ShaSyncBranch`` already uses for them (its "sidecar" is this engine's tree
25
+ file), and ``active_session_holds_file`` is a caller-supplied fact: the engine has no session
26
+ registry and must not grow one.
27
+
28
+ **What an open may and may not write.** The SOURCE file is immutable here: an open never rewrites
29
+ it, never repairs it and never normalises it, and it is not even part of the file transaction that
30
+ an open performs. The TREE file is a derived artefact and is persisted: created when absent,
31
+ refreshed when it disagrees with the source. That is not a violation of a read-only open, it is
32
+ what makes one useful -- a preview that reparses from scratch every time has no identity to hand
33
+ out and no history to record. :meth:`DocumentStore.open_file` therefore acts on the intent it
34
+ computes, while :meth:`DocumentStore.open_bytes` -- which holds content and no paths -- computes
35
+ the same intent, hands back the exact bytes to write, and touches no filesystem at all. Either way
36
+ the intent is reported, because the caller must know which paths changed in order to checkpoint
37
+ them, and :class:`WrittenPair` reports the same for a write.
38
+
39
+ **History.** Recording a document's history is part of this engine's lifecycle, not a favour a
40
+ consumer does afterwards: a checkpoint is taken when a document is opened and after every write,
41
+ by this module, through the :mod:`tree_engine.storage.history` port. The port is all the engine
42
+ knows -- it never creates or locates a store of any kind, and this module names no version-control
43
+ system. A consumer that supplies no port simply has no history recorded.
44
+
45
+ Source-of-truth labels honored here: {p085}-{p094}, {p097}, {p100}.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import uuid
51
+ from dataclasses import dataclass, replace as _replace
52
+ from enum import Enum
53
+ from pathlib import Path
54
+ from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, Union
55
+
56
+ from tree_engine.core.live_tree import TreeDocument, to_frozen, to_live, walk
57
+ from tree_engine.core.nodes import Document
58
+ from tree_engine.core.short_id import ShortIdMap
59
+ from tree_engine.exceptions import (
60
+ ConcurrentTreeModification, NodeIdConflict, ShortIdConflict, StorageIOError,
61
+ TreeEngineException, TreePayloadInvalid)
62
+ from tree_engine.plugins.fallback import PLAIN_TEXT_FORMAT_ID
63
+ from tree_engine.storage.codec import DecodedTreeFile
64
+ from tree_engine.storage.history import Checkpoint, CheckpointKind, HistoryPort
65
+ from tree_engine.storage.lifecycle import StorageLifecycle, canonical_tree_payload
66
+ from tree_engine.storage.session_guard import source_sha256, tree_payload_sha256
67
+
68
+ __all__ = ["FALLBACK_DIAGNOSTIC_KEY", "DocumentStore", "OpenBranch", "OpenedTree",
69
+ "TreeWriteIntent", "WrittenPair", "to_frozen_document", "to_tree_document"]
70
+
71
+ #: Envelope ``format_metadata`` key under which the plain-text fallback's structured diagnostic is
72
+ #: persisted. The fallback is a property of the REPRESENTATION, not of the tree, so the envelope is
73
+ #: where it belongs; without it a document that degraded to plain text would come back from its own
74
+ #: tree file unable to say why it is not in its source format.
75
+ FALLBACK_DIAGNOSTIC_KEY = "fallback_diagnostic"
76
+
77
+
78
+ class OpenBranch(str, Enum):
79
+ """Which of the four open cases the checksum decision landed in.
80
+
81
+ The names are the editor's (``ai_editor.commands.universal_file_edit.sha_sync_policy``), so the
82
+ two implementations of one rule are readably the same rule. ``NO_SIDECAR`` covers an absent
83
+ tree file AND one no gate would accept -- undecodable, structurally invalid, or written by a
84
+ plugin version this build does not have -- because in both cases there is no usable stored tree
85
+ and the source is all there is; :attr:`OpenedTree.refusal` says which it was.
86
+ """
87
+
88
+ NO_SIDECAR = "no_sidecar"
89
+ SHA_MATCH = "sha_match"
90
+ SHA_MISMATCH_NO_SESSION = "sha_mismatch_no_session"
91
+ SHA_MISMATCH_ACTIVE_SESSION = "sha_mismatch_active_session"
92
+ #: A foreign (undecodable) tree file whose node identity a caller-supplied ``sidecar_adopter``
93
+ #: mapped onto the freshly parsed source.
94
+ FOREIGN_TREE_ADOPTED = "foreign_tree_adopted"
95
+
96
+
97
+ class TreeWriteIntent(str, Enum):
98
+ """What has to happen to the tree file for it to describe the document just opened.
99
+
100
+ ``CREATE`` when there was no usable tree file, ``REPLACE`` when there was one and the source
101
+ superseded it, ``NONE`` when the stored tree IS the document or when no tree file can be
102
+ produced for this format at all. :meth:`DocumentStore.open_file` acts on it; the byte-level
103
+ open reports it and leaves the acting to a caller that owns the paths."""
104
+
105
+ NONE = "none"
106
+ CREATE = "create"
107
+ REPLACE = "replace"
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class OpenedTree:
112
+ """One open, its evidence, and the derived artefact it produced.
113
+
114
+ ``identity_preserved`` is the single fact a caller most often needs: True when every node came
115
+ back with the ``node_id`` AND ``short_id`` it was issued before, False when the tree was rebuilt
116
+ from source and identity is fresh. It is exactly ``branch`` in {SHA_MATCH,
117
+ SHA_MISMATCH_ACTIVE_SESSION}, restated as a boolean so no caller has to re-derive the rule.
118
+
119
+ ``tree_bytes`` are the serialized tree file for this document -- the stored bytes when they
120
+ were accepted, freshly encoded ones when the tree was rebuilt -- so a byte-level caller can act
121
+ on ``tree_write_intent`` without re-deriving anything. It is None only when no tree file can be
122
+ produced, and then ``tree_unavailable`` says why and the intent is ``NONE``: an intent that
123
+ cannot be acted on would be a lie. ``written_paths`` is what THIS call wrote, which is the
124
+ tree file or nothing, and never the source. ``refusal`` says why a supplied tree file was not
125
+ used, and is None when none was supplied or when it was accepted."""
126
+
127
+ document: TreeDocument
128
+ branch: OpenBranch
129
+ identity_preserved: bool
130
+ tree_write_intent: TreeWriteIntent
131
+ source_sha256: str
132
+ stored_source_sha256: Optional[str] = None
133
+ tree_path: Optional[Path] = None
134
+ tree_bytes: Optional[bytes] = None
135
+ tree_unavailable: Optional[str] = None
136
+ written_paths: Tuple[Path, ...] = ()
137
+ refusal: Optional[str] = None
138
+ checkpoint_id: Optional[str] = None
139
+ adopted_node_count: int = 0
140
+ unmatched_legacy_count: int = 0
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class WrittenPair:
145
+ """What one write actually put on disk, for a caller that has to stage it.
146
+
147
+ ``written_paths`` is the whole of the change, in publication order -- the source file and, for
148
+ a format whose plugin implements the storage half of the plugin contract, its tree file. On
149
+ success the file transaction leaves no journal, backup or temp file behind, so there is nothing
150
+ else to stage. ``tree_path``/``tree_bytes``/``tree_payload_sha256`` are None only for a format
151
+ plugin that cannot render a document into the storage layer, in which case identity was not
152
+ persisted at all and the source file was written alone."""
153
+
154
+ source_path: Path
155
+ tree_path: Optional[Path]
156
+ written_paths: Tuple[Path, ...]
157
+ source_bytes: bytes
158
+ source_sha256: str
159
+ tree_bytes: Optional[bytes] = None
160
+ tree_payload_sha256: Optional[str] = None
161
+ checkpoint_id: Optional[str] = None
162
+
163
+
164
+ def _records_a_fallback(decoded: Optional[DecodedTreeFile]) -> bool:
165
+ """True when a stored tree holds the degraded plain-text representation of another format
166
+ ({p088}) -- the thing ``allow_plain_text_fallback=False`` refuses to be given."""
167
+ return (decoded is not None
168
+ and decoded.document.format_id == PLAIN_TEXT_FORMAT_ID
169
+ and decoded.document.source_format_id != PLAIN_TEXT_FORMAT_ID)
170
+
171
+
172
+ def to_tree_document(decoded: DecodedTreeFile, source_bytes: bytes, *,
173
+ path: Optional[Path] = None,
174
+ short_id_order: Optional[Callable[[TreeDocument], Sequence[Any]]] = None
175
+ ) -> TreeDocument:
176
+ """Rebuild the mutable working document from an accepted tree file, identity intact.
177
+
178
+ The stored ``short_id_map`` is SEEDED into the live document rather than rebuilt: it is what
179
+ tells ``reindex()`` that a node already owns short_id 7, and it carries the monotonic
180
+ ``next_short_id`` above every value ever issued, so a short_id freed by an earlier delete is
181
+ still never reused across the reload ({p097}). The envelope's ``document_id`` is carried too,
182
+ so a persisted cross-document reference and a ``"document_id:node_id"`` address still resolve
183
+ after a reopen, and the fallback diagnostic is restored from ``format_metadata`` so a degraded
184
+ document still knows why it is degraded."""
185
+ diagnostic = decoded.envelope.format_metadata.get(FALLBACK_DIAGNOSTIC_KEY)
186
+ document = TreeDocument(
187
+ to_live(decoded.document.root), decoded.document.source_format_id,
188
+ decoded.document.format_id, source_bytes, path=path,
189
+ fallback_diagnostic=diagnostic if isinstance(diagnostic, Mapping) else None,
190
+ short_id_map=decoded.short_id_map, short_id_order=short_id_order)
191
+ document.document_id = decoded.envelope.document_id
192
+ return document
193
+
194
+
195
+ def to_frozen_document(document: TreeDocument) -> Document:
196
+ """The immutable ``core.nodes.Document`` the storage layer and the codec render and encode.
197
+
198
+ The inverse of :func:`to_tree_document` for everything storage reads: the node graph through
199
+ ``to_frozen`` (which carries each node's ``node_id`` and ``short_id`` across unchanged, so the
200
+ encoder's map is the live one), both format ids, and the ``document_id`` -- which is what makes
201
+ a save/reload keep the same document identity instead of minting one per open."""
202
+ frozen = Document(root=to_frozen(document.root), source_format_id=document.source_format_id,
203
+ representation_format_id=document.format_id)
204
+ frozen.document_id = document.document_id
205
+ return frozen
206
+
207
+
208
+ class DocumentStore:
209
+ """The facade's storage half: open a document from bytes or from a path, and write the pair.
210
+
211
+ Constructed once with the registry the facade itself resolves plugins through, so a format
212
+ registered with the facade is immediately storable. ``parse_source`` is the facade's own
213
+ ``loads`` and ``render_source`` its ``dumps``, injected rather than imported so this module
214
+ stays below the facade in the import order; going through them also means the rebuild branch
215
+ keeps the facade's own plugin resolution and its single authorized plain-text fallback instead
216
+ of a second copy of either. ``history`` is the default :class:`HistoryPort` for every call, and
217
+ any call may override it; with none, nothing is recorded.
218
+ """
219
+
220
+ def __init__(self, registry: Any, *, parse_source: Callable[..., TreeDocument],
221
+ render_source: Callable[[TreeDocument], bytes],
222
+ extension_table: Optional[Mapping[str, str]] = None,
223
+ lifecycle: Optional[StorageLifecycle] = None,
224
+ history: Optional[HistoryPort] = None,
225
+ short_id_order: Optional[Callable[[TreeDocument], Sequence[Any]]] = None,
226
+ sidecar_adopter: Optional[Callable[[bytes, bytes], Any]] = None) -> None:
227
+ self._sidecar_adopter = sidecar_adopter
228
+ self._registry = registry
229
+ self._parse_source = parse_source
230
+ self._render_source = render_source
231
+ self._history = history
232
+ self._short_id_order = short_id_order
233
+ self._lifecycle = (StorageLifecycle(registry, extension_table=extension_table)
234
+ if lifecycle is None else lifecycle)
235
+
236
+ @property
237
+ def lifecycle(self) -> StorageLifecycle:
238
+ """The storage lifecycle this store drives, for a caller that needs the pair's paths."""
239
+ return self._lifecycle
240
+
241
+ def tree_path_for(self, source_path: Union[str, Path]) -> Path:
242
+ """Where the tree file for ``source_path`` lives ({p085})."""
243
+ return self._lifecycle.tree_path_for(source_path)
244
+
245
+ def open_bytes(self, source: Union[str, bytes], *, tree: Optional[bytes] = None,
246
+ format_id: Optional[str] = None, file_path: Optional[str] = None,
247
+ allow_plain_text_fallback: bool = True,
248
+ active_session_holds_file: bool = False,
249
+ history: Optional[HistoryPort] = None,
250
+ path: Optional[Path] = None,
251
+ open_options: Optional[Mapping[str, Any]] = None) -> OpenedTree:
252
+ """Decide the open from bytes alone: source bytes, and the stored tree file's bytes when
253
+ the caller has them. Pure with respect to the filesystem -- it reads nothing and writes
254
+ nothing -- so it is the entry point for a consumer that fetched both files from somewhere
255
+ else entirely, and for one that must not create files where they live. The tree file the
256
+ decision calls for is returned as bytes, for that caller to persist as it sees fit."""
257
+ outcome = self._decide(source, tree, format_id, file_path, allow_plain_text_fallback,
258
+ active_session_holds_file, path, open_options)
259
+ return self._checkpointed(outcome, CheckpointKind.OPEN, history)
260
+
261
+ def open_file(self, path: Union[str, Path], *, format_id: Optional[str] = None,
262
+ allow_plain_text_fallback: bool = True,
263
+ active_session_holds_file: bool = False,
264
+ history: Optional[HistoryPort] = None,
265
+ open_options: Optional[Mapping[str, Any]] = None) -> OpenedTree:
266
+ """:meth:`open_bytes` over a real pair on disk, acting on the intent it computes.
267
+
268
+ The source file is READ and never written: it takes no part in the file transaction this
269
+ performs, so its bytes and its mtime are the same afterwards whatever the decision was. The
270
+ derived tree file is created when there is none and refreshed when the source has
271
+ superseded it, which is what gives the next open identity to hand out and this one a full
272
+ checkpoint to record. An unreadable source is a typed ``StorageIOError``; an unreadable
273
+ tree file is simply no tree file, which is the rebuild branch."""
274
+ source = Path(path)
275
+ try:
276
+ source_bytes = source.read_bytes()
277
+ except OSError as exc:
278
+ raise StorageIOError(f"cannot read {source}: {exc}", path=str(source),
279
+ phase="read") from exc
280
+ try:
281
+ tree_bytes: Optional[bytes] = self.tree_path_for(source).read_bytes()
282
+ except OSError:
283
+ tree_bytes = None
284
+ outcome = self._decide(source_bytes, tree_bytes, format_id, str(source),
285
+ allow_plain_text_fallback, active_session_holds_file, source,
286
+ open_options)
287
+ if outcome.tree_write_intent is not TreeWriteIntent.NONE and outcome.tree_bytes is not None:
288
+ try:
289
+ written = self._lifecycle.publish_tree_only(source, outcome.tree_bytes)
290
+ outcome = _replace(outcome, written_paths=(written,))
291
+ except ConcurrentTreeModification:
292
+ # Another process is publishing this pair: a read is never failed by the lock.
293
+ # The document is returned and the intent reported with nothing written.
294
+ pass
295
+ return self._checkpointed(outcome, CheckpointKind.OPEN, history)
296
+
297
+ def write(self, document: TreeDocument, path: Optional[Union[str, Path]] = None, *,
298
+ history: Optional[HistoryPort] = None) -> WrittenPair:
299
+ """Render ``document`` and publish the source/tree pair, reporting every path written.
300
+
301
+ This is where identity is persisted through an edit: the tree file carries each node's
302
+ ``node_id``/``short_id`` and the live ``short_id_map`` with its monotonic counter, so the
303
+ next open of these bytes takes the SHA_MATCH branch and every surviving node keeps both
304
+ identifiers. A format plugin that does not implement the storage half of the plugin
305
+ contract -- ``render_document``, the marker of ``core.plugin_boundary.FormatBoundary`` --
306
+ cannot be encoded into a tree file at all; its source is published alone and the returned
307
+ ``tree_path`` is None, so a caller is told plainly that identity was not persisted rather
308
+ than being left to assume it was. A checkpoint is recorded once the publication has been
309
+ verified on disk, never before."""
310
+ target = Path(path) if path is not None else document.path
311
+ if target is None:
312
+ raise StorageIOError("save() needs a path: this document came from loads(), not a file")
313
+ plugin = self._registry.get_format_plugin(document.format_id)
314
+ if not callable(getattr(plugin, "render_document", None)):
315
+ content = self._render_source(document)
316
+ self._lifecycle.publish_source_only(target, content)
317
+ document.path, document.source_bytes = target, content
318
+ pair = WrittenPair(source_path=target, tree_path=None, written_paths=(target,),
319
+ source_bytes=content, source_sha256=source_sha256(content))
320
+ return _replace(pair, checkpoint_id=self._record(
321
+ CheckpointKind.WRITE, document, pair.source_bytes, pair.source_sha256,
322
+ tree_path=None, tree_bytes=None, written_paths=pair.written_paths, branch=None,
323
+ history=history))
324
+ published = self._lifecycle.publish_pair(
325
+ target, to_frozen_document(document), short_id_map=document.short_id_map,
326
+ format_metadata=self._format_metadata(document),
327
+ document_version=document.document_version)
328
+ document.path, document.source_bytes = published.source_path, published.source_bytes
329
+ pair = WrittenPair(
330
+ source_path=published.source_path, tree_path=published.tree_path,
331
+ written_paths=published.written_paths, source_bytes=published.source_bytes,
332
+ source_sha256=published.source_sha256, tree_bytes=published.tree_bytes,
333
+ tree_payload_sha256=published.tree_payload_sha256)
334
+ return _replace(pair, checkpoint_id=self._record(
335
+ CheckpointKind.WRITE, document, pair.source_bytes, pair.source_sha256,
336
+ tree_path=pair.tree_path, tree_bytes=pair.tree_bytes,
337
+ written_paths=pair.written_paths, branch=None, history=history))
338
+
339
+ # -- the decision itself ----------------------------------------------------
340
+
341
+ def _decide(self, source: Union[str, bytes], tree: Optional[bytes], format_id: Optional[str],
342
+ file_path: Optional[str], allow_plain_text_fallback: bool,
343
+ active_session_holds_file: bool, path: Optional[Path],
344
+ open_options: Optional[Mapping[str, Any]] = None) -> OpenedTree:
345
+ """The four-branch checksum decision, with no checkpoint and no write."""
346
+ source_bytes = source.encode("utf-8") if isinstance(source, str) else bytes(source)
347
+ digest = source_sha256(source_bytes)
348
+ tree_path = None if path is None else self.tree_path_for(path)
349
+ if tree is None:
350
+ return self._rebuilt(source_bytes, digest, OpenBranch.NO_SIDECAR,
351
+ TreeWriteIntent.CREATE, format_id, file_path,
352
+ allow_plain_text_fallback, path, tree_path, None, None,
353
+ open_options=open_options)
354
+ acceptance = self._lifecycle.accept_tree_bytes(tree, digest, tree_path=tree_path)
355
+ if self._sidecar_adopter is not None and acceptance.stored_source_sha256 is None:
356
+ # A foreign tree file: it does not decode as an engine tree at all.
357
+ mapping = self._sidecar_adopter(bytes(tree), source_bytes)
358
+ if mapping is not None:
359
+ return self._rebuilt(source_bytes, digest, OpenBranch.FOREIGN_TREE_ADOPTED,
360
+ TreeWriteIntent.REPLACE, format_id, file_path,
361
+ allow_plain_text_fallback, path, tree_path, None,
362
+ acceptance.refusal, adoption=self._checked_mapping(mapping),
363
+ open_options=open_options)
364
+ if not allow_plain_text_fallback and _records_a_fallback(acceptance.stored):
365
+ # A caller that declined the degraded representation must not be handed one out of
366
+ # storage either: the stored tree IS a plain-text fallback of another format, so
367
+ # accepting it would answer "no fallback" with a fallback.
368
+ acceptance = _replace(
369
+ acceptance, decoded=None, stored=None,
370
+ refusal=f"stored tree file{'' if tree_path is None else f' {tree_path}'} holds "
371
+ "the plain-text fallback representation, which this call declined")
372
+ if (format_id not in (None, PLAIN_TEXT_FORMAT_ID) and acceptance.stored is not None
373
+ and acceptance.stored.document.format_id == PLAIN_TEXT_FORMAT_ID):
374
+ # Bug ec1b9aa4: a line-fallback session of a structured file (a broken .json opened
375
+ # as plain text) commits a plain-text tree whose source_format_id is plain_text too,
376
+ # so its checksum matches the repaired source. Accepting it for a call that names a
377
+ # structured format hands out the plain-text node ids (7,8,9) over a tree of that
378
+ # format, and no returned ref resolves. Rebuild from source instead.
379
+ acceptance = _replace(
380
+ acceptance, decoded=None, stored=None,
381
+ refusal=f"stored tree file{'' if tree_path is None else f' {tree_path}'} holds "
382
+ f"the plain-text representation, but format {format_id!r} was requested")
383
+ if acceptance.decoded is not None:
384
+ return OpenedTree(
385
+ document=to_tree_document(
386
+ acceptance.decoded,
387
+ source_bytes,
388
+ path=path,
389
+ short_id_order=self._short_id_order,
390
+ ),
391
+ branch=OpenBranch.SHA_MATCH, identity_preserved=True,
392
+ tree_write_intent=TreeWriteIntent.NONE, source_sha256=digest,
393
+ stored_source_sha256=acceptance.stored_source_sha256, tree_path=tree_path,
394
+ tree_bytes=tree)
395
+ if acceptance.stored is not None and active_session_holds_file:
396
+ # The tree is the truth here, so the document's source bytes are the ones the TREE
397
+ # renders to -- not the stale bytes on disk, whose offsets would misaddress every
398
+ # cached source slice.
399
+ stored = acceptance.stored
400
+ return OpenedTree(
401
+ document=to_tree_document(
402
+ stored,
403
+ self._render_stored(stored),
404
+ path=path,
405
+ short_id_order=self._short_id_order,
406
+ ),
407
+ branch=OpenBranch.SHA_MISMATCH_ACTIVE_SESSION, identity_preserved=True,
408
+ tree_write_intent=TreeWriteIntent.NONE, source_sha256=digest,
409
+ stored_source_sha256=acceptance.stored_source_sha256, tree_path=tree_path,
410
+ tree_bytes=tree, refusal=acceptance.refusal)
411
+ branch = (OpenBranch.SHA_MISMATCH_NO_SESSION if acceptance.stored is not None
412
+ else OpenBranch.NO_SIDECAR)
413
+ return self._rebuilt(source_bytes, digest, branch, TreeWriteIntent.REPLACE, format_id,
414
+ file_path, allow_plain_text_fallback, path, tree_path,
415
+ acceptance.stored_source_sha256, acceptance.refusal,
416
+ open_options=open_options)
417
+
418
+ def _rebuilt(self, source_bytes: bytes, digest: str, branch: OpenBranch,
419
+ intent: TreeWriteIntent, format_id: Optional[str], file_path: Optional[str],
420
+ allow_plain_text_fallback: bool, path: Optional[Path],
421
+ tree_path: Optional[Path], stored_digest: Optional[str],
422
+ refusal: Optional[str],
423
+ adoption: Optional[Mapping[Tuple[int, ...], Tuple[uuid.UUID, Optional[int]]]] = None,
424
+ open_options: Optional[Mapping[str, Any]] = None) -> OpenedTree:
425
+ """The rebuild branch: parse the source with fresh identity, then serialize the tree file
426
+ that would record it -- against the digest of the source bytes exactly as given, because
427
+ the source is not ours to rewrite."""
428
+ document = self._parse_source(source_bytes, format_id=format_id, file_path=file_path,
429
+ allow_plain_text_fallback=allow_plain_text_fallback,
430
+ **dict(open_options or {}))
431
+ if path is not None:
432
+ document.path = path
433
+ adopted = unmatched = 0
434
+ if adoption is not None:
435
+ adopted, unmatched = self._adopt(document, adoption)
436
+ elif self._short_id_order is not None:
437
+ document.short_id_map = ShortIdMap()
438
+ document.short_id_index = {}
439
+ document.short_id_order = self._short_id_order
440
+ document.reindex()
441
+ tree_bytes, unavailable = self._tree_artefact(document, source_bytes)
442
+ preserved = adoption is not None and adopted == len(document.nodes_by_id)
443
+ return OpenedTree(document=document, branch=branch, identity_preserved=preserved,
444
+ tree_write_intent=intent if tree_bytes is not None
445
+ else TreeWriteIntent.NONE,
446
+ source_sha256=digest, stored_source_sha256=stored_digest,
447
+ tree_path=tree_path, tree_bytes=tree_bytes,
448
+ tree_unavailable=unavailable, refusal=refusal,
449
+ adopted_node_count=adopted, unmatched_legacy_count=unmatched)
450
+
451
+ @staticmethod
452
+ def _checked_mapping(mapping: Any) -> "dict[Tuple[int, ...], Tuple[uuid.UUID, Optional[int]]]":
453
+ """Validate an adopter's mapping before anything is applied or written: every node_id a
454
+ UUID (``TREE_PAYLOAD_INVALID``), none repeated (``NODE_ID_CONFLICT``), every short_id
455
+ None or a distinct positive int (``SHORT_ID_CONFLICT``)."""
456
+ checked: "dict[Tuple[int, ...], Tuple[uuid.UUID, Optional[int]]]" = {}
457
+ node_ids: set = set()
458
+ short_ids: set = set()
459
+ for path, entry in dict(mapping).items():
460
+ try:
461
+ node_id, short_id = entry
462
+ except (TypeError, ValueError):
463
+ raise TreePayloadInvalid(
464
+ f"adopter entry for path {path!r} is not a (node_id, short_id) pair") from None
465
+ if not isinstance(node_id, uuid.UUID):
466
+ raise TreePayloadInvalid(
467
+ f"adopter node_id for path {path!r} is not a UUID: {node_id!r}")
468
+ if node_id in node_ids:
469
+ raise NodeIdConflict(f"adopter assigns node_id {node_id} more than once")
470
+ node_ids.add(node_id)
471
+ if short_id is not None:
472
+ if isinstance(short_id, bool) or not isinstance(short_id, int) or short_id < 1:
473
+ raise ShortIdConflict(
474
+ f"adopter short_id for path {path!r} is not a positive integer: {short_id!r}")
475
+ if short_id in short_ids:
476
+ raise ShortIdConflict(f"adopter assigns short_id {short_id} more than once")
477
+ short_ids.add(short_id)
478
+ checked[tuple(path)] = (node_id, short_id)
479
+ return checked
480
+
481
+ def _adopt(self, document: TreeDocument,
482
+ mapping: Mapping[Tuple[int, ...], Tuple[uuid.UUID, Optional[int]]]
483
+ ) -> Tuple[int, int]:
484
+ """Give every node whose structural path is mapped the supplied identity; the rest keep the
485
+ fresh identity the parse minted. Returns ``(adopted, unmatched_legacy)``."""
486
+ paths: dict = {}
487
+
488
+ def collect(node: Any, path: Tuple[int, ...]) -> None:
489
+ paths[path] = node
490
+ for index, child in enumerate(node.children):
491
+ collect(child, path + (index,))
492
+
493
+ collect(document.root, ())
494
+ matched = {p: v for p, v in mapping.items() if p in paths}
495
+ for path, (node_id, _) in matched.items():
496
+ paths[path].node_id = node_id
497
+ fresh_clash = {n.node_id for p, n in paths.items() if p not in matched}
498
+ if fresh_clash & {v[0] for v in matched.values()}:
499
+ raise NodeIdConflict("an adopted node_id collides with a fresh node_id")
500
+ document.short_id_map = ShortIdMap()
501
+ document.short_id_index = {}
502
+ document.short_id_map.merge_insert(
503
+ {node_id: short_id for node_id, short_id in matched.values() if short_id is not None})
504
+ document.short_id_order = self._short_id_order
505
+ document.reindex()
506
+ return len(matched), len(mapping) - len(matched)
507
+
508
+ def _tree_artefact(self, document: TreeDocument,
509
+ source_bytes: bytes) -> Tuple[Optional[bytes], Optional[str]]:
510
+ """The tree file bytes for a freshly parsed document, or the reason there are none.
511
+
512
+ The render check is the one gate an open owes that a write does not: a write publishes the
513
+ source from the same render, so the two agree by construction, while an open must leave the
514
+ source alone and record the tree against the digest of bytes it did not produce. If the
515
+ format's round trip does not reproduce those bytes -- a known-weak generator, an
516
+ unrepresentable construct -- then a tree stored under that digest would be accepted on the
517
+ next open and would hand back a document that is not the file. Refusing to produce it costs
518
+ one render and prevents silently substituting the wrong content."""
519
+ plugin = self._registry.get_format_plugin(document.format_id)
520
+ if not callable(getattr(plugin, "render_document", None)):
521
+ return None, (f"the {document.format_id!r} plugin does not implement the storage half "
522
+ "of the plugin contract, so it has no tree file and node identity "
523
+ "cannot be persisted for this format")
524
+ try:
525
+ rendered = self._render_source(document)
526
+ except TreeEngineException as exc:
527
+ return None, f"the parsed tree does not render back to source: {exc}"
528
+ if rendered != source_bytes:
529
+ return None, (f"the {document.format_id!r} round trip does not reproduce the source "
530
+ "bytes, so a tree file recorded against their checksum would not "
531
+ "describe this file")
532
+ try:
533
+ return self._lifecycle.encode_tree(
534
+ to_frozen_document(document), source_bytes,
535
+ short_id_map=document.short_id_map,
536
+ format_metadata=self._format_metadata(document),
537
+ document_version=document.document_version), None
538
+ except TreeEngineException as exc:
539
+ return None, f"the parsed tree cannot be serialized: {exc}"
540
+
541
+ def _format_metadata(self, document: TreeDocument) -> Mapping[str, Any]:
542
+ """Envelope metadata for this document: its fallback diagnostic, when it has one."""
543
+ return ({} if document.fallback_diagnostic is None
544
+ else {FALLBACK_DIAGNOSTIC_KEY: dict(document.fallback_diagnostic)})
545
+
546
+ def _render_stored(self, stored: DecodedTreeFile) -> bytes:
547
+ """The source bytes a stored tree renders to, through its own representation plugin."""
548
+ plugin = self._registry.get_format_plugin(stored.document.format_id)
549
+ rendered = plugin.render_document(stored.document)
550
+ return rendered if isinstance(rendered, bytes) else str(rendered).encode("utf-8")
551
+
552
+ # -- history ----------------------------------------------------------------
553
+
554
+ def _checkpointed(self, outcome: OpenedTree, kind: CheckpointKind,
555
+ history: Optional[HistoryPort]) -> OpenedTree:
556
+ """Record the open checkpoint, if a port was supplied, and carry back its revision."""
557
+ return _replace(outcome, checkpoint_id=self._record(
558
+ kind, outcome.document, outcome.document.source_bytes, outcome.source_sha256,
559
+ tree_path=outcome.tree_path, tree_bytes=outcome.tree_bytes,
560
+ written_paths=outcome.written_paths, branch=outcome.branch.value, history=history))
561
+
562
+ def _record(self, kind: CheckpointKind, document: TreeDocument, source_bytes: bytes,
563
+ digest: str, *, tree_path: Optional[Path], tree_bytes: Optional[bytes],
564
+ written_paths: Tuple[Path, ...], branch: Optional[str],
565
+ history: Optional[HistoryPort]) -> Optional[str]:
566
+ """Invoke the history port for one checkpoint. The engine calls this; a consumer never
567
+ does. With no port supplied there is no history and nothing happens."""
568
+ port = self._history if history is None else history
569
+ if port is None:
570
+ return None
571
+ return port.record_checkpoint(Checkpoint(
572
+ kind=kind, document_id=document.document_id,
573
+ document_version=document.document_version, source_path=document.path,
574
+ source_bytes=source_bytes, source_sha256=digest, tree_path=tree_path,
575
+ tree_bytes=tree_bytes,
576
+ tree_payload_sha256=None if tree_bytes is None
577
+ else tree_payload_sha256(canonical_tree_payload(tree_bytes)),
578
+ written_paths=written_paths, branch=branch, format_id=document.format_id,
579
+ source_format_id=document.source_format_id))