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,288 @@
1
+ """Compact ``model_outline`` response schema for concept C-018 (TreeInspection).
2
+
3
+ Scope (concept C-018, narrowed to the ``drill_down`` response shape and its
4
+ assembly into a serializable form, per HRS fragments {p070} and {p071}): this
5
+ module defines the ``model_outline`` response records -- the single meta
6
+ header, the flat preorder node record, the collapsed-subtree stub record, the
7
+ per-field and whole-response truncation contracts -- plus one assembly
8
+ helper, :func:`build_outline_response`, that stitches an already-built header
9
+ and an already-built ordered record list into the complete response object.
10
+
11
+ Non-goals, left entirely to the sibling ``drill_down`` inspection module:
12
+ tree traversal, address resolution (``normalize_node_address``), depth
13
+ control, auto-expansion decisions driven by ``expand_below_bytes``, and the
14
+ truncation *decisions* (what to cut and where). This file only shapes and
15
+ assembles values its caller already computed; it never walks a
16
+ :class:`tree_engine.core.nodes.Node` graph, never touches
17
+ ``tree_engine.core.short_id.ShortIdMap``, and never reads
18
+ ``tree_engine.core.positions.SubtreeBytesAggregate`` itself -- the caller
19
+ consumes that cache and simply passes the resulting integer (or ``None`` for
20
+ the missing/stale sentinel, per {p067}) into ``subtree_bytes`` below.
21
+
22
+ Per {p021}/{p070}/{p071}, every shown or collapsed node must carry both its
23
+ canonical UUID4 ``node_id`` and its compact ``short_id_hex`` together, the
24
+ latter never a substitute for the former. Rather than hand-roll that pair a
25
+ second time, every place this module needs it -- the viewed node in the
26
+ header, a node record's own address, a node record's parent reference, a
27
+ stub record's address, and the whole-response continuation address -- reuses
28
+ the existing {p021} pair type, ``tree_engine.core.address.NodeAddressView``,
29
+ the same pattern already followed by the sibling
30
+ ``tree_engine.query.results.QueryMatch.parent_path``. Callers are expected to
31
+ have produced each pair via ``tree_engine.core.address
32
+ .build_node_address_view``.
33
+
34
+ This file defines data only. It performs no I/O, no tree walking, no address
35
+ resolution, and no truncation decision of its own.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ from dataclasses import dataclass, field
41
+ from typing import Any, Mapping, Optional, Sequence, Tuple, Union
42
+
43
+ from tree_engine.core.address import NodeAddressView
44
+
45
+ __all__ = [
46
+ "OutlineMeta",
47
+ "TruncatedField",
48
+ "OutlineNodeRecord",
49
+ "OutlineStubRecord",
50
+ "OutlineTruncation",
51
+ "OutlineResponse",
52
+ "build_outline_response",
53
+ ]
54
+
55
+
56
+ # --------------------------------------------------------------------------
57
+ # Response header
58
+ # --------------------------------------------------------------------------
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class OutlineMeta:
63
+ """The single response header ``model_outline`` carries, per {p070}.
64
+
65
+ ``viewed`` is the {p021} node_id/short_id_hex pair of the node the
66
+ ``drill_down`` call was resolved to (see
67
+ ``tree_engine.core.address.build_node_address_view``). ``depth`` and
68
+ ``expand_below_bytes`` are the effective parameter values the caller
69
+ already applied ({p066}, {p067}) -- this module does not validate or
70
+ default them. ``document_version`` is the document version the response
71
+ was produced against, carried exactly as given so a caller can compare
72
+ it against a later ``expected_version`` ({p065}). ``node_count`` is the
73
+ number of entries (node records plus stub records) in the assembled
74
+ ``nodes`` list, and ``response_bytes`` is the serialized byte size of
75
+ the whole response -- both computed by the caller, not by this module.
76
+ """
77
+
78
+ viewed: NodeAddressView
79
+ depth: int
80
+ expand_below_bytes: int
81
+ document_version: Any
82
+ node_count: int
83
+ response_bytes: int
84
+
85
+
86
+ # --------------------------------------------------------------------------
87
+ # Per-field truncation contract
88
+ # --------------------------------------------------------------------------
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class TruncatedField:
93
+ """The per-field truncation contract for one oversized optional value.
94
+
95
+ Used when a single record's optional content -- a source preview or a
96
+ large attribute value -- would alone exceed the response budget
97
+ ({p069}). ``value`` is the (possibly already-shortened) content that is
98
+ still returned; ``field_truncated`` marks whether it was cut, and
99
+ ``original_field_bytes`` records the pre-truncation byte size only when
100
+ ``field_truncated`` is true. This contract applies to exactly the one
101
+ field it wraps -- a record's mandatory address and structural fields
102
+ (``node_id``, ``short_id_hex``, ``type``, ``child_count``, ...) are
103
+ never wrapped in this type and are always returned intact, per {p069}.
104
+ """
105
+
106
+ value: Any
107
+ field_truncated: bool = False
108
+ original_field_bytes: Optional[int] = None
109
+
110
+
111
+ # --------------------------------------------------------------------------
112
+ # Flat preorder node record
113
+ # --------------------------------------------------------------------------
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class OutlineNodeRecord:
118
+ """One entry of the flat, preorder ``nodes`` list, per {p070}.
119
+
120
+ ``address`` is this node's own {p021} node_id/short_id_hex pair.
121
+ ``depth`` is its distance (in edges) from the viewed node. ``parent`` is
122
+ the immediate parent's {p021} pair, or ``None`` -- absent only for the
123
+ viewed node itself when it has no shown parent in this response.
124
+ ``child_index`` is this node's position among its siblings, as the
125
+ caller determined it.
126
+
127
+ ``type`` and ``name_or_value`` are the node's short-form identity for
128
+ display. ``attributes`` is the selected-attributes payload, gated by
129
+ whether ``include_attributes`` was requested ({p068}): ``None`` means
130
+ attributes were not requested for this response; an (possibly empty)
131
+ mapping means they were. Any individual attribute value may itself be a
132
+ :class:`TruncatedField` when that one value alone was too large.
133
+
134
+ ``child_count`` is the node's total direct-child count; ``shown_child_count``
135
+ is how many of those children actually appear (as records or stubs)
136
+ in this response. ``subtree_bytes`` is the locally maintained aggregate
137
+ figure for this node (see ``tree_engine.core.positions
138
+ .SubtreeBytesAggregate``), or ``None`` when that cache is missing or
139
+ stale for this node ({p067}) -- this module never re-derives it.
140
+
141
+ ``source_preview`` is gated by whether ``include_source`` was requested
142
+ ({p068}): ``None`` means source was not requested; otherwise it is a
143
+ :class:`TruncatedField` wrapping the preview string (``field_truncated``
144
+ false when the preview fit whole).
145
+
146
+ ``expanded`` is true when this node's children were shown rather than
147
+ collapsed into a stub. ``auto_expanded`` is true when that expansion was
148
+ triggered by the ``expand_below_bytes`` threshold rather than the
149
+ requested ``depth`` ({p067}). ``truncated`` is true when this specific
150
+ record's own content was cut for the whole-response budget ({p069}).
151
+ """
152
+
153
+ node_id: Any
154
+ short_id_hex: str
155
+ depth: int
156
+ parent_id: Optional[Any]
157
+ parent_short_id_hex: Optional[str]
158
+ child_index: int
159
+ type: str
160
+ name_or_value: str
161
+ attributes: Optional[Mapping[str, Any]]
162
+ child_count: int
163
+ shown_child_count: int
164
+ subtree_bytes: Optional[int]
165
+ source_preview: Optional[TruncatedField]
166
+ expanded: bool
167
+ auto_expanded: bool
168
+ truncated: bool
169
+
170
+ @property
171
+ def address(self) -> NodeAddressView:
172
+ """This record's own {p021} node_id/short_id_hex pair."""
173
+
174
+ return NodeAddressView(short_id_hex=self.short_id_hex, node_id=str(self.node_id))
175
+
176
+ @property
177
+ def parent(self) -> Optional[NodeAddressView]:
178
+ """The immediate parent's {p021} pair, or ``None`` if unshown."""
179
+
180
+ if self.parent_id is None and self.parent_short_id_hex is None:
181
+ return None
182
+ return NodeAddressView(
183
+ short_id_hex=str(self.parent_short_id_hex), node_id=str(self.parent_id)
184
+ )
185
+
186
+
187
+ # --------------------------------------------------------------------------
188
+ # Collapsed-subtree stub record
189
+ # --------------------------------------------------------------------------
190
+
191
+
192
+ @dataclass(frozen=True)
193
+ class OutlineStubRecord:
194
+ """A stand-in record for a subtree ``drill_down`` did not expand, per {p071}.
195
+
196
+ Carries only enough to address and describe the collapsed subtree:
197
+ ``node_id``/``short_id_hex`` (the {p021} pair, always both present),
198
+ ``type``, ``child_count``, ``subtree_node_count`` (the collapsed
199
+ subtree's total node count), and ``subtree_bytes`` (the locally
200
+ maintained aggregate, or ``None`` when missing/stale, mirroring
201
+ :attr:`OutlineNodeRecord.subtree_bytes`). ``expandable`` is a literal
202
+ flag, always ``True`` -- it is not a constructor parameter, so a stub
203
+ can never be built claiming otherwise. This is sufficient, on its own,
204
+ for a follow-up command to address the node by ``short_id_hex`` without
205
+ a further search, per {p071}.
206
+ """
207
+
208
+ node_id: Any
209
+ short_id_hex: str
210
+ type: str
211
+ child_count: int
212
+ subtree_node_count: int
213
+ subtree_bytes: Optional[int]
214
+ expandable: bool = field(default=True, init=False)
215
+
216
+ @property
217
+ def address(self) -> NodeAddressView:
218
+ """This stub's own {p021} node_id/short_id_hex pair."""
219
+
220
+ return NodeAddressView(short_id_hex=self.short_id_hex, node_id=str(self.node_id))
221
+
222
+
223
+ # --------------------------------------------------------------------------
224
+ # Whole-response truncation and continuation contract
225
+ # --------------------------------------------------------------------------
226
+
227
+
228
+ @dataclass(frozen=True)
229
+ class OutlineTruncation:
230
+ """The whole-response truncation and continuation contract, per {p069}.
231
+
232
+ ``truncated`` is true when the serialized response was cut short (only
233
+ ever between node-record boundaries, never mid-record). ``omitted_nodes``
234
+ and ``omitted_bytes`` count what was left out. ``continuation`` is the
235
+ {p021} pair (``short_id_hex`` plus ``node_id``) identifying where a
236
+ follow-up call should resume -- ``None`` when there is nothing to
237
+ resume (the ordinary, untruncated case).
238
+ """
239
+
240
+ truncated: bool
241
+ omitted_nodes: int
242
+ omitted_bytes: int
243
+ continuation: Optional[NodeAddressView] = None
244
+
245
+
246
+ # --------------------------------------------------------------------------
247
+ # Assembled response and its assembly helper
248
+ # --------------------------------------------------------------------------
249
+
250
+
251
+ OutlineEntry = Union[OutlineNodeRecord, OutlineStubRecord]
252
+
253
+
254
+ @dataclass(frozen=True)
255
+ class OutlineResponse:
256
+ """The complete, serializable ``model_outline`` response ({p070}).
257
+
258
+ ``meta`` is the response header, ``nodes`` is the flat preorder list
259
+ (mixing :class:`OutlineNodeRecord` and :class:`OutlineStubRecord`
260
+ entries, in the exact order given), and ``truncation`` is the
261
+ whole-response truncation/continuation contract. This type never
262
+ reorders, filters, or otherwise recomputes what it was given.
263
+ """
264
+
265
+ meta: OutlineMeta
266
+ nodes: Tuple[OutlineEntry, ...]
267
+ truncation: OutlineTruncation
268
+
269
+
270
+ def build_outline_response(
271
+ meta: OutlineMeta,
272
+ nodes: Sequence[OutlineEntry],
273
+ truncation: OutlineTruncation,
274
+ ) -> OutlineResponse:
275
+ """Assemble an already-built header, node list, and truncation contract.
276
+
277
+ This is the module's one assembly helper: it performs no computation of
278
+ its own beyond wrapping ``nodes`` in an immutable, ordered tuple and
279
+ threading ``meta``/``truncation`` through unchanged. It does not compute
280
+ ``node_count``/``response_bytes`` (those belong on ``meta``, already
281
+ resolved by the caller), does not decide expansion or truncation, and
282
+ does not resolve addresses -- all of that is the sibling ``drill_down``
283
+ module's responsibility. The returned :class:`OutlineResponse` exposes
284
+ every value from ``meta``, ``nodes``, and ``truncation`` unchanged and in
285
+ the given order.
286
+ """
287
+
288
+ return OutlineResponse(meta=meta, nodes=tuple(nodes), truncation=truncation)
@@ -0,0 +1,263 @@
1
+ """Predicate evaluation for the ported tree-query engine (concept C-009).
2
+
3
+ Scope (concept C-009, narrowed to predicate evaluation only, per {p005} and
4
+ {p019}): this module owns exactly the two functions that decide whether an
5
+ already-parsed attribute predicate (or a set of them on one selector step)
6
+ holds against a concrete node from the loaded tree -- :func:`evaluate_predicate`
7
+ and :func:`evaluate_predicates`. It performs no selector/predicate parsing,
8
+ no tree traversal, and no query orchestration.
9
+
10
+ This is a PORT, not a redesign. The legacy predicate language and its
11
+ observable semantics live unchanged in the ``ai_editor`` package's
12
+ ``cst_query`` modules (``ai_editor.cst_query.ast`` and
13
+ ``ai_editor.cst_query.executor``). This module is deliberately built
14
+ directly on that legacy vocabulary rather than reinventing a parallel one:
15
+
16
+ * ``Predicate`` and ``PredicateOp`` are imported unchanged from
17
+ ``ai_editor.cst_query.ast`` -- they are exactly what the existing,
18
+ unchanged selector parser (``ai_editor.cst_query.parser.parse_selector``)
19
+ already produces, so no adapter/rewrap step is needed between "parsed
20
+ predicate" and "evaluated predicate".
21
+ * Per {p019}, the supported predicate forms are equality (``=``),
22
+ inequality (``!=``), containment (``~=``), prefix match (``^=``) and
23
+ suffix match (``$=``), plus the numeric comparisons greater-than (``>``),
24
+ less-than (``<``), greater-or-equal (``>=``) and less-or-equal (``<=``)
25
+ (S6a of wish 8564a2ba, closing the drop-in parity gap this module's
26
+ narrower first cut deliberately left open), plus the combination of more
27
+ than one predicate on the same step, all of which must hold together (a
28
+ logical AND). The four numeric operators mirror the legacy executor's own
29
+ ``_compare`` exactly: both operands are coerced via plain ``int()``, and a
30
+ non-numeric operand on EITHER side simply does not match (``False``),
31
+ never a raised error -- a predicate value that fails ``int()`` is a
32
+ legitimate "no match" outcome, not a shape violation.
33
+ * Attribute values are read directly off the ``node`` argument -- no tree
34
+ walking, no reparsing, no lookup through any sibling module. ``node`` is
35
+ duck-typed, deliberately compatible with more than one shape so this
36
+ module has no import-time dependency on the sibling traversal adapter
37
+ (written concurrently and not imported here) or on any one node
38
+ representation: a plain ``tree_engine.core.nodes.Node`` (kind/fields),
39
+ a ``tree_engine.core.node_types`` wrapper (``get_attribute``/property
40
+ descriptors, the same convention already used by that module's own
41
+ ``matches(**predicates)`` helper), or any other object exposing the
42
+ attribute directly.
43
+
44
+ Do not introduce any new predicate-error taxonomy here. Whenever a
45
+ predicate cannot be evaluated -- because it names an attribute the node's
46
+ shape does not expose, or an operator this module does not support, or an
47
+ attribute whose value is itself structural (a child ``Node`` or an ordered
48
+ child sequence) rather than a scalar suitable for string comparison -- this
49
+ module raises ``ai_editor.core.exceptions.QueryParseError``, imported
50
+ unchanged, with no renaming and no subclassing. The stable
51
+ ``tree_engine.errors.ErrorCode.INVALID_SELECTOR`` catalog code travels
52
+ alongside that legacy exception inside its existing ``details`` payload
53
+ (key ``"error_code"``), rather than replacing it.
54
+
55
+ Out of scope, owned by sibling artifacts under G-018/T-001: parsing
56
+ selector/predicate syntax from text, tree traversal, semantic-role
57
+ resolution, and full query orchestration. This file depends on nothing
58
+ from those siblings; it does not import the query-result record type
59
+ either, since nothing here needs it for type consistency.
60
+ """
61
+
62
+ from __future__ import annotations
63
+
64
+ from typing import Any, Mapping, Sequence
65
+
66
+ from tree_engine.query.selector import Predicate, PredicateOp, QueryParseError
67
+ from tree_engine.errors import ErrorCode
68
+
69
+ __all__ = [
70
+ "evaluate_predicate",
71
+ "evaluate_predicates",
72
+ ]
73
+
74
+ # Every operator the legacy grammar defines (``ai_editor.cst_query.ast
75
+ # .PredicateOp``) is supported here, per {p019} as extended by S6a of wish
76
+ # 8564a2ba: the five string operators plus the four numeric comparisons.
77
+ _SUPPORTED_OPS = (
78
+ PredicateOp.EQ,
79
+ PredicateOp.NE,
80
+ PredicateOp.CONTAINS,
81
+ PredicateOp.PREFIX,
82
+ PredicateOp.SUFFIX,
83
+ PredicateOp.GT,
84
+ PredicateOp.LT,
85
+ PredicateOp.GTE,
86
+ PredicateOp.LTE,
87
+ )
88
+
89
+ # Scalar value types a string predicate can meaningfully compare against.
90
+ # Anything else (a Node, an ordered child sequence, or any other object) is
91
+ # a structural value: the node's shape does not support comparing it.
92
+ _SCALAR_TYPES = (str, int, float, bool, bytes)
93
+
94
+
95
+ class _Missing:
96
+ """Private sentinel distinguishing "no such attribute" from a real ``None``."""
97
+
98
+ __slots__ = ()
99
+
100
+ def __repr__(self) -> str: # pragma: no cover - debug aid only
101
+ return "<missing>"
102
+
103
+
104
+ _MISSING = _Missing()
105
+
106
+
107
+ def _read_attribute(node: Any, attr: str) -> Any:
108
+ """Read ``attr`` off ``node`` without tree walking or reparsing.
109
+
110
+ Resolution order, matching the convention already established by
111
+ ``tree_engine.core.node_types``'s own ``matches(**predicates)`` helper:
112
+
113
+ 1. A ``property`` descriptor on ``type(node)`` (e.g. a node-type
114
+ wrapper's ``.name``) -- read through the descriptor.
115
+ 2. A callable ``node.get_attribute(name, default)`` (the node-type
116
+ wrapper contract) -- consulted with the private missing sentinel as
117
+ default so an absent key is distinguishable from a stored ``None``.
118
+ 3. A ``node.fields`` mapping (the base ``tree_engine.core.nodes.Node``
119
+ contract) -- looked up directly.
120
+ 4. A plain instance attribute (covers first-class ``Node`` slots such
121
+ as ``kind``, and any other duck-typed fixture).
122
+
123
+ Returns the private missing sentinel when none of the above resolves
124
+ ``attr``.
125
+ """
126
+
127
+ descriptor = getattr(type(node), attr, None)
128
+ if isinstance(descriptor, property):
129
+ return getattr(node, attr)
130
+
131
+ get_attribute = getattr(node, "get_attribute", None)
132
+ if callable(get_attribute):
133
+ value = get_attribute(attr, _MISSING)
134
+ if value is not _MISSING:
135
+ return value
136
+
137
+ fields = getattr(node, "fields", None)
138
+ if isinstance(fields, Mapping) and attr in fields:
139
+ return fields[attr]
140
+
141
+ if hasattr(node, attr):
142
+ return getattr(node, attr)
143
+
144
+ return _MISSING
145
+
146
+
147
+ def _invalid_selector(message: str, *, predicate: Predicate) -> QueryParseError:
148
+ """Build the shared legacy exception, with the catalog code attached.
149
+
150
+ Always the same, unchanged ``QueryParseError`` class -- never a
151
+ subclass, never a differently named exception -- carrying
152
+ ``ErrorCode.INVALID_SELECTOR`` inside its existing ``details`` dict so
153
+ the stable catalog code travels alongside it.
154
+ """
155
+
156
+ return QueryParseError(
157
+ message,
158
+ details={
159
+ "error_code": ErrorCode.INVALID_SELECTOR,
160
+ "attr": predicate.attr,
161
+ "op": predicate.op.value,
162
+ },
163
+ )
164
+
165
+
166
+ def _compare(left: str, op: PredicateOp, right: str) -> bool:
167
+ """Apply one of the nine supported operators; ``op`` is pre-validated."""
168
+
169
+ if op == PredicateOp.EQ:
170
+ return left == right
171
+ if op == PredicateOp.NE:
172
+ return left != right
173
+ if op == PredicateOp.CONTAINS:
174
+ return right in left
175
+ if op == PredicateOp.PREFIX:
176
+ return left.startswith(right)
177
+ if op == PredicateOp.SUFFIX:
178
+ return left.endswith(right)
179
+ # Numeric comparisons (S6a of wish 8564a2ba): mirror the legacy
180
+ # executor's own ``_compare`` exactly -- plain ``int()`` coercion on
181
+ # both sides, a non-numeric operand on either side is simply "no
182
+ # match", never a raised error.
183
+ try:
184
+ left_num, right_num = int(left), int(right)
185
+ except (TypeError, ValueError):
186
+ return False
187
+ if op == PredicateOp.GT:
188
+ return left_num > right_num
189
+ if op == PredicateOp.LT:
190
+ return left_num < right_num
191
+ if op == PredicateOp.GTE:
192
+ return left_num >= right_num
193
+ return left_num <= right_num # PredicateOp.LTE: the only case left
194
+
195
+
196
+ def evaluate_predicate(predicate: Predicate, node: Any) -> bool:
197
+ """Evaluate one already-parsed ``Predicate`` against a concrete ``node``.
198
+
199
+ Reads ``predicate.attr``'s current value directly off ``node`` (see
200
+ :func:`_read_attribute`) and compares it against ``predicate.value``
201
+ using ``predicate.op``. Supports exactly equality, inequality,
202
+ containment, prefix match and suffix match, per {p019}.
203
+
204
+ A recognized attribute whose current value is ``None`` simply does not
205
+ match (returns ``False``), the same as the legacy executor: an empty
206
+ value is not a shape problem.
207
+
208
+ Raises:
209
+ QueryParseError: (imported unchanged from ``ai_editor.core
210
+ .exceptions``, ``details["error_code"] is
211
+ ErrorCode.INVALID_SELECTOR``) when ``predicate.op`` is outside
212
+ the five supported operators, when ``node`` does not expose
213
+ ``predicate.attr`` at all, or when the attribute resolves to a
214
+ structural value (a child ``Node`` or an ordered child
215
+ sequence) that no string predicate can meaningfully compare.
216
+ """
217
+
218
+ if predicate.op not in _SUPPORTED_OPS:
219
+ raise _invalid_selector(
220
+ f"predicate operator {predicate.op.value!r} is not supported by "
221
+ "tree-query predicate evaluation",
222
+ predicate=predicate,
223
+ )
224
+
225
+ value = _read_attribute(node, predicate.attr)
226
+ if value is _MISSING:
227
+ raise _invalid_selector(
228
+ f"node has no attribute {predicate.attr!r} to evaluate a "
229
+ "predicate against",
230
+ predicate=predicate,
231
+ )
232
+ if value is None:
233
+ return False
234
+ if not isinstance(value, _SCALAR_TYPES):
235
+ raise _invalid_selector(
236
+ f"attribute {predicate.attr!r} holds a {type(value).__name__} "
237
+ "value that tree-query string predicates cannot compare",
238
+ predicate=predicate,
239
+ )
240
+
241
+ left = (
242
+ value.decode("utf-8", errors="replace")
243
+ if isinstance(value, bytes)
244
+ else str(value)
245
+ )
246
+ return _compare(left, predicate.op, predicate.value)
247
+
248
+
249
+ def evaluate_predicates(predicates: Sequence[Predicate], node: Any) -> bool:
250
+ """Evaluate every predicate in ``predicates`` against ``node`` (logical AND).
251
+
252
+ Mirrors the legacy executor's step-matching loop exactly: predicates
253
+ are checked in order and evaluation stops at the first one that does
254
+ not hold, so a later, possibly-unsupported predicate is never reached
255
+ once an earlier one has already failed. An empty ``predicates``
256
+ sequence holds vacuously (``True``), matching a selector step with no
257
+ predicates at all.
258
+ """
259
+
260
+ for predicate in predicates:
261
+ if not evaluate_predicate(predicate, node):
262
+ return False
263
+ return True
@@ -0,0 +1,46 @@
1
+ """Line spans of a node tree that keeps no byte offsets, derived from the nodes' own rendered text.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ The statement formats (``sql``, ``onec_query``) and ``csv`` store each top-level node's exact text, so the
7
+ line a node starts on is one plus the line breaks rendered before it. The answer follows the live tree, so it
8
+ stays right after edits (bug f840eb52, decision D-AD / hook D-CB.2).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from typing import Any, List, Sequence, Tuple
15
+
16
+ __all__ = ["break_count", "span_from", "covering_nodes"]
17
+
18
+ _BREAK = re.compile(r"\r\n|\n|\r")
19
+
20
+
21
+ def break_count(text: str) -> int:
22
+ """Number of line terminators in ``text`` (``CRLF`` counts once)."""
23
+ return len(_BREAK.findall(text))
24
+
25
+
26
+ def span_from(text: str, start_line: int) -> Tuple[int, int]:
27
+ """``(first, last)`` line of ``text`` placed to start on ``start_line``; its closing terminator ends
28
+ the last line, it does not start another one."""
29
+ breaks = break_count(text)
30
+ ends_with_break = bool(text) and _BREAK.search(text[-2:]) is not None and text[-1] in "\r\n"
31
+ last = start_line + breaks - (1 if ends_with_break else 0)
32
+ return start_line, max(start_line, last)
33
+
34
+
35
+ def covering_nodes(
36
+ line: int, entries: Sequence[Tuple[Any, Tuple[int, int], int]]
37
+ ) -> List[Tuple[Any, Tuple[int, int]]]:
38
+ """The ``(node, span)`` entries covering ``line``, smallest span first, deeper node first on a tie.
39
+ ``entries`` holds ``(node, (first, last), depth)``."""
40
+ covering = [
41
+ ((span[1] - span[0], -depth, index), node, span)
42
+ for index, (node, span, depth) in enumerate(entries)
43
+ if span[0] <= line <= span[1]
44
+ ]
45
+ covering.sort(key=lambda item: item[0])
46
+ return [(node, span) for _key, node, span in covering]