xindex 1.0.6 → 1.0.7

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/.tmp/watch.log CHANGED
@@ -1,9 +1,14 @@
1
- [xindex-1776976173089-3ab4dd18cfbfc8] started, indexing and watching: .
1
+ npm warn Unknown env config "version-git-tag". This will stop working in the next major version of npm.
2
+ npm warn Unknown env config "argv". This will stop working in the next major version of npm.
3
+ npm warn Unknown env config "version-commit-hooks". This will stop working in the next major version of npm.
4
+ npm warn Unknown env config "version-git-message". This will stop working in the next major version of npm.
5
+ npm warn Unknown env config "version-tag-prefix". This will stop working in the next major version of npm.
6
+ [xindex-1776991372027-99a3bfc69e73f] started, indexing and watching: .
2
7
  indexing: notes.md
3
8
  indexing: util.ts
4
9
  initial index complete, acquiring watcher lock...
5
- done. indexed: {"indexedAmount":2}
10
+ done. indexed: {"indexedAmount":0}
6
11
  watching for changes: .
7
12
  index: wombat.md
8
13
  remove: functional
9
- remove batch failed: Error saving index: Error: ENOENT: no such file or directory, open '.xindex/semantic/index.json'
14
+ index end failed: Error saving index: Error: ENOENT: no such file or directory, open '.xindex/semantic/index.json'
package/.xindex.json CHANGED
@@ -1,23 +1,95 @@
1
1
  {
2
2
  "ignoreKeywords": [
3
- "import", "export", "const", "function", "return", "async", "await", "type", "string", "number",
4
- "from", "default", "let", "var",
5
- "if", "else", "switch", "case", "break", "continue",
6
- "for", "of", "in",
7
- "try", "catch", "finally", "throw",
8
- "new", "delete", "as", "is", "typeof", "instanceof", "void",
9
- "this", "super",
10
- "interface", "class", "extends", "implements",
11
- "public", "private", "protected", "static", "abstract", "readonly",
12
- "declare", "namespace", "module", "enum",
13
- "boolean", "any", "unknown", "never",
14
- "undefined", "null", "object",
15
- "record", "array", "readonlyarray", "promise",
16
- "true", "false",
17
- "src", "packages", "fun", "componets", "streamx", "apps", "run", "rnd", "tsx",
18
- "utf8", "length", "map", "slice", "push", "join", "resolve", "stringify",
19
- "json", "settimeout", "path", "readfile"
3
+ "import",
4
+ "export",
5
+ "const",
6
+ "function",
7
+ "return",
8
+ "async",
9
+ "await",
10
+ "type",
11
+ "string",
12
+ "number",
13
+ "from",
14
+ "default",
15
+ "let",
16
+ "var",
17
+ "if",
18
+ "else",
19
+ "switch",
20
+ "case",
21
+ "break",
22
+ "continue",
23
+ "for",
24
+ "of",
25
+ "in",
26
+ "try",
27
+ "catch",
28
+ "finally",
29
+ "throw",
30
+ "new",
31
+ "delete",
32
+ "as",
33
+ "is",
34
+ "typeof",
35
+ "instanceof",
36
+ "void",
37
+ "this",
38
+ "super",
39
+ "interface",
40
+ "class",
41
+ "extends",
42
+ "implements",
43
+ "public",
44
+ "private",
45
+ "protected",
46
+ "static",
47
+ "abstract",
48
+ "readonly",
49
+ "declare",
50
+ "namespace",
51
+ "module",
52
+ "enum",
53
+ "boolean",
54
+ "any",
55
+ "unknown",
56
+ "never",
57
+ "undefined",
58
+ "null",
59
+ "object",
60
+ "record",
61
+ "array",
62
+ "readonlyarray",
63
+ "promise",
64
+ "true",
65
+ "false",
66
+ "src",
67
+ "packages",
68
+ "fun",
69
+ "componets",
70
+ "streamx",
71
+ "apps",
72
+ "run",
73
+ "rnd",
74
+ "tsx",
75
+ "utf8",
76
+ "length",
77
+ "map",
78
+ "slice",
79
+ "push",
80
+ "join",
81
+ "resolve",
82
+ "stringify",
83
+ "json",
84
+ "settimeout",
85
+ "path",
86
+ "readfile"
20
87
  ],
21
- "ignoreFiles": [".xindex", "media"],
22
- "maxLines": 12
88
+ "ignoreFiles": [
89
+ ".xindex",
90
+ "media"
91
+ ],
92
+ "maxLines": 30,
93
+ "maxFileBytes": 100000,
94
+ "followSymlinks": false
23
95
  }
package/README.md CHANGED
@@ -174,7 +174,7 @@ Project-root file. All fields optional; unknown keys ignored; missing/empty →
174
174
  - **`ignoreKeywords`** — `string[]`, default `[]`. Tokens stripped before embedding — add project slang/boilerplate polluting results. Entries ≤1 char warn.
175
175
  - **`ignoreFiles`** — `string[]`, default `[]`. Extra globs excluded during walk/watch, on top of `.gitignore` — add vendored/generated folders.
176
176
  - **`maxLines`** — `number`, default `30`. Lines per chunk — tune if chunks feel over/under-sized.
177
- - **`maxFileBytes`** — `number`, default `1000000`. Skip files over this (1 MB) — raise to index larger generated files.
177
+ - **`maxFileBytes`** — `number`, default `50000`. Skip files over this (50 KB) — raise to index larger generated files.
178
178
  - **`followSymlinks`** — `boolean`, default `false`. When `false`, symbolic links encountered during walk/watch are skipped with a log line. Set `true` to follow them (cycles are broken via `realpath` dedup).
179
179
 
180
180
  ```json
package/apps/run.index.ts CHANGED
@@ -3,17 +3,19 @@ import {BufferedLoggerToStdOut} from "../componets/logger.js";
3
3
  import {WalkFiles} from "../componets/walkFiles.js";
4
4
  import {IndexApp} from "./indexApp.js";
5
5
  import {AppId} from "../componets/appId.js";
6
+ import {INDEXING_COALESCE_MS} from "../componets/config/INDEXING_COALESCE_MS.js";
6
7
 
7
8
  const appId = AppId();
8
9
  const cwd = process.cwd();
9
10
  const log = BufferedLoggerToStdOut();
10
- const {indexContent, getIndexStats, config} = await BuildComponents({log});
11
+ const {indexContentBatch, getIndexStats, config, flush} = await BuildComponents({log, indexingCoalesceMs: INDEXING_COALESCE_MS});
11
12
  const walkFiles = WalkFiles({cwd, log, ignoreFiles: config.ignoreFiles, followSymlinks: config.followSymlinks});
12
- const indexApp = IndexApp({walkFiles, indexContent, log, maxFileBytes: config.maxFileBytes});
13
+ const indexApp = IndexApp({walkFiles, indexContent: indexContentBatch, log, maxFileBytes: config.maxFileBytes});
13
14
 
14
15
  const inputs = process.argv.slice(2);
15
16
  if (!inputs.length) inputs.push(".");
16
17
 
17
18
  log(`[${appId}] started, indexing: ${inputs.join(", ")}`);
18
19
  await indexApp(inputs);
20
+ await flush();
19
21
  log(`[${appId}] done:`, await getIndexStats());
package/apps/run.mcp.ts CHANGED
@@ -9,6 +9,8 @@ import {McpApp} from "./mcpApp.js";
9
9
  import {SearchApp} from "./searchApp.js";
10
10
  import {join} from "path";
11
11
  import {AppId} from "../componets/appId.js";
12
+ import {INDEXING_COALESCE_MS} from "../componets/config/INDEXING_COALESCE_MS.js";
13
+ import {WATCH_COALESCE_MS} from "../componets/config/WATCH_COALESCE_MS.js";
12
14
 
13
15
  const args = process.argv.slice(2);
14
16
  const watchDirArg = args.find(a => a.startsWith("--watch-dir="));
@@ -16,9 +18,17 @@ const watchDisabled = args.includes("--watch-disabled");
16
18
 
17
19
  const cwd = process.cwd();
18
20
  const log = BufferedLoggerToStdErr();
19
- const {indexContent, removeContent, getIndexStats, searchContentIndex, resetIndex, config} = await BuildComponents({log});
21
+ const {indexContentWatch, indexContentBatch, removeContent, getIndexStats, searchContentIndex, resetIndex, config, flush} = await BuildComponents({
22
+ log,
23
+ watchCoalesceMs: WATCH_COALESCE_MS,
24
+ indexingCoalesceMs: INDEXING_COALESCE_MS,
25
+ });
20
26
  const walkFiles = WalkFiles({cwd, log, ignoreFiles: config.ignoreFiles, followSymlinks: config.followSymlinks});
21
- const indexApp = IndexApp({walkFiles, indexContent, log, maxFileBytes: config.maxFileBytes});
27
+ const rawIndexApp = IndexApp({walkFiles, indexContent: indexContentBatch, log, maxFileBytes: config.maxFileBytes});
28
+ const indexApp = async (inputs: string[]) => {
29
+ await rawIndexApp(inputs);
30
+ await flush();
31
+ };
22
32
  const search = SearchApp({searchContentIndex});
23
33
 
24
34
  const appId = AppId();
@@ -31,18 +41,18 @@ const watcherLock = WatcherLock({
31
41
  const watch = watchDisabled ? undefined : {
32
42
  watchFiles: WatchFiles({cwd, log, ignoreFiles: config.ignoreFiles}),
33
43
  watchDir: watchDirArg ? watchDirArg.split("=")[1] : ".",
34
- handleFileEvents: HandleFileEvents({indexContent, removeContent, log, maxFileBytes: config.maxFileBytes}),
44
+ handleFileEvents: HandleFileEvents({indexContent: indexContentWatch, removeContent, log, maxFileBytes: config.maxFileBytes}),
35
45
  watcherLock,
36
46
  };
37
47
 
38
48
  process.on("SIGINT", async () => {
39
- log(`[${appId}] shutting down — stopping heartbeat...`);
49
+ log(`shutting down — stopping heartbeat...`);
40
50
  watcherLock.stopHeartbeat();
41
- log(`[${appId}] releasing lock...`);
51
+ log(`releasing lock...`);
42
52
  await watcherLock.release();
43
- log(`[${appId}] waiting 7s for another watcher to take over...`);
53
+ log(`waiting 7s for another watcher to take over...`);
44
54
  await new Promise(r => setTimeout(r, 7000));
45
- log(`[${appId}] exiting`);
55
+ log(`exiting`);
46
56
  process.exit(0);
47
57
  });
48
58
 
package/apps/run.watch.ts CHANGED
@@ -7,13 +7,19 @@ import {WatcherLock} from "../componets/index/watcherLock.js";
7
7
  import {WatchApp} from "./watchApp.js";
8
8
  import {AppId} from "../componets/appId.js";
9
9
  import {join} from "path";
10
+ import {WATCH_COALESCE_MS} from "../componets/config/WATCH_COALESCE_MS.js";
11
+ import {INDEXING_COALESCE_MS} from "../componets/config/INDEXING_COALESCE_MS.js";
10
12
 
11
13
  const cwd = process.cwd();
12
14
  const log = BufferedLoggerToStdOut();
13
- const {indexContent, removeContent, getIndexStats, config} = await BuildComponents({log});
15
+ const {indexContentWatch, indexContentBatch, removeContent, getIndexStats, config} = await BuildComponents({
16
+ log,
17
+ watchCoalesceMs: WATCH_COALESCE_MS,
18
+ indexingCoalesceMs: INDEXING_COALESCE_MS,
19
+ });
14
20
  const walkFiles = WalkFiles({cwd, log, ignoreFiles: config.ignoreFiles, followSymlinks: config.followSymlinks});
15
21
  const watchFiles = WatchFiles({cwd, log, ignoreFiles: config.ignoreFiles});
16
- const handleFileEvents = HandleFileEvents({indexContent, removeContent, log, maxFileBytes: config.maxFileBytes});
22
+ const handleFileEvents = HandleFileEvents({indexContent: indexContentWatch, removeContent, log, maxFileBytes: config.maxFileBytes});
17
23
 
18
24
  const appId = AppId();
19
25
  const watcherLock = WatcherLock({
@@ -22,7 +28,7 @@ const watcherLock = WatcherLock({
22
28
  log,
23
29
  });
24
30
 
25
- const app = WatchApp({walkFiles, watchFiles, handleFileEvents, indexContent, log, watcherLock, maxFileBytes: config.maxFileBytes});
31
+ const app = WatchApp({walkFiles, watchFiles, handleFileEvents, indexContent: indexContentBatch, log, watcherLock, maxFileBytes: config.maxFileBytes});
26
32
 
27
33
  const inputs = process.argv.slice(2);
28
34
  if (!inputs.length) inputs.push(".");
@@ -1,3 +1,3 @@
1
1
  export function AppId() {
2
- return `xindex-${Date.now()}-${Math.random().toString(16).slice(2)}`;
2
+ return `xindex-${Math.random().toString(16).slice(2)}`;
3
3
  }
@@ -6,7 +6,11 @@ import {LoadConfig} from "./config/loadConfig.js";
6
6
  import {ILogger} from "./logger.js";
7
7
  import {LocateInFile} from "./locate/locateInFile.js";
8
8
 
9
- export async function BuildComponents({log}: { log: ILogger }) {
9
+ export async function BuildComponents({log, watchCoalesceMs = 0, indexingCoalesceMs = 0}: {
10
+ log: ILogger,
11
+ watchCoalesceMs?: number,
12
+ indexingCoalesceMs?: number,
13
+ }) {
10
14
  const loadConfig = LoadConfig({configPath: ".xindex.json", log});
11
15
  const config = await loadConfig();
12
16
 
@@ -26,7 +30,7 @@ export async function BuildComponents({log}: { log: ILogger }) {
26
30
 
27
31
  const SCORE_THRESHOLD = 0.01;
28
32
 
29
- const {indexContent, removeContent, getIndexStats, searchContentIndex, resetIndex}
33
+ const {indexContentWatch, indexContentBatch, removeContent, getIndexStats, searchContentIndex, resetIndex, flush}
30
34
  = await ContentIndexDriver({
31
35
  path: DEFAULT_INDEX_PATH,
32
36
  embed,
@@ -35,10 +39,15 @@ export async function BuildComponents({log}: { log: ILogger }) {
35
39
  locateInFile,
36
40
  scoreThreshold: SCORE_THRESHOLD,
37
41
  log,
42
+ indexingWatchCoalesceMs: watchCoalesceMs,
43
+ indexingCoalesceMs,
38
44
  });
39
45
 
40
46
  return {
41
- extractKeywords, cleanUpKeywords, indexContent, removeContent, getIndexStats,
42
- searchContentIndex, resetIndex, locateInFile, config
47
+ extractKeywords, cleanUpKeywords,
48
+ indexContentWatch, indexContentBatch,
49
+ removeContent, getIndexStats,
50
+ searchContentIndex, resetIndex,
51
+ locateInFile, config, flush,
43
52
  };
44
53
  }
@@ -1 +1 @@
1
- export const DEFAULT_LOCATE_BATCH_SIZE = 3;
1
+ export const DEFAULT_LOCATE_BATCH_SIZE = 8;
@@ -0,0 +1 @@
1
+ export const INDEXING_COALESCE_MAX_ITEMS = 1000;
@@ -0,0 +1 @@
1
+ export const INDEXING_COALESCE_MS = 1000;
@@ -0,0 +1 @@
1
+ export const WATCH_COALESCE_MS = 100;
@@ -3,12 +3,13 @@ import {IXindexConfig} from "./xindexConfig.js";
3
3
  import {ILogger} from "../logger.js";
4
4
 
5
5
  const DEFAULT_MAX_LINES = 30;
6
- const DEFAULT_MAX_FILE_BYTES = 1_000_000;
6
+ const DEFAULT_MAX_FILE_BYTES = 50_000;
7
7
  const DEFAULT_FOLLOW_SYMLINKS = false;
8
+ const DEFAULT_IGNORE_FILES = ['.xindex', 'node_modules'];
8
9
 
9
10
  const DEFAULTS: IXindexConfig = {
10
11
  ignoreKeywords: [],
11
- ignoreFiles: [],
12
+ ignoreFiles: DEFAULT_IGNORE_FILES,
12
13
  maxLines: DEFAULT_MAX_LINES,
13
14
  maxFileBytes: DEFAULT_MAX_FILE_BYTES,
14
15
  followSymlinks: DEFAULT_FOLLOW_SYMLINKS,
@@ -0,0 +1,74 @@
1
+ import {IIndexApi, IndexCommandType} from "./indexApi.js";
2
+ import {ILogger} from "../logger.js";
3
+ import {INDEXING_COALESCE_MAX_ITEMS} from "../config/INDEXING_COALESCE_MAX_ITEMS.js";
4
+ import {Defer, IDefer} from "../../packages/fun/src/defer.js";
5
+
6
+ type Item = {id: string, vector: number[], keywords: string};
7
+
8
+ export function CoalesceIndexApi({inner, windowMs, maxItems = INDEXING_COALESCE_MAX_ITEMS, log}: {
9
+ inner: IIndexApi,
10
+ windowMs: number,
11
+ maxItems?: number,
12
+ log: ILogger,
13
+ }): IIndexApi {
14
+ if (windowMs <= 0) return inner;
15
+
16
+ let pending: Item[] = [];
17
+ let delivery: IDefer | null = null;
18
+ let timer: ReturnType<typeof setTimeout> | null = null;
19
+
20
+ async function deliver() {
21
+ if (delivery) { await delivery.promise; return; }
22
+ if (timer) { clearTimeout(timer); timer = null; }
23
+ if (pending.length === 0) return;
24
+
25
+ const d = Defer();
26
+ delivery = d;
27
+ const items = pending;
28
+ pending = [];
29
+ try {
30
+ await inner({type: IndexCommandType.index, items});
31
+ } catch (e: any) {
32
+ log(`coalesced flush failed (${items.length} items): ${e?.message ?? e}`);
33
+ } finally {
34
+ delivery = null;
35
+ d.resolve();
36
+ }
37
+
38
+ if (pending.length >= maxItems) {
39
+ await deliver();
40
+ } else if (pending.length > 0 && !timer) {
41
+ timer = setTimeout(deliver, windowMs);
42
+ }
43
+ }
44
+
45
+ const api = (async function coalescedIndexApi(msg) {
46
+ switch (msg.type) {
47
+ case IndexCommandType.index: {
48
+ // if (delivery) await delivery.promise;
49
+ pending.push(...msg.items);
50
+
51
+ if (!timer) {
52
+ timer = setTimeout(deliver, windowMs);
53
+ }
54
+
55
+ if (pending.length >= maxItems) {
56
+ await deliver();
57
+ }
58
+ return;
59
+ }
60
+ case IndexCommandType.delete:
61
+ case IndexCommandType.reset: {
62
+ while (pending.length > 0 || delivery) await deliver();
63
+ return inner(msg);
64
+ }
65
+ }
66
+ }) as IIndexApi;
67
+
68
+ api.flush = async () => {
69
+ while (pending.length > 0 || delivery) await deliver();
70
+ await inner.flush();
71
+ };
72
+
73
+ return api;
74
+ }
@@ -7,20 +7,25 @@ import {SearchIndex, ISearchIndex} from "../../features/searchIndex.js";
7
7
  import {RemoveContent, IRemoveContent} from "../../features/removeContent.js";
8
8
  import {ResetIndex, IResetIndex} from "../../features/resetIndex.js";
9
9
  import {VectraIndex} from "./vectraIndex.js";
10
- import {IndexApi} from "./indexApi.js";
10
+ import {IndexApi, IIndexApi} from "./indexApi.js";
11
+ import {CoalesceIndexApi} from "./coalesceIndexApi.js";
11
12
  import {ILocateInFile} from "../locate/locateInFile.js";
12
13
  import {ILogger} from "../logger.js";
13
14
 
14
15
  export type IContentIndexDriver = Readonly<{
15
16
  getIndexStats: IGetIndexStats,
16
- indexContent: IIndexContent,
17
+ indexContentWatch: IIndexContent,
18
+ indexContentBatch: IIndexContent,
17
19
  removeContent: IRemoveContent,
18
20
  searchContentIndex: ISearchIndex,
19
21
  resetIndex: IResetIndex,
20
22
  flush: () => Promise<void>,
21
23
  }>;
22
24
 
23
- export async function ContentIndexDriver({path, embed, extractKeywords, cleanUpKeywords, locateInFile, scoreThreshold, log}: {
25
+ export async function ContentIndexDriver({
26
+ path, embed, extractKeywords, cleanUpKeywords, locateInFile, scoreThreshold, log,
27
+ indexingWatchCoalesceMs = 0, indexingCoalesceMs = 0,
28
+ }: {
24
29
  path: string,
25
30
  embed: IEmbed,
26
31
  extractKeywords: IExtractKeywords,
@@ -28,16 +33,37 @@ export async function ContentIndexDriver({path, embed, extractKeywords, cleanUpK
28
33
  locateInFile: ILocateInFile,
29
34
  scoreThreshold: number,
30
35
  log: ILogger,
36
+ indexingWatchCoalesceMs?: number,
37
+ indexingCoalesceMs?: number,
31
38
  }): Promise<IContentIndexDriver> {
32
39
  const index = await VectraIndex(path + "/semantic");
33
- const indexApi = IndexApi({index});
40
+ const rawIndexApi = IndexApi({index, log});
41
+ const watchCoalesce = CoalesceIndexApi({inner: rawIndexApi, windowMs: indexingWatchCoalesceMs, log});
42
+ const batchCoalesce = CoalesceIndexApi({inner: rawIndexApi, windowMs: indexingCoalesceMs, log});
43
+
44
+ const flushAll = async () => {
45
+ await Promise.all([watchCoalesce.flush(), batchCoalesce.flush()]);
46
+ await rawIndexApi.flush();
47
+ };
48
+
49
+ const drainThen = (inner: IIndexApi): IIndexApi => {
50
+ const api = (async (msg) => {
51
+ await flushAll();
52
+ return inner(msg);
53
+ }) as IIndexApi;
54
+ api.flush = flushAll;
55
+ return api;
56
+ };
57
+
58
+ const drainingApi = drainThen(rawIndexApi);
34
59
 
35
60
  return {
36
61
  getIndexStats: GetIndexStats({index}),
37
- indexContent: IndexContent({extractKeywords, cleanUpKeywords, embed, indexApi, log}),
38
- removeContent: RemoveContent({indexApi}),
62
+ indexContentWatch: IndexContent({extractKeywords, cleanUpKeywords, embed, indexApi: watchCoalesce, log}),
63
+ indexContentBatch: IndexContent({extractKeywords, cleanUpKeywords, embed, indexApi: batchCoalesce, log}),
64
+ removeContent: RemoveContent({indexApi: drainingApi}),
39
65
  searchContentIndex: SearchIndex({extractKeywords, cleanUpKeywords, embed, index, locateInFile, scoreThreshold}),
40
- resetIndex: ResetIndex({indexApi}),
41
- flush: () => indexApi.flush(),
66
+ resetIndex: ResetIndex({indexApi: drainingApi}),
67
+ flush: flushAll,
42
68
  };
43
69
  }
@@ -84,7 +84,8 @@ export async function DocumentContentIndexDriver({path, model}: {
84
84
 
85
85
  return {
86
86
  getIndexStats,
87
- indexContent,
87
+ indexContentWatch: indexContent,
88
+ indexContentBatch: indexContent,
88
89
  removeContent,
89
90
  searchContentIndex,
90
91
  resetIndex,
@@ -2,6 +2,7 @@ import {LocalIndex} from "vectra";
2
2
  import {IType} from "../IType.js";
3
3
  import {ISerial, Serial} from "../../packages/fun/src/serial.js";
4
4
  import {caseNever} from "../../packages/fun/src/case-never.js";
5
+ import {ILogger} from "../logger.js";
5
6
 
6
7
  export enum IndexCommandType {
7
8
  index = 'index',
@@ -16,17 +17,29 @@ export type IIndexCommand =
16
17
 
17
18
  export type IIndexApi = ISerial<IIndexCommand, void>;
18
19
 
19
- export function IndexApi({index}: { index: LocalIndex }): IIndexApi {
20
+ export function IndexApi({index, log}: { index: LocalIndex, log: ILogger }): IIndexApi {
20
21
  return Serial<IIndexCommand, void>(async msg => {
21
22
  switch (msg.type) {
22
23
  case IndexCommandType.delete: {
23
- await index.beginUpdate();
24
24
  try {
25
- for (const id of msg.ids) {
26
- await index.deleteItem(id);
25
+ await index.beginUpdate();
26
+ try {
27
+ for (const id of msg.ids) {
28
+ try {
29
+ await index.deleteItem(id);
30
+ } catch (e: any) {
31
+ log(`delete failed for ${id}: ${e?.message ?? e}`);
32
+ }
33
+ }
34
+ } finally {
35
+ try {
36
+ await index.endUpdate();
37
+ } catch (e: any) {
38
+ log(`index end failed: ${e?.message ?? e}`);
39
+ }
27
40
  }
28
- } finally {
29
- await index.endUpdate();
41
+ } catch (e: any) {
42
+ log(`index begin failed: ${e?.message ?? e}`);
30
43
  }
31
44
  break;
32
45
  }
@@ -35,35 +48,51 @@ export function IndexApi({index}: { index: LocalIndex }): IIndexApi {
35
48
  await index.batchInsertItems(msg.items.map(item => ({
36
49
  id: item.id,
37
50
  vector: item.vector,
38
- metadata: {id: item.id, keywords: item.keywords},
51
+ metadata: {},
39
52
  })));
40
- } catch (error) {
41
- const errorMessage = String((error as Error)?.message ?? error).toLowerCase();
53
+ } catch (error: any) {
54
+ const errorMessage = String(error?.message ?? error).toLowerCase();
42
55
  const isDuplicateIdError =
43
56
  errorMessage.includes("already exists")
44
57
  || errorMessage.includes("duplicate");
45
58
  if (!isDuplicateIdError) {
46
- throw error;
59
+ log(`index write failed (${msg.items.length} items): ${error?.message ?? error}`);
60
+ break;
47
61
  }
48
-
49
- await index.beginUpdate();
50
62
  try {
51
- for (const item of msg.items) {
52
- await index.upsertItem({
53
- id: item.id,
54
- vector: item.vector,
55
- metadata: {id: item.id, keywords: item.keywords},
56
- });
63
+ await index.beginUpdate();
64
+ try {
65
+ for (const item of msg.items) {
66
+ try {
67
+ await index.upsertItem({
68
+ id: item.id,
69
+ vector: item.vector,
70
+ metadata: {},
71
+ });
72
+ } catch (e: any) {
73
+ log(`index write failed for ${item.id}: ${e?.message ?? e}`);
74
+ }
75
+ }
76
+ } finally {
77
+ try {
78
+ await index.endUpdate();
79
+ } catch (e: any) {
80
+ log(`index end failed: ${e?.message ?? e}`);
81
+ }
57
82
  }
58
- } finally {
59
- await index.endUpdate();
83
+ } catch (e: any) {
84
+ log(`index begin failed: ${e?.message ?? e}`);
60
85
  }
61
86
  }
62
87
  break;
63
88
  }
64
89
  case IndexCommandType.reset: {
65
- await index.deleteIndex();
66
- await index.createIndex();
90
+ try {
91
+ await index.deleteIndex();
92
+ await index.createIndex();
93
+ } catch (e: any) {
94
+ log(`reset failed: ${e?.message ?? e}`);
95
+ }
67
96
  break;
68
97
  }
69
98
  default:
@@ -1,18 +1,24 @@
1
1
  import {pipeline} from "@huggingface/transformers";
2
2
 
3
- const embedder = await pipeline(
4
- "feature-extraction",
5
- "sentence-transformers/all-MiniLM-L6-v2"
6
- );
3
+ const MODEL = "sentence-transformers/all-MiniLM-L6-v2";
7
4
 
8
5
  export type IEmbed = (text: string) => Promise<number[]>;
9
6
 
10
7
  type Pooling = "none" | "mean" | "cls" | "first_token" | "eos" | "last_token";
11
8
 
12
9
  export function Embed({pooling, normalize}: {pooling: Pooling, normalize: boolean}): IEmbed {
10
+ let embedderPromise: Promise<any> | null = null;
11
+
12
+ function getEmbedder() {
13
+ if (!embedderPromise) {
14
+ embedderPromise = pipeline("feature-extraction", MODEL);
15
+ }
16
+ return embedderPromise;
17
+ }
18
+
13
19
  return async function embed(text) {
20
+ const embedder = await getEmbedder();
14
21
  const result = await embedder(text, {pooling, normalize});
15
22
  return Array.from(result.data as Float32Array);
16
23
  }
17
24
  }
18
-
@@ -1,34 +1,37 @@
1
1
  export type ILogger = (...args: any[]) => void;
2
2
 
3
- export function Logger(fn: (...args: any[]) => void): ILogger {
4
- return function log(...args) {
5
- fn(...args);
6
- }
7
- }
8
-
9
3
  const DEFAULT_FLUSH_MS = 100;
4
+ const DEFAULT_FLUSH_LINES = 15;
10
5
 
11
- export function BufferedLoggerToStdOut(flushMs = DEFAULT_FLUSH_MS): ILogger {
12
- return BufferedLogger(s => process.stdout.write(s), flushMs);
6
+ export function BufferedLoggerToStdOut(flushMs = DEFAULT_FLUSH_MS, flushLines = DEFAULT_FLUSH_LINES): ILogger {
7
+ return BufferedLogger(s => process.stdout.write(s), flushMs, flushLines);
13
8
  }
14
9
 
15
- export function BufferedLoggerToStdErr(flushMs = DEFAULT_FLUSH_MS): ILogger {
16
- return BufferedLogger(s => process.stderr.write(s), flushMs);
10
+ export function BufferedLoggerToStdErr(flushMs = DEFAULT_FLUSH_MS, flushLines = DEFAULT_FLUSH_LINES): ILogger {
11
+ return BufferedLogger(s => process.stderr.write(s), flushMs, flushLines);
17
12
  }
18
13
 
19
- export function BufferedLogger(write: (text: string) => void, flushMs = DEFAULT_FLUSH_MS): ILogger {
14
+ export function BufferedLogger(
15
+ write: (text: string) => void,
16
+ flushMs = DEFAULT_FLUSH_MS,
17
+ flushLines = DEFAULT_FLUSH_LINES,
18
+ ): ILogger {
20
19
  let buffer: string[] = [];
21
20
  let timer: ReturnType<typeof setTimeout> | null = null;
22
21
 
23
22
  function flush() {
23
+ if (timer) { clearTimeout(timer); timer = null; }
24
24
  if (buffer.length === 0) return;
25
25
  write(buffer.join("\n") + "\n");
26
26
  buffer = [];
27
- timer = null;
28
27
  }
29
28
 
30
29
  return function log(...args) {
31
30
  buffer.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" "));
31
+ if (buffer.length >= flushLines) {
32
+ flush();
33
+ return;
34
+ }
32
35
  if (!timer) timer = setTimeout(flush, flushMs);
33
36
  }
34
37
  }
@@ -6,6 +6,8 @@ import {ILogger} from "../componets/logger.js";
6
6
 
7
7
  export type IIndexContent = (items: Array<{id: string, content: string}>) => Promise<void>;
8
8
 
9
+ const SLOW_WARN_MS = 3000;
10
+
9
11
  export function IndexContent({extractKeywords, cleanUpKeywords, embed, indexApi, log}: {
10
12
  extractKeywords: IExtractKeywords,
11
13
  cleanUpKeywords: ICleanUpKeywords,
@@ -15,6 +17,10 @@ export function IndexContent({extractKeywords, cleanUpKeywords, embed, indexApi,
15
17
  }): IIndexContent {
16
18
  return async function indexContent(items) {
17
19
  const indexItems = (await Promise.all(items.map(async (item) => {
20
+ const warn = setTimeout(
21
+ () => log(`slow: still embedding ${item.id} after ${SLOW_WARN_MS}ms`),
22
+ SLOW_WARN_MS,
23
+ );
18
24
  try {
19
25
  const keywords = cleanUpKeywords(extractKeywords(item.content)).join(", ");
20
26
  const vector = await embed(keywords);
@@ -22,11 +28,21 @@ export function IndexContent({extractKeywords, cleanUpKeywords, embed, indexApi,
22
28
  } catch (e: any) {
23
29
  log(`skip ${item.id}: keywords/embed failed — ${e?.code ?? e?.message ?? e}`);
24
30
  return null;
31
+ } finally {
32
+ clearTimeout(warn);
25
33
  }
26
34
  }))).filter((x): x is NonNullable<typeof x> => !!x);
27
35
 
28
36
  if (indexItems.length > 0) {
29
- await indexApi({type: IndexCommandType.index, items: indexItems});
37
+ const warn = setTimeout(
38
+ () => log(`slow: still writing index after ${SLOW_WARN_MS}ms — ${indexItems.map(i => i.id).join(", ")}`),
39
+ SLOW_WARN_MS,
40
+ );
41
+ try {
42
+ await indexApi({type: IndexCommandType.index, items: indexItems});
43
+ } finally {
44
+ clearTimeout(warn);
45
+ }
30
46
  }
31
47
  }
32
48
  }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "xindex",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Local semantic code search — index codebase, search by meaning or keywords",
5
5
  "type": "module",
6
6
  "main": "xindex.ts",
7
7
  "bin": {
8
+ "xindex": "bin/xindex-mcp",
8
9
  "xindex-index": "bin/xindex-index",
9
10
  "xindex-search": "bin/xindex-search",
10
11
  "xindex-mcp": "bin/xindex-mcp",