Repository navigation
Closed
Description
Overview
Refactor the domain event emission architecture to centralize change detection at the store layer with automatic notification, emit strongly-typed node payloads (TaskNode, SchemaNode, etc.), and solve the client_id tracking problem for shared NodeService singleton.
Architectural Discussion Summary
After extensive review with senior-architect-reviewer, we've identified critical issues with the current approach and designed a refined solution.
Current Architecture Problems
- Manual Emission Burden: 14+
emit_event()call sites scattered across NodeService methods - Complex Method Risk: Methods with multiple store operations require tracking each change manually
- Client ID Tracking: Current
client_idfield doesn't work with shared singleton NodeService - Forgetting to Emit: No compile-time guarantee that mutations emit events
- Type Mismatch: DomainEvent previously carried generic
Nodestruct, consumers needed type-specific data
Refined Solution: Store-Level Automatic Notification
Based on architectural review, we're adopting a store-level automatic notification pattern that eliminates manual emission entirely.
Architecture Design
Layer 1: Store Change Detection
// packages/core/src/db/surreal_store.rs
pub enum StoreOperation {
Created,
Updated,
Deleted,
}
pub struct StoreChange {
pub operation: StoreOperation,
pub node: Node,
pub source: Option<String>, // Optional for MVP (not persisted)
}
pub struct SurrealStore {
db: Surreal<Db>,
notifier: Option<Arc<dyn Fn(StoreChange) + Send + Sync>>,
}
impl SurrealStore {
pub fn register_notifier<F>(&mut self, notifier: F)
where F: Fn(StoreChange) + Send + Sync + 'static
{
self.notifier = Some(Arc::new(notifier));
}
async fn create_node(&self, node: Node, source: Option<String>) -> Result<Node> {
// DB operation
let created = self.db.create(("nodes", node.id.as_str())).content(node.clone()).await?;
// ✅ Store automatically notifies on every mutation
if let Some(notifier) = &self.notifier {
notifier(StoreChange {
operation: StoreOperation::Created,
node: created.clone(),
source,
});
}
Ok(created)
}
// Same pattern for update_node, delete_node, etc.
}Layer 2: NodeService Registration & Broadcast
// packages/core/src/services/node_service.rs
impl NodeService {
pub async fn new(mut store: Arc<SurrealStore>) -> Result<Self> {
let (event_tx, _) = broadcast::channel(128);
// ✅ Register ONE centralized handler for ALL store changes
let event_tx_clone = event_tx.clone();
store.register_notifier(move |change: StoreChange| {
let node_data = node_to_typed_value(&change.node)
.unwrap_or_else(|_| serde_json::to_value(&change.node).unwrap());
let event = match change.operation {
StoreOperation::Created => DomainEvent::NodeCreated {
node_id: change.node.id.clone(),
node_data,
source_client_id: change.source,
},
StoreOperation::Updated => DomainEvent::NodeUpdated {
node_id: change.node.id.clone(),
node_data,
source_client_id: change.source,
},
StoreOperation::Deleted => DomainEvent::NodeDeleted {
id: change.node.id.clone(),
source_client_id: change.source,
},
};
let _ = event_tx_clone.send(event);
});
Ok(Self { store, event_tx, /* ... */ })
}
// ✅ Methods just call store - NO manual emission!
async fn create_node(&self, node: Node, source: Option<String>) -> Result<String> {
let created = self.store.create_node(node, source).await?;
// Events emitted automatically by store notification!
Ok(created.id)
}
}Layer 3: Client Usage
// Each client passes their identifier per-request
// MCP Handler
let node_id = node_service.create_node(node, Some("mcp".to_string())).await?;
// Tauri Command
let node_id = node_service.create_node(node, Some("tauri".to_string())).await?;
// Proxy Server
let node_id = node_service.create_node(node, Some("proxy".to_string())).await?;
// Tests (no source needed)
let node_id = node_service.create_node(node, None).await?;Layer 4: Event Subscription & SSE
┌─────────────────────────────────────────┐
│ Clients Subscribe to DomainEvents │
│ - MCP: No subscription (doesn't need) │
│ - Tauri: Subscribes for window updates │
│ - Proxy: Subscribes, forwards via SSE │
│ - CloudSync: Subscribes for sync │
└─────────────────────────────────────────┘
↓ (Proxy forwards)
┌─────────────────────────────────────────┐
│ SSE → Multiple Browsers │
│ (All browsers treated as one client) │
└─────────────────────────────────────────┘
Benefits
1. Automatic Emission (Can't Forget)
async fn complex_business_logic(&self, params: Params) -> Result<()> {
// Multiple operations - all automatically emit events!
self.store.update_node(&id_a, update_a, source.clone()).await?;
if should_create_child() {
self.store.create_node(child, source.clone()).await?;
}
for id in obsolete_ids {
self.store.delete_node(&id, source.clone()).await?;
}
// ✅ All events emitted automatically!
// ✅ No manual tracking needed!
}2. Maintenance Reduction
- Current: 14+ manual emit sites → Proposed: 0 manual emit sites
- Current: ~150 lines of emit boilerplate → Proposed: ~20 lines setup
- 87% reduction in emission-related code
3. Type-Safe Payloads
- DomainEvent carries
serde_json::Valuewith typed data - TaskNode has flat
status/priorityfields (not nested inproperties) - Consumers receive ready-to-use data (no conversion needed)
4. Testing Confidence
- If store was called → event was emitted (guaranteed)
- Tests focus on WHAT changed, not IF notification happened
- Single point of failure (notifier setup) vs 14+ potential failure points
Implementation Plan
Phase 1: Store Infrastructure ✅
- Update
DomainEventto useserde_json::Value(completed) - Add
StoreChangestruct tosurreal_store.rs - Add
register_notifier()method toSurrealStore - Update all store mutation methods to call notifier
Phase 2: NodeService Integration
- Register notifier in
NodeService::new() - Remove all manual
emit_event()calls from methods - Update method signatures to accept
source: Option<String>parameter - Remove
emit_node_created()andemit_node_updated()helper methods
Phase 3: Client Updates
- Update MCP handlers to pass
Some("mcp") - Update Tauri commands to pass
Some("tauri") - Update Proxy handlers to pass
Some("proxy") - Update tests to pass
None
Phase 4: Testing & Verification
- Update event emission tests for new structure
- Add test verifying automatic notification
- Verify all 740 Rust tests pass
- Verify all 1546 frontend tests pass
Acceptance Criteria
-
DomainEvent::NodeCreatedandNodeUpdatedcarryserde_json::Valueinstead ofNode✅ - Store methods automatically notify on mutations (via registered callback)
- NodeService registers ONE centralized notification handler
- Zero manual emit_event() calls in NodeService methods
- All store methods accept
source: Option<String>parameter - SSE events contain type-specific data (TaskNode has flat
status, notproperties.status) - All existing tests pass
- MCP→Store→Notification→SSE→UI reactivity works end-to-end
Technical Specifications
Files to Modify
Core Changes:
packages/core/src/db/events.rs- DomainEvent enum (✅ completed)packages/core/src/db/surreal_store.rs- Add notification systempackages/core/src/services/node_service.rs- Remove manual emits, register handler
Test Updates:
packages/core/tests/event_emission_test.rs- Update for new structure (✅ completed)
Future Integration (not in scope):
- dev-proxy SSE bridge (not implemented yet)
- Frontend BrowserSyncService (not implemented yet)
Architectural Decision Rationale
Why Store-Level Notification?
- Scale: As business logic grows complex (50+ methods, 100+ emission sites), manual tracking becomes unsustainable
- Safety: Can't forget to emit - store automatically notifies on every mutation
- Industry Pattern: Similar to database triggers, RocksDB EventListener, event sourcing systems
- Separation: Store reports facts ("node created"), NodeService interprets domain meaning ("broadcast to all except source")
- Testing: Guaranteed emission improves test reliability
Why NOT Store Notification (Concerns Addressed):
- ❌ "Store knows about domain events" → ✅ Store only knows generic
StoreChange, notDomainEvent - ❌ "Callback complexity" → ✅ One-time setup, never touched after
- ❌ "Wrong layer" → ✅ Change detection IS a store concern (like DB triggers)
- ❌ "Client coupling" → ✅
sourceis optional metadata, not business logic
Design Principles:
- Store = Persistence + Change Detection (infrastructure)
- NodeService = Business Logic + Event Broadcasting (domain)
- Clients = Event Consumers (application)
Related Issues
- Rearchitect Domain Events to Support source_client_id Filtering #665 (Client ID tracking - foundation for this refactor)
- Refactor MCP server as managed service and enable browser mode support #715 (MCP server browser mode - discovered the type mismatch issue)
- Strongly-Typed Node Structs with Direct Spoke Table Deserialization #673 (Typed node payloads - node_to_typed_value() implementation)
Non-Goals
- Persisting
sourcefield to database (MVP is single-user) - Changing EdgeCreated/EdgeUpdated/EdgeDeleted events
- Adding new event types
- Modifying the broadcast channel mechanism
Notes
- SSE bridge and BrowserSyncService mentioned in original issue don't exist yet
- Implementation focuses on backend refactor (store notification + typed payloads)
- Frontend integration will happen when SSE/Tauri event forwarding is implemented
Activity
WIP: Fix MCP→UI reactivity for task status updates (Issue #715)
Refactor MCP server as managed service and enable browser mode support (
malibio commentedon Dec 3, 2025
Test baseline established: Frontend - 1546 tests passed (75 test files), Rust - 740 tests passed (16 ignored)
malibio commentedon Dec 3, 2025
WIP commit created with Phase 1 complete and architectural decisions documented. See commit 28bec02 for handoff context. Next session should implement store-level automatic notification (Phases 2-5).
WIP: Issue #718 - Architectural discussion complete, ready for implem…
WIP: Issue #718 - Architectural discussion complete, ready for implem…
Centralize domain event emission with store-level automatic notificat…
Centralize Domain Event Emission with Type-Safe Node Payloads (#723)
Refactor MCP server as managed service and enable browser mode support (
Centralize Domain Event Emission with Type-Safe Node Payloads (#723)
Refactor MCP server as managed service and enable browser mode support (
Centralize Domain Event Emission with Type-Safe Node Payloads (#723)
Refactor MCP server as managed service and enable browser mode support (
Centralize Domain Event Emission with Type-Safe Node Payloads (#723)