Skip to content

Create NodeOperations Business Logic Layer #332

Closed

Description

@malibio

Create NodeOperations Business Logic Layer

Overview

Create a centralized business logic layer (NodeOperations) in Rust that enforces data integrity rules for node creation, updates, and hierarchy management. This layer will be used by both MCP handlers and Tauri commands, eliminating duplicate logic and preventing database corruption.

Problem Statement

Current Architecture (Broken)

┌─────────────────────────────────────────┐
│  MCP Handlers                           │
│  - Direct NodeService calls             │
│  - NO business rule enforcement         │
│  - Can create corrupt data ❌           │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│  NodeService (database CRUD)            │
│  - Only has NodeBehavior validation     │
│  - No container enforcement ❌          │
│  - No sibling calculation ❌            │
└─────────────────────────────────────────┘

┌─────────────────────────────────────────┐
│  Frontend (TypeScript)                  │
│  - NodeOperationsService.ts             │
│  - HierarchyService.ts                  │
│  - Business logic NOT shared with MCP ❌│
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│  Tauri Commands → NodeService           │
│  - Frontend enforces rules              │
│  - Rules work for UI, broken in MCP ❌  │
└─────────────────────────────────────────┘

Critical Issues

  1. Database Corruption Risk

    • MCP clients can create nodes without container_node_id (non-containers MUST have one)
    • Broken sibling chains when before_sibling_id = None (should calculate last sibling)
    • Parent-container mismatches (parent must be in same container)
  2. Code Duplication

    • Business logic exists in TypeScript (NodeOperationsService)
    • Same logic NOT enforced in MCP handlers
    • Two codebases to maintain, easy to drift
  3. No Single Source of Truth

    • Frontend has business rules
    • Backend (MCP) bypasses rules
    • Different behavior depending on access path

Solution: NodeOperations Layer

Target Architecture

┌─────────────────────────────────────────┐
│  MCP Handlers + Tauri Commands          │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│  NodeOperations (NEW! ✅)               │
│  - Container validation                 │
│  - Sibling position calculation         │
│  - Parent-container consistency         │
│  - Type-specific rules                  │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│  NodeService (database CRUD)            │
└─────────────────────────────────────────┘

Public API

// packages/core/src/operations/mod.rs

pub struct NodeOperations {
    node_service: Arc<NodeService>,
}

impl NodeOperations {
    // CREATE Operations
    pub async fn create_node(
        &self,
        node_type: String,
        content: String,
        parent_id: Option<String>,
        container_node_id: Option<String>,
        before_sibling_id: Option<String>,
        properties: Value,
    ) -> Result<String, NodeOperationError>;
    
    // READ Operations (delegation)
    pub async fn get_node(&self, id: &str) -> Result<Option<Node>, NodeOperationError>;
    pub async fn query_nodes(&self, filter: NodeQueryFilter) -> Result<Vec<Node>, NodeOperationError>;
    
    // UPDATE Operations
    pub async fn update_node(&self, node_id: &str, content: Option<String>, node_type: Option<String>, properties: Option<Value>) -> Result<(), NodeOperationError>;
    pub async fn move_node(&self, node_id: &str, new_parent_id: Option<&str>) -> Result<(), NodeOperationError>;
    pub async fn reorder_node(&self, node_id: &str, before_sibling_id: Option<&str>) -> Result<(), NodeOperationError>;
    
    // DELETE Operations
    pub async fn delete_node(&self, node_id: &str) -> Result<DeleteResult, NodeOperationError>;
}

Business Rules Enforced

Rule 1: Container Node Validation

Container types (date, topic, project) force all hierarchy fields to None.

Rule 2: Container Requirement for Non-Containers

Every non-container node MUST have container_node_id (infer from parent if missing).

Rule 3: Sibling Position Calculation

If before_sibling_id not provided, calculate last sibling automatically.

Rule 4: Parent-Container Consistency

Parent and child must be in same container.

Rule 5: Update Operations Restrictions

Content updates cannot change hierarchy. Use move_node() or reorder_node() explicitly.

Implementation Tasks

Phase 1: Core Structure

  • Create packages/core/src/operations/mod.rs
  • Define NodeOperations struct
  • Define NodeOperationError enum

Phase 2: Business Logic Implementation

  • Implement container type detection
  • Implement container resolution with parent inference
  • Implement sibling position calculation
  • Implement parent-container validation
  • Implement all CRUD operations with rules

Phase 3: Integration

  • Update MCP handlers to use NodeOperations
  • Update Tauri commands to use NodeOperations
  • Update Tauri app initialization

Phase 4: Frontend Simplification

  • Remove TypeScript NodeOperationsService
  • Remove business logic from hierarchy-service
  • Update backend adapter to call Tauri directly

Phase 5: Testing

  • Unit tests for all business rules
  • Integration tests for MCP + Tauri
  • Edge case tests

Phase 6: Documentation

  • Update architecture docs
  • Document business rules
  • Update MCP/Tauri docs

Acceptance Criteria

  • MCP handlers cannot create corrupt data
  • Container nodes always have None for parent/container/sibling
  • Non-container nodes always have container_node_id
  • Sibling chains never broken
  • Parent-container mismatches impossible
  • Business logic exists ONLY in Rust
  • TypeScript NodeOperationsService removed
  • All operations work as specified
  • Comprehensive test coverage

Related Issues

Implementation Summary

✅ COMPLETE - All phases implemented and merged in PR #335

Key Files

  • packages/core/src/operations/mod.rs - NodeOperations implementation (31 tests passing)
  • packages/core/src/operations/error.rs - Error types
  • packages/core/src/mcp/handlers/nodes.rs - MCP integration
  • packages/desktop-app/src-tauri/src/commands/nodes.rs - Tauri integration

Test Results

  • 31 NodeOperations tests passing
  • All business rules validated
  • Integration tests for container inference, parent-container consistency, and sibling ordering

Documentation

  • Architecture docs updated in docs/architecture/business-logic/overview.md
  • All 5 business rules documented with examples

Activity

  1. self-assigned this
    on Oct 23, 2025
  2. malibio commented on Oct 23, 2025

    @malibio
    CollaboratorAuthor

    Code Review Recommendations Implemented

    All recommendations from the pragmatic code review have been addressed in commit 9f41c06.

    Changes Made

    ✅ Suggestion 1: Update Documentation

    • Updated docs/architecture/business-logic/overview.md
    • Removed outdated references to NodeOperationsService (which was deleted in Phase 4)
    • Updated "Why TypeScript Services Still Exist?" section to correctly list only HierarchyService and NodeReferenceService
    • Added note explaining the removal of duplicate business logic

    ✅ Suggestion 2: Add Rustdoc Example for Date Nodes

    • Enhanced create_node() method documentation with comprehensive date node example
    • Documented deterministic ID behavior (content becomes ID: "2025-10-23" → "2025-10-23")
    • Explained "get-or-create" semantics for daily notes use case

    ✅ Observation 2: Rename Method for Clarity

    • Renamed is_container_type() → can_be_container_type()
    • Updated all call sites (create_node, tests, documentation)
    • Enhanced comment to clarify: "Check if a node type is ALLOWED to be a container"
    • Makes distinction clearer: "CAN BE a container" vs "IS a container"

    ✅ Observation 1: Document save_node_with_parent Bypass

    • Added comprehensive doc comment explaining why save_node_with_parent() bypasses NodeOperations
    • Documents the transactional upsert requirement (ensure parent + upsert node atomically)
    • Notes safety measures (still validates node type)
    • Identifies future improvement opportunity

    Deferred to Future PR

    Suggestion 3: NodeOperations::upsert_node_with_parent() method

    • Requires deeper integration work to support transactional semantics within NodeOperations
    • Will be tracked in a separate follow-up issue
    • Current implementation is safe (validates node type) and limited to specific auto-save use case

    Quality Status

    • ✅ All quality checks pass (oxlint, prettier, svelte-check, clippy)
    • ✅ No regressions introduced
    • ✅ Enhanced code clarity and maintainability

    Next Steps

    Ready for final review and merge. All acceptance criteria met, all code review recommendations addressed (except optional future enhancement).

  3. malibio commented on Oct 31, 2025

    @malibio
    CollaboratorAuthor

    Implementation Status Update

    ✅ Phase 1-2 COMPLETE: Core Implementation

    • Created packages/core/src/operations/mod.rs
    • Implemented all 5 business rules
    • Comprehensive test coverage
    • Error types defined

    ❌ Phase 3-4 REMAINING: Integration

    • Update MCP handlers to use NodeOperations (instead of NodeService)
    • Update Tauri commands to use NodeOperations
    • Update Tauri app initialization to provide NodeOperations state
    • Remove TypeScript NodeOperationsService duplication
    • Verify business rules work end-to-end via MCP

    Next Steps

    Phase 3: MCP Integration - Update MCP handlers in packages/core/src/mcp/handlers/nodes.rs to use NodeOperations.

    Phase 4: Tauri Integration - Update commands in packages/desktop-app/src-tauri/src/commands/nodes.rs to use NodeOperations.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions