@dikolab/kbdb 0.4.0 → 0.4.3

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 (100) hide show
  1. package/README.md +30 -22
  2. package/dist/{chunk-BJPSPNGX.mjs → chunk-BJXEVALU.mjs} +115 -1
  3. package/dist/chunk-BJXEVALU.mjs.map +7 -0
  4. package/dist/cli.cjs +462 -79
  5. package/dist/cli.cjs.map +4 -4
  6. package/dist/cli.mjs +356 -79
  7. package/dist/cli.mjs.map +4 -4
  8. package/dist/kbdb-worker.cjs +413 -53
  9. package/dist/kbdb-worker.cjs.map +4 -4
  10. package/dist/mod.cjs +230 -54
  11. package/dist/mod.cjs.map +4 -4
  12. package/dist/mod.mjs +229 -53
  13. package/dist/mod.mjs.map +4 -4
  14. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +5 -0
  15. package/dist/src/shared/embedding/classes/tfidf-embedding-provider.class.d.ts +28 -0
  16. package/dist/src/shared/embedding/constants/tfidf-defaults.constant.d.ts +4 -0
  17. package/dist/src/shared/embedding/functions/create-embedding-provider.function.d.ts +5 -2
  18. package/dist/src/shared/embedding/index.d.ts +2 -0
  19. package/dist/src/shared/log/constants/log-colors.constant.d.ts +5 -0
  20. package/dist/src/shared/log/constants/log-defaults.constant.d.ts +3 -0
  21. package/dist/src/shared/log/constants/log-icons.constant.d.ts +3 -0
  22. package/dist/src/shared/log/functions/configure-log.function.d.ts +12 -0
  23. package/dist/src/shared/log/functions/log.function.d.ts +28 -0
  24. package/dist/src/shared/log/functions/parse-log-level.function.d.ts +10 -0
  25. package/dist/src/shared/log/functions/resolve-log-level.function.d.ts +12 -0
  26. package/dist/src/shared/log/functions/write-stderr.function.d.ts +10 -0
  27. package/dist/src/shared/log/index.d.ts +10 -0
  28. package/dist/src/shared/log/typings/log-config.interface.d.ts +7 -0
  29. package/dist/src/shared/log/typings/log-level.type.d.ts +7 -0
  30. package/dist/src/shared/log/typings/log-output.interface.d.ts +4 -0
  31. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  32. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +7 -0
  33. package/dist/src/shared/worker-client/functions/retry-on-timeout.function.d.ts +1 -0
  34. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +1 -0
  35. package/dist/src/shared/worker-daemon/functions/run-worker.function.d.ts +6 -1
  36. package/dist/src/shared/worker-daemon/typings/wasm-modules.interface.d.ts +5 -0
  37. package/dist/wasm/default-embedding/kbdb_default_embedding.d.ts +55 -0
  38. package/dist/wasm/default-embedding/kbdb_default_embedding.js +156 -0
  39. package/dist/wasm/default-embedding/kbdb_default_embedding_bg.wasm +0 -0
  40. package/dist/wasm/default-embedding/kbdb_default_embedding_bg.wasm.d.ts +12 -0
  41. package/dist/wasm/default-embedding/package.json +13 -0
  42. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  43. package/dist/wasm/fs-migration/kbdb_fs_migration.d.ts +38 -0
  44. package/dist/wasm/fs-migration/kbdb_fs_migration.js +130 -0
  45. package/dist/wasm/fs-migration/kbdb_fs_migration_bg.wasm +0 -0
  46. package/dist/wasm/fs-migration/kbdb_fs_migration_bg.wasm.d.ts +9 -0
  47. package/dist/wasm/fs-migration/package.json +13 -0
  48. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  49. package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  50. package/dist/worker.mjs +306 -54
  51. package/dist/worker.mjs.map +4 -4
  52. package/docs/details/agent-tooling.md +10 -0
  53. package/docs/details/cli.md +29 -13
  54. package/docs/details/knowledge-base.md +15 -8
  55. package/docs/details/mcp-server.md +16 -1
  56. package/docs/details/search-and-ranking.md +6 -2
  57. package/docs/goals/cli.md +33 -4
  58. package/docs/goals/content-parser.md +1 -1
  59. package/docs/goals/hybrid-search.md +71 -42
  60. package/docs/goals/mcp.md +3 -1
  61. package/docs/goals/overview.md +1 -1
  62. package/docs/goals/query-parser.md +1 -1
  63. package/docs/goals/semantic-dedup.md +7 -3
  64. package/docs/goals/worker-daemon.md +31 -20
  65. package/docs/modules/overview.md +43 -22
  66. package/docs/modules/rust/embedding/module.md +91 -0
  67. package/docs/modules/rust/overview.md +56 -21
  68. package/docs/modules/rust/query-parser/functions/module.md +7 -5
  69. package/docs/modules/rust/query-parser/functions/pipeline.md +6 -138
  70. package/docs/modules/rust/query-parser/module.md +16 -22
  71. package/docs/modules/rust/query-parser/types/module.md +5 -4
  72. package/docs/modules/rust/query-parser/types/token.md +5 -1
  73. package/docs/modules/rust/shared/content-parser/functions.md +1 -1
  74. package/docs/modules/rust/shared/memory/module.md +1 -1
  75. package/docs/modules/rust/shared/module.md +33 -5
  76. package/docs/modules/rust/shared/pipeline/functions.md +141 -0
  77. package/docs/modules/rust/shared/pipeline/module.md +62 -0
  78. package/docs/modules/rust/shared/pipeline/types.md +43 -0
  79. package/docs/modules/rust/shared/section/module.md +1 -1
  80. package/docs/modules/rust/shared/section/types.md +1 -1
  81. package/docs/modules/typescript/cli.md +4 -2
  82. package/docs/modules/typescript/kbdb-worker.md +20 -5
  83. package/docs/modules/typescript/overview.md +28 -6
  84. package/docs/modules/typescript/shared/cli/functions.md +15 -4
  85. package/docs/modules/typescript/shared/cli/typings.md +21 -0
  86. package/docs/modules/typescript/shared/embedding/functions.md +30 -3
  87. package/docs/modules/typescript/shared/embedding/module.md +10 -4
  88. package/docs/modules/typescript/shared/embedding/typings.md +7 -5
  89. package/docs/modules/typescript/shared/log/constants.md +82 -0
  90. package/docs/modules/typescript/shared/log/functions.md +131 -0
  91. package/docs/modules/typescript/shared/log/module.md +153 -0
  92. package/docs/modules/typescript/shared/log/typings.md +82 -0
  93. package/docs/modules/typescript/shared/module.md +22 -6
  94. package/docs/modules/typescript/shared/worker-daemon/functions.md +19 -6
  95. package/docs/modules/typescript/shared/worker-daemon/module.md +5 -2
  96. package/docs/modules/typescript/shared/worker-daemon/typings.md +13 -7
  97. package/docs/release-notes/0.4.1.md +149 -0
  98. package/docs/release-notes/0.4.3.md +60 -0
  99. package/package.json +2 -2
  100. package/dist/chunk-BJPSPNGX.mjs.map +0 -7
package/dist/cli.cjs CHANGED
@@ -69,6 +69,26 @@ var SUPPORTED_EXTENSIONS = [
69
69
  ".adoc"
70
70
  ];
71
71
 
72
+ // src/shared/log/typings/log-level.type.ts
73
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
74
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
75
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
76
+ LogLevel2[LogLevel2["WARNING"] = 2] = "WARNING";
77
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
78
+ return LogLevel2;
79
+ })(LogLevel || {});
80
+
81
+ // src/shared/log/functions/parse-log-level.function.ts
82
+ var LOG_LEVEL_MAP = {
83
+ debug: 0 /* DEBUG */,
84
+ info: 1 /* INFO */,
85
+ warning: 2 /* WARNING */,
86
+ error: 3 /* ERROR */
87
+ };
88
+ function parseLogLevel(value) {
89
+ return LOG_LEVEL_MAP[value.toLowerCase()] ?? 2 /* WARNING */;
90
+ }
91
+
72
92
  // src/shared/cli/functions/parse-args.function.ts
73
93
  function parseArgs(argv) {
74
94
  const options = {
@@ -92,19 +112,31 @@ function parseArgs(argv) {
92
112
  }
93
113
  return options;
94
114
  case "--version":
95
- case "-v":
96
115
  options.command = "version";
97
116
  return options;
117
+ case "-v":
118
+ case "--verbose": {
119
+ const next = argv[i + 1];
120
+ if (next && !next.startsWith("-")) {
121
+ options.logLevel = parseLogLevel(next);
122
+ i++;
123
+ } else {
124
+ options.logLevel = 2 /* WARNING */;
125
+ }
126
+ break;
127
+ }
128
+ case "-vv":
129
+ case "--verbose-info":
130
+ options.logLevel = 1 /* INFO */;
131
+ break;
132
+ case "-vvv":
133
+ case "--verbose-debug":
134
+ options.logLevel = 0 /* DEBUG */;
135
+ break;
98
136
  case "--init":
99
- console.error(
100
- 'warning: --init is deprecated, use "kbdb db init"'
101
- );
102
137
  options.command = "init";
103
138
  break;
104
139
  case "--migrate":
105
- console.error(
106
- 'warning: --migrate is deprecated, use "kbdb db migrate"'
107
- );
108
140
  options.command = "migrate";
109
141
  break;
110
142
  case "--db":
@@ -189,6 +221,9 @@ function parseArgs(argv) {
189
221
  case "--retry":
190
222
  options.retry = parseInt(argv[++i] ?? "", 10) || void 0;
191
223
  break;
224
+ case "--non-interactive":
225
+ options.nonInteractive = true;
226
+ break;
192
227
  default:
193
228
  if (!options.command) {
194
229
  options.command = arg;
@@ -263,8 +298,67 @@ function formatMcp(paged) {
263
298
  );
264
299
  }
265
300
 
301
+ // src/shared/log/constants/log-colors.constant.ts
302
+ var ANSI_RESET = "\x1B[0m";
303
+ var LOG_COLORS = {
304
+ [0 /* DEBUG */]: "\x1B[37m",
305
+ [1 /* INFO */]: "\x1B[36m",
306
+ [2 /* WARNING */]: "\x1B[33m",
307
+ [3 /* ERROR */]: "\x1B[91m"
308
+ };
309
+
310
+ // src/shared/log/constants/log-icons.constant.ts
311
+ var LOG_ICONS = {
312
+ [0 /* DEBUG */]: "\u25B8",
313
+ [1 /* INFO */]: "\u2139",
314
+ [2 /* WARNING */]: "\u26A0",
315
+ [3 /* ERROR */]: "\u2716"
316
+ };
317
+
318
+ // src/shared/log/constants/log-defaults.constant.ts
319
+ var DEFAULT_LOG_LEVEL = 3 /* ERROR */;
320
+
321
+ // src/shared/log/functions/write-stderr.function.ts
322
+ function writeStderr(message) {
323
+ const g = globalThis;
324
+ const proc = g["process"];
325
+ if (proc?.stderr) {
326
+ proc.stderr.write(message);
327
+ return;
328
+ }
329
+ const deno = g["Deno"];
330
+ deno?.stderr.writeSync(new TextEncoder().encode(message));
331
+ }
332
+
333
+ // src/shared/log/functions/log.function.ts
334
+ var currentLevel = DEFAULT_LOG_LEVEL;
335
+ var outputs = {
336
+ [0 /* DEBUG */]: writeStderr,
337
+ [1 /* INFO */]: writeStderr,
338
+ [2 /* WARNING */]: writeStderr,
339
+ [3 /* ERROR */]: writeStderr
340
+ };
341
+ function setLogLevel(level) {
342
+ currentLevel = level;
343
+ }
344
+ function setLogOutput(level, output) {
345
+ outputs[level] = output;
346
+ }
347
+ function log(message, level = 3 /* ERROR */) {
348
+ if (level < currentLevel) {
349
+ return;
350
+ }
351
+ const color = LOG_COLORS[level];
352
+ const icon = LOG_ICONS[level];
353
+ const name = LogLevel[level];
354
+ const line = `${color}${icon} [${name}] ${message}${ANSI_RESET}
355
+ `;
356
+ outputs[level](line);
357
+ }
358
+
266
359
  // src/shared/cli/functions/run-search.function.ts
267
360
  async function runSearch(client, options) {
361
+ log("searching: " + options.args.join(" "), 0 /* DEBUG */);
268
362
  const query = options.args.join(" ").trim();
269
363
  if (!query) {
270
364
  return {
@@ -284,6 +378,10 @@ async function runSearch(client, options) {
284
378
  algo: options.algo,
285
379
  relaxed: options.relaxed
286
380
  });
381
+ log(
382
+ "search returned " + results.total.toString() + " results",
383
+ 0 /* DEBUG */
384
+ );
287
385
  return {
288
386
  items: results.items.map((r) => ({
289
387
  kbid: r.kbid,
@@ -321,12 +419,14 @@ async function resolveKbidPrefix(prefix, client) {
321
419
  }
322
420
  }
323
421
  if (seen.size === 0) {
324
- throw new Error(`no section matches prefix "${prefix}"`);
422
+ const msg = `no section matches prefix "${prefix}"`;
423
+ log(msg, 3 /* ERROR */);
424
+ throw new Error(msg);
325
425
  }
326
426
  if (seen.size > 1) {
327
- throw new Error(
328
- `ambiguous prefix "${prefix}": ${seen.size.toString()} matches`
329
- );
427
+ const msg = `ambiguous prefix "${prefix}": ${seen.size.toString()} matches`;
428
+ log(msg, 3 /* ERROR */);
429
+ throw new Error(msg);
330
430
  }
331
431
  return [...seen][0];
332
432
  }
@@ -334,6 +434,7 @@ async function resolveKbidPrefix(prefix, client) {
334
434
  // src/shared/cli/functions/run-recall.function.ts
335
435
  var MAX_RECALL_DEPTH = 3;
336
436
  async function runRecall(client, options) {
437
+ log("running recall", 0 /* DEBUG */);
337
438
  if (options.args.length === 0) {
338
439
  return { error: "no kbid provided" };
339
440
  }
@@ -352,6 +453,7 @@ async function runRecall(client, options) {
352
453
 
353
454
  // src/shared/cli/functions/run-export.function.ts
354
455
  async function runExport(client, options) {
456
+ log("running export", 0 /* DEBUG */);
355
457
  const path = options.args[0];
356
458
  return client.export({ path });
357
459
  }
@@ -360,6 +462,10 @@ async function runExport(client, options) {
360
462
  var import_node_fs = require("node:fs");
361
463
  var import_node_path3 = require("node:path");
362
464
  async function runLearn(client, options, io) {
465
+ log(
466
+ "learning " + options.args.length.toString() + " targets",
467
+ 0 /* DEBUG */
468
+ );
363
469
  const results = [];
364
470
  let stdinConsumed = false;
365
471
  const readStdin = io?.readStdin ?? readProcessStdin;
@@ -398,6 +504,10 @@ async function runLearn(client, options, io) {
398
504
  );
399
505
  }
400
506
  }
507
+ log(
508
+ "learned " + results.length.toString() + " sections",
509
+ 0 /* DEBUG */
510
+ );
401
511
  return results;
402
512
  }
403
513
  function mapAddSectionResult(result, path, size) {
@@ -461,6 +571,7 @@ function isSupportedFile(path) {
461
571
 
462
572
  // src/shared/cli/functions/run-unlearn.function.ts
463
573
  async function runUnlearn(client, options) {
574
+ log("running unlearn", 0 /* DEBUG */);
464
575
  const results = [];
465
576
  for (const arg of options.args) {
466
577
  const kbid = await resolveKbidPrefix(arg, client);
@@ -472,6 +583,7 @@ async function runUnlearn(client, options) {
472
583
 
473
584
  // src/shared/cli/functions/run-content.function.ts
474
585
  async function runContent(client, options) {
586
+ log("running content", 0 /* DEBUG */);
475
587
  const resolved = await Promise.all(
476
588
  options.args.map((a) => resolveKbidPrefix(a, client))
477
589
  );
@@ -489,6 +601,7 @@ function parseDivergentContent(encoded) {
489
601
  }).filter((entry) => entry.kbids.length > 0);
490
602
  }
491
603
  async function runCheck(client, _options) {
604
+ log("running check", 0 /* DEBUG */);
492
605
  const raw = await client.integrityCheck();
493
606
  return {
494
607
  ok: raw.ok,
@@ -503,11 +616,13 @@ async function runCheck(client, _options) {
503
616
 
504
617
  // src/shared/cli/functions/run-gc.function.ts
505
618
  async function runGc(client, _options) {
619
+ log("running gc", 0 /* DEBUG */);
506
620
  return client.gc();
507
621
  }
508
622
 
509
623
  // src/shared/cli/functions/run-rebuild.function.ts
510
624
  async function runRebuild(client, _options) {
625
+ log("running rebuild", 0 /* DEBUG */);
511
626
  return client.rebuildIndexes();
512
627
  }
513
628
 
@@ -663,6 +778,7 @@ function createScaffold(dbDir) {
663
778
  (0, import_node_fs4.writeFileSync)((0, import_node_path6.join)(dbDir, ".gitignore"), GITIGNORE);
664
779
  }
665
780
  function runInit(options) {
781
+ log("running init", 0 /* DEBUG */);
666
782
  const basePath = options.dbPath ? (0, import_node_path6.resolve)(options.dbPath) : process.cwd();
667
783
  const dbDir = (0, import_node_path6.join)(basePath, ".kbdb");
668
784
  try {
@@ -714,11 +830,13 @@ function askReadline(question) {
714
830
 
715
831
  // src/shared/cli/functions/run-status.function.ts
716
832
  async function runStatus(client, _options) {
833
+ log("running status", 0 /* DEBUG */);
717
834
  return client.dbStatus();
718
835
  }
719
836
 
720
837
  // src/shared/cli/functions/run-db-init.function.ts
721
838
  function runDbInit(options, runInitFn) {
839
+ log("running db-init", 0 /* DEBUG */);
722
840
  const result = runInitFn(options);
723
841
  if (result.ok) {
724
842
  return {
@@ -738,6 +856,7 @@ function runDbInit(options, runInitFn) {
738
856
 
739
857
  // src/shared/cli/functions/run-db-migrate.function.ts
740
858
  async function runDbMigrate(client, options) {
859
+ log("running db-migrate", 0 /* DEBUG */);
741
860
  const dbPath = options.dbPath ?? process.cwd();
742
861
  return client.migrateDatabase(dbPath);
743
862
  }
@@ -765,6 +884,7 @@ function serializeSkillContent(skill) {
765
884
 
766
885
  // src/shared/cli/functions/run-skill-learn.function.ts
767
886
  async function runSkillLearn(client, options) {
887
+ log("running skill-learn", 0 /* DEBUG */);
768
888
  const name = options.name;
769
889
  if (!name) {
770
890
  return { error: "--name is required", exitCode: 1 };
@@ -795,6 +915,7 @@ async function runSkillLearn(client, options) {
795
915
 
796
916
  // src/shared/cli/functions/run-skill-list.function.ts
797
917
  async function runSkillList(client, _options) {
918
+ log("running skill-list", 0 /* DEBUG */);
798
919
  const records = await client.listByType("skill");
799
920
  const items = records.map((r) => {
800
921
  let argumentCount = 0;
@@ -822,9 +943,11 @@ async function runSkillList(client, _options) {
822
943
  function parseSkillContent(json) {
823
944
  const raw = JSON.parse(json);
824
945
  if (typeof raw["name"] !== "string" || !raw["name"]) {
946
+ log("skill name is required", 3 /* ERROR */);
825
947
  throw new Error("skill name is required");
826
948
  }
827
949
  if (typeof raw["body"] !== "string") {
950
+ log("skill body is required", 3 /* ERROR */);
828
951
  throw new Error("skill body is required");
829
952
  }
830
953
  return {
@@ -837,6 +960,7 @@ function parseSkillContent(json) {
837
960
 
838
961
  // src/shared/cli/functions/run-skill-get.function.ts
839
962
  async function runSkillGet(client, options) {
963
+ log("running skill-get", 0 /* DEBUG */);
840
964
  const identifier = options.args[0] ?? options.name;
841
965
  if (!identifier) {
842
966
  return {
@@ -873,6 +997,7 @@ async function runSkillGet(client, options) {
873
997
 
874
998
  // src/shared/cli/functions/run-skill-delete.function.ts
875
999
  async function runSkillDelete(client, options) {
1000
+ log("running skill-delete", 0 /* DEBUG */);
876
1001
  const kbid = options.args[0];
877
1002
  if (!kbid) {
878
1003
  return { error: "kbid is required", exitCode: 1 };
@@ -890,6 +1015,7 @@ async function runSkillDelete(client, options) {
890
1015
 
891
1016
  // src/shared/cli/functions/run-agent-create.function.ts
892
1017
  async function runAgentCreate(client, options) {
1018
+ log("running agent-create", 0 /* DEBUG */);
893
1019
  const name = options.name;
894
1020
  if (!name) {
895
1021
  return { error: "--name is required", exitCode: 1 };
@@ -935,6 +1061,7 @@ async function runAgentCreate(client, options) {
935
1061
 
936
1062
  // src/shared/cli/functions/run-agent-list.function.ts
937
1063
  async function runAgentList(client, _options) {
1064
+ log("running agent-list", 0 /* DEBUG */);
938
1065
  const docs = await client.listDocumentsByType("agent");
939
1066
  const items = docs.map((d) => ({
940
1067
  docid: d.docid,
@@ -991,6 +1118,7 @@ async function resolveSkills(client, skillRefs) {
991
1118
  });
992
1119
  }
993
1120
  async function runAgentGet(client, options) {
1121
+ log("running agent-get", 0 /* DEBUG */);
994
1122
  const docid = options.args[0];
995
1123
  if (!docid) {
996
1124
  return { error: "docid is required", exitCode: 1 };
@@ -1012,6 +1140,7 @@ async function runAgentGet(client, options) {
1012
1140
 
1013
1141
  // src/shared/cli/functions/run-agent-delete.function.ts
1014
1142
  async function runAgentDelete(client, options) {
1143
+ log("running agent-delete", 0 /* DEBUG */);
1015
1144
  const docid = options.args[0];
1016
1145
  if (!docid) {
1017
1146
  return { error: "docid is required", exitCode: 1 };
@@ -1027,7 +1156,9 @@ async function runAgentDelete(client, options) {
1027
1156
  async function runImport(client, options) {
1028
1157
  const from = options.from;
1029
1158
  if (!from) {
1030
- throw new Error("import requires --from <path>");
1159
+ const msg = "import requires --from <path>";
1160
+ log(msg, 3 /* ERROR */);
1161
+ throw new Error(msg);
1031
1162
  }
1032
1163
  return client.import({
1033
1164
  from,
@@ -1037,6 +1168,7 @@ async function runImport(client, options) {
1037
1168
 
1038
1169
  // src/shared/cli/functions/dispatch-command.function.ts
1039
1170
  async function dispatchCommand(client, options, io) {
1171
+ log("dispatching command: " + options.command, 0 /* DEBUG */);
1040
1172
  switch (options.command) {
1041
1173
  case "learn":
1042
1174
  return handleLearn(client, options, io);
@@ -1097,6 +1229,7 @@ async function dispatchCommand(client, options, io) {
1097
1229
  return result;
1098
1230
  }
1099
1231
  default:
1232
+ log("unknown command: " + options.command, 2 /* WARNING */);
1100
1233
  return {
1101
1234
  error: `unknown command: ${options.command}`,
1102
1235
  exitCode: 1
@@ -1296,7 +1429,7 @@ async function hydrateSearchPreviews(client, paged) {
1296
1429
  }
1297
1430
 
1298
1431
  // src/shared/version/constants/version.constant.ts
1299
- var VERSION = "0.4.0";
1432
+ var VERSION = "0.4.3";
1300
1433
 
1301
1434
  // src/shared/cli/functions/generate-help.function.ts
1302
1435
  var KNOWN_COMMANDS = /* @__PURE__ */ new Set([
@@ -1842,6 +1975,57 @@ function generateSubcommandHelp(command, subcommand) {
1842
1975
 
1843
1976
  // src/shared/worker-client/classes/worker-client.class.ts
1844
1977
  var import_node_net = require("node:net");
1978
+
1979
+ // src/shared/worker-client/functions/discover-daemon.function.ts
1980
+ var import_node_fs5 = require("node:fs");
1981
+ var import_node_path7 = require("node:path");
1982
+ var import_node_os = require("node:os");
1983
+
1984
+ // src/shared/platform/functions/is-process-alive.function.ts
1985
+ function isProcessAlive(pid) {
1986
+ try {
1987
+ process.kill(pid, 0);
1988
+ return true;
1989
+ } catch {
1990
+ return false;
1991
+ }
1992
+ }
1993
+
1994
+ // src/shared/worker-client/functions/discover-daemon.function.ts
1995
+ function discoverDaemon(contextId) {
1996
+ log("discovering daemon for context: " + contextId, 0 /* DEBUG */);
1997
+ const pidPath = (0, import_node_path7.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.pid`);
1998
+ if (!(0, import_node_fs5.existsSync)(pidPath)) {
1999
+ log(
2000
+ "no daemon PID file found for context: " + contextId,
2001
+ 0 /* DEBUG */
2002
+ );
2003
+ return null;
2004
+ }
2005
+ const pidStr = (0, import_node_fs5.readFileSync)(pidPath, "utf-8").trim();
2006
+ const pid = parseInt(pidStr, 10);
2007
+ if (isNaN(pid) || !isProcessAlive(pid)) {
2008
+ log(
2009
+ "daemon process not alive for context: " + contextId,
2010
+ 0 /* DEBUG */
2011
+ );
2012
+ try {
2013
+ (0, import_node_fs5.unlinkSync)(pidPath);
2014
+ } catch {
2015
+ }
2016
+ return null;
2017
+ }
2018
+ log("daemon found: pid=" + pid.toString(), 0 /* DEBUG */);
2019
+ const socketPath = (0, import_node_path7.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.sock`);
2020
+ const crashPath = (0, import_node_path7.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.crash`);
2021
+ try {
2022
+ (0, import_node_fs5.unlinkSync)(crashPath);
2023
+ } catch {
2024
+ }
2025
+ return { pid, socketPath };
2026
+ }
2027
+
2028
+ // src/shared/worker-client/classes/worker-client.class.ts
1845
2029
  var WorkerClient = class {
1846
2030
  /**
1847
2031
  * @param socketPath - absolute path to the daemon's IPC socket
@@ -1877,11 +2061,13 @@ var WorkerClient = class {
1877
2061
  * @throws {Error} if the connection cannot be established
1878
2062
  */
1879
2063
  async connect() {
2064
+ log("connecting to " + this.socketPath, 0 /* DEBUG */);
1880
2065
  const maxRetries = 5;
1881
2066
  let delay = 50;
1882
2067
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1883
2068
  try {
1884
2069
  await this.tryConnect();
2070
+ log("connected", 0 /* DEBUG */);
1885
2071
  return;
1886
2072
  } catch (err) {
1887
2073
  const code = err.code;
@@ -1889,6 +2075,10 @@ var WorkerClient = class {
1889
2075
  if (!retriable || attempt === maxRetries) {
1890
2076
  throw err;
1891
2077
  }
2078
+ log(
2079
+ "connect retry: attempt=" + attempt.toString() + " code=" + code + " delay=" + delay.toString() + "ms",
2080
+ 0 /* DEBUG */
2081
+ );
1892
2082
  await new Promise((r) => setTimeout(r, delay));
1893
2083
  delay = Math.min(delay * 2, 1e3);
1894
2084
  }
@@ -1896,11 +2086,32 @@ var WorkerClient = class {
1896
2086
  }
1897
2087
  /** Destroys the IPC socket and clears the connection state. */
1898
2088
  disconnect() {
2089
+ log("disconnecting client", 0 /* DEBUG */);
1899
2090
  if (this.socket) {
1900
2091
  this.socket.destroy();
1901
2092
  this.socket = null;
1902
2093
  }
1903
2094
  }
2095
+ /**
2096
+ * Kills the daemon process and disconnects the client.
2097
+ *
2098
+ * Discovers the daemon via PID file and sends `SIGTERM`.
2099
+ * Always disconnects the socket regardless of kill outcome.
2100
+ */
2101
+ killDaemon() {
2102
+ const info = discoverDaemon(this.contextId);
2103
+ log(
2104
+ "killing daemon: pid=" + (info ? info.pid.toString() : "unknown"),
2105
+ 0 /* DEBUG */
2106
+ );
2107
+ if (info) {
2108
+ try {
2109
+ process.kill(info.pid, "SIGTERM");
2110
+ } catch {
2111
+ }
2112
+ }
2113
+ this.disconnect();
2114
+ }
1904
2115
  /**
1905
2116
  * Single connection attempt with keepalive and
1906
2117
  * post-connect failure handlers.
@@ -1911,9 +2122,14 @@ var WorkerClient = class {
1911
2122
  sock.removeListener("error", reject);
1912
2123
  sock.setKeepAlive(true, 3e4);
1913
2124
  sock.on("error", (err) => {
2125
+ log(
2126
+ "socket error: code=" + (err.code ?? err.message),
2127
+ 0 /* DEBUG */
2128
+ );
1914
2129
  this.handleSocketFailure(err);
1915
2130
  });
1916
2131
  sock.on("close", () => {
2132
+ log("socket closed", 0 /* DEBUG */);
1917
2133
  if (this.pending.size > 0) {
1918
2134
  this.handleSocketFailure(
1919
2135
  new Error("connection closed")
@@ -1935,6 +2151,10 @@ var WorkerClient = class {
1935
2151
  * disconnected.
1936
2152
  */
1937
2153
  handleSocketFailure(err) {
2154
+ log(
2155
+ "socket failure: pending=" + this.pending.size.toString() + " err=" + err.message,
2156
+ 0 /* DEBUG */
2157
+ );
1938
2158
  const sock = this.socket;
1939
2159
  this.socket = null;
1940
2160
  for (const [id, call] of this.pending) {
@@ -2235,6 +2455,10 @@ var WorkerClient = class {
2235
2455
  throw new Error("not connected");
2236
2456
  }
2237
2457
  const id = this.nextId++;
2458
+ log(
2459
+ "call: method=" + method + " id=" + id.toString(),
2460
+ 0 /* DEBUG */
2461
+ );
2238
2462
  const request = {
2239
2463
  jsonrpc: "2.0",
2240
2464
  id,
@@ -2248,6 +2472,10 @@ var WorkerClient = class {
2248
2472
  call.timer = setTimeout(() => {
2249
2473
  if (!this.pending.has(id)) return;
2250
2474
  this.pending.delete(id);
2475
+ log(
2476
+ "request timeout after " + String(timeoutMs) + "ms",
2477
+ 2 /* WARNING */
2478
+ );
2251
2479
  const err = new Error(
2252
2480
  `request timeout after ${String(timeoutMs)}ms`
2253
2481
  );
@@ -2278,14 +2506,31 @@ var WorkerClient = class {
2278
2506
  this.pending.delete(response.id);
2279
2507
  if (pending.timer) clearTimeout(pending.timer);
2280
2508
  if (response.error) {
2509
+ log(
2510
+ "response error: id=" + response.id.toString() + " code=" + response.error.code.toString(),
2511
+ 0 /* DEBUG */
2512
+ );
2281
2513
  const err = new Error(response.error.message);
2282
2514
  err.code = response.error.code;
2283
2515
  pending.reject(err);
2284
2516
  } else {
2517
+ log(
2518
+ "response ok: id=" + response.id.toString(),
2519
+ 0 /* DEBUG */
2520
+ );
2285
2521
  pending.resolve(response.result);
2286
2522
  }
2523
+ } else {
2524
+ log(
2525
+ "unmatched response id=" + response.id.toString(),
2526
+ 0 /* DEBUG */
2527
+ );
2287
2528
  }
2288
- } catch {
2529
+ } catch (parseErr) {
2530
+ log(
2531
+ "json parse error: " + parseErr.message,
2532
+ 0 /* DEBUG */
2533
+ );
2289
2534
  }
2290
2535
  }
2291
2536
  }
@@ -2297,13 +2542,15 @@ var import_node_path11 = require("node:path");
2297
2542
  var import_node_os4 = require("node:os");
2298
2543
 
2299
2544
  // src/shared/worker-client/functions/resolve-db-path.function.ts
2300
- var import_node_fs5 = require("node:fs");
2301
- var import_node_path7 = require("node:path");
2545
+ var import_node_fs6 = require("node:fs");
2546
+ var import_node_path8 = require("node:path");
2302
2547
  function resolveDbPath(targetDir) {
2303
- const base = targetDir ? (0, import_node_path7.resolve)(targetDir) : process.cwd();
2304
- const dbPath = (0, import_node_path7.join)(base, ".kbdb");
2305
- if (!(0, import_node_fs5.existsSync)(dbPath)) {
2306
- throw new Error(`database not found: ${dbPath}`);
2548
+ const base = targetDir ? (0, import_node_path8.resolve)(targetDir) : process.cwd();
2549
+ const dbPath = (0, import_node_path8.join)(base, ".kbdb");
2550
+ if (!(0, import_node_fs6.existsSync)(dbPath)) {
2551
+ const msg = `database not found: ${dbPath}`;
2552
+ log(msg, 3 /* ERROR */);
2553
+ throw new Error(msg);
2307
2554
  }
2308
2555
  return dbPath;
2309
2556
  }
@@ -2322,53 +2569,22 @@ async function computeContextId(absolutePath) {
2322
2569
  return hash.slice(0, 16);
2323
2570
  }
2324
2571
 
2325
- // src/shared/worker-client/functions/discover-daemon.function.ts
2326
- var import_node_fs6 = require("node:fs");
2327
- var import_node_path8 = require("node:path");
2328
- var import_node_os = require("node:os");
2329
-
2330
- // src/shared/platform/functions/is-process-alive.function.ts
2331
- function isProcessAlive(pid) {
2332
- try {
2333
- process.kill(pid, 0);
2334
- return true;
2335
- } catch {
2336
- return false;
2337
- }
2338
- }
2339
-
2340
- // src/shared/worker-client/functions/discover-daemon.function.ts
2341
- function discoverDaemon(contextId) {
2342
- const pidPath = (0, import_node_path8.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.pid`);
2343
- if (!(0, import_node_fs6.existsSync)(pidPath)) return null;
2344
- const pidStr = (0, import_node_fs6.readFileSync)(pidPath, "utf-8").trim();
2345
- const pid = parseInt(pidStr, 10);
2346
- if (isNaN(pid) || !isProcessAlive(pid)) {
2347
- try {
2348
- (0, import_node_fs6.unlinkSync)(pidPath);
2349
- } catch {
2350
- }
2351
- return null;
2352
- }
2353
- const socketPath = (0, import_node_path8.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.sock`);
2354
- const crashPath = (0, import_node_path8.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.crash`);
2355
- try {
2356
- (0, import_node_fs6.unlinkSync)(crashPath);
2357
- } catch {
2358
- }
2359
- return { pid, socketPath };
2360
- }
2361
-
2362
2572
  // src/shared/worker-client/functions/spawn-daemon.function.ts
2363
2573
  var import_node_child_process = require("node:child_process");
2364
2574
  function spawnDaemon(contextPath, runtime2, workerScript2) {
2365
2575
  if (!workerScript2) {
2366
- throw new Error(
2367
- "workerScript must be provided (resolve at entry point)"
2368
- );
2576
+ const msg = "workerScript must be provided (resolve at entry point)";
2577
+ log(msg, 3 /* ERROR */);
2578
+ throw new Error(msg);
2369
2579
  }
2370
2580
  const execPath = runtime2 === "deno" ? "deno" : process.execPath;
2371
- const args = runtime2 === "deno" ? ["run", "--allow-all", workerScript2, contextPath] : [workerScript2, contextPath];
2581
+ const logLevelEnv = process.env["KBDB_LOG_LEVEL"];
2582
+ const logArgs = logLevelEnv ? ["--log-level", logLevelEnv] : [];
2583
+ const args = runtime2 === "deno" ? ["run", "--allow-all", workerScript2, contextPath, ...logArgs] : [workerScript2, contextPath, ...logArgs];
2584
+ log(
2585
+ "spawning daemon: " + execPath + " " + args.join(" "),
2586
+ 0 /* DEBUG */
2587
+ );
2372
2588
  const child = (0, import_node_child_process.spawn)(execPath, args, {
2373
2589
  detached: true,
2374
2590
  stdio: "ignore"
@@ -2383,12 +2599,30 @@ var import_node_os2 = require("node:os");
2383
2599
  var DEFAULT_TIMEOUT_MS = 1e4;
2384
2600
  var POLL_INTERVAL_MS = 100;
2385
2601
  async function waitForDaemon(contextId, timeoutMs = DEFAULT_TIMEOUT_MS) {
2602
+ log("waiting for daemon: contextId=" + contextId, 0 /* DEBUG */);
2386
2603
  const pidPath = (0, import_node_path9.join)((0, import_node_os2.tmpdir)(), `kbdb-${contextId}.pid`);
2387
2604
  const start = Date.now();
2605
+ let iteration = 0;
2388
2606
  while (Date.now() - start < timeoutMs) {
2389
- if ((0, import_node_fs7.existsSync)(pidPath)) return true;
2607
+ if ((0, import_node_fs7.existsSync)(pidPath)) {
2608
+ log("daemon PID file appeared", 0 /* DEBUG */);
2609
+ return true;
2610
+ }
2611
+ iteration++;
2612
+ if (iteration % 10 === 0) {
2613
+ const elapsed2 = Date.now() - start;
2614
+ log(
2615
+ "still waiting for daemon: elapsed=" + elapsed2.toString() + "ms",
2616
+ 0 /* DEBUG */
2617
+ );
2618
+ }
2390
2619
  await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
2391
2620
  }
2621
+ const elapsed = Date.now() - start;
2622
+ log(
2623
+ "timed out waiting for daemon: elapsed=" + elapsed.toString() + "ms",
2624
+ 0 /* DEBUG */
2625
+ );
2392
2626
  return false;
2393
2627
  }
2394
2628
 
@@ -2413,19 +2647,28 @@ function getIpcPath(ctx) {
2413
2647
  async function createWorkerClient(options) {
2414
2648
  const dbPath = options?.contextPath ?? resolveDbPath(options?.dbPath);
2415
2649
  const contextId = await computeContextId(dbPath);
2650
+ log("create-worker-client: contextId=" + contextId, 0 /* DEBUG */);
2416
2651
  const socketPath = getIpcPath(contextId);
2417
2652
  let daemon = discoverDaemon(contextId);
2653
+ if (daemon) {
2654
+ log("daemon found: pid=" + daemon.pid.toString(), 0 /* DEBUG */);
2655
+ } else {
2656
+ log("no daemon found", 0 /* DEBUG */);
2657
+ }
2418
2658
  if (!daemon && options?.autoSpawn !== false) {
2419
2659
  const runtime2 = detectRuntime();
2660
+ log("auto-spawning daemon", 0 /* DEBUG */);
2420
2661
  spawnDaemon(dbPath, runtime2, options?.workerScript);
2662
+ log("waiting for daemon after spawn", 0 /* DEBUG */);
2421
2663
  await waitForDaemon(contextId, options?.connectTimeoutMs);
2422
2664
  daemon = discoverDaemon(contextId);
2423
2665
  }
2424
2666
  if (!daemon) {
2425
- throw new Error(
2426
- `kbdb worker daemon did not start: ${readCrashReason(contextId)}`
2427
- );
2667
+ const msg = `kbdb worker daemon did not start: ${readCrashReason(contextId)}`;
2668
+ log(msg, 3 /* ERROR */);
2669
+ throw new Error(msg);
2428
2670
  }
2671
+ log("connecting to daemon", 0 /* DEBUG */);
2429
2672
  const client = new WorkerClient(
2430
2673
  socketPath,
2431
2674
  contextId,
@@ -2451,27 +2694,58 @@ function readCrashReason(contextId) {
2451
2694
 
2452
2695
  // src/shared/cli/functions/run-worker-stop.function.ts
2453
2696
  async function runWorkerStop(dbDir) {
2697
+ log("running worker-stop", 0 /* DEBUG */);
2454
2698
  const contextId = await computeContextId(dbDir);
2455
2699
  const info = discoverDaemon(contextId);
2456
2700
  if (!info) {
2457
2701
  return { output: "no daemon running", exitCode: 0 };
2458
2702
  }
2703
+ log("pid found: " + info.pid.toString(), 0 /* DEBUG */);
2459
2704
  try {
2460
2705
  process.kill(info.pid, "SIGTERM");
2461
- return {
2462
- output: `stopped daemon (pid ${info.pid.toString()})`,
2463
- exitCode: 0
2464
- };
2706
+ log("sigterm sent to pid=" + info.pid.toString(), 0 /* DEBUG */);
2465
2707
  } catch {
2466
2708
  return {
2467
2709
  error: "error: failed to stop daemon",
2468
2710
  exitCode: 1
2469
2711
  };
2470
2712
  }
2713
+ const deadline = Date.now() + 5e3;
2714
+ let pollIteration = 0;
2715
+ while (Date.now() < deadline) {
2716
+ try {
2717
+ process.kill(info.pid, 0);
2718
+ } catch {
2719
+ log(
2720
+ "process exited: pid=" + info.pid.toString(),
2721
+ 0 /* DEBUG */
2722
+ );
2723
+ break;
2724
+ }
2725
+ pollIteration++;
2726
+ if (pollIteration % 5 === 0) {
2727
+ log(
2728
+ "waiting for exit: pid=" + info.pid.toString() + " poll=" + pollIteration.toString(),
2729
+ 0 /* DEBUG */
2730
+ );
2731
+ }
2732
+ await new Promise((r) => setTimeout(r, 100));
2733
+ }
2734
+ if (Date.now() >= deadline) {
2735
+ log(
2736
+ "timed out waiting for exit: pid=" + info.pid.toString(),
2737
+ 0 /* DEBUG */
2738
+ );
2739
+ }
2740
+ return {
2741
+ output: `stopped daemon (pid ${info.pid.toString()})`,
2742
+ exitCode: 0
2743
+ };
2471
2744
  }
2472
2745
 
2473
2746
  // src/shared/cli/functions/run-worker-restart.function.ts
2474
2747
  async function runWorkerRestart(dbDir) {
2748
+ log("running worker-restart", 0 /* DEBUG */);
2475
2749
  const stopResult = await runWorkerStop(dbDir);
2476
2750
  if (stopResult.exitCode !== 0) return stopResult;
2477
2751
  return {
@@ -2489,20 +2763,44 @@ function resolveRawDbPath(options) {
2489
2763
  async function retryOnTimeout(createClient, operation, maxRetries) {
2490
2764
  let lastError = new Error("retryOnTimeout exhausted");
2491
2765
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
2766
+ log(
2767
+ "retry-on-timeout: attempt=" + attempt.toString() + " max=" + maxRetries.toString(),
2768
+ 0 /* DEBUG */
2769
+ );
2492
2770
  const client = await createClient();
2493
2771
  try {
2494
2772
  const result = await operation(client);
2773
+ log(
2774
+ "retry-on-timeout: success on attempt=" + attempt.toString(),
2775
+ 0 /* DEBUG */
2776
+ );
2495
2777
  return { client, result };
2496
2778
  } catch (err) {
2497
2779
  const code = err.code;
2498
2780
  if (code !== "REQUEST_TIMEOUT" || attempt >= maxRetries) {
2781
+ log(
2782
+ "retry-on-timeout: non-retriable error code=" + String(code),
2783
+ 0 /* DEBUG */
2784
+ );
2499
2785
  client.disconnect();
2500
2786
  throw err;
2501
2787
  }
2502
2788
  lastError = err;
2503
- client.disconnect();
2789
+ if (client.killDaemon) {
2790
+ log(
2791
+ "retry " + String(attempt + 1) + "/" + String(maxRetries) + ": killing daemon",
2792
+ 2 /* WARNING */
2793
+ );
2794
+ client.killDaemon();
2795
+ } else {
2796
+ client.disconnect();
2797
+ }
2504
2798
  }
2505
2799
  }
2800
+ log(
2801
+ "retry-on-timeout: all retries exhausted max=" + maxRetries.toString(),
2802
+ 0 /* DEBUG */
2803
+ );
2506
2804
  throw lastError;
2507
2805
  }
2508
2806
 
@@ -2512,11 +2810,57 @@ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
2512
2810
  // src/shared/worker-client/constants/retry-defaults.constant.ts
2513
2811
  var DEFAULT_RETRY_COUNT = 5;
2514
2812
 
2813
+ // src/shared/log/functions/resolve-log-level.function.ts
2814
+ function resolveLogLevel(cliLevel) {
2815
+ if (cliLevel !== void 0) {
2816
+ return cliLevel;
2817
+ }
2818
+ const envValue = process.env["KBDB_LOG_LEVEL"];
2819
+ if (envValue !== void 0) {
2820
+ return parseLogLevel(envValue);
2821
+ }
2822
+ return DEFAULT_LOG_LEVEL;
2823
+ }
2824
+
2825
+ // src/shared/log/functions/configure-log.function.ts
2826
+ function configureLog(config) {
2827
+ setLogLevel(config.level);
2828
+ if (config.outputs === void 0) {
2829
+ return;
2830
+ }
2831
+ const levels = [
2832
+ 0 /* DEBUG */,
2833
+ 1 /* INFO */,
2834
+ 2 /* WARNING */,
2835
+ 3 /* ERROR */
2836
+ ];
2837
+ for (const level of levels) {
2838
+ const output = config.outputs[level];
2839
+ if (output !== void 0) {
2840
+ setLogOutput(level, output.write);
2841
+ }
2842
+ }
2843
+ }
2844
+
2515
2845
  // src/shared/cli/functions/run-cli.function.ts
2516
2846
  async function runCli(argv, deps2) {
2517
2847
  const options = parseArgs(argv);
2848
+ const logLevel = resolveLogLevel(options.logLevel);
2849
+ configureLog({ level: logLevel });
2850
+ log("command: " + options.command, 0 /* DEBUG */);
2851
+ if (options.command === "init") {
2852
+ log('--init is deprecated, use "kbdb db init"', 2 /* WARNING */);
2853
+ }
2854
+ if (options.command === "migrate") {
2855
+ log(
2856
+ '--migrate is deprecated, use "kbdb db migrate"',
2857
+ 2 /* WARNING */
2858
+ );
2859
+ }
2860
+ const nonInteractive = options.nonInteractive || process.env["KBDB_NON_INTERACTIVE"] === "1" || process.env["KBDB_NON_INTERACTIVE"] === "true";
2861
+ const effectiveDeps = nonInteractive ? { ...deps2, isStdinTty: () => false } : deps2;
2518
2862
  if (!options.formatExplicit) {
2519
- options.format = deps2.isStdoutTty() ? "text" : "json";
2863
+ options.format = effectiveDeps.isStdoutTty() ? "text" : "json";
2520
2864
  }
2521
2865
  if (options.command === "help" || !options.command) {
2522
2866
  const helpCommand = options.args[0];
@@ -2531,21 +2875,29 @@ async function runCli(argv, deps2) {
2531
2875
  return { output: VERSION, exitCode: 0 };
2532
2876
  }
2533
2877
  if (options.command === "init" || options.command === "db-init") {
2534
- return handleInit(options, deps2);
2878
+ return handleInit(options, effectiveDeps);
2535
2879
  }
2536
2880
  if (options.command === "mcp") {
2537
- return handleMcp(options, deps2);
2881
+ return handleMcp(options, effectiveDeps);
2538
2882
  }
2539
2883
  if (options.command === "migrate" || options.command === "db-migrate") {
2540
- return handleMigrate(options, deps2);
2884
+ return handleMigrate(options, effectiveDeps);
2541
2885
  }
2542
2886
  if (options.command === "worker-stop") {
2543
- return handleWorkerLifecycle(options, deps2, runWorkerStop);
2887
+ return handleWorkerLifecycle(
2888
+ options,
2889
+ effectiveDeps,
2890
+ runWorkerStop
2891
+ );
2544
2892
  }
2545
2893
  if (options.command === "worker-restart") {
2546
- return handleWorkerLifecycle(options, deps2, runWorkerRestart);
2894
+ return handleWorkerLifecycle(
2895
+ options,
2896
+ effectiveDeps,
2897
+ runWorkerRestart
2898
+ );
2547
2899
  }
2548
- return handleDataCommand(options, deps2);
2900
+ return handleDataCommand(options, effectiveDeps);
2549
2901
  }
2550
2902
  function handleInit(options, deps2) {
2551
2903
  const result = deps2.runInit(options);
@@ -2686,6 +3038,7 @@ async function handleDataCommand(options, deps2) {
2686
3038
  }
2687
3039
  dbDir = initResult.targetPath;
2688
3040
  }
3041
+ log("db path: " + dbDir, 0 /* DEBUG */);
2689
3042
  const timeoutMs = resolveTimeoutMs(options);
2690
3043
  const maxRetries = resolveRetryCount(options);
2691
3044
  try {
@@ -3458,6 +3811,7 @@ function asStringArray2(value) {
3458
3811
  return [];
3459
3812
  }
3460
3813
  async function handleToolCall(client, name, args) {
3814
+ log("tool call: " + name, 0 /* DEBUG */);
3461
3815
  try {
3462
3816
  switch (name) {
3463
3817
  case "search":
@@ -3501,6 +3855,7 @@ async function handleToolCall(client, name, args) {
3501
3855
  case "auto-capture-review":
3502
3856
  return handleAutoCaptureReview();
3503
3857
  default:
3858
+ log("unknown tool: " + name, 2 /* WARNING */);
3504
3859
  return {
3505
3860
  content: [
3506
3861
  {
@@ -3512,6 +3867,10 @@ async function handleToolCall(client, name, args) {
3512
3867
  };
3513
3868
  }
3514
3869
  } catch (err) {
3870
+ log(
3871
+ "tool call failed: " + name + ": " + (err instanceof Error ? err.message : String(err)),
3872
+ 3 /* ERROR */
3873
+ );
3515
3874
  return {
3516
3875
  content: [
3517
3876
  {
@@ -3886,6 +4245,7 @@ async function handleResourceRead(client, uri) {
3886
4245
  ]
3887
4246
  };
3888
4247
  }
4248
+ log(`Unknown resource URI: ${uri}`, 3 /* ERROR */);
3889
4249
  throw new Error(`Unknown resource URI: ${uri}`);
3890
4250
  }
3891
4251
 
@@ -3962,6 +4322,7 @@ async function handleAgentPrompt(name, client) {
3962
4322
  const agents = await client.listDocumentsByType("agent");
3963
4323
  const doc = agents.find((a) => a.title === agentName);
3964
4324
  if (!doc) {
4325
+ log("agent not found: " + agentName, 3 /* ERROR */);
3965
4326
  throw new Error("agent not found: " + agentName);
3966
4327
  }
3967
4328
  const sections = doc.sections;
@@ -4006,6 +4367,7 @@ async function handleSkillPrompt(name, promptArgs, client) {
4006
4367
  }
4007
4368
  }
4008
4369
  if (matchContent === void 0) {
4370
+ log(`Prompt not found: ${name}`, 3 /* ERROR */);
4009
4371
  throw new Error(`Prompt not found: ${name}`);
4010
4372
  }
4011
4373
  const parsed = JSON.parse(matchContent);
@@ -4119,6 +4481,7 @@ function isSamplingResponse(v) {
4119
4481
  async function runAutoCapture(controller, config, client, hostCapabilities, requestSampling) {
4120
4482
  try {
4121
4483
  const trigger = controller.evaluate();
4484
+ log("auto-capture trigger evaluated", 0 /* DEBUG */);
4122
4485
  if (!trigger.shouldCapture) return;
4123
4486
  if (!hasSamplingCapability(hostCapabilities)) return;
4124
4487
  const prompt = buildCapturePrompt("recent conversation context");
@@ -4130,17 +4493,20 @@ async function runAutoCapture(controller, config, client, hostCapabilities, requ
4130
4493
  const text = raw.content.text.trim();
4131
4494
  if (!text) return;
4132
4495
  if (config.dryRun) return;
4496
+ log("auto-capture storing knowledge", 0 /* DEBUG */);
4133
4497
  await client.addSection({
4134
4498
  sectionType: "text/markdown",
4135
4499
  content: text,
4136
4500
  title: "Auto-captured knowledge"
4137
4501
  });
4138
4502
  } catch {
4503
+ log("auto-capture error (non-fatal)", 0 /* DEBUG */);
4139
4504
  }
4140
4505
  }
4141
4506
 
4142
4507
  // src/shared/auto-capture/functions/evaluate-trigger.function.ts
4143
4508
  function evaluateTrigger(config, state) {
4509
+ log("evaluating auto-capture trigger conditions", 0 /* DEBUG */);
4144
4510
  if (!config.enabled) {
4145
4511
  return {
4146
4512
  shouldCapture: false,
@@ -4192,6 +4558,7 @@ var AutoCaptureController = class {
4192
4558
  * @returns the trigger decision with a human-readable reason
4193
4559
  */
4194
4560
  evaluate() {
4561
+ log("evaluating auto-capture trigger", 0 /* DEBUG */);
4195
4562
  const trigger = evaluateTrigger(this.config, this.state());
4196
4563
  if (trigger.shouldCapture) {
4197
4564
  this.totalCapturesThisSession += 1;
@@ -4202,6 +4569,7 @@ var AutoCaptureController = class {
4202
4569
  }
4203
4570
  /** Reset all counters, e.g. on client disconnect. */
4204
4571
  reset() {
4572
+ log("resetting auto-capture controller", 0 /* DEBUG */);
4205
4573
  this.toolCallsSinceLastCapture = 0;
4206
4574
  this.lastCaptureTimestamp = 0;
4207
4575
  this.totalCapturesThisSession = 0;
@@ -4252,10 +4620,12 @@ var McpServer = class {
4252
4620
  }
4253
4621
  async reconnectClient() {
4254
4622
  if (!this.clientFactory) {
4623
+ log("no client factory for reconnect", 3 /* ERROR */);
4255
4624
  throw new Error("no client factory for reconnect");
4256
4625
  }
4257
4626
  this.client.disconnect();
4258
4627
  this.client = await this.clientFactory();
4628
+ log("MCP client reconnected", 0 /* DEBUG */);
4259
4629
  }
4260
4630
  async withRetry(fn) {
4261
4631
  for (let attempt = 0; ; attempt++) {
@@ -4266,6 +4636,10 @@ var McpServer = class {
4266
4636
  if (code !== "REQUEST_TIMEOUT" || attempt >= this.maxRetries || !this.clientFactory) {
4267
4637
  throw err;
4268
4638
  }
4639
+ log(
4640
+ "request timeout, reconnecting (attempt " + (attempt + 1).toString() + "/" + this.maxRetries.toString() + ")",
4641
+ 2 /* WARNING */
4642
+ );
4269
4643
  await this.reconnectClient();
4270
4644
  }
4271
4645
  }
@@ -4275,6 +4649,7 @@ var McpServer = class {
4275
4649
  input: process.stdin,
4276
4650
  terminal: false
4277
4651
  });
4652
+ log("MCP server listening on stdin", 0 /* DEBUG */);
4278
4653
  let pending = Promise.resolve();
4279
4654
  await new Promise((resolve4) => {
4280
4655
  rl.on("line", (line) => {
@@ -4285,6 +4660,7 @@ var McpServer = class {
4285
4660
  this.autoCaptureController?.reset();
4286
4661
  this.autoCaptureController = null;
4287
4662
  this.client.disconnect();
4663
+ log("MCP stdin closed", 0 /* DEBUG */);
4288
4664
  resolve4();
4289
4665
  });
4290
4666
  });
@@ -4348,6 +4724,7 @@ var McpServer = class {
4348
4724
  */
4349
4725
  async requestSampling(messages, maxTokens) {
4350
4726
  if (!this.hostCapabilities?.["sampling"]) {
4727
+ log("Host does not support sampling", 3 /* ERROR */);
4351
4728
  throw new Error("Host does not support sampling");
4352
4729
  }
4353
4730
  return this.sendRequest("sampling/createMessage", {
@@ -4394,10 +4771,12 @@ var McpServer = class {
4394
4771
  return null;
4395
4772
  }
4396
4773
  const request = parsed;
4774
+ log("MCP request: " + request.method, 0 /* DEBUG */);
4397
4775
  if (request.id === void 0) {
4398
4776
  if (request.method === "notifications/initialized" || request.method === "notifications/cancelled") {
4399
4777
  if (request.method === "notifications/initialized" && !this.initialized) {
4400
4778
  this.initialized = true;
4779
+ log("MCP initialized", 1 /* INFO */);
4401
4780
  if (this.autoCaptureConfig !== null) {
4402
4781
  this.autoCaptureController = new AutoCaptureController(this.autoCaptureConfig);
4403
4782
  }
@@ -4634,6 +5013,7 @@ var McpServer = class {
4634
5013
 
4635
5014
  // src/shared/mcp/functions/create-mcp-server.function.ts
4636
5015
  function createMcpServer(client, contextPath, autoCaptureConfig, clientFactory, maxRetries) {
5016
+ log("creating MCP server", 0 /* DEBUG */);
4637
5017
  return new McpServer(
4638
5018
  client,
4639
5019
  contextPath,
@@ -4775,6 +5155,7 @@ var deps = {
4775
5155
  findDb,
4776
5156
  runInit,
4777
5157
  startMcpServer: async (contextPath, clientFactory, maxRetries) => {
5158
+ log("starting MCP server", 1 /* INFO */);
4778
5159
  const client = await createWorkerClient({
4779
5160
  contextPath,
4780
5161
  workerScript
@@ -4795,7 +5176,9 @@ var deps = {
4795
5176
  clientFactory,
4796
5177
  maxRetries
4797
5178
  );
5179
+ log("MCP server listening on stdio", 0 /* DEBUG */);
4798
5180
  await server.listen();
5181
+ log("MCP server closed", 1 /* INFO */);
4799
5182
  } finally {
4800
5183
  client.disconnect();
4801
5184
  }
@@ -4807,7 +5190,7 @@ async function main() {
4807
5190
  console.log(result.output);
4808
5191
  }
4809
5192
  if (result.error) {
4810
- console.error(result.error);
5193
+ log(result.error, 3 /* ERROR */);
4811
5194
  }
4812
5195
  if (result.exitCode !== 0) {
4813
5196
  process.exitCode = result.exitCode;
@@ -4815,7 +5198,7 @@ async function main() {
4815
5198
  }
4816
5199
  main().catch((err) => {
4817
5200
  const msg = err instanceof Error ? err.message : String(err);
4818
- console.error(`error: ${msg}`);
5201
+ log("error: " + msg, 3 /* ERROR */);
4819
5202
  process.exitCode = 1;
4820
5203
  });
4821
5204
  //# sourceMappingURL=cli.cjs.map