Repository navigation
Migrate Tauri command handlers to gRPC proxy (closes #1113) - #1147
Conversation
Code Review SummaryThis PR completes Phase 5 of the gRPC proxy migration (issue #1113), rewriting all 33 One functional bug was found in the FindingsCritical Issues[Critical/Blocker]
// Current (broken):
status: update.status.map(|s| serde_json::to_string(&s).unwrap_or_default()),
// ...
value: serde_json::to_string(&p).unwrap_or_default(),
serde_json::from_value::<TaskStatus>(serde_json::Value::String(s.clone()))
The fix is straightforward: use the // Fixed:
status: update.status.map(|s| s.as_str().to_string()),
// ...
value: p.as_str().to_string(),On the server, Suggested Improvements[Improvement]
// nodes.rs: change visibility
pub(crate) fn proto_node_data_to_node(nd: NodeData) -> Result<Node, CommandError> { ... }// collections.rs and schemas.rs: replace the copy with
use super::nodes::proto_node_data_to_node;This avoids three divergence points for timestamp-parsing and [Improvement] Timestamp parse failures silently substitute
let created_at = DateTime::parse_from_rfc3339(&nd.created_at)
.map(|dt| dt.with_timezone(&Utc))
.unwrap_or_else(|_| Utc::now());If the gRPC server ever sends a malformed timestamp, [Improvement]
Err(s) if s.code() == tonic::Code::NotFound => Err(CommandError { code: "SCHEMA_NOT_FOUND", ... }),
Err(s) => Err(status_to_command_error(s)),
[Improvement]
[Improvement] Lines 108–121: when [Improvement] Missing unit tests for new conversion helpers
NitpicksNit: Nit: Nit: Nit: Acceptance Criteria Status
|
Address-Review Summary✅ Addressed (5 recommendations)🔴 Critical — Fixed:
🟡 Important — Fixed:
🟡 Important — Fixed: Silent
🟡 Important — Fixed:
🟢 Suggestion — Fixed:
⏭️ Skipped (2 recommendations)Unit tests for conversion helpers: Out of scope for this migration PR. The conversion functions are pure utility helpers that support the gRPC migration; a dedicated test issue would be the right venue.
Build clean: |
Re-Review: PR #1147 — gRPC Proxy Migration (Issue #1113)Commit reviewed: `c9f6c55d` — Address review: fix task encoding bug and consolidate conversion helpers All five recommendations from the initial review have been correctly addressed. No new issues introduced. Verification of Previous Findings1. [Critical] `task_update_to_proto` double-encoding — FIXED`packages/desktop-app/src-tauri/src/commands/nodes.rs` The fix is semantically correct. `s.as_str().to_string()` produces the raw variant string (e.g. `"open"`, `"in_progress"`) that the daemon's parse path expects. Both `TaskStatus` and `TaskPriority` have verified `as_str()` implementations tested in `task_node_test.rs` (lines 332-439), confirming the mapping is stable. The `OptionalStringClear` arm for `TaskPriority` was also fixed in the same change. 2. [Improvement] `proto_node_data_to_node` duplicated across 3 files — FIXEDThe function is correctly promoted to `pub(crate)` in `nodes.rs` and the verbatim copies have been deleted from `collections.rs` and `schemas.rs`. Both files now import via `super::nodes::proto_node_data_to_node`. The stale `use chrono::{DateTime, Utc}` and `NodeData` imports that existed only to support the local copy were also cleaned up — no dead imports remain. 3. [Improvement] Timestamp parse failures silently substituting `Utc::now()` — FIXEDBoth `created_at` and `modified_at` paths now use `.map_err(|e| CommandError { code: "PARSE_ERROR", ... })?`. The error messages include the offending timestamp string in `details`, which is useful for diagnostics. The fix applies through the single shared function, so all three call-sites (nodes.rs, collections.rs, schemas.rs) benefit automatically. 4. [Improvement] `validate_node_type` missing `FailedPrecondition` mapping — FIXEDThe guard pattern now reads: ```rust This correctly maps both `NotFound` (schema absent) and `FailedPrecondition` (node exists but wrong type) to `SCHEMA_NOT_FOUND`, with the catch-all `Err(s) => Err(status_to_command_error(s))` still in place for other status codes. 5. [Suggestion] `Vec::with_capacity` in `get_all_collections` — FIXEDPre-allocation is restored by materializing the response before iteration: ```rust This is correct and idiomatic. New Issues IntroducedNone. The address-review commit is tightly scoped: it modifies only the three files that were already part of the PR (`nodes.rs`, `collections.rs`, `schemas.rs`) and touches only the specific code paths called out in the review. The unused import cleanup in `schemas.rs` (`chrono`, `Node`, `NodeData`) is a welcome side-effect of removing the duplicated function. Acceptance Criteria Status
Approved. Ready to merge. |
malibio
left a comment
There was a problem hiding this comment.
Re-review complete: all 5 recommendations correctly addressed. No new issues. Approved — ready to merge.
Adds an in-process gRPC server (nodespace-daemon) to the Tauri desktop app and rewrites 33 #[tauri::command] handlers to proxy through tonic instead of calling packages/core directly. Extended NodeService with the full set of RPCs needed by the Tauri command layer: all CRUD, mention, hierarchy, task-update, schema (read-only), and collection operations. Introduced tri-state OptionalStringClear / OptionalTimestampClear wrappers to encode Option<Option<T>> fields for TaskNodeUpdate over the wire. - Implemented all 28 proto RPCs in NodeServiceImpl (node_service.rs): create/get/update/delete node, children tree, mentions, move/reorder, update_task_node, get_all_schemas, get_schema_definition, and the full collection surface (14 RPCs). WatchNodes and Chat remain stubbed (tracked in #1114). - service_error_to_status bridges NodeServiceError → OpsError → tonic::Status consistently across all handlers. GrpcClient spawns NodeServiceImpl on a loopback port chosen by the OS (127.0.0.1:0, no collision with a standalone nodespaced on [::1]:50051). Reuses the same Arc<NodeService> AppServices already owns — no second DB open, no RocksDB lock contention. Channel is Arc-backed; client() returns a cheap clone per call. Registered via app.manage() after init_services(). nodes.rs (19 handlers), collections.rs (12 handlers), schemas.rs (2 handlers): - All AppServices / NodeService / CollectionService deps removed. - proto_node_data_to_node (pub(crate)) reconstructs core::Node from wire NodeData (parses RFC3339 timestamps; returns PARSE_ERROR on malformed input rather than silently substituting Utc::now()). - status_to_command_error maps tonic::Status codes to existing CommandError codes (NotFound → NODE_NOT_FOUND, Aborted → VERSION_CONFLICT, etc.). - validate_node_type uses GetSchemaDefinition RPC; maps both NotFound and FailedPrecondition to SCHEMA_NOT_FOUND. - task_update_to_proto uses TaskStatus::as_str() / TaskPriority::as_str() (not serde_json::to_string, which would double-quote the values). - All existing Tauri command return types preserved — frontend unchanged. Added nodespace-daemon, tonic, prost to workspace Cargo.toml; chrono to daemon Cargo.toml; daemon + tonic + prost to desktop-app Cargo.toml. cargo clippy -p nodespace-app — zero warnings. Frontend test suite: 128 files / 3918 tests — no regressions. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
c9f6c55 to
5fe81f9
Compare
Implements 7 of 12 suggestions from the PR #1148 pragmatic review. Each change is small and self-contained; nothing affects the overall architecture or behavior beyond what the review identified. ## Addressed ### 1. LaunchSessionResponse.created_at uses authoritative started_at Previously the handler took a fresh `Utc::now()` after `manager.launch()` returned. The session's own `started_at` is set inside `spawn_in_pty` before the reader/watcher tasks are wired, so the wire-level timestamp drifted a few milliseconds behind it — and ListSessions reported the earlier (correct) one. Now `launch_session` does one `manager.get()` after launch and uses `session.started_at.timestamp()`. Single source of truth between LaunchSession and ListSessions. ### 2. Widen proto numeric fields to avoid silent casts - `WriteInputResponse.bytes_written`: int32 → int64. `usize as i32` was wraparound on 2 GiB+ payloads — unlikely for a PTY but the contract is the contract. - `ListSessionsResponse.count`: int32 → uint32. Saturating cast via `u32::try_from(...).unwrap_or(u32::MAX)` keeps the count monotonic for clients that diff snapshots. Greenfield-correct per CLAUDE.md (single consumer, no migration cost). ### 3. Hold session Arc through launch+resize `launch_session` now does one `manager.get(&id)` after launch and holds the resulting `Arc<PtySession>` for both `started_at` and the optional initial resize. Eliminates the redundant lock acquisition AND closes a small race where the spawned child could exit and the auto-prune watcher remove the entry between launch() and apply_resize(), returning NotFound for a session we just created. The old `apply_resize(manager, id, ...)` helper is replaced by `resize_session(&Arc<PtySession>, ...)`; `resize_terminal` does its own manager lookup since it doesn't have an Arc from elsewhere. ### 4. StreamOutput lag visibility (lowest-risk variant) Kept the current swallow-and-warn behavior — surfacing dropped bytes inline via a sentinel chunk or a session metric is a wider design change that should land in its own PR. Added a `debug_assert!(skipped > 0)` to catch future bugs that produce zero-byte lag events, and a TODO note pointing at the review discussion so the trade-off is visible to future maintainers. ### 5. ResizeTerminal rejects zero dimensions Unlike LaunchSession (0 = use default), ResizeTerminal has no default semantic — its job is "apply exactly this size". Now returns `InvalidArgument` if either axis is zero, rather than passing through to `portable_pty` with `PtySize { rows: 0, cols: 0, .. }` which is platform-dependent. Added integration test `resize_terminal_rejects_ zero_dimensions` pinning the contract across (0, N), (N, 0), (0, 0). Proto comment documents the [1, 65535] valid range. ### Nit: Remove snake_case agent_type acceptance Per CLAUDE.md's no-backwards-compat directive: the previous `raw.replace('_', "-")` was dead weight for a greenfield API with zero callers. Kebab-case is the only accepted form now. Added `parse_agent_type_rejects_snake_case` test pinning the new rejection so a future refactor cannot silently restore the dual-accept path. ### 6. Document testing-feature footgun in agent crate Expanded the `[features] testing = []` comment in `packages/agent/Cargo.toml` to explain Cargo's feature-unification behavior across dep/dev-dep within a single downstream package, and the rule that test-only stubs behind this feature must only widen visibility — never change runtime behavior, swap implementations, or skip safety checks. Test-only mutating stubs belong in test-only modules in the downstream crate, not behind this flag. ## Skipped, with reasoning - **#7 Daemon test for caller-supplied UUID path through CreateNode**: Reviewer explicitly marked this "out of scope for this PR" and the contract is already exercised in nodespace-core per #1147. Worth a follow-up issue if the daemon adapter ever diverges from a simple pass-through. - **Nit: `agent_type_to_string` debug_assert**: The dead-code fallback to `format!("{agent_type:?}")` is genuinely defensive — it makes the function infallible if `AgentType` ever gains a non-serde variant in the future. A `debug_assert!(false)` would catch that in test, but would also panic in production for a problem that's recoverable. The current shape is the right trade-off. - **Nit: connect-retry loop `last_err` Option indirection**: Purely stylistic and the existing shape already does the right thing (`panic!` formats `Some(e)` fine). Not worth a churn commit. - **Nit: `count: count` field-init shorthand**: Clippy didn't flag and the explicit form is consistent with other struct literals in the same file. No-op. - **Nit: `embedding_service = None` duplication in main.rs**: Will naturally resolve when the embedding service is wired by the follow- up issue (currently both arms become `Some(embedding_service.clone())`). Introducing a binding now would just need un-introducing later. ## Verified - `cargo build --bin nodespaced`: clean - `cargo test -p nodespace-daemon`: 26 passed (7 unit + 9 agent-session integration + 10 grpc-round-trip; added zero-reject + snake-case rejection tests) - `cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async`: clean - `bun run quality:fix`: clean (eslint + svelte-check + rustfmt + clippy across the full workspace) - `bun run test`: 3918/3918 across 128 files (matches baseline) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* Implement AgentSessionService gRPC handler (closes #1119) Wire the PTY engine from #1118 into the nodespaced gRPC server. The new AgentSessionService exposes the six PTY operations — Launch, StreamOutput (server-streaming), WriteInput, ResizeTerminal, TerminateSession, ListSessions — so the Tauri UI and CLI can drive agent sessions over loopback gRPC. ## Layout - packages/daemon/src/services/agent_session_service.rs (new) — tonic trait impl, parses kebab-case agent_type into AgentType, adapts each RPC into the matching PtySessionManager / PtySession call, returns status codes per failure mode (InvalidArgument for bad UUID / unknown agent_type, NotFound for missing sessions, Internal for PTY errors). - packages/daemon/src/services/mod.rs — re-export AgentSessionHandler. - packages/daemon/src/main.rs — refactor build_node_service → build_services so both headless and tray loops register NodeServiceServer *and* AgentSessionServiceServer. - packages/daemon/Cargo.toml — add nodespace-agent (path dep) plus uuid for ID parsing. ## Proto alignment packages/daemon/proto/agent_session_service.proto: the original message shape (raw command/args/cwd/env, separate stdout/stderr StreamKind, optional exit code on SessionInfo) predates the PtySessionManager API that landed in #1118 and would have required either (a) a parallel "raw-command" launch path that bypasses the agent catalog + GraphContextAssembler, or (b) a translation layer that maps strings back into the AgentType enum. Both are pure technical debt for a greenfield daemon. This commit rewrites the proto to match the engine: - LaunchSessionRequest is {agent_type, prompt, cols, rows} — the fields the issue body specifies and PtySessionManager::launch actually accepts. - OutputChunk drops StreamKind (PTYs merge stdout/stderr at the kernel level, there is no way to split them at this layer). - SessionInfo trims to {session_id, agent_type, started_at} matching the existing SessionMetadata struct. Status/exit-code fields would have required new bookkeeping in the manager for no consumer in this PR. - ResizeResponse / ListSessionsRequest become empty — the echoed cols/rows and status_filter were unused by every caller. Nothing else in the workspace consumed the old proto (only the daemon's lib.rs re-exported SessionInfo and no field was read), so the rewrite is safe. ## StreamOutput Subscribes to the session's broadcast::Receiver<OutputChunk> and forwards chunks as proto OutputChunk messages. On RecvError::Lagged the handler logs and continues — losing a render frame is preferable to tearing the stream down. On RecvError::Closed the stream ends naturally. Client disconnect drops only the subscriber, never the session (acceptance criterion #8); integration test stream_output_disconnect_does_not_kill_session pins that contract. ## Test helper visibility PtySession::launch_for_test moved from pub(crate) + #[cfg(test)] to pub + #[cfg(any(test, feature = "testing"))] so the daemon's integration tests can spawn shell utilities (echo, cat, sleep) without a real agent binary on PATH. The "testing" feature already exists in the agent crate for the same reason (ollama_integration tests). Same treatment for session_dir_path. ## Tests packages/daemon/tests/agent_session_grpc.rs (new) — 8 integration tests against the in-process tonic server: - stream_output_delivers_echo_hello (acceptance criterion #9) - stream_output_disconnect_does_not_kill_session (criterion #8) - write_input_is_echoed_back_through_stream (round-trip through cat) - list_sessions_reflects_manager_state - resize_terminal_succeeds_for_active_session - terminate_unknown_session_reports_was_not_running - unknown_session_returns_not_found (both StreamOutput and WriteInput) - invalid_session_id_returns_invalid_argument Plus 4 unit tests in agent_session_service.rs::tests covering the kebab/snake_case agent_type parsing, round-trip, UUID rejection. LaunchSession itself is exercised indirectly: the production launch path resolves the agent binary on PATH (which CI does not have), so tests seed the manager via PtySession::launch_for_test + manager.insert and drive every other RPC through the full gRPC stack. ## Lint note parse_session_id and parse_agent_type return Result<T, String> rather than Result<T, Status>. tonic::Status is ~176 bytes; Uuid is 16 and AgentType is 1, so Result<T, Status> trips clippy::result_large_err. The call sites lift the String into Status::invalid_argument in one line — keeps the parsers status-agnostic and the lint clean without any allow attribute. ## Drive-by fix from rebase PR #1147 added id + insert_after_node_id to CreateNodeRequest but did not update existing call sites in packages/daemon/tests/grpc_round_trip.rs or packages/cli/{src/commands/node.rs, tests/cli_integration.rs}. The existing rust:test script only covers nodespace-core --lib, so the breakage didn't surface in CI. Added the two missing fields (both defaulting to String::new()) so the daemon test binary and cli build compile on top of main. ## Verified - cargo build --bin nodespaced: success - cargo test -p nodespace-daemon: 24 passed (6 unit + 8 agent-session integration + 10 grpc-round-trip) - cargo test -p nodespace-agent --lib --features testing: 250 passed - bun run quality:fix: clean (eslint + svelte-check + rustfmt + clippy) - bun run test: 3918/3918 passed across 128 files (matches baseline) - bun run test:all: success (exit 0) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address review: tighten contracts, drop backwards-compat Implements 7 of 12 suggestions from the PR #1148 pragmatic review. Each change is small and self-contained; nothing affects the overall architecture or behavior beyond what the review identified. ## Addressed ### 1. LaunchSessionResponse.created_at uses authoritative started_at Previously the handler took a fresh `Utc::now()` after `manager.launch()` returned. The session's own `started_at` is set inside `spawn_in_pty` before the reader/watcher tasks are wired, so the wire-level timestamp drifted a few milliseconds behind it — and ListSessions reported the earlier (correct) one. Now `launch_session` does one `manager.get()` after launch and uses `session.started_at.timestamp()`. Single source of truth between LaunchSession and ListSessions. ### 2. Widen proto numeric fields to avoid silent casts - `WriteInputResponse.bytes_written`: int32 → int64. `usize as i32` was wraparound on 2 GiB+ payloads — unlikely for a PTY but the contract is the contract. - `ListSessionsResponse.count`: int32 → uint32. Saturating cast via `u32::try_from(...).unwrap_or(u32::MAX)` keeps the count monotonic for clients that diff snapshots. Greenfield-correct per CLAUDE.md (single consumer, no migration cost). ### 3. Hold session Arc through launch+resize `launch_session` now does one `manager.get(&id)` after launch and holds the resulting `Arc<PtySession>` for both `started_at` and the optional initial resize. Eliminates the redundant lock acquisition AND closes a small race where the spawned child could exit and the auto-prune watcher remove the entry between launch() and apply_resize(), returning NotFound for a session we just created. The old `apply_resize(manager, id, ...)` helper is replaced by `resize_session(&Arc<PtySession>, ...)`; `resize_terminal` does its own manager lookup since it doesn't have an Arc from elsewhere. ### 4. StreamOutput lag visibility (lowest-risk variant) Kept the current swallow-and-warn behavior — surfacing dropped bytes inline via a sentinel chunk or a session metric is a wider design change that should land in its own PR. Added a `debug_assert!(skipped > 0)` to catch future bugs that produce zero-byte lag events, and a TODO note pointing at the review discussion so the trade-off is visible to future maintainers. ### 5. ResizeTerminal rejects zero dimensions Unlike LaunchSession (0 = use default), ResizeTerminal has no default semantic — its job is "apply exactly this size". Now returns `InvalidArgument` if either axis is zero, rather than passing through to `portable_pty` with `PtySize { rows: 0, cols: 0, .. }` which is platform-dependent. Added integration test `resize_terminal_rejects_ zero_dimensions` pinning the contract across (0, N), (N, 0), (0, 0). Proto comment documents the [1, 65535] valid range. ### Nit: Remove snake_case agent_type acceptance Per CLAUDE.md's no-backwards-compat directive: the previous `raw.replace('_', "-")` was dead weight for a greenfield API with zero callers. Kebab-case is the only accepted form now. Added `parse_agent_type_rejects_snake_case` test pinning the new rejection so a future refactor cannot silently restore the dual-accept path. ### 6. Document testing-feature footgun in agent crate Expanded the `[features] testing = []` comment in `packages/agent/Cargo.toml` to explain Cargo's feature-unification behavior across dep/dev-dep within a single downstream package, and the rule that test-only stubs behind this feature must only widen visibility — never change runtime behavior, swap implementations, or skip safety checks. Test-only mutating stubs belong in test-only modules in the downstream crate, not behind this flag. ## Skipped, with reasoning - **#7 Daemon test for caller-supplied UUID path through CreateNode**: Reviewer explicitly marked this "out of scope for this PR" and the contract is already exercised in nodespace-core per #1147. Worth a follow-up issue if the daemon adapter ever diverges from a simple pass-through. - **Nit: `agent_type_to_string` debug_assert**: The dead-code fallback to `format!("{agent_type:?}")` is genuinely defensive — it makes the function infallible if `AgentType` ever gains a non-serde variant in the future. A `debug_assert!(false)` would catch that in test, but would also panic in production for a problem that's recoverable. The current shape is the right trade-off. - **Nit: connect-retry loop `last_err` Option indirection**: Purely stylistic and the existing shape already does the right thing (`panic!` formats `Some(e)` fine). Not worth a churn commit. - **Nit: `count: count` field-init shorthand**: Clippy didn't flag and the explicit form is consistent with other struct literals in the same file. No-op. - **Nit: `embedding_service = None` duplication in main.rs**: Will naturally resolve when the embedding service is wired by the follow- up issue (currently both arms become `Some(embedding_service.clone())`). Introducing a binding now would just need un-introducing later. ## Verified - `cargo build --bin nodespaced`: clean - `cargo test -p nodespace-daemon`: 26 passed (7 unit + 9 agent-session integration + 10 grpc-round-trip; added zero-reject + snake-case rejection tests) - `cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async`: clean - `bun run quality:fix`: clean (eslint + svelte-check + rustfmt + clippy across the full workspace) - `bun run test`: 3918/3918 across 128 files (matches baseline) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address re-review: surface dropped resize, deflake echo test Two small follow-ups from the re-review of 10041e3, plus a flake fix discovered while verifying. ## Addressed ### Re-review suggestion: warn-log silent resize skip in launch_session If the auto-prune watcher removes the session entry between launch() and the get() that pins the Arc for the optional initial resize, the resize silently no-op'd and the client got a successful LaunchSessionResponse with a session_id that the next RPC would reject as NotFound. Now logs at `tracing::warn!` with session_id + requested dims so the server-side trace makes the dropped resize discoverable. Kept the response semantics unchanged: the launch itself succeeded, so returning Status::failed_precondition would force every client to handle a confusing "launch succeeded but failed to resize" mid-failure. The next RPC's NotFound is a clearer signal for the (vanishingly rare) race that this branch handles. ### Re-review nit: agent_type_to_string fallback comment Updated the comment to explicitly state that the debug-format fallback is defense-in-depth, not a graceful-degradation path. AgentType is in-workspace and closed, so adding a new variant must extend parse_agent_type / agent_type_to_string together — the fallback is not a shortcut. ## Flake fix (discovered during verification) `stream_output_delivers_echo_hello` was timing-sensitive: on a fast machine the PTY reader could drain `echo hello` and broadcast the chunk before the gRPC client's StreamOutput subscriber attached. `tokio::sync::broadcast` does not replay missed messages to late subscribers (unlike `watch`), so the test would fail ~10% of runs. Changed the command from `echo hello` to `sleep 0.2 && echo hello` so the subscriber is guaranteed to attach before bytes hit the broadcast channel. Comment in the test body explains why. 5/5 passing after the change. This is a pre-existing flake in the original PR; the re-review missed it because the parallel test run masked it. Catching it now means it won't show up as intermittent CI failures later. ## Verified - cargo test -p nodespace-daemon: 26 passed (run 5x to confirm no flake) - cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async: clean - bun run quality:fix: clean 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Implements `nodespace diagnostics` and removes the corresponding Tauri command surface. Under ADR-031, diagnostic data lives in nodespaced, not the Tauri process — so a CLI subcommand is the correct surface for the intended audience (developers debugging persistence issues). CLI subcommand reports: database path, existence, size, total node count, root node count, schema count, recent node IDs. Honors --json for machine-readable output. Reuses the daemon's gRPC client (`QueryNodesSimple`, `GetAllSchemas`); the database path is resolved by a new `resolve_db_path()` helper hoisted from `main.rs` into the daemon's library surface so the CLI and daemon agree on the location without a settings RPC round-trip. Tauri side: deletes `commands/diagnostics.rs` and the two `#[tauri::command]` handlers (`get_database_diagnostics`, `test_node_persistence`). The developer-only diagnostic panel (Ctrl+Shift+D) loses the now-broken "Database" and "Persistence Test" tabs but keeps its Call Logs view, which is independent of the deleted backend commands. The corresponding `getDatabaseDiagnostics` / `testNodePersistence` helpers and their tests in `diagnostic-logger.ts` are removed; `withDiagnosticLogging` and the log buffer remain (used by `backend-adapter.ts` to wrap 18 Tauri calls). Drive-by: fix `CreateNodeRequest` literal sites in the CLI's `node create` command and the cli/daemon integration tests that #1147 left missing the new `id` and `insert_after_node_id` proto fields. Without this, `cargo build -p nodespace-cli` and `cargo test` on both test crates failed on a fresh clone of main. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
* Migrate diagnostics to nodespace CLI subcommand (closes #1139) Implements `nodespace diagnostics` and removes the corresponding Tauri command surface. Under ADR-031, diagnostic data lives in nodespaced, not the Tauri process — so a CLI subcommand is the correct surface for the intended audience (developers debugging persistence issues). CLI subcommand reports: database path, existence, size, total node count, root node count, schema count, recent node IDs. Honors --json for machine-readable output. Reuses the daemon's gRPC client (`QueryNodesSimple`, `GetAllSchemas`); the database path is resolved by a new `resolve_db_path()` helper hoisted from `main.rs` into the daemon's library surface so the CLI and daemon agree on the location without a settings RPC round-trip. Tauri side: deletes `commands/diagnostics.rs` and the two `#[tauri::command]` handlers (`get_database_diagnostics`, `test_node_persistence`). The developer-only diagnostic panel (Ctrl+Shift+D) loses the now-broken "Database" and "Persistence Test" tabs but keeps its Call Logs view, which is independent of the deleted backend commands. The corresponding `getDatabaseDiagnostics` / `testNodePersistence` helpers and their tests in `diagnostic-logger.ts` are removed; `withDiagnosticLogging` and the log buffer remain (used by `backend-adapter.ts` to wrap 18 Tauri calls). Drive-by: fix `CreateNodeRequest` literal sites in the CLI's `node create` command and the cli/daemon integration tests that #1147 left missing the new `id` and `insert_after_node_id` proto fields. Without this, `cargo build -p nodespace-cli` and `cargo test` on both test crates failed on a fresh clone of main. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * Address review: surface IO/truncation errors, sort recent IDs, add integration test Resolves the 🟡 Important and 🟢 Suggestion findings from PR #1150's review. - Sort all_nodes by created_at DESC before slicing for recent_node_ids, so the user-visible "recent" label means most-recently-created rather than first-in-iteration-order (review finding #1). - Have directory_size accumulate IO errors into the report's `errors` field instead of silently returning 0 on read_dir / file_type / metadata failures. A permissions error reporting "Database size: 0.00 B" was precisely the failure mode an operator running `nodespace diagnostics` needs to see (review finding #2). - Document the symlink-skipping behavior so a future "fix" doesn't reintroduce the loop risk that `fs::metadata` would (review finding #3). - Surface a warning when QueryNodesSimple returns exactly QUERY_LIMIT rows — the only signal we have that counts may be undercounts (review finding #4). - Drop root_node_count from the report. The daemon's query_nodes_simple handler returns NodeData with parent_id=None for every row because parentage is a graph edge, not a column — the field is unrecoverable from the current RPC surface and reporting it would be flat-out wrong (uncovered by the new integration test). A `GetRoots` RPC or extending NodeListResponse with parent ids is needed before this can come back. - Split collect() out of run() with an explicit db_path parameter so the integration test can point at a tempdir-backed daemon without the env-var dance resolve_db_path() requires (review testing gap). - Add `diagnostics_collect_reports_counts_and_recency` integration test that spawns the in-process daemon, captures a baseline, seeds three nodes with timestamp gaps, and asserts +3 total + newest-first ordering + no error accumulation. This is the test that caught the root-count bug above. - Add unit test exercising the happy path of directory_size on a nested tempdir tree, plus updated the missing-path test to assert the error is now surfaced through &mut Vec<String>. Skipped suggestions: - #5 (serial RPC calls): reviewer explicitly called this a nit on localhost gRPC and noted current code is more readable. Latency savings (low ms) don't justify the readability cost. - #6 (bind_addr hoist): reviewer noted "not a bug" — bind_addr is binary-only and there's no caller in the CLI that needs it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * Address re-review: document RFC3339 lexicographic sort invariant R2 from PR #1150's re-review: clarify why string-comparison of `created_at` is equivalent to chronological order. Single serialization path in node_to_proto + consistent `+00:00` suffix make it safe today; a second path (e.g. `Z` suffix) would break it silently. Comment names the fix path so a future maintainer can spot the trap. R1 (file GetRoots follow-up) tracked as #1153. R3 / R4 from re-review: no change needed (reviewer's own answer — pub surface is consistent with existing CLI test pattern; 20ms sleep is fine on microsecond-precision system clocks). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Addresses I-1, S-1, S-2, S-3 from the second /pragmatic-code-review pass.
**I-1: Multi-skill test brittle to MAX_TOOL_ITERATIONS reductions**
- Added a compile-time `const _: () = assert!(MAX_TOOL_ITERATIONS >= 5, ...)`
at the top of the agent_loop tests module. If someone bumps the constant
below 5, the test crate fails to compile with a clear error message
naming the affected test — better than a mysterious runtime failure
where the multi-skill assertions silently start exercising the
iteration-cap fallback path instead of the intended chain.
**S-1: Threshold doc said "every match" but filter is strict `>`**
- Tightened the SKILL_SEARCH_THRESHOLD doc comment in skill_ops.rs to
describe what actually happens: every match with strictly positive
cosine similarity (a zero match is orthogonal vector noise, which the
store filter `composite_score > $threshold` correctly excludes).
**S-2: MCP find_skills tool description advertised "guidance" field**
- Updated find_skills tool description in mcp/handlers/tools.rs:1464 to
match the new flat `{query, matches}` shape — same wording as the
local agent's search_skills description, dropping the now-bogus
"guidance" reference. Single source of truth for tool consumers.
**S-3: skill_ops doc missed `id` field**
- Added `id` to the field list in the find_skills doc comment.
**Skipped: none.** All four addressed.
Verification:
- nodespace-agent lib: 202 passed (the compile-time assert would have
blocked the build if violated, so the count holding steady is the
meaningful signal here, not the pass count itself)
- nodespace-core lib: 1182 passed
- cargo fmt + cargo clippy -p nodespace-agent -p nodespace-core clean
- Note: `bun run quality:fix` cannot complete on this branch right now
because origin/main has a pre-existing breakage in nodespace-cli and
nodespace-daemon tests (CreateNodeRequest gained `id` and
`insert_after_node_id` fields in PR #1147, but the cli/daemon test
fixtures were not updated). Verified this failure reproduces with
origin/main's version of those files checked out into our worktree —
not introduced by this branch. Will file a separate issue.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…oses #1130) (#1149) * Replace pre-LLM skill routing with LLM-orchestrated search_skills tool (closes #1130) Switches skill discovery from a pre-turn pipeline to an LLM-callable tool. The model now decides when to search for a skill, judges the results, and either invokes one or responds directly. Multi-skill turns and context-aware clarifications become possible. ## Agent layer - `search_skills(query, limit?)` exposed every turn (renamed from `find_skills`, with a flatter response shape: `{query, matches: [...]}` carrying raw confidence scores so the model judges relevance itself). - Pre-LLM dispatch path removed from `LocalAgentLoop::run_turn`: - `is_ambiguous` heuristic + `AMBIGUOUS_MESSAGE_WORD_LIMIT` constant - `CLARIFYING_QUESTION` constant + hardcoded short-circuit - `skill_pipeline.find_skill()` resolution + scoped-prompt branch - `skill_pipeline.scope_tools()` whitelist filtering - `SkillPipeline` / `SkillMatch` / `SkillPipelineConfig` types - `intent` module (only consumer was the removed pipeline) - Empty model output with no tool calls now surfaces as `InferenceError` (it's an inference bug, not a UX surface). - `SkillPipeline` collapsed to a thin wrapper that only re-exports the seed templates used by first-run DB seeding (issue #1130 explicitly scopes the change to the control flow, not the skill definitions). ## Storage layer - `SurrealStore::search_embeddings_by_node_type` — linear cosine scan restricted by `node.node_type` record-link traversal. Skips HNSW for high-selectivity types where a tiny candidate set (e.g. ~8-20 skill nodes) makes a linear scan both faster and exact, sidestepping HNSW's global top-K approximation + post-filter. - `EmbeddingService::semantic_search_nodes_of_type` — thin wrapper that embeds the query and delegates to the new store method. - `skill_ops::find_skills` rewritten to use the typed scan and return the flat shape; HIGH/MEDIUM confidence bucketing + `recommendation` strings dropped (model judges from raw scores). MCP `find_skills` handler inherits the new shape transparently. ## Prompts - `TOOL_STRATEGY_RULES`, fallback prompt, and byte-locking drift test updated with a `search_skills` strategy line that calls out the empty-matches signal so small models don't loop retrying the tool. ## Tests New coverage in `agent_loop.rs`: - `model_calls_search_skills_then_invokes_matched_skill` - `model_can_respond_without_calling_search_skills` - `search_skills_can_be_called_multiple_times_in_a_turn` - `empty_model_response_with_no_tools_returns_error` New coverage in `tools.rs`: - `search_skills_schema_exposes_optional_limit` - `search_skills_description_mentions_empty_signal` (load-bearing wording check — small models retry rephrased queries otherwise) Removed Category 8 of `agent_e2e.rs` (skill-pipeline scoping tests) — it exercised the deleted pre-LLM routing behaviour. All tests pass: vitest 3918, nodespace-core 1182, nodespace-agent 202, nodespace-app 54 (25 + 27 + 2). cargo clippy + fmt + eslint + svelte-check clean via `bun run quality:fix`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address PR #1149 review feedback Addresses findings from the /pragmatic-code-review pass on PR #1149. **Critical (both addressed)** - MCP `find_skills` handler (packages/core/src/mcp/handlers/skills.rs): drop the canned "Proceed with general capabilities" fallback so the response shape matches the local agent's `search_skills` tool ({query, matches: []}). External ACP agents now see the same flat shape and judge empty matches themselves, instead of receiving inconsistent payloads from the same `skill_ops::find_skills` backend. - New `SurrealStore::search_embeddings_by_node_type` got four integration tests in `packages/core/tests/search_handler_test.rs`: - confident match: only the typed node returns (proves the `node.node_type = $node_type` record-link filter actually works) - empty result for unknown type with other types present - empty database returns empty (not error) - ranking + limit honoured **Important** - `SKILL_SEARCH_THRESHOLD` dropped from 0.3 to 0.0 in `packages/core/src/ops/skill_ops.rs`. The non-zero floor partially undid the issue's "let the model judge" principle by hiding the long tail. - `MAX_SKILL_LIMIT` got a doc comment explaining the cap's rationale and when to revisit it. - Missing AC test scenarios added in `agent_loop.rs`: - `multi_skill_turn_invokes_skill_tools_between_searches` replaces the weaker prior test; now exercises the full chain (search_skills → search_semantic → search_skills → create_node) so a regression that breaks tool dispatch after a second `search_skills` call is caught here. - `empty_search_skills_matches_let_model_clarify_with_context` covers the "no skill applies" path the issue called out. - Empty-model-response error log gained structured fields (session_id, model, iteration, prompt/completion tokens, user_message_preview) so production dashboards can group these by model and replay sessions. - Filed follow-up #1152 for the latency-measurement AC (requires a warm NLP engine + real local model; out of scope for the unit-test pass). **Suggestions** - Deleted the `SkillPipeline` wrapper struct entirely (`packages/agent/src/skill_pipeline.rs`). Free function `seed_skill_nodes()` is the only public surface now; three call sites updated (db.rs, ollama_integration.rs). Matches CLAUDE.md "no backward compatibility" rule. - `MockToolExecutor::with_tool(name, schema, result)` builder added; the three new agent_loop tests use it instead of mutating internal `tools` / `results` fields. - `search_skills` description now specifies the bounds ("up to 3 by default, max 10") so the model isn't guessing what N is. **Skipped (1 of 12)** - Finding 12 (`humanize_tool_name("search_skills")` → "skill search" reads ambiguously). Subjective wording call; the reviewer's suggested replacement ("available skill lookup") reads more awkwardly. The existing label fits the verb-of-activity pattern the other tools use ("node search", "semantic search", "node lookup"). All tests still pass: - nodespace-core search_handler_test: 27 (was 23 + 4 new typed-scan tests) - nodespace-agent lib: 202 (held steady — net change of +0 after deleting the wrapper test and adding two AC tests) - nodespace-app lib + integration: 54 (25 + 27 + 2) - vitest frontend: 3918 (128 files) - cargo clippy + fmt + eslint + svelte-check clean via `bun run quality:fix` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address PR #1149 re-review feedback Addresses I-1, S-1, S-2, S-3 from the second /pragmatic-code-review pass. **I-1: Multi-skill test brittle to MAX_TOOL_ITERATIONS reductions** - Added a compile-time `const _: () = assert!(MAX_TOOL_ITERATIONS >= 5, ...)` at the top of the agent_loop tests module. If someone bumps the constant below 5, the test crate fails to compile with a clear error message naming the affected test — better than a mysterious runtime failure where the multi-skill assertions silently start exercising the iteration-cap fallback path instead of the intended chain. **S-1: Threshold doc said "every match" but filter is strict `>`** - Tightened the SKILL_SEARCH_THRESHOLD doc comment in skill_ops.rs to describe what actually happens: every match with strictly positive cosine similarity (a zero match is orthogonal vector noise, which the store filter `composite_score > $threshold` correctly excludes). **S-2: MCP find_skills tool description advertised "guidance" field** - Updated find_skills tool description in mcp/handlers/tools.rs:1464 to match the new flat `{query, matches}` shape — same wording as the local agent's search_skills description, dropping the now-bogus "guidance" reference. Single source of truth for tool consumers. **S-3: skill_ops doc missed `id` field** - Added `id` to the field list in the find_skills doc comment. **Skipped: none.** All four addressed. Verification: - nodespace-agent lib: 202 passed (the compile-time assert would have blocked the build if violated, so the count holding steady is the meaningful signal here, not the pass count itself) - nodespace-core lib: 1182 passed - cargo fmt + cargo clippy -p nodespace-agent -p nodespace-core clean - Note: `bun run quality:fix` cannot complete on this branch right now because origin/main has a pre-existing breakage in nodespace-cli and nodespace-daemon tests (CreateNodeRequest gained `id` and `insert_after_node_id` fields in PR #1147, but the cli/daemon test fixtures were not updated). Verified this failure reproduces with origin/main's version of those files checked out into our worktree — not introduced by this branch. Will file a separate issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…ri proxy (closes #1136) - `packages/daemon/proto/import_service.proto`: ImportService with ImportMarkdown and ImportMarkdownFiles server-streaming RPCs - `packages/daemon/src/services/import_service.rs`: handler preserving two-phase pipeline (parse → background DB write) and smart collection routing from commands/import.rs - `packages/daemon/src/main.rs`: registers ImportServiceServer alongside NodeServiceServer in both headless and tray server loops - `packages/desktop-app/src-tauri/src/commands/import.rs`: replaced direct nodespace-core calls with thin gRPC proxy; imports now survive Tauri window close - `packages/desktop-app/src-tauri/src/services/grpc_client.rs`: added ImportServiceClient to the in-process server; exposes import_client() - `packages/cli/src/commands/import.rs`: `nodespace import file` and `nodespace import dir` subcommands via ImportServiceClient - Fixed pre-existing CreateNodeRequest struct literal errors in grpc_round_trip.rs, cli/commands/node.rs, and cli_integration.rs (id and insert_after_node_id fields added in #1147 but not propagated) Co-Authored-By: Claude <[email protected]>
…ri proxy (closes #1136) (#1154) * Add ImportService gRPC: proto definition, nodespaced handler, and Tauri proxy (closes #1136) - `packages/daemon/proto/import_service.proto`: ImportService with ImportMarkdown and ImportMarkdownFiles server-streaming RPCs - `packages/daemon/src/services/import_service.rs`: handler preserving two-phase pipeline (parse → background DB write) and smart collection routing from commands/import.rs - `packages/daemon/src/main.rs`: registers ImportServiceServer alongside NodeServiceServer in both headless and tray server loops - `packages/desktop-app/src-tauri/src/commands/import.rs`: replaced direct nodespace-core calls with thin gRPC proxy; imports now survive Tauri window close - `packages/desktop-app/src-tauri/src/services/grpc_client.rs`: added ImportServiceClient to the in-process server; exposes import_client() - `packages/cli/src/commands/import.rs`: `nodespace import file` and `nodespace import dir` subcommands via ImportServiceClient - Fixed pre-existing CreateNodeRequest struct literal errors in grpc_round_trip.rs, cli/commands/node.rs, and cli_integration.rs (id and insert_after_node_id fields added in #1147 but not propagated) Co-Authored-By: Claude <[email protected]> * Fix silent bulk-insert failure and add ImportService integration tests - Surface bulk DB write failures to gRPC callers (bulk_insert_failed flag marks all phase1 results as failed rather than silently reporting success) - Add import_round_trip.rs: 3 in-process gRPC tests covering single-file import, batch import, and missing-file error surfacing Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude <[email protected]>
…1147) Adds an in-process gRPC server (nodespace-daemon) to the Tauri desktop app and rewrites 33 #[tauri::command] handlers to proxy through tonic instead of calling packages/core directly. Extended NodeService with the full set of RPCs needed by the Tauri command layer: all CRUD, mention, hierarchy, task-update, schema (read-only), and collection operations. Introduced tri-state OptionalStringClear / OptionalTimestampClear wrappers to encode Option<Option<T>> fields for TaskNodeUpdate over the wire. - Implemented all 28 proto RPCs in NodeServiceImpl (node_service.rs): create/get/update/delete node, children tree, mentions, move/reorder, update_task_node, get_all_schemas, get_schema_definition, and the full collection surface (14 RPCs). WatchNodes and Chat remain stubbed (tracked in #1114). - service_error_to_status bridges NodeServiceError → OpsError → tonic::Status consistently across all handlers. GrpcClient spawns NodeServiceImpl on a loopback port chosen by the OS (127.0.0.1:0, no collision with a standalone nodespaced on [::1]:50051). Reuses the same Arc<NodeService> AppServices already owns — no second DB open, no RocksDB lock contention. Channel is Arc-backed; client() returns a cheap clone per call. Registered via app.manage() after init_services(). nodes.rs (19 handlers), collections.rs (12 handlers), schemas.rs (2 handlers): - All AppServices / NodeService / CollectionService deps removed. - proto_node_data_to_node (pub(crate)) reconstructs core::Node from wire NodeData (parses RFC3339 timestamps; returns PARSE_ERROR on malformed input rather than silently substituting Utc::now()). - status_to_command_error maps tonic::Status codes to existing CommandError codes (NotFound → NODE_NOT_FOUND, Aborted → VERSION_CONFLICT, etc.). - validate_node_type uses GetSchemaDefinition RPC; maps both NotFound and FailedPrecondition to SCHEMA_NOT_FOUND. - task_update_to_proto uses TaskStatus::as_str() / TaskPriority::as_str() (not serde_json::to_string, which would double-quote the values). - All existing Tauri command return types preserved — frontend unchanged. Added nodespace-daemon, tonic, prost to workspace Cargo.toml; chrono to daemon Cargo.toml; daemon + tonic + prost to desktop-app Cargo.toml. cargo clippy -p nodespace-app — zero warnings. Frontend test suite: 128 files / 3918 tests — no regressions. Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* Implement AgentSessionService gRPC handler (closes #1119) Wire the PTY engine from #1118 into the nodespaced gRPC server. The new AgentSessionService exposes the six PTY operations — Launch, StreamOutput (server-streaming), WriteInput, ResizeTerminal, TerminateSession, ListSessions — so the Tauri UI and CLI can drive agent sessions over loopback gRPC. ## Layout - packages/daemon/src/services/agent_session_service.rs (new) — tonic trait impl, parses kebab-case agent_type into AgentType, adapts each RPC into the matching PtySessionManager / PtySession call, returns status codes per failure mode (InvalidArgument for bad UUID / unknown agent_type, NotFound for missing sessions, Internal for PTY errors). - packages/daemon/src/services/mod.rs — re-export AgentSessionHandler. - packages/daemon/src/main.rs — refactor build_node_service → build_services so both headless and tray loops register NodeServiceServer *and* AgentSessionServiceServer. - packages/daemon/Cargo.toml — add nodespace-agent (path dep) plus uuid for ID parsing. ## Proto alignment packages/daemon/proto/agent_session_service.proto: the original message shape (raw command/args/cwd/env, separate stdout/stderr StreamKind, optional exit code on SessionInfo) predates the PtySessionManager API that landed in #1118 and would have required either (a) a parallel "raw-command" launch path that bypasses the agent catalog + GraphContextAssembler, or (b) a translation layer that maps strings back into the AgentType enum. Both are pure technical debt for a greenfield daemon. This commit rewrites the proto to match the engine: - LaunchSessionRequest is {agent_type, prompt, cols, rows} — the fields the issue body specifies and PtySessionManager::launch actually accepts. - OutputChunk drops StreamKind (PTYs merge stdout/stderr at the kernel level, there is no way to split them at this layer). - SessionInfo trims to {session_id, agent_type, started_at} matching the existing SessionMetadata struct. Status/exit-code fields would have required new bookkeeping in the manager for no consumer in this PR. - ResizeResponse / ListSessionsRequest become empty — the echoed cols/rows and status_filter were unused by every caller. Nothing else in the workspace consumed the old proto (only the daemon's lib.rs re-exported SessionInfo and no field was read), so the rewrite is safe. ## StreamOutput Subscribes to the session's broadcast::Receiver<OutputChunk> and forwards chunks as proto OutputChunk messages. On RecvError::Lagged the handler logs and continues — losing a render frame is preferable to tearing the stream down. On RecvError::Closed the stream ends naturally. Client disconnect drops only the subscriber, never the session (acceptance criterion #8); integration test stream_output_disconnect_does_not_kill_session pins that contract. ## Test helper visibility PtySession::launch_for_test moved from pub(crate) + #[cfg(test)] to pub + #[cfg(any(test, feature = "testing"))] so the daemon's integration tests can spawn shell utilities (echo, cat, sleep) without a real agent binary on PATH. The "testing" feature already exists in the agent crate for the same reason (ollama_integration tests). Same treatment for session_dir_path. ## Tests packages/daemon/tests/agent_session_grpc.rs (new) — 8 integration tests against the in-process tonic server: - stream_output_delivers_echo_hello (acceptance criterion #9) - stream_output_disconnect_does_not_kill_session (criterion #8) - write_input_is_echoed_back_through_stream (round-trip through cat) - list_sessions_reflects_manager_state - resize_terminal_succeeds_for_active_session - terminate_unknown_session_reports_was_not_running - unknown_session_returns_not_found (both StreamOutput and WriteInput) - invalid_session_id_returns_invalid_argument Plus 4 unit tests in agent_session_service.rs::tests covering the kebab/snake_case agent_type parsing, round-trip, UUID rejection. LaunchSession itself is exercised indirectly: the production launch path resolves the agent binary on PATH (which CI does not have), so tests seed the manager via PtySession::launch_for_test + manager.insert and drive every other RPC through the full gRPC stack. ## Lint note parse_session_id and parse_agent_type return Result<T, String> rather than Result<T, Status>. tonic::Status is ~176 bytes; Uuid is 16 and AgentType is 1, so Result<T, Status> trips clippy::result_large_err. The call sites lift the String into Status::invalid_argument in one line — keeps the parsers status-agnostic and the lint clean without any allow attribute. ## Drive-by fix from rebase PR #1147 added id + insert_after_node_id to CreateNodeRequest but did not update existing call sites in packages/daemon/tests/grpc_round_trip.rs or packages/cli/{src/commands/node.rs, tests/cli_integration.rs}. The existing rust:test script only covers nodespace-core --lib, so the breakage didn't surface in CI. Added the two missing fields (both defaulting to String::new()) so the daemon test binary and cli build compile on top of main. ## Verified - cargo build --bin nodespaced: success - cargo test -p nodespace-daemon: 24 passed (6 unit + 8 agent-session integration + 10 grpc-round-trip) - cargo test -p nodespace-agent --lib --features testing: 250 passed - bun run quality:fix: clean (eslint + svelte-check + rustfmt + clippy) - bun run test: 3918/3918 passed across 128 files (matches baseline) - bun run test:all: success (exit 0) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address review: tighten contracts, drop backwards-compat Implements 7 of 12 suggestions from the PR #1148 pragmatic review. Each change is small and self-contained; nothing affects the overall architecture or behavior beyond what the review identified. ## Addressed ### 1. LaunchSessionResponse.created_at uses authoritative started_at Previously the handler took a fresh `Utc::now()` after `manager.launch()` returned. The session's own `started_at` is set inside `spawn_in_pty` before the reader/watcher tasks are wired, so the wire-level timestamp drifted a few milliseconds behind it — and ListSessions reported the earlier (correct) one. Now `launch_session` does one `manager.get()` after launch and uses `session.started_at.timestamp()`. Single source of truth between LaunchSession and ListSessions. ### 2. Widen proto numeric fields to avoid silent casts - `WriteInputResponse.bytes_written`: int32 → int64. `usize as i32` was wraparound on 2 GiB+ payloads — unlikely for a PTY but the contract is the contract. - `ListSessionsResponse.count`: int32 → uint32. Saturating cast via `u32::try_from(...).unwrap_or(u32::MAX)` keeps the count monotonic for clients that diff snapshots. Greenfield-correct per CLAUDE.md (single consumer, no migration cost). ### 3. Hold session Arc through launch+resize `launch_session` now does one `manager.get(&id)` after launch and holds the resulting `Arc<PtySession>` for both `started_at` and the optional initial resize. Eliminates the redundant lock acquisition AND closes a small race where the spawned child could exit and the auto-prune watcher remove the entry between launch() and apply_resize(), returning NotFound for a session we just created. The old `apply_resize(manager, id, ...)` helper is replaced by `resize_session(&Arc<PtySession>, ...)`; `resize_terminal` does its own manager lookup since it doesn't have an Arc from elsewhere. ### 4. StreamOutput lag visibility (lowest-risk variant) Kept the current swallow-and-warn behavior — surfacing dropped bytes inline via a sentinel chunk or a session metric is a wider design change that should land in its own PR. Added a `debug_assert!(skipped > 0)` to catch future bugs that produce zero-byte lag events, and a TODO note pointing at the review discussion so the trade-off is visible to future maintainers. ### 5. ResizeTerminal rejects zero dimensions Unlike LaunchSession (0 = use default), ResizeTerminal has no default semantic — its job is "apply exactly this size". Now returns `InvalidArgument` if either axis is zero, rather than passing through to `portable_pty` with `PtySize { rows: 0, cols: 0, .. }` which is platform-dependent. Added integration test `resize_terminal_rejects_ zero_dimensions` pinning the contract across (0, N), (N, 0), (0, 0). Proto comment documents the [1, 65535] valid range. ### Nit: Remove snake_case agent_type acceptance Per CLAUDE.md's no-backwards-compat directive: the previous `raw.replace('_', "-")` was dead weight for a greenfield API with zero callers. Kebab-case is the only accepted form now. Added `parse_agent_type_rejects_snake_case` test pinning the new rejection so a future refactor cannot silently restore the dual-accept path. ### 6. Document testing-feature footgun in agent crate Expanded the `[features] testing = []` comment in `packages/agent/Cargo.toml` to explain Cargo's feature-unification behavior across dep/dev-dep within a single downstream package, and the rule that test-only stubs behind this feature must only widen visibility — never change runtime behavior, swap implementations, or skip safety checks. Test-only mutating stubs belong in test-only modules in the downstream crate, not behind this flag. ## Skipped, with reasoning - **#7 Daemon test for caller-supplied UUID path through CreateNode**: Reviewer explicitly marked this "out of scope for this PR" and the contract is already exercised in nodespace-core per #1147. Worth a follow-up issue if the daemon adapter ever diverges from a simple pass-through. - **Nit: `agent_type_to_string` debug_assert**: The dead-code fallback to `format!("{agent_type:?}")` is genuinely defensive — it makes the function infallible if `AgentType` ever gains a non-serde variant in the future. A `debug_assert!(false)` would catch that in test, but would also panic in production for a problem that's recoverable. The current shape is the right trade-off. - **Nit: connect-retry loop `last_err` Option indirection**: Purely stylistic and the existing shape already does the right thing (`panic!` formats `Some(e)` fine). Not worth a churn commit. - **Nit: `count: count` field-init shorthand**: Clippy didn't flag and the explicit form is consistent with other struct literals in the same file. No-op. - **Nit: `embedding_service = None` duplication in main.rs**: Will naturally resolve when the embedding service is wired by the follow- up issue (currently both arms become `Some(embedding_service.clone())`). Introducing a binding now would just need un-introducing later. ## Verified - `cargo build --bin nodespaced`: clean - `cargo test -p nodespace-daemon`: 26 passed (7 unit + 9 agent-session integration + 10 grpc-round-trip; added zero-reject + snake-case rejection tests) - `cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async`: clean - `bun run quality:fix`: clean (eslint + svelte-check + rustfmt + clippy across the full workspace) - `bun run test`: 3918/3918 across 128 files (matches baseline) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address re-review: surface dropped resize, deflake echo test Two small follow-ups from the re-review of 10041e3, plus a flake fix discovered while verifying. ## Addressed ### Re-review suggestion: warn-log silent resize skip in launch_session If the auto-prune watcher removes the session entry between launch() and the get() that pins the Arc for the optional initial resize, the resize silently no-op'd and the client got a successful LaunchSessionResponse with a session_id that the next RPC would reject as NotFound. Now logs at `tracing::warn!` with session_id + requested dims so the server-side trace makes the dropped resize discoverable. Kept the response semantics unchanged: the launch itself succeeded, so returning Status::failed_precondition would force every client to handle a confusing "launch succeeded but failed to resize" mid-failure. The next RPC's NotFound is a clearer signal for the (vanishingly rare) race that this branch handles. ### Re-review nit: agent_type_to_string fallback comment Updated the comment to explicitly state that the debug-format fallback is defense-in-depth, not a graceful-degradation path. AgentType is in-workspace and closed, so adding a new variant must extend parse_agent_type / agent_type_to_string together — the fallback is not a shortcut. ## Flake fix (discovered during verification) `stream_output_delivers_echo_hello` was timing-sensitive: on a fast machine the PTY reader could drain `echo hello` and broadcast the chunk before the gRPC client's StreamOutput subscriber attached. `tokio::sync::broadcast` does not replay missed messages to late subscribers (unlike `watch`), so the test would fail ~10% of runs. Changed the command from `echo hello` to `sleep 0.2 && echo hello` so the subscriber is guaranteed to attach before bytes hit the broadcast channel. Comment in the test body explains why. 5/5 passing after the change. This is a pre-existing flake in the original PR; the re-review missed it because the parallel test run masked it. Catching it now means it won't show up as intermittent CI failures later. ## Verified - cargo test -p nodespace-daemon: 26 passed (run 5x to confirm no flake) - cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async: clean - bun run quality:fix: clean 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* Migrate diagnostics to nodespace CLI subcommand (closes #1139) Implements `nodespace diagnostics` and removes the corresponding Tauri command surface. Under ADR-031, diagnostic data lives in nodespaced, not the Tauri process — so a CLI subcommand is the correct surface for the intended audience (developers debugging persistence issues). CLI subcommand reports: database path, existence, size, total node count, root node count, schema count, recent node IDs. Honors --json for machine-readable output. Reuses the daemon's gRPC client (`QueryNodesSimple`, `GetAllSchemas`); the database path is resolved by a new `resolve_db_path()` helper hoisted from `main.rs` into the daemon's library surface so the CLI and daemon agree on the location without a settings RPC round-trip. Tauri side: deletes `commands/diagnostics.rs` and the two `#[tauri::command]` handlers (`get_database_diagnostics`, `test_node_persistence`). The developer-only diagnostic panel (Ctrl+Shift+D) loses the now-broken "Database" and "Persistence Test" tabs but keeps its Call Logs view, which is independent of the deleted backend commands. The corresponding `getDatabaseDiagnostics` / `testNodePersistence` helpers and their tests in `diagnostic-logger.ts` are removed; `withDiagnosticLogging` and the log buffer remain (used by `backend-adapter.ts` to wrap 18 Tauri calls). Drive-by: fix `CreateNodeRequest` literal sites in the CLI's `node create` command and the cli/daemon integration tests that #1147 left missing the new `id` and `insert_after_node_id` proto fields. Without this, `cargo build -p nodespace-cli` and `cargo test` on both test crates failed on a fresh clone of main. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * Address review: surface IO/truncation errors, sort recent IDs, add integration test Resolves the 🟡 Important and 🟢 Suggestion findings from PR #1150's review. - Sort all_nodes by created_at DESC before slicing for recent_node_ids, so the user-visible "recent" label means most-recently-created rather than first-in-iteration-order (review finding #1). - Have directory_size accumulate IO errors into the report's `errors` field instead of silently returning 0 on read_dir / file_type / metadata failures. A permissions error reporting "Database size: 0.00 B" was precisely the failure mode an operator running `nodespace diagnostics` needs to see (review finding #2). - Document the symlink-skipping behavior so a future "fix" doesn't reintroduce the loop risk that `fs::metadata` would (review finding #3). - Surface a warning when QueryNodesSimple returns exactly QUERY_LIMIT rows — the only signal we have that counts may be undercounts (review finding #4). - Drop root_node_count from the report. The daemon's query_nodes_simple handler returns NodeData with parent_id=None for every row because parentage is a graph edge, not a column — the field is unrecoverable from the current RPC surface and reporting it would be flat-out wrong (uncovered by the new integration test). A `GetRoots` RPC or extending NodeListResponse with parent ids is needed before this can come back. - Split collect() out of run() with an explicit db_path parameter so the integration test can point at a tempdir-backed daemon without the env-var dance resolve_db_path() requires (review testing gap). - Add `diagnostics_collect_reports_counts_and_recency` integration test that spawns the in-process daemon, captures a baseline, seeds three nodes with timestamp gaps, and asserts +3 total + newest-first ordering + no error accumulation. This is the test that caught the root-count bug above. - Add unit test exercising the happy path of directory_size on a nested tempdir tree, plus updated the missing-path test to assert the error is now surfaced through &mut Vec<String>. Skipped suggestions: - #5 (serial RPC calls): reviewer explicitly called this a nit on localhost gRPC and noted current code is more readable. Latency savings (low ms) don't justify the readability cost. - #6 (bind_addr hoist): reviewer noted "not a bug" — bind_addr is binary-only and there's no caller in the CLI that needs it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * Address re-review: document RFC3339 lexicographic sort invariant R2 from PR #1150's re-review: clarify why string-comparison of `created_at` is equivalent to chronological order. Single serialization path in node_to_proto + consistent `+00:00` suffix make it safe today; a second path (e.g. `Z` suffix) would break it silently. Comment names the fix path so a future maintainer can spot the trap. R1 (file GetRoots follow-up) tracked as #1153. R3 / R4 from re-review: no change needed (reviewer's own answer — pub surface is consistent with existing CLI test pattern; 20ms sleep is fine on microsecond-precision system clocks). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Sonnet 4.6 <[email protected]>
…oses #1130) (#1149) * Replace pre-LLM skill routing with LLM-orchestrated search_skills tool (closes #1130) Switches skill discovery from a pre-turn pipeline to an LLM-callable tool. The model now decides when to search for a skill, judges the results, and either invokes one or responds directly. Multi-skill turns and context-aware clarifications become possible. ## Agent layer - `search_skills(query, limit?)` exposed every turn (renamed from `find_skills`, with a flatter response shape: `{query, matches: [...]}` carrying raw confidence scores so the model judges relevance itself). - Pre-LLM dispatch path removed from `LocalAgentLoop::run_turn`: - `is_ambiguous` heuristic + `AMBIGUOUS_MESSAGE_WORD_LIMIT` constant - `CLARIFYING_QUESTION` constant + hardcoded short-circuit - `skill_pipeline.find_skill()` resolution + scoped-prompt branch - `skill_pipeline.scope_tools()` whitelist filtering - `SkillPipeline` / `SkillMatch` / `SkillPipelineConfig` types - `intent` module (only consumer was the removed pipeline) - Empty model output with no tool calls now surfaces as `InferenceError` (it's an inference bug, not a UX surface). - `SkillPipeline` collapsed to a thin wrapper that only re-exports the seed templates used by first-run DB seeding (issue #1130 explicitly scopes the change to the control flow, not the skill definitions). ## Storage layer - `SurrealStore::search_embeddings_by_node_type` — linear cosine scan restricted by `node.node_type` record-link traversal. Skips HNSW for high-selectivity types where a tiny candidate set (e.g. ~8-20 skill nodes) makes a linear scan both faster and exact, sidestepping HNSW's global top-K approximation + post-filter. - `EmbeddingService::semantic_search_nodes_of_type` — thin wrapper that embeds the query and delegates to the new store method. - `skill_ops::find_skills` rewritten to use the typed scan and return the flat shape; HIGH/MEDIUM confidence bucketing + `recommendation` strings dropped (model judges from raw scores). MCP `find_skills` handler inherits the new shape transparently. ## Prompts - `TOOL_STRATEGY_RULES`, fallback prompt, and byte-locking drift test updated with a `search_skills` strategy line that calls out the empty-matches signal so small models don't loop retrying the tool. ## Tests New coverage in `agent_loop.rs`: - `model_calls_search_skills_then_invokes_matched_skill` - `model_can_respond_without_calling_search_skills` - `search_skills_can_be_called_multiple_times_in_a_turn` - `empty_model_response_with_no_tools_returns_error` New coverage in `tools.rs`: - `search_skills_schema_exposes_optional_limit` - `search_skills_description_mentions_empty_signal` (load-bearing wording check — small models retry rephrased queries otherwise) Removed Category 8 of `agent_e2e.rs` (skill-pipeline scoping tests) — it exercised the deleted pre-LLM routing behaviour. All tests pass: vitest 3918, nodespace-core 1182, nodespace-agent 202, nodespace-app 54 (25 + 27 + 2). cargo clippy + fmt + eslint + svelte-check clean via `bun run quality:fix`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address PR #1149 review feedback Addresses findings from the /pragmatic-code-review pass on PR #1149. **Critical (both addressed)** - MCP `find_skills` handler (packages/core/src/mcp/handlers/skills.rs): drop the canned "Proceed with general capabilities" fallback so the response shape matches the local agent's `search_skills` tool ({query, matches: []}). External ACP agents now see the same flat shape and judge empty matches themselves, instead of receiving inconsistent payloads from the same `skill_ops::find_skills` backend. - New `SurrealStore::search_embeddings_by_node_type` got four integration tests in `packages/core/tests/search_handler_test.rs`: - confident match: only the typed node returns (proves the `node.node_type = $node_type` record-link filter actually works) - empty result for unknown type with other types present - empty database returns empty (not error) - ranking + limit honoured **Important** - `SKILL_SEARCH_THRESHOLD` dropped from 0.3 to 0.0 in `packages/core/src/ops/skill_ops.rs`. The non-zero floor partially undid the issue's "let the model judge" principle by hiding the long tail. - `MAX_SKILL_LIMIT` got a doc comment explaining the cap's rationale and when to revisit it. - Missing AC test scenarios added in `agent_loop.rs`: - `multi_skill_turn_invokes_skill_tools_between_searches` replaces the weaker prior test; now exercises the full chain (search_skills → search_semantic → search_skills → create_node) so a regression that breaks tool dispatch after a second `search_skills` call is caught here. - `empty_search_skills_matches_let_model_clarify_with_context` covers the "no skill applies" path the issue called out. - Empty-model-response error log gained structured fields (session_id, model, iteration, prompt/completion tokens, user_message_preview) so production dashboards can group these by model and replay sessions. - Filed follow-up #1152 for the latency-measurement AC (requires a warm NLP engine + real local model; out of scope for the unit-test pass). **Suggestions** - Deleted the `SkillPipeline` wrapper struct entirely (`packages/agent/src/skill_pipeline.rs`). Free function `seed_skill_nodes()` is the only public surface now; three call sites updated (db.rs, ollama_integration.rs). Matches CLAUDE.md "no backward compatibility" rule. - `MockToolExecutor::with_tool(name, schema, result)` builder added; the three new agent_loop tests use it instead of mutating internal `tools` / `results` fields. - `search_skills` description now specifies the bounds ("up to 3 by default, max 10") so the model isn't guessing what N is. **Skipped (1 of 12)** - Finding 12 (`humanize_tool_name("search_skills")` → "skill search" reads ambiguously). Subjective wording call; the reviewer's suggested replacement ("available skill lookup") reads more awkwardly. The existing label fits the verb-of-activity pattern the other tools use ("node search", "semantic search", "node lookup"). All tests still pass: - nodespace-core search_handler_test: 27 (was 23 + 4 new typed-scan tests) - nodespace-agent lib: 202 (held steady — net change of +0 after deleting the wrapper test and adding two AC tests) - nodespace-app lib + integration: 54 (25 + 27 + 2) - vitest frontend: 3918 (128 files) - cargo clippy + fmt + eslint + svelte-check clean via `bun run quality:fix` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Address PR #1149 re-review feedback Addresses I-1, S-1, S-2, S-3 from the second /pragmatic-code-review pass. **I-1: Multi-skill test brittle to MAX_TOOL_ITERATIONS reductions** - Added a compile-time `const _: () = assert!(MAX_TOOL_ITERATIONS >= 5, ...)` at the top of the agent_loop tests module. If someone bumps the constant below 5, the test crate fails to compile with a clear error message naming the affected test — better than a mysterious runtime failure where the multi-skill assertions silently start exercising the iteration-cap fallback path instead of the intended chain. **S-1: Threshold doc said "every match" but filter is strict `>`** - Tightened the SKILL_SEARCH_THRESHOLD doc comment in skill_ops.rs to describe what actually happens: every match with strictly positive cosine similarity (a zero match is orthogonal vector noise, which the store filter `composite_score > $threshold` correctly excludes). **S-2: MCP find_skills tool description advertised "guidance" field** - Updated find_skills tool description in mcp/handlers/tools.rs:1464 to match the new flat `{query, matches}` shape — same wording as the local agent's search_skills description, dropping the now-bogus "guidance" reference. Single source of truth for tool consumers. **S-3: skill_ops doc missed `id` field** - Added `id` to the field list in the find_skills doc comment. **Skipped: none.** All four addressed. Verification: - nodespace-agent lib: 202 passed (the compile-time assert would have blocked the build if violated, so the count holding steady is the meaningful signal here, not the pass count itself) - nodespace-core lib: 1182 passed - cargo fmt + cargo clippy -p nodespace-agent -p nodespace-core clean - Note: `bun run quality:fix` cannot complete on this branch right now because origin/main has a pre-existing breakage in nodespace-cli and nodespace-daemon tests (CreateNodeRequest gained `id` and `insert_after_node_id` fields in PR #1147, but the cli/daemon test fixtures were not updated). Verified this failure reproduces with origin/main's version of those files checked out into our worktree — not introduced by this branch. Will file a separate issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…ri proxy (closes #1136) (#1154) * Add ImportService gRPC: proto definition, nodespaced handler, and Tauri proxy (closes #1136) - `packages/daemon/proto/import_service.proto`: ImportService with ImportMarkdown and ImportMarkdownFiles server-streaming RPCs - `packages/daemon/src/services/import_service.rs`: handler preserving two-phase pipeline (parse → background DB write) and smart collection routing from commands/import.rs - `packages/daemon/src/main.rs`: registers ImportServiceServer alongside NodeServiceServer in both headless and tray server loops - `packages/desktop-app/src-tauri/src/commands/import.rs`: replaced direct nodespace-core calls with thin gRPC proxy; imports now survive Tauri window close - `packages/desktop-app/src-tauri/src/services/grpc_client.rs`: added ImportServiceClient to the in-process server; exposes import_client() - `packages/cli/src/commands/import.rs`: `nodespace import file` and `nodespace import dir` subcommands via ImportServiceClient - Fixed pre-existing CreateNodeRequest struct literal errors in grpc_round_trip.rs, cli/commands/node.rs, and cli_integration.rs (id and insert_after_node_id fields added in #1147 but not propagated) Co-Authored-By: Claude <[email protected]> * Fix silent bulk-insert failure and add ImportService integration tests - Surface bulk DB write failures to gRPC callers (bulk_insert_failed flag marks all phase1 results as failed rather than silently reporting success) - Add import_round_trip.rs: 3 in-process gRPC tests covering single-file import, batch import, and missing-file error surfacing Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude <[email protected]>
Summary
nodes.rs(19 handlers),collections.rs(12 handlers), andschemas.rs(2 handlers) so every#[tauri::command]proxies through the in-processGrpcClientinstead of callingpackages/coredirectlyAppServices/NodeService/CollectionServicedependencies from the three migrated command files — no directpackages/coreimports remain in scopeproto_node_data_to_node/proto_node_response_to_nodehelpers to reconstructcore::Nodefrom wireNodeData(parse JSON properties, RFC 3339 timestamps)status_to_command_errormappingtonic::Statuscodes to the existingCommandErrorerror codes (NotFound → NODE_NOT_FOUND, Aborted → VERSION_CONFLICT, etc.)validate_node_typerewritten to callGetSchemaDefinitionRPC instead ofNodeService.get_schema_for_type()update_task_nodeencodesOption<Option<T>>fields viaOptionalStringClear/OptionalTimestampClearwrappers on the way toUpdateTaskNodeRPCschemas.rsremoves duplicateCommandErrordefinition; imports fromnodes::CommandError; reconstructsSchemaNodeviaSchemaNode::from_node()on returnedNodeDataTest plan
cargo build -p nodespace-daemon— cleancargo build -p nodespace-app— cleancargo clippy -p nodespace-app -- -D warnings— zero warningscargo fmt --allappliedScope
This closes #1113 (nodes / collections / schemas proxy migration). Out-of-scope command files tracked separately: embeddings.rs (#1135), import.rs (#1136), local_agent.rs (#1137), settings.rs (#1138).
🤖 Generated with Claude Code