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,378 @@
1
+ """Automatic post-mutation reparse of a single edited node (concept C-006,
2
+ {p098}, {p099}).
3
+
4
+ Scope: this module owns exactly one stage -- what happens *after* a node's
5
+ text content has already changed through ``set_body`` or a source-fragment
6
+ update, invoked by the sibling ``updates.py`` file immediately once that
7
+ change has been applied. It never decides *when* such a change occurs, and
8
+ it never applies one itself; it only decides what the format plugin's
9
+ ``parse_fragment`` result means for the edited node's structure.
10
+
11
+ Fragment-level only -- never a whole-document reparse: this stage always
12
+ calls the injected ``parse_fragment`` callable, the fragment-level half of
13
+ ``core/plugin_boundary.py``'s ``FormatBoundary`` (``source: str ->
14
+ Node``), and nothing here ever calls, references, or approximates the
15
+ whole-document counterpart (``FormatBoundary.parse_document``). A full
16
+ reparse of an entire file is a different, separately governed operation
17
+ (permitted only on initial load, an explicit full check, recovery from an
18
+ external change, or as the closing check of a completed batch) and is out
19
+ of scope for this file in every code path: calling
20
+ :func:`reparse_edited_node` any number of times for a batch of ``K`` edited
21
+ nodes triggers at most ``K`` fragment-level ``parse_fragment`` calls -- one
22
+ per node whose type admits nested structure -- and zero whole-document
23
+ parses, never a whole-document reparse per element and never one at all
24
+ from this module.
25
+
26
+ Consult-before-parse: per {p098}, ``parse_fragment`` is only invoked when
27
+ the caller-supplied ``admits_nested_structure`` predicate says the edited
28
+ node's type admits nested structure. That predicate is where a caller
29
+ consults the format plugin's declared ``capabilities`` and its node-kind
30
+ policy (``plugin_boundary.py`` does not yet define a concrete capability/
31
+ node-kind-policy surface in this worktree, so -- mirroring how
32
+ ``validation.py`` already takes ``is_type_compatible`` and ``next_short_id``
33
+ as caller-injected callables for the same reason -- this file takes the
34
+ already-consulted decision as one injected callable rather than importing,
35
+ stubbing, or guessing at a plugin contract that is not merged yet). The
36
+ concrete parser itself is likewise never imported here: ``parse_fragment``
37
+ is an injected callable, satisfied later by a real plugin.
38
+
39
+ Three outcomes, per {p098}/{p099}:
40
+
41
+ * The node's type does not admit nested structure: ``parse_fragment`` is
42
+ never called at all.
43
+ * ``parse_fragment`` returns a ``str``: a successful outcome meaning no
44
+ recognized structure; the node remains textual and no child is routed
45
+ anywhere.
46
+ * ``parse_fragment`` returns a structured object or a set of common-model
47
+ nodes: the edited node keeps its own identity as the container, and
48
+ every new child is preflighted via the sibling ``validation.py``'s
49
+ :func:`~tree_engine.core.validation.validate_mutation` and then applied
50
+ via the sibling ``operations.py``'s :func:`~tree_engine.core.operations.insert`
51
+ -- the same shared preflight/atomic-apply pair every other mutation in
52
+ this concept uses, so short_id assignment, index-map registration, and
53
+ reference resolution happen exactly as they do for any other insert.
54
+
55
+ Failure, per {p099}: a raised exception or a return value that is not a
56
+ ``str`` and not a recognizable node/node-sequence shape is reported as
57
+ :class:`ReparseError` carrying ``ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED``.
58
+ A return value shaped like structured content that nonetheless violates the
59
+ common-model contract (bad node shape, an empty node set, a batch-internal
60
+ node_id collision, or a new child that fails preflight against its new
61
+ parent) is reported as :class:`ReparseError` carrying
62
+ ``ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR``. In both cases nothing from the
63
+ rejected parse result is ever written to the tree -- the whole batch of new
64
+ children is preflighted to completion before any one of them is applied --
65
+ and plain-text fallback is never substituted for a local mutation; the
66
+ caller (``updates.py``) is expected to catch :class:`ReparseError` and roll
67
+ the entire mutation back, since only it owns the text change this stage
68
+ was invoked to interpret.
69
+
70
+ This file duplicates nothing from its already-merged siblings: it imports
71
+ ``validate_mutation``/``ValidationError`` from ``validation.py``,
72
+ ``insert``/``MutationError``/``MutationResult`` from ``operations.py``, and
73
+ ``generate_node_id`` from ``identity.py``, and otherwise stays duck-typed
74
+ about the tree/node shape exactly as those two files already are, so it
75
+ needs no change when the concrete live-tree/document type lands later.
76
+ """
77
+
78
+ from __future__ import annotations
79
+
80
+ from dataclasses import dataclass
81
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
82
+
83
+ from tree_engine.core.identity import generate_node_id as _generate_node_id
84
+ from tree_engine.core.operations import MutationError, MutationResult, insert
85
+ from tree_engine.core.validation import ValidationError, validate_mutation
86
+ from tree_engine.errors import ErrorCode
87
+
88
+ __all__ = [
89
+ "STATUS_SKIPPED",
90
+ "STATUS_TEXTUAL",
91
+ "STATUS_STRUCTURED",
92
+ "ReparseError",
93
+ "ReparseOutcome",
94
+ "reparse_edited_node",
95
+ ]
96
+
97
+ # ReparseOutcome.status values.
98
+ STATUS_SKIPPED = "skipped_no_nested_structure"
99
+ STATUS_TEXTUAL = "textual"
100
+ STATUS_STRUCTURED = "structured"
101
+
102
+
103
+ class ReparseError(Exception):
104
+ """Raised instead of applying anything, per {p099}.
105
+
106
+ ``code`` is either ``ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED`` (a raised
107
+ exception or an unrecognized return type from ``parse_fragment``) or
108
+ ``ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR`` (a recognizable-but-invalid
109
+ common-model result). ``errors`` optionally carries the underlying
110
+ :class:`~tree_engine.core.validation.ValidationError` list when the
111
+ failure came from routing a new child through the shared preflight.
112
+ """
113
+
114
+ def __init__(self, code: ErrorCode, message: str, errors: Sequence[ValidationError] = ()) -> None:
115
+ self.code = code
116
+ self.errors: List[ValidationError] = list(errors)
117
+ super().__init__(f"[{code.value}] {message}")
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class ReparseOutcome:
122
+ """Result of one successful :func:`reparse_edited_node` call.
123
+
124
+ ``node_id`` is the edited node's own, unchanged identity. ``text`` is
125
+ populated only for :data:`STATUS_TEXTUAL`. ``applied`` is populated
126
+ only for :data:`STATUS_STRUCTURED`: the ordered
127
+ :class:`~tree_engine.core.operations.MutationResult` of each new child,
128
+ in the order it was inserted.
129
+ """
130
+
131
+ status: str
132
+ node_id: Any
133
+ text: Optional[str] = None
134
+ applied: Tuple[MutationResult, ...] = ()
135
+
136
+
137
+ # -- internal helpers --------------------------------------------------------
138
+
139
+
140
+ def _looks_like_common_model_node(value: Any) -> bool:
141
+ """Minimal shape check for "a common-model node": a non-empty ``kind``
142
+ string, and a ``children`` attribute that, when present, is an ordered
143
+ sequence. Duck-typed on purpose -- mirrors the rest of this concept's
144
+ already-merged files, none of which require a specific concrete node
145
+ class."""
146
+
147
+ kind = getattr(value, "kind", None)
148
+ if not isinstance(kind, str) or not kind:
149
+ return False
150
+ children = getattr(value, "children", None)
151
+ if children is not None and not isinstance(children, (list, tuple)):
152
+ return False
153
+ return True
154
+
155
+
156
+ def _validate_common_model_shape(root: Any) -> None:
157
+ """Recursively confirm ``root`` and every descendant satisfies
158
+ :func:`_looks_like_common_model_node`. Raises :class:`ReparseError`
159
+ with ``FORMAT_PLUGIN_CONTRACT_ERROR`` at the first violation."""
160
+
161
+ stack = [root]
162
+ while stack:
163
+ node = stack.pop()
164
+ if not _looks_like_common_model_node(node):
165
+ raise ReparseError(
166
+ ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
167
+ f"parse_fragment result is not a valid common-model node: {node!r}",
168
+ )
169
+ stack.extend(getattr(node, "children", None) or ())
170
+
171
+
172
+ def _collect_fragment_nodes(root: Any) -> List[Any]:
173
+ """Pre-order ``root`` and every descendant (mirrors ``operations.py``'s
174
+ own ``_fragment_nodes``, duplicated rather than imported since it is a
175
+ private helper of that module)."""
176
+
177
+ ordered: List[Any] = []
178
+ stack = [root]
179
+ while stack:
180
+ node = stack.pop(0)
181
+ ordered.append(node)
182
+ stack = list(getattr(node, "children", None) or ()) + stack
183
+ return ordered
184
+
185
+
186
+ def _classify_parse_result(raw_result: Any) -> List[Any]:
187
+ """Turn a non-``str`` ``parse_fragment`` return into an ordered list of
188
+ new root nodes ("a structured object or a set of common-model nodes").
189
+
190
+ A single node-shaped object becomes a one-element list. A non-empty
191
+ ``list``/``tuple`` is the explicit "set of nodes" form. Anything else
192
+ -- not a recognizable node shape at all, or an empty sequence -- is
193
+ rejected: an unrecognized shape never even claims to be structured
194
+ content, so it is ``FORMAT_FRAGMENT_PARSE_FAILED``; an empty sequence
195
+ claims to be a node set but holds no content, so it is
196
+ ``FORMAT_PLUGIN_CONTRACT_ERROR``.
197
+ """
198
+
199
+ if isinstance(raw_result, (list, tuple)):
200
+ if not raw_result:
201
+ raise ReparseError(
202
+ ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
203
+ "parse_fragment returned an empty node sequence",
204
+ )
205
+ return list(raw_result)
206
+ if _looks_like_common_model_node(raw_result):
207
+ return [raw_result]
208
+ raise ReparseError(
209
+ ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED,
210
+ f"parse_fragment returned an unrecognized type: {type(raw_result).__name__}",
211
+ )
212
+
213
+
214
+ def _assign_missing_identity(roots: Sequence[Any], generate_id: Callable[[], Any]) -> None:
215
+ """Assign a fresh UUID4 ``node_id`` (per {p098}, "new child nodes...
216
+ receive new UUID4s") to every node across ``roots`` that does not
217
+ already carry one. A node that refuses the assignment (e.g. an
218
+ immutable object that raises on attribute assignment) is a
219
+ common-model contract violation, not a parser failure -- this engine's
220
+ mutation pipeline requires new content to accept an assigned
221
+ identity."""
222
+
223
+ for root in roots:
224
+ for node in _collect_fragment_nodes(root):
225
+ if getattr(node, "node_id", None) is None:
226
+ try:
227
+ node.node_id = generate_id()
228
+ except (AttributeError, TypeError) as exc:
229
+ raise ReparseError(
230
+ ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
231
+ f"node does not accept an assigned node_id: {node!r}",
232
+ ) from exc
233
+
234
+
235
+ def _check_no_duplicate_node_ids(nodes: Sequence[Any]) -> None:
236
+ """Guard against a node_id repeated within the same parsed batch, which
237
+ ``validate_mutation`` cannot see on its own since each call only checks
238
+ one root against the document (mirrors ``operations.replace_range``'s
239
+ own same-batch collision guard)."""
240
+
241
+ seen: set = set()
242
+ for node in nodes:
243
+ raw_id = getattr(node, "node_id", None)
244
+ if raw_id is not None and raw_id in seen:
245
+ raise ReparseError(
246
+ ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
247
+ f"node_id repeated among parsed children: {raw_id!r}",
248
+ )
249
+ seen.add(raw_id)
250
+
251
+
252
+ # -- public entry point -------------------------------------------------------
253
+
254
+
255
+ def reparse_edited_node(
256
+ document: Any,
257
+ edited_node: Any,
258
+ edited_text: str,
259
+ *,
260
+ source_format_id: str,
261
+ admits_nested_structure: Callable[[Any], bool],
262
+ parse_fragment: Callable[..., Any],
263
+ generate_node_id: Callable[[], Any] = _generate_node_id,
264
+ is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]] = None,
265
+ references: Optional[Iterable[Any]] = None,
266
+ loaded_documents: Optional[Dict[Any, Any]] = None,
267
+ used_short_ids: Optional[Sequence[Any]] = None,
268
+ next_short_id: Optional[Callable[[], Any]] = None,
269
+ ) -> ReparseOutcome:
270
+ """Run the {p098}/{p099} post-mutation reparse stage for one node whose
271
+ text content was just changed by ``set_body`` or a source-fragment
272
+ update in the sibling ``updates.py`` file.
273
+
274
+ Args:
275
+ document: the target document, read only via ``document.nodes_by_id``
276
+ and passed through, unread otherwise, to ``validate_mutation``
277
+ and ``insert``.
278
+ edited_node: the node whose text just changed. Its own identity is
279
+ never modified by this function; new children, if any, are
280
+ attached under it.
281
+ edited_text: the node's new text content, exactly as just written
282
+ by ``set_body``/the source-fragment update -- this file does
283
+ not read it from anywhere else.
284
+ source_format_id: the format id passed through to ``parse_fragment``.
285
+ admits_nested_structure: caller-supplied predicate, already having
286
+ consulted the format plugin's capabilities and node-kind
287
+ policy, deciding whether ``edited_node``'s type may hold nested
288
+ structure at all. ``parse_fragment`` is never called when this
289
+ returns falsy.
290
+ parse_fragment: the injected fragment parser, called as
291
+ ``parse_fragment(edited_text, source_format_id=source_format_id)``,
292
+ mirroring ``FormatBoundary.parse_fragment``'s signature. Never
293
+ imported or stubbed by this module -- always caller-supplied.
294
+ generate_node_id: the fresh-UUID4 allocator for new children,
295
+ defaulting to ``identity.generate_node_id``.
296
+ is_type_compatible, references, loaded_documents, used_short_ids,
297
+ next_short_id: threaded through, unchanged, to every
298
+ ``validate_mutation``/``insert`` call this function makes --
299
+ same meaning as on those two functions.
300
+
301
+ Returns:
302
+ A :class:`ReparseOutcome` describing which of the three {p098}
303
+ outcomes occurred.
304
+
305
+ Raises:
306
+ ReparseError: on any of the {p099} rejection conditions. Nothing is
307
+ written to ``document`` in that case.
308
+ """
309
+
310
+ node_id = getattr(edited_node, "node_id", None)
311
+
312
+ if not admits_nested_structure(edited_node):
313
+ return ReparseOutcome(status=STATUS_SKIPPED, node_id=node_id)
314
+
315
+ try:
316
+ raw_result = parse_fragment(edited_text, source_format_id=source_format_id)
317
+ except Exception as exc:
318
+ raise ReparseError(
319
+ ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED,
320
+ f"parse_fragment raised for node {node_id!r}: {exc}",
321
+ ) from exc
322
+
323
+ if isinstance(raw_result, str):
324
+ return ReparseOutcome(status=STATUS_TEXTUAL, node_id=node_id, text=raw_result)
325
+
326
+ roots = _classify_parse_result(raw_result)
327
+ for root in roots:
328
+ _validate_common_model_shape(root)
329
+
330
+ _assign_missing_identity(roots, generate_node_id)
331
+
332
+ all_new_nodes: List[Any] = []
333
+ for root in roots:
334
+ all_new_nodes.extend(_collect_fragment_nodes(root))
335
+ _check_no_duplicate_node_ids(all_new_nodes)
336
+
337
+ # Preflight the whole batch to completion first -- a dry run, with
338
+ # next_short_id withheld so no allocator side effect happens here --
339
+ # so that either every new root is admissible or none of them are ever
340
+ # written to the tree. The real allocator only runs once, below, during
341
+ # the actual apply pass.
342
+ dry_errors: List[ValidationError] = []
343
+ for root in roots:
344
+ result = validate_mutation(
345
+ document, root, parent=edited_node, position="last_child",
346
+ is_type_compatible=is_type_compatible, references=references,
347
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids,
348
+ next_short_id=None,
349
+ )
350
+ dry_errors.extend(result.errors)
351
+ if dry_errors:
352
+ raise ReparseError(
353
+ ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
354
+ "parsed content failed preflight validation against its new parent",
355
+ errors=dry_errors,
356
+ )
357
+
358
+ # Every root passed the dry run; apply each through the same atomic
359
+ # insert path every other mutation in this concept uses.
360
+ applied: List[MutationResult] = []
361
+ for root in roots:
362
+ try:
363
+ applied.append(
364
+ insert(
365
+ document, root, position="last_child", parent=edited_node,
366
+ is_type_compatible=is_type_compatible, references=references,
367
+ loaded_documents=loaded_documents, used_short_ids=used_short_ids,
368
+ next_short_id=next_short_id,
369
+ )
370
+ )
371
+ except MutationError as exc:
372
+ raise ReparseError(
373
+ ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
374
+ "parsed content failed atomic application after passing preflight",
375
+ errors=exc.errors,
376
+ ) from exc
377
+
378
+ return ReparseOutcome(status=STATUS_STRUCTURED, node_id=node_id, applied=tuple(applied))
@@ -0,0 +1,296 @@
1
+ """Document-local short_id bidirectional map and lifecycle.
2
+
3
+ Scope (concept C-004, narrowed to the short_id subsystem only): this module
4
+ owns the positive-integer ``short_id`` <-> canonical ``uuid.UUID`` node_id
5
+ bidirectional map, its monotonic allocator, and its hex rendering. Per
6
+ {p097}, a short_id is document-local, persisted as a bidirectional map with
7
+ a monotonic ``next_short_id`` counter, rendered externally as 0x-prefixed
8
+ hex, and -- once issued -- is never reused after a delete or a rollback
9
+ (gaps are allowed).
10
+
11
+ This module is standalone: it depends only on the standard library
12
+ (``uuid``, ``dataclasses``, ``typing``) and imports nothing from any
13
+ sibling project module, including ``identity.py``. It operates purely on
14
+ ``uuid.UUID`` node ids passed in by callers; ``NodeAddress``,
15
+ ``replace_node_id``, and ``normalize_node_address`` are out of scope here
16
+ and belong to sibling artifacts, which use ``allocate``/``release``/
17
+ ``rekey`` as building blocks.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import uuid
23
+ from dataclasses import dataclass
24
+ from typing import Dict, Mapping, Optional, Sequence
25
+
26
+ __all__ = [
27
+ "ShortIdError",
28
+ "UnknownShortIdError",
29
+ "InvalidShortIdHexError",
30
+ "DuplicateNodeIdError",
31
+ "to_hex",
32
+ "from_hex",
33
+ "ShortIdMapSnapshot",
34
+ "ShortIdMap",
35
+ ]
36
+
37
+
38
+ class ShortIdError(Exception):
39
+ """Base exception for the short_id subsystem (concept C-004, {p097})."""
40
+
41
+
42
+ class UnknownShortIdError(ShortIdError):
43
+ """Raised when an int/hex short_id is not present in the map.
44
+
45
+ Covers :meth:`ShortIdMap.resolve_hex` and :meth:`ShortIdMap.rekey`
46
+ (when ``old_node_id`` has no short_id) per {p097}.
47
+ """
48
+
49
+
50
+ class InvalidShortIdHexError(ShortIdError):
51
+ """Raised by :func:`from_hex` when its input is malformed ({p097})."""
52
+
53
+
54
+ class DuplicateNodeIdError(ShortIdError):
55
+ """Raised when allocating or merging a node_id already in the map.
56
+
57
+ Covers :meth:`ShortIdMap.allocate`, :meth:`ShortIdMap.assign_bulk`,
58
+ :meth:`ShortIdMap.rekey` (when ``new_node_id`` already has a short_id),
59
+ and :meth:`ShortIdMap.merge_insert`, per {p097}.
60
+ """
61
+
62
+
63
+ def to_hex(short_id: int) -> str:
64
+ """Render a positive integer short_id as lowercase 0x-prefixed hex.
65
+
66
+ Per {p097}, short_id "is a positive integer and is rendered externally
67
+ as 0x-prefixed hex" (e.g. ``1 -> '0x1'``, ``255 -> '0xff'``). Raises
68
+ ``ValueError`` if ``short_id`` is not an ``int`` or is less than 1.
69
+ """
70
+
71
+ if isinstance(short_id, bool) or not isinstance(short_id, int):
72
+ raise ValueError(f"short_id must be an int, got {short_id!r}")
73
+ if short_id < 1:
74
+ raise ValueError(f"short_id must be >= 1, got {short_id!r}")
75
+ return f"0x{short_id:x}"
76
+
77
+
78
+ def from_hex(value: str) -> int:
79
+ """Parse a 0x-prefixed hex string back into a positive integer.
80
+
81
+ Accepts a case-insensitive ``0x`` prefix and hex digits of either
82
+ case. Raises :class:`InvalidShortIdHexError` for a missing/invalid
83
+ prefix, non-hex characters, or a decoded value less than 1, per
84
+ {p097}'s hex rendering contract.
85
+ """
86
+
87
+ if not isinstance(value, str):
88
+ raise InvalidShortIdHexError(f"short_id hex value must be a str, got {value!r}")
89
+ if len(value) < 3 or value[:2].lower() != "0x":
90
+ raise InvalidShortIdHexError(f"short_id hex value must start with '0x': {value!r}")
91
+ digits = value[2:]
92
+ try:
93
+ decoded = int(digits, 16)
94
+ except ValueError as exc:
95
+ raise InvalidShortIdHexError(
96
+ f"short_id hex value has non-hex digits: {value!r}"
97
+ ) from exc
98
+ if decoded < 1:
99
+ raise InvalidShortIdHexError(f"short_id hex value must decode to >= 1: {value!r}")
100
+ return decoded
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class ShortIdMapSnapshot:
105
+ """Immutable capture of a :class:`ShortIdMap`'s state ({p097}).
106
+
107
+ Produced only via :meth:`ShortIdMap.snapshot` and consumed only via
108
+ :meth:`ShortIdMap.restore`, for transaction/rollback support.
109
+ """
110
+
111
+ by_short: Mapping[int, uuid.UUID]
112
+ by_node: Mapping[uuid.UUID, int]
113
+ next_short_id: int
114
+
115
+
116
+ class ShortIdMap:
117
+ """Document-local bidirectional short_id <-> node_id map ({p097}).
118
+
119
+ Maintains a monotonic ``next_short_id`` counter: a short_id, once
120
+ issued, is never reused after a node delete (:meth:`release`) or a
121
+ rollback (:meth:`restore` to an earlier snapshot). Gaps in the
122
+ sequence are expected and allowed.
123
+ """
124
+
125
+ def __init__(self, next_short_id: int = 1) -> None:
126
+ """Create an empty bidirectional map with the given start counter."""
127
+
128
+ self._by_short: Dict[int, uuid.UUID] = {}
129
+ self._by_node: Dict[uuid.UUID, int] = {}
130
+ self._next_short_id: int = next_short_id
131
+
132
+ def allocate(self, node_id: uuid.UUID) -> int:
133
+ """Assign the next monotonic short_id to ``node_id`` and return it.
134
+
135
+ Stores both map directions and advances the counter. Raises
136
+ :class:`DuplicateNodeIdError` if ``node_id`` already has a
137
+ short_id.
138
+ """
139
+
140
+ if node_id in self._by_node:
141
+ raise DuplicateNodeIdError(
142
+ f"node_id already has a short_id: {node_id!r}"
143
+ )
144
+ short_id = self._next_short_id
145
+ self._by_short[short_id] = node_id
146
+ self._by_node[node_id] = short_id
147
+ self._next_short_id += 1
148
+ return short_id
149
+
150
+ def assign_bulk(self, node_ids: Sequence[uuid.UUID]) -> Dict[uuid.UUID, int]:
151
+ """Allocate fresh short_ids for each of ``node_ids``, in order.
152
+
153
+ Used for ``copy_subtree``, where {p097} requires short_ids to
154
+ always be freshly assigned in the new document. Raises
155
+ :class:`DuplicateNodeIdError` on the first repeated node_id,
156
+ leaving earlier allocations made by this call intact.
157
+ """
158
+
159
+ assigned: Dict[uuid.UUID, int] = {}
160
+ for node_id in node_ids:
161
+ assigned[node_id] = self.allocate(node_id)
162
+ return assigned
163
+
164
+ def get_node_id(self, short_id: int) -> Optional[uuid.UUID]:
165
+ """Return the node_id for ``short_id``, or ``None`` if absent."""
166
+
167
+ return self._by_short.get(short_id)
168
+
169
+ def get_short_id(self, node_id: uuid.UUID) -> Optional[int]:
170
+ """Return the short_id for ``node_id``, or ``None`` if absent."""
171
+
172
+ return self._by_node.get(node_id)
173
+
174
+ def resolve_hex(self, hex_value: str) -> uuid.UUID:
175
+ """Resolve a 0x-prefixed hex short_id to its canonical node_id.
176
+
177
+ Raises :class:`InvalidShortIdHexError` (via :func:`from_hex`) for
178
+ a malformed hex value, or :class:`UnknownShortIdError` if the
179
+ decoded short_id is not present in this map.
180
+ """
181
+
182
+ short_id = from_hex(hex_value)
183
+ node_id = self._by_short.get(short_id)
184
+ if node_id is None:
185
+ raise UnknownShortIdError(f"short_id not found: {hex_value!r}")
186
+ return node_id
187
+
188
+ def release(self, node_id: uuid.UUID) -> None:
189
+ """Remove ``node_id``'s entry from both map directions.
190
+
191
+ Used on node delete. A no-op if ``node_id`` is absent. Never
192
+ decrements the internal counter: the freed integer is never
193
+ reused, per {p097} "no reuse after delete".
194
+ """
195
+
196
+ short_id = self._by_node.pop(node_id, None)
197
+ if short_id is not None:
198
+ self._by_short.pop(short_id, None)
199
+
200
+ def rekey(self, old_node_id: uuid.UUID, new_node_id: uuid.UUID) -> None:
201
+ """Move a short_id from ``old_node_id`` to ``new_node_id`` intact.
202
+
203
+ Used by ``replace_node_id`` to preserve the exact same short_id
204
+ across an id replacement, per {p097}. Raises
205
+ :class:`UnknownShortIdError` if ``old_node_id`` has no short_id,
206
+ or :class:`DuplicateNodeIdError` if ``new_node_id`` already has
207
+ one.
208
+ """
209
+
210
+ short_id = self._by_node.get(old_node_id)
211
+ if short_id is None:
212
+ raise UnknownShortIdError(
213
+ f"old_node_id has no short_id: {old_node_id!r}"
214
+ )
215
+ if new_node_id in self._by_node:
216
+ raise DuplicateNodeIdError(
217
+ f"new_node_id already has a short_id: {new_node_id!r}"
218
+ )
219
+ del self._by_node[old_node_id]
220
+ self._by_node[new_node_id] = short_id
221
+ self._by_short[short_id] = new_node_id
222
+
223
+ def snapshot(self) -> ShortIdMapSnapshot:
224
+ """Return an immutable capture of this map's current state."""
225
+
226
+ return ShortIdMapSnapshot(
227
+ by_short=dict(self._by_short),
228
+ by_node=dict(self._by_node),
229
+ next_short_id=self._next_short_id,
230
+ )
231
+
232
+ def restore(self, snapshot: ShortIdMapSnapshot) -> None:
233
+ """Restore this map's directions from ``snapshot``.
234
+
235
+ The counter is set to ``max(current, snapshot.next_short_id)``:
236
+ rollback must never lower it, so a short_id issued at any point
237
+ (even one later undone by this restore) is never reused, per
238
+ {p097} "no reuse ... after rollback".
239
+ """
240
+
241
+ self._by_short = dict(snapshot.by_short)
242
+ self._by_node = dict(snapshot.by_node)
243
+ self._next_short_id = max(self._next_short_id, snapshot.next_short_id)
244
+
245
+ def merge_insert(self, incoming: Mapping[uuid.UUID, int]) -> Dict[uuid.UUID, int]:
246
+ """Insert a cross-document batch of node_id -> candidate short_id.
247
+
248
+ Iterated in ``incoming`` order. If a node_id is already present
249
+ in this map, raises :class:`DuplicateNodeIdError`. If the
250
+ candidate short_id is free here, it is kept (and the counter is
251
+ advanced past it if needed); otherwise it conflicts and a fresh
252
+ short_id is allocated via the normal monotonic counter instead.
253
+ Returns the final ``node_id -> short_id`` mapping for the whole
254
+ batch. Implements {p097} "cross-document insertion preserves free
255
+ short_ids and remaps conflicting ones".
256
+ """
257
+
258
+ result: Dict[uuid.UUID, int] = {}
259
+ for node_id, candidate_short_id in incoming.items():
260
+ if node_id in self._by_node:
261
+ raise DuplicateNodeIdError(
262
+ f"node_id already present in the map: {node_id!r}"
263
+ )
264
+ if candidate_short_id not in self._by_short:
265
+ final_short_id = candidate_short_id
266
+ self._by_short[final_short_id] = node_id
267
+ self._by_node[node_id] = final_short_id
268
+ if final_short_id >= self._next_short_id:
269
+ self._next_short_id = final_short_id + 1
270
+ else:
271
+ final_short_id = self.allocate(node_id)
272
+ result[node_id] = final_short_id
273
+ return result
274
+
275
+ def to_dict(self) -> dict:
276
+ """Serialize this map for the sibling persistence code ({p100})."""
277
+
278
+ return {
279
+ "entries": {
280
+ str(short_id): str(node_id)
281
+ for short_id, node_id in self._by_short.items()
282
+ },
283
+ "next_short_id": self._next_short_id,
284
+ }
285
+
286
+ @classmethod
287
+ def from_dict(cls, data: dict) -> "ShortIdMap":
288
+ """Deserialize a map previously produced by :meth:`to_dict`."""
289
+
290
+ result = cls(next_short_id=data["next_short_id"])
291
+ for short_id_str, node_id_str in data["entries"].items():
292
+ short_id = int(short_id_str)
293
+ node_id = uuid.UUID(node_id_str)
294
+ result._by_short[short_id] = node_id
295
+ result._by_node[node_id] = short_id
296
+ return result