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,341 @@
1
+ """Local post-mutation reference-integrity validator (concept C-008).
2
+
3
+ Scope (concept C-008, narrowed to *local* post-mutation validation only):
4
+ this module owns exactly one entry point, :func:`validate_after_mutation`,
5
+ that the core mutation and batch-operation surface must call after each
6
+ individual operation is applied -- including every operation inside a
7
+ batch -- to confirm the reference subsystem is still internally consistent
8
+ around the just-changed part of the tree, per {p081}/{p082}.
9
+
10
+ Per {p082}, this validator's scope is strictly bounded: the changed nodes,
11
+ their immediate structural neighbours (parent + direct children), the
12
+ ``NodeAddress`` references touched by the mutation, and the index-map
13
+ entries just updated for those nodes. It never walks the whole tree, and
14
+ its cost never grows with total tree size -- only with the size of the
15
+ touched neighbourhood. On any mismatch the caller's operation is
16
+ considered unsuccessful and must be fully rolled back by the caller; this
17
+ module performs no mutation and no recovery of its own, in any code path.
18
+
19
+ This module owns none of the heavier machinery it checks: the index maps
20
+ and the generation-tracked direct-object cache are owned by the sibling
21
+ ``core/reference_cache.py`` (:class:`~tree_engine.core.reference_cache.ReferenceIndex`,
22
+ :class:`~tree_engine.core.reference_cache.CachedObjectRef`), and the
23
+ canonical ``NodeAddress``/locality helpers are owned by
24
+ ``core/identity.py`` and ``core/references.py``. This file imports and
25
+ reuses their public API and reimplements none of it. Full-document
26
+ validation (global id/short_id uniqueness, external resolver checks,
27
+ cycle detection, version consistency), performed before export/generate/
28
+ storage handoff per {p083}, is out of scope here and belongs to the
29
+ separate integrity-full step.
30
+
31
+ Duck-typed ``tree`` contract, mirroring the rest of this package: ``tree``
32
+ is either a :class:`~tree_engine.core.reference_cache.ReferenceIndex`
33
+ instance itself, or any object exposing one through a ``reference_index``
34
+ attribute -- the shape a later tree/document facade is expected to use.
35
+ A node record registered in the index may optionally expose a
36
+ ``cached_refs`` attribute -- a single
37
+ :class:`~tree_engine.core.reference_cache.CachedObjectRef` or an iterable
38
+ of them -- naming the direct-object cache entries that node currently
39
+ holds; nodes without such an attribute simply contribute no cache checks.
40
+
41
+ Source-of-truth requirement labels honored here: {p080}, {p081}, {p082},
42
+ {p084}.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ from dataclasses import dataclass, field
48
+ from typing import Any, Iterable, Optional, Set, Tuple, Union
49
+ from uuid import UUID
50
+
51
+ from tree_engine.core.identity import NodeAddress
52
+ from tree_engine.core.reference_cache import CachedObjectRef, ReferenceIndex
53
+ from tree_engine.core.references import is_local
54
+
55
+ __all__ = ["IntegrityError", "ValidationSummary", "validate_after_mutation"]
56
+
57
+ #: One touched outgoing reference, either as a bare target address (source
58
+ #: unknown to the caller) or as an explicit ``(source_node_id, address)``
59
+ #: pair -- the shape :meth:`ReferenceIndex.update_references` diffs into.
60
+ TouchedReference = Union[NodeAddress, Tuple[UUID, NodeAddress]]
61
+
62
+
63
+ class IntegrityError(Exception):
64
+ """Raised by :func:`validate_after_mutation` on the first failing check.
65
+
66
+ ``check`` names which local check failed -- one of ``"symmetry"``,
67
+ ``"cache-conformance"``, ``"backlink"``, or ``"local-resolvability"`` --
68
+ and ``message`` names the specific offending node(s)/reference(s), so a
69
+ caller can log/diagnose without re-deriving the failure from scratch.
70
+ Raising this error means the module found the inconsistency; rolling
71
+ the just-applied operation back is entirely the caller's
72
+ responsibility.
73
+ """
74
+
75
+ def __init__(self, check: str, message: str) -> None:
76
+ self.check = check
77
+ super().__init__(f"[{check}] {message}")
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class ValidationSummary:
82
+ """Small, informational success result of :func:`validate_after_mutation`.
83
+
84
+ Counts describe how much the call actually touched, so a caller (or a
85
+ test) can confirm the scope stayed bounded: ``checked_nodes`` is the
86
+ size of the structural scope, ``checked_references`` is the number of
87
+ distinct touched-reference edges examined, and ``checked_caches`` is
88
+ the number of direct-object cache entries examined.
89
+ """
90
+
91
+ checked_nodes: int
92
+ checked_references: int
93
+ checked_caches: int
94
+
95
+
96
+ @dataclass
97
+ class _Scope:
98
+ """The bounded set of nodes/edges a single call must examine ({p082})."""
99
+
100
+ node_ids: Set[UUID] = field(default_factory=set)
101
+ # Edges with a known source: (source_node_id, target_address).
102
+ outgoing_edges: Set[Tuple[UUID, NodeAddress]] = field(default_factory=set)
103
+ # Edges recorded the other way: (target_node_id, source_node_id).
104
+ incoming_edges: Set[Tuple[UUID, UUID]] = field(default_factory=set)
105
+ # Touched addresses whose source the caller did not name.
106
+ loose_addresses: Set[NodeAddress] = field(default_factory=set)
107
+
108
+
109
+ def _index_of(tree: Any) -> ReferenceIndex:
110
+ """Resolve ``tree`` to the :class:`ReferenceIndex` it exposes.
111
+
112
+ Duck-typed: only presence of ``nodes_by_id`` is checked directly;
113
+ every other attribute access below fails naturally with
114
+ ``AttributeError`` if ``tree`` does not actually implement the
115
+ ReferenceIndex API.
116
+ """
117
+
118
+ candidate = getattr(tree, "reference_index", tree)
119
+ if not hasattr(candidate, "nodes_by_id"):
120
+ raise TypeError(
121
+ "tree must be a ReferenceIndex, or expose one via a "
122
+ "'reference_index' attribute"
123
+ )
124
+ return candidate
125
+
126
+
127
+ def _normalize_touched(
128
+ touched_references: Optional[Iterable[TouchedReference]],
129
+ ) -> Iterable[Tuple[Optional[UUID], NodeAddress]]:
130
+ for item in touched_references or ():
131
+ if isinstance(item, NodeAddress):
132
+ yield None, item
133
+ else:
134
+ source_id, address = item
135
+ yield source_id, address
136
+
137
+
138
+ def _scope_from_changed_nodes(
139
+ index: ReferenceIndex,
140
+ changed_node_ids: Iterable[UUID],
141
+ touched_references: Optional[Iterable[TouchedReference]] = None,
142
+ ) -> _Scope:
143
+ """Build the {p082}-bounded scope for one ``validate_after_mutation`` call."""
144
+
145
+ changed_ids = list(dict.fromkeys(changed_node_ids))
146
+ scope = _Scope(node_ids=set(changed_ids))
147
+
148
+ # Immediate structural neighbours: parent + direct children only.
149
+ for node_id in changed_ids:
150
+ parent_id = index.get_parent(node_id)
151
+ if parent_id is not None:
152
+ scope.node_ids.add(parent_id)
153
+ scope.node_ids.update(index.get_children(node_id))
154
+
155
+ # References touched by the mutation: outgoing/incoming edges of the
156
+ # changed nodes themselves, as already recorded in the updated index.
157
+ for node_id in changed_ids:
158
+ for address in index.get_outgoing(node_id):
159
+ scope.outgoing_edges.add((node_id, address))
160
+ for source_id in index.get_incoming(node_id):
161
+ scope.incoming_edges.add((node_id, source_id))
162
+
163
+ # Caller-supplied touched references, additive and equally bounded
164
+ # (their count is fixed by the mutation, never by tree size).
165
+ for source_id, address in _normalize_touched(touched_references):
166
+ if source_id is not None:
167
+ scope.node_ids.add(source_id)
168
+ scope.outgoing_edges.add((source_id, address))
169
+ else:
170
+ scope.loose_addresses.add(address)
171
+ if is_local(address):
172
+ scope.node_ids.add(address.node_id)
173
+
174
+ return scope
175
+
176
+
177
+ def _check_parent_child_symmetry(index: ReferenceIndex, scope: _Scope) -> None:
178
+ for node_id in scope.node_ids:
179
+ parent_id = index.get_parent(node_id)
180
+ if parent_id is not None and node_id not in index.child_index.get(parent_id, ()):
181
+ raise IntegrityError(
182
+ "symmetry",
183
+ f"node {node_id} records parent {parent_id}, but "
184
+ f"{parent_id}'s child_index does not list {node_id} back",
185
+ )
186
+ for child_id in index.child_index.get(node_id, ()):
187
+ recorded_parent = index.get_parent(child_id)
188
+ if recorded_parent != node_id:
189
+ raise IntegrityError(
190
+ "symmetry",
191
+ f"node {node_id} lists child {child_id}, but "
192
+ f"{child_id}'s parent_index points to "
193
+ f"{recorded_parent!r} instead of {node_id}",
194
+ )
195
+
196
+
197
+ def _iter_cached_refs(record: Any) -> Tuple[CachedObjectRef, ...]:
198
+ refs = getattr(record, "cached_refs", None)
199
+ if refs is None:
200
+ return ()
201
+ if isinstance(refs, CachedObjectRef):
202
+ return (refs,)
203
+ return tuple(refs)
204
+
205
+
206
+ def _check_cache_conformance(index: ReferenceIndex, scope: _Scope) -> int:
207
+ """Fast-path-check every cache entry attached to a node in scope.
208
+
209
+ Reuses :class:`CachedObjectRef`'s own fast-path condition ({p084}) by
210
+ reading its two public fields directly, and reuses
211
+ :meth:`ReferenceIndex.resolve_node_id` for the read-only UUID4
212
+ re-resolution -- never :meth:`CachedObjectRef.resolve`, which would
213
+ mutate the entry and violate this module's read-only contract. A
214
+ fast-path mismatch is never silently accepted: it always raises,
215
+ whether or not the target still resolves elsewhere.
216
+ """
217
+
218
+ checked = 0
219
+ for node_id in scope.node_ids:
220
+ entry = index.nodes_by_id.get(node_id)
221
+ if entry is None:
222
+ continue
223
+ for cache_ref in _iter_cached_refs(entry.record):
224
+ checked += 1
225
+ target_id = cache_ref.node_address.node_id
226
+ live_entry = index.nodes_by_id.get(target_id)
227
+ fast_path_ok = (
228
+ live_entry is not None
229
+ and live_entry.generation == cache_ref.cached_generation
230
+ and live_entry.record is cache_ref.cached_object
231
+ )
232
+ if fast_path_ok:
233
+ continue
234
+
235
+ resolved_entry = index.resolve_node_id(target_id)
236
+ if resolved_entry is None:
237
+ raise IntegrityError(
238
+ "cache-conformance",
239
+ f"node {node_id}'s cached_object for "
240
+ f"{cache_ref.node_address!r} cannot be re-resolved: "
241
+ f"{target_id} is not present in the reference index",
242
+ )
243
+ raise IntegrityError(
244
+ "cache-conformance",
245
+ f"node {node_id}'s cached_object for "
246
+ f"{cache_ref.node_address!r} is stale "
247
+ f"(cached_generation={cache_ref.cached_generation}, "
248
+ f"live generation={resolved_entry.generation}); a stale "
249
+ "cache is never silently accepted",
250
+ )
251
+ return checked
252
+
253
+
254
+ def _check_backlinks(index: ReferenceIndex, scope: _Scope) -> None:
255
+ """Check backlink symmetry for edges whose endpoints both resolve.
256
+
257
+ An edge naming a target/source not present in ``nodes_by_id`` at all
258
+ is not a backlink-symmetry question -- it is caught, with its own
259
+ dedicated diagnosis, by :func:`_check_local_resolvability` instead.
260
+ """
261
+
262
+ for source_id, address in scope.outgoing_edges:
263
+ if not is_local(address) or address.node_id not in index.nodes_by_id:
264
+ continue
265
+ if source_id not in index.get_incoming(address.node_id):
266
+ raise IntegrityError(
267
+ "backlink",
268
+ f"outgoing reference {source_id} -> {address.node_id} has "
269
+ f"no matching incoming_refs entry at {address.node_id}",
270
+ )
271
+ for target_id, source_id in scope.incoming_edges:
272
+ if source_id not in index.nodes_by_id:
273
+ continue
274
+ outgoing_targets = {
275
+ addr.node_id for addr in index.get_outgoing(source_id) if is_local(addr)
276
+ }
277
+ if target_id not in outgoing_targets:
278
+ raise IntegrityError(
279
+ "backlink",
280
+ f"incoming reference at {target_id} claims source "
281
+ f"{source_id}, but {source_id}'s outgoing_refs has no "
282
+ f"matching NodeAddress back to {target_id}",
283
+ )
284
+
285
+
286
+ def _check_local_resolvability(index: ReferenceIndex, scope: _Scope) -> None:
287
+ addresses = {addr for _source_id, addr in scope.outgoing_edges}
288
+ addresses.update(scope.loose_addresses)
289
+ for address in addresses:
290
+ if not is_local(address):
291
+ continue # external addresses are out of scope here ({p081}/{p083}).
292
+ if address.node_id not in index.nodes_by_id:
293
+ raise IntegrityError(
294
+ "local-resolvability",
295
+ f"local reference to {address.node_id} does not resolve: "
296
+ f"{address.node_id} is not present in nodes_by_id",
297
+ )
298
+
299
+
300
+ def validate_after_mutation(
301
+ tree: Any,
302
+ changed_node_ids: Iterable[UUID],
303
+ touched_references: Optional[Iterable[TouchedReference]] = None,
304
+ ) -> ValidationSummary:
305
+ """Validate the tree's reference subsystem around one applied mutation.
306
+
307
+ The single entry point the core mutation and batch-operation surface
308
+ must call after each individual operation is applied, including every
309
+ operation inside a batch ({p081}, {p082}). Runs, in order, on the
310
+ {p082}-bounded scope derived from ``changed_node_ids`` (see module
311
+ docstring): parent/child symmetry, direct-object cache conformance,
312
+ backlink correctness, and local resolvability. Raises
313
+ :class:`IntegrityError` on the first failing check; performs no
314
+ mutation, in any code path, whether it succeeds or fails.
315
+
316
+ ``touched_references`` optionally supplements the scope with
317
+ references the caller knows were touched but that ``changed_node_ids``
318
+ alone would not surface (e.g. edges recorded by a call to
319
+ :meth:`ReferenceIndex.update_references`); it accepts either a bare
320
+ :class:`NodeAddress` or an explicit ``(source_node_id, NodeAddress)``
321
+ pair.
322
+
323
+ Returns a :class:`ValidationSummary` on success.
324
+ """
325
+
326
+ index = _index_of(tree)
327
+ scope = _scope_from_changed_nodes(index, changed_node_ids, touched_references)
328
+
329
+ _check_parent_child_symmetry(index, scope)
330
+ checked_caches = _check_cache_conformance(index, scope)
331
+ _check_backlinks(index, scope)
332
+ _check_local_resolvability(index, scope)
333
+
334
+ checked_references = len(scope.outgoing_edges) + len(scope.incoming_edges) + len(
335
+ scope.loose_addresses
336
+ )
337
+ return ValidationSummary(
338
+ checked_nodes=len(scope.node_ids),
339
+ checked_references=checked_references,
340
+ checked_caches=checked_caches,
341
+ )