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,360 @@
1
+ """In-memory reference index and generation-tracked object cache (C-008).
2
+
3
+ Scope (concept C-008, narrowed to the index/object-cache primitives only):
4
+ this module owns two things and nothing else.
5
+
6
+ 1. :class:`ReferenceIndex` — the in-memory bidirectional index maps
7
+ (identity, short_id, parent/child structure, outgoing/incoming
8
+ ``NodeAddress`` references) and their synchronous, per-operation update
9
+ API. Per {p042} and {p081}, every applied mutation — including each
10
+ individual operation inside a batch — must update the maps for the
11
+ affected nodes/edges immediately, before any following lookup or
12
+ mutation runs; resolution is always direct ``dict`` access, never tree
13
+ traversal. Every mutation that touches a node's identity, structure, or
14
+ references bumps that node's own integer generation counter.
15
+ 2. :class:`CachedObjectRef` — a derived direct-object reference cache
16
+ entry. Per {p080}/{p084}, ``NodeAddress`` is the sole canonical source
17
+ of truth; a cached object is only an accelerating derivative that is
18
+ valid exactly while its recorded generation matches the target's
19
+ current generation in the index AND the cached object is (identity)
20
+ the live record held there. Otherwise it is re-resolved by UUID4, or
21
+ :class:`ReferenceIntegrityError` is raised when the target cannot be
22
+ found. Invalidation is strictly per-target: mutating one node's record
23
+ must never force re-resolution of caches pointing at unrelated nodes.
24
+
25
+ Out of scope here, delivered by sibling atomic steps under G-013/T-001:
26
+ node identity/addressing itself (``core/identity.py``), the reference
27
+ string-form helpers (``core/references.py``), local post-mutation
28
+ validation, and full-document validation. This module performs no I/O and
29
+ defines no export/generate hooks or validators of its own; it is pure
30
+ in-memory bookkeeping plus the resolve API described above.
31
+
32
+ Source-of-truth requirement labels honored here: {p042}, {p080}, {p081},
33
+ {p084}.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from dataclasses import dataclass
39
+ from typing import Any, Dict, FrozenSet, Iterable, Optional, Set
40
+ from uuid import UUID
41
+
42
+ from tree_engine.core.identity import NodeAddress
43
+ from tree_engine.core.references import is_local
44
+
45
+ __all__ = [
46
+ "ReferenceIntegrityError",
47
+ "NodeEntry",
48
+ "ReferenceIndex",
49
+ "CachedObjectRef",
50
+ ]
51
+
52
+
53
+ class ReferenceIntegrityError(Exception):
54
+ """Raised by :meth:`CachedObjectRef.resolve` on an explicit integrity failure.
55
+
56
+ Covers exactly the case where a ``NodeAddress`` cannot be re-resolved
57
+ to a live record through the :class:`ReferenceIndex` — its
58
+ ``node_id`` is simply absent from ``nodes_by_id``. Never raised for a
59
+ successful fast-path or slow-path resolution, and never raised by
60
+ :class:`ReferenceIndex`'s own update API, which only maintains maps
61
+ and never judges resolvability.
62
+ """
63
+
64
+
65
+ @dataclass
66
+ class NodeEntry:
67
+ """One ``nodes_by_id`` record: the live node object plus its generation.
68
+
69
+ Deliberately mutable and exposed as a plain attribute-bearing object
70
+ (not frozen) so that direct dict access — ``index.nodes_by_id[id]`` —
71
+ is the only operation either side of the cache contract ever needs,
72
+ per {p042}'s "no tree traversal" rule. ``record`` is whatever node
73
+ object the caller registered; this module does not constrain its
74
+ type. ``generation`` starts at ``0`` and is incremented by
75
+ :class:`ReferenceIndex` on every mutation that touches this node's
76
+ identity, structure, or references, per {p084}.
77
+ """
78
+
79
+ node_id: UUID
80
+ record: Any
81
+ generation: int = 0
82
+
83
+
84
+ class ReferenceIndex:
85
+ """Synchronously maintained in-memory reference/structure index.
86
+
87
+ All maps below are public attributes, not accessors, precisely so
88
+ that resolution and (in tests) inspection is always a direct O(1)
89
+ dict/set operation:
90
+
91
+ * ``nodes_by_id``: ``node_id -> NodeEntry`` (record + generation).
92
+ * ``short_id_to_node_id`` / ``node_id_to_short_id``: bidirectional
93
+ document-local short_id map.
94
+ * ``parent_index``: ``child_id -> parent_id``.
95
+ * ``child_index``: ``parent_id -> set of child_id``.
96
+ * ``outgoing_refs``: ``node_id -> set of NodeAddress`` it references.
97
+ * ``incoming_refs``: ``target node_id -> set of referencing node_id``,
98
+ populated only for local targets (``is_local``): an external
99
+ ``NodeAddress`` names a node_id that belongs to another document's
100
+ own index, so this index never records it as an incoming edge.
101
+
102
+ Every method below mutates only the entries for the nodes/edges it is
103
+ actually told about, and returns only after those maps are fully
104
+ consistent — there is no deferred rebuild step, per {p042}/{p081}.
105
+ """
106
+
107
+ def __init__(self) -> None:
108
+ self.nodes_by_id: Dict[UUID, NodeEntry] = {}
109
+ self.short_id_to_node_id: Dict[int, UUID] = {}
110
+ self.node_id_to_short_id: Dict[UUID, int] = {}
111
+ self.parent_index: Dict[UUID, UUID] = {}
112
+ self.child_index: Dict[UUID, Set[UUID]] = {}
113
+ self.outgoing_refs: Dict[UUID, Set[NodeAddress]] = {}
114
+ self.incoming_refs: Dict[UUID, Set[UUID]] = {}
115
+
116
+ # -- registration ---------------------------------------------------
117
+
118
+ def register_node(
119
+ self,
120
+ node_id: UUID,
121
+ record: Any,
122
+ *,
123
+ parent_id: Optional[UUID] = None,
124
+ short_id: Optional[int] = None,
125
+ ) -> None:
126
+ """Register a new node at generation 0 and index its edges.
127
+
128
+ Raises ``ValueError`` if ``node_id`` is already registered, or if
129
+ ``short_id`` collides with one already in use. On any failure
130
+ nothing is mutated.
131
+ """
132
+
133
+ if node_id in self.nodes_by_id:
134
+ raise ValueError(f"node_id already registered: {node_id!r}")
135
+ if short_id is not None and short_id in self.short_id_to_node_id:
136
+ raise ValueError(f"short_id already in use: {short_id!r}")
137
+
138
+ self.nodes_by_id[node_id] = NodeEntry(node_id=node_id, record=record)
139
+ self.outgoing_refs[node_id] = set()
140
+
141
+ if short_id is not None:
142
+ self.short_id_to_node_id[short_id] = node_id
143
+ self.node_id_to_short_id[node_id] = short_id
144
+
145
+ if parent_id is not None:
146
+ self.parent_index[node_id] = parent_id
147
+ self.child_index.setdefault(parent_id, set()).add(node_id)
148
+
149
+ def unregister_node(self, node_id: UUID) -> None:
150
+ """Remove a node and every index entry that names it.
151
+
152
+ Detaches it from its parent's child set, drops its short_id
153
+ mapping, discards its outgoing references (mirroring each removal
154
+ into the target's ``incoming_refs``), and drops any
155
+ ``incoming_refs`` entry recorded under this node_id as a target.
156
+ Raises ``ValueError`` if ``node_id`` is not registered.
157
+ """
158
+
159
+ if node_id not in self.nodes_by_id:
160
+ raise ValueError(f"node_id not registered: {node_id!r}")
161
+
162
+ parent_id = self.parent_index.pop(node_id, None)
163
+ if parent_id is not None:
164
+ self._discard_child(parent_id, node_id)
165
+ self.child_index.pop(node_id, None)
166
+
167
+ short_id = self.node_id_to_short_id.pop(node_id, None)
168
+ if short_id is not None:
169
+ self.short_id_to_node_id.pop(short_id, None)
170
+
171
+ targets = self.outgoing_refs.pop(node_id, set())
172
+ for target in targets:
173
+ if is_local(target):
174
+ self._discard_incoming(target.node_id, node_id)
175
+
176
+ self.incoming_refs.pop(node_id, None)
177
+ del self.nodes_by_id[node_id]
178
+
179
+ # -- structural mutation ---------------------------------------------
180
+
181
+ def reparent(self, node_id: UUID, new_parent_id: UUID) -> None:
182
+ """Move ``node_id`` to ``new_parent_id`` and bump its generation.
183
+
184
+ Updates ``parent_index`` and both the old and new ``child_index``
185
+ entries synchronously, in this call, before returning. Raises
186
+ ``ValueError`` if ``node_id`` is not registered.
187
+ """
188
+
189
+ if node_id not in self.nodes_by_id:
190
+ raise ValueError(f"node_id not registered: {node_id!r}")
191
+
192
+ old_parent_id = self.parent_index.get(node_id)
193
+ if old_parent_id is not None:
194
+ self._discard_child(old_parent_id, node_id)
195
+
196
+ self.parent_index[node_id] = new_parent_id
197
+ self.child_index.setdefault(new_parent_id, set()).add(node_id)
198
+ self._bump_generation(node_id)
199
+
200
+ def update_references(
201
+ self,
202
+ node_id: UUID,
203
+ old_targets: Iterable[NodeAddress],
204
+ new_targets: Iterable[NodeAddress],
205
+ ) -> None:
206
+ """Replace ``node_id``'s outgoing references and bump its generation.
207
+
208
+ ``old_targets`` is the previously registered set (as returned by
209
+ :attr:`outgoing_refs` before the call); ``new_targets`` is the
210
+ full replacement set. Only the symmetric difference is touched:
211
+ removed local targets lose ``node_id`` from their
212
+ ``incoming_refs`` entry, added local targets gain it, both within
213
+ this same call, per {p081}. Raises ``ValueError`` if ``node_id``
214
+ is not registered.
215
+ """
216
+
217
+ if node_id not in self.nodes_by_id:
218
+ raise ValueError(f"node_id not registered: {node_id!r}")
219
+
220
+ old_set = set(old_targets)
221
+ new_set = set(new_targets)
222
+
223
+ for target in old_set - new_set:
224
+ if is_local(target):
225
+ self._discard_incoming(target.node_id, node_id)
226
+ for target in new_set - old_set:
227
+ if is_local(target):
228
+ self.incoming_refs.setdefault(target.node_id, set()).add(node_id)
229
+
230
+ self.outgoing_refs[node_id] = new_set
231
+ self._bump_generation(node_id)
232
+
233
+ # -- lookups (direct dict access only, per {p042}) --------------------
234
+
235
+ def get_generation(self, node_id: UUID) -> Optional[int]:
236
+ """Return ``node_id``'s current generation, or ``None`` if absent."""
237
+
238
+ entry = self.nodes_by_id.get(node_id)
239
+ return entry.generation if entry is not None else None
240
+
241
+ def resolve_node_id(self, node_id: UUID) -> Optional[NodeEntry]:
242
+ """Direct O(1) re-resolution of ``node_id`` to its current entry.
243
+
244
+ This is the slow-path lookup :class:`CachedObjectRef` calls when
245
+ its fast path is not valid; it is never consulted on the fast
246
+ path, which checks generation and object identity directly
247
+ against ``nodes_by_id`` instead. Returns ``None`` when ``node_id``
248
+ is not registered — callers that need an integrity error (such as
249
+ :meth:`CachedObjectRef.resolve`) raise it themselves.
250
+ """
251
+
252
+ return self.nodes_by_id.get(node_id)
253
+
254
+ def get_parent(self, node_id: UUID) -> Optional[UUID]:
255
+ """Return ``node_id``'s current parent_id, or ``None`` if root/absent."""
256
+
257
+ return self.parent_index.get(node_id)
258
+
259
+ def get_children(self, node_id: UUID) -> FrozenSet[UUID]:
260
+ """Return a snapshot of ``node_id``'s current child ids."""
261
+
262
+ return frozenset(self.child_index.get(node_id, ()))
263
+
264
+ def get_outgoing(self, node_id: UUID) -> FrozenSet[NodeAddress]:
265
+ """Return a snapshot of ``node_id``'s current outgoing references."""
266
+
267
+ return frozenset(self.outgoing_refs.get(node_id, ()))
268
+
269
+ def get_incoming(self, node_id: UUID) -> FrozenSet[UUID]:
270
+ """Return a snapshot of the node ids that reference ``node_id`` locally."""
271
+
272
+ return frozenset(self.incoming_refs.get(node_id, ()))
273
+
274
+ # -- internal helpers --------------------------------------------------
275
+
276
+ def _discard_child(self, parent_id: UUID, child_id: UUID) -> None:
277
+ siblings = self.child_index.get(parent_id)
278
+ if siblings is None:
279
+ return
280
+ siblings.discard(child_id)
281
+ if not siblings:
282
+ del self.child_index[parent_id]
283
+
284
+ def _discard_incoming(self, target_node_id: UUID, referencing_node_id: UUID) -> None:
285
+ refs = self.incoming_refs.get(target_node_id)
286
+ if refs is None:
287
+ return
288
+ refs.discard(referencing_node_id)
289
+ if not refs:
290
+ del self.incoming_refs[target_node_id]
291
+
292
+ def _bump_generation(self, node_id: UUID) -> None:
293
+ entry = self.nodes_by_id.get(node_id)
294
+ if entry is not None:
295
+ entry.generation += 1
296
+
297
+
298
+ @dataclass
299
+ class CachedObjectRef:
300
+ """A derived, generation-scoped direct-object reference cache entry.
301
+
302
+ Per {p080}, ``node_address`` is the canonical source of truth and
303
+ this cache carries no independent authority; per {p084}, its fast
304
+ path is valid only while ``cached_generation`` still matches the
305
+ target's live generation in the index AND ``cached_object`` is
306
+ (identity) the live record. Both conditions are checked, because
307
+ generation alone does not prove the same object is still installed
308
+ (an index entry could in principle be repointed without a generation
309
+ bump, or vice versa) — either mismatch alone forces re-resolution.
310
+ """
311
+
312
+ node_address: NodeAddress
313
+ cached_generation: int
314
+ cached_object: Any
315
+
316
+ @classmethod
317
+ def create(cls, index: "ReferenceIndex", node_address: NodeAddress) -> "CachedObjectRef":
318
+ """Build a freshly resolved cache entry for ``node_address``.
319
+
320
+ Raises :class:`ReferenceIntegrityError` if ``node_address`` does
321
+ not resolve in ``index`` right now.
322
+ """
323
+
324
+ ref = cls(node_address=node_address, cached_generation=-1, cached_object=None)
325
+ ref.resolve(index)
326
+ return ref
327
+
328
+ def resolve(self, index: "ReferenceIndex") -> Any:
329
+ """Return the live object ``node_address`` currently addresses.
330
+
331
+ Fast path (no call into :meth:`ReferenceIndex.resolve_node_id`):
332
+ valid only when ``index.nodes_by_id`` still holds an entry for
333
+ this node_id whose generation equals ``cached_generation`` and
334
+ whose record *is* ``cached_object``. Otherwise, re-resolves by
335
+ UUID4 through :meth:`ReferenceIndex.resolve_node_id`, refreshes
336
+ both ``cached_generation`` and ``cached_object`` on success, and
337
+ raises :class:`ReferenceIntegrityError` when the target cannot be
338
+ found. A mutation elsewhere in the index never affects this
339
+ method's outcome for an untouched target, per {p084}.
340
+ """
341
+
342
+ node_id = self.node_address.node_id
343
+ live_entry = index.nodes_by_id.get(node_id)
344
+ if (
345
+ live_entry is not None
346
+ and live_entry.generation == self.cached_generation
347
+ and live_entry.record is self.cached_object
348
+ ):
349
+ return self.cached_object
350
+
351
+ resolved_entry = index.resolve_node_id(node_id)
352
+ if resolved_entry is None:
353
+ raise ReferenceIntegrityError(
354
+ f"cannot resolve NodeAddress(document_id={self.node_address.document_id!r}, "
355
+ f"node_id={node_id!r}): node_id is not present in the reference index"
356
+ )
357
+
358
+ self.cached_generation = resolved_entry.generation
359
+ self.cached_object = resolved_entry.record
360
+ return self.cached_object
@@ -0,0 +1,223 @@
1
+ """Canonical reference-representation helpers for concept C-008 (ReferenceIntegrity).
2
+
3
+ Scope (concept C-008, narrowed to the reference-representation surface
4
+ only): this module adds the small set of pure helpers that sit directly on
5
+ top of the canonical ``NodeAddress`` value type — locality classification,
6
+ external string-form parsing, and external string-form serialization. It
7
+ owns none of the heavier C-008 machinery: no index maps, no derived
8
+ object-reference cache, no generation-based cache invalidation, no
9
+ post-mutation local validation, and no full-document validation. Those are
10
+ delivered by sibling atomic steps under G-013/T-001 (and, for the object
11
+ cache specifically, the step tied to the ``generation-tracked-object-cache``
12
+ output). This file also contains no tree traversal and no mutation logic.
13
+
14
+ Dual-representation contract, per {p080}: references between nodes are
15
+ carried by two consistent representations. The canonical one is
16
+ ``NodeAddress(document_id, node_id)``, imported unchanged from the sibling
17
+ C-004 identity module (``tree_engine.core.identity``) — this module does
18
+ NOT define a second ``NodeAddress`` type. For an intra-document reference,
19
+ ``document_id`` may be held implicitly in memory as "the current document"
20
+ (represented here, per the C-004 contract, as ``document_id is None``);
21
+ but when such a reference is serialized to its external string form, the
22
+ document identifier is always made explicit. ``NodeAddress`` is the
23
+ canonical source of truth; a direct object reference is only a derived,
24
+ accelerating cache with no independent authority over identity — that
25
+ cache (and its generation-based invalidation) is owned by a sibling
26
+ artifact, not by this file.
27
+
28
+ External string-form grammar, shared with and kept round-trippable
29
+ against the C-004 addressing contract in ``core/address.py``:
30
+
31
+ "<document_id>:<node_id>"
32
+
33
+ where ``<document_id>`` and ``<node_id>`` are each the canonical
34
+ hyphenated ``uuid.UUID`` string form (e.g.
35
+ ``"550e8400-e29b-41d4-a716-446655440000"``), separated by exactly one
36
+ ``":"`` character, with no leading, trailing, or embedded whitespace and
37
+ no additional segments. Parsing performs no I/O, no document loading, and
38
+ no resolvability check of any kind — it only accepts or rejects the
39
+ syntactic shape of the text and, on acceptance, builds the corresponding
40
+ explicit-``document_id`` ``NodeAddress``. Whether either UUID actually
41
+ identifies something that exists is a question for local or full
42
+ validation, both delivered by sibling steps.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ from typing import Optional
48
+ from uuid import UUID
49
+
50
+ from tree_engine.core.identity import NodeAddress
51
+ from tree_engine.errors import ErrorCode, error_layer
52
+
53
+ __all__ = [
54
+ "InvalidNodeAddressError",
55
+ "is_local",
56
+ "is_external",
57
+ "parse_node_address",
58
+ "node_address_to_string",
59
+ ]
60
+
61
+
62
+ class InvalidNodeAddressError(ValueError):
63
+ """Raised when a NodeAddress external string form cannot be produced or parsed.
64
+
65
+ Covers exactly two situations, both purely syntactic / representational
66
+ — never a resolvability or existence check, which belongs to sibling
67
+ local/full validation steps:
68
+
69
+ * ``parse_node_address`` was given text that does not match the
70
+ ``"<document_id>:<node_id>"`` grammar (bad UUID segment, wrong
71
+ separator count, missing or extra parts, empty string).
72
+ * ``node_address_to_string`` was asked to serialize a local
73
+ (``document_id is None``) address without an explicit
74
+ ``current_document_id`` to substitute, so no document identifier is
75
+ available to emit.
76
+
77
+ Carries the stable ``ErrorCode``/``ErrorLayer`` pair from the shared
78
+ catalog in ``tree_engine.errors`` (see {p023}) instead of inventing a
79
+ new ad-hoc error identifier: ``ErrorCode.INVALID_SELECTOR`` is the
80
+ closest existing catalog entry for "the reference text/shape handed in
81
+ is malformed", as distinct from ``ErrorCode.UNRESOLVED_REFERENCE``,
82
+ which names a semantic resolution failure this module never performs.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ message: str,
88
+ *,
89
+ code: ErrorCode = ErrorCode.INVALID_SELECTOR,
90
+ ) -> None:
91
+ super().__init__(message)
92
+ self.code = code
93
+ self.layer = error_layer(code)
94
+
95
+
96
+ def is_local(address: NodeAddress) -> bool:
97
+ """Return ``True`` iff ``address`` is in the implicit-current-document form.
98
+
99
+ Per {p080}, an intra-document reference may hold ``document_id``
100
+ implicitly as "the current document"; the imported C-004
101
+ ``NodeAddress`` contract represents that implicit form as
102
+ ``document_id is None``. This is a pure field check: no I/O, no
103
+ resolvability check, no lookup against any document or index.
104
+ """
105
+
106
+ return address.document_id is None
107
+
108
+
109
+ def is_external(address: NodeAddress) -> bool:
110
+ """Return ``True`` iff ``address`` carries an explicit ``document_id``.
111
+
112
+ The exact negation of :func:`is_local`. An "external" address here
113
+ means only "this instance names its document explicitly" — it says
114
+ nothing about whether that document is loaded or whether the address
115
+ actually resolves to a real node; both are questions for sibling
116
+ local/full validation steps, never answered here.
117
+ """
118
+
119
+ return not is_local(address)
120
+
121
+
122
+ def _parse_uuid_segment(segment: str, *, what: str, original_text: str) -> UUID:
123
+ """Parse one ``:``-delimited segment of an external address as a UUID.
124
+
125
+ Raises :class:`InvalidNodeAddressError` when ``segment`` is empty or is
126
+ not a syntactically valid UUID. This performs no interpretation beyond
127
+ UUID syntax: it does not require UUID version 4 specifically, since the
128
+ address grammar's job is only to recognize the ``"a:b"`` shape, not to
129
+ police identifier-generation policy (that is owned by the C-004
130
+ identity module for freshly minted ids).
131
+ """
132
+
133
+ if not segment:
134
+ raise InvalidNodeAddressError(
135
+ f"malformed node address {original_text!r}: {what} segment is empty"
136
+ )
137
+ try:
138
+ return UUID(segment)
139
+ except (ValueError, AttributeError, TypeError) as exc:
140
+ raise InvalidNodeAddressError(
141
+ f"malformed node address {original_text!r}: {what} segment "
142
+ f"{segment!r} is not a valid UUID"
143
+ ) from exc
144
+
145
+
146
+ def parse_node_address(text: str) -> NodeAddress:
147
+ """Parse the external string form into a ``NodeAddress`` with an explicit document_id.
148
+
149
+ Accepts only text matching the ``"<document_id>:<node_id>"`` grammar
150
+ documented at module level: exactly one ``":"`` separator and two
151
+ non-empty UUID segments. Performs no I/O, no document loading, and no
152
+ resolvability check of any kind — local and full validation are owned
153
+ by sibling steps under G-013/T-001.
154
+
155
+ Raises :class:`InvalidNodeAddressError` for every syntactically
156
+ malformed input, including (non-exhaustively): a non-string argument,
157
+ the empty string, text with no ``":"`` separator, text with more than
158
+ one ``":"`` (extra segments), a missing document_id or node_id
159
+ segment, and a segment that is not a syntactically valid UUID.
160
+
161
+ On success, always returns a ``NodeAddress`` whose ``document_id`` is
162
+ not ``None`` — the external form has no implicit-document case, per
163
+ {p080} ("at serialization of an external reference, document_id is
164
+ given explicitly").
165
+ """
166
+
167
+ if not isinstance(text, str):
168
+ raise InvalidNodeAddressError(
169
+ f"malformed node address: expected a str, got {type(text).__name__}"
170
+ )
171
+
172
+ parts = text.split(":")
173
+ if len(parts) != 2:
174
+ raise InvalidNodeAddressError(
175
+ f"malformed node address {text!r}: expected exactly one ':' "
176
+ f"separator (document_id:node_id), found {len(parts) - 1}"
177
+ )
178
+
179
+ document_part, node_part = parts
180
+ document_id = _parse_uuid_segment(document_part, what="document_id", original_text=text)
181
+ node_id = _parse_uuid_segment(node_part, what="node_id", original_text=text)
182
+
183
+ return NodeAddress(document_id=document_id, node_id=node_id)
184
+
185
+
186
+ def node_address_to_string(
187
+ address: NodeAddress,
188
+ current_document_id: Optional[UUID] = None,
189
+ ) -> str:
190
+ """Serialize ``address`` to its external string form with an explicit document_id.
191
+
192
+ Per {p080}, an external serialization always names its document
193
+ explicitly, even when the in-memory ``NodeAddress`` held it implicitly
194
+ as "the current document" (``document_id is None``). Contract:
195
+
196
+ * If ``address.document_id`` is already set, it is used verbatim and
197
+ ``current_document_id`` is ignored (no conflict check is performed
198
+ between the two — the instance's own explicit id always wins, since
199
+ it unambiguously already names one document).
200
+ * If ``address.document_id`` is ``None`` (the local/implicit case),
201
+ the caller MUST supply ``current_document_id`` so a document
202
+ identifier is available to emit; when both are ``None``, no
203
+ document identifier exists to serialize and
204
+ :class:`InvalidNodeAddressError` is raised instead of silently
205
+ guessing or omitting it.
206
+
207
+ The output always matches the ``"<document_id>:<node_id>"`` grammar
208
+ parsed by :func:`parse_node_address`, using each UUID's canonical
209
+ hyphenated string form, so round-tripping through
210
+ ``parse_node_address(node_address_to_string(addr))`` reproduces an
211
+ equal ``NodeAddress`` whenever ``addr`` already carries an explicit
212
+ ``document_id``.
213
+ """
214
+
215
+ document_id = address.document_id if address.document_id is not None else current_document_id
216
+ if document_id is None:
217
+ raise InvalidNodeAddressError(
218
+ "cannot serialize NodeAddress to its external string form: "
219
+ "address.document_id is None (implicit current-document form) "
220
+ "and no current_document_id was supplied to substitute"
221
+ )
222
+
223
+ return f"{document_id}:{address.node_id}"