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,497 @@
1
+ """The single format-plugin registry (concept C-010, {p055}, {p059}, {p101}).
2
+
3
+ Scope: the one authority for plugin registration, lookup, and lazy
4
+ entry-point discovery, plus the public ``convert``/``generate_output`` call
5
+ surface built on top of it. Does not define the plugin contract
6
+ (``tree_engine.plugins.contract``), the CORE-side boundary
7
+ (``tree_engine.core.plugin_boundary``), deterministic extension-based
8
+ selection (``tree_engine.plugins.selection`` -- T-002), or any concrete
9
+ plugin (T-002/T-003/T-004). ``FormatPluginRegistry`` is exactly the object
10
+ ``resolve_format_plugin`` expects as its ``registry`` parameter: any object
11
+ exposing ``get_format_plugin(format_id)``.
12
+
13
+ Registration ({p055}): ``register_format_plugin``/``unregister_format_plugin``/
14
+ ``get_format_plugin``/``list_format_plugins`` are the only mutation/lookup
15
+ surface. A ``format_id``, alias, or file extension already claimed by a
16
+ *different* plugin is a configuration error, never silently overwritten;
17
+ re-registering the *same* ``format_id`` requires explicit ``replace=True``.
18
+
19
+ Lazy entry-point discovery ({p059}, {p101}): plugins advertise themselves
20
+ under the standard entry-point group ``ENTRY_POINT_GROUP``. The registry
21
+ reads entry-point *metadata* (name, value) via ``importlib.metadata`` --
22
+ no import needed for that -- and calls ``entry_point.load()`` only the
23
+ first time that ``format_id`` is actually requested. Nothing here scans
24
+ ``sys.path``, imports every installed distribution, or runs discovery code
25
+ beyond the standard entry-point index; nothing runs at core import time --
26
+ discovery happens only inside a ``FormatPluginRegistry`` instance's own
27
+ methods, on demand.
28
+
29
+ Errors: every failure here is a catalog code from
30
+ ``tree_engine.errors.ErrorCode``, wrapped in :class:`PluginRegistrationError`
31
+ (configuration errors) or :class:`FormatPluginNotFoundError` (lookup
32
+ absence) -- no bare ``KeyError``/``ValueError``, no silent ``None``.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import ast
38
+ import importlib.util
39
+ import os
40
+ import sys
41
+ from importlib import metadata as importlib_metadata
42
+ from typing import Any, Dict, Iterator, Mapping, Optional, Tuple
43
+
44
+ from tree_engine.errors import ErrorCode
45
+ from tree_engine.plugins.contract import FormatPluginContract, FormatPluginMetadata
46
+
47
+ __all__ = [
48
+ "ENTRY_POINT_GROUP",
49
+ "PluginRegistrationError",
50
+ "FormatPluginNotFoundError",
51
+ "FormatPluginRegistry",
52
+ "convert",
53
+ "generate_output",
54
+ ]
55
+
56
+ # Standard entry-point group an installable format-plugin package
57
+ # advertises itself under ({p101}). Entry-point *value* is
58
+ # ``"module:attribute"`` -- a module-level ``FormatPluginContract``
59
+ # instance or a zero-arg callable returning one, e.g. ``PYTHON_FORMAT_PLUGIN``
60
+ # in ``tree_engine.plugins.python.plugin``.
61
+ ENTRY_POINT_GROUP = "tree_engine.format_plugins"
62
+
63
+ # Only the major component of a plugin's contract_version must match;
64
+ # an incompatible major is rejected before import, never silently accepted.
65
+ _SUPPORTED_CONTRACT_MAJOR = "1"
66
+
67
+
68
+ class PluginRegistrationError(Exception):
69
+ """Registration- or discovery-time configuration error.
70
+
71
+ Covers a ``format_id``/alias/extension conflict, a malformed or
72
+ unresolvable entry point, plugin metadata that fails structural
73
+ validation, and an incompatible ``contract_version`` -- every case
74
+ where the registry refuses a plugin, as opposed to failing to find one
75
+ already accepted.
76
+ """
77
+
78
+ def __init__(self, *, error_code: ErrorCode, message: str, **details: Any) -> None:
79
+ self.error_code: ErrorCode = error_code
80
+ self.details: Mapping[str, Any] = dict(details)
81
+ super().__init__(message)
82
+
83
+
84
+ class FormatPluginNotFoundError(Exception):
85
+ """Raised when ``get_format_plugin`` cannot resolve ``format_id``.
86
+
87
+ Always carries :attr:`ErrorCode.FORMAT_PLUGIN_NOT_FOUND` -- the single
88
+ explicit failure signal {p053} requires instead of ``None`` or a bare
89
+ ``KeyError``.
90
+ """
91
+
92
+ error_code: ErrorCode = ErrorCode.FORMAT_PLUGIN_NOT_FOUND
93
+
94
+ def __init__(self, *, format_id: str) -> None:
95
+ self.format_id = format_id
96
+ super().__init__(f"no format plugin is registered for format_id {format_id!r}")
97
+
98
+
99
+ class _EntryPointRecord:
100
+ """A not-yet-loaded entry-point candidate, identified by its own name.
101
+
102
+ Uniqueness of ``format_id`` (the entry point's ``name``) is checked
103
+ without loading the plugin. The plugin object is loaded (``.load()``)
104
+ exactly once, on the first call to :meth:`resolve`.
105
+ """
106
+
107
+ __slots__ = ("entry_point", "format_id", "_loaded", "_extensions")
108
+
109
+ def __init__(self, entry_point: Any, format_id: str) -> None:
110
+ self.entry_point = entry_point
111
+ self.format_id = format_id
112
+ self._loaded: Optional[FormatPluginContract] = None
113
+ self._extensions: Optional[Tuple[str, ...]] = None
114
+
115
+ def declared_extensions(self) -> Tuple[str, ...]:
116
+ """The file extensions (lower case, no dot) this entry point's plugin declares.
117
+
118
+ Read from the plugin module's source without importing it (:func:`_static_file_extensions`)
119
+ so listing and resolving an unrelated extension never imports a plugin; a module whose
120
+ declaration is not one literal is imported once, which is the only way to know it.
121
+ """
122
+
123
+ if self._extensions is None:
124
+ found = _static_file_extensions(self.entry_point)
125
+ if found is None:
126
+ found = tuple(self.resolve().metadata.file_extensions)
127
+ self._extensions = tuple(
128
+ (e[1:] if e.startswith(".") else e).lower() for e in found if e
129
+ )
130
+ return self._extensions
131
+
132
+ def resolve(self) -> FormatPluginContract:
133
+ """Import (on first call only) and validate the plugin, then cache it."""
134
+
135
+ if self._loaded is not None:
136
+ return self._loaded
137
+ try:
138
+ candidate = self.entry_point.load()
139
+ except Exception as exc: # noqa: BLE001 - re-raised as a catalog error
140
+ raise PluginRegistrationError(
141
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
142
+ message=f"entry point {self.entry_point.name!r} in group {ENTRY_POINT_GROUP!r} failed to load: {exc}",
143
+ entry_point=self.entry_point.name,
144
+ ) from exc
145
+ plugin = candidate() if isinstance(candidate, type) else candidate
146
+ _validate_plugin(plugin, source=f"entry point {self.entry_point.name!r}")
147
+ if plugin.metadata.format_id != self.format_id:
148
+ raise PluginRegistrationError(
149
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
150
+ message=(
151
+ f"entry point {self.entry_point.name!r} advertises format_id {self.format_id!r} "
152
+ f"but loaded plugin declares {plugin.metadata.format_id!r}"
153
+ ),
154
+ entry_point=self.entry_point.name,
155
+ )
156
+ self._loaded = plugin
157
+ return plugin
158
+
159
+
160
+ def _static_file_extensions(entry_point: Any) -> Optional[Tuple[str, ...]]:
161
+ """The ``file_extensions`` literal of the one ``FormatPluginMetadata(...)`` call in the entry
162
+ point's module, read with ``ast`` and never imported; ``None`` when the module is not a plain
163
+ source file or does not declare exactly one literal tuple of strings."""
164
+
165
+ module_name = str(getattr(entry_point, "value", "")).split(":", 1)[0].strip()
166
+ if not module_name:
167
+ return None
168
+ try:
169
+ spec = importlib.util.find_spec(module_name)
170
+ origin = getattr(spec, "origin", None)
171
+ if not origin or not str(origin).endswith(".py"):
172
+ return None
173
+ with open(origin, "r", encoding="utf-8") as handle:
174
+ tree = ast.parse(handle.read())
175
+ except (ImportError, OSError, ValueError, SyntaxError):
176
+ return None
177
+ declared = []
178
+ for node in ast.walk(tree):
179
+ if not isinstance(node, ast.Call):
180
+ continue
181
+ name = getattr(node.func, "id", None) or getattr(node.func, "attr", None)
182
+ if name != "FormatPluginMetadata":
183
+ continue
184
+ for keyword in node.keywords:
185
+ if keyword.arg != "file_extensions":
186
+ continue
187
+ value = keyword.value
188
+ if not isinstance(value, (ast.Tuple, ast.List)) or not all(
189
+ isinstance(item, ast.Constant) and isinstance(item.value, str)
190
+ for item in value.elts
191
+ ):
192
+ return None
193
+ declared.append(tuple(item.value for item in value.elts))
194
+ return declared[0] if len(declared) == 1 else None
195
+
196
+
197
+ def _path_signature() -> Tuple[Any, ...]:
198
+ """A cheap fingerprint of where distributions can be installed: ``sys.path`` and the
199
+ modification time of each directory on it. A new distribution changes it."""
200
+
201
+ stamps = []
202
+ for entry in sys.path:
203
+ try:
204
+ stamps.append(os.stat(entry or ".").st_mtime_ns)
205
+ except OSError:
206
+ stamps.append(0)
207
+ return (tuple(sys.path), tuple(stamps))
208
+
209
+
210
+ def _validate_plugin(plugin: Any, *, source: str) -> None:
211
+ """Validate a resolved plugin's metadata shape ({p055}, {p056}): a
212
+ ``metadata`` property yielding :class:`FormatPluginMetadata` with a
213
+ non-empty ``format_id``/``plugin_version`` and a supported
214
+ ``contract_version`` -- never file-content probing or sniffing.
215
+ """
216
+
217
+ metadata = getattr(plugin, "metadata", None)
218
+ if not isinstance(metadata, FormatPluginMetadata):
219
+ raise PluginRegistrationError(
220
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
221
+ message=f"{source} did not resolve to a FormatPluginContract with valid metadata",
222
+ )
223
+ for field_name in ("format_id", "plugin_version"):
224
+ if not getattr(metadata, field_name):
225
+ raise PluginRegistrationError(
226
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
227
+ message=f"{source} declares an empty {field_name}",
228
+ )
229
+ _check_contract_version(metadata.contract_version, source=source)
230
+
231
+
232
+ def _check_contract_version(contract_version: str, *, source: str) -> None:
233
+ major = (contract_version or "").split(".", 1)[0]
234
+ if major != _SUPPORTED_CONTRACT_MAJOR:
235
+ raise PluginRegistrationError(
236
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
237
+ message=(
238
+ f"{source} declares contract_version {contract_version!r}, "
239
+ f"incompatible with supported major {_SUPPORTED_CONTRACT_MAJOR!r}"
240
+ ),
241
+ contract_version=contract_version,
242
+ )
243
+
244
+
245
+ class FormatPluginRegistry:
246
+ """The single authority for format-plugin registration and lookup.
247
+
248
+ Satisfies ``tree_engine.plugins.selection.FormatPluginLookup`` (a plain
249
+ ``get_format_plugin(format_id)`` method), so an instance is exactly what
250
+ ``resolve_format_plugin``/``build_extension_table`` expect to be
251
+ injected as ``registry``/among ``plugins``.
252
+ """
253
+
254
+ def __init__(self) -> None:
255
+ self._plugins: Dict[str, FormatPluginContract] = {}
256
+ self._alias_index: Dict[str, str] = {}
257
+ self._extension_index: Dict[str, str] = {}
258
+ self._entry_points: Dict[str, _EntryPointRecord] = {}
259
+ self._entry_point_values: Dict[str, str] = {}
260
+ self._entry_points_scanned = False
261
+ self._scan_signature: Optional[Tuple[Any, ...]] = None
262
+
263
+ # -- manual registration ({p055}) ------------------------------------
264
+
265
+ def register_format_plugin(
266
+ self, plugin: FormatPluginContract, *, replace: bool = False
267
+ ) -> None:
268
+ """Register ``plugin`` under its declared identity.
269
+
270
+ Re-registering an already-registered ``format_id`` requires
271
+ ``replace=True``, else :class:`PluginRegistrationError`. A
272
+ ``format_id``, alias, or extension already claimed by a
273
+ *different* plugin is always a configuration error, ``replace`` or
274
+ not -- ``replace`` only lets a plugin overwrite its own prior entry.
275
+ """
276
+
277
+ _validate_plugin(plugin, source=f"plugin {plugin!r}")
278
+ metadata = plugin.metadata
279
+ format_id = metadata.format_id
280
+
281
+ if format_id in self._plugins and not replace:
282
+ raise PluginRegistrationError(
283
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
284
+ message=(
285
+ f"format_id {format_id!r} is already registered; pass "
286
+ "replace=True to re-register it"
287
+ ),
288
+ format_id=format_id,
289
+ )
290
+
291
+ names = list(self._claimed_names(metadata))
292
+ for kind, name, index in names:
293
+ owner = index.get(name)
294
+ if owner is not None and owner != format_id:
295
+ raise PluginRegistrationError(
296
+ error_code=ErrorCode.FORMAT_EXTENSION_CONFLICT
297
+ if kind == "extension"
298
+ else ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
299
+ message=(
300
+ f"{kind} {name!r} is already claimed by format_id "
301
+ f"{owner!r}, cannot register it for {format_id!r}"
302
+ ),
303
+ **{kind: name, "existing_format_id": owner, "format_id": format_id},
304
+ )
305
+
306
+ self._unindex(format_id)
307
+ self._plugins[format_id] = plugin
308
+ for _, name, index in names:
309
+ index[name] = format_id
310
+ self._entry_points.pop(format_id, None)
311
+
312
+ def unregister_format_plugin(self, format_id: str) -> None:
313
+ """Remove ``format_id`` and every alias/extension it claimed.
314
+
315
+ Silently accepts an unknown ``format_id``: a no-op, not an error.
316
+ """
317
+
318
+ self._unindex(format_id)
319
+ self._plugins.pop(format_id, None)
320
+ self._entry_points.pop(format_id, None)
321
+
322
+ def get_format_plugin(self, format_id: str) -> FormatPluginContract:
323
+ """Resolve ``format_id`` (a primary id or alias).
324
+
325
+ Order: an already-registered/loaded plugin first, then lazy
326
+ entry-point discovery ({p059}, {p101}) -- importing at most the one
327
+ matching entry point. Raises :class:`FormatPluginNotFoundError`
328
+ when nothing matches.
329
+ """
330
+
331
+ resolved_id = self._alias_index.get(format_id, format_id)
332
+ plugin = self._plugins.get(resolved_id)
333
+ if plugin is not None:
334
+ return plugin
335
+
336
+ self._ensure_entry_points_scanned()
337
+ record = self._entry_points.get(format_id) or self._entry_points.get(resolved_id)
338
+ if record is not None:
339
+ plugin = record.resolve()
340
+ self.register_format_plugin(plugin, replace=True)
341
+ return plugin
342
+
343
+ raise FormatPluginNotFoundError(format_id=format_id)
344
+
345
+ def list_format_plugins(self) -> Tuple[FormatPluginMetadata, ...]:
346
+ """Return metadata for every currently *loaded* plugin.
347
+
348
+ Deliberately does not force-load every discoverable entry point --
349
+ that would defeat laziness ({p059}). Call :meth:`get_format_plugin`
350
+ first for a ``format_id`` to bring it into this list.
351
+ """
352
+
353
+ return tuple(plugin.metadata for plugin in self._plugins.values())
354
+
355
+ # -- lazy entry-point discovery ({p059}, {p101}) ----------------------
356
+
357
+ def _load_entry_point_plugins(self) -> None:
358
+ """Index (but do not import) every candidate entry point, once.
359
+
360
+ Reads ``importlib.metadata.entry_points(group=ENTRY_POINT_GROUP)``
361
+ -- package index metadata, not a ``sys.path`` scan and not an
362
+ import of any distribution. Each candidate's ``format_id`` (the
363
+ entry point's own ``name``) is checked against already-known names
364
+ before it is indexed; nothing is imported here.
365
+ """
366
+
367
+ signature = _path_signature()
368
+ if self._entry_points_scanned and signature == self._scan_signature:
369
+ return
370
+ self._entry_points_scanned = True
371
+ self._scan_signature = signature
372
+
373
+ try:
374
+ candidates = importlib_metadata.entry_points(group=ENTRY_POINT_GROUP)
375
+ except Exception as exc: # noqa: BLE001 - surfaced as a configuration error
376
+ raise PluginRegistrationError(
377
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
378
+ message=f"failed to read entry-point group {ENTRY_POINT_GROUP!r}: {exc}",
379
+ ) from exc
380
+
381
+ seen_in_scan: set = set()
382
+ for entry_point in candidates:
383
+ format_id = entry_point.name
384
+ duplicate_in_scan = format_id in seen_in_scan
385
+ seen_in_scan.add(format_id)
386
+ if not format_id:
387
+ raise PluginRegistrationError(
388
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
389
+ message=(
390
+ f"entry point {entry_point!r} in group {ENTRY_POINT_GROUP!r} "
391
+ "has an empty name"
392
+ ),
393
+ )
394
+ value = str(getattr(entry_point, "value", ""))
395
+ if not duplicate_in_scan and self._entry_point_values.get(format_id) == value:
396
+ continue # seen by an earlier scan (still pending or already loaded)
397
+ if format_id in self._plugins or format_id in self._entry_points:
398
+ raise PluginRegistrationError(
399
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
400
+ message=(
401
+ f"entry point {entry_point.name!r} in group "
402
+ f"{ENTRY_POINT_GROUP!r} duplicates an already-known format_id"
403
+ ),
404
+ format_id=format_id,
405
+ )
406
+ self._entry_point_values[format_id] = value
407
+ self._entry_points[format_id] = _EntryPointRecord(entry_point, format_id)
408
+
409
+ def entry_point_format_ids(self) -> Tuple[str, ...]:
410
+ """The ``format_id`` of every discovered entry-point plugin not yet loaded (names only,
411
+ nothing imported). Rescans when the set of installed distributions may have changed."""
412
+
413
+ self._ensure_entry_points_scanned()
414
+ return tuple(self._entry_points)
415
+
416
+ def entry_point_extensions(self, format_id: str) -> Tuple[str, ...]:
417
+ """The extensions a discovered, not yet loaded entry-point plugin declares (no dot, lower
418
+ case); read statically, see :meth:`_EntryPointRecord.declared_extensions`."""
419
+
420
+ self._ensure_entry_points_scanned()
421
+ record = self._entry_points.get(format_id)
422
+ return record.declared_extensions() if record is not None else ()
423
+
424
+ def _ensure_entry_points_scanned(self) -> None:
425
+ self._load_entry_point_plugins()
426
+
427
+ # -- internal bookkeeping ----------------------------------------------
428
+
429
+ def _claimed_names(
430
+ self, metadata: FormatPluginMetadata
431
+ ) -> Iterator[Tuple[str, str, Dict[str, str]]]:
432
+ for alias in (metadata.format_id, *metadata.aliases):
433
+ yield "alias", alias, self._alias_index
434
+ for extension in metadata.file_extensions:
435
+ normalized = extension[1:] if extension.startswith(".") else extension
436
+ yield "extension", normalized.lower(), self._extension_index
437
+
438
+ def _unindex(self, format_id: str) -> None:
439
+ existing = self._plugins.get(format_id)
440
+ if existing is None:
441
+ return
442
+ for _, name, index in self._claimed_names(existing.metadata):
443
+ if index.get(name) == format_id:
444
+ del index[name]
445
+
446
+
447
+ # -- module-level default registry and public conversion API ({p053}, {p054}) --
448
+
449
+ _DEFAULT_REGISTRY = FormatPluginRegistry()
450
+
451
+
452
+ def convert(
453
+ common_model: Any,
454
+ *,
455
+ target_format_id: str,
456
+ options: Optional[Mapping[str, Any]] = None,
457
+ registry: Optional[FormatPluginRegistry] = None,
458
+ ) -> Any:
459
+ """Resolve ``target_format_id`` and run the plugin's export stage.
460
+
461
+ Finds the registered plugin, runs ``export_from_common`` on
462
+ ``common_model``, and returns its plugin-specific representation
463
+ verbatim, exactly as {p053} specifies. A deliberate, documented
464
+ exception to "backend representations stay inside the plugin" -- the
465
+ same kind of one-purpose bridge as a plugin's own
466
+ ``import_tree``/``export_tree`` pair ({p048}); the external
467
+ parser/codegen library's own AST/CST type is never touched here, only
468
+ what the plugin's translator already produced. Raises
469
+ :class:`FormatPluginNotFoundError` when ``target_format_id`` is not
470
+ registered; propagates ``UnsupportedTranslationError``/
471
+ ``FormatPluginContractError`` unchanged -- never a default, never a
472
+ dropped node.
473
+ """
474
+
475
+ plugin = (registry or _DEFAULT_REGISTRY).get_format_plugin(target_format_id)
476
+ return plugin.export_from_common(common_model, dict(options or {}))
477
+
478
+
479
+ def generate_output(
480
+ common_model: Any,
481
+ target_format_id: str,
482
+ options: Optional[Mapping[str, Any]] = None,
483
+ *,
484
+ registry: Optional[FormatPluginRegistry] = None,
485
+ ) -> Any:
486
+ """Resolve ``target_format_id`` and run export + output generation.
487
+
488
+ Per {p054}: selects the plugin, exports to its backend representation,
489
+ then generates final text/bytes -- for explicit export/save only, never
490
+ after every mutation. Raises :class:`FormatPluginNotFoundError` when
491
+ ``target_format_id`` is not registered; a plugin failure propagates
492
+ unchanged rather than being masked.
493
+ """
494
+
495
+ plugin = (registry or _DEFAULT_REGISTRY).get_format_plugin(target_format_id)
496
+ exported = plugin.export_from_common(common_model, dict(options or {}))
497
+ return plugin.generate_output(exported, dict(options or {}))
@@ -0,0 +1,87 @@
1
+ """Built-in plugin discovery by scanning ``tree_engine/plugins/`` (matrix decision D-CB.3, P3).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ A built-in format is a module (or a package with a ``plugin`` module) under ``tree_engine/plugins/`` that holds a module-level
7
+ plugin object named ``PLUGIN`` or ``<NAME>_FORMAT_PLUGIN``, an instance of a class defined in that same module. Dropping such a
8
+ module in is the whole act of adding a format: ``facade.py`` is not edited.
9
+
10
+ Two kinds of module are not scanned for auto-registration. The language plugins declared in ``detachable.py`` are loaded through
11
+ their declaration, because their parser library may be missing and that must be a typed refusal, not an ImportError. The C-family
12
+ package is shipped but never registered (the editor serves those files as text, bug 3aa93da8).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import importlib
18
+ import os
19
+ from typing import Any, List, Tuple
20
+
21
+ from tree_engine.plugins.contract import FormatPluginMetadata
22
+
23
+ __all__ = ["scan_builtin_plugins"]
24
+
25
+ #: Modules of this package that hold infrastructure, never a plugin.
26
+ _INFRASTRUCTURE = frozenset(
27
+ {"contract", "registry", "selection", "fallback", "detachable", "json_pointer", "scan"}
28
+ )
29
+ #: Shipped but intentionally not auto-registered (see the module docstring).
30
+ _NOT_AUTO_REGISTERED = frozenset({"cpp"})
31
+ #: The order ``list_formats()`` has always reported the data formats in; only used to keep that
32
+ #: order stable. A format not named here follows, in module-name order.
33
+ _LEGACY_ORDER = ("json", "toml", "yaml", "ini", "xml", "markdown", "jsonl", "plain_text")
34
+
35
+
36
+ def _plugin_objects(module: Any) -> List[Any]:
37
+ found = []
38
+ for name, value in vars(module).items():
39
+ if not (name == "PLUGIN" or name.endswith("_FORMAT_PLUGIN")):
40
+ continue
41
+ if type(value).__module__ != module.__name__:
42
+ continue # imported from another module; that module registers it
43
+ if isinstance(getattr(value, "metadata", None), FormatPluginMetadata):
44
+ found.append(value)
45
+ return found
46
+
47
+
48
+ def _candidates(package: Any) -> List[Tuple[str, bool]]:
49
+ """(name, is_package) of every module file and every directory holding a ``plugin.py`` in the
50
+ package path. The directories are namespace packages (no ``__init__.py``), which
51
+ ``pkgutil.iter_modules`` does not list."""
52
+
53
+ found = {}
54
+ for root in package.__path__:
55
+ for entry in sorted(os.scandir(root), key=lambda e: e.name):
56
+ if entry.is_file() and entry.name.endswith(".py") and entry.name != "__init__.py":
57
+ found[entry.name[:-3]] = False
58
+ elif entry.is_dir() and os.path.isfile(os.path.join(entry.path, "plugin.py")):
59
+ found[entry.name] = True
60
+ return sorted(found.items())
61
+
62
+
63
+ def scan_builtin_plugins(package: Any, skip_modules: frozenset = frozenset()) -> List[Any]:
64
+ """Every plugin object found by scanning ``package`` (``tree_engine.plugins``), in a stable order.
65
+
66
+ ``skip_modules`` are dotted module names loaded elsewhere (the detachable language plugins).
67
+ """
68
+
69
+ plugins: List[Any] = []
70
+ seen = set()
71
+ for name, ispkg in _candidates(package):
72
+ if name.startswith("_") or name in _INFRASTRUCTURE or name in _NOT_AUTO_REGISTERED:
73
+ continue
74
+ dotted = f"{package.__name__}.{name}" + (".plugin" if ispkg else "")
75
+ if dotted in skip_modules:
76
+ continue
77
+ module = importlib.import_module(dotted)
78
+ for plugin in _plugin_objects(module):
79
+ if id(plugin) not in seen:
80
+ seen.add(id(plugin))
81
+ plugins.append(plugin)
82
+
83
+ def rank(plugin: Any) -> int:
84
+ fid = plugin.metadata.format_id
85
+ return _LEGACY_ORDER.index(fid) if fid in _LEGACY_ORDER else len(_LEGACY_ORDER)
86
+
87
+ return sorted(plugins, key=rank) # stable: ties keep module-name order