Repository navigation
Description
Summary
Three related gaps in the schema relationship system need addressing, identified during architecture review of how custom types (like adr, project, playbook) relate to each other:
target_typeis required but should be optional — not all relationships need to constrain the target node type (e.g., a generic "related" relationship can point to any node)requiredfield on relationships is declared but never enforced — the schema definesrequired: truebut nothing checks whether required relationships actually exist- No completeness query — no way to ask "is this node missing any required relationships?" which is needed for workflows (e.g., a playbook step is incomplete until its required ADR is linked)
Context
How relationships work today
When create_relationship is called (node_service.rs:5330), validation currently:
- Looks up the source node's schema to find the relationship definition
- Strictly checks target node type matches
target_type(line 5391) — fails if mismatch - Checks cardinality constraints (one vs many)
The SchemaRelationship struct (schema.rs:259) has target_type: String as a required field. The required: Option<bool> field exists on the struct but is never read by any validation or query logic.
Why this matters
A user defining a custom adr type might want:
- A
"related"relationship that can point to any node type (document, task, person, etc.) - A
"decision_doc"relationship constrained totarget_type: "header"(the document root) - A
"reviewer"relationship withrequired: true— the ADR is incomplete without a reviewer
Currently, only the second case works correctly. The first case is impossible (no way to omit target_type), and the third declares intent but has no enforcement.
Acceptance Criteria
Part 1: Make target_type optional
- Change
target_typefromStringtoOption<String>inSchemaRelationship
File: packages/core/src/models/schema.rs:267
Before:
/// Target node type (e.g., "customer", "person")
pub target_type: String,After:
/// Target node type constraint (e.g., "customer", "person")
/// When None, the relationship accepts any node type as target.
#[serde(skip_serializing_if = "Option::is_none")]
pub target_type: Option<String>,- Update
compute_edge_table_name(schema.rs:317) to handleNone
Before:
pub fn compute_edge_table_name(&self, source_type: &str) -> String {
self.edge_table
.clone()
.unwrap_or_else(|| format!("{}_{}_{}", source_type, self.name, self.target_type))
}After:
pub fn compute_edge_table_name(&self, source_type: &str) -> String {
self.edge_table
.clone()
.unwrap_or_else(|| {
match &self.target_type {
Some(tt) => format!("{}_{}_{}", source_type, self.name, tt),
None => format!("{}_{}", source_type, self.name),
}
})
}- Update
create_relationshipvalidation (node_service.rs:5391) to skip type check whentarget_typeisNone
Before:
if target.node_type != relationship.target_type {
return Err(NodeServiceError::invalid_update(format!(
"Target node type '{}' doesn't match expected type '{}' for relationship '{}'",
target.node_type, relationship.target_type, relationship_name
)));
}After:
if let Some(ref expected_type) = relationship.target_type {
if target.node_type != *expected_type {
return Err(NodeServiceError::invalid_update(format!(
"Target node type '{}' doesn't match expected type '{}' for relationship '{}'",
target.node_type, expected_type, relationship_name
)));
}
}
// When target_type is None, any node type is accepted- Update
schema_table_manager.rs:105— skipvalidate_type_namewhentarget_typeisNone
Before:
Self::validate_type_name(&relationship.target_type)?;After:
if let Some(ref tt) = relationship.target_type {
Self::validate_type_name(tt)?;
}Also update the same pattern at schema_table_manager.rs:779.
- Update
relationship_cache.rs:210— handleNonein the inbound relationship index
Currently indexes by relationship.target_type.clone(). When target_type is None, the relationship is untyped and won't appear in target-type-specific lookups. Use a sentinel key like "*" or store untyped relationships separately so they can be included in all lookups.
Before:
index
.entry(relationship.target_type.clone())
.or_default()
.push(inbound);After:
match &relationship.target_type {
Some(tt) => {
index.entry(tt.clone()).or_default().push(inbound);
}
None => {
// Untyped relationships apply to all target types
// Store under wildcard key for inclusion in all lookups
index.entry("*".to_string()).or_default().push(inbound.clone());
}
}Then update the lookup method to merge wildcard entries with type-specific entries.
Part 2: Add node completeness check
- Add a
check_node_completenessmethod toNodeService
This method checks whether a node has all its required relationships populated:
/// Result of a node completeness check
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompletenessResult {
/// The node ID that was checked
pub node_id: String,
/// Whether all required relationships are satisfied
pub is_complete: bool,
/// List of missing required relationships
pub missing_relationships: Vec<MissingRelationship>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MissingRelationship {
/// Relationship name from schema (e.g., "reviewer", "decision_doc")
pub name: String,
/// Expected target type (if constrained)
pub target_type: Option<String>,
/// Human-readable description from schema
pub description: Option<String>,
}Implementation logic (add to node_service.rs):
pub async fn check_node_completeness(&self, node_id: &str) -> Result<CompletenessResult, NodeServiceError> {
// 1. Get the node
let node = self.get_node(node_id).await?
.ok_or_else(|| NodeServiceError::node_not_found(node_id))?;
// 2. Get the node's schema
let schema_node = self.get_node(&node.node_type).await?;
let relationships: Vec<SchemaRelationship> = schema_node
.and_then(|s| s.properties.get("relationships")
.and_then(|r| serde_json::from_value(r.clone()).ok()))
.unwrap_or_default();
// 3. Filter to required relationships
let required_rels: Vec<&SchemaRelationship> = relationships.iter()
.filter(|r| r.required == Some(true))
.collect();
// 4. For each required relationship, check if an edge exists
let mut missing = Vec::new();
for rel in required_rels {
let source_thing = surrealdb::sql::Thing::from(("node".to_string(), node_id.to_string()));
let query = "SELECT * FROM relationship WHERE in = $source AND relationship_type = $rel_type LIMIT 1";
let mut result = self.store.db()
.query(query)
.bind(("source", source_thing))
.bind(("rel_type", rel.name.clone()))
.await
.map_err(|e| NodeServiceError::query_failed(format!("Completeness check failed: {}", e)))?;
let existing: Vec<Value> = result.take(0)
.map_err(|e| NodeServiceError::query_failed(format!("Completeness parse failed: {}", e)))?;
if existing.is_empty() {
missing.push(MissingRelationship {
name: rel.name.clone(),
target_type: rel.target_type.clone(),
description: rel.description.clone(),
});
}
}
Ok(CompletenessResult {
node_id: node_id.to_string(),
is_complete: missing.is_empty(),
missing_relationships: missing,
})
}- Expose as MCP tool:
check_node_completeness
File: packages/core/src/mcp/handlers/tools.rs
Add tool definition:
{
"name": "check_node_completeness",
"description": "Check if a node has all required relationships populated. Returns completeness status and lists any missing required relationships as defined by the node's schema.",
"inputSchema": {
"type": "object",
"properties": {
"node_id": {
"type": "string",
"description": "ID of the node to check"
}
},
"required": ["node_id"]
}
}Add as a Tier 2 (Discoverable) tool — discoverable via search_tools with keywords: "completeness", "required", "validation", "workflow".
- Add MCP handler in
packages/core/src/mcp/handlers/relationships.rs:
pub async fn handle_check_node_completeness<C>(
node_service: &Arc<NodeService<C>>,
params: Value,
) -> Result<Value, MCPError>
where
C: surrealdb::Connection,
{
let node_id = params.get("node_id")
.and_then(|v| v.as_str())
.ok_or_else(|| MCPError::invalid_params("node_id is required"))?;
let result = node_service.check_node_completeness(node_id).await
.map_err(|e| MCPError::internal_error(format!("Completeness check failed: {}", e)))?;
Ok(serde_json::to_value(result).unwrap())
}Wire it up in tools.rs route dispatch (around line 398):
"check_node_completeness" => {
relationships::handle_check_node_completeness(node_service, arguments).await
}Files to Modify
| File | Change |
|---|---|
packages/core/src/models/schema.rs |
Change target_type: String → Option<String>, update compute_edge_table_name |
packages/core/src/services/node_service.rs |
Update type check at line 5391 to handle None, add check_node_completeness method |
packages/core/src/services/schema_table_manager.rs |
Skip validate_type_name when target_type is None (lines 105, 779) |
packages/core/src/services/relationship_cache.rs |
Handle None target_type in index (line 210), merge wildcard entries in lookups |
packages/core/src/mcp/handlers/relationships.rs |
Add handle_check_node_completeness handler |
packages/core/src/mcp/handlers/tools.rs |
Add check_node_completeness tool definition and route |
Testing
Part 1: Optional target_type
- Unit test: Create schema with relationship where
target_typeisNone— succeeds - Unit test: Create relationship with untyped relationship — accepts any target node type
- Unit test: Create relationship with typed relationship — still rejects wrong target type
- Unit test:
compute_edge_table_namewithNonetarget_type produces{source}_{name}format - Unit test:
compute_edge_table_namewithSometarget_type produces{source}_{name}_{target}format (existing behavior preserved) - Unit test: Inbound relationship cache returns untyped relationships for all target type lookups
- Existing relationship tests continue to pass (backward compatible —
Some("type")works identically to current"type")
Part 2: Completeness check
- Unit test: Node with no required relationships →
is_complete: true,missing_relationships: [] - Unit test: Node with required relationship that exists →
is_complete: true - Unit test: Node with required relationship that is missing →
is_complete: false, missing list populated - Unit test: Node with mix of required (satisfied) and required (missing) → correct missing list
- Unit test: Node with
required: None(unset) relationships are treated as not required - Unit test: Node type with no schema at all →
is_complete: true(no requirements to violate) - Integration test: MCP
check_node_completenesstool returns correct JSON structure
Notes
- Backward compatibility: Existing schemas with
target_typeas a string will deserialize intoSome(string)— no migration needed. Serde handles this automatically sinceOption<String>accepts both"person"(→Some("person")) and absence/null (→None). - Edge table naming: When
target_typeisNone, auto-computed edge table names become{source}_{name}instead of{source}_{name}_{target}. If a user later adds atarget_typeconstraint, they should explicitly setedge_tableto avoid a naming change. - Completeness is read-only:
check_node_completenessis a query, not a gate. It does NOT block node creation or updates. It's an introspection tool for workflows and UI to surface incomplete state. - Performance: The completeness check does 1 query per required relationship. For schemas with many required relationships, this could be optimized into a single query in the future, but the simple approach is correct first.
Activity
Fix: Make target_type optional on SchemaRelationship and add check_no…
Make target_type optional on SchemaRelationship and add node complete…
Make target_type optional on SchemaRelationship and add node complete…
Address review: add --console-* tokens, drop the modal shadow
Replace hardcoded status colors and phantom CSS variables with design…