@aivin-labs/cli 1.0.8 → 1.0.13

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.
Files changed (63) hide show
  1. package/README.md +41 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1979 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +187 -37
  9. package/bin/lib/remote/callLedger.mjs +74 -15
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +174 -11
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +293 -0
  15. package/bin/lib/remote/constants.mjs +78 -0
  16. package/bin/lib/remote/dailyBrowser.mjs +9 -3
  17. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  18. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  19. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  20. package/bin/lib/remote/desktop/index.mjs +309 -0
  21. package/bin/lib/remote/desktop/linux.mjs +144 -0
  22. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
  23. package/bin/lib/remote/desktop/mac.mjs +187 -0
  24. package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
  25. package/bin/lib/remote/desktop/strings.mjs +74 -0
  26. package/bin/lib/remote/desktop/traySource.mjs +541 -0
  27. package/bin/lib/remote/deviceProfile.mjs +1 -0
  28. package/bin/lib/remote/docText.mjs +86 -1
  29. package/bin/lib/remote/fileIndexer.mjs +757 -399
  30. package/bin/lib/remote/folderRules.mjs +140 -0
  31. package/bin/lib/remote/gui/index.mjs +208 -18
  32. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  33. package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
  34. package/bin/lib/remote/idempotency.mjs +50 -21
  35. package/bin/lib/remote/localPolicy.mjs +17 -4
  36. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  37. package/bin/lib/remote/mascot/ask.mjs +768 -0
  38. package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
  39. package/bin/lib/remote/mascot/assets.mjs +825 -216
  40. package/bin/lib/remote/mascot/bot.mjs +397 -0
  41. package/bin/lib/remote/mascot/hostSource.mjs +500 -103
  42. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  43. package/bin/lib/remote/mascot/index.mjs +199 -28
  44. package/bin/lib/remote/mascot/labels.mjs +2 -3
  45. package/bin/lib/remote/mascot/rigSource.mjs +614 -0
  46. package/bin/lib/remote/mascot/strings.mjs +204 -18
  47. package/bin/lib/remote/mascot/ui.mjs +104 -0
  48. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  49. package/bin/lib/remote/meeting/index.mjs +415 -0
  50. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  51. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  52. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  53. package/bin/lib/remote/osSearch.mjs +107 -0
  54. package/bin/lib/remote/sqliteDb.mjs +51 -0
  55. package/bin/lib/remote/tabGroups.mjs +209 -0
  56. package/bin/lib/remote/toolHandlers.mjs +788 -726
  57. package/bin/lib/remoteControl.mjs +26 -26
  58. package/docs/AIVIN_MASCOT.md +130 -0
  59. package/docs/CLI.md +1504 -1353
  60. package/docs/media/aivin-mascot-live.gif +0 -0
  61. package/docs/media/aivin-mascot-live.png +0 -0
  62. package/docs/media/aivin-remote-architecture.svg +102 -0
  63. package/package.json +71 -71
@@ -1,399 +1,757 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
- import zlib from 'zlib';
5
- import { IGNORED_DIRS, REMOTE_CONFIG_DIR } from './constants.mjs';
6
- import { extractDocText, isDocFile, wellFormed } from './docText.mjs';
7
- import { isProtectedPath } from './sandbox.mjs';
8
- import { createTextIndex, decodeInt8, int8Cosine } from './textIndex.mjs';
9
-
10
- /**
11
- * Chỉ mục tệp trong RAM cho các thư mục được phép: tên/đường dẫn + định danh đầu tệp (hàm, lớp, khoá…) → tìm tức thì theo tên lẫn nội
12
- * dung chính mà không quét đĩa mỗi lần. Khởi động: nạp bản chụp gzip, quét lại TĂNG DẦN (chỉ đọc tệp có mtime/size đổi). Chạy: theo
13
- * dõi thư mục (`fs.watch` đệ quy), cập nhật đúng tệp đổi.
14
- *
15
- * Tệp dạng tài liệu (docx/xlsx/pptx/pdf/txt…) có thêm đoạn chữ đầu (`preview`, đọc cả trong gói Office) và vector bge-m3 do BE tính
16
- * (`vectorize`, chạy nền): tìm kết hợp từ khoá BM25 + ngữ nghĩa (cosine) gộp bằng RRF — "hợp đồng thuê văn phòng" ra
17
- * `HD_thue_VP_2026.pdf`. Thư mục người dùng (Desktop, Documents, Downloads, OneDrive…) quét trước để trần số tệp không cắt mất chúng.
18
- */
19
-
20
- const SNAPSHOT_FILE = path.join(REMOTE_CONFIG_DIR, 'file-index.json.gz');
21
- const VECTORS_FILE = path.join(REMOTE_CONFIG_DIR, 'file-vectors.json.gz');
22
- const SNAPSHOT_VERSION = 3;
23
- const MAX_FILES = 200_000;
24
- const HEAD_BYTES = 16 * 1024;
25
- const MAX_HEAD_FILE_BYTES = 2 * 1024 * 1024;
26
- const MAX_IDENTIFIERS = 200;
27
- const STAT_CONCURRENCY = 64;
28
- const WATCH_DEBOUNCE_MS = 800;
29
- const SNAPSHOT_DEBOUNCE_MS = 10_000;
30
- /** Số tệp tài liệu tối đa có vector (mỗi vector ~1,4 KB). */
31
- const MAX_VECTOR_FILES = Number(process.env.AIVIN_REMOTE_MAX_VECTOR_FILES) || 20_000;
32
- const EMBED_BATCH = 32;
33
- const BACKOFF_BASE_MS = 30_000;
34
- const BACKOFF_MAX_MS = 30 * 60_000;
35
- const RANK_DEPTH = 50;
36
- /** Hằng số k của Reciprocal Rank Fusion. */
37
- const RRF_K = 60;
38
- const TEXT_EXTENSIONS = new Set([
39
- '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.md', '.txt', '.yaml', '.yml', '.toml', '.ini', '.env', '.py', '.go', '.rs',
40
- '.java', '.kt', '.cs', '.cpp', '.cc', '.c', '.h', '.hpp', '.php', '.rb', '.swift', '.scala', '.sql', '.sh', '.ps1', '.bat', '.cmd',
41
- '.html', '.css', '.scss', '.vue', '.svelte', '.xml', '.gradle', '.proto', '.graphql', '.dart', '.lua', '.r', '.csv',
42
- ]);
43
- /** Chỉ bỏ khi LẬP CHỈ MỤC (fs.list / fs.grep vẫn vào được): dữ liệu ứng dụng, hệ điều hành, thùng rác, kho gói — hàng trăm nghìn tệp vô ích. */
44
- const INDEX_SKIP_DIRS = new Set([
45
- 'AppData', 'Application Data', 'Local Settings', '$Recycle.Bin', 'System Volume Information', 'Windows', 'Program Files',
46
- 'Program Files (x86)', 'ProgramData', 'Library', '.Trash', '.npm', '.yarn', '.pnpm-store', '.nuget', '.m2', '.cargo', '.rustup',
47
- '.vscode', '.cursor', '.docker', 'miniconda3', 'anaconda3', 'snap',
48
- ]);
49
- /** Thư mục người dùng quét trước (ngay dưới gốc) — tài liệu thật thường nằm ở đây. */
50
- const PRIORITY_DIRS = ['Desktop', 'Documents', 'Downloads', 'OneDrive', 'Pictures', 'Dropbox', 'Google Drive'];
51
- /** Bộ theo dõi thư mục hỏng (gốc bị xoá, rút ổ ngoài, Linux hết inotify) → quét lại tăng dần theo nhịp này thay vì để chỉ mục cũ mãi. */
52
- const RESCAN_MS = 10 * 60_000;
53
-
54
- /**
55
- * Tệp nhìn như chứa bí mật (tên hoặc đoạn đầu): không giữ đoạn chữ / định danh trong chỉ mục, không gửi đi tính vector, không đưa vào gợi
56
- * ý của Planner — "mat-khau.txt" tên bình thường mà nội dung là mật khẩu (rà 28/10/2026). Vẫn tìm được theo TÊN tệp.
57
- */
58
- const SECRET_NAME_RE = /(passw|mat[-_ ]?khau|mật[-_ ]?khẩu|secret|credential|(^|[^a-z])tokens?([^a-z]|$)|private[-_ ]?key|recovery[-_ ]?code|seed[-_ ]?phrase|(^|[^a-z0-9])(2fa|otp)([^a-z]|$)|\.env$|id_(rsa|ed25519|ecdsa|dsa)|\.(pem|key|p12|pfx|kdbx|ovpn)$)/i;
59
- const SECRET_TEXT_RE = /(-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(password|passwd|pwd|mật khẩu|mat khau|api[_-]?key|secret|token)\s*[:=]\s*\S{4,}|\bAKIA[0-9A-Z]{16}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bsk-[A-Za-z0-9_-]{20,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,})/i;
60
-
61
- export function looksSecret(abs, text = '') {
62
- return SECRET_NAME_RE.test(path.basename(abs)) || (!!text && SECRET_TEXT_RE.test(text));
63
- }
64
-
65
- const skipDir = (name) => IGNORED_DIRS.has(name) || INDEX_SKIP_DIRS.has(name);
66
-
67
- function identifiersOf(text) {
68
- const seen = new Set();
69
- for (const m of text.matchAll(/[\p{L}_][\p{L}\p{N}_]{2,}/gu)) {
70
- seen.add(m[0]);
71
- if (seen.size >= MAX_IDENTIFIERS) break;
72
- }
73
- return [...seen].join(' ');
74
- }
75
-
76
- async function headTokens(abs, size) {
77
- if (!TEXT_EXTENSIONS.has(path.extname(abs).toLowerCase()) || size > MAX_HEAD_FILE_BYTES) return '';
78
- let handle;
79
- try {
80
- handle = await fs.promises.open(abs, 'r');
81
- const buf = Buffer.alloc(Math.min(HEAD_BYTES, size));
82
- const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
83
- return identifiersOf(buf.subarray(0, bytesRead).toString('utf8'));
84
- } catch {
85
- return '';
86
- } finally {
87
- await handle?.close().catch(() => undefined);
88
- }
89
- }
90
-
91
- async function mapLimit(items, limit, fn) {
92
- let cursor = 0;
93
- const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
94
- while (cursor < items.length) {
95
- const i = cursor++;
96
- await fn(items[i], i);
97
- }
98
- });
99
- await Promise.all(workers);
100
- }
101
-
102
- /** Duyệt cây (bỏ thư mục rác / hệ thống, không theo symlink ra ngoài) → danh sách đường tuyệt đối của tệp. */
103
- async function walk(root, limit, skip = new Set()) {
104
- const files = [];
105
- const queue = [root];
106
- while (queue.length && files.length < limit) {
107
- const batch = queue.splice(0, STAT_CONCURRENCY);
108
- await mapLimit(batch, STAT_CONCURRENCY, async (dir) => {
109
- let entries;
110
- try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return; }
111
- for (const entry of entries) {
112
- if (entry.isSymbolicLink()) continue;
113
- const full = path.join(dir, entry.name);
114
- if (isProtectedPath(full) || skip.has(full)) continue;
115
- if (entry.isDirectory()) { if (!skipDir(entry.name)) queue.push(full); } else if (entry.isFile()) files.push(full);
116
- }
117
- });
118
- }
119
- return files.slice(0, limit);
120
- }
121
-
122
- /** Thư mục ưu tiên có thật ngay dưới các gốc (kể cả `OneDrive - Công ty`). */
123
- function priorityDirsOf(roots) {
124
- const out = [];
125
- for (const root of roots) {
126
- let names = [];
127
- try { names = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name); } catch { continue; }
128
- for (const want of PRIORITY_DIRS) {
129
- for (const name of names) if (name === want || name.startsWith(`${want} -`)) out.push(path.join(root, name));
130
- }
131
- }
132
- return out;
133
- }
134
-
135
- const vectorKey = (entry) => `${entry.mtime}:${entry.size}`;
136
-
137
- export function createFileIndex(roots) {
138
- const resolvedRoots = roots.map((r) => path.resolve(r));
139
- const entries = new Map(); // abs → { mtime, size, tokens, preview? }
140
- const vectors = new Map(); // abs → { key, b64, vec: Int8Array }
141
- const index = createTextIndex();
142
- const watchers = [];
143
- let rescanTimer = null;
144
- let snapshotTimer;
145
- let vectorTimer;
146
- let lastBuild = null;
147
- let priorityDirs = [];
148
- let embedder = null;
149
- let vectorizing = false;
150
- let failures = 0;
151
- let pausedUntil = 0;
152
-
153
- const docText = (abs, entry) => `${abs.split(path.sep).slice(-6).join(' ')} ${entry.tokens || ''} ${entry.preview || ''}`;
154
- const isPriority = (abs) => priorityDirs.some((d) => abs.startsWith(d + path.sep));
155
-
156
- function setEntry(abs, entry) {
157
- entries.set(abs, entry);
158
- index.add(abs, docText(abs, entry));
159
- }
160
-
161
- function dropEntry(abs) {
162
- entries.delete(abs);
163
- vectors.delete(abs);
164
- index.remove(abs);
165
- }
166
-
167
- function loadSnapshot() {
168
- try {
169
- const data = JSON.parse(zlib.gunzipSync(fs.readFileSync(SNAPSHOT_FILE)).toString('utf8'));
170
- if (data?.version !== SNAPSHOT_VERSION || JSON.stringify(data.roots) !== JSON.stringify(resolvedRoots)) return 0;
171
- for (const [abs, mtime, size, tokens, preview] of data.entries || []) setEntry(abs, { mtime, size, tokens, ...(preview ? { preview } : {}) });
172
- loadVectors();
173
- return entries.size;
174
- } catch {
175
- return 0;
176
- }
177
- }
178
-
179
- function loadVectors() {
180
- try {
181
- const data = JSON.parse(zlib.gunzipSync(fs.readFileSync(VECTORS_FILE)).toString('utf8'));
182
- for (const [abs, key, b64] of data.vectors || []) {
183
- const entry = entries.get(abs);
184
- if (entry && vectorKey(entry) === key) vectors.set(abs, { key, b64, vec: decodeInt8(b64) });
185
- }
186
- } catch { /* chưa có vector — tính dần */ }
187
- }
188
-
189
- function atomicGzip(file, payload) {
190
- fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
191
- const tmp = `${file}.tmp-${process.pid}`;
192
- fs.writeFileSync(tmp, zlib.gzipSync(JSON.stringify(payload)));
193
- fs.renameSync(tmp, file);
194
- }
195
-
196
- function saveSnapshot() {
197
- try {
198
- atomicGzip(SNAPSHOT_FILE, {
199
- version: SNAPSHOT_VERSION, roots: resolvedRoots,
200
- entries: [...entries.entries()].map(([abs, e]) => (e.preview ? [abs, e.mtime, e.size, e.tokens, e.preview] : [abs, e.mtime, e.size, e.tokens])),
201
- });
202
- atomicGzip(VECTORS_FILE, { vectors: [...vectors.entries()].map(([abs, v]) => [abs, v.key, v.b64]) });
203
- } catch { /* bản chụp chỉ để khởi động nhanh — hỏng thì lần sau quét lại */ }
204
- }
205
-
206
- function scheduleSnapshot() {
207
- clearTimeout(snapshotTimer);
208
- snapshotTimer = setTimeout(saveSnapshot, SNAPSHOT_DEBOUNCE_MS);
209
- snapshotTimer.unref?.();
210
- }
211
-
212
- async function refreshFile(abs) {
213
- let stat;
214
- try { stat = await fs.promises.stat(abs); } catch { if (entries.has(abs)) dropEntry(abs); return 'removed'; }
215
- if (!stat.isFile()) return 'skipped';
216
- const mtime = Math.floor(stat.mtimeMs);
217
- const prev = entries.get(abs);
218
- if (prev && prev.mtime === mtime && prev.size === stat.size) return 'same';
219
- const preview = isDocFile(abs) ? await extractDocText(abs, stat.size) : '';
220
- const tokens = await headTokens(abs, stat.size);
221
- // Tệp như chứa bí mật: chỉ giữ tên (tìm theo tên vẫn được), bỏ đoạn chữ + định danh.
222
- if (looksSecret(abs, `${preview}\n${tokens}`)) setEntry(abs, { mtime, size: stat.size, tokens: '', secret: true });
223
- else setEntry(abs, { mtime, size: stat.size, tokens, ...(preview ? { preview } : {}) });
224
- vectors.delete(abs);
225
- return 'updated';
226
- }
227
-
228
- /** Quét tăng dần: thư mục người dùng trước, rồi phần còn lại của các gốc. Tệp mới / đổi được đọc lại, tệp mất bị bỏ. */
229
- async function build() {
230
- const startedAt = Date.now();
231
- const fromSnapshot = entries.size ? 0 : loadSnapshot();
232
- priorityDirs = priorityDirsOf(resolvedRoots);
233
- const found = new Set();
234
- let updated = 0;
235
- for (const dir of [...priorityDirs, ...resolvedRoots]) {
236
- if (found.size >= MAX_FILES) break;
237
- const skip = resolvedRoots.includes(dir) ? new Set(priorityDirs) : new Set();
238
- const files = (await walk(dir, MAX_FILES - found.size, skip)).filter((f) => !found.has(f));
239
- files.forEach((f) => found.add(f));
240
- await mapLimit(files, STAT_CONCURRENCY, async (abs) => { if ((await refreshFile(abs)) === 'updated') updated++; });
241
- }
242
- let removed = 0;
243
- for (const abs of [...entries.keys()]) if (!found.has(abs)) { dropEntry(abs); removed++; }
244
- saveSnapshot();
245
- lastBuild = { files: entries.size, updated, removed, from_snapshot: fromSnapshot, capped: found.size >= MAX_FILES, ms: Date.now() - startedAt, at: new Date().toISOString() };
246
- scheduleVectorize(0);
247
- return lastBuild;
248
- }
249
-
250
- function watch() {
251
- const pending = new Set();
252
- let timer;
253
- const flush = async () => {
254
- const batch = [...pending];
255
- pending.clear();
256
- await mapLimit(batch, STAT_CONCURRENCY, refreshFile);
257
- scheduleSnapshot();
258
- scheduleVectorize(5_000);
259
- };
260
- const fallBackToRescan = () => {
261
- // Bộ theo dõi hỏng: đóng, chuyển sang quét lại định kỳ (tăng dần — chỉ đọc tệp có mtime / size đổi).
262
- if (rescanTimer) return;
263
- rescanTimer = setInterval(() => void build().catch(() => undefined), RESCAN_MS);
264
- rescanTimer.unref?.();
265
- };
266
- for (const root of resolvedRoots) {
267
- try {
268
- const w = fs.watch(root, { recursive: true }, (_event, name) => {
269
- if (!name) return;
270
- const rel = String(name);
271
- if (rel.split(/[\\/]/).some((seg) => skipDir(seg))) return;
272
- if (isProtectedPath(path.join(root, rel))) return;
273
- pending.add(path.join(root, rel));
274
- clearTimeout(timer);
275
- timer = setTimeout(() => void flush(), WATCH_DEBOUNCE_MS);
276
- });
277
- // Không có listener 'error' thì lỗi của bộ theo dõi (gốc bị xoá, rút ổ ngoài, hết inotify) ném ra ngoài và làm sập daemon.
278
- w.on('error', () => {
279
- try { w.close(); } catch { /* đã đóng */ }
280
- fallBackToRescan();
281
- });
282
- w.unref?.();
283
- watchers.push(w);
284
- } catch { fallBackToRescan(); /* không theo dõi được (hệ thống tệp mạng…) */ }
285
- }
286
- }
287
-
288
- /** Đoạn mô tả đưa đi tính vector: tên + thư mục gần nhất + chữ đầu tệp. */
289
- const embedText = (abs, entry) => `${path.basename(abs)} | ${path.dirname(abs).split(path.sep).slice(-3).join(' / ')}${entry.preview ? ` | ${entry.preview}` : ''}`;
290
-
291
- /** Tệp tài liệu cần (tính lại) vector: thư mục người dùng trước, mới sửa trước; giữ trong trần MAX_VECTOR_FILES. */
292
- function vectorQueue() {
293
- const docs = [...entries.entries()].filter(([abs, e]) => isDocFile(abs) && !e.secret)
294
- .sort(([a, ea], [b, eb]) => (Number(isPriority(b)) - Number(isPriority(a))) || (eb.mtime - ea.mtime))
295
- .slice(0, MAX_VECTOR_FILES);
296
- const keep = new Set(docs.map(([abs]) => abs));
297
- for (const abs of [...vectors.keys()]) if (!keep.has(abs)) vectors.delete(abs);
298
- return docs.filter(([abs, e]) => vectors.get(abs)?.key !== vectorKey(e));
299
- }
300
-
301
- /**
302
- * Tính vector nền theo lô (`embed(texts) → base64[]`, BE tính bằng bge-m3). BE cũ / lỗi → dừng, lần sau thử lại; tìm theo từ khoá vẫn
303
- * chạy bình thường.
304
- */
305
- async function vectorize() {
306
- if (!embedder || vectorizing || Date.now() < pausedUntil) return { embedded: 0, total: vectors.size };
307
- vectorizing = true;
308
- let embedded = 0;
309
- let failed = false;
310
- try {
311
- const queue = vectorQueue();
312
- for (let i = 0; i < queue.length; i += EMBED_BATCH) {
313
- const batch = queue.slice(i, i + EMBED_BATCH);
314
- const out = await embedder(batch.map(([abs, e]) => wellFormed(embedText(abs, e))));
315
- if (!Array.isArray(out) || out.length !== batch.length) { failed = true; break; }
316
- batch.forEach(([abs, e], j) => { if (out[j]) vectors.set(abs, { key: vectorKey(e), b64: out[j], vec: decodeInt8(out[j]) }); });
317
- embedded += batch.length;
318
- failures = 0;
319
- if (embedded % 512 === 0) scheduleSnapshot();
320
- }
321
- } catch { failed = true; } finally {
322
- vectorizing = false;
323
- }
324
- if (embedded) scheduleSnapshot();
325
- // BE bận / lỗi → nghỉ giãn dần (30 s → tối đa 30 phút) thay vì thử lại mỗi lần tệp đổi — không dồn tải lên dịch vụ vector dùng chung.
326
- if (failed) {
327
- failures++;
328
- const pauseMs = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (failures - 1));
329
- pausedUntil = Date.now() + pauseMs;
330
- scheduleVectorize(pauseMs + 1_000);
331
- }
332
- return { embedded, total: vectors.size, failed: failed || undefined };
333
- }
334
-
335
- function scheduleVectorize(delayMs) {
336
- if (!embedder) return;
337
- clearTimeout(vectorTimer);
338
- vectorTimer = setTimeout(() => void vectorize(), delayMs);
339
- vectorTimer.unref?.();
340
- }
341
-
342
- function setEmbedder(fn) {
343
- embedder = fn;
344
- if (lastBuild) scheduleVectorize(2_000);
345
- }
346
-
347
- function close() {
348
- if (rescanTimer) { clearInterval(rescanTimer); rescanTimer = null; }
349
- watchers.splice(0).forEach((w) => w.close());
350
- clearTimeout(snapshotTimer);
351
- clearTimeout(vectorTimer);
352
- saveSnapshot();
353
- }
354
-
355
- /**
356
- * Tìm theo tên / đường dẫn / định danh / chữ đầu tài liệu; có `vector` (bge-m3 int8 base64 của câu hỏi) thì gộp thêm xếp hạng ngữ
357
- * nghĩa. Trả đường hiển thị tương đối với gốc + dung lượng, ngày sửa, đoạn xem trước.
358
- */
359
- function search(query, limit = 10, vector) {
360
- const lexical = index.search(query, { limit: Math.max(limit, RANK_DEPTH) }).map((r) => r.id);
361
- const q = vector ? decodeInt8(vector) : null;
362
- const semantic = q && vectors.size
363
- ? [...vectors.entries()].map(([abs, v]) => [abs, int8Cosine(q, v.vec)]).sort((a, b) => b[1] - a[1]).slice(0, RANK_DEPTH)
364
- : [];
365
- const similarity = new Map(semantic);
366
- const ranked = semantic.length ? fuse(lexical, semantic.map(([abs]) => abs), similarity) : lexical;
367
- return ranked.slice(0, limit).map((id) => {
368
- const root = resolvedRoots.find((r) => id.startsWith(r)) || resolvedRoots[0];
369
- const e = entries.get(id);
370
- return {
371
- path: path.relative(root, id) || id,
372
- size: e?.size,
373
- modified: e?.mtime ? new Date(e.mtime).toISOString().slice(0, 10) : undefined,
374
- ...(e?.preview ? { preview: e.preview.slice(0, 200) } : {}),
375
- ...(similarity.has(id) ? { similarity: Number(similarity.get(id).toFixed(3)) } : {}),
376
- };
377
- });
378
- }
379
-
380
- return {
381
- build, watch, close, search, refreshFile, vectorize, setEmbedder,
382
- stats: () => ({ files: entries.size, vectors: vectors.size, last_build: lastBuild }),
383
- };
384
- }
385
-
386
- /**
387
- * Gộp hai bảng xếp hạng (RRF). Hoà điểm — tệp đầu bảng từ khoá vs tệp đầu bảng ngữ nghĩa — thì tệp gần nghĩa hơn đứng trước: từ khoá
388
- * chỉ trùng một chữ chung ("thuê") hay gặp hơn là trùng nghĩa.
389
- */
390
- function fuse(lexical, semantic, similarity) {
391
- const score = new Map();
392
- for (const list of [lexical, semantic]) list.forEach((id, rank) => score.set(id, (score.get(id) || 0) + 1 / (RRF_K + rank + 1)));
393
- return [...score.keys()].sort((a, b) => (score.get(b) - score.get(a)) || ((similarity.get(b) ?? -1) - (similarity.get(a) ?? -1)));
394
- }
395
-
396
- /** Gốc lập chỉ mục: máy toàn quyền chỉ quét thư mục nhà (cả ổ là hàng trăm nghìn tệp hệ thống). */
397
- export function indexRootsFor(roots, fullAccess) {
398
- return fullAccess ? [os.homedir()] : roots;
399
- }
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import zlib from 'zlib';
5
+ import { REMOTE_CONFIG_DIR } from './constants.mjs';
6
+ import { cloudOnlyFiles, inCloudFolder } from './cloudFiles.mjs';
7
+ import { extractDocText, isDocFile, wellFormed } from './docText.mjs';
8
+ import { FolderKind, classifyDir, folderSummary, skipDir, skipFile } from './folderRules.mjs';
9
+ import { isProtectedPath } from './sandbox.mjs';
10
+ import { openSqlite } from './sqliteDb.mjs';
11
+ import { decodeInt8, int8Cosine, tokenize } from './textIndex.mjs';
12
+
13
+ /**
14
+ * Chỉ mục tệp (SQLite trên đĩa) cho các thư mục được phép: tên/đường dẫn + định danh đầu tệp (hàm, lớp, khoá…) → tìm tức thì theo tên lẫn
15
+ * nội dung chính mà không quét đĩa mỗi lần. Khởi động: mở chỉ mục đã có, quét lại TĂNG DẦN (chỉ đọc tệp có mtime/size đổi). Chạy: theo
16
+ * dõi thư mục (`fs.watch` đệ quy), cập nhật đúng tệp đổi.
17
+ *
18
+ * Tệp dạng tài liệu (docx/xlsx/pptx/pdf/txt…) có thêm đoạn chữ đầu (`preview`, đọc cả trong gói Office) và vector bge-m3 do BE tính
19
+ * (`vectorize`, chạy nền): tìm kết hợp từ khoá BM25 + ngữ nghĩa (cosine) gộp bằng RRF — "hợp đồng thuê văn phòng" ra
20
+ * `HD_thue_VP_2026.pdf`. Thư mục người dùng (Desktop, Documents, Downloads, OneDrive…) quét trước để trần số tệp không cắt mất chúng.
21
+ *
22
+ * Bỏ / gộp theo folderRules.mjs (thư mục ẩn, tệp tạm, thư mục ứng dụng, thư mục hàng loạt ảnh / log, kho git → một mục đại diện). Tệp chỉ có
23
+ * trên mây: chỉ lập chỉ mục tên (cloudFiles.mjs). Thư mục làm việc người dùng chỉ định (`addFolder`, `index-folders.json`) lập chỉ mục đầy
24
+ * đủ, kể cả code trong kho git.
25
+ */
26
+
27
+ const DB_FILE = path.join(REMOTE_CONFIG_DIR, 'file-index.db');
28
+ /** Thư mục làm việc người dùng chỉ định (qua chat — công cụ fs.index_folder — hoặc `aivin remote index add`). */
29
+ const INDEX_FOLDERS_FILE = path.join(REMOTE_CONFIG_DIR, 'index-folders.json');
30
+ /** Mẫu loại trừ người dùng chỉ định (`aivin remote index-exclude add`). */
31
+ const INDEX_EXCLUDES_FILE = path.join(REMOTE_CONFIG_DIR, 'index-excludes.json');
32
+ /** Bản chụp gzip của bản giữ chỉ mục trong RAM (≤ 1.0.11) — chép sang SQLite lần đầu rồi xoá. */
33
+ const LEGACY_SNAPSHOT_FILE = path.join(REMOTE_CONFIG_DIR, 'file-index.json.gz');
34
+ const LEGACY_VECTORS_FILE = path.join(REMOTE_CONFIG_DIR, 'file-vectors.json.gz');
35
+ const LEGACY_SNAPSHOT_VERSION = 3;
36
+ const MAX_FILES = 200_000;
37
+ const HEAD_BYTES = 16 * 1024;
38
+ const MAX_HEAD_FILE_BYTES = 2 * 1024 * 1024;
39
+ const MAX_IDENTIFIERS = 200;
40
+ const STAT_CONCURRENCY = 64;
41
+ const WATCH_DEBOUNCE_MS = 800;
42
+ /** Từ trong câu hỏi dài từ chừng này trở lên thì khớp cả tiền tố ("auth" ↔ "authentication"). */
43
+ const PREFIX_MIN = 4;
44
+ /** Số vector đọc mỗi lần khi tìm theo nghĩa. */
45
+ const VECTOR_SCAN_CHUNK = 2000;
46
+ /** Số tệp tài liệu tối đa có vector (mỗi vector ~1,4 KB). */
47
+ const MAX_VECTOR_FILES = Number(process.env.AIVIN_REMOTE_MAX_VECTOR_FILES) || 20_000;
48
+ const EMBED_BATCH = 32;
49
+ const BACKOFF_BASE_MS = 30_000;
50
+ const BACKOFF_MAX_MS = 30 * 60_000;
51
+ const RANK_DEPTH = 50;
52
+ /** Hằng số k của Reciprocal Rank Fusion. */
53
+ const RRF_K = 60;
54
+ const TEXT_EXTENSIONS = new Set([
55
+ '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.md', '.txt', '.yaml', '.yml', '.toml', '.py', '.go', '.rs',
56
+ '.java', '.kt', '.cs', '.cpp', '.cc', '.c', '.h', '.hpp', '.php', '.rb', '.swift', '.scala', '.sql', '.sh', '.ps1', '.bat', '.cmd',
57
+ '.html', '.css', '.scss', '.vue', '.svelte', '.xml', '.gradle', '.proto', '.graphql', '.dart', '.lua', '.r', '.csv',
58
+ ]);
59
+ /** Thư mục người dùng quét trước (ngay dưới gốc) — tài liệu thật thường nằm ở đây. */
60
+ const PRIORITY_DIRS = ['Desktop', 'Documents', 'Downloads', 'OneDrive', 'Pictures', 'Dropbox', 'Google Drive'];
61
+ /** Bộ theo dõi thư mục hỏng (gốc bị xoá, rút ổ ngoài, Linux hết inotify) → quét lại tăng dần theo nhịp này thay vì để chỉ mục cũ mãi. */
62
+ const RESCAN_MS = 10 * 60_000;
63
+ /** CLI (`aivin remote index add`) sửa danh sách thư mục làm việc khi listener đang chạy → listener thấy sau chừng này. */
64
+ const INDEX_FOLDERS_POLL_MS = 5_000;
65
+
66
+ /**
67
+ * Tệp nhìn như chứa bí mật (tên hoặc đoạn đầu): không giữ đoạn chữ / định danh trong chỉ mục, không gửi đi tính vector, không đưa vào gợi
68
+ * ý của Planner — "mat-khau.txt" tên bình thường mà nội dung là mật khẩu (rà 28/10/2026). Vẫn tìm được theo TÊN tệp.
69
+ */
70
+ const SECRET_NAME_RE = /(passw|mat[-_ ]?khau|mật[-_ ]?khẩu|secret|credential|(^|[^a-z])tokens?([^a-z]|$)|private[-_ ]?key|recovery[-_ ]?code|seed[-_ ]?phrase|(^|[^a-z0-9])(2fa|otp)([^a-z]|$)|\.env$|id_(rsa|ed25519|ecdsa|dsa)|\.(pem|key|p12|pfx|kdbx|ovpn)$)/i;
71
+ const SECRET_TEXT_RE = /(-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(password|passwd|pwd|mật khẩu|mat khau|api[_-]?key|secret|token)\s*[:=]\s*\S{4,}|\bAKIA[0-9A-Z]{16}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bsk-[A-Za-z0-9_-]{20,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,})/i;
72
+
73
+ export function looksSecret(abs, text = '') {
74
+ return SECRET_NAME_RE.test(path.basename(abs)) || (!!text && SECRET_TEXT_RE.test(text));
75
+ }
76
+
77
+ function identifiersOf(text) {
78
+ const seen = new Set();
79
+ for (const m of text.matchAll(/[\p{L}_][\p{L}\p{N}_]{2,}/gu)) {
80
+ seen.add(m[0]);
81
+ if (seen.size >= MAX_IDENTIFIERS) break;
82
+ }
83
+ return [...seen].join(' ');
84
+ }
85
+
86
+ const readsContent = (abs) => isDocFile(abs) || TEXT_EXTENSIONS.has(path.extname(abs).toLowerCase());
87
+
88
+ async function headTokens(abs, size) {
89
+ if (!TEXT_EXTENSIONS.has(path.extname(abs).toLowerCase()) || size > MAX_HEAD_FILE_BYTES) return '';
90
+ let handle;
91
+ try {
92
+ handle = await fs.promises.open(abs, 'r');
93
+ const buf = Buffer.alloc(Math.min(HEAD_BYTES, size));
94
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
95
+ return identifiersOf(buf.subarray(0, bytesRead).toString('utf8'));
96
+ } catch {
97
+ return '';
98
+ } finally {
99
+ await handle?.close().catch(() => undefined);
100
+ }
101
+ }
102
+
103
+ async function mapLimit(items, limit, fn) {
104
+ let cursor = 0;
105
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
106
+ while (cursor < items.length) {
107
+ const i = cursor++;
108
+ await fn(items[i], i);
109
+ }
110
+ });
111
+ await Promise.all(workers);
112
+ }
113
+
114
+ /**
115
+ * Duyệt cây theo folderRules (không theo symlink ra ngoài): bỏ thư mục ẩn / rác, gộp thư mục ứng dụng / hàng loạt / kho git thành một mục.
116
+ * `full` (thư mục làm việc người dùng chỉ định): kho git bên trong cũng lập chỉ mục đầy đủ. Gốc của lần duyệt không bị gộp.
117
+ * → `{ files: [{ abs, repo }], folders: [{ abs, kind, mtime, count, note, words }] }` (`repo` = nằm trong kho git → chỉ giữ tài liệu).
118
+ */
119
+ async function walk(root, limit, { skip = new Set(), full = false, excludes = null } = {}) {
120
+ const files = [];
121
+ const folders = [];
122
+ const queue = [{ dir: root, repo: false }];
123
+ const collapse = async (dir, kind, entries) => {
124
+ const stat = await fs.promises.stat(dir).catch(() => null);
125
+ folders.push({ abs: dir, kind, mtime: stat ? Math.floor(stat.mtimeMs) : 0, ...folderSummary(kind, dir, entries) });
126
+ };
127
+ while (queue.length && files.length < limit) {
128
+ const batch = queue.splice(0, STAT_CONCURRENCY);
129
+ await mapLimit(batch, STAT_CONCURRENCY, async ({ dir, repo }) => {
130
+ let entries;
131
+ try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return; }
132
+ const kind = dir === root ? null : classifyDir(path.basename(dir), entries);
133
+ if (kind === FolderKind.APP) return collapse(dir, kind, entries);
134
+ let inRepo = repo;
135
+ if (kind === FolderKind.REPO && !full) {
136
+ if (!repo) await collapse(dir, kind, entries);
137
+ inRepo = true;
138
+ }
139
+ const bulk = kind === FolderKind.BULK;
140
+ if (bulk) await collapse(dir, kind, entries);
141
+ for (const entry of entries) {
142
+ if (entry.isSymbolicLink()) continue;
143
+ const abs = path.join(dir, entry.name);
144
+ if (isProtectedPath(abs) || skip.has(abs)) continue;
145
+ if (entry.isDirectory()) {
146
+ if (!skipDir(entry.name, excludes)) queue.push({ dir: abs, repo: inRepo });
147
+ } else if (entry.isFile() && !skipFile(entry.name, excludes) && (!(bulk || inRepo) || isDocFile(entry.name))) {
148
+ files.push({ abs, repo: inRepo });
149
+ }
150
+ }
151
+ });
152
+ }
153
+ return { files: files.slice(0, limit), folders };
154
+ }
155
+
156
+ /** Thư mục ưu tiên có thật ngay dưới các gốc (kể cả `OneDrive - Công ty`). */
157
+ function priorityDirsOf(roots) {
158
+ const out = [];
159
+ for (const root of roots) {
160
+ let names;
161
+ try { names = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name); } catch { continue; }
162
+ for (const want of PRIORITY_DIRS) {
163
+ for (const name of names) if (name === want || name.startsWith(`${want} -`)) out.push(path.join(root, name));
164
+ }
165
+ }
166
+ return out;
167
+ }
168
+
169
+ /** Thư mục làm việc người dùng chỉ định (đường tuyệt đối). */
170
+ export function loadIndexFolders() {
171
+ try {
172
+ const data = JSON.parse(fs.readFileSync(INDEX_FOLDERS_FILE, 'utf8'));
173
+ return Array.isArray(data?.folders) ? data.folders.filter((f) => typeof f === 'string' && path.isAbsolute(f)) : [];
174
+ } catch {
175
+ return [];
176
+ }
177
+ }
178
+
179
+ export function saveIndexFolders(folders) {
180
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
181
+ const list = [...new Set(folders.map((f) => path.resolve(f)))];
182
+ fs.writeFileSync(INDEX_FOLDERS_FILE, JSON.stringify({ folders: list }, null, 2));
183
+ return list;
184
+ }
185
+
186
+ /** Mẫu loại trừ người dùng chỉ định (`index-excludes.json`). */
187
+ export function loadIndexExcludes() {
188
+ try {
189
+ const data = JSON.parse(fs.readFileSync(INDEX_EXCLUDES_FILE, 'utf8'));
190
+ return Array.isArray(data?.excludes) ? data.excludes.filter((e) => typeof e === 'string' && e.trim().length > 0) : [];
191
+ } catch {
192
+ return [];
193
+ }
194
+ }
195
+
196
+ export function saveIndexExcludes(excludes) {
197
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
198
+ const list = [...new Set(excludes.map((e) => String(e).trim()).filter(Boolean))];
199
+ fs.writeFileSync(INDEX_EXCLUDES_FILE, JSON.stringify({ excludes: list }, null, 2));
200
+ return list;
201
+ }
202
+
203
+ /** Đọc các mẫu loại trừ từ tệp `.aivinignore` trong thư mục (nếu có). */
204
+ export function loadIgnoreFile(dir) {
205
+ const ignorePath = path.join(dir, '.aivinignore');
206
+ try {
207
+ return fs.readFileSync(ignorePath, 'utf8')
208
+ .split(/\r?\n/)
209
+ .map((line) => line.trim())
210
+ .filter((line) => line.length > 0 && !line.startsWith('#'));
211
+ } catch {
212
+ return [];
213
+ }
214
+ }
215
+
216
+ const within = (dir, abs) => abs === dir || abs.startsWith(dir.endsWith(path.sep) ? dir : dir + path.sep);
217
+ const vectorKey = (entry) => `${entry.mtime}:${entry.size}`;
218
+
219
+ /** Đổi bảng → tăng số này: chỉ mục cũ bị bỏ, quét lại từ đầu. */
220
+ const SCHEMA_VERSION = '2';
221
+ const PRAGMAS = `
222
+ PRAGMA journal_mode = WAL;
223
+ PRAGMA synchronous = NORMAL;
224
+ PRAGMA busy_timeout = 5000;
225
+ PRAGMA cache_size = -8000;
226
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
227
+ `;
228
+ // FTS5 không giữ bản chữ (contentless) — chữ tách sẵn chỉ cần để lập chỉ mục; xem / xếp hạng dùng bảng files. `kind` ≠ NULL: mục đại diện
229
+ // cho một thư mục gộp (FolderKind), `size` = số mục bên trong, `preview` = ghi chú cho agent.
230
+ const SCHEMA = `
231
+ CREATE TABLE IF NOT EXISTS files (
232
+ id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE, mtime INTEGER, size INTEGER, preview TEXT, kind TEXT,
233
+ secret INTEGER NOT NULL DEFAULT 0, doc INTEGER NOT NULL DEFAULT 0, prio INTEGER NOT NULL DEFAULT 0
234
+ );
235
+ CREATE INDEX IF NOT EXISTS files_vector_order ON files (doc, secret, prio DESC, mtime DESC);
236
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5 (
237
+ body, content = '', contentless_delete = 1, tokenize = 'unicode61 remove_diacritics 0', prefix = '${PREFIX_MIN}'
238
+ );
239
+ CREATE TABLE IF NOT EXISTS vectors (id INTEGER PRIMARY KEY, key TEXT NOT NULL, vec BLOB NOT NULL);
240
+ `;
241
+
242
+ /**
243
+ * Chỉ mục nằm trên đĩa (SQLite, `file-index.db`), không nạp vào RAM: bảng `files` (đường dẫn, mtime/size, chữ đầu tài liệu, mục thư mục
244
+ * gộp), FTS5 cho từ khoá (BM25 + khớp tiền tố, chữ đã tách sẵn bằng `tokenize` — bỏ dấu, camelCase, chữ Hán thành cặp), `vectors` (int8
245
+ * BLOB). Tìm chỉ đọc vài trang B-tree; vector quét theo khúc. ~100k tệp từng ngốn ~1 GB RAM khi mọi thứ là Map / Set trong bộ nhớ.
246
+ */
247
+ export function createFileIndex(roots) {
248
+ const resolvedRoots = roots.map((r) => path.resolve(r));
249
+ const watchers = new Map(); // thư mục được theo dõi → fs.FSWatcher
250
+ let db = null;
251
+ let opening = null;
252
+ let st = null;
253
+ let migrated = 0;
254
+ let rescanTimer = null;
255
+ let vectorTimer;
256
+ let lastBuild = null;
257
+ let priorityDirs = [];
258
+ let indexFolders = loadIndexFolders();
259
+ let indexExcludes = loadIndexExcludes();
260
+ const rootIgnores = resolvedRoots.flatMap(loadIgnoreFile);
261
+ let activeExcludes = new Set([...indexExcludes, ...rootIgnores].map((s) => s.toLowerCase()));
262
+
263
+ const reloadExcludes = () => {
264
+ indexExcludes = loadIndexExcludes();
265
+ const updatedRoots = resolvedRoots.flatMap(loadIgnoreFile);
266
+ activeExcludes = new Set([...indexExcludes, ...updatedRoots].map((s) => s.toLowerCase()));
267
+ };
268
+ /** Thư mục gộp đã biết (từ chỉ mục) — để bộ theo dõi không lập chỉ mục lẻ từng ảnh chụp màn hình mới. */
269
+ let collapsed = [];
270
+ let watching = false;
271
+ let embedder = null;
272
+ let vectorizing = false;
273
+ let failures = 0;
274
+ let pausedUntil = 0;
275
+
276
+ const docText = (abs, entry) => `${abs.split(path.sep).slice(-6).join(' ')} ${entry.tokens || ''} ${entry.preview || ''}`;
277
+ const isPriority = (abs) => priorityDirs.some((d) => within(d, abs)) || indexFolders.some((d) => within(d, abs));
278
+ /** Nằm trong thư mục / là tệp không lập chỉ mục (tính từ gốc) — bản chụp cũ còn giữ những tệp này. */
279
+ const skippedPath = (abs) => {
280
+ const root = resolvedRoots.find((r) => within(r, abs));
281
+ if (!root) return true;
282
+ const segs = path.relative(root, abs).split(path.sep);
283
+ return segs.slice(0, -1).some((d) => skipDir(d, activeExcludes)) || skipFile(segs[segs.length - 1], activeExcludes);
284
+ };
285
+
286
+ function ensureOpen() {
287
+ if (!opening) {
288
+ opening = (async () => {
289
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
290
+ db = await openSqlite(DB_FILE);
291
+ db.exec(PRAGMAS);
292
+ const meta = (key) => db.prepare('SELECT value FROM meta WHERE key = ?').get(key)?.value;
293
+ const setMeta = db.prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value');
294
+ if (meta('schema') !== SCHEMA_VERSION) {
295
+ db.exec('DROP TABLE IF EXISTS files; DROP TABLE IF EXISTS fts; DROP TABLE IF EXISTS vectors; DELETE FROM meta;');
296
+ setMeta.run('schema', SCHEMA_VERSION);
297
+ }
298
+ db.exec(SCHEMA);
299
+ // Đổi gốc (ghép lại với thư mục khác / bật toàn quyền) → chỉ mục cũ vô dụng.
300
+ if (meta('roots') !== JSON.stringify(resolvedRoots)) {
301
+ db.exec('DELETE FROM files; DELETE FROM fts; DELETE FROM vectors;');
302
+ setMeta.run('roots', JSON.stringify(resolvedRoots));
303
+ }
304
+ st = {
305
+ find: db.prepare('SELECT id, mtime, size, kind, doc FROM files WHERE path = ?'),
306
+ upsert: db.prepare(`INSERT INTO files (path, mtime, size, preview, kind, secret, doc, prio) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
307
+ ON CONFLICT(path) DO UPDATE SET mtime = excluded.mtime, size = excluded.size, preview = excluded.preview, kind = excluded.kind,
308
+ secret = excluded.secret, doc = excluded.doc, prio = excluded.prio RETURNING id`),
309
+ flags: db.prepare('UPDATE files SET doc = ?, prio = ? WHERE id = ?'),
310
+ ftsDelete: db.prepare('DELETE FROM fts WHERE rowid = ?'),
311
+ ftsInsert: db.prepare('INSERT INTO fts (rowid, body) VALUES (?, ?)'),
312
+ fileDelete: db.prepare('DELETE FROM files WHERE id = ?'),
313
+ vectorDelete: db.prepare('DELETE FROM vectors WHERE id = ?'),
314
+ vectorPut: db.prepare('INSERT INTO vectors (id, key, vec) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET key = excluded.key, vec = excluded.vec'),
315
+ vectorChunk: db.prepare('SELECT id, vec FROM vectors WHERE id > ? ORDER BY id LIMIT ?'),
316
+ lexical: db.prepare('SELECT rowid AS id FROM fts WHERE fts MATCH ? ORDER BY rank LIMIT ?'),
317
+ row: db.prepare('SELECT path, size, mtime, preview, kind FROM files WHERE id = ?'),
318
+ paths: db.prepare('SELECT id, path FROM files'),
319
+ collapsed: db.prepare('SELECT path, kind FROM files WHERE kind IS NOT NULL'),
320
+ fileCount: db.prepare('SELECT count(*) AS n FROM files WHERE kind IS NULL'),
321
+ folderCount: db.prepare('SELECT count(*) AS n FROM files WHERE kind IS NOT NULL'),
322
+ vectorCount: db.prepare('SELECT count(*) AS n FROM vectors'),
323
+ };
324
+ priorityDirs = priorityDirsOf(resolvedRoots);
325
+ migrated = migrateLegacySnapshot();
326
+ collapsed = st.collapsed.all().map((r) => ({ abs: r.path, kind: r.kind }));
327
+ })();
328
+ }
329
+ return opening;
330
+ }
331
+
332
+ function setEntry(abs, entry) {
333
+ const { id } = st.upsert.get(abs, entry.mtime, entry.size, entry.preview || null, entry.kind || null, entry.secret ? 1 : 0,
334
+ entry.doc ? 1 : 0, isPriority(abs) ? 1 : 0);
335
+ st.ftsDelete.run(id);
336
+ st.ftsInsert.run(id, tokenize(docText(abs, entry)).join(' '));
337
+ return id;
338
+ }
339
+
340
+ function dropId(id) {
341
+ st.ftsDelete.run(id);
342
+ st.vectorDelete.run(id);
343
+ st.fileDelete.run(id);
344
+ }
345
+
346
+ /** Bản chụp gzip của bản cũ (giữ mọi thứ trong RAM) → chép sang SQLite một lần, kể cả vector (khỏi bắt BE tính lại), rồi xoá. */
347
+ function migrateLegacySnapshot() {
348
+ if (!fs.existsSync(LEGACY_SNAPSHOT_FILE)) return 0;
349
+ let count = 0;
350
+ try {
351
+ const data = JSON.parse(zlib.gunzipSync(fs.readFileSync(LEGACY_SNAPSHOT_FILE)).toString('utf8'));
352
+ if (data?.version === LEGACY_SNAPSHOT_VERSION && JSON.stringify(data.roots) === JSON.stringify(resolvedRoots) && !st.fileCount.get().n) {
353
+ let vectors = [];
354
+ try { vectors = JSON.parse(zlib.gunzipSync(fs.readFileSync(LEGACY_VECTORS_FILE)).toString('utf8')).vectors || []; } catch { /* chưa có */ }
355
+ db.transaction(() => {
356
+ const keys = new Map();
357
+ for (const [abs, mtime, size, tokens, preview] of data.entries || []) {
358
+ if (skippedPath(abs)) continue;
359
+ const entry = { mtime, size, tokens, preview, secret: looksSecret(abs), doc: isDocFile(abs) };
360
+ keys.set(abs, { id: setEntry(abs, entry), key: vectorKey(entry) });
361
+ count++;
362
+ }
363
+ for (const [abs, key, b64] of vectors) {
364
+ const file = keys.get(abs);
365
+ if (file && file.key === key && b64) st.vectorPut.run(file.id, key, Buffer.from(b64, 'base64'));
366
+ }
367
+ });
368
+ }
369
+ } catch { count = 0; /* hỏng → quét lại từ đầu */ }
370
+ for (const f of [LEGACY_SNAPSHOT_FILE, LEGACY_VECTORS_FILE]) fs.rmSync(f, { force: true });
371
+ return count;
372
+ }
373
+
374
+ /** Mục đại diện cho thư mục gộp — chỉ ghi khi đổi (mtime thư mục / số mục / loại). */
375
+ function setFolder(f) {
376
+ const prev = st.find.get(f.abs);
377
+ if (prev && prev.kind === f.kind && prev.mtime === f.mtime && prev.size === f.count) return false;
378
+ setEntry(f.abs, { mtime: f.mtime, size: f.count, preview: f.note, tokens: f.words, kind: f.kind });
379
+ return true;
380
+ }
381
+
382
+ /**
383
+ * Đọc lại một tệp nếu mtime / size đổi. `repo`: nằm trong kho git (tài liệu ở đây không tính vector). `contentOk`: undefined = tệp trong
384
+ * thư mục đám mây thì trả 'cloud' để người gọi hỏi thuộc tính cả lô; false = chỉ lập chỉ mục tên (tệp chỉ có trên mây).
385
+ */
386
+ async function refreshFile(abs, { repo = false, contentOk } = {}) {
387
+ await ensureOpen();
388
+ const prev = st.find.get(abs);
389
+ let stat;
390
+ try { stat = await fs.promises.stat(abs); } catch {
391
+ if (prev) dropId(prev.id);
392
+ return 'removed';
393
+ }
394
+ if (!stat.isFile()) return 'skipped';
395
+ const mtime = Math.floor(stat.mtimeMs);
396
+ const doc = isDocFile(abs) && !repo;
397
+ if (prev && prev.mtime === mtime && prev.size === stat.size) {
398
+ // Cùng tệp nhưng nay thuộc / không còn thuộc thư mục làm việc người dùng chỉ định → chỉ sửa cờ.
399
+ if (Boolean(prev.doc) !== doc) st.flags.run(doc ? 1 : 0, isPriority(abs) ? 1 : 0, prev.id);
400
+ return 'same';
401
+ }
402
+ if (contentOk === undefined && readsContent(abs) && inCloudFolder(abs)) return 'cloud';
403
+ const read = contentOk !== false;
404
+ const preview = read && isDocFile(abs) ? await extractDocText(abs, stat.size) : '';
405
+ const tokens = read ? await headTokens(abs, stat.size) : '';
406
+ // Tệp như chứa bí mật: chỉ giữ tên (tìm theo tên vẫn được), bỏ đoạn chữ + định danh.
407
+ const id = looksSecret(abs, `${preview}\n${tokens}`)
408
+ ? setEntry(abs, { mtime, size: stat.size, tokens: '', secret: true, doc })
409
+ : setEntry(abs, { mtime, size: stat.size, tokens, preview, doc });
410
+ st.vectorDelete.run(id);
411
+ return 'updated';
412
+ }
413
+
414
+ /** Lô tệp ở thư mục đám mây: hỏi thuộc tính một lần, tệp chỉ có trên mây chỉ lập chỉ mục tên. */
415
+ async function refreshCloud(list) {
416
+ if (!list.length) return 0;
417
+ const offline = await cloudOnlyFiles(list.map((f) => f.abs));
418
+ let updated = 0;
419
+ await mapLimit(list, STAT_CONCURRENCY, async (f) => {
420
+ if ((await refreshFile(f.abs, { repo: f.repo, contentOk: !offline.has(f.abs) })) === 'updated') updated++;
421
+ });
422
+ return updated;
423
+ }
424
+
425
+ /** Lập chỉ mục một cây (gốc / thư mục ưu tiên / thư mục làm việc) → số tệp cập nhật; ghi nhận mọi đường đã thấy vào `found`. */
426
+ async function indexTree(dir, { found, limit, skip, full }) {
427
+ const { files, folders } = await walk(dir, limit, { skip, full, excludes: activeExcludes });
428
+ let updated = 0;
429
+ for (const f of folders) {
430
+ if (found.has(f.abs)) continue;
431
+ found.add(f.abs);
432
+ if (setFolder(f)) updated++;
433
+ }
434
+ const fresh = files.filter((f) => !found.has(f.abs));
435
+ fresh.forEach((f) => found.add(f.abs));
436
+ const cloud = [];
437
+ await mapLimit(fresh, STAT_CONCURRENCY, async (f) => {
438
+ const r = await refreshFile(f.abs, { repo: f.repo });
439
+ if (r === 'updated') updated++;
440
+ else if (r === 'cloud') cloud.push(f);
441
+ });
442
+ return updated + await refreshCloud(cloud);
443
+ }
444
+
445
+ /**
446
+ * Quét tăng dần: thư mục làm việc người dùng chỉ định trước, rồi thư mục người dùng, rồi phần còn lại của các gốc. Tệp mới / đổi được đọc
447
+ * lại, tệp không còn thấy bị bỏ.
448
+ */
449
+ async function build() {
450
+ const startedAt = Date.now();
451
+ const first = !lastBuild;
452
+ await ensureOpen();
453
+ reloadExcludes();
454
+ priorityDirs = priorityDirsOf(resolvedRoots);
455
+ indexFolders = loadIndexFolders();
456
+ const found = new Set();
457
+ let updated = 0;
458
+ const plan = [
459
+ ...indexFolders.map((dir) => ({ dir, full: true })),
460
+ ...priorityDirs.map((dir) => ({ dir })),
461
+ ...resolvedRoots.map((dir) => ({ dir, root: true })),
462
+ ];
463
+ for (const { dir, full, root } of plan) {
464
+ if (found.size >= MAX_FILES) break;
465
+ const skip = new Set([...indexFolders.filter((d) => d !== dir), ...(root ? priorityDirs : [])]);
466
+ updated += await indexTree(dir, { found, limit: MAX_FILES - found.size, skip, full });
467
+ }
468
+ // Có trong chỉ mục mà lần quét này không thấy (đã xoá / đổi tên / nay bị bỏ qua) — một lần đọc, không ghi gì cho tệp không đổi.
469
+ const gone = st.paths.all().filter((r) => !found.has(r.path));
470
+ db.transaction(() => { for (const { id } of gone) dropId(id); });
471
+ collapsed = st.collapsed.all().map((r) => ({ abs: r.path, kind: r.kind }));
472
+ lastBuild = {
473
+ files: st.fileCount.get().n, folders: st.folderCount.get().n, updated, removed: gone.length, from_snapshot: first ? migrated : 0,
474
+ capped: found.size >= MAX_FILES, ms: Date.now() - startedAt, at: new Date().toISOString(),
475
+ };
476
+ scheduleVectorize(0);
477
+ return lastBuild;
478
+ }
479
+
480
+ /**
481
+ * Tệp bộ theo dõi báo đổi: có lập chỉ mục không, và có nằm trong kho git không. null = bỏ (thư mục ẩn / rác, tệp tạm, trong thư mục ứng
482
+ * dụng, tệp không phải tài liệu trong thư mục hàng loạt hay kho git).
483
+ */
484
+ function ruleFor(abs) {
485
+ const folder = indexFolders.filter((d) => within(d, abs)).sort((a, b) => b.length - a.length)[0];
486
+ const base = folder || resolvedRoots.find((r) => within(r, abs));
487
+ if (!base || isProtectedPath(abs)) return null;
488
+ const segs = path.relative(base, abs).split(path.sep);
489
+ if (segs.slice(0, -1).some((d) => skipDir(d, activeExcludes)) || skipFile(segs[segs.length - 1], activeExcludes)) return null;
490
+ let repo = false;
491
+ for (const c of collapsed) {
492
+ // Chỉ thư mục gộp nằm GIỮA gốc và tệp; gộp bao trùm cả gốc (thư mục làm việc nằm trong một kho git…) không tính.
493
+ if (c.abs === abs || !within(c.abs, abs) || within(c.abs, base)) continue;
494
+ if (c.kind === FolderKind.APP) return null;
495
+ if (c.kind === FolderKind.BULK && path.dirname(abs) === c.abs && !isDocFile(abs)) return null;
496
+ if (c.kind === FolderKind.REPO && !folder) repo = true;
497
+ }
498
+ if (repo && !isDocFile(abs)) return null;
499
+ return { repo };
500
+ }
501
+
502
+ function watchDir(dir, pending, flush, fallBackToRescan) {
503
+ if (watchers.has(dir)) return;
504
+ try {
505
+ const w = fs.watch(dir, { recursive: true }, (_event, name) => {
506
+ if (!name) return;
507
+ pending.add(path.join(dir, String(name)));
508
+ flush();
509
+ });
510
+ // Không có listener 'error' thì lỗi của bộ theo dõi (gốc bị xoá, rút ổ ngoài, hết inotify) ném ra ngoài và làm sập daemon.
511
+ w.on('error', () => {
512
+ try { w.close(); } catch { /* đã đóng */ }
513
+ watchers.delete(dir);
514
+ fallBackToRescan();
515
+ });
516
+ w.unref?.();
517
+ watchers.set(dir, w);
518
+ } catch { fallBackToRescan(); /* không theo dõi được (hệ thống tệp mạng…) */ }
519
+ }
520
+
521
+ let rewatch = () => {};
522
+
523
+ function watch() {
524
+ watching = true;
525
+ const pending = new Set();
526
+ let timer;
527
+ const run = async () => {
528
+ const batch = [...pending];
529
+ pending.clear();
530
+ const cloud = [];
531
+ await mapLimit(batch, STAT_CONCURRENCY, async (abs) => {
532
+ const rule = ruleFor(abs);
533
+ if (!rule) return;
534
+ if ((await refreshFile(abs, { repo: rule.repo })) === 'cloud') cloud.push({ abs, repo: rule.repo });
535
+ });
536
+ await refreshCloud(cloud);
537
+ scheduleVectorize(5_000);
538
+ };
539
+ const flush = () => {
540
+ clearTimeout(timer);
541
+ timer = setTimeout(() => void run(), WATCH_DEBOUNCE_MS);
542
+ };
543
+ const fallBackToRescan = () => {
544
+ // Bộ theo dõi hỏng: chuyển sang quét lại định kỳ (tăng dần — chỉ đọc tệp có mtime / size đổi).
545
+ if (rescanTimer) return;
546
+ rescanTimer = setInterval(() => void build().catch(() => undefined), RESCAN_MS);
547
+ rescanTimer.unref?.();
548
+ };
549
+ rewatch = () => {
550
+ const want = [...resolvedRoots, ...indexFolders.filter((d) => !resolvedRoots.some((r) => within(r, d)))];
551
+ for (const [dir, w] of watchers) if (!want.includes(dir)) { try { w.close(); } catch { /* đã đóng */ } watchers.delete(dir); }
552
+ for (const dir of want) watchDir(dir, pending, flush, fallBackToRescan);
553
+ };
554
+ rewatch();
555
+ // `aivin remote index add|remove` (tiến trình khác) sửa danh sách → quét lại tăng dần.
556
+ fs.watchFile(INDEX_FOLDERS_FILE, { interval: INDEX_FOLDERS_POLL_MS, persistent: false }, () => {
557
+ if (JSON.stringify(loadIndexFolders()) === JSON.stringify(indexFolders)) return;
558
+ void build().then(() => rewatch()).catch(() => undefined);
559
+ });
560
+ // `aivin remote index-exclude` sửa danh sách mẫu loại trừ → quét lại tăng dần.
561
+ fs.watchFile(INDEX_EXCLUDES_FILE, { interval: INDEX_FOLDERS_POLL_MS, persistent: false }, () => {
562
+ if (JSON.stringify(loadIndexExcludes()) === JSON.stringify(indexExcludes)) return;
563
+ void build().then(() => rewatch()).catch(() => undefined);
564
+ });
565
+ }
566
+
567
+ /**
568
+ * Thư mục làm việc người dùng chỉ định (qua chat → fs.index_folder): lập chỉ mục đầy đủ ngay (kể cả code trong kho git), ưu tiên tính
569
+ * vector, theo dõi thay đổi. Chờ tối đa `waitMs` — quá thì vẫn chạy tiếp ở nền (`done: false`).
570
+ */
571
+ async function addFolder(dir, { waitMs = 15_000 } = {}) {
572
+ const abs = path.resolve(dir);
573
+ indexFolders = saveIndexFolders([...loadIndexFolders(), abs]);
574
+ await ensureOpen();
575
+ const found = new Set();
576
+ const job = indexTree(abs, { found, limit: MAX_FILES, skip: new Set(indexFolders.filter((d) => d !== abs)), full: true })
577
+ .then((updated) => {
578
+ collapsed = st.collapsed.all().map((r) => ({ abs: r.path, kind: r.kind }));
579
+ if (watching) rewatch();
580
+ scheduleVectorize(1_000);
581
+ return updated;
582
+ });
583
+ let timer;
584
+ const result = await Promise.race([job.then((updated) => ({ done: true, updated })), new Promise((r) => { timer = setTimeout(() => r({ done: false }), waitMs); })]);
585
+ clearTimeout(timer);
586
+ return { folder: abs, folders: indexFolders, indexed: [...found].length, ...result };
587
+ }
588
+
589
+ /** Bỏ thư mục làm việc: quét lại tăng dần để bỏ những gì chỉ có vì thư mục này (code trong kho git, thư mục ngoài gốc). */
590
+ async function removeFolder(dir) {
591
+ const abs = path.resolve(dir);
592
+ indexFolders = saveIndexFolders(loadIndexFolders().filter((d) => d !== abs));
593
+ const stats = await build();
594
+ if (watching) rewatch();
595
+ return { folder: abs, folders: indexFolders, removed: stats.removed };
596
+ }
597
+
598
+ /** Đoạn mô tả đưa đi tính vector: tên + thư mục gần nhất + chữ đầu tệp. */
599
+ const embedText = (abs, entry) => `${path.basename(abs)} | ${path.dirname(abs).split(path.sep).slice(-3).join(' / ')}${entry.preview ? ` | ${entry.preview}` : ''}`;
600
+
601
+ /** Tệp tài liệu cần (tính lại) vector: thư mục ưu tiên trước, mới sửa trước; giữ trong trần MAX_VECTOR_FILES. */
602
+ function vectorQueue() {
603
+ const order = 'FROM files WHERE doc = 1 AND secret = 0 ORDER BY prio DESC, mtime DESC LIMIT ?';
604
+ db.prepare(`DELETE FROM vectors WHERE id NOT IN (SELECT id ${order})`).run(MAX_VECTOR_FILES);
605
+ return db.prepare(`SELECT f.id, f.path, f.mtime, f.size, f.preview, v.key AS vkey FROM (SELECT * ${order}) f LEFT JOIN vectors v ON v.id = f.id`)
606
+ .all(MAX_VECTOR_FILES).filter((r) => r.vkey !== vectorKey(r));
607
+ }
608
+
609
+ /**
610
+ * Tính vector nền theo lô (`embed(texts) → base64[]`, BE tính bằng bge-m3). BE cũ / lỗi → dừng, lần sau thử lại; tìm theo từ khoá vẫn
611
+ * chạy bình thường.
612
+ */
613
+ async function vectorize() {
614
+ if (!db || !embedder || vectorizing || Date.now() < pausedUntil) return { embedded: 0, total: db ? st.vectorCount.get().n : 0 };
615
+ vectorizing = true;
616
+ let embedded = 0;
617
+ let failed = false;
618
+ try {
619
+ const queue = vectorQueue();
620
+ for (let i = 0; i < queue.length; i += EMBED_BATCH) {
621
+ const batch = queue.slice(i, i + EMBED_BATCH);
622
+ const out = await embedder(batch.map((r) => wellFormed(embedText(r.path, r))));
623
+ if (!Array.isArray(out) || out.length !== batch.length) { failed = true; break; }
624
+ if (!db) break;
625
+ db.transaction(() => batch.forEach((r, j) => { if (out[j]) st.vectorPut.run(r.id, vectorKey(r), Buffer.from(out[j], 'base64')); }));
626
+ embedded += batch.length;
627
+ failures = 0;
628
+ }
629
+ } catch { failed = true; } finally {
630
+ vectorizing = false;
631
+ }
632
+ // BE bận / lỗi → nghỉ giãn dần (30 s → tối đa 30 phút) thay vì thử lại mỗi lần tệp đổi — không dồn tải lên dịch vụ vector dùng chung.
633
+ if (failed) {
634
+ failures++;
635
+ const pauseMs = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (failures - 1));
636
+ pausedUntil = Date.now() + pauseMs;
637
+ scheduleVectorize(pauseMs + 1_000);
638
+ }
639
+ return { embedded, total: db ? st.vectorCount.get().n : 0, failed: failed || undefined };
640
+ }
641
+
642
+ function scheduleVectorize(delayMs) {
643
+ if (!embedder) return;
644
+ clearTimeout(vectorTimer);
645
+ vectorTimer = setTimeout(() => void vectorize(), delayMs);
646
+ vectorTimer.unref?.();
647
+ }
648
+
649
+ function setEmbedder(fn) {
650
+ embedder = fn;
651
+ if (lastBuild) scheduleVectorize(2_000);
652
+ }
653
+
654
+ function close() {
655
+ if (rescanTimer) { clearInterval(rescanTimer); rescanTimer = null; }
656
+ for (const w of watchers.values()) { try { w.close(); } catch { /* đã đóng */ } }
657
+ watchers.clear();
658
+ if (watching) {
659
+ fs.unwatchFile(INDEX_FOLDERS_FILE);
660
+ fs.unwatchFile(INDEX_EXCLUDES_FILE);
661
+ }
662
+ watching = false;
663
+ clearTimeout(vectorTimer);
664
+ try { db?.close(); } catch { /* đã đóng */ }
665
+ db = null;
666
+ opening = null;
667
+ }
668
+
669
+ /** Từ khoá → FTS5: mỗi từ một vế OR; từ ≥ PREFIX_MIN ký tự khớp cả tiền tố ("auth" ↔ "authentication"). Từ chỉ có chữ / số — không cần thoát. */
670
+ const matchExpr = (query) => [...new Set(tokenize(query))].map((t) => `"${t}"${t.length >= PREFIX_MIN ? '*' : ''}`).join(' OR ');
671
+
672
+ /** Vector gần câu hỏi nhất: quét bảng theo khúc (không giữ cả bảng trong RAM). */
673
+ function nearest(q, depth) {
674
+ let top = [];
675
+ for (let after = 0; ;) {
676
+ const rows = st.vectorChunk.all(after, VECTOR_SCAN_CHUNK);
677
+ for (const r of rows) top.push([r.id, int8Cosine(q, new Int8Array(r.vec.buffer, r.vec.byteOffset, r.vec.byteLength))]);
678
+ top = top.sort((a, b) => b[1] - a[1]).slice(0, depth);
679
+ if (rows.length < VECTOR_SCAN_CHUNK) return top;
680
+ after = rows[rows.length - 1].id;
681
+ }
682
+ }
683
+
684
+ /**
685
+ * Tìm theo tên / đường dẫn / định danh / chữ đầu tài liệu; có `vector` (bge-m3 int8 base64 của câu hỏi) thì gộp thêm xếp hạng ngữ
686
+ * nghĩa. Trả đường hiển thị (tương đối với gốc; thư mục làm việc ngoài gốc thì tuyệt đối) + dung lượng, ngày sửa, đoạn xem trước; thư mục
687
+ * gộp có `type: 'folder'` + `note`. `abs` = đường tuyệt đối (để gộp với kết quả của bộ tìm hệ điều hành).
688
+ */
689
+ function search(query, limit = 10, vector) {
690
+ if (!db) return [];
691
+ const depth = Math.max(limit, RANK_DEPTH);
692
+ const words = [...new Set(tokenize(query))];
693
+ let lexical = [];
694
+ if (words.length > 1) {
695
+ const andExpr = words.map((t) => `"${t}"${t.length >= PREFIX_MIN ? '*' : ''}`).join(' AND ');
696
+ const orExpr = words.map((t) => `"${t}"${t.length >= PREFIX_MIN ? '*' : ''}`).join(' OR ');
697
+ const andHits = st.lexical.all(andExpr, depth).map((r) => r.id);
698
+ const orHits = st.lexical.all(orExpr, depth).map((r) => r.id);
699
+ lexical = [...new Set([...andHits, ...orHits])].slice(0, depth);
700
+ } else if (words.length === 1) {
701
+ const expr = matchExpr(query);
702
+ lexical = expr ? st.lexical.all(expr, depth).map((r) => r.id) : [];
703
+ }
704
+ const q = vector ? decodeInt8(vector) : null;
705
+ const semantic = q ? nearest(q, RANK_DEPTH) : [];
706
+ const similarity = new Map(semantic);
707
+ const ranked = semantic.length ? fuse(lexical, semantic.map(([id]) => id), similarity) : lexical;
708
+ return ranked.slice(0, limit).flatMap((id) => {
709
+ const e = st.row.get(id);
710
+ if (!e) return [];
711
+ const root = resolvedRoots.find((r) => within(r, e.path));
712
+ const modified = e.mtime ? new Date(e.mtime).toISOString().slice(0, 10) : undefined;
713
+ const shown = root ? path.relative(root, e.path) || e.path : e.path;
714
+ if (e.kind) return [{ path: shown, abs: e.path, type: 'folder', kind: e.kind, items: e.size, modified, note: e.preview }];
715
+ return [{
716
+ path: shown, abs: e.path, size: e.size, modified,
717
+ ...(e.preview ? { preview: e.preview.slice(0, 200) } : {}),
718
+ ...(similarity.has(id) ? { similarity: Number(similarity.get(id).toFixed(3)) } : {}),
719
+ }];
720
+ });
721
+ }
722
+
723
+ return {
724
+ build, watch, close, search, refreshFile, vectorize, setEmbedder, addFolder, removeFolder,
725
+ folders: () => [...indexFolders],
726
+ excludes: () => [...activeExcludes],
727
+ addExclude: async (pattern) => {
728
+ saveIndexExcludes([...loadIndexExcludes(), pattern]);
729
+ reloadExcludes();
730
+ return build();
731
+ },
732
+ removeExclude: async (pattern) => {
733
+ saveIndexExcludes(loadIndexExcludes().filter((e) => e.toLowerCase() !== pattern.toLowerCase()));
734
+ reloadExcludes();
735
+ return build();
736
+ },
737
+ stats: () => ({
738
+ files: db ? st.fileCount.get().n : 0, folders: db ? st.folderCount.get().n : 0, vectors: db ? st.vectorCount.get().n : 0,
739
+ index_folders: [...indexFolders], index_excludes: [...activeExcludes], last_build: lastBuild,
740
+ }),
741
+ };
742
+ }
743
+
744
+ /**
745
+ * Gộp hai bảng xếp hạng (RRF). Hoà điểm — tệp đầu bảng từ khoá vs tệp đầu bảng ngữ nghĩa — thì tệp gần nghĩa hơn đứng trước: từ khoá
746
+ * chỉ trùng một chữ chung ("thuê") hay gặp hơn là trùng nghĩa.
747
+ */
748
+ function fuse(lexical, semantic, similarity) {
749
+ const score = new Map();
750
+ for (const list of [lexical, semantic]) list.forEach((id, rank) => score.set(id, (score.get(id) || 0) + 1 / (RRF_K + rank + 1)));
751
+ return [...score.keys()].sort((a, b) => (score.get(b) - score.get(a)) || ((similarity.get(b) ?? -1) - (similarity.get(a) ?? -1)));
752
+ }
753
+
754
+ /** Gốc lập chỉ mục: máy toàn quyền chỉ quét thư mục nhà (cả ổ là hàng trăm nghìn tệp hệ thống). */
755
+ export function indexRootsFor(roots, fullAccess) {
756
+ return fullAccess ? [os.homedir()] : roots;
757
+ }