obsidian-hybrid-search 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +200 -0
- package/dist/src/chunker.js +96 -0
- package/dist/src/cli.js +172 -0
- package/dist/src/config.js +37 -0
- package/dist/src/db.js +269 -0
- package/dist/src/embedder.js +140 -0
- package/dist/src/indexer.js +279 -0
- package/dist/src/searcher.js +233 -0
- package/dist/src/server.js +174 -0
- package/package.json +36 -0
package/README.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# obsidian-hybrid-search
|
|
2
|
+
|
|
3
|
+
A fast hybrid search server for [Obsidian](https://obsidian.md) vaults. Combines BM25 full-text search, fuzzy title matching, and semantic vector search via Reciprocal Rank Fusion (RRF).
|
|
4
|
+
|
|
5
|
+
Works as an [MCP server](https://modelcontextprotocol.io) for Claude and other AI assistants, and as a standalone CLI tool.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Hybrid search** — BM25 + fuzzy title + semantic embeddings, fused with RRF
|
|
10
|
+
- **Four search modes** — `hybrid`, `semantic`, `fulltext`, `title`
|
|
11
|
+
- **Similar note lookup** — pass a path to find semantically related notes
|
|
12
|
+
- **Links & backlinks** — every result includes outgoing links and backlinks
|
|
13
|
+
- **Scope filtering** — restrict search to a subfolder
|
|
14
|
+
- **Incremental indexing** — only re-indexes changed files; watches for edits in real time
|
|
15
|
+
- **Local embeddings** — works offline via `@xenova/transformers` (no API key required)
|
|
16
|
+
- **Remote embeddings** — OpenAI-compatible API (OpenRouter, Ollama, etc.)
|
|
17
|
+
- **Ignore patterns** — exclude folders, extensions, or specific files
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install -g obsidian-hybrid-search
|
|
23
|
+
# or run directly without installing:
|
|
24
|
+
npx obsidian-hybrid-search
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## CLI usage
|
|
28
|
+
|
|
29
|
+
The tool auto-discovers the database by walking up from the current directory looking for `.obsidian-hybrid-search.db`. The simplest way to use it — run from inside your vault:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
cd /path/to/your/vault
|
|
33
|
+
obsidian-hybrid-search "zettelkasten"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
If you want to run it from anywhere (e.g. via shell aliases), set the environment variables explicitly. Add to your `~/.zshrc` or `~/.bashrc`:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
export OBSIDIAN_VAULT_PATH="/path/to/your/vault"
|
|
40
|
+
|
|
41
|
+
# Optional — only needed if using a remote embedding API instead of local model
|
|
42
|
+
export OPENAI_API_KEY="sk-..."
|
|
43
|
+
export OPENAI_BASE_URL="https://openrouter.ai/api/v1"
|
|
44
|
+
export OPENAI_EMBEDDING_MODEL="openai/text-embedding-3-small"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Without `OPENAI_API_KEY` the local `Xenova/all-MiniLM-L6-v2` model is used automatically (no API key needed, ~50 MB download on first run).
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
# Hybrid search (default)
|
|
51
|
+
obsidian-hybrid-search "zettelkasten atomic notes"
|
|
52
|
+
|
|
53
|
+
# Fulltext BM25 search
|
|
54
|
+
obsidian-hybrid-search "permanent notes" --mode fulltext
|
|
55
|
+
|
|
56
|
+
# Fuzzy title search (fast, no snippets)
|
|
57
|
+
obsidian-hybrid-search "zettleksten" --mode title
|
|
58
|
+
|
|
59
|
+
# Semantic / vector search
|
|
60
|
+
obsidian-hybrid-search "how to build a knowledge graph" --mode semantic
|
|
61
|
+
|
|
62
|
+
# Limit results and set a score threshold
|
|
63
|
+
obsidian-hybrid-search "productivity systems" --limit 5 --threshold 0.3
|
|
64
|
+
|
|
65
|
+
# Restrict to a subfolder
|
|
66
|
+
obsidian-hybrid-search "daily review" --scope notes/periodic/
|
|
67
|
+
|
|
68
|
+
# Find notes similar to a specific note
|
|
69
|
+
obsidian-hybrid-search "notes/pkm/zettelkasten.md"
|
|
70
|
+
|
|
71
|
+
# JSON output (for scripting)
|
|
72
|
+
obsidian-hybrid-search "spaced repetition" --json
|
|
73
|
+
|
|
74
|
+
# Reindex the vault
|
|
75
|
+
obsidian-hybrid-search reindex
|
|
76
|
+
|
|
77
|
+
# Force full reindex
|
|
78
|
+
obsidian-hybrid-search reindex --force
|
|
79
|
+
|
|
80
|
+
# Reindex a single file
|
|
81
|
+
obsidian-hybrid-search reindex notes/pkm/zettelkasten.md
|
|
82
|
+
|
|
83
|
+
# Show indexing status
|
|
84
|
+
obsidian-hybrid-search status
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Shell aliases
|
|
88
|
+
|
|
89
|
+
Add to your `~/.zshrc` or `~/.bashrc` for quick access:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
alias ohs='obsidian-hybrid-search'
|
|
93
|
+
alias ohss='obsidian-hybrid-search --mode semantic'
|
|
94
|
+
alias ohst='obsidian-hybrid-search --mode title'
|
|
95
|
+
alias ohsf='obsidian-hybrid-search --mode fulltext'
|
|
96
|
+
alias ohsi='obsidian-hybrid-search reindex'
|
|
97
|
+
alias ohsst='obsidian-hybrid-search status'
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Then reload (`source ~/.zshrc`) and use:
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
ohs "zettelkasten" # hybrid search
|
|
104
|
+
ohss "how to build a knowledge graph" # semantic
|
|
105
|
+
ohst "zettleksten" # fuzzy title (typo-tolerant)
|
|
106
|
+
ohsf "permanent notes" # fulltext BM25
|
|
107
|
+
ohsi # reindex vault
|
|
108
|
+
ohsst # show status
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Output example
|
|
112
|
+
|
|
113
|
+
Hybrid search returns a table with scores and snippets:
|
|
114
|
+
|
|
115
|
+
```
|
|
116
|
+
┌───────┬───────────────────────────────┬────────────────────────────────────────────┐
|
|
117
|
+
│ SCORE │ PATH │ SNIPPET │
|
|
118
|
+
├───────┼───────────────────────────────┼────────────────────────────────────────────┤
|
|
119
|
+
│ 0.98 │ notes/pkm/zettelkasten.md │ A note-taking method developed by Niklas │
|
|
120
|
+
│ │ │ Luhmann. Each note contains one atomic... │
|
|
121
|
+
├───────┼───────────────────────────────┼────────────────────────────────────────────┤
|
|
122
|
+
│ 0.72 │ notes/pkm/evergreen-notes.md │ Evergreen notes are written to evolve over │
|
|
123
|
+
│ │ │ time. Unlike fleeting notes, they are... │
|
|
124
|
+
└───────┴───────────────────────────────┴────────────────────────────────────────────┘
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Title mode omits the snippet column automatically.
|
|
128
|
+
|
|
129
|
+
## MCP server (Claude integration)
|
|
130
|
+
|
|
131
|
+
Add to your Claude MCP config (`.mcp.json` or `claude_desktop_config.json`):
|
|
132
|
+
|
|
133
|
+
```json
|
|
134
|
+
{
|
|
135
|
+
"mcpServers": {
|
|
136
|
+
"obsidian-hybrid-search": {
|
|
137
|
+
"command": "npx",
|
|
138
|
+
"args": ["-y", "-p", "obsidian-hybrid-search", "obsidian-hybrid-search-mcp"],
|
|
139
|
+
"env": {
|
|
140
|
+
"OBSIDIAN_VAULT_PATH": "/path/to/your/vault",
|
|
141
|
+
"OBSIDIAN_IGNORE_PATTERNS": ".obsidian/**,templates/**,*.canvas",
|
|
142
|
+
"OPENAI_API_KEY": "sk-...",
|
|
143
|
+
"OPENAI_BASE_URL": "https://openrouter.ai/api/v1",
|
|
144
|
+
"OPENAI_EMBEDDING_MODEL": "openai/text-embedding-3-small"
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Omit `OPENAI_API_KEY` to use the local `Xenova/all-MiniLM-L6-v2` model (downloads ~50 MB on first run).
|
|
152
|
+
|
|
153
|
+
> **Note:** On first run, `npx` will install the package automatically. Ignore patterns are persisted in the database and restored on every subsequent startup even if the env var is missing.
|
|
154
|
+
|
|
155
|
+
The server exposes three tools:
|
|
156
|
+
|
|
157
|
+
| Tool | Description |
|
|
158
|
+
|------|-------------|
|
|
159
|
+
| `search` | Search the vault with optional `mode`, `scope`, `limit`, `threshold` |
|
|
160
|
+
| `reindex` | Reindex the vault or a specific file |
|
|
161
|
+
| `status` | Show total notes, indexed count, last indexed time |
|
|
162
|
+
|
|
163
|
+
## Configuration
|
|
164
|
+
|
|
165
|
+
| Environment variable | Default | Description |
|
|
166
|
+
|----------------------|---------|-------------|
|
|
167
|
+
| `OBSIDIAN_VAULT_PATH` | *(required)* | Absolute path to your vault |
|
|
168
|
+
| `OBSIDIAN_IGNORE_PATTERNS` | `.obsidian/**,templates/**,*.canvas` | Comma-separated ignore patterns |
|
|
169
|
+
| `OPENAI_API_KEY` | — | API key (omit for local embeddings) |
|
|
170
|
+
| `OPENAI_BASE_URL` | `https://openrouter.ai/api/v1` | API base URL |
|
|
171
|
+
| `OPENAI_EMBEDDING_MODEL` | `openai/text-embedding-3-small` | Embedding model name |
|
|
172
|
+
|
|
173
|
+
### Ignore patterns
|
|
174
|
+
|
|
175
|
+
- `folder/**` — ignore a directory and all its contents
|
|
176
|
+
- `*.canvas` — ignore by extension
|
|
177
|
+
- `exact/path.md` — ignore a specific file
|
|
178
|
+
|
|
179
|
+
The ignore configuration is persisted in the database, so it is restored automatically even if the environment variable is missing on restart.
|
|
180
|
+
|
|
181
|
+
## How it works
|
|
182
|
+
|
|
183
|
+
1. **Indexing** — notes are chunked by headings (with sliding-window fallback), embedded, and stored in SQLite with FTS5 and `sqlite-vec`.
|
|
184
|
+
2. **Search** — BM25, fuzzy trigram title search, and vector ANN search run in parallel; results are fused with RRF and scored 0–1 (higher = more relevant).
|
|
185
|
+
3. **Links** — wikilinks (`[[note]]`) are resolved to note paths and stored; every search result includes `links` and `backlinks` arrays.
|
|
186
|
+
4. **Watcher** — `chokidar` watches for file changes and incrementally re-indexes in the background.
|
|
187
|
+
|
|
188
|
+
## Development
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
npm install
|
|
192
|
+
npm test # run test suite
|
|
193
|
+
npm run build # compile TypeScript
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Tests use fake embeddings (no API key required) and run against a temporary vault. All 25 tests cover chunking, BM25 scoring, fuzzy search, links/backlinks, `deleteNote` semantics, and ignore pattern matching.
|
|
197
|
+
|
|
198
|
+
## License
|
|
199
|
+
|
|
200
|
+
MIT
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { config } from './config.js';
|
|
2
|
+
export function estimateTokens(text) {
|
|
3
|
+
// Cyrillic and other non-ASCII scripts: ~1 char per token
|
|
4
|
+
// ASCII (English): ~4 chars per token
|
|
5
|
+
let tokens = 0;
|
|
6
|
+
for (const char of text) {
|
|
7
|
+
const cp = char.codePointAt(0);
|
|
8
|
+
if (cp > 127) {
|
|
9
|
+
tokens += 1; // non-ASCII (Cyrillic, CJK, etc.)
|
|
10
|
+
}
|
|
11
|
+
else {
|
|
12
|
+
tokens += 0.25; // ASCII
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return Math.ceil(tokens);
|
|
16
|
+
}
|
|
17
|
+
export function splitBySections(content) {
|
|
18
|
+
const lines = content.split('\n');
|
|
19
|
+
const sections = [];
|
|
20
|
+
let currentHeading = '';
|
|
21
|
+
let currentBody = [];
|
|
22
|
+
const flush = () => {
|
|
23
|
+
const body = currentBody.join('\n');
|
|
24
|
+
if (body.trim().length >= config.chunkMinLength) {
|
|
25
|
+
const text = currentHeading
|
|
26
|
+
? `${currentHeading}\n${body}`.trim()
|
|
27
|
+
: body.trim();
|
|
28
|
+
sections.push({ heading: currentHeading, body, text });
|
|
29
|
+
}
|
|
30
|
+
currentBody = [];
|
|
31
|
+
};
|
|
32
|
+
for (const line of lines) {
|
|
33
|
+
const isHeading = /^#{1,6}\s+/.test(line);
|
|
34
|
+
if (isHeading) {
|
|
35
|
+
flush();
|
|
36
|
+
currentHeading = line;
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
currentBody.push(line);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
flush();
|
|
43
|
+
return sections;
|
|
44
|
+
}
|
|
45
|
+
export function slidingWindow(text, contextLength, overlap) {
|
|
46
|
+
const stepTokens = Math.max(contextLength - overlap, Math.ceil(contextLength / 2));
|
|
47
|
+
const chunks = [];
|
|
48
|
+
let start = 0;
|
|
49
|
+
while (start < text.length) {
|
|
50
|
+
// Advance char by char until we reach contextLength tokens
|
|
51
|
+
let end = start;
|
|
52
|
+
let tokens = 0;
|
|
53
|
+
while (end < text.length && tokens < contextLength) {
|
|
54
|
+
const cp = text.codePointAt(end);
|
|
55
|
+
tokens += cp > 127 ? 1 : 0.25;
|
|
56
|
+
end += cp > 0xffff ? 2 : 1;
|
|
57
|
+
}
|
|
58
|
+
const chunk = text.slice(start, end).trim();
|
|
59
|
+
if (chunk.length >= config.chunkMinLength) {
|
|
60
|
+
chunks.push({ text: chunk });
|
|
61
|
+
}
|
|
62
|
+
if (end >= text.length)
|
|
63
|
+
break;
|
|
64
|
+
// Advance start by stepTokens worth of chars
|
|
65
|
+
let stepped = 0;
|
|
66
|
+
let stepTokensAccum = 0;
|
|
67
|
+
while (stepped < text.length - start && stepTokensAccum < stepTokens) {
|
|
68
|
+
const cp = text.codePointAt(start + stepped);
|
|
69
|
+
stepTokensAccum += cp > 127 ? 1 : 0.25;
|
|
70
|
+
stepped += cp > 0xffff ? 2 : 1;
|
|
71
|
+
}
|
|
72
|
+
start += stepped;
|
|
73
|
+
}
|
|
74
|
+
return chunks.length > 0 ? chunks : [{ text: text.trim() }];
|
|
75
|
+
}
|
|
76
|
+
export function chunkNote(content, contextLength) {
|
|
77
|
+
if (estimateTokens(content) <= contextLength) {
|
|
78
|
+
return [{ text: content.trim() }];
|
|
79
|
+
}
|
|
80
|
+
const sections = splitBySections(content);
|
|
81
|
+
if (sections.length <= 1) {
|
|
82
|
+
return slidingWindow(content, contextLength, config.chunkOverlap);
|
|
83
|
+
}
|
|
84
|
+
const chunks = [];
|
|
85
|
+
for (const section of sections) {
|
|
86
|
+
if (section.body.trim().length < config.chunkMinLength)
|
|
87
|
+
continue;
|
|
88
|
+
if (estimateTokens(section.text) <= contextLength) {
|
|
89
|
+
chunks.push({ text: section.text });
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
chunks.push(...slidingWindow(section.text, contextLength, config.chunkOverlap));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return chunks.length > 0 ? chunks : slidingWindow(content, contextLength, config.chunkOverlap);
|
|
96
|
+
}
|
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
import Table from 'cli-table3';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import Database from 'better-sqlite3';
|
|
7
|
+
import { openDb, initVecTable, getStats } from './db.js';
|
|
8
|
+
import { getContextLength, getEmbeddingDim } from './embedder.js';
|
|
9
|
+
import { search } from './searcher.js';
|
|
10
|
+
import { indexVaultSync, indexFile } from './indexer.js';
|
|
11
|
+
import { config } from './config.js';
|
|
12
|
+
/**
|
|
13
|
+
* Find .obsidian-hybrid-search.db by walking up from dir,
|
|
14
|
+
* read vault_path / api_base_url / api_model from its settings table,
|
|
15
|
+
* and inject them into process.env (only if not already set).
|
|
16
|
+
*/
|
|
17
|
+
async function discoverConfig(dbPathOpt) {
|
|
18
|
+
let dbFile = dbPathOpt;
|
|
19
|
+
if (!dbFile) {
|
|
20
|
+
let dir = process.cwd();
|
|
21
|
+
while (true) {
|
|
22
|
+
const candidate = path.join(dir, '.obsidian-hybrid-search.db');
|
|
23
|
+
if (existsSync(candidate)) {
|
|
24
|
+
dbFile = candidate;
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
const parent = path.dirname(dir);
|
|
28
|
+
if (parent === dir)
|
|
29
|
+
break; // reached filesystem root
|
|
30
|
+
dir = parent;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (!dbFile) {
|
|
34
|
+
if (!process.env.OBSIDIAN_VAULT_PATH) {
|
|
35
|
+
console.error('Error: Could not find .obsidian-hybrid-search.db\n' +
|
|
36
|
+
'Run this command from inside your Obsidian vault, use --db <path>, or set OBSIDIAN_VAULT_PATH.');
|
|
37
|
+
process.exit(1);
|
|
38
|
+
}
|
|
39
|
+
return; // env vars already set — proceed normally
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
// Open read-only without sqlite-vec (settings table needs no vector extension)
|
|
43
|
+
const db = new Database(dbFile, { readonly: true });
|
|
44
|
+
const get = (key) => db.prepare('SELECT value FROM settings WHERE key = ?').get(key)?.value;
|
|
45
|
+
const vaultPath = get('vault_path');
|
|
46
|
+
const apiBaseUrl = get('api_base_url');
|
|
47
|
+
const apiModel = get('api_model');
|
|
48
|
+
const ignorePatternsCsv = get('ignore_patterns_csv');
|
|
49
|
+
db.close();
|
|
50
|
+
// Env vars take precedence over DB-stored values
|
|
51
|
+
if (vaultPath && !process.env.OBSIDIAN_VAULT_PATH) {
|
|
52
|
+
process.env.OBSIDIAN_VAULT_PATH = vaultPath;
|
|
53
|
+
}
|
|
54
|
+
if (apiBaseUrl && !process.env.OPENAI_BASE_URL) {
|
|
55
|
+
process.env.OPENAI_BASE_URL = apiBaseUrl;
|
|
56
|
+
}
|
|
57
|
+
if (apiModel && !process.env.OPENAI_EMBEDDING_MODEL) {
|
|
58
|
+
process.env.OPENAI_EMBEDDING_MODEL = apiModel;
|
|
59
|
+
}
|
|
60
|
+
if (ignorePatternsCsv && !process.env.OBSIDIAN_IGNORE_PATTERNS) {
|
|
61
|
+
process.env.OBSIDIAN_IGNORE_PATTERNS = ignorePatternsCsv;
|
|
62
|
+
}
|
|
63
|
+
// Fallback: infer vault path from DB location if not stored in settings
|
|
64
|
+
if (!process.env.OBSIDIAN_VAULT_PATH) {
|
|
65
|
+
process.env.OBSIDIAN_VAULT_PATH = path.dirname(dbFile);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
// DB unreadable — let normal startup errors surface
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function init() {
|
|
73
|
+
openDb();
|
|
74
|
+
const [contextLength, embeddingDim] = await Promise.all([
|
|
75
|
+
getContextLength(),
|
|
76
|
+
getEmbeddingDim(),
|
|
77
|
+
]);
|
|
78
|
+
initVecTable(embeddingDim);
|
|
79
|
+
return contextLength;
|
|
80
|
+
}
|
|
81
|
+
const program = new Command()
|
|
82
|
+
.name('obsidian-hybrid-search')
|
|
83
|
+
.description('Hybrid search for your Obsidian vault')
|
|
84
|
+
.version('0.1.0')
|
|
85
|
+
.option('--db <path>', 'Path to .obsidian-hybrid-search.db (auto-discovered from CWD by default)');
|
|
86
|
+
program.hook('preAction', async (thisCommand) => {
|
|
87
|
+
const opts = thisCommand.opts();
|
|
88
|
+
await discoverConfig(opts.db);
|
|
89
|
+
});
|
|
90
|
+
program
|
|
91
|
+
.command('search [query]', { isDefault: true })
|
|
92
|
+
.description('Search the vault (default command)')
|
|
93
|
+
.option('--mode <mode>', 'Search mode: hybrid|semantic|fulltext|title', 'hybrid')
|
|
94
|
+
.option('--scope <scope>', 'Limit to a subfolder, e.g. notes/pkm/')
|
|
95
|
+
.option('--limit <n>', 'Maximum results', '10')
|
|
96
|
+
.option('--threshold <n>', 'Minimum score threshold 0..1', '0')
|
|
97
|
+
.option('--json', 'Output as JSON')
|
|
98
|
+
.action(async (query, opts) => {
|
|
99
|
+
if (!query) {
|
|
100
|
+
program.help();
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
await init();
|
|
104
|
+
const results = await search(query, {
|
|
105
|
+
mode: opts.mode,
|
|
106
|
+
scope: opts.scope,
|
|
107
|
+
limit: parseInt(opts.limit),
|
|
108
|
+
threshold: parseFloat(opts.threshold),
|
|
109
|
+
});
|
|
110
|
+
if (opts.json) {
|
|
111
|
+
console.log(JSON.stringify(results, null, 2));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (results.length === 0) {
|
|
115
|
+
console.log('No results found.');
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const hasSnippets = results.some(r => (r.snippet ?? '').trim().length > 0);
|
|
119
|
+
const table = hasSnippets
|
|
120
|
+
? new Table({ head: ['SCORE', 'PATH', 'SNIPPET'], colWidths: [7, 45, 60], wordWrap: true })
|
|
121
|
+
: new Table({ head: ['SCORE', 'PATH'], colWidths: [7, 60], wordWrap: true });
|
|
122
|
+
for (const r of results) {
|
|
123
|
+
if (hasSnippets) {
|
|
124
|
+
table.push([r.score.toFixed(2), r.path, (r.snippet ?? '').slice(0, 120)]);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
table.push([r.score.toFixed(2), r.path]);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
console.log(table.toString());
|
|
131
|
+
});
|
|
132
|
+
program
|
|
133
|
+
.command('reindex [path]')
|
|
134
|
+
.description('Reindex the vault or a specific file')
|
|
135
|
+
.option('--force', 'Force reindex even if unchanged')
|
|
136
|
+
.action(async (filePath, opts) => {
|
|
137
|
+
const contextLength = await init();
|
|
138
|
+
if (filePath) {
|
|
139
|
+
const fullPath = path.join(config.vaultPath, filePath);
|
|
140
|
+
const status = await indexFile(fullPath, contextLength, opts.force);
|
|
141
|
+
console.log(JSON.stringify(status === 'indexed'
|
|
142
|
+
? { indexed: 1, skipped: 0, errors: [] }
|
|
143
|
+
: status === 'skipped'
|
|
144
|
+
? { indexed: 0, skipped: 1, errors: [] }
|
|
145
|
+
: { indexed: 0, skipped: 0, errors: [{ path: filePath, error: 'indexing failed' }] }, null, 2));
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
console.error('Indexing vault...');
|
|
149
|
+
const result = await indexVaultSync(opts.force);
|
|
150
|
+
console.log(JSON.stringify(result, null, 2));
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
program
|
|
154
|
+
.command('status')
|
|
155
|
+
.description('Show indexing status and configuration')
|
|
156
|
+
.action(async () => {
|
|
157
|
+
const contextLength = await init();
|
|
158
|
+
const stats = getStats();
|
|
159
|
+
console.log(JSON.stringify({
|
|
160
|
+
vault: config.vaultPath,
|
|
161
|
+
total: stats.total,
|
|
162
|
+
indexed: stats.indexed,
|
|
163
|
+
pending: stats.pending,
|
|
164
|
+
last_indexed: stats.lastIndexed,
|
|
165
|
+
model: config.apiKey ? config.apiModel : 'Xenova/all-MiniLM-L6-v2 (local)',
|
|
166
|
+
context_length: contextLength,
|
|
167
|
+
}, null, 2));
|
|
168
|
+
});
|
|
169
|
+
program.parseAsync(process.argv).catch(err => {
|
|
170
|
+
console.error('Error:', err.message);
|
|
171
|
+
process.exit(1);
|
|
172
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
export const config = {
|
|
3
|
+
get vaultPath() {
|
|
4
|
+
const v = process.env.OBSIDIAN_VAULT_PATH;
|
|
5
|
+
if (!v)
|
|
6
|
+
throw new Error('OBSIDIAN_VAULT_PATH environment variable is required');
|
|
7
|
+
return v;
|
|
8
|
+
},
|
|
9
|
+
get ignorePatterns() {
|
|
10
|
+
return (process.env.OBSIDIAN_IGNORE_PATTERNS ?? '.obsidian/**,templates/**,*.canvas')
|
|
11
|
+
.split(',')
|
|
12
|
+
.map(p => p.trim())
|
|
13
|
+
.filter(Boolean);
|
|
14
|
+
},
|
|
15
|
+
get apiKey() {
|
|
16
|
+
return process.env.OPENAI_API_KEY;
|
|
17
|
+
},
|
|
18
|
+
get apiBaseUrl() {
|
|
19
|
+
return process.env.OPENAI_BASE_URL ?? 'https://openrouter.ai/api/v1';
|
|
20
|
+
},
|
|
21
|
+
get apiModel() {
|
|
22
|
+
return process.env.OPENAI_EMBEDDING_MODEL ?? 'openai/text-embedding-3-small';
|
|
23
|
+
},
|
|
24
|
+
get dbPath() {
|
|
25
|
+
const v = process.env.OBSIDIAN_VAULT_PATH;
|
|
26
|
+
if (!v)
|
|
27
|
+
throw new Error('OBSIDIAN_VAULT_PATH environment variable is required');
|
|
28
|
+
return path.join(v, '.obsidian-hybrid-search.db');
|
|
29
|
+
},
|
|
30
|
+
// internal defaults
|
|
31
|
+
chunkContextFallback: 512,
|
|
32
|
+
chunkOverlap: 64,
|
|
33
|
+
chunkMinLength: 50,
|
|
34
|
+
chunkHeadingLevel: 0,
|
|
35
|
+
batchSize: 10,
|
|
36
|
+
debounce: 30_000,
|
|
37
|
+
};
|