Repository navigation
Description
Spun off from architectural-audit tracking issue #1228, finding C2 (frontend cluster anchor). Verified against
main2026-05-30; the audit's line numbers/counts were stale and are corrected below.
Problem
NodeSpace keeps hierarchy in two independent caches that must be hand-synced:
SharedNodeStore.nodes(packages/desktop-app/src/lib/services/shared-node-store.svelte.ts, ~3,317 lines) —Map<string, Node>where eachNodecarries a storedparentIdfield.ReactiveStructureTree.children(packages/desktop-app/src/lib/stores/reactive-structure-tree.svelte.ts, 305 lines) —$state.raw(Map<parentId, ChildInfo[]>), the parent→ordered-children edge map.
These are populated by two parallel, hand-written sync implementations that have already drifted:
- Tauri path —
services/tauri-sync-listener.ts,relationship:created(lines 195-229) has careful order-fallback: when an incominghas_childedge lacksorder, preserve existing structureTree order, else append at tail with jitter.relationship:updated(lines 261-271) →structureTree.updateChildOrder(...). - Browser path —
services/browser-sync-service.ts,relationshipCreated(lines 281-290) instead does naive(event.properties?.order) ?? Date.now()with a different existence check, andrelationshipUpdated(lines 309-312) is a no-op stub that only logs. ADate.now()fallback sorts the node ~11 orders of magnitude past any sibling — the exact Delete obsolete cache management code from SharedNodeStore #557 / nodespace-sync#77 bug class.
So the same event sequence produces different cache state depending on runtime mode, and there is no invariant check to catch divergence.
The codebase already half-acknowledges the target end state:
shared-node-store.svelte.ts:565-571documents thatstructureTreeis authoritative andNode.parentIdis "never rely onNode.parentIdalone."- Reads already route through structureTree:
getNodesForParent(794), parent lookup (818-820),shouldClearStaleInsertAfter(589), ancestor walk (2695-2701) all callstructureTree.getParent/getChildren, notNode.parentId. - Zero component reads of
.parentId— grep finds.parentIdonly in 4 service-layer files; the entirecomponents/tree consumes hierarchy via service accessors.parentIdis dead as a read surface but still written on every hierarchy mutation (guardedisComputedField: true— itself a tell it's non-authoritative).
A1 relationship events (relationship_created/updated/deleted on WatchNodes) have landed — the daemon emits them and tauri-sync-listener already consumes has_child events. The infrastructure to drive structureTree is in place.
Scope decision (read first)
Fully removing the Node.parentId field from the Node type is out of scope and split into follow-up C2b. Reason: getNode() (line 767) returns a live reference into this.nodes, and Node is a plain serialized object (also produced by backend-adapter, the wire shape, and loadChildrenTree reconstruction at 2003-2021). A parentId getter can't attach to plain Map-stored objects without wrapping every Node — touching the type boundary, serialization, and OCC snapshotting ({ ...node } at 3190). Too invasive to land safely with the sync-unification work.
This issue delivers the smaller correct slice:
- Demote
parentIdto read-through at the service accessor layer — delete all storedparentIdwrites on hierarchy mutations; the only authoritative read path isstructureTree.getParent(id). - Unify the two sync paths behind one shared hierarchy-application module.
- Add an init-time invariant check.
C2b removes the field from the Node type entirely once wire/serialization is addressed.
Target state
1. structureTree is THE single source of truth for hierarchy
- Delete the stored
parentIdwrites inreactive-node-service.svelte.tsthat mirror the tree: thesharedNodeStore.updateNode(nodeId, { parentId: ... }, ..., { isComputedField: true })calls at lines 1110-1115, 1143-1148, 1171-1176 (and analogous indent-path writes). These exist only to keepNode.parentIdin lockstep; with structureTree authoritative they're redundant. - Exception: the
parentIdset at node creation (line 308 literal) and the in-flight-CREATE fix-up survive only if the CREATE persistence path readsnode.parentIdto build the backend payload. Verify before deleting (comment at 1100-1102 says CREATE "reads current node state fromthis.nodes"). If it readsparentIdfor hierarchy, route throughstructureTree.getParent(nodeId). If it's only the RPC payload, keep the minimal wire-only write and document it. - Provide a single service accessor
getParentId(nodeId): string | nulldelegating tostructureTree.getParent(nodeId). All parent reads go through it.
2. Unify the two sync paths
Create one shared hierarchy-application module (e.g. services/hierarchy-sync.ts) exporting pure functions both paths call:
applyHasChildCreated(structureTree, { parentId, childId, order })— owns the order-fallback contract once: use incoming order when it's a realnumber(typeof gate so0/negative count); else preserve existing structureTree order; else append at tail (lastOrder + 1 + jitter). DeleteDate.now()fallback entirely. Tauri logic (tauri-sync-listener 202-228) is the correct reference — lift it verbatim.applyHasChildUpdated(...)→updateChildOrder. Browser currently no-ops (309-312); after unification it gets real behavior for free.applyHasChildDeleted(...)→removeChild.
Both sync files keep only their transport + id-normalization differences (Tauri must stripNodePrefix per 46-48; browser ids are bare). After normalizing to bare ids, both call the same applyHasChild* functions. Funnel node-data updates through a shared helper too if the two copies (tauri 74-89, browser 349-364) differ only by reason string — pass reason as a param.
Net: the edge-application logic and order-fallback contract exist in exactly one place; drift is structurally impossible.
3. Init-time invariant check
Add structureTree.assertInvariants() (or a free function in hierarchy-sync.ts) run once after hydration completes (after loadChildrenTree's batchAddRelationships, ~line 2034):
- I1 — no orphan edges: every
childId/parentIdinstructureTree.childrenexists insharedNodeStore.nodes. (Allowlist virtual/root sentinels:__root__, virtual date node at 1971-1985.) - I2 — single parent: no
childIdunder two different parents (addChildInternalguards reactively at 116-127; this is a full-scan backstop). - I3 — sorted order: each parent's
ChildInfo[]non-decreasing byorder.
On violation: log via createLogger('HierarchyInvariant') at error with offending ids. In dev (import.meta.env.DEV) throw (surfaces in tests/dev). In prod, log only and continue — never crash the outliner. No auto-repair in this issue (note as possible C2b).
moveInMemoryRelationship call sites
The audit cited 6; real count is 9 (reactive-node-service.svelte.ts lines 414, 446, 844, 915, 1012, 1090, 1127, 1155, 1180, plus child-reparent at 1373). Classify each:
- Survive (legit optimistic updates): indent/outdent/move paths firing before the backend round-trips and before any
relationship:*event. In browser dev mode no events fire automatically, so these are the only optimistic tree update. Keep, but route any inline order math through the shared helper. - Must NOT also write
parentId: every site pairsmoveInMemoryRelationship(...)withsharedNodeStore.updateNode(..., { parentId }). Delete the paired write; the move call alone is now the complete optimistic update. - Reconcile with events: when the authoritative
relationship:created/updatedevent arrives via the unified path,applyHasChild*is idempotent (addChilddedups + re-sorts, 102-114), so the optimistic move is harmlessly overwritten with backend order. Confirm idempotency for the move case in tests.
Acceptance criteria
- All mirror-only stored-
parentIdwrites deleted fromreactive-node-service.svelte.ts(~1110-1115, 1143-1148, 1171-1176 + indent-path equivalents). - Any surviving
parentIdwrite (creation/wire-only) documented as wire-only and NOT read as a hierarchy source; in-flight CREATE parent decision readsstructureTree.getParent. - Single
getParentId(nodeId)accessor delegates tostructureTree.getParent; no code readsNode.parentIdfor hierarchy. - New
services/hierarchy-sync.tsexportsapplyHasChildCreated/Updated/Deleted; both sync files call them after id normalization. No duplicated edge/order logic remains in either. -
Date.now()order fallback removed from both sync paths. -
relationship:updated/relationshipUpdatedproduce identicalupdateChildOrderbehavior in both modes (browser no-op stub gone). - Init-time invariant check (I1/I2/I3) runs after hydration, logs via
createLogger, throws in dev, logs-only in prod, allowlists__root__+ virtual date sentinels. - All 9
moveInMemoryRelationshipsites reviewed; optimistic sites retained, pairedparentIdwrites removed. - No new
bun run checkerrors; noany, no lint suppression,createLoggeronly.
Testing requirements
- Anti-drift regression guard (key test): feed an identical
has_childevent sequence (create → reorder → move → delete, incl. missing-orderecho) through both Tauri and browser paths; assertstructureTree.childrenis byte-identical afterward. Extendtests/services/tauri-sync-listener.test.ts+tests/services/browser-sync-service.test.ts, or add sharedhierarchy-sync.test.ts. - Order-fallback test: missing
orderpreserves existing; brand-new child appends at tail (notDate.now());order: 0honored (not falsy). - Invariant-check test: orphan edge / dual-parent / unsorted state → I1/I2/I3 fire (throw in dev, logged in prod via mocked
import.meta.env.DEV). - Optimistic-then-event idempotency: optimistic
moveInMemoryRelationshipthen authoritativerelationship:createdleaves a single correct edge with backend order. - Extend
tests/unit/reactive-structure-tree.test.tsfor any new method (assertInvariants). -
bun run test(Happy-DOM — neverbun test) green;bun run test:allbefore PR.
Risks
- Live outliner code, Delete obsolete cache management code from SharedNodeStore #557 bug class. indent/outdent/move are the most user-visible interactions; an order regression silently relocates nodes. Anti-drift + idempotency tests are the guardrails — do not skip.
- Browser-mode optimistic updates depend on
moveInMemoryRelationship. Deleting a survive-class call breaks browser dev mode (no events to compensate). Classify all 9 before deleting. - Hydration timing: invariant check must run after
batchAddRelationshipscompletes (place at end ofdoLoadChildrenTree, not insideprocessNode) — else false-positives on partial loads. - In-flight CREATE parent read: confirm whether the CREATE payload builder consumes
Node.parentIdbefore deleting the creation-time write.
Coordination with C1 / C3 (#1228)
C2 is the anchor of the frontend cluster and should land before C1 and C3:
- C1 (collapse 5 wrapper layers) touches the same files. Landing C2 first gives C1 a single-source-of-truth model to collapse around — fewer call sites, no
parentIdmirror writes to carry through. - C3 (move ordering logic to daemon) depends on the frontend trusting structureTree's order as backend-derived. Once C2 makes the unified sync path the only edge-order writer, C3 shifts order computation server-side and the frontend applies emitted orders via
applyHasChild*. C2'shierarchy-sync.tsis the seam C3 plugs into.
Recommended sequence: C2 → C1 → C3. C6 (#1246) is independent (focus/lifecycle, not hierarchy) and parallel-safe.
Follow-up C2b: remove the Node.parentId field from the type entirely once wire/serialization is addressed.
Standard NodeSpace startup / PR sequence
EnterWorktree({name: "issue-<N>-c2-hierarchy-source-of-truth"}); bun install; bun run test baseline; bun run gh:assign <N> "@me"; bun run gh:status <N> "In Progress". Implement with createLogger (no console), no any, no {@html}, no lint suppression; bun run test not bun test. Before PR: bun run test:all + bun run check (no new failures), bun run quality:fix (then git status, revert unrelated reformats), commit, bun run gh:pr <N>. /pragmatic-code-review before merge, then ExitWorktree({action:"remove", discard_changes:true}) and gh pr merge <PR#> --squash --delete-branch.
Spun off from #1228 (architectural audit), finding C2.
Activity
C2: Unify hierarchy sync paths behind hierarchy-sync.ts, add invarian…
C2: Make structureTree single source of truth — unify dual sync paths…
C2: Make structureTree single source of truth — unify dual sync paths…