Skip to content

Architectural audit (post-daemon + post-SQLite): structural findings & improvement plan #1228

Closed

Description

@malibio

Purpose

A whole-codebase architectural audit conducted after the daemon-client (ADR-031/032) and SQLite (#1222/#1224) migrations. Goal: an honest map of where the architecture actually is vs. where the docs/ADRs claim it is, and a prioritized list of what to improve. Findings below are evidence-backed (file:line). This is a tracking/planning issue — each section should spin off its own implementation issue.

Companion: #1226 handles the dead-code/doc purge. This issue is the higher-level structural assessment. Where they overlap, #1226 is the cleanup and this is the "what should the shape be."

Strategic direction (set 2026-05-29)

We are moving away from MCP entirely toward published skills + scripts for AI-agent integration. Rationale: avoid MCP surface bloat, and skills are the better long-term fit (domain knowledge + multi-step procedures + composition, distributable to any agent). The audit's MCP findings below should be read as "migrate off," not "consolidate." Interacts with #1199 (whose title still assumes an MCP server ships — needs reframing) and #1181.


A. Transport / proto layer

A1. packages/daemon/proto/ is a stale duplicate that TS clients still load 🔴

  • packages/proto/proto/ is canonical — the Rust build (packages/proto/build.rs) compiles it, and it received the relationship-event messages in commit 54f11796.
  • packages/daemon/proto/ is an abandoned copy, last touched at Push GetRoots limit/offset pagination into SurrealStore::get_children #1175 (before the proto crate was extracted). It is missing relationship_created/updated/deleted + RelationshipPayload / RelationshipDeletedPayload.
  • TS clients load the stale copy: packages/agent-tools/src/client.ts:9 and packages/dev-tools/src/dev-proxy.ts:21 both resolve ../../daemon/proto/node_service.proto. → They are blind to the relationship/hierarchy events the daemon now emits on WatchNodes. The comment in the canonical proto says these events are exactly what lets a pulled child node attach to its parent in the outliner.
  • Action: delete packages/daemon/proto/; repoint TS consumers at packages/proto/proto/ (or a generated artifact). Verify TS clients then receive relationship events. (Folds into Audit & cleanup: finish daemon + SQLite migrations (purge dead HTTP MCP / SurrealDB / RocksDB from code and docs) #1226 A3.)

B. Daemon + core service layer

B1. NodeService is a god-object 🔴

  • packages/core/src/services/node_service.rs — 58 pub async fn, ~11,772 lines, mixing CRUD, hierarchy, relationships/mentions, embeddings/search, playbook execution context, and schema field ops.
  • Action: split into focused services (NodeCrud / Hierarchy / Relationship / Embedding); move playbook execution-context out of the core service into a wrapper/middleware.

B2. Sleep-based eventual-consistency retry loops survive into the SQLite era 🔴

  • node_service.rs:2100-2119 (5×50ms), :4625-4692 (create_parent_edge sibling-not-found, 20×100ms), plus :9030/9039/9458/9471/9510. Comments still cite "SurrealDB eventual consistency."
  • SQLite is synchronous/ACID — these add 50-2000ms latency and mask whether the path is actually correct.
  • Action: remove or replace with explicit transaction semantics; confirm the stale-sibling scenario can't occur under SQLite.

B3. Business logic leaks into the daemon gRPC adapters 🟠

  • The daemon RPCs are meant to be thin (ADR-031), but daemon/src/services/node_service.rs does real work: collection-path add on create (:96-107), lifecycle_status defaulting (:110-123), auto-fetch version on update/delete (:175-179, :225-244).
  • Clients calling core directly (agent, tests) don't get these behaviors → inconsistent contract.
  • Action: push collection resolution, lifecycle defaulting, version-fetch defaulting down into NodeService.

B4. CollectionService re-instantiated per-RPC 🟠

  • CollectionService::new() called 14× across single RPCs in daemon/node_service.rs (:99,193,202,744,...) + import_service. Stateless but rebuilt every call; daemon shouldn't know collection semantics at all.
  • Action: inject once at construction, or fold collection ops into core.

B5. empty_to_none sentinel pattern is pervasive and fragile 🟠

B6. Lossy core→gRPC error mapping 🟠

  • service_error_to_status() (:1252-1274) routes most variants through a generic OpsError pass-through; fetch_node() (:1136) wraps everything as Status::internal(). Clients can't distinguish not-found / version-conflict / validation.
  • Action: map every NodeServiceError variant explicitly; ensure VersionConflict → aborted; add parity tests.

B7. Fractional-ordering jitter is a SurrealDB-era artifact 🟡

  • db/fractional_ordering.rs:21-32 adds random jitter "to prevent collisions under eventual consistency (SurrealDB/RocksDB)." Under SQLite's serialized writes this is unnecessary and complicates rebalancing.
  • Action: verify and remove; make ordering deterministic.

B8. Possible TOCTOU in bulk ops 🟡

  • sqlite_store.rs:1625-1648 (bulk_update_nodes) and bulk_create_hierarchy (:1659-1699) call get_node() before / outside the surrounding transaction → read-then-update race; bulk op can partially complete.
  • Action: move reads inside the transaction or document the partial-failure contract.

C. Frontend state / service layer

C1. Five stacked wrappers around node CRUD 🟠

  • tauri-commands.ts (548) → backend-adapter.ts (670) → shared-node-store.svelte.ts (3,305) → reactive-node-service.svelte.ts (1,788) + reactive-structure-tree.svelte.ts. Four hops between component and backend; unclear ownership.
  • Action: merge transport layers (backend-adapter + tauri-commands); clarify the data-vs-hierarchy split.

C2. Dual hierarchy caches must be hand-synced 🟠

  • SharedNodeStore.nodes (has parentId) and ReactiveStructureTree.children (edges) are independent; frontend manually calls moveInMemoryRelationship() on parent change (reactive-node-service.svelte.ts:911). Tauri vs browser modes use different sync paths; no invariant check. This caused the Delete obsolete cache management code from SharedNodeStore #557 class of bug.
  • Action: make structureTree the single source of truth; derive parentId; unify Tauri/browser sync; add an init-time invariant check. (Note B-layer: relationship events from A1 are what should drive this.)

C3. Hierarchy/ordering business logic lives in the frontend 🟠

  • calculateOutdentInsertOrderPure() (reactive-node-service.svelte.ts:60-85), canHaveChildren() indent gating (:875), depth recursion (:131-138), child-transfer-on-split (:384-450). If the daemon's rules change, the frontend diverges; can't validate end-to-end.
  • Action: move ordering math + container rules + depth into the daemon; return order hints in RPC responses.

C4. Three message/entity shapes converted at multiple boundaries 🟡

  • chat: protocol/view-model/persisted (components/chat/types.ts:6-9); nodeToTaskNode() (task-node.ts:268); separate normalizers in tauri-sync-listener.ts:62 and browser-sync-service.ts:208.
  • Action: normalize once at the sync boundary; reduce per-viewer converters.

C5. Last-Write-Wins conflict resolution is incomplete 🟡

  • shared-node-store.svelte.ts:409-429 always discards local; hardcoded 5s detection window (:506); nodeType-conversion special-case bypasses detection (:2273-2278). Concurrent edits outside the window are silently lost.
  • Action: move conflict adjudication to the daemon (return version + conflict marker in RPC error); revisit OT/CRDT (already flagged "Phase 7" in code).

C6. Migration residue in the frontend 🟡


D. AI-agent integration surfaces (MCP → skills+scripts)

Strategic direction (2026-05-29): migrate off MCP to published skills + scripts. These findings define the target architecture, what it deletes, and what must be preserved.

D0. The target architecture — and why it's sound

Guiding principle: the skill is a teacher, not a wrapper. An LLM arrives knowing nothing about NodeSpace — what a node is, that hierarchy is edges (not nesting), that node types are schema-defined, that there's a daemon, or when it should reach for this tool at all. MCP gives the model a flat list of tool signatures with no worldview. A skill imparts the domain model and usage judgment first, then the mechanism. That is the core reason skills beat MCP here, not just "less surface."

A good NodeSpace SKILL.md must convey, in order:

  1. What NodeSpace is — local-first knowledge graph; typed nodes (note/task/date/custom); relationships are first-class edges.
  2. The mental model — parent/child via edges + fractional ordering; date nodes anchor daily context; content is markdown.
  3. When to use it — "search for prior context at session start"; "save findings as you go"; "this persists across sessions" — the judgment the model has no prior for.
  4. How — the CLI commands / scripts as the mechanism.

The runtime topology (no server, no protocol):

Agent loads SKILL.md (domain model + when/how)
  → runs `nodespace …` directly  OR  runs a bundled script for a fixed multi-step procedure
  → nodespace CLI ──gRPC(UDS)──► nodespaced → NodeService → SQLite

The script is optional and earns its place only for determinism. Default: no script — SKILL.md → CLI directly (covers single ops). Add a script only when a procedure is multi-step, order-sensitive, and you've seen the agent get it wrong (e.g. "ensure today's date node → attach finding → link to project"). The script chains CLI calls, parses --json, handles errors, and returns a clean pass/fail — turning N fuzzy agent decisions into one reliable call.

Layer Responsibility
SKILL.md What NodeSpace is + when/why to use it (teaches the model)
Script (optional) How, deterministically: fixed multi-step procedure + parsing + error handling
CLI one typed operation per call (gRPC client to daemon)
Daemon the actual work

This already exists in skeleton: @nodespaceai/skill ships SKILL.md + an install-time installer.ts that copies the skill into detected agents (Claude Code, Codex, Gemini, OpenCode). The installer runs once at install, not at agent-runtime. So the pattern is proven — the gaps are coverage (D3) and quality of teaching (D4).

D1. Four overlapping tool surfaces, ~60% duplicated 🔴

  • (1) Rust handlers core/src/mcp/handlers/ — richest (~40 ops incl. markdown, schema, batch, index ops, relationship graph, playbook).
  • (2) @nodespaceai/agent-tools (TS, gRPC) — only 5 (search/get/create/update/getChildren).
  • (3) packages/mcp (TS, stdio→CLI) — 6.
  • (4) packages/agent local-agent Rust tools — its own catalog again.
  • No single source of truth; parameter naming (node_id vs nodeId vs id) and return shapes (full vs truncated 2000/500 vs minimal) diverge across surfaces. The target collapses these to one path: CLI → daemon, taught by the skill.

D2. The dead thing is the HTTP transport, not the handler logic 🔴 (corrects #1226)

  • McpServerService / run_mcp_server / McpTransport::Http — dead (nothing in prod starts it; only dev-mcp constructs it).
  • BUT handler functions are reused as a library by packages/agent: prepare_nodes_from_template, NodeTemplate (skill_pipeline.rs:17,231, prompt_assembler.rs:12,257,409), handle_create_schema, handle_get_markdown_from_node_id (local_agent/tools.rs:10,894,1215).
  • Action: extract the reusable logic into a transport-agnostic core module, repoint packages/agent, then delete the MCP server + transport. Tracked in Audit & cleanup: finish daemon + SQLite migrations (purge dead HTTP MCP / SurrealDB / RocksDB from code and docs) #1226 A1.

D3. CLI coverage gap blocks the migration 🔴

D4. SKILL.md under-teaches and mis-teaches 🟠

D5. Decommission plan 🟠


Cross-cutting themes

  1. Unfinished migrations left residue at every layer — SurrealDB-era retry loops/jitter (B2, B7), stale proto copy (A1), dead MCP transport (D2), frontend TODO graveyard (C6). Audit & cleanup: finish daemon + SQLite migrations (purge dead HTTP MCP / SurrealDB / RocksDB from code and docs) #1226 covers the mechanical purge.
  2. Business logic drifts upward and outward — ordering/hierarchy rules live in the frontend (C3) and the daemon adapters (B3) instead of core. Pull them down so every client (UI, CLI, agent, future scripts) gets one contract.
  3. No single source of truth — tool catalog (D1), proto location (A1), entity shape (C4) each exist in multiple hand-synced copies.
  4. The daemon boundary itself is sound — src-tauri deliberately does NOT depend on nodespace-core (types.rs mirrors sever it); the gRPC separation holds. The problems are what flows across the boundary, not the boundary.

Suggested issue breakdown (spin-offs)

Status reconciled 2026-05-30 against main (not by checkbox trust — verified in code).

Done / merged:

Open / spun off:

Backend section (A, B) is COMPLETE. Every A/B finding is merged: A1 (#1230), B1 (#1240), B2 (#1239), B3/B4 (#1244), B5 (#1245), B6 (#1257), B7 (#1256). The only B item never separately filed is B8 (possible TOCTOU in bulk ops, 🟡) — see below.

Frontend section (C) is well-advanced. Merged: C2 (#1250), C2b (#1252), C6 (#1249), C1a (#1255). C3 filed & split (see below).

C3 was already ~90% done. Investigation found the write path already delegates ordering to the daemon (InsertPosition from #1216) and the authoritative order already reaches the frontend via the relationship:updated event (C2's hierarchy-sync.ts). So C3 is mostly deleting the redundant frontend duplicate, plus one real gap (the daemon doesn't enforce container rules on move). Split into C3a/C3b (filed) + C3c (deferred).

Done — all merged:

In review (open):

Remaining — deferred, intentionally not filed (gated):

✅ AUDIT COMPLETE (2026-05-30)

Every original finding (A1, B1–B8, C1–C6, D1–D5) is resolved. This tracking issue is being closed.

Follow-ons spun out of this audit, tracked independently (not blockers to closing):

The audit did its job: mapped reality vs. docs, spun off ~25 implementation issues, and drove the entire backend (A+B), the MCP→skills teardown (D), and the frontend hierarchy/conflict rework (C) to completion. Remaining work is ordinary backlog (#1275, #1277), no longer "audit findings." Closing.

Out of scope

  • Implementation of any single fix (each spins off its own issue).
  • The cloud-sync internals (separate audit).

Activity

  1. malibio commented on May 29, 2026

    @malibio
    CollaboratorAuthor

    Spun off two backend findings into trackable issues:

    Parallelization: sequenced with partial overlap. #1237 lands FIRST (small, deletion-only, removes the very hierarchy code #1238 would otherwise relocate). #1238 runs its non-hierarchy phases (ctx extraction, Relationship/Schema/Query/Embedding/Bulk, playbook-context wrapper) in parallel, but blocks its Hierarchy phase on #1237's merge, then rebases. Both touch create_parent_edge/move_node/reorder — that's the collision zone.

  2. malibio commented on May 30, 2026

    @malibio
    CollaboratorAuthor

    ✅ Audit complete — closing

    Every finding (A1, B1–B8, C1–C6, D1–D5) is resolved. Summary:

    • Backend (A+B): 100% — proto dedup, NodeService god-object split, SurrealDB-era retry/jitter removed, thin daemon adapters, empty_to_none audited, exhaustive error mapping, bulk-op TOCTOU closed.
    • Frontend (C): 100% of findings — transport consolidated (C1a), structureTree as single source of truth (C2/C2b), ordering math + container rules moved to the daemon (C3a/C3b), normalizer deduped (C4), daemon-OCC conflict resolution (C5), residue purged (C6). C1b re-audited → boundary is now clean, no refactor needed.
    • MCP→skills (D): 100% — MCP fully decommissioned, skills+CLI is the one integration surface (ADR-035).

    Several findings were reframed during scoping rather than taken at face value — C3 was ~90% already done; C4's '3 message shapes' were deliberate layering; B6 was mostly complete. The investigate-before-filing approach kept us from manufacturing work.

    Follow-ons tracked independently (ordinary backlog, not audit findings):

    Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions