Repository navigation
Migrate local DB from SurrealDB embedded to SQLite (libsql) - #1222
Conversation
…model cleanup ## Completed in This Session - [x] Phase 1: schema.sql created (3 tables: node, relationship, embedding + indexes) - [x] Phase 2: Cargo.toml updated — surrealdb removed, libsql kept as sole DB dep - [x] Phase 3: sqlite_store.rs written (~1700 lines, all 76 public methods implemented) - [x] Phase 3: db/mod.rs swapped to re-export SqliteStore as SurrealStore - [x] Phase 5 (partial): embedding.rs, task_node.rs, query_service/mod.rs surrealdb derives/impls removed ## Remaining Work - [ ] Fix remaining compile errors in query_service/mod.rs (execute_query_for_ids still uses .db() + RecordId) - [ ] Fix all 12 .db() bypass sites in node_service.rs (lines ~6382-11454) - [ ] Remove surrealdb imports/extract_record_key from node_service.rs - [ ] Delete surreal_store.rs and schema.surql - [ ] Remove 10MiB Tokio thread stack from main.rs - [ ] cargo build -p nodespace-core — must compile clean - [ ] cargo test -p nodespace-core - [ ] bun run test:all ## Current State - Files modified: schema.sql (new), sqlite_store.rs (new), mod.rs, embedding.rs, task_node.rs, query_service/mod.rs, Cargo.toml, core/Cargo.toml - Tests status: Not yet run (compile errors remain) - Known issues: query_service execute_query_for_ids still has .db() call + RecordId refs; node_service.rs has ~12 .db() bypass sites with surrealdb types; surreal_store.rs still present ## Context for Next Session SqliteStore is fully written with SQLite equivalents for all 76 public SurrealStore methods. The type-alias swap in db/mod.rs is in place. The remaining work is mechanical cleanup: rewrite execute_query_for_ids in query_service to use store.query_nodes, then fix each .db() bypass site in node_service.rs (each one needs to call a proper store method instead of reaching into the raw SurrealDB connection). After that, delete surreal_store.rs and schema.surql, fix main.rs, then build clean. ## Acceptance Criteria Status From issue #1219: - [ ] All local DB reads/writes use SQLite file - [ ] DB file is inspectable with DB Browser for SQLite - [ ] No SurrealDB/RocksDB dependency in core - [ ] All existing tests pass Co-Authored-By: Claude <[email protected]>
## Completed in This Session
- [x] Phase 4: Fixed all 12 .db() bypass sites in node_service.rs
- Added SqliteStore methods: check_relationship_exists, relationship_exists,
create_generic_relationship, get_relationship_id, delete_generic_relationship,
get_nodes_by_relationship, count_nodes_by_type, get_relationship_orders,
get_relationship_count, query_node_ids_raw
- Removed all surrealdb::types::{RecordId, SurrealValue} references
- Removed extract_record_key import and extract_record_id_string helper
- [x] Phase 5 (partial): query_service rewritten for SQLite
- resolve_field: dot-path → json_extract()
- Contains: CONTAINS/string::lowercase → INSTR/LOWER LIKE
- Exists: IS NOT NONE → IS NOT NULL
- In: [...] → (...)
- Relationship filters: node:⟨id⟩ → plain string IDs, in/out → in_node/out_node
- [x] Fixed PRAGMA journal_mode = WAL (uses query() not execute())
- [x] Fixed get_nodes_by_relationship column order (SELECT n.*)
- [x] Rewrote collection_membership_test.rs — all 32 tests pass with SqliteStore API
- [x] Fixed schema_hydration_test.rs — path fix for SQLite file vs directory
- [x] Fixed event_emission_test.rs — node: prefix in from_id/to_id assertions
- [x] Fixed bench/performance.rs — setup_test_store removed, setup_test_service
returns (Arc<SurrealStore>, Arc<NodeService>, TempDir); fixed on both branches
- [x] Filed issue #1221 for sqlite-vec HNSW follow-on
## Remaining Work
- [ ] Delete surreal_store.rs and schema.surql (dead code)
- [ ] Run quality:fix (1 unused_assignments warning in sqlite_store.rs:757)
- [ ] Run full test:all
- [ ] Create PR
## Current State
- Files modified: sqlite_store.rs, node_service.rs, query_service/mod.rs,
collection_membership_test.rs, event_emission_test.rs, schema_hydration_test.rs,
benches/performance.rs (both branches)
- Tests status: 1128+ unit tests passing, all integration tests passing
- Known issues: none blocking
- Performance: SQLite is 6-25× faster than SurrealDB across all benchmarks
## Context for Next Session
Migration from SurrealDB to SQLite is functionally complete. SurrealStore is now
a type alias for SqliteStore in db/mod.rs. Two cleanup tasks remain: delete the
old surreal_store.rs and schema.surql files, fix the one unused_assignments warning,
then run quality:fix and create the PR. Do NOT re-run startup sequence.
## Acceptance Criteria Status
From issue #1219:
- [x] SQLite file format (readable by sqlite3 / DB Browser)
- [x] All existing tests pass
- [x] No SurrealDB dependency in packages/core
- [x] Performance equal or better (confirmed: 6-25× faster)
- [ ] sqlite-vec HNSW search (tracked in #1221, deferred)
Co-Authored-By: Claude <[email protected]>
Replace SurrealDB/RocksDB with libsql SQLite for local embedded storage. Three-table schema (node, relationship, embedding) with WAL mode, FK cascade deletes, FTS5 full-text search, and sqlite-vec HNSW stubs. Delete surreal_store.rs (8k lines) and schema.surql; SqliteStore is now the single concrete DB implementation exported as SurrealStore for zero consumer changes. Also fix pre-existing clippy errors in nodespace-cli (PathBuf→Path, unused async) and Node 26 localStorage polyfill gap in test setup that was silently failing 93 tests. Co-Authored-By: Claude <[email protected]>
Code Review — PR #1222: Migrate local DB from SurrealDB to SQLite (libsql)SummaryThis is a well-executed, substantive migration. Deleting 8k lines of SurrealDB code and replacing with a clean, lean SQLite implementation is a net positive for the codebase. The schema design is sound, all acceptance criteria from #1219 are met (with sqlite-vec HNSW correctly deferred to #1221), and the test infrastructure cleanup (Node v26 localStorage polyfill) is a legitimate fix. The implementation is mergeable with two issues that require attention before merge. Findings[Critical/Blocker] —
|
malibio
left a comment
There was a problem hiding this comment.
Two issues require attention before merge: (1) incorrect SQLite escaping in query_service (backslash-escape is not valid SQL — use doubled single quotes), and (2) update_node_with_version_check leaves properties/title updates outside the version-checked transaction, breaking the OCC atomicity guarantee. Both are straightforward fixes. See the detailed comment for all findings.
escape_string used backslash escaping which SQLite doesn't recognize;
fix to standard single-quote doubling ('').
update_node_with_version_check split content/props/title/status across
separate statements after the version-checked UPDATE, breaking atomicity.
Consolidate all fields into a single UPDATE ... WHERE id=? AND version=?
statement so the entire update is one atomic operation.
Co-Authored-By: Claude <[email protected]>
Performance Benchmarks: SQLite (libsql) vs SurrealDB embeddedRun on the same machine back-to-back. Lower is better.
Across the board SQLite is significantly faster — 2–25× depending on operation. The heaviest wins are on read-heavy and update-heavy workloads where SurrealDB's graph engine overhead was most visible. |
Re-Review — PR #1222: Fix Commit
|
malibio
left a comment
There was a problem hiding this comment.
Both critical blockers are correctly fixed: SQL escaping now uses the standard SQLite double-single-quote form, and the OCC update is now a single atomic statement covering all fields. The three previously-noted improvements (bulk_update stale reads, get_collection_by_name content/title mismatch, stale SurrealQL doc comments) remain open but are not blocking. Approved — ready to merge.
…ollow-up) (#1225) * WIP: AI-Chat provider picker redesign + hydration fix (handoff) Follow-up to merged #1220. Turns the inert provider picker into a dropdown-driven, per-provider flow and fixes the real root cause of "clicking a provider does nothing". See .claude/HANDOFF-issue-1220-picker-redesign.md for the FULL context, decisions, and remaining work (read it first). ## Root cause found (via Playwright/WebKit live debugging) The picker persisted `provider` fine, but the viewer hydrates nodes from the `children-tree` endpoint, which returned `"properties": {}` — a #1222 (SurrealDB→libsql) regression: build_node_tree_recursive ran flatten_properties_for_api (drops props when the namespaced shape doesn't match) while every other endpoint returns raw props. Plus the ai-chat provider enum rejected the ADR-034 modes. ## Completed in this session - [x] Backend fix A: build_node_tree_recursive returns RAW properties (matches get_node/get_children/etc.). Regression test added. packages/core/src/services/node_service.rs - [x] Backend fix B: AiChatNodeBehavior::validate provider enum widened to native|ollama|openai|pty (ADR-034). Tests updated. packages/core/src/behaviors/mod.rs - [x] cargo test -p nodespace-core (behaviors + children-tree) green; daemon builds. - [x] tauri-commands.ts: added ChatModelEntry type + ollamaAvailable() wrapper; fixed chatModelList() return type (was wrongly ModelInfo[]). - [x] Renamed ai-chat-pty-view.svelte -> ai-chat-pty-session.svelte (naming: no *View/*Viewer suffix on helpers; AiChatNodeViewer is THE viewer). - [x] Added ai-chat-model-picker.svelte (native gguf + ollama model lists, download w/ progress, RAM-aware recommend). - [x] Stripped [DIAG] debug logs from ai-chat-node-viewer selectProvider. ## Remaining work (see HANDOFF doc for detail) - [ ] Move DisplayMessage -> packages/desktop-app/src/lib/components/chat/types.ts (architect-confirmed: it's a legit view-model; NOT in agent-types.ts/protocol boundary, NOT inside the .svelte). Repoint importers (viewer, chat-message, ai-chat-viewer.test). - [ ] Rewrite AiChatNodeViewer as the single dispatcher: header provider DROPDOWN (native / ollama[gray if !ollamaAvailable] / openai[disabled] / pty); route placeholder->dropdown, pty->ai-chat-pty-session, native|ollama w/o model-> ai-chat-model-picker, native|ollama w/ model->message UI. - [ ] Per-node send/stream (Option 1): the viewer owns its OWN session (localAgentNewSession/localAgentSend/streaming events/ensureModelReady using node.properties.provider+model), persists to node.properties.messages (ADR-028). NO shared store. - [ ] DELETE chatStore + ChatPanel (pre-ADR-034 ephemeral singleton; user: "no need to keep chatStore"). Remove: chat-store.svelte.ts, chat-panel.svelte, chat-store.test.ts; 'chat' tab type (navigation.ts), <ChatPanel> branch (pane-content.svelte:101), persistence guard (tab-persistence-service.ts); repoint "AI Chat" nav item to create/open a new ai-chat node. - [ ] Verify: cargo test -p nodespace-core; bun run test / test:all; quality:fix (NB: runs cargo fmt --all — revert stray reformats); Playwright e2e of the original bug (pick provider -> children-tree returns provider -> persists across reload); pty under tauri:dev only. ## Deferred to a SEPARATE follow-up issue - "AI Chat" sidebar item -> collapsible LIST of ai-chat nodes (like Collections). This PR only repoints it to create-a-node. - Typed canonical persisted-message schema owned by the ai-chat behavior + typed persisted<->DisplayMessage converters (replaces the untyped Record<string,unknown> mappers in the viewer — the real type-safety win). ## Current state - Branch: issue-1220-followup-provider-picker-conflict (== origin/main + this WIP; includes #1222 libsql + #1224 sqlite-vec). - Also carries the earlier skipConflictDetection fix in selectProvider (#1220 re-review follow-on) — intentional intentional-config-write guard. - Tests: Rust green; frontend NOT yet run against the new components (viewer rewrite pending — handleSend still references chatStore, will break build until the rewrite lands). - Dev env (this machine): daemon sidecar staged at target/debug/binaries/ *-aarch64-apple-darwin; old RocksDB daemon-db moved to daemon-db.surreal-bak-* (libsql needs a fresh DB); dev-tools @grpc deps installed; Playwright MCP set to --browser webkit. ## Key decisions (rationale in HANDOFF doc) - One inference engine (daemon) serves all ai-chat nodes via independent sessions. - Three message shapes kept distinct: ChatMessage (protocol), DisplayMessage (view-model), ADR-028 persisted JSON. Do NOT converge. - All providers (native/ollama/openai/pty) route through the daemon; never direct from the frontend. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Make AiChatNodeViewer the per-node dispatcher; delete chatStore/ChatPanel Completes the #1220 follow-up frontend integration on top of the backend fixes already on this branch (children-tree raw properties; provider enum widened to native|ollama|openai|pty). AiChatNodeViewer is now THE single dispatcher for the ai-chat type: - Header provider dropdown (Built-in / Ollama [grayed when not running] / OpenAI [disabled, no backend] / Agent terminal). - Routes on provider (+model): unset -> prompt; pty -> AiChatPtySession; native|ollama without model -> AiChatModelPicker; with model -> message UI. - Owns its OWN per-node daemon session (ensureModelReady -> localAgentNewSession -> localAgentSend + streaming/download/load event listeners), keyed off the node's provider/model. No shared store (Option 1, ADR-034). Persists to node.properties.messages with debounced flush + ADR-028 tool-result archival. - Hydration fallback: fetches the node by id on mount if absent from sharedNodeStore, so the dispatcher always has properties to route on (closes the root-cause class behind the original "picker does nothing"). DisplayMessage moved to components/chat/types.ts as the view-model type (architect-confirmed layering: protocol / view-model / persisted stay distinct). Importers repointed (chat-message, viewer, ai-chat-viewer.test). Deletions (pre-ADR-034 ephemeral singleton, no dual-mode per CLAUDE.md): chat-store.svelte.ts, chat-panel.svelte, chat-store.test.ts; the 'chat' tab type (navigation.ts), its <ChatPanel> branch (pane-content.svelte), persistence guard (tab-persistence-service.ts), and the dead chat-tab nav override (app-shell.svelte). "AI Chat" sidebar item commented out pending its rework into an expandable list of recent ai-chat nodes (follow-up issue). Incidental: the WIP's chatModelList() retype (ChatModelEntry[]) had broken its two consumers; retyped modelToAgent (agent-store) and added a ChatModelEntry -> ModelInfo adapter in model-store.refreshModels. Verified: svelte-check 0 errors; eslint clean; vitest 3913 passed / 129 files. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address review: exclude Ollama rows from model-store; robust progress placeholder Addresses 🟢 suggestions from the PR #1225 review. - model-store now manages only built-in (GGUF) models — its consumers (model-manager, ai-onboarding-dialog) download by URL and recommend a model to fetch. refreshModels() filters to backend === 'gguf', so Ollama rows (which carry no URL here and are surfaced separately by AiChatModelPicker) can no longer leak into the list. This removes the dead-download-button and un-downloadable-recommendedModel hazards in one move. (findings #1, #2) - chatEntryToModelInfo infers family from the id (gemma* -> gemma4) instead of always 'ministral', and no longer carries a now-dead 'ollama' branch. (#2) - ai-chat-node-viewer: the transient model-prep progress placeholder is now updated by id (renderProgress helper) to match its by-id removal, so it's order-independent rather than relying on positional slice(0,-1). (#3) Skipped: adding unit tests for archiveMessages/loadMessagesFromNode (#4) — these functions are already covered by the "Tool result archival" and "Write buffering" suites in ai-chat-viewer.test.ts; adding more would duplicate existing coverage. Verified: svelte-check 0 errors; eslint clean; vitest 3913 passed / 129 files. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…CP / SurrealDB / RocksDB from code and docs) (#1230) * Part A: purge dead HTTP MCP transport, SurrealStore alias, and surreal/rocksdb naming (#1226) Reconciles the code with two completed migrations (daemon-client ADR-031/032, SQLite/libsql #1222/#1224) that left dead code and stale naming behind. A1 — MCP transport vs. live handler library: - Extract the transport-agnostic library logic the agent/daemon/benches still use out of `core/src/mcp/handlers/` into normal core modules: * `core/src/markdown/` (convert/template/links/export + MarkdownError, replacing the MCPError dependency) * `core/src/schema/` (handle_create_schema / handle_update_schema) * `core/src/node_batch.rs` (batch get/update used by perf benches) * `core/src/agent_params.rs` (Search*Params used by the local agent) - Repoint agent (skill_pipeline, prompt_assembler, local_agent/tools), daemon (main, import_service), and benches to the new module paths. - Delete the dead HTTP/JSON-RPC transport entirely: the whole `core/src/mcp/` tree, `services/mcp_server_service.rs`, and `dev-tools/src/bin/dev-mcp.rs` (its only caller). The dev-tools Rust crate had no other source, so it's removed from the workspace (dev-proxy.ts is a standalone Bun script). - Delete the orphaned handler integration tests (mcp_handlers_integration_test, relationships_handler_test, search_handler_test). A2 — Drop the `SqliteStore as SurrealStore` compatibility alias and rename all 241 `SurrealStore` identifiers to `SqliteStore`. A3 — Proto consolidation: `packages/proto/proto/` is the single source (the only protos Rust compiles). Deleted the stale `packages/daemon/proto/` copy (its node_service.proto was missing the relationship events) and repointed the TS consumers (dev-proxy.ts, agent-tools/client.ts) to the canonical path. A4 — Cleanse all surreal/rocksdb naming residue from `.rs`/`.ts` comments, doc-comments, test fixtures, and string literals; obsolete "eventual consistency / write visibility" caveats (false under SQLite) reworded or removed. Deleted the stray nested check-dev-deps.ts that gated dev startup on a SurrealDB CLI binary. `grep -riE "surreal|rocksdb"` over .rs/.ts is now empty. Also fixes a latent SQLite-migration bug surfaced by the cleanup: CLI `diagnostics` sized the database by walking it as a RocksDB directory tree; SQLite is a single file, so it now sizes the file (plus -wal/-shm sidecars) or a directory. Tests: core 966 lib + 223 integration, agent 223 lib, daemon 36, cli 5, src-tauri 24, agent-tools 17, frontend 3913 — all green. (Live-Ollama integration tests require a running model and are excluded.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address review: remove stale MCP doc-comment references in relocated modules (#1226) Fixes the broken [`mcp`] rustdoc link in lib.rs and the residual 'MCP handler/tool/request' wording in the relocated markdown/schema modules and their tests — the MCP transport no longer exists; these are now plain core library functions. Comment-only; core builds green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address review: drop remaining MCP wording in schema/markdown doc-comments (#1226) Completes the review-nit sweep: the `# MCP Tool:` headings in schema/mod.rs and the residual 'MCP request/response/tool' comments in markdown/mod.rs are now phrased as plain library docs. Legitimate historical MCP references in error.rs/node_batch.rs/agent_params.rs (explaining the relocation) are kept. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
* WIP: Phases 1-3 complete — schema.sql + SqliteStore implementation + model cleanup ## Completed in This Session - [x] Phase 1: schema.sql created (3 tables: node, relationship, embedding + indexes) - [x] Phase 2: Cargo.toml updated — surrealdb removed, libsql kept as sole DB dep - [x] Phase 3: sqlite_store.rs written (~1700 lines, all 76 public methods implemented) - [x] Phase 3: db/mod.rs swapped to re-export SqliteStore as SurrealStore - [x] Phase 5 (partial): embedding.rs, task_node.rs, query_service/mod.rs surrealdb derives/impls removed ## Remaining Work - [ ] Fix remaining compile errors in query_service/mod.rs (execute_query_for_ids still uses .db() + RecordId) - [ ] Fix all 12 .db() bypass sites in node_service.rs (lines ~6382-11454) - [ ] Remove surrealdb imports/extract_record_key from node_service.rs - [ ] Delete surreal_store.rs and schema.surql - [ ] Remove 10MiB Tokio thread stack from main.rs - [ ] cargo build -p nodespace-core — must compile clean - [ ] cargo test -p nodespace-core - [ ] bun run test:all ## Current State - Files modified: schema.sql (new), sqlite_store.rs (new), mod.rs, embedding.rs, task_node.rs, query_service/mod.rs, Cargo.toml, core/Cargo.toml - Tests status: Not yet run (compile errors remain) - Known issues: query_service execute_query_for_ids still has .db() call + RecordId refs; node_service.rs has ~12 .db() bypass sites with surrealdb types; surreal_store.rs still present ## Context for Next Session SqliteStore is fully written with SQLite equivalents for all 76 public SurrealStore methods. The type-alias swap in db/mod.rs is in place. The remaining work is mechanical cleanup: rewrite execute_query_for_ids in query_service to use store.query_nodes, then fix each .db() bypass site in node_service.rs (each one needs to call a proper store method instead of reaching into the raw SurrealDB connection). After that, delete surreal_store.rs and schema.surql, fix main.rs, then build clean. ## Acceptance Criteria Status From issue #1219: - [ ] All local DB reads/writes use SQLite file - [ ] DB file is inspectable with DB Browser for SQLite - [ ] No SurrealDB/RocksDB dependency in core - [ ] All existing tests pass Co-Authored-By: Claude <[email protected]> * WIP: Phases 4-5 complete — all compile errors fixed, all tests passing ## Completed in This Session - [x] Phase 4: Fixed all 12 .db() bypass sites in node_service.rs - Added SqliteStore methods: check_relationship_exists, relationship_exists, create_generic_relationship, get_relationship_id, delete_generic_relationship, get_nodes_by_relationship, count_nodes_by_type, get_relationship_orders, get_relationship_count, query_node_ids_raw - Removed all surrealdb::types::{RecordId, SurrealValue} references - Removed extract_record_key import and extract_record_id_string helper - [x] Phase 5 (partial): query_service rewritten for SQLite - resolve_field: dot-path → json_extract() - Contains: CONTAINS/string::lowercase → INSTR/LOWER LIKE - Exists: IS NOT NONE → IS NOT NULL - In: [...] → (...) - Relationship filters: node:⟨id⟩ → plain string IDs, in/out → in_node/out_node - [x] Fixed PRAGMA journal_mode = WAL (uses query() not execute()) - [x] Fixed get_nodes_by_relationship column order (SELECT n.*) - [x] Rewrote collection_membership_test.rs — all 32 tests pass with SqliteStore API - [x] Fixed schema_hydration_test.rs — path fix for SQLite file vs directory - [x] Fixed event_emission_test.rs — node: prefix in from_id/to_id assertions - [x] Fixed bench/performance.rs — setup_test_store removed, setup_test_service returns (Arc<SurrealStore>, Arc<NodeService>, TempDir); fixed on both branches - [x] Filed issue #1221 for sqlite-vec HNSW follow-on ## Remaining Work - [ ] Delete surreal_store.rs and schema.surql (dead code) - [ ] Run quality:fix (1 unused_assignments warning in sqlite_store.rs:757) - [ ] Run full test:all - [ ] Create PR ## Current State - Files modified: sqlite_store.rs, node_service.rs, query_service/mod.rs, collection_membership_test.rs, event_emission_test.rs, schema_hydration_test.rs, benches/performance.rs (both branches) - Tests status: 1128+ unit tests passing, all integration tests passing - Known issues: none blocking - Performance: SQLite is 6-25× faster than SurrealDB across all benchmarks ## Context for Next Session Migration from SurrealDB to SQLite is functionally complete. SurrealStore is now a type alias for SqliteStore in db/mod.rs. Two cleanup tasks remain: delete the old surreal_store.rs and schema.surql files, fix the one unused_assignments warning, then run quality:fix and create the PR. Do NOT re-run startup sequence. ## Acceptance Criteria Status From issue #1219: - [x] SQLite file format (readable by sqlite3 / DB Browser) - [x] All existing tests pass - [x] No SurrealDB dependency in packages/core - [x] Performance equal or better (confirmed: 6-25× faster) - [ ] sqlite-vec HNSW search (tracked in #1221, deferred) Co-Authored-By: Claude <[email protected]> * Migrate local DB from SurrealDB to SQLite (libsql) (closes #1219) Replace SurrealDB/RocksDB with libsql SQLite for local embedded storage. Three-table schema (node, relationship, embedding) with WAL mode, FK cascade deletes, FTS5 full-text search, and sqlite-vec HNSW stubs. Delete surreal_store.rs (8k lines) and schema.surql; SqliteStore is now the single concrete DB implementation exported as SurrealStore for zero consumer changes. Also fix pre-existing clippy errors in nodespace-cli (PathBuf→Path, unused async) and Node 26 localStorage polyfill gap in test setup that was silently failing 93 tests. Co-Authored-By: Claude <[email protected]> * Fix SQL escape bug and OCC atomicity in sqlite_store escape_string used backslash escaping which SQLite doesn't recognize; fix to standard single-quote doubling (''). update_node_with_version_check split content/props/title/status across separate statements after the version-checked UPDATE, breaking atomicity. Consolidate all fields into a single UPDATE ... WHERE id=? AND version=? statement so the entire update is one atomic operation. Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude <[email protected]>
…ollow-up) (#1225) * WIP: AI-Chat provider picker redesign + hydration fix (handoff) Follow-up to merged #1220. Turns the inert provider picker into a dropdown-driven, per-provider flow and fixes the real root cause of "clicking a provider does nothing". See .claude/HANDOFF-issue-1220-picker-redesign.md for the FULL context, decisions, and remaining work (read it first). ## Root cause found (via Playwright/WebKit live debugging) The picker persisted `provider` fine, but the viewer hydrates nodes from the `children-tree` endpoint, which returned `"properties": {}` — a #1222 (SurrealDB→libsql) regression: build_node_tree_recursive ran flatten_properties_for_api (drops props when the namespaced shape doesn't match) while every other endpoint returns raw props. Plus the ai-chat provider enum rejected the ADR-034 modes. ## Completed in this session - [x] Backend fix A: build_node_tree_recursive returns RAW properties (matches get_node/get_children/etc.). Regression test added. packages/core/src/services/node_service.rs - [x] Backend fix B: AiChatNodeBehavior::validate provider enum widened to native|ollama|openai|pty (ADR-034). Tests updated. packages/core/src/behaviors/mod.rs - [x] cargo test -p nodespace-core (behaviors + children-tree) green; daemon builds. - [x] tauri-commands.ts: added ChatModelEntry type + ollamaAvailable() wrapper; fixed chatModelList() return type (was wrongly ModelInfo[]). - [x] Renamed ai-chat-pty-view.svelte -> ai-chat-pty-session.svelte (naming: no *View/*Viewer suffix on helpers; AiChatNodeViewer is THE viewer). - [x] Added ai-chat-model-picker.svelte (native gguf + ollama model lists, download w/ progress, RAM-aware recommend). - [x] Stripped [DIAG] debug logs from ai-chat-node-viewer selectProvider. ## Remaining work (see HANDOFF doc for detail) - [ ] Move DisplayMessage -> packages/desktop-app/src/lib/components/chat/types.ts (architect-confirmed: it's a legit view-model; NOT in agent-types.ts/protocol boundary, NOT inside the .svelte). Repoint importers (viewer, chat-message, ai-chat-viewer.test). - [ ] Rewrite AiChatNodeViewer as the single dispatcher: header provider DROPDOWN (native / ollama[gray if !ollamaAvailable] / openai[disabled] / pty); route placeholder->dropdown, pty->ai-chat-pty-session, native|ollama w/o model-> ai-chat-model-picker, native|ollama w/ model->message UI. - [ ] Per-node send/stream (Option 1): the viewer owns its OWN session (localAgentNewSession/localAgentSend/streaming events/ensureModelReady using node.properties.provider+model), persists to node.properties.messages (ADR-028). NO shared store. - [ ] DELETE chatStore + ChatPanel (pre-ADR-034 ephemeral singleton; user: "no need to keep chatStore"). Remove: chat-store.svelte.ts, chat-panel.svelte, chat-store.test.ts; 'chat' tab type (navigation.ts), <ChatPanel> branch (pane-content.svelte:101), persistence guard (tab-persistence-service.ts); repoint "AI Chat" nav item to create/open a new ai-chat node. - [ ] Verify: cargo test -p nodespace-core; bun run test / test:all; quality:fix (NB: runs cargo fmt --all — revert stray reformats); Playwright e2e of the original bug (pick provider -> children-tree returns provider -> persists across reload); pty under tauri:dev only. ## Deferred to a SEPARATE follow-up issue - "AI Chat" sidebar item -> collapsible LIST of ai-chat nodes (like Collections). This PR only repoints it to create-a-node. - Typed canonical persisted-message schema owned by the ai-chat behavior + typed persisted<->DisplayMessage converters (replaces the untyped Record<string,unknown> mappers in the viewer — the real type-safety win). ## Current state - Branch: issue-1220-followup-provider-picker-conflict (== origin/main + this WIP; includes #1222 libsql + #1224 sqlite-vec). - Also carries the earlier skipConflictDetection fix in selectProvider (#1220 re-review follow-on) — intentional intentional-config-write guard. - Tests: Rust green; frontend NOT yet run against the new components (viewer rewrite pending — handleSend still references chatStore, will break build until the rewrite lands). - Dev env (this machine): daemon sidecar staged at target/debug/binaries/ *-aarch64-apple-darwin; old RocksDB daemon-db moved to daemon-db.surreal-bak-* (libsql needs a fresh DB); dev-tools @grpc deps installed; Playwright MCP set to --browser webkit. ## Key decisions (rationale in HANDOFF doc) - One inference engine (daemon) serves all ai-chat nodes via independent sessions. - Three message shapes kept distinct: ChatMessage (protocol), DisplayMessage (view-model), ADR-028 persisted JSON. Do NOT converge. - All providers (native/ollama/openai/pty) route through the daemon; never direct from the frontend. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Make AiChatNodeViewer the per-node dispatcher; delete chatStore/ChatPanel Completes the #1220 follow-up frontend integration on top of the backend fixes already on this branch (children-tree raw properties; provider enum widened to native|ollama|openai|pty). AiChatNodeViewer is now THE single dispatcher for the ai-chat type: - Header provider dropdown (Built-in / Ollama [grayed when not running] / OpenAI [disabled, no backend] / Agent terminal). - Routes on provider (+model): unset -> prompt; pty -> AiChatPtySession; native|ollama without model -> AiChatModelPicker; with model -> message UI. - Owns its OWN per-node daemon session (ensureModelReady -> localAgentNewSession -> localAgentSend + streaming/download/load event listeners), keyed off the node's provider/model. No shared store (Option 1, ADR-034). Persists to node.properties.messages with debounced flush + ADR-028 tool-result archival. - Hydration fallback: fetches the node by id on mount if absent from sharedNodeStore, so the dispatcher always has properties to route on (closes the root-cause class behind the original "picker does nothing"). DisplayMessage moved to components/chat/types.ts as the view-model type (architect-confirmed layering: protocol / view-model / persisted stay distinct). Importers repointed (chat-message, viewer, ai-chat-viewer.test). Deletions (pre-ADR-034 ephemeral singleton, no dual-mode per CLAUDE.md): chat-store.svelte.ts, chat-panel.svelte, chat-store.test.ts; the 'chat' tab type (navigation.ts), its <ChatPanel> branch (pane-content.svelte), persistence guard (tab-persistence-service.ts), and the dead chat-tab nav override (app-shell.svelte). "AI Chat" sidebar item commented out pending its rework into an expandable list of recent ai-chat nodes (follow-up issue). Incidental: the WIP's chatModelList() retype (ChatModelEntry[]) had broken its two consumers; retyped modelToAgent (agent-store) and added a ChatModelEntry -> ModelInfo adapter in model-store.refreshModels. Verified: svelte-check 0 errors; eslint clean; vitest 3913 passed / 129 files. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address review: exclude Ollama rows from model-store; robust progress placeholder Addresses 🟢 suggestions from the PR #1225 review. - model-store now manages only built-in (GGUF) models — its consumers (model-manager, ai-onboarding-dialog) download by URL and recommend a model to fetch. refreshModels() filters to backend === 'gguf', so Ollama rows (which carry no URL here and are surfaced separately by AiChatModelPicker) can no longer leak into the list. This removes the dead-download-button and un-downloadable-recommendedModel hazards in one move. (findings #1, #2) - chatEntryToModelInfo infers family from the id (gemma* -> gemma4) instead of always 'ministral', and no longer carries a now-dead 'ollama' branch. (#2) - ai-chat-node-viewer: the transient model-prep progress placeholder is now updated by id (renderProgress helper) to match its by-id removal, so it's order-independent rather than relying on positional slice(0,-1). (#3) Skipped: adding unit tests for archiveMessages/loadMessagesFromNode (#4) — these functions are already covered by the "Tool result archival" and "Write buffering" suites in ai-chat-viewer.test.ts; adding more would duplicate existing coverage. Verified: svelte-check 0 errors; eslint clean; vitest 3913 passed / 129 files. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…CP / SurrealDB / RocksDB from code and docs) (#1230) * Part A: purge dead HTTP MCP transport, SurrealStore alias, and surreal/rocksdb naming (#1226) Reconciles the code with two completed migrations (daemon-client ADR-031/032, SQLite/libsql #1222/#1224) that left dead code and stale naming behind. A1 — MCP transport vs. live handler library: - Extract the transport-agnostic library logic the agent/daemon/benches still use out of `core/src/mcp/handlers/` into normal core modules: * `core/src/markdown/` (convert/template/links/export + MarkdownError, replacing the MCPError dependency) * `core/src/schema/` (handle_create_schema / handle_update_schema) * `core/src/node_batch.rs` (batch get/update used by perf benches) * `core/src/agent_params.rs` (Search*Params used by the local agent) - Repoint agent (skill_pipeline, prompt_assembler, local_agent/tools), daemon (main, import_service), and benches to the new module paths. - Delete the dead HTTP/JSON-RPC transport entirely: the whole `core/src/mcp/` tree, `services/mcp_server_service.rs`, and `dev-tools/src/bin/dev-mcp.rs` (its only caller). The dev-tools Rust crate had no other source, so it's removed from the workspace (dev-proxy.ts is a standalone Bun script). - Delete the orphaned handler integration tests (mcp_handlers_integration_test, relationships_handler_test, search_handler_test). A2 — Drop the `SqliteStore as SurrealStore` compatibility alias and rename all 241 `SurrealStore` identifiers to `SqliteStore`. A3 — Proto consolidation: `packages/proto/proto/` is the single source (the only protos Rust compiles). Deleted the stale `packages/daemon/proto/` copy (its node_service.proto was missing the relationship events) and repointed the TS consumers (dev-proxy.ts, agent-tools/client.ts) to the canonical path. A4 — Cleanse all surreal/rocksdb naming residue from `.rs`/`.ts` comments, doc-comments, test fixtures, and string literals; obsolete "eventual consistency / write visibility" caveats (false under SQLite) reworded or removed. Deleted the stray nested check-dev-deps.ts that gated dev startup on a SurrealDB CLI binary. `grep -riE "surreal|rocksdb"` over .rs/.ts is now empty. Also fixes a latent SQLite-migration bug surfaced by the cleanup: CLI `diagnostics` sized the database by walking it as a RocksDB directory tree; SQLite is a single file, so it now sizes the file (plus -wal/-shm sidecars) or a directory. Tests: core 966 lib + 223 integration, agent 223 lib, daemon 36, cli 5, src-tauri 24, agent-tools 17, frontend 3913 — all green. (Live-Ollama integration tests require a running model and are excluded.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address review: remove stale MCP doc-comment references in relocated modules (#1226) Fixes the broken [`mcp`] rustdoc link in lib.rs and the residual 'MCP handler/tool/request' wording in the relocated markdown/schema modules and their tests — the MCP transport no longer exists; these are now plain core library functions. Comment-only; core builds green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address review: drop remaining MCP wording in schema/markdown doc-comments (#1226) Completes the review-nit sweep: the `# MCP Tool:` headings in schema/mod.rs and the residual 'MCP request/response/tool' comments in markdown/mod.rs are now phrased as plain library docs. Legitimate historical MCP references in error.rs/node_batch.rs/agent_params.rs (explaining the relocation) are kept. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
libsqlSQLite for all local data operationssurreal_store.rs(8,287 lines) andschema.surql; newsqlite_store.rs(1,600 lines) implements the same interface exported asSurrealStorefor zero consumer-side changesnode,relationship,embedding) with WAL mode, FK cascade deletes, FTS5 full-text search, and sqlite-vec HNSW stubs (full HNSW implementation tracked in Integrate sqlite-vec for HNSW vector search (follow-on to #1219) #1221)Also fixes pre-existing issues found during quality pass:
nodespace-cli:PathBuf→Pathin function signatures, remove unusedasyncfromuninstall::runpackages/desktop-apptest setup: localStorage polyfill now applies whenlocalStorageisundefined(Node v26 regression that silently failed 93 tests)Acceptance Criteria
sqlite3CLI can open the libsql-created SQLite fileget_children, ancestor path) viaWITH RECURSIVETest plan
bun run test:all— 3,936 frontend + 1,128 Rust, 0 failuresbun run quality:fix— zero warnings/errors across all packages~/.nodespace/database/nodespace.dbin DB Browser for SQLite and confirm tables are visible🤖 Generated with Claude Code