Skip to content

Integrate sqlite-vec for vector search (closes #1221) - #1224

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1221-sqlite-vec
May 28, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1221-sqlite-vec

Conversation

@malibio

@malibio malibio commented May 28, 2026

Copy link
Copy Markdown
Collaborator

Summary

Replaces the linear-scan embedding search (deferred from the SQLite migration #1219/#1222) with a statically-linked sqlite-vec vec0 virtual table queried via native KNN MATCH.

Correction to the issue framing: sqlite-vec's vec0 is a fast brute-force SIMD scan over a compact columnar store — not an HNSW/ANN index, so there is no O(log N) complexity change. The win is a compiled vectorized scan vs. the previous decode-f32-in-Rust loop.

Changes

  • Extension registration (SqliteStore::new / ensure_sqlite_vec_registered): register sqlite-vec as a SQLite auto-extension, once per process. libsql lazily runs sqlite3_config(SERIALIZED) on its first connect(), and sqlite3_config fails after SQLite init — so we warm up libsql first, then register, inside a single tokio::sync::OnceCell (avoids a concurrency race during new()).
  • Schema (initialize_schema): create vec_embeddings USING vec0(embedding_id TEXT PRIMARY KEY, vector FLOAT[768] distance_metric=cosine).
  • Sync (upsert_embeddings, delete_embeddings, mark_root_embedding_stale): keep vec_embeddings as a mirror of non-stale vectors only, all in transactions. Stale placeholder markers (create_stale_embedding_marker[_bulk]) are deliberately not mirrored so they never surface in KNN.
  • Search (search_embeddings, search_embeddings_by_node_type): rewritten to vec0 KNN + JOIN; similarity = 1 - distance; over-fetch k to cover enough distinct nodes after per-node grouping. Composite-score formula and EmbeddingSearchResult shape preserved exactly.
  • Deleted the now-unused cosine_similarity helper.
  • Added 5 unit tests (self-query, delete clears vec0, re-upsert replaces, stale exclusion, marker-never-in-KNN).

Approach: static linking (no shipped binaries)

A spike confirmed sqlite-vec 0.1.9 statically links and registers against libsql 0.6 via libsql::ffi::sqlite3_auto_extension — no per-platform .dylib/.so/.dll needs to be built or shipped.

Migration note (greenfield)

Per the no-backward-compat policy: there is no backfill. A pre-existing dev DB would have an empty vec_embeddings until re-embedding — delete the local dev .db if you have one. (The SQLite migration only just merged, so this is a non-issue in practice.)

Testing

  • cargo test -p nodespace-core — all targets green (1133 lib + integration suites incl. embedding_service_test).
  • cargo clippy -p nodespace-core --all-targets -- -D warnings — clean.
  • bun run test:all — frontend 3936, agent-tools 17, mcp 10, skill 13, Rust 1133; no new failures vs. baseline.

🤖 Generated with Claude Code

Replace the linear-scan embedding search with a statically-linked
sqlite-vec vec0 virtual table queried via native KNN MATCH.

- Register sqlite-vec as a SQLite auto-extension on the libsql connection
  (once per process; warm up libsql's SERIALIZED config first, then
  register, so the vec0 module is available).
- Mirror non-stale embedding vectors into a vec_embeddings vec0 table
  (distance_metric=cosine, FLOAT[768]); keep it in sync on upsert,
  delete, and mark-stale. Stale placeholder markers are deliberately
  excluded so they never surface in KNN results.
- Rewrite search_embeddings / search_embeddings_by_node_type to KNN +
  JOIN; preserve the composite-score formula and result shape. Delete
  the now-unused cosine_similarity helper.

Note: vec0 is a fast brute-force SIMD scan, not HNSW — the win is a
compiled vectorized scan vs decode-in-Rust, not lower complexity.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@malibio

malibio commented May 28, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1224 — Integrate sqlite-vec for vector search (closes #1221)

Review Type: Initial Review
Reviewer: Principal Engineer (Pragmatic Quality framework)
Verdict: COMMENT — net-positive change, builds clean, all 7 tests pass (5 new). Two behavioral notes worth a human decision before merge; no blockers.


Requirements Check (issue #1221)

  • ✅ Add sqlite-vec to workspace + packages/core Cargo.toml — done (0.1.9, statically linked).
  • ✅ Create vec_embeddings vec0 virtual table — done, with distance_metric=cosine and FLOAT[768] driven by DEFAULT_EMBEDDING_DIMENSION.
  • ✅ upsert_embeddings mirrors into vec0 — done, transactionally.
  • ✅ delete_embeddings clears vec0 — done, transactionally.
  • ✅ search_embeddings rewritten to vec0 KNN + JOIN, grouped by node with same composite-score formula — done; search_embeddings_by_node_type likewise.
  • 📝 The issue title/body assume vec0 gives "O(log N) HNSW". That premise is wrong — vec0 is a brute-force SIMD scan. The PR correctly does NOT claim HNSW and documents this in the commit and code comments. This is the right call; the win is a compiled vectorized scan vs decode-in-Rust, not lower asymptotic complexity. Not a defect.

Findings

🟡 Important

1. Density / matching_chunks semantics changed silently — affects ranking.
📁 packages/core/src/db/sqlite_store.rs:2299-2315 (and the typed variant ~2390)

In the old linear scan, every non-stale chunk of a node was loaded and matching_chunks (entry.1 += 1) counted all of the node's chunks, so density = matching_chunks/total_chunks was effectively ~1.0 and composite_score ≈ max_similarity * 1.3. With KNN, only chunks that land in the top-k are counted, so matching_chunks ≤ total_chunks and is now a genuine "fraction of chunks near the query" signal. This is arguably better, but it is a behavioral change to the composite score that the PR doesn't call out, and it interacts with finding #2: if KNN under-fetches a node's chunks, its density (and thus rank) is understated. Recommend either (a) documenting the intended new semantics, or (b) confirming downstream consumers/tests of score ranking aren't sensitive to the shift. Engineering principle: changes to a ranking formula's inputs are behavioral changes even when the formula text is unchanged.

2. Silent under-fetch is possible and undocumented for the typed variant.
📁 packages/core/src/db/sqlite_store.rs:2278 and 2358

k = limit * EMBEDDING_KNN_OVERFETCH (×10), and ×50 for the typed variant. The type filter (n.node_type = ?3) and stale = 0 are applied after KNN selects the global top-k. If the corpus is dominated by other node types, the requested type can be crowded out of the top-k and the query returns fewer (or zero) results even though matching nodes exist — a recall cliff, not an error. The over-fetch constants are a reasonable pragmatic mitigation, but the failure mode is invisible (no warning, no metric). Recommend a one-line doc note on the limitation and, ideally, a tracing::debug! when the post-filter survivor count is suspiciously low (e.g. < limit). Engineering principle: make silent degradation observable.

🟢 Suggestions

3. SAFETY comment is slightly inaccurate (the transmute is still sound).
📁 packages/core/src/db/sqlite_store.rs:88-96

The comment says sqlite_vec::sqlite3_vec_init "is the extension's C entry point with exactly this signature." The Rust-visible declaration in the sqlite-vec crate is actually extern "C" fn sqlite3_vec_init() (zero args) — the 3-arg EntryPoint is the true underlying C signature. The transmute-from-*const () is exactly the pattern the upstream crate itself uses, so it is correct, but the comment should say "the upstream Rust binding is declared fn(); we transmute its address to the real 3-arg SQLite entry-point signature" to avoid misleading a future reader. Nit-level precision only.

4. k is computed as i64 from limit * 10 (or *50) without an upper clamp.
📁 packages/core/src/db/sqlite_store.rs:2278, 2358

For normal limit values this is fine. A pathological caller passing a very large limit would push a large k into vec0. Not exploitable (input is internal, not user-controlled), but a .min(SOME_CAP) would be cheap defensive hygiene. Optional.

Nit: The two search methods are now near-identical (blob encode → KNN+JOIN → group → score → sort → truncate). DRY would suggest a shared private helper taking the SQL/params, but the divergence (extra JOIN, different over-fetch) is small enough that duplication is defensible. Optional.


What's done well (verified, not just asserted)

  • Init-ordering race is correctly fixed. ensure_sqlite_vec_registered warms libsql (so its lazy sqlite3_config(SERIALIZED) runs) then registers the auto-extension, both inside a single tokio::sync::OnceCell::get_or_init. The warm-up + registration are atomic within the closure, so concurrent new() calls cannot interleave — no TOCTOU. Confirmed runs exactly once per process before any real connection opens.
  • The vec0-only-holds-non-stale invariant is maintained on every path. upsert, delete, and mark_root_embedding_stale all delete from vec_embeddings via embedding_id IN (SELECT id FROM embedding WHERE node_id=?) before the embedding rows change — correct ordering. Stale markers (create_stale_embedding_marker[_bulk]) are deliberately NOT mirrored, with explanatory comments. Tests assert vec_row_count == 0 for stale/marker/delete cases — these assertions are meaningful and directly exercise the invariant.
  • Multi-statement writes are transactional. All three mutators wrap their two/three statements in db.transaction(); on early ? return the tx is dropped without commit → libsql rolls back. Correct.
  • 1 - distance → similarity is correct for distance_metric=cosine. Self-query test asserts max_similarity ≈ 1.0; orthogonal-axis test asserts non-match. Good determinism design via unit-axis vectors.
  • Dimension is correctly FLOAT[768] sourced from DEFAULT_EMBEDDING_DIMENSION (no hardcoded literal in the DDL).
  • cosine_similarity fully deleted; no dangling references in packages/core (the cosine_similarity in packages/nlp-engine/tests/integration_tests.rs is an unrelated local test helper).
  • Static linking works at runtime — the 5 new tests pass, proving the sqlite3_auto_extension registration makes vec0 available on real connections. No per-platform dylib shipping needed.
  • No project-standard violations: no #[allow(dead_code)], no lint suppression, no backward-compat cruft, uses tracing (no raw logging concern in Rust).

Recommendation: COMMENT

Net-positive, atomic, well-tested change that does what the issue asks and correctly avoids the issue's mistaken HNSW premise. No blockers. Before merge, a human should decide whether findings #1 (density semantics shift) and #2 (typed-search recall cliff under over-fetch) warrant a doc note / debug log now or a follow-up issue.

Reviewed by Claude Code (Opus 4.8) under the Pragmatic Quality framework.

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

Code Review: PR #1224 — Integrate sqlite-vec for vector search (closes #1221)

Review Type: Initial Review
Reviewer: Principal Engineer (Pragmatic Quality framework)
Verdict: COMMENT — net-positive change, builds clean, all 7 tests pass (5 new). Two behavioral notes worth a human decision before merge; no blockers.


Requirements Check (issue #1221)

  • ✅ Add sqlite-vec to workspace + packages/core Cargo.toml — done (0.1.9, statically linked).
  • ✅ Create vec_embeddings vec0 virtual table — done, with distance_metric=cosine and FLOAT[768] driven by DEFAULT_EMBEDDING_DIMENSION.
  • ✅ upsert_embeddings mirrors into vec0 — done, transactionally.
  • ✅ delete_embeddings clears vec0 — done, transactionally.
  • ✅ search_embeddings rewritten to vec0 KNN + JOIN, grouped by node with same composite-score formula — done; search_embeddings_by_node_type likewise.
  • 📝 The issue title/body assume vec0 gives "O(log N) HNSW". That premise is wrong — vec0 is a brute-force SIMD scan. The PR correctly does NOT claim HNSW and documents this in the commit and code comments. This is the right call; the win is a compiled vectorized scan vs decode-in-Rust, not lower asymptotic complexity. Not a defect.

Findings

🟡 Important

1. Density / matching_chunks semantics changed silently — affects ranking.
📁 packages/core/src/db/sqlite_store.rs:2299-2315 (and the typed variant ~2390)

In the old linear scan, every non-stale chunk of a node was loaded and matching_chunks (entry.1 += 1) counted all of the node's chunks, so density = matching_chunks/total_chunks was effectively ~1.0 and composite_score ≈ max_similarity * 1.3. With KNN, only chunks that land in the top-k are counted, so matching_chunks ≤ total_chunks and is now a genuine "fraction of chunks near the query" signal. This is arguably better, but it is a behavioral change to the composite score that the PR doesn't call out, and it interacts with finding #2: if KNN under-fetches a node's chunks, its density (and thus rank) is understated. Recommend either (a) documenting the intended new semantics, or (b) confirming downstream consumers/tests of score ranking aren't sensitive to the shift. Engineering principle: changes to a ranking formula's inputs are behavioral changes even when the formula text is unchanged.

2. Silent under-fetch is possible and undocumented for the typed variant.
📁 packages/core/src/db/sqlite_store.rs:2278 and 2358

k = limit * EMBEDDING_KNN_OVERFETCH (×10), and ×50 for the typed variant. The type filter (n.node_type = ?3) and stale = 0 are applied after KNN selects the global top-k. If the corpus is dominated by other node types, the requested type can be crowded out of the top-k and the query returns fewer (or zero) results even though matching nodes exist — a recall cliff, not an error. The over-fetch constants are a reasonable pragmatic mitigation, but the failure mode is invisible (no warning, no metric). Recommend a one-line doc note on the limitation and, ideally, a tracing::debug! when the post-filter survivor count is suspiciously low (e.g. < limit). Engineering principle: make silent degradation observable.

🟢 Suggestions

3. SAFETY comment is slightly inaccurate (the transmute is still sound).
📁 packages/core/src/db/sqlite_store.rs:88-96

The comment says sqlite_vec::sqlite3_vec_init "is the extension's C entry point with exactly this signature." The Rust-visible declaration in the sqlite-vec crate is actually extern "C" fn sqlite3_vec_init() (zero args) — the 3-arg EntryPoint is the true underlying C signature. The transmute-from-*const () is exactly the pattern the upstream crate itself uses, so it is correct, but the comment should say "the upstream Rust binding is declared fn(); we transmute its address to the real 3-arg SQLite entry-point signature" to avoid misleading a future reader. Nit-level precision only.

4. k is computed as i64 from limit * 10 (or *50) without an upper clamp.
📁 packages/core/src/db/sqlite_store.rs:2278, 2358

For normal limit values this is fine. A pathological caller passing a very large limit would push a large k into vec0. Not exploitable (input is internal, not user-controlled), but a .min(SOME_CAP) would be cheap defensive hygiene. Optional.

Nit: The two search methods are now near-identical (blob encode → KNN+JOIN → group → score → sort → truncate). DRY would suggest a shared private helper taking the SQL/params, but the divergence (extra JOIN, different over-fetch) is small enough that duplication is defensible. Optional.


What's done well (verified, not just asserted)

  • Init-ordering race is correctly fixed. ensure_sqlite_vec_registered warms libsql (so its lazy sqlite3_config(SERIALIZED) runs) then registers the auto-extension, both inside a single tokio::sync::OnceCell::get_or_init. The warm-up + registration are atomic within the closure, so concurrent new() calls cannot interleave — no TOCTOU. Confirmed runs exactly once per process before any real connection opens.
  • The vec0-only-holds-non-stale invariant is maintained on every path. upsert, delete, and mark_root_embedding_stale all delete from vec_embeddings via embedding_id IN (SELECT id FROM embedding WHERE node_id=?) before the embedding rows change — correct ordering. Stale markers (create_stale_embedding_marker[_bulk]) are deliberately NOT mirrored, with explanatory comments. Tests assert vec_row_count == 0 for stale/marker/delete cases — these assertions are meaningful and directly exercise the invariant.
  • Multi-statement writes are transactional. All three mutators wrap their two/three statements in db.transaction(); on early ? return the tx is dropped without commit → libsql rolls back. Correct.
  • 1 - distance → similarity is correct for distance_metric=cosine. Self-query test asserts max_similarity ≈ 1.0; orthogonal-axis test asserts non-match. Good determinism design via unit-axis vectors.
  • Dimension is correctly FLOAT[768] sourced from DEFAULT_EMBEDDING_DIMENSION (no hardcoded literal in the DDL).
  • cosine_similarity fully deleted; no dangling references in packages/core (the cosine_similarity in packages/nlp-engine/tests/integration_tests.rs is an unrelated local test helper).
  • Static linking works at runtime — the 5 new tests pass, proving the sqlite3_auto_extension registration makes vec0 available on real connections. No per-platform dylib shipping needed.
  • No project-standard violations: no #[allow(dead_code)], no lint suppression, no backward-compat cruft, uses tracing (no raw logging concern in Rust).

Recommendation: COMMENT

Net-positive, atomic, well-tested change that does what the issue asks and correctly avoids the issue's mistaken HNSW premise. No blockers. Before merge, a human should decide whether findings #1 (density semantics shift) and #2 (typed-search recall cliff under over-fetch) warrant a doc note / debug log now or a follow-up issue.

Reviewed by Claude Code (Opus 4.8) under the Pragmatic Quality framework.

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

Pragmatic code review posted as a PR comment above. Verdict: COMMENT (net-positive, no blockers; all 7 tests pass). Two items for human decision before merge: (1) density/matching_chunks ranking semantics shifted with KNN; (2) typed-search recall cliff when type filter is applied after global top-k. See the full report in the comment.

- Document that KNN changes `matching_chunks`/`density` semantics (now
  fraction of a node's chunks near the query, not ~1.0).
- Emit a tracing::debug! when typed search returns fewer than `limit`
  results so the post-KNN node_type filter's recall cliff is visible.
- Clarify the sqlite3_vec_init transmute SAFETY comment.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@malibio

malibio commented May 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed (commit b7eedcc)

Finding Severity Status
#1 — matching_chunks/density semantics changed under KNN 🟡 ✅ Documented in search_embeddings (density now = fraction of a node's chunks near the query; same composite formula)
#2 — Silent typed-search under-fetch / recall cliff 🟡 ✅ Added tracing::debug! when typed search returns < limit, noting EMBEDDING_KNN_OVERFETCH is the tuning lever
#3 — sqlite3_vec_init SAFETY comment accuracy 🟢 ✅ Clarified: the binding is declared zero-arg; we transmute to the real 3-arg C signature (the crate's own rusqlite pattern)
#4 — k upper clamp 🟢 ⏭️ Skipped — limit is already hard-capped at 1000 by the MCP search handler (test_search_rejects_limit_exceeds_max), so worst-case k is bounded (≤50k) and handled fine by vec0. A redundant in-function clamp would add an arbitrary magic number with no real benefit. The reviewer also flagged this as optional/non-exploitable.

Verification: 7 sqlite_store tests pass, cargo clippy --lib -D warnings clean, bun run test:all green (no new failures vs. baseline).

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: All changes are doc comments and one observability tracing::debug! line — no logic, control-flow, or query changes. Search behavior, the vec0 sync invariant, and result shapes are unchanged. Low-risk, straightforward edits.

🤖 Generated with Claude Code

@malibio
malibio merged commit d816f07 into main May 28, 2026
@malibio
malibio deleted the worktree-issue-1221-sqlite-vec branch May 28, 2026 22:20
malibio added a commit that referenced this pull request May 29, 2026
…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]>
malibio added a commit that referenced this pull request May 29, 2026
…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]>
malibio added a commit that referenced this pull request Jun 22, 2026
* Integrate sqlite-vec for vector search (closes #1221)

Replace the linear-scan embedding search with a statically-linked
sqlite-vec vec0 virtual table queried via native KNN MATCH.

- Register sqlite-vec as a SQLite auto-extension on the libsql connection
  (once per process; warm up libsql's SERIALIZED config first, then
  register, so the vec0 module is available).
- Mirror non-stale embedding vectors into a vec_embeddings vec0 table
  (distance_metric=cosine, FLOAT[768]); keep it in sync on upsert,
  delete, and mark-stale. Stale placeholder markers are deliberately
  excluded so they never surface in KNN results.
- Rewrite search_embeddings / search_embeddings_by_node_type to KNN +
  JOIN; preserve the composite-score formula and result shape. Delete
  the now-unused cosine_similarity helper.

Note: vec0 is a fast brute-force SIMD scan, not HNSW — the win is a
compiled vectorized scan vs decode-in-Rust, not lower complexity.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Address review: density-semantics doc, typed under-fetch debug log

- Document that KNN changes `matching_chunks`/`density` semantics (now
  fraction of a node's chunks near the query, not ~1.0).
- Emit a tracing::debug! when typed search returns fewer than `limit`
  results so the post-KNN node_type filter's recall cliff is visible.
- Clarify the sqlite3_vec_init transmute SAFETY comment.

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]>
malibio added a commit that referenced this pull request Jun 22, 2026
…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]>
malibio added a commit that referenced this pull request Jun 22, 2026
…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]>
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.

1 participant