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,382 @@
1
+ """Full-document reference-integrity validator (concept C-008).
2
+
3
+ Scope (concept C-008, the last of four ReferenceIntegrity siblings): this
4
+ module owns exactly one entry point, :func:`validate_full_document`, that
5
+ ``export_tree``, ``generate_output``, and the storage-layer handoff must
6
+ call before producing output, per {p083}. Where the already-merged
7
+ ``core/integrity.py`` (:func:`~tree_engine.core.integrity.validate_after_mutation`)
8
+ deliberately bounds its checks to changed nodes and their immediate
9
+ neighbours ({p082}), this module drives the *same* low-level primitives
10
+ across every node, id, and index entry of the document, plus the checks
11
+ that only make sense at whole-document scope: id/short_id uniqueness,
12
+ external-address syntax and resolver-based liveness, cycle detection, and
13
+ range/version consistency.
14
+
15
+ Reuse, not reimplementation: this module imports ``core/integrity.py``'s
16
+ own private per-item check functions (``_index_of``, ``_Scope``,
17
+ ``_check_parent_child_symmetry``, ``_check_cache_conformance``,
18
+ ``_check_backlinks``, ``_check_local_resolvability``) and drives each of
19
+ them once per node/edge/address instead of re-deriving equivalent
20
+ symmetry/cache/backlink/resolvability logic. Those functions already
21
+ raise :class:`~tree_engine.core.integrity.IntegrityError` on the first
22
+ mismatch of a given single-item scope; calling them per item, rather than
23
+ once over a scope covering the whole document, is what turns their
24
+ fail-fast behaviour into the aggregate-all-violations behaviour {p083}
25
+ requires without touching a line of their bodies. External-address syntax
26
+ reuses ``core/references.py``'s own round-trip helpers
27
+ (``node_address_to_string`` / ``parse_node_address``) rather than
28
+ reimplementing UUID-shape checking. The generation fast-path check for
29
+ cache and range/version conformance reuses the exact comparison
30
+ ``core/reference_cache.py`` defines for {p084} (``cached_generation`` vs.
31
+ the live ``nodes_by_id`` entry's ``generation``).
32
+
33
+ Duck-typed ``document`` contract, extending the one ``integrity.py``
34
+ already uses: ``document`` is either a
35
+ :class:`~tree_engine.core.reference_cache.ReferenceIndex` itself, or any
36
+ object exposing one through a ``reference_index`` attribute. Three further
37
+ attributes are read only if present, each an independent, purely
38
+ additive extension point -- their absence never blocks validation, it only
39
+ narrows what gets checked:
40
+
41
+ * ``root`` -- a :class:`~tree_engine.core.nodes.Node` (per {p016}'s
42
+ "explicit full check" case), walked to cross-check the raw node graph's
43
+ own ``node_id`` values for duplicates the index's dict-keyed maps cannot
44
+ represent by construction.
45
+ * ``ranges`` -- a mapping or iterable of range records, each either an
46
+ object exposing ``node_id``/``generation`` or a ``(node_id,
47
+ generation)`` pair, checked against the node's live generation.
48
+ * ``version`` and ``version_generations`` -- a document version marker
49
+ plus the ``node_id -> generation`` snapshot it was computed from, that
50
+ full validation confirms is still current.
51
+
52
+ This module performs no mutation, in any code path, of ``document``, its
53
+ index maps, or any cache entry -- including on the raising path -- and
54
+ implements no export/generate/storage I/O of its own; it is only the
55
+ validator those layers must call.
56
+
57
+ Source-of-truth requirement labels honored here: {p016}, {p042}, {p080},
58
+ {p081}, {p083}, {p084}.
59
+ """
60
+
61
+ from __future__ import annotations
62
+
63
+ from collections import Counter
64
+ from dataclasses import dataclass
65
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
66
+ from uuid import UUID
67
+
68
+ from tree_engine.core.identity import NodeAddress
69
+ from tree_engine.core.integrity import (
70
+ IntegrityError,
71
+ _Scope,
72
+ _check_backlinks,
73
+ _check_cache_conformance,
74
+ _check_local_resolvability,
75
+ _check_parent_child_symmetry,
76
+ _index_of,
77
+ )
78
+ from tree_engine.core.nodes import walk as walk_nodes
79
+ from tree_engine.core.reference_cache import ReferenceIndex
80
+ from tree_engine.core.references import (
81
+ InvalidNodeAddressError,
82
+ is_external,
83
+ is_local,
84
+ node_address_to_string,
85
+ parse_node_address,
86
+ )
87
+
88
+ __all__ = ["FullIntegrityError", "FullIntegrityReport", "validate_full_document"]
89
+
90
+ #: A resolver probes whether an external document is loaded. It takes the
91
+ #: target ``document_id`` and returns ``None`` when that document is not
92
+ #: loaded/unavailable (legal per {p083}), or -- when it is loaded -- an
93
+ #: object exposing membership for node ids, either directly (``in``) or via
94
+ #: a ``nodes_by_id`` mapping attribute, mirroring ``_index_of``'s own
95
+ #: duck typing.
96
+ DocumentResolver = Callable[[UUID], Optional[Any]]
97
+
98
+ Violation = Tuple[str, str]
99
+
100
+
101
+ class FullIntegrityError(IntegrityError):
102
+ """Raised by :func:`validate_full_document` with every violation found.
103
+
104
+ Subclasses ``integrity.py``'s :class:`~tree_engine.core.integrity.IntegrityError`
105
+ so a caller already handling that type also catches this one, per the
106
+ instruction to reuse the existing violation/error type rather than
107
+ defining a parallel hierarchy. ``violations`` is the full, ordered
108
+ tuple of ``(check, message)`` pairs found in a single run -- this
109
+ error is only ever raised once all checks have run, never on the
110
+ first mismatch. ``check`` reuses the exact vocabulary
111
+ :class:`IntegrityError` already defines (``"symmetry"``,
112
+ ``"cache-conformance"``, ``"backlink"``, ``"local-resolvability"``)
113
+ for the checks that are full-scope replays of ``integrity.py``'s own,
114
+ plus the full-document-only additions this module introduces:
115
+ ``"uniqueness"``, ``"external-address"``, ``"cycle"``, and
116
+ ``"range-version"``.
117
+ """
118
+
119
+ def __init__(self, violations: Iterable[Violation]) -> None:
120
+ self.violations: Tuple[Violation, ...] = tuple(violations)
121
+ lead_check = self.violations[0][0] if self.violations else "full-integrity"
122
+ summary = "; ".join(message for _check, message in self.violations)
123
+ super().__init__(lead_check, f"{len(self.violations)} violation(s): {summary}")
124
+
125
+
126
+ @dataclass(frozen=True)
127
+ class FullIntegrityReport:
128
+ """Success summary of one :func:`validate_full_document` run.
129
+
130
+ ``nodes_checked`` is the number of registered index entries examined
131
+ by the structural checks; ``ids_checked`` is the number of raw
132
+ node_id occurrences examined for the uniqueness check (from the
133
+ ``root`` walk when supplied, otherwise the same as ``nodes_checked``);
134
+ ``external_references_checked`` counts every external ``NodeAddress``
135
+ examined, whether or not its document was loaded; ``unresolved_external``
136
+ lists the syntactically-valid external references whose target
137
+ document is not loaded -- informational per {p083}, never a violation.
138
+ """
139
+
140
+ nodes_checked: int
141
+ ids_checked: int
142
+ external_references_checked: int
143
+ unresolved_external: Tuple[NodeAddress, ...]
144
+
145
+
146
+ def _record(violations: List[Violation], exc: IntegrityError) -> None:
147
+ violations.append((exc.check, str(exc)))
148
+
149
+
150
+ def _check_uniqueness(document: Any, index: ReferenceIndex, violations: List[Violation]) -> int:
151
+ """Duplicate node_id (via ``root``) and duplicate short_id ({p097})."""
152
+
153
+ root = getattr(document, "root", None)
154
+ ids_checked = len(index.nodes_by_id)
155
+ if root is not None:
156
+ seen = [node.node_id for node in walk_nodes(root) if getattr(node, "node_id", None) is not None]
157
+ ids_checked = len(seen)
158
+ for node_id, count in Counter(seen).items():
159
+ if count > 1:
160
+ violations.append((
161
+ "uniqueness",
162
+ f"node_id {node_id} appears {count} times in the document's node graph",
163
+ ))
164
+
165
+ by_short_id: Dict[Any, List[UUID]] = {}
166
+ for node_id, short_id in index.node_id_to_short_id.items():
167
+ by_short_id.setdefault(short_id, []).append(node_id)
168
+ for short_id, node_ids in by_short_id.items():
169
+ if len(node_ids) > 1:
170
+ violations.append((
171
+ "uniqueness",
172
+ f"short_id {short_id!r} is used by {len(node_ids)} distinct node ids: "
173
+ f"{sorted(str(n) for n in node_ids)}",
174
+ ))
175
+ return ids_checked
176
+
177
+
178
+ def _check_full_symmetry_and_cache(index: ReferenceIndex, violations: List[Violation]) -> None:
179
+ """Drive ``integrity.py``'s per-item symmetry/backlink/cache checks over every entry."""
180
+
181
+ for node_id in index.nodes_by_id:
182
+ scope = _Scope(node_ids={node_id})
183
+ try:
184
+ _check_parent_child_symmetry(index, scope)
185
+ except IntegrityError as exc:
186
+ _record(violations, exc)
187
+ try:
188
+ _check_cache_conformance(index, scope)
189
+ except IntegrityError as exc:
190
+ _record(violations, exc)
191
+
192
+ for source_id, targets in index.outgoing_refs.items():
193
+ for address in targets:
194
+ try:
195
+ _check_backlinks(index, _Scope(outgoing_edges={(source_id, address)}))
196
+ except IntegrityError as exc:
197
+ _record(violations, exc)
198
+ for target_id, sources in index.incoming_refs.items():
199
+ for source_id in sources:
200
+ try:
201
+ _check_backlinks(index, _Scope(incoming_edges={(target_id, source_id)}))
202
+ except IntegrityError as exc:
203
+ _record(violations, exc)
204
+
205
+
206
+ def _resolver_target(loaded: Any) -> Any:
207
+ return getattr(loaded, "nodes_by_id", loaded)
208
+
209
+
210
+ def _check_local_and_external(
211
+ index: ReferenceIndex,
212
+ resolver: Optional[DocumentResolver],
213
+ violations: List[Violation],
214
+ ) -> Tuple[int, Tuple[NodeAddress, ...]]:
215
+ """Full local resolvability ({p081}) plus external syntax/liveness ({p083})."""
216
+
217
+ external_checked = 0
218
+ unresolved: List[NodeAddress] = []
219
+
220
+ for source_id, targets in index.outgoing_refs.items():
221
+ for address in targets:
222
+ if is_local(address):
223
+ try:
224
+ _check_local_resolvability(index, _Scope(loose_addresses={address}))
225
+ except IntegrityError as exc:
226
+ _record(violations, exc)
227
+ continue
228
+
229
+ external_checked += 1
230
+ try:
231
+ parse_node_address(node_address_to_string(address))
232
+ except InvalidNodeAddressError as exc:
233
+ violations.append((
234
+ "external-address",
235
+ f"node {source_id}'s external reference {address!r} is malformed: {exc}",
236
+ ))
237
+ continue
238
+
239
+ if resolver is None:
240
+ unresolved.append(address)
241
+ continue
242
+
243
+ loaded = resolver(address.document_id)
244
+ if loaded is None:
245
+ unresolved.append(address)
246
+ continue
247
+ if address.node_id not in _resolver_target(loaded):
248
+ violations.append((
249
+ "external-address",
250
+ f"node {source_id}'s external reference {address!r} points at a "
251
+ "loaded document that does not contain that node_id",
252
+ ))
253
+
254
+ return external_checked, tuple(unresolved)
255
+
256
+
257
+ def _check_cycles(index: ReferenceIndex, violations: List[Violation]) -> None:
258
+ """Detect forbidden reference cycles in the parent/child structure ({p083}).
259
+
260
+ Iterative three-colour DFS over ``child_index`` so it never depends on
261
+ Python's recursion limit. Runs across every node in ``nodes_by_id``
262
+ (not just those reachable from a single root) so a cycle in a
263
+ detached fragment is still caught. On finding a back-edge it records
264
+ the cycle and keeps scanning -- it does not stop at the first one.
265
+ """
266
+
267
+ color: Dict[UUID, int] = {}
268
+ for start in index.nodes_by_id:
269
+ if color.get(start, 0) != 0:
270
+ continue
271
+ path = [start]
272
+ color[start] = 1
273
+ stack = [(start, iter(index.get_children(start)))]
274
+ while stack:
275
+ node_id, children = stack[-1]
276
+ advanced = False
277
+ for child_id in children:
278
+ if child_id not in index.nodes_by_id:
279
+ continue
280
+ state = color.get(child_id, 0)
281
+ if state == 0:
282
+ color[child_id] = 1
283
+ path.append(child_id)
284
+ stack.append((child_id, iter(index.get_children(child_id))))
285
+ advanced = True
286
+ break
287
+ if state == 1:
288
+ cycle = path[path.index(child_id):] + [child_id]
289
+ violations.append((
290
+ "cycle",
291
+ "forbidden reference cycle detected: "
292
+ + " -> ".join(str(n) for n in cycle),
293
+ ))
294
+ if not advanced:
295
+ stack.pop()
296
+ path.pop()
297
+ color[node_id] = 2
298
+
299
+
300
+ def _range_fields(entry: Any) -> Optional[Tuple[UUID, int]]:
301
+ if isinstance(entry, tuple) and len(entry) == 2:
302
+ return entry[0], entry[1]
303
+ node_id = getattr(entry, "node_id", None)
304
+ generation = getattr(entry, "generation", None)
305
+ if node_id is None or generation is None:
306
+ return None
307
+ return node_id, generation
308
+
309
+
310
+ def _iter_range_entries(ranges: Any) -> Iterable[Any]:
311
+ if hasattr(ranges, "values"):
312
+ return ranges.values()
313
+ return ranges
314
+
315
+
316
+ def _check_ranges_and_version(document: Any, index: ReferenceIndex, violations: List[Violation]) -> None:
317
+ """Range and document-version consistency against live generations ({p084}, {p083})."""
318
+
319
+ ranges = getattr(document, "ranges", None)
320
+ if ranges:
321
+ for entry in _iter_range_entries(ranges):
322
+ fields = _range_fields(entry)
323
+ if fields is None:
324
+ continue
325
+ node_id, recorded_generation = fields
326
+ live_generation = index.get_generation(node_id)
327
+ if live_generation is None or live_generation != recorded_generation:
328
+ violations.append((
329
+ "range-version",
330
+ f"range for node {node_id} is stale: recorded generation "
331
+ f"{recorded_generation!r}, live generation {live_generation!r}",
332
+ ))
333
+
334
+ version = getattr(document, "version", None)
335
+ version_generations = getattr(document, "version_generations", None)
336
+ if version is not None and version_generations:
337
+ for node_id, recorded_generation in version_generations.items():
338
+ live_generation = index.get_generation(node_id)
339
+ if live_generation is None or live_generation != recorded_generation:
340
+ violations.append((
341
+ "range-version",
342
+ f"document version {version!r} is inconsistent: node {node_id} "
343
+ f"recorded generation {recorded_generation!r}, live generation "
344
+ f"{live_generation!r}",
345
+ ))
346
+
347
+
348
+ def validate_full_document(
349
+ document: Any,
350
+ *,
351
+ resolver: Optional[DocumentResolver] = None,
352
+ ) -> FullIntegrityReport:
353
+ """Validate the whole document's reference integrity before export ({p083}).
354
+
355
+ Read-only in every branch: never mutates ``document``, its index
356
+ maps, or any cache entry, whether it returns normally or raises.
357
+ Runs, aggregating every violation rather than stopping at the first:
358
+ id/short_id uniqueness, full local resolvability, external-address
359
+ syntax and resolver-based liveness, direct-object cache conformance,
360
+ full parent/child and incoming/outgoing symmetry, cycle absence, and
361
+ range/version consistency. Raises :class:`FullIntegrityError` if any
362
+ check found a violation; otherwise returns a :class:`FullIntegrityReport`.
363
+ """
364
+
365
+ index = _index_of(document)
366
+ violations: List[Violation] = []
367
+
368
+ ids_checked = _check_uniqueness(document, index, violations)
369
+ _check_full_symmetry_and_cache(index, violations)
370
+ external_checked, unresolved_external = _check_local_and_external(index, resolver, violations)
371
+ _check_cycles(index, violations)
372
+ _check_ranges_and_version(document, index, violations)
373
+
374
+ if violations:
375
+ raise FullIntegrityError(violations)
376
+
377
+ return FullIntegrityReport(
378
+ nodes_checked=len(index.nodes_by_id),
379
+ ids_checked=ids_checked,
380
+ external_references_checked=external_checked,
381
+ unresolved_external=unresolved_external,
382
+ )
@@ -0,0 +1,260 @@
1
+ """Mutation journal for concept C-005 (MutationJournal).
2
+
3
+ This module implements the journal that records every mutation to the object tree.
4
+ Per the C-005 contract, each applied facade operation (insert, delete, replace, move,
5
+ set_attribute, set_body, replace_node_id) appends exactly one journal entry. A move
6
+ across parent boundaries applied as two facade commits (source parent delete, target
7
+ parent insert) yields two entries.
8
+
9
+ The journal defines five boundary events at which full-document operations are
10
+ permitted (INITIAL_LOAD, EXPLICIT_FULL_CHECK, EXTERNAL_MODIFICATION_RECOVERY,
11
+ BATCH_CONTROL_CHECK, POSITION_MAP_DERIVATION), and supports undo/redo by tracking
12
+ entries up to a save boundary — the undo horizon moves with the save boundary per
13
+ the owner's redesign.
14
+
15
+ Listeners (e.g., position_map.py) register with the journal to be notified after
16
+ each entry is appended. The journal's cost is O(1) plus listener count per mutation,
17
+ never proportional to document size or journal length.
18
+
19
+ This module is self-contained on the standard library. It does not import any
20
+ sibling module from tree_engine.core, and position_map.py imports FROM this file
21
+ (never the reverse).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from dataclasses import dataclass
27
+ from enum import Enum
28
+ from typing import Any, List, Mapping, Optional, Protocol, Tuple
29
+
30
+ __all__ = [
31
+ "JournalEntry",
32
+ "JournalListener",
33
+ "BoundaryEvent",
34
+ "MutationJournal",
35
+ ]
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class JournalEntry:
40
+ """A single entry in the mutation journal.
41
+
42
+ Records WHAT changed in the object tree. Entries carry the operation name,
43
+ the path to the touched node, and minimal op-specific payload (e.g. byte-size
44
+ delta for the subtree_bytes aggregate). Positional data is never stored in
45
+ the entry itself; it is derived by listeners on demand.
46
+
47
+ Attributes:
48
+ seq: Monotonic sequence number, 1-based. Stable across truncation
49
+ (offset is subtracted from retained entries).
50
+ op: The applied facade operation name: 'insert', 'delete', 'replace',
51
+ 'move', 'set_attribute', 'set_body', 'replace_node_id', or 'boundary'.
52
+ node_path: Tuple of node IDs from root to the touched node (inclusive).
53
+ parent_id: ID of the parent containing the touched node.
54
+ payload: Op-specific minimal data (e.g. {'size_delta': 3}). For boundary
55
+ entries, payload is {'event': <BoundaryEvent.name>}.
56
+ """
57
+
58
+ seq: int
59
+ op: str
60
+ node_path: Tuple[str, ...]
61
+ parent_id: str
62
+ payload: Mapping[str, Any]
63
+
64
+
65
+ class JournalListener(Protocol):
66
+ """Interface implemented by consumers that react to journal entries.
67
+
68
+ Sibling ``position_map.py`` implements this to invalidate its cache when
69
+ a mutation occurs. The editor's session-history surface (G-029/T-001/A-003)
70
+ composes entries for undo/redo. This module defines the interface only;
71
+ it does not implement or instantiate any listener.
72
+ """
73
+
74
+ def on_journal_entry(self, entry: JournalEntry) -> None:
75
+ ...
76
+
77
+
78
+ class BoundaryEvent(Enum):
79
+ """The five and only five events at which a full parse or full-document
80
+ traversal is permitted.
81
+
82
+ Per {p016}, these are the explicit boundaries where O(document) operations
83
+ are contracted. At each boundary, derived caches (e.g. position_map) can
84
+ record the seq they are valid for, and undo/redo can reset to that boundary.
85
+ """
86
+
87
+ INITIAL_LOAD = "INITIAL_LOAD"
88
+ EXPLICIT_FULL_CHECK = "EXPLICIT_FULL_CHECK"
89
+ EXTERNAL_MODIFICATION_RECOVERY = "EXTERNAL_MODIFICATION_RECOVERY"
90
+ BATCH_CONTROL_CHECK = "BATCH_CONTROL_CHECK"
91
+ POSITION_MAP_DERIVATION = "POSITION_MAP_DERIVATION"
92
+
93
+
94
+ class MutationJournal:
95
+ """The journal that records every mutation to the object tree.
96
+
97
+ Mutations are applied via the mutation engine (C-006, G-002), which calls
98
+ ``append()`` exactly once per applied facade operation. The journal assigns
99
+ a monotonic seq number, stores the entry, notifies all registered listeners
100
+ in registration order, and returns the entry. Cost is O(1) plus listener
101
+ count, never proportional to document size or journal length.
102
+
103
+ A cross-parent move applied as two facade commits (source parent delete,
104
+ target parent insert) yields two separate entries.
105
+
106
+ Boundary events are marked via ``mark_boundary()``, which appends a
107
+ checkpoint entry (op='boundary') that shares the seq numbering, allowing
108
+ caches derived at the boundary to record the seq they are valid for.
109
+
110
+ The undo horizon moves with the save boundary per the owner's redesign.
111
+ ``truncate_before()`` removes entries before a given seq, keeping the
112
+ seq numbering stable (internal offset is subtracted from retained entries).
113
+ """
114
+
115
+ def __init__(self) -> None:
116
+ self._entries: List[JournalEntry] = []
117
+ self._seq: int = 0
118
+ self._seq_offset: int = 0 # seq subtracted from retained entries
119
+ self._listeners: List[JournalListener] = []
120
+
121
+ def append(
122
+ self,
123
+ op: str,
124
+ node_path: Tuple[str, ...],
125
+ parent_id: str,
126
+ payload: Mapping[str, Any],
127
+ ) -> JournalEntry:
128
+ """Append a journal entry after one applied facade operation.
129
+
130
+ The mutation engine (C-006) calls this exactly once per applied
131
+ operation. This method assigns the next seq number, creates and stores
132
+ the entry, notifies all registered listeners in registration order,
133
+ and returns the entry.
134
+
135
+ Cost is O(1) plus listener count; never proportional to document size
136
+ or journal length.
137
+
138
+ Args:
139
+ op: The facade operation name (e.g. 'insert', 'delete', 'replace',
140
+ 'move', 'set_attribute', 'set_body', 'replace_node_id').
141
+ node_path: Tuple of node IDs from root to the touched node.
142
+ parent_id: ID of the parent containing the touched node.
143
+ payload: Op-specific minimal data (e.g. {'size_delta': 3}).
144
+
145
+ Returns:
146
+ The newly appended JournalEntry.
147
+ """
148
+ self._seq += 1
149
+ entry = JournalEntry(
150
+ seq=self._seq,
151
+ op=op,
152
+ node_path=tuple(node_path),
153
+ parent_id=parent_id,
154
+ payload=payload,
155
+ )
156
+ self._entries.append(entry)
157
+ for listener in self._listeners:
158
+ listener.on_journal_entry(entry)
159
+ return entry
160
+
161
+ def mark_boundary(self, event: BoundaryEvent) -> JournalEntry:
162
+ """Append a boundary checkpoint entry.
163
+
164
+ Marks one of the five permitted full-document operation boundaries.
165
+ The entry is appended with op='boundary' and payload={'event': <name>},
166
+ sharing the seq numbering so a cache derived at the boundary can record
167
+ the seq it is valid for.
168
+
169
+ Args:
170
+ event: The BoundaryEvent marking this checkpoint.
171
+
172
+ Returns:
173
+ The newly appended boundary JournalEntry.
174
+ """
175
+ return self.append(
176
+ op="boundary",
177
+ node_path=(),
178
+ parent_id="",
179
+ payload={"event": event.name},
180
+ )
181
+
182
+ @property
183
+ def last_seq(self) -> int:
184
+ """The seq number of the most recently appended entry (0 if journal is empty)."""
185
+ return self._seq
186
+
187
+ def entries_since(self, seq: int) -> Tuple[JournalEntry, ...]:
188
+ """Return all entries with seq > given seq.
189
+
190
+ Must be O(result size), not O(journal length). Uses index arithmetic:
191
+ entry at index i has seq = offset + i + 1, so entries_since(seq)
192
+ starts at index seq - offset.
193
+
194
+ Args:
195
+ seq: The cutoff sequence number (exclusive).
196
+
197
+ Returns:
198
+ Tuple of entries with seq > cutoff, in seq order.
199
+ """
200
+ if seq >= self._seq:
201
+ return ()
202
+ start_index = seq - self._seq_offset
203
+ if start_index < 0:
204
+ start_index = 0
205
+ return tuple(self._entries[start_index:])
206
+
207
+ def truncate_before(self, seq: int) -> int:
208
+ """Drop all entries with seq < given seq.
209
+
210
+ Keeps seq numbering stable for retained entries: after truncate_before(N),
211
+ the first kept entry (at index 0) has seq = N, and offset = N - 1.
212
+ Entry at index i has seq = offset + i + 1.
213
+
214
+ Args:
215
+ seq: All entries with seq < this value will be dropped.
216
+
217
+ Returns:
218
+ The count of entries dropped.
219
+ """
220
+ if seq <= self._seq_offset:
221
+ return 0
222
+ if seq > self._seq:
223
+ dropped = len(self._entries)
224
+ self._entries.clear()
225
+ self._seq_offset = seq - 1
226
+ return dropped
227
+
228
+ # Find first index where seq = offset + i + 1 >= target seq
229
+ # Want: offset + i + 1 >= seq, so i >= seq - offset - 1
230
+ first_keep_index = seq - self._seq_offset - 1
231
+ if first_keep_index <= 0:
232
+ return 0
233
+
234
+ dropped = first_keep_index
235
+ self._entries = self._entries[first_keep_index:]
236
+ self._seq_offset = seq - 1
237
+ return dropped
238
+
239
+ def add_listener(self, listener: JournalListener) -> None:
240
+ """Register a listener to be notified after each entry is appended.
241
+
242
+ Listeners are notified in registration order.
243
+
244
+ Args:
245
+ listener: An object implementing the JournalListener protocol.
246
+ """
247
+ self._listeners.append(listener)
248
+
249
+ def remove_listener(self, listener: JournalListener) -> None:
250
+ """Unregister a previously registered listener.
251
+
252
+ If the listener is not registered, this is a no-op.
253
+
254
+ Args:
255
+ listener: The listener to remove.
256
+ """
257
+ try:
258
+ self._listeners.remove(listener)
259
+ except ValueError:
260
+ pass