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,571 @@
1
+ """Journal composition and inversion for concept G-014 (undo/redo journaling).
2
+
3
+ This module implements the pure composition and inversion layer over JournalEntry
4
+ sequences, enabling undo/redo, diff views, and unified rendering of mutations without
5
+ materializing any document copy or traversing the full tree.
6
+
7
+ Key concepts:
8
+ - Inversion: Each operation is reversible; boundary entries are not.
9
+ - Composition: Contiguous entry sequences collapse under specific rules:
10
+ * An insert immediately followed by a delete of the SAME node cancel out entirely.
11
+ * Two edits to the same node's same property collapse to net effect (first before,
12
+ last after).
13
+ * Unrelated entries are preserved in order without collapsing.
14
+ * A move is surfaced AS a move (two adjacent move entries fold into one composed item).
15
+ * Boundary entries partition composition: edits are never collapsed ACROSS a boundary.
16
+ - Diff view: Composed items between two journal positions without materializing the
17
+ document.
18
+ - Rendering: Unified-diff-style text from before/after fragments; structured data
19
+ rendered as pseudo-hunks.
20
+
21
+ All functions are total over well-formed entries and raise ValueError naming the offending
22
+ seq for malformed input (e.g., a lone move entry with no pair, unknown op).
23
+
24
+ Cost: All functions O(entries considered), never O(document size).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from dataclasses import dataclass
30
+ from typing import Any, List, Mapping, Optional, Tuple, Union
31
+
32
+ from tree_engine.core.journal import JournalEntry
33
+
34
+ __all__ = [
35
+ "InverseOp",
36
+ "ComposedItem",
37
+ "invert_entry",
38
+ "compose_entries",
39
+ "diff_between",
40
+ "render_unified",
41
+ ]
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class InverseOp:
46
+ """The inverse operation description for undo.
47
+
48
+ Represents the logical inverse of a JournalEntry, suitable for applying
49
+ through the facade to undo the original operation. Boundary entries are
50
+ not invertible.
51
+
52
+ Attributes:
53
+ op: The inverted facade operation name (e.g., 'delete' for an original 'insert').
54
+ node_path: Tuple of node IDs from root to the touched node (same as original).
55
+ parent_id: ID of the parent containing the touched node. For moves, parent_id is
56
+ passed through unchanged; the caller reconstructs the move-back target from the
57
+ removal entry's parent_id and anchor.
58
+ payload: Op-specific data with before/after swapped relative to the original.
59
+ """
60
+
61
+ op: str
62
+ node_path: Tuple[str, ...]
63
+ parent_id: str
64
+ payload: Mapping[str, Any]
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class ComposedItem:
69
+ """A single item in the composed view of a journal entry sequence.
70
+
71
+ Represents the net effect of one or more collapsed journal entries, or a boundary
72
+ marker that partitions composition.
73
+
74
+ Attributes:
75
+ kind: 'edit' for a mutation, 'move' for a move operation, 'boundary' for a
76
+ full-document checkpoint.
77
+ op: The facade operation name (e.g., 'delete', 'set_attribute', 'move').
78
+ node_id: The last element of the touched node's path (the touched node itself).
79
+ Empty for boundary entries.
80
+ before: The source/state before the net effect (str/bytes/dict/None).
81
+ after: The source/state after the net effect (str/bytes/dict/None).
82
+ source_parent_id: For moves: the ID of the parent before the move.
83
+ For other kinds: always "".
84
+ target_parent_id: For moves: the ID of the parent after the move.
85
+ For other kinds: always "".
86
+ parent_id: ID of the parent containing the touched node (for non-moves).
87
+ seqs: Tuple of seq numbers of the journal entries that contributed to this item.
88
+ boundary_event: For 'boundary' kind: the event name (from payload['event']).
89
+ """
90
+
91
+ kind: str # 'edit', 'move', 'boundary'
92
+ op: str
93
+ node_id: str # Last element of node_path
94
+ before: Union[str, bytes, dict, None]
95
+ after: Union[str, bytes, dict, None]
96
+ source_parent_id: str = "" # For moves only
97
+ target_parent_id: str = "" # For moves only
98
+ parent_id: str = "" # For non-moves only
99
+ seqs: Tuple[int, ...] = ()
100
+ boundary_event: Optional[str] = None
101
+
102
+
103
+ def invert_entry(entry: JournalEntry) -> InverseOp:
104
+ """Compute the inverse operation for undo.
105
+
106
+ For text operations (insert, delete, replace, set_body, apply_subtree),
107
+ swaps before/after and inverts insert<->delete. For move, swaps source
108
+ and target parent_id. For structured operations (set_attribute, replace_node_id),
109
+ swaps before/after. Boundary entries are not invertible and raise ValueError.
110
+
111
+ Args:
112
+ entry: The journal entry to invert.
113
+
114
+ Returns:
115
+ An InverseOp describing the logical inverse operation.
116
+
117
+ Raises:
118
+ ValueError: If the entry is a boundary or has an unknown operation.
119
+
120
+ Cost: O(1).
121
+ """
122
+ if entry.op == "boundary":
123
+ raise ValueError(f"Boundary entries are not invertible (seq {entry.seq})")
124
+
125
+ if entry.op == "insert":
126
+ # Insert inverts to delete
127
+ inverted_op = "delete"
128
+ inverted_payload = {
129
+ "size_delta": -entry.payload.get("size_delta", 0),
130
+ "before": entry.payload.get("after"),
131
+ "after": None,
132
+ }
133
+ # Pass through anchor unchanged
134
+ if "anchor" in entry.payload:
135
+ inverted_payload["anchor"] = entry.payload["anchor"]
136
+ elif entry.op == "delete":
137
+ # Delete inverts to insert
138
+ inverted_op = "insert"
139
+ inverted_payload = {
140
+ "size_delta": -entry.payload.get("size_delta", 0),
141
+ "before": None,
142
+ "after": entry.payload.get("before"),
143
+ }
144
+ # Pass through anchor unchanged
145
+ if "anchor" in entry.payload:
146
+ inverted_payload["anchor"] = entry.payload["anchor"]
147
+ # Pass through root trailing separator restoration if present (bug 1f11a73b)
148
+ if "root_trailing_separator_before" in entry.payload:
149
+ inverted_payload["root_trailing_separator_restore"] = entry.payload["root_trailing_separator_before"]
150
+ elif entry.op == "replace":
151
+ # Replace swaps before/after
152
+ inverted_op = "replace"
153
+ inverted_payload = {
154
+ "size_delta": -entry.payload.get("size_delta", 0),
155
+ "before": entry.payload.get("after"),
156
+ "after": entry.payload.get("before"),
157
+ }
158
+ # Pass through anchor unchanged
159
+ if "anchor" in entry.payload:
160
+ inverted_payload["anchor"] = entry.payload["anchor"]
161
+ elif entry.op == "move":
162
+ # Move swaps source and target parent_id
163
+ inverted_op = "move"
164
+ # Keep the fragment same; caller will swap parent_ids
165
+ inverted_payload = {
166
+ "size_delta": entry.payload.get("size_delta", 0),
167
+ "before": entry.payload.get("before"),
168
+ "after": entry.payload.get("after"),
169
+ }
170
+ # Pass through anchor unchanged
171
+ if "anchor" in entry.payload:
172
+ inverted_payload["anchor"] = entry.payload["anchor"]
173
+ elif entry.op == "set_body":
174
+ # set_body swaps before/after
175
+ inverted_op = "set_body"
176
+ inverted_payload = {
177
+ "size_delta": -entry.payload.get("size_delta", 0),
178
+ "before": entry.payload.get("after"),
179
+ "after": entry.payload.get("before"),
180
+ }
181
+ # Pass through anchor unchanged
182
+ if "anchor" in entry.payload:
183
+ inverted_payload["anchor"] = entry.payload["anchor"]
184
+ elif entry.op == "set_attribute":
185
+ # set_attribute swaps before/after
186
+ inverted_op = "set_attribute"
187
+ inverted_payload = {
188
+ "size_delta": 0,
189
+ "before": entry.payload.get("after"),
190
+ "after": entry.payload.get("before"),
191
+ }
192
+ # anchor should be None for set_attribute, but pass through if present
193
+ if "anchor" in entry.payload:
194
+ inverted_payload["anchor"] = entry.payload["anchor"]
195
+ elif entry.op == "replace_node_id":
196
+ # replace_node_id swaps before/after
197
+ inverted_op = "replace_node_id"
198
+ inverted_payload = {
199
+ "size_delta": 0,
200
+ "before": entry.payload.get("after"),
201
+ "after": entry.payload.get("before"),
202
+ }
203
+ # anchor should be None for replace_node_id, but pass through if present
204
+ if "anchor" in entry.payload:
205
+ inverted_payload["anchor"] = entry.payload["anchor"]
206
+ elif entry.op == "apply_subtree":
207
+ # apply_subtree swaps before/after
208
+ inverted_op = "apply_subtree"
209
+ inverted_payload = {
210
+ "size_delta": -entry.payload.get("size_delta", 0),
211
+ "before": entry.payload.get("after"),
212
+ "after": entry.payload.get("before"),
213
+ }
214
+ # Pass through anchor unchanged
215
+ if "anchor" in entry.payload:
216
+ inverted_payload["anchor"] = entry.payload["anchor"]
217
+ else:
218
+ raise ValueError(f"Unknown operation '{entry.op}' (seq {entry.seq})")
219
+
220
+ return InverseOp(
221
+ op=inverted_op,
222
+ node_path=entry.node_path,
223
+ parent_id=entry.parent_id,
224
+ payload=inverted_payload,
225
+ )
226
+
227
+
228
+ def _touched_node_id(entry: JournalEntry) -> Optional[str]:
229
+ """The identity of the node an entry touches: the last element of node_path.
230
+
231
+ This is the ONLY identity that is guaranteed stable across the two halves of a
232
+ cross-parent move and across an insert/delete pair for the same node. The full
233
+ node_path is NOT stable in either case (bug 0718bb18):
234
+ - facade.py's ``move()`` captures the removal entry's node_path through the
235
+ SOURCE parent chain (before the splice) but lets the addition entry's
236
+ node_path be computed on-the-fly through the TARGET parent chain (after the
237
+ splice) -- two different tuples for the same touched node.
238
+ - facade.py's ``delete()`` runs the core delete (which detaches
239
+ ``touched_node.parent``) BEFORE ``_commit_mutation`` walks the parent chain,
240
+ so a delete entry's node_path collapses to a single-element ``(node_id,)``
241
+ while the matching insert's node_path is the full root-to-node chain.
242
+
243
+ Returns None for an empty node_path (e.g. a boundary entry, which never reaches
244
+ this helper in practice).
245
+
246
+ Cost: O(1).
247
+ """
248
+ return entry.node_path[-1] if entry.node_path else None
249
+
250
+
251
+ def _get_property_key(entry: JournalEntry) -> str:
252
+ """Compute the property key for an entry.
253
+
254
+ For set_attribute, the key is 'attr:<name>'. For other operations,
255
+ the key is 'text'. This allows set_attribute edits to the same name
256
+ on the same node to collapse, but not with other operation types.
257
+
258
+ Cost: O(1).
259
+ """
260
+ if entry.op == "set_attribute":
261
+ # For set_attribute, the name is nested in the before/after dicts
262
+ # Read from payload['before']['name'] or payload['after']['name']
263
+ before = entry.payload.get("before")
264
+ if isinstance(before, dict) and "name" in before:
265
+ return f"attr:{before['name']}"
266
+ after = entry.payload.get("after")
267
+ if isinstance(after, dict) and "name" in after:
268
+ return f"attr:{after['name']}"
269
+ # If neither has a name, treat as non-collapsible
270
+ return f"attr:__unique_{entry.seq}"
271
+ return "text"
272
+
273
+
274
+ def compose_entries(entries: List[JournalEntry]) -> List[ComposedItem]:
275
+ """Compose a sequence of journal entries into their net effects.
276
+
277
+ Collapses entries under the following rules:
278
+ 1. An insert immediately followed by a delete of the SAME node (same last element
279
+ of node_path) cancel out entirely, leaving no trace.
280
+ 2. Two edits to the same node's same property collapse to their net effect:
281
+ - For set_attribute: same payload['name']
282
+ - For text ops: all treated as 'text' property
283
+ For collapsed edits, the first entry's before and the last entry's after form
284
+ the net effect; intermediate edits are absorbed.
285
+ 3. Unrelated entries are preserved in order without collapsing.
286
+ 4. A move is surfaced as ONE composed item: two adjacent entries with op=='move'
287
+ arriving as a contiguous pair (same touched node -- the last element of
288
+ node_path -- with different parent_ids) fold into a single item with both
289
+ source and target parent_id. The two halves' FULL node_path is not compared:
290
+ a real cross-parent move's removal entry walks the source ancestor chain and
291
+ its addition entry walks the target ancestor chain (bug 0718bb18).
292
+ 5. Boundary entries partition composition: edits are never collapsed ACROSS a
293
+ boundary, and boundary entries are surfaced as markers in the output.
294
+
295
+ Args:
296
+ entries: A list of JournalEntry objects (may be empty).
297
+
298
+ Returns:
299
+ A list of ComposedItem objects representing the composed view.
300
+
301
+ Raises:
302
+ ValueError: If a lone move entry is encountered (unpaired), an unknown
303
+ operation, or other malformed input (named by seq).
304
+
305
+ Cost: O(len(entries)).
306
+ """
307
+ if not entries:
308
+ return []
309
+
310
+ composed: List[ComposedItem] = []
311
+ i = 0
312
+
313
+ # Known operations that are valid in journal entries
314
+ KNOWN_OPS = {
315
+ "insert",
316
+ "delete",
317
+ "replace",
318
+ "set_body",
319
+ "set_attribute",
320
+ "move",
321
+ "replace_node_id",
322
+ "apply_subtree",
323
+ "boundary",
324
+ }
325
+
326
+ while i < len(entries):
327
+ entry = entries[i]
328
+
329
+ # Boundary entries partition composition: emit as-is
330
+ if entry.op == "boundary":
331
+ boundary_event = entry.payload.get("event", "")
332
+ composed.append(
333
+ ComposedItem(
334
+ kind="boundary",
335
+ op="boundary",
336
+ node_id="",
337
+ before=None,
338
+ after=None,
339
+ seqs=(entry.seq,),
340
+ boundary_event=boundary_event,
341
+ )
342
+ )
343
+ i += 1
344
+ continue
345
+
346
+ # Validate that the operation is known
347
+ if entry.op not in KNOWN_OPS:
348
+ raise ValueError(f"Unknown operation '{entry.op}' (seq {entry.seq})")
349
+
350
+ # Check for move pair (two adjacent moves touching the same node -- see
351
+ # _touched_node_id for why this must key on the touched node id, not on full
352
+ # node_path equality: a real cross-parent move's two halves carry different
353
+ # ancestor chains, bug 0718bb18).
354
+ if entry.op == "move":
355
+ entry_node_id = _touched_node_id(entry)
356
+ if (
357
+ i + 1 < len(entries)
358
+ and entries[i + 1].op == "move"
359
+ and entry_node_id is not None
360
+ and _touched_node_id(entries[i + 1]) == entry_node_id
361
+ ):
362
+ # This is a cross-parent move: two move entries
363
+ second = entries[i + 1]
364
+ node_id = entry_node_id
365
+ composed.append(
366
+ ComposedItem(
367
+ kind="move",
368
+ op="move",
369
+ node_id=node_id,
370
+ before=entry.payload.get("before"),
371
+ after=entry.payload.get("after"),
372
+ source_parent_id=entry.parent_id,
373
+ target_parent_id=second.parent_id,
374
+ seqs=(entry.seq, second.seq),
375
+ )
376
+ )
377
+ i += 2
378
+ continue
379
+ else:
380
+ # Lone move entry (malformed input)
381
+ raise ValueError(f"Unpaired move entry (seq {entry.seq})")
382
+
383
+ # Check for insert+delete cancellation (immediate adjacency, same node -- keyed
384
+ # on the touched node id, not full node_path equality: delete's node_path is a
385
+ # single-element (node_id,) because facade.py's delete() detaches the node's
386
+ # parent before the journal entry is built, while insert's node_path is the
387
+ # full ancestor chain, bug 0718bb18).
388
+ if (
389
+ entry.op == "insert"
390
+ and i + 1 < len(entries)
391
+ and entries[i + 1].op == "delete"
392
+ and _touched_node_id(entry) is not None
393
+ and _touched_node_id(entries[i + 1]) == _touched_node_id(entry)
394
+ ):
395
+ # They cancel out; skip both
396
+ i += 2
397
+ continue
398
+
399
+ # Collect consecutive edits to same node+property for collapsing
400
+ node_path = entry.node_path
401
+ node_id = node_path[-1] if node_path else ""
402
+ prop_key = _get_property_key(entry)
403
+
404
+ # Find the end of the run of same-node same-property edits
405
+ j = i + 1
406
+ collected_seqs = [entry.seq]
407
+ before_fragment = entry.payload.get("before")
408
+ after_fragment = entry.payload.get("after")
409
+
410
+ while j < len(entries):
411
+ next_entry = entries[j]
412
+
413
+ # Boundary breaks the collection
414
+ if next_entry.op == "boundary":
415
+ break
416
+
417
+ # Check if next entry is for same node+property
418
+ if next_entry.node_path != node_path:
419
+ break
420
+
421
+ if _get_property_key(next_entry) != prop_key:
422
+ break
423
+
424
+ # Collapse: update after_fragment and remember the seq
425
+ after_fragment = next_entry.payload.get("after")
426
+ collected_seqs.append(next_entry.seq)
427
+ j += 1
428
+
429
+ # Emit the composed item
430
+ composed.append(
431
+ ComposedItem(
432
+ kind="edit",
433
+ op=entry.op,
434
+ node_id=node_id,
435
+ before=before_fragment,
436
+ after=after_fragment,
437
+ parent_id=entry.parent_id,
438
+ seqs=tuple(collected_seqs),
439
+ )
440
+ )
441
+ i = j
442
+
443
+ return composed
444
+
445
+
446
+ def diff_between(
447
+ entries: List[JournalEntry], from_seq: int, to_seq: int
448
+ ) -> List[ComposedItem]:
449
+ """Compute composed items strictly between two journal positions.
450
+
451
+ Returns only items where from_seq < seq <= to_seq, composed under the same
452
+ rules as compose_entries(). This operation never materializes any document copy.
453
+
454
+ Args:
455
+ entries: A list of JournalEntry objects.
456
+ from_seq: The exclusive lower bound (entries with seq > from_seq are included).
457
+ to_seq: The inclusive upper bound (entries with seq <= to_seq are included).
458
+
459
+ Returns:
460
+ A list of ComposedItem objects strictly between the bounds.
461
+
462
+ Raises:
463
+ ValueError: If from_seq > to_seq.
464
+
465
+ Cost: O(number of entries in range).
466
+ """
467
+ if from_seq > to_seq:
468
+ raise ValueError(f"from_seq ({from_seq}) > to_seq ({to_seq})")
469
+
470
+ # Filter entries in range
471
+ entries_in_range = [e for e in entries if from_seq < e.seq <= to_seq]
472
+
473
+ # Compose the range
474
+ return compose_entries(entries_in_range)
475
+
476
+
477
+ def render_unified(composed_items: List[ComposedItem]) -> str:
478
+ """Render composed items as unified-diff-style text.
479
+
480
+ For each item with text fragments (str/bytes before/after), renders a unified
481
+ diff hunk. For items lacking text fragments (structured dict payloads or None),
482
+ renders the structured form as a single-line pseudo-hunk. Boundary items are
483
+ rendered as markers. Bytes fragments are decoded UTF-8 with 'replace' error
484
+ handling.
485
+
486
+ Args:
487
+ composed_items: A list of ComposedItem objects.
488
+
489
+ Returns:
490
+ A unified-diff-style string (may be empty if no items).
491
+
492
+ Cost: O(total size of rendered fragments).
493
+ """
494
+ lines: List[str] = []
495
+
496
+ for item in composed_items:
497
+ if item.kind == "boundary":
498
+ # Render boundary as a marker line
499
+ event = item.boundary_event or "UNKNOWN"
500
+ lines.append(f"@@ BOUNDARY: {event} @@")
501
+ continue
502
+
503
+ # Decode fragments if bytes
504
+ before_text = None
505
+ after_text = None
506
+
507
+ if isinstance(item.before, bytes):
508
+ before_text = item.before.decode("utf-8", errors="replace")
509
+ elif isinstance(item.before, str):
510
+ before_text = item.before
511
+ elif item.before is None:
512
+ before_text = ""
513
+ else:
514
+ # Structured data (dict)
515
+ before_text = None
516
+
517
+ if isinstance(item.after, bytes):
518
+ after_text = item.after.decode("utf-8", errors="replace")
519
+ elif isinstance(item.after, str):
520
+ after_text = item.after
521
+ elif item.after is None:
522
+ after_text = ""
523
+ else:
524
+ # Structured data (dict)
525
+ after_text = None
526
+
527
+ # Handle structured data (no text fragments available)
528
+ if before_text is None or after_text is None:
529
+ # Pseudo-hunk for structured data
530
+ before_str = _format_structured(item.before)
531
+ after_str = _format_structured(item.after)
532
+ lines.append(f"@@ {item.op} on {item.node_id} @@")
533
+ lines.append(f"- {before_str}")
534
+ lines.append(f"+ {after_str}")
535
+ continue
536
+
537
+ # Text-based diff hunk
538
+ before_lines = before_text.splitlines(keepends=True)
539
+ after_lines = after_text.splitlines(keepends=True)
540
+
541
+ # Unified diff header
542
+ lines.append(f"@@ {item.op} on {item.node_id} @@")
543
+
544
+ # Emit before lines with '-' prefix
545
+ for line in before_lines:
546
+ if line.endswith("\n"):
547
+ lines.append(f"- {line.rstrip()}")
548
+ else:
549
+ lines.append(f"- {line}")
550
+
551
+ # Emit after lines with '+' prefix
552
+ for line in after_lines:
553
+ if line.endswith("\n"):
554
+ lines.append(f"+ {line.rstrip()}")
555
+ else:
556
+ lines.append(f"+ {line}")
557
+
558
+ return "\n".join(lines)
559
+
560
+
561
+ def _format_structured(value: Any) -> str:
562
+ """Format a structured value (dict/None) as a single-line pseudo-hunk.
563
+
564
+ Cost: O(size of value).
565
+ """
566
+ if value is None:
567
+ return "(none)"
568
+ if isinstance(value, dict):
569
+ items = [f"{k}={repr(v)}" for k, v in sorted(value.items())]
570
+ return "{" + ", ".join(items) + "}"
571
+ return repr(value)