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,853 @@
1
+ """Top-level entry point of the ported cst_query engine (concept C-009,
2
+ atomic step G-018/T-001/A-004).
3
+
4
+ Scope, per {p005}, {p018}, {p019}, {p020}, and {p040}: composes four
5
+ already-finished pieces -- the unchanged legacy selector parser/AST and the
6
+ three sibling modules delivered earlier under this tactical step (T-001)
7
+ -- into the one query entry point a caller invokes. No new selector syntax,
8
+ no new predicate/combinator/pseudo-selector semantics:
9
+
10
+ * ``ai_editor.cst_query.parser.parse_selector``/``ai_editor.cst_query.ast``
11
+ are imported unchanged, used exactly as the legacy executor
12
+ (``ai_editor.cst_query.executor``) used them -- this module mirrors that
13
+ executor's ``query_source``/``_eval_query``/``_apply_step``/
14
+ ``_apply_combinator`` shape, walking the common tree instead of a LibCST
15
+ index. A malformed selector's ``QueryParseError`` propagates untouched
16
+ from the parser -- never caught or wrapped here.
17
+ * ``TreeTraversalAdapter.iter_nodes`` supplies every node this module ever
18
+ sees: one raw, role-tagged, pre-order walk, indexed once by ``node_id``
19
+ for predicate lookup, ancestor-chain combinator checks, and assembly.
20
+ * Node-type matching reuses the adapter's own proven rule for what it
21
+ already covers -- a standard role (from ``resolve_semantic_role``, never
22
+ re-derived) or an exact literal ``kind`` string, per {p018} -- and adds
23
+ only the one legacy capability the adapter's public surface has no room
24
+ for: the ``"Type:*"`` prefix/suffix type *pattern* {p018} requires stay
25
+ preserved (the reused parser still emits a ``node_type`` ending in
26
+ ``":*"`` for it). Modeled on the legacy executor's own wildcard branch:
27
+ case-insensitive ``kind`` prefix/suffix, or role equality when the
28
+ pattern's stem itself names a standard role.
29
+ * ``evaluate_predicates`` filters each step's type-matched candidates by
30
+ their already-parsed ``Predicate`` tuple, reading attributes off the raw
31
+ node ({p019}).
32
+ * ``build_query_match`` is the sole assembler of every returned record
33
+ ({p021}), called once per indexed node while indexing (the same
34
+ ``to_hex``/``build_node_address_view`` pairing the adapter's own
35
+ ``iter_matching_nodes`` uses), so every match here is shaped identically
36
+ to one the adapter would build.
37
+
38
+ Combinators ({p020}: descendant, direct child) and ``:first``/``:last``/
39
+ ``:nth`` are evaluated over the ordered step chain, mirroring the legacy
40
+ executor: each step's candidates are matched independently over the whole
41
+ indexed tree, then narrowed to those related to the previous step's
42
+ survivors by the combinator between them (child: immediate parent must
43
+ survive; descendant: any ancestor must survive), pseudos applied last per
44
+ step. The legacy ``:not(...)`` pseudo (not enumerated among this step's
45
+ required pseudo-selectors, but present in the reused AST) is still honored
46
+ for full parity: evaluated by recursing into this same machinery with the
47
+ candidate universe narrowed to just the one node under test, mirroring
48
+ ``_eval_query([node], step.not_selector)``.
49
+
50
+ Never reparses the source: every lookup reads the already-built
51
+ ``Document``/``Node`` graph from one ``iter_nodes()`` walk, per {p040}.
52
+ On-request source inclusion renders a matched node's text via the loaded
53
+ plugin's duck-typed ``render_fragment`` (the same "if callable, use it"
54
+ convention ``resolve_semantic_role`` established for ``role_for``) --
55
+ regenerating text from the already-parsed tree via the plugin's own code
56
+ generator, never by reparsing -- falling back to the node's own stored
57
+ ``content`` field (as ``tree_engine.core.node_types`` wrappers use it), and
58
+ to ``None`` if neither applies.
59
+
60
+ Where this module detects, only after the reused parser already
61
+ succeeded, that the resulting chain has no executable first step (a
62
+ ``Query`` with no ``SelectorStep`` -- unreachable through
63
+ ``parse_selector`` on real text, but reachable by a caller driving
64
+ :meth:`TreeQueryEngine.execute` directly with a hand-built ``Query``), it
65
+ raises the same unchanged ``QueryParseError`` with
66
+ ``ErrorCode.INVALID_SELECTOR`` in its ``details`` payload -- the
67
+ convention the sibling predicate module already established -- rather
68
+ than a second exception type.
69
+
70
+ Out of scope, owned by sibling artifacts under this tactical step: new
71
+ predicate/combinator syntax, tree traversal internals (delegated to the
72
+ adapter), and predicate evaluation internals.
73
+ """
74
+
75
+ from __future__ import annotations
76
+
77
+ from bisect import bisect_right
78
+ from dataclasses import replace
79
+ from typing import Any, Dict, FrozenSet, List, Mapping, Optional, Sequence, Tuple
80
+
81
+ from tree_engine.query.selector import (
82
+ Combinator,
83
+ PseudoKind,
84
+ Query,
85
+ QueryParseError,
86
+ SelectorStep,
87
+ parse_selector,
88
+ )
89
+
90
+ from tree_engine.core.address import build_node_address_view
91
+ from tree_engine.core.live_tree import LiveNode, to_frozen
92
+ from tree_engine.core.nodes import Document, Node
93
+ from tree_engine.core.short_id import to_hex
94
+ from tree_engine.errors import ErrorCode
95
+ from tree_engine.query.adapter import TreeTraversalAdapter, resolve_semantic_role
96
+ from tree_engine.query.predicates import evaluate_predicates
97
+ from tree_engine.query.results import Position, QueryMatch, Range, build_query_match
98
+
99
+ __all__ = [
100
+ "TreeQueryEngine",
101
+ "legacy_kind",
102
+ "query",
103
+ ]
104
+
105
+ # The four standard semantic roles a "Type:*" pattern's stem, or a bare
106
+ # node-type selector, may name -- kept in lockstep with
107
+ # ``tree_engine.query.adapter``'s own alias set ({p018}).
108
+ _STANDARD_ROLE_NAMES = frozenset({"function", "method", "class", "module"})
109
+
110
+ # The full legacy ``cst_query`` 8-word alias vocabulary (S6a of wish
111
+ # 8564a2ba, G1): the original four standard roles above, PLUS the four
112
+ # extra words the legacy selector language also accepts as a bare node-type
113
+ # token -- ``ai_editor.cst_query.executor._matches_node_type``'s own alias
114
+ # set. Matched against whatever "kind" a node was indexed with: the narrow
115
+ # 4-value semantic role for a format with no richer classification, or the
116
+ # format's own wider legacy-kind vocabulary (see :func:`_index_document`,
117
+ # which resolves it via a plugin's own ``legacy_kind_for`` when declared)
118
+ # when its plugin declares one -- either way, a generic format's role is
119
+ # structurally never one of the extra four words, so widening this set costs
120
+ # such a format nothing.
121
+ _LEGACY_KIND_ALIASES = _STANDARD_ROLE_NAMES | frozenset(
122
+ {"stmt", "smallstmt", "import", "node"}
123
+ )
124
+
125
+ # One indexed entry per node: the RAW node (for node-type matching and, in
126
+ # ``_finalize``, on-request source rendering -- never the overlay below,
127
+ # which a format plugin's own ``render_fragment``/``export_from_common``
128
+ # does not know how to consume), its ancestor chain as a root-to-parent
129
+ # tuple of ``str(node_id)`` (for combinator checks), its "matching kind"
130
+ # (the narrow four-value semantic role for a format with no richer
131
+ # classification, or the fuller 8-word legacy vocabulary for one that
132
+ # declares ``legacy_kind_for`` -- S6a of wish 8564a2ba), its
133
+ # already-assembled ``QueryMatch`` (built once per node while indexing, per
134
+ # {p021}), and the "predicate node" predicate evaluation reads attributes
135
+ # off -- the same raw node again for a format with no python-parity
136
+ # support, or a :class:`_QueryAttributeView` overlay (``name``/
137
+ # ``qualname``/bare ``type``/``range`` resolved) for one that has it.
138
+ _IndexEntry = Tuple[Node, Tuple[str, ...], str, QueryMatch, Any]
139
+ _NodeIndex = Mapping[str, _IndexEntry]
140
+
141
+ # One candidate mid-evaluation: the node's own id, its ancestor id chain,
142
+ # and the already-assembled ``QueryMatch`` the results module produced.
143
+ _Candidate = Tuple[str, Tuple[str, ...], QueryMatch]
144
+
145
+
146
+ def _unexecutable_selector_error(reason: str) -> QueryParseError:
147
+ """Build the shared legacy exception for a post-parse unexecutable chain.
148
+
149
+ Always the same, unchanged ``QueryParseError`` -- never a subclass --
150
+ carrying ``ErrorCode.INVALID_SELECTOR`` in its existing ``details``
151
+ dict, exactly as ``tree_engine.query.predicates`` already does for its
152
+ own post-parse rejections.
153
+ """
154
+
155
+ return QueryParseError(
156
+ f"selector step chain is not executable: {reason}",
157
+ details={"error_code": ErrorCode.INVALID_SELECTOR},
158
+ )
159
+
160
+
161
+ def _require_executable(parsed_query: Query) -> None:
162
+ """Reject a parsed ``Query`` with no executable first step.
163
+
164
+ Not reachable through ``parse_selector`` on any real selector text --
165
+ its own transformer already refuses to build a ``Query`` with no first
166
+ step -- but a caller driving :meth:`TreeQueryEngine.execute` directly
167
+ with a hand-built ``Query`` (bypassing text parsing entirely) can reach
168
+ this, so it is checked here rather than assumed impossible.
169
+ """
170
+
171
+ if not isinstance(parsed_query, Query) or not isinstance(
172
+ parsed_query.first, SelectorStep
173
+ ):
174
+ raise _unexecutable_selector_error("no executable first step")
175
+
176
+
177
+ def legacy_kind(plugin: Any, node: Node, ancestors: Sequence[Node] = ()) -> str:
178
+ """Public helper: ``node``'s legacy ``cst_query`` kind classification.
179
+
180
+ S6a of wish 8564a2ba (G5): consumers migrating off
181
+ ``ai_editor.cst_query`` (``cst_patcher.py``, ``python_handler.py``) need
182
+ the SAME 8-word vocabulary (``module``/``decorator``/``class``/
183
+ ``function``/``method``/``import``/``smallstmt``/``stmt``/``node``) the
184
+ legacy engine's ``node_type_utils.get_node_kind`` produces, without
185
+ driving a full query. Duck-typed exactly like
186
+ :func:`tree_engine.query.adapter.resolve_semantic_role`: calls
187
+ ``plugin.legacy_kind_for(node, ancestors)`` when the plugin declares one
188
+ (only the python plugin does, at the time of writing) and falls back to
189
+ the narrower, four-value :func:`~tree_engine.query.adapter
190
+ .resolve_semantic_role` for any format that does not -- never raises
191
+ for a format with neither.
192
+ """
193
+
194
+ legacy_kind_for = getattr(plugin, "legacy_kind_for", None)
195
+ if callable(legacy_kind_for):
196
+ return str(legacy_kind_for(node, tuple(ancestors)))
197
+ return resolve_semantic_role(plugin, node, ancestors)
198
+
199
+
200
+ def _bare_type(node: Node) -> str:
201
+ """The node's own bare, format-local type name: the part of its
202
+ namespaced ``kind`` string after the LAST ``":"`` (or the whole string
203
+ when there is none) -- e.g. ``"python:FunctionDef"`` -> ``"FunctionDef"``,
204
+ matching the legacy engine's ``NodeInfo.node_type`` (the bare LibCST
205
+ class name, never namespaced)."""
206
+
207
+ raw = str(node.kind)
208
+ return raw.rpartition(":")[2] or raw
209
+
210
+
211
+ def _resolve_source_bytes(document: Any, plugin: Any) -> Optional[bytes]:
212
+ """The document's own raw source bytes, for byte-offset -> line/column
213
+ conversion ({p021}/G4), never by reparsing.
214
+
215
+ A ``tree_engine.core.live_tree.TreeDocument`` (the facade's live,
216
+ mutable document) already carries them on ``.source_bytes`` -- read
217
+ directly. A plain, immutable ``tree_engine.core.nodes.Document`` (e.g.
218
+ one built straight off ``plugin.parse_document(source)``, as
219
+ ``tests/query/test_compat_cst_query.py`` does) carries no such
220
+ attribute at all; for that shape this falls back to the format
221
+ plugin's own ``render_document`` (the EXPORT direction, tree -> bytes
222
+ -- never the parser, so this is not a reparse), which the python
223
+ plugin's own measured byte-identical round trip guarantees reproduces
224
+ the original bytes exactly. Returns ``None`` (never raises) when
225
+ neither source is available, e.g. a plugin with no ``render_document``
226
+ or one whose export fails on this particular tree -- callers treat a
227
+ ``None`` result as "no position data for this query", not an error.
228
+ """
229
+
230
+ source_bytes = getattr(document, "source_bytes", None)
231
+ if isinstance(source_bytes, (bytes, bytearray)):
232
+ return bytes(source_bytes)
233
+ renderer = getattr(plugin, "render_document", None)
234
+ if callable(renderer):
235
+ try:
236
+ rendered = renderer(document)
237
+ except Exception:
238
+ return None
239
+ if isinstance(rendered, (bytes, bytearray)):
240
+ return bytes(rendered)
241
+ if isinstance(rendered, str):
242
+ return rendered.encode("utf-8")
243
+ return None
244
+
245
+
246
+ class _PositionIndex:
247
+ """Byte-offset -> 1-based line / 0-based column resolver (G4), built
248
+ once per :meth:`TreeQueryEngine.execute` call from the document's own
249
+ source bytes (see :func:`_resolve_source_bytes`) -- never a reparse,
250
+ only a newline count over bytes the document already produced.
251
+
252
+ Column numbering matches legacy's ``PositionProvider`` convention
253
+ EXACTLY: a CHARACTER (Unicode code point) count from the start of the
254
+ line, not a byte count (S6a verifier finding #5, fixed here: an
255
+ earlier cut of this class counted raw bytes, which only coincides
256
+ with the character count for a pure-ASCII line -- a line containing
257
+ e.g. Cyrillic text measured too many columns, one per UTF-8 continuation
258
+ byte). ``buffer_range`` itself is still a BYTE offset (LibCST's own
259
+ ``ByteSpanPositionProvider``), so the fix is in how a byte offset is
260
+ turned into a column: the bytes from the line's own start up to that
261
+ offset are decoded as UTF-8 and COUNTED, never the raw byte span
262
+ itself -- this assumes ``buffer_range`` boundaries always land on a
263
+ character boundary (true for any span LibCST itself resolved, since it
264
+ parsed valid UTF-8 source), so the slice always decodes cleanly.
265
+ """
266
+
267
+ __slots__ = ("_source", "_newline_offsets")
268
+
269
+ def __init__(self, source: bytes) -> None:
270
+ self._source = source
271
+ offsets: List[int] = []
272
+ index = source.find(b"\n")
273
+ while index != -1:
274
+ offsets.append(index)
275
+ index = source.find(b"\n", index + 1)
276
+ self._newline_offsets = offsets
277
+
278
+ def _position(self, offset: int) -> Position:
279
+ line_index = bisect_right(self._newline_offsets, offset - 1)
280
+ line_start = 0 if line_index == 0 else self._newline_offsets[line_index - 1] + 1
281
+ column = len(self._source[line_start:offset].decode("utf-8", errors="replace"))
282
+ return Position(line=line_index + 1, column=column)
283
+
284
+ def range_for(self, buffer_range: Optional[Tuple[int, int]]) -> Optional[Range]:
285
+ """``Range`` for a node's own ``(start_byte, end_byte)``
286
+ ``buffer_range``, or ``None`` when the node carries none."""
287
+
288
+ if buffer_range is None:
289
+ return None
290
+ start, end = buffer_range
291
+ return Range(start=self._position(start), end=self._position(end))
292
+
293
+
294
+ class _QueryAttributeView:
295
+ """Per-node overlay layering query-facing scalar attributes -- ``name``,
296
+ ``qualname``, a bare ``type``, and a source ``range`` (plus the
297
+ ``start_line``/``end_line``/``start_col``/``end_col`` ints a predicate
298
+ may ask for) -- on top of one wrapped, unmodified ``Node`` (G2/G4/D2 of
299
+ S6a, wish 8564a2ba).
300
+
301
+ Every override below is a real ``property``, deliberately: per
302
+ ``tree_engine.query.predicates._read_attribute``'s own documented
303
+ resolution order, a property descriptor on ``type(node)`` is consulted
304
+ BEFORE ``node.fields`` -- critical here, since a python
305
+ ``FunctionDef``/``ClassDef``'s own ``fields["name"]`` holds a nested
306
+ ``Node`` (LibCST's own ``Name`` child), not the scalar this overlay
307
+ resolves instead; a plain instance attribute would lose to that
308
+ ``fields`` entry under the same resolution order. This is the one place
309
+ that duck-typed order is depended on rather than merely documented, so
310
+ neither ``predicates.py`` nor ``results.py`` needs a single line of
311
+ format-specific branching to get the right value for these four names.
312
+
313
+ ``kind`` is ALSO overridden -- to the already-resolved legacy 8-word
314
+ classification (``matching_kind``, see :func:`_index_document`), not the
315
+ node's raw namespaced ``Node.kind`` -- because that is exactly what a
316
+ legacy ``[kind=...]``/``[kind~=...]`` predicate compares against
317
+ (``ai_editor.cst_query.executor._get_attr``'s own ``"kind"`` branch
318
+ reads the ALREADY-resolved ``NodeInfo.kind``, never the raw LibCST
319
+ class name). This does not disturb ``QueryMatch.kind`` (the RESULT
320
+ field, always assembled from the ``kind`` argument
321
+ :func:`build_query_match` receives directly, never read off ``node``)
322
+ nor ``QueryMatch.kind_namespaced`` (which :func:`_index_document`
323
+ corrects back to the raw kind after assembly, since
324
+ ``build_query_match`` would otherwise read this same overridden value).
325
+
326
+ Every other attribute (``node_id``, ``fields``, ``short_id``,
327
+ ``buffer_range``, ...) is read straight off the wrapped node via
328
+ ``__getattr__``, so this overlay is a strict superset of the raw node
329
+ for every consumer's purposes.
330
+
331
+ ``get_attribute`` (S6a verifier finding #3) is the OTHER half of the
332
+ legacy-parity surface: ``predicates._read_attribute`` consults a
333
+ callable ``get_attribute(name, default)`` before ever looking at
334
+ ``fields``, and this one implements legacy's own ``_get_attr`` CLOSED
335
+ whitelist verbatim -- ``type``/``kind``/``name``/``qualname``/
336
+ ``start_line``/``end_line``/``children_count``/``module`` -- always
337
+ returning a real value (``None`` included) and NEVER the missing
338
+ sentinel, so a predicate naming any OTHER attribute (or one of these
339
+ on a node it does not apply to) resolves to ``None`` -- a silent
340
+ "does not match", exactly mirroring legacy, never a raised
341
+ ``QueryParseError``. Two legacy quirks are pinned here, not "fixed":
342
+ ``children_count`` is unconditionally ``0`` for every node whatsoever
343
+ (legacy's own ``NodeInfo`` dataclass has no ``children`` field at
344
+ all, so its ``getattr(node, "children", None) or []`` is always
345
+ empty -- verified against the real legacy engine); ``module``
346
+ resolves only for an ``ImportFrom`` (``None`` otherwise, ``self
347
+ ._module_text`` pre-rendered once per node in :func:`_build_overlay`).
348
+ ``start_col``/``end_col`` are deliberately NOT resolvable here at
349
+ all (return ``None``, like everything outside the whitelist): legacy
350
+ has no such predicate attribute either.
351
+ """
352
+
353
+ __slots__ = (
354
+ "_node",
355
+ "_name",
356
+ "_qualname",
357
+ "_type",
358
+ "_kind",
359
+ "_range",
360
+ "_module_text",
361
+ )
362
+
363
+ def __init__(
364
+ self,
365
+ node: Node,
366
+ *,
367
+ name: Optional[str],
368
+ qualname: Optional[str],
369
+ type_: str,
370
+ kind: str,
371
+ range_: Optional[Range],
372
+ module_text: Optional[str] = None,
373
+ ) -> None:
374
+ self._node = node
375
+ self._name = name
376
+ self._qualname = qualname
377
+ self._type = type_
378
+ self._kind = kind
379
+ self._range = range_
380
+ self._module_text = module_text
381
+
382
+ def __getattr__(self, attr: str) -> Any:
383
+ # Only reached when normal attribute/slot lookup on this overlay
384
+ # itself fails -- i.e. for everything this overlay does not
385
+ # override, delegated straight to the wrapped node.
386
+ return getattr(self._node, attr)
387
+
388
+ @property
389
+ def name(self) -> Optional[str]:
390
+ return self._name
391
+
392
+ @property
393
+ def qualname(self) -> Optional[str]:
394
+ return self._qualname
395
+
396
+ @property
397
+ def type(self) -> str:
398
+ return self._type
399
+
400
+ @property
401
+ def kind(self) -> str:
402
+ return self._kind
403
+
404
+ @property
405
+ def range(self) -> Optional[Range]:
406
+ return self._range
407
+
408
+ def get_attribute(self, attr: str, default: Any = None) -> Any:
409
+ if attr == "type":
410
+ return self._type
411
+ if attr == "kind":
412
+ return self._kind
413
+ if attr == "name":
414
+ return self._name
415
+ if attr == "qualname":
416
+ return self._qualname
417
+ if attr == "start_line":
418
+ return self._range.start.line if self._range is not None else None
419
+ if attr == "end_line":
420
+ return self._range.end.line if self._range is not None else None
421
+ if attr == "children_count":
422
+ return 0
423
+ if attr == "module":
424
+ return self._module_text
425
+ return None
426
+
427
+
428
+ def _build_overlay(
429
+ plugin: Any,
430
+ node: Node,
431
+ ancestors: Sequence[Node],
432
+ position_index: Optional[_PositionIndex],
433
+ matching_kind: str,
434
+ ) -> _QueryAttributeView:
435
+ """Build the one :class:`_QueryAttributeView` a python-parity-capable
436
+ plugin's node gets indexed with -- only called once ``legacy_kind_for``
437
+ is already known to exist on ``plugin`` (see :func:`_index_document`).
438
+ """
439
+
440
+ name_for = getattr(plugin, "name_for", None)
441
+ name = name_for(node) if callable(name_for) else None
442
+ qualname_for = getattr(plugin, "qualname_for", None)
443
+ qualname = qualname_for(node, tuple(ancestors)) if callable(qualname_for) else None
444
+ range_ = (
445
+ position_index.range_for(node.buffer_range)
446
+ if position_index is not None
447
+ else None
448
+ )
449
+ module_text_for = getattr(plugin, "module_text_for", None)
450
+ module_text = module_text_for(node) if callable(module_text_for) else None
451
+ return _QueryAttributeView(
452
+ node,
453
+ name=name,
454
+ qualname=qualname,
455
+ type_=_bare_type(node),
456
+ kind=matching_kind,
457
+ range_=range_,
458
+ module_text=module_text,
459
+ )
460
+
461
+
462
+ def _index_document(adapter: TreeTraversalAdapter) -> _NodeIndex:
463
+ """Walk the whole document exactly once, via the adapter, and pre-build
464
+ every node's {p021} result record plus the bookkeeping later steps need.
465
+
466
+ The single full traversal any query needs: node-type/predicate
467
+ filtering reads the raw node and its matching kind; combinator
468
+ evaluation reads the ancestor id chain; final assembly reuses the
469
+ already-built ``QueryMatch`` (via the sibling results module's own
470
+ constructor) rather than re-deriving it per step.
471
+
472
+ S6a of wish 8564a2ba: when the loaded plugin declares
473
+ ``legacy_kind_for`` (only the python plugin, at the time of writing),
474
+ every node is ALSO wrapped in a :class:`_QueryAttributeView` (built
475
+ once per node, here, alongside its ``QueryMatch``) so predicate
476
+ evaluation and result assembly see the legacy-parity ``name``/
477
+ ``qualname``/bare ``type``/``range`` values instead of the raw common
478
+ node -- and the node's "matching kind" (used both for node-type
479
+ matching below and as the resulting ``QueryMatch.kind``) is the full
480
+ 8-word legacy vocabulary instead of the narrower 4-value semantic role.
481
+ A plugin with no such hook is completely unaffected: it gets the exact
482
+ same raw node and role this function has always produced.
483
+ """
484
+
485
+ plugin = adapter.plugin
486
+ has_legacy_support = callable(getattr(plugin, "legacy_kind_for", None))
487
+ position_index: Optional[_PositionIndex] = None
488
+ if has_legacy_support:
489
+ source_bytes = _resolve_source_bytes(adapter.document, plugin)
490
+ if source_bytes is not None:
491
+ position_index = _PositionIndex(source_bytes)
492
+
493
+ index: Dict[str, _IndexEntry] = {}
494
+ for node, ancestors, role in adapter.iter_nodes():
495
+ ancestor_ids = tuple(str(ancestor.node_id) for ancestor in ancestors)
496
+ parent_path = tuple(
497
+ build_node_address_view(ancestor.node_id, ancestor.short_id)
498
+ for ancestor in ancestors
499
+ )
500
+ if has_legacy_support:
501
+ matching_kind = str(plugin.legacy_kind_for(node, tuple(ancestors)))
502
+ predicate_node: Any = _build_overlay(
503
+ plugin, node, ancestors, position_index, matching_kind
504
+ )
505
+ else:
506
+ matching_kind = role
507
+ predicate_node = node
508
+ match = build_query_match(
509
+ predicate_node, matching_kind, to_hex(node.short_id), parent_path
510
+ )
511
+ if has_legacy_support:
512
+ # The overlay's own ``.kind`` is the resolved legacy kind (so a
513
+ # ``[kind=...]`` predicate compares the right thing, per
514
+ # ``_QueryAttributeView``'s own docstring) -- correct
515
+ # ``kind_namespaced`` back to the node's true raw kind, which
516
+ # ``build_query_match`` would otherwise have read off that same
517
+ # overridden attribute.
518
+ match = replace(match, kind_namespaced=str(node.kind))
519
+ index[str(node.node_id)] = (
520
+ node,
521
+ ancestor_ids,
522
+ matching_kind,
523
+ match,
524
+ predicate_node,
525
+ )
526
+ return index
527
+
528
+
529
+ def _node_type_matches(node: Node, kind: str, node_type: Optional[str]) -> bool:
530
+ """True when ``node`` (already tagged with ``kind``) satisfies ``node_type``.
531
+
532
+ The one canonical node-type-matching rule for the whole ``tree_engine
533
+ .query`` package (D1 of S6a, wish 8564a2ba) -- ``tree_engine.query
534
+ .adapter``'s own copy delegates here instead of keeping a second,
535
+ independently-maintained implementation. ``kind`` is whatever the
536
+ caller already resolved a node's "matching kind" to: the narrow
537
+ four-value standard semantic role for a format with no richer
538
+ classification (``adapter.py``'s own callers, and any non-python
539
+ document here), or the fuller 8-word legacy ``cst_query`` vocabulary
540
+ for a format whose plugin declares ``legacy_kind_for`` (only python, at
541
+ the time of writing) -- see :func:`_index_document`. A generic format's
542
+ ``kind`` is structurally never one of the four EXTRA legacy words
543
+ (``stmt``/``smallstmt``/``import``/``node``), so widening the alias set
544
+ to all eight costs such a format nothing.
545
+
546
+ Matching order, mirroring the legacy executor's own
547
+ ``_matches_node_type`` exactly:
548
+
549
+ 1. ``None``/``"*"`` matches everything (the universal selector).
550
+ 2. A ``"Type:*"`` prefix/suffix pattern (the reused parser's own
551
+ ``node_type`` transformer product): an empty stem matches
552
+ everything; a stem naming one of the eight legacy alias words
553
+ matches by ``kind`` equality; any other stem matches
554
+ case-insensitively as a prefix or suffix of the LOCAL part of the
555
+ node's own raw ``kind`` string (S6a verifier finding #2: matching
556
+ against the FULL namespaced string, as an earlier cut of this
557
+ function did, made every stem that happens to prefix-match the
558
+ format namespace itself -- e.g. a bogus ``"python:*"`` -- match
559
+ every node in the document; legacy's own wildcard branch compares
560
+ against the bare, un-namespaced LibCST class name).
561
+ 3. One of the eight legacy alias words (bare, no ``":*"`` suffix)
562
+ matches by ``kind`` equality.
563
+ 4. The node's own raw, namespaced ``kind`` string, compared
564
+ case-sensitively and in full (the pre-existing, unchanged
565
+ extension-type reach: e.g. ``"fmt:PreprocessorDirective"``).
566
+ 5. Otherwise, the LOCAL part of the node's raw ``kind`` (after its
567
+ last ``":"``, or the whole string when there is none) compared
568
+ case-insensitively against ``node_type`` (G1): a BARE literal
569
+ node-type token, e.g. ``"ClassDef"`` or ``"SimpleStatementLine"``,
570
+ reaches a node by its own concrete type name with no namespace
571
+ prefix needed -- mirroring the legacy engine's own literal
572
+ LibCST-class-name fallback, generalized across formats via the
573
+ ``"<format>:<local>"`` kind convention every plugin already follows.
574
+ """
575
+
576
+ if node_type is None or node_type == "*":
577
+ return True
578
+ if node_type.endswith(":*"):
579
+ stem = node_type[:-2].strip().lower()
580
+ if not stem:
581
+ return True
582
+ if stem in _LEGACY_KIND_ALIASES:
583
+ return kind == stem
584
+ raw_kind = str(node.kind)
585
+ local_kind = (raw_kind.rpartition(":")[2] or raw_kind).lower()
586
+ return local_kind.startswith(stem) or local_kind.endswith(stem)
587
+ normalized = node_type.lower()
588
+ if normalized in _LEGACY_KIND_ALIASES:
589
+ return kind == normalized
590
+ raw_kind = str(node.kind)
591
+ if raw_kind == node_type:
592
+ return True
593
+ local = raw_kind.rpartition(":")[2] or raw_kind
594
+ return local.lower() == normalized
595
+
596
+
597
+ def _apply_pseudos(
598
+ candidates: List[_Candidate], pseudos: Sequence[Any]
599
+ ) -> List[_Candidate]:
600
+ """Apply ``:first``/``:last``/``:nth`` in order, mirroring the legacy
601
+ executor's ``_apply_step``, which always narrows *after* type/predicate/
602
+ ``:not`` filtering has already produced the full matched list for this
603
+ step. ``:not`` itself never appears here: the reused parser routes it
604
+ into ``SelectorStep.not_selector`` instead of ``SelectorStep.pseudos``.
605
+ """
606
+
607
+ for pseudo in pseudos:
608
+ if pseudo.kind == PseudoKind.FIRST:
609
+ candidates = candidates[:1]
610
+ elif pseudo.kind == PseudoKind.LAST:
611
+ candidates = candidates[-1:] if candidates else []
612
+ elif pseudo.kind == PseudoKind.NTH:
613
+ index = pseudo.index if pseudo.index is not None else 0
614
+ candidates = [candidates[index]] if 0 <= index < len(candidates) else []
615
+ return candidates
616
+
617
+
618
+ def _not_excludes(index: _NodeIndex, not_selector: Query, node_id: str) -> bool:
619
+ """True when ``not_selector`` matches ``node_id`` (the owning
620
+ ``:not(...)`` step must then exclude it), mirroring the legacy
621
+ executor's ``_eval_query([node], step.not_selector)``: the sub-query's
622
+ candidate universe is narrowed to just this one node throughout.
623
+ """
624
+
625
+ return bool(_run_query(index, not_selector, universe=frozenset({node_id})))
626
+
627
+
628
+ def _step_candidates(
629
+ index: _NodeIndex, step: SelectorStep, universe: Optional[FrozenSet[str]]
630
+ ) -> List[_Candidate]:
631
+ """Resolve one selector step's surviving candidates over ``index``.
632
+
633
+ In legacy order: type-match on the RAW node and its matching kind (see
634
+ :func:`_node_type_matches`); restrict to ``universe`` when narrowing
635
+ for a ``:not(...)`` sub-query (``None`` means "the whole document", the
636
+ ordinary case); filter by this step's predicates -- read off the
637
+ PREDICATE node (the python-parity overlay when one applies, per
638
+ :func:`_index_document`, else the same raw node) via the sibling
639
+ predicate module; filter by ``:not(...)`` when present; finally narrow
640
+ by any ``:first``/``:last``/``:nth``.
641
+ """
642
+
643
+ survivors: List[_Candidate] = []
644
+ for node_id, (
645
+ node,
646
+ ancestor_ids,
647
+ matching_kind,
648
+ match,
649
+ predicate_node,
650
+ ) in index.items():
651
+ if universe is not None and node_id not in universe:
652
+ continue
653
+ if not _node_type_matches(node, matching_kind, step.node_type):
654
+ continue
655
+ if not evaluate_predicates(step.predicates, predicate_node):
656
+ continue
657
+ if step.not_selector is not None and _not_excludes(
658
+ index, step.not_selector, node_id
659
+ ):
660
+ continue
661
+ survivors.append((node_id, ancestor_ids, match))
662
+ return _apply_pseudos(survivors, step.pseudos)
663
+
664
+
665
+ def _apply_combinator(
666
+ prev: List[_Candidate], next_candidates: List[_Candidate], combinator: Combinator
667
+ ) -> List[_Candidate]:
668
+ """Narrow ``next_candidates`` to those related to a ``prev`` survivor
669
+ by ``combinator``, exactly mirroring the legacy executor's
670
+ ``_apply_combinator``: direct child compares only the immediate parent
671
+ (the last entry of the ancestor id chain); descendant and recursive
672
+ descendant (both space- and ``//``-spelled in the legacy grammar) admit
673
+ a match anywhere in the ancestor chain.
674
+ """
675
+
676
+ if not prev or not next_candidates:
677
+ return []
678
+ prev_ids = {node_id for node_id, _ancestors, _match in prev}
679
+ if combinator == Combinator.CHILD:
680
+ return [c for c in next_candidates if c[1] and c[1][-1] in prev_ids]
681
+ return [
682
+ c
683
+ for c in next_candidates
684
+ if any(ancestor_id in prev_ids for ancestor_id in c[1])
685
+ ]
686
+
687
+
688
+ def _run_query(
689
+ index: _NodeIndex, parsed_query: Query, *, universe: Optional[FrozenSet[str]] = None
690
+ ) -> List[_Candidate]:
691
+ """Evaluate every step of ``parsed_query`` in order, exactly mirroring
692
+ the legacy executor's ``_eval_query``: the first step's candidates come
693
+ from the whole (or, under ``:not(...)``, the narrowed) universe, and
694
+ each subsequent step's candidates are narrowed again by the combinator
695
+ that precedes it.
696
+ """
697
+
698
+ current = _step_candidates(index, parsed_query.first, universe)
699
+ for combinator, step in parsed_query.rest:
700
+ next_candidates = _step_candidates(index, step, universe)
701
+ current = _apply_combinator(current, next_candidates, combinator)
702
+ return current
703
+
704
+
705
+ def _render_source(plugin: Any, node: Node) -> Optional[str]:
706
+ """Render ``node``'s own source text on request, never by reparsing.
707
+
708
+ Prefers a duck-typed, callable ``plugin.render_fragment`` (the same
709
+ "if callable, use it" convention ``tree_engine.query.adapter
710
+ .resolve_semantic_role`` already established for ``role_for``): this
711
+ regenerates the one node's text from the already-parsed tree through
712
+ the format plugin's own code generator, never through the document's
713
+ source-parsing entry point. Falls back to the node's own stored
714
+ ``content`` field -- the convention already used by
715
+ ``tree_engine.core.node_types`` extension wrappers -- when no such
716
+ renderer is available, and to ``None`` when neither applies.
717
+
718
+ ``node`` comes straight off ``TreeTraversalAdapter.iter_nodes()``, which
719
+ walks the document's live, mutable tree -- a ``LiveNode``, not the
720
+ immutable common-model ``Node`` a format plugin's ``render_fragment``
721
+ contract actually renders from (``tree_engine.core.nodes.Node``, whose
722
+ ``children`` is a tuple and whose node-valued fields are frozen, unlike
723
+ a ``LiveNode``'s mutable back-linked ones). Handing a live node straight
724
+ to a real plugin's ``render_fragment`` violates that contract -- the
725
+ python plugin's ``export_from_common`` rejects it outright
726
+ (``FormatPluginContractError: expected a common-model Node or Document,
727
+ got LiveNode``, bug b4cc5134) -- so it is converted via
728
+ ``tree_engine.core.live_tree.to_frozen`` first, exactly the same
729
+ conversion ``facade._render_source_via_plugin``/
730
+ ``facade._extract_cached_source`` already apply before calling a
731
+ plugin's own render entry points. A synthetic test double that is
732
+ already a common-model ``Node`` (never a ``LiveNode``) is passed through
733
+ unconverted, so the contract tests driving this module with hand-built
734
+ ``Node`` fixtures are unaffected.
735
+
736
+ S6a verifier finding #6: ``renderer(frozen)`` is wrapped in a broad
737
+ ``try``/``except`` -- re-running a format's own code generator on an
738
+ EXTRACTED fragment (rather than the whole originally-parsed tree,
739
+ which is all legacy's own ``code_for_node`` ever does) can genuinely
740
+ fail for a node whose rendering depends on surrounding context LibCST
741
+ no longer has once isolated (measured: a bare ``Param``'s own
742
+ ``MaybeSentinel`` default-equals-sign indicator raises LibCST's own
743
+ ``CSTCodegenError`` when regenerated alone). Legacy has no equivalent
744
+ failure mode at all, so the closest parity available is "no source for
745
+ this one match" rather than propagating a request for one match's text
746
+ into a failure of the whole query.
747
+ """
748
+
749
+ renderer = getattr(plugin, "render_fragment", None)
750
+ if callable(renderer):
751
+ frozen = to_frozen(node) if isinstance(node, LiveNode) else node
752
+ try:
753
+ rendered = renderer(frozen)
754
+ except Exception:
755
+ rendered = None
756
+ if isinstance(rendered, str):
757
+ return rendered
758
+ fields = getattr(node, "fields", None)
759
+ if isinstance(fields, Mapping):
760
+ content = fields.get("content")
761
+ if isinstance(content, str):
762
+ return content
763
+ return None
764
+
765
+
766
+ def _finalize(
767
+ candidates: List[_Candidate], index: _NodeIndex, plugin: Any, include_source: bool
768
+ ) -> List[QueryMatch]:
769
+ """Turn surviving candidates into the ordered ``QueryMatch`` list.
770
+
771
+ Each candidate's ``QueryMatch`` was already assembled by the sibling
772
+ results module while indexing; this function performs no further shape
773
+ computation beyond, on request, attaching rendered ``source`` text via
774
+ ``dataclasses.replace`` -- never rebuilding any other field.
775
+ """
776
+
777
+ if not include_source:
778
+ return [match for _node_id, _ancestors, match in candidates]
779
+ results: List[QueryMatch] = []
780
+ for node_id, _ancestors, match in candidates:
781
+ node = index[node_id][0]
782
+ results.append(replace(match, source=_render_source(plugin, node)))
783
+ return results
784
+
785
+
786
+ class TreeQueryEngine:
787
+ """Binds one already-loaded ``Document`` and its format plugin to the
788
+ full ported cst_query engine (concept C-009): the reused legacy
789
+ selector parser, the sibling traversal adapter, the sibling predicate
790
+ evaluator, and the sibling result-record model, composed into one
791
+ ``query``/``execute`` entry point.
792
+
793
+ ``document`` and ``plugin`` are handed straight to a new
794
+ :class:`~tree_engine.query.adapter.TreeTraversalAdapter`, stored
795
+ exactly as that adapter already documents: the caller is expected to
796
+ have already loaded the document's tree and resolved its format
797
+ plugin, e.g. via ``tree_engine.plugins.selection``.
798
+ """
799
+
800
+ def __init__(self, document: Document, plugin: Any) -> None:
801
+ self._adapter = TreeTraversalAdapter(document, plugin)
802
+
803
+ @property
804
+ def adapter(self) -> TreeTraversalAdapter:
805
+ """The ``TreeTraversalAdapter`` bound to this engine's document/plugin."""
806
+
807
+ return self._adapter
808
+
809
+ def query(self, selector: str, *, include_source: bool = False) -> List[QueryMatch]:
810
+ """Parse ``selector`` (via the reused, unchanged legacy parser) and
811
+ run it. A malformed ``selector`` propagates
812
+ ``ai_editor.core.exceptions.QueryParseError`` straight from the
813
+ parser, untouched.
814
+ """
815
+
816
+ parsed_query = parse_selector(selector)
817
+ return self.execute(parsed_query, include_source=include_source)
818
+
819
+ def execute(
820
+ self, parsed_query: Query, *, include_source: bool = False
821
+ ) -> List[QueryMatch]:
822
+ """Run an already-parsed legacy ``Query`` against this engine's
823
+ document, without ever reparsing its source text ({p040}).
824
+
825
+ Raises the legacy ``QueryParseError`` (``details["error_code"] is
826
+ ErrorCode.INVALID_SELECTOR``) when ``parsed_query`` has no
827
+ executable first step -- see :func:`_require_executable`. Returns
828
+ the ordered list of surviving :class:`~tree_engine.query.results
829
+ .QueryMatch` records, source text attached only when
830
+ ``include_source`` is true.
831
+ """
832
+
833
+ _require_executable(parsed_query)
834
+ index = _index_document(self._adapter)
835
+ candidates = _run_query(index, parsed_query)
836
+ return _finalize(candidates, index, self._adapter.plugin, include_source)
837
+
838
+
839
+ def query(
840
+ document: Document,
841
+ plugin: Any,
842
+ selector: str,
843
+ *,
844
+ include_source: bool = False,
845
+ ) -> List[QueryMatch]:
846
+ """Module-level convenience wrapper: ``TreeQueryEngine(document,
847
+ plugin).query(selector, include_source=include_source)``, for a caller
848
+ that does not need to keep the engine instance around.
849
+ """
850
+
851
+ return TreeQueryEngine(document, plugin).query(
852
+ selector, include_source=include_source
853
+ )