@abraca/dabra 2.36.0 → 2.38.0

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.
package/dist/index.d.ts CHANGED
@@ -5256,6 +5256,20 @@ declare class TreeManager {
5256
5256
  rename(docId: string, label: string): void;
5257
5257
  /** Move a document to a new parent. */
5258
5258
  move(docId: string, newParentId?: string | null, order?: number): void;
5259
+ /**
5260
+ * Heal converged move-cycles in the stored tree itself.
5261
+ *
5262
+ * The read paths already present a cycle-free, fully-reachable tree
5263
+ * without writing (see {@link cycleBreakIds}); this *persists* that repair
5264
+ * into the CRDT so the stored structure is acyclic too — useful as a
5265
+ * one-shot on load, or behind a "repair tree" action. Deterministic and
5266
+ * convergent: every replica computes the identical break set, so even
5267
+ * concurrent calls from multiple peers write the same `parentId: null` and
5268
+ * converge. Returns the number of nodes reparented to root (0 when already
5269
+ * acyclic — the common case, where no transaction is opened). Optional —
5270
+ * the always-on read guard already makes the corruption invisible.
5271
+ */
5272
+ repairTree(): number;
5259
5273
  /** Change the page type of a document. */
5260
5274
  changeType(docId: string, type: string): void;
5261
5275
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/dabra",
3
- "version": "2.36.0",
3
+ "version": "2.38.0",
4
4
  "description": "abracadabra provider",
5
5
  "keywords": [
6
6
  "abracadabra",
@@ -41,7 +41,7 @@
41
41
  "yjs": "^13.6.8"
42
42
  },
43
43
  "devDependencies": {
44
- "@abraca/schema": "2.36.0"
44
+ "@abraca/schema": "2.38.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -660,6 +660,19 @@ export class AbracadabraProvider extends AbracadabraBaseProvider {
660
660
  }
661
661
 
662
662
  unloadChild(childId: string) {
663
+ // A PINNED child is actively bound to an open UI view (a TipTap editor or
664
+ // a page-type renderer reading this exact Y.Doc). Destroying it detaches
665
+ // the Y.Doc and wipes its WebSocket route, so the open view goes blank —
666
+ // "title + meta render, body never arrives, fixed only by a full reload".
667
+ // Pinning is the UI's ownership claim: ONLY `unpinChild` may release a
668
+ // pinned doc, after which LRU eviction reclaims it normally. Background
669
+ // indexers (search/file index + blob prefetch via BackgroundSyncManager)
670
+ // and subdoc-removal cleanup must never tear a pinned doc out from under
671
+ // the view — this guard is the hard invariant that makes that impossible.
672
+ // (Full provider `destroy()` bypasses this: it tears children down
673
+ // directly, which is correct for whole-provider teardown.)
674
+ if (this.pinnedChildren.has(childId)) return;
675
+
663
676
  const provider = this.childProviders.get(childId);
664
677
  if (provider) {
665
678
  provider.destroy();
@@ -676,6 +689,17 @@ export class AbracadabraProvider extends AbracadabraBaseProvider {
676
689
  */
677
690
  pinChild(childId: string) {
678
691
  this.pinnedChildren.add(childId);
692
+ // Pinning means the UI is actively using this doc, so it is no longer a
693
+ // mere transient indexer scan. Promote it OUT of transient so that:
694
+ // (a) the background indexer's "still ours" check (`isChildTransient`)
695
+ // correctly leaves it alone even when the UI reused the provider
696
+ // WITHOUT going back through `loadChild` (e.g. resolving it from an
697
+ // already-open tree) — the gap that let the indexer's finally-unload
698
+ // destroy the doc being viewed; and
699
+ // (b) once unpinned it is a normal evictable child again, instead of
700
+ // leaking forever as an unreclaimable transient (evictLRU skips
701
+ // transient children).
702
+ this.transientChildren.delete(childId);
679
703
  }
680
704
 
681
705
  /**
@@ -5,19 +5,19 @@
5
5
  * Extracted from `mcp/tools/tree.ts` and `cli/commands/documents.ts` logic.
6
6
  * All tree CRUD operations go through this class.
7
7
  */
8
- import * as Y from "yjs";
8
+ import type * as Y from "yjs";
9
9
  import type {
10
+ PageMeta,
10
11
  TreeEntry,
11
12
  TreeNode,
12
13
  TreeSearchResult,
13
- PageMeta,
14
14
  } from "./DocTypes.ts";
15
15
  import { resolvePageType } from "./DocTypes.ts";
16
16
  import {
17
- toPlain,
18
- normalizeRootId,
19
17
  makeEntryMap,
18
+ normalizeRootId,
20
19
  patchEntry,
20
+ toPlain,
21
21
  } from "./DocUtils.ts";
22
22
  import type { DocumentManager } from "./DocumentManager.ts";
23
23
  import {
@@ -40,6 +40,62 @@ function cmpEntry(a: TreeEntry, b: TreeEntry): number {
40
40
  return cmpKey(a.order ?? 0, a.id, b.order ?? 0, b.id);
41
41
  }
42
42
 
43
+ /**
44
+ * Deterministic, convergent cycle break for the parent-pointer forest.
45
+ *
46
+ * Concurrent offline reparents converge (Yjs LWW on each entry's *own*
47
+ * `parentId` key) to a state that can contain a directed cycle — e.g. peer A
48
+ * moves X under Y while peer B moves Y under X yields `X.parent=Y` AND
49
+ * `Y.parent=X`. Both writes touch different keys so both survive, and the
50
+ * whole subtree then floats unreachable from root (the "orphaned subtree"
51
+ * corruption — §3b of OFFLINE-FIRST-TREE-AUDIT). Yjs guarantees every replica
52
+ * converges to the SAME cyclic map, so any repair that is a pure function of
53
+ * that map is itself convergent: every replica picks the identical break and
54
+ * agrees on the result with no coordinator (a lightweight stand-in for the
55
+ * full Kleppmann fold — it loses one move's intent, but never corrupts).
56
+ *
57
+ * Rule: in each cycle, the node with the lexicographically-greatest id is
58
+ * logically reparented to root. Returns the set of such break-node ids — empty
59
+ * when the forest is already acyclic (the overwhelmingly common case, so the
60
+ * hot path adds one O(n) walk and changes no behavior).
61
+ *
62
+ * `parentOf` returns the effective *normalized* parent (null = root); a parent
63
+ * id absent from `ids` is a strand, not a cycle (Tier-0 does not auto-rescue
64
+ * strands). Self-loops (`parentId === id`) are a degenerate one-node cycle and
65
+ * are handled. The Rust provider mirrors this exactly (`cycle_break_ids`).
66
+ */
67
+ function cycleBreakIds(
68
+ ids: Iterable<string>,
69
+ parentOf: (id: string) => string | null,
70
+ ): Set<string> {
71
+ const idSet = new Set(ids);
72
+ const done = new Set<string>();
73
+ const breaks = new Set<string>();
74
+ for (const start of idSet) {
75
+ if (done.has(start)) continue;
76
+ const path: string[] = [];
77
+ const onPath = new Map<string, number>();
78
+ let cur: string | null = start;
79
+ while (cur !== null && idSet.has(cur) && !done.has(cur)) {
80
+ const seenAt = onPath.get(cur);
81
+ if (seenAt !== undefined) {
82
+ // path[seenAt..] is the cycle; break its greatest id.
83
+ let maxId = path[seenAt];
84
+ for (let i = seenAt + 1; i < path.length; i++) {
85
+ if (path[i] > maxId) maxId = path[i];
86
+ }
87
+ breaks.add(maxId);
88
+ break;
89
+ }
90
+ onPath.set(cur, path.length);
91
+ path.push(cur);
92
+ cur = parentOf(cur);
93
+ }
94
+ for (const id of path) done.add(id);
95
+ }
96
+ return breaks;
97
+ }
98
+
43
99
  /** Opaque, dependency-free cursor over the (order,id) sibling order. */
44
100
  function encodeCursor(order: number, id: string): string {
45
101
  return encodeURIComponent(JSON.stringify([order ?? 0, id]));
@@ -126,11 +182,10 @@ export class TreeManager {
126
182
  private rebuildIndex(treeMap: Y.Map<unknown>): void {
127
183
  const root = this.dm.rootDocId;
128
184
  const byId = new Map<string, TreeEntry>();
129
- const childrenByParent = new Map<string | null, TreeEntry[]>();
130
185
  treeMap.forEach((raw: unknown, id: string) => {
131
186
  const value = toPlain(raw) as Record<string, unknown>;
132
187
  if (typeof value !== "object" || value === null) return;
133
- const entry: TreeEntry = {
188
+ byId.set(id, {
134
189
  id,
135
190
  label: (value.label as string) || "Untitled",
136
191
  parentId: normalizeRootId(
@@ -142,15 +197,31 @@ export class TreeManager {
142
197
  meta: value.meta as PageMeta | undefined,
143
198
  createdAt: value.createdAt as number | undefined,
144
199
  updatedAt: value.updatedAt as number | undefined,
145
- };
146
- byId.set(id, entry);
200
+ });
201
+ });
202
+ // Converge concurrent-move cycles: logically reparent each cycle's
203
+ // break node to root so the materialized adjacency is acyclic and
204
+ // fully reachable. Non-mutating — the CRDT is untouched; only this
205
+ // read-side cache is corrected (`repairTree()` persists the fix when
206
+ // a writer wants it). No-op for the common acyclic tree. See
207
+ // {@link cycleBreakIds}.
208
+ const breaks = cycleBreakIds(
209
+ byId.keys(),
210
+ (id) => byId.get(id)?.parentId ?? null,
211
+ );
212
+ for (const id of breaks) {
213
+ const e = byId.get(id);
214
+ if (e) e.parentId = null;
215
+ }
216
+ const childrenByParent = new Map<string | null, TreeEntry[]>();
217
+ for (const entry of byId.values()) {
147
218
  let bucket = childrenByParent.get(entry.parentId);
148
219
  if (!bucket) {
149
220
  bucket = [];
150
221
  childrenByParent.set(entry.parentId, bucket);
151
222
  }
152
223
  bucket.push(entry);
153
- });
224
+ }
154
225
  for (const bucket of childrenByParent.values()) bucket.sort(cmpEntry);
155
226
  this._byId = byId;
156
227
  this._childrenByParent = childrenByParent;
@@ -205,10 +276,23 @@ export class TreeManager {
205
276
  private normalizedEntries(): TreeEntry[] {
206
277
  if (this.ensureIndex()) return Array.from(this._byId.values());
207
278
  const root = this.dm.rootDocId;
208
- return this.readEntries().map((e) => ({
279
+ const entries = this.readEntries().map((e) => ({
209
280
  ...e,
210
281
  parentId: normalizeRootId(e.parentId, root),
211
282
  }));
283
+ // Same read-side cycle break as the indexed path (see
284
+ // {@link rebuildIndex} / {@link cycleBreakIds}) so the legacy scan
285
+ // walks an acyclic, fully-reachable tree too. No-op when acyclic.
286
+ const byId = new Map(entries.map((e) => [e.id, e]));
287
+ const breaks = cycleBreakIds(
288
+ byId.keys(),
289
+ (id) => byId.get(id)?.parentId ?? null,
290
+ );
291
+ for (const id of breaks) {
292
+ const e = byId.get(id);
293
+ if (e) e.parentId = null;
294
+ }
295
+ return entries;
212
296
  }
213
297
 
214
298
  /** Get immediate children of a parent (sorted by order). */
@@ -240,16 +324,13 @@ export class TreeManager {
240
324
  ): ChildrenPage {
241
325
  const all = this.childrenOf(parentId);
242
326
  const limit =
243
- opts.limit != null && opts.limit > 0
244
- ? Math.floor(opts.limit)
245
- : 100;
327
+ opts.limit != null && opts.limit > 0 ? Math.floor(opts.limit) : 100;
246
328
  let start = 0;
247
329
  if (opts.cursor) {
248
330
  const dec = decodeCursor(opts.cursor);
249
331
  if (dec) {
250
332
  const at = all.findIndex(
251
- (e) =>
252
- cmpKey(e.order ?? 0, e.id, dec.order, dec.id) > 0,
333
+ (e) => cmpKey(e.order ?? 0, e.id, dec.order, dec.id) > 0,
253
334
  );
254
335
  start = at < 0 ? all.length : at;
255
336
  }
@@ -303,21 +384,10 @@ export class TreeManager {
303
384
  }
304
385
 
305
386
  /** Build nested tree JSON. */
306
- buildTree(
307
- rootId?: string | null,
308
- maxDepth = 3,
309
- ): TreeNode[] {
310
- const normalized = normalizeRootId(
311
- rootId ?? null,
312
- this.dm.rootDocId,
313
- );
387
+ buildTree(rootId?: string | null, maxDepth = 3): TreeNode[] {
388
+ const normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);
314
389
  if (this.ensureIndex()) {
315
- return this._buildTreeIndexed(
316
- normalized,
317
- maxDepth,
318
- 0,
319
- new Set(),
320
- );
390
+ return this._buildTreeIndexed(normalized, maxDepth, 0, new Set());
321
391
  }
322
392
  const entries = this.normalizedEntries();
323
393
  return this._buildTree(entries, normalized, maxDepth, 0, new Set());
@@ -397,10 +467,7 @@ export class TreeManager {
397
467
  * Rule 4 alignment: when the entry's type doesn't match, returns null
398
468
  * rather than throwing — callers branch on the result.
399
469
  */
400
- getTyped<
401
- TMap extends Record<string, unknown>,
402
- N extends keyof TMap & string,
403
- >(
470
+ getTyped<TMap extends Record<string, unknown>, N extends keyof TMap & string>(
404
471
  _schema: SchemaRegistryLike<TMap>,
405
472
  expectedType: N,
406
473
  docId: string,
@@ -429,20 +496,12 @@ export class TreeManager {
429
496
  }
430
497
 
431
498
  /** Search by label (case-insensitive substring match). */
432
- find(
433
- query: string,
434
- rootId?: string | null,
435
- ): TreeSearchResult[] {
499
+ find(query: string, rootId?: string | null): TreeSearchResult[] {
436
500
  const entries = this.normalizedEntries();
437
501
  const lowerQuery = query.toLowerCase();
438
502
 
439
- const normalized = normalizeRootId(
440
- rootId ?? null,
441
- this.dm.rootDocId,
442
- );
443
- const searchSet = normalized
444
- ? this.descendantsOf(normalized)
445
- : entries;
503
+ const normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);
504
+ const searchSet = normalized ? this.descendantsOf(normalized) : entries;
446
505
 
447
506
  const matches = searchSet.filter((e) =>
448
507
  e.label.toLowerCase().includes(lowerQuery),
@@ -533,7 +592,11 @@ export class TreeManager {
533
592
  const autoMeta: Record<string, unknown> = {};
534
593
  if (typeInfo?.defaultMetaFields) {
535
594
  for (const field of typeInfo.defaultMetaFields) {
536
- if (field.type === "toggle" && field.key && field.default !== undefined) {
595
+ if (
596
+ field.type === "toggle" &&
597
+ field.key &&
598
+ field.default !== undefined
599
+ ) {
537
600
  autoMeta[field.key] = field.default;
538
601
  }
539
602
  }
@@ -565,11 +628,7 @@ export class TreeManager {
565
628
  }
566
629
 
567
630
  /** Move a document to a new parent. */
568
- move(
569
- docId: string,
570
- newParentId?: string | null,
571
- order?: number,
572
- ): void {
631
+ move(docId: string, newParentId?: string | null, order?: number): void {
573
632
  const treeMap = this.dm.getTreeMap();
574
633
  const rootDoc = this.dm.rootDocument;
575
634
  if (!treeMap || !rootDoc) throw new Error("Not connected");
@@ -579,16 +638,58 @@ export class TreeManager {
579
638
 
580
639
  rootDoc.transact(() => {
581
640
  patchEntry(treeMap, docId, {
582
- parentId: normalizeRootId(
583
- newParentId ?? null,
584
- this.dm.rootDocId,
585
- ),
641
+ parentId: normalizeRootId(newParentId ?? null, this.dm.rootDocId),
586
642
  order: order ?? Date.now(),
587
643
  updatedAt: Date.now(),
588
644
  });
589
645
  });
590
646
  }
591
647
 
648
+ /**
649
+ * Heal converged move-cycles in the stored tree itself.
650
+ *
651
+ * The read paths already present a cycle-free, fully-reachable tree
652
+ * without writing (see {@link cycleBreakIds}); this *persists* that repair
653
+ * into the CRDT so the stored structure is acyclic too — useful as a
654
+ * one-shot on load, or behind a "repair tree" action. Deterministic and
655
+ * convergent: every replica computes the identical break set, so even
656
+ * concurrent calls from multiple peers write the same `parentId: null` and
657
+ * converge. Returns the number of nodes reparented to root (0 when already
658
+ * acyclic — the common case, where no transaction is opened). Optional —
659
+ * the always-on read guard already makes the corruption invisible.
660
+ */
661
+ repairTree(): number {
662
+ const treeMap = this.dm.getTreeMap();
663
+ const rootDoc = this.dm.rootDocument;
664
+ if (!treeMap || !rootDoc) throw new Error("Not connected");
665
+ const root = this.dm.rootDocId;
666
+ const parentById = new Map<string, string | null>();
667
+ treeMap.forEach((raw: unknown, id: string) => {
668
+ const value = toPlain(raw) as Record<string, unknown>;
669
+ if (typeof value !== "object" || value === null) return;
670
+ parentById.set(
671
+ id,
672
+ normalizeRootId((value.parentId as string | null) ?? null, root),
673
+ );
674
+ });
675
+ const breaks = cycleBreakIds(
676
+ parentById.keys(),
677
+ (id) => parentById.get(id) ?? null,
678
+ );
679
+ if (!breaks.size) return 0;
680
+ rootDoc.transact(() => {
681
+ for (const id of breaks) {
682
+ if (treeMap.get(id)) {
683
+ patchEntry(treeMap, id, {
684
+ parentId: null,
685
+ updatedAt: Date.now(),
686
+ });
687
+ }
688
+ }
689
+ });
690
+ return breaks.size;
691
+ }
692
+
592
693
  /** Change the page type of a document. */
593
694
  changeType(docId: string, type: string): void {
594
695
  const treeMap = this.dm.getTreeMap();
@@ -776,10 +877,7 @@ export class TreeManager {
776
877
 
777
878
  // ── Internal helpers ──────────────────────────────────────────────────────
778
879
 
779
- private _descendantIds(
780
- entries: TreeEntry[],
781
- parentId: string,
782
- ): string[] {
880
+ private _descendantIds(entries: TreeEntry[], parentId: string): string[] {
783
881
  const result: string[] = [];
784
882
  const visited = new Set<string>();
785
883
  const collect = (pid: string) => {