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.
- ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
- tree_engine/PUBLIC_API.md +161 -0
- tree_engine/__init__.py +327 -0
- tree_engine/checks/__init__.py +60 -0
- tree_engine/checks/builtin/__init__.py +5 -0
- tree_engine/checks/builtin/compile_check.py +53 -0
- tree_engine/checks/builtin/csv_syntax.py +51 -0
- tree_engine/checks/builtin/docstrings.py +211 -0
- tree_engine/checks/builtin/encoding.py +55 -0
- tree_engine/checks/builtin/fleet_rules.py +227 -0
- tree_engine/checks/builtin/format_syntax.py +82 -0
- tree_engine/checks/builtin/jsonl_syntax.py +49 -0
- tree_engine/checks/builtin/shipped.py +52 -0
- tree_engine/checks/builtin/syntax.py +118 -0
- tree_engine/checks/builtin/xml_wellformed.py +51 -0
- tree_engine/checks/chain.py +332 -0
- tree_engine/checks/external/__init__.py +5 -0
- tree_engine/checks/external/_base.py +61 -0
- tree_engine/checks/external/bandit.py +53 -0
- tree_engine/checks/external/black.py +48 -0
- tree_engine/checks/external/flake8.py +38 -0
- tree_engine/checks/external/isort.py +38 -0
- tree_engine/checks/external/mypy.py +45 -0
- tree_engine/checks/external/ruff.py +45 -0
- tree_engine/checks/external/runner.py +197 -0
- tree_engine/checks/model.py +110 -0
- tree_engine/checks/options.py +73 -0
- tree_engine/checks/plugin.py +171 -0
- tree_engine/checks/registry.py +349 -0
- tree_engine/core/address.py +376 -0
- tree_engine/core/identifier_map.py +266 -0
- tree_engine/core/identity.py +226 -0
- tree_engine/core/instrumentation.py +399 -0
- tree_engine/core/integrity.py +341 -0
- tree_engine/core/integrity_full.py +382 -0
- tree_engine/core/journal.py +260 -0
- tree_engine/core/journal_compose.py +571 -0
- tree_engine/core/live_tree.py +785 -0
- tree_engine/core/locking.py +188 -0
- tree_engine/core/move.py +585 -0
- tree_engine/core/move_references.py +323 -0
- tree_engine/core/node_types.py +408 -0
- tree_engine/core/nodes.py +348 -0
- tree_engine/core/offsets.py +24 -0
- tree_engine/core/operations.py +825 -0
- tree_engine/core/plugin_boundary.py +160 -0
- tree_engine/core/position_map.py +263 -0
- tree_engine/core/position_transfer.py +512 -0
- tree_engine/core/range_refresh.py +366 -0
- tree_engine/core/reference_cache.py +360 -0
- tree_engine/core/references.py +223 -0
- tree_engine/core/reparse.py +378 -0
- tree_engine/core/short_id.py +296 -0
- tree_engine/core/subtree_apply.py +397 -0
- tree_engine/core/subtree_copy.py +399 -0
- tree_engine/core/transactions.py +397 -0
- tree_engine/core/trivia.py +396 -0
- tree_engine/core/updates.py +398 -0
- tree_engine/core/validation.py +377 -0
- tree_engine/errors.py +104 -0
- tree_engine/exceptions.py +376 -0
- tree_engine/facade.py +4524 -0
- tree_engine/plugins/_statements.py +369 -0
- tree_engine/plugins/bsl/block_edit.py +449 -0
- tree_engine/plugins/bsl/blocks.py +127 -0
- tree_engine/plugins/bsl/checker.py +297 -0
- tree_engine/plugins/bsl/dialects.py +303 -0
- tree_engine/plugins/bsl/generator.py +481 -0
- tree_engine/plugins/bsl/import_map.py +995 -0
- tree_engine/plugins/bsl/plugin.py +452 -0
- tree_engine/plugins/contract.py +355 -0
- tree_engine/plugins/cpp/import_map.py +505 -0
- tree_engine/plugins/cpp/languages.py +99 -0
- tree_engine/plugins/cpp/plugin.py +501 -0
- tree_engine/plugins/csv_format.py +676 -0
- tree_engine/plugins/detachable.py +156 -0
- tree_engine/plugins/fallback.py +421 -0
- tree_engine/plugins/ini_format.py +330 -0
- tree_engine/plugins/json_format.py +813 -0
- tree_engine/plugins/json_pointer.py +203 -0
- tree_engine/plugins/jsonl_format.py +392 -0
- tree_engine/plugins/markdown_format.py +748 -0
- tree_engine/plugins/onec_query_format.py +61 -0
- tree_engine/plugins/parse_position.py +54 -0
- tree_engine/plugins/plain_text.py +1543 -0
- tree_engine/plugins/python/export_map.py +306 -0
- tree_engine/plugins/python/import_map.py +429 -0
- tree_engine/plugins/python/plugin.py +1710 -0
- tree_engine/plugins/registry.py +497 -0
- tree_engine/plugins/scan.py +87 -0
- tree_engine/plugins/selection.py +228 -0
- tree_engine/plugins/sql_format.py +61 -0
- tree_engine/plugins/toml_format.py +1072 -0
- tree_engine/plugins/xml_format.py +911 -0
- tree_engine/plugins/yaml/builder.py +49 -0
- tree_engine/plugins/yaml/emitter.py +225 -0
- tree_engine/plugins/yaml/flow.py +227 -0
- tree_engine/plugins/yaml/plugin.py +458 -0
- tree_engine/plugins/yaml/ranges.py +52 -0
- tree_engine/plugins/yaml/reader.py +359 -0
- tree_engine/plugins/yaml/scanner.py +298 -0
- tree_engine/query/adapter.py +283 -0
- tree_engine/query/engine.py +853 -0
- tree_engine/query/inspection.py +498 -0
- tree_engine/query/outline.py +288 -0
- tree_engine/query/predicates.py +263 -0
- tree_engine/query/rendered_lines.py +46 -0
- tree_engine/query/results.py +206 -0
- tree_engine/query/selector.py +400 -0
- tree_engine/query/xml_query.py +747 -0
- tree_engine/storage/codec.py +400 -0
- tree_engine/storage/document_bridge.py +579 -0
- tree_engine/storage/file_txn.py +459 -0
- tree_engine/storage/history.py +106 -0
- tree_engine/storage/lifecycle.py +622 -0
- tree_engine/storage/schema.py +403 -0
- tree_engine/storage/session_guard.py +398 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""Canonical address-normalization layer for concept C-004 (NodeIdentityAndAddressing).
|
|
2
|
+
|
|
3
|
+
Scope (concept C-004, narrowed to string-form serialization of ``NodeAddress``
|
|
4
|
+
and the mandatory ``normalize_node_address`` entry point): this module owns
|
|
5
|
+
the ``to_str``/``from_str`` external string-form helpers for the imported
|
|
6
|
+
``NodeAddress`` type, the single ``normalize_node_address`` function every
|
|
7
|
+
public node-address operation must call first per {j9rh}, the
|
|
8
|
+
``NodeAddressError`` exception hierarchy, and the {p021} node-view helper
|
|
9
|
+
``build_node_address_view``.
|
|
10
|
+
|
|
11
|
+
ACCEPTANCE NOTE (orchestrator integration decision): the canonical
|
|
12
|
+
``NodeAddress`` and ``AddressRemap`` types are defined in the sibling module
|
|
13
|
+
``tree_engine.core.identity`` -- this file imports ``NodeAddress`` from
|
|
14
|
+
there and never redefines it. This module is read-only with respect to
|
|
15
|
+
document state: no code path here mutates a short_id map, a node table, a
|
|
16
|
+
generation counter, or an allocator.
|
|
17
|
+
|
|
18
|
+
Sibling contract not yet available as an importable module in this worktree
|
|
19
|
+
-- the document-local bidirectional short_id<->UUID4 map (``short_id.py``,
|
|
20
|
+
delivered by a parallel T-001 artifact) -- is consumed here only as a
|
|
21
|
+
caller-injected, duck-typed callable, following the same pattern already
|
|
22
|
+
used by ``core/validation.py`` (``next_short_id``) and ``core/node_types.py``
|
|
23
|
+
(``index_map_hook``): this file never imports that sibling module and never
|
|
24
|
+
stubs a fake replacement for it.
|
|
25
|
+
|
|
26
|
+
``document`` is consumed only through minimal, duck-typed attributes, the
|
|
27
|
+
same convention ``core/identity.py``'s ``replace_node_id`` and
|
|
28
|
+
``core/validation.py``'s ``validate_mutation`` already rely on:
|
|
29
|
+
|
|
30
|
+
* ``document.nodes_by_id`` -- a mapping (supports ``in``) of canonical
|
|
31
|
+
``uuid.UUID`` node_id to node object. Read-only here.
|
|
32
|
+
* ``document.resolve_short_id(short_id: int) -> Sequence[uuid.UUID]`` --
|
|
33
|
+
the short-id-map module's public accessor, consulted only when no
|
|
34
|
+
``resolve_short_id`` callable is explicitly injected into
|
|
35
|
+
:func:`normalize_node_address`. It returns the sequence of node_id
|
|
36
|
+
matches for ``short_id`` (normally zero or one; more than one is treated
|
|
37
|
+
defensively as an ambiguous resolution rather than assumed impossible).
|
|
38
|
+
|
|
39
|
+
Source-of-truth requirement labels honored here: {j9rh}, {p021}, {p080}.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
from dataclasses import dataclass
|
|
45
|
+
from typing import Any, Callable, Optional, Sequence, Union
|
|
46
|
+
from uuid import UUID
|
|
47
|
+
|
|
48
|
+
from tree_engine.core.identity import NodeAddress
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"to_str",
|
|
52
|
+
"serialize",
|
|
53
|
+
"from_str",
|
|
54
|
+
"parse",
|
|
55
|
+
"NodeAddressError",
|
|
56
|
+
"UnknownAddressError",
|
|
57
|
+
"AmbiguousAddressError",
|
|
58
|
+
"ForeignDocumentAddressError",
|
|
59
|
+
"ShortIdResolver",
|
|
60
|
+
"normalize_node_address",
|
|
61
|
+
"NodeAddressView",
|
|
62
|
+
"build_node_address_view",
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
# Duck-typed accessor injected by a caller (or looked up on ``document`` as
|
|
66
|
+
# ``document.resolve_short_id``) to resolve a positive-int short_id to the
|
|
67
|
+
# sequence of matching canonical node_id values. See module docstring.
|
|
68
|
+
ShortIdResolver = Callable[[int], Sequence[UUID]]
|
|
69
|
+
|
|
70
|
+
_HEX_PREFIXES = ("0x", "0X")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# --------------------------------------------------------------------------
|
|
74
|
+
# External string-form serialization ({p080} explicit round-trip form)
|
|
75
|
+
# --------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def to_str(address: NodeAddress) -> str:
|
|
79
|
+
"""Serialize ``address`` to its ``"document_id:node_id"`` string form.
|
|
80
|
+
|
|
81
|
+
Both parts are always emitted explicitly as canonical hyphenated UUID4
|
|
82
|
+
strings, regardless of the implicit-local in-memory form ``NodeAddress``
|
|
83
|
+
otherwise permits. Raises ``ValueError`` when ``address.document_id`` is
|
|
84
|
+
``None`` (the implicit-local form), since no document identifier is
|
|
85
|
+
then available to emit.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
if address.document_id is None:
|
|
89
|
+
raise ValueError(
|
|
90
|
+
"cannot serialize NodeAddress to its string form: document_id "
|
|
91
|
+
"is None (implicit-local form carries no explicit document_id)"
|
|
92
|
+
)
|
|
93
|
+
return f"{address.document_id}:{address.node_id}"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# Alias, per the step spec's "to_str/serialize" naming.
|
|
97
|
+
serialize = to_str
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def from_str(text: str) -> NodeAddress:
|
|
101
|
+
"""Parse the ``"document_id:node_id"`` string form into a ``NodeAddress``.
|
|
102
|
+
|
|
103
|
+
Both parts are required. Raises ``ValueError`` for any malformed input:
|
|
104
|
+
a non-string argument, a missing or extra ``":"`` separator, an empty
|
|
105
|
+
segment, or a segment that is not a syntactically valid UUID.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
if not isinstance(text, str):
|
|
109
|
+
raise ValueError(f"expected a str, got {type(text).__name__}")
|
|
110
|
+
|
|
111
|
+
parts = text.split(":")
|
|
112
|
+
if len(parts) != 2:
|
|
113
|
+
raise ValueError(
|
|
114
|
+
f"malformed node address {text!r}: expected exactly one ':' "
|
|
115
|
+
f"separator (document_id:node_id), found {len(parts) - 1}"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
document_part, node_part = parts
|
|
119
|
+
if not document_part or not node_part:
|
|
120
|
+
raise ValueError(f"malformed node address {text!r}: empty segment")
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
document_id = UUID(document_part)
|
|
124
|
+
node_id = UUID(node_part)
|
|
125
|
+
except (ValueError, AttributeError, TypeError) as exc:
|
|
126
|
+
raise ValueError(f"malformed node address {text!r}: invalid UUID segment") from exc
|
|
127
|
+
|
|
128
|
+
return NodeAddress(document_id=document_id, node_id=node_id)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# Alias, per the step spec's "from_str/parse" naming.
|
|
132
|
+
parse = from_str
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# --------------------------------------------------------------------------
|
|
136
|
+
# Exception hierarchy
|
|
137
|
+
# --------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class NodeAddressError(Exception):
|
|
141
|
+
"""Base error for a rejected node-address normalization.
|
|
142
|
+
|
|
143
|
+
Always carries the offending raw ``address`` argument exactly as given
|
|
144
|
+
to :func:`normalize_node_address`, so a caller can inspect what was
|
|
145
|
+
rejected without re-parsing an error message.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
def __init__(self, raw_address: Any, message: Optional[str] = None) -> None:
|
|
149
|
+
self.raw_address = raw_address
|
|
150
|
+
super().__init__(message or f"invalid node address: {raw_address!r}")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class UnknownAddressError(NodeAddressError):
|
|
154
|
+
"""Raised when ``address`` cannot be resolved to any node of the document.
|
|
155
|
+
|
|
156
|
+
Covers a UUID4 node_id absent from the document's node table and an
|
|
157
|
+
int/hex short_id absent from the document's short_id map.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class AmbiguousAddressError(NodeAddressError):
|
|
162
|
+
"""Raised when short_id resolution defensively detects more than one match.
|
|
163
|
+
|
|
164
|
+
The short_id<->UUID4 map is a bidirectional map and should never
|
|
165
|
+
legitimately produce more than one match for a single short_id; this
|
|
166
|
+
error exists purely as a defensive guard against that invariant being
|
|
167
|
+
violated, rather than an assumption that it cannot happen.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class ForeignDocumentAddressError(NodeAddressError):
|
|
172
|
+
"""Raised when ``address`` explicitly names a document_id other than the current one.
|
|
173
|
+
|
|
174
|
+
Raised immediately, before any local short_id-map or node-table lookup
|
|
175
|
+
is attempted -- ``document_id`` carries the offending foreign document
|
|
176
|
+
identifier.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
def __init__(self, raw_address: Any, document_id: UUID, message: Optional[str] = None) -> None:
|
|
180
|
+
self.document_id = document_id
|
|
181
|
+
super().__init__(
|
|
182
|
+
raw_address,
|
|
183
|
+
message
|
|
184
|
+
or (
|
|
185
|
+
f"node address {raw_address!r} names foreign document_id "
|
|
186
|
+
f"{document_id!r}"
|
|
187
|
+
),
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# --------------------------------------------------------------------------
|
|
192
|
+
# normalize_node_address -- the single mandatory entry point per {j9rh}
|
|
193
|
+
# --------------------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _validate_node_id_presence(document: Any, node_id: UUID, raw_address: Any) -> UUID:
|
|
197
|
+
"""Confirm ``node_id`` is present in ``document.nodes_by_id``, or reject.
|
|
198
|
+
|
|
199
|
+
Pure lookup: never mutates ``document`` or anything reachable from it.
|
|
200
|
+
"""
|
|
201
|
+
|
|
202
|
+
nodes_by_id = getattr(document, "nodes_by_id", None)
|
|
203
|
+
if nodes_by_id is None or node_id not in nodes_by_id:
|
|
204
|
+
raise UnknownAddressError(raw_address)
|
|
205
|
+
return node_id
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _resolve_node_address_value(
|
|
209
|
+
document: Any,
|
|
210
|
+
node_address: NodeAddress,
|
|
211
|
+
raw_address: Any,
|
|
212
|
+
current_document_id: Optional[UUID],
|
|
213
|
+
) -> UUID:
|
|
214
|
+
"""Apply the foreign-document check, then validate the local node_id."""
|
|
215
|
+
|
|
216
|
+
if node_address.document_id is not None and node_address.document_id != current_document_id:
|
|
217
|
+
raise ForeignDocumentAddressError(raw_address, node_address.document_id)
|
|
218
|
+
return _validate_node_id_presence(document, node_address.node_id, raw_address)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _resolve_short_id(
|
|
222
|
+
document: Any,
|
|
223
|
+
short_id: int,
|
|
224
|
+
raw_address: Any,
|
|
225
|
+
resolve_short_id: Optional[ShortIdResolver],
|
|
226
|
+
) -> UUID:
|
|
227
|
+
"""Resolve a positive-int short_id via the injected or duck-typed accessor.
|
|
228
|
+
|
|
229
|
+
Never touches the short-id-map's internal storage directly: it only
|
|
230
|
+
calls the public accessor, either explicitly injected by the caller or
|
|
231
|
+
found as ``document.resolve_short_id``. Read-only: performs no
|
|
232
|
+
mutation regardless of outcome.
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
resolver = resolve_short_id if resolve_short_id is not None else getattr(
|
|
236
|
+
document, "resolve_short_id", None
|
|
237
|
+
)
|
|
238
|
+
if resolver is None:
|
|
239
|
+
# No accessor available at all: the address cannot be resolved.
|
|
240
|
+
raise UnknownAddressError(raw_address)
|
|
241
|
+
|
|
242
|
+
matches = list(resolver(short_id))
|
|
243
|
+
if len(matches) == 0:
|
|
244
|
+
raise UnknownAddressError(raw_address)
|
|
245
|
+
if len(matches) > 1:
|
|
246
|
+
raise AmbiguousAddressError(raw_address)
|
|
247
|
+
return matches[0]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def normalize_node_address(
|
|
251
|
+
document: Any,
|
|
252
|
+
address: Union[UUID, int, str, NodeAddress],
|
|
253
|
+
*,
|
|
254
|
+
current_document_id: Optional[UUID],
|
|
255
|
+
resolve_short_id: Optional[ShortIdResolver] = None,
|
|
256
|
+
) -> UUID:
|
|
257
|
+
"""Resolve any accepted address form to its canonical ``uuid.UUID`` node_id.
|
|
258
|
+
|
|
259
|
+
The single mandatory entry point every public node-address operation
|
|
260
|
+
must call first, per {j9rh}. Accepts ``address`` as:
|
|
261
|
+
|
|
262
|
+
* ``uuid.UUID`` -- a canonical node_id, validated against
|
|
263
|
+
``document.nodes_by_id``.
|
|
264
|
+
* ``int`` -- a positive document-local short_id, resolved through the
|
|
265
|
+
short_id map.
|
|
266
|
+
* ``str`` -- a ``"0x"``-prefixed hex short_id, a DECIMAL-digit short_id,
|
|
267
|
+
a bare UUID string, or a serialized ``"document_id:node_id"``
|
|
268
|
+
``NodeAddress`` (see :func:`from_str`). The decimal form is tried
|
|
269
|
+
before the UUID form and resolves exactly like the ``int`` it spells,
|
|
270
|
+
so ``"3"`` and ``3`` are the same address: callers that carry a
|
|
271
|
+
short_id through a string-typed protocol field -- the editor's
|
|
272
|
+
``node_ref`` is one -- would otherwise fall through every branch and
|
|
273
|
+
be rejected as unknown. Only ASCII digits count, so a non-ASCII
|
|
274
|
+
decimal digit is not silently reinterpreted.
|
|
275
|
+
* ``NodeAddress`` -- resolved directly.
|
|
276
|
+
|
|
277
|
+
A ``NodeAddress``-shaped address (an explicit ``NodeAddress`` instance
|
|
278
|
+
or a serialized string form) whose ``document_id`` differs from
|
|
279
|
+
``current_document_id`` raises :class:`ForeignDocumentAddressError`
|
|
280
|
+
immediately, before any local short_id-map or node-table lookup. An
|
|
281
|
+
unresolvable UUID or short_id raises :class:`UnknownAddressError`. A
|
|
282
|
+
defensively-detected multi-match short_id resolution raises
|
|
283
|
+
:class:`AmbiguousAddressError`. Every rejection path is read-only: no
|
|
284
|
+
mutation of the short_id map, node table, generation counters, or
|
|
285
|
+
allocator state, and no partial operation is ever started.
|
|
286
|
+
|
|
287
|
+
Returns the canonical ``uuid.UUID`` node_id -- the canonicalization
|
|
288
|
+
target per {j9rh} -- never a ``NodeAddress``.
|
|
289
|
+
"""
|
|
290
|
+
|
|
291
|
+
raw_address = address
|
|
292
|
+
|
|
293
|
+
if isinstance(address, NodeAddress):
|
|
294
|
+
return _resolve_node_address_value(document, address, raw_address, current_document_id)
|
|
295
|
+
|
|
296
|
+
if isinstance(address, UUID):
|
|
297
|
+
return _validate_node_id_presence(document, address, raw_address)
|
|
298
|
+
|
|
299
|
+
if isinstance(address, bool):
|
|
300
|
+
# bool is a subclass of int in Python; explicitly not an accepted
|
|
301
|
+
# address form.
|
|
302
|
+
raise UnknownAddressError(raw_address)
|
|
303
|
+
|
|
304
|
+
if isinstance(address, int):
|
|
305
|
+
if address <= 0:
|
|
306
|
+
raise UnknownAddressError(raw_address)
|
|
307
|
+
return _resolve_short_id(document, address, raw_address, resolve_short_id)
|
|
308
|
+
|
|
309
|
+
if isinstance(address, str):
|
|
310
|
+
if address.startswith(_HEX_PREFIXES):
|
|
311
|
+
try:
|
|
312
|
+
short_id = int(address, 16)
|
|
313
|
+
except ValueError:
|
|
314
|
+
raise UnknownAddressError(raw_address) from None
|
|
315
|
+
if short_id <= 0:
|
|
316
|
+
raise UnknownAddressError(raw_address)
|
|
317
|
+
return _resolve_short_id(document, short_id, raw_address, resolve_short_id)
|
|
318
|
+
|
|
319
|
+
if ":" in address:
|
|
320
|
+
try:
|
|
321
|
+
parsed_address = from_str(address)
|
|
322
|
+
except ValueError:
|
|
323
|
+
raise UnknownAddressError(raw_address) from None
|
|
324
|
+
return _resolve_node_address_value(
|
|
325
|
+
document, parsed_address, raw_address, current_document_id
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
if address.isascii() and address.isdigit():
|
|
329
|
+
short_id = int(address)
|
|
330
|
+
if short_id <= 0:
|
|
331
|
+
raise UnknownAddressError(raw_address)
|
|
332
|
+
return _resolve_short_id(document, short_id, raw_address, resolve_short_id)
|
|
333
|
+
|
|
334
|
+
try:
|
|
335
|
+
node_id = UUID(address)
|
|
336
|
+
except ValueError:
|
|
337
|
+
raise UnknownAddressError(raw_address) from None
|
|
338
|
+
return _validate_node_id_presence(document, node_id, raw_address)
|
|
339
|
+
|
|
340
|
+
raise UnknownAddressError(raw_address)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# --------------------------------------------------------------------------
|
|
344
|
+
# View contract per {p021}
|
|
345
|
+
# --------------------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
@dataclass(frozen=True)
|
|
349
|
+
class NodeAddressView:
|
|
350
|
+
"""The pair of identifiers {p021} requires every node view to expose.
|
|
351
|
+
|
|
352
|
+
``short_id_hex`` is the compact, ``"0x"``-prefixed hexadecimal
|
|
353
|
+
rendering used for later re-addressing; ``node_id`` is the canonical
|
|
354
|
+
UUID4 string. ``short_id_hex`` never replaces ``node_id`` -- both are
|
|
355
|
+
always present together.
|
|
356
|
+
"""
|
|
357
|
+
|
|
358
|
+
short_id_hex: str
|
|
359
|
+
node_id: str
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def build_node_address_view(node_id: Union[UUID, str], short_id: int) -> NodeAddressView:
|
|
363
|
+
"""Build the {p021} view pair from a canonical node_id and its short_id.
|
|
364
|
+
|
|
365
|
+
``node_id`` may be given as a ``uuid.UUID`` or its canonical string
|
|
366
|
+
form; ``short_id`` is the positive document-local integer id. Every
|
|
367
|
+
node listing/view assembler elsewhere in the tree engine is expected to
|
|
368
|
+
call this helper so ``short_id_hex`` and ``node_id`` are always
|
|
369
|
+
populated together.
|
|
370
|
+
"""
|
|
371
|
+
|
|
372
|
+
node_id_value = node_id if isinstance(node_id, UUID) else UUID(str(node_id))
|
|
373
|
+
return NodeAddressView(
|
|
374
|
+
short_id_hex=f"0x{int(short_id):x}",
|
|
375
|
+
node_id=str(node_id_value),
|
|
376
|
+
)
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""The three-way identifier map: short_id <-> node_id <-> native reference.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Scope: one uniform correspondence per semantic node across EVERY format -- the
|
|
7
|
+
compact integer ``short_id``, the canonical UUID4 ``node_id``, and, for a format
|
|
8
|
+
whose plugin declares a reference notation of its own, that native reference (a
|
|
9
|
+
JSON Pointer for the data formats). Structural wrapper nodes may deliberately
|
|
10
|
+
have no compact id; they remain UUID-addressable through the document but are
|
|
11
|
+
absent from compact-map enumeration.
|
|
12
|
+
|
|
13
|
+
Two of the three already existed: ``core.short_id.ShortIdMap`` is the
|
|
14
|
+
persisted int<->UUID4 bidirectional map, and ``core.address
|
|
15
|
+
.normalize_node_address`` is the single entry point that canonicalizes an int,
|
|
16
|
+
a ``0x`` hex short_id, a decimal string, a UUID4, or a ``"document:node"``
|
|
17
|
+
string to a UUID4. This module adds the third correspondence and nothing else:
|
|
18
|
+
it never allocates a short_id, never mutates the document, and never
|
|
19
|
+
re-implements address normalization -- it delegates to it.
|
|
20
|
+
|
|
21
|
+
Where the native reference comes from is the design constraint that shaped
|
|
22
|
+
this file. A format is a pluggable module, so the notation is a PLUGIN
|
|
23
|
+
DECLARATION, read here duck-typed off the resolved plugin exactly as
|
|
24
|
+
``facade._fragment`` already reads ``fragment_container_kinds``::
|
|
25
|
+
|
|
26
|
+
plugin.native_reference.notation -> the notation's name
|
|
27
|
+
plugin.native_reference.index(root) -> both directions of the index
|
|
28
|
+
|
|
29
|
+
A plugin that declares nothing simply has no third slot, and the ``ref`` of
|
|
30
|
+
every one of its nodes is ``None``. Nothing here tests the format id, and
|
|
31
|
+
nothing here knows what a JSON Pointer looks like: resolving a reference is a
|
|
32
|
+
dictionary lookup in the index the PLUGIN built, so a format that some day
|
|
33
|
+
speaks XPath needs no change on this side.
|
|
34
|
+
|
|
35
|
+
Position independence is inherited, not re-established. The integer is issued
|
|
36
|
+
by ``ShortIdMap`` against a node's UUID4 and ``TreeDocument.reindex`` keeps
|
|
37
|
+
whatever a node already holds, so inserting a line above a node moves its line
|
|
38
|
+
number and leaves its short_id alone. The native reference is the one
|
|
39
|
+
identifier of the three that is a PATH and therefore genuinely positional: a
|
|
40
|
+
JSON Pointer of ``/items/1`` names whatever now sits at index 1. That is what
|
|
41
|
+
the notation means, and this module reports it as the format defines it rather
|
|
42
|
+
than pretending a path is stable.
|
|
43
|
+
|
|
44
|
+
The ``style`` flag selects which identifier the engine REPORTS. It never
|
|
45
|
+
narrows what the engine ACCEPTS: :meth:`IdentifierMap.resolve` takes all three
|
|
46
|
+
forms under either style, because the map is precisely what makes them
|
|
47
|
+
equivalent. It is a constructor argument on an ordinary object -- there is no
|
|
48
|
+
module-level switch, and no caller can change another caller's reporting.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import enum
|
|
54
|
+
from dataclasses import dataclass
|
|
55
|
+
from typing import Any, Optional, Tuple, Union
|
|
56
|
+
from uuid import UUID
|
|
57
|
+
|
|
58
|
+
from tree_engine.core.address import NodeAddressError, UnknownAddressError, normalize_node_address
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"IdentifierStyle",
|
|
62
|
+
"NodeIdentifiers",
|
|
63
|
+
"native_reference_of",
|
|
64
|
+
"IdentifierMap",
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class IdentifierStyle(str, enum.Enum):
|
|
69
|
+
"""Which of the two document-wide identifiers the engine reports.
|
|
70
|
+
|
|
71
|
+
``SHORT_ID`` is the default because brevity is the reason the integer
|
|
72
|
+
exists at all; ``NODE_ID`` reports the canonical UUID4 for a caller that
|
|
73
|
+
would rather work in it directly. Being a ``str`` enum, either member can
|
|
74
|
+
be passed as its own plain string over a protocol boundary.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
SHORT_ID = "short_id"
|
|
78
|
+
NODE_ID = "node_id"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class NodeIdentifiers:
|
|
83
|
+
"""Every identifier one node answers to, and the one currently reported.
|
|
84
|
+
|
|
85
|
+
``short_id`` and ``node_id`` are always present -- every node enumerated by
|
|
86
|
+
the compact map has both. ``ref`` is the format's own reference for this
|
|
87
|
+
node, or ``None`` when the format declares no notation (plain text, Python,
|
|
88
|
+
BSL) or when this particular node has none the notation can express (a YAML
|
|
89
|
+
comment, a TOML blank line, a JSON object member as distinct from its value).
|
|
90
|
+
``notation`` names the language ``ref`` is written in, and is ``None``
|
|
91
|
+
exactly when the format declares none.
|
|
92
|
+
|
|
93
|
+
``reported`` is what ``style`` selects. It is the ONLY thing ``style``
|
|
94
|
+
changes: the other fields are identical under both settings.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
node_id: UUID
|
|
98
|
+
short_id: int
|
|
99
|
+
ref: Optional[str] = None
|
|
100
|
+
notation: Optional[str] = None
|
|
101
|
+
style: IdentifierStyle = IdentifierStyle.SHORT_ID
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def reported(self) -> Union[int, str]:
|
|
105
|
+
"""The identifier to show: the integer, or the UUID4 as a string."""
|
|
106
|
+
|
|
107
|
+
return self.short_id if self.style is IdentifierStyle.SHORT_ID else str(self.node_id)
|
|
108
|
+
|
|
109
|
+
def with_style(self, style: IdentifierStyle) -> "NodeIdentifiers":
|
|
110
|
+
"""The same three identifiers, reported under ``style`` instead."""
|
|
111
|
+
|
|
112
|
+
return NodeIdentifiers(node_id=self.node_id, short_id=self.short_id, ref=self.ref,
|
|
113
|
+
notation=self.notation, style=IdentifierStyle(style))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def native_reference_of(plugin: Any) -> Optional[Any]:
|
|
117
|
+
"""The reference notation ``plugin`` declares, or ``None``.
|
|
118
|
+
|
|
119
|
+
Duck-typed on purpose, following ``fragment_container_kinds``: a plugin
|
|
120
|
+
opts in by publishing a ``native_reference`` object exposing ``notation``
|
|
121
|
+
and ``index(root)``. An object that does not expose both is not a
|
|
122
|
+
declaration and is ignored rather than half-used, so a partially written
|
|
123
|
+
plugin degrades to "this format has no reference notation" instead of
|
|
124
|
+
failing every address resolution in the document.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
declared = getattr(plugin, "native_reference", None)
|
|
128
|
+
if declared is None:
|
|
129
|
+
return None
|
|
130
|
+
if not isinstance(getattr(declared, "notation", None), str):
|
|
131
|
+
return None
|
|
132
|
+
return declared if callable(getattr(declared, "index", None)) else None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class IdentifierMap:
|
|
136
|
+
"""A document's three-way correspondence, under one reporting style.
|
|
137
|
+
|
|
138
|
+
Built over a live document rather than a copy of it, so the integers and
|
|
139
|
+
UUID4s it reports are the document's own. The native-reference index is
|
|
140
|
+
the one part that has to be derived, and it is derived LAZILY and cached
|
|
141
|
+
against ``document_version``: a caller that never asks for a reference
|
|
142
|
+
never pays for the walk, and an edit that bumps the version invalidates
|
|
143
|
+
the cache instead of serving a stale path.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
__slots__ = ("_document", "_plugin", "_style", "_notation", "_index", "_indexed_version")
|
|
147
|
+
|
|
148
|
+
def __init__(self, document: Any, plugin: Any = None, *,
|
|
149
|
+
style: Union[IdentifierStyle, str] = IdentifierStyle.SHORT_ID) -> None:
|
|
150
|
+
self._document = document
|
|
151
|
+
self._plugin = plugin
|
|
152
|
+
self._style = IdentifierStyle(style)
|
|
153
|
+
self._notation = native_reference_of(plugin)
|
|
154
|
+
self._index: Any = None
|
|
155
|
+
self._indexed_version: Any = None
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def style(self) -> IdentifierStyle:
|
|
159
|
+
"""The style this map reports under; fixed for this object's lifetime."""
|
|
160
|
+
|
|
161
|
+
return self._style
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def notation(self) -> Optional[str]:
|
|
165
|
+
"""The name of this format's reference notation, or ``None``."""
|
|
166
|
+
|
|
167
|
+
return None if self._notation is None else self._notation.notation
|
|
168
|
+
|
|
169
|
+
def with_style(self, style: Union[IdentifierStyle, str]) -> "IdentifierMap":
|
|
170
|
+
"""A second view of the same document reporting under ``style``.
|
|
171
|
+
|
|
172
|
+
A new object rather than a mutation: two callers may hold two styles
|
|
173
|
+
over one document at the same time without either changing the other.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
return IdentifierMap(self._document, self._plugin, style=style)
|
|
177
|
+
|
|
178
|
+
# -- the native-reference index -----------------------------------------
|
|
179
|
+
|
|
180
|
+
def _pointer_index(self) -> Any:
|
|
181
|
+
"""The plugin-built reference index, rebuilt when the document moved."""
|
|
182
|
+
|
|
183
|
+
if self._notation is None:
|
|
184
|
+
return None
|
|
185
|
+
version = getattr(self._document, "document_version", None)
|
|
186
|
+
if self._index is None or self._indexed_version != version:
|
|
187
|
+
self._index = self._notation.index(getattr(self._document, "root", None))
|
|
188
|
+
self._indexed_version = version
|
|
189
|
+
return self._index
|
|
190
|
+
|
|
191
|
+
def ref_for(self, node_id: UUID) -> Optional[str]:
|
|
192
|
+
"""This node's native reference, or ``None`` when it has none."""
|
|
193
|
+
|
|
194
|
+
index = self._pointer_index()
|
|
195
|
+
return None if index is None else index.ref_for(node_id)
|
|
196
|
+
|
|
197
|
+
def node_for_ref(self, ref: Any) -> Optional[UUID]:
|
|
198
|
+
"""The node ``ref`` names, or ``None`` -- unknown ref, or no notation.
|
|
199
|
+
|
|
200
|
+
A pure lookup in the index the plugin built. This module never parses
|
|
201
|
+
the reference itself, which is what keeps the notation entirely inside
|
|
202
|
+
the plugin that speaks it.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
index = self._pointer_index()
|
|
206
|
+
if index is None or not isinstance(ref, str):
|
|
207
|
+
return None
|
|
208
|
+
return index.node_for(ref)
|
|
209
|
+
|
|
210
|
+
# -- resolution and reporting -------------------------------------------
|
|
211
|
+
|
|
212
|
+
def resolve(self, address: Any) -> UUID:
|
|
213
|
+
"""Canonicalize any of the three forms to the node's UUID4.
|
|
214
|
+
|
|
215
|
+
The int/hex/decimal/UUID4/``"document:node"`` forms go through
|
|
216
|
+
``normalize_node_address`` ({j9rh}) untouched, so this adds no second
|
|
217
|
+
address parser. Only when that rejects a STRING is the native-reference
|
|
218
|
+
index consulted, which keeps every existing address form on exactly the
|
|
219
|
+
path it already took and never builds the index for a caller that is
|
|
220
|
+
not using references. An address no form resolves raises the original
|
|
221
|
+
``NodeAddressError``, not a substituted one.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
try:
|
|
225
|
+
return normalize_node_address(
|
|
226
|
+
self._document, address,
|
|
227
|
+
current_document_id=getattr(self._document, "document_id", None),
|
|
228
|
+
resolve_short_id=getattr(self._document, "resolve_short_id", None))
|
|
229
|
+
except NodeAddressError:
|
|
230
|
+
resolved = self.node_for_ref(address)
|
|
231
|
+
if resolved is None:
|
|
232
|
+
raise
|
|
233
|
+
return resolved
|
|
234
|
+
|
|
235
|
+
def identifiers(self, address: Any) -> NodeIdentifiers:
|
|
236
|
+
"""Every identifier of the addressed node, reported under this style."""
|
|
237
|
+
|
|
238
|
+
node_id = self.resolve(address)
|
|
239
|
+
node = getattr(self._document, "nodes_by_id", {}).get(node_id)
|
|
240
|
+
short_id = getattr(node, "short_id", None)
|
|
241
|
+
if not isinstance(short_id, int) or isinstance(short_id, bool):
|
|
242
|
+
# reindex() gives every live node a short_id, so this is a document
|
|
243
|
+
# whose indexes were never built -- report it rather than invent one.
|
|
244
|
+
raise UnknownAddressError(address, f"node {node_id} carries no short_id")
|
|
245
|
+
return NodeIdentifiers(node_id=node_id, short_id=short_id, ref=self.ref_for(node_id),
|
|
246
|
+
notation=self.notation, style=self._style)
|
|
247
|
+
|
|
248
|
+
def report(self, address: Any) -> Union[int, str]:
|
|
249
|
+
"""The single identifier this style reports for the addressed node."""
|
|
250
|
+
|
|
251
|
+
return self.identifiers(address).reported
|
|
252
|
+
|
|
253
|
+
def entries(self) -> Tuple[NodeIdentifiers, ...]:
|
|
254
|
+
"""Every compact-ID-bearing node, ordered by short_id."""
|
|
255
|
+
|
|
256
|
+
nodes = getattr(self._document, "nodes_by_id", {})
|
|
257
|
+
compact = (
|
|
258
|
+
(node.short_id, node_id)
|
|
259
|
+
for node_id, node in nodes.items()
|
|
260
|
+
if isinstance(getattr(node, "short_id", None), int)
|
|
261
|
+
and not isinstance(node.short_id, bool)
|
|
262
|
+
)
|
|
263
|
+
return tuple(
|
|
264
|
+
self.identifiers(node_id)
|
|
265
|
+
for _short_id, node_id in sorted(compact, key=lambda item: item[0])
|
|
266
|
+
)
|