claude-memory-layer 1.0.31 → 1.0.33

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 (343) hide show
  1. package/README.md +9 -2
  2. package/dist/cli/index.js +1110 -72
  3. package/dist/cli/index.js.map +4 -4
  4. package/dist/core/index.js +414 -25
  5. package/dist/core/index.js.map +2 -2
  6. package/dist/hooks/post-tool-use.js +416 -27
  7. package/dist/hooks/post-tool-use.js.map +2 -2
  8. package/dist/hooks/semantic-daemon.js +416 -27
  9. package/dist/hooks/semantic-daemon.js.map +2 -2
  10. package/dist/hooks/session-end.js +416 -27
  11. package/dist/hooks/session-end.js.map +2 -2
  12. package/dist/hooks/session-start.js +416 -27
  13. package/dist/hooks/session-start.js.map +2 -2
  14. package/dist/hooks/stop.js +416 -27
  15. package/dist/hooks/stop.js.map +2 -2
  16. package/dist/hooks/user-prompt-submit.js +504 -34
  17. package/dist/hooks/user-prompt-submit.js.map +2 -2
  18. package/dist/index.js +416 -27
  19. package/dist/index.js.map +2 -2
  20. package/dist/mcp/index.js +407 -32
  21. package/dist/mcp/index.js.map +2 -2
  22. package/dist/server/api/index.js +850 -44
  23. package/dist/server/api/index.js.map +3 -3
  24. package/dist/server/index.js +1073 -64
  25. package/dist/server/index.js.map +3 -3
  26. package/dist/services/memory-service.js +416 -27
  27. package/dist/services/memory-service.js.map +2 -2
  28. package/dist/ui/assets/js/bootstrap.js +2 -0
  29. package/dist/ui/assets/js/overview.js +166 -3
  30. package/dist/ui/assets/js/state.js +3 -0
  31. package/dist/ui/index.html +20 -0
  32. package/dist/ui/style.css +193 -0
  33. package/package.json +15 -2
  34. package/scripts/postinstall-embedding-backend.cjs +16 -12
  35. package/AGENTS.md +0 -71
  36. package/CLAUDE.md +0 -30
  37. package/HANDOFF.md +0 -92
  38. package/Memo.txt +0 -558
  39. package/benchmarks/replay/anonymized-real-sessions.json +0 -48
  40. package/config/kpi-thresholds.json +0 -7
  41. package/context.md +0 -636
  42. package/docs/ARCHITECTURE_COMPARISON_AND_RECOMMENDATIONS.md +0 -627
  43. package/docs/HERMES_MEMORY_INGESTION_ANALYSIS.md +0 -440
  44. package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +0 -271
  45. package/docs/MEMORY_USEFULNESS_AUDIT.md +0 -371
  46. package/docs/MEMORY_USEFULNESS_AUDIT_RAW.json +0 -80
  47. package/docs/MEMSEARCH_PROJECT_STRUCTURE_ANALYSIS.md +0 -333
  48. package/docs/MEMU_ADOPTION.md +0 -40
  49. package/docs/OPERATIONS.md +0 -18
  50. package/docs/PRODUCT_VALIDATION_MATRIX.md +0 -82
  51. package/docs/PROJECT_STRUCTURE_ANALYSIS.md +0 -421
  52. package/docs/REFACTORING_MILESTONES_AND_ISSUES.md +0 -501
  53. package/docs/REFACTORING_PLAN_THIN_CORE.md +0 -414
  54. package/docs/REFERENCE_PROJECT_ANALYSES.md +0 -25
  55. package/docs/SUPERLOCALMEMORY_PROJECT_STRUCTURE_ANALYSIS.md +0 -452
  56. package/docs/TARGET_ARCHITECTURE_AND_FOLDER_STRUCTURE.md +0 -446
  57. package/docs/architecture/comparison-index.md +0 -47
  58. package/docs/reports/codex-real-data-validation-20260505T040447Z.md +0 -46
  59. package/plan.md +0 -1642
  60. package/scripts/build.ts +0 -159
  61. package/scripts/bump-patch-version.sh +0 -18
  62. package/scripts/delete-unknown-projects.js +0 -154
  63. package/scripts/fix-sync-gap.js +0 -32
  64. package/scripts/generate-session-qrels.ts +0 -126
  65. package/scripts/heartbeat-memory-orchestrator.sh +0 -28
  66. package/scripts/replay-retrieval-benchmark.ts +0 -69
  67. package/scripts/report-sync-gap.js +0 -26
  68. package/scripts/review-queue-auto-resolve.js +0 -21
  69. package/scripts/sync-gap-auto-heal.sh +0 -17
  70. package/spec.md +0 -624
  71. package/specs/20260207-dashboard-upgrade/context.md +0 -38
  72. package/specs/20260207-dashboard-upgrade/spec.md +0 -96
  73. package/specs/citations-system/context.md +0 -243
  74. package/specs/citations-system/plan.md +0 -495
  75. package/specs/citations-system/spec.md +0 -371
  76. package/specs/endless-mode/context.md +0 -305
  77. package/specs/endless-mode/plan.md +0 -620
  78. package/specs/endless-mode/spec.md +0 -455
  79. package/specs/entity-edge-model/context.md +0 -401
  80. package/specs/entity-edge-model/plan.md +0 -459
  81. package/specs/entity-edge-model/spec.md +0 -391
  82. package/specs/evidence-aligner-v2/context.md +0 -401
  83. package/specs/evidence-aligner-v2/plan.md +0 -303
  84. package/specs/evidence-aligner-v2/spec.md +0 -312
  85. package/specs/mcp-desktop-integration/context.md +0 -278
  86. package/specs/mcp-desktop-integration/plan.md +0 -550
  87. package/specs/mcp-desktop-integration/spec.md +0 -494
  88. package/specs/memory-utilization-improvements/context.md +0 -145
  89. package/specs/memory-utilization-improvements/plan.md +0 -361
  90. package/specs/memory-utilization-improvements/spec.md +0 -361
  91. package/specs/post-tool-use-hook/context.md +0 -319
  92. package/specs/post-tool-use-hook/plan.md +0 -469
  93. package/specs/post-tool-use-hook/spec.md +0 -364
  94. package/specs/private-tags/context.md +0 -288
  95. package/specs/private-tags/plan.md +0 -412
  96. package/specs/private-tags/spec.md +0 -345
  97. package/specs/progressive-disclosure/context.md +0 -346
  98. package/specs/progressive-disclosure/plan.md +0 -663
  99. package/specs/progressive-disclosure/spec.md +0 -415
  100. package/specs/selective-tool-observation/context.md +0 -100
  101. package/specs/selective-tool-observation/plan.md +0 -158
  102. package/specs/selective-tool-observation/spec.md +0 -127
  103. package/specs/task-entity-system/context.md +0 -297
  104. package/specs/task-entity-system/plan.md +0 -301
  105. package/specs/task-entity-system/spec.md +0 -314
  106. package/specs/thin-core-refactor/context.md +0 -275
  107. package/specs/thin-core-refactor/plan.md +0 -536
  108. package/specs/thin-core-refactor/spec.md +0 -465
  109. package/specs/vector-outbox-v2/context.md +0 -470
  110. package/specs/vector-outbox-v2/plan.md +0 -562
  111. package/specs/vector-outbox-v2/spec.md +0 -466
  112. package/specs/web-viewer-ui/context.md +0 -384
  113. package/specs/web-viewer-ui/plan.md +0 -797
  114. package/specs/web-viewer-ui/spec.md +0 -516
  115. package/src/adapters/claude/capture/index.ts +0 -3
  116. package/src/adapters/claude/context/index.ts +0 -3
  117. package/src/adapters/claude/hooks/index.ts +0 -21
  118. package/src/adapters/claude/hooks/post-tool-use.ts +0 -239
  119. package/src/adapters/claude/hooks/prompt-injection-policy.ts +0 -104
  120. package/src/adapters/claude/hooks/semantic-daemon-client.ts +0 -209
  121. package/src/adapters/claude/hooks/semantic-daemon.ts +0 -283
  122. package/src/adapters/claude/hooks/session-end.ts +0 -59
  123. package/src/adapters/claude/hooks/session-start.ts +0 -73
  124. package/src/adapters/claude/hooks/stop.ts +0 -128
  125. package/src/adapters/claude/hooks/user-prompt-submit.ts +0 -361
  126. package/src/adapters/claude/index.ts +0 -4
  127. package/src/adapters/claude/transcript/index.ts +0 -4
  128. package/src/adapters/claude/transcript/transcript-reader.ts +0 -57
  129. package/src/adapters/claude/transcript/turn-reconstructor.ts +0 -65
  130. package/src/apps/cli/claude-settings-hooks.ts +0 -138
  131. package/src/apps/cli/codex-import-runner.ts +0 -125
  132. package/src/apps/cli/codex-validation-output.ts +0 -95
  133. package/src/apps/cli/hermes-import-runner.ts +0 -130
  134. package/src/apps/cli/hermes-validation-output.ts +0 -91
  135. package/src/apps/cli/index.ts +0 -1735
  136. package/src/apps/cli/mcp-install.ts +0 -106
  137. package/src/apps/cli/retrieval-disclosure-output.ts +0 -196
  138. package/src/apps/dashboard/assets/js/bootstrap.js +0 -244
  139. package/src/apps/dashboard/assets/js/chat.js +0 -373
  140. package/src/apps/dashboard/assets/js/disclosure.js +0 -232
  141. package/src/apps/dashboard/assets/js/modals.js +0 -298
  142. package/src/apps/dashboard/assets/js/overview.js +0 -655
  143. package/src/apps/dashboard/assets/js/state.js +0 -72
  144. package/src/apps/dashboard/assets/js/views.js +0 -468
  145. package/src/apps/dashboard/index.html +0 -543
  146. package/src/apps/dashboard/index.ts +0 -3
  147. package/src/apps/dashboard/style.css +0 -1750
  148. package/src/apps/index.ts +0 -5
  149. package/src/apps/server/api/chat.ts +0 -244
  150. package/src/apps/server/api/citations.ts +0 -105
  151. package/src/apps/server/api/events.ts +0 -137
  152. package/src/apps/server/api/health.ts +0 -53
  153. package/src/apps/server/api/index.ts +0 -26
  154. package/src/apps/server/api/projects.ts +0 -74
  155. package/src/apps/server/api/search.ts +0 -184
  156. package/src/apps/server/api/sessions.ts +0 -115
  157. package/src/apps/server/api/stats.ts +0 -723
  158. package/src/apps/server/api/turns.ts +0 -143
  159. package/src/apps/server/api/utils.ts +0 -65
  160. package/src/apps/server/index.ts +0 -111
  161. package/src/cli/index.ts +0 -3
  162. package/src/cli/retrieval-disclosure-output.ts +0 -2
  163. package/src/compat/index.ts +0 -5
  164. package/src/core/canonical-key.ts +0 -186
  165. package/src/core/citation-generator.ts +0 -63
  166. package/src/core/consolidated-store.ts +0 -356
  167. package/src/core/consolidation-worker.ts +0 -493
  168. package/src/core/context-formatter.ts +0 -276
  169. package/src/core/continuity-manager.ts +0 -341
  170. package/src/core/db-wrapper.ts +0 -64
  171. package/src/core/derive/fact-deriver.ts +0 -170
  172. package/src/core/derive/index.ts +0 -2
  173. package/src/core/derive/summary-deriver.ts +0 -76
  174. package/src/core/edge-repo.ts +0 -333
  175. package/src/core/embedder.ts +0 -4
  176. package/src/core/engine/embedding-maintenance-service.ts +0 -187
  177. package/src/core/engine/endless-memory-services.ts +0 -4
  178. package/src/core/engine/index.ts +0 -19
  179. package/src/core/engine/memory-engine-services.ts +0 -170
  180. package/src/core/engine/memory-ingest-service.ts +0 -317
  181. package/src/core/engine/memory-query-service.ts +0 -173
  182. package/src/core/engine/memory-runtime-service.ts +0 -162
  183. package/src/core/engine/memory-service-composition.ts +0 -231
  184. package/src/core/engine/retrieval-analytics-service.ts +0 -181
  185. package/src/core/engine/retrieval-disclosure-service.ts +0 -420
  186. package/src/core/engine/retrieval-orchestrator.ts +0 -377
  187. package/src/core/engine/retrieval-services.ts +0 -176
  188. package/src/core/engine/shared-memory-services.ts +0 -4
  189. package/src/core/entity-repo.ts +0 -349
  190. package/src/core/event-store.ts +0 -779
  191. package/src/core/evidence-aligner.ts +0 -635
  192. package/src/core/external-market-context.ts +0 -582
  193. package/src/core/graduation-worker.ts +0 -171
  194. package/src/core/graduation.ts +0 -377
  195. package/src/core/index.ts +0 -64
  196. package/src/core/ingest-interceptor.ts +0 -80
  197. package/src/core/markdown-mirror.ts +0 -70
  198. package/src/core/matcher.ts +0 -208
  199. package/src/core/md-mirror.ts +0 -92
  200. package/src/core/metadata-extractor.ts +0 -203
  201. package/src/core/model/memory-fact.ts +0 -30
  202. package/src/core/model/memory-rule.ts +0 -14
  203. package/src/core/model/memory-summary.ts +0 -21
  204. package/src/core/model/raw-event.ts +0 -28
  205. package/src/core/model/retrieval-result.ts +0 -35
  206. package/src/core/mongo-sync-config.ts +0 -165
  207. package/src/core/mongo-sync-worker.ts +0 -381
  208. package/src/core/privacy/filter.ts +0 -190
  209. package/src/core/privacy/index.ts +0 -20
  210. package/src/core/privacy/tag-parser.ts +0 -145
  211. package/src/core/product-validation-matrix.ts +0 -314
  212. package/src/core/progressive-retriever.ts +0 -414
  213. package/src/core/registry/project-path.ts +0 -54
  214. package/src/core/registry/session-registry.ts +0 -69
  215. package/src/core/replay-evaluator.ts +0 -625
  216. package/src/core/retrieval-benchmark.ts +0 -117
  217. package/src/core/retrieval-quality.ts +0 -109
  218. package/src/core/retriever.ts +0 -800
  219. package/src/core/session-qrels.ts +0 -360
  220. package/src/core/shared-event-store.ts +0 -114
  221. package/src/core/shared-promoter.ts +0 -249
  222. package/src/core/shared-store.ts +0 -289
  223. package/src/core/shared-vector-store.ts +0 -203
  224. package/src/core/sqlite-event-store.ts +0 -1846
  225. package/src/core/sqlite-wrapper.ts +0 -116
  226. package/src/core/sync-worker.ts +0 -228
  227. package/src/core/tag-taxonomy.ts +0 -51
  228. package/src/core/task/blocker-resolver.ts +0 -333
  229. package/src/core/task/index.ts +0 -9
  230. package/src/core/task/task-matcher.ts +0 -240
  231. package/src/core/task/task-projector.ts +0 -358
  232. package/src/core/task/task-resolver.ts +0 -421
  233. package/src/core/turn-state.ts +0 -207
  234. package/src/core/types.ts +0 -952
  235. package/src/core/vector-outbox.ts +0 -299
  236. package/src/core/vector-store.ts +0 -231
  237. package/src/core/vector-worker.ts +0 -521
  238. package/src/core/working-set-store.ts +0 -257
  239. package/src/extensions/endless-memory/endless-memory-services.ts +0 -350
  240. package/src/extensions/endless-memory/index.ts +0 -1
  241. package/src/extensions/index.ts +0 -5
  242. package/src/extensions/mcp/handlers.ts +0 -960
  243. package/src/extensions/mcp/index.ts +0 -48
  244. package/src/extensions/mcp/tools.ts +0 -252
  245. package/src/extensions/shared-memory/index.ts +0 -1
  246. package/src/extensions/shared-memory/shared-memory-services.ts +0 -211
  247. package/src/extensions/vector/embedder.ts +0 -234
  248. package/src/extensions/vector/index.ts +0 -1
  249. package/src/hooks/post-tool-use.ts +0 -9
  250. package/src/hooks/semantic-daemon-client.ts +0 -1
  251. package/src/hooks/semantic-daemon.ts +0 -11
  252. package/src/hooks/session-end.ts +0 -9
  253. package/src/hooks/session-start.ts +0 -9
  254. package/src/hooks/stop.ts +0 -9
  255. package/src/hooks/user-prompt-submit.ts +0 -9
  256. package/src/index.ts +0 -13
  257. package/src/mcp/handlers.ts +0 -2
  258. package/src/mcp/index.ts +0 -4
  259. package/src/mcp/tools.ts +0 -2
  260. package/src/server/api/chat.ts +0 -2
  261. package/src/server/api/citations.ts +0 -2
  262. package/src/server/api/events.ts +0 -2
  263. package/src/server/api/health.ts +0 -2
  264. package/src/server/api/index.ts +0 -2
  265. package/src/server/api/projects.ts +0 -2
  266. package/src/server/api/search.ts +0 -2
  267. package/src/server/api/sessions.ts +0 -2
  268. package/src/server/api/stats.ts +0 -2
  269. package/src/server/api/turns.ts +0 -2
  270. package/src/server/api/utils.ts +0 -2
  271. package/src/server/index.ts +0 -2
  272. package/src/services/bootstrap-organizer.ts +0 -463
  273. package/src/services/codex-session-history-importer.ts +0 -966
  274. package/src/services/hermes-session-history-importer.ts +0 -733
  275. package/src/services/memory-service-config.ts +0 -36
  276. package/src/services/memory-service-registry.ts +0 -150
  277. package/src/services/memory-service.ts +0 -688
  278. package/src/services/session-history-importer.ts +0 -629
  279. package/tests/README.md +0 -23
  280. package/tests/adapters/claude/claude-semantic-daemon-adapter.test.ts +0 -54
  281. package/tests/adapters/claude/claude-transcript-reconstructor.test.ts +0 -98
  282. package/tests/adapters/claude-hook-prompt-injection-policy.test.ts +0 -99
  283. package/tests/apps/app-layer-boundary.test.ts +0 -48
  284. package/tests/apps/claude-settings-hooks.test.ts +0 -107
  285. package/tests/apps/cli-disclosure-output.test.ts +0 -212
  286. package/tests/apps/codex-import-runner.test.ts +0 -99
  287. package/tests/apps/codex-validation-output.test.ts +0 -100
  288. package/tests/apps/hermes-import-runner.test.ts +0 -99
  289. package/tests/apps/mcp-install-command.test.ts +0 -59
  290. package/tests/apps/package-build-entrypoints.test.ts +0 -30
  291. package/tests/apps/postinstall-embedding-backend.test.ts +0 -185
  292. package/tests/apps/search-api-disclosure.test.ts +0 -162
  293. package/tests/apps/stats-api-lightweight.test.ts +0 -67
  294. package/tests/apps/ui-disclosure-output.test.ts +0 -140
  295. package/tests/core/bootstrap-organizer.test.ts +0 -111
  296. package/tests/core/canonical-key.test.ts +0 -101
  297. package/tests/core/codex-session-history-importer-validation.test.ts +0 -185
  298. package/tests/core/consolidation-worker.test.ts +0 -75
  299. package/tests/core/embedding-maintenance-service.test.ts +0 -282
  300. package/tests/core/evidence-aligner.test.ts +0 -152
  301. package/tests/core/external-market-context.test.ts +0 -209
  302. package/tests/core/fact-deriver.test.ts +0 -79
  303. package/tests/core/hermes-session-history-importer-validation.test.ts +0 -609
  304. package/tests/core/ingest-interceptor.test.ts +0 -38
  305. package/tests/core/markdown-mirror.test.ts +0 -85
  306. package/tests/core/matcher.test.ts +0 -112
  307. package/tests/core/md-mirror.test.ts +0 -50
  308. package/tests/core/memory-engine-services.test.ts +0 -240
  309. package/tests/core/memory-ingest-service.test.ts +0 -296
  310. package/tests/core/memory-query-service.test.ts +0 -129
  311. package/tests/core/memory-runtime-service.test.ts +0 -201
  312. package/tests/core/memory-service-composition.test.ts +0 -192
  313. package/tests/core/memory-service-config.test.ts +0 -41
  314. package/tests/core/memory-service-facade.test.ts +0 -30
  315. package/tests/core/memory-service-registry.test.ts +0 -206
  316. package/tests/core/product-validation-matrix.test.ts +0 -61
  317. package/tests/core/project-registry.test.ts +0 -78
  318. package/tests/core/replay-evaluator.test.ts +0 -181
  319. package/tests/core/retrieval-analytics-service.test.ts +0 -210
  320. package/tests/core/retrieval-benchmark.test.ts +0 -93
  321. package/tests/core/retrieval-disclosure-service.test.ts +0 -264
  322. package/tests/core/retrieval-orchestrator.test.ts +0 -403
  323. package/tests/core/retrieval-quality.test.ts +0 -31
  324. package/tests/core/retrieval-services.test.ts +0 -185
  325. package/tests/core/retriever-fallback-chain.test.ts +0 -223
  326. package/tests/core/retriever-strategy-scope.test.ts +0 -164
  327. package/tests/core/retriever.memu-adoption.test.ts +0 -122
  328. package/tests/core/session-history-importer-filter.test.ts +0 -78
  329. package/tests/core/session-qrels.test.ts +0 -250
  330. package/tests/core/sqlite-event-store-replication.test.ts +0 -127
  331. package/tests/core/summary-deriver.test.ts +0 -66
  332. package/tests/extensions/embedder-warning-suppression.test.ts +0 -84
  333. package/tests/extensions/endless-memory-extension-boundary.test.ts +0 -17
  334. package/tests/extensions/endless-memory-services.test.ts +0 -325
  335. package/tests/extensions/mcp-context-tools.test.ts +0 -905
  336. package/tests/extensions/mcp-extension-boundary.test.ts +0 -21
  337. package/tests/extensions/mcp-package-build.test.ts +0 -22
  338. package/tests/extensions/mcp-project-aware-tools.test.ts +0 -102
  339. package/tests/extensions/shared-memory-extension-boundary.test.ts +0 -24
  340. package/tests/extensions/shared-memory-services.test.ts +0 -309
  341. package/tests/extensions/vector-extension-boundary.test.ts +0 -21
  342. package/tsconfig.json +0 -24
  343. package/vitest.config.ts +0 -15
package/dist/cli/index.js CHANGED
@@ -2248,10 +2248,15 @@ function sqliteClose(db) {
2248
2248
  function toDateFromSQLite(value) {
2249
2249
  if (value instanceof Date)
2250
2250
  return value;
2251
- if (typeof value === "string")
2252
- return new Date(value);
2253
2251
  if (typeof value === "number")
2254
2252
  return new Date(value);
2253
+ if (typeof value === "string") {
2254
+ const trimmed = value.trim();
2255
+ if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(trimmed)) {
2256
+ return /* @__PURE__ */ new Date(trimmed.replace(" ", "T") + "Z");
2257
+ }
2258
+ return new Date(trimmed);
2259
+ }
2255
2260
  return new Date(String(value));
2256
2261
  }
2257
2262
  function toSQLiteTimestamp(date) {
@@ -2317,6 +2322,13 @@ var MarkdownMirror2 = class {
2317
2322
  };
2318
2323
 
2319
2324
  // src/core/sqlite-event-store.ts
2325
+ function normalizeQueryRewriteKind(value) {
2326
+ const normalized = (value || "").trim().toLowerCase();
2327
+ if (normalized === "follow-up-context" || normalized === "intent-rewrite")
2328
+ return normalized;
2329
+ return "none";
2330
+ }
2331
+ var REWRITTEN_QUERY_REWRITE_KIND_SQL = `LOWER(TRIM(COALESCE(query_rewrite_kind, 'none'))) IN ('follow-up-context', 'intent-rewrite')`;
2320
2332
  var SQLiteEventStore = class {
2321
2333
  db;
2322
2334
  initialized = false;
@@ -2577,6 +2589,8 @@ var SQLiteEventStore = class {
2577
2589
  session_id TEXT,
2578
2590
  project_hash TEXT,
2579
2591
  query_text TEXT NOT NULL,
2592
+ raw_query_text TEXT,
2593
+ query_rewrite_kind TEXT,
2580
2594
  strategy TEXT,
2581
2595
  candidate_event_ids TEXT,
2582
2596
  selected_event_ids TEXT,
@@ -2618,6 +2632,8 @@ var SQLiteEventStore = class {
2618
2632
  CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
2619
2633
  CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
2620
2634
  CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
2635
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_created_at ON memory_helpfulness(created_at);
2636
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_measured_at ON memory_helpfulness(measured_at);
2621
2637
  CREATE INDEX IF NOT EXISTS idx_retrieval_traces_created_at ON retrieval_traces(created_at DESC);
2622
2638
  CREATE INDEX IF NOT EXISTS idx_retrieval_traces_project_hash ON retrieval_traces(project_hash);
2623
2639
  CREATE INDEX IF NOT EXISTS idx_retrieval_traces_session_id ON retrieval_traces(session_id);
@@ -2651,6 +2667,18 @@ var SQLiteEventStore = class {
2651
2667
  sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN candidate_details_json TEXT;`);
2652
2668
  } catch {
2653
2669
  }
2670
+ try {
2671
+ sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN raw_query_text TEXT;`);
2672
+ } catch {
2673
+ }
2674
+ try {
2675
+ sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN query_rewrite_kind TEXT;`);
2676
+ } catch {
2677
+ }
2678
+ try {
2679
+ sqliteExec(this.db, `CREATE INDEX IF NOT EXISTS idx_retrieval_traces_query_rewrite_kind ON retrieval_traces(query_rewrite_kind);`);
2680
+ } catch {
2681
+ }
2654
2682
  const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
2655
2683
  const columnNames = tableInfo.map((col) => col.name);
2656
2684
  if (!columnNames.includes("access_count")) {
@@ -3436,8 +3464,11 @@ var SQLiteEventStore = class {
3436
3464
  /**
3437
3465
  * Get helpfulness statistics for dashboard
3438
3466
  */
3439
- async getHelpfulnessStats() {
3467
+ async getHelpfulnessStats(since) {
3440
3468
  await this.initialize();
3469
+ const sinceIso = since?.toISOString();
3470
+ const evaluatedWhere = sinceIso ? `WHERE measured_at IS NOT NULL AND datetime(created_at) >= datetime(?)` : `WHERE measured_at IS NOT NULL`;
3471
+ const totalWhere = sinceIso ? `WHERE datetime(created_at) >= datetime(?)` : ``;
3441
3472
  const stats = sqliteGet(
3442
3473
  this.db,
3443
3474
  `SELECT
@@ -3447,11 +3478,13 @@ var SQLiteEventStore = class {
3447
3478
  SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
3448
3479
  SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
3449
3480
  FROM memory_helpfulness
3450
- WHERE measured_at IS NOT NULL`
3481
+ ${evaluatedWhere}`,
3482
+ sinceIso ? [sinceIso] : []
3451
3483
  );
3452
3484
  const totalRow = sqliteGet(
3453
3485
  this.db,
3454
- `SELECT COUNT(*) as total FROM memory_helpfulness`
3486
+ `SELECT COUNT(*) as total FROM memory_helpfulness ${totalWhere}`,
3487
+ sinceIso ? [sinceIso] : []
3455
3488
  );
3456
3489
  return {
3457
3490
  avgScore: Math.round((stats?.avg_score || 0) * 100) / 100,
@@ -3550,18 +3583,21 @@ var SQLiteEventStore = class {
3550
3583
  async recordRetrievalTrace(input) {
3551
3584
  await this.initialize();
3552
3585
  const traceId = randomUUID5();
3586
+ const queryRewriteKind = normalizeQueryRewriteKind(input.queryRewriteKind);
3553
3587
  sqliteRun(
3554
3588
  this.db,
3555
3589
  `INSERT INTO retrieval_traces (
3556
- trace_id, session_id, project_hash, query_text, strategy,
3590
+ trace_id, session_id, project_hash, query_text, raw_query_text, query_rewrite_kind, strategy,
3557
3591
  candidate_event_ids, selected_event_ids, candidate_details_json, selected_details_json,
3558
3592
  candidate_count, selected_count, confidence, fallback_trace
3559
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3593
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3560
3594
  [
3561
3595
  traceId,
3562
3596
  input.sessionId || null,
3563
3597
  input.projectHash || null,
3564
3598
  input.queryText,
3599
+ input.rawQueryText || null,
3600
+ queryRewriteKind,
3565
3601
  input.strategy || null,
3566
3602
  JSON.stringify(input.candidateEventIds || []),
3567
3603
  JSON.stringify(input.selectedEventIds || []),
@@ -3587,6 +3623,8 @@ var SQLiteEventStore = class {
3587
3623
  sessionId: row.session_id || void 0,
3588
3624
  projectHash: row.project_hash || void 0,
3589
3625
  queryText: row.query_text,
3626
+ rawQueryText: row.raw_query_text || void 0,
3627
+ queryRewriteKind: normalizeQueryRewriteKind(row.query_rewrite_kind),
3590
3628
  strategy: row.strategy || void 0,
3591
3629
  candidateEventIds: row.candidate_event_ids ? JSON.parse(row.candidate_event_ids) : [],
3592
3630
  selectedEventIds: row.selected_event_ids ? JSON.parse(row.selected_event_ids) : [],
@@ -3613,6 +3651,11 @@ var SQLiteEventStore = class {
3613
3651
  COUNT(*) as total_queries,
3614
3652
  AVG(candidate_count) as avg_candidate_count,
3615
3653
  AVG(selected_count) as avg_selected_count,
3654
+ SUM(CASE WHEN ${REWRITTEN_QUERY_REWRITE_KIND_SQL} THEN 1 ELSE 0 END) as rewritten_queries,
3655
+ SUM(CASE WHEN ${REWRITTEN_QUERY_REWRITE_KIND_SQL} AND selected_count > 0 THEN 1 ELSE 0 END) as rewritten_queries_with_selection,
3656
+ SUM(CASE WHEN NOT (${REWRITTEN_QUERY_REWRITE_KIND_SQL}) AND selected_count > 0 THEN 1 ELSE 0 END) as raw_queries_with_selection,
3657
+ AVG(CASE WHEN ${REWRITTEN_QUERY_REWRITE_KIND_SQL} THEN selected_count END) as avg_selected_count_for_rewritten_queries,
3658
+ AVG(CASE WHEN NOT (${REWRITTEN_QUERY_REWRITE_KIND_SQL}) THEN selected_count END) as avg_selected_count_for_raw_queries,
3616
3659
  CASE
3617
3660
  WHEN SUM(candidate_count) > 0 THEN (SUM(selected_count) * 1.0 / SUM(candidate_count))
3618
3661
  ELSE 0
@@ -3620,15 +3663,41 @@ var SQLiteEventStore = class {
3620
3663
  FROM retrieval_traces`,
3621
3664
  []
3622
3665
  );
3666
+ const totalQueries = Number(row?.total_queries || 0);
3667
+ const rewrittenQueries = Number(row?.rewritten_queries || 0);
3668
+ const rawQueries = Math.max(0, totalQueries - rewrittenQueries);
3669
+ const rewrittenQueriesWithSelection = Number(row?.rewritten_queries_with_selection || 0);
3670
+ const rawQueriesWithSelection = Number(row?.raw_queries_with_selection || 0);
3623
3671
  return {
3624
- totalQueries: Number(row?.total_queries || 0),
3672
+ totalQueries,
3625
3673
  avgCandidateCount: Number(row?.avg_candidate_count || 0),
3626
3674
  avgSelectedCount: Number(row?.avg_selected_count || 0),
3627
- selectionRate: Number(row?.selection_rate || 0)
3675
+ selectionRate: Number(row?.selection_rate || 0),
3676
+ rewrittenQueries,
3677
+ rewriteRate: totalQueries > 0 ? rewrittenQueries / totalQueries : 0,
3678
+ rewrittenQueriesWithSelection,
3679
+ rawQueriesWithSelection,
3680
+ rewrittenSelectionRate: rewrittenQueries > 0 ? rewrittenQueriesWithSelection / rewrittenQueries : 0,
3681
+ rawSelectionRate: rawQueries > 0 ? rawQueriesWithSelection / rawQueries : 0,
3682
+ avgSelectedCountForRewrittenQueries: Number(row?.avg_selected_count_for_rewritten_queries || 0),
3683
+ avgSelectedCountForRawQueries: Number(row?.avg_selected_count_for_raw_queries || 0)
3628
3684
  };
3629
3685
  } catch (err) {
3630
3686
  if (err?.message?.includes("no such table")) {
3631
- return { totalQueries: 0, avgCandidateCount: 0, avgSelectedCount: 0, selectionRate: 0 };
3687
+ return {
3688
+ totalQueries: 0,
3689
+ avgCandidateCount: 0,
3690
+ avgSelectedCount: 0,
3691
+ selectionRate: 0,
3692
+ rewrittenQueries: 0,
3693
+ rewriteRate: 0,
3694
+ rewrittenQueriesWithSelection: 0,
3695
+ rawQueriesWithSelection: 0,
3696
+ rewrittenSelectionRate: 0,
3697
+ rawSelectionRate: 0,
3698
+ avgSelectedCountForRewrittenQueries: 0,
3699
+ avgSelectedCountForRawQueries: 0
3700
+ };
3632
3701
  }
3633
3702
  throw err;
3634
3703
  }
@@ -4440,6 +4509,57 @@ var COMMAND_ARTIFACT_PATTERNS = [
4440
4509
  /<local-command-stdout>[\s\S]*?<\/local-command-stdout>/i,
4441
4510
  /<local-command-stderr>[\s\S]*?<\/local-command-stderr>/i
4442
4511
  ];
4512
+ var CONTINUATION_QUERY_PATTERNS = [
4513
+ /^\s*(?:continue|resume|next|what(?:'s| is)? next|next\s+(?:step|task|action)|recommended\s+(?:next\s+)?(?:step|task|action)|what should (?:we|i) do next)\??\s*$/i,
4514
+ /^\s*(?:응\s*)?(?:이어서(?:\s*진행(?:해줘)?)?|계속(?:\s*해줘)?|다음\s*(?:단계|작업|추천\s*작업|추천|할\s*일)?(?:은|는)?(?:\s*(?:뭐야|진행(?:해줘)?))?\??|남은\s*(?:추가(?:로)?\s*)?(?:(?:할\s*만한\s*)?(?:작업|일)|할\s*일)?(?:은|는)?\s*(?:있어|있나|있나요|뭐야)\??|추천\s*작업(?:은|는)?(?:\s*뭐야)?\??|진행해줘)\s*$/i
4515
+ ];
4516
+ var SHORT_REPAIR_FOLLOW_UP_PATTERNS = [
4517
+ /^\s*(?:fix\s+(?:it|that)|repair\s+(?:it|that)|resolve\s+(?:it|that)|that\s+bug|same\s+issue)\s*$/i,
4518
+ /^\s*(?:그거|그것|이거|이것)?\s*(?:고쳐줘|수정해줘|해결해줘|처리해줘)\s*$/i
4519
+ ];
4520
+ var CURRENT_STATE_QUERY_PATTERNS = [
4521
+ /\bcurrent\b.*\b(?:state|status|deployment|blocker|pr|pull request)\b/i,
4522
+ /\b(?:still|as current|current)\b.*\b(?:unresolved|open|pending|not completed)\b/i,
4523
+ /\b(?:old|obsolete|stale|resolved|already resolved)\b.*\b(?:current|still|unresolved|open|state|status)\b/i,
4524
+ /(?:현재|아직|이전|오래된|해결된).*(?:상태|미해결|열린|블로커|PR|풀리퀘스트)/i
4525
+ ];
4526
+ var STALE_CONTENT_PATTERNS = [
4527
+ /\b(?:obsolete|superseded|outdated)\b/i,
4528
+ /\bstale\s+(?:operational\s+)?state\b/i,
4529
+ /\bstale\s+after\b/i,
4530
+ /\bno\s+longer\s+(?:valid|current|applies?)\b/i,
4531
+ /\bearlier\s+(?:pull request|pr)\b[\s\S]{0,160}\b(?:open|not completed|had not completed)\b/i,
4532
+ /\bshould\s+not\s+be\s+injected\s+as\s+current\s+context\b/i,
4533
+ /(?:오래된|더 이상 유효하지|현재 상태가 아님)/i
4534
+ ];
4535
+ var CONTINUATION_EXPANSION = "current next step plan roadmap status validation replay rerank memory usefulness continuation";
4536
+ var REPAIR_FOLLOW_UP_EXPANSION = "review blocker fix pattern dashboard error state metrics bucket validation sanitize rerun unresolved";
4537
+ var RETRIEVAL_PRIVACY_DECISION_EXPANSION = "retrieval telemetry privacy public api dashboard dashboards rawQueryText queryText raw query text expose safe trace metadata trace id reason strategy rewrite kind aggregate count counts candidate selected public panel";
4538
+ var DECISION_RECALL_TERMS = /* @__PURE__ */ new Set([
4539
+ "decide",
4540
+ "decided",
4541
+ "decision",
4542
+ "agreed",
4543
+ "policy",
4544
+ "constraint"
4545
+ ]);
4546
+ var RETRIEVAL_PRIVACY_SURFACE_TERMS = /* @__PURE__ */ new Set([
4547
+ "retrieval",
4548
+ "dashboard",
4549
+ "telemetry",
4550
+ "trace"
4551
+ ]);
4552
+ var DECISION_TOPIC_WEAK_TERMS = /* @__PURE__ */ new Set([
4553
+ "api",
4554
+ "dashboard",
4555
+ "retrieval",
4556
+ "trace",
4557
+ "telemetry",
4558
+ "query",
4559
+ "raw",
4560
+ "count",
4561
+ "counts"
4562
+ ]);
4443
4563
  var GENERIC_TECHNICAL_TERMS = /* @__PURE__ */ new Set([
4444
4564
  "api",
4445
4565
  "cli",
@@ -4457,6 +4577,87 @@ var GENERIC_TECHNICAL_TERMS = /* @__PURE__ */ new Set([
4457
4577
  "db",
4458
4578
  "sql"
4459
4579
  ]);
4580
+ var LOW_INFORMATION_QUERY_TERMS = /* @__PURE__ */ new Set([
4581
+ "the",
4582
+ "and",
4583
+ "or",
4584
+ "for",
4585
+ "from",
4586
+ "with",
4587
+ "without",
4588
+ "about",
4589
+ "what",
4590
+ "when",
4591
+ "where",
4592
+ "which",
4593
+ "who",
4594
+ "why",
4595
+ "how",
4596
+ "did",
4597
+ "does",
4598
+ "do",
4599
+ "we",
4600
+ "i",
4601
+ "in",
4602
+ "to",
4603
+ "of",
4604
+ "on",
4605
+ "as",
4606
+ "be",
4607
+ "was",
4608
+ "were",
4609
+ "decide",
4610
+ "decided",
4611
+ "decision",
4612
+ "agreed",
4613
+ "policy",
4614
+ "constraint",
4615
+ "showing",
4616
+ "can",
4617
+ "you",
4618
+ "me",
4619
+ "show",
4620
+ "tell",
4621
+ "please",
4622
+ "should",
4623
+ "would",
4624
+ "could",
4625
+ "this",
4626
+ "that",
4627
+ "these",
4628
+ "those",
4629
+ "use",
4630
+ "using",
4631
+ "treat",
4632
+ "continue",
4633
+ "resume",
4634
+ "next",
4635
+ "step",
4636
+ "task",
4637
+ "action",
4638
+ "current",
4639
+ "state",
4640
+ "status",
4641
+ "old",
4642
+ "already",
4643
+ "still",
4644
+ "near",
4645
+ "today",
4646
+ "\uC751",
4647
+ "\uADF8\uAC70",
4648
+ "\uADF8\uAC83",
4649
+ "\uC774\uAC70",
4650
+ "\uC774\uAC83",
4651
+ "\uB2E4\uC74C",
4652
+ "\uB2E8\uACC4",
4653
+ "\uC9C4\uD589",
4654
+ "\uC9C4\uD589\uD574\uC918",
4655
+ "\uACC4\uC18D",
4656
+ "\uC774\uC5B4\uC11C",
4657
+ "\uACE0\uCCD0\uC918",
4658
+ "\uC218\uC815\uD574\uC918",
4659
+ "\uD574\uACB0\uD574\uC918"
4660
+ ]);
4460
4661
  function isCommandArtifactQuery(query) {
4461
4662
  const trimmed = query.trim();
4462
4663
  if (!trimmed)
@@ -4468,6 +4669,73 @@ function isCommandArtifactQuery(query) {
4468
4669
  return true;
4469
4670
  return COMMAND_ARTIFACT_PATTERNS.some((pattern) => pattern.test(trimmed));
4470
4671
  }
4672
+ function isGenericContinuationQuery(query) {
4673
+ const trimmed = query.trim();
4674
+ if (!trimmed)
4675
+ return false;
4676
+ if (!CONTINUATION_QUERY_PATTERNS.some((pattern) => pattern.test(trimmed)))
4677
+ return false;
4678
+ if (extractTechnicalQueryTerms(trimmed).length > 0)
4679
+ return false;
4680
+ const tokens = trimmed.match(/[A-Za-z0-9가-힣#._/-]+/g) ?? [];
4681
+ if (tokens.length > 10)
4682
+ return false;
4683
+ return !/[A-Za-z0-9_-]+\.[A-Za-z0-9]+/.test(trimmed) && !/(?:^|\s)(?:feat|fix|chore|refactor|docs)\/[A-Za-z0-9._-]+/.test(trimmed) && !/[A-Za-z]:?[\\/]|\/Users\/|\.\/|\.\.\//.test(trimmed);
4684
+ }
4685
+ function isShortRepairFollowUpQuery(query) {
4686
+ const trimmed = query.trim();
4687
+ if (!trimmed)
4688
+ return false;
4689
+ if (extractTechnicalQueryTerms(trimmed).length > 0)
4690
+ return false;
4691
+ const tokens = trimmed.match(/[A-Za-z0-9가-힣#._/-]+/g) ?? [];
4692
+ if (tokens.length > 8)
4693
+ return false;
4694
+ return SHORT_REPAIR_FOLLOW_UP_PATTERNS.some((pattern) => pattern.test(trimmed));
4695
+ }
4696
+ function isCurrentStateQuery(query) {
4697
+ const trimmed = query.trim();
4698
+ if (!trimmed)
4699
+ return false;
4700
+ return CURRENT_STATE_QUERY_PATTERNS.some((pattern) => pattern.test(trimmed));
4701
+ }
4702
+ function isStaleOrSupersededContent(content) {
4703
+ const trimmed = content.trim();
4704
+ if (!trimmed)
4705
+ return false;
4706
+ return STALE_CONTENT_PATTERNS.some((pattern) => pattern.test(trimmed));
4707
+ }
4708
+ function buildRetrievalQualityQuery(query) {
4709
+ const trimmed = query.trim();
4710
+ if (!trimmed)
4711
+ return query;
4712
+ if (isRetrievalPrivacyDecisionQuery(trimmed)) {
4713
+ return `${trimmed} ${RETRIEVAL_PRIVACY_DECISION_EXPANSION}`;
4714
+ }
4715
+ if (isGenericContinuationQuery(trimmed)) {
4716
+ return `${trimmed} ${CONTINUATION_EXPANSION}`;
4717
+ }
4718
+ if (isShortRepairFollowUpQuery(trimmed)) {
4719
+ return `${trimmed} ${REPAIR_FOLLOW_UP_EXPANSION}`;
4720
+ }
4721
+ return query;
4722
+ }
4723
+ function isRetrievalPrivacyDecisionQuery(query) {
4724
+ const trimmed = query.trim();
4725
+ if (!trimmed)
4726
+ return false;
4727
+ const terms = new Set(tokenizeQualityText(trimmed));
4728
+ const hasDecisionSignal = hasAnyTerm(terms, DECISION_RECALL_TERMS) || /(?:결정|정책|원칙)/i.test(trimmed);
4729
+ if (!hasDecisionSignal)
4730
+ return false;
4731
+ const hasRawQuerySignal = terms.has("raw") && terms.has("query");
4732
+ const hasPrivacySignal = terms.has("privacy") || terms.has("expose") || terms.has("redacted");
4733
+ const hasRetrievalSurface = hasAnyTerm(terms, RETRIEVAL_PRIVACY_SURFACE_TERMS) || terms.has("api") && terms.has("query");
4734
+ const hasQuerySurface = terms.has("query") && (terms.has("dashboard") || terms.has("trace") || terms.has("telemetry") || terms.has("api"));
4735
+ const hasKoreanRetrievalSurface = /(?:검색|리트리벌|retrieval|대시보드|트레이스|텔레메트리|telemetry)/i.test(trimmed);
4736
+ const hasKoreanPrivacySurface = /(?:원문|쿼리|프라이버시|개인정보|노출|트레이스|메타데이터)/i.test(trimmed);
4737
+ return (hasRetrievalSurface || hasKoreanRetrievalSurface && hasKoreanPrivacySurface) && (hasRawQuerySignal || hasPrivacySignal || hasQuerySurface || hasKoreanPrivacySurface);
4738
+ }
4471
4739
  function extractTechnicalQueryTerms(query) {
4472
4740
  const matches = query.match(/[A-Za-z][A-Za-z0-9_.:-]{2,}/g) ?? [];
4473
4741
  const terms = matches.filter((term) => {
@@ -4485,9 +4753,87 @@ function hasTechnicalTermOverlap(query, content) {
4485
4753
  const normalizedContent = content.toLowerCase();
4486
4754
  return terms.some((term) => normalizedContent.includes(term));
4487
4755
  }
4756
+ function hasDiscriminativeTermOverlap(query, content) {
4757
+ const queryTerms = extractDiscriminativeQueryTerms(query);
4758
+ const contentTerms = new Set(tokenizeQualityText(content));
4759
+ if (isRetrievalPrivacyDecisionQuery(query) && hasRetrievalPrivacyDecisionContent(contentTerms)) {
4760
+ return true;
4761
+ }
4762
+ if (shouldRequireDecisionTopicOverlap(query)) {
4763
+ const topicTerms = queryTerms.filter((term) => !DECISION_TOPIC_WEAK_TERMS.has(term));
4764
+ if (topicTerms.length > 0) {
4765
+ return topicTerms.some((term) => contentTerms.has(term));
4766
+ }
4767
+ }
4768
+ if (queryTerms.length < 3)
4769
+ return true;
4770
+ const requiredHits = queryTerms.length >= 3 ? 2 : 1;
4771
+ let hits = 0;
4772
+ for (const term of queryTerms) {
4773
+ if (contentTerms.has(term))
4774
+ hits += 1;
4775
+ if (hits >= requiredHits)
4776
+ return true;
4777
+ }
4778
+ return false;
4779
+ }
4488
4780
  function shouldApplyTechnicalGuard(query) {
4489
4781
  return extractTechnicalQueryTerms(query).length > 0;
4490
4782
  }
4783
+ function hasAnyTerm(terms, expectedTerms) {
4784
+ let found = false;
4785
+ expectedTerms.forEach((term) => {
4786
+ if (terms.has(term))
4787
+ found = true;
4788
+ });
4789
+ return found;
4790
+ }
4791
+ function shouldRequireDecisionTopicOverlap(query) {
4792
+ if (isRetrievalPrivacyDecisionQuery(query))
4793
+ return false;
4794
+ const trimmed = query.trim();
4795
+ if (!trimmed)
4796
+ return false;
4797
+ const terms = new Set(tokenizeQualityText(trimmed));
4798
+ return hasAnyTerm(terms, DECISION_RECALL_TERMS) || /(?:결정|정책|원칙)/i.test(trimmed);
4799
+ }
4800
+ function extractDiscriminativeQueryTerms(query) {
4801
+ const seen = /* @__PURE__ */ new Set();
4802
+ const terms = [];
4803
+ for (const token of tokenizeQualityText(query)) {
4804
+ if (LOW_INFORMATION_QUERY_TERMS.has(token))
4805
+ continue;
4806
+ if (GENERIC_TECHNICAL_TERMS.has(token))
4807
+ continue;
4808
+ if (seen.has(token))
4809
+ continue;
4810
+ seen.add(token);
4811
+ terms.push(token);
4812
+ }
4813
+ return terms;
4814
+ }
4815
+ function hasRetrievalPrivacyDecisionContent(contentTerms) {
4816
+ const hasDashboardTraceMetadata = contentTerms.has("dashboard") && (contentTerms.has("trace") || contentTerms.has("metadata")) && (contentTerms.has("safe") || contentTerms.has("strategy") || contentTerms.has("rewrite") || contentTerms.has("candidate") || contentTerms.has("selected") || contentTerms.has("count") || contentTerms.has("reason"));
4817
+ const hasRawQueryPrivacyPolicy = contentTerms.has("retrieval") && (contentTerms.has("privacy") || contentTerms.has("expose") || contentTerms.has("raw") && contentTerms.has("query") && (contentTerms.has("dashboard") || contentTerms.has("telemetry") || contentTerms.has("api") || contentTerms.has("public")));
4818
+ return hasDashboardTraceMetadata || hasRawQueryPrivacyPolicy;
4819
+ }
4820
+ function tokenizeQualityText(text) {
4821
+ return text.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().replace(/[^A-Za-z0-9가-힣\s_.:-]/g, " ").split(/\s+/).flatMap((token) => token.split(/(?=[._:-])|(?<=[._:-])/g)).map((token) => normalizeQualityToken(token.replace(/^[._:-]+|[._:-]+$/g, ""))).filter((token) => token.length >= 2);
4822
+ }
4823
+ function normalizeQualityToken(token) {
4824
+ if (token === "apis")
4825
+ return "api";
4826
+ if (token === "ids")
4827
+ return "id";
4828
+ if (LOW_INFORMATION_QUERY_TERMS.has(token) || GENERIC_TECHNICAL_TERMS.has(token))
4829
+ return token;
4830
+ if (token.length > 4 && token.endsWith("ies"))
4831
+ return `${token.slice(0, -3)}y`;
4832
+ if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") && !token.endsWith("us") && !token.endsWith("is")) {
4833
+ return token.slice(0, -1);
4834
+ }
4835
+ return token;
4836
+ }
4491
4837
 
4492
4838
  // src/core/retriever.ts
4493
4839
  var DEFAULT_OPTIONS = {
@@ -4540,6 +4886,7 @@ var Retriever = class {
4540
4886
  const opts = { ...DEFAULT_OPTIONS, ...options };
4541
4887
  const sessionFilter = opts.scope?.sessionId ?? opts.sessionId;
4542
4888
  const fallbackTrace = [];
4889
+ const qualityQuery = buildRetrievalQualityQuery(query);
4543
4890
  if (isCommandArtifactQuery(query)) {
4544
4891
  fallbackTrace.push("guard:command-artifact-query");
4545
4892
  const emptyMatch = this.matcher.matchSearchResults([], () => 0);
@@ -4556,6 +4903,7 @@ var Retriever = class {
4556
4903
  const fallbackEnabled = (opts.strategy ?? "auto") === "auto";
4557
4904
  const primaryStrategy = opts.strategy === "auto" ? "fast" : opts.strategy || "fast";
4558
4905
  let current = await this.runStage(query, {
4906
+ qualityQuery,
4559
4907
  strategy: primaryStrategy,
4560
4908
  topK: opts.topK,
4561
4909
  minScore: opts.minScore,
@@ -4573,6 +4921,7 @@ var Retriever = class {
4573
4921
  fallbackTrace.push(`stage:primary:${primaryStrategy}`);
4574
4922
  if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results) && primaryStrategy !== "deep") {
4575
4923
  current = await this.runStage(query, {
4924
+ qualityQuery,
4576
4925
  strategy: "deep",
4577
4926
  topK: opts.topK,
4578
4927
  minScore: opts.minScore,
@@ -4590,6 +4939,7 @@ var Retriever = class {
4590
4939
  }
4591
4940
  if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results)) {
4592
4941
  current = await this.runStage(query, {
4942
+ qualityQuery,
4593
4943
  strategy: "deep",
4594
4944
  topK: opts.topK,
4595
4945
  minScore: Math.max(0.5, opts.minScore - 0.15),
@@ -4606,11 +4956,21 @@ var Retriever = class {
4606
4956
  fallbackTrace.push("fallback:scope-expanded");
4607
4957
  }
4608
4958
  if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results)) {
4609
- const summary = await this.buildSummaryFallback(query, opts.topK);
4959
+ const summary = await this.buildSummaryFallback(qualityQuery, opts.topK);
4960
+ const scopedSummary = await this.applyScopeFilters(summary, {
4961
+ scope: opts.scope,
4962
+ projectScopeMode: opts.projectScopeMode,
4963
+ projectHash: opts.projectHash,
4964
+ allowedProjectHashes: opts.allowedProjectHashes
4965
+ });
4966
+ const filteredSummary = this.applyQualityFilters(scopedSummary, {
4967
+ query,
4968
+ minScore: opts.minScore
4969
+ });
4610
4970
  current = {
4611
- results: summary,
4612
- candidateResults: summary,
4613
- matchResult: this.matcher.matchSearchResults(summary, () => 0)
4971
+ results: filteredSummary,
4972
+ candidateResults: filteredSummary,
4973
+ matchResult: this.matcher.matchSearchResults(filteredSummary, () => 0)
4614
4974
  };
4615
4975
  fallbackTrace.push("fallback:summary");
4616
4976
  }
@@ -4635,7 +4995,10 @@ var Retriever = class {
4635
4995
  semanticScore: r.semanticScore,
4636
4996
  lexicalScore: r.lexicalScore,
4637
4997
  recencyScore: r.recencyScore
4638
- }))
4998
+ })),
4999
+ rawQueryText: current.queryRewriteKind ? query : void 0,
5000
+ effectiveQueryText: current.effectiveQueryText,
5001
+ queryRewriteKind: current.queryRewriteKind
4639
5002
  };
4640
5003
  }
4641
5004
  async retrieveUnified(query, options = {}) {
@@ -4673,8 +5036,11 @@ var Retriever = class {
4673
5036
  }
4674
5037
  }
4675
5038
  async runStage(query, input) {
4676
- let rerankQuery = query;
4677
- let initialResults = await this.searchByStrategy(query, {
5039
+ const searchQuery = input.qualityQuery ?? query;
5040
+ let rerankQuery = searchQuery;
5041
+ let effectiveQueryText;
5042
+ let queryRewriteKind;
5043
+ let initialResults = await this.searchByStrategy(searchQuery, {
4678
5044
  strategy: input.strategy,
4679
5045
  topK: input.topK,
4680
5046
  minScore: input.minScore,
@@ -4682,9 +5048,12 @@ var Retriever = class {
4682
5048
  });
4683
5049
  if (input.intentRewrite && input.strategy === "deep" && this.queryRewriter) {
4684
5050
  const rewritten = (await this.queryRewriter(query))?.trim();
4685
- if (rewritten && rewritten !== query) {
4686
- rerankQuery = `${query} ${rewritten}`;
4687
- const rewrittenResults = await this.searchByStrategy(rewritten, {
5051
+ const normalizedQuery = query.trim();
5052
+ if (rewritten && rewritten !== normalizedQuery) {
5053
+ effectiveQueryText = `${normalizedQuery} ${rewritten}`.trim();
5054
+ queryRewriteKind = "intent-rewrite";
5055
+ rerankQuery = buildRetrievalQualityQuery(effectiveQueryText);
5056
+ const rewrittenResults = await this.searchByStrategy(buildRetrievalQualityQuery(rewritten), {
4688
5057
  strategy: "deep",
4689
5058
  topK: input.topK,
4690
5059
  minScore: Math.max(0.5, input.minScore - 0.1),
@@ -4711,10 +5080,14 @@ var Retriever = class {
4711
5080
  });
4712
5081
  const top = qualityFiltered.slice(0, input.topK);
4713
5082
  const matchResult = this.matcher.matchSearchResults(top, () => 0);
4714
- return { results: top, candidateResults: qualityFiltered, matchResult };
5083
+ return { results: top, candidateResults: qualityFiltered, matchResult, effectiveQueryText, queryRewriteKind };
4715
5084
  }
4716
5085
  applyQualityFilters(results, options) {
4717
5086
  let filtered = [...results];
5087
+ if (isCurrentStateQuery(options.query)) {
5088
+ filtered = filtered.filter((result) => !isStaleOrSupersededContent(result.content));
5089
+ }
5090
+ filtered = filtered.filter((result) => hasDiscriminativeTermOverlap(options.query, result.content));
4718
5091
  if (shouldApplyTechnicalGuard(options.query)) {
4719
5092
  filtered = filtered.filter((result) => hasTechnicalTermOverlap(options.query, result.content));
4720
5093
  }
@@ -5022,7 +5395,21 @@ _Context:_ ${sessionContext}`;
5022
5395
  });
5023
5396
  }
5024
5397
  tokenize(text) {
5025
- return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length >= 2).slice(0, 64);
5398
+ return text.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).map((token) => this.normalizeToken(token)).filter((t) => t.length >= 2).slice(0, 64);
5399
+ }
5400
+ normalizeToken(token) {
5401
+ if (token === "apis")
5402
+ return "api";
5403
+ if (token === "ids")
5404
+ return "id";
5405
+ if (token === "does")
5406
+ return token;
5407
+ if (token.length > 4 && token.endsWith("ies"))
5408
+ return `${token.slice(0, -3)}y`;
5409
+ if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") && !token.endsWith("us") && !token.endsWith("is") && !token.endsWith("ps")) {
5410
+ return token.slice(0, -1);
5411
+ }
5412
+ return token;
5026
5413
  }
5027
5414
  keywordOverlap(a, b) {
5028
5415
  if (a.length === 0 || b.length === 0)
@@ -5085,9 +5472,9 @@ var RetrievalAnalyticsService = class {
5085
5472
  await this.deps.initialize();
5086
5473
  return this.deps.retrievalStore.getHelpfulMemories(limit);
5087
5474
  }
5088
- async getHelpfulnessStats() {
5475
+ async getHelpfulnessStats(since) {
5089
5476
  await this.deps.initialize();
5090
- return this.deps.retrievalStore.getHelpfulnessStats();
5477
+ return this.deps.retrievalStore.getHelpfulnessStats(since);
5091
5478
  }
5092
5479
  /**
5093
5480
  * Extract topic keywords from event content (markdown headings and key terms).
@@ -5512,7 +5899,9 @@ var RetrievalOrchestrator = class {
5512
5899
  await this.deps.traceStore.recordRetrievalTrace({
5513
5900
  sessionId: options?.sessionId,
5514
5901
  projectHash: projectHash || void 0,
5515
- queryText: query,
5902
+ queryText: result.effectiveQueryText || query,
5903
+ rawQueryText: result.rawQueryText || (result.queryRewriteKind ? query : void 0),
5904
+ queryRewriteKind: result.queryRewriteKind || "none",
5516
5905
  strategy: options?.strategy || "auto",
5517
5906
  candidateEventIds,
5518
5907
  selectedEventIds,
@@ -7531,8 +7920,8 @@ var MemoryService = class {
7531
7920
  /**
7532
7921
  * Get helpfulness statistics for dashboard
7533
7922
  */
7534
- async getHelpfulnessStats() {
7535
- return this.retrievalAnalyticsService.getHelpfulnessStats();
7923
+ async getHelpfulnessStats(since) {
7924
+ return this.retrievalAnalyticsService.getHelpfulnessStats(since);
7536
7925
  }
7537
7926
  /**
7538
7927
  * Mark a consolidated memory as accessed
@@ -9914,11 +10303,13 @@ async function bootstrapKnowledgeBase(options) {
9914
10303
  // src/apps/server/index.ts
9915
10304
  import { Hono as Hono11 } from "hono";
9916
10305
  import { cors } from "hono/cors";
10306
+ import { getCookie, setCookie, deleteCookie } from "hono/cookie";
9917
10307
  import { logger } from "hono/logger";
9918
10308
  import { serve } from "@hono/node-server";
9919
10309
  import { serveStatic } from "@hono/node-server/serve-static";
9920
10310
  import * as path17 from "path";
9921
10311
  import * as fs15 from "fs";
10312
+ import { createHmac, timingSafeEqual } from "crypto";
9922
10313
  import { fileURLToPath as fileUrlToPath } from "url";
9923
10314
 
9924
10315
  // src/apps/server/api/index.ts
@@ -10360,6 +10751,346 @@ function computeSessionTurnCount(sessionEvents) {
10360
10751
  return turnIds.size;
10361
10752
  return sessionEvents.filter((e) => e.eventType === "user_prompt").length;
10362
10753
  }
10754
+ function normalizeQueryRewriteKind2(value) {
10755
+ const normalized = (value || "").trim().toLowerCase();
10756
+ if (normalized === "follow-up-context" || normalized === "intent-rewrite")
10757
+ return normalized;
10758
+ return "none";
10759
+ }
10760
+ function normalizeMetric(value) {
10761
+ const numberValue = Number(value || 0);
10762
+ if (!Number.isFinite(numberValue))
10763
+ return 0;
10764
+ return Math.max(0, Math.min(1, numberValue));
10765
+ }
10766
+ function getTimestampMs(value) {
10767
+ if (value instanceof Date)
10768
+ return value.getTime();
10769
+ if (typeof value === "string") {
10770
+ const parsed = new Date(value).getTime();
10771
+ return Number.isFinite(parsed) ? parsed : 0;
10772
+ }
10773
+ return 0;
10774
+ }
10775
+ function isRewrittenRetrievalTrace(trace) {
10776
+ return normalizeQueryRewriteKind2(trace.queryRewriteKind) !== "none";
10777
+ }
10778
+ function getTraceSelectedCount(trace) {
10779
+ return Number(trace.selectedCount ?? trace.selectedEventIds?.length ?? 0);
10780
+ }
10781
+ function getTraceCandidateCount(trace) {
10782
+ return Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? trace.candidateDetails?.length ?? 0);
10783
+ }
10784
+ function makeRetrievalReviewItem(trace) {
10785
+ const candidateCount = getTraceCandidateCount(trace);
10786
+ const selectedCount = getTraceSelectedCount(trace);
10787
+ const queryRewriteKind = normalizeQueryRewriteKind2(trace.queryRewriteKind);
10788
+ const rewritten = queryRewriteKind !== "none";
10789
+ const createdAtMs = getTimestampMs(trace.createdAt);
10790
+ const createdAt = createdAtMs > 0 ? new Date(createdAtMs).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
10791
+ let reason = null;
10792
+ let severity = "info";
10793
+ let priority = 0;
10794
+ let title = "";
10795
+ let detail = "";
10796
+ let action = "";
10797
+ if (candidateCount > 0 && selectedCount === 0 && rewritten) {
10798
+ reason = "rewritten-query-no-selection";
10799
+ severity = "warn";
10800
+ priority = 100;
10801
+ title = "Rewritten query selected no memories";
10802
+ detail = `${candidateCount} candidates were found after query rewrite, but no memory was selected.`;
10803
+ action = "Review rewrite wording, rerank scores, and final selection thresholds for this trace.";
10804
+ } else if (candidateCount > 0 && selectedCount === 0) {
10805
+ reason = "candidate-no-selection";
10806
+ severity = "warn";
10807
+ priority = 90;
10808
+ title = "Candidates found but nothing selected";
10809
+ detail = `${candidateCount} candidates were available, but the final selection injected no memory.`;
10810
+ action = "Review rerank thresholds and candidate filtering; consider overfetching before final selection.";
10811
+ } else if (candidateCount === 0) {
10812
+ reason = "empty-candidate-set";
10813
+ severity = "info";
10814
+ priority = 70;
10815
+ title = "Retrieval found no candidates";
10816
+ detail = "The retrieval pipeline returned no candidate memories for this trace.";
10817
+ action = "Check trigger/query rewrite coverage and whether the project has indexed memories for this topic.";
10818
+ } else if (candidateCount >= 10 && safeRatio(selectedCount, candidateCount) < 0.15) {
10819
+ reason = "low-selection-rate";
10820
+ severity = "info";
10821
+ priority = 60;
10822
+ title = "Low selection ratio from many candidates";
10823
+ detail = `${selectedCount} of ${candidateCount} candidates were selected.`;
10824
+ action = "Inspect score distribution and MMR/diversity settings before lowering thresholds.";
10825
+ }
10826
+ if (!reason)
10827
+ return null;
10828
+ return {
10829
+ traceId: trace.traceId || "unknown-trace",
10830
+ reason,
10831
+ severity,
10832
+ priority,
10833
+ title,
10834
+ detail,
10835
+ action,
10836
+ queryRewriteKind,
10837
+ rewritten,
10838
+ strategy: trace.strategy || null,
10839
+ candidateCount,
10840
+ selectedCount,
10841
+ candidateEventIds: (trace.candidateEventIds || []).slice(0, 5),
10842
+ selectedEventIds: (trace.selectedEventIds || []).slice(0, 5),
10843
+ candidateDetails: (trace.candidateDetails || []).slice(0, 3).map((detail2) => ({
10844
+ eventId: detail2.eventId,
10845
+ score: detail2.score,
10846
+ semanticScore: detail2.semanticScore,
10847
+ lexicalScore: detail2.lexicalScore,
10848
+ recencyScore: detail2.recencyScore
10849
+ })),
10850
+ selectedDetails: (trace.selectedDetails || []).slice(0, 3).map((detail2) => ({
10851
+ eventId: detail2.eventId,
10852
+ score: detail2.score,
10853
+ semanticScore: detail2.semanticScore,
10854
+ lexicalScore: detail2.lexicalScore,
10855
+ recencyScore: detail2.recencyScore
10856
+ })),
10857
+ createdAt
10858
+ };
10859
+ }
10860
+ function buildRetrievalReviewQueue(traces, limit) {
10861
+ const reviewItems = traces.map(makeRetrievalReviewItem).filter((item) => item !== null).sort((a, b) => b.priority - a.priority || new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
10862
+ return {
10863
+ summary: {
10864
+ totalTraces: traces.length,
10865
+ reviewItems: reviewItems.length,
10866
+ returnedItems: Math.min(reviewItems.length, limit),
10867
+ candidateNoSelection: reviewItems.filter((item) => item.reason === "candidate-no-selection").length,
10868
+ emptyCandidateSet: reviewItems.filter((item) => item.reason === "empty-candidate-set").length,
10869
+ rewrittenNoSelection: reviewItems.filter((item) => item.reason === "rewritten-query-no-selection").length,
10870
+ lowSelectionRate: reviewItems.filter((item) => item.reason === "low-selection-rate").length
10871
+ },
10872
+ items: reviewItems.slice(0, limit)
10873
+ };
10874
+ }
10875
+ function parseStatsLimit(value, fallback, max) {
10876
+ if (!value)
10877
+ return fallback;
10878
+ if (!/^\d+$/.test(value))
10879
+ return fallback;
10880
+ const parsed = Number(value);
10881
+ if (!Number.isFinite(parsed) || parsed <= 0)
10882
+ return fallback;
10883
+ return Math.min(parsed, max);
10884
+ }
10885
+ function usefulnessScoreLabel(score, confidence) {
10886
+ if (confidence <= 0)
10887
+ return "unknown";
10888
+ if (score >= 80)
10889
+ return "excellent";
10890
+ if (score >= 60)
10891
+ return "good";
10892
+ if (score >= 40)
10893
+ return "watch";
10894
+ return "low";
10895
+ }
10896
+ function buildMemoryUsefulnessDiagnostics(input) {
10897
+ const { metrics, counts } = input;
10898
+ const diagnostics = [];
10899
+ if (counts.promptCount > 0 && counts.retrievalQueries === 0) {
10900
+ diagnostics.push({
10901
+ key: "no-retrieval-traces",
10902
+ severity: "warn",
10903
+ metric: "retrievalUsageRate",
10904
+ value: 0,
10905
+ target: 0.5,
10906
+ title: "No retrieval traces were recorded",
10907
+ detail: `${counts.promptCount} prompts were seen, but none produced a retrieval trace in this window.`,
10908
+ action: "Confirm the prompt hook is enabled and broaden adherence triggers for continuation, write-intent, and project-specific prompts."
10909
+ });
10910
+ }
10911
+ if (counts.promptCount > 0 && metrics.memoryHitRate < 0.5) {
10912
+ diagnostics.push({
10913
+ key: "low-memory-hit-rate",
10914
+ severity: "warn",
10915
+ metric: "memoryHitRate",
10916
+ value: metrics.memoryHitRate,
10917
+ target: 0.5,
10918
+ title: "Memory checks are missing many prompts",
10919
+ detail: `Only ${counts.memoryCheckedPrompts} of ${counts.promptCount} prompts had an adherence check in this window.`,
10920
+ action: "Broaden adherence triggers for continuation, write-intent, topic-shift, and project-specific prompts."
10921
+ });
10922
+ }
10923
+ if (counts.retrievalQueries > 0 && metrics.queryYieldRate < 0.6) {
10924
+ diagnostics.push({
10925
+ key: "low-query-yield-rate",
10926
+ severity: "warn",
10927
+ metric: "queryYieldRate",
10928
+ value: metrics.queryYieldRate,
10929
+ target: 0.6,
10930
+ title: "Searches often select no memory",
10931
+ detail: `${counts.queriesWithSelected} of ${counts.retrievalQueries} retrieval queries injected at least one memory.`,
10932
+ action: "Overfetch candidates, then filter/rerank before applying the final injection threshold."
10933
+ });
10934
+ }
10935
+ if (counts.totalEvaluated > 0 && metrics.avgHelpfulnessScore < 0.7) {
10936
+ diagnostics.push({
10937
+ key: "low-helpfulness-score",
10938
+ severity: "warn",
10939
+ metric: "avgHelpfulnessScore",
10940
+ value: metrics.avgHelpfulnessScore,
10941
+ target: 0.7,
10942
+ title: "Injected memories are not translating into outcomes",
10943
+ detail: `${counts.totalEvaluated} evaluated retrievals averaged ${(metrics.avgHelpfulnessScore * 100).toFixed(1)}% helpfulness.`,
10944
+ action: "Review low-scoring retrieval samples for stale decisions, cross-project noise, or raw transcript snippets."
10945
+ });
10946
+ }
10947
+ if (counts.totalRetrievals > 0 && metrics.evaluationCoverage < 0.8) {
10948
+ diagnostics.push({
10949
+ key: "low-evaluation-coverage",
10950
+ severity: "info",
10951
+ metric: "evaluationCoverage",
10952
+ value: metrics.evaluationCoverage,
10953
+ target: 0.8,
10954
+ title: "Many retrievals are still unevaluated",
10955
+ detail: `${counts.totalEvaluated} of ${counts.totalRetrievals} retrievals have measured helpfulness.`,
10956
+ action: "Ensure Stop/session-end hooks or pending-session backfill are running so usefulness reflects real outcomes."
10957
+ });
10958
+ }
10959
+ if (counts.candidateMemories > 0 && counts.selectedMemories === 0) {
10960
+ diagnostics.push({
10961
+ key: "candidates-without-selection",
10962
+ severity: "warn",
10963
+ metric: "selectionRate",
10964
+ value: metrics.selectionRate,
10965
+ target: 0.2,
10966
+ title: "Candidates are found but none are injected",
10967
+ detail: `${counts.candidateMemories} candidates were retrieved, but no memories passed the injection policy.`,
10968
+ action: "Inspect threshold settings and prompt-injection policy before lowering filters globally."
10969
+ });
10970
+ }
10971
+ return diagnostics.slice(0, 3);
10972
+ }
10973
+ function computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, limits = {}) {
10974
+ const windowEvents = events.filter((event) => inWindow(event, now, window));
10975
+ const prompts = windowEvents.filter((event) => event.eventType === "user_prompt");
10976
+ const promptCount = prompts.length;
10977
+ const memoryCheckedPrompts = prompts.filter((prompt) => prompt.metadata?.adherence?.checked).length;
10978
+ const windowMs = windowToMs(window);
10979
+ const windowStart = now - windowMs;
10980
+ const windowTraces = traces.filter((trace) => {
10981
+ const ts = getTimestampMs(trace.createdAt);
10982
+ return ts > 0 && ts >= windowStart;
10983
+ });
10984
+ const oldestEventTimestamp = events.reduce((oldest, event) => {
10985
+ const timestamp = event.timestamp?.getTime?.() || 0;
10986
+ return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
10987
+ }, Number.POSITIVE_INFINITY);
10988
+ const oldestTraceTimestamp = traces.reduce((oldest, trace) => {
10989
+ const timestamp = getTimestampMs(trace.createdAt);
10990
+ return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
10991
+ }, Number.POSITIVE_INFINITY);
10992
+ const eventWindowTruncated = Boolean(
10993
+ limits.eventsLimit && events.length >= limits.eventsLimit && Number.isFinite(oldestEventTimestamp) && oldestEventTimestamp >= windowStart
10994
+ );
10995
+ const traceWindowTruncated = Boolean(
10996
+ limits.tracesLimit && traces.length >= limits.tracesLimit && Number.isFinite(oldestTraceTimestamp) && oldestTraceTimestamp >= windowStart
10997
+ );
10998
+ const retrievalQueries = windowTraces.length;
10999
+ const candidateCounts = windowTraces.map((trace) => Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? 0));
11000
+ const selectedCounts = windowTraces.map((trace) => getTraceSelectedCount(trace));
11001
+ const totalCandidateCount = candidateCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
11002
+ const totalSelectedCount = selectedCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
11003
+ const queriesWithSelected = selectedCounts.filter((count) => Number.isFinite(count) && count > 0).length;
11004
+ const rewrittenTraces = windowTraces.filter(isRewrittenRetrievalTrace);
11005
+ const rawTraces = windowTraces.filter((trace) => !isRewrittenRetrievalTrace(trace));
11006
+ const rewrittenQueries = rewrittenTraces.length;
11007
+ const rawQueries = rawTraces.length;
11008
+ const rewrittenSelectedCount = rewrittenTraces.reduce((sum, trace) => {
11009
+ const selectedCount = getTraceSelectedCount(trace);
11010
+ return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
11011
+ }, 0);
11012
+ const rawSelectedCount = rawTraces.reduce((sum, trace) => {
11013
+ const selectedCount = getTraceSelectedCount(trace);
11014
+ return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
11015
+ }, 0);
11016
+ const rewrittenQueriesWithSelected = rewrittenTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
11017
+ const rawQueriesWithSelected = rawTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
11018
+ const totalEvaluated = Number(helpfulness.totalEvaluated || 0);
11019
+ const totalRetrievals = Number(helpfulness.totalRetrievals || 0);
11020
+ const helpful = Number(helpfulness.helpful || 0);
11021
+ const neutral = Number(helpfulness.neutral || 0);
11022
+ const unhelpful = Number(helpfulness.unhelpful || 0);
11023
+ const retrievalsPerPrompt = safeRatio(retrievalQueries, promptCount);
11024
+ const metrics = {
11025
+ avgHelpfulnessScore: round(normalizeMetric(helpfulness.avgScore)),
11026
+ usefulRecallRate: round(safeRatio(helpful, totalEvaluated)),
11027
+ memoryHitRate: round(safeRatio(memoryCheckedPrompts, promptCount)),
11028
+ retrievalUsageRate: round(Math.min(1, retrievalsPerPrompt)),
11029
+ queryYieldRate: round(safeRatio(queriesWithSelected, retrievalQueries)),
11030
+ evaluationCoverage: round(safeRatio(totalEvaluated, totalRetrievals)),
11031
+ retrievalsPerPrompt: round(retrievalsPerPrompt),
11032
+ avgCandidatesPerQuery: round(safeRatio(totalCandidateCount, retrievalQueries), 2),
11033
+ avgSelectedPerQuery: round(safeRatio(totalSelectedCount, retrievalQueries), 2),
11034
+ selectionRate: round(safeRatio(totalSelectedCount, totalCandidateCount)),
11035
+ queryRewriteRate: round(safeRatio(rewrittenQueries, retrievalQueries)),
11036
+ rewrittenQueryYieldRate: round(safeRatio(rewrittenQueriesWithSelected, rewrittenQueries)),
11037
+ rawQueryYieldRate: round(safeRatio(rawQueriesWithSelected, rawQueries)),
11038
+ avgSelectedPerRewrittenQuery: round(safeRatio(rewrittenSelectedCount, rewrittenQueries), 2),
11039
+ avgSelectedPerRawQuery: round(safeRatio(rawSelectedCount, rawQueries), 2)
11040
+ };
11041
+ const counts = {
11042
+ promptCount,
11043
+ memoryCheckedPrompts,
11044
+ retrievalQueries,
11045
+ queriesWithSelected,
11046
+ rewrittenQueries,
11047
+ rawQueries,
11048
+ rewrittenQueriesWithSelected,
11049
+ rawQueriesWithSelected,
11050
+ selectedMemories: totalSelectedCount,
11051
+ candidateMemories: totalCandidateCount,
11052
+ totalEvaluated,
11053
+ totalRetrievals,
11054
+ helpful,
11055
+ neutral,
11056
+ unhelpful
11057
+ };
11058
+ const componentSpecs = [
11059
+ { key: "avgHelpfulnessScore", label: "Average helpfulness score", value: metrics.avgHelpfulnessScore, weight: 0.3, available: totalEvaluated > 0 },
11060
+ { key: "usefulRecallRate", label: "Useful recall rate", value: metrics.usefulRecallRate, weight: 0.25, available: totalEvaluated > 0 },
11061
+ { key: "memoryHitRate", label: "Memory hit rate", value: metrics.memoryHitRate, weight: 0.2, available: promptCount > 0 },
11062
+ { key: "retrievalUsageRate", label: "Retrieval usage rate", value: metrics.retrievalUsageRate, weight: 0.15, available: promptCount > 0 },
11063
+ { key: "queryYieldRate", label: "Query yield rate", value: metrics.queryYieldRate, weight: 0.1, available: retrievalQueries > 0 }
11064
+ ];
11065
+ const totalWeight = componentSpecs.reduce((sum, component) => sum + component.weight, 0);
11066
+ const availableWeight = componentSpecs.filter((component) => component.available).reduce((sum, component) => sum + component.weight, 0);
11067
+ const weightedScore = availableWeight > 0 ? componentSpecs.reduce((sum, component) => sum + (component.available ? component.value * component.weight : 0), 0) / availableWeight : 0;
11068
+ const scoreValue = round(weightedScore * 100, 1);
11069
+ const confidence = round(safeRatio(availableWeight, totalWeight), 2);
11070
+ const components = componentSpecs.map((component) => ({
11071
+ ...component,
11072
+ contribution: component.available ? round(component.value * component.weight * 100, 2) : 0
11073
+ }));
11074
+ return {
11075
+ window,
11076
+ score: {
11077
+ value: scoreValue,
11078
+ label: usefulnessScoreLabel(scoreValue, confidence),
11079
+ confidence
11080
+ },
11081
+ metrics,
11082
+ counts,
11083
+ components,
11084
+ diagnostics: buildMemoryUsefulnessDiagnostics({ metrics, counts }),
11085
+ limits: {
11086
+ eventsLimit: limits.eventsLimit || events.length,
11087
+ tracesLimit: limits.tracesLimit || traces.length,
11088
+ eventWindowTruncated,
11089
+ traceWindowTruncated
11090
+ },
11091
+ generatedAt: new Date(now).toISOString()
11092
+ };
11093
+ }
10363
11094
  function computeKpiMetrics(events, usefulRecallRate) {
10364
11095
  const prompts = events.filter((e) => e.eventType === "user_prompt");
10365
11096
  const promptCount = prompts.length;
@@ -10686,6 +11417,32 @@ statsRouter.get("/helpfulness", async (c) => {
10686
11417
  await memoryService.shutdown();
10687
11418
  }
10688
11419
  });
11420
+ statsRouter.get("/usefulness", async (c) => {
11421
+ const rawWindow = c.req.query("window") || "7d";
11422
+ const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
11423
+ const memoryService = getLightweightServiceFromQuery(c);
11424
+ try {
11425
+ await memoryService.initialize();
11426
+ const now = Date.now();
11427
+ const eventLimit = 2e4;
11428
+ const traceLimit = 5e3;
11429
+ const windowStart = new Date(now - windowToMs(window));
11430
+ const [events, helpfulness, traces] = await Promise.all([
11431
+ memoryService.getRecentEvents(eventLimit),
11432
+ memoryService.getHelpfulnessStats(windowStart),
11433
+ memoryService.getRecentRetrievalTraces(traceLimit)
11434
+ ]);
11435
+ return c.json(computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, {
11436
+ eventsLimit: eventLimit,
11437
+ tracesLimit: traceLimit
11438
+ }));
11439
+ } catch (error) {
11440
+ console.error("[stats/usefulness] failed to calculate dashboard metrics", error);
11441
+ return c.json({ error: "Unable to calculate memory usefulness statistics" }, 500);
11442
+ } finally {
11443
+ await memoryService.shutdown();
11444
+ }
11445
+ });
10689
11446
  statsRouter.get("/retrieval-traces", async (c) => {
10690
11447
  const limit = parseInt(c.req.query("limit") || "50", 10);
10691
11448
  const memoryService = getServiceFromQuery(c);
@@ -10695,26 +11452,43 @@ statsRouter.get("/retrieval-traces", async (c) => {
10695
11452
  const traceStats = await memoryService.getRetrievalTraceStats();
10696
11453
  return c.json({
10697
11454
  stats: traceStats,
10698
- traces: traces.map((t) => ({
10699
- traceId: t.traceId,
10700
- sessionId: t.sessionId || null,
10701
- projectHash: t.projectHash || null,
10702
- queryText: t.queryText,
10703
- strategy: t.strategy || null,
10704
- candidateEventIds: t.candidateEventIds,
10705
- selectedEventIds: t.selectedEventIds,
10706
- candidateDetails: t.candidateDetails || [],
10707
- selectedDetails: t.selectedDetails || [],
10708
- candidateCount: t.candidateCount,
10709
- selectedCount: t.selectedCount,
10710
- confidence: t.confidence || null,
10711
- fallbackTrace: t.fallbackTrace,
10712
- createdAt: t.createdAt.toISOString()
10713
- }))
11455
+ traces: traces.map((t) => {
11456
+ const queryRewriteKind = normalizeQueryRewriteKind2(t.queryRewriteKind);
11457
+ return {
11458
+ traceId: t.traceId,
11459
+ sessionId: t.sessionId || null,
11460
+ projectHash: t.projectHash || null,
11461
+ queryRewriteKind,
11462
+ rewritten: queryRewriteKind !== "none",
11463
+ strategy: t.strategy || null,
11464
+ candidateEventIds: t.candidateEventIds,
11465
+ selectedEventIds: t.selectedEventIds,
11466
+ candidateDetails: t.candidateDetails || [],
11467
+ selectedDetails: t.selectedDetails || [],
11468
+ candidateCount: t.candidateCount,
11469
+ selectedCount: t.selectedCount,
11470
+ confidence: t.confidence || null,
11471
+ fallbackTrace: t.fallbackTrace,
11472
+ createdAt: t.createdAt.toISOString()
11473
+ };
11474
+ })
10714
11475
  });
10715
11476
  } catch (error) {
10716
11477
  return c.json({
10717
- stats: { totalQueries: 0, avgCandidateCount: 0, avgSelectedCount: 0, selectionRate: 0 },
11478
+ stats: {
11479
+ totalQueries: 0,
11480
+ avgCandidateCount: 0,
11481
+ avgSelectedCount: 0,
11482
+ selectionRate: 0,
11483
+ rewrittenQueries: 0,
11484
+ rewriteRate: 0,
11485
+ rewrittenQueriesWithSelection: 0,
11486
+ rawQueriesWithSelection: 0,
11487
+ rewrittenSelectionRate: 0,
11488
+ rawSelectionRate: 0,
11489
+ avgSelectedCountForRewrittenQueries: 0,
11490
+ avgSelectedCountForRawQueries: 0
11491
+ },
10718
11492
  traces: [],
10719
11493
  error: error.message
10720
11494
  }, 500);
@@ -10722,6 +11496,40 @@ statsRouter.get("/retrieval-traces", async (c) => {
10722
11496
  await memoryService.shutdown();
10723
11497
  }
10724
11498
  });
11499
+ statsRouter.get("/retrieval-review-queue", async (c) => {
11500
+ const limit = parseStatsLimit(c.req.query("limit"), 10, 50);
11501
+ const scanLimit = parseStatsLimit(c.req.query("scanLimit"), 500, 5e3);
11502
+ const memoryService = getServiceFromQuery(c);
11503
+ try {
11504
+ await memoryService.initialize();
11505
+ const traces = await memoryService.getRecentRetrievalTraces(scanLimit);
11506
+ return c.json({
11507
+ ...buildRetrievalReviewQueue(traces, limit),
11508
+ limits: {
11509
+ requestedLimit: limit,
11510
+ scanLimit,
11511
+ scannedTraces: traces.length
11512
+ }
11513
+ });
11514
+ } catch (error) {
11515
+ console.error("Failed to build retrieval review queue");
11516
+ return c.json({
11517
+ summary: {
11518
+ totalTraces: 0,
11519
+ reviewItems: 0,
11520
+ returnedItems: 0,
11521
+ candidateNoSelection: 0,
11522
+ emptyCandidateSet: 0,
11523
+ rewrittenNoSelection: 0,
11524
+ lowSelectionRate: 0
11525
+ },
11526
+ items: [],
11527
+ error: "Unable to build retrieval review queue"
11528
+ }, 500);
11529
+ } finally {
11530
+ await memoryService.shutdown();
11531
+ }
11532
+ });
10725
11533
  statsRouter.get("/kpi", async (c) => {
10726
11534
  const rawWindow = c.req.query("window") || "7d";
10727
11535
  const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
@@ -11373,12 +12181,9 @@ healthRouter.get("/", async (c) => {
11373
12181
  var apiRouter = new Hono10().route("/sessions", sessionsRouter).route("/events", eventsRouter).route("/search", searchRouter).route("/stats", statsRouter).route("/citations", citationsRouter).route("/turns", turnsRouter).route("/projects", projectsRouter).route("/chat", chatRouter).route("/health", healthRouter);
11374
12182
 
11375
12183
  // src/apps/server/index.ts
11376
- var app = new Hono11();
11377
12184
  var moduleDir = path17.dirname(fileUrlToPath(import.meta.url));
11378
- app.use("/*", cors());
11379
- app.use("/*", logger());
11380
- app.route("/api", apiRouter);
11381
- app.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
12185
+ var DASHBOARD_SESSION_COOKIE = "cml_dashboard_session";
12186
+ var DEFAULT_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
11382
12187
  function resolveUiPath() {
11383
12188
  const candidates = [
11384
12189
  // Built server: dist/server/index.js -> dist/ui
@@ -11391,28 +12196,230 @@ function resolveUiPath() {
11391
12196
  ];
11392
12197
  return candidates.find((candidate) => fs15.existsSync(path17.join(candidate, "index.html"))) ?? candidates[0];
11393
12198
  }
11394
- var uiPath = resolveUiPath();
11395
- if (fs15.existsSync(uiPath)) {
11396
- app.use("/*", serveStatic({ root: uiPath }));
12199
+ function normalizeDashboardHost(host = "localhost") {
12200
+ const normalized = host.trim().toLowerCase();
12201
+ if (normalized === "" || normalized === "localhost" || normalized === "127.0.0.1") {
12202
+ return "127.0.0.1";
12203
+ }
12204
+ if (normalized === "0.0.0.0") {
12205
+ return "0.0.0.0";
12206
+ }
12207
+ throw new Error("Invalid dashboard host: expected localhost, 127.0.0.1, or 0.0.0.0");
12208
+ }
12209
+ function displayHost(hostname2) {
12210
+ return hostname2 === "0.0.0.0" ? "0.0.0.0" : "localhost";
11397
12211
  }
11398
- app.get("*", (c) => {
11399
- const indexPath = path17.join(uiPath, "index.html");
11400
- if (fs15.existsSync(indexPath)) {
11401
- return c.html(fs15.readFileSync(indexPath, "utf-8"));
12212
+ function normalizeServerOptions(portOrOptions) {
12213
+ if (typeof portOrOptions === "number") {
12214
+ return { port: portOrOptions, host: "localhost" };
11402
12215
  }
11403
- return c.text('UI not built. Run "npm run build:ui" first.', 404);
11404
- });
12216
+ return {
12217
+ port: portOrOptions?.port ?? 37777,
12218
+ host: portOrOptions?.host ?? "localhost",
12219
+ password: portOrOptions?.password,
12220
+ cookieMaxAgeSeconds: portOrOptions?.cookieMaxAgeSeconds,
12221
+ now: portOrOptions?.now
12222
+ };
12223
+ }
12224
+ function parseDashboardServerPort(portOption) {
12225
+ const normalized = (portOption ?? "37777").trim();
12226
+ if (!/^\d+$/.test(normalized)) {
12227
+ throw new Error("Invalid PORT: expected a positive integer");
12228
+ }
12229
+ const port = Number.parseInt(normalized, 10);
12230
+ if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
12231
+ throw new Error("Invalid PORT: expected a TCP port between 1 and 65535");
12232
+ }
12233
+ return port;
12234
+ }
12235
+ function resolveDashboardServerEnv(env) {
12236
+ const hostname2 = normalizeDashboardHost(env.DASHBOARD_HOST ?? "localhost");
12237
+ const password = env.DASHBOARD_PASSWORD || env.CLAUDE_MEMORY_LAYER_DASHBOARD_PASSWORD;
12238
+ return {
12239
+ port: parseDashboardServerPort(env.PORT),
12240
+ host: displayHost(hostname2),
12241
+ password: password || void 0
12242
+ };
12243
+ }
12244
+ function nowSeconds(now) {
12245
+ return Math.floor(now() / 1e3);
12246
+ }
12247
+ function signSessionPayload(payload, password) {
12248
+ return createHmac("sha256", password).update(`claude-memory-layer-dashboard:${payload}`).digest("base64url");
12249
+ }
12250
+ function createDashboardSessionToken(password, now) {
12251
+ const payload = String(nowSeconds(now));
12252
+ return `${payload}.${signSessionPayload(payload, password)}`;
12253
+ }
12254
+ function timingSafeStringEqual(a, b) {
12255
+ const left = Buffer.from(a);
12256
+ const right = Buffer.from(b);
12257
+ return left.length === right.length && timingSafeEqual(left, right);
12258
+ }
12259
+ function verifyDashboardSessionToken(token, password, maxAgeSeconds, now) {
12260
+ if (!token)
12261
+ return false;
12262
+ const [payload, signature, extra] = token.split(".");
12263
+ if (!payload || !signature || extra !== void 0 || !/^\d+$/.test(payload))
12264
+ return false;
12265
+ const expectedSignature = signSessionPayload(payload, password);
12266
+ if (!timingSafeStringEqual(signature, expectedSignature))
12267
+ return false;
12268
+ const issuedAt = Number.parseInt(payload, 10);
12269
+ const age = nowSeconds(now) - issuedAt;
12270
+ return Number.isSafeInteger(issuedAt) && age >= 0 && age <= maxAgeSeconds;
12271
+ }
12272
+ function isDashboardAuthenticated(c, options) {
12273
+ if (!options.password)
12274
+ return true;
12275
+ return verifyDashboardSessionToken(
12276
+ getCookie(c, DASHBOARD_SESSION_COOKIE),
12277
+ options.password,
12278
+ options.cookieMaxAgeSeconds,
12279
+ options.now
12280
+ );
12281
+ }
12282
+ function isApiRequest(c) {
12283
+ return c.req.path.startsWith("/api/");
12284
+ }
12285
+ function wantsAuthJson(c) {
12286
+ const accept = c.req.header("accept") ?? "";
12287
+ const contentType = c.req.header("content-type") ?? "";
12288
+ return accept.includes("application/json") || contentType.includes("application/json");
12289
+ }
12290
+ function isSecureRequest(c) {
12291
+ const forwardedProto = c.req.header("x-forwarded-proto");
12292
+ return forwardedProto === "https" || c.req.url.startsWith("https://");
12293
+ }
12294
+ function renderLoginPage(message) {
12295
+ const errorBlock = message ? `<div class="error">${message}</div>` : "";
12296
+ return `<!DOCTYPE html>
12297
+ <html lang="en">
12298
+ <head>
12299
+ <meta charset="UTF-8">
12300
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
12301
+ <title>Dashboard Login</title>
12302
+ <style>
12303
+ :root { color-scheme: dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
12304
+ body { min-height: 100vh; margin: 0; display: grid; place-items: center; background: radial-gradient(circle at top, #243b55 0%, #141e30 42%, #070b12 100%); color: #f8fafc; }
12305
+ .card { width: min(420px, calc(100vw - 40px)); padding: 32px; border: 1px solid rgba(148,163,184,.25); border-radius: 20px; background: rgba(15,23,42,.78); box-shadow: 0 24px 80px rgba(0,0,0,.35); }
12306
+ h1 { margin: 0 0 8px; font-size: 28px; }
12307
+ p { margin: 0 0 24px; color: #cbd5e1; }
12308
+ label { display: block; margin-bottom: 8px; color: #e2e8f0; font-size: 14px; }
12309
+ input { width: 100%; box-sizing: border-box; padding: 12px 14px; border-radius: 12px; border: 1px solid rgba(148,163,184,.35); background: rgba(2,6,23,.72); color: #f8fafc; font-size: 16px; }
12310
+ button { width: 100%; margin-top: 16px; padding: 12px 14px; border: 0; border-radius: 12px; background: linear-gradient(135deg, #38bdf8, #818cf8); color: #020617; font-weight: 700; cursor: pointer; }
12311
+ .error { margin-bottom: 16px; padding: 10px 12px; border-radius: 10px; background: rgba(248,113,113,.14); color: #fecaca; border: 1px solid rgba(248,113,113,.35); }
12312
+ </style>
12313
+ </head>
12314
+ <body>
12315
+ <main class="card">
12316
+ <h1>Dashboard Login</h1>
12317
+ <p>Enter the dashboard password to continue.</p>
12318
+ ${errorBlock}
12319
+ <form method="post" action="/api/auth/login">
12320
+ <label for="password">Password</label>
12321
+ <input id="password" name="password" type="password" autocomplete="current-password" autofocus required>
12322
+ <button type="submit">Unlock dashboard</button>
12323
+ </form>
12324
+ </main>
12325
+ </body>
12326
+ </html>`;
12327
+ }
12328
+ async function readSubmittedPassword(c) {
12329
+ const contentType = c.req.header("content-type") ?? "";
12330
+ if (contentType.includes("application/json")) {
12331
+ const body2 = await c.req.json().catch(() => ({}));
12332
+ return typeof body2.password === "string" ? body2.password : "";
12333
+ }
12334
+ const body = await c.req.parseBody().catch(() => ({}));
12335
+ const password = body.password;
12336
+ return typeof password === "string" ? password : "";
12337
+ }
12338
+ function createAuthOptions(options) {
12339
+ return {
12340
+ password: options.password ?? "",
12341
+ cookieMaxAgeSeconds: options.cookieMaxAgeSeconds ?? DEFAULT_SESSION_MAX_AGE_SECONDS,
12342
+ now: options.now ?? Date.now
12343
+ };
12344
+ }
12345
+ function createDashboardApp(options = {}) {
12346
+ const app2 = new Hono11();
12347
+ const authOptions = createAuthOptions(options);
12348
+ app2.use("*", cors());
12349
+ app2.use("*", logger());
12350
+ app2.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
12351
+ app2.get("/api/auth/status", (c) => c.json({
12352
+ enabled: Boolean(authOptions.password),
12353
+ authenticated: isDashboardAuthenticated(c, authOptions)
12354
+ }));
12355
+ app2.post("/api/auth/login", async (c) => {
12356
+ if (!authOptions.password) {
12357
+ return c.json({ enabled: false, authenticated: true });
12358
+ }
12359
+ const submittedPassword = await readSubmittedPassword(c);
12360
+ if (!timingSafeStringEqual(submittedPassword, authOptions.password)) {
12361
+ if (wantsAuthJson(c))
12362
+ return c.json({ error: "Invalid password" }, 401);
12363
+ return c.html(renderLoginPage("Invalid password"), 401);
12364
+ }
12365
+ const token = createDashboardSessionToken(authOptions.password, authOptions.now);
12366
+ setCookie(c, DASHBOARD_SESSION_COOKIE, token, {
12367
+ httpOnly: true,
12368
+ sameSite: "Lax",
12369
+ secure: isSecureRequest(c),
12370
+ path: "/",
12371
+ maxAge: authOptions.cookieMaxAgeSeconds
12372
+ });
12373
+ if (wantsAuthJson(c))
12374
+ return c.json({ authenticated: true });
12375
+ return c.redirect("/", 303);
12376
+ });
12377
+ app2.post("/api/auth/logout", (c) => {
12378
+ deleteCookie(c, DASHBOARD_SESSION_COOKIE, { path: "/" });
12379
+ if (wantsAuthJson(c))
12380
+ return c.json({ authenticated: false });
12381
+ return c.redirect("/", 303);
12382
+ });
12383
+ if (authOptions.password) {
12384
+ app2.use("*", async (c, next) => {
12385
+ if (isDashboardAuthenticated(c, authOptions)) {
12386
+ await next();
12387
+ return;
12388
+ }
12389
+ if (isApiRequest(c))
12390
+ return c.json({ error: "Authentication required" }, 401);
12391
+ return c.html(renderLoginPage(), 401);
12392
+ });
12393
+ }
12394
+ app2.route("/api", apiRouter);
12395
+ const uiPath = resolveUiPath();
12396
+ if (fs15.existsSync(uiPath)) {
12397
+ app2.use("/*", serveStatic({ root: uiPath }));
12398
+ }
12399
+ app2.get("*", (c) => {
12400
+ const indexPath = path17.join(uiPath, "index.html");
12401
+ if (fs15.existsSync(indexPath)) {
12402
+ return c.html(fs15.readFileSync(indexPath, "utf-8"));
12403
+ }
12404
+ return c.text('UI not built. Run "npm run build:ui" first.', 404);
12405
+ });
12406
+ return app2;
12407
+ }
12408
+ var app = createDashboardApp();
11405
12409
  var serverInstance = null;
11406
- function startServer(port = 37777) {
12410
+ function startServer(portOrOptions = 37777) {
11407
12411
  if (serverInstance) {
11408
12412
  return serverInstance;
11409
12413
  }
12414
+ const options = normalizeServerOptions(portOrOptions);
12415
+ const hostname2 = normalizeDashboardHost(options.host);
12416
+ const port = options.port;
11410
12417
  serverInstance = serve({
11411
- fetch: app.fetch,
12418
+ fetch: createDashboardApp(options).fetch,
11412
12419
  port,
11413
- hostname: "127.0.0.1"
12420
+ hostname: hostname2
11414
12421
  });
11415
- console.log(`\u{1F9E0} Code Memory viewer started at http://localhost:${port}`);
12422
+ console.log(`\u{1F9E0} Code Memory viewer started at http://${displayHost(hostname2)}:${port}`);
11416
12423
  return serverInstance;
11417
12424
  }
11418
12425
  function stopServer() {
@@ -11431,8 +12438,7 @@ async function isServerRunning(port = 37777) {
11431
12438
  }
11432
12439
  var isMainModule = process.argv[1]?.includes("server/index") || process.argv[1]?.endsWith("server.js");
11433
12440
  if (isMainModule) {
11434
- const port = parseInt(process.env.PORT || "37777", 10);
11435
- startServer(port);
12441
+ startServer(resolveDashboardServerEnv(process.env));
11436
12442
  }
11437
12443
 
11438
12444
  // src/core/mongo-sync-worker.ts
@@ -12327,6 +13333,32 @@ async function runHermesImportOnce(options, deps = realDeps2) {
12327
13333
  }
12328
13334
  }
12329
13335
 
13336
+ // src/apps/cli/dashboard-command.ts
13337
+ function parseDashboardPort(portOption) {
13338
+ const normalized = (portOption ?? "37777").trim();
13339
+ if (!/^\d+$/.test(normalized)) {
13340
+ throw new Error("Invalid --port: expected a positive integer");
13341
+ }
13342
+ const port = Number.parseInt(normalized, 10);
13343
+ if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
13344
+ throw new Error("Invalid --port: expected a TCP port between 1 and 65535");
13345
+ }
13346
+ return port;
13347
+ }
13348
+ function normalizeDashboardCommandHost(hostOption) {
13349
+ return normalizeDashboardHost(hostOption) === "0.0.0.0" ? "0.0.0.0" : "localhost";
13350
+ }
13351
+ function resolveDashboardCommandOptions(options) {
13352
+ const port = parseDashboardPort(options.port);
13353
+ const host = normalizeDashboardCommandHost(options.host ?? options.bind ?? "localhost");
13354
+ return {
13355
+ port,
13356
+ host,
13357
+ password: options.password,
13358
+ dashboardUrl: `http://localhost:${port}`
13359
+ };
13360
+ }
13361
+
12330
13362
  // src/core/external-market-context.ts
12331
13363
  var MAX_RENDERED_ITEMS = 8;
12332
13364
  var MAX_FRED_SERIES = 10;
@@ -12937,7 +13969,7 @@ async function runMarketContextCommand(options) {
12937
13969
  }
12938
13970
  }
12939
13971
  var program = new Command();
12940
- program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.31");
13972
+ program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.33");
12941
13973
  program.command("market-context").description("Fetch read-only DART/FRED/Finnhub context with structured MarketContextSnapshot bull/bear/risk/catalyst analysis").option("--company <name>", "Company name for DART fallback search and report subject").option("--dart-corp-code <code>", "Exact DART corp_code for issuer-specific filings").option("--symbol <ticker>", "Listed ticker for Finnhub company profile").option("--providers <list>", "Comma-separated providers: dart,fred,finnhub").option("--fred-series <list>", "Comma-separated FRED series IDs").option("--json", "Print structured JSON including analysis.marketSnapshot").option("--no-snapshot", "Disable MarketContextSnapshot and DART company snapshot analysis").action(async (options) => {
12942
13974
  try {
12943
13975
  await runMarketContextCommand(options);
@@ -13873,28 +14905,34 @@ Dry run only. No changes written to ${configPath}`);
13873
14905
  process.exit(1);
13874
14906
  }
13875
14907
  });
13876
- program.command("dashboard").description("Open memory dashboard in browser").option("-p, --port <port>", "Server port", "37777").option("--no-open", "Do not auto-open browser").action(async (options) => {
13877
- const port = parseInt(options.port, 10);
14908
+ program.command("dashboard").description("Open memory dashboard in browser").option("-p, --port <port>", "Server port", "37777").option("--bind <host>", "Bind host: localhost (default) or 0.0.0.0").option("--host <host>", "Alias for --bind <host>").option("--password <password>", "Require this password before serving the dashboard").option("--no-open", "Do not auto-open browser").action(async (options) => {
14909
+ const dashboard = resolveDashboardCommandOptions(options);
14910
+ const { port, host, password, dashboardUrl } = dashboard;
13878
14911
  try {
13879
14912
  const running = await isServerRunning(port);
13880
14913
  if (running) {
13881
14914
  console.log(`
13882
- \u{1F9E0} Dashboard already running at http://localhost:${port}
14915
+ \u{1F9E0} Dashboard already running at ${dashboardUrl}
13883
14916
  `);
13884
14917
  if (options.open) {
13885
- openBrowser(`http://localhost:${port}`);
14918
+ openBrowser(dashboardUrl);
13886
14919
  }
13887
14920
  return;
13888
14921
  }
13889
14922
  console.log("\n\u{1F9E0} Starting Code Memory Dashboard...\n");
13890
- startServer(port);
14923
+ startServer({ port, host, password });
13891
14924
  if (options.open) {
13892
14925
  setTimeout(() => {
13893
- openBrowser(`http://localhost:${port}`);
14926
+ openBrowser(dashboardUrl);
13894
14927
  }, 500);
13895
14928
  }
13896
14929
  console.log(`
13897
- \u{1F4CA} Dashboard: http://localhost:${port}`);
14930
+ \u{1F4CA} Dashboard: ${dashboardUrl}`);
14931
+ console.log(`\u{1F50C} Bind: ${host}`);
14932
+ console.log(`\u{1F510} Password: ${password ? "enabled" : "disabled"}`);
14933
+ if (host === "0.0.0.0" && !password) {
14934
+ console.log("\u26A0\uFE0F Bound to 0.0.0.0 without --password; anyone on the reachable network can access it.");
14935
+ }
13898
14936
  console.log("Press Ctrl+C to stop the server\n");
13899
14937
  const shutdown = () => {
13900
14938
  console.log("\n\n\u{1F44B} Shutting down dashboard...");