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,398 @@
1
+ """Attribute, body, source-fragment, and identifier updates (concept C-006,
2
+ {p011}, {p038}, {p109}).
3
+
4
+ Runs on top of the sibling files already merged for this concept:
5
+ ``validation.py`` (``validate_mutation``), ``operations.py`` (``insert``,
6
+ ``delete``, ``MutationResult``, ``MutationError``), ``reparse.py``
7
+ (``reparse_edited_node``, the post-text-change auto-reparse stage this file
8
+ is the sole caller-facing counterpart of), and ``identity.py``
9
+ (``replace_node_id``, the low-level ``nodes_by_id`` id swap this file's own
10
+ ``replace_node_id`` builds on). Same duck-typed ``document``/``node``
11
+ contract as those files: ``document.nodes_by_id``, an optional
12
+ ``document.short_id_index`` (``short_id -> node_id``), and a node exposing
13
+ ``node_id``, ``short_id``, ``parent``, ``children``. A node may additionally
14
+ expose ``get_attribute``/``set_attribute`` (the already-merged
15
+ ``node_types.py`` wrapper contract) and a ``references`` tuple of
16
+ ``NodeAddress``-like values (the reserved slot documented on ``nodes.py``'s
17
+ ``Node``).
18
+
19
+ ``set_attribute`` never classifies which attributes are export fields, or
20
+ implements any other field-admissibility policy, itself: it resolves the
21
+ target node and calls the node's own already-merged ``set_attribute``
22
+ method, which is where ``node_types.py``'s ``ExportFieldMixin`` already
23
+ decides -- before mutating anything -- whether a given field (``export`` in
24
+ particular) is admissible for that node's concrete type. A rejection
25
+ (``NodeSchemaError``, e.g. ``ExportNotApplicableError``) is caught and
26
+ re-raised as this concept's own ``MutationError`` carrying the same
27
+ ``ErrorCode``; nothing is mutated on that path, since the node's own method
28
+ already validates before it writes.
29
+
30
+ ``set_body`` accepts plain text, a single node, or a non-empty/empty
31
+ sequence of nodes. Text (and ``set_source_fragment``, always textual)
32
+ preserves the edited node's own existing leading indentation when the new
33
+ text does not already carry it, touches no sibling, and -- once the text is
34
+ written -- hands off exactly once to ``reparse.reparse_edited_node``,
35
+ surfacing whatever :class:`~tree_engine.core.reparse.ReparseOutcome` it
36
+ returns; a raised ``ReparseError`` restores the node's prior text before
37
+ propagating, so the whole update rolls back under the reparse stage's own
38
+ error code. A node or sequence body never goes through reparse (it is
39
+ already structured, not new text): every incoming root is preflighted with
40
+ ``validate_mutation`` against the target as parent (``position=
41
+ "last_child"``, mirroring how ``reparse.py`` attaches new children) before
42
+ anything is touched; only after every root clears preflight are the node's
43
+ current children removed via the sibling ``operations.delete`` and the new
44
+ roots attached via ``operations.insert``, one call per root -- the same
45
+ reuse ``reparse.py`` already makes of those two functions.
46
+
47
+ ``replace_node_id`` builds on ``identity.replace_node_id`` (validates and
48
+ swaps ``nodes_by_id`` atomically, raising before any mutation on a
49
+ malformed or colliding id) and additionally rekeys ``document
50
+ .short_id_index`` (the short_id itself is untouched, per {p097}; only the
51
+ node_id it currently points at moves) and rewrites the matching
52
+ ``references`` entries of every node in ``document`` and in each
53
+ ``loaded_documents`` entry the caller actually supplied -- never any other
54
+ document. Duplicates none of ``identity.py``'s validation.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ from dataclasses import dataclass
60
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
61
+ from uuid import UUID
62
+
63
+ from tree_engine.core.identity import AddressRemap, NodeAddress
64
+ from tree_engine.core.identity import replace_node_id as _identity_replace_node_id
65
+ from tree_engine.core.nodes import NodeSchemaError
66
+ from tree_engine.core.operations import MutationError, MutationResult, delete, insert
67
+ from tree_engine.core.reparse import ReparseError, ReparseOutcome, reparse_edited_node
68
+ from tree_engine.core.validation import ValidationError, validate_mutation
69
+ from tree_engine.errors import ErrorCode
70
+
71
+ __all__ = [
72
+ "UpdateOutcome",
73
+ "set_attribute",
74
+ "set_body",
75
+ "set_source_fragment",
76
+ "replace_node_id",
77
+ ]
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class UpdateOutcome:
82
+ """Result of ``set_body``/``set_source_fragment``: the structural
83
+ ``mutation`` (affected node's identity, unchanged position), plus
84
+ ``reparse`` -- the :class:`~tree_engine.core.reparse.ReparseOutcome`
85
+ when a text change was routed through the reparse stage, or ``None``
86
+ for a node/sequence body (never reparsed, see module docstring)."""
87
+
88
+ mutation: MutationResult
89
+ reparse: Optional[ReparseOutcome] = None
90
+
91
+
92
+ # -- internal helpers, duplicated in miniature from the sibling files since
93
+ # they are private there (mirrors reparse.py's own precedent) ---------------
94
+
95
+
96
+ def _resolve(document: Any, ref: Any) -> Optional[Any]:
97
+ if ref is None:
98
+ return None
99
+ nodes_by_id = getattr(document, "nodes_by_id", None) or {}
100
+ candidate_id = getattr(ref, "node_id", None)
101
+ if candidate_id is not None and nodes_by_id.get(candidate_id) is ref:
102
+ return ref
103
+ if isinstance(ref, UUID) and ref in nodes_by_id:
104
+ return nodes_by_id[ref]
105
+ short_index = getattr(document, "short_id_index", None)
106
+ if isinstance(short_index, dict) and ref in short_index:
107
+ return nodes_by_id.get(short_index[ref])
108
+ for candidate in nodes_by_id.values():
109
+ if getattr(candidate, "short_id", None) == ref:
110
+ return candidate
111
+ return None
112
+
113
+
114
+ def _fragment_nodes(root: Any) -> List[Any]:
115
+ ordered: List[Any] = []
116
+ stack = [root]
117
+ while stack:
118
+ node = stack.pop(0)
119
+ ordered.append(node)
120
+ stack = list(getattr(node, "children", None) or ()) + stack
121
+ return ordered
122
+
123
+
124
+ def _get_content(node: Any) -> str:
125
+ getter = getattr(node, "get_attribute", None)
126
+ if callable(getter):
127
+ return getter("content", "") or ""
128
+ return getattr(node, "content", "") or ""
129
+
130
+
131
+ def _set_content(node: Any, text: str) -> None:
132
+ setter = getattr(node, "set_attribute", None)
133
+ if callable(setter):
134
+ setter("content", text)
135
+ return
136
+ node.content = text
137
+
138
+
139
+ def _preserve_indentation(old_text: str, new_text: str) -> str:
140
+ """Keep ``old_text``'s own leading indentation when ``new_text`` does
141
+ not already carry it, so a caller passing bare re-indented content does
142
+ not strip the node's place in its surrounding layout. Never touches any
143
+ sibling: only ``old_text``/``new_text`` of this one node are read."""
144
+ stripped_old = old_text.lstrip(" \t")
145
+ indent = old_text[: len(old_text) - len(stripped_old)]
146
+ if indent and not new_text.startswith(indent):
147
+ return indent + new_text.lstrip(" \t")
148
+ return new_text
149
+
150
+
151
+ def _retarget(address: Any, old_id: UUID, new_id: UUID, scanned_doc_id: Any, target_doc_id: Any) -> Any:
152
+ """Retarget one reference iff it names the renamed node ``old_id`` *in
153
+ the document being renamed* (``target_doc_id``): either an implicit
154
+ local address (``document_id is None``) found while scanning that same
155
+ document, or an explicit address naming ``target_doc_id`` outright. A
156
+ local address found in any other scanned document names a node local to
157
+ that other document instead, never the renamed one, and is left alone."""
158
+ if getattr(address, "node_id", None) != old_id:
159
+ return address
160
+ addr_doc_id = getattr(address, "document_id", None)
161
+ if addr_doc_id is None:
162
+ if scanned_doc_id != target_doc_id:
163
+ return address
164
+ elif addr_doc_id != target_doc_id:
165
+ return address
166
+ return NodeAddress(document_id=addr_doc_id, node_id=new_id)
167
+
168
+
169
+ def _apply_text_and_reparse(
170
+ document: Any,
171
+ target: Any,
172
+ new_text: str,
173
+ *,
174
+ source_format_id: str,
175
+ admits_nested_structure: Callable[[Any], bool],
176
+ parse_fragment: Callable[..., Any],
177
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]],
178
+ references: Optional[Iterable[Any]],
179
+ loaded_documents: Optional[Dict[Any, Any]],
180
+ used_short_ids: Optional[Sequence[Any]],
181
+ next_short_id: Optional[Callable[[], Any]],
182
+ generate_node_id: Optional[Callable[[], Any]],
183
+ ) -> UpdateOutcome:
184
+ if is_type_compatible is not None and not is_type_compatible(target, "body", new_text):
185
+ raise MutationError([
186
+ ValidationError(
187
+ code=ErrorCode.INVALID_PARENT_TYPE,
188
+ message="text body is not admissible for this node's type",
189
+ node_id=getattr(target, "node_id", None),
190
+ )
191
+ ])
192
+ old_text = _get_content(target)
193
+ final_text = _preserve_indentation(old_text, new_text)
194
+ _set_content(target, final_text)
195
+ kwargs: Dict[str, Any] = dict(
196
+ is_type_compatible=is_type_compatible, references=references,
197
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids,
198
+ next_short_id=next_short_id,
199
+ )
200
+ if generate_node_id is not None:
201
+ kwargs["generate_node_id"] = generate_node_id
202
+ try:
203
+ outcome = reparse_edited_node(
204
+ document, target, final_text, source_format_id=source_format_id,
205
+ admits_nested_structure=admits_nested_structure, parse_fragment=parse_fragment,
206
+ **kwargs,
207
+ )
208
+ except ReparseError:
209
+ _set_content(target, old_text)
210
+ raise
211
+ mutation = MutationResult(
212
+ node_id=getattr(target, "node_id", None), short_id=getattr(target, "short_id", None), position=None,
213
+ )
214
+ return UpdateOutcome(mutation=mutation, reparse=outcome)
215
+
216
+
217
+ def _replace_children(
218
+ document: Any,
219
+ parent_node: Any,
220
+ roots: Sequence[Any],
221
+ *,
222
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]],
223
+ references: Optional[Iterable[Any]],
224
+ loaded_documents: Optional[Dict[Any, Any]],
225
+ used_short_ids: Optional[Sequence[Any]],
226
+ next_short_id: Optional[Callable[[], Any]],
227
+ ) -> MutationResult:
228
+ old_children = list(getattr(parent_node, "children", None) or ())
229
+ all_fragment_nodes: List[Any] = []
230
+ for root in roots:
231
+ all_fragment_nodes.extend(_fragment_nodes(root))
232
+ seen: set = set()
233
+ for fnode in all_fragment_nodes:
234
+ rid = getattr(fnode, "node_id", None)
235
+ if rid is not None and rid in seen:
236
+ raise MutationError([ValidationError(code=ErrorCode.NODE_ID_CONFLICT, message=f"node_id repeated in incoming body: {rid!r}")])
237
+ seen.add(rid)
238
+ dry_errors: List[ValidationError] = []
239
+ for root in roots:
240
+ result = validate_mutation(
241
+ document, root, parent=parent_node, position="last_child",
242
+ is_type_compatible=is_type_compatible, references=references,
243
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids, next_short_id=None,
244
+ )
245
+ dry_errors.extend(result.errors)
246
+ if dry_errors:
247
+ raise MutationError(dry_errors)
248
+
249
+ # Preflight cleared for every root -- nothing has been touched yet.
250
+ removed: Tuple[NodeAddress, ...] = ()
251
+ if old_children:
252
+ removed = delete(document, old_children).removed
253
+ remap: List[Any] = []
254
+ inserted: List[NodeAddress] = []
255
+ for root in roots:
256
+ result = insert(
257
+ document, root, position="last_child", parent=parent_node,
258
+ is_type_compatible=is_type_compatible, references=references,
259
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids, next_short_id=next_short_id,
260
+ )
261
+ remap.extend(result.remap)
262
+ inserted.extend(result.inserted)
263
+ return MutationResult(
264
+ node_id=getattr(parent_node, "node_id", None), short_id=getattr(parent_node, "short_id", None),
265
+ position=0, remap=tuple(remap), removed=removed, inserted=tuple(inserted),
266
+ )
267
+
268
+
269
+ # -- public operations --------------------------------------------------
270
+
271
+
272
+ def set_attribute(document: Any, node: Any, name: str, value: Any) -> MutationResult:
273
+ """Set field ``name`` on ``node`` ({p011}). Admissibility -- including
274
+ whether ``name`` is an export field for this node's concrete type -- is
275
+ decided entirely by the node's own already-merged ``set_attribute``
276
+ method (see module docstring); this function adds no classification of
277
+ its own and mutates nothing when that call raises."""
278
+ target = _resolve(document, node)
279
+ if target is None:
280
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"node could not be resolved: {node!r}")])
281
+ setter = getattr(target, "set_attribute", None)
282
+ if not callable(setter):
283
+ raise MutationError([ValidationError(code=ErrorCode.INVALID_SELECTOR, message=f"node exposes no set_attribute: {type(target).__name__}")])
284
+ try:
285
+ setter(name, value)
286
+ except NodeSchemaError as exc:
287
+ raise MutationError([ValidationError(code=exc.code, message=str(exc), node_id=getattr(target, "node_id", None))]) from exc
288
+ return MutationResult(node_id=getattr(target, "node_id", None), short_id=getattr(target, "short_id", None), position=None)
289
+
290
+
291
+ def set_body(
292
+ document: Any,
293
+ node: Any,
294
+ body: Any,
295
+ *,
296
+ admits_nested_structure: Callable[[Any], bool],
297
+ parse_fragment: Callable[..., Any],
298
+ source_format_id: str = "",
299
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]] = None,
300
+ references: Optional[Iterable[Any]] = None,
301
+ loaded_documents: Optional[Dict[Any, Any]] = None,
302
+ used_short_ids: Optional[Sequence[Any]] = None,
303
+ next_short_id: Optional[Callable[[], Any]] = None,
304
+ generate_node_id: Optional[Callable[[], Any]] = None,
305
+ ) -> UpdateOutcome:
306
+ """Set ``node``'s body ({p038}): ``body`` is plain text, a single node,
307
+ or a sequence of nodes. Text preserves the node's own indentation (see
308
+ ``_preserve_indentation``) and, once written, routes exactly once
309
+ through ``reparse.reparse_edited_node`` (rolled back on
310
+ ``ReparseError``). A node/sequence body is preflighted whole against
311
+ ``node`` as parent via the injected ``is_type_compatible`` -- the same
312
+ compatibility rules ``validate_mutation`` already uses -- before any of
313
+ the node's current children are removed or the new ones attached; a
314
+ rejection leaves the node's existing children completely untouched."""
315
+ target = _resolve(document, node)
316
+ if target is None:
317
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"node could not be resolved: {node!r}")])
318
+ if isinstance(body, str):
319
+ return _apply_text_and_reparse(
320
+ document, target, body, source_format_id=source_format_id,
321
+ admits_nested_structure=admits_nested_structure, parse_fragment=parse_fragment,
322
+ is_type_compatible=is_type_compatible, references=references, loaded_documents=loaded_documents,
323
+ used_short_ids=used_short_ids, next_short_id=next_short_id, generate_node_id=generate_node_id,
324
+ )
325
+ roots = list(body) if isinstance(body, (list, tuple)) else [body]
326
+ mutation = _replace_children(
327
+ document, target, roots, is_type_compatible=is_type_compatible, references=references,
328
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids, next_short_id=next_short_id,
329
+ )
330
+ return UpdateOutcome(mutation=mutation, reparse=None)
331
+
332
+
333
+ def set_source_fragment(
334
+ document: Any,
335
+ node: Any,
336
+ fragment_text: str,
337
+ *,
338
+ admits_nested_structure: Callable[[Any], bool],
339
+ parse_fragment: Callable[..., Any],
340
+ source_format_id: str = "",
341
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]] = None,
342
+ references: Optional[Iterable[Any]] = None,
343
+ loaded_documents: Optional[Dict[Any, Any]] = None,
344
+ used_short_ids: Optional[Sequence[Any]] = None,
345
+ next_short_id: Optional[Callable[[], Any]] = None,
346
+ generate_node_id: Optional[Callable[[], Any]] = None,
347
+ ) -> UpdateOutcome:
348
+ """Overwrite ``node``'s raw source text ({p011}). Always textual --
349
+ unlike ``set_body`` there is no node/sequence form -- so this always
350
+ preserves indentation and routes exactly once through
351
+ ``reparse.reparse_edited_node``, exactly like ``set_body``'s text path
352
+ (see :func:`_apply_text_and_reparse`)."""
353
+ target = _resolve(document, node)
354
+ if target is None:
355
+ raise MutationError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"node could not be resolved: {node!r}")])
356
+ return _apply_text_and_reparse(
357
+ document, target, fragment_text, source_format_id=source_format_id,
358
+ admits_nested_structure=admits_nested_structure, parse_fragment=parse_fragment,
359
+ is_type_compatible=is_type_compatible, references=references, loaded_documents=loaded_documents,
360
+ used_short_ids=used_short_ids, next_short_id=next_short_id, generate_node_id=generate_node_id,
361
+ )
362
+
363
+
364
+ def replace_node_id(
365
+ document: Any, old_node_id: UUID, new_node_id: UUID, *, loaded_documents: Optional[Dict[Any, Any]] = None,
366
+ ) -> AddressRemap:
367
+ """Atomically rewrite a node's UUID4 ({p109}). Delegates the id-format
368
+ validation and the ``nodes_by_id`` swap itself to
369
+ ``identity.replace_node_id`` -- raising before any mutation on a
370
+ malformed or colliding new id, exactly as that function already
371
+ guarantees -- then rekeys ``document.short_id_index`` (only the
372
+ node_id a short_id points at moves; the short_id itself never changes,
373
+ per {p097}) and rewrites the ``references`` of every node in
374
+ ``document`` and in each ``loaded_documents`` entry supplied, and only
375
+ those; a document the caller did not pass here is left untouched by
376
+ design."""
377
+ remap = _identity_replace_node_id(document, old_node_id, new_node_id)
378
+ short_index = getattr(document, "short_id_index", None)
379
+ if isinstance(short_index, dict):
380
+ for key, val in list(short_index.items()):
381
+ if val == old_node_id:
382
+ short_index[key] = new_node_id
383
+ target_doc_id = getattr(document, "document_id", None)
384
+ docs: Dict[Any, Any] = {target_doc_id: document}
385
+ for doc_id, doc in (loaded_documents or {}).items():
386
+ docs.setdefault(doc_id, doc)
387
+ for doc_id, doc in docs.items():
388
+ for candidate in (getattr(doc, "nodes_by_id", None) or {}).values():
389
+ refs = getattr(candidate, "references", None)
390
+ if not refs:
391
+ continue
392
+ updated = tuple(_retarget(addr, old_node_id, new_node_id, doc_id, target_doc_id) for addr in refs)
393
+ if updated != tuple(refs):
394
+ try:
395
+ candidate.references = updated
396
+ except AttributeError:
397
+ pass
398
+ return remap