# File index on the desktop

This is the work for the desktop app. The user's files stay on that computer. The server never receives the folder, the file bytes, the hashes, or the index.

The live scan in `search_documents` already works. This index replaces that scan when it is ready, and the live scan remains the fallback.

Code today:

| Piece | Where |
|---|---|
| Allowed folder | `searchRoot` in `settings.json` under Electron `userData`. The user picks it in the app. |
| File tools | `desktop/files.js`. `main.js` calls `runFileTool(settings.searchRoot, name, args, options)`. |
| Ignore rules | `desktop/files.js`. Hidden names, symbolic links, `node_modules`, `.git`, `build`, `.dart_tool`, and `.agentignore`. |
| Current search | `searchDocuments` walks the folder on every call. |
| Tests | `desktop/files.test.js`. Run with `node --test desktop/files.test.js`. |

Do not put the index database inside the allowed folder. The model can read that folder. Store the database under Electron `userData`, in a `file-index` directory. Name the file from the SHA-256 of the real path of `searchRoot`, so two allowed folders do not share one index.

## What is already done

Leave these in place and call them from the index. Do not write a second path checker or a second ignore list.

- Paths must stay inside the allowed folder. Absolute paths, drive letters, and `..` are refused.
- Symbolic links are not followed and cannot be read.
- `.agentignore` at the folder root: a name such as `secret` skips that name anywhere, a path such as `docs/private` skips that path, and `#` starts a comment.
- Text reads are UTF-8, reject a null byte, and skip files over 1 MB.
- `search_documents` returns at most 5 hits. Each hit has `filePath`, `line`, and `content`. `content` is at most 700 characters and starts 180 characters before the first query word. `line` is the line of that word.

The server already tells the model to cite `filePath` and `line`. Keep that JSON shape.

```json
{
  "query": "architecture boundaries",
  "searchedFolder": "/Users/me/Notes",
  "results": [
    {
      "filePath": "docs/architecture.md",
      "line": 3,
      "content": "The service has three layers.\nThe api layer depends on the domain layer.\nArchitecture boundaries stay between those layers."
    }
  ]
}
```

If no folder is allowed, keep the current error: `No folder is allowed. Choose a folder in the desktop app before searching files.`

## Step 1. Create the index database

Add `desktop/file-index.js`. It must not import Electron, so the tests can pass a temporary database path.

Use `node:sqlite` (`DatabaseSync`). Open the file with `WAL`. Create these tables:

```sql
CREATE TABLE IF NOT EXISTS files (
  path TEXT PRIMARY KEY,
  bytes INTEGER NOT NULL,
  modified_ms INTEGER NOT NULL,
  content_hash TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS chunks (
  id INTEGER PRIMARY KEY,
  path TEXT NOT NULL,
  start_line INTEGER NOT NULL,
  text TEXT NOT NULL,
  FOREIGN KEY (path) REFERENCES files(path) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS chunks_path ON chunks(path);
```

`path` is relative to the allowed folder and uses forward slashes.

Export four functions:

| Function | Behavior |
|---|---|
| `openIndex(dbPath)` | Open or create the database. |
| `refreshIndex(root, db)` | Walk the folder and add, update, rename, and delete rows. |
| `updatePath(root, db, relativePath)` | Re-read one path after a write, or delete the row if the file is gone or excluded. |
| `searchIndex(root, db, query)` | Return the same object `searchDocuments` returns today. |

`searchDocuments` keeps its signature. Add an optional index handle so tests can inject a temporary database. When the handle is missing, or the database cannot be opened, call the existing live scan and return that.

## Step 2. Read text with the same limits

Reuse the walk and the exclusion check already in `desktop/files.js`. A file is indexed only when all of these are true:

- The walk would already visit it: not hidden, not a symlink, not excluded, depth at most 8, and the walk stops at 5,000 directory entries.
- The extension is one of `.txt`, `.md`, `.markdown`, `.csv`, `.json`, `.log`, `.html`, `.htm`, `.css`, `.scss`, `.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.vue`, `.php`, `.py`, `.rb`, `.go`, `.java`, `.sql`, `.sh`, `.yml`, `.yaml`, `.xml`, `.svg`, `.toml`.
- The size is 1 MB or less.
- The bytes are text.

Read UTF-8. If the file starts with a UTF-8 or UTF-16 BOM, decode that encoding. If the text contains a null byte, skip the file. Do not guess other encodings in this step.

The content hash is SHA-256 of the decoded text, not of the raw bytes, so the same text with a different newline encoding can still match a rename. Normalize CRLF to LF before hashing and before chunking.

## Step 3. Store chunks

A short file is one chunk with `start_line` 1 and the whole text.

A longer file is split by lines:

- Fill a chunk until it would pass 2,000 characters, then start the next chunk.
- Repeat the last 5 lines at the start of the next chunk, so a match on a boundary is still in one chunk.
- `start_line` is the line number of the first line of that chunk in the original file.

Do not store a file that produced no text.

## Step 4. Refresh

`refreshIndex` walks the allowed folder once.

For each file that passes step 2:

| Disk compared with the row | Action |
|---|---|
| No row for that path | Hash, replace any chunks, insert the row. |
| Same `bytes` and `modified_ms` | Leave the row and the chunks. |
| Size or time changed, hash unchanged | Update `bytes` and `modified_ms` only. |
| Hash changed | Delete the old chunks, insert the new chunks, update the row. |

After the walk, any `files.path` that was not seen is a candidate for deletion. Step 5 decides whether it was renamed or deleted.

Also delete a row, without waiting for the size check, when its path is now excluded. Changing `.agentignore` must drop those paths on the next refresh.

Call `refreshIndex` at the start of `search_documents`, before the query runs. A missing database is created on that call.

## Step 5. Detect a rename or a delete

Build this from the candidates left at the end of the walk: paths that are in the index and were not seen, and paths that were inserted on this refresh.

A rename is a pair where all of these are true:

- The old path was not seen.
- The new path was inserted on this refresh.
- Both rows have the same `content_hash`.
- That hash belongs to only one old path and only one new path.

Update the old row's `path` and the `chunks.path` values. Do not re-chunk. If the hash is shared by two files, delete the old row and keep the new row as a new file.

Every remaining unseen path is a delete. Delete the `files` row and its chunks.

## Step 6. Search the index

`searchIndex` uses the same query rules as the live scan:

- Lowercase the query and split on spaces.
- Drop words of one character.
- A word scores 1 when it appears anywhere in the chunk. The match is a substring. Case does not matter.
- The chunk score is the number of words that appear.

Group chunks by `path`. Keep the highest-scoring chunk for each file. Sort files by that score, high to low. Return at most 5 files. A score of 0 is omitted.

For the winning chunk:

- `filePath` is `chunks.path`.
- Find the first query word in the chunk text. `line` is `start_line` plus the number of newlines before that word. If the first word is missing and a later word matched, `line` is `start_line`.
- `content` is at most 700 characters, starting 180 characters before that word.

`searchedFolder` remains the real path of the allowed folder.

If the index has no `files` rows after refresh, fall back to the live scan. An empty folder and a failed index should still return `{ query, searchedFolder, results: [] }` when the scan also finds nothing.

## Step 7. Update a path after the app writes it

A search must see a file the agent just wrote, even when the file system time has not moved.

After a successful `write_file`, `edit_file`, `replace_file_content`, `append_to_file`, `apply_patch`, `copy_file`, or `create_directory`, call `updatePath` for each path that was written.

After a successful `move_file`, delete the old path and update the new path.

After a successful `trash_file`, delete that path.

`updatePath` uses the same rules as refresh for that one path. If the path is excluded, missing, or over 1 MB, delete its row.

Do this inside `runFileTool`, after the tool returns, so each tool does not need its own index code. A failure to update the index must not fail the write. The next `search_documents` refresh will correct it.

## Step 8. Tests

Add these to `desktop/files.test.js`. Point them at a temporary folder and a temporary database. Do not use Electron `userData`.

| Test | Pass condition |
|---|---|
| First search builds the index | Two markdown files are searchable. The file that contains both query words is first. `line` is the line of the first word. |
| Unchanged file is not reread | Refresh twice. The second refresh does not change `content_hash` when size and modified time are unchanged. |
| Edit changes the passage | Change the file through `edit_file`, then search. The new text is in `content`, and the old text is not. |
| Rename keeps the hash | Move `docs/a.md` to `docs/b.md` with the same text. The index has one row, the new path, and the same `content_hash`. |
| Delete drops the row | Remove the file and refresh. A search no longer returns it. |
| Excluded path stays out | A file under `node_modules`, a symlink, a file over 1 MB, and a path listed in `.agentignore` are absent after refresh. Reading the excluded path still throws `That path is excluded.` |
| Fallback | A database path that cannot be opened still returns the live-scan result for a small folder. |

Run:

```bash
node --test desktop/files.test.js
```

## What is stored, and when it refreshes

The index stores text. A file of any name is included when it is not binary: source files, `Dockerfile`, `.svg`, logs, and files larger than 1 MB. The first 64 MB of a text file are indexed, so a multi-gigabyte log cannot fill the database. Images, video, audio, archives, fonts, executables, and PDFs are left out. Hidden names, symlinks, `node_modules`, `.git`, `build`, `.dart_tool`, and `.agentignore` paths are left out.

Each file row stores the relative path, size, modified time, and SHA-256 of the text. Each chunk stores its starting line, text, and, once embedded, a vector. A chunk with an empty vector has not been embedded yet.

`search_documents` refreshes the index first. A file whose size and modified time are unchanged is not read again. A changed size or time is hashed. The same hash updates the time only. A new hash replaces the chunks and clears their vectors. A path that disappeared is removed, unless its hash moved to exactly one new path, which is kept as a rename.

A desktop write, edit, append, patch, copy, move, or trash updates that path immediately. A shell command is picked up on the next `search_documents` refresh.

Embeddings run after the text index is saved. The model is OpenAI `text-embedding-3-small`. Each vector is 1,536 numbers. The desktop stores the vector beside the chunk. The server does not save the vector or the chunk.

The desktop has no OpenAI key. It calls one authenticated route on the agent server. The server uses the existing `OPENAI_API_KEY`, calls OpenAI, and returns the vectors.

```text
POST /api/agent/embeddings
Authorization: Bearer <agent access token>
Content-Type: application/json

{ "inputs": ["The service has three layers.", "architecture boundaries"] }
```

```json
{
  "model": "text-embedding-3-small",
  "vectors": [
    [0.01, 0.02],
    [0.03, 0.04]
  ]
}
```

`vectors[i]` matches `inputs[i]`. A real vector has 1,536 numbers. Send at most 64 inputs, each at most the chunk size from step 3.

When a chunk is new or its text changed, send that chunk text and store the returned vector. On a search, send only the query, then compare that one vector with the stored chunk vectors on the machine. Unchanged chunks are not sent again.

## What the server does

No server change is required for steps 1 through 8. Step 9 adds `POST /api/agent/embeddings` only. That route returns vectors and stores nothing.

The tool name stays `search_documents`. The arguments stay `{ "query": "..." }`. The posted body stays `{ callId, ok, result }` with `result.results[]` of `{ filePath, line, content }`.

The server work, if any, is a schema description when a new desktop tool is added. Do not add one for refresh. Refresh runs inside `search_documents`.

Leave these server files unchanged unless the JSON result changes:

- `agentic/src/tools/desktop/files.js`
- `agentic/src/agent/policies.js`
- `agentic/src/tools/index.js`
- `agentic/docs/search-documents.md`

If the desktop result gains or drops a field, stop and update `search-documents.md` in the same change. The model cites those fields.

## Done when

- A second search of an unchanged folder does not reread every file.
- Changing, renaming, and deleting a file shows up on the next search.
- `node_modules`, symlinks, files over 1 MB, and `.agentignore` paths are not in the results.
- The posted JSON still has `filePath`, `line`, and `content`.
- Quit the app and start it again with `npm start` before trying the prompt in the chat window. A reload of the window is not enough.
