pi-knowledge 0.15.0 → 0.16.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +59 -22
  3. package/dist/index.d.ts +10 -4
  4. package/dist/index.js +145 -166
  5. package/dist/src/coverage-snapshot.d.ts +23 -0
  6. package/dist/src/coverage-snapshot.js +53 -0
  7. package/dist/src/daemon/client.d.ts +60 -0
  8. package/dist/src/daemon/client.js +360 -0
  9. package/dist/src/daemon/main.d.ts +2 -0
  10. package/dist/src/daemon/main.js +109 -0
  11. package/dist/src/daemon/protocol.d.ts +71 -0
  12. package/dist/src/daemon/protocol.js +170 -0
  13. package/dist/src/daemon/runtime.d.ts +26 -0
  14. package/dist/src/daemon/runtime.js +192 -0
  15. package/dist/src/daemon/server.d.ts +46 -0
  16. package/dist/src/daemon/server.js +500 -0
  17. package/dist/src/daemon/service.d.ts +49 -0
  18. package/dist/src/daemon/service.js +527 -0
  19. package/dist/src/diagnostics/health.d.ts +6 -0
  20. package/dist/src/diagnostics/health.js +135 -2
  21. package/dist/src/engine.d.ts +13 -8
  22. package/dist/src/engine.js +569 -100
  23. package/dist/src/filesystem-access.d.ts +9 -0
  24. package/dist/src/filesystem-access.js +100 -0
  25. package/dist/src/indexer/chunker.d.ts +10 -0
  26. package/dist/src/indexer/chunker.js +284 -9
  27. package/dist/src/mcp/http.d.ts +47 -0
  28. package/dist/src/mcp/http.js +564 -0
  29. package/dist/src/mcp/main.d.ts +2 -0
  30. package/dist/src/mcp/main.js +97 -0
  31. package/dist/src/mcp/protocol.d.ts +81 -0
  32. package/dist/src/mcp/protocol.js +444 -0
  33. package/dist/src/mcp/server.d.ts +42 -0
  34. package/dist/src/mcp/server.js +378 -0
  35. package/dist/src/model-worker-client.js +9 -0
  36. package/dist/src/model-worker-contract.d.ts +3 -0
  37. package/dist/src/model-worker-contract.js +8 -0
  38. package/dist/src/model-worker.js +76 -4
  39. package/dist/src/network/safe-fetch.d.ts +7 -0
  40. package/dist/src/network/safe-fetch.js +199 -0
  41. package/dist/src/node-runtime.d.ts +3 -0
  42. package/dist/src/node-runtime.js +78 -0
  43. package/dist/src/profiles.d.ts +15 -0
  44. package/dist/src/profiles.js +160 -0
  45. package/dist/src/runtime-config.js +5 -6
  46. package/dist/src/secure-files.d.ts +17 -0
  47. package/dist/src/secure-files.js +184 -0
  48. package/dist/src/status.js +12 -7
  49. package/dist/src/storage/sqlite.d.ts +4 -1
  50. package/dist/src/storage/sqlite.js +46 -3
  51. package/dist/src/type-guards.d.ts +1 -0
  52. package/dist/src/type-guards.js +3 -0
  53. package/dist/src/watcher/file-watcher.d.ts +3 -1
  54. package/dist/src/watcher/file-watcher.js +166 -32
  55. package/dist/src/windows-security.d.ts +4 -0
  56. package/dist/src/windows-security.js +47 -0
  57. package/docs/configuration.md +39 -9
  58. package/docs/daemon-profiles.md +302 -0
  59. package/docs/mcp-clients.md +266 -0
  60. package/docs/offline-mode.md +6 -6
  61. package/package.json +28 -2
@@ -0,0 +1,527 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { boundedCoverageSnapshotError, writeCoverageSnapshot, } from "../coverage-snapshot.js";
3
+ import { KnowledgeEngine } from "../engine.js";
4
+ import { configureModelWorkerNodePath, shutdownModelWorker } from "../model-worker-client.js";
5
+ import { configureDaemonNodePath, resolveDaemonNodePath } from "../node-runtime.js";
6
+ import { isObjectRecord } from "../type-guards.js";
7
+ import { getActiveWatcherCount, getActiveWatcherScanCount, startWatcher, stopAllWatchers, stopAllWatchersAndWait, stopWatcher, } from "../watcher/file-watcher.js";
8
+ const MAX_RPC_KNOWLEDGE_BASES = 1_000;
9
+ const MAX_RPC_DIAGNOSTIC_PATHS = 2_000;
10
+ const MAX_RPC_OPTION_ITEMS = 128;
11
+ const MAX_RPC_OPTION_PATH_BYTES = 4_096;
12
+ const MAX_RPC_OPTIONS_BYTES = 64 * 1_024;
13
+ const SEARCH_MODES = [
14
+ "auto",
15
+ "fast",
16
+ "semantic",
17
+ "hybrid",
18
+ "semantic_hybrid",
19
+ "deep",
20
+ "adaptive",
21
+ "code",
22
+ "config",
23
+ "docs",
24
+ "errors",
25
+ "decision",
26
+ ];
27
+ const SEARCH_PROFILES = [
28
+ "auto",
29
+ "balanced",
30
+ "low_token",
31
+ "precision",
32
+ "recall",
33
+ "long_context",
34
+ "code",
35
+ "docs",
36
+ ];
37
+ const DIVERSITY_MODES = ["off", "balanced", "strong"];
38
+ const SYMBOL_KINDS = [
39
+ "function",
40
+ "class",
41
+ "interface",
42
+ "type",
43
+ "variable",
44
+ "heading",
45
+ "config_key",
46
+ "env_var",
47
+ "route",
48
+ ];
49
+ const RPC_STRING_LIMITS = {
50
+ name: 512,
51
+ target: 512,
52
+ query: 64 * 1_024,
53
+ input: 32 * 1_024,
54
+ output: 32 * 1_024,
55
+ source: 10 * 1_024 * 1_024 + 32 * 1_024,
56
+ kb_id: 512,
57
+ file_type: 1_024,
58
+ path_pattern: MAX_RPC_OPTION_PATH_BYTES,
59
+ file_pattern: MAX_RPC_OPTION_PATH_BYTES,
60
+ };
61
+ function requiredString(params, key) {
62
+ const value = params[key];
63
+ if (typeof value !== "string" || !value.trim())
64
+ throw new Error(`Missing or invalid ${key}`);
65
+ const maxBytes = RPC_STRING_LIMITS[key];
66
+ if (maxBytes !== undefined && Buffer.byteLength(value) > maxBytes) {
67
+ throw new Error(`${key} exceeds the ${maxBytes}-byte RPC limit`);
68
+ }
69
+ return value;
70
+ }
71
+ function assertKnownKeys(value, allowed, label) {
72
+ for (const key of Object.keys(value)) {
73
+ if (!allowed.includes(key))
74
+ throw new Error(`Invalid ${label}.${key}`);
75
+ }
76
+ }
77
+ function boundedOptionalString(value, key) {
78
+ const candidate = value[key];
79
+ if (candidate === undefined)
80
+ return undefined;
81
+ if (typeof candidate !== "string")
82
+ throw new Error(`Invalid options.${key}`);
83
+ const maxBytes = RPC_STRING_LIMITS[key] ?? MAX_RPC_OPTION_PATH_BYTES;
84
+ if (Buffer.byteLength(candidate) > maxBytes)
85
+ throw new Error(`options.${key} exceeds the ${maxBytes}-byte limit`);
86
+ return candidate;
87
+ }
88
+ function boundedOptionalInteger(value, key, minimum, maximum) {
89
+ const candidate = value[key];
90
+ if (candidate === undefined)
91
+ return undefined;
92
+ if (!Number.isInteger(candidate) || typeof candidate !== "number" || candidate < minimum || candidate > maximum) {
93
+ throw new Error(`Invalid options.${key}`);
94
+ }
95
+ return candidate;
96
+ }
97
+ function isOneOf(value, allowed) {
98
+ return typeof value === "string" && allowed.includes(value);
99
+ }
100
+ function boundedStringArray(value, key) {
101
+ if (value === undefined)
102
+ return undefined;
103
+ if (!Array.isArray(value) || value.length > MAX_RPC_OPTION_ITEMS)
104
+ throw new Error(`Invalid options.${key}`);
105
+ const normalized = [];
106
+ for (const item of value) {
107
+ if (typeof item !== "string" || Buffer.byteLength(item) > MAX_RPC_OPTION_PATH_BYTES) {
108
+ throw new Error(`Invalid options.${key}`);
109
+ }
110
+ normalized.push(item);
111
+ }
112
+ return normalized;
113
+ }
114
+ function optionsRecord(params) {
115
+ const value = params.options;
116
+ if (value === undefined)
117
+ return undefined;
118
+ if (!isObjectRecord(value))
119
+ throw new Error("Invalid options");
120
+ if (Buffer.byteLength(JSON.stringify(value)) > MAX_RPC_OPTIONS_BYTES) {
121
+ throw new Error(`options exceed the ${MAX_RPC_OPTIONS_BYTES}-byte limit`);
122
+ }
123
+ return value;
124
+ }
125
+ function parseAddOptions(params) {
126
+ const value = optionsRecord(params);
127
+ if (!value)
128
+ return undefined;
129
+ assertKnownKeys(value, ["include_suggested_text", "include_paths", "exclude_paths"], "options");
130
+ const includeSuggestedText = value.include_suggested_text;
131
+ if (includeSuggestedText !== undefined && typeof includeSuggestedText !== "boolean") {
132
+ throw new Error("Invalid options.include_suggested_text");
133
+ }
134
+ return {
135
+ include_suggested_text: includeSuggestedText,
136
+ include_paths: boundedStringArray(value.include_paths, "include_paths"),
137
+ exclude_paths: boundedStringArray(value.exclude_paths, "exclude_paths"),
138
+ };
139
+ }
140
+ function parseFilesystemAccess(params) {
141
+ const value = params.access;
142
+ if (value === undefined)
143
+ return undefined;
144
+ if (!isObjectRecord(value))
145
+ throw new Error("Invalid access policy");
146
+ assertKnownKeys(value, ["allowed_roots", "allow_network"], "access");
147
+ if (value.allow_network !== true && value.allow_network !== false) {
148
+ throw new Error("Invalid access.allow_network");
149
+ }
150
+ if (!Array.isArray(value.allowed_roots) || value.allowed_roots.length > MAX_RPC_OPTION_ITEMS) {
151
+ throw new Error("Invalid access.allowed_roots");
152
+ }
153
+ const allowedRoots = [];
154
+ for (const root of value.allowed_roots) {
155
+ if (typeof root !== "string" || Buffer.byteLength(root) > MAX_RPC_OPTION_PATH_BYTES) {
156
+ throw new Error("Invalid access.allowed_roots");
157
+ }
158
+ allowedRoots.push(root);
159
+ }
160
+ return { allowedRoots, allowNetwork: value.allow_network };
161
+ }
162
+ function parseSearchOptions(params) {
163
+ const value = optionsRecord(params);
164
+ if (!value)
165
+ return undefined;
166
+ assertKnownKeys(value, ["mode", "profile", "limit", "offset", "kb_id", "filters", "diversity"], "options");
167
+ if (value.mode !== undefined && !isOneOf(value.mode, SEARCH_MODES))
168
+ throw new Error("Invalid options.mode");
169
+ if (value.profile !== undefined && !isOneOf(value.profile, SEARCH_PROFILES))
170
+ throw new Error("Invalid options.profile");
171
+ if (value.diversity !== undefined && !isOneOf(value.diversity, DIVERSITY_MODES)) {
172
+ throw new Error("Invalid options.diversity");
173
+ }
174
+ let filters;
175
+ if (value.filters !== undefined) {
176
+ if (!isObjectRecord(value.filters))
177
+ throw new Error("Invalid options.filters");
178
+ assertKnownKeys(value.filters, ["file_type", "path_pattern"], "options.filters");
179
+ filters = {
180
+ file_type: boundedOptionalString(value.filters, "file_type"),
181
+ path_pattern: boundedOptionalString(value.filters, "path_pattern"),
182
+ };
183
+ }
184
+ return {
185
+ mode: value.mode,
186
+ profile: value.profile,
187
+ limit: boundedOptionalInteger(value, "limit", 1, 50),
188
+ offset: boundedOptionalInteger(value, "offset", 0, 799),
189
+ kb_id: boundedOptionalString(value, "kb_id"),
190
+ filters,
191
+ diversity: value.diversity,
192
+ };
193
+ }
194
+ function parseSymbolSearchOptions(params) {
195
+ const value = optionsRecord(params);
196
+ if (!value)
197
+ return undefined;
198
+ assertKnownKeys(value, ["kb_id", "kind", "file_pattern", "limit", "offset", "exact"], "options");
199
+ if (value.kind !== undefined && !isOneOf(value.kind, SYMBOL_KINDS))
200
+ throw new Error("Invalid options.kind");
201
+ if (value.exact !== undefined && typeof value.exact !== "boolean")
202
+ throw new Error("Invalid options.exact");
203
+ return {
204
+ kb_id: boundedOptionalString(value, "kb_id"),
205
+ kind: value.kind,
206
+ file_pattern: boundedOptionalString(value, "file_pattern"),
207
+ limit: boundedOptionalInteger(value, "limit", 1, 200),
208
+ offset: boundedOptionalInteger(value, "offset", 0, 799),
209
+ exact: value.exact,
210
+ };
211
+ }
212
+ function scanOptionsFromSourceOptions(raw) {
213
+ if (!raw)
214
+ return {};
215
+ try {
216
+ const parsed = JSON.parse(raw);
217
+ return {
218
+ includeSuggestedText: parsed.include_suggested_text === true,
219
+ includePaths: Array.isArray(parsed.include_paths)
220
+ ? parsed.include_paths.filter((item) => typeof item === "string")
221
+ : undefined,
222
+ excludePaths: Array.isArray(parsed.exclude_paths)
223
+ ? parsed.exclude_paths.filter((item) => typeof item === "string")
224
+ : undefined,
225
+ };
226
+ }
227
+ catch {
228
+ return {};
229
+ }
230
+ }
231
+ function waitForSettlement(run, signal) {
232
+ if (signal?.aborted)
233
+ return Promise.reject(new Error("Cancelled"));
234
+ const { promise, resolve, reject } = Promise.withResolvers();
235
+ let settled = false;
236
+ const finish = () => {
237
+ if (settled)
238
+ return;
239
+ settled = true;
240
+ signal?.removeEventListener("abort", abort);
241
+ resolve();
242
+ };
243
+ const abort = () => {
244
+ if (settled)
245
+ return;
246
+ settled = true;
247
+ signal?.removeEventListener("abort", abort);
248
+ reject(new Error("Cancelled"));
249
+ };
250
+ signal?.addEventListener("abort", abort, { once: true });
251
+ void run.then(finish, finish);
252
+ return promise;
253
+ }
254
+ export class KnowledgeDaemonService {
255
+ engine = new KnowledgeEngine();
256
+ updates = new Map();
257
+ watcherDirty = new Set();
258
+ watcherRetryTimers = new Map();
259
+ profile;
260
+ snapshotWriter;
261
+ onSnapshotStateChange;
262
+ initialized = false;
263
+ watchersEnabled = false;
264
+ shuttingDown = false;
265
+ lastSnapshotError;
266
+ constructor(profile, snapshotWriter = undefined, onSnapshotStateChange = undefined) {
267
+ this.profile = profile;
268
+ this.snapshotWriter = snapshotWriter;
269
+ this.onSnapshotStateChange = onSnapshotStateChange;
270
+ }
271
+ async initialize(watchersEnabled) {
272
+ if (this.initialized)
273
+ return;
274
+ await this.engine.initialize(this.profile.storageDir);
275
+ this.initialized = true;
276
+ this.refreshCoverageSnapshot();
277
+ if (watchersEnabled)
278
+ this.enableWatchers();
279
+ }
280
+ refreshCoverageSnapshot() {
281
+ try {
282
+ writeCoverageSnapshot(this.profile, this.engine.list(), this.snapshotWriter);
283
+ this.lastSnapshotError = undefined;
284
+ }
285
+ catch (error) {
286
+ this.lastSnapshotError = boundedCoverageSnapshotError(error);
287
+ console.error(this.lastSnapshotError);
288
+ }
289
+ finally {
290
+ this.onSnapshotStateChange?.();
291
+ }
292
+ }
293
+ coverageSnapshotError() {
294
+ return this.lastSnapshotError;
295
+ }
296
+ assertReady() {
297
+ if (!this.initialized)
298
+ throw new Error("Knowledge profile daemon is still initializing");
299
+ if (this.shuttingDown)
300
+ throw new Error("Knowledge profile daemon is shutting down");
301
+ }
302
+ triggerWatcherUpdate(kbId) {
303
+ if (this.shuttingDown)
304
+ return;
305
+ if (this.updates.has(kbId)) {
306
+ this.watcherDirty.add(kbId);
307
+ return;
308
+ }
309
+ void this.coordinateUpdate(`watcher:${randomUUID()}`, kbId, undefined, () => { }).catch((error) => {
310
+ if (this.shuttingDown)
311
+ return;
312
+ const blockedByMutation = error instanceof Error && error.message.includes("already running");
313
+ if (!blockedByMutation) {
314
+ this.watcherDirty.delete(kbId);
315
+ console.error("Watcher update failed; waiting for a new filesystem change");
316
+ return;
317
+ }
318
+ this.watcherDirty.add(kbId);
319
+ if (this.watcherRetryTimers.has(kbId))
320
+ return;
321
+ const timer = setTimeout(() => {
322
+ this.watcherRetryTimers.delete(kbId);
323
+ if (this.watcherDirty.delete(kbId))
324
+ this.triggerWatcherUpdate(kbId);
325
+ }, 250);
326
+ timer.unref();
327
+ this.watcherRetryTimers.set(kbId, timer);
328
+ });
329
+ }
330
+ startWatcherFor(kb) {
331
+ if (!this.watchersEnabled || !kb.source_path || kb.source_type !== "directory")
332
+ return;
333
+ startWatcher(kb.id, kb.source_path, (kbId) => this.triggerWatcherUpdate(kbId), scanOptionsFromSourceOptions(kb.source_options));
334
+ }
335
+ enableWatchers() {
336
+ this.assertReady();
337
+ if (!this.watchersEnabled) {
338
+ this.watchersEnabled = true;
339
+ for (const kb of this.engine.list())
340
+ this.startWatcherFor(kb);
341
+ }
342
+ return getActiveWatcherCount();
343
+ }
344
+ resolveKnowledgeBase(target) {
345
+ const knowledgeBases = this.engine.list();
346
+ const kb = knowledgeBases.find((candidate) => candidate.id === target) ??
347
+ knowledgeBases.find((candidate) => candidate.name === target);
348
+ if (!kb)
349
+ throw new Error(`Knowledge base not found: ${target}`);
350
+ return kb;
351
+ }
352
+ coordinateUpdate(subscriberId, target, signal, onProgress, access) {
353
+ this.assertReady();
354
+ if (signal?.aborted)
355
+ return Promise.reject(new Error("Cancelled"));
356
+ const kb = this.resolveKnowledgeBase(target);
357
+ let operation = this.updates.get(kb.id);
358
+ if (operation?.closing) {
359
+ return waitForSettlement(operation.promise, signal).then(() => this.coordinateUpdate(subscriberId, target, signal, onProgress, access));
360
+ }
361
+ if (!operation) {
362
+ const controller = new AbortController();
363
+ const subscribers = new Map();
364
+ const promise = this.engine
365
+ .update(kb.id, (message) => {
366
+ for (const subscriber of subscribers.values())
367
+ subscriber.onProgress(message);
368
+ }, controller.signal, access)
369
+ .then((result) => {
370
+ this.refreshCoverageSnapshot();
371
+ return result;
372
+ })
373
+ .finally(() => {
374
+ if (this.updates.get(kb.id)?.promise !== promise)
375
+ return;
376
+ this.updates.delete(kb.id);
377
+ if (this.watcherDirty.delete(kb.id) && !this.shuttingDown) {
378
+ queueMicrotask(() => this.triggerWatcherUpdate(kb.id));
379
+ }
380
+ });
381
+ operation = { controller, subscribers, promise, closing: false };
382
+ this.updates.set(kb.id, operation);
383
+ }
384
+ const active = operation;
385
+ const { promise, resolve, reject } = Promise.withResolvers();
386
+ let settled = false;
387
+ const abort = () => {
388
+ if (settled)
389
+ return;
390
+ settled = true;
391
+ active.subscribers.delete(subscriberId);
392
+ signal?.removeEventListener("abort", abort);
393
+ reject(new Error("Cancelled"));
394
+ if (active.subscribers.size === 0) {
395
+ active.closing = true;
396
+ active.controller.abort();
397
+ }
398
+ };
399
+ const cleanup = () => signal?.removeEventListener("abort", abort);
400
+ active.subscribers.set(subscriberId, { resolve, reject, onProgress, cleanup });
401
+ signal?.addEventListener("abort", abort, { once: true });
402
+ void active.promise.then((result) => {
403
+ const subscriber = active.subscribers.get(subscriberId);
404
+ if (!subscriber || settled)
405
+ return;
406
+ settled = true;
407
+ active.subscribers.delete(subscriberId);
408
+ subscriber.cleanup();
409
+ subscriber.resolve(result);
410
+ }, (error) => {
411
+ const subscriber = active.subscribers.get(subscriberId);
412
+ if (!subscriber || settled)
413
+ return;
414
+ settled = true;
415
+ active.subscribers.delete(subscriberId);
416
+ subscriber.cleanup();
417
+ subscriber.reject(error instanceof Error ? error : new Error(String(error)));
418
+ });
419
+ return promise;
420
+ }
421
+ async dispatch(method, params, context) {
422
+ this.assertReady();
423
+ switch (method) {
424
+ case "plan":
425
+ return this.engine.planAsync(requiredString(params, "source"), parseAddOptions(params), context.signal, parseFilesystemAccess(params));
426
+ case "configure": {
427
+ if (params.node_path !== undefined && typeof params.node_path !== "string") {
428
+ throw new Error("Invalid node_path");
429
+ }
430
+ const nodePath = params.node_path === undefined
431
+ ? resolveDaemonNodePath(this.profile)
432
+ : configureDaemonNodePath(this.profile, params.node_path);
433
+ return { node_path: configureModelWorkerNodePath(nodePath) };
434
+ }
435
+ case "add": {
436
+ const result = await this.engine.add(requiredString(params, "source"), requiredString(params, "name"), context.onProgress, context.signal, parseAddOptions(params), parseFilesystemAccess(params));
437
+ this.startWatcherFor(result.kb);
438
+ this.refreshCoverageSnapshot();
439
+ return result;
440
+ }
441
+ case "update":
442
+ return this.coordinateUpdate(context.requestId, requiredString(params, "target"), context.signal, context.onProgress, parseFilesystemAccess(params));
443
+ case "remove": {
444
+ const target = requiredString(params, "target");
445
+ const kb = this.engine.list().find((candidate) => candidate.id === target || candidate.name === target);
446
+ const removed = this.engine.remove(target);
447
+ if (removed && kb) {
448
+ this.watcherDirty.delete(kb.id);
449
+ const timer = this.watcherRetryTimers.get(kb.id);
450
+ if (timer)
451
+ clearTimeout(timer);
452
+ this.watcherRetryTimers.delete(kb.id);
453
+ stopWatcher(kb.id);
454
+ }
455
+ if (removed)
456
+ this.refreshCoverageSnapshot();
457
+ return removed;
458
+ }
459
+ case "clear":
460
+ this.engine.clear();
461
+ this.watcherDirty.clear();
462
+ for (const timer of this.watcherRetryTimers.values())
463
+ clearTimeout(timer);
464
+ this.watcherRetryTimers.clear();
465
+ stopAllWatchers();
466
+ this.refreshCoverageSnapshot();
467
+ return undefined;
468
+ case "import": {
469
+ const result = await this.engine.importKB(requiredString(params, "input"), context.onProgress, context.signal, parseFilesystemAccess(params));
470
+ this.refreshCoverageSnapshot();
471
+ return result;
472
+ }
473
+ case "export":
474
+ return this.engine.exportKB(requiredString(params, "target"), requiredString(params, "output"), context.signal, context.onProgress, parseFilesystemAccess(params));
475
+ case "search":
476
+ return this.engine.search(requiredString(params, "query"), parseSearchOptions(params), context.signal);
477
+ case "symbol_search":
478
+ return this.engine.symbolSearch(requiredString(params, "query"), parseSymbolSearchOptions(params), context.signal);
479
+ case "list": {
480
+ const knowledgeBases = this.engine.list(context.signal, MAX_RPC_KNOWLEDGE_BASES + 1);
481
+ if (knowledgeBases.length > MAX_RPC_KNOWLEDGE_BASES) {
482
+ throw new Error(`Knowledge list exceeds the ${MAX_RPC_KNOWLEDGE_BASES}-knowledge-base RPC limit`);
483
+ }
484
+ return knowledgeBases;
485
+ }
486
+ case "status":
487
+ return {
488
+ profile: { name: this.profile.name, id: this.profile.id },
489
+ storage_path: this.profile.storageDir,
490
+ watch_count: getActiveWatcherCount(),
491
+ snapshot_error: this.lastSnapshotError,
492
+ snapshot: await this.engine.statusSnapshotAsync(context.signal, MAX_RPC_KNOWLEDGE_BASES, MAX_RPC_DIAGNOSTIC_PATHS),
493
+ };
494
+ case "doctor":
495
+ return this.engine.doctorAsync(context.signal, MAX_RPC_KNOWLEDGE_BASES, MAX_RPC_DIAGNOSTIC_PATHS);
496
+ case "enable_watchers":
497
+ return { watch_count: this.enableWatchers() };
498
+ case "ping":
499
+ return { ready: true };
500
+ case "shutdown":
501
+ throw new Error("Shutdown must be handled by the daemon server");
502
+ }
503
+ }
504
+ abortOperations() {
505
+ this.shuttingDown = true;
506
+ stopAllWatchers();
507
+ this.watcherDirty.clear();
508
+ for (const timer of this.watcherRetryTimers.values())
509
+ clearTimeout(timer);
510
+ this.watcherRetryTimers.clear();
511
+ for (const operation of this.updates.values())
512
+ operation.controller.abort();
513
+ }
514
+ forceTerminateModelWorker() {
515
+ shutdownModelWorker();
516
+ }
517
+ activeUpdateCount() {
518
+ return this.updates.size + getActiveWatcherScanCount();
519
+ }
520
+ async dispose() {
521
+ this.shuttingDown = true;
522
+ stopAllWatchers();
523
+ await stopAllWatchersAndWait();
524
+ await this.engine.dispose();
525
+ this.initialized = false;
526
+ }
527
+ }
@@ -10,10 +10,16 @@ export interface DiagnosticResult {
10
10
  stuck_indexing: boolean;
11
11
  stale_files: string[];
12
12
  orphan_files: string[];
13
+ stale_file_count?: number;
14
+ orphan_file_count?: number;
15
+ stale_files_truncated?: boolean;
16
+ orphan_files_truncated?: boolean;
13
17
  coverage_percent: number;
14
18
  total_source_files: number;
15
19
  indexed_files: number;
16
20
  skipped_files: ScanResult["skipped"];
21
+ scan_error?: string;
17
22
  job?: IndexingJob;
18
23
  }
19
24
  export declare function diagnoseKB(db: Database.Database, kb: KnowledgeBase, signal?: AbortSignal): DiagnosticResult;
25
+ export declare function diagnoseKBAsync(db: Database.Database, kb: KnowledgeBase, signal?: AbortSignal, maxDiagnosticPaths?: number): Promise<DiagnosticResult>;