Skip to content

Migrate Tauri command handlers to gRPC proxy (closes #1113) - #1147

Merged
malibio merged 1 commit into
mainfrom
worktree-issue-1113-grpc-proxy
May 18, 2026
Merged

malibio merged 1 commit into
mainfrom
worktree-issue-1113-grpc-proxy

Conversation

@malibio

@malibio malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Rewrites nodes.rs (19 handlers), collections.rs (12 handlers), and schemas.rs (2 handlers) so every #[tauri::command] proxies through the in-process GrpcClient instead of calling packages/core directly
  • Removes all AppServices / NodeService / CollectionService dependencies from the three migrated command files — no direct packages/core imports remain in scope
  • Adds proto_node_data_to_node / proto_node_response_to_node helpers to reconstruct core::Node from wire NodeData (parse JSON properties, RFC 3339 timestamps)
  • Adds status_to_command_error mapping tonic::Status codes to the existing CommandError error codes (NotFound → NODE_NOT_FOUND, Aborted → VERSION_CONFLICT, etc.)
  • validate_node_type rewritten to call GetSchemaDefinition RPC instead of NodeService.get_schema_for_type()
  • update_task_node encodes Option<Option<T>> fields via OptionalStringClear / OptionalTimestampClear wrappers on the way to UpdateTaskNode RPC
  • schemas.rs removes duplicate CommandError definition; imports from nodes::CommandError; reconstructs SchemaNode via SchemaNode::from_node() on returned NodeData
  • All existing Tauri command return types preserved — frontend unchanged

Test plan

  • cargo build -p nodespace-daemon — clean
  • cargo build -p nodespace-app — clean
  • cargo clippy -p nodespace-app -- -D warnings — zero warnings
  • cargo fmt --all applied
  • Frontend: 128 files / 3918 tests — no regressions vs baseline

Scope

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

@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This PR completes Phase 5 of the gRPC proxy migration (issue #1113), rewriting all 33 #[tauri::command] handlers in nodes.rs, collections.rs, and schemas.rs to proxy through an in-process tonic GrpcClient instead of calling packages/core directly. The architectural direction is correct and the in-process server design (shared Arc<NodeService>, OS-assigned port, no second DB open) is well-considered. The migration is complete, mechanically consistent, and the commit message is accurate.

One functional bug was found in the TaskStatus/TaskPriority serialization path that will silently corrupt task updates. All other findings are improvements or nits.


Findings

Critical Issues

[Critical/Blocker] task_update_to_proto: TaskStatus and TaskPriority are double-encoded as JSON strings

packages/desktop-app/src-tauri/src/commands/nodes.rs — task_update_to_proto

// 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::to_string(&TaskStatus::Open) produces "\"open\"" — a Rust String whose content is the JSON text "open" (with surrounding quote characters). When this value arrives at the gRPC server, build_task_node_update parses it as:

serde_json::from_value::<TaskStatus>(serde_json::Value::String(s.clone()))

from_value(Value::String("\"open\"")) passes the string "\"open\"" (with embedded quotes) through TaskStatus::from_str, which matches none of the known variants ("open", "in_progress", etc.) and silently falls back to TaskStatus::User("\"open\""). The same bug applies to TaskPriority via parse_task_priority.

The fix is straightforward: use the as_str() accessor instead of serde_json::to_string:

// Fixed:
status: update.status.map(|s| s.as_str().to_string()),
// ...
value: p.as_str().to_string(),

On the server, parse_task_priority should correspondingly use from_str instead of from_value. This bug affects every update_task_node call from the frontend.


Suggested Improvements

[Improvement] proto_node_data_to_node is duplicated verbatim across three files

nodes.rs (private), collections.rs (private, with inline use chrono), and schemas.rs (private) each contain an identical 20-line function body. The comment in collections.rs notes it is there "to avoid cross-module import of private fn" — the solution is to make the function pub(crate) in nodes.rs (as was already done for node_to_typed_value and nodes_to_typed_values) and remove the copies:

// 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 Node field defaults.

[Improvement] Timestamp parse failures silently substitute Utc::now()

proto_node_data_to_node in all three files:

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, created_at and modified_at silently become the current wall-clock time — making the node appear just-created/-modified and potentially triggering false OCC conflicts on subsequent updates. The server always generates valid RFC3339 via DateTime::to_rfc3339(), so this path should never be hit today, but the silent substitution masks data corruption instead of surfacing it. Returning Err(CommandError { code: "PARSE_ERROR", ... }) would be safer.

[Improvement] validate_node_type does not handle FailedPrecondition from GetSchemaDefinition

packages/desktop-app/src-tauri/src/commands/nodes.rs — validate_node_type:

Err(s) if s.code() == tonic::Code::NotFound => Err(CommandError { code: "SCHEMA_NOT_FOUND", ... }),
Err(s) => Err(status_to_command_error(s)),

GetSchemaDefinition on the server returns FailedPrecondition when a node exists but has the wrong type (node_type != "schema"). validate_node_type routes this through status_to_command_error, which maps it to generic "GRPC_ERROR" rather than "SCHEMA_NOT_FOUND". In practice this scenario is unlikely (a node whose ID matches a type name but is not a schema), but the error code exposed to the frontend is misleading. Mapping FailedPrecondition to "SCHEMA_NOT_FOUND" here would be consistent.

[Improvement] get_collection_members in node_service.rs calls CollectionService::new(store, &self.node_service) but uses store.get_collection_members() style on older code paths — confirm API

packages/daemon/src/services/node_service.rs line 734: collection_service.get_collection_members(...) — this is correct (it goes through CollectionService). However, CollectionService::new is constructed fresh per RPC call and the store ref is obtained via self.node_service.store(). This is a trivially cheap operation and there is no lifetime issue, but it would be worth a follow-up to cache the CollectionService on NodeServiceImpl if CollectionService::new becomes non-trivial.

[Improvement] create_node in node_service.rs lifecycle_status update path is non-atomic and doubles read traffic

Lines 108–121: when lifecycle_status != "active", the handler does: create → fetch (to get version) → update → fetch again (to build response). This is 4 sequential round-trips to the core service. While the lifecycle_status field is never sent as non-empty from the current Tauri command layer, this code path is on the gRPC hot path and the non-atomicity is a correctness risk if the code is reused. A cleaner approach is to have CoreNodeService::create_node_with_parent accept lifecycle_status directly, or to special-case this only if lifecycle_status is non-empty.

[Improvement] Missing unit tests for new conversion helpers

proto_node_data_to_node, task_update_to_proto, status_to_command_error, and build_task_node_update have no unit tests. These are pure functions with non-trivial encoding logic (especially the tri-state OptionalStringClear/OptionalTimestampClear encoding). The existing test module in nodes.rs only covers CommandError serialization. Adding property-based or table-driven tests for the converters would catch regressions like the TaskStatus encoding bug during development rather than at runtime.


Nitpicks

Nit: nodes.rs line 304 — update.node_type.unwrap_or_default() sends an empty string when node_type is None. The UpdateNodeRequest proto comment says "empty string = no change," which is correct, but a comment at the call site explaining this semantic would aid future readers.

Nit: grpc_client.rs — The CONNECT_TIMEOUT constant is 5 seconds. For an in-process loopback that completes in microseconds, this is generous and appropriate. The comment explains the rationale; no change needed.

Nit: node_service.rs — service_error_to_status converts NodeServiceError → OpsError → Status via OpsError::from. The intermediate OpsError conversion is an artifact of reusing the existing ops_error_to_status function. A direct match would be marginally cleaner, but the current approach is a pragmatic choice that avoids duplication.

Nit: collections.rs — get_all_collections switches from Vec::with_capacity(collections_with_counts.len()) to Vec::new(). Now that the length is unknown before iteration (response field is a Vec), using Vec::with_capacity(resp.into_inner().collections.len()) before the for loop would restore the pre-allocation behaviour.


Acceptance Criteria Status

  • All #[tauri::command] handlers in nodes.rs (19), collections.rs (12), schemas.rs (2) now call nodespaced via gRPC — 33/33 complete
  • No direct packages/core ops invocations remain in the three migrated files (remaining imports are type aliases only)
  • gRPC client initialized on Tauri startup and stored in tauri::State
  • All existing Tauri command return types preserved
  • Error cases propagate (gRPC status codes → CommandError) with appropriate codes
  • cargo clippy -p nodespace-app passes per commit message
  • Frontend tests pass (3918 tests, no regressions per commit message)
  • Blocked: update_task_node silently corrupts status and priority fields due to double-JSON-encoding — must be fixed before merge

@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Address-Review Summary

✅ Addressed (5 recommendations)

🔴 Critical — Fixed: task_update_to_proto double-encoding

  • Replaced serde_json::to_string(&s).unwrap_or_default() with s.as_str().to_string() for TaskStatus and TaskPriority. The previous code produced JSON-quoted strings like "\"open\"" which the daemon's build_task_node_update couldn't parse, silently corrupting every task status/priority update.

🟡 Important — Fixed: proto_node_data_to_node duplicated across 3 files

  • Promoted to pub(crate) in nodes.rs; removed verbatim copies from collections.rs and schemas.rs which now import via super::nodes::proto_node_data_to_node.

🟡 Important — Fixed: Silent Utc::now() timestamp fallback

  • Replaced .unwrap_or_else(|_| Utc::now()) with .map_err(|e| CommandError { code: "PARSE_ERROR", ... })? in proto_node_data_to_node. Malformed timestamps now surface as errors.

🟡 Important — Fixed: validate_node_type missing FailedPrecondition mapping

  • Added || s.code() == tonic::Code::FailedPrecondition alongside NotFound so both cases return SCHEMA_NOT_FOUND consistently.

🟢 Suggestion — Fixed: Vec::with_capacity in get_all_collections

  • Restored pre-allocation by capturing the response before iteration.

⏭️ 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.

create_node lifecycle_status non-atomic path: The Tauri layer always sends an empty string here so this path is never exercised. It's in daemon internals (node_service.rs) and is out of scope for this PR's migration work.


Build clean: cargo build -p nodespace-app ✅

@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

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 Findings

1. [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 — FIXED

The 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()` — FIXED

Both `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 — FIXED

The guard pattern now reads:

```rust
Err(s) if s.code() == tonic::Code::NotFound || s.code() == tonic::Code::FailedPrecondition
```

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` — FIXED

Pre-allocation is restored by materializing the response before iteration:

```rust
let collections = resp.into_inner().collections;
let mut result = Vec::with_capacity(collections.len());
for proto_info in collections { ... }
```

This is correct and idiomatic.


New Issues Introduced

None. 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

  • All 33 `#[tauri::command]` handlers proxy through gRPC
  • No direct `packages/core` ops invocations remain in the three migrated files
  • gRPC client initialized on Tauri startup and stored in `tauri::State`
  • All existing Tauri command return types preserved
  • Error cases propagate with appropriate codes
  • `cargo clippy -p nodespace-app` passes
  • Frontend tests pass (3918 tests per commit message)
  • `task_update_to_proto` encoding bug fixed — `update_task_node` no longer silently corrupts status/priority

Approved. Ready to merge.

@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.

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]>
@malibio
malibio force-pushed the worktree-issue-1113-grpc-proxy branch from c9f6c55 to 5fe81f9 Compare May 18, 2026 02:11
@malibio
malibio merged commit 22ff6cb into main May 18, 2026
@malibio
malibio deleted the worktree-issue-1113-grpc-proxy branch May 18, 2026 02:11
malibio pushed a commit that referenced this pull request May 18, 2026
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]>
malibio added a commit that referenced this pull request May 18, 2026
* 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]>
malibio pushed a commit that referenced this pull request May 18, 2026
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]>
malibio added a commit that referenced this pull request May 18, 2026
* 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]>
malibio pushed a commit that referenced this pull request May 18, 2026
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]>
malibio added a commit that referenced this pull request May 18, 2026
…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]>
malibio pushed a commit that referenced this pull request May 18, 2026
…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]>
malibio added a commit that referenced this pull request May 18, 2026
…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]>
malibio added a commit that referenced this pull request Jun 22, 2026
…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]>
malibio added a commit that referenced this pull request Jun 22, 2026
* 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]>
malibio added a commit that referenced this pull request Jun 22, 2026
* 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]>
malibio added a commit that referenced this pull request Jun 22, 2026
…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]>
malibio added a commit that referenced this pull request Jun 22, 2026
…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]>
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.

Migrate Tauri command handlers to thin gRPC proxy wrappers

1 participant