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
tree_engine/facade.py ADDED
@@ -0,0 +1,4524 @@
1
+ """The single public entry point of the tree engine (concept C-021).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Everything a caller needs is here -- :class:`TreeDocument`, the file/content entry points, the read and
7
+ mutating operations, and their result types ({p037}) -- so nothing needs an import from
8
+ ``tree_engine.core.*``/``tree_engine.plugins.*``, and every error raised is a ``tree_engine.exceptions``
9
+ class carrying an ``ErrorCode`` of ``tree_engine.errors``. File calls route to the storage layer, format
10
+ selection/parsing/rendering to the plugin layer (including the authorized plain-text fallback after
11
+ ``FORMAT_CONTENT_PARSE_FAILED`` and nothing else) and document operations to the core ({p025}); every
12
+ address-taking command resolves through ``normalize_node_address`` first ({j9rh}) and every mutating one
13
+ checks ``expected_version`` against the monotonic ``document_version`` ({p024}) under the shared lock
14
+ coordinator, a two-document ``move`` taking both locks in document_id order ({p035}). The mutable
15
+ working representation the core's splices need, its conversion pair with the immutable
16
+ ``core.nodes.Node``, and the fields/children and cached-source rules that keep an edit renderable are
17
+ owned by ``core.live_tree``; this module only drives them.
18
+
19
+ Instrumentation ({{p030}}): Every mutating operation (insert, delete, replace, move, set_body,
20
+ set_attribute, replace_node_id, apply_subtree) reports PHASE_MUTATE with the count of affected
21
+ nodes. The load/parse operations (loads, reparse, replace_source) mark MARKER_FULL_PARSE; replace_source
22
+ also marks MARKER_FULL_INDEX_REBUILD. Instrumentation is disabled by default: call
23
+ :func:`tree_engine.core.instrumentation.enable` to turn it on per the module's contract. When disabled,
24
+ all measurement is a no-op with O(1) cost; when enabled, call :func:`tree_engine.core.instrumentation.query_counters`
25
+ to read the accumulated counters.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import contextvars
31
+ import inspect
32
+ from contextlib import contextmanager
33
+ from dataclasses import replace as _replace_dataclass
34
+ from pathlib import Path
35
+ from typing import (
36
+ Any,
37
+ Callable,
38
+ Dict,
39
+ Iterator,
40
+ List,
41
+ Mapping,
42
+ Optional,
43
+ Sequence,
44
+ Tuple,
45
+ Union,
46
+ )
47
+ from uuid import UUID
48
+
49
+ from tree_engine.core import range_refresh as _range_refresh
50
+ from tree_engine.storage.file_txn import inherit_ownership
51
+
52
+ from tree_engine.core import (
53
+ move as _move_mod,
54
+ operations as _ops,
55
+ subtree_apply as _apply_mod,
56
+ )
57
+ from tree_engine.core import (
58
+ instrumentation as _instr,
59
+ position_transfer as _spans,
60
+ subtree_copy as _copy_mod,
61
+ updates as _updates,
62
+ )
63
+ from tree_engine.core.address import NodeAddressError, normalize_node_address
64
+ from tree_engine.core.identifier_map import (
65
+ IdentifierMap,
66
+ IdentifierStyle,
67
+ NodeIdentifiers,
68
+ )
69
+ from tree_engine.core.identity import AddressRemap, NodeAddress, generate_node_id
70
+ from tree_engine.core.journal import BoundaryEvent
71
+ from tree_engine.core.live_tree import (
72
+ LiveNode,
73
+ TreeDocument,
74
+ invalidate_cached_source,
75
+ relink,
76
+ sync_fields,
77
+ to_frozen,
78
+ to_live,
79
+ walk,
80
+ )
81
+ from tree_engine.core.locking import DocumentLockCoordinator
82
+ from tree_engine.core.nodes import Document, NodeSchemaError
83
+ from tree_engine.core.short_id import ShortIdMap
84
+ from tree_engine.errors import ErrorCode
85
+ from tree_engine.exceptions import (
86
+ DocumentVersionConflict,
87
+ FormatExtensionConflict,
88
+ FormatContentParseFailed,
89
+ FormatFragmentParseFailed,
90
+ FormatPluginNotFound,
91
+ InvalidPosition,
92
+ NodeNotFound,
93
+ PluginCapabilityNotSupported,
94
+ ShortIdConflict,
95
+ TreeEngineException,
96
+ exception_for_code,
97
+ )
98
+ from tree_engine.plugins.bsl import block_edit as _bsl_edit
99
+ from tree_engine.plugins.bsl import blocks as _bsl_blocks
100
+ from tree_engine.plugins.contract import (
101
+ FormatPluginContractError as PluginContractError,
102
+ UnsupportedTranslationError as PluginUnsupportedTranslation,
103
+ )
104
+ from tree_engine.plugins.detachable import (
105
+ DETACHABLE_PLUGIN_SPECS,
106
+ load_detachable_plugin,
107
+ )
108
+ from tree_engine.plugins.fallback import PLAIN_TEXT_FORMAT_ID, build_fallback_tree
109
+ from tree_engine.plugins.plain_text import (
110
+ PARAGRAPH_KIND as _PLAIN_TEXT_PARAGRAPH_KIND,
111
+ PLAIN_TEXT_FORMAT_PLUGIN,
112
+ ROOT_KIND as _PLAIN_TEXT_ROOT_KIND,
113
+ SEPARATOR_FIELD as _PLAIN_TEXT_SEPARATOR_FIELD,
114
+ TRAILING_SEPARATOR_FIELD as _PLAIN_TEXT_TRAILING_SEPARATOR_FIELD,
115
+ )
116
+ import tree_engine.plugins as _plugins_package
117
+ from tree_engine.plugins.parse_position import utf8_failure_details
118
+ from tree_engine.plugins.registry import FormatPluginRegistry
119
+ from tree_engine.plugins.scan import scan_builtin_plugins
120
+ from tree_engine.plugins.selection import build_extension_table, resolve_format_plugin
121
+ from tree_engine.query.engine import legacy_kind as _legacy_kind
122
+ from tree_engine.query.engine import query as _query
123
+ from tree_engine.query.inspection import (
124
+ SOURCE_FULL,
125
+ SOURCE_NONE,
126
+ SOURCE_PREVIEW,
127
+ drill_down as _drill_down,
128
+ )
129
+ from tree_engine.query.outline import OutlineResponse
130
+ from tree_engine.query.results import QueryMatch
131
+ from tree_engine.storage.document_bridge import (
132
+ DocumentStore,
133
+ OpenBranch,
134
+ OpenedTree,
135
+ TreeWriteIntent,
136
+ WrittenPair,
137
+ )
138
+ from tree_engine.storage.history import Checkpoint, CheckpointKind, HistoryPort
139
+ from tree_engine.storage.lifecycle import DEFAULT_TREE_SUFFIX, StorageLifecycle
140
+
141
+ __all__ = [
142
+ "TreeDocument",
143
+ "Address",
144
+ "load",
145
+ "save",
146
+ "node_source_text",
147
+ "reparse",
148
+ "replace_source",
149
+ "identity_by_path_snapshot",
150
+ "loads",
151
+ "dumps",
152
+ "query",
153
+ "drill_down",
154
+ "insert",
155
+ "count_fragment_nodes",
156
+ "delete",
157
+ "replace",
158
+ "move",
159
+ "copy_subtree",
160
+ "apply_subtree",
161
+ "set_attribute",
162
+ "set_body",
163
+ "replace_node_id",
164
+ "resolve_address",
165
+ "register_format_plugin",
166
+ "edit_attributes",
167
+ "edit_content",
168
+ "format_hook",
169
+ "list_extensions",
170
+ "list_formats",
171
+ "format_capabilities",
172
+ "open_bytes",
173
+ "open_file",
174
+ "write",
175
+ "SOURCE_NONE",
176
+ "SOURCE_PREVIEW",
177
+ "SOURCE_FULL",
178
+ "PLAIN_TEXT_FORMAT_ID",
179
+ "AddressRemap",
180
+ "ApplySubtreeResult",
181
+ "Checkpoint",
182
+ "CheckpointKind",
183
+ "CopiedDocument",
184
+ "HistoryPort",
185
+ "MoveResult",
186
+ "MutationResult",
187
+ "NodeAddress",
188
+ "OpenBranch",
189
+ "OpenedTree",
190
+ "OutlineResponse",
191
+ "QueryMatch",
192
+ "legacy_kind",
193
+ "is_trivia_kind",
194
+ "is_non_content_token",
195
+ "StorageFacade",
196
+ "inherit_ownership",
197
+ "TreeWriteIntent",
198
+ "WrittenPair",
199
+ "IdentifierMap",
200
+ "IdentifierStyle",
201
+ "NodeIdentifiers",
202
+ "identifier_map",
203
+ "identifiers",
204
+ "node_identifier",
205
+ "node_ref",
206
+ "reference_notation",
207
+ ]
208
+
209
+ #: Every address form {j9rh} accepts, on every address-taking command below, plus the format's own
210
+ #: native reference where its plugin declares one -- a JSON Pointer for json/yaml/toml. All three
211
+ #: identifiers of ``core.identifier_map`` are accepted here whatever style a caller reports in.
212
+ Address = Union[UUID, int, str, NodeAddress]
213
+
214
+ #: Result types re-exported off the core modules already imported above, so a caller annotating or
215
+ #: isinstance-checking a result never has to reach past this facade for the type.
216
+ MoveResult, MutationResult = _move_mod.MoveResult, _ops.MutationResult
217
+ ApplySubtreeResult, CopiedDocument = (
218
+ _apply_mod.ApplySubtreeResult,
219
+ _copy_mod.CopiedDocument,
220
+ )
221
+
222
+ #: The built-in data formats are found by scanning ``tree_engine/plugins/`` (``plugins/scan.py``): a new
223
+ #: module with a module-level plugin object is a new format with no edit here (decision D-CB.3). The LANGUAGE
224
+ #: formats are the exception -- see ``plugins/detachable.py`` for why python and bsl are loaded through an
225
+ #: import that is allowed to fail.
226
+ _REGISTRY = FormatPluginRegistry()
227
+ _EXTENSIONS: Dict[str, str] = {}
228
+ #: format_id -> the refusal for a format that ships here but whose parser library is not installed.
229
+ #: An entry means the format is KNOWN and unavailable, which is a different answer from unknown,
230
+ #: and the facade gives it before any resolution so the caller is told what to install ({p023}).
231
+ _DETACHED: Dict[str, str] = {}
232
+ for _spec in DETACHABLE_PLUGIN_SPECS:
233
+ _plugin_object, _why = load_detachable_plugin(_spec)
234
+ if _plugin_object is None:
235
+ _DETACHED[_spec.format_id] = _why or ""
236
+ _EXTENSIONS.update(
237
+ {extension: _spec.format_id for extension in _spec.file_extensions}
238
+ )
239
+ continue
240
+ _REGISTRY.register_format_plugin(_plugin_object, replace=True)
241
+ _EXTENSIONS.update(build_extension_table([_plugin_object]))
242
+ _BASE_PLUGINS = tuple(
243
+ scan_builtin_plugins(
244
+ _plugins_package, frozenset(spec.module for spec in DETACHABLE_PLUGIN_SPECS)
245
+ )
246
+ )
247
+ for _builtin in _BASE_PLUGINS:
248
+ _REGISTRY.register_format_plugin(_builtin, replace=True)
249
+ _EXTENSIONS.update(build_extension_table(_BASE_PLUGINS))
250
+ _LOCKS = DocumentLockCoordinator()
251
+
252
+ # -- typed-error boundary ---------------------------------------------------
253
+
254
+
255
+ def _code_of(exc: BaseException) -> Optional[ErrorCode]:
256
+ """The stable ``ErrorCode`` an internal exception already declares, if any: ``.code``, then the
257
+ older ``.error_code`` the plugin contract/registry errors still carry, then the first entry of a
258
+ ``.errors`` validation list. ``None`` when it declares none."""
259
+ for name in ("code", "error_code"):
260
+ if isinstance(getattr(exc, name, None), ErrorCode):
261
+ return getattr(exc, name)
262
+ for entry in getattr(exc, "errors", None) or ():
263
+ if isinstance(getattr(entry, "code", None), ErrorCode):
264
+ return entry.code
265
+ return None
266
+
267
+
268
+ @contextmanager
269
+ def _typed(default: ErrorCode) -> Iterator[None]:
270
+ """Guarantee every escaping error is a typed ``tree_engine.exceptions``: one already in the public
271
+ hierarchy passes through untouched, any other is re-raised (chained) as the class owning its
272
+ declared ``ErrorCode``, or ``default`` when it declares none -- so no bare ``KeyError``,
273
+ ``ValueError`` or ``AttributeError`` from an internal layer ever reaches a caller.
274
+
275
+ ``default`` is reached ONLY when ``exc`` declares no code of its own (neither ``_code_of``
276
+ branch matches) and is not an ``OSError`` -- every GENUINE validation rejection already
277
+ carries its own real code by then (a ``MutationError.errors`` entry, a
278
+ ``NodeSchemaError.code``, ...) and takes the ``_code_of(exc)`` branch instead, untouched.
279
+ What actually reaches ``default`` is a bare, undeclared exception: a real bug in an internal
280
+ layer that happens to surface while THIS operation's ``default`` code was in scope (bug
281
+ dbc47fcb, half 2). Before this fix the message carried only ``str(exc)``, making such a bug
282
+ byte-for-byte indistinguishable from a genuine ``default``-coded rejection -- e.g. an
283
+ ``AttributeError`` from an unrelated internal mistake during ``set_body`` surfaced as a
284
+ plain ``InvalidParentType("...")``, exactly as if the caller's node type really had been
285
+ inadmissible. The taxonomy is frozen (per {p023}; no code is invented here, and no
286
+ currently-declared code's genuine case is touched), so the CODE for this fallback stays
287
+ ``default`` -- there is no dedicated "unclassified internal error" code to reach for
288
+ instead. What changes is the MESSAGE: it is now prefixed to honestly disclose that this is
289
+ an unclassified internal failure and names the real exception type, so a caller or a log
290
+ can tell the two apart even though the ``ErrorCode`` alone cannot.
291
+ """
292
+ try:
293
+ yield
294
+ except TreeEngineException:
295
+ raise
296
+ except Exception as exc:
297
+ declared_code = _code_of(exc)
298
+ if declared_code is not None:
299
+ code, detail = declared_code, (str(exc) or type(exc).__name__)
300
+ elif isinstance(exc, OSError):
301
+ code, detail = ErrorCode.STORAGE_IO_ERROR, (str(exc) or type(exc).__name__)
302
+ else:
303
+ code = default
304
+ detail = (
305
+ f"internal engine error (unclassified {type(exc).__name__}): "
306
+ f"{exc or 'no message'}"
307
+ )
308
+ carried = getattr(exc, "details", None)
309
+ extra = dict(carried) if declared_code is not None and isinstance(carried, Mapping) else {}
310
+ raise exception_for_code(code)(detail, **extra) from exc
311
+
312
+
313
+ # -- plugin resolution, content and file entry points ({p037}) --------------
314
+
315
+
316
+ def _detached(
317
+ format_id: Optional[str] = None, file_path: Optional[str] = None
318
+ ) -> Optional[str]:
319
+ """The refusal for a format that ships with the engine but whose parser is not installed, or
320
+ ``None``. Resolution order mirrors :func:`_plugin`'s: an explicit ``format_id`` decides alone
321
+ ({p061}), otherwise the path's extension does, through the same table."""
322
+ if format_id is not None:
323
+ return _DETACHED.get(format_id)
324
+ if file_path:
325
+ extension = Path(file_path).suffix.lstrip(".").lower()
326
+ return _DETACHED.get(_EXTENSIONS.get(extension, ""))
327
+ return None
328
+
329
+
330
+ def _plugin(format_id: Optional[str] = None, file_path: Optional[str] = None) -> Any:
331
+ """Resolve exactly one format plugin, explicit ``format_id`` first ({p061}).
332
+
333
+ A format whose plugin is shipped but detached is refused here, by name, before resolution: the
334
+ alternative answers are all worse than a refusal -- ``FORMAT_UNKNOWN_EXTENSION`` would claim
335
+ the engine has never heard of ``.py``, a bare ``FORMAT_PLUGIN_NOT_FOUND`` would not say what to
336
+ install, and the plain-text fallback would quietly hand back a Python file parsed as text.
337
+ """
338
+ refusal = _detached(format_id, file_path)
339
+ if refusal is not None:
340
+ raise FormatPluginNotFound(refusal)
341
+ if format_id is None and file_path:
342
+ _claim_extension(Path(file_path).suffix.lstrip(".").lower())
343
+ return resolve_format_plugin(
344
+ format_id=format_id,
345
+ file_path=file_path,
346
+ registry=_REGISTRY,
347
+ extension_table=_EXTENSIONS,
348
+ )
349
+
350
+
351
+ def format_hook(format_id: str, name: str) -> Optional[Callable[..., Any]]:
352
+ """The optional editor hook ``name`` of the plugin registered for ``format_id``, or ``None``.
353
+
354
+ A hook is a method a plugin MAY define beyond the format contract for something only that format
355
+ knows (``check_source``, ``preview_info``, ``plan_edit_attributes``, ``plan_edit_content``). It lets
356
+ the editor serve any plugin through one generic group without a per-format branch (D-CB.2).
357
+ """
358
+ try:
359
+ plugin = _REGISTRY.get_format_plugin(format_id)
360
+ except Exception: # noqa: BLE001 - an unknown or unloadable format has no hooks
361
+ return None
362
+ hook = getattr(plugin, name, None)
363
+ return hook if callable(hook) else None
364
+
365
+
366
+ def _entry_point_claims() -> Dict[str, List[str]]:
367
+ """extension -> format ids of the discovered entry-point plugins not yet loaded ({p059}, D-CB.3).
368
+
369
+ Names and extensions only: nothing is imported unless a plugin module declares its extensions
370
+ in a form that cannot be read statically (``plugins/registry.py``). Rescans when the installed
371
+ distributions may have changed.
372
+ """
373
+ claims: Dict[str, List[str]] = {}
374
+ for format_id in _REGISTRY.entry_point_format_ids():
375
+ for extension in _REGISTRY.entry_point_extensions(format_id):
376
+ claims.setdefault(extension, []).append(format_id)
377
+ return claims
378
+
379
+
380
+ def _claim_extension(extension: str) -> None:
381
+ """Make ``extension`` resolvable when an entry-point plugin claims it, and refuse an ambiguous
382
+ claim: two plugins (an entry-point plugin and a built-in or another entry-point plugin) on one
383
+ extension raise ``FORMAT_EXTENSION_CONFLICT`` naming both, never a winner by import order."""
384
+ if not extension:
385
+ return
386
+ claimants = list(_entry_point_claims().get(extension, ()))
387
+ if not claimants:
388
+ # An entry-point plugin that is already loaded no longer counts as a pending claim.
389
+ loaded = _REGISTRY._extension_index.get(extension)
390
+ if loaded is not None:
391
+ _EXTENSIONS.setdefault(extension, loaded)
392
+ return
393
+ owner = _EXTENSIONS.get(extension)
394
+ if owner is not None and owner not in claimants:
395
+ claimants.insert(0, owner)
396
+ if len(claimants) > 1:
397
+ raise FormatExtensionConflict(
398
+ f"extension '.{extension}' is claimed by both "
399
+ + " and ".join(f"'{fid}'" for fid in claimants)
400
+ )
401
+ _EXTENSIONS.setdefault(extension, claimants[0])
402
+
403
+
404
+ def list_extensions() -> Dict[str, str]:
405
+ """extension (with its leading dot, lower case) -> ``format_id`` for every format this facade can
406
+ resolve a path for: the built-ins, the formats registered here and the entry-point plugins
407
+ discovered under ``tree_engine.format_plugins`` (D-CB.3). An extension two plugins claim is left
408
+ out -- resolving it raises ``FORMAT_EXTENSION_CONFLICT``. The editor reads its supported
409
+ extensions from here and types none of them.
410
+ """
411
+ table = dict(_EXTENSIONS)
412
+ for extension, format_id in _REGISTRY._extension_index.items():
413
+ table.setdefault(extension, format_id) # a loaded entry-point plugin keeps its extensions
414
+ for extension, claimants in _entry_point_claims().items():
415
+ owners = set(claimants) | ({table[extension]} if extension in table else set())
416
+ if len(owners) > 1:
417
+ table.pop(extension, None)
418
+ else:
419
+ table[extension] = claimants[0]
420
+ return {f".{extension}": format_id for extension, format_id in sorted(table.items())}
421
+
422
+
423
+ def register_format_plugin(plugin: Any, *, replace: bool = False) -> None:
424
+ """Register a format plugin with this facade: it joins both the registry and the extension table,
425
+ so an explicit ``format_id`` and each of its declared file extensions resolve to it from here on.
426
+ """
427
+ with _typed(ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR):
428
+ _REGISTRY.register_format_plugin(plugin, replace=replace)
429
+ _EXTENSIONS.update(build_extension_table([plugin]))
430
+
431
+
432
+ def list_formats() -> Tuple[str, ...]:
433
+ """The ``format_id`` of every format plugin currently registered with this facade."""
434
+ loaded = tuple(metadata.format_id for metadata in _REGISTRY.list_format_plugins())
435
+ return loaded + tuple(f for f in _REGISTRY.entry_point_format_ids() if f not in loaded)
436
+
437
+
438
+ def format_capabilities() -> Dict[str, Dict[str, Any]]:
439
+ """The declared capability dict of every format plugin currently registered with this facade.
440
+
441
+ Keyed by ``format_id``, mirroring :func:`list_formats`; each value is a fresh copy of that
442
+ plugin's own ``FormatPluginMetadata.capabilities`` (``tree_engine.plugins.contract``) --
443
+ verbatim, never re-derived or hardcoded here. A format whose parser library is not installed
444
+ (a detachable plugin, see ``plugins/detachable.py``) is simply absent, exactly as it is from
445
+ :func:`list_formats`. A caller after just the three canonical keys every plugin declares
446
+ (``navigable``, ``editable``, ``byte_identical_round_trip`` -- TODO 27d10bbd) reads them off
447
+ each value; formats may declare additional keys beyond those three.
448
+ """
449
+ for format_id in _REGISTRY.entry_point_format_ids():
450
+ _REGISTRY.get_format_plugin(format_id) # an entry-point plugin is loaded to read its flags
451
+ return {
452
+ metadata.format_id: dict(metadata.capabilities)
453
+ for metadata in _REGISTRY.list_format_plugins()
454
+ }
455
+
456
+
457
+ def _is_yaml_anchored(exc: BaseException, source_id: str) -> bool:
458
+ """True for the yaml reader's ``UNSUPPORTED_TRANSLATION`` of an anchor, alias or tag
459
+ (``node_type`` ``Anchored``); FlowKey/MergeKey/BlockScalar keep their typed error."""
460
+ if source_id != "yaml" or _code_of(exc) is not ErrorCode.UNSUPPORTED_TRANSLATION:
461
+ return False
462
+ details = getattr(exc, "details", None)
463
+ node_type = details.get("node_type") if isinstance(details, Mapping) else None
464
+ return (node_type or getattr(exc, "node_type", None)) == "Anchored"
465
+
466
+
467
+ def loads(
468
+ content: Union[str, bytes],
469
+ *,
470
+ format_id: Optional[str] = None,
471
+ file_path: Optional[str] = None,
472
+ allow_plain_text_fallback: bool = True,
473
+ semantic_compact_ids: bool = False,
474
+ **open_options: Any,
475
+ ) -> TreeDocument:
476
+ """Parse in-memory content into a :class:`TreeDocument` ({p037}): the format is ``format_id`` when
477
+ given, else ``file_path``'s extension, and neither resolving raises ``FormatUnknownExtension``. Only
478
+ a ``FORMAT_CONTENT_PARSE_FAILED`` from the resolved plugin may open the authorized plain-text
479
+ fallback ({p058}, {p063}); every other failure reaches the caller unmasked.
480
+
481
+ ``semantic_compact_ids`` selects the SAME ``short_id`` eligibility rule
482
+ :class:`StorageFacade` applies via its own identically-named constructor
483
+ flag for a document opened through storage (a persisted ``.tree``
484
+ sidecar, session-backed): only nodes the format's own reference notation
485
+ addresses get a compact id, in that notation's walk order, rather than
486
+ each plugin's raw parse/allocation order (which a structural wrapper the
487
+ notation skips still consumes a number from, and a container node closed
488
+ only after its children numbers AFTER them). Applying it HERE, at
489
+ construction, is what makes it take effect at all: :class:`TreeDocument`
490
+ only renumbers a node that has never held a short_id, so reindexing an
491
+ already-built document under a narrower eligibility set prunes and
492
+ extends the existing numbering instead of restarting it -- a caller
493
+ wanting the clean 1..N sequence (e.g. a one-shot, no-session preview of a
494
+ structured file nobody has open) needs it selected before the first
495
+ ``reindex()`` this constructor already runs, not after.
496
+
497
+ ``open_options`` (keyword arguments) are the options the format declares (the format's ``open_options()`` hook,
498
+ for csv ``delimiter`` and ``record_separator``); they are passed to ``plugin.parse_document`` only when
499
+ given, and a plugin ignores a name it does not read. A value the plugin refuses raises
500
+ ``FORMAT_PLUGIN_CONTRACT_ERROR`` and never opens the fallback.
501
+
502
+ Content that is not valid UTF-8 raises ``FORMAT_CONTENT_PARSE_FAILED`` whose details carry the
503
+ 1-based ``line`` / ``column`` of the first bad byte; with the fallback allowed it opens as the
504
+ plain-text tree and ``dumps`` returns the original bytes (the bad bytes ride as surrogate escapes).
505
+
506
+ The returned document's journal marks BoundaryEvent.INITIAL_LOAD after construction {{p016}},
507
+ recording the load boundary where initial indexing is permitted.
508
+
509
+ Instrumentation: marks MARKER_FULL_PARSE per the module's mechanism (enable/disable via
510
+ tree_engine.core.instrumentation)."""
511
+ with _typed(ErrorCode.FORMAT_CONTENT_PARSE_FAILED):
512
+ undecodable: Optional[FormatContentParseFailed] = None
513
+ if isinstance(content, (bytes, bytearray)):
514
+ try:
515
+ text = bytes(content).decode("utf-8")
516
+ except UnicodeDecodeError as bad:
517
+ undecodable = FormatContentParseFailed(
518
+ "content is not valid UTF-8",
519
+ **utf8_failure_details(bytes(content), bad),
520
+ )
521
+ text = bytes(content).decode("utf-8", errors="surrogateescape")
522
+ else:
523
+ text = content
524
+ try:
525
+ plugin = _plugin(format_id, file_path)
526
+ except Exception as unresolved:
527
+ if _code_of(unresolved) is not ErrorCode.FORMAT_UNKNOWN_EXTENSION:
528
+ raise
529
+ # D-CL: an unknown name opens as the plain-text paragraph/line tree while the fallback is allowed.
530
+ if format_id is not None or not file_path or not allow_plain_text_fallback:
531
+ raise
532
+ plugin = PLAIN_TEXT_FORMAT_PLUGIN
533
+ undecodable = None # text mode: undecodable bytes ride as surrogate escapes, nothing failed
534
+ source_id, path = plugin.metadata.format_id, (
535
+ Path(file_path) if file_path else None
536
+ )
537
+ order = _semantic_short_id_order if semantic_compact_ids else None
538
+ open_options = {name: value for name, value in open_options.items() if value is not None}
539
+ with _instr.measure(
540
+ _instr.PHASE_PARSE, markers=[_instr.MARKER_FULL_PARSE], changed_text=text
541
+ ):
542
+ try:
543
+ if undecodable is not None:
544
+ raise undecodable
545
+ parsed = (
546
+ plugin.parse_document(text, open_options)
547
+ if open_options
548
+ else plugin.parse_document(text)
549
+ )
550
+ except Exception as exc:
551
+ if not allow_plain_text_fallback:
552
+ raise
553
+ if _is_yaml_anchored(exc, source_id):
554
+ # Matrix D-AK (bug e4346c5e): an anchor, alias or tag cannot round-trip
555
+ # structurally, so the document opens as the plain-text fallback.
556
+ exc = FormatContentParseFailed(str(exc), plugin_id=source_id)
557
+ elif _code_of(exc) is not ErrorCode.FORMAT_CONTENT_PARSE_FAILED:
558
+ raise
559
+ back = build_fallback_tree(text, exc, source_format_id=source_id)
560
+ # The fallback document is the plain_text paragraph/line tree of the text, with
561
+ # buffer_range on every node (bug b548f445, D-AL rule 4); ``back`` is the gate
562
+ # (only a permitted diagnostic gets here) and the diagnostic carrier.
563
+ document = TreeDocument(
564
+ to_live(PLAIN_TEXT_FORMAT_PLUGIN.parse_document(text).root),
565
+ source_id,
566
+ PLAIN_TEXT_FORMAT_ID,
567
+ text.encode("utf-8", errors="surrogateescape"),
568
+ path=path,
569
+ fallback_diagnostic=back.metadata.diagnostic,
570
+ short_id_order=order,
571
+ )
572
+ document.journal.mark_boundary(BoundaryEvent.INITIAL_LOAD)
573
+ document.recompute_subtree_bytes(
574
+ _leaf_fragment_walk(document, PLAIN_TEXT_FORMAT_PLUGIN)
575
+ )
576
+ return document
577
+ document = TreeDocument(
578
+ to_live(parsed.root),
579
+ source_id,
580
+ parsed.representation_format_id,
581
+ text.encode("utf-8", errors="surrogateescape"),
582
+ path=path,
583
+ short_id_order=order,
584
+ )
585
+ document.journal.mark_boundary(BoundaryEvent.INITIAL_LOAD)
586
+ document.recompute_subtree_bytes(_leaf_fragment_walk(document, plugin))
587
+ return document
588
+
589
+
590
+ def dumps(document: TreeDocument) -> bytes:
591
+ """Render ``document`` back to source bytes through its own format plugin."""
592
+ with _typed(ErrorCode.UNSUPPORTED_TRANSLATION):
593
+ common = Document(
594
+ root=to_frozen(document.root),
595
+ source_format_id=document.source_format_id,
596
+ representation_format_id=document.format_id,
597
+ )
598
+ # BSL's tree-sitter nodes carry byte ranges and its renderer uses the
599
+ # original buffer only for untouched inter-node gaps (BOM, mixed line
600
+ # endings and trivia). A mutation invalidates ancestor ``content``
601
+ # caches, so retain that buffer while substituted child fragments are
602
+ # rendered. Other plugins keep their existing option surface.
603
+ options = {"source": document.source_bytes} if document.format_id == "bsl" else {}
604
+ output = _plugin(document.format_id).generate_output(common, options)
605
+ return (
606
+ output
607
+ if isinstance(output, bytes)
608
+ else str(output).encode("utf-8", errors="surrogateescape")
609
+ )
610
+
611
+
612
+ def _semantic_short_id_order(document: TreeDocument) -> Sequence[UUID]:
613
+ """Compact-ID order for editor-visible semantic nodes only.
614
+
615
+ Structured formats expose exactly the nodes their native reference
616
+ notation can address; parser-only wrappers therefore receive no compact
617
+ identifier. Plain text preserves the editor's established order: content
618
+ lines, then paragraphs, then the document root. JSON Lines exposes lines
619
+ only, matching its flat record model.
620
+ """
621
+ if document.format_id == PLAIN_TEXT_FORMAT_ID:
622
+ paragraphs = list(document.root.children)
623
+ lines = [
624
+ line.node_id for paragraph in paragraphs for line in paragraph.children
625
+ ]
626
+ suffix = "" if document.path is None else document.path.suffix.lower()
627
+ if suffix in (".jsonl", ".ndjson"):
628
+ return lines
629
+ return (
630
+ lines
631
+ + [paragraph.node_id for paragraph in paragraphs]
632
+ + [document.root.node_id]
633
+ )
634
+ plugin = _plugin(document.format_id)
635
+ notation = getattr(plugin, "native_reference", None)
636
+ if notation is None or getattr(plugin, "all_nodes_compact_ids", False):
637
+ return [node.node_id for node in walk(document.root)]
638
+ public = notation.index(document.root).by_node
639
+ #: A plugin may declare kinds whose compact id is issued AFTER every
640
+ #: other addressable node's (``deferred_short_id_kinds``, duck-typed
641
+ #: like ``fragment_container_kinds``). Both groups keep document order
642
+ #: within themselves; only the two groups are ordered against each
643
+ #: other. A format that declares none is numbered exactly as before --
644
+ #: one pass in document order.
645
+ deferred = frozenset(getattr(plugin, "deferred_short_id_kinds", ()) or ())
646
+ if not deferred:
647
+ return [node.node_id for node in walk(document.root) if node.node_id in public]
648
+ primary: List[UUID] = []
649
+ secondary: List[UUID] = []
650
+ for node in walk(document.root):
651
+ if node.node_id not in public:
652
+ continue
653
+ (secondary if node.kind in deferred else primary).append(node.node_id)
654
+ return primary + secondary
655
+
656
+
657
+ #: The storage half of this facade: the source/tree pair, the checksum open decision, and the write
658
+ #: that persists node identity. Built over the same registry and extension table every other call
659
+ #: resolves through, and driven through this module's own ``loads``/``dumps`` so the rebuild branch
660
+ #: keeps one plugin resolution and one authorized plain-text fallback rather than a second copy.
661
+ class StorageFacade:
662
+ """Storage entry points bound to one engine-owned tree-path convention.
663
+
664
+ Standalone callers use the engine default, ``.tree.json``. Consumers with
665
+ an already-frozen sibling convention construct one facade with their suffix;
666
+ path derivation remains inside the engine and every open/write operation uses
667
+ the same :class:`DocumentStore` decision and publication lifecycle.
668
+
669
+ ``sidecar_adopter(tree_bytes, source_bytes)`` may map a FOREIGN (undecodable) tree file's
670
+ identity onto the freshly parsed source (branch ``FOREIGN_TREE_ADOPTED``);
671
+ ``tree_publish_hook(staged_path, reference_path)`` runs on each staged file before its
672
+ publishing rename (see :func:`inherit_ownership`); ``cross_process_lock`` (default True) makes
673
+ publication of one pair exclusive across processes.
674
+ """
675
+
676
+ def __init__(
677
+ self,
678
+ *,
679
+ tree_suffix: str = DEFAULT_TREE_SUFFIX,
680
+ semantic_compact_ids: bool = False,
681
+ sidecar_adopter: Optional[Callable[[bytes, bytes], Any]] = None,
682
+ tree_publish_hook: Optional[Callable[[Path, Path], None]] = None,
683
+ cross_process_lock: bool = True,
684
+ ) -> None:
685
+ if not isinstance(tree_suffix, str) or not tree_suffix:
686
+ raise ValueError("tree_suffix must be a non-empty string")
687
+ if sidecar_adopter is not None and not callable(sidecar_adopter):
688
+ raise TypeError("sidecar_adopter must be callable or None")
689
+ if tree_publish_hook is not None and not callable(tree_publish_hook):
690
+ raise TypeError("tree_publish_hook must be callable or None")
691
+ if not isinstance(cross_process_lock, bool):
692
+ raise TypeError("cross_process_lock must be a bool")
693
+ lifecycle = StorageLifecycle(
694
+ _REGISTRY,
695
+ extension_table=_EXTENSIONS,
696
+ tree_suffix=tree_suffix,
697
+ tree_publish_hook=tree_publish_hook,
698
+ cross_process_lock=cross_process_lock,
699
+ )
700
+ self._store = DocumentStore(
701
+ _REGISTRY,
702
+ parse_source=loads,
703
+ render_source=dumps,
704
+ extension_table=_EXTENSIONS,
705
+ lifecycle=lifecycle,
706
+ short_id_order=(_semantic_short_id_order if semantic_compact_ids else None),
707
+ sidecar_adopter=sidecar_adopter,
708
+ )
709
+
710
+ def tree_path_for(self, source_path: Union[str, Path]) -> Path:
711
+ """Return the configured tree path for ``source_path``."""
712
+ return self._store.tree_path_for(source_path)
713
+
714
+ def open_bytes(
715
+ self,
716
+ source: Union[str, bytes],
717
+ *,
718
+ tree: Optional[bytes] = None,
719
+ format_id: Optional[str] = None,
720
+ file_path: Optional[str] = None,
721
+ allow_plain_text_fallback: bool = True,
722
+ active_session_holds_file: bool = False,
723
+ history: Optional[HistoryPort] = None,
724
+ open_options: Optional[Mapping[str, Any]] = None,
725
+ ) -> OpenedTree:
726
+ """Open bytes through this instance's storage lifecycle. ``open_options`` are the format's
727
+ declared open options (the plugin's ``open_options()`` hook), passed to ``loads``."""
728
+ return self._store.open_bytes(
729
+ source,
730
+ tree=tree,
731
+ format_id=format_id,
732
+ file_path=file_path,
733
+ allow_plain_text_fallback=allow_plain_text_fallback,
734
+ active_session_holds_file=active_session_holds_file,
735
+ history=history,
736
+ open_options=open_options,
737
+ )
738
+
739
+ def open_file(
740
+ self,
741
+ path: Union[str, Path],
742
+ *,
743
+ format_id: Optional[str] = None,
744
+ allow_plain_text_fallback: bool = True,
745
+ active_session_holds_file: bool = False,
746
+ history: Optional[HistoryPort] = None,
747
+ open_options: Optional[Mapping[str, Any]] = None,
748
+ ) -> OpenedTree:
749
+ """Open a file through this instance's storage lifecycle. ``open_options`` as in
750
+ :meth:`open_bytes`."""
751
+ return self._store.open_file(
752
+ path,
753
+ format_id=format_id,
754
+ allow_plain_text_fallback=allow_plain_text_fallback,
755
+ active_session_holds_file=active_session_holds_file,
756
+ history=history,
757
+ open_options=open_options,
758
+ )
759
+
760
+ def write(
761
+ self,
762
+ document: TreeDocument,
763
+ path: Optional[Union[str, Path]] = None,
764
+ *,
765
+ history: Optional[HistoryPort] = None,
766
+ ) -> WrittenPair:
767
+ """Publish through this instance's storage lifecycle."""
768
+ return self._store.write(document, path, history=history)
769
+
770
+
771
+ _STORAGE = StorageFacade()
772
+
773
+
774
+ def open_bytes(
775
+ source: Union[str, bytes],
776
+ *,
777
+ tree: Optional[bytes] = None,
778
+ format_id: Optional[str] = None,
779
+ file_path: Optional[str] = None,
780
+ allow_plain_text_fallback: bool = True,
781
+ active_session_holds_file: bool = False,
782
+ history: Optional[HistoryPort] = None,
783
+ ) -> OpenedTree:
784
+ """Take the open decision from BYTES: the source bytes, and the stored tree file's bytes when
785
+ the caller has them ({p087}). For a caller that already holds the content -- one that fetched
786
+ both files from somewhere that is not this filesystem, or that must not create files where
787
+ they live -- this is the whole of open, and it touches no filesystem at all.
788
+
789
+ The recorded ``source_sha256`` decides. Matching, the stored tree IS the document and every
790
+ node keeps its ``node_id`` and its ``short_id``; absent or unusable, the source is parsed with
791
+ fresh identity. A mismatch is decided by ``active_session_holds_file``, which only the caller
792
+ knows: with no session the file on disk is the truth and the tree is rebuilt, with a session
793
+ holding it the tree is the truth and is kept. :class:`OpenedTree` reports which of the four
794
+ branches was taken, whether identity survived, the tree file bytes the decision calls for, and
795
+ what would have to happen to the tree file for it to agree -- which this call leaves to the
796
+ caller, having written nothing."""
797
+ return _STORAGE.open_bytes(
798
+ source,
799
+ tree=tree,
800
+ format_id=format_id,
801
+ file_path=file_path,
802
+ allow_plain_text_fallback=allow_plain_text_fallback,
803
+ active_session_holds_file=active_session_holds_file,
804
+ history=history,
805
+ )
806
+
807
+
808
+ def open_file(
809
+ path: Union[str, Path],
810
+ *,
811
+ format_id: Optional[str] = None,
812
+ allow_plain_text_fallback: bool = True,
813
+ active_session_holds_file: bool = False,
814
+ history: Optional[HistoryPort] = None,
815
+ ) -> OpenedTree:
816
+ """:func:`open_bytes` over a real pair on disk, acting on the intent it computes.
817
+
818
+ The SOURCE file is read and never written: it takes no part in the file transaction this
819
+ performs, so its bytes and its mtime are unchanged whatever the decision was. The derived TREE
820
+ file is created when there is none and refreshed when the source has superseded it -- that is
821
+ not a violation of a read-only open, it is what gives the next open identity to hand out.
822
+ ``written_paths`` on the result is exactly what was written, which is the tree file or nothing.
823
+ Use :func:`open_bytes` where even the derived artefact must not be created."""
824
+ return _STORAGE.open_file(
825
+ path,
826
+ format_id=format_id,
827
+ allow_plain_text_fallback=allow_plain_text_fallback,
828
+ active_session_holds_file=active_session_holds_file,
829
+ history=history,
830
+ )
831
+
832
+
833
+ def load(
834
+ path: Union[str, Path],
835
+ *,
836
+ format_id: Optional[str] = None,
837
+ allow_plain_text_fallback: bool = True,
838
+ active_session_holds_file: bool = False,
839
+ history: Optional[HistoryPort] = None,
840
+ ) -> TreeDocument:
841
+ """Read ``path`` and open it into a :class:`TreeDocument`, through the storage layer ({p085}).
842
+ The document of :func:`open_file` and nothing else: a valid tree file beside ``path`` is
843
+ accepted and identity survives the reload, a stale or absent one is rebuilt from the source and
844
+ the tree file brought up to date. Use :func:`open_file` instead when the branch, the refusal
845
+ reason, the write intent or the paths written matter."""
846
+ return open_file(
847
+ path,
848
+ format_id=format_id,
849
+ allow_plain_text_fallback=allow_plain_text_fallback,
850
+ active_session_holds_file=active_session_holds_file,
851
+ history=history,
852
+ ).document
853
+
854
+
855
+ def write(
856
+ document: TreeDocument,
857
+ path: Optional[Union[str, Path]] = None,
858
+ *,
859
+ history: Optional[HistoryPort] = None,
860
+ ) -> WrittenPair:
861
+ """Render ``document`` and publish the source/tree pair as one recoverable transaction ({p090}),
862
+ reporting every path written. This is where identity is persisted through an edit: the tree
863
+ file carries each node's ``node_id``/``short_id`` and the live ``short_id_map`` with its
864
+ monotonic counter, so the next open of these bytes takes the SHA_MATCH branch with identity
865
+ intact.
866
+
867
+ ``written_paths`` is the whole of the change -- nothing else is created and no journal survives
868
+ a successful publication -- so a caller that owns atomicity elsewhere can stage exactly those
869
+ files. A checkpoint is recorded through ``history`` once the publication is verified on disk.
870
+ """
871
+ with _typed(ErrorCode.STORAGE_IO_ERROR):
872
+ return _STORAGE.write(document, path, history=history)
873
+
874
+
875
+ def save(
876
+ document: TreeDocument,
877
+ path: Optional[Union[str, Path]] = None,
878
+ *,
879
+ history: Optional[HistoryPort] = None,
880
+ ) -> Path:
881
+ """The source path :func:`write` published, for a caller that needs nothing else from it."""
882
+ return write(document, path, history=history).source_path
883
+
884
+
885
+ def reparse(document: TreeDocument) -> TreeDocument:
886
+ """Rebuild ``document`` from its own rendered source, in place ({p037}): render, parse again with
887
+ the source format's plugin, and swap the result in with fresh indexes and a bumped version. Never
888
+ an implicit side effect of any other call.
889
+
890
+ Instrumentation: marks MARKER_FULL_PARSE per the module's mechanism (enable/disable via
891
+ tree_engine.core.instrumentation)."""
892
+ content = dumps(document)
893
+ rebuilt = loads(
894
+ content, format_id=document.source_format_id, allow_plain_text_fallback=False
895
+ )
896
+ with _operation(document, None, require_editable=False):
897
+ with _instr.measure(
898
+ _instr.PHASE_PARSE, markers=[_instr.MARKER_FULL_PARSE], changed_text=content
899
+ ):
900
+ document.root, document.source_bytes = rebuilt.root, content
901
+ document.format_id, document.fallback_diagnostic = rebuilt.format_id, None
902
+ document.short_id_map, document.short_id_index = ShortIdMap(), {}
903
+ document.reindex()
904
+ # rebuilt's node_ids are exactly document's post-reindex node_ids (reparse never
905
+ # remaps identity, unlike replace_source's by_path/by_reference hints), so the
906
+ # {p067} aggregate loads() already computed on rebuilt carries over verbatim instead
907
+ # of paying for a second render pass over the same tree.
908
+ document._subtree_bytes = rebuilt._subtree_bytes
909
+ document.document_version += 1
910
+ return document
911
+
912
+
913
+ def replace_source(
914
+ document: TreeDocument,
915
+ content: Union[str, bytes],
916
+ *,
917
+ identity_by_reference: Optional[Mapping[str, UUID]] = None,
918
+ identity_by_path: Optional[Mapping[Tuple[int, ...], UUID]] = None,
919
+ boundary: BoundaryEvent = BoundaryEvent.EXTERNAL_MODIFICATION_RECOVERY,
920
+ ) -> TreeDocument:
921
+ """Replace a document from source while carrying caller-known node identity.
922
+
923
+ This is the supported seam for a source-oriented consumer whose mutation
924
+ already knows which logical nodes survived. Hints name nodes either by the
925
+ format's native reference or by their structural child path. The engine
926
+ applies the UUIDs before reindexing, so its existing ``ShortIdMap`` remains
927
+ the sole allocator and the next serialized tree is the identity truth.
928
+
929
+ A full rebuild via loads()+reindex() is a boundary operation ({{p016}}). The
930
+ ``boundary`` parameter selects which boundary event to record; the default
931
+ EXTERNAL_MODIFICATION_RECOVERY signals that an outside source has changed
932
+ and the tree is recovering by re-parsing. The journal entry is appended after
933
+ the rebuild completes, marking the recovery point.
934
+
935
+ Instrumentation: marks MARKER_FULL_PARSE and MARKER_FULL_INDEX_REBUILD per the module's
936
+ mechanism (enable/disable via tree_engine.core.instrumentation)."""
937
+
938
+ rebuilt = loads(
939
+ content,
940
+ format_id=document.source_format_id,
941
+ allow_plain_text_fallback=document.format_id == PLAIN_TEXT_FORMAT_ID,
942
+ )
943
+ by_reference = dict(identity_by_reference or {})
944
+ by_path = dict(identity_by_path or {})
945
+
946
+ paths: Dict[Tuple[int, ...], LiveNode] = {}
947
+
948
+ def collect(node: LiveNode, path: Tuple[int, ...]) -> None:
949
+ paths[path] = node
950
+ for index, child in enumerate(node.children):
951
+ collect(child, path + (index,))
952
+
953
+ collect(rebuilt.root, ())
954
+ assignments: Dict[LiveNode, UUID] = {}
955
+ for path, node_id in by_path.items():
956
+ node = paths.get(tuple(path))
957
+ if node is not None:
958
+ assignments[node] = node_id
959
+
960
+ notation = getattr(_plugin(rebuilt.format_id), "native_reference", None)
961
+ if notation is not None and by_reference:
962
+ index = notation.index(rebuilt.root)
963
+ for node in walk(rebuilt.root):
964
+ reference = index.by_node.get(node.node_id)
965
+ if reference is not None and reference in by_reference:
966
+ assignments[node] = by_reference[reference]
967
+
968
+ claimed: set[UUID] = set()
969
+ for node, node_id in assignments.items():
970
+ if node_id in claimed:
971
+ raise ShortIdConflict(
972
+ f"identity hints assign node_id {node_id} more than once"
973
+ )
974
+ claimed.add(node_id)
975
+ node.node_id = node_id
976
+
977
+ with _operation(
978
+ document, None, ErrorCode.FORMAT_CONTENT_PARSE_FAILED, require_editable=False
979
+ ):
980
+ with _instr.measure(
981
+ _instr.PHASE_PARSE,
982
+ markers=[_instr.MARKER_FULL_PARSE, _instr.MARKER_FULL_INDEX_REBUILD],
983
+ changed_text=content,
984
+ ):
985
+ document.root = rebuilt.root
986
+ document.source_bytes = (
987
+ content.encode("utf-8") if isinstance(content, str) else bytes(content)
988
+ )
989
+ document.format_id = rebuilt.format_id
990
+ document.fallback_diagnostic = rebuilt.fallback_diagnostic
991
+ relink(document.root)
992
+ document.reindex()
993
+ # Unlike reparse(), the by_path/by_reference hints above reassign node_id on some of
994
+ # rebuilt's nodes AFTER loads() already computed rebuilt's own {p067} aggregate, so
995
+ # that aggregate's paths no longer match document's post-remap node_ids -- recompute
996
+ # from document's own (already-remapped) tree instead of reusing it.
997
+ document.recompute_subtree_bytes(
998
+ _leaf_fragment_walk(document, _plugin(document.format_id))
999
+ )
1000
+ document.journal.mark_boundary(boundary)
1001
+ document.document_version += 1
1002
+ return document
1003
+
1004
+
1005
+ def identity_by_path_snapshot(document: TreeDocument) -> Dict[Tuple[int, ...], UUID]:
1006
+ """A structural-path -> ``node_id`` snapshot of ``document``'s CURRENT tree, in the exact
1007
+ shape :func:`replace_source`'s own ``identity_by_path`` parameter expects: root at ``()``,
1008
+ each child at its parent's path plus its own index in ``node.children``.
1009
+
1010
+ For a caller that needs to survive a full-document :func:`replace_source` rebuild (an
1011
+ external-modification recovery, a batch-rollback reparse) with the SAME node identities its
1012
+ already-recorded state (an undo journal, a caller-held UUID) still addresses by: taking this
1013
+ snapshot of the LIVE document BEFORE the rebuild and passing it straight through as
1014
+ ``identity_by_path`` is the only way those UUIDs survive the reparse, because
1015
+ ``identity_by_path``/``identity_by_reference`` hints are only ever as good as the VALUES they
1016
+ carry -- a hint dict built from anything else (an unrelated fresh allocator, a differently
1017
+ time text-identity map) supplies the CORRECT parameter shape with the WRONG values, which
1018
+ preserves nothing (see bug ce2348bb: python_engine_edit's own rollback used to build its
1019
+ hints from a brand-new ``TextIdentityMap()``, a completely different -- and, being freshly
1020
+ constructed, randomly-keyed -- address space than this engine's own structural paths).
1021
+
1022
+ Read-only and format-agnostic: walks ``document.root`` via the shared duck-typed
1023
+ ``node.children`` contract every core module already relies on (mirrors ``replace_source``'s
1024
+ own internal ``collect`` closure), touching no field, no index map, no journal."""
1025
+ snapshot: Dict[Tuple[int, ...], UUID] = {}
1026
+
1027
+ def collect(node: Any, path: Tuple[int, ...]) -> None:
1028
+ node_id = getattr(node, "node_id", None)
1029
+ if node_id is not None:
1030
+ snapshot[path] = node_id
1031
+ for index, child in enumerate(getattr(node, "children", None) or ()):
1032
+ collect(child, path + (index,))
1033
+
1034
+ collect(document.root, ())
1035
+ return snapshot
1036
+
1037
+
1038
+ # -- addressing, versioning, locking ----------------------------------------
1039
+
1040
+
1041
+ def identifier_map(
1042
+ document: TreeDocument,
1043
+ *,
1044
+ style: Union[IdentifierStyle, str] = IdentifierStyle.SHORT_ID,
1045
+ ) -> IdentifierMap:
1046
+ """The document's three-way identifier map: short_id, node_id, and -- where this format's
1047
+ plugin declares a reference notation -- its native reference ({p021}, {p097}).
1048
+
1049
+ ``style`` selects which of the two document-wide identifiers the map REPORTS; it never narrows
1050
+ what it ACCEPTS, since the map is what makes the three forms equivalent. It is an argument on a
1051
+ freshly built object, so two callers may hold two styles over one document at once and neither
1052
+ can change the other's."""
1053
+ return IdentifierMap(document, _plugin(document.format_id), style=style)
1054
+
1055
+
1056
+ def identifiers(
1057
+ document: TreeDocument,
1058
+ address: Address,
1059
+ *,
1060
+ style: Union[IdentifierStyle, str] = IdentifierStyle.SHORT_ID,
1061
+ ) -> NodeIdentifiers:
1062
+ """Every identifier the addressed node answers to, reported under ``style``. ``ref``/``notation``
1063
+ are ``None`` for a format that declares no reference notation, and for a node its notation
1064
+ cannot express -- never a synthesized string standing in for one."""
1065
+ with _typed(ErrorCode.NODE_NOT_FOUND):
1066
+ return identifier_map(document, style=style).identifiers(
1067
+ resolve_address(document, address)
1068
+ )
1069
+
1070
+
1071
+ def node_identifier(
1072
+ document: TreeDocument,
1073
+ address: Address,
1074
+ *,
1075
+ style: Union[IdentifierStyle, str] = IdentifierStyle.SHORT_ID,
1076
+ ) -> Union[int, str]:
1077
+ """The single identifier ``style`` reports for the addressed node: the compact integer by
1078
+ default, or the canonical UUID4 as a string."""
1079
+ return identifiers(document, address, style=style).reported
1080
+
1081
+
1082
+ def node_ref(document: TreeDocument, address: Address) -> Optional[str]:
1083
+ """The addressed node's native reference -- a JSON Pointer for json/yaml/toml -- or ``None``."""
1084
+ return identifiers(document, address).ref
1085
+
1086
+
1087
+ def reference_notation(document: TreeDocument) -> Optional[str]:
1088
+ """The name of this format's reference notation (``"json_pointer"``), or ``None`` for a format
1089
+ whose plugin declares none, such as plain_text."""
1090
+ return identifier_map(document).notation
1091
+
1092
+
1093
+ def resolve_address(document: TreeDocument, address: Address) -> UUID:
1094
+ """Resolve any accepted address form -- a UUID4, a positive-int or ``0x``-hex short_id, a
1095
+ ``"document_id:node_id"`` string, or this format's own native reference -- to its canonical
1096
+ UUID4 ({j9rh}). An unknown or foreign-document address raises ``NodeNotFound`` and an ambiguous
1097
+ short_id ``ShortIdConflict``, both before any operation starts.
1098
+
1099
+ The native reference is tried only AFTER ``normalize_node_address`` has refused a string, which
1100
+ is what keeps every pre-existing address form on exactly the path it already took and builds the
1101
+ plugin's reference index only for a caller actually using one.
1102
+
1103
+ A live node of this document names itself: its ``node_id`` is the address."""
1104
+ if isinstance(address, LiveNode):
1105
+ address = address.node_id
1106
+ try:
1107
+ return normalize_node_address(
1108
+ document,
1109
+ address,
1110
+ current_document_id=document.document_id,
1111
+ resolve_short_id=document.resolve_short_id,
1112
+ )
1113
+ except NodeAddressError as exc:
1114
+ if isinstance(address, str):
1115
+ by_ref = identifier_map(document).node_for_ref(address)
1116
+ if by_ref is not None:
1117
+ return by_ref
1118
+ failure = (
1119
+ ShortIdConflict
1120
+ if type(exc).__name__ == "AmbiguousAddressError"
1121
+ else NodeNotFound
1122
+ )
1123
+ raise failure(
1124
+ f"unresolvable node address {address!r}", address=str(address)
1125
+ ) from exc
1126
+
1127
+
1128
+ def _nodes(document: TreeDocument, targets: Any) -> List[LiveNode]:
1129
+ """One address, or an ordered sequence of them, all resolved before any work begins."""
1130
+ return [
1131
+ document.nodes_by_id[resolve_address(document, a)]
1132
+ for a in (targets if isinstance(targets, (list, tuple)) else [targets])
1133
+ ]
1134
+
1135
+
1136
+ def _check_version(document: TreeDocument, expected: Optional[int]) -> None:
1137
+ """Reject a stale operation before any mutation starts ({p024})."""
1138
+ if expected is not None and expected != document.document_version:
1139
+ raise DocumentVersionConflict(
1140
+ f"expected_version {expected!r} does not match "
1141
+ f"document_version {document.document_version!r}",
1142
+ expected_version=expected,
1143
+ current_version=document.document_version,
1144
+ )
1145
+
1146
+
1147
+ def _require_editable(*documents: TreeDocument) -> None:
1148
+ """Refuse a structural mutation on a format plugin that declares ``editable: False``,
1149
+ before any splice runs (bug 3aa93da8).
1150
+
1151
+ A format that promises no lossless write-back path (see
1152
+ ``tree_engine.plugins.contract.FormatPluginMetadata``'s ``"editable"`` key) is navigable
1153
+ and renderable only: ``insert``/``delete``/``replace``/``move``/``apply_subtree``/
1154
+ ``set_attribute``/``set_body``/``replace_node_id`` all reach here first, one shared gate
1155
+ for every plugin (cpp-family and bsl alike) rather than each mutation entry point trusting
1156
+ the plugin to survive being spliced. Before this gate existed, such a mutation SUCCEEDED
1157
+ silently and only ``dumps()`` failed afterwards -- for a format like ``c``/``cpp``/``cuda``
1158
+ whose ``generate_output`` echoes a node's own cached ``content`` field, the mutation's own
1159
+ ``invalidate_cached_source`` (``tree_engine.core.live_tree``) had already dropped that field
1160
+ off the whole ancestor chain, leaving the document permanently unrenderable
1161
+ (``FORMAT_PLUGIN_CONTRACT_ERROR: node kind ... carries no renderable string 'content'
1162
+ field``) with no way back short of reloading from disk. Checked by ``format_id`` so a
1163
+ cross-document ``move`` between two documents of different formats is refused if EITHER
1164
+ side is read-only, not only the source.
1165
+
1166
+ Deliberately NOT applied to ``reparse``/``replace_source``: both rebuild the tree whole,
1167
+ from the format's own rendered/given source through a fresh ``parse_document``, never by
1168
+ incrementally splicing the existing tree -- so they carry none of this risk and stay usable
1169
+ on a read-only format (e.g. to resynchronize after an external file change).
1170
+ """
1171
+ seen: set = set()
1172
+ for document in documents:
1173
+ format_id = document.format_id
1174
+ if format_id in seen:
1175
+ continue
1176
+ seen.add(format_id)
1177
+ capabilities = _plugin(format_id).metadata.capabilities
1178
+ # Absence is permissive, not a refusal: a third-party plugin authored against the
1179
+ # published contract before TODO 27d10bbd's canonical capability keys existed (see
1180
+ # tests/test_facade.py's own `_KeyValuePlugin`) never declares "editable" at all, and
1181
+ # was always mutable -- only an EXPLICIT `editable: False` triggers this refusal.
1182
+ if capabilities.get("editable") is False:
1183
+ raise PluginCapabilityNotSupported(
1184
+ f"format {format_id!r} declares editable=False: structural mutation is "
1185
+ "refused -- this format supports navigation and rendering only, and forcing "
1186
+ "a mutation onto it leaves the document unrenderable (bug 3aa93da8)",
1187
+ format_id=format_id,
1188
+ capability="editable",
1189
+ )
1190
+
1191
+
1192
+ def _node_path_to_root(node: Optional[LiveNode]) -> Tuple[str, ...]:
1193
+ """Compute the path of node IDs from root to node as strings.
1194
+
1195
+ Walks up the parent chain to the root, then reverses to get root-first order.
1196
+ If node is None, returns empty tuple.
1197
+ """
1198
+ if node is None:
1199
+ return ()
1200
+ path = []
1201
+ current = node
1202
+ while current is not None:
1203
+ path.append(str(current.node_id))
1204
+ current = current.parent
1205
+ return tuple(reversed(path))
1206
+
1207
+
1208
+ def _leaf_fragment_walk(
1209
+ document: TreeDocument, plugin: Any
1210
+ ) -> Callable[[], Iterator[Tuple[Tuple[str, ...], bytes]]]:
1211
+ """Build the one-time ``FragmentWalk`` a fresh-parse/full-rebuild boundary feeds to
1212
+ :meth:`TreeDocument.recompute_subtree_bytes` (bug ca64b1d3, {p067}).
1213
+
1214
+ Every LEAF live node (``node.children`` empty) contributes its own rendered bytes via the
1215
+ format plugin's ``render_fragment`` -- the same per-node rendering contract ``dumps()``
1216
+ already builds on for a whole document -- so this walk needs no plugin-specific byte-offset
1217
+ tracking: ``buffer_range`` is populated by only some plugins (python, bsl, via libcst/
1218
+ tree-sitter positions) and never by ``json_format``, so it cannot be the universal source
1219
+ here. A container node (non-leaf) contributes no fragment of its own -- its subtree size is
1220
+ entirely the sum of its descendants' fragments, per ``SubtreeBytesAggregate``'s own
1221
+ ancestor-chain-sum contract. A leaf ``render_fragment`` cannot render standalone (e.g. a
1222
+ python ``$sentinel`` ``MaybeSentinel`` placeholder, which carries no source text of its own
1223
+ anyway) contributes zero bytes rather than aborting the whole computation.
1224
+ """
1225
+
1226
+ def _walk() -> Iterator[Tuple[Tuple[str, ...], bytes]]:
1227
+ for node in walk(document.root):
1228
+ if node.children:
1229
+ continue
1230
+ try:
1231
+ text = plugin.render_fragment(to_frozen(node))
1232
+ fragment = text.encode("utf-8") if isinstance(text, str) else bytes(text)
1233
+ except Exception:
1234
+ # Still yielded (as an empty fragment), never skipped: skipping would leave
1235
+ # this leaf's whole ancestor chain absent from the aggregate's dict, which
1236
+ # SubtreeBytesAggregate.bytes_of reads back as the {p067} MISSING sentinel
1237
+ # rather than the deliberate "measured, sized zero" this leaf actually is.
1238
+ fragment = b""
1239
+ yield _node_path_to_root(node), fragment
1240
+
1241
+ return _walk
1242
+
1243
+
1244
+ @contextmanager
1245
+ def _operation(
1246
+ document: TreeDocument,
1247
+ expected: Optional[int],
1248
+ default: ErrorCode = ErrorCode.INVALID_POSITION,
1249
+ *,
1250
+ require_editable: bool = True,
1251
+ ) -> Iterator[None]:
1252
+ """One mutating command: check ``expected_version`` ({p024}), refuse an ``editable: False``
1253
+ format before anything splices (bug 3aa93da8, see ``_require_editable``), hold this
1254
+ document's lock for the whole operation ({p035}), and type every escaping error.
1255
+
1256
+ ``require_editable=False`` is the one documented opt-out, used only by ``reparse`` and
1257
+ ``replace_source``: both rebuild the tree wholesale from a fresh parse rather than splicing
1258
+ the existing one, so neither carries the risk ``_require_editable`` guards against, and a
1259
+ read-only format legitimately needs to resynchronize through them."""
1260
+ _check_version(document, expected)
1261
+ if require_editable:
1262
+ _require_editable(document)
1263
+ token = _TOUCHED.set([])
1264
+ try:
1265
+ with _LOCKS.acquire_locks([document.document_id]), _typed(default):
1266
+ yield
1267
+ if require_editable:
1268
+ _refresh_ranges(document)
1269
+ finally:
1270
+ _TOUCHED.reset(token)
1271
+
1272
+
1273
+ #: Nodes the current mutation touched (the parents / modified nodes its ``_commit_mutation`` calls
1274
+ #: name), collected so ``core.range_refresh`` can re-derive ``buffer_range`` around exactly them.
1275
+ _TOUCHED: "contextvars.ContextVar[Optional[List[Tuple[TreeDocument, LiveNode]]]]" = contextvars.ContextVar(
1276
+ "tree_engine_touched_nodes", default=None
1277
+ )
1278
+
1279
+
1280
+ @contextmanager
1281
+ def _reset_touched(token: Any) -> Iterator[None]:
1282
+ try:
1283
+ yield
1284
+ finally:
1285
+ _TOUCHED.reset(token)
1286
+
1287
+
1288
+ def _refresh_ranges(document: TreeDocument) -> None:
1289
+ """Pointwise ``buffer_range`` upkeep for a json/yaml/toml/plain_text mutation (bug b548f445)."""
1290
+ collected = _TOUCHED.get()
1291
+ if document.format_id not in _range_refresh.RANGED_FORMATS or collected is None:
1292
+ return
1293
+ touched = [node for owner, node in collected if owner is document and node is not None]
1294
+ _range_refresh.refresh_ranges(document, touched, _plugin(document.format_id))
1295
+
1296
+
1297
+ def _extract_cached_source(node: Optional[LiveNode]) -> Optional[Union[str, bytes]]:
1298
+ """Extract cached source from a single node's fields.
1299
+
1300
+ Checks 'raw' (JSON/YAML), 'content' (BSL), 'source_text'
1301
+ (``plugins.plain_text.VERBATIM_TEXT_FIELD`` -- a paragraph produced by the
1302
+ parse-error fallback tree, ``plugins/fallback.py``, whose own 'text' is a
1303
+ normalized human-facing view, not the verbatim slice) and 'text'
1304
+ (``plain_text:line``/``plain_text:paragraph`` nodes built by the NORMAL
1305
+ plain_text parse path -- ``plugins/plain_text.py``'s
1306
+ ``make_node(_LINE_KIND, fields={"text": text})`` -- whose 'text' IS
1307
+ already verbatim; also some TOML entries, ``plugins/toml_format.py``)
1308
+ fields where plugins cache the node's original source slice. 'source_text'
1309
+ is checked BEFORE 'text', mirroring ``plugins/plain_text.py::_node_text``'s
1310
+ own precedence, so a fallback paragraph's normalized 'text' is never
1311
+ mistaken for its faithful source. Returns the cached value if found, else
1312
+ None.
1313
+
1314
+ Bug (historical, fixed here): 'text'/'source_text' were missing here, so
1315
+ EVERY plain_text mutation (insert, delete, replace, set_body, move) fell
1316
+ through to the structured ``{'node_ids': [...], 'kinds': [...]}``
1317
+ fallback for its before/after journal fragment -- never a real string --
1318
+ because neither this function nor the plugin-render fallback below found
1319
+ 'raw'/'content'/'text'/'source_text' anywhere in a plain_text tree
1320
+ either (the render fallback has since been ungated entirely, bug
1321
+ 6df2cf33's python residual; it no longer depends on any field being
1322
+ cached before it will even try). The journal recorded a real mutation, but its captured fragments were
1323
+ never faithful text, so anything reading them back as a source string --
1324
+ undo/redo's journal replay (``edit_session_mutations._apply_journal_like_op``,
1325
+ which raises ``JournalReplayUnavailable`` for a non-str/bytes fragment)
1326
+ foremost -- silently could not use them. Evidence: 192.168.254.26:15000,
1327
+ 1.0.132, ``session_undo`` on a single plain-text line replace answered
1328
+ ``NOTHING_TO_UNDO`` instead of actually reverting.
1329
+
1330
+ Cost is O(1): field lookup only, never traversal or serialization.
1331
+ """
1332
+ if node is None:
1333
+ return None
1334
+ for field_name in ("raw", "content", "source_text", "text"):
1335
+ if field_name in node.fields:
1336
+ value = node.fields[field_name]
1337
+ if isinstance(value, (str, bytes)):
1338
+ return value
1339
+ return None
1340
+
1341
+
1342
+ def _get_child_position_anchor(
1343
+ parent: Optional[LiveNode], child: Optional[LiveNode]
1344
+ ) -> Optional[Dict[str, Any]]:
1345
+ """Compute position anchor for a child node within its parent.
1346
+
1347
+ Returns a dict with 'child_index' (int) and 'prev_sibling' (node_id str or None),
1348
+ or None if parent or child is None, or if child is not in parent's children.
1349
+
1350
+ Cost is O(children of parent): single list.index() call.
1351
+ """
1352
+ if parent is None or child is None:
1353
+ return None
1354
+ try:
1355
+ child_index = parent.children.index(child)
1356
+ prev_sibling_node = (
1357
+ parent.children[child_index - 1] if child_index > 0 else None
1358
+ )
1359
+ prev_sibling_id = (
1360
+ str(prev_sibling_node.node_id) if prev_sibling_node is not None else None
1361
+ )
1362
+ return {"child_index": child_index, "prev_sibling": prev_sibling_id}
1363
+ except ValueError:
1364
+ return None
1365
+
1366
+
1367
+ def _structured_fallback_for_nodes(
1368
+ nodes: Sequence[LiveNode],
1369
+ ) -> Optional[Dict[str, Any]]:
1370
+ """Build a structured minimal form when no cached source is available.
1371
+
1372
+ Returns {'node_ids': [str, ...], 'kinds': [str, ...]} containing the
1373
+ touched nodes' IDs and kinds, or None if nodes is empty.
1374
+
1375
+ This is used when container kinds or the python plugin provide no cached
1376
+ 'raw'/'content' field, and the fragment must still be captured as structured data.
1377
+ """
1378
+ if not nodes:
1379
+ return None
1380
+ return {
1381
+ "node_ids": [str(n.node_id) for n in nodes],
1382
+ "kinds": [n.kind for n in nodes],
1383
+ }
1384
+
1385
+
1386
+ def _render_source_via_plugin(
1387
+ node: LiveNode, document: TreeDocument
1388
+ ) -> Optional[Union[str, bytes]]:
1389
+ """Byte-faithful source for one node whose OWN fields carry no cached
1390
+ 'raw'/'content' -- delegating to the document's own format plugin to
1391
+ render it in isolation, the same way that plugin renders the node in
1392
+ place inside its parent (bug 6df2cf33, and its python residual).
1393
+
1394
+ This is what makes a structural wrapper node capturable: a
1395
+ ``json:Member`` (post-5dfa5ae3 layout) carries 'leading'/'sep' but no
1396
+ 'raw' of its own -- its source lives on its leaf value child -- and a
1397
+ ``toml:Table``/``ini:Section`` similarly carries only 'header_raw' plus
1398
+ its children's own 'raw' lines. Each plugin already knows how to compose
1399
+ exactly this (JSON's ``_render_object`` renders a member's key+sep+value
1400
+ inline; TOML/INI's ``_render`` walks header_raw + children directly) --
1401
+ ``FormatPluginContract.generate_output`` is the existing, general
1402
+ entrypoint into that same path for a single node, so this stays
1403
+ plugin-agnostic: no format-specific branch here, only the contract call.
1404
+
1405
+ UNGATED (bug 6df2cf33's python residual): an earlier version of this
1406
+ function skipped straight to the structured fallback whenever NEITHER
1407
+ ``node`` nor any descendant carried a cached 'raw'/'content' field
1408
+ anywhere, on the premise that python -- which caches no such field on
1409
+ ANY node, leaf or container, relying entirely on LibCST codegen instead
1410
+ -- "has nothing cached to compose from". That premise does not hold:
1411
+ ``PythonExportMap.export_from_common`` (``_rebuild`` + ``_generate``)
1412
+ renders the GIVEN node's own subtree standalone, wrapping it in a
1413
+ throwaway ``libcst.Module`` purely for codegen purposes, and never reads
1414
+ any cached field OR any sibling/ancestor content to do it -- verified
1415
+ directly: ``generate_output`` on an isolated ``python:FunctionDef``
1416
+ plucked out of a larger module reproduces exactly that function's own
1417
+ source, unchanged. The gate was blocking a render path that already
1418
+ worked in isolation; every node is now offered to the plugin, and a
1419
+ plugin that genuinely cannot render one standalone (e.g. a bare
1420
+ ``MaybeSentinel`` "$sentinel" marker node, which is never a real
1421
+ mutation target) still degrades to the structured fallback via the
1422
+ except-clause below, exactly as before.
1423
+
1424
+ Cost stays O(fragment): every plugin's render reuses each descendant's
1425
+ own cached 'raw'/'content'/'header_raw' first (for a format that caches
1426
+ one) and only recomposes the positions that were never cached, or (for
1427
+ python, which caches none) regenerates from the GIVEN subtree's own
1428
+ LibCST shape alone -- never a full-document re-parse, never a sibling or
1429
+ ancestor read. A dedicated locality test
1430
+ (``TestPythonNodeFaithfulCapture.test_delete_python_functiondef_render_stays_local_to_the_subtree``,
1431
+ ``tests/core/test_facade_journal.py``) proves this by counting
1432
+ ``PythonExportMap.export_from_common`` calls and asserting the node
1433
+ handed to the one call this capture makes is never the document root.
1434
+
1435
+ Returns None (never raises) when the plugin cannot render this node in
1436
+ isolation -- either its own declared "cannot do this" contract error
1437
+ (``tree_engine.plugins.contract.FormatPluginContractError``/
1438
+ ``UnsupportedTranslationError``, the generic plugin-boundary shape every
1439
+ plugin already raises for exactly this, not a python-specific branch) or
1440
+ a ``tree_engine.exceptions.TreeEngineException`` -- so the caller falls
1441
+ through to the structured fallback exactly as it did before this path
1442
+ existed.
1443
+ """
1444
+ try:
1445
+ plugin = _plugin(document.format_id)
1446
+ rendered = plugin.generate_output(to_frozen(node))
1447
+ except (TreeEngineException, PluginContractError, PluginUnsupportedTranslation):
1448
+ return None
1449
+ return rendered if isinstance(rendered, (str, bytes)) else None
1450
+
1451
+
1452
+ def _render_source_for_node(
1453
+ node: LiveNode, document: TreeDocument
1454
+ ) -> Optional[Union[str, bytes]]:
1455
+ """One node's byte-faithful source: its own cached field first (O(1)),
1456
+ then the plugin-composed fallback above for a wrapper node with none of
1457
+ its own (bug 6df2cf33)."""
1458
+ cached = _extract_cached_source(node)
1459
+ if cached is not None:
1460
+ return cached
1461
+ return _render_source_via_plugin(node, document)
1462
+
1463
+
1464
+ def node_source_text(
1465
+ document: TreeDocument, node: LiveNode
1466
+ ) -> Optional[Union[str, bytes]]:
1467
+ """Public wrapper over :func:`_render_source_for_node`: one node's own
1468
+ byte-faithful source, rendered node-locally (never a whole-document
1469
+ render), for a caller that needs a node's OWN text when it has no
1470
+ ``buffer_range`` of its own -- e.g. a node this batch just inserted,
1471
+ whose range ``facade.insert`` deliberately leaves unmeasured (see its
1472
+ docstring). Returns ``None`` when the plugin cannot render this node
1473
+ standalone (never raises)."""
1474
+ return _render_source_for_node(node, document)
1475
+
1476
+
1477
+ def _measure_insert_delta(
1478
+ document: TreeDocument, parent_node: LiveNode, node: LiveNode
1479
+ ) -> Optional[int]:
1480
+ """Measure how many bytes ``node`` actually added to ``parent_node``'s own rendered text, by
1481
+ rendering ``parent_node`` alone TWICE -- once with ``node`` temporarily removed, once with it
1482
+ back -- and diffing the lengths. Used by :func:`insert` to give the freshly-spliced fragment's
1483
+ later siblings a correct ``buffer_range`` refresh (bug ed579e33 / b4cc5134 defect #2, see
1484
+ ``core.operations.apply_insert_buffer_range``).
1485
+
1486
+ Deliberately node-local, never document-wide: rendering ``node`` in ISOLATION is not a
1487
+ reliable proxy for its true byte contribution (a format's own trailing-newline/separator
1488
+ convention can attach bytes to an isolated render that the same node's ``buffer_range`` never
1489
+ counts once embedded for real), so this instead diffs two renders of the one node ``node``
1490
+ actually landed under -- via ``_render_source_via_plugin`` (never ``_render_source_for_node``:
1491
+ a container's own CACHED source field, when one exists, would replay stale pre-mutation text
1492
+ for both the "removed" and "restored" render alike, since removing ``node`` from ``children``
1493
+ does not itself invalidate that cache) -- so the cost is O(``parent_node``'s own subtree),
1494
+ never O(document): no ``facade.dumps`` call, no full-document ``live_tree.walk``, matching the
1495
+ zero-whole-document-access contract ``tests/core/test_journal_compose.py
1496
+ ::TestNoWholeDocumentAccessDuringCapture`` already pins for every pointwise mutation.
1497
+
1498
+ Restores ``parent_node.children`` to its original (including ``node``) order before
1499
+ returning, in every case -- success, a resolution failure, or a render failure -- so this
1500
+ function never leaves the tree in an inconsistent state. Returns ``None`` (skip bookkeeping
1501
+ entirely, never guess) when ``node`` is not found among ``parent_node.children`` or either
1502
+ render is unavailable."""
1503
+ siblings = list(getattr(parent_node, "children", None) or ())
1504
+ try:
1505
+ position = siblings.index(node)
1506
+ except ValueError:
1507
+ return None
1508
+ without = siblings[:position] + siblings[position + 1:]
1509
+ try:
1510
+ parent_node.children = without
1511
+ sync_fields(parent_node)
1512
+ before = _render_source_via_plugin(parent_node, document)
1513
+ finally:
1514
+ # Unconditional, whatever happened above (a raise from `sync_fields` on the
1515
+ # temporarily-incomplete `without` state included): `children` must never be
1516
+ # observed missing `node` once this function returns or raises.
1517
+ parent_node.children = siblings
1518
+ sync_fields(parent_node)
1519
+ if before is None:
1520
+ return None
1521
+ after = _render_source_via_plugin(parent_node, document)
1522
+ if after is None:
1523
+ return None
1524
+ before_length = len(before.encode("utf-8")) if isinstance(before, str) else len(before)
1525
+ after_length = len(after.encode("utf-8")) if isinstance(after, str) else len(after)
1526
+ return after_length - before_length
1527
+
1528
+
1529
+ def _byte_length(rendered: Union[str, bytes]) -> int:
1530
+ return len(rendered.encode("utf-8")) if isinstance(rendered, str) else len(rendered)
1531
+
1532
+
1533
+ def _faithful_fragment_length(
1534
+ source: Optional[Union[str, bytes, Dict[str, Any]]]
1535
+ ) -> Optional[int]:
1536
+ """Byte length of a faithful source capture -- the exact shape
1537
+ :func:`_extract_source_from_nodes` already returns for a node's own faithful text -- or
1538
+ ``None`` when only its structured fallback (no faithful render available at all) came back.
1539
+ Never guesses from a partial/fallback capture.
1540
+
1541
+ Bug 97329272's fix hinges on this being the RIGHT quantity to diff, which is subtler than it
1542
+ looks: a node's own faithful render already carries whatever trivia the format attaches AS
1543
+ THE NODE'S OWN DATA -- e.g. LibCST attaches blank-line/comment trivia BEFORE a statement to
1544
+ THAT statement's own ``leading_lines`` field, not to the PRECEDING statement's trailing
1545
+ whitespace. Empirically (python): deleting a plain import statement immediately before a
1546
+ function still leaves that function's own faithful render carrying its OWN 2 leading blank
1547
+ lines unchanged (``node_source_text`` on it returns ``'\\n\\ndef ...'`` before AND after the
1548
+ neighbour is touched) -- that trivia never moves and is never part of what a delete/replace
1549
+ removes or a replace's incoming content adds. A boundary-arithmetic guess (next remaining
1550
+ sibling's own ``buffer_range`` start minus the touched range's start) looks appealingly O(1)
1551
+ but silently double-counts exactly that persistent trivia as "removed", overshooting the
1552
+ shift applied to every later sibling by the trivia's own width -- caught empirically here
1553
+ while proving this fix, not merely theorized. Each touched node's OWN faithful text (never
1554
+ reaching past it into a neighbour) is the only quantity immune to that double-count, and
1555
+ ``_extract_source_from_nodes`` already produces exactly that -- for BOTH ``before_source``
1556
+ (already captured by ``facade.delete``/``facade.replace`` for the journal, reused here for
1557
+ free) and, for replace, the incoming fragment's own faithful text -- so no new rendering
1558
+ mechanism, no whole-parent or windowed-clone render, and no ``sync_fields``/scalar-field
1559
+ hazard is introduced: this never touches ``children``/``fields`` at all, only reads each
1560
+ node's own already-faithful text one node at a time (O(fragment), the same bound
1561
+ ``_extract_source_from_nodes`` itself already holds)."""
1562
+ if isinstance(source, (str, bytes)):
1563
+ return _byte_length(source)
1564
+ return None
1565
+
1566
+
1567
+ def _measure_delete_delta(
1568
+ before_source: Optional[Union[str, bytes, Dict[str, Any]]]
1569
+ ) -> Optional[int]:
1570
+ """The TRUE number of bytes removing the already-captured ``before_source`` (the deleted
1571
+ nodes' own faithful text, exactly as ``facade.delete`` already extracts it for the journal)
1572
+ takes out of the document (bug 97329272) -- see :func:`_faithful_fragment_length`'s docstring
1573
+ for why THIS quantity, and not a next-sibling-boundary guess, is the correct one. Returns
1574
+ ``None`` (skip the ``removed_length`` override -- ``core.operations.delete`` falls back to its
1575
+ own approximate, boundary-based math) when no faithful capture is available."""
1576
+ return _faithful_fragment_length(before_source)
1577
+
1578
+
1579
+ def _measure_replace_delta(
1580
+ document: TreeDocument,
1581
+ incoming_roots: Sequence[Any],
1582
+ before_source: Optional[Union[str, bytes, Dict[str, Any]]],
1583
+ ) -> Optional[int]:
1584
+ """An APPROXIMATE signed byte delta (``inserted - removed``) for splicing ``incoming_roots`` in
1585
+ place of the nodes ``before_source`` was captured from (bug 97329272) -- the LAST-RESORT
1586
+ fallback, kept only for a run the exact measurement cannot reach at all.
1587
+
1588
+ Approximate in one specific way, which is why it is no longer the primary: both halves are
1589
+ rendered in ISOLATION, and a node renders at whatever indentation its own subtree implies
1590
+ rather than the depth it actually sits at. The bias cancels in the difference only when both
1591
+ sides have the same number of lines; when they do not it is one indent width per line of
1592
+ difference, so a nested replace that adds or removes lines comes out wrong by exactly that.
1593
+ ``facade.replace`` uses it only where ``_anchored_run`` could not characterise the run being
1594
+ replaced -- a format that populates no ``buffer_range`` at all, for which the whole quantity is
1595
+ inert anyway. Everywhere else the delta comes from the two runs' mapped lengths, measured in
1596
+ real document coordinates (see the exact-splice-geometry block below).
1597
+
1598
+ Both halves are each touched node's OWN faithful text length, never a neighbour's -- see
1599
+ :func:`_faithful_fragment_length`'s docstring for why that is the quantity immune to
1600
+ double-counting a neighbour's persistent leading trivia. The REMOVED half reuses
1601
+ ``before_source`` (``facade.replace`` already captures it for the journal). The INSERTED half
1602
+ is ``incoming_roots``' own faithful text via :func:`_extract_source_from_nodes` -- ``incoming``
1603
+ is a list of fresh, not-yet-spliced fragment roots (``facade._fragment``'s own output), but
1604
+ that extraction only ever renders each node's OWN subtree in isolation
1605
+ (``_render_source_for_node``), never touching ``parent``/document registration/``children``/
1606
+ ``fields`` on anything else, so measuring before the real splice runs is safe. O(fragment) on
1607
+ both sides, never O(parent) let alone O(document) -- preserving the same bounded-locality
1608
+ contract {p029}/{p030} pins, live, in ``tests/core/test_facade_journal.py
1609
+ ::TestPythonNodeFaithfulCapture
1610
+ ::test_delete_python_functiondef_render_stays_local_to_the_subtree``. Returns ``None`` (skip
1611
+ the ``net_delta`` override -- ``core.operations.replace_range`` then applies no shift at all,
1612
+ exactly its pre-fix behaviour) when either side has no faithful capture available."""
1613
+ removed_length = _faithful_fragment_length(before_source)
1614
+ if removed_length is None:
1615
+ return None
1616
+ inserted_length = _faithful_fragment_length(
1617
+ _extract_source_from_nodes(list(incoming_roots), document)
1618
+ )
1619
+ if inserted_length is None:
1620
+ return None
1621
+ return inserted_length - removed_length
1622
+
1623
+
1624
+ # -- exact splice geometry (bugs b47c3558, 20fb996e) -----------------------
1625
+ #
1626
+ # Every mutation that changes the document's bytes has to answer two questions, and the engine
1627
+ # used to answer both by guessing from neighbouring positions:
1628
+ #
1629
+ # HOW MUCH did the document grow or shrink? Every position after the splice moves by exactly
1630
+ # that, at EVERY level of the tree -- `_ops.apply_splice_delta`.
1631
+ # WHERE do the freshly spliced nodes now sit? `core.position_transfer` measures it from the
1632
+ # run's own re-rendered, re-parsed bytes.
1633
+ #
1634
+ # A guess is what made bug b47c3558 worse rather than better: a range reaching to the next MEASURED
1635
+ # sibling swallows every unmeasured node in between, and one anchored on the replaced node's own
1636
+ # start is a decorator short of the truth. Both quantities below come from ONE measured map --
1637
+ # re-render the run, re-parse those exact bytes, and solve the ISO->DOCUMENT map against the spans
1638
+ # the run being replaced already carries, which pins the enclosing container's indent width and
1639
+ # is verified against every one of them. The delta then follows from the two runs' mapped lengths,
1640
+ # and the positions from the same map. Nothing is assigned when a measurement does not check out:
1641
+ # `buffer_range` stays `None`, which is the engine's established safe absence (no reader can read
1642
+ # the wrong bytes for a range that is not there), never a plausible-looking wrong span.
1643
+ #
1644
+ # Deliberately NOT measured by rendering: the obvious "render the parent before and after and diff
1645
+ # the lengths" is both WRONG and SLOW here. Wrong, because a container renders its own content at
1646
+ # its own nesting depth, not the document's -- a doubly nested suite comes back one indent level
1647
+ # short, so the diff misses that indent on every line the splice added or removed. Slow, because
1648
+ # for a top-level edit that parent IS the whole document: measured at 1.2 s per render on a 35 KB
1649
+ # module, twice per mutation. The mapped lengths cost one fragment parse instead.
1650
+
1651
+ _SPAN_MEASUREMENT_FAILURES = (
1652
+ TreeEngineException,
1653
+ PluginContractError,
1654
+ PluginUnsupportedTranslation,
1655
+ NodeSchemaError,
1656
+ )
1657
+
1658
+
1659
+ def _parse_document_root(document: TreeDocument, text: str) -> Optional[LiveNode]:
1660
+ """The root of a fresh, SPAN-RESOLVED parse of ``text`` through this document's own format
1661
+ plugin -- the only authority on where a rendered run's bytes begin and end, since a plugin
1662
+ resolves byte spans for a full-document parse and never for a bare fragment
1663
+ (``plugins/python/import_map.py``: "no absolute buffer to range over").
1664
+
1665
+ Deliberately ``plugin.parse_document`` and NOT :func:`loads`: this parses a FRAGMENT'S OWN
1666
+ rendered text, not a document, so it must create no ``TreeDocument``, allocate no identity,
1667
+ touch no journal and -- the one that would be observable -- raise no ``MARKER_FULL_PARSE``
1668
+ instrumentation marker, which the {p030} benchmark gate reads as a whole-document parse having
1669
+ happened inside a local mutation. ``None`` on any plugin-side failure; never raises."""
1670
+ try:
1671
+ parsed = _plugin(document.format_id).parse_document(text)
1672
+ except _SPAN_MEASUREMENT_FAILURES:
1673
+ return None
1674
+ return getattr(parsed, "root", parsed)
1675
+
1676
+
1677
+ def _run_spans(
1678
+ document: TreeDocument, nodes: Sequence[LiveNode]
1679
+ ) -> Optional["_spans.RunSpans"]:
1680
+ """Re-render ``nodes`` (a contiguous sibling run, in order) and align a fresh parse of those
1681
+ exact bytes back onto them, so every node the parse could be matched with carries the span it
1682
+ occupies inside the run's OWN text. ``None`` when nothing can be measured; never raises."""
1683
+ try:
1684
+ return _spans.measure_run(
1685
+ nodes,
1686
+ lambda node: _render_source_for_node(node, document),
1687
+ lambda text: _parse_document_root(document, text),
1688
+ )
1689
+ except _SPAN_MEASUREMENT_FAILURES:
1690
+ return None
1691
+
1692
+
1693
+ def _anchored_run(
1694
+ document: TreeDocument, nodes: Sequence[LiveNode]
1695
+ ) -> Optional[Tuple["_spans.RunSpans", "_spans.IndentModel"]]:
1696
+ """The measured geometry of a run that ALREADY carries correct ``buffer_range`` values: its own
1697
+ rendered text plus the ISO->DOCUMENT map solved from, and verified against, every span those
1698
+ nodes already hold. This is what anchors a splice -- the incoming content lands exactly where
1699
+ this run's text starts, under exactly the same per-line indentation.
1700
+
1701
+ ``None`` (measure nothing, assign nothing, fall back to the pre-existing approximate
1702
+ bookkeeping) when the run carries no spans at all -- every format but python and bsl, whose
1703
+ addressing does not use ``buffer_range`` in the first place -- or when no single map reproduces
1704
+ the spans it does carry."""
1705
+ if not any(getattr(node, "buffer_range", None) is not None for node in nodes):
1706
+ return None
1707
+ run = _run_spans(document, nodes)
1708
+ if run is None:
1709
+ return None
1710
+ return _spans.solve_model(run)
1711
+
1712
+
1713
+ def _accumulated_parent_indent_width(
1714
+ document: TreeDocument, parent: Optional[LiveNode]
1715
+ ) -> Optional[int]:
1716
+ """Byte width of the prefix a Python container adds to a statement run."""
1717
+ if parent is None or document.format_id != "python":
1718
+ return None
1719
+ root = getattr(document, "root", None)
1720
+ default_indent = None
1721
+ if isinstance(getattr(root, "fields", None), dict):
1722
+ default_indent = root.fields.get("default_indent")
1723
+ if not isinstance(default_indent, str) or not default_indent:
1724
+ default_indent = " "
1725
+ pieces: List[str] = []
1726
+ current: Optional[LiveNode] = parent
1727
+ while current is not None:
1728
+ if str(getattr(current, "kind", "")) == "python:IndentedBlock":
1729
+ fields = getattr(current, "fields", None)
1730
+ indent = fields.get("indent") if isinstance(fields, dict) else None
1731
+ pieces.append(indent if isinstance(indent, str) else default_indent)
1732
+ current = getattr(current, "parent", None)
1733
+ if not pieces:
1734
+ return 0
1735
+ return _byte_length("".join(reversed(pieces)))
1736
+
1737
+
1738
+ def _resolve_insert_anchor_model(
1739
+ document: TreeDocument,
1740
+ parent: Optional[LiveNode],
1741
+ run: "_spans.RunSpans",
1742
+ model: "_spans.IndentModel",
1743
+ ) -> Tuple["_spans.RunSpans", "_spans.IndentModel"]:
1744
+ """Re-solve an INSERT neighbour anchor when a width-0 model is underdetermined."""
1745
+ if model.width != 0:
1746
+ return run, model
1747
+ width = _accumulated_parent_indent_width(document, parent)
1748
+ if width is None or width <= 0:
1749
+ return run, model
1750
+ resolved = _spans.solve_model(run, width=width)
1751
+ return resolved if resolved is not None else (run, model)
1752
+
1753
+
1754
+ def _insert_anchor(
1755
+ document: TreeDocument, node: LiveNode
1756
+ ) -> Optional["_spans.IndentModel"]:
1757
+ """Where a just-spliced INSERT's own bytes begin, read off an IMMEDIATE neighbour.
1758
+
1759
+ An insert has no removed run to anchor on, so the boundary comes from the sibling it now abuts:
1760
+ the one directly before it ends exactly where it begins, or -- when it landed first -- the one
1761
+ directly after it begins exactly where it does. Only a DIRECTLY adjacent sibling is accepted,
1762
+ and only one whose own geometry measures cleanly: an unmeasured node in between would mean the
1763
+ boundary belongs to that node instead, which is exactly the mis-attribution that made bug
1764
+ b47c3558's first fix swallow an inserted sibling into the node before it.
1765
+
1766
+ Must be called BEFORE ``core.operations.apply_insert_buffer_range`` shifts what follows, so the
1767
+ neighbour on the right is still read at its pre-splice position -- the position the incoming
1768
+ node is taking over. ``None`` when no adjacent neighbour can anchor it, leaving the inserted
1769
+ node's range at its ``None`` default exactly as before."""
1770
+ parent_node = getattr(node, "parent", None)
1771
+ siblings = list(getattr(parent_node, "children", None) or ())
1772
+ try:
1773
+ position = siblings.index(node)
1774
+ except ValueError:
1775
+ return None
1776
+ if position > 0:
1777
+ previous = siblings[position - 1]
1778
+ anchored = _anchored_run(document, [previous])
1779
+ if anchored is not None:
1780
+ run, model = anchored
1781
+ run, model = _resolve_insert_anchor_model(document, parent_node, run, model)
1782
+ return _spans.IndentModel(
1783
+ base=model.base + run.embedded_length(model), width=model.width
1784
+ )
1785
+ if position + 1 < len(siblings):
1786
+ anchored = _anchored_run(document, [siblings[position + 1]])
1787
+ if anchored is not None:
1788
+ run, model = anchored
1789
+ return _resolve_insert_anchor_model(document, parent_node, run, model)[1]
1790
+ return None
1791
+
1792
+
1793
+ def _child_span_extremes(node: LiveNode) -> Tuple[Optional[int], Optional[int]]:
1794
+ """The lowest start and highest end among ``node``'s children's OWN spans."""
1795
+ starts = [
1796
+ child.buffer_range[0]
1797
+ for child in (getattr(node, "children", None) or ())
1798
+ if getattr(child, "buffer_range", None) is not None
1799
+ ]
1800
+ ends = [
1801
+ child.buffer_range[1]
1802
+ for child in (getattr(node, "children", None) or ())
1803
+ if getattr(child, "buffer_range", None) is not None
1804
+ ]
1805
+ return (min(starts) if starts else None, max(ends) if ends else None)
1806
+
1807
+
1808
+ def _boundary_ties(container: Optional[LiveNode]) -> List[Tuple[LiveNode, bool, bool]]:
1809
+ """Which of the splice's ancestors have a span boundary that FOLLOWS a child's, bottom-up.
1810
+
1811
+ A container's own span does not always simply grow by what a splice added inside it: several
1812
+ node kinds take a boundary straight from their extreme child, and a child's boundary can move
1813
+ for reasons that are not length at all. Two observed on real python trees: giving the first
1814
+ method of a class a decorator moves the enclosing suite's START forward, because the suite
1815
+ begins where its first statement's own span begins and a decorator is not part of that span;
1816
+ and a replacement ending in a trailing comment moves the suite's END BACK, because that comment
1817
+ becomes trailing trivia, which spans exclude. A flat "add the delta to every ancestor's end"
1818
+ gets both wrong, the second one by the entire length of the added line.
1819
+
1820
+ Which containers behave this way is not assumed -- it is OBSERVED, here, before the splice:
1821
+ a boundary that coincides with the extreme child's boundary is one that follows it, and is
1822
+ re-derived afterwards; one that does not (a python ``Module``'s end, which sits past its last
1823
+ statement's own span, or a ``ClassDef``'s start, which sits after its own leading trivia) is
1824
+ left to the plain delta. Captured for the whole ancestor chain and replayed bottom-up, so each
1825
+ ancestor is re-derived from a child that has already been corrected."""
1826
+ ties: List[Tuple[LiveNode, bool, bool]] = []
1827
+ current = container
1828
+ while current is not None:
1829
+ span = getattr(current, "buffer_range", None)
1830
+ if span is not None:
1831
+ lowest, highest = _child_span_extremes(current)
1832
+ # The ROOT spans the whole document by definition, so its start is byte 0 whatever its
1833
+ # first child does; only a nested container takes a start from its first child.
1834
+ is_root = getattr(current, "parent", None) is None
1835
+ ties.append((
1836
+ current,
1837
+ (not is_root) and lowest is not None and span[0] == lowest,
1838
+ highest is not None and span[1] == highest,
1839
+ ))
1840
+ current = getattr(current, "parent", None)
1841
+ return ties
1842
+
1843
+
1844
+ def _repair_boundaries(ties: Sequence[Tuple[LiveNode, bool, bool]]) -> None:
1845
+ """Re-derive every boundary :func:`_boundary_ties` observed to follow a child's, bottom-up."""
1846
+ for node, follows_start, follows_end in ties:
1847
+ span = getattr(node, "buffer_range", None)
1848
+ if span is None or not (follows_start or follows_end):
1849
+ continue
1850
+ lowest, highest = _child_span_extremes(node)
1851
+ start = lowest if (follows_start and lowest is not None) else span[0]
1852
+ end = highest if (follows_end and highest is not None) else span[1]
1853
+ if start <= end:
1854
+ node.buffer_range = (start, end)
1855
+
1856
+
1857
+ def _rendered_length(
1858
+ document: TreeDocument, node: Optional[LiveNode], *, resync: Optional[LiveNode] = None
1859
+ ) -> Optional[int]:
1860
+ """Byte length of ``node``'s own faithful render right now, or ``None`` when it has none.
1861
+
1862
+ ``resync`` is the container a splice has just rewritten, and syncing it first is not optional:
1863
+ a splice assigns ``children`` while the node still RENDERS from ``fields``, and
1864
+ ``_ops.replace_range``/``delete`` leave the two out of step until the caller's own sync runs --
1865
+ so a render taken in between replays the PRE-splice text and reports a flat, wrong length.
1866
+ Only that one node needs it: every ancestor holds the same node object in its own fields, which
1867
+ ``core.live_tree.to_frozen`` re-points as it rebuilds.
1868
+
1869
+ Measured through the plugin's compose path only (``_render_source_via_plugin``, never
1870
+ ``_render_source_for_node``): a container's own CACHED source field, where one exists, would
1871
+ replay stale pre-mutation text for the same reason -- the hazard
1872
+ :func:`_measure_insert_delta` already documents."""
1873
+ if node is None:
1874
+ return None
1875
+ try:
1876
+ if resync is not None:
1877
+ sync_fields(resync)
1878
+ rendered = _render_source_via_plugin(node, document)
1879
+ except _SPAN_MEASUREMENT_FAILURES:
1880
+ return None
1881
+ return None if rendered is None else _byte_length(rendered)
1882
+
1883
+
1884
+ def _blank_line_ambiguity(text: Optional[Union[str, bytes]]) -> bool:
1885
+ """Whether ``text`` contains a line whose indentation, once embedded, cannot be predicted.
1886
+
1887
+ Only a BLANK line raises the question, and only inside an indented container: a format may or
1888
+ may not indent one (python's ``EmptyLine`` carries its own flag, and the fragment re-parse a
1889
+ replace performs can flip it -- observed turning a bare ``"\n"`` separator into ``" \n"``),
1890
+ and a run's own text at indent zero looks identical either way. The final line after a trailing
1891
+ newline is never at issue: there is nothing on it to indent."""
1892
+ if text is None:
1893
+ return False
1894
+ body = text.decode("utf-8", "replace") if isinstance(text, (bytes, bytearray)) else text
1895
+ lines = body.split("\n")
1896
+ return any(not line.strip() for line in lines[:-1])
1897
+
1898
+
1899
+ def _mapped_delta(
1900
+ model: "_spans.IndentModel",
1901
+ before: Optional["_spans.RunSpans"],
1902
+ after: Optional["_spans.RunSpans"],
1903
+ ) -> Optional[int]:
1904
+ """The signed byte delta of a splice, from the two runs' own mapped lengths.
1905
+
1906
+ Both lengths are read through the SAME verified map, so the enclosing container's indentation
1907
+ is counted identically on each side and cannot bias the difference -- the flaw that makes a
1908
+ node's, or a nested container's, isolated render unusable as an absolute measure. ``None``
1909
+ when either side could not be measured."""
1910
+ removed = before.embedded_length(model) if before is not None else 0
1911
+ added = after.embedded_length(model) if after is not None else 0
1912
+ if (before is None and removed) or (after is None and added):
1913
+ return None
1914
+ return added - removed
1915
+
1916
+
1917
+ def _indentation_undetermined(
1918
+ model: "_spans.IndentModel",
1919
+ before: Optional["_spans.RunSpans"],
1920
+ after: Optional["_spans.RunSpans"],
1921
+ ) -> bool:
1922
+ """Whether either side of the splice has a line whose embedded indentation the map cannot
1923
+ settle, making the mapped delta untrustworthy by a whole indent width per such line.
1924
+
1925
+ Never an issue at the top level, where there is no indentation to add. For the run being
1926
+ REPLACED the question usually answers itself: its own already-known spans reject one of the two
1927
+ readings outright, and only a run whose spans BOTH readings reproduce is genuinely undetermined.
1928
+ For the run being SPLICED IN there are no known spans to test against, so any blank line in it
1929
+ leaves the question open."""
1930
+ if model.width <= 0:
1931
+ return False
1932
+ if before is not None:
1933
+ alternative = before.with_blank_line_policy(not before.blank_lines_indented)
1934
+ if (
1935
+ alternative is not before
1936
+ and alternative.embedded_length(model) != before.embedded_length(model)
1937
+ and _spans.reproduces(alternative, model)
1938
+ ):
1939
+ return True
1940
+ return after is not None and _blank_line_ambiguity(after.text)
1941
+
1942
+
1943
+ def _rendered_splice_delta(
1944
+ document: TreeDocument, parent_node: Optional[LiveNode], mapped: int
1945
+ ) -> Optional[int]:
1946
+ """The splice's byte delta measured against the WHOLE document, for the one case the map
1947
+ cannot settle on its own.
1948
+
1949
+ The document's length before the splice is already in hand -- the root's own span end, which
1950
+ this same bookkeeping keeps equal to it -- so only the AFTER side has to be rendered, once,
1951
+ and only here. That render is the expensive operation this module otherwise avoids entirely
1952
+ (1.2 s on a 35 KB module), which is why it is reached only when
1953
+ :func:`_indentation_undetermined` says the cheap answer cannot be trusted.
1954
+
1955
+ Falls back to ``mapped`` when the root carries no usable span or cannot be rendered: a
1956
+ measurement that is undetermined by an indent width is still far closer than none at all, and
1957
+ the geometry's own length check independently refuses to place anything on top of it."""
1958
+ root = getattr(document, "root", None)
1959
+ span = getattr(root, "buffer_range", None)
1960
+ if root is None or span is None or span[0] != 0:
1961
+ return mapped
1962
+ rendered = _rendered_length(document, root, resync=parent_node)
1963
+ return mapped if rendered is None else rendered - span[1]
1964
+
1965
+
1966
+ def _apply_spliced_geometry(
1967
+ document: TreeDocument,
1968
+ model: Optional["_spans.IndentModel"],
1969
+ new_run: Optional["_spans.RunSpans"],
1970
+ expected_length: Optional[int],
1971
+ ) -> int:
1972
+ """Give a freshly spliced run the spans it actually occupies.
1973
+
1974
+ ``model`` fixes both unknowns from content whose position is already known -- ``base``, the
1975
+ document offset the spliced run's first byte lands on (for a replace, exactly where the removed
1976
+ run's own text started; for an insert, exactly where the preceding sibling's text ended), and
1977
+ ``width``, the indent prefix the enclosing container adds to each content line. ``new_run``
1978
+ carries the spans a fresh parse of the run's own rendered bytes resolved, and the map turns
1979
+ them into document offsets -- so a decorator, a leading comment run and every other byte of
1980
+ leading trivia is accounted for in the geometry, while each node's own range comes out exactly
1981
+ as a fresh parse of the whole document would give it. Several incoming roots are handled by
1982
+ construction: the run is measured as ONE rendered text, so the roots divide it at the
1983
+ boundaries the re-parse itself found.
1984
+
1985
+ ``expected_length`` is the byte count this splice actually added; the mapped run must occupy
1986
+ exactly that or nothing is assigned at all. Where the delta was measured independently (a
1987
+ whole-document render, taken when the run's own indentation was ambiguous) that is a real
1988
+ cross-check; where it came from the same map it is a consistency guard. Returns how many nodes
1989
+ were given a span (0 when the measurement was declined)."""
1990
+ if model is None or new_run is None or expected_length is None:
1991
+ return 0
1992
+ for blank_policy in _spans.BLANK_LINE_POLICIES:
1993
+ candidate = new_run.with_blank_line_policy(blank_policy)
1994
+ if candidate.embedded_length(model) == expected_length:
1995
+ return _spans.assign_spans(candidate, model)
1996
+ return 0
1997
+
1998
+
1999
+ def _finish_splice(
2000
+ document: TreeDocument,
2001
+ parent_node: Optional[LiveNode],
2002
+ model: "_spans.IndentModel",
2003
+ before_run: Optional["_spans.RunSpans"],
2004
+ after_run: Optional["_spans.RunSpans"],
2005
+ following: Sequence[LiveNode],
2006
+ ties: Sequence[Tuple[LiveNode, bool, bool]],
2007
+ *,
2008
+ measured_delta: Optional[int],
2009
+ fallback_delta: Union[Optional[int], Callable[[], Optional[int]]],
2010
+ ) -> None:
2011
+ """Apply one splice's whole positional consequence: shift what follows, position what arrived,
2012
+ and re-derive the container boundaries that follow a child's.
2013
+
2014
+ ``measured_delta``, when given, is an independently measured byte delta (a whole-document
2015
+ render taken across the splice, used only where the run's own indentation was ambiguous) and
2016
+ wins. Otherwise the delta comes from the two runs' mapped lengths. ``fallback_delta`` is the
2017
+ pre-existing approximate measurement, used only when neither of those is available, so a run
2018
+ this machinery cannot measure is left no worse off than before it existed.
2019
+
2020
+ ``fallback_delta`` may be the value itself (cheap to obtain -- ``delete``/``replace`` already
2021
+ computed it from an isolated, O(fragment) render before calling here) or a zero-argument
2022
+ callable that computes it lazily (``insert``'s own ``_measure_insert_delta``, whose cost is
2023
+ O(``parent_node``'s own rendered subtree) -- O(document) when ``parent_node`` is the document
2024
+ root, as a bulk top-level insert's ``parent_node`` always is). Bug 86107a8f: with an eagerly
2025
+ passed value, the caller pays that render on EVERY splice even when ``measured_delta``/mapped
2026
+ delta above already settled it -- exactly the expensive-render-avoidance this function's own
2027
+ ``_rendered_splice_delta`` docstring says is reached "only when the cheap answer cannot be
2028
+ trusted". The callable form defers the render to here, where it is invoked only on the actual
2029
+ last-resort path, so a splice whose delta the cheap paths already resolved never pays for it."""
2030
+ delta = measured_delta
2031
+ if delta is None:
2032
+ delta = _mapped_delta(model, before_run, after_run)
2033
+ emptied = not (getattr(parent_node, "children", None) or ())
2034
+ if delta is not None and (
2035
+ emptied or _indentation_undetermined(model, before_run, after_run)
2036
+ ):
2037
+ # `emptied`: a container a delete left with nothing in it no longer renders as the sum
2038
+ # of its parts -- a format may substitute a placeholder body, drop the block, or emit
2039
+ # nothing at all -- so the removed run's own length stops describing what the document
2040
+ # lost. Measure it instead.
2041
+ delta = _rendered_splice_delta(document, parent_node, delta)
2042
+ if delta is None:
2043
+ delta = fallback_delta() if callable(fallback_delta) else fallback_delta
2044
+ if delta is None:
2045
+ return
2046
+ _ops.apply_splice_delta(parent_node, following, delta)
2047
+ expected = (before_run.embedded_length(model) if before_run is not None else 0) + delta
2048
+ if _apply_spliced_geometry(document, model, after_run, expected):
2049
+ _repair_boundaries(ties)
2050
+
2051
+
2052
+ def _extract_source_from_nodes(
2053
+ nodes: Sequence[LiveNode], document: TreeDocument
2054
+ ) -> Optional[Union[str, bytes, Dict[str, Any]]]:
2055
+ """Extract or render source from a sequence of nodes at O(fragment) cost.
2056
+
2057
+ For each node:
2058
+ 1. Try cached source first (O(1))
2059
+ 2. Then try the plugin's own compose/render path for a wrapper node with
2060
+ no cached source of its own (O(fragment); bug 6df2cf33)
2061
+ 3. If unavailable for all, return structured fallback form
2062
+
2063
+ Args:
2064
+ nodes: The nodes to extract source from.
2065
+ document: The document (for potential multi-node rendering).
2066
+
2067
+ Returns:
2068
+ str/bytes if faithful source (cached or plugin-rendered) is available
2069
+ for all nodes; structured dict {'fragments': [...]} if per-child
2070
+ extraction used with multiple nodes; structured dict
2071
+ {'node_ids': [...], 'kinds': [...]} as minimal fallback when no
2072
+ faithful source exists; None only if nodes is empty.
2073
+ """
2074
+ if not nodes:
2075
+ return None
2076
+
2077
+ # Collect faithful sources for all nodes
2078
+ fragments = []
2079
+ all_available = True
2080
+ for node in nodes:
2081
+ rendered = _render_source_for_node(node, document)
2082
+ if rendered is None:
2083
+ all_available = False
2084
+ break
2085
+ fragments.append(rendered)
2086
+
2087
+ # If all nodes have faithful source, concatenate and return
2088
+ if all_available:
2089
+ if all(isinstance(f, bytes) for f in fragments):
2090
+ return b"".join(fragments)
2091
+ elif all(isinstance(f, str) for f in fragments):
2092
+ return "".join(fragments)
2093
+ else:
2094
+ # Mixed str/bytes; convert all to bytes
2095
+ result = []
2096
+ for f in fragments:
2097
+ if isinstance(f, bytes):
2098
+ result.append(f)
2099
+ else:
2100
+ result.append(f.encode("utf-8"))
2101
+ return b"".join(result)
2102
+
2103
+ # No faithful source available for at least one node.
2104
+ # For multiple nodes, use structured form with fragments list.
2105
+ if len(nodes) > 1:
2106
+ structured_fragments = []
2107
+ for node in nodes:
2108
+ rendered = _render_source_for_node(node, document)
2109
+ if rendered is not None:
2110
+ structured_fragments.append(rendered)
2111
+ # If a node has no faithful source, we skip it and let the structured
2112
+ # form capture node_ids/kinds instead
2113
+ if structured_fragments:
2114
+ # Some (but not all) nodes have faithful source: use fragments list
2115
+ return {"fragments": structured_fragments}
2116
+
2117
+ # No faithful source anywhere: use minimal structured fallback
2118
+ return _structured_fallback_for_nodes(nodes)
2119
+
2120
+
2121
+ _COMPUTE_ANCHOR_SENTINEL = object()
2122
+
2123
+
2124
+ def _commit_mutation(
2125
+ document: TreeDocument,
2126
+ op: str,
2127
+ touched_node: Optional[LiveNode],
2128
+ *,
2129
+ sync_parent: Optional[LiveNode] = None,
2130
+ invalidate_node: Optional[LiveNode] = None,
2131
+ inserted: Optional[Sequence[LiveNode]] = None,
2132
+ deleted: Optional[Sequence[LiveNode]] = None,
2133
+ size_delta: int = 0,
2134
+ node_path_override: Optional[Tuple[str, ...]] = None,
2135
+ before_fragment: Optional[Union[str, bytes, Dict[str, Any]]] = None,
2136
+ after_fragment: Optional[Union[str, bytes, Dict[str, Any]]] = None,
2137
+ anchor: Union[None, Dict[str, Any], object] = _COMPUTE_ANCHOR_SENTINEL,
2138
+ extra_payload: Optional[Dict[str, Any]] = None,
2139
+ record_journal: bool = True,
2140
+ ) -> None:
2141
+ """Apply a mutation atomically: pointwise index updates, field sync, cache invalidation,
2142
+ journal entry, and version bump.
2143
+
2144
+ ``record_journal`` (default True): when False, every effect below still runs EXCEPT the
2145
+ journal append -- see ``replace_node_id``'s own ``record_journal`` for the one caller that
2146
+ passes False and why. The version bump still happens either way (an internal counter, never
2147
+ itself journaled or replayed).
2148
+
2149
+ Per the G-014 group invariant (C-005/C-006 model), atomic application performs NO full
2150
+ tree traversal, NO full re-parse, NO full index rebuild. The only extra effects are the
2151
+ ancestor-chain aggregate update and EXACTLY ONE appended mutation-journal entry per
2152
+ applied operation.
2153
+
2154
+ Args:
2155
+ document: The TreeDocument being mutated.
2156
+ op: The facade operation name ('insert', 'delete', 'replace', 'move', 'set_attribute',
2157
+ 'set_body', 'replace_node_id', 'apply_subtree').
2158
+ touched_node: The node that was affected by the operation (inserted, deleted, or modified).
2159
+ May be None for operations with no specific touched node. Used to compute node_path
2160
+ for the journal entry and position anchor.
2161
+ sync_parent: The parent node whose fields should be synced with children. None to skip
2162
+ sync_fields. Only operations that change children call this (insert, delete, replace,
2163
+ move, apply_subtree, set_body); set_attribute and replace_node_id pass None.
2164
+ invalidate_node: The node whose cached source should be invalidated. None to skip
2165
+ invalidation. Operations that modify the tree pass the affected node/parent; set_attribute
2166
+ invalidates the node itself; replace_node_id passes None (no cached source change).
2167
+ inserted: Sequence of nodes newly added to the tree. Each is indexed via index_subtree().
2168
+ deleted: Sequence of nodes removed from the tree. Each is deindexed via deindex_subtree().
2169
+ size_delta: Byte-size delta of the touched fragment (when cheaply known, else 0).
2170
+ Included in journal payload.
2171
+ node_path_override: A precomputed root-to-node path to record instead of walking
2172
+ ``touched_node.parent`` here. ``move`` needs this: by the time this function runs,
2173
+ ``_move_mod.move`` has already completed the full detach-and-reattach, so
2174
+ ``touched_node.parent`` is already the TARGET parent for both of the two calls a
2175
+ cross-parent move makes -- the caller captures the SOURCE-side path before calling
2176
+ ``_move_mod.move`` and passes it here for the removal entry, leaving the addition
2177
+ entry's on-the-fly computation (correct by then) untouched.
2178
+ before_fragment: The source/state before the mutation (str/bytes or structured dict).
2179
+ For text operations (insert, delete, replace, set_body, move, apply_subtree):
2180
+ - str/bytes: the source text of the touched fragment
2181
+ - dict: structured form when rendering is not cheaply available
2182
+ - None: indicates the fragment was created/does not exist before (insert)
2183
+ For structured operations (set_attribute, replace_node_id):
2184
+ - dict: minimal form like {'name': ..., 'value': <old>} or {'node_id': <uuid>}
2185
+ after_fragment: The source/state after the mutation (str/bytes or structured dict).
2186
+ Same structure as before_fragment. For delete, this is None (fragment was removed).
2187
+ anchor_before_delete_move_removal: Flag indicating whether to capture anchor BEFORE
2188
+ the mutation applies (True for delete/move-removal) or AFTER (False/default for
2189
+ insert/move-attach/set_body). set_attribute/replace_node_id always use
2190
+ anchor=None; set_body computes a real position anchor like the other
2191
+ text operations.
2192
+ Journal Payload per operation (all have exactly 4 keys: size_delta, before, after, anchor):
2193
+ insert: {'size_delta': ..., 'before': None, 'after': <source>, 'anchor': {...}}
2194
+ delete: {'size_delta': ..., 'before': <source>, 'after': None, 'anchor': {...}}
2195
+ replace: {'size_delta': ..., 'before': <old source>, 'after': <new source>, 'anchor': {...}}
2196
+ move: {'size_delta': ..., 'before': <source>, 'after': <source>, 'anchor': {...}} (both entries)
2197
+ set_body: {'size_delta': ..., 'before': <old body source>, 'after': <new source>, 'anchor': {...}}
2198
+ set_attribute: {'size_delta': 0, 'before': {'name': ..., 'value': ...},
2199
+ 'after': {'name': ..., 'value': ...}, 'anchor': None}
2200
+ replace_node_id: {'size_delta': 0, 'before': {'node_id': <old>}, 'after': {'node_id': <new>},
2201
+ 'anchor': None}
2202
+ apply_subtree: {'size_delta': ..., 'before': <old source>, 'after': <new source>, 'anchor': {...}}
2203
+
2204
+ Position anchor (when not None): {'child_index': <int>, 'prev_sibling': <node_id str or None>}
2205
+ For insert/delete/replace/move/set_body/apply_subtree: the touched node's position in
2206
+ parent's children at capture time (before for delete/move-removal, after for
2207
+ insert/move-attach/set_body).
2208
+ For set_attribute/replace_node_id: always None.
2209
+ """
2210
+ _collected = _TOUCHED.get()
2211
+ if _collected is not None:
2212
+ _collected.append((document, sync_parent or invalidate_node or touched_node))
2213
+
2214
+ # Sync fields and invalidate cached source (when applicable per operation semantics).
2215
+ #
2216
+ # DECISION (bug 17f05476 residue): this used to snapshot `sync_parent.children` HERE and
2217
+ # restore it if `sync_fields` raised below -- a "safety net" that was always too late to be
2218
+ # safe. By the time this function runs, the operation's own splice
2219
+ # (`core.operations.insert/delete/replace_range` or `core.move.move`'s `_detach`/`_attach`)
2220
+ # has ALREADY mutated `sync_parent.children` (and, for delete/replace/move, already dropped
2221
+ # the removed node's identity from `document.nodes_by_id` via `_unregister_subtree`/
2222
+ # `_detach`'s own log) -- so a snapshot taken here always captured the POST-splice shape,
2223
+ # not the pre-splice one, and restoring `children` alone from it could never undo the
2224
+ # matching `nodes_by_id`/short_id/parent-link mutations anyway: a partial, misleading
2225
+ # rollback, not a real one. The actual fix is upfront, not here: `insert`, `delete`,
2226
+ # `replace_range` and `move` each now call the shared `_single_sequence_field` precheck
2227
+ # BEFORE their own splice runs (see their own docstrings/comments), refusing cleanly with
2228
+ # the identical `NodeSchemaError(INVALID_PARENT_TYPE, ...)` `sync_fields` would otherwise
2229
+ # have discovered only afterward. That precheck is deliberately narrower than `sync_fields`
2230
+ # itself for one ambiguous shape -- a parent with MORE THAN ONE node-sequence field -- left
2231
+ # for `sync_fields`'s own "already matches `children`" fallback to resolve; nothing this
2232
+ # backup/restore ever did made that residual case safer either (same partial-undo problem).
2233
+ # So the post-hoc restore is dropped outright rather than relocated: there is no point in
2234
+ # this call chain, before the mutation already happened three frames up, left to take a
2235
+ # PRE-splice snapshot from.
2236
+ sync_fields(sync_parent)
2237
+ invalidate_cached_source(invalidate_node)
2238
+
2239
+ # Pointwise index updates for inserted and deleted nodes
2240
+ if inserted:
2241
+ for node in inserted:
2242
+ document.index_subtree(node)
2243
+ if deleted:
2244
+ for node in deleted:
2245
+ document.deindex_subtree(node)
2246
+
2247
+ # Compute parent_id for journal entry: use sync_parent if set, else touched_node's parent
2248
+ journal_parent_id = ""
2249
+ if sync_parent is not None:
2250
+ journal_parent_id = str(sync_parent.node_id)
2251
+ elif touched_node is not None and touched_node.parent is not None:
2252
+ journal_parent_id = str(touched_node.parent.node_id)
2253
+
2254
+ # Compute node_path from root to touched_node for journal entry, unless the caller
2255
+ # already captured it (move's removal entry -- see node_path_override above).
2256
+ node_path = (
2257
+ node_path_override
2258
+ if node_path_override is not None
2259
+ else _node_path_to_root(touched_node)
2260
+ )
2261
+
2262
+ # Compute position anchor for the touched node
2263
+ # For set_attribute, replace_node_id: always None
2264
+ # For text operations: compute position in parent (unless explicitly provided)
2265
+ computed_anchor: Optional[Dict[str, Any]] = None
2266
+ if anchor is _COMPUTE_ANCHOR_SENTINEL:
2267
+ # Compute anchor if not provided
2268
+ if op not in ("set_attribute", "replace_node_id"):
2269
+ parent_for_anchor = (
2270
+ touched_node.parent if touched_node is not None else None
2271
+ )
2272
+ computed_anchor = _get_child_position_anchor(
2273
+ parent_for_anchor, touched_node
2274
+ )
2275
+ else:
2276
+ # Use provided anchor (which may be None)
2277
+ computed_anchor = anchor # type: ignore
2278
+
2279
+ # Build payload with exactly 4 keys: size_delta, before, after, anchor
2280
+ payload: Dict[str, Any] = {
2281
+ "size_delta": size_delta,
2282
+ "before": before_fragment,
2283
+ "after": after_fragment,
2284
+ "anchor": computed_anchor,
2285
+ }
2286
+ # Merge any extra payload fields (e.g., for format-specific metadata like root_trailing_separator_before)
2287
+ if extra_payload:
2288
+ payload.update(extra_payload)
2289
+
2290
+ # Append exactly one journal entry, unless the caller opted out (record_journal=False;
2291
+ # see replace_node_id's own docstring for the one caller that does).
2292
+ if record_journal:
2293
+ document.journal.append(
2294
+ op=op,
2295
+ node_path=node_path,
2296
+ parent_id=journal_parent_id,
2297
+ payload=payload,
2298
+ )
2299
+
2300
+ # Bump document version
2301
+ document.document_version += 1
2302
+
2303
+
2304
+ def _fragment(
2305
+ document: TreeDocument, source: Union[str, bytes], *, context_kind: Optional[str] = None,
2306
+ parent_node: Optional[LiveNode] = None,
2307
+ ) -> List[LiveNode]:
2308
+ """Parse caller-supplied source into fresh live nodes through the document's own plugin, giving a
2309
+ node whose id would collide with a live one a fresh UUID4 and leaving short_id allocation to the
2310
+ core preflight.
2311
+
2312
+ A fragment parser is free to wrap its result in a CONTAINER of its own -- ``plain_text``'s does,
2313
+ documenting that ``parse_fragment`` "always yields a root container Node" -- and splicing that
2314
+ container in as a sibling builds a tree the same format then cannot render: ``dumps()`` fails
2315
+ with ``UNSUPPORTED_TRANSLATION`` on a ``plain_text:root`` found where a paragraph belongs. A
2316
+ plugin says so by declaring ``fragment_container_kinds``, and such a node is unwrapped to its
2317
+ children, which are the content the caller meant. The declaration is what keeps this narrow:
2318
+ for JSON an object returned by ``parse_fragment`` is a genuine value and must NOT be unwrapped,
2319
+ even though it carries the document root's own kind. An empty container carries no content at
2320
+ all, so it raises like every other structureless fragment instead of splicing nothing.
2321
+
2322
+ ``context_kind`` (bug f2991fc0) is an optional hint -- the kind of the node this fragment is
2323
+ about to replace, or of the anchor node it will land beside/inside -- forwarded verbatim as
2324
+ ``options={"context_kind": ...}`` to ``plugin.parse_fragment``. Every plugin ignores an option
2325
+ key it does not recognize (the shared, generic ``options: Mapping`` contract), so this is a
2326
+ no-op for every format but python, where it disambiguates a fragment that is syntactically
2327
+ both a valid bare expression and a valid statement (see
2328
+ ``plugins.python.plugin._context_prefers_statement``): omitted (``None``, every call site
2329
+ unaware of or indifferent to the target shape) preserves today's unconditional
2330
+ expression-first parse order exactly.
2331
+
2332
+ ``parent_node`` (bug c6042d8c) is the live node this fragment is about to be spliced UNDER, if
2333
+ known. It is used for exactly one thing: when its ``kind`` is one of the plugin's OWN declared
2334
+ ``document_level_parent_kinds`` (the same duck-typed declaration style as
2335
+ ``fragment_container_kinds`` above -- absent on every plugin but TOML today), this passes
2336
+ ``options["mode"] = "document"`` through to ``plugin.parse_fragment``. TOML declares
2337
+ ``(toml:Document,)``: a fragment landing directly under the document root is unambiguously a
2338
+ whole top-level statement, so its shape must not be inferred from whether the caller happened
2339
+ to newline-terminate it (see ``plugins.toml_format.TomlFormatPlugin.parse_fragment`` and its
2340
+ ``document_level_parent_kinds`` declaration for why only the document root itself qualifies).
2341
+ A plugin that declares nothing here is completely unaffected.
2342
+ """
2343
+ plugin = _plugin(document.format_id)
2344
+ options = {}
2345
+ if context_kind is not None:
2346
+ options["context_kind"] = context_kind
2347
+ document_level_parent_kinds = getattr(plugin, "document_level_parent_kinds", ()) or ()
2348
+ if parent_node is not None and parent_node.kind in document_level_parent_kinds:
2349
+ options["mode"] = "document"
2350
+ document_options = getattr(plugin, "fragment_options", None)
2351
+ if callable(document_options):
2352
+ # A format whose fragments depend on the document they land in (csv: its delimiter) says so
2353
+ # by publishing ``fragment_options(root) -> mapping``; duck-typed like the hooks above.
2354
+ options.update(document_options(document.root))
2355
+ options = options if options else None
2356
+ parsed = plugin.parse_fragment(source, options)
2357
+ if isinstance(parsed, str):
2358
+ raise FormatFragmentParseFailed(
2359
+ f"{document.format_id} found no structure in the given fragment"
2360
+ )
2361
+ roots = [
2362
+ to_live(n) for n in (parsed if isinstance(parsed, (list, tuple)) else [parsed])
2363
+ ]
2364
+ containers = tuple(getattr(plugin, "fragment_container_kinds", ()) or ())
2365
+ if len(roots) == 1 and roots[0].kind in containers:
2366
+ roots = roots[0].children
2367
+ for node in roots:
2368
+ node.parent = None
2369
+ if not roots:
2370
+ raise FormatFragmentParseFailed(
2371
+ f"{document.format_id} found no structure in the given fragment"
2372
+ )
2373
+ for node in (n for root in roots for n in walk(root)):
2374
+ if node.node_id in document.nodes_by_id:
2375
+ node.node_id = generate_node_id()
2376
+ node.short_id = None
2377
+ return roots
2378
+
2379
+
2380
+ # -- BSL method blocks ------------------------------------------------------
2381
+
2382
+ _BSL_METHOD_KINDS = frozenset({"bsl:procedure_definition", "bsl:function_definition"})
2383
+ _BSL_METHOD_TRIVIA_KINDS = frozenset({"bsl:line_comment", "core:annotation"})
2384
+
2385
+
2386
+ def _bsl_method_scope(node: LiveNode) -> Optional[List[LiveNode]]:
2387
+ """Return the source-file siblings owned by one BSL method block.
2388
+
2389
+ tree-sitter represents a leading comment and ``&`` directive as siblings
2390
+ of the procedure/function. The editor exposes the procedure/function as
2391
+ the block handle, so a method mutation must carry those immediately
2392
+ preceding siblings with it.
2393
+ """
2394
+ if node.kind not in _BSL_METHOD_KINDS:
2395
+ return None
2396
+ parent = node.parent
2397
+ if parent is None or parent.kind != "bsl:source_file":
2398
+ return None
2399
+ children = list(parent.children)
2400
+ try:
2401
+ index = children.index(node)
2402
+ except ValueError:
2403
+ return None
2404
+ first = index
2405
+ while first > 0 and children[first - 1].kind in _BSL_METHOD_TRIVIA_KINDS:
2406
+ first -= 1
2407
+ return children[first:index + 1]
2408
+
2409
+
2410
+ def _bsl_scope_for_resolved(resolved: Sequence[LiveNode]) -> Optional[List[LiveNode]]:
2411
+ """Return the one complete BSL method block represented by ``resolved``.
2412
+
2413
+ Journal replay resolves a stored multi-node fragment by its sibling range.
2414
+ A method fragment with its leading comment and directive therefore arrives
2415
+ as all three source-file siblings, whereas a live caller normally names
2416
+ only the procedure/function. Treat both forms as one logical method
2417
+ block, but do not widen an arbitrary adjacent-node range.
2418
+ """
2419
+ if not resolved:
2420
+ return None
2421
+ method_index = next(
2422
+ (index for index, node in enumerate(resolved) if node.kind in _BSL_METHOD_KINDS),
2423
+ None,
2424
+ )
2425
+ if method_index is None:
2426
+ return None
2427
+ scope = _bsl_method_scope(resolved[method_index])
2428
+ if scope is None:
2429
+ return None
2430
+ if len(resolved) == 1 and resolved[0] is scope[-1]:
2431
+ return scope
2432
+ if list(resolved[:method_index + 1]) != scope:
2433
+ return None
2434
+ trailing = list(resolved[method_index + 1:])
2435
+ if not trailing or all(node.kind == "bsl:ERROR" for node in trailing):
2436
+ # A raw replacement may intentionally retain text tree-sitter cannot
2437
+ # classify. Replay resolves that retained suffix as ``bsl:ERROR``;
2438
+ # keep it in the byte span so undo removes the whole replacement.
2439
+ return scope + trailing
2440
+ return None
2441
+
2442
+
2443
+ def _bsl_scope_method(scope: Sequence[LiveNode]) -> Optional[LiveNode]:
2444
+ """Return the procedure/function that owns one logical BSL source span."""
2445
+ return next((node for node in reversed(scope) if node.kind in _BSL_METHOD_KINDS), None)
2446
+
2447
+
2448
+ def _bsl_scope_span(scope: Sequence[LiveNode]) -> Optional[Tuple[int, int]]:
2449
+ if not scope:
2450
+ return None
2451
+ first, last = scope[0].buffer_range, scope[-1].buffer_range
2452
+ if first is None or last is None:
2453
+ return None
2454
+ return first[0], last[1]
2455
+
2456
+
2457
+ def _bsl_scope_before(scope: Sequence[LiveNode], source: bytes) -> Optional[bytes]:
2458
+ span = _bsl_scope_span(scope)
2459
+ if span is None:
2460
+ return None
2461
+ start, end = span
2462
+ return source[start:end] if 0 <= start <= end <= len(source) else None
2463
+
2464
+
2465
+ def _bsl_next_sibling_start(scope: Sequence[LiveNode], source: bytes) -> int:
2466
+ parent = scope[0].parent
2467
+ if parent is None:
2468
+ return len(source)
2469
+ children = list(parent.children)
2470
+ try:
2471
+ index = children.index(scope[-1]) + 1
2472
+ except ValueError:
2473
+ return len(source)
2474
+ if index < len(children) and children[index].buffer_range is not None:
2475
+ return children[index].buffer_range[0]
2476
+ return len(source)
2477
+
2478
+
2479
+ def _bsl_separator(
2480
+ source: bytes,
2481
+ previous: Optional[LiveNode],
2482
+ following: Optional[LiveNode],
2483
+ ) -> bytes:
2484
+ if previous is not None and following is not None:
2485
+ before, after = previous.buffer_range, following.buffer_range
2486
+ if before is not None and after is not None and 0 <= before[1] <= after[0] <= len(source):
2487
+ gap = source[before[1]:after[0]]
2488
+ if gap and gap.strip() == b"":
2489
+ return gap
2490
+ return b"\n"
2491
+
2492
+
2493
+ def _bsl_refresh_from_source(document: TreeDocument, source: bytes) -> None:
2494
+ """Replace BSL's live parse tree from known edited bytes without a boundary.
2495
+
2496
+ A tree-sitter fragment has byte offsets relative to itself. After a
2497
+ splice those offsets cannot safely share the original document buffer.
2498
+ The source splice is already exact here, so rebuild the live tree from it
2499
+ while retaining each post-mutation node id by structural path. This is
2500
+ internal mutation maintenance, never external recovery: the operation's
2501
+ existing journal entry and document version remain the sole history step.
2502
+ """
2503
+ identity = identity_by_path_snapshot(document)
2504
+ rebuilt = loads(source, format_id="bsl", allow_plain_text_fallback=False)
2505
+ paths: Dict[Tuple[int, ...], LiveNode] = {}
2506
+
2507
+ def collect(node: LiveNode, path: Tuple[int, ...]) -> None:
2508
+ paths[path] = node
2509
+ for index, child in enumerate(node.children):
2510
+ collect(child, path + (index,))
2511
+
2512
+ collect(rebuilt.root, ())
2513
+ for path, node_id in identity.items():
2514
+ node = paths.get(path)
2515
+ if node is not None:
2516
+ node.node_id = node_id
2517
+ document.root = rebuilt.root
2518
+ document.source_bytes = source
2519
+ document.format_id = rebuilt.format_id
2520
+ document.fallback_diagnostic = rebuilt.fallback_diagnostic
2521
+ relink(document.root)
2522
+ document.reindex()
2523
+
2524
+
2525
+ def _bsl_set_ref_alias(
2526
+ document: TreeDocument,
2527
+ old_short_id: Optional[int],
2528
+ new_node_id: Optional[UUID],
2529
+ ) -> None:
2530
+ if old_short_id is None or new_node_id is None:
2531
+ return
2532
+ new_node = document.nodes_by_id.get(new_node_id)
2533
+ if new_node is None or new_node.short_id is None:
2534
+ return
2535
+ aliases = getattr(document, "_bsl_node_ref_aliases", None)
2536
+ if not isinstance(aliases, dict):
2537
+ aliases = {}
2538
+ setattr(document, "_bsl_node_ref_aliases", aliases)
2539
+ aliases[str(old_short_id)] = new_node.short_id
2540
+
2541
+
2542
+ # -- BSL blocks: edits planned on the source bytes (D-CE.5, D-CF.2-D-CF.4) ---------------------------
2543
+
2544
+
2545
+ def _bsl_in_scope(*nodes: Optional[LiveNode]) -> bool:
2546
+ """True when any node is, or lies inside, a block, a branch or a method body."""
2547
+ return any(node is not None and _bsl_edit.involved(node) for node in nodes)
2548
+
2549
+
2550
+ def _bsl_source_has_block(document: TreeDocument, source: Union[str, bytes]) -> bool:
2551
+ """True when the fragment parses into at least one block or branch node."""
2552
+ try:
2553
+ roots = _fragment(document, source)
2554
+ except Exception:
2555
+ return False
2556
+ return any(
2557
+ _bsl_blocks.is_block(node) or _bsl_blocks.is_branch(node) for root in roots for node in walk(root)
2558
+ )
2559
+
2560
+
2561
+ def _bsl_chain(node: Optional[LiveNode]) -> List[LiveNode]:
2562
+ chain: List[LiveNode] = []
2563
+ while node is not None:
2564
+ chain.append(node)
2565
+ node = node.parent
2566
+ return chain
2567
+
2568
+
2569
+ def _bsl_lowest_common(nodes: Sequence[LiveNode]) -> Optional[LiveNode]:
2570
+ chains = [_bsl_chain(node) for node in nodes]
2571
+ for candidate in chains[0]:
2572
+ if all(any(candidate is other for other in chain) for chain in chains[1:]):
2573
+ return candidate
2574
+ return None
2575
+
2576
+
2577
+ def _bsl_unit_of(node: Optional[LiveNode]) -> Optional[LiveNode]:
2578
+ """The nearest block (never a branch) or method at or above ``node``."""
2579
+ while node is not None:
2580
+ if (_bsl_blocks.is_block(node) and not _bsl_blocks.is_branch(node)) or node.kind in _BSL_METHOD_KINDS:
2581
+ return node
2582
+ node = node.parent
2583
+ return None
2584
+
2585
+
2586
+ def _bsl_adopt(document: TreeDocument, source: bytes, rebuilt: TreeDocument) -> None:
2587
+ """Make ``rebuilt`` the live tree of ``document``, keeping node ids by structural path."""
2588
+ identity = identity_by_path_snapshot(document)
2589
+ paths: Dict[Tuple[int, ...], LiveNode] = {}
2590
+
2591
+ def collect(node: LiveNode, path: Tuple[int, ...]) -> None:
2592
+ paths[path] = node
2593
+ for position, child in enumerate(node.children):
2594
+ collect(child, path + (position,))
2595
+
2596
+ collect(rebuilt.root, ())
2597
+ for path, node_id in identity.items():
2598
+ node = paths.get(path)
2599
+ if node is not None:
2600
+ node.node_id = node_id
2601
+ document.root = rebuilt.root
2602
+ document.source_bytes = source
2603
+ document.format_id = rebuilt.format_id
2604
+ document.fallback_diagnostic = rebuilt.fallback_diagnostic
2605
+ relink(document.root)
2606
+ document.reindex()
2607
+
2608
+
2609
+ def _bsl_apply_plan(document: TreeDocument, plan: "_bsl_edit.Plan") -> Tuple[LiveNode, int]:
2610
+ """Validate, journal (ONE step) and apply a source-splice plan; rebuild the tree from the new bytes.
2611
+
2612
+ The new bytes are parsed first: a structure the plugin refuses (an unbalanced replacement, a second
2613
+ ``Иначе``, a lone closing line) raises ``FORMAT_FRAGMENT_PARSE_FAILED`` and the document is untouched.
2614
+
2615
+ Journal: an edit inside a block or a method is ONE ``replace`` of that unit's whole lines (its text is
2616
+ balanced, so undo and redo replay it as a fragment); at module level an insert / delete / replace of
2617
+ whole lines is journaled as such and a module-level move as a ``replace`` of the covering run.
2618
+
2619
+ Returns:
2620
+ The first new node at the journaled position and that position.
2621
+ """
2622
+ src = bytes(document.source_bytes)
2623
+ new_src = _bsl_edit.apply_splices(src, plan.splices)
2624
+ try:
2625
+ rebuilt = loads(new_src, format_id="bsl", allow_plain_text_fallback=False)
2626
+ except TreeEngineException as exc:
2627
+ raise FormatFragmentParseFailed(
2628
+ f"bsl: the edit would leave an unbalanced or invalid structure: {exc}"
2629
+ ) from exc
2630
+ delta = len(new_src) - len(src)
2631
+ lowest = _bsl_lowest_common([plan.container, *plan.extra_containers])
2632
+ unit = _bsl_unit_of(lowest)
2633
+ root = document.root
2634
+ index: int
2635
+ if unit is not None:
2636
+ run = _bsl_edit.scope_of(unit)
2637
+ parent: LiveNode = unit.parent # type: ignore[assignment]
2638
+ if parent is None:
2639
+ raise InvalidPosition("bsl: the edited unit has no parent")
2640
+ else:
2641
+ parent = root
2642
+ run = _bsl_module_run(src, root, plan)
2643
+ if not run:
2644
+ # An empty module: the only possible plan is one insertion.
2645
+ offset = plan.splices[0].start
2646
+ index = 0
2647
+ op, before, after = "insert", None, _BslLines(plan.splices[0].data)
2648
+ anchor: Optional[Dict[str, Any]] = {"child_index": 0, "prev_sibling": None}
2649
+ old_path: Tuple[str, ...] = ()
2650
+ old_short = None
2651
+ else:
2652
+ op = "replace"
2653
+ start, end = _bsl_edit.line_extent(src, run)
2654
+ if any(sp.start < start or sp.end > end for sp in plan.splices):
2655
+ raise InvalidPosition("bsl: the edit reaches outside the lines of its block")
2656
+ before = _BslLines(src[start:end])
2657
+ after = _BslLines(new_src[start:end + delta])
2658
+ index = list(parent.children).index(run[0])
2659
+ anchor = _get_child_position_anchor(parent, run[0]) or {"child_index": index, "prev_sibling": None}
2660
+ old_path = _node_path_to_root(run[0])
2661
+ old_short = run[0].short_id
2662
+ parent_id = parent.node_id
2663
+ _bsl_adopt(document, new_src, rebuilt)
2664
+ parent_live = document.nodes_by_id[parent_id]
2665
+ kids_after = list(parent_live.children)
2666
+ touched = kids_after[min(index, len(kids_after) - 1)] if kids_after else parent_live
2667
+ document.journal.append(
2668
+ op=op,
2669
+ node_path=_node_path_to_root(touched) if kids_after else old_path,
2670
+ parent_id=str(parent_id),
2671
+ payload={"size_delta": delta, "before": before, "after": after, "anchor": anchor},
2672
+ )
2673
+ document.document_version += 1
2674
+ if op == "replace":
2675
+ _bsl_set_ref_alias(document, old_short, touched.node_id)
2676
+ return touched, index
2677
+
2678
+
2679
+ class _BslLines(bytes):
2680
+ """Marks a journal fragment written by the BSL block edit layer (whole lines of a block, a method or a
2681
+ covering run of top-level nodes). A replay of such a fragment goes back through the same layer, never
2682
+ through the byte-span method splice, so undo and redo restore the bytes exactly."""
2683
+
2684
+
2685
+ def _bsl_module_run(src: bytes, root: LiveNode, plan: "_bsl_edit.Plan") -> List[LiveNode]:
2686
+ """The top-level nodes a module-level plan changes, plus one unchanged neighbour.
2687
+
2688
+ The neighbour keeps the journaled text non-empty and carries the blank lines around the change, so
2689
+ undo restores them byte for byte."""
2690
+ kids = list(root.children)
2691
+ if not kids:
2692
+ return []
2693
+ low = min(sp.start for sp in plan.splices)
2694
+ high = max(sp.end for sp in plan.splices)
2695
+ spans = [_bsl_edit.line_extent(src, [k]) for k in kids]
2696
+ overlap = [i for i, (a, b) in enumerate(spans) if a < high and b > low]
2697
+ following = next((i for i, (a, _b) in enumerate(spans) if a >= high), None)
2698
+ previous = [i for i, (_a, b) in enumerate(spans) if b <= low and i not in overlap]
2699
+ indexes = overlap + ([following] if following is not None else []) + ([previous[-1]] if previous else [])
2700
+ if not indexes:
2701
+ return kids[:1]
2702
+ return kids[min(indexes): max(indexes) + 1]
2703
+
2704
+
2705
+ def _bsl_mutation_result(touched: LiveNode, index: int) -> "_ops.MutationResult":
2706
+ return _ops.MutationResult(node_id=touched.node_id, short_id=touched.short_id, position=index)
2707
+
2708
+
2709
+ def _bsl_plan_error(exc: "_bsl_edit.BlockEditError") -> InvalidPosition:
2710
+ return InvalidPosition(f"bsl: {exc}")
2711
+
2712
+
2713
+ def _insert_context_kind(
2714
+ parent_node: Optional[LiveNode], sibling_node: Optional[LiveNode]
2715
+ ) -> Optional[str]:
2716
+ """The ``context_kind`` hint (bug f2991fc0) for ``insert()``'s own call to :func:`_fragment`:
2717
+ the kind of whatever node the incoming fragment will actually land beside/among, so a
2718
+ fragment that is syntactically both a valid bare expression and a valid statement (any string
2719
+ literal, including a docstring) lands in the SHAPE the target position needs rather than
2720
+ always the bare expression (see ``plugins.python.plugin._context_prefers_statement``).
2721
+
2722
+ ``before``/``after`` place the fragment directly among ``sibling_node``'s own siblings --
2723
+ ``sibling_node`` IS that position's own occupant, so its kind is the exact answer.
2724
+ ``first_child``/``last_child``/``child_index`` address ``parent_node``, which
2725
+ ``core.operations._sequence_splice_target`` may still route one level down (a
2726
+ ``ClassDef``/``FunctionDef`` addressed directly, whose real statement sequence lives in its
2727
+ nested ``IndentedBlock`` -- the same routing ``_ops.insert`` itself applies to the actual
2728
+ splice, replicated here read-only so the hint agrees with where the fragment truly lands):
2729
+ an existing child of that routed node is as good a witness as a sibling; absent that (an
2730
+ empty suite), the routed node's OWN kind (``python:IndentedBlock``/``python:Module``) still
2731
+ tells the python plugin this position holds statements, not expressions.
2732
+ """
2733
+ if sibling_node is not None:
2734
+ return sibling_node.kind
2735
+ if parent_node is None:
2736
+ return None
2737
+ routed = _ops._sequence_splice_target(parent_node)
2738
+ children = getattr(routed, "children", None) or ()
2739
+ if children:
2740
+ return children[0].kind
2741
+ return getattr(routed, "kind", None)
2742
+
2743
+
2744
+ def count_fragment_nodes(
2745
+ document: TreeDocument, source: Union[str, bytes], *, context_kind: Optional[str] = None,
2746
+ ) -> int:
2747
+ """How many top-level sibling nodes ``insert(document, source, ...)`` would create for
2748
+ this ``source``, WITHOUT mutating ``document`` or allocating any id: the same parse
2749
+ ``_fragment`` performs, read-only.
2750
+
2751
+ Bug 51567f3d: an insert whose fragment parses into several nodes (a multi-statement
2752
+ python fragment, a multi-paragraph text fragment) still gets exactly ONE 'insert' journal
2753
+ entry (per ``insert()``'s own docstring), anchored at the first of those nodes. Undoing it
2754
+ is a "delete" replay (``ai_editor.core.edit_session.edit_session_mutations
2755
+ ._apply_journal_like_op``) that must remove the WHOLE contiguous range the original insert
2756
+ created, not just that first node -- and the inverted entry's own payload always carries
2757
+ the original insert's exact 'after' source text (``journal_compose.invert_entry``'s insert
2758
+ branch: inverted 'before' = the original 'after'), so re-parsing that SAME text here
2759
+ recovers the exact node count the original insert produced.
2760
+
2761
+ ``context_kind`` (verifier finding D, S3 of wish 8564a2ba): the SAME hint the original
2762
+ ``insert()`` call used for this exact fragment. Some fragment shapes ONLY parse with the
2763
+ hint their original insert position supplied (a bare flow item/pair, which has no OTHER
2764
+ valid parse at all); omitting it here would make undo fail exactly where the original
2765
+ insert succeeded. This is NOT stored on the journal payload -- the ``JournalEntry``/anchor
2766
+ shape is UNCHANGED (still exactly the 4 payload keys / 2 anchor keys pinned by
2767
+ ``tests/core/test_journal_compose.py``'s "FINAL CONTRACT"). The caller instead DERIVES it
2768
+ at call time, the same way ``edit_session_mutations._apply_journal_like_op`` does: at the
2769
+ point this runs, the original insert has not been undone yet, so its node(s) are still live
2770
+ at the anchor position, and the FIRST one's own ``kind`` is exactly as valid a context_kind
2771
+ for re-parsing this fragment as the original hint was (both route ``parse_fragment`` to the
2772
+ same shape decision).
2773
+
2774
+ Cost: one fragment parse, same as ``insert()`` itself performs.
2775
+ """
2776
+ return len(_fragment(document, source, context_kind=context_kind))
2777
+
2778
+
2779
+ def _type_compatibility(
2780
+ document: TreeDocument,
2781
+ ) -> Optional[Callable[[Any, Optional[str], Any], bool]]:
2782
+ """The document's own format plugin's ``is_type_compatible``, if it declares one, else
2783
+ ``None`` (bug dbc47fcb).
2784
+
2785
+ ``insert``/``replace``/``set_body`` each call the shared core mutation path
2786
+ (``operations.insert``/``replace_range``, ``updates.set_body``) with an
2787
+ ``is_type_compatible`` callable, which ``validate_mutation`` (stage 3,
2788
+ ``core/validation.py``) uses to reject an incoming node a parent/position cannot legally
2789
+ host -- e.g. a ``plain_text:line`` (always a leaf) must never accept a child. Before this
2790
+ fix none of the three call sites ever passed one, so stage 3 was unconditionally skipped
2791
+ for every format, for every one of these three operations. This helper is the single
2792
+ wiring point: it is duck-typed and additive -- a plugin that declares no
2793
+ ``is_type_compatible`` method leaves the check skipped exactly as before (never a new
2794
+ rejection for a plugin that opts out), while a plugin that does declare one gets it
2795
+ enforced everywhere the core preflight already runs it.
2796
+ """
2797
+ plugin = _plugin(document.format_id)
2798
+ checker = getattr(plugin, "is_type_compatible", None)
2799
+ return checker if callable(checker) else None
2800
+
2801
+
2802
+ def _short_id_allocator(
2803
+ document: TreeDocument, roots: Sequence[LiveNode]
2804
+ ) -> Callable[[], int]:
2805
+ """The document's own monotonic allocator, injected into the core preflight ({p097}), as a
2806
+ zero-arg callable correlated to the REAL node it allocates for.
2807
+
2808
+ Every node reachable from ``roots`` came out of :func:`_fragment`, which unconditionally
2809
+ clears ``short_id`` to ``None`` on all of them, so the shared preflight (``validate_mutation``)
2810
+ calls the returned callable exactly once per fragment node -- in the same depth-first
2811
+ pre-order :func:`walk` produces here, root by root -- which is exactly how ``insert``,
2812
+ ``replace_range`` and ``set_body`` walk their own incoming roots internally. Zipping the two
2813
+ traversals by position is therefore enough to know which node each call is for, and this
2814
+ allocates DIRECTLY against that node's own ``node_id`` via ``short_id_map.allocate`` -- one
2815
+ real registration, at the one place the value is both minted and recorded.
2816
+
2817
+ This replaces a version that allocated against a throwaway, freshly generated UUID4 instead:
2818
+ that call still returned a valid monotonic integer, but registered it in ``short_id_map``
2819
+ under an identity nothing else ever looked up, leaving the real node's own ``node_id``
2820
+ unregistered. ``TreeDocument.index_subtree`` (the pointwise indexer every mutation commits
2821
+ through) would then find no existing entry for that real id and allocate a SECOND, different
2822
+ short_id for the same node -- the dual-bookkeeping defect this closure exists to close: with
2823
+ it, ``index_subtree`` always finds the value already registered and never allocates again.
2824
+ """
2825
+ pending = iter(n for root in roots for n in walk(root))
2826
+
2827
+ def _next() -> int:
2828
+ return document.short_id_map.allocate(next(pending).node_id)
2829
+
2830
+ return _next
2831
+
2832
+
2833
+ def _reconcile_cross_document_short_ids(
2834
+ target: TreeDocument, roots: Sequence[LiveNode]
2835
+ ) -> None:
2836
+ """The cross-document half of the move short_id contract ({p009}: "free short_ids kept,
2837
+ conflicting ones reassigned from the target's own allocator"), applied through
2838
+ ``target.short_id_map`` -- the single allocator -- BEFORE the pointwise commit's
2839
+ ``index_subtree`` pass runs over the same nodes.
2840
+
2841
+ A moved node still carries the short_id it had in the SOURCE document (``_move_mod.move``
2842
+ never clears it), and ``_move_mod._attach`` writes that value straight into
2843
+ ``target.short_id_index`` -- a raw dict write, never through ``target.short_id_map`` -- so a
2844
+ value that happens to collide with an unrelated node already live in ``target`` silently
2845
+ clobbers that node's row. This is the one place that knows the moved nodes came from another
2846
+ document (within-document move never reaches this function), so it is the only place that can
2847
+ correctly draw the "free vs conflicting" line: ``ShortIdMap.merge_insert`` cannot tell
2848
+ "free because foreign" from "free because released in THIS document" apart on its own, which
2849
+ is exactly why ``TreeDocument.index_subtree`` must not attempt this itself.
2850
+
2851
+ For every moved node still carrying a short_id, ``merge_insert`` is consulted once: a free
2852
+ candidate is kept verbatim (registered into ``target.short_id_map`` for the first time,
2853
+ matching what ``_attach`` already wrote into ``short_id_index``); a conflicting one is
2854
+ reassigned to a fresh value, the node's own ``.short_id`` is updated to match, and the
2855
+ ``short_id_index`` row ``_attach`` clobbered under the OLD value is restored to whichever node
2856
+ ``target.short_id_map`` says legitimately owns it now (or dropped, if no live node does).
2857
+ Once this returns, every moved node's real id is registered in ``target.short_id_map``, so the
2858
+ ``index_subtree`` call that follows finds an existing entry for each and allocates nothing.
2859
+ """
2860
+ moved_nodes = [n for root in roots for n in walk(root)]
2861
+ candidates = {n.node_id: n.short_id for n in moved_nodes if n.short_id is not None}
2862
+ if not candidates:
2863
+ return
2864
+ assigned = target.short_id_map.merge_insert(candidates)
2865
+ for n in moved_nodes:
2866
+ final = assigned.get(n.node_id)
2867
+ if final is None or final == n.short_id:
2868
+ continue
2869
+ old_value = n.short_id
2870
+ n.short_id = final
2871
+ true_owner = target.short_id_map.get_node_id(old_value)
2872
+ if true_owner is not None:
2873
+ target.short_id_index[old_value] = true_owner
2874
+ else:
2875
+ target.short_id_index.pop(old_value, None)
2876
+
2877
+
2878
+ def _adjust_after_insert(
2879
+ document: TreeDocument, parent: Optional[LiveNode], inserted: List[LiveNode]
2880
+ ) -> None:
2881
+ """Let the format repair a stored byte the splice put in the wrong place.
2882
+
2883
+ Declared and duck-typed, following ``fragment_container_kinds`` and ``native_reference``: a
2884
+ plugin opts in by publishing a callable ``adjust_after_insert(parent, inserted)``, and the
2885
+ ABSENCE of one is a statement, not a gap -- it says this format regenerates its punctuation
2886
+ from ``children`` when it renders, so no stored byte can be stranded by a splice. That is true
2887
+ of json, toml, yaml, python and bsl. It is NOT true of plain_text, which stores separator bytes
2888
+ verbatim so a four-newline gap renders back as four newlines; ``plugins/plain_text.py``
2889
+ documents the one placement an insert invalidates and how it is repaired.
2890
+
2891
+ The hook runs INSIDE ``insert``'s ``_operation`` block, before ``_committed``, so anything it
2892
+ changes is part of the same version bump and is covered by the same typed-error boundary as
2893
+ the splice itself. It adjusts fields on nodes already in the tree; it never adds, removes or
2894
+ reorders a node, and it returns nothing.
2895
+ """
2896
+ adjust = getattr(_plugin(document.format_id), "adjust_after_insert", None)
2897
+ if callable(adjust):
2898
+ adjust(parent, inserted)
2899
+
2900
+
2901
+ def _adjust_after_delete(
2902
+ document: TreeDocument,
2903
+ parent: Optional[LiveNode],
2904
+ deleted: List[LiveNode],
2905
+ *,
2906
+ children_before: List[LiveNode],
2907
+ ) -> Optional[str]:
2908
+ """Let the format repair a stored byte when a deletion changes the tree structure.
2909
+
2910
+ For plain_text, when the paragraph(s) deleted reached the document's original last child,
2911
+ the document's trailing_separator (the closing newline run) must leave with them instead of
2912
+ being stacked onto whatever paragraph is now last, which would render one extra byte.
2913
+
2914
+ ``children_before`` is ``parent.children`` exactly as it stood before this delete ran -- the
2915
+ plugin needs it to tell "the deleted range reached the original tail" from "it didn't"
2916
+ reliably by POSITION. A field-based signal (e.g. "the last deleted node's own separator was
2917
+ empty") is not reliable for this: an empty ``separator`` can legitimately belong to a
2918
+ paragraph that is not last, for instance right after an earlier insert placed it ahead of an
2919
+ existing sibling rather than at the document's end, so keying off it caused deleting THAT
2920
+ paragraph to wrongly steal trailing_separator's byte from the real last paragraph -- exactly
2921
+ the failure a repeated delete/reinsert cycle surfaces.
2922
+
2923
+ This is the mirror repair to _adjust_after_insert: insert appends paragraphs and moves the
2924
+ trailing run forward; delete removes paragraphs and must move the trailing run backward.
2925
+ The hook follows the same contract: duck-typed, called only when the format has declared
2926
+ the capability, and run inside the _operation block before _commit_mutation.
2927
+
2928
+ Returns the prior value of any trailing separator that was released, or None.
2929
+ """
2930
+ adjust = getattr(_plugin(document.format_id), "adjust_after_delete", None)
2931
+ if callable(adjust):
2932
+ return adjust(parent, deleted, children_before=children_before)
2933
+ return None
2934
+
2935
+
2936
+ def _adjust_replace_fragment(
2937
+ document: TreeDocument,
2938
+ deleted: List[LiveNode],
2939
+ incoming: List[LiveNode],
2940
+ *,
2941
+ fragment_carries_boundary: bool = False,
2942
+ ) -> None:
2943
+ """Let the format transplant a node's own POSITIONAL/SEPARATING trivia -- the layout that
2944
+ places it relative to its previous sibling, not its own content -- from the node ``replace``
2945
+ is about to remove onto the fragment about to take its place, when that fragment's own
2946
+ parsed source did not carry that separation itself (bug b4cc5134, item 1).
2947
+
2948
+ Declared and duck-typed like ``adjust_after_insert``/``adjust_after_delete``: a plugin opts
2949
+ in by publishing a callable ``adjust_replace_fragment(deleted, incoming)``, and the ABSENCE
2950
+ of one says this format has no such node-owned-vs-layout split to defend (json/toml/yaml
2951
+ keep positional trivia on a dedicated wrapper -- a ``json:Member``'s own ``leading`` -- that
2952
+ ``replace`` of a value node never touches in the first place; plain_text's separator lives on
2953
+ the parent, already covered by ``adjust_after_insert``/``adjust_after_delete``).
2954
+
2955
+ Unlike those two hooks, this one runs BEFORE the splice, on ``incoming`` -- fragment roots
2956
+ ``_ops.replace_range`` has not yet spliced into the document or registered -- specifically so
2957
+ a plugin MAY add nodes here (a new EmptyLine run, say): grafting them onto an unregistered
2958
+ fragment costs nothing extra, while ``adjust_after_insert``/``adjust_after_delete`` run
2959
+ against an ALREADY-spliced, already-registered tree where adding a node would need its own
2960
+ registration pass, which is why those two hooks are documented as never doing that.
2961
+ """
2962
+ adjust = getattr(_plugin(document.format_id), "adjust_replace_fragment", None)
2963
+ if callable(adjust):
2964
+ if fragment_carries_boundary and "fragment_carries_boundary" in inspect.signature(
2965
+ adjust
2966
+ ).parameters:
2967
+ adjust(deleted, incoming, fragment_carries_boundary=True)
2968
+ else:
2969
+ adjust(deleted, incoming)
2970
+
2971
+
2972
+ def _adjust_after_move(
2973
+ document: TreeDocument,
2974
+ source_parent: Optional[LiveNode],
2975
+ target_parent: Optional[LiveNode],
2976
+ moved: List[LiveNode],
2977
+ *,
2978
+ source_children_before: List[LiveNode],
2979
+ ) -> None:
2980
+ """Let the format repair separator ownership for a move in ONE pass.
2981
+
2982
+ A move is a detach immediately followed by an attach. Calling the generic
2983
+ ``adjust_after_delete``/``adjust_after_insert`` hooks independently for each half -- as this
2984
+ function used to -- lets the detach step's field writes race the attach step's reads of the
2985
+ very same fields (``trailing_separator``, a paragraph's ``separator``): whichever runs first
2986
+ can leave stale or double-counted bytes for the other to read. That race was the root cause
2987
+ of bug 7dcb35e4.
2988
+
2989
+ A plugin that needs move-specific handling instead publishes one function,
2990
+ ``adjust_after_move(source_parent, target_parent, moved, *, source_children_before)``, and
2991
+ gets called ONCE, with ``source_children_before`` -- the source parent's ``children`` exactly
2992
+ as they stood immediately before the move ran -- as the one piece of "before" state a hook
2993
+ cannot recover any other way (every node's OWN fields are untouched by the move itself; only
2994
+ ``children`` lists and ``parent`` back-links change). Absence of the hook falls back to the
2995
+ same two generic calls used for a plain delete and a plain insert, unchanged for every format
2996
+ that might one day rely on them -- today only plain_text needs either.
2997
+ """
2998
+ plugin = _plugin(document.format_id)
2999
+ adjust_move = getattr(plugin, "adjust_after_move", None)
3000
+ if callable(adjust_move):
3001
+ adjust_move(
3002
+ source_parent,
3003
+ target_parent,
3004
+ moved,
3005
+ source_children_before=source_children_before,
3006
+ )
3007
+ return
3008
+ _adjust_after_delete(
3009
+ document, source_parent, moved, children_before=source_children_before
3010
+ )
3011
+ _adjust_after_insert(document, target_parent, moved)
3012
+
3013
+
3014
+ # -- plain_text insert decomposition (owner ruling, TODO fb6b4587) ----------
3015
+ #
3016
+ # THE CONTRACT: any text inserted through ``insert()`` decomposes to paragraphs and lines --
3017
+ # always. A fragment with NO paragraph boundary (``plain_text``'s own rule, ``split_text_
3018
+ # paragraphs`` -- never re-implemented here) has its LINES join the CURRENT paragraph at the
3019
+ # insertion point, rather than landing as a second, nested paragraph node inside the first (the
3020
+ # old behaviour: it rendered byte-identically, since render walks structurally regardless of
3021
+ # nesting depth, but it broke the format's own "root -> paragraph -> line, always exactly two
3022
+ # levels" shape, and -- the real defect -- it silently DROPPED a nested paragraph's own separator
3023
+ # bytes, since only the top-level ``_iter_export_paragraphs`` walk ever reads a paragraph's
3024
+ # ``SEPARATOR_FIELD``). A fragment WITH a boundary forces the target paragraph to split in two
3025
+ # around the insertion point, with the fragment's own paragraph(s) landing between the halves --
3026
+ # unless the point sits exactly at the paragraph's own start or end, where nothing needs to
3027
+ # split at all: the paragraph keeps its whole, untouched identity and the fragment lands beside
3028
+ # it. Placement is derived purely from OWNER NODE + CHILD POSITION, never from a line number.
3029
+ #
3030
+ # Split identity rule: the FIRST half keeps the target paragraph's own node_id/short_id --
3031
+ # nothing about the paragraph a caller already holds a reference to invalidates just because a
3032
+ # split happened past its own last line. The SECOND half is a genuinely NEW node.
3033
+
3034
+
3035
+ def _paragraph_split_point(
3036
+ parent_node: Optional[LiveNode],
3037
+ sibling_node: Optional[LiveNode],
3038
+ position: str,
3039
+ index: Optional[int],
3040
+ ) -> Tuple[Optional[LiveNode], Optional[int]]:
3041
+ """Resolve ``insert()``'s own addressing ({p107}) to a plain_text split point, read-only.
3042
+
3043
+ Mirrors ``core.operations.insert``'s own address resolution (never mutates, never raises --
3044
+ an address this cannot make sense of is left for the real splice to accept or reject) far
3045
+ enough to answer one question: does this address land INSIDE an existing paragraph -- i.e.
3046
+ does the parent that would actually receive the spliced node turn out to be a
3047
+ ``plain_text:paragraph`` -- and if so, at which position among that paragraph's OWN line
3048
+ children (0 meaning "before every line it currently has", ``len(children)`` meaning "after
3049
+ all of them").
3050
+
3051
+ Returns ``(None, None)`` whenever the address does not resolve inside a paragraph at all --
3052
+ most commonly because it targets the ROOT (a whole paragraph landing beside another paragraph,
3053
+ which is not this contract's concern: nothing is being joined or split, a new paragraph is
3054
+ simply arriving beside existing ones, exactly as before this fix).
3055
+ """
3056
+ if position in ("before", "after"):
3057
+ if sibling_node is None:
3058
+ return None, None
3059
+ resolved_parent = parent_node if parent_node is not None else sibling_node.parent
3060
+ if resolved_parent is None or resolved_parent.kind != _PLAIN_TEXT_PARAGRAPH_KIND:
3061
+ return None, None
3062
+ siblings = list(resolved_parent.children)
3063
+ try:
3064
+ anchor = siblings.index(sibling_node)
3065
+ except ValueError:
3066
+ return None, None
3067
+ return resolved_parent, (anchor if position == "before" else anchor + 1)
3068
+ if position in ("first_child", "last_child", "child_index"):
3069
+ if parent_node is None or parent_node.kind != _PLAIN_TEXT_PARAGRAPH_KIND:
3070
+ return None, None
3071
+ siblings = list(parent_node.children)
3072
+ if position == "first_child":
3073
+ return parent_node, 0
3074
+ if position == "last_child":
3075
+ return parent_node, len(siblings)
3076
+ idx = 0 if index is None else max(0, min(index, len(siblings)))
3077
+ return parent_node, idx
3078
+ return None, None
3079
+
3080
+
3081
+ def _split_paragraph_node(
3082
+ document: TreeDocument,
3083
+ target_paragraph: LiveNode,
3084
+ split_idx: int,
3085
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]],
3086
+ ) -> LiveNode:
3087
+ """Split ``target_paragraph`` in two around ``split_idx`` (``0 < split_idx <
3088
+ len(target_paragraph.children)``, guaranteed by the caller -- both halves keep at least one
3089
+ line, so no empty paragraph is ever created).
3090
+
3091
+ The FIRST half keeps ``target_paragraph``'s own identity and every line before ``split_idx``;
3092
+ a brand-new paragraph node takes ``target_paragraph``'s OLD ``SEPARATOR_FIELD`` (the run that
3093
+ used to follow it) plus every line from ``split_idx`` on, and is spliced into ``target_
3094
+ paragraph``'s own parent (the root) immediately after it -- there is no gap between the two
3095
+ halves themselves, since nothing about the original text changed there, only which node each
3096
+ line belongs to.
3097
+
3098
+ Built from the SAME two validated primitives every other structural change in this module
3099
+ goes through -- ``core.operations.insert`` (to register and place the new second-half node)
3100
+ and ``core.move.move`` (to relocate the tail lines into it, the one operation that can
3101
+ reparent already-registered nodes without ``validate_mutation`` mistaking them for a node_id
3102
+ collision) -- called with ``lock_coordinator=None`` because ``insert()``'s own ``_operation``
3103
+ already holds this document's lock for the whole call; re-entering it here would deadlock the
3104
+ coordinator's own re-entrancy guard.
3105
+
3106
+ Deliberately does NOT call the generic ``_adjust_after_insert`` hook after placing
3107
+ ``new_paragraph``: that hook's job is to hand the document's ``trailing_separator`` from the
3108
+ paragraph that USED TO be last onto genuinely new content taking its place as the new last
3109
+ child, crediting the OLD last paragraph with the boundary bytes as its own new ``separator``
3110
+ -- correct when the new content is unrelated to it, wrong here, where ``new_paragraph`` is not
3111
+ unrelated content but the tail END of ``target_paragraph`` itself. If ``target_paragraph`` was
3112
+ the document's last paragraph, ``root``'s ``trailing_separator`` already describes exactly
3113
+ what follows ``new_paragraph``'s own last line now -- nothing needs to move at all, since
3114
+ ``new_paragraph`` inherits the "last paragraph" role with its own ``separator`` correctly
3115
+ empty by construction (A-018's invariant already holds, unchanged).
3116
+ """
3117
+ children = list(target_paragraph.children)
3118
+ tail = children[split_idx:]
3119
+ old_separator = target_paragraph.fields.get(_PLAIN_TEXT_SEPARATOR_FIELD, "")
3120
+ new_paragraph = LiveNode(
3121
+ kind=_PLAIN_TEXT_PARAGRAPH_KIND,
3122
+ fields={"line_count": len(tail), _PLAIN_TEXT_SEPARATOR_FIELD: old_separator},
3123
+ children=[],
3124
+ node_id=generate_node_id(),
3125
+ short_id=None,
3126
+ )
3127
+ target_paragraph.fields = {
3128
+ **target_paragraph.fields,
3129
+ _PLAIN_TEXT_SEPARATOR_FIELD: "",
3130
+ "line_count": split_idx,
3131
+ }
3132
+ _ops.insert(
3133
+ document,
3134
+ new_paragraph,
3135
+ position="after",
3136
+ sibling=target_paragraph,
3137
+ is_type_compatible=is_type_compatible,
3138
+ next_short_id=_short_id_allocator(document, [new_paragraph]),
3139
+ )
3140
+ _move_mod.move(
3141
+ document,
3142
+ tail,
3143
+ position="last_child",
3144
+ parent=new_paragraph,
3145
+ target_document=document,
3146
+ is_type_compatible=is_type_compatible,
3147
+ lock_coordinator=None,
3148
+ )
3149
+ # `_move_mod.move` does not maintain `document.parent_index` (only `facade.move`'s own
3150
+ # within-document branch does, one root at a time); re-walking the whole new paragraph here
3151
+ # -- itself plus the tail lines it just received -- fixes every entry this split touched in
3152
+ # one pass (idempotent for `nodes_by_id`/`short_id_index`, which the move already updated).
3153
+ document.index_subtree(new_paragraph)
3154
+ return new_paragraph
3155
+
3156
+
3157
+ def _fold_root_trailing_before_paragraph_tail_extension(
3158
+ document: TreeDocument, target_paragraph: LiveNode
3159
+ ) -> None:
3160
+ """Restore ``target_paragraph``'s own current last line's missing terminator BEFORE new
3161
+ content is spliced in right after it, when ``target_paragraph`` is root's actual last
3162
+ paragraph -- a no-op otherwise (most inserts: nothing to fold).
3163
+
3164
+ Every OTHER structural change in this file that can make a paragraph stop being root's
3165
+ last child works at PARAGRAPH granularity (``_claim_trailing_for_new_last``): the paragraph
3166
+ losing "last" status gets the run folded onto its own ``SEPARATOR_FIELD``, a field that
3167
+ exists precisely for this. The no-boundary join is different -- it extends an EXISTING
3168
+ paragraph's own line list rather than adding a new paragraph -- so there is no paragraph
3169
+ boundary being crossed and no ``SEPARATOR_FIELD`` write applies; the run has to fold into
3170
+ the LINE that is (for one more moment) the document's own physically last line instead.
3171
+ """
3172
+ parent = target_paragraph.parent
3173
+ if (
3174
+ parent is None
3175
+ or parent.kind != _PLAIN_TEXT_ROOT_KIND
3176
+ or not parent.children
3177
+ or parent.children[-1] is not target_paragraph
3178
+ ):
3179
+ return
3180
+ trailing = parent.fields.get(_PLAIN_TEXT_TRAILING_SEPARATOR_FIELD, "")
3181
+ if not trailing or not target_paragraph.children:
3182
+ return
3183
+ last_line = target_paragraph.children[-1]
3184
+ last_line.fields = {
3185
+ **last_line.fields,
3186
+ "text": last_line.fields.get("text", "") + trailing,
3187
+ }
3188
+ parent.fields = {**parent.fields, _PLAIN_TEXT_TRAILING_SEPARATOR_FIELD: ""}
3189
+
3190
+
3191
+ def _decompose_plain_text_insert(
3192
+ document: TreeDocument,
3193
+ parent_node: Optional[LiveNode],
3194
+ sibling_node: Optional[LiveNode],
3195
+ position: str,
3196
+ index: Optional[int],
3197
+ incoming: List[LiveNode],
3198
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]],
3199
+ ) -> Optional[Tuple[Optional[LiveNode], Optional[LiveNode], str, Optional[int], List[LiveNode], bool]]:
3200
+ """plain_text's own insert-decomposition contract (TODO fb6b4587); ``None`` means "this
3201
+ address is not inside a paragraph -- leave ``insert()``'s own splice loop untouched",
3202
+ covering both a document-level (root) insert and every other format.
3203
+
3204
+ On a real decomposition, returns the ``(parent_node, sibling_node, position, index,
3205
+ incoming, reverse)`` tuple ``insert()``'s own splice loop should use instead of the caller's
3206
+ original addressing -- ``reverse`` recomputed for whichever ``position`` this substitutes,
3207
+ exactly as ``insert()`` computes it for the caller's own original one.
3208
+ """
3209
+ target_paragraph, split_idx = _paragraph_split_point(
3210
+ parent_node, sibling_node, position, index
3211
+ )
3212
+ if target_paragraph is None or split_idx is None:
3213
+ return None
3214
+
3215
+ if len(incoming) == 1:
3216
+ # No paragraph boundary in the fragment: its own lines join the CURRENT paragraph,
3217
+ # spliced at exactly the same address the caller gave -- only WHAT splices there
3218
+ # (bare lines, not a second nested paragraph) changes.
3219
+ lines = list(incoming[0].children)
3220
+ for line in lines:
3221
+ line.parent = None
3222
+ if split_idx >= len(target_paragraph.children):
3223
+ # Landing at the paragraph's own TAIL: if this paragraph is also root's actual
3224
+ # last paragraph, its own current last line is carrying no terminator of its own
3225
+ # (the document's real trailing newline run lives on root.trailing_separator, per
3226
+ # the plugin's "document's two edge attributes" convention) -- new content is
3227
+ # about to follow it, so that run stops being trailing at all and must be folded
3228
+ # back into that line's own text FIRST, or it renders as a duplicated/misplaced
3229
+ # newline instead of the byte that used to sit between the old and new content.
3230
+ _fold_root_trailing_before_paragraph_tail_extension(document, target_paragraph)
3231
+ return parent_node, sibling_node, position, index, lines, position in (
3232
+ "first_child",
3233
+ "after",
3234
+ )
3235
+
3236
+ # A paragraph boundary is present: the target paragraph splits around `split_idx`, unless
3237
+ # the insertion point sits exactly at its start or end, where the paragraph needs no split
3238
+ # at all -- the fragment's own paragraph(s) simply land beside it, keeping its whole
3239
+ # identity untouched.
3240
+ children_count = len(target_paragraph.children)
3241
+ if split_idx <= 0:
3242
+ return None, target_paragraph, "before", None, incoming, False
3243
+ if split_idx >= children_count:
3244
+ return None, target_paragraph, "after", None, incoming, True
3245
+
3246
+ _split_paragraph_node(document, target_paragraph, split_idx, is_type_compatible)
3247
+ return None, target_paragraph, "after", None, incoming, True
3248
+
3249
+
3250
+ # -- document operations ({p037}) -------------------------------------------
3251
+
3252
+
3253
+ def query(
3254
+ document: TreeDocument, selector: str, *, include_source: bool = False
3255
+ ) -> List[QueryMatch]:
3256
+ """Run a selector over the loaded tree, never reparsing its source; a malformed selector raises
3257
+ ``InvalidSelector``."""
3258
+ with _typed(ErrorCode.INVALID_SELECTOR):
3259
+ if document.format_id == "xml":
3260
+ # XML has its own XPath-like evaluator (single "/", "[N]", "[@a]", "@a", "text()",
3261
+ # "comment()", "processing-instruction()", "prefix:name"); every other format keeps
3262
+ # the shared selector grammar unchanged. See ``tree_engine.query.xml_query``.
3263
+ from tree_engine.query.xml_query import query_xml
3264
+
3265
+ return query_xml(document, selector, include_source=include_source)
3266
+ return _query(
3267
+ document,
3268
+ _plugin(document.format_id),
3269
+ selector,
3270
+ include_source=include_source,
3271
+ )
3272
+
3273
+
3274
+ def legacy_kind(document: TreeDocument, node: Any, ancestors: Sequence[Any] = ()) -> str:
3275
+ """The legacy ``ai_editor.cst_query`` 8-word kind classification for
3276
+ ``node`` (S6a of wish 8564a2ba, verifier finding #7; additive -- see
3277
+ ``tree_engine.query.engine.legacy_kind``, which this thinly wraps,
3278
+ resolving ``document``'s own already-loaded format plugin via
3279
+ ``_plugin(document.format_id)`` so a caller migrating off
3280
+ ``ai_editor.cst_query`` (``cst_patcher.py``, ``python_handler.py``)
3281
+ never needs to import ``tree_engine.query.engine`` directly for this
3282
+ one, otherwise-internal helper."""
3283
+
3284
+ return _legacy_kind(_plugin(document.format_id), node, ancestors)
3285
+
3286
+
3287
+ def is_trivia_kind(document: TreeDocument, node: Any) -> bool:
3288
+ """True when ``node`` is a PURE WHITESPACE/format-only node for ``document``'s own format
3289
+ plugin (bug 98478e1f follow-up): zero-width or pure formatting, never independently
3290
+ renderable/spliceable on its own -- e.g. python's ``SimpleWhitespace``/
3291
+ ``ParenthesizedWhitespace``/``TrailingWhitespace``/``Newline``.
3292
+
3293
+ Delegates to the plugin's own ``is_trivia_kind`` hook when declared -- the SAME duck-typed
3294
+ dispatch convention :func:`legacy_kind` already uses for ``legacy_kind_for`` -- so a
3295
+ consumer asks the format plugin that actually owns this knowledge instead of keeping its
3296
+ own parallel kind list (which drifts: see bug 98478e1f's own follow-up, where an
3297
+ editor-layer list omitted ``TrailingWhitespace``). ``False`` for a plugin that declares no
3298
+ such hook (this notion is meaningful only for a format with real syntactic trivia)."""
3299
+ hook = getattr(_plugin(document.format_id), "is_trivia_kind", None)
3300
+ return bool(hook(node)) if callable(hook) else False
3301
+
3302
+
3303
+ def is_non_content_token(document: TreeDocument, node: Any) -> bool:
3304
+ """True when ``node`` is a PURE PUNCTUATION/CONNECTIVE token for ``document``'s own format
3305
+ plugin (bug 98478e1f follow-up): not whitespace, but still carrying no independently
3306
+ addressable content of its own -- a fixed textual form for the syntax position it
3307
+ occupies, with no legitimate alternative text a caller could substitute in its place --
3308
+ e.g. python's ``Comma``/``Dot``/``AssignEqual``/bracket and operator tokens.
3309
+
3310
+ Delegates to the plugin's own ``is_non_content_token`` hook when declared, the same
3311
+ duck-typed dispatch convention as :func:`is_trivia_kind`/:func:`legacy_kind`. ``False`` for
3312
+ a plugin that declares no such hook."""
3313
+ hook = getattr(_plugin(document.format_id), "is_non_content_token", None)
3314
+ return bool(hook(node)) if callable(hook) else False
3315
+
3316
+
3317
+ def drill_down(
3318
+ document: TreeDocument,
3319
+ address: Optional[Address] = None,
3320
+ *,
3321
+ depth: int = 1,
3322
+ expand_below_bytes: int = 8192,
3323
+ expected_version: Optional[int] = None,
3324
+ include_attributes: bool = True,
3325
+ include_source: str = SOURCE_PREVIEW,
3326
+ source_preview_bytes: int = 256,
3327
+ max_output_bytes: int = 65536,
3328
+ ) -> OutlineResponse:
3329
+ """Read-only compact outline around ``address`` (the document root by default).
3330
+
3331
+ ``expand_below_bytes`` (per {p067}) auto-expands any subtree whose
3332
+ aggregate byte size is under this threshold regardless of ``depth``; 0
3333
+ disables auto-expansion entirely. This parameter was previously computed
3334
+ by ``tree_engine.query.inspection.drill_down`` but not forwarded by this
3335
+ facade wrapper -- every caller outside this package was silently pinned
3336
+ to the inspection module's own default (8192) with no way to override
3337
+ it, which is the gap G-029/T-001/A-005 closes.
3338
+ """
3339
+ _check_version(document, expected_version)
3340
+ if address is not None:
3341
+ resolve_address(document, address)
3342
+ with _typed(ErrorCode.INVALID_SELECTOR):
3343
+ return _drill_down(
3344
+ document,
3345
+ address,
3346
+ depth=depth,
3347
+ expand_below_bytes=expand_below_bytes,
3348
+ include_attributes=include_attributes,
3349
+ include_source=include_source,
3350
+ source_preview_bytes=source_preview_bytes,
3351
+ max_output_bytes=max_output_bytes,
3352
+ )
3353
+
3354
+
3355
+ def insert(
3356
+ document: TreeDocument,
3357
+ source: Union[str, bytes],
3358
+ *,
3359
+ position: str,
3360
+ parent: Optional[Address] = None,
3361
+ sibling: Optional[Address] = None,
3362
+ index: Optional[int] = None,
3363
+ expected_version: Optional[int] = None,
3364
+ ) -> MutationResult:
3365
+ """Parse ``source`` and insert it at one {p107} positional address: ``first_child``,
3366
+ ``last_child``, ``child_index`` (with ``index``), ``before``, or ``after``.
3367
+
3368
+ A fragment that parses into SEVERAL nodes is inserted whole, in order, rather than having
3369
+ everything after the first silently dropped. The core splice takes one node at a time against a
3370
+ fixed anchor, so the order of the calls is what fixes the final order: ``first_child`` and
3371
+ ``after`` are spliced back to front, ``before``/``last_child``/``child_index`` front to back.
3372
+ The returned :class:`MutationResult` describes the FIRST fragment node -- its ``node_id``,
3373
+ ``short_id`` and final ``position`` -- and carries the ``inserted`` addresses and short_id
3374
+ ``remap`` of every one of them, in fragment order.
3375
+
3376
+ Once the splice is done the format gets to repair any byte of its own the new child order
3377
+ stranded, through ``_adjust_after_insert``; for plain_text that is the document's trailing
3378
+ newline run, which belongs to the paragraph a freshly appended one now follows.
3379
+
3380
+ plain_text ALSO decomposes the fragment itself before this splices anything, when the given
3381
+ address lands inside an existing paragraph (TODO fb6b4587, owner ruling): a fragment with no
3382
+ paragraph boundary has its lines join that paragraph directly, and a fragment WITH a
3383
+ boundary splits the paragraph in two around the address and lands its own paragraph(s)
3384
+ between the halves -- see ``_decompose_plain_text_insert``. Addressing a paragraph or the
3385
+ root directly (a whole new paragraph landing beside existing ones) is unaffected.
3386
+
3387
+ Appends exactly one mutation journal entry (op='insert') with the path to the first inserted
3388
+ node and the parent containing them.
3389
+
3390
+ Instrumentation: records PHASE_MUTATE with inserted node count per the module's mechanism
3391
+ (enable/disable via tree_engine.core.instrumentation)."""
3392
+ reverse = position in ("first_child", "after")
3393
+ with _operation(document, expected_version):
3394
+ parent_node = _nodes(document, parent)[0] if parent is not None else None
3395
+ sibling_node = _nodes(document, sibling)[0] if sibling is not None else None
3396
+ if document.format_id == "bsl" and (
3397
+ isinstance(source, _BslLines)
3398
+ or _bsl_in_scope(parent_node, sibling_node)
3399
+ or _bsl_source_has_block(document, source)
3400
+ ):
3401
+ raw = bytes(source) if isinstance(source, (bytes, bytearray)) else str(source).encode("utf-8")
3402
+ try:
3403
+ plan = _bsl_edit.plan_insert(bytes(document.source_bytes), raw, position, parent_node, sibling_node, index)
3404
+ except _bsl_edit.BlockEditError as exc:
3405
+ raise _bsl_plan_error(exc) from exc
3406
+ return _bsl_mutation_result(*_bsl_apply_plan(document, plan))
3407
+ insert_context_kind = _insert_context_kind(parent_node, sibling_node)
3408
+ incoming = _fragment(
3409
+ document, source,
3410
+ context_kind=insert_context_kind,
3411
+ parent_node=parent_node,
3412
+ )
3413
+ bsl_source_after: Optional[bytes] = None
3414
+ if document.format_id == "bsl":
3415
+ inserted_method = next((node for node in incoming if node.kind in _BSL_METHOD_KINDS), None)
3416
+ bsl_parent = sibling_node.parent if sibling_node is not None else parent_node
3417
+ if inserted_method is not None and bsl_parent is not None and bsl_parent.kind == "bsl:source_file":
3418
+ siblings_before = list(bsl_parent.children)
3419
+ if sibling_node is not None:
3420
+ sibling_index = siblings_before.index(sibling_node)
3421
+ insert_index = sibling_index + (1 if position == "after" else 0)
3422
+ elif position == "first_child":
3423
+ insert_index = 0
3424
+ elif position == "last_child":
3425
+ insert_index = len(siblings_before)
3426
+ elif position == "child_index" and index is not None:
3427
+ insert_index = index
3428
+ else:
3429
+ insert_index = -1
3430
+ if 0 <= insert_index <= len(siblings_before):
3431
+ raw_source = bytes(source) if isinstance(source, (bytes, bytearray)) else str(source).encode("utf-8")
3432
+ previous = siblings_before[insert_index - 1] if insert_index else None
3433
+ following = siblings_before[insert_index] if insert_index < len(siblings_before) else None
3434
+ if position == "after" and sibling_node is not None and sibling_node.buffer_range is not None:
3435
+ offset = sibling_node.buffer_range[1]
3436
+ prefix, suffix = _bsl_separator(bytes(document.source_bytes), sibling_node, following), b""
3437
+ elif following is not None and following.buffer_range is not None:
3438
+ offset = following.buffer_range[0]
3439
+ prefix, suffix = b"", _bsl_separator(bytes(document.source_bytes), previous, following)
3440
+ else:
3441
+ offset = len(document.source_bytes)
3442
+ prefix, suffix = b"\n" if previous is not None else b"", b""
3443
+ if raw_source.endswith((b" ", b"\t", b"\r", b"\n")):
3444
+ suffix = b""
3445
+ current_source = bytes(document.source_bytes)
3446
+ bsl_source_after = (
3447
+ current_source[:offset] + prefix + raw_source + suffix + current_source[offset:]
3448
+ )
3449
+ is_type_compatible = _type_compatibility(document)
3450
+ if document.format_id == PLAIN_TEXT_FORMAT_ID:
3451
+ decomposed = _decompose_plain_text_insert(
3452
+ document, parent_node, sibling_node, position, index, incoming,
3453
+ is_type_compatible,
3454
+ )
3455
+ if decomposed is not None:
3456
+ (
3457
+ parent_node,
3458
+ sibling_node,
3459
+ position,
3460
+ index,
3461
+ incoming,
3462
+ reverse,
3463
+ ) = decomposed
3464
+ results = []
3465
+ for offset, node in enumerate(reversed(incoming) if reverse else incoming):
3466
+ step = _ops.insert(
3467
+ document,
3468
+ node,
3469
+ position=position,
3470
+ parent=parent_node,
3471
+ sibling=sibling_node,
3472
+ index=index if index is None else index + offset,
3473
+ is_type_compatible=is_type_compatible,
3474
+ next_short_id=_short_id_allocator(document, [node]),
3475
+ )
3476
+ # Refresh buffer_range for every LATER sibling this fragment root landed ahead of
3477
+ # (bug ed579e33 / b4cc5134 defect #2): `_ops.insert` itself never touches
3478
+ # buffer_range (it has no reliable way to measure the byte delta on its own), so
3479
+ # `_measure_insert_delta` measures it -- node-locally, never a whole-document render
3480
+ # -- and `_ops.apply_insert_buffer_range` applies it. Best-effort and silent on any
3481
+ # failure: this is metadata refresh on top of an ALREADY-successful structural
3482
+ # splice, never allowed to turn that success into a raised exception.
3483
+ if node.parent is not None:
3484
+ _adjust_after_insert(document, node.parent, [node])
3485
+ try:
3486
+ # `_ops.apply_insert_buffer_range` deliberately leaves the inserted node's own
3487
+ # range `None`: from a byte count alone it cannot tell how the boundary bytes
3488
+ # divide between the new node and the neighbour it now abuts, and a two-sided
3489
+ # guess mis-attributes them. `_insert_anchor` does not guess -- it reads that
3490
+ # boundary off an ADJACENT neighbour whose own geometry is already measured --
3491
+ # so the node gets a real span, and everything after it the whole-document
3492
+ # shift it has always been owed (bugs b47c3558, 20fb996e).
3493
+ landed = node.parent
3494
+ anchor = _insert_anchor(document, node)
3495
+ if anchor is not None:
3496
+ ties = _boundary_ties(landed)
3497
+ landed_children = list(getattr(landed, "children", None) or ())
3498
+ landed_at = landed_children.index(node)
3499
+ _finish_splice(
3500
+ document, landed, anchor, None,
3501
+ _run_spans(document, [node]),
3502
+ landed_children[landed_at + 1:], ties,
3503
+ measured_delta=None,
3504
+ # Bug 86107a8f: lazy -- `_finish_splice` only calls this
3505
+ # when its own cheap mapped-delta path did not already
3506
+ # settle the delta. Passed eagerly (as a plain value),
3507
+ # this O(parent_node's subtree) render -- O(document)
3508
+ # for a top-level insert, whose parent IS the document
3509
+ # root -- ran on every single insert of a bulk batch
3510
+ # regardless of whether the anchor path above already
3511
+ # made it unnecessary, which is exactly the CPU-bound
3512
+ # per-op full-document re-render a ~2000-line bulk
3513
+ # insert measured at 15s+ (py-spy: this call ->
3514
+ # `_render_source_via_plugin` -> `to_frozen`).
3515
+ fallback_delta=lambda: _measure_insert_delta(
3516
+ document, landed, node
3517
+ ),
3518
+ )
3519
+ else:
3520
+ delta = _measure_insert_delta(document, landed, node)
3521
+ if delta is not None:
3522
+ _ops.apply_insert_buffer_range(landed, node, delta)
3523
+ except Exception:
3524
+ # bug 25c37cc1, second defect: this block is documented above as
3525
+ # best-effort metadata refresh on top of an ALREADY-successful structural
3526
+ # splice that must never escalate into a raised exception -- but the
3527
+ # narrower tuple this previously caught (TreeEngineException,
3528
+ # PluginContractError, PluginUnsupportedTranslation, NodeSchemaError) let a
3529
+ # bare, undeclared exception from the plugin's own renderer (e.g. a
3530
+ # malformed-node codegen ``TypeError``) escape uncaught. That aborted
3531
+ # `insert()` AFTER `_ops.insert` had already spliced `node` into `landed`'s
3532
+ # children and registered it in `document.nodes_by_id`/`short_id_index`,
3533
+ # but BEFORE `_commit_mutation` below could append the journal entry or bump
3534
+ # `document_version` -- leaving the live tree silently holding the new node
3535
+ # with no journal record of it, and the caller seeing a REJECTED operation
3536
+ # for what had, structurally, already succeeded. Catching every exception
3537
+ # here, exactly as this block's own docstring already promises, keeps a
3538
+ # buffer_range bookkeeping failure from ever undermining that invariant: the
3539
+ # splice this loop iteration performed either commits in full (structure +
3540
+ # journal + version), never partially.
3541
+ pass
3542
+ results.append(step)
3543
+ ordered = list(reversed(results)) if reverse else results
3544
+ result = _replace_dataclass(
3545
+ ordered[0],
3546
+ remap=tuple(entry for step in ordered for entry in step.remap),
3547
+ inserted=tuple(address for step in ordered for address in step.inserted),
3548
+ )
3549
+ # Compute size delta from source if available
3550
+ size_delta = len(source) if isinstance(source, (str, bytes)) else 0
3551
+ # Capture fragments: before=None (inserting), after=source (the inserted content)
3552
+ # Anchor is captured AFTER insertion (the node has just landed)
3553
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=len(incoming)):
3554
+ _commit_mutation(
3555
+ document,
3556
+ "insert",
3557
+ incoming[0],
3558
+ sync_parent=incoming[0].parent,
3559
+ invalidate_node=incoming[0].parent,
3560
+ inserted=incoming,
3561
+ size_delta=size_delta,
3562
+ before_fragment=None,
3563
+ after_fragment=source,
3564
+ )
3565
+ if bsl_source_after is not None:
3566
+ _bsl_refresh_from_source(document, bsl_source_after)
3567
+ return result
3568
+
3569
+
3570
+ def delete(
3571
+ document: TreeDocument, targets: Any, *, expected_version: Optional[int] = None
3572
+ ) -> MutationResult:
3573
+ """Delete a node, a contiguous sibling range, or a subtree ({p010}).
3574
+
3575
+ Appends exactly one mutation journal entry (op='delete') with the path to the first
3576
+ deleted node and the parent containing them.
3577
+
3578
+ Instrumentation: records PHASE_MUTATE with deleted node count per the module's mechanism
3579
+ (enable/disable via tree_engine.core.instrumentation)."""
3580
+ with _operation(document, expected_version):
3581
+ resolved = _nodes(document, targets)
3582
+ bsl_scope: Optional[List[LiveNode]] = None
3583
+ bsl_source_after: Optional[bytes] = None
3584
+ bsl_before_fragment: Optional[bytes] = None
3585
+ if document.format_id == "bsl" and _bsl_in_scope(*resolved):
3586
+ try:
3587
+ plan = _bsl_edit.plan_delete(bytes(document.source_bytes), resolved)
3588
+ except _bsl_edit.BlockEditError as exc:
3589
+ raise _bsl_plan_error(exc) from exc
3590
+ touched, position = _bsl_apply_plan(document, plan)
3591
+ return _ops.MutationResult(node_id=touched.parent.node_id if touched.parent else None,
3592
+ short_id=None, position=position)
3593
+ if document.format_id == "bsl":
3594
+ bsl_scope = _bsl_scope_for_resolved(resolved)
3595
+ if bsl_scope is not None:
3596
+ source_before = bytes(document.source_bytes)
3597
+ span = _bsl_scope_span(bsl_scope)
3598
+ if span is not None:
3599
+ start, _ = span
3600
+ end = _bsl_next_sibling_start(bsl_scope, source_before)
3601
+ bsl_before_fragment = source_before[start:end]
3602
+ bsl_source_after = source_before[:start] + source_before[end:]
3603
+ resolved = bsl_scope
3604
+ parent_node = resolved[0].parent
3605
+ # Capture before fragment (the deleted nodes' source) and anchor before core delete runs
3606
+ # (the node is still in place at this point). children_before is the same kind of
3607
+ # pre-mutation snapshot, for _adjust_after_delete's format-specific repair below.
3608
+ before_source = _extract_source_from_nodes(resolved, document)
3609
+ if bsl_before_fragment is not None:
3610
+ before_source = bsl_before_fragment
3611
+ anchor_at_capture = _get_child_position_anchor(parent_node, resolved[0])
3612
+ children_before = list(parent_node.children) if parent_node is not None else []
3613
+ # Measure the TRUE removed byte length from the deleted nodes' own already-captured
3614
+ # faithful text (bug 97329272) instead of letting `_ops.delete` fall back to its own
3615
+ # node-range-only guess, which silently excludes any separator byte the format attaches
3616
+ # to the boundary with the next sibling -- see `_measure_delete_delta`'s docstring.
3617
+ # The exact byte cost of this deletion is the parent's own render shrinking (bugs
3618
+ # b47c3558, 20fb996e) -- measured across the splice, and across the format's own
3619
+ # post-delete repair below, which can move further bytes of its own. `removed_length` is
3620
+ # the pre-existing approximate measurement, used only where no exact one is available
3621
+ # (a format that never populates `buffer_range`, for which the whole quantity is inert).
3622
+ anchor = _anchored_run(document, resolved)
3623
+ ties = _boundary_ties(parent_node) if anchor is not None else []
3624
+ fallback_length = _measure_delete_delta(before_source)
3625
+ result = _ops.delete(
3626
+ document,
3627
+ resolved,
3628
+ removed_length=0 if anchor is not None else fallback_length,
3629
+ )
3630
+ # Apply format-specific repair after delete: for plain_text, migrate trailing_separator
3631
+ # when the last paragraph(s) are removed (bug f8b37aac fix).
3632
+ root_trailing_before = _adjust_after_delete(
3633
+ document, parent_node, resolved, children_before=children_before
3634
+ )
3635
+ extra_payload = None
3636
+ if root_trailing_before is not None:
3637
+ extra_payload = {"root_trailing_separator_before": root_trailing_before}
3638
+ if anchor is not None:
3639
+ old_run, model = anchor
3640
+ position = result.position or 0
3641
+ siblings = list(getattr(parent_node, "children", None) or ())
3642
+ _finish_splice(
3643
+ document, parent_node, model, old_run, None,
3644
+ siblings[position:], ties,
3645
+ measured_delta=None,
3646
+ fallback_delta=None if fallback_length is None else -fallback_length,
3647
+ )
3648
+ _repair_boundaries(ties)
3649
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=len(resolved)):
3650
+ _commit_mutation(
3651
+ document,
3652
+ "delete",
3653
+ resolved[0],
3654
+ sync_parent=parent_node,
3655
+ invalidate_node=parent_node,
3656
+ deleted=resolved,
3657
+ before_fragment=before_source,
3658
+ after_fragment=None,
3659
+ anchor=anchor_at_capture,
3660
+ extra_payload=extra_payload,
3661
+ )
3662
+ if bsl_source_after is not None:
3663
+ _bsl_refresh_from_source(document, bsl_source_after)
3664
+ return result
3665
+
3666
+
3667
+ def _statement_escalated_replace_target(
3668
+ document: TreeDocument, node: LiveNode
3669
+ ) -> Optional[LiveNode]:
3670
+ """Bug f2991fc0 (nested-indentation extension, residue round K19b): when ``node`` is held
3671
+ as the WHOLE (sole) body of a ``SimpleStatementLine`` -- either directly (a bare
3672
+ ``BaseSmallStatement`` such as ``Return``/``Assign``/``Pass``/..., LibCST's own
3673
+ ``body: Sequence[BaseSmallStatement]`` shape) or one level down through an ``Expr`` wrapper
3674
+ (a bare expression-statement -- a docstring, most commonly: an ``Expr``'s sole ``value``,
3675
+ itself the statement's only body entry) -- return the enclosing ``SimpleStatementLine``
3676
+ instead, so a leaf-level node_ref (the "most specific node"
3677
+ ``universal_file_node_at_line``/``universal_file_search`` hand back -- a docstring's own
3678
+ inner ``SimpleString``, or a bare ``Return``/``Assign``/... living directly in its
3679
+ statement's ``body``) is replaced through the SAME statement-level path a caller addressing
3680
+ the enclosing ``SimpleStatementLine`` directly already gets (bugs b47c3558/20fb996e/
3681
+ 466c10c8), never a bare scalar-field/small-statement splice.
3682
+
3683
+ Root cause this works around: a bare-target splice's own post-splice geometry bookkeeping
3684
+ (``_anchored_run``/``_run_spans``/``_apply_spliced_geometry`` below) cannot measure such a
3685
+ node's span. For a leaf expression (no children of its own, e.g. a one-line docstring's
3686
+ ``SimpleString``): re-rendering just its own text and re-parsing it through the format's
3687
+ DOCUMENT-root parser wraps it in fresh statement scaffolding that no longer aligns 1:1 with
3688
+ the flat, unwrapped node the splice actually touched, so ``_run_spans`` returns ``None``. For
3689
+ a bare small statement (``Return``, ...): the SAME wrapping happens, and
3690
+ ``position_transfer.measure_run``'s one exception for a wrapped single node --
3691
+ ``_single_leaf_run``, "a single-line scalar leaf" -- explicitly declines whenever the node
3692
+ has children of its own (``any(_is_node(child) for child in node.children)``), which every
3693
+ non-trivial small statement does (its own ``value``/target/... field). Either way
3694
+ ``_apply_spliced_geometry`` declines the measurement (returns 0) -- silently leaving the new
3695
+ node's own ``buffer_range`` unset and every later sibling's stale. ``facade.dumps()`` is
3696
+ unaffected (it never reads ``buffer_range``), so the spliced BYTES are byte-exact even on the
3697
+ unpatched path -- only ``buffer_range``-driven readers (``universal_file_preview``,
3698
+ ``universal_file_node_at_line``, ``universal_file_search``'s line reporting -- confirmed:
3699
+ ``universal_file_search`` for a small statement whose ``buffer_range`` went ``None`` this way
3700
+ reports ``node_ref: None`` / "No engine node found for this match", exactly the K19b residue)
3701
+ see the corruption. Escalating to the enclosing statement sidesteps the whole measurement
3702
+ gap: a ``SimpleStatementLine`` run's own re-render/re-parse round-trips through the
3703
+ document-root parser with no shape change at all, so ``_run_spans`` already measures it
3704
+ correctly (proven by the pre-existing statement-level regression tests) -- and
3705
+ ``bug 622727bd``'s own splice-shape fix (``plugin._unwrap_small_statement``, which keeps the
3706
+ RESULT a bare small statement, never a wrapping ``SimpleStatementLine``) is untouched by this:
3707
+ escalating here only changes the ADDRESS ``replace()`` resolves and measures against, and
3708
+ ``context_kind`` becomes the statement's own kind either way, which is what already selects
3709
+ the statement-first fragment parser for this shape.
3710
+
3711
+ Returns ``None`` for every other shape -- a scalar field on ``Return.value``/``Assign.value``/
3712
+ ``BinaryOperation``/a sequence element/... (not the whole body, just one of its OWN fields) is
3713
+ untouched (see ``test_replace_scalar_expression_target_still_prefers_expression_first``), and
3714
+ a multi-statement line (``a = 1; b = 2``, ``body`` has more than one entry) is untouched too
3715
+ (ambiguous which one the caller meant to isolate) -- and for every format but python, where
3716
+ ``SimpleStatementLine``/``Expr`` are not even node kinds."""
3717
+ if document.format_id != "python":
3718
+ return None
3719
+ parent = getattr(node, "parent", None)
3720
+ if parent is None:
3721
+ return None
3722
+ parent_kind = str(getattr(parent, "kind", ""))
3723
+ if parent_kind == "python:SimpleStatementLine":
3724
+ statement_line, held = parent, node
3725
+ elif parent_kind == "python:Expr":
3726
+ parent_fields = getattr(parent, "fields", None)
3727
+ if not isinstance(parent_fields, dict) or parent_fields.get("value") is not node:
3728
+ return None
3729
+ grandparent = getattr(parent, "parent", None)
3730
+ if (
3731
+ grandparent is None
3732
+ or str(getattr(grandparent, "kind", "")) != "python:SimpleStatementLine"
3733
+ ):
3734
+ return None
3735
+ statement_line, held = grandparent, parent
3736
+ else:
3737
+ return None
3738
+ statement_fields = getattr(statement_line, "fields", None)
3739
+ body = statement_fields.get("body") if isinstance(statement_fields, dict) else None
3740
+ if not (isinstance(body, tuple) and len(body) == 1 and body[0] is held):
3741
+ return None
3742
+ return statement_line
3743
+
3744
+
3745
+ def _flatten_plain_text_replacement(
3746
+ resolved: Sequence[LiveNode], incoming: List[LiveNode]
3747
+ ) -> Tuple[List[LiveNode], Optional[Tuple[LiveNode, List[LiveNode], str]]]:
3748
+ """Owner ruling 2026-11-02 (decision D-AV, bug b548f445, B12): replacing plain_text LINES with a
3749
+ paragraph fragment splices that fragment's LINES in, never a paragraph, so no paragraph is ever
3750
+ nested in a paragraph and the tree keeps the shape of a fresh parse.
3751
+
3752
+ A one-paragraph fragment: its lines replace the targets; its separator run (the blank lines
3753
+ after its last line) stays attached to its last line, so the rendered bytes are exactly the
3754
+ fragment's. A fragment of several paragraphs: the first paragraph's lines replace the targets
3755
+ inside the paragraph that holds them and the rest is returned as ``(last_paragraph,
3756
+ middle_paragraphs, first_separator)`` for :func:`_split_paragraph_after_replace`, which splits
3757
+ that paragraph around the replacement. Any other combination is returned unchanged."""
3758
+ if (
3759
+ not incoming
3760
+ or any(node.kind != "plain_text:paragraph" or not node.children for node in incoming)
3761
+ or any(node.kind != "plain_text:line" for node in resolved)
3762
+ ):
3763
+ return incoming, None
3764
+ first = incoming[0]
3765
+ lines = list(first.children)
3766
+ for line in lines:
3767
+ line.parent = None
3768
+ if len(incoming) == 1:
3769
+ separator = first.fields.get("separator", "")
3770
+ if separator:
3771
+ last = lines[-1]
3772
+ last.fields = {**last.fields, "text": str(last.fields.get("text", "")) + separator}
3773
+ return lines, None
3774
+ holder = resolved[0].parent
3775
+ if holder is None or holder.kind != "plain_text:paragraph" or holder.parent is None:
3776
+ return incoming, None
3777
+ for node in incoming[1:]:
3778
+ node.parent = None
3779
+ return lines, (incoming[-1], list(incoming[1:-1]), str(first.fields.get("separator", "")))
3780
+
3781
+
3782
+ def _consume_closing_break(root: LiveNode, last_line: LiveNode) -> None:
3783
+ """The replaced last line stood for the document's closing line break too: when the fragment's
3784
+ own last line ends with a line break, that terminator takes its place, so the bytes are the
3785
+ original with the target replaced by the fragment text (decision D-AV)."""
3786
+ closing = root.fields.get("trailing_separator", "")
3787
+ text = str(last_line.fields.get("text", ""))
3788
+ if closing and text[-1:] in ("\n", "\r"):
3789
+ first_break = closing.splitlines(keepends=True)[0]
3790
+ root.fields = {**root.fields, "trailing_separator": closing[len(first_break):]}
3791
+
3792
+
3793
+ def _split_paragraph_after_replace(
3794
+ holder: LiveNode,
3795
+ inserted_count: int,
3796
+ position: int,
3797
+ split: Tuple[LiveNode, List[LiveNode], str],
3798
+ ) -> List[LiveNode]:
3799
+ """Split ``holder`` (the paragraph a multi-paragraph fragment replaced lines in) around the
3800
+ replacement: lines up to the end of the first fragment paragraph stay in ``holder`` (which keeps
3801
+ its identity and now ends with the first fragment paragraph's separator run), the middle
3802
+ fragment paragraphs follow it as siblings, and the last fragment paragraph's lines plus the
3803
+ lines that came after the targets form a new paragraph that inherits ``holder``'s original
3804
+ separator. Returns the new paragraph nodes (for the caller to index)."""
3805
+ last_paragraph, middle, first_separator = split
3806
+ root = holder.parent
3807
+ assert root is not None
3808
+ cut = position + inserted_count
3809
+ tail_lines = list(holder.children[cut:])
3810
+ original_separator = holder.fields.get("separator", "")
3811
+ holder.children = list(holder.children[:cut])
3812
+ holder.fields = {**holder.fields, "separator": first_separator, "line_count": len(holder.children)}
3813
+ tail = last_paragraph
3814
+ tail.children = list(last_paragraph.children) + tail_lines
3815
+ tail.fields = {**tail.fields, "separator": original_separator, "line_count": len(tail.children)}
3816
+ created = list(middle) + [tail]
3817
+ for node in created:
3818
+ relink(node, root)
3819
+ siblings = list(root.children)
3820
+ where = siblings.index(holder) + 1
3821
+ root.children = siblings[:where] + created + siblings[where:]
3822
+ closing = root.fields.get("trailing_separator", "")
3823
+ last_text = str(tail.children[-1].fields.get("text", "")) if tail.children else ""
3824
+ if where == len(siblings) and not tail_lines and closing and last_text[-1:] in ("\n", "\r"):
3825
+ # The replaced last line stood for the document's closing line break too: the fragment's
3826
+ # own final terminator takes its place, so the bytes are the original with the target
3827
+ # replaced by the fragment text (decision D-AV).
3828
+ first_break = closing.splitlines(keepends=True)[0]
3829
+ root.fields = {**root.fields, "trailing_separator": closing[len(first_break):]}
3830
+ return created
3831
+
3832
+
3833
+ def replace(
3834
+ document: TreeDocument,
3835
+ targets: Any,
3836
+ source: Union[str, bytes],
3837
+ *,
3838
+ expected_version: Optional[int] = None,
3839
+ fragment_carries_boundary: bool = False,
3840
+ ) -> MutationResult:
3841
+ """Atomically replace a contiguous sibling range with parsed ``source`` ({p108}): no intermediate
3842
+ range-missing state is ever observable.
3843
+
3844
+ Appends exactly one mutation journal entry (op='replace') with the path to the first
3845
+ replaced node and the parent containing them.
3846
+
3847
+ Instrumentation: records PHASE_MUTATE with inserted+deleted node count per the module's mechanism
3848
+ (enable/disable via tree_engine.core.instrumentation)."""
3849
+ with _operation(document, expected_version):
3850
+ resolved = _nodes(document, targets)
3851
+ if len(resolved) == 1:
3852
+ # bug f2991fc0 (nested-indentation extension, residue K19b): a leaf-level ref naming
3853
+ # a bare expression-statement's own expression (a docstring's inner SimpleString) OR
3854
+ # a bare small statement (Return/Assign/...) held directly in its SimpleStatementLine
3855
+ # is escalated to that enclosing SimpleStatementLine BEFORE anything below measures
3856
+ # or splices it -- see _statement_escalated_replace_target.
3857
+ escalated = _statement_escalated_replace_target(document, resolved[0])
3858
+ if escalated is not None:
3859
+ resolved = [escalated]
3860
+ bsl_scope: Optional[List[LiveNode]] = None
3861
+ bsl_source_after: Optional[bytes] = None
3862
+ bsl_old_short_id: Optional[int] = None
3863
+ if document.format_id == "bsl" and (
3864
+ isinstance(source, _BslLines) or _bsl_in_scope(*resolved) or _bsl_source_has_block(document, source)
3865
+ ):
3866
+ raw = bytes(source) if isinstance(source, (bytes, bytearray)) else str(source).encode("utf-8")
3867
+ try:
3868
+ plan = _bsl_edit.plan_replace(bytes(document.source_bytes), resolved, raw)
3869
+ except _bsl_edit.BlockEditError as exc:
3870
+ raise _bsl_plan_error(exc) from exc
3871
+ return _bsl_mutation_result(*_bsl_apply_plan(document, plan))
3872
+ if document.format_id == "bsl":
3873
+ bsl_scope = _bsl_scope_for_resolved(resolved)
3874
+ if bsl_scope is not None:
3875
+ source_before = bytes(document.source_bytes)
3876
+ span = _bsl_scope_span(bsl_scope)
3877
+ if span is not None:
3878
+ start, end = span
3879
+ replacement = (
3880
+ bytes(source)
3881
+ if isinstance(source, (bytes, bytearray))
3882
+ else str(source).encode("utf-8")
3883
+ )
3884
+ bsl_source_after = source_before[:start] + replacement + source_before[end:]
3885
+ bsl_method = _bsl_scope_method(bsl_scope)
3886
+ bsl_old_short_id = bsl_method.short_id if bsl_method is not None else None
3887
+ resolved = bsl_scope
3888
+ # A byte-for-byte BSL replacement is a successful no-op. Avoid a
3889
+ # fragment reparse here: tree-sitter fragment offsets start at zero
3890
+ # and cannot distinguish a leading BOM from source at the document
3891
+ # origin. Leaving the already-identical subtree in place preserves
3892
+ # the original BOM and all surrounding gap ownership.
3893
+ if document.format_id == "bsl" and bsl_scope is not None:
3894
+ existing = _bsl_scope_before(bsl_scope, bytes(document.source_bytes))
3895
+ expected = source if isinstance(source, bytes) else str(source).encode("utf-8")
3896
+ bsl_method = _bsl_scope_method(bsl_scope)
3897
+ if existing == expected and bsl_method is not None:
3898
+ return _ops.MutationResult(
3899
+ node_id=bsl_method.node_id,
3900
+ short_id=bsl_method.short_id,
3901
+ position=None,
3902
+ )
3903
+ # context_kind=resolved[0].kind (bug f2991fc0): the fragment must match the SHAPE of the
3904
+ # node it is replacing -- a bare expression fragment landing where a full statement/suite
3905
+ # entry is being swapped out renders with no indentation and no trailing separator of its
3906
+ # own, gluing onto whatever follows it (see plugins.python.plugin
3907
+ # ._context_prefers_statement). A no-op hint for every format but python.
3908
+ incoming = _fragment(document, source, context_kind=resolved[-1].kind)
3909
+ paragraph_split = None
3910
+ closes_document = False
3911
+ if document.format_id == PLAIN_TEXT_FORMAT_ID:
3912
+ incoming, paragraph_split = _flatten_plain_text_replacement(resolved, incoming)
3913
+ holder = resolved[-1].parent
3914
+ closes_document = (
3915
+ paragraph_split is None
3916
+ and bool(incoming)
3917
+ and incoming[0].kind == "plain_text:line"
3918
+ and holder is not None
3919
+ and holder.parent is not None
3920
+ and holder.children[-1] is resolved[-1]
3921
+ and holder.parent.children[-1] is holder
3922
+ )
3923
+ parent_node = resolved[0].parent
3924
+ # Capture before fragment (the replaced nodes' source) and anchor before core replace runs
3925
+ before_source = _extract_source_from_nodes(resolved, document)
3926
+ if bsl_scope is not None:
3927
+ bsl_before = _bsl_scope_before(bsl_scope, bytes(document.source_bytes))
3928
+ if bsl_before is not None:
3929
+ before_source = bsl_before
3930
+ closing_run = getattr(_plugin(document.format_id), "replace_closing_run", None)
3931
+ if callable(closing_run) and isinstance(before_source, str):
3932
+ # Unit C27: a format whose closing run lives outside the replaced nodes journals it
3933
+ # with the fragment, so an undo restores the document's tail byte for byte.
3934
+ before_source = before_source + closing_run(resolved)
3935
+ anchor_at_capture = _get_child_position_anchor(parent_node, resolved[0])
3936
+ # Let the format transplant the replaced node's own separating trivia onto the
3937
+ # incoming fragment when the fragment's own source did not carry it (bug b4cc5134,
3938
+ # item 1); must run before the splice below -- see _adjust_replace_fragment.
3939
+ _adjust_replace_fragment(
3940
+ document, resolved, incoming, fragment_carries_boundary=fragment_carries_boundary
3941
+ )
3942
+ # Measure, BEFORE the splice unregisters them, exactly where the nodes being replaced sit
3943
+ # and how their container indents them (bugs b47c3558, 20fb996e) -- the anchor the incoming
3944
+ # run's own geometry is laid out against below, and the parent's own rendered length, the
3945
+ # "before" half of the byte delta this splice applies. `None` for a format whose addressing
3946
+ # does not use `buffer_range` at all (json/yaml/toml/ini/plain_text, which never populate
3947
+ # it), and then the pre-existing approximate bookkeeping runs unchanged.
3948
+ anchor = _anchored_run(document, resolved)
3949
+ ties = _boundary_ties(parent_node) if anchor is not None else []
3950
+ # `net_delta` is the APPROXIMATE, isolated-render measurement (bug 97329272) -- correct
3951
+ # only where the container adds no indentation of its own. With an anchor in hand the
3952
+ # splice runs with no bookkeeping of its own and the exact delta is applied afterwards; it
3953
+ # is still computed, as the last-resort fallback for a run that cannot be measured at all.
3954
+ net_delta = _measure_replace_delta(document, incoming, before_source)
3955
+ result = _ops.replace_range(
3956
+ document,
3957
+ resolved,
3958
+ incoming,
3959
+ is_type_compatible=_type_compatibility(document),
3960
+ next_short_id=_short_id_allocator(document, incoming),
3961
+ net_delta=None if anchor is not None else net_delta,
3962
+ )
3963
+ if anchor is not None:
3964
+ old_run, model = anchor
3965
+ position = result.position or 0
3966
+ siblings = list(getattr(parent_node, "children", None) or ())
3967
+ _finish_splice(
3968
+ document, parent_node, model, old_run, _run_spans(document, incoming),
3969
+ siblings[position + len(incoming):], ties,
3970
+ measured_delta=None, fallback_delta=net_delta,
3971
+ )
3972
+ split_paragraphs: List[LiveNode] = []
3973
+ if paragraph_split is not None:
3974
+ split_paragraphs = _split_paragraph_after_replace(
3975
+ parent_node, len(incoming), result.position or 0, paragraph_split
3976
+ )
3977
+ if closes_document:
3978
+ _consume_closing_break(parent_node.parent, incoming[-1])
3979
+ size_delta = len(source) if isinstance(source, (str, bytes)) else 0
3980
+ affected = len(incoming) + len(resolved)
3981
+ bsl_method = _bsl_scope_method(bsl_scope) if bsl_scope is not None else None
3982
+ bsl_touched = next(
3983
+ (node for node in incoming if node.kind == (bsl_method.kind if bsl_method else "")),
3984
+ incoming[0] if incoming else None,
3985
+ )
3986
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=affected):
3987
+ _commit_mutation(
3988
+ document,
3989
+ "replace",
3990
+ bsl_touched,
3991
+ sync_parent=parent_node,
3992
+ invalidate_node=parent_node,
3993
+ inserted=list(incoming) + split_paragraphs,
3994
+ deleted=resolved,
3995
+ size_delta=size_delta,
3996
+ before_fragment=before_source,
3997
+ after_fragment=source,
3998
+ anchor=anchor_at_capture,
3999
+ )
4000
+ if bsl_source_after is not None:
4001
+ bsl_new_node_id = getattr(bsl_touched, "node_id", None)
4002
+ _bsl_refresh_from_source(document, bsl_source_after)
4003
+ _bsl_set_ref_alias(document, bsl_old_short_id, bsl_new_node_id)
4004
+ return result
4005
+
4006
+
4007
+ def move(
4008
+ document: TreeDocument,
4009
+ targets: Any,
4010
+ *,
4011
+ position: str,
4012
+ parent: Optional[Address] = None,
4013
+ sibling: Optional[Address] = None,
4014
+ index: Optional[int] = None,
4015
+ target_document: Optional[TreeDocument] = None,
4016
+ expected_version: Optional[int] = None,
4017
+ ) -> MoveResult:
4018
+ """Move a subtree or sibling range, within one document or across two: both locks are taken in
4019
+ deterministic document_id order by the shared coordinator, so a concurrent move can neither
4020
+ deadlock nor publish partly ({p035}).
4021
+
4022
+ A cross-parent move appends TWO mutation journal entries (op='move'), one for each parent
4023
+ affected: one for the source parent (recording the removal), one for the target parent
4024
+ (recording the addition). Within-document moves have the same parent for both entries.
4025
+
4026
+ Instrumentation: records PHASE_MUTATE with moved node count per the module's mechanism
4027
+ (enable/disable via tree_engine.core.instrumentation)."""
4028
+ _check_version(document, expected_version)
4029
+ target = target_document if target_document is not None else document
4030
+ _require_editable(document, target)
4031
+ resolved = _nodes(document, targets)
4032
+ if document.format_id == "bsl" and target is document:
4033
+ bsl_parent = _nodes(document, parent)[0] if parent is not None else None
4034
+ bsl_sibling = _nodes(document, sibling)[0] if sibling is not None else None
4035
+ # A top-level method moves as whole lines through the same plan as a block (bug 94822248): the generic
4036
+ # detach/attach left the buffer ranges of the siblings stale and stitched the bytes of the wrong spans.
4037
+ if _bsl_in_scope(*resolved, bsl_parent, bsl_sibling) or any(
4038
+ getattr(node, "kind", None) in _bsl_edit.METHOD_KINDS for node in (*resolved, bsl_sibling)
4039
+ ):
4040
+ with _operation(document, expected_version):
4041
+ try:
4042
+ plan = _bsl_edit.plan_move(
4043
+ bytes(document.source_bytes), resolved, position, bsl_parent, bsl_sibling, index
4044
+ )
4045
+ except _bsl_edit.BlockEditError as exc:
4046
+ raise _bsl_plan_error(exc) from exc
4047
+ if plan is None:
4048
+ siblings = list(getattr(resolved[0].parent, "children", None) or ())
4049
+ return MoveResult(
4050
+ node_id=resolved[0].node_id, short_id=resolved[0].short_id,
4051
+ position=siblings.index(resolved[0]),
4052
+ )
4053
+ touched, position_after = _bsl_apply_plan(document, plan)
4054
+ return MoveResult(node_id=touched.node_id, short_id=touched.short_id, position=position_after)
4055
+ if (
4056
+ document.format_id == "bsl"
4057
+ and target is document
4058
+ and len(resolved) == 1
4059
+ and sibling is not None
4060
+ and _nodes(document, sibling)[0] is resolved[0]
4061
+ ):
4062
+ siblings = list(getattr(resolved[0].parent, "children", None) or ())
4063
+ return MoveResult(
4064
+ node_id=resolved[0].node_id,
4065
+ short_id=resolved[0].short_id,
4066
+ position=siblings.index(resolved[0]),
4067
+ )
4068
+ source_parent = resolved[0].parent
4069
+ # Captured BEFORE _move_mod.move() runs: that call completes the full detach-and-reattach
4070
+ # internally, so resolved[0].parent is already the TARGET parent by the time the two
4071
+ # _commit_mutation calls below run. The removal entry's node_path and anchor must lead through the
4072
+ # SOURCE parent chain, which only this pre-move snapshot still has.
4073
+ source_path = _node_path_to_root(resolved[0])
4074
+ # Capture anchor BEFORE move (for the removal entry, node is still in source parent)
4075
+ anchor_before_move = _get_child_position_anchor(source_parent, resolved[0])
4076
+ # Capture fragment source BEFORE move (content unchanged by move, only position changes)
4077
+ fragment_source = _extract_source_from_nodes(resolved, document)
4078
+ # Snapshot of the source parent's children exactly as they stood before the move -- the one
4079
+ # piece of "before" state _adjust_after_move's hook cannot recover from the post-move tree.
4080
+ source_children_before = (
4081
+ list(source_parent.children) if source_parent is not None else []
4082
+ )
4083
+ parent_node = _nodes(target, parent)[0] if parent is not None else None
4084
+ sibling_node = _nodes(target, sibling)[0] if sibling is not None else None
4085
+ _touched_token = _TOUCHED.set([])
4086
+ with _typed(ErrorCode.INVALID_POSITION), _reset_touched(_touched_token):
4087
+ result = _move_mod.move(
4088
+ document,
4089
+ resolved,
4090
+ position=position,
4091
+ target_document=target,
4092
+ parent=parent_node,
4093
+ sibling=sibling_node,
4094
+ index=index,
4095
+ lock_coordinator=_LOCKS.acquire_locks,
4096
+ )
4097
+ # Apply format-specific separator-ownership repair for the whole move in one pass (bug
4098
+ # 7dcb35e4 fix); see _adjust_after_move.
4099
+ _adjust_after_move(
4100
+ document,
4101
+ source_parent,
4102
+ resolved[0].parent,
4103
+ resolved,
4104
+ source_children_before=source_children_before,
4105
+ )
4106
+ # Move yields TWO journal entries: one for source parent (removal), one for target parent (addition)
4107
+ # Both entries carry the same fragment (content unchanged, position changed)
4108
+ # Removal entry: anchor captured BEFORE move
4109
+ affected = len(resolved)
4110
+ # For within-document moves, skip deindexing (the structural move preserves short_id correctly).
4111
+ # For cross-document moves, must deindex from the source document.
4112
+ removal_deleted = None if target is document else resolved
4113
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=affected):
4114
+ _commit_mutation(
4115
+ document,
4116
+ "move",
4117
+ resolved[0],
4118
+ sync_parent=source_parent,
4119
+ invalidate_node=source_parent,
4120
+ deleted=removal_deleted,
4121
+ node_path_override=source_path,
4122
+ before_fragment=fragment_source,
4123
+ after_fragment=fragment_source,
4124
+ anchor=anchor_before_move,
4125
+ )
4126
+ if target is not document:
4127
+ _reconcile_cross_document_short_ids(target, resolved)
4128
+ # Addition entry: anchor computed AFTER move (node is now in target parent)
4129
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=affected):
4130
+ _commit_mutation(
4131
+ target,
4132
+ "move",
4133
+ resolved[0],
4134
+ sync_parent=resolved[0].parent,
4135
+ invalidate_node=resolved[0].parent,
4136
+ inserted=resolved,
4137
+ before_fragment=fragment_source,
4138
+ after_fragment=fragment_source,
4139
+ )
4140
+ else:
4141
+ # Within-document move: target parent is resolved[0].parent after the splice.
4142
+ # Pass inserted=None to avoid redundant bookkeeping (short_id churn)
4143
+ # that the structural relocation already handles correctly (bug 49c4276b).
4144
+ # Addition entry: anchor computed AFTER move
4145
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=affected):
4146
+ _commit_mutation(
4147
+ document,
4148
+ "move",
4149
+ resolved[0],
4150
+ sync_parent=resolved[0].parent,
4151
+ invalidate_node=resolved[0].parent,
4152
+ inserted=None,
4153
+ before_fragment=fragment_source,
4154
+ after_fragment=fragment_source,
4155
+ )
4156
+ # Refresh parent_index for each moved node after relocation
4157
+ for root in resolved:
4158
+ document.reparent(root)
4159
+ # _reconcile_cross_document_short_ids() above may have reassigned resolved[0].short_id
4160
+ # after `result` was already built inside _move_mod.move(). Re-read the live node so
4161
+ # MoveResult.short_id never disagrees with the node it names ({p097} single-allocator
4162
+ # fixed point).
4163
+ if result.short_id != resolved[0].short_id:
4164
+ result = _replace_dataclass(result, short_id=resolved[0].short_id)
4165
+ _refresh_ranges(document)
4166
+ if target is not document:
4167
+ _refresh_ranges(target)
4168
+ return result
4169
+
4170
+
4171
+ def copy_subtree(
4172
+ document: TreeDocument,
4173
+ address: Optional[Address] = None,
4174
+ *,
4175
+ expected_version: Optional[int] = None,
4176
+ preserve_ids: bool = False,
4177
+ ) -> CopiedDocument:
4178
+ """An independent, read-only copy of the subtree at ``address`` ({p072}), for
4179
+ :func:`apply_subtree`. ``preserve_ids`` keeps the original UUID4s ({p074}) instead of minting
4180
+ fresh ones ({p073})."""
4181
+ _check_version(document, expected_version)
4182
+ node_id = resolve_address(document, address) if address is not None else None
4183
+ with _typed(ErrorCode.NODE_NOT_FOUND):
4184
+ copy = _copy_mod.copy_subtree(document, node_id, expected_version, preserve_ids)
4185
+ relink(copy.root, None)
4186
+ return copy
4187
+
4188
+
4189
+ def apply_subtree(
4190
+ document: TreeDocument,
4191
+ copy: CopiedDocument,
4192
+ *,
4193
+ expected_version: Optional[int] = None,
4194
+ ) -> ApplySubtreeResult:
4195
+ """Return ``copy`` into ``document``, replacing the subtree it was taken from ({p076}).
4196
+
4197
+ Appends exactly one mutation journal entry (op='apply_subtree') with the path to the
4198
+ applied subtree root and its parent.
4199
+
4200
+ Instrumentation: records PHASE_MUTATE with inserted+deleted node count per the module's mechanism
4201
+ (enable/disable via tree_engine.core.instrumentation)."""
4202
+ with _operation(document, expected_version, ErrorCode.NODE_ID_CONFLICT):
4203
+ # Captured BEFORE the core call: _apply_mod.apply_subtree()'s internal _splice() pops
4204
+ # the replaced subtree's nodes out of nodes_by_id/short_id_index directly (never through
4205
+ # document.deindex_subtree), so this is the only chance to still resolve the OLD root and
4206
+ # pass it through as `deleted` below -- otherwise document.parent_index is the one map
4207
+ # nobody ever tells the old subtree is gone (nodes_by_id/short_id_index already agree
4208
+ # with the reindex oracle without it; parent_index does not).
4209
+ old_root_id = next(
4210
+ (
4211
+ old_id
4212
+ for old_id, new_id in copy.old_uuid_to_new_uuid.items()
4213
+ if new_id == copy.root.node_id
4214
+ ),
4215
+ None,
4216
+ )
4217
+ old_root = (
4218
+ document.nodes_by_id.get(old_root_id) if old_root_id is not None else None
4219
+ )
4220
+ # Capture before fragment (the old subtree that will be replaced)
4221
+ # and anchor BEFORE the apply (old root is still in place)
4222
+ old_root_parent = old_root.parent if old_root is not None else None
4223
+ anchor_before_apply = _get_child_position_anchor(old_root_parent, old_root)
4224
+
4225
+ # Collect all nodes that will genuinely be removed
4226
+ surviving_ids_before_apply = (
4227
+ {n.node_id for n in walk(copy.root)} if copy.root is not None else set()
4228
+ )
4229
+
4230
+ def _genuinely_removed_before(candidate: LiveNode) -> List[LiveNode]:
4231
+ if candidate.node_id in surviving_ids_before_apply:
4232
+ removed: List[LiveNode] = []
4233
+ for child in candidate.children:
4234
+ removed.extend(_genuinely_removed_before(child))
4235
+ return removed
4236
+ return [candidate]
4237
+
4238
+ removed_nodes_before = (
4239
+ _genuinely_removed_before(old_root) if old_root is not None else []
4240
+ )
4241
+ before_source = _extract_source_from_nodes(removed_nodes_before, document)
4242
+
4243
+ result = _apply_mod.apply_subtree(
4244
+ document, copy, expected_version=expected_version
4245
+ )
4246
+ relink(document.root, None)
4247
+ applied = document.nodes_by_id.get(result.node_id)
4248
+ # The applied subtree is the newly inserted one
4249
+ applied_parent = applied.parent if applied is not None else None
4250
+ # A `preserve_ids=True` apply ({p074}) can resurrect some or all of the old subtree's own
4251
+ # node_ids under the NEW nodes _splice() just spliced in (an unedited copy resurrects
4252
+ # every one of them). Deindexing old_root's stale subtree wholesale would then pop the
4253
+ # very entries index_subtree() above just wrote for those same ids. Walk down from
4254
+ # old_root only as far as ids that do NOT survive in the applied subtree, so `deleted`
4255
+ # names exactly the nodes genuinely gone -- never one a surviving id still needs.
4256
+ surviving_ids = (
4257
+ {n.node_id for n in walk(applied)} if applied is not None else set()
4258
+ )
4259
+
4260
+ def _genuinely_removed(candidate: LiveNode) -> List[LiveNode]:
4261
+ if candidate.node_id in surviving_ids:
4262
+ removed: List[LiveNode] = []
4263
+ for child in candidate.children:
4264
+ removed.extend(_genuinely_removed(child))
4265
+ return removed
4266
+ return [candidate]
4267
+
4268
+ removed_roots = _genuinely_removed(old_root) if old_root is not None else []
4269
+ # Capture after fragment (the applied subtree)
4270
+ after_source = _extract_source_from_nodes(
4271
+ [applied] if applied is not None else [], document
4272
+ )
4273
+ inserted_count = 1 if applied is not None else 0
4274
+ deleted_count = len(removed_roots) if removed_roots else 0
4275
+ affected = inserted_count + deleted_count
4276
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=affected):
4277
+ _commit_mutation(
4278
+ document,
4279
+ "apply_subtree",
4280
+ applied,
4281
+ sync_parent=applied_parent,
4282
+ invalidate_node=applied_parent,
4283
+ inserted=[applied] if applied is not None else None,
4284
+ deleted=removed_roots or None,
4285
+ before_fragment=before_source,
4286
+ after_fragment=after_source,
4287
+ anchor=anchor_before_apply,
4288
+ )
4289
+ return result
4290
+
4291
+
4292
+ def set_attribute(
4293
+ document: TreeDocument,
4294
+ address: Address,
4295
+ name: str,
4296
+ value: Any,
4297
+ *,
4298
+ expected_version: Optional[int] = None,
4299
+ ) -> MutationResult:
4300
+ """Set one primitive field on the addressed node ({p011}); admissibility is decided by the node
4301
+ itself and a rejection mutates nothing.
4302
+
4303
+ Appends exactly one mutation journal entry (op='set_attribute') with the path to the
4304
+ modified node and its parent.
4305
+
4306
+ Instrumentation: records PHASE_MUTATE with 1 affected node per the module's mechanism
4307
+ (enable/disable via tree_engine.core.instrumentation)."""
4308
+ with _operation(document, expected_version, ErrorCode.INVALID_PARENT_TYPE):
4309
+ node = _nodes(document, address)[0]
4310
+ if document.format_id == "bsl" and (_bsl_blocks.is_block(node) or _bsl_blocks.is_branch(node)):
4311
+ try:
4312
+ plan = _bsl_edit.plan_attribute(bytes(document.source_bytes), node, name, value)
4313
+ except _bsl_edit.BlockEditError as exc:
4314
+ raise _bsl_plan_error(exc) from exc
4315
+ return _bsl_mutation_result(*_bsl_apply_plan(document, plan))
4316
+ # Capture old attribute value for before fragment
4317
+ old_value = node.get_attribute(name)
4318
+ result = _updates.set_attribute(document, node, name, value)
4319
+ # Route through shared mutation commit path: invalidate only, no sync_fields
4320
+ # Use structured form for set_attribute: before/after are dicts with name and value
4321
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=1):
4322
+ _commit_mutation(
4323
+ document,
4324
+ "set_attribute",
4325
+ node,
4326
+ invalidate_node=node,
4327
+ before_fragment={"name": name, "value": old_value},
4328
+ after_fragment={"name": name, "value": value},
4329
+ )
4330
+ return result
4331
+
4332
+
4333
+ def _plugin_of(document: TreeDocument) -> Any:
4334
+ return _REGISTRY.get_format_plugin(document.format_id)
4335
+
4336
+
4337
+ def edit_attributes(
4338
+ document: TreeDocument,
4339
+ address: Address,
4340
+ attributes: Mapping[str, Any],
4341
+ *,
4342
+ expected_version: Optional[int] = None,
4343
+ ) -> None:
4344
+ """Change the named attributes of the addressed node (``None`` removes one).
4345
+
4346
+ A format whose attributes live inside the node's own text (xml: the start tag) declares
4347
+ ``plan_edit_attributes(node, attributes) -> {field: value}`` on its plugin and only those fields
4348
+ are set; every other format sets one field per attribute with :func:`set_attribute`. The editor
4349
+ holds no per-format branch for this (decision D-CB.2)."""
4350
+ node = document.nodes_by_id[resolve_address(document, address)]
4351
+ plan = getattr(_plugin_of(document), "plan_edit_attributes", None)
4352
+ if plan is None:
4353
+ for name, value in attributes.items():
4354
+ set_attribute(document, node.node_id, name, value, expected_version=expected_version)
4355
+ return
4356
+ with _typed(ErrorCode.INVALID_PARENT_TYPE):
4357
+ updates = plan(node, attributes)
4358
+ for name, value in updates.items():
4359
+ set_attribute(document, node.node_id, name, value, expected_version=expected_version)
4360
+
4361
+
4362
+ def edit_content(
4363
+ document: TreeDocument,
4364
+ address: Address,
4365
+ content: str,
4366
+ *,
4367
+ expected_version: Optional[int] = None,
4368
+ ) -> None:
4369
+ """Replace the content of the addressed node, keeping its kind: :func:`set_body` unless the
4370
+ format's plugin declares ``plan_edit_content(node, content) -> ("set_body"|"replace", text)``."""
4371
+ node = document.nodes_by_id[resolve_address(document, address)]
4372
+ plan = getattr(_plugin_of(document), "plan_edit_content", None)
4373
+ if plan is None:
4374
+ set_body(document, node.node_id, content, expected_version=expected_version)
4375
+ return
4376
+ with _typed(ErrorCode.INVALID_PARENT_TYPE):
4377
+ action, text = plan(node, content)
4378
+ (replace if action == "replace" else set_body)(
4379
+ document, node.node_id, text, expected_version=expected_version
4380
+ )
4381
+
4382
+
4383
+ def set_body(
4384
+ document: TreeDocument,
4385
+ address: Address,
4386
+ source: Union[str, bytes],
4387
+ *,
4388
+ expected_version: Optional[int] = None,
4389
+ ) -> MutationResult:
4390
+ """Replace the addressed node's children with ``source``, parsed ({p038}): every incoming root
4391
+ clears the shared preflight before any existing child is removed, so a rejection leaves the node
4392
+ untouched.
4393
+
4394
+ Appends exactly one mutation journal entry (op='set_body') with the path to the modified node
4395
+ and its parent.
4396
+
4397
+ Instrumentation: records PHASE_MUTATE with inserted+deleted children node count per the module's
4398
+ mechanism (enable/disable via tree_engine.core.instrumentation)."""
4399
+ with _operation(document, expected_version, ErrorCode.INVALID_PARENT_TYPE):
4400
+ node = _nodes(document, address)[0]
4401
+ old_children = list(node.children)
4402
+ # Capture before fragment: the addressed node's OWN cached source is the
4403
+ # PRIMARY capture, unconditionally -- whether the node is a leaf or a
4404
+ # container with children. A container's own cached 'raw'/'content' is
4405
+ # the faithful original source (e.g. a json:Array's "[1, 2, 3]",
4406
+ # separators and all); naive per-child "".join() concatenation cannot
4407
+ # reconstruct that (it loses the separators entirely, e.g. "123"
4408
+ # instead of "[1, 2, 3]", which reparses as a different value). Only
4409
+ # fall back to per-child extraction when the node itself has no cached
4410
+ # source.
4411
+ before_source: Optional[Union[str, bytes, Dict[str, Any]]] = (
4412
+ _render_source_for_node(node, document)
4413
+ )
4414
+ if before_source is None:
4415
+ # No cached source on the node itself; fall back to per-child
4416
+ # extraction. For multiple children without cached node source, use
4417
+ # structured form {'fragments': [...]}; with no cached source
4418
+ # anywhere, {'node_ids': [...], 'kinds': [...]} is the last resort.
4419
+ before_source = _extract_source_from_nodes(old_children, document)
4420
+ incoming = _fragment(document, source)
4421
+ outcome = _updates.set_body(
4422
+ document,
4423
+ node,
4424
+ incoming,
4425
+ admits_nested_structure=lambda _n: True,
4426
+ parse_fragment=lambda text, **_kw: _fragment(document, text)[0],
4427
+ source_format_id=document.format_id,
4428
+ is_type_compatible=_type_compatibility(document),
4429
+ next_short_id=_short_id_allocator(document, incoming),
4430
+ )
4431
+ size_delta = len(source) if isinstance(source, (str, bytes)) else 0
4432
+ affected = len(incoming) + len(old_children)
4433
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=affected):
4434
+ _commit_mutation(
4435
+ document,
4436
+ "set_body",
4437
+ node,
4438
+ sync_parent=node,
4439
+ invalidate_node=node,
4440
+ inserted=incoming,
4441
+ deleted=old_children,
4442
+ size_delta=size_delta,
4443
+ before_fragment=before_source,
4444
+ after_fragment=source,
4445
+ )
4446
+ return outcome.mutation
4447
+
4448
+
4449
+ def set_root_trailing_separator(
4450
+ document: TreeDocument,
4451
+ value: str,
4452
+ ) -> None:
4453
+ """Set the root node's trailing separator (for plain_text format only).
4454
+
4455
+ This is a low-level mutation without journal tracking, used during undo replay
4456
+ to restore the trailing newline on documents that lost it during delete-last-paragraph
4457
+ (bug 1f11a73b).
4458
+ """
4459
+ root = document.root
4460
+ if root is not None and document.format_id == "plain_text":
4461
+ root.fields = {**root.fields, _PLAIN_TEXT_TRAILING_SEPARATOR_FIELD: value}
4462
+ _range_refresh.refresh_ranges(document, [root], _plugin(document.format_id))
4463
+
4464
+
4465
+ def replace_node_id(
4466
+ document: TreeDocument,
4467
+ address: Address,
4468
+ new_node_id: UUID,
4469
+ *,
4470
+ expected_version: Optional[int] = None,
4471
+ record_journal: bool = True,
4472
+ ) -> AddressRemap:
4473
+ """Atomically rewrite the addressed node's UUID4, keeping its short_id ({p109}).
4474
+
4475
+ Appends exactly one mutation journal entry (op='replace_node_id') with the path to the
4476
+ modified node and its parent. Uses pointwise index update (reparent) only, not full reindex.
4477
+
4478
+ ``record_journal`` (default True) controls only whether that entry is appended.
4479
+ ``False`` is a narrow escape hatch for a caller correcting or restoring a node's identity
4480
+ as pure bookkeeping -- never as a new semantic edit a user could undo/redo on its own.
4481
+ A journaled ``replace_node_id`` becomes part of every LATER undo/redo window computed
4482
+ over the seq range it falls in (``entries_since``); a caller that calls this DURING its
4483
+ own undo/redo replay to restore a node's pre/post-edit identity would otherwise inject an
4484
+ entry into that same journal that a SUBSEQUENT window recomputation picks up and replays
4485
+ against a node that may no longer exist by then (unconditional-history-corruption footgun,
4486
+ not merely a leaked no-op). ``record_journal=False`` performs every other effect below
4487
+ identically -- index/short_id/parent_index rekeying, the version bump -- with no journal
4488
+ entry and therefore no inverse for undo/redo to ever see.
4489
+
4490
+ Instrumentation: records PHASE_MUTATE with 1 affected node per the module's mechanism
4491
+ (enable/disable via tree_engine.core.instrumentation)."""
4492
+ with _operation(document, expected_version, ErrorCode.NODE_ID_CONFLICT):
4493
+ old_node_id = resolve_address(document, address)
4494
+ node = document.nodes_by_id[old_node_id]
4495
+ remap = _updates.replace_node_id(document, old_node_id, new_node_id)
4496
+ document.short_id_map.rekey(old_node_id, new_node_id)
4497
+ # Update nodes_by_id with new node_id key
4498
+ document.nodes_by_id[new_node_id] = node
4499
+ document.nodes_by_id.pop(old_node_id, None)
4500
+ # Update parent_index with new node_id key
4501
+ parent_id = document.parent_index.pop(old_node_id, None)
4502
+ document.parent_index[new_node_id] = parent_id
4503
+ # The renamed node's own children still point at its OLD id in parent_index --
4504
+ # nodes_by_id/short_id_index/short_id_map and the LiveNode.parent back-links are already
4505
+ # correctly rekeyed above (and by _updates.replace_node_id), but parent_index is this
4506
+ # document's own separate pointwise map and nothing else rewrites its rows. Exactly the
4507
+ # renamed node's direct children are affected, so this stays pointwise, not a reindex.
4508
+ for child in node.children:
4509
+ document.parent_index[child.node_id] = new_node_id
4510
+ # Update short_id_index if node has a short_id
4511
+ if node.short_id is not None:
4512
+ document.short_id_index[node.short_id] = new_node_id
4513
+ # Route through shared mutation commit path: no sync/invalidate, pointwise updates only
4514
+ # Use structured form for replace_node_id: before/after are dicts with node_id
4515
+ with _instr.measure(_instr.PHASE_MUTATE, affected_nodes=1):
4516
+ _commit_mutation(
4517
+ document,
4518
+ "replace_node_id",
4519
+ node,
4520
+ before_fragment={"node_id": str(old_node_id)},
4521
+ after_fragment={"node_id": str(new_node_id)},
4522
+ record_journal=record_journal,
4523
+ )
4524
+ return remap