> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch28-memory-system/28.2-vector-memory-search.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 28.2 Vector Memory Search

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~320k tokens, Output \~8k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In the previous section, we learned about the memory system's file layout and chunking mechanism—Markdown files are split into text blocks (Chunks) awaiting indexing. But what does "indexing" actually mean? How can the Agent find relevant memories based on the user's natural language question?

The answer is **vector search**: converting text blocks into high-dimensional vectors (embeddings), then finding semantically closest results through cosine similarity. This section deeply analyzes OpenClaw's embedding engine, multi-provider architecture, SQLite storage scheme, and sqlite-vec vector acceleration.

***

## 28.2.1 Embeddings Engine

### What are Embeddings?

> **Sidebar**: An embedding is a technique that maps text to a high-dimensional array of floating-point numbers. For example, the sentence "I like TypeScript" might be mapped to a 1536-dimensional vector `[0.023, -0.017, 0.041, ...]`. Semantically similar texts are closer in vector space—"I like TypeScript" and "TypeScript is my preferred language" have a small angle between their vectors, while "The weather is nice today" has a large angle. By computing the **cosine similarity** between vectors, we can quantify the semantic relevance of two text segments.

OpenClaw's embedding engine is defined in `src/memory/embeddings.ts`, with the core interface being `EmbeddingProvider`:

```typescript
// src/memory/embeddings.ts

export type EmbeddingProvider = {
  id: string;                                      // Provider identifier: "openai" | "gemini" | "voyage" | "local"
  model: string;                                   // Model name, e.g., "text-embedding-3-small"
  embedQuery: (text: string) => Promise<number[]>;  // Convert single text to vector
  embedBatch: (texts: string[]) => Promise<number[][]>; // Batch conversion
};
```

This is a classic **Strategy Pattern**—all embedding providers implement the same interface, and the system decides at runtime which one to use. `embedQuery` is used during search to convert user queries to vectors, while `embedBatch` is used during indexing to batch-process text chunks.

### Provider Selection Flow

`createEmbeddingProvider()` is the entry point of the embedding engine. It decides which provider to use based on configuration and implements two fault-tolerance mechanisms: **auto-detection** and **fallback**:

```typescript
// src/memory/embeddings.ts (simplified)

export async function createEmbeddingProvider(
  options: EmbeddingProviderOptions,
): Promise<EmbeddingProviderResult> {
  const requestedProvider = options.provider; // "auto" | "openai" | "gemini" | "voyage" | "local"
  const fallback = options.fallback;

  if (requestedProvider === "auto") {
    // 1. Try local first (if model file exists on disk)
    if (canAutoSelectLocal(options)) {
      try { return await createProvider("local"); }
      catch (err) { localError = formatLocalSetupError(err); }
    }
    // 2. Try remote providers in sequence: openai → gemini → voyage
    for (const provider of ["openai", "gemini", "voyage"] as const) {
      try { return await createProvider(provider); }
      catch (err) {
        if (isMissingApiKeyError(err)) continue; // No API Key, skip
        throw err;                                 // Other errors, throw immediately
      }
    }
    throw new Error("No embeddings provider available.");
  }

  // Non-auto mode: create specified provider, try fallback on failure
  try {
    return await createProvider(requestedProvider);
  } catch (primaryErr) {
    if (fallback && fallback !== "none") {
      return await createProvider(fallback); // Record fallbackFrom and fallbackReason
    }
    throw primaryErr;
  }
}
```

Represented as a flowchart:

```
                   ┌─────────────┐
                   │ provider=?  │
                   └──────┬──────┘
                          │
               ┌──────────┴──────────┐
               │                     │
          provider="auto"      provider=specific
               │                     │
     ┌─────────▼─────────┐    ┌─────▼──────┐
     │ Local model file   │    │ Create      │
     │ exists?            │    │ specified   │
     │ canAutoSelectLocal │    │ provider    │
     └────┬─────────┬────┘    └──┬──────┬──┘
          │YES      │NO          │OK    │fail
     ┌────▼────┐    │            │    ┌──▼──────┐
     │ Try      │    │            │    │ fallback │
     │ local    │    │            │    │ provider │
     └──┬───┬──┘    │            │    └─────────┘
        │   │fail   │            │
        │OK ▼       │            │
        │  ┌────────▼──────────┐ │
        │  │ openai→gemini→    │ │
        │  │ voyage in sequence│ │
        │  └───────────────────┘ │
        │                        │
        └────────────────────────┘
                 Return EmbeddingProviderResult
```

The logic of `canAutoSelectLocal` is worth noting—it returns `true` **only when the local model file actually exists on disk**, excluding remote URLs or Hugging Face Hub paths (`hf:` prefix):

```typescript
// src/memory/embeddings.ts

function canAutoSelectLocal(options: EmbeddingProviderOptions): boolean {
  const modelPath = options.local?.modelPath?.trim();
  if (!modelPath) return false;
  if (/^(hf:|https?:)/i.test(modelPath)) return false; // Remote paths not auto-selected
  const resolved = resolveUserPath(modelPath);
  return fsSync.statSync(resolved).isFile();             // File must exist
}
```

This avoids blocking startup in auto mode due to downloading large models.

### Vector Normalization

All locally-generated embedding vectors are **normalized** before being returned:

```typescript
// src/memory/embeddings.ts

function sanitizeAndNormalizeEmbedding(vec: number[]): number[] {
  const sanitized = vec.map(v => Number.isFinite(v) ? v : 0); // Clean NaN/Infinity
  const magnitude = Math.sqrt(sanitized.reduce((sum, v) => sum + v * v, 0));
  if (magnitude < 1e-10) return sanitized; // Zero vector not processed
  return sanitized.map(v => v / magnitude); // L2 normalization
}
```

> **Sidebar**: L2 normalization scales a vector to unit length (magnitude 1). After normalization, cosine similarity is equivalent to vector dot product, which is more efficient to compute. Additionally, normalization ensures vectors from different text chunks are compared on the same "scale", avoiding bias from differences in vector magnitude.

***

## 28.2.2 Multi-Embedding Provider Support

OpenClaw supports four embedding providers, covering the complete spectrum from cloud to local.

### Provider Comparison

| Provider   | Default Model            | Dimensions       | Location | API Key          | Features                                          |
| ---------- | ------------------------ | ---------------- | -------- | ---------------- | ------------------------------------------------- |
| **OpenAI** | `text-embedding-3-small` | 1536             | Cloud    | `OPENAI_API_KEY` | Most widely used, stable quality                  |
| **Gemini** | `gemini-embedding-001`   | 768              | Cloud    | `GOOGLE_API_KEY` | Supports `taskType` to distinguish query/document |
| **Voyage** | `voyage-4-large`         | 1024             | Cloud    | `VOYAGE_API_KEY` | Focused on retrieval, supports `input_type`       |
| **Local**  | `embeddinggemma-300M`    | Depends on model | Local    | None required    | Completely offline, privacy-first                 |

### OpenAI Provider

OpenAI's implementation is the simplest—standard REST API calls:

```typescript
// src/memory/embeddings-openai.ts (simplified)

export const DEFAULT_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";

async function createOpenAiEmbeddingProvider(options) {
  const client = await resolveOpenAiEmbeddingClient(options);
  const url = `${client.baseUrl}/embeddings`;

  const embed = async (input: string[]): Promise<number[][]> => {
    const res = await fetch(url, {
      method: "POST",
      headers: client.headers, // Authorization: Bearer ${apiKey}
      body: JSON.stringify({ model: client.model, input }),
    });
    const payload = await res.json();
    return payload.data.map(entry => entry.embedding ?? []);
  };

  return {
    provider: {
      id: "openai",
      model: client.model,
      embedQuery: async (text) => (await embed([text]))[0] ?? [],
      embedBatch: embed, // Native batch support
    },
    client,
  };
}
```

`embedQuery` and `embedBatch` share the same `embed` function—OpenAI's `/embeddings` endpoint naturally supports multiple text inputs, with a single query being just a special case where the `input` array has length 1.

### Gemini Provider

Gemini's implementation has two notable differences:

1. **Separate query/document endpoints**: Gemini provides `embedContent` (single) and `batchEmbedContents` (batch) APIs, distinguishing usage through the `taskType` field—`RETRIEVAL_QUERY` for queries, `RETRIEVAL_DOCUMENT` for documents.
2. **Model path format**: Gemini API requires a `models/` prefix (e.g., `models/gemini-embedding-001`), with specialized `buildGeminiModelPath` handling in the code.

```typescript
// src/memory/embeddings-gemini.ts (simplified)

const embedUrl = `${baseUrl}/${modelPath}:embedContent`;
const batchUrl = `${baseUrl}/${modelPath}:batchEmbedContents`;

// Query embedding
const embedQuery = async (text: string): Promise<number[]> => {
  const res = await fetch(embedUrl, {
    headers: client.headers, // x-goog-api-key: ${apiKey}
    body: JSON.stringify({
      content: { parts: [{ text }] },
      taskType: "RETRIEVAL_QUERY",   // ← Query type
    }),
  });
  return (await res.json()).embedding?.values ?? [];
};

// Batch document embedding
const embedBatch = async (texts: string[]): Promise<number[][]> => {
  const requests = texts.map(text => ({
    model: modelPath,
    content: { parts: [{ text }] },
    taskType: "RETRIEVAL_DOCUMENT",  // ← Document type
  }));
  const res = await fetch(batchUrl, {
    body: JSON.stringify({ requests }),
  });
  return (await res.json()).embeddings.map(e => e.values ?? []);
};
```

> **Sidebar**: The difference between `RETRIEVAL_QUERY` and `RETRIEVAL_DOCUMENT` lies in how the embedding model internally processes text. Queries are typically shorter and express "information needs", while documents are longer and contain "information content". This asymmetric embedding improves retrieval accuracy—the model optimizes vector representation separately for queries and documents.

### Voyage Provider

Voyage AI focuses on retrieval scenarios, with an API similar to OpenAI but distinguishing queries and documents through the `input_type` field:

```typescript
// src/memory/embeddings-voyage.ts (simplified)

export const DEFAULT_VOYAGE_EMBEDDING_MODEL = "voyage-4-large";

const embed = async (input: string[], input_type?: "query" | "document") => {
  const body = { model: client.model, input };
  if (input_type) body.input_type = input_type;
  const res = await fetch(url, { body: JSON.stringify(body) });
  return (await res.json()).data.map(entry => entry.embedding ?? []);
};

return {
  provider: {
    id: "voyage",
    model: client.model,
    embedQuery: async (text) => (await embed([text], "query"))[0],   // ← query
    embedBatch: async (texts) => embed(texts, "document"),            // ← document
  },
};
```

### Local Provider (node-llama-cpp)

The local provider is the most unique—it runs a small embedding model on the user's machine, requiring no network at all. It defaults to Google's `embeddinggemma-300M` (GGUF quantized format, \~300MB):

```typescript
// src/memory/embeddings.ts (simplified)

const DEFAULT_LOCAL_MODEL =
  "hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf";

async function createLocalEmbeddingProvider(options) {
  const modelPath = options.local?.modelPath || DEFAULT_LOCAL_MODEL;
  const { getLlama, resolveModelFile, LlamaLogLevel } = await importNodeLlamaCpp();

  let llama, embeddingModel, embeddingContext; // Lazy initialization

  const ensureContext = async () => {
    if (!llama)
      llama = await getLlama({ logLevel: LlamaLogLevel.error });
    if (!embeddingModel) {
      const resolved = await resolveModelFile(modelPath); // Auto-download from HF Hub on first use
      embeddingModel = await llama.loadModel({ modelPath: resolved });
    }
    if (!embeddingContext)
      embeddingContext = await embeddingModel.createEmbeddingContext();
    return embeddingContext;
  };

  return {
    id: "local",
    model: modelPath,
    embedQuery: async (text) => {
      const ctx = await ensureContext();
      const embedding = await ctx.getEmbeddingFor(text);
      return sanitizeAndNormalizeEmbedding(Array.from(embedding.vector));
    },
    embedBatch: async (texts) => {
      // Process each text individually, normalize each result
      return Promise.all(texts.map(async text => {
        const ctx = await ensureContext();
        const embedding = await ctx.getEmbeddingFor(text);
        return sanitizeAndNormalizeEmbedding(Array.from(embedding.vector));
      }));
    },
  };
}
```

Several key design decisions:

1. **Lazy Loading**: `node-llama-cpp` is an optional dependency, loaded dynamically via `import()`, avoiding startup failure if not installed.
2. **Model file resolution**: `resolveModelFile` supports local paths and `hf:` Hub links, auto-downloading to cache on first use.
3. **Serial Batch**: The local model's `embedBatch` actually calls `getEmbeddingFor` sequentially—because local inference is limited by CPU/GPU resources, parallelism can't scale like cloud APIs.

### API Key Resolution

All cloud providers share a unified API Key resolution flow. Using OpenAI as an example:

```typescript
// src/memory/embeddings-openai.ts (simplified)

const apiKey = remoteApiKey               // 1. Key passed from remote config (e.g., MCP server)
  ? remoteApiKey
  : requireApiKey(
      await resolveApiKeyForProvider({    // 2. Resolve from global config + environment variables
        provider: "openai",
        cfg: options.config,
        agentDir: options.agentDir,
      }),
      "openai",
    );
```

Three-tier priority: remote passed > config file > environment variable (`OPENAI_API_KEY`). If none are found, `requireApiKey` throws "No API key found for provider openai"—in auto mode this exception is caught and that provider is skipped.

***

## 28.2.3 SQLite Storage

### Why SQLite?

OpenClaw's memory index is stored in a SQLite database. For a CLI tool, SQLite is the ideal choice:

* **Zero-server**: No need to start a database server, single file is the entire database
* **In-process**: Directly embedded in Node.js process, accessed via `node:sqlite` module (natively supported in Node.js 22+)
* **Transaction safety**: ACID guarantees, index won't be corrupted even if process crashes
* **Extensibility**: Can load extensions like `sqlite-vec` to implement vector search

> **Sidebar**: Starting from version 22, Node.js includes the `node:sqlite` module (experimental), providing a synchronous API (`DatabaseSync`) to directly operate SQLite databases. This means no need for third-party native modules like `better-sqlite3`, reducing installation and compatibility issues. OpenClaw wraps this built-in module through the `requireNodeSqlite()` function.

### Schema Design

The `ensureMemoryIndexSchema()` function defines the complete database structure:

```typescript
// src/memory/memory-schema.ts (simplified)

export function ensureMemoryIndexSchema(params: {
  db: DatabaseSync;
  embeddingCacheTable: string;  // Default "embedding_cache"
  ftsTable: string;             // Default "chunks_fts"
  ftsEnabled: boolean;
}): { ftsAvailable: boolean; ftsError?: string } {

  // 1. Metadata table
  params.db.exec(`
    CREATE TABLE IF NOT EXISTS meta (
      key TEXT PRIMARY KEY,
      value TEXT NOT NULL
    );
  `);

  // 2. File tracking table
  params.db.exec(`
    CREATE TABLE IF NOT EXISTS files (
      path TEXT PRIMARY KEY,
      source TEXT NOT NULL DEFAULT 'memory',
      hash TEXT NOT NULL,
      mtime INTEGER NOT NULL,
      size INTEGER NOT NULL
    );
  `);

  // 3. Text chunks table (core)
  params.db.exec(`
    CREATE TABLE IF NOT EXISTS chunks (
      id TEXT PRIMARY KEY,
      path TEXT NOT NULL,
      source TEXT NOT NULL DEFAULT 'memory',
      start_line INTEGER NOT NULL,
      end_line INTEGER NOT NULL,
      hash TEXT NOT NULL,
      model TEXT NOT NULL,
      text TEXT NOT NULL,
      embedding TEXT NOT NULL,
      updated_at INTEGER NOT NULL
    );
  `);

  // 4. Embedding cache table
  params.db.exec(`
    CREATE TABLE IF NOT EXISTS ${params.embeddingCacheTable} (
      provider TEXT NOT NULL,
      model TEXT NOT NULL,
      provider_key TEXT NOT NULL,
      hash TEXT NOT NULL,
      embedding TEXT NOT NULL,
      dims INTEGER,
      updated_at INTEGER NOT NULL,
      PRIMARY KEY (provider, model, provider_key, hash)
    );
  `);
  // ...index creation omitted
}
```

Four tables, each with its own responsibility:

| Table             | Primary Key   | Purpose                                                             |
| ----------------- | ------------- | ------------------------------------------------------------------- |
| `meta`            | `key`         | Store index metadata (e.g., vector dimensions `vectorDims`)         |
| `files`           | `path`        | Track indexed files and their hash for incremental sync             |
| `chunks`          | `id`          | Store complete text chunk information (text + embedding + position) |
| `embedding_cache` | Composite key | Cache computed embeddings, avoid duplicate API calls                |

The `chunks` table is the core—each text chunk corresponds to one row, with the `embedding` field storing the complete floating-point array as a JSON string. The `model` field records which model was used to generate the embedding, ensuring vectors from different models aren't mixed in comparisons.

The `hash` field in the `files` table enables **incremental indexing**: during sync, the current file hash is compared with the stored hash, and only changed files need re-chunking and re-embedding. The `source` field distinguishes memory sources (`"memory"` for memory files, `"session"` for session records).

### FTS5 Full-Text Search Table

The schema creation function also attempts to establish an FTS5 virtual table:

```typescript
// src/memory/memory-schema.ts (simplified)

if (params.ftsEnabled) {
  try {
    params.db.exec(
      `CREATE VIRTUAL TABLE IF NOT EXISTS ${params.ftsTable} USING fts5(
        text,                    -- Text content for full-text search
        id UNINDEXED,           -- Following fields are stored only, not indexed
        path UNINDEXED,
        source UNINDEXED,
        model UNINDEXED,
        start_line UNINDEXED,
        end_line UNINDEXED
      );`
    );
    ftsAvailable = true;
  } catch (err) {
    ftsAvailable = false;       // Graceful degradation if FTS5 unavailable
    ftsError = err.message;
  }
}
```

> **Sidebar**: FTS5 (Full-Text Search 5) is SQLite's built-in full-text search engine. It builds an inverted index for text, supporting `MATCH` queries and BM25 ranking. The `UNINDEXED` keyword means that column only stores data but doesn't build a full-text index—here we only need full-text search on the `text` column, other columns are for associative queries.

Note that FTS5 creation is wrapped in `try/catch`—some SQLite compiled versions may not include FTS5 support, in which case the system gracefully degrades to pure vector search.

***

## 28.2.4 sqlite-vec Vector Acceleration

### Why Vector Acceleration?

The `chunks` table already stores embedding vectors (as JSON strings). The simplest search approach would be: read all chunks, parse each vector, compute cosine similarity one by one, then sort—this is the brute-force search path of `listChunks` + `cosineSimilarity`. But when there are many memory files, this O(n) row-by-row computation becomes slow.

`sqlite-vec` is a SQLite extension that provides **native vector distance computation** through vector virtual tables, executing `vec_distance_cosine()` directly in SQL queries, with performance far exceeding row-by-row JavaScript calculation.

### Extension Loading

```typescript
// src/memory/sqlite-vec.ts

export async function loadSqliteVecExtension(params: {
  db: DatabaseSync;
  extensionPath?: string;
}): Promise<{ ok: boolean; extensionPath?: string; error?: string }> {
  try {
    const sqliteVec = await import("sqlite-vec");
    const extensionPath = params.extensionPath ?? sqliteVec.getLoadablePath();
    params.db.enableLoadExtension(true);  // Must enable extension loading first
    sqliteVec.load(params.db);
    return { ok: true, extensionPath };
  } catch (err) {
    return { ok: false, error: err.message }; // Load failure is not fatal
  }
}
```

`sqlite-vec` is distributed via npm package, with `getLoadablePath()` returning the path to the compiled `.dylib/.so/.dll` file. Load failure only logs an error, doesn't prevent system operation—the system falls back to brute-force search.

### Vector Table Management

After loading the extension, `MemoryIndexManager` creates a `vec0` virtual table:

```typescript
// src/memory/manager.ts (simplified)

private async ensureVectorReady(dimensions?: number): Promise<boolean> {
  if (!this.vector.enabled) return false;

  // Lazy-load sqlite-vec extension (with 30s timeout)
  if (!this.vectorReady) {
    this.vectorReady = this.withTimeout(
      this.loadVectorExtension(),
      VECTOR_LOAD_TIMEOUT_MS,   // 30_000ms
      `sqlite-vec load timed out after 30s`,
    );
  }

  const ready = await this.vectorReady;
  if (ready && dimensions) {
    this.ensureVectorTable(dimensions); // Ensure vector table dimension matches
  }
  return ready;
}

private ensureVectorTable(dimensions: number): void {
  if (this.vector.dims === dimensions) return;   // Dimension unchanged, no action needed
  if (this.vector.dims && this.vector.dims !== dimensions) {
    this.dropVectorTable();                       // Dimension changed, drop then recreate
  }
  this.db.exec(
    `CREATE VIRTUAL TABLE IF NOT EXISTS chunks_vec USING vec0(
      id TEXT PRIMARY KEY,
      embedding FLOAT[${dimensions}]
    )`
  );
  this.vector.dims = dimensions;
}
```

`vec0` is the virtual table type provided by sqlite-vec. `FLOAT[${dimensions}]` declares a fixed-dimension floating-point vector column. If the user switches embedding models (dimension changes), the vector table is **completely rebuilt**—because vectors of different dimensions cannot be compared.

### Vector Search Implementation

With the `chunks_vec` table, search can be accomplished via SQL:

```typescript
// src/memory/manager-search.ts

const vectorToBlob = (embedding: number[]): Buffer =>
  Buffer.from(new Float32Array(embedding).buffer);

export async function searchVector(params: {
  db: DatabaseSync;
  vectorTable: string;       // "chunks_vec"
  providerModel: string;     // Ensure only comparing vectors of same model
  queryVec: number[];
  limit: number;
  snippetMaxChars: number;
  ensureVectorReady: (dimensions: number) => Promise<boolean>;
  sourceFilterVec: { sql: string; params: string[] };
  sourceFilterChunks: { sql: string; params: string[] };
}): Promise<SearchRowResult[]> {
  if (params.queryVec.length === 0) return [];

  // Path A: sqlite-vec available → SQL vector search
  if (await params.ensureVectorReady(params.queryVec.length)) {
    const rows = params.db.prepare(
      `SELECT c.id, c.path, c.start_line, c.end_line, c.text, c.source,
              vec_distance_cosine(v.embedding, ?) AS dist
         FROM chunks_vec v
         JOIN chunks c ON c.id = v.id
        WHERE c.model = ?
        ORDER BY dist ASC
        LIMIT ?`
    ).all(
      vectorToBlob(params.queryVec),  // Convert query vector to binary Blob
      params.providerModel,
      params.limit
    );
    return rows.map(row => ({
      ...row,
      score: 1 - row.dist,            // Convert distance to similarity: distance = 1 - cosine_similarity
    }));
  }

  // Path B: sqlite-vec unavailable → JavaScript brute-force search
  const candidates = listChunks({ db, providerModel, sourceFilter });
  const scored = candidates
    .map(chunk => ({ chunk, score: cosineSimilarity(queryVec, chunk.embedding) }))
    .filter(entry => Number.isFinite(entry.score));
  return scored.toSorted((a, b) => b.score - a.score).slice(0, limit);
}
```

Performance differences between the two paths:

| Aspect             | sqlite-vec (Path A)                    | Brute-force (Path B)                    |
| ------------------ | -------------------------------------- | --------------------------------------- |
| Vector computation | C implementation, inside SQLite engine | JavaScript `cosineSimilarity()`         |
| Data transfer      | Only Top-K results transmitted         | All chunk embeddings read from DB to JS |
| Sorting            | SQL `ORDER BY`                         | JavaScript `.toSorted()`                |
| Memory usage       | Low (streaming)                        | High (all vectors loaded to memory)     |

Note the `vectorToBlob` function—sqlite-vec requires vectors as `Float32Array` binary Buffer form, not JSON arrays. This avoids serialization/deserialization overhead.

### Dual-Path Degradation Strategy

The entire vector search degradation strategy forms a clear hierarchy:

```
sqlite-vec load successful?
    ├── YES → vec0 virtual table + vec_distance_cosine() (fast)
    └── NO  → Read embedding JSON from chunks table
              → parseEmbedding() parsing
              → cosineSimilarity() compute one by one (slow but correct)
```

This design ensures **functional consistency**—regardless of whether sqlite-vec is available, users can search memory, just at different speeds. For users with not many memory files (tens to hundreds of chunks), brute-force search latency is usually acceptable.

***

## Summary of This Section

1. **Embedding engine** is based on Strategy Pattern, `EmbeddingProvider` interface unifies `embedQuery` and `embedBatch` operations, all providers implement the same contract.
2. **Four providers** cover different scenarios: OpenAI (general), Gemini (asymmetric embedding), Voyage (retrieval-optimized), Local (offline privacy). `auto` mode auto-selects in order: local → openai → gemini → voyage.
3. **SQLite storage** uses four tables: `meta` (metadata), `files` (file tracking), `chunks` (text chunks + embeddings), `embedding_cache` (embedding cache), implementing incremental indexing via `hash` field.
4. **FTS5 virtual table** provides BM25 ranking for full-text search, gracefully degrades when unavailable.
5. **sqlite-vec extension** provides native vector distance computation, implementing in-SQL vector search via `vec0` virtual table and `vec_distance_cosine()` function. Automatically falls back to JavaScript brute-force search when unavailable.
6. **Dual-path degradation** runs through the entire design—from embedding provider auto/fallback, to vector search sqlite-vec/brute-force computation, each stage has a degradation plan, ensuring functionality is always available.
