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
@@ -8,11 +8,13 @@ const __dirname = dirname(__filename);
8
8
  // src/apps/server/index.ts
9
9
  import { Hono as Hono11 } from "hono";
10
10
  import { cors } from "hono/cors";
11
+ import { getCookie, setCookie, deleteCookie } from "hono/cookie";
11
12
  import { logger } from "hono/logger";
12
13
  import { serve } from "@hono/node-server";
13
14
  import { serveStatic } from "@hono/node-server/serve-static";
14
15
  import * as path13 from "path";
15
16
  import * as fs11 from "fs";
17
+ import { createHmac, timingSafeEqual } from "crypto";
16
18
  import { fileURLToPath as fileUrlToPath } from "url";
17
19
 
18
20
  // src/apps/server/api/index.ts
@@ -2256,10 +2258,15 @@ function sqliteClose(db) {
2256
2258
  function toDateFromSQLite(value) {
2257
2259
  if (value instanceof Date)
2258
2260
  return value;
2259
- if (typeof value === "string")
2260
- return new Date(value);
2261
2261
  if (typeof value === "number")
2262
2262
  return new Date(value);
2263
+ if (typeof value === "string") {
2264
+ const trimmed = value.trim();
2265
+ if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(trimmed)) {
2266
+ return /* @__PURE__ */ new Date(trimmed.replace(" ", "T") + "Z");
2267
+ }
2268
+ return new Date(trimmed);
2269
+ }
2263
2270
  return new Date(String(value));
2264
2271
  }
2265
2272
  function toSQLiteTimestamp(date) {
@@ -2325,6 +2332,13 @@ var MarkdownMirror2 = class {
2325
2332
  };
2326
2333
 
2327
2334
  // src/core/sqlite-event-store.ts
2335
+ function normalizeQueryRewriteKind(value) {
2336
+ const normalized = (value || "").trim().toLowerCase();
2337
+ if (normalized === "follow-up-context" || normalized === "intent-rewrite")
2338
+ return normalized;
2339
+ return "none";
2340
+ }
2341
+ var REWRITTEN_QUERY_REWRITE_KIND_SQL = `LOWER(TRIM(COALESCE(query_rewrite_kind, 'none'))) IN ('follow-up-context', 'intent-rewrite')`;
2328
2342
  var SQLiteEventStore = class {
2329
2343
  db;
2330
2344
  initialized = false;
@@ -2585,6 +2599,8 @@ var SQLiteEventStore = class {
2585
2599
  session_id TEXT,
2586
2600
  project_hash TEXT,
2587
2601
  query_text TEXT NOT NULL,
2602
+ raw_query_text TEXT,
2603
+ query_rewrite_kind TEXT,
2588
2604
  strategy TEXT,
2589
2605
  candidate_event_ids TEXT,
2590
2606
  selected_event_ids TEXT,
@@ -2626,6 +2642,8 @@ var SQLiteEventStore = class {
2626
2642
  CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
2627
2643
  CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
2628
2644
  CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
2645
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_created_at ON memory_helpfulness(created_at);
2646
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_measured_at ON memory_helpfulness(measured_at);
2629
2647
  CREATE INDEX IF NOT EXISTS idx_retrieval_traces_created_at ON retrieval_traces(created_at DESC);
2630
2648
  CREATE INDEX IF NOT EXISTS idx_retrieval_traces_project_hash ON retrieval_traces(project_hash);
2631
2649
  CREATE INDEX IF NOT EXISTS idx_retrieval_traces_session_id ON retrieval_traces(session_id);
@@ -2659,6 +2677,18 @@ var SQLiteEventStore = class {
2659
2677
  sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN candidate_details_json TEXT;`);
2660
2678
  } catch {
2661
2679
  }
2680
+ try {
2681
+ sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN raw_query_text TEXT;`);
2682
+ } catch {
2683
+ }
2684
+ try {
2685
+ sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN query_rewrite_kind TEXT;`);
2686
+ } catch {
2687
+ }
2688
+ try {
2689
+ sqliteExec(this.db, `CREATE INDEX IF NOT EXISTS idx_retrieval_traces_query_rewrite_kind ON retrieval_traces(query_rewrite_kind);`);
2690
+ } catch {
2691
+ }
2662
2692
  const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
2663
2693
  const columnNames = tableInfo.map((col) => col.name);
2664
2694
  if (!columnNames.includes("access_count")) {
@@ -3444,8 +3474,11 @@ var SQLiteEventStore = class {
3444
3474
  /**
3445
3475
  * Get helpfulness statistics for dashboard
3446
3476
  */
3447
- async getHelpfulnessStats() {
3477
+ async getHelpfulnessStats(since) {
3448
3478
  await this.initialize();
3479
+ const sinceIso = since?.toISOString();
3480
+ const evaluatedWhere = sinceIso ? `WHERE measured_at IS NOT NULL AND datetime(created_at) >= datetime(?)` : `WHERE measured_at IS NOT NULL`;
3481
+ const totalWhere = sinceIso ? `WHERE datetime(created_at) >= datetime(?)` : ``;
3449
3482
  const stats = sqliteGet(
3450
3483
  this.db,
3451
3484
  `SELECT
@@ -3455,11 +3488,13 @@ var SQLiteEventStore = class {
3455
3488
  SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
3456
3489
  SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
3457
3490
  FROM memory_helpfulness
3458
- WHERE measured_at IS NOT NULL`
3491
+ ${evaluatedWhere}`,
3492
+ sinceIso ? [sinceIso] : []
3459
3493
  );
3460
3494
  const totalRow = sqliteGet(
3461
3495
  this.db,
3462
- `SELECT COUNT(*) as total FROM memory_helpfulness`
3496
+ `SELECT COUNT(*) as total FROM memory_helpfulness ${totalWhere}`,
3497
+ sinceIso ? [sinceIso] : []
3463
3498
  );
3464
3499
  return {
3465
3500
  avgScore: Math.round((stats?.avg_score || 0) * 100) / 100,
@@ -3558,18 +3593,21 @@ var SQLiteEventStore = class {
3558
3593
  async recordRetrievalTrace(input) {
3559
3594
  await this.initialize();
3560
3595
  const traceId = randomUUID5();
3596
+ const queryRewriteKind = normalizeQueryRewriteKind(input.queryRewriteKind);
3561
3597
  sqliteRun(
3562
3598
  this.db,
3563
3599
  `INSERT INTO retrieval_traces (
3564
- trace_id, session_id, project_hash, query_text, strategy,
3600
+ trace_id, session_id, project_hash, query_text, raw_query_text, query_rewrite_kind, strategy,
3565
3601
  candidate_event_ids, selected_event_ids, candidate_details_json, selected_details_json,
3566
3602
  candidate_count, selected_count, confidence, fallback_trace
3567
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3603
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3568
3604
  [
3569
3605
  traceId,
3570
3606
  input.sessionId || null,
3571
3607
  input.projectHash || null,
3572
3608
  input.queryText,
3609
+ input.rawQueryText || null,
3610
+ queryRewriteKind,
3573
3611
  input.strategy || null,
3574
3612
  JSON.stringify(input.candidateEventIds || []),
3575
3613
  JSON.stringify(input.selectedEventIds || []),
@@ -3595,6 +3633,8 @@ var SQLiteEventStore = class {
3595
3633
  sessionId: row.session_id || void 0,
3596
3634
  projectHash: row.project_hash || void 0,
3597
3635
  queryText: row.query_text,
3636
+ rawQueryText: row.raw_query_text || void 0,
3637
+ queryRewriteKind: normalizeQueryRewriteKind(row.query_rewrite_kind),
3598
3638
  strategy: row.strategy || void 0,
3599
3639
  candidateEventIds: row.candidate_event_ids ? JSON.parse(row.candidate_event_ids) : [],
3600
3640
  selectedEventIds: row.selected_event_ids ? JSON.parse(row.selected_event_ids) : [],
@@ -3621,6 +3661,11 @@ var SQLiteEventStore = class {
3621
3661
  COUNT(*) as total_queries,
3622
3662
  AVG(candidate_count) as avg_candidate_count,
3623
3663
  AVG(selected_count) as avg_selected_count,
3664
+ SUM(CASE WHEN ${REWRITTEN_QUERY_REWRITE_KIND_SQL} THEN 1 ELSE 0 END) as rewritten_queries,
3665
+ SUM(CASE WHEN ${REWRITTEN_QUERY_REWRITE_KIND_SQL} AND selected_count > 0 THEN 1 ELSE 0 END) as rewritten_queries_with_selection,
3666
+ SUM(CASE WHEN NOT (${REWRITTEN_QUERY_REWRITE_KIND_SQL}) AND selected_count > 0 THEN 1 ELSE 0 END) as raw_queries_with_selection,
3667
+ AVG(CASE WHEN ${REWRITTEN_QUERY_REWRITE_KIND_SQL} THEN selected_count END) as avg_selected_count_for_rewritten_queries,
3668
+ AVG(CASE WHEN NOT (${REWRITTEN_QUERY_REWRITE_KIND_SQL}) THEN selected_count END) as avg_selected_count_for_raw_queries,
3624
3669
  CASE
3625
3670
  WHEN SUM(candidate_count) > 0 THEN (SUM(selected_count) * 1.0 / SUM(candidate_count))
3626
3671
  ELSE 0
@@ -3628,15 +3673,41 @@ var SQLiteEventStore = class {
3628
3673
  FROM retrieval_traces`,
3629
3674
  []
3630
3675
  );
3676
+ const totalQueries = Number(row?.total_queries || 0);
3677
+ const rewrittenQueries = Number(row?.rewritten_queries || 0);
3678
+ const rawQueries = Math.max(0, totalQueries - rewrittenQueries);
3679
+ const rewrittenQueriesWithSelection = Number(row?.rewritten_queries_with_selection || 0);
3680
+ const rawQueriesWithSelection = Number(row?.raw_queries_with_selection || 0);
3631
3681
  return {
3632
- totalQueries: Number(row?.total_queries || 0),
3682
+ totalQueries,
3633
3683
  avgCandidateCount: Number(row?.avg_candidate_count || 0),
3634
3684
  avgSelectedCount: Number(row?.avg_selected_count || 0),
3635
- selectionRate: Number(row?.selection_rate || 0)
3685
+ selectionRate: Number(row?.selection_rate || 0),
3686
+ rewrittenQueries,
3687
+ rewriteRate: totalQueries > 0 ? rewrittenQueries / totalQueries : 0,
3688
+ rewrittenQueriesWithSelection,
3689
+ rawQueriesWithSelection,
3690
+ rewrittenSelectionRate: rewrittenQueries > 0 ? rewrittenQueriesWithSelection / rewrittenQueries : 0,
3691
+ rawSelectionRate: rawQueries > 0 ? rawQueriesWithSelection / rawQueries : 0,
3692
+ avgSelectedCountForRewrittenQueries: Number(row?.avg_selected_count_for_rewritten_queries || 0),
3693
+ avgSelectedCountForRawQueries: Number(row?.avg_selected_count_for_raw_queries || 0)
3636
3694
  };
3637
3695
  } catch (err) {
3638
3696
  if (err?.message?.includes("no such table")) {
3639
- return { totalQueries: 0, avgCandidateCount: 0, avgSelectedCount: 0, selectionRate: 0 };
3697
+ return {
3698
+ totalQueries: 0,
3699
+ avgCandidateCount: 0,
3700
+ avgSelectedCount: 0,
3701
+ selectionRate: 0,
3702
+ rewrittenQueries: 0,
3703
+ rewriteRate: 0,
3704
+ rewrittenQueriesWithSelection: 0,
3705
+ rawQueriesWithSelection: 0,
3706
+ rewrittenSelectionRate: 0,
3707
+ rawSelectionRate: 0,
3708
+ avgSelectedCountForRewrittenQueries: 0,
3709
+ avgSelectedCountForRawQueries: 0
3710
+ };
3640
3711
  }
3641
3712
  throw err;
3642
3713
  }
@@ -4448,6 +4519,57 @@ var COMMAND_ARTIFACT_PATTERNS = [
4448
4519
  /<local-command-stdout>[\s\S]*?<\/local-command-stdout>/i,
4449
4520
  /<local-command-stderr>[\s\S]*?<\/local-command-stderr>/i
4450
4521
  ];
4522
+ var CONTINUATION_QUERY_PATTERNS = [
4523
+ /^\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,
4524
+ /^\s*(?:응\s*)?(?:이어서(?:\s*진행(?:해줘)?)?|계속(?:\s*해줘)?|다음\s*(?:단계|작업|추천\s*작업|추천|할\s*일)?(?:은|는)?(?:\s*(?:뭐야|진행(?:해줘)?))?\??|남은\s*(?:추가(?:로)?\s*)?(?:(?:할\s*만한\s*)?(?:작업|일)|할\s*일)?(?:은|는)?\s*(?:있어|있나|있나요|뭐야)\??|추천\s*작업(?:은|는)?(?:\s*뭐야)?\??|진행해줘)\s*$/i
4525
+ ];
4526
+ var SHORT_REPAIR_FOLLOW_UP_PATTERNS = [
4527
+ /^\s*(?:fix\s+(?:it|that)|repair\s+(?:it|that)|resolve\s+(?:it|that)|that\s+bug|same\s+issue)\s*$/i,
4528
+ /^\s*(?:그거|그것|이거|이것)?\s*(?:고쳐줘|수정해줘|해결해줘|처리해줘)\s*$/i
4529
+ ];
4530
+ var CURRENT_STATE_QUERY_PATTERNS = [
4531
+ /\bcurrent\b.*\b(?:state|status|deployment|blocker|pr|pull request)\b/i,
4532
+ /\b(?:still|as current|current)\b.*\b(?:unresolved|open|pending|not completed)\b/i,
4533
+ /\b(?:old|obsolete|stale|resolved|already resolved)\b.*\b(?:current|still|unresolved|open|state|status)\b/i,
4534
+ /(?:현재|아직|이전|오래된|해결된).*(?:상태|미해결|열린|블로커|PR|풀리퀘스트)/i
4535
+ ];
4536
+ var STALE_CONTENT_PATTERNS = [
4537
+ /\b(?:obsolete|superseded|outdated)\b/i,
4538
+ /\bstale\s+(?:operational\s+)?state\b/i,
4539
+ /\bstale\s+after\b/i,
4540
+ /\bno\s+longer\s+(?:valid|current|applies?)\b/i,
4541
+ /\bearlier\s+(?:pull request|pr)\b[\s\S]{0,160}\b(?:open|not completed|had not completed)\b/i,
4542
+ /\bshould\s+not\s+be\s+injected\s+as\s+current\s+context\b/i,
4543
+ /(?:오래된|더 이상 유효하지|현재 상태가 아님)/i
4544
+ ];
4545
+ var CONTINUATION_EXPANSION = "current next step plan roadmap status validation replay rerank memory usefulness continuation";
4546
+ var REPAIR_FOLLOW_UP_EXPANSION = "review blocker fix pattern dashboard error state metrics bucket validation sanitize rerun unresolved";
4547
+ 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";
4548
+ var DECISION_RECALL_TERMS = /* @__PURE__ */ new Set([
4549
+ "decide",
4550
+ "decided",
4551
+ "decision",
4552
+ "agreed",
4553
+ "policy",
4554
+ "constraint"
4555
+ ]);
4556
+ var RETRIEVAL_PRIVACY_SURFACE_TERMS = /* @__PURE__ */ new Set([
4557
+ "retrieval",
4558
+ "dashboard",
4559
+ "telemetry",
4560
+ "trace"
4561
+ ]);
4562
+ var DECISION_TOPIC_WEAK_TERMS = /* @__PURE__ */ new Set([
4563
+ "api",
4564
+ "dashboard",
4565
+ "retrieval",
4566
+ "trace",
4567
+ "telemetry",
4568
+ "query",
4569
+ "raw",
4570
+ "count",
4571
+ "counts"
4572
+ ]);
4451
4573
  var GENERIC_TECHNICAL_TERMS = /* @__PURE__ */ new Set([
4452
4574
  "api",
4453
4575
  "cli",
@@ -4465,6 +4587,87 @@ var GENERIC_TECHNICAL_TERMS = /* @__PURE__ */ new Set([
4465
4587
  "db",
4466
4588
  "sql"
4467
4589
  ]);
4590
+ var LOW_INFORMATION_QUERY_TERMS = /* @__PURE__ */ new Set([
4591
+ "the",
4592
+ "and",
4593
+ "or",
4594
+ "for",
4595
+ "from",
4596
+ "with",
4597
+ "without",
4598
+ "about",
4599
+ "what",
4600
+ "when",
4601
+ "where",
4602
+ "which",
4603
+ "who",
4604
+ "why",
4605
+ "how",
4606
+ "did",
4607
+ "does",
4608
+ "do",
4609
+ "we",
4610
+ "i",
4611
+ "in",
4612
+ "to",
4613
+ "of",
4614
+ "on",
4615
+ "as",
4616
+ "be",
4617
+ "was",
4618
+ "were",
4619
+ "decide",
4620
+ "decided",
4621
+ "decision",
4622
+ "agreed",
4623
+ "policy",
4624
+ "constraint",
4625
+ "showing",
4626
+ "can",
4627
+ "you",
4628
+ "me",
4629
+ "show",
4630
+ "tell",
4631
+ "please",
4632
+ "should",
4633
+ "would",
4634
+ "could",
4635
+ "this",
4636
+ "that",
4637
+ "these",
4638
+ "those",
4639
+ "use",
4640
+ "using",
4641
+ "treat",
4642
+ "continue",
4643
+ "resume",
4644
+ "next",
4645
+ "step",
4646
+ "task",
4647
+ "action",
4648
+ "current",
4649
+ "state",
4650
+ "status",
4651
+ "old",
4652
+ "already",
4653
+ "still",
4654
+ "near",
4655
+ "today",
4656
+ "\uC751",
4657
+ "\uADF8\uAC70",
4658
+ "\uADF8\uAC83",
4659
+ "\uC774\uAC70",
4660
+ "\uC774\uAC83",
4661
+ "\uB2E4\uC74C",
4662
+ "\uB2E8\uACC4",
4663
+ "\uC9C4\uD589",
4664
+ "\uC9C4\uD589\uD574\uC918",
4665
+ "\uACC4\uC18D",
4666
+ "\uC774\uC5B4\uC11C",
4667
+ "\uACE0\uCCD0\uC918",
4668
+ "\uC218\uC815\uD574\uC918",
4669
+ "\uD574\uACB0\uD574\uC918"
4670
+ ]);
4468
4671
  function isCommandArtifactQuery(query) {
4469
4672
  const trimmed = query.trim();
4470
4673
  if (!trimmed)
@@ -4476,6 +4679,73 @@ function isCommandArtifactQuery(query) {
4476
4679
  return true;
4477
4680
  return COMMAND_ARTIFACT_PATTERNS.some((pattern) => pattern.test(trimmed));
4478
4681
  }
4682
+ function isGenericContinuationQuery(query) {
4683
+ const trimmed = query.trim();
4684
+ if (!trimmed)
4685
+ return false;
4686
+ if (!CONTINUATION_QUERY_PATTERNS.some((pattern) => pattern.test(trimmed)))
4687
+ return false;
4688
+ if (extractTechnicalQueryTerms(trimmed).length > 0)
4689
+ return false;
4690
+ const tokens = trimmed.match(/[A-Za-z0-9가-힣#._/-]+/g) ?? [];
4691
+ if (tokens.length > 10)
4692
+ return false;
4693
+ 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);
4694
+ }
4695
+ function isShortRepairFollowUpQuery(query) {
4696
+ const trimmed = query.trim();
4697
+ if (!trimmed)
4698
+ return false;
4699
+ if (extractTechnicalQueryTerms(trimmed).length > 0)
4700
+ return false;
4701
+ const tokens = trimmed.match(/[A-Za-z0-9가-힣#._/-]+/g) ?? [];
4702
+ if (tokens.length > 8)
4703
+ return false;
4704
+ return SHORT_REPAIR_FOLLOW_UP_PATTERNS.some((pattern) => pattern.test(trimmed));
4705
+ }
4706
+ function isCurrentStateQuery(query) {
4707
+ const trimmed = query.trim();
4708
+ if (!trimmed)
4709
+ return false;
4710
+ return CURRENT_STATE_QUERY_PATTERNS.some((pattern) => pattern.test(trimmed));
4711
+ }
4712
+ function isStaleOrSupersededContent(content) {
4713
+ const trimmed = content.trim();
4714
+ if (!trimmed)
4715
+ return false;
4716
+ return STALE_CONTENT_PATTERNS.some((pattern) => pattern.test(trimmed));
4717
+ }
4718
+ function buildRetrievalQualityQuery(query) {
4719
+ const trimmed = query.trim();
4720
+ if (!trimmed)
4721
+ return query;
4722
+ if (isRetrievalPrivacyDecisionQuery(trimmed)) {
4723
+ return `${trimmed} ${RETRIEVAL_PRIVACY_DECISION_EXPANSION}`;
4724
+ }
4725
+ if (isGenericContinuationQuery(trimmed)) {
4726
+ return `${trimmed} ${CONTINUATION_EXPANSION}`;
4727
+ }
4728
+ if (isShortRepairFollowUpQuery(trimmed)) {
4729
+ return `${trimmed} ${REPAIR_FOLLOW_UP_EXPANSION}`;
4730
+ }
4731
+ return query;
4732
+ }
4733
+ function isRetrievalPrivacyDecisionQuery(query) {
4734
+ const trimmed = query.trim();
4735
+ if (!trimmed)
4736
+ return false;
4737
+ const terms = new Set(tokenizeQualityText(trimmed));
4738
+ const hasDecisionSignal = hasAnyTerm(terms, DECISION_RECALL_TERMS) || /(?:결정|정책|원칙)/i.test(trimmed);
4739
+ if (!hasDecisionSignal)
4740
+ return false;
4741
+ const hasRawQuerySignal = terms.has("raw") && terms.has("query");
4742
+ const hasPrivacySignal = terms.has("privacy") || terms.has("expose") || terms.has("redacted");
4743
+ const hasRetrievalSurface = hasAnyTerm(terms, RETRIEVAL_PRIVACY_SURFACE_TERMS) || terms.has("api") && terms.has("query");
4744
+ const hasQuerySurface = terms.has("query") && (terms.has("dashboard") || terms.has("trace") || terms.has("telemetry") || terms.has("api"));
4745
+ const hasKoreanRetrievalSurface = /(?:검색|리트리벌|retrieval|대시보드|트레이스|텔레메트리|telemetry)/i.test(trimmed);
4746
+ const hasKoreanPrivacySurface = /(?:원문|쿼리|프라이버시|개인정보|노출|트레이스|메타데이터)/i.test(trimmed);
4747
+ return (hasRetrievalSurface || hasKoreanRetrievalSurface && hasKoreanPrivacySurface) && (hasRawQuerySignal || hasPrivacySignal || hasQuerySurface || hasKoreanPrivacySurface);
4748
+ }
4479
4749
  function extractTechnicalQueryTerms(query) {
4480
4750
  const matches = query.match(/[A-Za-z][A-Za-z0-9_.:-]{2,}/g) ?? [];
4481
4751
  const terms = matches.filter((term) => {
@@ -4493,9 +4763,87 @@ function hasTechnicalTermOverlap(query, content) {
4493
4763
  const normalizedContent = content.toLowerCase();
4494
4764
  return terms.some((term) => normalizedContent.includes(term));
4495
4765
  }
4766
+ function hasDiscriminativeTermOverlap(query, content) {
4767
+ const queryTerms = extractDiscriminativeQueryTerms(query);
4768
+ const contentTerms = new Set(tokenizeQualityText(content));
4769
+ if (isRetrievalPrivacyDecisionQuery(query) && hasRetrievalPrivacyDecisionContent(contentTerms)) {
4770
+ return true;
4771
+ }
4772
+ if (shouldRequireDecisionTopicOverlap(query)) {
4773
+ const topicTerms = queryTerms.filter((term) => !DECISION_TOPIC_WEAK_TERMS.has(term));
4774
+ if (topicTerms.length > 0) {
4775
+ return topicTerms.some((term) => contentTerms.has(term));
4776
+ }
4777
+ }
4778
+ if (queryTerms.length < 3)
4779
+ return true;
4780
+ const requiredHits = queryTerms.length >= 3 ? 2 : 1;
4781
+ let hits = 0;
4782
+ for (const term of queryTerms) {
4783
+ if (contentTerms.has(term))
4784
+ hits += 1;
4785
+ if (hits >= requiredHits)
4786
+ return true;
4787
+ }
4788
+ return false;
4789
+ }
4496
4790
  function shouldApplyTechnicalGuard(query) {
4497
4791
  return extractTechnicalQueryTerms(query).length > 0;
4498
4792
  }
4793
+ function hasAnyTerm(terms, expectedTerms) {
4794
+ let found = false;
4795
+ expectedTerms.forEach((term) => {
4796
+ if (terms.has(term))
4797
+ found = true;
4798
+ });
4799
+ return found;
4800
+ }
4801
+ function shouldRequireDecisionTopicOverlap(query) {
4802
+ if (isRetrievalPrivacyDecisionQuery(query))
4803
+ return false;
4804
+ const trimmed = query.trim();
4805
+ if (!trimmed)
4806
+ return false;
4807
+ const terms = new Set(tokenizeQualityText(trimmed));
4808
+ return hasAnyTerm(terms, DECISION_RECALL_TERMS) || /(?:결정|정책|원칙)/i.test(trimmed);
4809
+ }
4810
+ function extractDiscriminativeQueryTerms(query) {
4811
+ const seen = /* @__PURE__ */ new Set();
4812
+ const terms = [];
4813
+ for (const token of tokenizeQualityText(query)) {
4814
+ if (LOW_INFORMATION_QUERY_TERMS.has(token))
4815
+ continue;
4816
+ if (GENERIC_TECHNICAL_TERMS.has(token))
4817
+ continue;
4818
+ if (seen.has(token))
4819
+ continue;
4820
+ seen.add(token);
4821
+ terms.push(token);
4822
+ }
4823
+ return terms;
4824
+ }
4825
+ function hasRetrievalPrivacyDecisionContent(contentTerms) {
4826
+ 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"));
4827
+ 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")));
4828
+ return hasDashboardTraceMetadata || hasRawQueryPrivacyPolicy;
4829
+ }
4830
+ function tokenizeQualityText(text) {
4831
+ 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);
4832
+ }
4833
+ function normalizeQualityToken(token) {
4834
+ if (token === "apis")
4835
+ return "api";
4836
+ if (token === "ids")
4837
+ return "id";
4838
+ if (LOW_INFORMATION_QUERY_TERMS.has(token) || GENERIC_TECHNICAL_TERMS.has(token))
4839
+ return token;
4840
+ if (token.length > 4 && token.endsWith("ies"))
4841
+ return `${token.slice(0, -3)}y`;
4842
+ if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") && !token.endsWith("us") && !token.endsWith("is")) {
4843
+ return token.slice(0, -1);
4844
+ }
4845
+ return token;
4846
+ }
4499
4847
 
4500
4848
  // src/core/retriever.ts
4501
4849
  var DEFAULT_OPTIONS = {
@@ -4548,6 +4896,7 @@ var Retriever = class {
4548
4896
  const opts = { ...DEFAULT_OPTIONS, ...options };
4549
4897
  const sessionFilter = opts.scope?.sessionId ?? opts.sessionId;
4550
4898
  const fallbackTrace = [];
4899
+ const qualityQuery = buildRetrievalQualityQuery(query);
4551
4900
  if (isCommandArtifactQuery(query)) {
4552
4901
  fallbackTrace.push("guard:command-artifact-query");
4553
4902
  const emptyMatch = this.matcher.matchSearchResults([], () => 0);
@@ -4564,6 +4913,7 @@ var Retriever = class {
4564
4913
  const fallbackEnabled = (opts.strategy ?? "auto") === "auto";
4565
4914
  const primaryStrategy = opts.strategy === "auto" ? "fast" : opts.strategy || "fast";
4566
4915
  let current = await this.runStage(query, {
4916
+ qualityQuery,
4567
4917
  strategy: primaryStrategy,
4568
4918
  topK: opts.topK,
4569
4919
  minScore: opts.minScore,
@@ -4581,6 +4931,7 @@ var Retriever = class {
4581
4931
  fallbackTrace.push(`stage:primary:${primaryStrategy}`);
4582
4932
  if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results) && primaryStrategy !== "deep") {
4583
4933
  current = await this.runStage(query, {
4934
+ qualityQuery,
4584
4935
  strategy: "deep",
4585
4936
  topK: opts.topK,
4586
4937
  minScore: opts.minScore,
@@ -4598,6 +4949,7 @@ var Retriever = class {
4598
4949
  }
4599
4950
  if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results)) {
4600
4951
  current = await this.runStage(query, {
4952
+ qualityQuery,
4601
4953
  strategy: "deep",
4602
4954
  topK: opts.topK,
4603
4955
  minScore: Math.max(0.5, opts.minScore - 0.15),
@@ -4614,11 +4966,21 @@ var Retriever = class {
4614
4966
  fallbackTrace.push("fallback:scope-expanded");
4615
4967
  }
4616
4968
  if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results)) {
4617
- const summary = await this.buildSummaryFallback(query, opts.topK);
4969
+ const summary = await this.buildSummaryFallback(qualityQuery, opts.topK);
4970
+ const scopedSummary = await this.applyScopeFilters(summary, {
4971
+ scope: opts.scope,
4972
+ projectScopeMode: opts.projectScopeMode,
4973
+ projectHash: opts.projectHash,
4974
+ allowedProjectHashes: opts.allowedProjectHashes
4975
+ });
4976
+ const filteredSummary = this.applyQualityFilters(scopedSummary, {
4977
+ query,
4978
+ minScore: opts.minScore
4979
+ });
4618
4980
  current = {
4619
- results: summary,
4620
- candidateResults: summary,
4621
- matchResult: this.matcher.matchSearchResults(summary, () => 0)
4981
+ results: filteredSummary,
4982
+ candidateResults: filteredSummary,
4983
+ matchResult: this.matcher.matchSearchResults(filteredSummary, () => 0)
4622
4984
  };
4623
4985
  fallbackTrace.push("fallback:summary");
4624
4986
  }
@@ -4643,7 +5005,10 @@ var Retriever = class {
4643
5005
  semanticScore: r.semanticScore,
4644
5006
  lexicalScore: r.lexicalScore,
4645
5007
  recencyScore: r.recencyScore
4646
- }))
5008
+ })),
5009
+ rawQueryText: current.queryRewriteKind ? query : void 0,
5010
+ effectiveQueryText: current.effectiveQueryText,
5011
+ queryRewriteKind: current.queryRewriteKind
4647
5012
  };
4648
5013
  }
4649
5014
  async retrieveUnified(query, options = {}) {
@@ -4681,8 +5046,11 @@ var Retriever = class {
4681
5046
  }
4682
5047
  }
4683
5048
  async runStage(query, input) {
4684
- let rerankQuery = query;
4685
- let initialResults = await this.searchByStrategy(query, {
5049
+ const searchQuery = input.qualityQuery ?? query;
5050
+ let rerankQuery = searchQuery;
5051
+ let effectiveQueryText;
5052
+ let queryRewriteKind;
5053
+ let initialResults = await this.searchByStrategy(searchQuery, {
4686
5054
  strategy: input.strategy,
4687
5055
  topK: input.topK,
4688
5056
  minScore: input.minScore,
@@ -4690,9 +5058,12 @@ var Retriever = class {
4690
5058
  });
4691
5059
  if (input.intentRewrite && input.strategy === "deep" && this.queryRewriter) {
4692
5060
  const rewritten = (await this.queryRewriter(query))?.trim();
4693
- if (rewritten && rewritten !== query) {
4694
- rerankQuery = `${query} ${rewritten}`;
4695
- const rewrittenResults = await this.searchByStrategy(rewritten, {
5061
+ const normalizedQuery = query.trim();
5062
+ if (rewritten && rewritten !== normalizedQuery) {
5063
+ effectiveQueryText = `${normalizedQuery} ${rewritten}`.trim();
5064
+ queryRewriteKind = "intent-rewrite";
5065
+ rerankQuery = buildRetrievalQualityQuery(effectiveQueryText);
5066
+ const rewrittenResults = await this.searchByStrategy(buildRetrievalQualityQuery(rewritten), {
4696
5067
  strategy: "deep",
4697
5068
  topK: input.topK,
4698
5069
  minScore: Math.max(0.5, input.minScore - 0.1),
@@ -4719,10 +5090,14 @@ var Retriever = class {
4719
5090
  });
4720
5091
  const top = qualityFiltered.slice(0, input.topK);
4721
5092
  const matchResult = this.matcher.matchSearchResults(top, () => 0);
4722
- return { results: top, candidateResults: qualityFiltered, matchResult };
5093
+ return { results: top, candidateResults: qualityFiltered, matchResult, effectiveQueryText, queryRewriteKind };
4723
5094
  }
4724
5095
  applyQualityFilters(results, options) {
4725
5096
  let filtered = [...results];
5097
+ if (isCurrentStateQuery(options.query)) {
5098
+ filtered = filtered.filter((result) => !isStaleOrSupersededContent(result.content));
5099
+ }
5100
+ filtered = filtered.filter((result) => hasDiscriminativeTermOverlap(options.query, result.content));
4726
5101
  if (shouldApplyTechnicalGuard(options.query)) {
4727
5102
  filtered = filtered.filter((result) => hasTechnicalTermOverlap(options.query, result.content));
4728
5103
  }
@@ -5030,7 +5405,21 @@ _Context:_ ${sessionContext}`;
5030
5405
  });
5031
5406
  }
5032
5407
  tokenize(text) {
5033
- return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length >= 2).slice(0, 64);
5408
+ 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);
5409
+ }
5410
+ normalizeToken(token) {
5411
+ if (token === "apis")
5412
+ return "api";
5413
+ if (token === "ids")
5414
+ return "id";
5415
+ if (token === "does")
5416
+ return token;
5417
+ if (token.length > 4 && token.endsWith("ies"))
5418
+ return `${token.slice(0, -3)}y`;
5419
+ if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") && !token.endsWith("us") && !token.endsWith("is") && !token.endsWith("ps")) {
5420
+ return token.slice(0, -1);
5421
+ }
5422
+ return token;
5034
5423
  }
5035
5424
  keywordOverlap(a, b) {
5036
5425
  if (a.length === 0 || b.length === 0)
@@ -5093,9 +5482,9 @@ var RetrievalAnalyticsService = class {
5093
5482
  await this.deps.initialize();
5094
5483
  return this.deps.retrievalStore.getHelpfulMemories(limit);
5095
5484
  }
5096
- async getHelpfulnessStats() {
5485
+ async getHelpfulnessStats(since) {
5097
5486
  await this.deps.initialize();
5098
- return this.deps.retrievalStore.getHelpfulnessStats();
5487
+ return this.deps.retrievalStore.getHelpfulnessStats(since);
5099
5488
  }
5100
5489
  /**
5101
5490
  * Extract topic keywords from event content (markdown headings and key terms).
@@ -5520,7 +5909,9 @@ var RetrievalOrchestrator = class {
5520
5909
  await this.deps.traceStore.recordRetrievalTrace({
5521
5910
  sessionId: options?.sessionId,
5522
5911
  projectHash: projectHash || void 0,
5523
- queryText: query,
5912
+ queryText: result.effectiveQueryText || query,
5913
+ rawQueryText: result.rawQueryText || (result.queryRewriteKind ? query : void 0),
5914
+ queryRewriteKind: result.queryRewriteKind || "none",
5524
5915
  strategy: options?.strategy || "auto",
5525
5916
  candidateEventIds,
5526
5917
  selectedEventIds,
@@ -7514,8 +7905,8 @@ var MemoryService = class {
7514
7905
  /**
7515
7906
  * Get helpfulness statistics for dashboard
7516
7907
  */
7517
- async getHelpfulnessStats() {
7518
- return this.retrievalAnalyticsService.getHelpfulnessStats();
7908
+ async getHelpfulnessStats(since) {
7909
+ return this.retrievalAnalyticsService.getHelpfulnessStats(since);
7519
7910
  }
7520
7911
  /**
7521
7912
  * Mark a consolidated memory as accessed
@@ -8070,6 +8461,346 @@ function computeSessionTurnCount(sessionEvents) {
8070
8461
  return turnIds.size;
8071
8462
  return sessionEvents.filter((e) => e.eventType === "user_prompt").length;
8072
8463
  }
8464
+ function normalizeQueryRewriteKind2(value) {
8465
+ const normalized = (value || "").trim().toLowerCase();
8466
+ if (normalized === "follow-up-context" || normalized === "intent-rewrite")
8467
+ return normalized;
8468
+ return "none";
8469
+ }
8470
+ function normalizeMetric(value) {
8471
+ const numberValue = Number(value || 0);
8472
+ if (!Number.isFinite(numberValue))
8473
+ return 0;
8474
+ return Math.max(0, Math.min(1, numberValue));
8475
+ }
8476
+ function getTimestampMs(value) {
8477
+ if (value instanceof Date)
8478
+ return value.getTime();
8479
+ if (typeof value === "string") {
8480
+ const parsed = new Date(value).getTime();
8481
+ return Number.isFinite(parsed) ? parsed : 0;
8482
+ }
8483
+ return 0;
8484
+ }
8485
+ function isRewrittenRetrievalTrace(trace) {
8486
+ return normalizeQueryRewriteKind2(trace.queryRewriteKind) !== "none";
8487
+ }
8488
+ function getTraceSelectedCount(trace) {
8489
+ return Number(trace.selectedCount ?? trace.selectedEventIds?.length ?? 0);
8490
+ }
8491
+ function getTraceCandidateCount(trace) {
8492
+ return Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? trace.candidateDetails?.length ?? 0);
8493
+ }
8494
+ function makeRetrievalReviewItem(trace) {
8495
+ const candidateCount = getTraceCandidateCount(trace);
8496
+ const selectedCount = getTraceSelectedCount(trace);
8497
+ const queryRewriteKind = normalizeQueryRewriteKind2(trace.queryRewriteKind);
8498
+ const rewritten = queryRewriteKind !== "none";
8499
+ const createdAtMs = getTimestampMs(trace.createdAt);
8500
+ const createdAt = createdAtMs > 0 ? new Date(createdAtMs).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
8501
+ let reason = null;
8502
+ let severity = "info";
8503
+ let priority = 0;
8504
+ let title = "";
8505
+ let detail = "";
8506
+ let action = "";
8507
+ if (candidateCount > 0 && selectedCount === 0 && rewritten) {
8508
+ reason = "rewritten-query-no-selection";
8509
+ severity = "warn";
8510
+ priority = 100;
8511
+ title = "Rewritten query selected no memories";
8512
+ detail = `${candidateCount} candidates were found after query rewrite, but no memory was selected.`;
8513
+ action = "Review rewrite wording, rerank scores, and final selection thresholds for this trace.";
8514
+ } else if (candidateCount > 0 && selectedCount === 0) {
8515
+ reason = "candidate-no-selection";
8516
+ severity = "warn";
8517
+ priority = 90;
8518
+ title = "Candidates found but nothing selected";
8519
+ detail = `${candidateCount} candidates were available, but the final selection injected no memory.`;
8520
+ action = "Review rerank thresholds and candidate filtering; consider overfetching before final selection.";
8521
+ } else if (candidateCount === 0) {
8522
+ reason = "empty-candidate-set";
8523
+ severity = "info";
8524
+ priority = 70;
8525
+ title = "Retrieval found no candidates";
8526
+ detail = "The retrieval pipeline returned no candidate memories for this trace.";
8527
+ action = "Check trigger/query rewrite coverage and whether the project has indexed memories for this topic.";
8528
+ } else if (candidateCount >= 10 && safeRatio(selectedCount, candidateCount) < 0.15) {
8529
+ reason = "low-selection-rate";
8530
+ severity = "info";
8531
+ priority = 60;
8532
+ title = "Low selection ratio from many candidates";
8533
+ detail = `${selectedCount} of ${candidateCount} candidates were selected.`;
8534
+ action = "Inspect score distribution and MMR/diversity settings before lowering thresholds.";
8535
+ }
8536
+ if (!reason)
8537
+ return null;
8538
+ return {
8539
+ traceId: trace.traceId || "unknown-trace",
8540
+ reason,
8541
+ severity,
8542
+ priority,
8543
+ title,
8544
+ detail,
8545
+ action,
8546
+ queryRewriteKind,
8547
+ rewritten,
8548
+ strategy: trace.strategy || null,
8549
+ candidateCount,
8550
+ selectedCount,
8551
+ candidateEventIds: (trace.candidateEventIds || []).slice(0, 5),
8552
+ selectedEventIds: (trace.selectedEventIds || []).slice(0, 5),
8553
+ candidateDetails: (trace.candidateDetails || []).slice(0, 3).map((detail2) => ({
8554
+ eventId: detail2.eventId,
8555
+ score: detail2.score,
8556
+ semanticScore: detail2.semanticScore,
8557
+ lexicalScore: detail2.lexicalScore,
8558
+ recencyScore: detail2.recencyScore
8559
+ })),
8560
+ selectedDetails: (trace.selectedDetails || []).slice(0, 3).map((detail2) => ({
8561
+ eventId: detail2.eventId,
8562
+ score: detail2.score,
8563
+ semanticScore: detail2.semanticScore,
8564
+ lexicalScore: detail2.lexicalScore,
8565
+ recencyScore: detail2.recencyScore
8566
+ })),
8567
+ createdAt
8568
+ };
8569
+ }
8570
+ function buildRetrievalReviewQueue(traces, limit) {
8571
+ 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());
8572
+ return {
8573
+ summary: {
8574
+ totalTraces: traces.length,
8575
+ reviewItems: reviewItems.length,
8576
+ returnedItems: Math.min(reviewItems.length, limit),
8577
+ candidateNoSelection: reviewItems.filter((item) => item.reason === "candidate-no-selection").length,
8578
+ emptyCandidateSet: reviewItems.filter((item) => item.reason === "empty-candidate-set").length,
8579
+ rewrittenNoSelection: reviewItems.filter((item) => item.reason === "rewritten-query-no-selection").length,
8580
+ lowSelectionRate: reviewItems.filter((item) => item.reason === "low-selection-rate").length
8581
+ },
8582
+ items: reviewItems.slice(0, limit)
8583
+ };
8584
+ }
8585
+ function parseStatsLimit(value, fallback, max) {
8586
+ if (!value)
8587
+ return fallback;
8588
+ if (!/^\d+$/.test(value))
8589
+ return fallback;
8590
+ const parsed = Number(value);
8591
+ if (!Number.isFinite(parsed) || parsed <= 0)
8592
+ return fallback;
8593
+ return Math.min(parsed, max);
8594
+ }
8595
+ function usefulnessScoreLabel(score, confidence) {
8596
+ if (confidence <= 0)
8597
+ return "unknown";
8598
+ if (score >= 80)
8599
+ return "excellent";
8600
+ if (score >= 60)
8601
+ return "good";
8602
+ if (score >= 40)
8603
+ return "watch";
8604
+ return "low";
8605
+ }
8606
+ function buildMemoryUsefulnessDiagnostics(input) {
8607
+ const { metrics, counts } = input;
8608
+ const diagnostics = [];
8609
+ if (counts.promptCount > 0 && counts.retrievalQueries === 0) {
8610
+ diagnostics.push({
8611
+ key: "no-retrieval-traces",
8612
+ severity: "warn",
8613
+ metric: "retrievalUsageRate",
8614
+ value: 0,
8615
+ target: 0.5,
8616
+ title: "No retrieval traces were recorded",
8617
+ detail: `${counts.promptCount} prompts were seen, but none produced a retrieval trace in this window.`,
8618
+ action: "Confirm the prompt hook is enabled and broaden adherence triggers for continuation, write-intent, and project-specific prompts."
8619
+ });
8620
+ }
8621
+ if (counts.promptCount > 0 && metrics.memoryHitRate < 0.5) {
8622
+ diagnostics.push({
8623
+ key: "low-memory-hit-rate",
8624
+ severity: "warn",
8625
+ metric: "memoryHitRate",
8626
+ value: metrics.memoryHitRate,
8627
+ target: 0.5,
8628
+ title: "Memory checks are missing many prompts",
8629
+ detail: `Only ${counts.memoryCheckedPrompts} of ${counts.promptCount} prompts had an adherence check in this window.`,
8630
+ action: "Broaden adherence triggers for continuation, write-intent, topic-shift, and project-specific prompts."
8631
+ });
8632
+ }
8633
+ if (counts.retrievalQueries > 0 && metrics.queryYieldRate < 0.6) {
8634
+ diagnostics.push({
8635
+ key: "low-query-yield-rate",
8636
+ severity: "warn",
8637
+ metric: "queryYieldRate",
8638
+ value: metrics.queryYieldRate,
8639
+ target: 0.6,
8640
+ title: "Searches often select no memory",
8641
+ detail: `${counts.queriesWithSelected} of ${counts.retrievalQueries} retrieval queries injected at least one memory.`,
8642
+ action: "Overfetch candidates, then filter/rerank before applying the final injection threshold."
8643
+ });
8644
+ }
8645
+ if (counts.totalEvaluated > 0 && metrics.avgHelpfulnessScore < 0.7) {
8646
+ diagnostics.push({
8647
+ key: "low-helpfulness-score",
8648
+ severity: "warn",
8649
+ metric: "avgHelpfulnessScore",
8650
+ value: metrics.avgHelpfulnessScore,
8651
+ target: 0.7,
8652
+ title: "Injected memories are not translating into outcomes",
8653
+ detail: `${counts.totalEvaluated} evaluated retrievals averaged ${(metrics.avgHelpfulnessScore * 100).toFixed(1)}% helpfulness.`,
8654
+ action: "Review low-scoring retrieval samples for stale decisions, cross-project noise, or raw transcript snippets."
8655
+ });
8656
+ }
8657
+ if (counts.totalRetrievals > 0 && metrics.evaluationCoverage < 0.8) {
8658
+ diagnostics.push({
8659
+ key: "low-evaluation-coverage",
8660
+ severity: "info",
8661
+ metric: "evaluationCoverage",
8662
+ value: metrics.evaluationCoverage,
8663
+ target: 0.8,
8664
+ title: "Many retrievals are still unevaluated",
8665
+ detail: `${counts.totalEvaluated} of ${counts.totalRetrievals} retrievals have measured helpfulness.`,
8666
+ action: "Ensure Stop/session-end hooks or pending-session backfill are running so usefulness reflects real outcomes."
8667
+ });
8668
+ }
8669
+ if (counts.candidateMemories > 0 && counts.selectedMemories === 0) {
8670
+ diagnostics.push({
8671
+ key: "candidates-without-selection",
8672
+ severity: "warn",
8673
+ metric: "selectionRate",
8674
+ value: metrics.selectionRate,
8675
+ target: 0.2,
8676
+ title: "Candidates are found but none are injected",
8677
+ detail: `${counts.candidateMemories} candidates were retrieved, but no memories passed the injection policy.`,
8678
+ action: "Inspect threshold settings and prompt-injection policy before lowering filters globally."
8679
+ });
8680
+ }
8681
+ return diagnostics.slice(0, 3);
8682
+ }
8683
+ function computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, limits = {}) {
8684
+ const windowEvents = events.filter((event) => inWindow(event, now, window));
8685
+ const prompts = windowEvents.filter((event) => event.eventType === "user_prompt");
8686
+ const promptCount = prompts.length;
8687
+ const memoryCheckedPrompts = prompts.filter((prompt) => prompt.metadata?.adherence?.checked).length;
8688
+ const windowMs = windowToMs(window);
8689
+ const windowStart = now - windowMs;
8690
+ const windowTraces = traces.filter((trace) => {
8691
+ const ts = getTimestampMs(trace.createdAt);
8692
+ return ts > 0 && ts >= windowStart;
8693
+ });
8694
+ const oldestEventTimestamp = events.reduce((oldest, event) => {
8695
+ const timestamp = event.timestamp?.getTime?.() || 0;
8696
+ return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
8697
+ }, Number.POSITIVE_INFINITY);
8698
+ const oldestTraceTimestamp = traces.reduce((oldest, trace) => {
8699
+ const timestamp = getTimestampMs(trace.createdAt);
8700
+ return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
8701
+ }, Number.POSITIVE_INFINITY);
8702
+ const eventWindowTruncated = Boolean(
8703
+ limits.eventsLimit && events.length >= limits.eventsLimit && Number.isFinite(oldestEventTimestamp) && oldestEventTimestamp >= windowStart
8704
+ );
8705
+ const traceWindowTruncated = Boolean(
8706
+ limits.tracesLimit && traces.length >= limits.tracesLimit && Number.isFinite(oldestTraceTimestamp) && oldestTraceTimestamp >= windowStart
8707
+ );
8708
+ const retrievalQueries = windowTraces.length;
8709
+ const candidateCounts = windowTraces.map((trace) => Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? 0));
8710
+ const selectedCounts = windowTraces.map((trace) => getTraceSelectedCount(trace));
8711
+ const totalCandidateCount = candidateCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
8712
+ const totalSelectedCount = selectedCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
8713
+ const queriesWithSelected = selectedCounts.filter((count) => Number.isFinite(count) && count > 0).length;
8714
+ const rewrittenTraces = windowTraces.filter(isRewrittenRetrievalTrace);
8715
+ const rawTraces = windowTraces.filter((trace) => !isRewrittenRetrievalTrace(trace));
8716
+ const rewrittenQueries = rewrittenTraces.length;
8717
+ const rawQueries = rawTraces.length;
8718
+ const rewrittenSelectedCount = rewrittenTraces.reduce((sum, trace) => {
8719
+ const selectedCount = getTraceSelectedCount(trace);
8720
+ return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
8721
+ }, 0);
8722
+ const rawSelectedCount = rawTraces.reduce((sum, trace) => {
8723
+ const selectedCount = getTraceSelectedCount(trace);
8724
+ return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
8725
+ }, 0);
8726
+ const rewrittenQueriesWithSelected = rewrittenTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
8727
+ const rawQueriesWithSelected = rawTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
8728
+ const totalEvaluated = Number(helpfulness.totalEvaluated || 0);
8729
+ const totalRetrievals = Number(helpfulness.totalRetrievals || 0);
8730
+ const helpful = Number(helpfulness.helpful || 0);
8731
+ const neutral = Number(helpfulness.neutral || 0);
8732
+ const unhelpful = Number(helpfulness.unhelpful || 0);
8733
+ const retrievalsPerPrompt = safeRatio(retrievalQueries, promptCount);
8734
+ const metrics = {
8735
+ avgHelpfulnessScore: round(normalizeMetric(helpfulness.avgScore)),
8736
+ usefulRecallRate: round(safeRatio(helpful, totalEvaluated)),
8737
+ memoryHitRate: round(safeRatio(memoryCheckedPrompts, promptCount)),
8738
+ retrievalUsageRate: round(Math.min(1, retrievalsPerPrompt)),
8739
+ queryYieldRate: round(safeRatio(queriesWithSelected, retrievalQueries)),
8740
+ evaluationCoverage: round(safeRatio(totalEvaluated, totalRetrievals)),
8741
+ retrievalsPerPrompt: round(retrievalsPerPrompt),
8742
+ avgCandidatesPerQuery: round(safeRatio(totalCandidateCount, retrievalQueries), 2),
8743
+ avgSelectedPerQuery: round(safeRatio(totalSelectedCount, retrievalQueries), 2),
8744
+ selectionRate: round(safeRatio(totalSelectedCount, totalCandidateCount)),
8745
+ queryRewriteRate: round(safeRatio(rewrittenQueries, retrievalQueries)),
8746
+ rewrittenQueryYieldRate: round(safeRatio(rewrittenQueriesWithSelected, rewrittenQueries)),
8747
+ rawQueryYieldRate: round(safeRatio(rawQueriesWithSelected, rawQueries)),
8748
+ avgSelectedPerRewrittenQuery: round(safeRatio(rewrittenSelectedCount, rewrittenQueries), 2),
8749
+ avgSelectedPerRawQuery: round(safeRatio(rawSelectedCount, rawQueries), 2)
8750
+ };
8751
+ const counts = {
8752
+ promptCount,
8753
+ memoryCheckedPrompts,
8754
+ retrievalQueries,
8755
+ queriesWithSelected,
8756
+ rewrittenQueries,
8757
+ rawQueries,
8758
+ rewrittenQueriesWithSelected,
8759
+ rawQueriesWithSelected,
8760
+ selectedMemories: totalSelectedCount,
8761
+ candidateMemories: totalCandidateCount,
8762
+ totalEvaluated,
8763
+ totalRetrievals,
8764
+ helpful,
8765
+ neutral,
8766
+ unhelpful
8767
+ };
8768
+ const componentSpecs = [
8769
+ { key: "avgHelpfulnessScore", label: "Average helpfulness score", value: metrics.avgHelpfulnessScore, weight: 0.3, available: totalEvaluated > 0 },
8770
+ { key: "usefulRecallRate", label: "Useful recall rate", value: metrics.usefulRecallRate, weight: 0.25, available: totalEvaluated > 0 },
8771
+ { key: "memoryHitRate", label: "Memory hit rate", value: metrics.memoryHitRate, weight: 0.2, available: promptCount > 0 },
8772
+ { key: "retrievalUsageRate", label: "Retrieval usage rate", value: metrics.retrievalUsageRate, weight: 0.15, available: promptCount > 0 },
8773
+ { key: "queryYieldRate", label: "Query yield rate", value: metrics.queryYieldRate, weight: 0.1, available: retrievalQueries > 0 }
8774
+ ];
8775
+ const totalWeight = componentSpecs.reduce((sum, component) => sum + component.weight, 0);
8776
+ const availableWeight = componentSpecs.filter((component) => component.available).reduce((sum, component) => sum + component.weight, 0);
8777
+ const weightedScore = availableWeight > 0 ? componentSpecs.reduce((sum, component) => sum + (component.available ? component.value * component.weight : 0), 0) / availableWeight : 0;
8778
+ const scoreValue = round(weightedScore * 100, 1);
8779
+ const confidence = round(safeRatio(availableWeight, totalWeight), 2);
8780
+ const components = componentSpecs.map((component) => ({
8781
+ ...component,
8782
+ contribution: component.available ? round(component.value * component.weight * 100, 2) : 0
8783
+ }));
8784
+ return {
8785
+ window,
8786
+ score: {
8787
+ value: scoreValue,
8788
+ label: usefulnessScoreLabel(scoreValue, confidence),
8789
+ confidence
8790
+ },
8791
+ metrics,
8792
+ counts,
8793
+ components,
8794
+ diagnostics: buildMemoryUsefulnessDiagnostics({ metrics, counts }),
8795
+ limits: {
8796
+ eventsLimit: limits.eventsLimit || events.length,
8797
+ tracesLimit: limits.tracesLimit || traces.length,
8798
+ eventWindowTruncated,
8799
+ traceWindowTruncated
8800
+ },
8801
+ generatedAt: new Date(now).toISOString()
8802
+ };
8803
+ }
8073
8804
  function computeKpiMetrics(events, usefulRecallRate) {
8074
8805
  const prompts = events.filter((e) => e.eventType === "user_prompt");
8075
8806
  const promptCount = prompts.length;
@@ -8396,6 +9127,32 @@ statsRouter.get("/helpfulness", async (c) => {
8396
9127
  await memoryService.shutdown();
8397
9128
  }
8398
9129
  });
9130
+ statsRouter.get("/usefulness", async (c) => {
9131
+ const rawWindow = c.req.query("window") || "7d";
9132
+ const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
9133
+ const memoryService = getLightweightServiceFromQuery(c);
9134
+ try {
9135
+ await memoryService.initialize();
9136
+ const now = Date.now();
9137
+ const eventLimit = 2e4;
9138
+ const traceLimit = 5e3;
9139
+ const windowStart = new Date(now - windowToMs(window));
9140
+ const [events, helpfulness, traces] = await Promise.all([
9141
+ memoryService.getRecentEvents(eventLimit),
9142
+ memoryService.getHelpfulnessStats(windowStart),
9143
+ memoryService.getRecentRetrievalTraces(traceLimit)
9144
+ ]);
9145
+ return c.json(computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, {
9146
+ eventsLimit: eventLimit,
9147
+ tracesLimit: traceLimit
9148
+ }));
9149
+ } catch (error) {
9150
+ console.error("[stats/usefulness] failed to calculate dashboard metrics", error);
9151
+ return c.json({ error: "Unable to calculate memory usefulness statistics" }, 500);
9152
+ } finally {
9153
+ await memoryService.shutdown();
9154
+ }
9155
+ });
8399
9156
  statsRouter.get("/retrieval-traces", async (c) => {
8400
9157
  const limit = parseInt(c.req.query("limit") || "50", 10);
8401
9158
  const memoryService = getServiceFromQuery(c);
@@ -8405,26 +9162,43 @@ statsRouter.get("/retrieval-traces", async (c) => {
8405
9162
  const traceStats = await memoryService.getRetrievalTraceStats();
8406
9163
  return c.json({
8407
9164
  stats: traceStats,
8408
- traces: traces.map((t) => ({
8409
- traceId: t.traceId,
8410
- sessionId: t.sessionId || null,
8411
- projectHash: t.projectHash || null,
8412
- queryText: t.queryText,
8413
- strategy: t.strategy || null,
8414
- candidateEventIds: t.candidateEventIds,
8415
- selectedEventIds: t.selectedEventIds,
8416
- candidateDetails: t.candidateDetails || [],
8417
- selectedDetails: t.selectedDetails || [],
8418
- candidateCount: t.candidateCount,
8419
- selectedCount: t.selectedCount,
8420
- confidence: t.confidence || null,
8421
- fallbackTrace: t.fallbackTrace,
8422
- createdAt: t.createdAt.toISOString()
8423
- }))
9165
+ traces: traces.map((t) => {
9166
+ const queryRewriteKind = normalizeQueryRewriteKind2(t.queryRewriteKind);
9167
+ return {
9168
+ traceId: t.traceId,
9169
+ sessionId: t.sessionId || null,
9170
+ projectHash: t.projectHash || null,
9171
+ queryRewriteKind,
9172
+ rewritten: queryRewriteKind !== "none",
9173
+ strategy: t.strategy || null,
9174
+ candidateEventIds: t.candidateEventIds,
9175
+ selectedEventIds: t.selectedEventIds,
9176
+ candidateDetails: t.candidateDetails || [],
9177
+ selectedDetails: t.selectedDetails || [],
9178
+ candidateCount: t.candidateCount,
9179
+ selectedCount: t.selectedCount,
9180
+ confidence: t.confidence || null,
9181
+ fallbackTrace: t.fallbackTrace,
9182
+ createdAt: t.createdAt.toISOString()
9183
+ };
9184
+ })
8424
9185
  });
8425
9186
  } catch (error) {
8426
9187
  return c.json({
8427
- stats: { totalQueries: 0, avgCandidateCount: 0, avgSelectedCount: 0, selectionRate: 0 },
9188
+ stats: {
9189
+ totalQueries: 0,
9190
+ avgCandidateCount: 0,
9191
+ avgSelectedCount: 0,
9192
+ selectionRate: 0,
9193
+ rewrittenQueries: 0,
9194
+ rewriteRate: 0,
9195
+ rewrittenQueriesWithSelection: 0,
9196
+ rawQueriesWithSelection: 0,
9197
+ rewrittenSelectionRate: 0,
9198
+ rawSelectionRate: 0,
9199
+ avgSelectedCountForRewrittenQueries: 0,
9200
+ avgSelectedCountForRawQueries: 0
9201
+ },
8428
9202
  traces: [],
8429
9203
  error: error.message
8430
9204
  }, 500);
@@ -8432,6 +9206,40 @@ statsRouter.get("/retrieval-traces", async (c) => {
8432
9206
  await memoryService.shutdown();
8433
9207
  }
8434
9208
  });
9209
+ statsRouter.get("/retrieval-review-queue", async (c) => {
9210
+ const limit = parseStatsLimit(c.req.query("limit"), 10, 50);
9211
+ const scanLimit = parseStatsLimit(c.req.query("scanLimit"), 500, 5e3);
9212
+ const memoryService = getServiceFromQuery(c);
9213
+ try {
9214
+ await memoryService.initialize();
9215
+ const traces = await memoryService.getRecentRetrievalTraces(scanLimit);
9216
+ return c.json({
9217
+ ...buildRetrievalReviewQueue(traces, limit),
9218
+ limits: {
9219
+ requestedLimit: limit,
9220
+ scanLimit,
9221
+ scannedTraces: traces.length
9222
+ }
9223
+ });
9224
+ } catch (error) {
9225
+ console.error("Failed to build retrieval review queue");
9226
+ return c.json({
9227
+ summary: {
9228
+ totalTraces: 0,
9229
+ reviewItems: 0,
9230
+ returnedItems: 0,
9231
+ candidateNoSelection: 0,
9232
+ emptyCandidateSet: 0,
9233
+ rewrittenNoSelection: 0,
9234
+ lowSelectionRate: 0
9235
+ },
9236
+ items: [],
9237
+ error: "Unable to build retrieval review queue"
9238
+ }, 500);
9239
+ } finally {
9240
+ await memoryService.shutdown();
9241
+ }
9242
+ });
8435
9243
  statsRouter.get("/kpi", async (c) => {
8436
9244
  const rawWindow = c.req.query("window") || "7d";
8437
9245
  const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
@@ -9083,12 +9891,9 @@ healthRouter.get("/", async (c) => {
9083
9891
  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);
9084
9892
 
9085
9893
  // src/apps/server/index.ts
9086
- var app = new Hono11();
9087
9894
  var moduleDir = path13.dirname(fileUrlToPath(import.meta.url));
9088
- app.use("/*", cors());
9089
- app.use("/*", logger());
9090
- app.route("/api", apiRouter);
9091
- app.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
9895
+ var DASHBOARD_SESSION_COOKIE = "cml_dashboard_session";
9896
+ var DEFAULT_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
9092
9897
  function resolveUiPath() {
9093
9898
  const candidates = [
9094
9899
  // Built server: dist/server/index.js -> dist/ui
@@ -9101,28 +9906,230 @@ function resolveUiPath() {
9101
9906
  ];
9102
9907
  return candidates.find((candidate) => fs11.existsSync(path13.join(candidate, "index.html"))) ?? candidates[0];
9103
9908
  }
9104
- var uiPath = resolveUiPath();
9105
- if (fs11.existsSync(uiPath)) {
9106
- app.use("/*", serveStatic({ root: uiPath }));
9909
+ function normalizeDashboardHost(host = "localhost") {
9910
+ const normalized = host.trim().toLowerCase();
9911
+ if (normalized === "" || normalized === "localhost" || normalized === "127.0.0.1") {
9912
+ return "127.0.0.1";
9913
+ }
9914
+ if (normalized === "0.0.0.0") {
9915
+ return "0.0.0.0";
9916
+ }
9917
+ throw new Error("Invalid dashboard host: expected localhost, 127.0.0.1, or 0.0.0.0");
9918
+ }
9919
+ function displayHost(hostname) {
9920
+ return hostname === "0.0.0.0" ? "0.0.0.0" : "localhost";
9107
9921
  }
9108
- app.get("*", (c) => {
9109
- const indexPath = path13.join(uiPath, "index.html");
9110
- if (fs11.existsSync(indexPath)) {
9111
- return c.html(fs11.readFileSync(indexPath, "utf-8"));
9922
+ function normalizeServerOptions(portOrOptions) {
9923
+ if (typeof portOrOptions === "number") {
9924
+ return { port: portOrOptions, host: "localhost" };
9112
9925
  }
9113
- return c.text('UI not built. Run "npm run build:ui" first.', 404);
9114
- });
9926
+ return {
9927
+ port: portOrOptions?.port ?? 37777,
9928
+ host: portOrOptions?.host ?? "localhost",
9929
+ password: portOrOptions?.password,
9930
+ cookieMaxAgeSeconds: portOrOptions?.cookieMaxAgeSeconds,
9931
+ now: portOrOptions?.now
9932
+ };
9933
+ }
9934
+ function parseDashboardServerPort(portOption) {
9935
+ const normalized = (portOption ?? "37777").trim();
9936
+ if (!/^\d+$/.test(normalized)) {
9937
+ throw new Error("Invalid PORT: expected a positive integer");
9938
+ }
9939
+ const port = Number.parseInt(normalized, 10);
9940
+ if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
9941
+ throw new Error("Invalid PORT: expected a TCP port between 1 and 65535");
9942
+ }
9943
+ return port;
9944
+ }
9945
+ function resolveDashboardServerEnv(env) {
9946
+ const hostname = normalizeDashboardHost(env.DASHBOARD_HOST ?? "localhost");
9947
+ const password = env.DASHBOARD_PASSWORD || env.CLAUDE_MEMORY_LAYER_DASHBOARD_PASSWORD;
9948
+ return {
9949
+ port: parseDashboardServerPort(env.PORT),
9950
+ host: displayHost(hostname),
9951
+ password: password || void 0
9952
+ };
9953
+ }
9954
+ function nowSeconds(now) {
9955
+ return Math.floor(now() / 1e3);
9956
+ }
9957
+ function signSessionPayload(payload, password) {
9958
+ return createHmac("sha256", password).update(`claude-memory-layer-dashboard:${payload}`).digest("base64url");
9959
+ }
9960
+ function createDashboardSessionToken(password, now) {
9961
+ const payload = String(nowSeconds(now));
9962
+ return `${payload}.${signSessionPayload(payload, password)}`;
9963
+ }
9964
+ function timingSafeStringEqual(a, b) {
9965
+ const left = Buffer.from(a);
9966
+ const right = Buffer.from(b);
9967
+ return left.length === right.length && timingSafeEqual(left, right);
9968
+ }
9969
+ function verifyDashboardSessionToken(token, password, maxAgeSeconds, now) {
9970
+ if (!token)
9971
+ return false;
9972
+ const [payload, signature, extra] = token.split(".");
9973
+ if (!payload || !signature || extra !== void 0 || !/^\d+$/.test(payload))
9974
+ return false;
9975
+ const expectedSignature = signSessionPayload(payload, password);
9976
+ if (!timingSafeStringEqual(signature, expectedSignature))
9977
+ return false;
9978
+ const issuedAt = Number.parseInt(payload, 10);
9979
+ const age = nowSeconds(now) - issuedAt;
9980
+ return Number.isSafeInteger(issuedAt) && age >= 0 && age <= maxAgeSeconds;
9981
+ }
9982
+ function isDashboardAuthenticated(c, options) {
9983
+ if (!options.password)
9984
+ return true;
9985
+ return verifyDashboardSessionToken(
9986
+ getCookie(c, DASHBOARD_SESSION_COOKIE),
9987
+ options.password,
9988
+ options.cookieMaxAgeSeconds,
9989
+ options.now
9990
+ );
9991
+ }
9992
+ function isApiRequest(c) {
9993
+ return c.req.path.startsWith("/api/");
9994
+ }
9995
+ function wantsAuthJson(c) {
9996
+ const accept = c.req.header("accept") ?? "";
9997
+ const contentType = c.req.header("content-type") ?? "";
9998
+ return accept.includes("application/json") || contentType.includes("application/json");
9999
+ }
10000
+ function isSecureRequest(c) {
10001
+ const forwardedProto = c.req.header("x-forwarded-proto");
10002
+ return forwardedProto === "https" || c.req.url.startsWith("https://");
10003
+ }
10004
+ function renderLoginPage(message) {
10005
+ const errorBlock = message ? `<div class="error">${message}</div>` : "";
10006
+ return `<!DOCTYPE html>
10007
+ <html lang="en">
10008
+ <head>
10009
+ <meta charset="UTF-8">
10010
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
10011
+ <title>Dashboard Login</title>
10012
+ <style>
10013
+ :root { color-scheme: dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
10014
+ 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; }
10015
+ .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); }
10016
+ h1 { margin: 0 0 8px; font-size: 28px; }
10017
+ p { margin: 0 0 24px; color: #cbd5e1; }
10018
+ label { display: block; margin-bottom: 8px; color: #e2e8f0; font-size: 14px; }
10019
+ 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; }
10020
+ 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; }
10021
+ .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); }
10022
+ </style>
10023
+ </head>
10024
+ <body>
10025
+ <main class="card">
10026
+ <h1>Dashboard Login</h1>
10027
+ <p>Enter the dashboard password to continue.</p>
10028
+ ${errorBlock}
10029
+ <form method="post" action="/api/auth/login">
10030
+ <label for="password">Password</label>
10031
+ <input id="password" name="password" type="password" autocomplete="current-password" autofocus required>
10032
+ <button type="submit">Unlock dashboard</button>
10033
+ </form>
10034
+ </main>
10035
+ </body>
10036
+ </html>`;
10037
+ }
10038
+ async function readSubmittedPassword(c) {
10039
+ const contentType = c.req.header("content-type") ?? "";
10040
+ if (contentType.includes("application/json")) {
10041
+ const body2 = await c.req.json().catch(() => ({}));
10042
+ return typeof body2.password === "string" ? body2.password : "";
10043
+ }
10044
+ const body = await c.req.parseBody().catch(() => ({}));
10045
+ const password = body.password;
10046
+ return typeof password === "string" ? password : "";
10047
+ }
10048
+ function createAuthOptions(options) {
10049
+ return {
10050
+ password: options.password ?? "",
10051
+ cookieMaxAgeSeconds: options.cookieMaxAgeSeconds ?? DEFAULT_SESSION_MAX_AGE_SECONDS,
10052
+ now: options.now ?? Date.now
10053
+ };
10054
+ }
10055
+ function createDashboardApp(options = {}) {
10056
+ const app2 = new Hono11();
10057
+ const authOptions = createAuthOptions(options);
10058
+ app2.use("*", cors());
10059
+ app2.use("*", logger());
10060
+ app2.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
10061
+ app2.get("/api/auth/status", (c) => c.json({
10062
+ enabled: Boolean(authOptions.password),
10063
+ authenticated: isDashboardAuthenticated(c, authOptions)
10064
+ }));
10065
+ app2.post("/api/auth/login", async (c) => {
10066
+ if (!authOptions.password) {
10067
+ return c.json({ enabled: false, authenticated: true });
10068
+ }
10069
+ const submittedPassword = await readSubmittedPassword(c);
10070
+ if (!timingSafeStringEqual(submittedPassword, authOptions.password)) {
10071
+ if (wantsAuthJson(c))
10072
+ return c.json({ error: "Invalid password" }, 401);
10073
+ return c.html(renderLoginPage("Invalid password"), 401);
10074
+ }
10075
+ const token = createDashboardSessionToken(authOptions.password, authOptions.now);
10076
+ setCookie(c, DASHBOARD_SESSION_COOKIE, token, {
10077
+ httpOnly: true,
10078
+ sameSite: "Lax",
10079
+ secure: isSecureRequest(c),
10080
+ path: "/",
10081
+ maxAge: authOptions.cookieMaxAgeSeconds
10082
+ });
10083
+ if (wantsAuthJson(c))
10084
+ return c.json({ authenticated: true });
10085
+ return c.redirect("/", 303);
10086
+ });
10087
+ app2.post("/api/auth/logout", (c) => {
10088
+ deleteCookie(c, DASHBOARD_SESSION_COOKIE, { path: "/" });
10089
+ if (wantsAuthJson(c))
10090
+ return c.json({ authenticated: false });
10091
+ return c.redirect("/", 303);
10092
+ });
10093
+ if (authOptions.password) {
10094
+ app2.use("*", async (c, next) => {
10095
+ if (isDashboardAuthenticated(c, authOptions)) {
10096
+ await next();
10097
+ return;
10098
+ }
10099
+ if (isApiRequest(c))
10100
+ return c.json({ error: "Authentication required" }, 401);
10101
+ return c.html(renderLoginPage(), 401);
10102
+ });
10103
+ }
10104
+ app2.route("/api", apiRouter);
10105
+ const uiPath = resolveUiPath();
10106
+ if (fs11.existsSync(uiPath)) {
10107
+ app2.use("/*", serveStatic({ root: uiPath }));
10108
+ }
10109
+ app2.get("*", (c) => {
10110
+ const indexPath = path13.join(uiPath, "index.html");
10111
+ if (fs11.existsSync(indexPath)) {
10112
+ return c.html(fs11.readFileSync(indexPath, "utf-8"));
10113
+ }
10114
+ return c.text('UI not built. Run "npm run build:ui" first.', 404);
10115
+ });
10116
+ return app2;
10117
+ }
10118
+ var app = createDashboardApp();
9115
10119
  var serverInstance = null;
9116
- function startServer(port = 37777) {
10120
+ function startServer(portOrOptions = 37777) {
9117
10121
  if (serverInstance) {
9118
10122
  return serverInstance;
9119
10123
  }
10124
+ const options = normalizeServerOptions(portOrOptions);
10125
+ const hostname = normalizeDashboardHost(options.host);
10126
+ const port = options.port;
9120
10127
  serverInstance = serve({
9121
- fetch: app.fetch,
10128
+ fetch: createDashboardApp(options).fetch,
9122
10129
  port,
9123
- hostname: "127.0.0.1"
10130
+ hostname
9124
10131
  });
9125
- console.log(`\u{1F9E0} Code Memory viewer started at http://localhost:${port}`);
10132
+ console.log(`\u{1F9E0} Code Memory viewer started at http://${displayHost(hostname)}:${port}`);
9126
10133
  return serverInstance;
9127
10134
  }
9128
10135
  function stopServer() {
@@ -9141,12 +10148,14 @@ async function isServerRunning(port = 37777) {
9141
10148
  }
9142
10149
  var isMainModule = process.argv[1]?.includes("server/index") || process.argv[1]?.endsWith("server.js");
9143
10150
  if (isMainModule) {
9144
- const port = parseInt(process.env.PORT || "37777", 10);
9145
- startServer(port);
10151
+ startServer(resolveDashboardServerEnv(process.env));
9146
10152
  }
9147
10153
  export {
9148
10154
  app,
10155
+ createDashboardApp,
9149
10156
  isServerRunning,
10157
+ normalizeDashboardHost,
10158
+ resolveDashboardServerEnv,
9150
10159
  startServer,
9151
10160
  stopServer
9152
10161
  };