Skip to content

Implement type-namespaced properties for preserving state across type conversions #397

Closed

Description

@malibio

Summary

Refactor the properties JSON field to use type-namespaced structure, allowing nodes to preserve properties when converting between types.

Current Implementation

Properties are stored at the root level:

{
  "status": "OPEN",
  "due_date": "2025-10-25"
}

Problem: When a task node converts to text or another type, these properties are lost or become meaningless for the new type.

Proposed Implementation

Store properties under type-specific namespaces:

{
  "task": {
    "status": "OPEN",
    "due_date": "2025-10-25"
  },
  "project": {
    "name": "Q1 Planning",
    "status": "active"
  }
}

Benefits

  1. Type History Preservation - Properties from previous types remain when converting
  2. Safe Type Conversion - No data loss when changing node types (task → text → task preserves task properties)
  3. Clean Separation - Each type's properties are isolated and well-defined
  4. Multi-Type Support - A node could theoretically support properties for multiple types simultaneously
  5. Better Schema Validation - Schema system can validate type-specific properties more precisely

Implementation Scope

Backend Changes (Required)

  • Database seed schemas - Update default property structure in packages/core/src/db/database.rs
  • Node behaviors - Update validation in packages/core/src/behaviors/mod.rs to check properties.{type}.*
  • Node service - Update CRUD operations in packages/core/src/services/node_service.rs
  • Backward compatibility - Accept both formats during transition period
  • Migration helper - Auto-migrate old format to new on first update
  • Update all Rust tests - Fix test data and assertions

Frontend Changes (Minimal)

  • Property access patterns - Update services to use properties.task.status instead of properties.status
  • Property forms - Update schema property forms to read/write nested properties
  • Update all frontend tests - Fix test data and assertions

Migration Strategy

  1. Phase 1: Backend Support

    • Implement nested property support
    • Maintain backward compatibility (read both formats)
    • New nodes created with nested format
  2. Phase 2: Frontend Updates

    • Update property access patterns
    • Update property forms
  3. Phase 3: Cleanup

    • Remove backward compatibility after migration period
    • Archive migration helper code

Design Decisions Needed

  1. Multiple Active Types: Should a node support multiple type properties simultaneously? (e.g., both task and project)

    • Recommendation: Yes, allow but only validate properties for current node_type
  2. Property Lookup: Should lookups fall back to root level for backward compat?

    • Recommendation: Yes during migration, then remove fallback
  3. Auto-Initialize: Should changing types auto-create nested property structure?

    • Recommendation: Yes, use schema defaults when converting types

Related Issues

Acceptance Criteria

  • Database seed schemas use nested property format
  • Node behaviors validate properties.{type}.* instead of properties.*
  • Converting task → text → task preserves task properties
  • All backend tests pass with new format
  • Frontend can read/write nested properties
  • All frontend tests pass with new format
  • Documentation updated with new property structure
  • Backward compatibility maintained during transition

Priority

Medium - Important for data preservation during type conversions, but not blocking current features.

Labels

enhancement, backend, architecture, schema, technical-debt

Activity

  1. self-assigned this
    on Nov 4, 2025
  2. malibio commented on Nov 4, 2025

    @malibio
    CollaboratorAuthor

    Implementation Approach Update

    This is a PURE BACKEND implementation - the frontend will be completely oblivious to the internal property structure change.

    How It Works

    Internal Storage (Database) - Type-namespaced:

    {
      "task": {"status": "OPEN", "due_date": "2025-10-25"},
      "project": {"name": "Q1", "status": "active"}
    }

    API Response (What Frontend Sees) - Flattened based on current node_type:

    {
      "status": "OPEN",
      "due_date": "2025-10-25"
    }

    Backend Responsibilities

    1. Serialization: Flatten properties.{node_type}.* → properties.* when returning nodes
    2. Deserialization: Nest properties.* → properties.{node_type}.* when saving nodes
    3. Type Conversion: Preserve all type-namespaced properties when node_type changes
    4. Validation: Validate only the properties for the current node_type

    Frontend Impact

    NONE - Frontend continues to work exactly as before:

    • Reads: node.properties.status
    • Writes: PATCH /nodes/{id} {"properties": {"status": "IN_PROGRESS"}}

    Implementation Scope (Updated)

    Backend Changes (Pure Backend)

    • Database seed schemas - Already updated with nested structure
    • Node model serialization - Add flatten/nest helpers in packages/core/src/models/node.rs
    • Node service - Update CRUD in packages/core/src/services/node_service.rs
    • Behaviors - Update validation in packages/core/src/behaviors/mod.rs to validate nested structure
    • All Rust tests - Update test data to use nested format

    Frontend Changes

    NONE ✅


    Benefits of Pure Backend Approach:

    • ✅ Zero frontend changes required
    • ✅ Type conversion preserves properties transparently
    • ✅ Clean separation of concerns (storage vs. API contract)
    • ✅ Easy to roll back if needed (no coordinated frontend/backend deploy)
  3. malibio commented on Nov 4, 2025

    @malibio
    CollaboratorAuthor

    Session Handoff - Progress Update

    ✅ Completed Work

    1. Schema Seed Data - COMPLETE (Commit: deea207)

    • ✅ Added missing schemas: code-block, quote-block, ordered-list
    • ✅ Added required version and description fields to ALL schemas
    • ✅ Removed incorrect headerLevel property from header schema
    • ✅ All database tests passing (9 core schemas seeded correctly)

    Why version/description are critical:
    Frontend SchemaDefinition interface requires these fields:

    export interface SchemaDefinition {
      isCore: boolean;      // ✅ All had
      version: number;      // ❌ Only task had → NOW FIXED
      description: string;  // ❌ Only task had → NOW FIXED
      fields: SchemaField[];
    }

    2. Project Management

    • ✅ Branch created: feature/issue-397-type-namespaced-properties
    • ✅ Issue assigned and status set to "In Progress"
    • ✅ Implementation plan documented and clarified (pure backend)

    📋 Remaining Implementation - Type-Namespaced Properties

    Objective: Store properties under type namespaces internally while presenting flat properties to frontend.

    Architecture

    Internal Storage (Database):

    {
      "task": {"status": "OPEN", "due_date": "2025-10-25"},
      "project": {"name": "Q1", "status": "active"}
    }

    API Response (Frontend sees):

    {
      "status": "OPEN",
      "due_date": "2025-10-25"
    }

    Flattened based on current node_type

    Benefits:

    • Type conversions preserve properties (task → text → task restores task props)
    • Frontend completely unaware of internal structure
    • Zero frontend changes required

    🔨 Next Session Implementation Plan

    Step 1: Node Model Helpers

    packages/core/src/models/node.rs

    Add to impl Node:

    /// Flatten properties for API serialization
    /// Example: {"task": {"status": "OPEN"}} → {"status": "OPEN"}
    pub fn flatten_properties(&self) -> serde_json::Value {
        if let Some(obj) = self.properties.as_object() {
            if let Some(type_props) = obj.get(&self.node_type) {
                return type_props.clone();
            }
        }
        // Backward compatibility: return as-is if not nested
        self.properties.clone()
    }
    
    /// Nest properties for storage
    /// Example: {"status": "OPEN"} → {"task": {"status": "OPEN"}}
    pub fn nest_properties(
        node_type: &str, 
        flat_props: serde_json::Value,
        existing_props: Option<serde_json::Value>
    ) -> serde_json::Value {
        let mut result = existing_props
            .and_then(|v| v.as_object().cloned())
            .unwrap_or_default();
        
        result.insert(node_type.to_string(), flat_props);
        serde_json::Value::Object(result)
    }

    Step 2: NodeService Updates

    packages/core/src/services/node_service.rs

    In create_node():

    // Before insert:
    node.properties = Node::nest_properties(&node.node_type, node.properties, None);

    In update_node():

    // Preserve other type namespaces:
    let existing_node = self.get_node(id).await?;
    node.properties = Node::nest_properties(
        &node.node_type, 
        node.properties,
        Some(existing_node.properties)
    );

    In get_node() and query_nodes():

    // Before return:
    node.properties = node.flatten_properties();

    Step 3: Behavior Validation Updates

    packages/core/src/behaviors/mod.rs

    Update each behavior to validate nested properties:

    // OLD:
    if let Some(status) = node.properties.get("status") { ... }
    
    // NEW:
    if let Some(task_props) = node.properties.get("task") {
        if let Some(status) = task_props.get("status") { ... }
    }

    Step 4: Test Updates

    Search and replace across ~377 tests:

    # Find test files with property access
    rg 'json!\(\{.*"status"' packages/core/src --type rust
    
    # Update test data
    json!({"status": "OPEN"})  
    →  
    json!({"task": {"status": "OPEN"}})

    Key test files:

    • packages/core/src/behaviors/mod.rs (behavior tests)
    • packages/core/src/services/node_service.rs (service tests)
    • packages/core/src/db/database.rs (seed data tests - already updated)

    Step 5: Validation

    cargo test --package nodespace-core

    Fix failures iteratively.


    🎯 Success Criteria

    • Node model has flatten_properties() and nest_properties() helpers
    • NodeService CRUD operations nest/flatten transparently
    • Behaviors validate nested structure (e.g., properties.task.status)
    • All Rust tests pass with nested property format
    • Frontend tests still pass (no changes needed)
    • Type conversion preserves properties (manual test: task→text→task)

    📦 Current State

    Branch: feature/issue-397-type-namespaced-properties
    Commit: deea207 - Schema fixes complete
    Status: Ready for property implementation
    Tests: All database tests passing ✅

    To continue:

    git checkout feature/issue-397-type-namespaced-properties
    git pull origin feature/issue-397-type-namespaced-properties
    # Start with Step 1: Node Model Helpers

    💡 Implementation Notes

    1. Backward Compatibility: If properties aren't nested, return as-is (handles old data)
    2. Type Preservation: When updating, merge nested properties don't overwrite other types
    3. Validation: Only validate properties for current node_type
    4. Frontend Impact: ZERO - all nesting/flattening happens in backend

    Estimated Effort: 4-6 hours

    • Node model: 30min
    • Service updates: 1-2 hours
    • Behavior updates: 1 hour
    • Test updates: 2-3 hours
  4. 4 remaining items

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions