claude-memory-layer 1.0.32 → 1.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -9424,7 +9813,8 @@ var HermesSessionHistoryImporter = class {
9424
9813
  source: "hermes",
9425
9814
  hermesSource: session.source,
9426
9815
  sourceSessionId: session.id,
9427
- sourceSessionHash: hashLabel(session.id)
9816
+ sourceSessionHash: hashLabel(session.id),
9817
+ projectPath: effectiveProjectPath
9428
9818
  }
9429
9819
  );
9430
9820
  if (appendResult.success && appendResult.isDuplicate) {
@@ -9461,7 +9851,8 @@ var HermesSessionHistoryImporter = class {
9461
9851
  source: "hermes",
9462
9852
  hermesSource: session.source,
9463
9853
  sourceSessionId: session.id,
9464
- sourceSessionHash: hashLabel(session.id)
9854
+ sourceSessionHash: hashLabel(session.id),
9855
+ projectPath: effectiveProjectPath
9465
9856
  }
9466
9857
  );
9467
9858
  if (appendResult.success && appendResult.isDuplicate) {
@@ -9914,11 +10305,13 @@ async function bootstrapKnowledgeBase(options) {
9914
10305
  // src/apps/server/index.ts
9915
10306
  import { Hono as Hono11 } from "hono";
9916
10307
  import { cors } from "hono/cors";
10308
+ import { getCookie, setCookie, deleteCookie } from "hono/cookie";
9917
10309
  import { logger } from "hono/logger";
9918
10310
  import { serve } from "@hono/node-server";
9919
10311
  import { serveStatic } from "@hono/node-server/serve-static";
9920
10312
  import * as path17 from "path";
9921
10313
  import * as fs15 from "fs";
10314
+ import { createHmac, timingSafeEqual } from "crypto";
9922
10315
  import { fileURLToPath as fileUrlToPath } from "url";
9923
10316
 
9924
10317
  // src/apps/server/api/index.ts
@@ -10360,6 +10753,346 @@ function computeSessionTurnCount(sessionEvents) {
10360
10753
  return turnIds.size;
10361
10754
  return sessionEvents.filter((e) => e.eventType === "user_prompt").length;
10362
10755
  }
10756
+ function normalizeQueryRewriteKind2(value) {
10757
+ const normalized = (value || "").trim().toLowerCase();
10758
+ if (normalized === "follow-up-context" || normalized === "intent-rewrite")
10759
+ return normalized;
10760
+ return "none";
10761
+ }
10762
+ function normalizeMetric(value) {
10763
+ const numberValue = Number(value || 0);
10764
+ if (!Number.isFinite(numberValue))
10765
+ return 0;
10766
+ return Math.max(0, Math.min(1, numberValue));
10767
+ }
10768
+ function getTimestampMs(value) {
10769
+ if (value instanceof Date)
10770
+ return value.getTime();
10771
+ if (typeof value === "string") {
10772
+ const parsed = new Date(value).getTime();
10773
+ return Number.isFinite(parsed) ? parsed : 0;
10774
+ }
10775
+ return 0;
10776
+ }
10777
+ function isRewrittenRetrievalTrace(trace) {
10778
+ return normalizeQueryRewriteKind2(trace.queryRewriteKind) !== "none";
10779
+ }
10780
+ function getTraceSelectedCount(trace) {
10781
+ return Number(trace.selectedCount ?? trace.selectedEventIds?.length ?? 0);
10782
+ }
10783
+ function getTraceCandidateCount(trace) {
10784
+ return Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? trace.candidateDetails?.length ?? 0);
10785
+ }
10786
+ function makeRetrievalReviewItem(trace) {
10787
+ const candidateCount = getTraceCandidateCount(trace);
10788
+ const selectedCount = getTraceSelectedCount(trace);
10789
+ const queryRewriteKind = normalizeQueryRewriteKind2(trace.queryRewriteKind);
10790
+ const rewritten = queryRewriteKind !== "none";
10791
+ const createdAtMs = getTimestampMs(trace.createdAt);
10792
+ const createdAt = createdAtMs > 0 ? new Date(createdAtMs).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
10793
+ let reason = null;
10794
+ let severity = "info";
10795
+ let priority = 0;
10796
+ let title = "";
10797
+ let detail = "";
10798
+ let action = "";
10799
+ if (candidateCount > 0 && selectedCount === 0 && rewritten) {
10800
+ reason = "rewritten-query-no-selection";
10801
+ severity = "warn";
10802
+ priority = 100;
10803
+ title = "Rewritten query selected no memories";
10804
+ detail = `${candidateCount} candidates were found after query rewrite, but no memory was selected.`;
10805
+ action = "Review rewrite wording, rerank scores, and final selection thresholds for this trace.";
10806
+ } else if (candidateCount > 0 && selectedCount === 0) {
10807
+ reason = "candidate-no-selection";
10808
+ severity = "warn";
10809
+ priority = 90;
10810
+ title = "Candidates found but nothing selected";
10811
+ detail = `${candidateCount} candidates were available, but the final selection injected no memory.`;
10812
+ action = "Review rerank thresholds and candidate filtering; consider overfetching before final selection.";
10813
+ } else if (candidateCount === 0) {
10814
+ reason = "empty-candidate-set";
10815
+ severity = "info";
10816
+ priority = 70;
10817
+ title = "Retrieval found no candidates";
10818
+ detail = "The retrieval pipeline returned no candidate memories for this trace.";
10819
+ action = "Check trigger/query rewrite coverage and whether the project has indexed memories for this topic.";
10820
+ } else if (candidateCount >= 10 && safeRatio(selectedCount, candidateCount) < 0.15) {
10821
+ reason = "low-selection-rate";
10822
+ severity = "info";
10823
+ priority = 60;
10824
+ title = "Low selection ratio from many candidates";
10825
+ detail = `${selectedCount} of ${candidateCount} candidates were selected.`;
10826
+ action = "Inspect score distribution and MMR/diversity settings before lowering thresholds.";
10827
+ }
10828
+ if (!reason)
10829
+ return null;
10830
+ return {
10831
+ traceId: trace.traceId || "unknown-trace",
10832
+ reason,
10833
+ severity,
10834
+ priority,
10835
+ title,
10836
+ detail,
10837
+ action,
10838
+ queryRewriteKind,
10839
+ rewritten,
10840
+ strategy: trace.strategy || null,
10841
+ candidateCount,
10842
+ selectedCount,
10843
+ candidateEventIds: (trace.candidateEventIds || []).slice(0, 5),
10844
+ selectedEventIds: (trace.selectedEventIds || []).slice(0, 5),
10845
+ candidateDetails: (trace.candidateDetails || []).slice(0, 3).map((detail2) => ({
10846
+ eventId: detail2.eventId,
10847
+ score: detail2.score,
10848
+ semanticScore: detail2.semanticScore,
10849
+ lexicalScore: detail2.lexicalScore,
10850
+ recencyScore: detail2.recencyScore
10851
+ })),
10852
+ selectedDetails: (trace.selectedDetails || []).slice(0, 3).map((detail2) => ({
10853
+ eventId: detail2.eventId,
10854
+ score: detail2.score,
10855
+ semanticScore: detail2.semanticScore,
10856
+ lexicalScore: detail2.lexicalScore,
10857
+ recencyScore: detail2.recencyScore
10858
+ })),
10859
+ createdAt
10860
+ };
10861
+ }
10862
+ function buildRetrievalReviewQueue(traces, limit) {
10863
+ 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());
10864
+ return {
10865
+ summary: {
10866
+ totalTraces: traces.length,
10867
+ reviewItems: reviewItems.length,
10868
+ returnedItems: Math.min(reviewItems.length, limit),
10869
+ candidateNoSelection: reviewItems.filter((item) => item.reason === "candidate-no-selection").length,
10870
+ emptyCandidateSet: reviewItems.filter((item) => item.reason === "empty-candidate-set").length,
10871
+ rewrittenNoSelection: reviewItems.filter((item) => item.reason === "rewritten-query-no-selection").length,
10872
+ lowSelectionRate: reviewItems.filter((item) => item.reason === "low-selection-rate").length
10873
+ },
10874
+ items: reviewItems.slice(0, limit)
10875
+ };
10876
+ }
10877
+ function parseStatsLimit(value, fallback, max) {
10878
+ if (!value)
10879
+ return fallback;
10880
+ if (!/^\d+$/.test(value))
10881
+ return fallback;
10882
+ const parsed = Number(value);
10883
+ if (!Number.isFinite(parsed) || parsed <= 0)
10884
+ return fallback;
10885
+ return Math.min(parsed, max);
10886
+ }
10887
+ function usefulnessScoreLabel(score, confidence) {
10888
+ if (confidence <= 0)
10889
+ return "unknown";
10890
+ if (score >= 80)
10891
+ return "excellent";
10892
+ if (score >= 60)
10893
+ return "good";
10894
+ if (score >= 40)
10895
+ return "watch";
10896
+ return "low";
10897
+ }
10898
+ function buildMemoryUsefulnessDiagnostics(input) {
10899
+ const { metrics, counts } = input;
10900
+ const diagnostics = [];
10901
+ if (counts.promptCount > 0 && counts.retrievalQueries === 0) {
10902
+ diagnostics.push({
10903
+ key: "no-retrieval-traces",
10904
+ severity: "warn",
10905
+ metric: "retrievalUsageRate",
10906
+ value: 0,
10907
+ target: 0.5,
10908
+ title: "No retrieval traces were recorded",
10909
+ detail: `${counts.promptCount} prompts were seen, but none produced a retrieval trace in this window.`,
10910
+ action: "Confirm the prompt hook is enabled and broaden adherence triggers for continuation, write-intent, and project-specific prompts."
10911
+ });
10912
+ }
10913
+ if (counts.promptCount > 0 && metrics.memoryHitRate < 0.5) {
10914
+ diagnostics.push({
10915
+ key: "low-memory-hit-rate",
10916
+ severity: "warn",
10917
+ metric: "memoryHitRate",
10918
+ value: metrics.memoryHitRate,
10919
+ target: 0.5,
10920
+ title: "Memory checks are missing many prompts",
10921
+ detail: `Only ${counts.memoryCheckedPrompts} of ${counts.promptCount} prompts had an adherence check in this window.`,
10922
+ action: "Broaden adherence triggers for continuation, write-intent, topic-shift, and project-specific prompts."
10923
+ });
10924
+ }
10925
+ if (counts.retrievalQueries > 0 && metrics.queryYieldRate < 0.6) {
10926
+ diagnostics.push({
10927
+ key: "low-query-yield-rate",
10928
+ severity: "warn",
10929
+ metric: "queryYieldRate",
10930
+ value: metrics.queryYieldRate,
10931
+ target: 0.6,
10932
+ title: "Searches often select no memory",
10933
+ detail: `${counts.queriesWithSelected} of ${counts.retrievalQueries} retrieval queries injected at least one memory.`,
10934
+ action: "Overfetch candidates, then filter/rerank before applying the final injection threshold."
10935
+ });
10936
+ }
10937
+ if (counts.totalEvaluated > 0 && metrics.avgHelpfulnessScore < 0.7) {
10938
+ diagnostics.push({
10939
+ key: "low-helpfulness-score",
10940
+ severity: "warn",
10941
+ metric: "avgHelpfulnessScore",
10942
+ value: metrics.avgHelpfulnessScore,
10943
+ target: 0.7,
10944
+ title: "Injected memories are not translating into outcomes",
10945
+ detail: `${counts.totalEvaluated} evaluated retrievals averaged ${(metrics.avgHelpfulnessScore * 100).toFixed(1)}% helpfulness.`,
10946
+ action: "Review low-scoring retrieval samples for stale decisions, cross-project noise, or raw transcript snippets."
10947
+ });
10948
+ }
10949
+ if (counts.totalRetrievals > 0 && metrics.evaluationCoverage < 0.8) {
10950
+ diagnostics.push({
10951
+ key: "low-evaluation-coverage",
10952
+ severity: "info",
10953
+ metric: "evaluationCoverage",
10954
+ value: metrics.evaluationCoverage,
10955
+ target: 0.8,
10956
+ title: "Many retrievals are still unevaluated",
10957
+ detail: `${counts.totalEvaluated} of ${counts.totalRetrievals} retrievals have measured helpfulness.`,
10958
+ action: "Ensure Stop/session-end hooks or pending-session backfill are running so usefulness reflects real outcomes."
10959
+ });
10960
+ }
10961
+ if (counts.candidateMemories > 0 && counts.selectedMemories === 0) {
10962
+ diagnostics.push({
10963
+ key: "candidates-without-selection",
10964
+ severity: "warn",
10965
+ metric: "selectionRate",
10966
+ value: metrics.selectionRate,
10967
+ target: 0.2,
10968
+ title: "Candidates are found but none are injected",
10969
+ detail: `${counts.candidateMemories} candidates were retrieved, but no memories passed the injection policy.`,
10970
+ action: "Inspect threshold settings and prompt-injection policy before lowering filters globally."
10971
+ });
10972
+ }
10973
+ return diagnostics.slice(0, 3);
10974
+ }
10975
+ function computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, limits = {}) {
10976
+ const windowEvents = events.filter((event) => inWindow(event, now, window));
10977
+ const prompts = windowEvents.filter((event) => event.eventType === "user_prompt");
10978
+ const promptCount = prompts.length;
10979
+ const memoryCheckedPrompts = prompts.filter((prompt) => prompt.metadata?.adherence?.checked).length;
10980
+ const windowMs = windowToMs(window);
10981
+ const windowStart = now - windowMs;
10982
+ const windowTraces = traces.filter((trace) => {
10983
+ const ts = getTimestampMs(trace.createdAt);
10984
+ return ts > 0 && ts >= windowStart;
10985
+ });
10986
+ const oldestEventTimestamp = events.reduce((oldest, event) => {
10987
+ const timestamp = event.timestamp?.getTime?.() || 0;
10988
+ return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
10989
+ }, Number.POSITIVE_INFINITY);
10990
+ const oldestTraceTimestamp = traces.reduce((oldest, trace) => {
10991
+ const timestamp = getTimestampMs(trace.createdAt);
10992
+ return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
10993
+ }, Number.POSITIVE_INFINITY);
10994
+ const eventWindowTruncated = Boolean(
10995
+ limits.eventsLimit && events.length >= limits.eventsLimit && Number.isFinite(oldestEventTimestamp) && oldestEventTimestamp >= windowStart
10996
+ );
10997
+ const traceWindowTruncated = Boolean(
10998
+ limits.tracesLimit && traces.length >= limits.tracesLimit && Number.isFinite(oldestTraceTimestamp) && oldestTraceTimestamp >= windowStart
10999
+ );
11000
+ const retrievalQueries = windowTraces.length;
11001
+ const candidateCounts = windowTraces.map((trace) => Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? 0));
11002
+ const selectedCounts = windowTraces.map((trace) => getTraceSelectedCount(trace));
11003
+ const totalCandidateCount = candidateCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
11004
+ const totalSelectedCount = selectedCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
11005
+ const queriesWithSelected = selectedCounts.filter((count) => Number.isFinite(count) && count > 0).length;
11006
+ const rewrittenTraces = windowTraces.filter(isRewrittenRetrievalTrace);
11007
+ const rawTraces = windowTraces.filter((trace) => !isRewrittenRetrievalTrace(trace));
11008
+ const rewrittenQueries = rewrittenTraces.length;
11009
+ const rawQueries = rawTraces.length;
11010
+ const rewrittenSelectedCount = rewrittenTraces.reduce((sum, trace) => {
11011
+ const selectedCount = getTraceSelectedCount(trace);
11012
+ return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
11013
+ }, 0);
11014
+ const rawSelectedCount = rawTraces.reduce((sum, trace) => {
11015
+ const selectedCount = getTraceSelectedCount(trace);
11016
+ return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
11017
+ }, 0);
11018
+ const rewrittenQueriesWithSelected = rewrittenTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
11019
+ const rawQueriesWithSelected = rawTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
11020
+ const totalEvaluated = Number(helpfulness.totalEvaluated || 0);
11021
+ const totalRetrievals = Number(helpfulness.totalRetrievals || 0);
11022
+ const helpful = Number(helpfulness.helpful || 0);
11023
+ const neutral = Number(helpfulness.neutral || 0);
11024
+ const unhelpful = Number(helpfulness.unhelpful || 0);
11025
+ const retrievalsPerPrompt = safeRatio(retrievalQueries, promptCount);
11026
+ const metrics = {
11027
+ avgHelpfulnessScore: round(normalizeMetric(helpfulness.avgScore)),
11028
+ usefulRecallRate: round(safeRatio(helpful, totalEvaluated)),
11029
+ memoryHitRate: round(safeRatio(memoryCheckedPrompts, promptCount)),
11030
+ retrievalUsageRate: round(Math.min(1, retrievalsPerPrompt)),
11031
+ queryYieldRate: round(safeRatio(queriesWithSelected, retrievalQueries)),
11032
+ evaluationCoverage: round(safeRatio(totalEvaluated, totalRetrievals)),
11033
+ retrievalsPerPrompt: round(retrievalsPerPrompt),
11034
+ avgCandidatesPerQuery: round(safeRatio(totalCandidateCount, retrievalQueries), 2),
11035
+ avgSelectedPerQuery: round(safeRatio(totalSelectedCount, retrievalQueries), 2),
11036
+ selectionRate: round(safeRatio(totalSelectedCount, totalCandidateCount)),
11037
+ queryRewriteRate: round(safeRatio(rewrittenQueries, retrievalQueries)),
11038
+ rewrittenQueryYieldRate: round(safeRatio(rewrittenQueriesWithSelected, rewrittenQueries)),
11039
+ rawQueryYieldRate: round(safeRatio(rawQueriesWithSelected, rawQueries)),
11040
+ avgSelectedPerRewrittenQuery: round(safeRatio(rewrittenSelectedCount, rewrittenQueries), 2),
11041
+ avgSelectedPerRawQuery: round(safeRatio(rawSelectedCount, rawQueries), 2)
11042
+ };
11043
+ const counts = {
11044
+ promptCount,
11045
+ memoryCheckedPrompts,
11046
+ retrievalQueries,
11047
+ queriesWithSelected,
11048
+ rewrittenQueries,
11049
+ rawQueries,
11050
+ rewrittenQueriesWithSelected,
11051
+ rawQueriesWithSelected,
11052
+ selectedMemories: totalSelectedCount,
11053
+ candidateMemories: totalCandidateCount,
11054
+ totalEvaluated,
11055
+ totalRetrievals,
11056
+ helpful,
11057
+ neutral,
11058
+ unhelpful
11059
+ };
11060
+ const componentSpecs = [
11061
+ { key: "avgHelpfulnessScore", label: "Average helpfulness score", value: metrics.avgHelpfulnessScore, weight: 0.3, available: totalEvaluated > 0 },
11062
+ { key: "usefulRecallRate", label: "Useful recall rate", value: metrics.usefulRecallRate, weight: 0.25, available: totalEvaluated > 0 },
11063
+ { key: "memoryHitRate", label: "Memory hit rate", value: metrics.memoryHitRate, weight: 0.2, available: promptCount > 0 },
11064
+ { key: "retrievalUsageRate", label: "Retrieval usage rate", value: metrics.retrievalUsageRate, weight: 0.15, available: promptCount > 0 },
11065
+ { key: "queryYieldRate", label: "Query yield rate", value: metrics.queryYieldRate, weight: 0.1, available: retrievalQueries > 0 }
11066
+ ];
11067
+ const totalWeight = componentSpecs.reduce((sum, component) => sum + component.weight, 0);
11068
+ const availableWeight = componentSpecs.filter((component) => component.available).reduce((sum, component) => sum + component.weight, 0);
11069
+ const weightedScore = availableWeight > 0 ? componentSpecs.reduce((sum, component) => sum + (component.available ? component.value * component.weight : 0), 0) / availableWeight : 0;
11070
+ const scoreValue = round(weightedScore * 100, 1);
11071
+ const confidence = round(safeRatio(availableWeight, totalWeight), 2);
11072
+ const components = componentSpecs.map((component) => ({
11073
+ ...component,
11074
+ contribution: component.available ? round(component.value * component.weight * 100, 2) : 0
11075
+ }));
11076
+ return {
11077
+ window,
11078
+ score: {
11079
+ value: scoreValue,
11080
+ label: usefulnessScoreLabel(scoreValue, confidence),
11081
+ confidence
11082
+ },
11083
+ metrics,
11084
+ counts,
11085
+ components,
11086
+ diagnostics: buildMemoryUsefulnessDiagnostics({ metrics, counts }),
11087
+ limits: {
11088
+ eventsLimit: limits.eventsLimit || events.length,
11089
+ tracesLimit: limits.tracesLimit || traces.length,
11090
+ eventWindowTruncated,
11091
+ traceWindowTruncated
11092
+ },
11093
+ generatedAt: new Date(now).toISOString()
11094
+ };
11095
+ }
10363
11096
  function computeKpiMetrics(events, usefulRecallRate) {
10364
11097
  const prompts = events.filter((e) => e.eventType === "user_prompt");
10365
11098
  const promptCount = prompts.length;
@@ -10686,6 +11419,32 @@ statsRouter.get("/helpfulness", async (c) => {
10686
11419
  await memoryService.shutdown();
10687
11420
  }
10688
11421
  });
11422
+ statsRouter.get("/usefulness", async (c) => {
11423
+ const rawWindow = c.req.query("window") || "7d";
11424
+ const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
11425
+ const memoryService = getLightweightServiceFromQuery(c);
11426
+ try {
11427
+ await memoryService.initialize();
11428
+ const now = Date.now();
11429
+ const eventLimit = 2e4;
11430
+ const traceLimit = 5e3;
11431
+ const windowStart = new Date(now - windowToMs(window));
11432
+ const [events, helpfulness, traces] = await Promise.all([
11433
+ memoryService.getRecentEvents(eventLimit),
11434
+ memoryService.getHelpfulnessStats(windowStart),
11435
+ memoryService.getRecentRetrievalTraces(traceLimit)
11436
+ ]);
11437
+ return c.json(computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, {
11438
+ eventsLimit: eventLimit,
11439
+ tracesLimit: traceLimit
11440
+ }));
11441
+ } catch (error) {
11442
+ console.error("[stats/usefulness] failed to calculate dashboard metrics", error);
11443
+ return c.json({ error: "Unable to calculate memory usefulness statistics" }, 500);
11444
+ } finally {
11445
+ await memoryService.shutdown();
11446
+ }
11447
+ });
10689
11448
  statsRouter.get("/retrieval-traces", async (c) => {
10690
11449
  const limit = parseInt(c.req.query("limit") || "50", 10);
10691
11450
  const memoryService = getServiceFromQuery(c);
@@ -10695,26 +11454,43 @@ statsRouter.get("/retrieval-traces", async (c) => {
10695
11454
  const traceStats = await memoryService.getRetrievalTraceStats();
10696
11455
  return c.json({
10697
11456
  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
- }))
11457
+ traces: traces.map((t) => {
11458
+ const queryRewriteKind = normalizeQueryRewriteKind2(t.queryRewriteKind);
11459
+ return {
11460
+ traceId: t.traceId,
11461
+ sessionId: t.sessionId || null,
11462
+ projectHash: t.projectHash || null,
11463
+ queryRewriteKind,
11464
+ rewritten: queryRewriteKind !== "none",
11465
+ strategy: t.strategy || null,
11466
+ candidateEventIds: t.candidateEventIds,
11467
+ selectedEventIds: t.selectedEventIds,
11468
+ candidateDetails: t.candidateDetails || [],
11469
+ selectedDetails: t.selectedDetails || [],
11470
+ candidateCount: t.candidateCount,
11471
+ selectedCount: t.selectedCount,
11472
+ confidence: t.confidence || null,
11473
+ fallbackTrace: t.fallbackTrace,
11474
+ createdAt: t.createdAt.toISOString()
11475
+ };
11476
+ })
10714
11477
  });
10715
11478
  } catch (error) {
10716
11479
  return c.json({
10717
- stats: { totalQueries: 0, avgCandidateCount: 0, avgSelectedCount: 0, selectionRate: 0 },
11480
+ stats: {
11481
+ totalQueries: 0,
11482
+ avgCandidateCount: 0,
11483
+ avgSelectedCount: 0,
11484
+ selectionRate: 0,
11485
+ rewrittenQueries: 0,
11486
+ rewriteRate: 0,
11487
+ rewrittenQueriesWithSelection: 0,
11488
+ rawQueriesWithSelection: 0,
11489
+ rewrittenSelectionRate: 0,
11490
+ rawSelectionRate: 0,
11491
+ avgSelectedCountForRewrittenQueries: 0,
11492
+ avgSelectedCountForRawQueries: 0
11493
+ },
10718
11494
  traces: [],
10719
11495
  error: error.message
10720
11496
  }, 500);
@@ -10722,6 +11498,40 @@ statsRouter.get("/retrieval-traces", async (c) => {
10722
11498
  await memoryService.shutdown();
10723
11499
  }
10724
11500
  });
11501
+ statsRouter.get("/retrieval-review-queue", async (c) => {
11502
+ const limit = parseStatsLimit(c.req.query("limit"), 10, 50);
11503
+ const scanLimit = parseStatsLimit(c.req.query("scanLimit"), 500, 5e3);
11504
+ const memoryService = getServiceFromQuery(c);
11505
+ try {
11506
+ await memoryService.initialize();
11507
+ const traces = await memoryService.getRecentRetrievalTraces(scanLimit);
11508
+ return c.json({
11509
+ ...buildRetrievalReviewQueue(traces, limit),
11510
+ limits: {
11511
+ requestedLimit: limit,
11512
+ scanLimit,
11513
+ scannedTraces: traces.length
11514
+ }
11515
+ });
11516
+ } catch (error) {
11517
+ console.error("Failed to build retrieval review queue");
11518
+ return c.json({
11519
+ summary: {
11520
+ totalTraces: 0,
11521
+ reviewItems: 0,
11522
+ returnedItems: 0,
11523
+ candidateNoSelection: 0,
11524
+ emptyCandidateSet: 0,
11525
+ rewrittenNoSelection: 0,
11526
+ lowSelectionRate: 0
11527
+ },
11528
+ items: [],
11529
+ error: "Unable to build retrieval review queue"
11530
+ }, 500);
11531
+ } finally {
11532
+ await memoryService.shutdown();
11533
+ }
11534
+ });
10725
11535
  statsRouter.get("/kpi", async (c) => {
10726
11536
  const rawWindow = c.req.query("window") || "7d";
10727
11537
  const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
@@ -11373,12 +12183,9 @@ healthRouter.get("/", async (c) => {
11373
12183
  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
12184
 
11375
12185
  // src/apps/server/index.ts
11376
- var app = new Hono11();
11377
12186
  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() }));
12187
+ var DASHBOARD_SESSION_COOKIE = "cml_dashboard_session";
12188
+ var DEFAULT_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
11382
12189
  function resolveUiPath() {
11383
12190
  const candidates = [
11384
12191
  // Built server: dist/server/index.js -> dist/ui
@@ -11391,28 +12198,230 @@ function resolveUiPath() {
11391
12198
  ];
11392
12199
  return candidates.find((candidate) => fs15.existsSync(path17.join(candidate, "index.html"))) ?? candidates[0];
11393
12200
  }
11394
- var uiPath = resolveUiPath();
11395
- if (fs15.existsSync(uiPath)) {
11396
- app.use("/*", serveStatic({ root: uiPath }));
12201
+ function normalizeDashboardHost(host = "localhost") {
12202
+ const normalized = host.trim().toLowerCase();
12203
+ if (normalized === "" || normalized === "localhost" || normalized === "127.0.0.1") {
12204
+ return "127.0.0.1";
12205
+ }
12206
+ if (normalized === "0.0.0.0") {
12207
+ return "0.0.0.0";
12208
+ }
12209
+ throw new Error("Invalid dashboard host: expected localhost, 127.0.0.1, or 0.0.0.0");
12210
+ }
12211
+ function displayHost(hostname2) {
12212
+ return hostname2 === "0.0.0.0" ? "0.0.0.0" : "localhost";
11397
12213
  }
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"));
12214
+ function normalizeServerOptions(portOrOptions) {
12215
+ if (typeof portOrOptions === "number") {
12216
+ return { port: portOrOptions, host: "localhost" };
11402
12217
  }
11403
- return c.text('UI not built. Run "npm run build:ui" first.', 404);
11404
- });
12218
+ return {
12219
+ port: portOrOptions?.port ?? 37777,
12220
+ host: portOrOptions?.host ?? "localhost",
12221
+ password: portOrOptions?.password,
12222
+ cookieMaxAgeSeconds: portOrOptions?.cookieMaxAgeSeconds,
12223
+ now: portOrOptions?.now
12224
+ };
12225
+ }
12226
+ function parseDashboardServerPort(portOption) {
12227
+ const normalized = (portOption ?? "37777").trim();
12228
+ if (!/^\d+$/.test(normalized)) {
12229
+ throw new Error("Invalid PORT: expected a positive integer");
12230
+ }
12231
+ const port = Number.parseInt(normalized, 10);
12232
+ if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
12233
+ throw new Error("Invalid PORT: expected a TCP port between 1 and 65535");
12234
+ }
12235
+ return port;
12236
+ }
12237
+ function resolveDashboardServerEnv(env) {
12238
+ const hostname2 = normalizeDashboardHost(env.DASHBOARD_HOST ?? "localhost");
12239
+ const password = env.DASHBOARD_PASSWORD || env.CLAUDE_MEMORY_LAYER_DASHBOARD_PASSWORD;
12240
+ return {
12241
+ port: parseDashboardServerPort(env.PORT),
12242
+ host: displayHost(hostname2),
12243
+ password: password || void 0
12244
+ };
12245
+ }
12246
+ function nowSeconds(now) {
12247
+ return Math.floor(now() / 1e3);
12248
+ }
12249
+ function signSessionPayload(payload, password) {
12250
+ return createHmac("sha256", password).update(`claude-memory-layer-dashboard:${payload}`).digest("base64url");
12251
+ }
12252
+ function createDashboardSessionToken(password, now) {
12253
+ const payload = String(nowSeconds(now));
12254
+ return `${payload}.${signSessionPayload(payload, password)}`;
12255
+ }
12256
+ function timingSafeStringEqual(a, b) {
12257
+ const left = Buffer.from(a);
12258
+ const right = Buffer.from(b);
12259
+ return left.length === right.length && timingSafeEqual(left, right);
12260
+ }
12261
+ function verifyDashboardSessionToken(token, password, maxAgeSeconds, now) {
12262
+ if (!token)
12263
+ return false;
12264
+ const [payload, signature, extra] = token.split(".");
12265
+ if (!payload || !signature || extra !== void 0 || !/^\d+$/.test(payload))
12266
+ return false;
12267
+ const expectedSignature = signSessionPayload(payload, password);
12268
+ if (!timingSafeStringEqual(signature, expectedSignature))
12269
+ return false;
12270
+ const issuedAt = Number.parseInt(payload, 10);
12271
+ const age = nowSeconds(now) - issuedAt;
12272
+ return Number.isSafeInteger(issuedAt) && age >= 0 && age <= maxAgeSeconds;
12273
+ }
12274
+ function isDashboardAuthenticated(c, options) {
12275
+ if (!options.password)
12276
+ return true;
12277
+ return verifyDashboardSessionToken(
12278
+ getCookie(c, DASHBOARD_SESSION_COOKIE),
12279
+ options.password,
12280
+ options.cookieMaxAgeSeconds,
12281
+ options.now
12282
+ );
12283
+ }
12284
+ function isApiRequest(c) {
12285
+ return c.req.path.startsWith("/api/");
12286
+ }
12287
+ function wantsAuthJson(c) {
12288
+ const accept = c.req.header("accept") ?? "";
12289
+ const contentType = c.req.header("content-type") ?? "";
12290
+ return accept.includes("application/json") || contentType.includes("application/json");
12291
+ }
12292
+ function isSecureRequest(c) {
12293
+ const forwardedProto = c.req.header("x-forwarded-proto");
12294
+ return forwardedProto === "https" || c.req.url.startsWith("https://");
12295
+ }
12296
+ function renderLoginPage(message) {
12297
+ const errorBlock = message ? `<div class="error">${message}</div>` : "";
12298
+ return `<!DOCTYPE html>
12299
+ <html lang="en">
12300
+ <head>
12301
+ <meta charset="UTF-8">
12302
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
12303
+ <title>Dashboard Login</title>
12304
+ <style>
12305
+ :root { color-scheme: dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
12306
+ 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; }
12307
+ .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); }
12308
+ h1 { margin: 0 0 8px; font-size: 28px; }
12309
+ p { margin: 0 0 24px; color: #cbd5e1; }
12310
+ label { display: block; margin-bottom: 8px; color: #e2e8f0; font-size: 14px; }
12311
+ 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; }
12312
+ 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; }
12313
+ .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); }
12314
+ </style>
12315
+ </head>
12316
+ <body>
12317
+ <main class="card">
12318
+ <h1>Dashboard Login</h1>
12319
+ <p>Enter the dashboard password to continue.</p>
12320
+ ${errorBlock}
12321
+ <form method="post" action="/api/auth/login">
12322
+ <label for="password">Password</label>
12323
+ <input id="password" name="password" type="password" autocomplete="current-password" autofocus required>
12324
+ <button type="submit">Unlock dashboard</button>
12325
+ </form>
12326
+ </main>
12327
+ </body>
12328
+ </html>`;
12329
+ }
12330
+ async function readSubmittedPassword(c) {
12331
+ const contentType = c.req.header("content-type") ?? "";
12332
+ if (contentType.includes("application/json")) {
12333
+ const body2 = await c.req.json().catch(() => ({}));
12334
+ return typeof body2.password === "string" ? body2.password : "";
12335
+ }
12336
+ const body = await c.req.parseBody().catch(() => ({}));
12337
+ const password = body.password;
12338
+ return typeof password === "string" ? password : "";
12339
+ }
12340
+ function createAuthOptions(options) {
12341
+ return {
12342
+ password: options.password ?? "",
12343
+ cookieMaxAgeSeconds: options.cookieMaxAgeSeconds ?? DEFAULT_SESSION_MAX_AGE_SECONDS,
12344
+ now: options.now ?? Date.now
12345
+ };
12346
+ }
12347
+ function createDashboardApp(options = {}) {
12348
+ const app2 = new Hono11();
12349
+ const authOptions = createAuthOptions(options);
12350
+ app2.use("*", cors());
12351
+ app2.use("*", logger());
12352
+ app2.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
12353
+ app2.get("/api/auth/status", (c) => c.json({
12354
+ enabled: Boolean(authOptions.password),
12355
+ authenticated: isDashboardAuthenticated(c, authOptions)
12356
+ }));
12357
+ app2.post("/api/auth/login", async (c) => {
12358
+ if (!authOptions.password) {
12359
+ return c.json({ enabled: false, authenticated: true });
12360
+ }
12361
+ const submittedPassword = await readSubmittedPassword(c);
12362
+ if (!timingSafeStringEqual(submittedPassword, authOptions.password)) {
12363
+ if (wantsAuthJson(c))
12364
+ return c.json({ error: "Invalid password" }, 401);
12365
+ return c.html(renderLoginPage("Invalid password"), 401);
12366
+ }
12367
+ const token = createDashboardSessionToken(authOptions.password, authOptions.now);
12368
+ setCookie(c, DASHBOARD_SESSION_COOKIE, token, {
12369
+ httpOnly: true,
12370
+ sameSite: "Lax",
12371
+ secure: isSecureRequest(c),
12372
+ path: "/",
12373
+ maxAge: authOptions.cookieMaxAgeSeconds
12374
+ });
12375
+ if (wantsAuthJson(c))
12376
+ return c.json({ authenticated: true });
12377
+ return c.redirect("/", 303);
12378
+ });
12379
+ app2.post("/api/auth/logout", (c) => {
12380
+ deleteCookie(c, DASHBOARD_SESSION_COOKIE, { path: "/" });
12381
+ if (wantsAuthJson(c))
12382
+ return c.json({ authenticated: false });
12383
+ return c.redirect("/", 303);
12384
+ });
12385
+ if (authOptions.password) {
12386
+ app2.use("*", async (c, next) => {
12387
+ if (isDashboardAuthenticated(c, authOptions)) {
12388
+ await next();
12389
+ return;
12390
+ }
12391
+ if (isApiRequest(c))
12392
+ return c.json({ error: "Authentication required" }, 401);
12393
+ return c.html(renderLoginPage(), 401);
12394
+ });
12395
+ }
12396
+ app2.route("/api", apiRouter);
12397
+ const uiPath = resolveUiPath();
12398
+ if (fs15.existsSync(uiPath)) {
12399
+ app2.use("/*", serveStatic({ root: uiPath }));
12400
+ }
12401
+ app2.get("*", (c) => {
12402
+ const indexPath = path17.join(uiPath, "index.html");
12403
+ if (fs15.existsSync(indexPath)) {
12404
+ return c.html(fs15.readFileSync(indexPath, "utf-8"));
12405
+ }
12406
+ return c.text('UI not built. Run "npm run build:ui" first.', 404);
12407
+ });
12408
+ return app2;
12409
+ }
12410
+ var app = createDashboardApp();
11405
12411
  var serverInstance = null;
11406
- function startServer(port = 37777) {
12412
+ function startServer(portOrOptions = 37777) {
11407
12413
  if (serverInstance) {
11408
12414
  return serverInstance;
11409
12415
  }
12416
+ const options = normalizeServerOptions(portOrOptions);
12417
+ const hostname2 = normalizeDashboardHost(options.host);
12418
+ const port = options.port;
11410
12419
  serverInstance = serve({
11411
- fetch: app.fetch,
12420
+ fetch: createDashboardApp(options).fetch,
11412
12421
  port,
11413
- hostname: "127.0.0.1"
12422
+ hostname: hostname2
11414
12423
  });
11415
- console.log(`\u{1F9E0} Code Memory viewer started at http://localhost:${port}`);
12424
+ console.log(`\u{1F9E0} Code Memory viewer started at http://${displayHost(hostname2)}:${port}`);
11416
12425
  return serverInstance;
11417
12426
  }
11418
12427
  function stopServer() {
@@ -11431,8 +12440,7 @@ async function isServerRunning(port = 37777) {
11431
12440
  }
11432
12441
  var isMainModule = process.argv[1]?.includes("server/index") || process.argv[1]?.endsWith("server.js");
11433
12442
  if (isMainModule) {
11434
- const port = parseInt(process.env.PORT || "37777", 10);
11435
- startServer(port);
12443
+ startServer(resolveDashboardServerEnv(process.env));
11436
12444
  }
11437
12445
 
11438
12446
  // src/core/mongo-sync-worker.ts
@@ -12327,6 +13335,32 @@ async function runHermesImportOnce(options, deps = realDeps2) {
12327
13335
  }
12328
13336
  }
12329
13337
 
13338
+ // src/apps/cli/dashboard-command.ts
13339
+ function parseDashboardPort(portOption) {
13340
+ const normalized = (portOption ?? "37777").trim();
13341
+ if (!/^\d+$/.test(normalized)) {
13342
+ throw new Error("Invalid --port: expected a positive integer");
13343
+ }
13344
+ const port = Number.parseInt(normalized, 10);
13345
+ if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
13346
+ throw new Error("Invalid --port: expected a TCP port between 1 and 65535");
13347
+ }
13348
+ return port;
13349
+ }
13350
+ function normalizeDashboardCommandHost(hostOption) {
13351
+ return normalizeDashboardHost(hostOption) === "0.0.0.0" ? "0.0.0.0" : "localhost";
13352
+ }
13353
+ function resolveDashboardCommandOptions(options) {
13354
+ const port = parseDashboardPort(options.port);
13355
+ const host = normalizeDashboardCommandHost(options.host ?? options.bind ?? "localhost");
13356
+ return {
13357
+ port,
13358
+ host,
13359
+ password: options.password,
13360
+ dashboardUrl: `http://localhost:${port}`
13361
+ };
13362
+ }
13363
+
12330
13364
  // src/core/external-market-context.ts
12331
13365
  var MAX_RENDERED_ITEMS = 8;
12332
13366
  var MAX_FRED_SERIES = 10;
@@ -12937,7 +13971,7 @@ async function runMarketContextCommand(options) {
12937
13971
  }
12938
13972
  }
12939
13973
  var program = new Command();
12940
- program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.32");
13974
+ program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.34");
12941
13975
  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
13976
  try {
12943
13977
  await runMarketContextCommand(options);
@@ -13873,28 +14907,34 @@ Dry run only. No changes written to ${configPath}`);
13873
14907
  process.exit(1);
13874
14908
  }
13875
14909
  });
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);
14910
+ 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) => {
14911
+ const dashboard = resolveDashboardCommandOptions(options);
14912
+ const { port, host, password, dashboardUrl } = dashboard;
13878
14913
  try {
13879
14914
  const running = await isServerRunning(port);
13880
14915
  if (running) {
13881
14916
  console.log(`
13882
- \u{1F9E0} Dashboard already running at http://localhost:${port}
14917
+ \u{1F9E0} Dashboard already running at ${dashboardUrl}
13883
14918
  `);
13884
14919
  if (options.open) {
13885
- openBrowser(`http://localhost:${port}`);
14920
+ openBrowser(dashboardUrl);
13886
14921
  }
13887
14922
  return;
13888
14923
  }
13889
14924
  console.log("\n\u{1F9E0} Starting Code Memory Dashboard...\n");
13890
- startServer(port);
14925
+ startServer({ port, host, password });
13891
14926
  if (options.open) {
13892
14927
  setTimeout(() => {
13893
- openBrowser(`http://localhost:${port}`);
14928
+ openBrowser(dashboardUrl);
13894
14929
  }, 500);
13895
14930
  }
13896
14931
  console.log(`
13897
- \u{1F4CA} Dashboard: http://localhost:${port}`);
14932
+ \u{1F4CA} Dashboard: ${dashboardUrl}`);
14933
+ console.log(`\u{1F50C} Bind: ${host}`);
14934
+ console.log(`\u{1F510} Password: ${password ? "enabled" : "disabled"}`);
14935
+ if (host === "0.0.0.0" && !password) {
14936
+ console.log("\u26A0\uFE0F Bound to 0.0.0.0 without --password; anyone on the reachable network can access it.");
14937
+ }
13898
14938
  console.log("Press Ctrl+C to stop the server\n");
13899
14939
  const shutdown = () => {
13900
14940
  console.log("\n\n\u{1F44B} Shutting down dashboard...");