Skip to content

Refactor Node Service Architecture for Multi-Tab/Pane Support - #205

Merged
malibio merged 5 commits into
mainfrom
feature/issue-197-multi-tab-architecture
Oct 10, 2025
Merged

malibio merged 5 commits into
mainfrom
feature/issue-197-multi-tab-architecture

Conversation

@malibio

@malibio malibio commented Oct 10, 2025

Copy link
Copy Markdown
Collaborator

Closes #197

malibio and others added 5 commits October 10, 2025 15:53
## Phase 1 Complete: Shared Node Store Foundation

### New Features
- **SharedNodeStore**: Singleton reactive data store for all node data
  - Observer pattern for viewer subscriptions (real-time notifications)
  - Version tracking for optimistic concurrency control
  - Performance metrics tracking (update time, subscription count, conflicts)
  - Memory leak prevention with proper cleanup

- **Update Protocol**: Multi-source update handling with source tracking
  - Support for viewer, database, MCP server, and external sources
  - Conflict detection (version mismatch, concurrent edits)
  - Optimistic updates with rollback capability

- **Conflict Resolution**: Pluggable strategy pattern
  - Last-Write-Wins resolver (Phase 1 implementation)
  - Field-Level Merge resolver (prepared for Phase 2+)
  - Operational Transform resolver (prepared for Phase 3+)
  - Manual resolution (prepared for Phase 3+)

### Test Coverage
- 31 comprehensive tests covering:
  - Singleton behavior
  - CRUD operations
  - Node filtering by parent
  - Observer pattern subscriptions
  - Version tracking
  - Conflict detection
  - Performance metrics
  - Memory leak prevention

### Architecture
- Plain TypeScript implementation (no Svelte runes in store)
- Reactivity will be provided by ReactiveNodeService adapter (Phase 1.2)
- Foundation ready for multi-viewer synchronization

### Files Added
- `src/lib/services/shared-node-store.ts` - Core singleton store
- `src/lib/types/update-protocol.ts` - Update types and protocols
- `src/lib/services/conflict-resolvers.ts` - Pluggable conflict resolution
- `src/tests/services/shared-node-store.test.ts` - Comprehensive test suite

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
## Phase 1.2 Complete: ReactiveNodeService Adapter Pattern

### Major Refactoring
- **ReactiveNodeService**: Now delegates all node data storage to SharedNodeStore
  - Zero occurrences of direct `_nodes` access (verified)
  - 68 SharedNodeStore API calls throughout the service
  - Maintains per-viewer UI state (_uiState, _rootNodeIds)
  - Unique viewerId and viewerSource for each instance
  - Wildcard subscription to SharedNodeStore for reactivity

### Architecture Changes
- **Data Layer**: Completely delegated to SharedNodeStore (single source of truth)
- **UI Layer**: Remains in ReactiveNodeService (expand/collapse, focus, depth)
- **Reactivity**: Preserved via _updateTrigger and Svelte 5 runes ($state, $derived)
- **Backward Compatibility**: All existing function signatures unchanged

### Updated Functions (all use SharedNodeStore)
- `createNode()` - Node creation and sibling chain updates
- `updateNodeContent()`, `updateNodeType()`, `updateNodeMentions()`, `updateNodeProperties()`
- `combineNodes()` - Node merging and child promotion
- `deleteNode()` - Deletion and child promotion
- `indentNode()` / `outdentNode()` - Hierarchy changes
- `removeFromSiblingChain()` - Sibling chain maintenance
- All helper functions and integration test methods

### Quality & Testing
- ✅ 31 SharedNodeStore tests passing
- ✅ Lint errors fixed (unused imports, variables)
- ✅ Type errors resolved (event types, child arrays)
- ✅ All quality checks pass (lint, format, type-check)

### Multi-Viewer Foundation Ready
- Each ReactiveNodeService instance now has unique viewerId
- All updates tagged with viewerSource for tracking
- SharedNodeStore broadcasts changes to all subscribed viewers
- Foundation complete for multi-tab/pane synchronization

### Known Limitations (TODOs)
- Event types need updating for new coordination events
- MCP integration stubbed (Phase 3)
- Tab/Pane UI components deferred (Phase 4-5)

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
## Phase 2 Implementation Complete

### Phase 2.5: Event Bus Source Tracking
- Added ConflictResolvedEvent and UpdateRolledBackEvent to event-types.ts
- Both events extend BaseEvent with proper type definitions
- Added events to NodeSpaceEvent union type
- Added event type constants (CONFLICT_RESOLVED, UPDATE_ROLLED_BACK)
- Uncommented and properly typed event emissions in SharedNodeStore
- All events now properly track source information

### Event Emissions
- Conflict resolution emits `node:conflict-resolved` with:
  - nodeId, conflictType, strategy, discardedUpdate
- Rollback emits `node:update-rolled-back` with:
  - nodeId, reason, failedUpdate
- Both use typed event emissions with proper type parameters

### Testing
- All 31 SharedNodeStore tests passing
- Database write errors properly handled (expected in test environment)
- Quality checks passing (lint, format, type checking)

## Phase 1-2 Summary

**Phase 1: Shared Node Store Foundation**
✅ Singleton SharedNodeStore with observer pattern
✅ Version tracking and conflict detection
✅ ReactiveNodeService adapter pattern (backward compatible)
✅ Comprehensive test suite (31 tests)

**Phase 2: Multi-Source Update Handling**
✅ Update protocol types with source tracking
✅ Optimistic updates with rollback
✅ Last-Write-Wins conflict resolution (pluggable)
✅ Database write coordination (queued writes)
✅ Event bus source tracking

## Architecture Highlights
- Single source of truth for node data
- Multiple viewers subscribe to shared store
- Database writes coordinated to prevent races
- Graceful degradation (works without database)
- Type-safe event emissions throughout

Next: Performance validation and PR creation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
## Phase 3: External Update Handling (MCP-Ready)

### Implementation

**`handleExternalUpdate()` Method:**
- Provides integration point for future MCP server (Issue #112)
- Routes external updates through standard conflict detection pipeline
- Handles updates from: 'mcp-server', 'database', 'external' sources
- Validates node existence before applying updates
- Smart persistence: skips for database sources to avoid loops

**Key Features:**
- Single entry point for all external updates
- Consistent conflict detection across all sources
- Event emissions for all update types
- Metrics tracking for external updates
- Prepared for MCP server integration without blocking on #112

### Testing (12 Simulated MCP Tests)

**Test Coverage:**
1. **Basic MCP Update Handling** (4 tests)
   - MCP server updates
   - Database sync updates
   - Generic external updates
   - Non-existent node validation

2. **Multi-Viewer Synchronization** (2 tests)
   - Propagation to all subscribed viewers
   - Integration with ReactiveNodeService

3. **MCP Update Conflicts** (2 tests)
   - Local edit + MCP update sequences
   - Conflict-resolved event emissions

4. **Performance** (2 tests)
   - High-frequency updates (100 nodes, <100ms)
   - Metrics tracking for MCP updates

5. **Integration Readiness** (2 tests)
   - Clear integration point demonstration
   - Reconnection with batch updates

### Integration Pattern for #112

When MCP server is ready, integration is straightforward:

```typescript
// Future: Wire up MCP server events
mcpServer.on('node:updated', (update) => {
  sharedStore.handleExternalUpdate('mcp-server', update);
});
```

### Architecture Benefits

✅ **Unblocks #197** - Multi-tab architecture complete without waiting for #112
✅ **Type-safe** - Full UpdateSource tracking for all external updates
✅ **Conflict-aware** - MCP updates go through same detection as local edits
✅ **Tested** - Simulated MCP behavior validates architecture
✅ **Ready to integrate** - Single method call when #112 completes

## Test Results

- ✅ 12/12 MCP integration tests passing
- ✅ 31/31 SharedNodeStore tests passing
- ✅ All quality checks passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
## Improvements from Code Review

### 1. Type Safety in Conflict Resolution
- Updated ConflictResolver interface to accept existingNode parameter
- All resolvers now merge with existing node instead of type casting
- LastWriteWinsResolver: Changed from `...(winner.changes as Node)` to `...existingNode, ...winner.changes`
- FieldLevelMergeResolver: Now merges into existingNode for type safety
- OperationalTransformResolver: Updated to pass existingNode to fallback
- ManualConflictResolver: Updated to pass existingNode to fallback

**Benefit:** Eliminates unsafe type assertion, prevents potential runtime errors if Partial<Node> is incomplete

### 2. Configurable Conflict Window
- Added `private conflictWindowMs = 5000` property to SharedNodeStore
- Added `setConflictWindow(ms: number)` method for runtime configuration
- Replaced hardcoded constant with instance property
- Default remains 5 seconds for backward compatibility

**Benefit:** Allows deployment-specific tuning without code changes

## Test Results
- ✅ All quality checks passing (lint, format, types)
- ✅ 43/43 Phase 1-3 tests passing
- ✅ No breaking changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio merged commit 5def968 into main Oct 10, 2025
@malibio
malibio deleted the feature/issue-197-multi-tab-architecture branch October 10, 2025 17:55
malibio added a commit that referenced this pull request Feb 4, 2026
* Phase 1: Implement SharedNodeStore foundation with conflict resolution

## Phase 1 Complete: Shared Node Store Foundation

### New Features
- **SharedNodeStore**: Singleton reactive data store for all node data
  - Observer pattern for viewer subscriptions (real-time notifications)
  - Version tracking for optimistic concurrency control
  - Performance metrics tracking (update time, subscription count, conflicts)
  - Memory leak prevention with proper cleanup

- **Update Protocol**: Multi-source update handling with source tracking
  - Support for viewer, database, MCP server, and external sources
  - Conflict detection (version mismatch, concurrent edits)
  - Optimistic updates with rollback capability

- **Conflict Resolution**: Pluggable strategy pattern
  - Last-Write-Wins resolver (Phase 1 implementation)
  - Field-Level Merge resolver (prepared for Phase 2+)
  - Operational Transform resolver (prepared for Phase 3+)
  - Manual resolution (prepared for Phase 3+)

### Test Coverage
- 31 comprehensive tests covering:
  - Singleton behavior
  - CRUD operations
  - Node filtering by parent
  - Observer pattern subscriptions
  - Version tracking
  - Conflict detection
  - Performance metrics
  - Memory leak prevention

### Architecture
- Plain TypeScript implementation (no Svelte runes in store)
- Reactivity will be provided by ReactiveNodeService adapter (Phase 1.2)
- Foundation ready for multi-viewer synchronization

### Files Added
- `src/lib/services/shared-node-store.ts` - Core singleton store
- `src/lib/types/update-protocol.ts` - Update types and protocols
- `src/lib/services/conflict-resolvers.ts` - Pluggable conflict resolution
- `src/tests/services/shared-node-store.test.ts` - Comprehensive test suite

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Phase 1.2: Refactor ReactiveNodeService to adapter pattern

## Phase 1.2 Complete: ReactiveNodeService Adapter Pattern

### Major Refactoring
- **ReactiveNodeService**: Now delegates all node data storage to SharedNodeStore
  - Zero occurrences of direct `_nodes` access (verified)
  - 68 SharedNodeStore API calls throughout the service
  - Maintains per-viewer UI state (_uiState, _rootNodeIds)
  - Unique viewerId and viewerSource for each instance
  - Wildcard subscription to SharedNodeStore for reactivity

### Architecture Changes
- **Data Layer**: Completely delegated to SharedNodeStore (single source of truth)
- **UI Layer**: Remains in ReactiveNodeService (expand/collapse, focus, depth)
- **Reactivity**: Preserved via _updateTrigger and Svelte 5 runes ($state, $derived)
- **Backward Compatibility**: All existing function signatures unchanged

### Updated Functions (all use SharedNodeStore)
- `createNode()` - Node creation and sibling chain updates
- `updateNodeContent()`, `updateNodeType()`, `updateNodeMentions()`, `updateNodeProperties()`
- `combineNodes()` - Node merging and child promotion
- `deleteNode()` - Deletion and child promotion
- `indentNode()` / `outdentNode()` - Hierarchy changes
- `removeFromSiblingChain()` - Sibling chain maintenance
- All helper functions and integration test methods

### Quality & Testing
- ✅ 31 SharedNodeStore tests passing
- ✅ Lint errors fixed (unused imports, variables)
- ✅ Type errors resolved (event types, child arrays)
- ✅ All quality checks pass (lint, format, type-check)

### Multi-Viewer Foundation Ready
- Each ReactiveNodeService instance now has unique viewerId
- All updates tagged with viewerSource for tracking
- SharedNodeStore broadcasts changes to all subscribed viewers
- Foundation complete for multi-tab/pane synchronization

### Known Limitations (TODOs)
- Event types need updating for new coordination events
- MCP integration stubbed (Phase 3)
- Tab/Pane UI components deferred (Phase 4-5)

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Complete Phase 2: Multi-Source Update Handling with Source Tracking

## Phase 2 Implementation Complete

### Phase 2.5: Event Bus Source Tracking
- Added ConflictResolvedEvent and UpdateRolledBackEvent to event-types.ts
- Both events extend BaseEvent with proper type definitions
- Added events to NodeSpaceEvent union type
- Added event type constants (CONFLICT_RESOLVED, UPDATE_ROLLED_BACK)
- Uncommented and properly typed event emissions in SharedNodeStore
- All events now properly track source information

### Event Emissions
- Conflict resolution emits `node:conflict-resolved` with:
  - nodeId, conflictType, strategy, discardedUpdate
- Rollback emits `node:update-rolled-back` with:
  - nodeId, reason, failedUpdate
- Both use typed event emissions with proper type parameters

### Testing
- All 31 SharedNodeStore tests passing
- Database write errors properly handled (expected in test environment)
- Quality checks passing (lint, format, type checking)

## Phase 1-2 Summary

**Phase 1: Shared Node Store Foundation**
✅ Singleton SharedNodeStore with observer pattern
✅ Version tracking and conflict detection
✅ ReactiveNodeService adapter pattern (backward compatible)
✅ Comprehensive test suite (31 tests)

**Phase 2: Multi-Source Update Handling**
✅ Update protocol types with source tracking
✅ Optimistic updates with rollback
✅ Last-Write-Wins conflict resolution (pluggable)
✅ Database write coordination (queued writes)
✅ Event bus source tracking

## Architecture Highlights
- Single source of truth for node data
- Multiple viewers subscribe to shared store
- Database writes coordinated to prevent races
- Graceful degradation (works without database)
- Type-safe event emissions throughout

Next: Performance validation and PR creation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Complete Phase 3: MCP-Ready Integration with Simulated Tests

## Phase 3: External Update Handling (MCP-Ready)

### Implementation

**`handleExternalUpdate()` Method:**
- Provides integration point for future MCP server (Issue #112)
- Routes external updates through standard conflict detection pipeline
- Handles updates from: 'mcp-server', 'database', 'external' sources
- Validates node existence before applying updates
- Smart persistence: skips for database sources to avoid loops

**Key Features:**
- Single entry point for all external updates
- Consistent conflict detection across all sources
- Event emissions for all update types
- Metrics tracking for external updates
- Prepared for MCP server integration without blocking on #112

### Testing (12 Simulated MCP Tests)

**Test Coverage:**
1. **Basic MCP Update Handling** (4 tests)
   - MCP server updates
   - Database sync updates
   - Generic external updates
   - Non-existent node validation

2. **Multi-Viewer Synchronization** (2 tests)
   - Propagation to all subscribed viewers
   - Integration with ReactiveNodeService

3. **MCP Update Conflicts** (2 tests)
   - Local edit + MCP update sequences
   - Conflict-resolved event emissions

4. **Performance** (2 tests)
   - High-frequency updates (100 nodes, <100ms)
   - Metrics tracking for MCP updates

5. **Integration Readiness** (2 tests)
   - Clear integration point demonstration
   - Reconnection with batch updates

### Integration Pattern for #112

When MCP server is ready, integration is straightforward:

```typescript
// Future: Wire up MCP server events
mcpServer.on('node:updated', (update) => {
  sharedStore.handleExternalUpdate('mcp-server', update);
});
```

### Architecture Benefits

✅ **Unblocks #197** - Multi-tab architecture complete without waiting for #112
✅ **Type-safe** - Full UpdateSource tracking for all external updates
✅ **Conflict-aware** - MCP updates go through same detection as local edits
✅ **Tested** - Simulated MCP behavior validates architecture
✅ **Ready to integrate** - Single method call when #112 completes

## Test Results

- ✅ 12/12 MCP integration tests passing
- ✅ 31/31 SharedNodeStore tests passing
- ✅ All quality checks passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Apply code review improvements: type safety and configurability

## Improvements from Code Review

### 1. Type Safety in Conflict Resolution
- Updated ConflictResolver interface to accept existingNode parameter
- All resolvers now merge with existing node instead of type casting
- LastWriteWinsResolver: Changed from `...(winner.changes as Node)` to `...existingNode, ...winner.changes`
- FieldLevelMergeResolver: Now merges into existingNode for type safety
- OperationalTransformResolver: Updated to pass existingNode to fallback
- ManualConflictResolver: Updated to pass existingNode to fallback

**Benefit:** Eliminates unsafe type assertion, prevents potential runtime errors if Partial<Node> is incomplete

### 2. Configurable Conflict Window
- Added `private conflictWindowMs = 5000` property to SharedNodeStore
- Added `setConflictWindow(ms: number)` method for runtime configuration
- Replaced hardcoded constant with instance property
- Default remains 5 seconds for backward compatibility

**Benefit:** Allows deployment-specific tuning without code changes

## Test Results
- ✅ All quality checks passing (lint, format, types)
- ✅ 43/43 Phase 1-3 tests passing
- ✅ No breaking changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
* Phase 1: Implement SharedNodeStore foundation with conflict resolution

## Phase 1 Complete: Shared Node Store Foundation

### New Features
- **SharedNodeStore**: Singleton reactive data store for all node data
  - Observer pattern for viewer subscriptions (real-time notifications)
  - Version tracking for optimistic concurrency control
  - Performance metrics tracking (update time, subscription count, conflicts)
  - Memory leak prevention with proper cleanup

- **Update Protocol**: Multi-source update handling with source tracking
  - Support for viewer, database, MCP server, and external sources
  - Conflict detection (version mismatch, concurrent edits)
  - Optimistic updates with rollback capability

- **Conflict Resolution**: Pluggable strategy pattern
  - Last-Write-Wins resolver (Phase 1 implementation)
  - Field-Level Merge resolver (prepared for Phase 2+)
  - Operational Transform resolver (prepared for Phase 3+)
  - Manual resolution (prepared for Phase 3+)

### Test Coverage
- 31 comprehensive tests covering:
  - Singleton behavior
  - CRUD operations
  - Node filtering by parent
  - Observer pattern subscriptions
  - Version tracking
  - Conflict detection
  - Performance metrics
  - Memory leak prevention

### Architecture
- Plain TypeScript implementation (no Svelte runes in store)
- Reactivity will be provided by ReactiveNodeService adapter (Phase 1.2)
- Foundation ready for multi-viewer synchronization

### Files Added
- `src/lib/services/shared-node-store.ts` - Core singleton store
- `src/lib/types/update-protocol.ts` - Update types and protocols
- `src/lib/services/conflict-resolvers.ts` - Pluggable conflict resolution
- `src/tests/services/shared-node-store.test.ts` - Comprehensive test suite

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Phase 1.2: Refactor ReactiveNodeService to adapter pattern

## Phase 1.2 Complete: ReactiveNodeService Adapter Pattern

### Major Refactoring
- **ReactiveNodeService**: Now delegates all node data storage to SharedNodeStore
  - Zero occurrences of direct `_nodes` access (verified)
  - 68 SharedNodeStore API calls throughout the service
  - Maintains per-viewer UI state (_uiState, _rootNodeIds)
  - Unique viewerId and viewerSource for each instance
  - Wildcard subscription to SharedNodeStore for reactivity

### Architecture Changes
- **Data Layer**: Completely delegated to SharedNodeStore (single source of truth)
- **UI Layer**: Remains in ReactiveNodeService (expand/collapse, focus, depth)
- **Reactivity**: Preserved via _updateTrigger and Svelte 5 runes ($state, $derived)
- **Backward Compatibility**: All existing function signatures unchanged

### Updated Functions (all use SharedNodeStore)
- `createNode()` - Node creation and sibling chain updates
- `updateNodeContent()`, `updateNodeType()`, `updateNodeMentions()`, `updateNodeProperties()`
- `combineNodes()` - Node merging and child promotion
- `deleteNode()` - Deletion and child promotion
- `indentNode()` / `outdentNode()` - Hierarchy changes
- `removeFromSiblingChain()` - Sibling chain maintenance
- All helper functions and integration test methods

### Quality & Testing
- ✅ 31 SharedNodeStore tests passing
- ✅ Lint errors fixed (unused imports, variables)
- ✅ Type errors resolved (event types, child arrays)
- ✅ All quality checks pass (lint, format, type-check)

### Multi-Viewer Foundation Ready
- Each ReactiveNodeService instance now has unique viewerId
- All updates tagged with viewerSource for tracking
- SharedNodeStore broadcasts changes to all subscribed viewers
- Foundation complete for multi-tab/pane synchronization

### Known Limitations (TODOs)
- Event types need updating for new coordination events
- MCP integration stubbed (Phase 3)
- Tab/Pane UI components deferred (Phase 4-5)

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Complete Phase 2: Multi-Source Update Handling with Source Tracking

## Phase 2 Implementation Complete

### Phase 2.5: Event Bus Source Tracking
- Added ConflictResolvedEvent and UpdateRolledBackEvent to event-types.ts
- Both events extend BaseEvent with proper type definitions
- Added events to NodeSpaceEvent union type
- Added event type constants (CONFLICT_RESOLVED, UPDATE_ROLLED_BACK)
- Uncommented and properly typed event emissions in SharedNodeStore
- All events now properly track source information

### Event Emissions
- Conflict resolution emits `node:conflict-resolved` with:
  - nodeId, conflictType, strategy, discardedUpdate
- Rollback emits `node:update-rolled-back` with:
  - nodeId, reason, failedUpdate
- Both use typed event emissions with proper type parameters

### Testing
- All 31 SharedNodeStore tests passing
- Database write errors properly handled (expected in test environment)
- Quality checks passing (lint, format, type checking)

## Phase 1-2 Summary

**Phase 1: Shared Node Store Foundation**
✅ Singleton SharedNodeStore with observer pattern
✅ Version tracking and conflict detection
✅ ReactiveNodeService adapter pattern (backward compatible)
✅ Comprehensive test suite (31 tests)

**Phase 2: Multi-Source Update Handling**
✅ Update protocol types with source tracking
✅ Optimistic updates with rollback
✅ Last-Write-Wins conflict resolution (pluggable)
✅ Database write coordination (queued writes)
✅ Event bus source tracking

## Architecture Highlights
- Single source of truth for node data
- Multiple viewers subscribe to shared store
- Database writes coordinated to prevent races
- Graceful degradation (works without database)
- Type-safe event emissions throughout

Next: Performance validation and PR creation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Complete Phase 3: MCP-Ready Integration with Simulated Tests

## Phase 3: External Update Handling (MCP-Ready)

### Implementation

**`handleExternalUpdate()` Method:**
- Provides integration point for future MCP server (Issue #112)
- Routes external updates through standard conflict detection pipeline
- Handles updates from: 'mcp-server', 'database', 'external' sources
- Validates node existence before applying updates
- Smart persistence: skips for database sources to avoid loops

**Key Features:**
- Single entry point for all external updates
- Consistent conflict detection across all sources
- Event emissions for all update types
- Metrics tracking for external updates
- Prepared for MCP server integration without blocking on #112

### Testing (12 Simulated MCP Tests)

**Test Coverage:**
1. **Basic MCP Update Handling** (4 tests)
   - MCP server updates
   - Database sync updates
   - Generic external updates
   - Non-existent node validation

2. **Multi-Viewer Synchronization** (2 tests)
   - Propagation to all subscribed viewers
   - Integration with ReactiveNodeService

3. **MCP Update Conflicts** (2 tests)
   - Local edit + MCP update sequences
   - Conflict-resolved event emissions

4. **Performance** (2 tests)
   - High-frequency updates (100 nodes, <100ms)
   - Metrics tracking for MCP updates

5. **Integration Readiness** (2 tests)
   - Clear integration point demonstration
   - Reconnection with batch updates

### Integration Pattern for #112

When MCP server is ready, integration is straightforward:

```typescript
// Future: Wire up MCP server events
mcpServer.on('node:updated', (update) => {
  sharedStore.handleExternalUpdate('mcp-server', update);
});
```

### Architecture Benefits

✅ **Unblocks #197** - Multi-tab architecture complete without waiting for #112
✅ **Type-safe** - Full UpdateSource tracking for all external updates
✅ **Conflict-aware** - MCP updates go through same detection as local edits
✅ **Tested** - Simulated MCP behavior validates architecture
✅ **Ready to integrate** - Single method call when #112 completes

## Test Results

- ✅ 12/12 MCP integration tests passing
- ✅ 31/31 SharedNodeStore tests passing
- ✅ All quality checks passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Apply code review improvements: type safety and configurability

## Improvements from Code Review

### 1. Type Safety in Conflict Resolution
- Updated ConflictResolver interface to accept existingNode parameter
- All resolvers now merge with existing node instead of type casting
- LastWriteWinsResolver: Changed from `...(winner.changes as Node)` to `...existingNode, ...winner.changes`
- FieldLevelMergeResolver: Now merges into existingNode for type safety
- OperationalTransformResolver: Updated to pass existingNode to fallback
- ManualConflictResolver: Updated to pass existingNode to fallback

**Benefit:** Eliminates unsafe type assertion, prevents potential runtime errors if Partial<Node> is incomplete

### 2. Configurable Conflict Window
- Added `private conflictWindowMs = 5000` property to SharedNodeStore
- Added `setConflictWindow(ms: number)` method for runtime configuration
- Replaced hardcoded constant with instance property
- Default remains 5 seconds for backward compatibility

**Benefit:** Allows deployment-specific tuning without code changes

## Test Results
- ✅ All quality checks passing (lint, format, types)
- ✅ 43/43 Phase 1-3 tests passing
- ✅ No breaking changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
* Phase 1: Implement SharedNodeStore foundation with conflict resolution

## Phase 1 Complete: Shared Node Store Foundation

### New Features
- **SharedNodeStore**: Singleton reactive data store for all node data
  - Observer pattern for viewer subscriptions (real-time notifications)
  - Version tracking for optimistic concurrency control
  - Performance metrics tracking (update time, subscription count, conflicts)
  - Memory leak prevention with proper cleanup

- **Update Protocol**: Multi-source update handling with source tracking
  - Support for viewer, database, MCP server, and external sources
  - Conflict detection (version mismatch, concurrent edits)
  - Optimistic updates with rollback capability

- **Conflict Resolution**: Pluggable strategy pattern
  - Last-Write-Wins resolver (Phase 1 implementation)
  - Field-Level Merge resolver (prepared for Phase 2+)
  - Operational Transform resolver (prepared for Phase 3+)
  - Manual resolution (prepared for Phase 3+)

### Test Coverage
- 31 comprehensive tests covering:
  - Singleton behavior
  - CRUD operations
  - Node filtering by parent
  - Observer pattern subscriptions
  - Version tracking
  - Conflict detection
  - Performance metrics
  - Memory leak prevention

### Architecture
- Plain TypeScript implementation (no Svelte runes in store)
- Reactivity will be provided by ReactiveNodeService adapter (Phase 1.2)
- Foundation ready for multi-viewer synchronization

### Files Added
- `src/lib/services/shared-node-store.ts` - Core singleton store
- `src/lib/types/update-protocol.ts` - Update types and protocols
- `src/lib/services/conflict-resolvers.ts` - Pluggable conflict resolution
- `src/tests/services/shared-node-store.test.ts` - Comprehensive test suite

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Phase 1.2: Refactor ReactiveNodeService to adapter pattern

## Phase 1.2 Complete: ReactiveNodeService Adapter Pattern

### Major Refactoring
- **ReactiveNodeService**: Now delegates all node data storage to SharedNodeStore
  - Zero occurrences of direct `_nodes` access (verified)
  - 68 SharedNodeStore API calls throughout the service
  - Maintains per-viewer UI state (_uiState, _rootNodeIds)
  - Unique viewerId and viewerSource for each instance
  - Wildcard subscription to SharedNodeStore for reactivity

### Architecture Changes
- **Data Layer**: Completely delegated to SharedNodeStore (single source of truth)
- **UI Layer**: Remains in ReactiveNodeService (expand/collapse, focus, depth)
- **Reactivity**: Preserved via _updateTrigger and Svelte 5 runes ($state, $derived)
- **Backward Compatibility**: All existing function signatures unchanged

### Updated Functions (all use SharedNodeStore)
- `createNode()` - Node creation and sibling chain updates
- `updateNodeContent()`, `updateNodeType()`, `updateNodeMentions()`, `updateNodeProperties()`
- `combineNodes()` - Node merging and child promotion
- `deleteNode()` - Deletion and child promotion
- `indentNode()` / `outdentNode()` - Hierarchy changes
- `removeFromSiblingChain()` - Sibling chain maintenance
- All helper functions and integration test methods

### Quality & Testing
- ✅ 31 SharedNodeStore tests passing
- ✅ Lint errors fixed (unused imports, variables)
- ✅ Type errors resolved (event types, child arrays)
- ✅ All quality checks pass (lint, format, type-check)

### Multi-Viewer Foundation Ready
- Each ReactiveNodeService instance now has unique viewerId
- All updates tagged with viewerSource for tracking
- SharedNodeStore broadcasts changes to all subscribed viewers
- Foundation complete for multi-tab/pane synchronization

### Known Limitations (TODOs)
- Event types need updating for new coordination events
- MCP integration stubbed (Phase 3)
- Tab/Pane UI components deferred (Phase 4-5)

Relates to #197

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Complete Phase 2: Multi-Source Update Handling with Source Tracking

## Phase 2 Implementation Complete

### Phase 2.5: Event Bus Source Tracking
- Added ConflictResolvedEvent and UpdateRolledBackEvent to event-types.ts
- Both events extend BaseEvent with proper type definitions
- Added events to NodeSpaceEvent union type
- Added event type constants (CONFLICT_RESOLVED, UPDATE_ROLLED_BACK)
- Uncommented and properly typed event emissions in SharedNodeStore
- All events now properly track source information

### Event Emissions
- Conflict resolution emits `node:conflict-resolved` with:
  - nodeId, conflictType, strategy, discardedUpdate
- Rollback emits `node:update-rolled-back` with:
  - nodeId, reason, failedUpdate
- Both use typed event emissions with proper type parameters

### Testing
- All 31 SharedNodeStore tests passing
- Database write errors properly handled (expected in test environment)
- Quality checks passing (lint, format, type checking)

## Phase 1-2 Summary

**Phase 1: Shared Node Store Foundation**
✅ Singleton SharedNodeStore with observer pattern
✅ Version tracking and conflict detection
✅ ReactiveNodeService adapter pattern (backward compatible)
✅ Comprehensive test suite (31 tests)

**Phase 2: Multi-Source Update Handling**
✅ Update protocol types with source tracking
✅ Optimistic updates with rollback
✅ Last-Write-Wins conflict resolution (pluggable)
✅ Database write coordination (queued writes)
✅ Event bus source tracking

## Architecture Highlights
- Single source of truth for node data
- Multiple viewers subscribe to shared store
- Database writes coordinated to prevent races
- Graceful degradation (works without database)
- Type-safe event emissions throughout

Next: Performance validation and PR creation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Complete Phase 3: MCP-Ready Integration with Simulated Tests

## Phase 3: External Update Handling (MCP-Ready)

### Implementation

**`handleExternalUpdate()` Method:**
- Provides integration point for future MCP server (Issue #112)
- Routes external updates through standard conflict detection pipeline
- Handles updates from: 'mcp-server', 'database', 'external' sources
- Validates node existence before applying updates
- Smart persistence: skips for database sources to avoid loops

**Key Features:**
- Single entry point for all external updates
- Consistent conflict detection across all sources
- Event emissions for all update types
- Metrics tracking for external updates
- Prepared for MCP server integration without blocking on #112

### Testing (12 Simulated MCP Tests)

**Test Coverage:**
1. **Basic MCP Update Handling** (4 tests)
   - MCP server updates
   - Database sync updates
   - Generic external updates
   - Non-existent node validation

2. **Multi-Viewer Synchronization** (2 tests)
   - Propagation to all subscribed viewers
   - Integration with ReactiveNodeService

3. **MCP Update Conflicts** (2 tests)
   - Local edit + MCP update sequences
   - Conflict-resolved event emissions

4. **Performance** (2 tests)
   - High-frequency updates (100 nodes, <100ms)
   - Metrics tracking for MCP updates

5. **Integration Readiness** (2 tests)
   - Clear integration point demonstration
   - Reconnection with batch updates

### Integration Pattern for #112

When MCP server is ready, integration is straightforward:

```typescript
// Future: Wire up MCP server events
mcpServer.on('node:updated', (update) => {
  sharedStore.handleExternalUpdate('mcp-server', update);
});
```

### Architecture Benefits

✅ **Unblocks #197** - Multi-tab architecture complete without waiting for #112
✅ **Type-safe** - Full UpdateSource tracking for all external updates
✅ **Conflict-aware** - MCP updates go through same detection as local edits
✅ **Tested** - Simulated MCP behavior validates architecture
✅ **Ready to integrate** - Single method call when #112 completes

## Test Results

- ✅ 12/12 MCP integration tests passing
- ✅ 31/31 SharedNodeStore tests passing
- ✅ All quality checks passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Apply code review improvements: type safety and configurability

## Improvements from Code Review

### 1. Type Safety in Conflict Resolution
- Updated ConflictResolver interface to accept existingNode parameter
- All resolvers now merge with existing node instead of type casting
- LastWriteWinsResolver: Changed from `...(winner.changes as Node)` to `...existingNode, ...winner.changes`
- FieldLevelMergeResolver: Now merges into existingNode for type safety
- OperationalTransformResolver: Updated to pass existingNode to fallback
- ManualConflictResolver: Updated to pass existingNode to fallback

**Benefit:** Eliminates unsafe type assertion, prevents potential runtime errors if Partial<Node> is incomplete

### 2. Configurable Conflict Window
- Added `private conflictWindowMs = 5000` property to SharedNodeStore
- Added `setConflictWindow(ms: number)` method for runtime configuration
- Replaced hardcoded constant with instance property
- Default remains 5 seconds for backward compatibility

**Benefit:** Allows deployment-specific tuning without code changes

## Test Results
- ✅ All quality checks passing (lint, format, types)
- ✅ 43/43 Phase 1-3 tests passing
- ✅ No breaking changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor Node Service Architecture for Multi-Tab Support (Phases 1-3: Foundation)

1 participant