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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,825 @@
1
+ """Atomic core node operations: insert, delete, replace_range (concept C-006).
2
+
3
+ Runs on top of the shared preflight validator in the sibling
4
+ ``validation.py`` ({p009}): every operation that introduces new content
5
+ calls :func:`~tree_engine.core.validation.validate_mutation` first and only
6
+ touches the tree and its index maps -- ``document.nodes_by_id`` and, when
7
+ present, a ``document.short_id_index`` map of ``short_id -> node_id`` --
8
+ after validation succeeds, raising :class:`MutationError` on any failure
9
+ before writing anything, so no partial mutation is ever observable.
10
+
11
+ Duck-typed contract (mirrors ``validation.py``; no concrete tree/document
12
+ type is imported): ``document.nodes_by_id`` is a mutable ``node_id ->
13
+ node`` map; ``document.short_id_index`` is an optional mutable ``short_id
14
+ -> node_id`` map; ``document.document_id`` is read only to build a
15
+ :class:`~tree_engine.core.identity.NodeAddress`. A node exposes
16
+ ``node_id``, ``short_id``, a settable ``parent`` back-link, and a settable
17
+ ``children`` sequence (list or tuple, preserved either way).
18
+ ``buffer_range`` -- an optional ``(start, end)`` byte span -- is read and,
19
+ for ``delete``, updated when present; its absence is never a hard failure.
20
+ Every operation returns the single shared :class:`MutationResult`.
21
+
22
+ API choices made where {p010}/{p107}/{p108} under-specify the exact shape:
23
+ ``insert`` takes one ``incoming`` root and a ``parent`` and/or ``sibling``
24
+ reference -- each a short_id, a UUID4, or an already-resolved node --
25
+ normalized before use ({p107}). ``delete``/``replace_range`` take
26
+ ``targets``: a reference or a non-empty sequence naming an existing,
27
+ contiguous run of one parent's children, in order; one reference
28
+ removes/replaces that node with its whole subtree (inherent, since
29
+ descendants are only reachable through it), a multi-element sequence acts
30
+ on a contiguous sibling range ({p010}). ``replace_range``'s incoming side
31
+ is a non-empty sequence of new sibling roots, each preflighted with its
32
+ own ``validate_mutation`` call ({p108}'s "runs the same insertion
33
+ preflight"), plus a same-batch node_id-collision guard since
34
+ ``validate_mutation`` never sees two calls' roots together. The old range
35
+ is removed and the new one inserted through one combined ``children``
36
+ assignment -- no reader ever observes the range missing with nothing yet
37
+ in its place ({p108}'s "does not publish an intermediate deletion").
38
+
39
+ Out of scope, owned by sibling files: automatic reparse of edited text
40
+ (``reparse.py``); attribute/body/source-fragment/identifier updates
41
+ (``updates.py``).
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ from dataclasses import dataclass
47
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
48
+ from uuid import UUID
49
+
50
+ from tree_engine.core.identity import NodeAddress
51
+ from tree_engine.core.nodes import NodeSchemaError
52
+ from tree_engine.core.validation import (
53
+ ShortIdReassignment,
54
+ ValidationError,
55
+ validate_mutation,
56
+ )
57
+ from tree_engine.errors import ErrorCode
58
+
59
+ __all__ = [
60
+ "MutationError", "MutationResult", "insert", "delete", "replace_range",
61
+ "apply_insert_buffer_range", "apply_splice_delta",
62
+ ]
63
+
64
+ _BEFORE_AFTER = frozenset({"before", "after"})
65
+ _PARENT_POSITIONS = frozenset({"first_child", "last_child", "child_index"})
66
+
67
+
68
+ class MutationError(Exception):
69
+ """Raised before any write, carrying the never-empty ``errors`` list
70
+ from the shared preflight validator or this file's own reference-
71
+ resolution / contiguity pre-checks."""
72
+
73
+ def __init__(self, errors: Sequence[ValidationError]) -> None:
74
+ self.errors: List[ValidationError] = list(errors)
75
+ summary = "; ".join(f"{e.code.value}: {e.message}" for e in self.errors)
76
+ super().__init__(summary or "mutation rejected")
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class MutationResult:
81
+ """Shared result: affected root ``node_id``/``short_id`` (the inserted
82
+ node for ``insert``, the shared parent for ``delete``/``replace_range``),
83
+ final ``position``, the applied short_id ``remap``, and the touched
84
+ ``removed``/``inserted`` :class:`~tree_engine.core.identity.NodeAddress`
85
+ values."""
86
+
87
+ node_id: Optional[UUID]
88
+ short_id: Optional[Any]
89
+ position: Optional[int]
90
+ remap: Tuple[ShortIdReassignment, ...] = ()
91
+ removed: Tuple[NodeAddress, ...] = ()
92
+ inserted: Tuple[NodeAddress, ...] = ()
93
+
94
+ # -- internal helpers -------------------------------------------------------
95
+
96
+
97
+ def _parse_uuid(value: Any) -> Optional[UUID]:
98
+ if isinstance(value, UUID):
99
+ return value
100
+ try:
101
+ return UUID(str(value))
102
+ except (ValueError, AttributeError, TypeError):
103
+ return None
104
+
105
+
106
+ def _resolve(document: Any, ref: Any) -> Optional[Any]:
107
+ """Normalize ``ref`` (a node, a short_id, or a UUID4) to a node object.
108
+ An already-resolved node is accepted only if it is literally the object
109
+ stored under its own ``node_id`` in ``document.nodes_by_id`` (rejecting
110
+ look-alikes, e.g. a bare ``NodeAddress``). Otherwise ``ref`` is tried as
111
+ a UUID4, then as a short_id against ``short_id_index`` when present,
112
+ then via a linear short_id scan -- so a short_id resolves exactly as
113
+ reliably as a UUID4, per {p107}."""
114
+ if ref is None:
115
+ return None
116
+ nodes_by_id = getattr(document, "nodes_by_id", None) or {}
117
+ candidate_id = getattr(ref, "node_id", None)
118
+ if candidate_id is not None and nodes_by_id.get(candidate_id) is ref:
119
+ return ref
120
+ parsed = _parse_uuid(ref)
121
+ if parsed is not None and parsed in nodes_by_id:
122
+ return nodes_by_id[parsed]
123
+ short_index = getattr(document, "short_id_index", None)
124
+ if isinstance(short_index, dict) and ref in short_index:
125
+ return nodes_by_id.get(short_index[ref])
126
+ for node in nodes_by_id.values():
127
+ if getattr(node, "short_id", None) == ref:
128
+ return node
129
+ return None
130
+
131
+
132
+ def _children_list(node: Any) -> List[Any]:
133
+ return list(getattr(node, "children", None) or ())
134
+
135
+
136
+ def _set_children(node: Any, children: Sequence[Any]) -> None:
137
+ if isinstance(getattr(node, "children", None), tuple):
138
+ node.children = tuple(children)
139
+ else:
140
+ node.children = list(children)
141
+
142
+
143
+ def _owned_sequence_field(node: Any) -> Optional[str]:
144
+ """The name of the single field on ``node`` holding a non-empty tuple of node-shaped
145
+ children, or ``None`` when zero or more than one such field exists. Mirrors
146
+ ``core.live_tree.sync_fields``'s own detection exactly (a node-shaped item is one with a
147
+ ``kind`` attribute, matching this module's duck-typed, format-agnostic contract), so a
148
+ node this returns a name for is one ``sync_fields`` can mirror ``children`` back into
149
+ without raising ``NodeSchemaError``."""
150
+ fields = getattr(node, "fields", None)
151
+ if not isinstance(fields, dict):
152
+ return None
153
+ sequences = [
154
+ name for name, value in fields.items()
155
+ if isinstance(value, tuple) and value and all(hasattr(item, "kind") for item in value)
156
+ ]
157
+ if len(sequences) == 1:
158
+ return sequences[0]
159
+ if not sequences and isinstance(fields.get("body"), tuple):
160
+ # Mirrors the same by-name fallback in ``core.live_tree.sync_fields``
161
+ # (bug 62759f8a): a node whose OWN sequence field(s) are all
162
+ # CURRENTLY empty (e.g. a freshly-parsed empty module) must still be
163
+ # recognized as splice-able, or a caller addressing it (a class/
164
+ # function whose suite is empty) can never be routed to its real
165
+ # body at all.
166
+ return "body"
167
+ return None
168
+
169
+
170
+ def _sequence_splice_target(node: Any) -> Any:
171
+ """When exactly one of ``node``'s OWN fields holds a single nested node-shaped value that
172
+ itself owns a sequence field, that descendant; otherwise ``node`` itself when IT owns exactly
173
+ one child-sequence field ({p045}); otherwise ``node`` unchanged.
174
+
175
+ A Python ``ClassDef``/``FunctionDef`` never holds its statement body directly among its own
176
+ flat ``children``: the body lives one level down, inside the ``IndentedBlock`` suite attached
177
+ at ``fields["body"]`` (whose OWN ``fields["body"]`` is the real, splice-able statement
178
+ sequence). Addressing the class/function is how a caller names "this node's body" without
179
+ knowing the suite exists as a separate node at all, so a splice targeting such a parent is
180
+ routed one level down to the sequence-owning descendant instead of being rejected outright
181
+ (defect #4 of bug 554f6521).
182
+
183
+ The descendant is checked FIRST, ahead of ``node``'s own sequence field, deliberately: a
184
+ compound statement like ``ClassDef`` can incidentally OWN a non-empty sequence field of its
185
+ own that has nothing to do with its body -- ``leading_lines``, the blank-line/comment run
186
+ BEFORE ``class C:`` itself, is a real, non-empty tuple-of-node field on any class preceded by
187
+ so much as a module docstring and a blank line (the ordinary shape of a real python file) --
188
+ and checking ``node`` first would let that incidental field silently win the "exactly one
189
+ sequence field" contest purely because it happens to be non-empty right now, routing a
190
+ same-shaped insert into the class's own leading trivia instead of its body with no error at
191
+ all (caught empirically: this exact fixture is what exposed it). The class's real content is
192
+ ALWAYS the nested suite when one exists, never a sibling trivia field, so preferring the
193
+ descendant whenever it is uniquely identifiable removes the ambiguity instead of resolving it
194
+ by accident. Returns ``node`` unchanged when no such descendant exists AND ``node`` owns no
195
+ sequence field of its own either -- leaving today's clean ``NodeSchemaError`` refusal exactly
196
+ as before for every shape neither branch recognizes."""
197
+ fields = getattr(node, "fields", None)
198
+ if isinstance(fields, dict):
199
+ candidates = [
200
+ (name, value) for name, value in fields.items()
201
+ if hasattr(value, "kind") and _owned_sequence_field(value) is not None
202
+ ]
203
+ if len(candidates) == 1:
204
+ return candidates[0][1]
205
+ # Bug e486ea5d: if multiple candidates, prefer the one named "body"
206
+ if len(candidates) > 1:
207
+ body_candidates = [value for name, value in candidates if name == "body"]
208
+ if len(body_candidates) == 1:
209
+ return body_candidates[0]
210
+ # No unique descendant: fall back to node's own sequence field, if it has exactly one
211
+ # (unchanged from before), or leave it unrouted for validate_mutation/sync_fields to refuse.
212
+ return node
213
+
214
+
215
+ def _scalar_field_owner(parent_node: Any, node: Any) -> Optional[str]:
216
+ """The name of the field on ``parent_node`` whose value IS ``node`` itself (by identity,
217
+ not wrapped in a tuple), or ``None`` when no field holds it that way -- i.e. ``node`` sits
218
+ only among ``parent_node``'s flat ``children``, held by a SCALAR field such as
219
+ ``BinaryOperation.left``/``.right``, ``Return.value``, ``Attribute.value``, ``Call.func``.
220
+ A node found this way has no sibling contesting its field slot, so overwriting that one
221
+ field with a replacement is always unambiguous -- unlike the tuple-sequence case
222
+ ``sync_fields`` already handles, there is no "which position" question to answer."""
223
+ fields = getattr(parent_node, "fields", None)
224
+ if not isinstance(fields, dict):
225
+ return None
226
+ for name, value in fields.items():
227
+ if value is node:
228
+ return name
229
+ return None
230
+
231
+
232
+ def _address(document: Any, node: Any) -> NodeAddress:
233
+ return NodeAddress(document_id=getattr(document, "document_id", None), node_id=getattr(node, "node_id", None))
234
+
235
+
236
+ def _fragment_nodes(root: Any) -> List[Any]:
237
+ """Pre-order ``root`` and every descendant (mirrors validation.py)."""
238
+ ordered: List[Any] = []
239
+ stack = [root]
240
+ while stack:
241
+ node = stack.pop(0)
242
+ ordered.append(node)
243
+ stack = list(getattr(node, "children", None) or ()) + stack
244
+ return ordered
245
+
246
+
247
+ def _apply_short_id_plan(fragment_nodes: Sequence[Any], plan: Sequence[ShortIdReassignment]) -> None:
248
+ by_id = {getattr(n, "node_id", None): n for n in fragment_nodes}
249
+ for entry in plan:
250
+ node = by_id.get(entry.node_id)
251
+ if node is not None and hasattr(node, "short_id"):
252
+ node.short_id = entry.new_short_id
253
+
254
+
255
+ def _register_fragment(document: Any, fragment_nodes: Sequence[Any]) -> None:
256
+ nodes_by_id = getattr(document, "nodes_by_id", None)
257
+ if nodes_by_id is None:
258
+ nodes_by_id = {}
259
+ document.nodes_by_id = nodes_by_id
260
+ short_index = getattr(document, "short_id_index", None)
261
+ for node in fragment_nodes:
262
+ node_id = getattr(node, "node_id", None)
263
+ if node_id is not None:
264
+ nodes_by_id[node_id] = node
265
+ if isinstance(short_index, dict):
266
+ short_id = getattr(node, "short_id", None)
267
+ if short_id is not None:
268
+ short_index[short_id] = node_id
269
+
270
+
271
+ def _unregister_subtree(document: Any, root: Any) -> None:
272
+ nodes_by_id = getattr(document, "nodes_by_id", None) or {}
273
+ short_index = getattr(document, "short_id_index", None)
274
+ for node in _fragment_nodes(root):
275
+ nodes_by_id.pop(getattr(node, "node_id", None), None)
276
+ if isinstance(short_index, dict):
277
+ short_index.pop(getattr(node, "short_id", None), None)
278
+ if hasattr(root, "parent"):
279
+ root.parent = None
280
+
281
+
282
+ def _range_byte_length(nodes: Sequence[Any]) -> int:
283
+ ranges = [getattr(n, "buffer_range", None) for n in nodes]
284
+ if not ranges or any(r is None for r in ranges):
285
+ return 0
286
+ return ranges[-1][1] - ranges[0][0]
287
+
288
+
289
+ def _shift_subtree(node: Any, delta: int) -> None:
290
+ rng = getattr(node, "buffer_range", None)
291
+ if rng is not None and hasattr(node, "buffer_range"):
292
+ node.buffer_range = (rng[0] + delta, rng[1] + delta)
293
+ for child in _children_list(node):
294
+ _shift_subtree(child, delta)
295
+
296
+
297
+ def _extend_range(node: Any, delta: int) -> None:
298
+ """Grow (or, with a negative ``delta``, shrink) ``node``'s own ``buffer_range`` END, leaving
299
+ its start untouched -- what a container's range does when a splice happens INSIDE it.
300
+
301
+ Never past its own start: a container whose whole content a deletion removed can be asked to
302
+ shrink by more bytes than its own span covers (a span excludes the indentation and trailing
303
+ newline its content sits between, so the two quantities are not the same), and an inverted
304
+ range is a worse answer than an empty one."""
305
+ rng = getattr(node, "buffer_range", None)
306
+ if rng is not None and hasattr(node, "buffer_range"):
307
+ node.buffer_range = (rng[0], max(rng[0], rng[1] + delta))
308
+
309
+
310
+ def _subtree_min_start(node: Any) -> Optional[int]:
311
+ """The lowest ``buffer_range`` start anywhere in ``node``'s subtree -- the first byte the
312
+ document holds for it, LEADING TRIVIA INCLUDED. A format can attach a node's own leading blank
313
+ lines, comments or decorators as children whose spans sit BEFORE the node's own start (python
314
+ does exactly that), so the node's own start is not where its text begins."""
315
+ lowest: Optional[int] = None
316
+ rng = getattr(node, "buffer_range", None)
317
+ if rng is not None:
318
+ lowest = rng[0]
319
+ for child in _children_list(node):
320
+ candidate = _subtree_min_start(child)
321
+ if candidate is not None and (lowest is None or candidate < lowest):
322
+ lowest = candidate
323
+ return lowest
324
+
325
+
326
+ def _shift_positioned_after(node: Any, delta: int, threshold: int) -> None:
327
+ """Move ``node``'s subtree by ``delta`` if it is positioned AT OR AFTER ``threshold``.
328
+
329
+ POSITION decides, never sibling order: a node's place among ``children`` is the order its
330
+ format's own fields happen to be declared in, not the order its bytes appear in. A python
331
+ ``ClassDef`` keeps its leading blank lines in ``children`` AFTER its body, so "every sibling
332
+ following the edited one" sweeps up nodes that sit hundreds of bytes BEFORE the edit and shifts
333
+ them off their own text -- which is the shape of bug 20fb996e's damage, not its repair.
334
+
335
+ A node that already carries a range answers for its whole subtree: it either begins after the
336
+ splice, in which case all of it moves together, or it begins before, in which case nothing
337
+ under it lies after the splice either (a node that spanned the splice would be an ancestor of
338
+ it, and those are handled by the caller's own walk up the chain). Only a node with NO range of
339
+ its own -- a freshly spliced sibling, not yet measured -- is descended into, in case something
340
+ beneath it does carry one.
341
+ """
342
+ rng = getattr(node, "buffer_range", None)
343
+ if rng is not None:
344
+ if rng[0] >= threshold:
345
+ _shift_subtree(node, delta)
346
+ return
347
+ for child in _children_list(node):
348
+ _shift_positioned_after(child, delta, threshold)
349
+
350
+
351
+ def apply_splice_delta(container: Any, following: Sequence[Any], delta: int) -> None:
352
+ """The complete positional consequence of ONE splice, for the whole document (bug 20fb996e).
353
+
354
+ ``delta`` is the signed byte count the splice added inside ``container``. Everything the
355
+ document positions after the splice point moves by exactly that -- not merely the edited node's
356
+ own later siblings, which is all each of :func:`insert`, :func:`delete` and
357
+ :func:`replace_range` used to move. Shifting only those left a NESTED edit's every
358
+ ancestor-level later sibling (a top-level function after the class whose method was just
359
+ edited, and every node inside it) holding a range stale by the full delta, so the next line
360
+ lookup or search correlation resolved to the WRONG NODE and an edit addressed through it
361
+ overwrote content the caller never named.
362
+
363
+ ``following`` -- the splice's own later siblings under ``container``, the one thing only the
364
+ caller can identify -- moves whole. Its first byte is also where the splice ENDS, which is the
365
+ threshold everything else is judged against; when nothing follows, the splice ended at
366
+ ``container``'s own end and nothing beyond it exists to move. From there the walk goes up the
367
+ ancestor chain: each ancestor's own range END grows by ``delta`` (its start cannot move, the
368
+ splice happened inside it) and each of that ancestor's siblings moves if, and only if, its own
369
+ text begins at or after the threshold.
370
+
371
+ Cost is bounded by the nodes positioned after the splice point -- precisely the set whose
372
+ positions actually changed. No full-document walk, no re-index, no re-parse, no render.
373
+ """
374
+ if not delta:
375
+ return
376
+ threshold: Optional[int] = None
377
+ for later in following:
378
+ candidate = _subtree_min_start(later)
379
+ if candidate is not None and (threshold is None or candidate < threshold):
380
+ threshold = candidate
381
+ if threshold is None:
382
+ own = getattr(container, "buffer_range", None)
383
+ threshold = own[1] if own is not None else None
384
+ for later in following:
385
+ _shift_subtree(later, delta)
386
+ current = container
387
+ while current is not None:
388
+ _extend_range(current, delta)
389
+ parent = getattr(current, "parent", None)
390
+ if parent is None:
391
+ return
392
+ if threshold is not None:
393
+ for sibling in _children_list(parent):
394
+ if sibling is not current:
395
+ _shift_positioned_after(sibling, delta, threshold)
396
+ current = parent
397
+
398
+
399
+ def apply_insert_buffer_range(parent_node: Any, inserted_node: Any, inserted_length: int) -> bool:
400
+ """Post-splice ``buffer_range`` bookkeeping for a fresh :func:`insert` (bug ed579e33 /
401
+ b4cc5134 defect #2): a fragment fresh off a format's ``parse_fragment`` genuinely has no
402
+ ``buffer_range`` at all ("no absolute buffer to range over" -- see
403
+ ``plugins/python/import_map.py``), so left alone it stays ``None`` forever and every LATER
404
+ sibling under the same parent keeps its stale pre-insert range once this new content lands
405
+ before it -- exactly the metadata a following byte-range read (a preview, or any caller
406
+ slicing the document's source by a node's ``buffer_range``) then trusts and gets wrong.
407
+
408
+ Called AFTER :func:`insert` has already spliced ``inserted_node`` into ``parent_node``'s
409
+ children, with ``inserted_length`` the caller-MEASURED byte delta the document actually grew
410
+ by (``facade.insert`` measures it from two full renders straddling the splice). Shifts every
411
+ LATER sibling's whole subtree right by ``inserted_length`` via :func:`_shift_subtree`, and
412
+ extends ``parent_node``'s own range by the same amount -- and, through
413
+ :func:`apply_splice_delta`, moves everything after ``parent_node`` at every level above it
414
+ too, the exact mirror of what :func:`delete` does with a negative delta.
415
+
416
+ Deliberately leaves ``inserted_node``'s own ``buffer_range`` untouched (``None``, exactly as
417
+ ``parse_fragment`` produced it): a format's own trailing-newline/separator convention can
418
+ attach bytes to one of the fragment's TWO new neighbour boundaries -- how much of the total
419
+ delta the newly-adjacent PRECEDING sibling's own hidden trailing whitespace absorbs, versus
420
+ how much is ``inserted_node``'s own -- that neither this file nor its caller can tell apart
421
+ from the byte count alone (observed on a real Python module: the true span between two
422
+ consecutive top-level statements includes one byte belonging to neither's own advertised
423
+ ``buffer_range``, a hidden trailing newline any two-sided guess mis-attributes by exactly
424
+ one). Absent is a SAFE degradation here (nothing downstream can silently read the wrong
425
+ bytes for a range that is ``None``); a two-sided guess is not, so none is made.
426
+
427
+ A no-op (returns ``False``) when ``inserted_length`` is falsy or ``inserted_node`` is not
428
+ found among ``parent_node``'s current children; returns ``True`` when the later-sibling/
429
+ parent refresh ran (even when ``inserted_node`` landed last, with no later sibling to shift)."""
430
+ if not inserted_length:
431
+ return False
432
+ siblings = _children_list(parent_node)
433
+ try:
434
+ position = siblings.index(inserted_node)
435
+ except ValueError:
436
+ return False
437
+ apply_splice_delta(parent_node, siblings[position + 1:], inserted_length)
438
+ return True
439
+
440
+
441
+ def _resolve_contiguous_range(document: Any, targets: Any) -> Tuple[List[Any], Any, int, int]:
442
+ """Resolve ``targets`` to an ordered, contiguous sibling run, shared by
443
+ ``delete``/``replace_range``. Returns ``(resolved_nodes, parent_node,
444
+ start_index, end_index)``; raises :class:`MutationError` -- no mutation
445
+ performed -- when a reference does not resolve, the nodes do not share
446
+ one parent, or they are not contiguous, in order, among its children."""
447
+ refs = list(targets) if isinstance(targets, (list, tuple)) else [targets]
448
+ if not refs:
449
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="at least one target is required")])
450
+ resolved: List[Any] = []
451
+ for ref in refs:
452
+ node = _resolve(document, ref)
453
+ if node is None:
454
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"target could not be resolved: {ref!r}")])
455
+ resolved.append(node)
456
+ parent_node = getattr(resolved[0], "parent", None)
457
+ if parent_node is None:
458
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="target has no resolvable parent")])
459
+ for node in resolved[1:]:
460
+ if getattr(node, "parent", None) is not parent_node:
461
+ raise MutationError([ValidationError(code=ErrorCode.INVALID_POSITION, message="targets do not share the same parent")])
462
+ siblings = _children_list(parent_node)
463
+ try:
464
+ start = siblings.index(resolved[0])
465
+ except ValueError:
466
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="target is not among its parent's children")])
467
+ end = start + len(resolved)
468
+ if siblings[start:end] != resolved:
469
+ raise MutationError(
470
+ [ValidationError(code=ErrorCode.INVALID_POSITION, message="targets are not a contiguous sibling range in the given order")]
471
+ )
472
+ return resolved, parent_node, start, end
473
+
474
+
475
+ # bug 25c37cc1 (Tuple-container half): the field names LibCST's own node schema universally
476
+ # reserves for a node's OPTIONAL WRAPPING parentheses -- ``lpar: Sequence[LeftParen]``/
477
+ # ``rpar: Sequence[RightParen]``, present on 41 distinct LibCST classes at the time of writing
478
+ # (every parenthesizable expression, ``Tuple`` among them) via its shared base mixin. Unlike
479
+ # every OTHER sequence field on a node (``elements``, ``body``, ...), a non-empty ``lpar``/
480
+ # ``rpar`` never carries genuine child content a caller could mean to splice into -- it is
481
+ # always exactly the literal ``(``/``)`` byte(s) the source happened to wrap the whole node in.
482
+ # A bare/unparenthesized ``python:Tuple`` (``x, y``) already has ``lpar=()``/``rpar=()`` (empty,
483
+ # so never counted as a sequence field to begin with, by the plain non-emptiness check both
484
+ # ``_single_sequence_field`` and ``core.live_tree.sync_fields`` already apply); a
485
+ # PARENTHESIZED one (``(x, y)``, the ordinary way most callers write a tuple literal) has both
486
+ # non-empty, which -- without this exclusion -- makes ``elements``/``lpar``/``rpar`` look like
487
+ # THREE competing candidate sequence fields instead of the one real one, and the "exactly one
488
+ # sequence field" splice precondition (and its mirror-image update in ``sync_fields``) refuses
489
+ # every insert/delete/replace targeting that content, even though which field is the genuine
490
+ # content is completely unambiguous once ``lpar``/``rpar`` are recognized for what they are.
491
+ _PAREN_WRAPPER_FIELD_NAMES = frozenset({"lpar", "rpar"})
492
+
493
+
494
+ def _single_sequence_field(parent_node: Any) -> None:
495
+ """Validate that ``parent_node`` can hold its children in a sequence field.
496
+
497
+ This validation runs BEFORE any splice modifies ``parent.children``, ensuring that
498
+ if a splice succeeds structurally, ``sync_fields`` will not later raise
499
+ ``NodeSchemaError`` when trying to mirror the new children back into fields.
500
+
501
+ Replicates the core logic from sync_fields: identifies which sequence field (if any)
502
+ should hold the children, and raises the same NodeSchemaError when the structure
503
+ cannot support the children.
504
+
505
+ Uses duck typing to identify node-valued fields and sequence fields without importing
506
+ LiveNode."""
507
+
508
+ if parent_node is None:
509
+ return
510
+
511
+ # Handle nodes without a 'fields' attribute (e.g., test mocks)
512
+ if not hasattr(parent_node, 'fields'):
513
+ return
514
+
515
+ field_items = list(parent_node.fields.items())
516
+
517
+ # A sequence field is a non-empty tuple of items that all have a 'kind' attribute (nodes)
518
+ def is_node_sequence(value: Any) -> bool:
519
+ return bool(
520
+ isinstance(value, tuple)
521
+ and value
522
+ and all(hasattr(item, 'kind') for item in value)
523
+ )
524
+
525
+ # A node-valued field is either a scalar node or a sequence of nodes
526
+ def is_node_field(value: Any) -> bool:
527
+ return hasattr(value, 'kind') or is_node_sequence(value)
528
+
529
+ # bug 25c37cc1 (Tuple-container half): ``lpar``/``rpar`` (see
530
+ # ``_PAREN_WRAPPER_FIELD_NAMES``'s docstring at its definition in this module) are never
531
+ # real child content -- excluding them here is what lets a node like ``python:Tuple``
532
+ # (``fields`` = ``elements``/``lpar``/``rpar``) still resolve to its one genuine content
533
+ # sequence (``elements``) instead of being refused as ambiguous purely because its literal
534
+ # parentheses happen to populate two more incidental non-empty sequence fields.
535
+ sequences = [
536
+ name for name, value in field_items
537
+ if name not in _PAREN_WRAPPER_FIELD_NAMES and is_node_sequence(value)
538
+ ]
539
+
540
+ seq_name: Optional[str] = None
541
+ if len(sequences) == 1:
542
+ seq_name = sequences[0]
543
+ elif not sequences and isinstance(parent_node.fields.get("body"), tuple):
544
+ # Mirrors core.live_tree.sync_fields's own widened check EXACTLY (bug 62759f8a): a
545
+ # node whose "body" field is CURRENTLY an EMPTY tuple (a freshly-parsed empty module,
546
+ # or a suite whose sole statement was just deleted) must still be recognized as
547
+ # splice-able -- sync_fields itself accepts "body" here on plain tuple-ness alone, with
548
+ # no non-emptiness/all-node-kind requirement, so this precheck must be no stricter than
549
+ # that or it would refuse a splice sync_fields would later have accepted.
550
+ seq_name = "body"
551
+
552
+ if seq_name is not None:
553
+ # We have a clear sequence field to mirror into; this will work
554
+ return
555
+
556
+ # If we don't have a clear sequence field, check if there are any node-valued fields
557
+ # (scalar or sequence). If there are, the sync will attempt to verify that expected
558
+ # children match the current children, and that check will happen in sync_fields.
559
+ # If there are NO node-valued fields at all, it's a children-driven format and OK.
560
+ has_node_valued_fields = any(is_node_field(value) for value in parent_node.fields.values())
561
+
562
+ if not has_node_valued_fields:
563
+ # Children-driven format, no node-valued fields to mirror into
564
+ return
565
+
566
+ # There are node-valued fields but no sequence field (sequences is empty).
567
+ # If only scalar fields, sync_fields will fail because children can't fit.
568
+ # If sequences was empty but we fell through (no single sequence, no 'body'),
569
+ # and there are node-valued fields, it's unsafe to splice.
570
+ # Raise the same error as sync_fields would.
571
+ if not sequences:
572
+ # No sequence fields at all, but there are node-valued (scalar) fields
573
+ # Splicing multiple children is impossible
574
+ raise NodeSchemaError(
575
+ ErrorCode.INVALID_PARENT_TYPE,
576
+ f"node kind {parent_node.kind!r} does not hold its children in exactly one sequence "
577
+ "field, so a sequence edit cannot be expressed on it; splice into the "
578
+ "sequence-holding descendant instead",
579
+ )
580
+
581
+ # Otherwise, sequences is non-empty (multiple sequences).
582
+ # sync_fields will check if expected == children and raise if not.
583
+ # We can't determine the result here, so we let sync_fields handle it.
584
+ # The safety net in _commit_mutation will catch if it fails.
585
+
586
+ # -- public operations --------------------------------------------------
587
+
588
+
589
+ def insert(
590
+ document: Any, incoming: Any, *, position: str, parent: Any = None, sibling: Any = None,
591
+ index: Optional[int] = None,
592
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]] = None,
593
+ references: Optional[Iterable[Any]] = None, loaded_documents: Optional[Dict[Any, Any]] = None,
594
+ used_short_ids: Optional[Sequence[Any]] = None, next_short_id: Optional[Callable[[], Any]] = None,
595
+ ) -> MutationResult:
596
+ """Insert ``incoming`` at one {p107} positional address: ``first_child``,
597
+ ``last_child``, ``child_index`` (with ``index``), ``before``, or
598
+ ``after``. ``parent``/``sibling`` are each a short_id, a UUID4, or an
599
+ already-resolved node, normalized before use; ``before``/``after``
600
+ resolve their parent from the sibling when ``parent`` is not given.
601
+
602
+ Leaves ``incoming``'s own ``buffer_range`` exactly as ``parse_fragment`` produced it
603
+ (typically ``None`` -- "no absolute buffer to range over") and touches no sibling's range
604
+ either: this file never renders anything and so has no reliable way to measure how many
605
+ bytes ``incoming`` actually added (see :func:`apply_insert_buffer_range`'s docstring for why
606
+ an isolated render of ``incoming`` is not trustworthy for that). A caller that needs the
607
+ freshly-spliced tree's ``buffer_range`` bookkeeping refreshed calls
608
+ :func:`apply_insert_buffer_range` immediately after this returns, with a byte delta it
609
+ measured itself (bug ed579e33 / b4cc5134 defect #2; ``facade.insert`` does exactly this)."""
610
+ parent_node = _resolve(document, parent) if parent is not None else None
611
+ sibling_node = _resolve(document, sibling) if sibling is not None else None
612
+ if position in _BEFORE_AFTER:
613
+ if sibling_node is None:
614
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"sibling could not be resolved: {sibling!r}")])
615
+ if parent_node is None:
616
+ parent_node = getattr(sibling_node, "parent", None)
617
+ if parent_node is None:
618
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="sibling has no resolvable parent")])
619
+ siblings = _children_list(parent_node)
620
+ try:
621
+ anchor = siblings.index(sibling_node)
622
+ except ValueError:
623
+ raise MutationError([ValidationError(code=ErrorCode.INVALID_POSITION, message="sibling is not a child of its parent")])
624
+ splice_index = anchor if position == "before" else anchor + 1
625
+ elif position in _PARENT_POSITIONS:
626
+ if parent_node is None:
627
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"parent could not be resolved: {parent!r}")])
628
+ # A caller names the ADDRESSABLE node ("this class", "this function"), not the
629
+ # internal suite node holding its real statement sequence one level down; route the
630
+ # splice to that sequence-owning descendant when the addressed node has none of its
631
+ # own (defect #4 of bug 554f6521) -- see _sequence_splice_target.
632
+ parent_node = _sequence_splice_target(parent_node)
633
+ siblings = _children_list(parent_node)
634
+ if position == "first_child":
635
+ splice_index = 0
636
+ elif position == "last_child":
637
+ splice_index = len(siblings)
638
+ else:
639
+ splice_index = 0 if index is None else max(0, min(index, len(siblings)))
640
+ else:
641
+ raise MutationError([ValidationError(code=ErrorCode.INVALID_POSITION, message=f"unrecognized position: {position!r}")])
642
+
643
+ result = validate_mutation(
644
+ document, incoming, parent=parent_node, position=position, index=index,
645
+ is_type_compatible=is_type_compatible, references=references,
646
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids, next_short_id=next_short_id,
647
+ )
648
+ if not result.success:
649
+ raise MutationError(result.errors)
650
+ # Validate the parent can hold its children in a sequence field BEFORE splicing
651
+ _single_sequence_field(parent_node)
652
+ fragment_nodes = _fragment_nodes(incoming)
653
+ _apply_short_id_plan(fragment_nodes, result.short_id_plan)
654
+ siblings = _children_list(parent_node)
655
+ siblings.insert(splice_index, incoming)
656
+ _set_children(parent_node, siblings)
657
+ if hasattr(incoming, "parent"):
658
+ incoming.parent = parent_node
659
+ _register_fragment(document, fragment_nodes)
660
+ return MutationResult(
661
+ node_id=getattr(incoming, "node_id", None),
662
+ short_id=getattr(incoming, "short_id", None),
663
+ position=splice_index,
664
+ remap=tuple(result.short_id_plan),
665
+ inserted=(_address(document, incoming),),
666
+ )
667
+
668
+
669
+ def delete(
670
+ document: Any, targets: Any, *, removed_length: Optional[int] = None
671
+ ) -> MutationResult:
672
+ """Delete a node, a contiguous sibling range, or a subtree ({p010}).
673
+ ``targets`` is a reference (short_id, UUID4, or node) or a non-empty
674
+ sequence naming an existing contiguous run of one parent's children, in
675
+ order; each removed node's whole subtree is purged from
676
+ ``nodes_by_id``/``short_id_index`` with it. Parent links, sibling
677
+ order, and -- when every touched node exposes ``buffer_range`` -- text
678
+ ranges (parent shrinks, later siblings shift left) are updated only
679
+ after every target resolves and the range is confirmed contiguous.
680
+
681
+ ``removed_length`` is an optional caller-MEASURED override for the number of bytes this
682
+ deletion actually removes from ``parent_node``'s rendered text. Left ``None`` (the default,
683
+ unchanged for every caller that has no renderer available -- e.g. ``core.transactions``/
684
+ ``core.updates`` calling this module directly), it falls back to the internal
685
+ :func:`_range_byte_length` guess: ``resolved[-1].buffer_range[1] - resolved[0].buffer_range[0]``,
686
+ i.e. purely the SUM of the targets' own spans. That guess silently excludes any
687
+ separator/blank-line byte a format attaches to the BOUNDARY between the removed run and its
688
+ next sibling rather than to either node's own ``buffer_range`` (bug 97329272) -- e.g. the
689
+ single ``\\n`` separating two top-level python statements belongs to neither statement's own
690
+ span. Undercounting the shift by that boundary width leaves every LATER sibling's
691
+ ``buffer_range`` permanently off by exactly that many bytes, which is exactly what a preview
692
+ slicing ``source_text[start:end]`` against a too-high ``start`` then drops: the node's own
693
+ leading character(s) (``'from ...'`` -> ``'rom ...'``, ``'import ...'`` -> ``'mport ...'``,
694
+ ``'def ...'`` -> ``'ef ...'``). ``facade.delete`` measures the TRUE value via a real
695
+ before/after render diff (see ``facade._measure_delete_delta``) and passes it here instead of
696
+ letting this guess run."""
697
+ resolved, parent_node, start, end = _resolve_contiguous_range(document, targets)
698
+ # Validate the parent can still hold whatever remains in a sequence field BEFORE
699
+ # splicing (bug 17f05476 residue): unlike `replace_range`, `delete` never rewrites a
700
+ # scalar field directly (there is no replacement node to mirror into it), so a target
701
+ # held only in a scalar field (e.g. `Return.value`) can never be deleted without leaving
702
+ # that field stale -- refuse it here, before `children`/`nodes_by_id` are touched, the
703
+ # same way `insert` already does.
704
+ _single_sequence_field(parent_node)
705
+ if removed_length is None:
706
+ removed_length = _range_byte_length(resolved)
707
+ removed_addresses = tuple(_address(document, node) for node in resolved)
708
+ siblings = _children_list(parent_node)
709
+ remaining = siblings[:start] + siblings[end:]
710
+ _set_children(parent_node, remaining)
711
+ if removed_length:
712
+ apply_splice_delta(parent_node, remaining[start:], -removed_length)
713
+ for node in resolved:
714
+ _unregister_subtree(document, node)
715
+ return MutationResult(
716
+ node_id=getattr(parent_node, "node_id", None),
717
+ short_id=getattr(parent_node, "short_id", None),
718
+ position=start,
719
+ removed=removed_addresses,
720
+ )
721
+
722
+
723
+ def replace_range(
724
+ document: Any, targets: Any, incoming: Sequence[Any], *,
725
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]] = None,
726
+ references: Optional[Iterable[Any]] = None, loaded_documents: Optional[Dict[Any, Any]] = None,
727
+ used_short_ids: Optional[Sequence[Any]] = None, next_short_id: Optional[Callable[[], Any]] = None,
728
+ net_delta: Optional[int] = None,
729
+ ) -> MutationResult:
730
+ """Atomically replace a contiguous sibling range ({p108}). ``targets``
731
+ names the existing contiguous range to remove (see :func:`delete`).
732
+ ``incoming`` is a non-empty sequence of new sibling roots; each is
733
+ preflighted with its own ``validate_mutation`` call against the
734
+ range's parent, all running to completion before anything is written.
735
+ The old range is removed and the new one inserted through one combined
736
+ ``children`` assignment, so no intermediate, range-missing state is
737
+ ever observable.
738
+
739
+ ``net_delta`` is an optional caller-MEASURED signed byte delta (``len(new) - len(old)``) for
740
+ this splice's effect on ``parent_node``'s own rendered text. Left ``None`` (the default,
741
+ unchanged for every caller with no renderer available), NO ``buffer_range`` bookkeeping runs
742
+ at all for anything past the splice point -- every LATER sibling (and ``parent_node`` itself)
743
+ keeps its stale PRE-replace ``buffer_range`` forever, exactly as before this parameter
744
+ existed. That is bug 97329272's other half: unlike :func:`delete` and :func:`insert`, this
745
+ function never had ANY later-sibling refresh, so a replace whose incoming content differs in
746
+ length from what it replaced (the overwhelmingly common case) leaves every following sibling's
747
+ ``buffer_range`` off by the FULL length delta, not just a boundary byte -- a preview slicing
748
+ ``source_text[start:end]`` off it reads garbled, unrelated bytes. ``facade.replace`` measures
749
+ the TRUE value via a real before/after render diff (see ``facade._measure_replace_delta``) and
750
+ passes it here; when given and nonzero, :func:`apply_splice_delta` moves every position after the
751
+ incoming range by it -- the run's own later siblings, and everything after ``parent_node`` at
752
+ every level above it."""
753
+ resolved, parent_node, start, end = _resolve_contiguous_range(document, targets)
754
+ incoming_roots = list(incoming)
755
+ if not incoming_roots:
756
+ raise MutationError([ValidationError(code=ErrorCode.INVALID_SELECTOR, message="at least one incoming node is required")])
757
+ # Validate the parent can still hold the new range in a sequence field BEFORE splicing
758
+ # (bug 17f05476 residue), UNLESS this is the one shape that never needed a sequence field
759
+ # to begin with: a single target held by `parent_node` as a bare SCALAR field value, being
760
+ # replaced 1-for-1 -- the block below (defect #6 of bug 554f6521) mirrors the replacement
761
+ # directly into that field instead, so `children`/`fields` are already back in agreement
762
+ # by the time `sync_fields` runs and nothing here would refuse it. Every other shape (a
763
+ # scalar-only parent with a mismatched incoming count, or no sequence field at all) is
764
+ # refused up front instead of splicing first and letting `sync_fields` discover it only
765
+ # after `nodes_by_id` has already lost the replaced node's identity.
766
+ if not (len(resolved) == 1 and len(incoming_roots) == 1
767
+ and _scalar_field_owner(parent_node, resolved[0]) is not None):
768
+ _single_sequence_field(parent_node)
769
+ all_fragment_nodes: List[Any] = []
770
+ for root in incoming_roots:
771
+ all_fragment_nodes.extend(_fragment_nodes(root))
772
+ seen_ids: set = set()
773
+ for node in all_fragment_nodes:
774
+ raw_id = getattr(node, "node_id", None)
775
+ if raw_id is not None and raw_id in seen_ids:
776
+ raise MutationError([ValidationError(code=ErrorCode.NODE_ID_CONFLICT, message=f"node_id repeated in incoming batch: {raw_id!r}")])
777
+ seen_ids.add(raw_id)
778
+ all_errors: List[ValidationError] = []
779
+ combined_plan: List[ShortIdReassignment] = []
780
+ for root in incoming_roots:
781
+ result = validate_mutation(
782
+ document, root, parent=parent_node, position="child_index", index=start,
783
+ is_type_compatible=is_type_compatible, references=references,
784
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids, next_short_id=next_short_id,
785
+ )
786
+ if not result.success:
787
+ all_errors.extend(result.errors)
788
+ else:
789
+ combined_plan.extend(result.short_id_plan)
790
+ if all_errors:
791
+ raise MutationError(all_errors)
792
+ removed_addresses = tuple(_address(document, node) for node in resolved)
793
+ _apply_short_id_plan(all_fragment_nodes, combined_plan)
794
+ for root in incoming_roots:
795
+ if hasattr(root, "parent"):
796
+ root.parent = parent_node
797
+ siblings = _children_list(parent_node)
798
+ new_siblings = siblings[:start] + incoming_roots + siblings[end:]
799
+ _set_children(parent_node, new_siblings)
800
+ # A range of exactly one node that ``parent_node`` holds as a bare SCALAR field value
801
+ # (never wrapped in a tuple -- e.g. BinaryOperation.left/.right, Return.value,
802
+ # Attribute.value, Call.func) has no sequence field for sync_fields to rewrite at all, so
803
+ # the children-splice above leaves that field stale (still pointing at the removed node);
804
+ # mirror the replacement into it directly here, at the one place that already knows which
805
+ # old node the new one replaced (defect #6 of bug 554f6521). This keeps ``fields`` and
806
+ # ``children`` consistent from the moment of the splice, before the caller's own
807
+ # ``sync_fields`` call ever runs against this parent.
808
+ if len(resolved) == 1 and len(incoming_roots) == 1:
809
+ scalar_field = _scalar_field_owner(parent_node, resolved[0])
810
+ if scalar_field is not None:
811
+ parent_node.fields = {**parent_node.fields, scalar_field: incoming_roots[0]}
812
+ for node in resolved:
813
+ _unregister_subtree(document, node)
814
+ _register_fragment(document, all_fragment_nodes)
815
+ if net_delta:
816
+ apply_splice_delta(parent_node, new_siblings[start + len(incoming_roots):], net_delta)
817
+ inserted_addresses = tuple(_address(document, root) for root in incoming_roots)
818
+ return MutationResult(
819
+ node_id=getattr(parent_node, "node_id", None),
820
+ short_id=getattr(parent_node, "short_id", None),
821
+ position=start,
822
+ remap=tuple(combined_plan),
823
+ removed=removed_addresses,
824
+ inserted=inserted_addresses,
825
+ )