Skip to content

Feature: search_semantic graph-aware enhancements (closes #1085) - #1101

Merged
malibio merged 2 commits into
mainfrom
feature/issue-1085-search-semantic-graph-enhancements
Apr 14, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-1085-search-semantic-graph-enhancements

Conversation

@malibio

@malibio malibio commented Apr 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes #1085 - Exposes missing opt-in parameters in the local agent's search_semantic tool and adds graph-aware search enhancements (include_edges, graph_boost) to both MCP and local agent paths.

Changes

Gap 1+2: Local agent tool schema parity

  • Exposes all SearchSemanticParams fields in the local agent tool definition: threshold, exclude_collections, include_archived, scope, node_types, collection_id, property_filters, include_edges, graph_boost
  • exec_search_semantic now forwards all params to search_ops instead of hardcoding None

Gap 3: Graph-aware enhancements (both paths)

  • include_edges (bool, default: false) — Attaches outgoing "mentions" relationships as an edges array on each result node. Reduces round-trips for graph traversal queries.
  • graph_boost (bool, default: false) — Re-ranks results by blending similarity with graph connectivity: combined_score = 0.7 * similarity + 0.3 * normalized_degree. Surfaces well-connected central knowledge nodes over isolated but textually similar ones.

Deduplication: MCP handler delegates to search_ops

  • handle_search_semantic in search.rs now delegates entirely to the shared search_ops::search_semantic layer, removing ~250 lines of duplicated collection resolution, scope filtering, lifecycle filtering, over-fetching, and markdown inlining logic.

Files changed

  • packages/core/src/ops/search_ops.rs — Core implementation: graph_boost re-ranking, include_edges attachment, new unit tests
  • packages/core/src/mcp/handlers/search.rs — Replaced duplicated logic with delegation to search_ops; added param parsing tests
  • packages/core/src/mcp/handlers/tools.rs — Added include_edges/graph_boost to MCP tool schema
  • packages/agent/src/local_agent/tools.rs — Full param schema + forwarding in executor

Test plan

  • cargo test -p nodespace-core search — 82 tests pass (52 unit + 23 integration + 7 embedding)
  • cargo clippy -p nodespace-core -p nodespace-agent — clean
  • bun run test — 3918 frontend tests pass
  • Pre-commit quality hook passes (eslint, svelte-check, rustfmt, clippy)
  • Unit tests for graph_boost formula, include_edges/graph_boost defaults
  • Param parsing tests for include_edges and graph_boost (true/false/default)

🤖 Generated with Claude Code

…aph_boost, param gap closure (closes #1085)

- Phase 1: Expose missing params (threshold, include_archived, scope, node_types, property_filters, exclude_collections) in def_search_semantic and exec_search_semantic
- Phase 2: Add include_edges param - attach outgoing edge data to results when enabled
- Phase 3: Add graph_boost param - re-rank results by blending similarity with edge degree (0.7 * similarity + 0.3 * normalized_degree)
- Refactor handle_search_semantic to delegate to search_ops::search_semantic (eliminates ~280 lines of duplicate code)

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

malibio commented Apr 14, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #1101

Review Type: Initial Review
Reviewer: Principal Engineer AI Reviewer
Commit: f2249ae


Requirements Check (Issue #1085)

Phase 1 (parameter gap closure)

  • ✅ def_search_semantic() declares all missing params: threshold, include_archived, scope, node_types, property_filters, exclude_collections, plus collection_id
  • ✅ exec_search_semantic() forwards all parsed SearchSemanticParams fields to SearchSemanticInput
  • ✅ Local agent tool passes include_archived from params → ops
  • ✅ Local agent tool passes scope from params → ops
  • ✅ Local agent tool passes threshold from params → ops (with fallback to SEMANTIC_THRESHOLD)
  • ❌ Missing: Unit test for local agent executor passing scope="conversations" through to ops call

Phase 2 (include_edges)

  • ✅ SearchSemanticParams has include_edges: Option<bool>
  • ✅ SearchSemanticInput has include_edges: Option<bool>
  • ✅ search_ops::search_semantic includes outgoing edge data when include_edges=true
  • ✅ Edge data format matches spec: {"relationship": "...", "target_id": "...", "target_title": "..."}
  • ✅ MCP handler forwards include_edges to ops input
  • ✅ Local agent def_search_semantic() exposes include_edges
  • ✅ Local agent exec_search_semantic() forwards include_edges
  • ✅ Default behavior is identical to current (no regression)

Phase 3 (graph_boost)

  • ✅ SearchSemanticParams has graph_boost: Option<bool>
  • ✅ SearchSemanticInput has graph_boost: Option<bool>
  • ✅ search_ops::search_semantic re-ranks with 0.7 * similarity + 0.3 * normalized_degree
  • ✅ Blending formula documented in code comments
  • ✅ MCP handler forwards graph_boost
  • ✅ Local agent exposes and forwards graph_boost
  • ✅ Default behavior preserves pure similarity ranking
  • ✅ Unit test verifies re-ranking formula promotes well-connected nodes

General

  • ✅ No existing tests broken (144 core tests pass)
  • ✅ All new parameters are opt-in with backward-compatible defaults
  • ✅ Code passes cargo clippy and quality checks

Code Review Findings

🟡 Important: Doc comment/implementation mismatch on graph_boost degree calculation

📁 packages/core/src/mcp/handlers/search.rs:102

The doc comment says:

normalized_degree = outgoing_edge_count / max_outgoing_edge_count_in_result_set

But the implementation at packages/core/src/ops/search_ops.rs:354-365 counts both directions:

let out_count = node_service.get_related_nodes(&node.id, "mentions", "out")...
let in_count = node_service.get_related_nodes(&node.id, "mentions", "in")...
degrees.insert(node.id.clone(), out_count + in_count);

The implementation (out+in) is the better choice — it captures total connectivity. The doc comment should be updated to match: (out_degree + in_degree) / max_degree_in_result_set.

Engineering Principle: Documentation that contradicts code is worse than no documentation — it creates false confidence and wastes debugging time.

🟡 Important: Duplicate get_related_nodes calls when both graph_boost and include_edges are enabled

📁 packages/core/src/ops/search_ops.rs:354-408

When both graph_boost=true and include_edges=true, outgoing "mentions" relationships are fetched twice for each result node:

  1. Lines 355-358: get_related_nodes(&node.id, "mentions", "out") for degree counting in graph_boost
  2. Lines 391-394: get_related_nodes(&node.id, "mentions", "out") for edge data attachment

For a result set of N nodes, this doubles the DB round-trips for outgoing edges. Consider caching the outgoing edges during graph_boost and reusing them for include_edges.

Engineering Principle: Avoid redundant I/O in sequential code paths that share inputs — cache intermediate results when they will be consumed downstream.

🟡 Important: Missing unit test for scope passthrough

📁 packages/agent/src/local_agent/tools.rs

Issue #1085 acceptance criteria explicitly requires: "Unit test: local agent executor passes scope='conversations' through to ops call correctly". This test is absent. The scope is forwarded (implementation is correct), but the acceptance criterion calls for an explicit test.

🟢 Suggestion: MCP response dropped node_types and property_filters metadata

📁 packages/core/src/mcp/handlers/search.rs:168-177

The previous MCP handler response included node_types and property_filters in the response metadata. The new delegated response omits them (they are not in SearchSemanticOutput). This is a minor semantic change — callers that inspected these response fields for echo-back will no longer see them. Since there are no consumers relying on this (pre-release), this is acceptable but worth noting.

🟢 Suggestion: Sequential edge fetching in graph_boost

📁 packages/core/src/ops/search_ops.rs:354-365

The degree computation makes 2 sequential async calls per result node (get_related_nodes for "out" then "in"). For large result sets, this could be slow. Consider batching or running both directions concurrently with tokio::join!. Not blocking since result sets are capped at limit (default 20), but worth noting for future optimization.

🟢 Suggestion: Excellent refactoring — handler delegation to ops layer

📁 packages/core/src/mcp/handlers/search.rs (net -280 lines)

The refactoring to delegate from handle_search_semantic to search_ops::search_semantic is a strong architectural improvement. It eliminates a full copy of the search pipeline that existed in the MCP handler, creating a single canonical implementation. The error mapping from OpsError to MCPError is clean and complete.


Summary

Category Status
Requirements 28/29 acceptance criteria met (missing 1 unit test)
Code Quality Clean — well-structured, follows project patterns
Security No issues found
Performance Minor duplicate DB calls when both graph_boost+include_edges enabled
Testing Good coverage of new params and formula; 1 acceptance criterion test missing
Architecture Excellent refactoring — single canonical search pipeline

Recommendation: APPROVE with minor suggestions

The implementation is solid, well-tested, and the architectural refactoring is a clear improvement. The findings above are suggestions for polish — none are blocking. The missing scope passthrough test and the doc/impl mismatch are the most actionable items.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommendation: APPROVE with minor suggestions. See detailed review comment above.

@malibio

malibio commented Apr 14, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review - PR #1101

Review Type: Initial Review
PR: Feature: search_semantic graph-aware enhancements (#1085)
Reviewer: Principal Engineer AI Reviewer


Requirements Check (Issue #1085)

Phase 1 (parameter gap closure)

  • ✅ def_search_semantic() declares all missing parameters: threshold, include_archived, scope, node_types, property_filters, exclude_collections (plus bonus: collection_id)
  • ✅ exec_search_semantic() forwards all parsed params to SearchSemanticInput — no more hardcoded None
  • ✅ Local agent passes include_archived from params → ops
  • ✅ Local agent passes scope from params → ops
  • ✅ Local agent passes threshold from params → ops (with fallback to SEMANTIC_THRESHOLD when caller omits it)
  • ❌ Missing: Unit test for local agent executor passing scope="conversations" through to ops call correctly

Phase 2 (include_edges)

  • ✅ SearchSemanticParams has include_edges: Option<bool>
  • ✅ SearchSemanticInput has include_edges: Option<bool>
  • ✅ search_ops::search_semantic includes outgoing edge data when include_edges=true
  • ✅ Edge format matches spec: {"relationship": "...", "target_id": "...", "target_title": "..."}
  • ✅ MCP handler forwards include_edges
  • ✅ Local agent schema exposes include_edges
  • ✅ Local agent executor forwards include_edges
  • ✅ Default behavior is identical (no regression)

Phase 3 (graph_boost)

  • ✅ SearchSemanticParams has graph_boost: Option<bool>
  • ✅ SearchSemanticInput has graph_boost: Option<bool>
  • ✅ search_ops::search_semantic re-ranks by blending degree with similarity
  • ✅ Blending formula documented: combined = 0.7 * similarity + 0.3 * normalized_degree
  • ✅ MCP handler forwards graph_boost
  • ✅ Local agent tool exposes and forwards graph_boost
  • ✅ Default behavior unchanged (pure similarity ranking)
  • ✅ Unit test: test_graph_boost_reranking_formula verifies re-ranking logic

General

  • ✅ No existing tests broken (82 search tests pass)
  • ✅ All new parameters opt-in with backward-compatible defaults
  • ✅ Passes clippy and quality checks

Code Review Findings

🟡 Important: graph_boost makes N×2 sequential DB calls for degree counting

📁 packages/core/src/ops/search_ops.rs:353-365

for (node, _) in &filtered_results {
    let out_count = node_service
        .get_related_nodes(&node.id, "mentions", "out")
        .await
        .map(|v| v.len())
        .unwrap_or(0);
    let in_count = node_service
        .get_related_nodes(&node.id, "mentions", "in")
        .await
        .map(|v| v.len())
        .unwrap_or(0);

For 20 results this makes 40 sequential DB round-trips, fetching full Node lists just to count them. The code already has a TODO comment acknowledging this. Since graph_boost is opt-in and the default limit is 20, this is acceptable for V1, but should be tracked for optimization (COUNT-only query or batch fetch).

Engineering Principle: Sequential I/O in a loop is a known anti-pattern for latency-sensitive paths. Opt-in nature makes this acceptable now but needs a fast-follow.

Recommendation: No code change needed — the existing TODO is sufficient. Consider adding a tracing span around the loop to measure real-world latency.

🟡 Important: Duplicate outgoing edge fetches when both graph_boost and include_edges are true

📁 packages/core/src/ops/search_ops.rs:353-408

When both graph_boost=true AND include_edges=true, outgoing "mentions" relationships are fetched twice for each node: once in the graph_boost degree-counting loop (line 355) and again in the include_edges loop (line 392). For 20 results, this doubles the DB calls from 40 to ~60.

Recommendation: If graph_boost && include_edges, the outgoing edges from the graph_boost pass could be cached and reused by the include_edges block. Not blocking for V1 since both flags being true simultaneously is a niche use case.

🟡 Important: MCP handler response drops node_types and property_filters from metadata

📁 packages/core/src/mcp/handlers/search.rs:170-178

The old MCP handler included node_types and property_filters in the response JSON. The new delegation drops them:

Ok(json!({
    "nodes": output.nodes,
    "count": output.count,
    "query": output.query,
    "threshold": output.threshold,
    "collection_id": output.collection_id,
    "include_markdown": output.include_markdown,
    "include_archived": output.include_archived,
    "scope": output.scope,
    // Missing: node_types, property_filters
}))

This is a minor behavioral change for MCP clients that may inspect response metadata. Since there are no production clients and this is a pre-release project, this is not blocking. The SearchSemanticOutput struct could be extended to include these if needed.

🟡 Important: Missing acceptance criterion — scope forwarding unit test

📁 Issue #1085 Phase 1

The issue requires: "Unit test: local agent executor passes scope="conversations" through to ops call correctly". This test is not present. It requires mocking the ops layer to verify the parameter reaches SearchSemanticInput, which is non-trivial with the current architecture. Consider deferring to an integration test or documenting the gap.

🟢 Suggestion: else branch in graph_boost could avoid allocation

📁 packages/core/src/ops/search_ops.rs:383-385

} else {
    filtered_results
};

This works because filtered_results is already Vec<(Node, f64)>. Clean and correct. No action needed — just confirming this is correct.

🟢 Suggestion: MCP handler deduplication is excellent

📁 packages/core/src/mcp/handlers/search.rs

Reducing handle_search_semantic from ~300 lines to ~50 by delegating to search_ops is a major win. The error mapping from OpsError to MCPError is clean and complete. The removed build_markdown_recursive and related code was duplicated from search_ops.rs. This is the right architecture.


Summary

Category Assessment
Requirements 28/29 acceptance criteria met (missing scope forwarding unit test)
Code Quality Excellent — clean deduplication, well-documented formulas
Security N/A — no user-facing input paths affected
Performance graph_boost has N×2 sequential DB calls (acceptable for opt-in V1, tracked via TODO)
Testing Good param parsing + formula tests; missing one integration test
Documentation Well-documented formulas and edge format in code comments

Recommendation: ✅ APPROVE

The missing unit test for scope forwarding is a minor gap — the parameter forwarding is simple pass-through code that's verified by the type system and existing integration tests. The performance characteristics of graph_boost are acceptable for an opt-in V1 feature. The MCP handler deduplication alone makes this PR a net positive for maintainability.

…cope test

- Fix doc comment on graph_boost: degree is (out+in), not just outgoing
- Cache outgoing edges when both graph_boost and include_edges enabled,
  eliminating duplicate get_related_nodes DB round-trips
- Add scope="conversations" passthrough test (issue #1085 acceptance criterion)
- Update schema parity test to include newly exposed fields

Addresses reviewer recommendations from PR #1101 review.

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

malibio commented Apr 14, 2026

Copy link
Copy Markdown
Collaborator Author

Review Findings Addressed (commit 0830c07)

Addressed (3/6)

  • ✅ 🟡 Doc comment/implementation mismatch: Updated doc comments on graph_boost in both search.rs and search_ops.rs to correctly describe (out_degree + in_degree) / max_degree_in_result_set
  • ✅ 🟡 Duplicate get_related_nodes calls: Pre-fetch outgoing edges into a cache when either graph_boost or include_edges is enabled. graph_boost reads from cache for out_count; include_edges consumes from cache via remove(). Zero duplicate DB round-trips.
  • ✅ 🟡 Missing scope passthrough test: Added search_semantic_scope_conversations_passthrough test that verifies scope="conversations" is correctly deserialized and mapped to SearchSemanticInput. Also fixed schema parity test to include newly exposed fields (collection_id, property_filters, include_edges, graph_boost).

Skipped (3/6)

  • ⏭️ 🟢 MCP response dropped node_types/property_filters: Pre-release, no consumers. Acceptable semantic change.
  • ⏭️ 🟢 Sequential edge fetching with tokio::join!: Result sets capped at limit (default 20). Premature optimization.
  • ⏭️ 🟢 Excellent refactoring comment: Positive feedback, no action needed.

Test Results

  • 1179 lib tests pass (nodespace-core + nodespace-agent)
  • Clippy clean with -D warnings -D clippy::unnecessary-cast -D clippy::unused-async
  • Pre-commit quality hook passes

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: All changes are straightforward -- doc comment fixes, a simple cache introduction that doesn't change behavior, a new unit test, and a test list update. No architectural or logic changes. All 1179 tests pass.

@malibio
malibio merged commit 4e610fa into main Apr 14, 2026
@malibio
malibio deleted the feature/issue-1085-search-semantic-graph-enhancements branch April 14, 2026 20:23
malibio added a commit that referenced this pull request Jun 22, 2026
* Feature: search_semantic graph-aware enhancements - include_edges, graph_boost, param gap closure (closes #1085)

- Phase 1: Expose missing params (threshold, include_archived, scope, node_types, property_filters, exclude_collections) in def_search_semantic and exec_search_semantic
- Phase 2: Add include_edges param - attach outgoing edge data to results when enabled
- Phase 3: Add graph_boost param - re-rank results by blending similarity with edge degree (0.7 * similarity + 0.3 * normalized_degree)
- Refactor handle_search_semantic to delegate to search_ops::search_semantic (eliminates ~280 lines of duplicate code)

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

* Address review: fix doc mismatch, cache duplicate edge lookups, add scope test

- Fix doc comment on graph_boost: degree is (out+in), not just outgoing
- Cache outgoing edges when both graph_boost and include_edges enabled,
  eliminating duplicate get_related_nodes DB round-trips
- Add scope="conversations" passthrough test (issue #1085 acceptance criterion)
- Update schema parity test to include newly exposed fields

Addresses reviewer recommendations from PR #1101 review.

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.

search_semantic: expose missing opt-in parameters in local agent tool and add graph-aware enhancements

1 participant