Repository navigation
Description
Overview
Refactor the embedding pipeline so that each node type's NodeBehavior is the single source of truth for embedding decisions. Uses a two-phase content extraction approach (sync + async) and introduces a NodeAccessor trait so the embedding service goes through NodeService instead of SurrealStore directly.
Architecture decision: ADR-029
Problem
Current architecture has split responsibilities:
NodeBehaviortrait definesget_embeddable_content()andget_parent_contribution()— each type implements these correctlyNodeEmbeddingServiceignores these methods entirely:- Uses
is_embeddable_type()(hardcodedEMBEDDABLE_NODE_TYPESlist) to decide root embeddability - Calls
SurrealStoredirectly to fetch subtree nodes - Concatenates
node.contentfrom root + descendants, ignoring behavior methods
- Uses
- Existing bug:
TableNodeBehavior.get_embeddable_content()returnsSome(content)buttableis missing fromEMBEDDABLE_NODE_TYPES— the dual source of truth problem is already causing issues
This means:
- Types cannot customize what content gets embedded (e.g., ai-chat extracting messages from
properties.messages[]) - Adding a new embeddable type requires editing TWO places
- Embedding service bypasses NodeService business rules
Proposed Architecture
Two-Phase Content Extraction (ADR-029)
/// Phase 1: Content from this node alone. Synchronous, no I/O.
/// Returns Some(text) if embeddable, None if not.
fn get_embeddable_content(&self, node: &Node) -> Option<String>;
/// Phase 2: Additional content aggregated from related nodes.
/// Called only when the embedding service is building a composite embedding.
/// Default: None (no aggregation needed). Async, opt-in.
async fn get_aggregated_content(
&self,
node: &Node,
accessor: &dyn NodeAccessor,
) -> Option<String> {
None // default: no aggregation
}
/// Content this node contributes to its parent's embedding.
/// Synchronous, no I/O. Unchanged from current trait.
fn get_parent_contribution(&self, node: &Node) -> Option<String>;Rationale: Most types only need the sync path. Only tree-walking types (text, header) need async aggregation. Keeps the common case fast.
NodeAccessor Trait (new, minimal)
#[async_trait]
pub trait NodeAccessor: Send + Sync {
async fn get_node(&self, id: &str) -> Result<Option<Node>, NodeServiceError>;
async fn get_children(&self, id: &str) -> Result<Vec<Node>, NodeServiceError>;
async fn get_nodes(&self, ids: &[&str]) -> Result<Vec<Node>, NodeServiceError>;
}NodeServiceimplementsNodeAccessorget_nodes_in_subtree()excluded — no current behavior needs arbitrary-depth traversalget_nodes()(batch) included for efficient multi-node fetching- Read-only — behaviors cannot mutate through this interface
- Minimal — resist scope creep
SearchScope Enum
pub enum SearchScope {
/// Default: knowledge nodes (text, header, code-block, schema, table)
Knowledge,
/// Include conversations
Everything,
/// Only conversations
Conversations,
/// Custom type filter
Custom { include_types: Vec<String>, exclude_types: Vec<String> },
}Replaces exclude_types parameter approach. More stable as new types are added — callers don't need to know about every type.
Dependency Change
Before:
NodeEmbeddingService -> SurrealStore (direct)
After:
NodeEmbeddingService -> NodeService (via NodeAccessor trait)
|
BehaviorRegistry + SurrealStore
Circular Dependency Prevention
NodeService->EmbeddingWaker(lightweight mpsc channel, not the service)NodeEmbeddingService->NodeService(viaNodeAccessorfor reads)- No circular reference. Waker pattern already breaks the cycle.
Embedding Service Simplification
pub async fn embed_root_node(&self, root_id: &str) -> Result<(), NodeServiceError> {
let node = self.node_service.get_node(root_id).await?;
let behavior = self.node_service.behavior_for(&node.node_type);
// Phase 1: node's own content (sync, no I/O)
let own_content = behavior.get_embeddable_content(&node);
if own_content.is_none() {
self.delete_embeddings(root_id).await?;
return Ok(());
}
// Phase 2: aggregated content (async, optional)
let aggregated = behavior.get_aggregated_content(&node, &*self.node_service).await;
let full_content = match (own_content, aggregated) {
(Some(own), Some(agg)) => format!("{}\n\n{}", own, agg),
(Some(own), None) => own,
_ => return Ok(()),
};
// Chunk, generate vectors, store (unchanged)
let chunks = self.chunk_content(&full_content);
// ...
}No aggregate_subtree_content(). No is_embeddable_type(). No EMBEDDABLE_NODE_TYPES.
Acceptance Criteria
-
NodeAccessortrait defined withget_node,get_children,get_nodes -
NodeServiceimplementsNodeAccessor -
get_aggregated_content()added toNodeBehaviortrait with defaultNoneimplementation - Text/header behaviors implement
get_aggregated_content()to fetch and aggregate children -
NodeEmbeddingServicedepends onNodeService(viaNodeAccessor), notSurrealStoredirectly -
aggregate_subtree_content()removed from embedding service -
EMBEDDABLE_NODE_TYPESconstant andis_embeddable_type()function removed -
should_embed_root()removed (behavior decides viaget_embeddable_content()) -
SearchScopeenum implemented in semantic search API - MCP
search_semantictool accepts optionalscopeparameter defaulting toKnowledge -
tabletype now correctly embeddable (was excluded from hardcoded list despite behavior returning content) - All existing embedding tests pass unchanged
- New test: mock
NodeAccessor, verify behavior controls content extraction - Batch processing (10 roots per pass) still works correctly
- Code passes
bun run quality:fix
Technical Specifications
Files to Modify
packages/core/src/services/embedding_service.rs— replaceSurrealStorewithNodeService, removeaggregate_subtree_content(),should_embed_root()packages/core/src/services/embedding_processor.rs— wireNodeServicethroughpackages/core/src/behaviors/mod.rs— addget_aggregated_content(), update existing implementationspackages/core/src/models/embedding.rs— removeEMBEDDABLE_NODE_TYPES,is_embeddable_type()packages/core/src/services/mod.rs— defineNodeAccessortraitpackages/core/src/mcp/handlers/search.rs— addSearchScopesupport- Tests referencing removed functions
How Each Type Works After Refactor
| Type | get_embeddable_content |
get_aggregated_content |
get_parent_contribution |
|---|---|---|---|
| text | Some(node.content) |
Fetches children, aggregates | Some(node.content) |
| header | Some(node.content) |
Fetches children, aggregates | Some(node.content) |
| ai-chat | Extracts user+assistant from properties.messages[] |
None |
None |
| task | None |
N/A | None |
| date | None |
N/A | None |
| table | Some(node.content) (BUG FIX: now actually embedded) |
None |
Some(node.content) |
| collection | None |
N/A | None |
Batch Processing
Unchanged. Processor still fetches stale root IDs in batches of 10, calls embed_root_node() per root. The behavior handles content extraction instead of the embedding service.
Dependencies
- None (refactor of existing code)
Related Issues
- ACP Integration and Local LLM Capability #997 (parent epic)
- AI Chat node type: schema, behavior, plugin, and viewer #1017 (ai-chat node type — benefits from this for behavior-based embedding)
Activity
[-]Wire embedding service to use NodeBehavior methods for content extraction[/-][+]Refactor embedding service to use NodeBehavior via NodeService for content extraction[/+]malibio commentedon Apr 3, 2026
Baseline: 119 test files, 3748 tests passing
malibio commentedon Apr 3, 2026
Baseline: 119 test files, 3748 tests passing
refactor: embedding service uses NodeBehavior for content extraction (c…