claude-memory-layer 1.0.32 → 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.
- package/dist/cli/index.js +1110 -72
- package/dist/cli/index.js.map +4 -4
- package/dist/core/index.js +414 -25
- package/dist/core/index.js.map +2 -2
- package/dist/hooks/post-tool-use.js +416 -27
- package/dist/hooks/post-tool-use.js.map +2 -2
- package/dist/hooks/semantic-daemon.js +416 -27
- package/dist/hooks/semantic-daemon.js.map +2 -2
- package/dist/hooks/session-end.js +416 -27
- package/dist/hooks/session-end.js.map +2 -2
- package/dist/hooks/session-start.js +416 -27
- package/dist/hooks/session-start.js.map +2 -2
- package/dist/hooks/stop.js +416 -27
- package/dist/hooks/stop.js.map +2 -2
- package/dist/hooks/user-prompt-submit.js +504 -34
- package/dist/hooks/user-prompt-submit.js.map +2 -2
- package/dist/index.js +416 -27
- package/dist/index.js.map +2 -2
- package/dist/mcp/index.js +407 -32
- package/dist/mcp/index.js.map +2 -2
- package/dist/server/api/index.js +850 -44
- package/dist/server/api/index.js.map +3 -3
- package/dist/server/index.js +1073 -64
- package/dist/server/index.js.map +3 -3
- package/dist/services/memory-service.js +416 -27
- package/dist/services/memory-service.js.map +2 -2
- package/dist/ui/assets/js/bootstrap.js +2 -0
- package/dist/ui/assets/js/overview.js +166 -3
- package/dist/ui/assets/js/state.js +3 -0
- package/dist/ui/index.html +20 -0
- package/dist/ui/style.css +193 -0
- package/package.json +5 -1
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
|
-
|
|
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
|
|
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 {
|
|
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(
|
|
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:
|
|
4612
|
-
candidateResults:
|
|
4613
|
-
matchResult: this.matcher.matchSearchResults(
|
|
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
|
-
|
|
4677
|
-
let
|
|
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
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
5051
|
+
const normalizedQuery = query.trim();
|
|
5052
|
+
if (rewritten && rewritten !== normalizedQuery) {
|
|
5053
|
+
effectiveQueryText = `${normalizedQuery} ${rewritten}`.trim();
|
|
5054
|
+
queryRewriteKind = "intent-rewrite";
|
|
5055
|
+
rerankQuery = buildRetrievalQualityQuery(effectiveQueryText);
|
|
5056
|
+
const rewrittenResults = await this.searchByStrategy(buildRetrievalQualityQuery(rewritten), {
|
|
4688
5057
|
strategy: "deep",
|
|
4689
5058
|
topK: input.topK,
|
|
4690
5059
|
minScore: Math.max(0.5, input.minScore - 0.1),
|
|
@@ -4711,10 +5080,14 @@ var Retriever = class {
|
|
|
4711
5080
|
});
|
|
4712
5081
|
const top = qualityFiltered.slice(0, input.topK);
|
|
4713
5082
|
const matchResult = this.matcher.matchSearchResults(top, () => 0);
|
|
4714
|
-
return { results: top, candidateResults: qualityFiltered, matchResult };
|
|
5083
|
+
return { results: top, candidateResults: qualityFiltered, matchResult, effectiveQueryText, queryRewriteKind };
|
|
4715
5084
|
}
|
|
4716
5085
|
applyQualityFilters(results, options) {
|
|
4717
5086
|
let filtered = [...results];
|
|
5087
|
+
if (isCurrentStateQuery(options.query)) {
|
|
5088
|
+
filtered = filtered.filter((result) => !isStaleOrSupersededContent(result.content));
|
|
5089
|
+
}
|
|
5090
|
+
filtered = filtered.filter((result) => hasDiscriminativeTermOverlap(options.query, result.content));
|
|
4718
5091
|
if (shouldApplyTechnicalGuard(options.query)) {
|
|
4719
5092
|
filtered = filtered.filter((result) => hasTechnicalTermOverlap(options.query, result.content));
|
|
4720
5093
|
}
|
|
@@ -5022,7 +5395,21 @@ _Context:_ ${sessionContext}`;
|
|
|
5022
5395
|
});
|
|
5023
5396
|
}
|
|
5024
5397
|
tokenize(text) {
|
|
5025
|
-
return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length >= 2).slice(0, 64);
|
|
5398
|
+
return text.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).map((token) => this.normalizeToken(token)).filter((t) => t.length >= 2).slice(0, 64);
|
|
5399
|
+
}
|
|
5400
|
+
normalizeToken(token) {
|
|
5401
|
+
if (token === "apis")
|
|
5402
|
+
return "api";
|
|
5403
|
+
if (token === "ids")
|
|
5404
|
+
return "id";
|
|
5405
|
+
if (token === "does")
|
|
5406
|
+
return token;
|
|
5407
|
+
if (token.length > 4 && token.endsWith("ies"))
|
|
5408
|
+
return `${token.slice(0, -3)}y`;
|
|
5409
|
+
if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") && !token.endsWith("us") && !token.endsWith("is") && !token.endsWith("ps")) {
|
|
5410
|
+
return token.slice(0, -1);
|
|
5411
|
+
}
|
|
5412
|
+
return token;
|
|
5026
5413
|
}
|
|
5027
5414
|
keywordOverlap(a, b) {
|
|
5028
5415
|
if (a.length === 0 || b.length === 0)
|
|
@@ -5085,9 +5472,9 @@ var RetrievalAnalyticsService = class {
|
|
|
5085
5472
|
await this.deps.initialize();
|
|
5086
5473
|
return this.deps.retrievalStore.getHelpfulMemories(limit);
|
|
5087
5474
|
}
|
|
5088
|
-
async getHelpfulnessStats() {
|
|
5475
|
+
async getHelpfulnessStats(since) {
|
|
5089
5476
|
await this.deps.initialize();
|
|
5090
|
-
return this.deps.retrievalStore.getHelpfulnessStats();
|
|
5477
|
+
return this.deps.retrievalStore.getHelpfulnessStats(since);
|
|
5091
5478
|
}
|
|
5092
5479
|
/**
|
|
5093
5480
|
* Extract topic keywords from event content (markdown headings and key terms).
|
|
@@ -5512,7 +5899,9 @@ var RetrievalOrchestrator = class {
|
|
|
5512
5899
|
await this.deps.traceStore.recordRetrievalTrace({
|
|
5513
5900
|
sessionId: options?.sessionId,
|
|
5514
5901
|
projectHash: projectHash || void 0,
|
|
5515
|
-
queryText: query,
|
|
5902
|
+
queryText: result.effectiveQueryText || query,
|
|
5903
|
+
rawQueryText: result.rawQueryText || (result.queryRewriteKind ? query : void 0),
|
|
5904
|
+
queryRewriteKind: result.queryRewriteKind || "none",
|
|
5516
5905
|
strategy: options?.strategy || "auto",
|
|
5517
5906
|
candidateEventIds,
|
|
5518
5907
|
selectedEventIds,
|
|
@@ -7531,8 +7920,8 @@ var MemoryService = class {
|
|
|
7531
7920
|
/**
|
|
7532
7921
|
* Get helpfulness statistics for dashboard
|
|
7533
7922
|
*/
|
|
7534
|
-
async getHelpfulnessStats() {
|
|
7535
|
-
return this.retrievalAnalyticsService.getHelpfulnessStats();
|
|
7923
|
+
async getHelpfulnessStats(since) {
|
|
7924
|
+
return this.retrievalAnalyticsService.getHelpfulnessStats(since);
|
|
7536
7925
|
}
|
|
7537
7926
|
/**
|
|
7538
7927
|
* Mark a consolidated memory as accessed
|
|
@@ -9914,11 +10303,13 @@ async function bootstrapKnowledgeBase(options) {
|
|
|
9914
10303
|
// src/apps/server/index.ts
|
|
9915
10304
|
import { Hono as Hono11 } from "hono";
|
|
9916
10305
|
import { cors } from "hono/cors";
|
|
10306
|
+
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
|
|
9917
10307
|
import { logger } from "hono/logger";
|
|
9918
10308
|
import { serve } from "@hono/node-server";
|
|
9919
10309
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
9920
10310
|
import * as path17 from "path";
|
|
9921
10311
|
import * as fs15 from "fs";
|
|
10312
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
9922
10313
|
import { fileURLToPath as fileUrlToPath } from "url";
|
|
9923
10314
|
|
|
9924
10315
|
// src/apps/server/api/index.ts
|
|
@@ -10360,6 +10751,346 @@ function computeSessionTurnCount(sessionEvents) {
|
|
|
10360
10751
|
return turnIds.size;
|
|
10361
10752
|
return sessionEvents.filter((e) => e.eventType === "user_prompt").length;
|
|
10362
10753
|
}
|
|
10754
|
+
function normalizeQueryRewriteKind2(value) {
|
|
10755
|
+
const normalized = (value || "").trim().toLowerCase();
|
|
10756
|
+
if (normalized === "follow-up-context" || normalized === "intent-rewrite")
|
|
10757
|
+
return normalized;
|
|
10758
|
+
return "none";
|
|
10759
|
+
}
|
|
10760
|
+
function normalizeMetric(value) {
|
|
10761
|
+
const numberValue = Number(value || 0);
|
|
10762
|
+
if (!Number.isFinite(numberValue))
|
|
10763
|
+
return 0;
|
|
10764
|
+
return Math.max(0, Math.min(1, numberValue));
|
|
10765
|
+
}
|
|
10766
|
+
function getTimestampMs(value) {
|
|
10767
|
+
if (value instanceof Date)
|
|
10768
|
+
return value.getTime();
|
|
10769
|
+
if (typeof value === "string") {
|
|
10770
|
+
const parsed = new Date(value).getTime();
|
|
10771
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
10772
|
+
}
|
|
10773
|
+
return 0;
|
|
10774
|
+
}
|
|
10775
|
+
function isRewrittenRetrievalTrace(trace) {
|
|
10776
|
+
return normalizeQueryRewriteKind2(trace.queryRewriteKind) !== "none";
|
|
10777
|
+
}
|
|
10778
|
+
function getTraceSelectedCount(trace) {
|
|
10779
|
+
return Number(trace.selectedCount ?? trace.selectedEventIds?.length ?? 0);
|
|
10780
|
+
}
|
|
10781
|
+
function getTraceCandidateCount(trace) {
|
|
10782
|
+
return Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? trace.candidateDetails?.length ?? 0);
|
|
10783
|
+
}
|
|
10784
|
+
function makeRetrievalReviewItem(trace) {
|
|
10785
|
+
const candidateCount = getTraceCandidateCount(trace);
|
|
10786
|
+
const selectedCount = getTraceSelectedCount(trace);
|
|
10787
|
+
const queryRewriteKind = normalizeQueryRewriteKind2(trace.queryRewriteKind);
|
|
10788
|
+
const rewritten = queryRewriteKind !== "none";
|
|
10789
|
+
const createdAtMs = getTimestampMs(trace.createdAt);
|
|
10790
|
+
const createdAt = createdAtMs > 0 ? new Date(createdAtMs).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
|
|
10791
|
+
let reason = null;
|
|
10792
|
+
let severity = "info";
|
|
10793
|
+
let priority = 0;
|
|
10794
|
+
let title = "";
|
|
10795
|
+
let detail = "";
|
|
10796
|
+
let action = "";
|
|
10797
|
+
if (candidateCount > 0 && selectedCount === 0 && rewritten) {
|
|
10798
|
+
reason = "rewritten-query-no-selection";
|
|
10799
|
+
severity = "warn";
|
|
10800
|
+
priority = 100;
|
|
10801
|
+
title = "Rewritten query selected no memories";
|
|
10802
|
+
detail = `${candidateCount} candidates were found after query rewrite, but no memory was selected.`;
|
|
10803
|
+
action = "Review rewrite wording, rerank scores, and final selection thresholds for this trace.";
|
|
10804
|
+
} else if (candidateCount > 0 && selectedCount === 0) {
|
|
10805
|
+
reason = "candidate-no-selection";
|
|
10806
|
+
severity = "warn";
|
|
10807
|
+
priority = 90;
|
|
10808
|
+
title = "Candidates found but nothing selected";
|
|
10809
|
+
detail = `${candidateCount} candidates were available, but the final selection injected no memory.`;
|
|
10810
|
+
action = "Review rerank thresholds and candidate filtering; consider overfetching before final selection.";
|
|
10811
|
+
} else if (candidateCount === 0) {
|
|
10812
|
+
reason = "empty-candidate-set";
|
|
10813
|
+
severity = "info";
|
|
10814
|
+
priority = 70;
|
|
10815
|
+
title = "Retrieval found no candidates";
|
|
10816
|
+
detail = "The retrieval pipeline returned no candidate memories for this trace.";
|
|
10817
|
+
action = "Check trigger/query rewrite coverage and whether the project has indexed memories for this topic.";
|
|
10818
|
+
} else if (candidateCount >= 10 && safeRatio(selectedCount, candidateCount) < 0.15) {
|
|
10819
|
+
reason = "low-selection-rate";
|
|
10820
|
+
severity = "info";
|
|
10821
|
+
priority = 60;
|
|
10822
|
+
title = "Low selection ratio from many candidates";
|
|
10823
|
+
detail = `${selectedCount} of ${candidateCount} candidates were selected.`;
|
|
10824
|
+
action = "Inspect score distribution and MMR/diversity settings before lowering thresholds.";
|
|
10825
|
+
}
|
|
10826
|
+
if (!reason)
|
|
10827
|
+
return null;
|
|
10828
|
+
return {
|
|
10829
|
+
traceId: trace.traceId || "unknown-trace",
|
|
10830
|
+
reason,
|
|
10831
|
+
severity,
|
|
10832
|
+
priority,
|
|
10833
|
+
title,
|
|
10834
|
+
detail,
|
|
10835
|
+
action,
|
|
10836
|
+
queryRewriteKind,
|
|
10837
|
+
rewritten,
|
|
10838
|
+
strategy: trace.strategy || null,
|
|
10839
|
+
candidateCount,
|
|
10840
|
+
selectedCount,
|
|
10841
|
+
candidateEventIds: (trace.candidateEventIds || []).slice(0, 5),
|
|
10842
|
+
selectedEventIds: (trace.selectedEventIds || []).slice(0, 5),
|
|
10843
|
+
candidateDetails: (trace.candidateDetails || []).slice(0, 3).map((detail2) => ({
|
|
10844
|
+
eventId: detail2.eventId,
|
|
10845
|
+
score: detail2.score,
|
|
10846
|
+
semanticScore: detail2.semanticScore,
|
|
10847
|
+
lexicalScore: detail2.lexicalScore,
|
|
10848
|
+
recencyScore: detail2.recencyScore
|
|
10849
|
+
})),
|
|
10850
|
+
selectedDetails: (trace.selectedDetails || []).slice(0, 3).map((detail2) => ({
|
|
10851
|
+
eventId: detail2.eventId,
|
|
10852
|
+
score: detail2.score,
|
|
10853
|
+
semanticScore: detail2.semanticScore,
|
|
10854
|
+
lexicalScore: detail2.lexicalScore,
|
|
10855
|
+
recencyScore: detail2.recencyScore
|
|
10856
|
+
})),
|
|
10857
|
+
createdAt
|
|
10858
|
+
};
|
|
10859
|
+
}
|
|
10860
|
+
function buildRetrievalReviewQueue(traces, limit) {
|
|
10861
|
+
const reviewItems = traces.map(makeRetrievalReviewItem).filter((item) => item !== null).sort((a, b) => b.priority - a.priority || new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
|
10862
|
+
return {
|
|
10863
|
+
summary: {
|
|
10864
|
+
totalTraces: traces.length,
|
|
10865
|
+
reviewItems: reviewItems.length,
|
|
10866
|
+
returnedItems: Math.min(reviewItems.length, limit),
|
|
10867
|
+
candidateNoSelection: reviewItems.filter((item) => item.reason === "candidate-no-selection").length,
|
|
10868
|
+
emptyCandidateSet: reviewItems.filter((item) => item.reason === "empty-candidate-set").length,
|
|
10869
|
+
rewrittenNoSelection: reviewItems.filter((item) => item.reason === "rewritten-query-no-selection").length,
|
|
10870
|
+
lowSelectionRate: reviewItems.filter((item) => item.reason === "low-selection-rate").length
|
|
10871
|
+
},
|
|
10872
|
+
items: reviewItems.slice(0, limit)
|
|
10873
|
+
};
|
|
10874
|
+
}
|
|
10875
|
+
function parseStatsLimit(value, fallback, max) {
|
|
10876
|
+
if (!value)
|
|
10877
|
+
return fallback;
|
|
10878
|
+
if (!/^\d+$/.test(value))
|
|
10879
|
+
return fallback;
|
|
10880
|
+
const parsed = Number(value);
|
|
10881
|
+
if (!Number.isFinite(parsed) || parsed <= 0)
|
|
10882
|
+
return fallback;
|
|
10883
|
+
return Math.min(parsed, max);
|
|
10884
|
+
}
|
|
10885
|
+
function usefulnessScoreLabel(score, confidence) {
|
|
10886
|
+
if (confidence <= 0)
|
|
10887
|
+
return "unknown";
|
|
10888
|
+
if (score >= 80)
|
|
10889
|
+
return "excellent";
|
|
10890
|
+
if (score >= 60)
|
|
10891
|
+
return "good";
|
|
10892
|
+
if (score >= 40)
|
|
10893
|
+
return "watch";
|
|
10894
|
+
return "low";
|
|
10895
|
+
}
|
|
10896
|
+
function buildMemoryUsefulnessDiagnostics(input) {
|
|
10897
|
+
const { metrics, counts } = input;
|
|
10898
|
+
const diagnostics = [];
|
|
10899
|
+
if (counts.promptCount > 0 && counts.retrievalQueries === 0) {
|
|
10900
|
+
diagnostics.push({
|
|
10901
|
+
key: "no-retrieval-traces",
|
|
10902
|
+
severity: "warn",
|
|
10903
|
+
metric: "retrievalUsageRate",
|
|
10904
|
+
value: 0,
|
|
10905
|
+
target: 0.5,
|
|
10906
|
+
title: "No retrieval traces were recorded",
|
|
10907
|
+
detail: `${counts.promptCount} prompts were seen, but none produced a retrieval trace in this window.`,
|
|
10908
|
+
action: "Confirm the prompt hook is enabled and broaden adherence triggers for continuation, write-intent, and project-specific prompts."
|
|
10909
|
+
});
|
|
10910
|
+
}
|
|
10911
|
+
if (counts.promptCount > 0 && metrics.memoryHitRate < 0.5) {
|
|
10912
|
+
diagnostics.push({
|
|
10913
|
+
key: "low-memory-hit-rate",
|
|
10914
|
+
severity: "warn",
|
|
10915
|
+
metric: "memoryHitRate",
|
|
10916
|
+
value: metrics.memoryHitRate,
|
|
10917
|
+
target: 0.5,
|
|
10918
|
+
title: "Memory checks are missing many prompts",
|
|
10919
|
+
detail: `Only ${counts.memoryCheckedPrompts} of ${counts.promptCount} prompts had an adherence check in this window.`,
|
|
10920
|
+
action: "Broaden adherence triggers for continuation, write-intent, topic-shift, and project-specific prompts."
|
|
10921
|
+
});
|
|
10922
|
+
}
|
|
10923
|
+
if (counts.retrievalQueries > 0 && metrics.queryYieldRate < 0.6) {
|
|
10924
|
+
diagnostics.push({
|
|
10925
|
+
key: "low-query-yield-rate",
|
|
10926
|
+
severity: "warn",
|
|
10927
|
+
metric: "queryYieldRate",
|
|
10928
|
+
value: metrics.queryYieldRate,
|
|
10929
|
+
target: 0.6,
|
|
10930
|
+
title: "Searches often select no memory",
|
|
10931
|
+
detail: `${counts.queriesWithSelected} of ${counts.retrievalQueries} retrieval queries injected at least one memory.`,
|
|
10932
|
+
action: "Overfetch candidates, then filter/rerank before applying the final injection threshold."
|
|
10933
|
+
});
|
|
10934
|
+
}
|
|
10935
|
+
if (counts.totalEvaluated > 0 && metrics.avgHelpfulnessScore < 0.7) {
|
|
10936
|
+
diagnostics.push({
|
|
10937
|
+
key: "low-helpfulness-score",
|
|
10938
|
+
severity: "warn",
|
|
10939
|
+
metric: "avgHelpfulnessScore",
|
|
10940
|
+
value: metrics.avgHelpfulnessScore,
|
|
10941
|
+
target: 0.7,
|
|
10942
|
+
title: "Injected memories are not translating into outcomes",
|
|
10943
|
+
detail: `${counts.totalEvaluated} evaluated retrievals averaged ${(metrics.avgHelpfulnessScore * 100).toFixed(1)}% helpfulness.`,
|
|
10944
|
+
action: "Review low-scoring retrieval samples for stale decisions, cross-project noise, or raw transcript snippets."
|
|
10945
|
+
});
|
|
10946
|
+
}
|
|
10947
|
+
if (counts.totalRetrievals > 0 && metrics.evaluationCoverage < 0.8) {
|
|
10948
|
+
diagnostics.push({
|
|
10949
|
+
key: "low-evaluation-coverage",
|
|
10950
|
+
severity: "info",
|
|
10951
|
+
metric: "evaluationCoverage",
|
|
10952
|
+
value: metrics.evaluationCoverage,
|
|
10953
|
+
target: 0.8,
|
|
10954
|
+
title: "Many retrievals are still unevaluated",
|
|
10955
|
+
detail: `${counts.totalEvaluated} of ${counts.totalRetrievals} retrievals have measured helpfulness.`,
|
|
10956
|
+
action: "Ensure Stop/session-end hooks or pending-session backfill are running so usefulness reflects real outcomes."
|
|
10957
|
+
});
|
|
10958
|
+
}
|
|
10959
|
+
if (counts.candidateMemories > 0 && counts.selectedMemories === 0) {
|
|
10960
|
+
diagnostics.push({
|
|
10961
|
+
key: "candidates-without-selection",
|
|
10962
|
+
severity: "warn",
|
|
10963
|
+
metric: "selectionRate",
|
|
10964
|
+
value: metrics.selectionRate,
|
|
10965
|
+
target: 0.2,
|
|
10966
|
+
title: "Candidates are found but none are injected",
|
|
10967
|
+
detail: `${counts.candidateMemories} candidates were retrieved, but no memories passed the injection policy.`,
|
|
10968
|
+
action: "Inspect threshold settings and prompt-injection policy before lowering filters globally."
|
|
10969
|
+
});
|
|
10970
|
+
}
|
|
10971
|
+
return diagnostics.slice(0, 3);
|
|
10972
|
+
}
|
|
10973
|
+
function computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, limits = {}) {
|
|
10974
|
+
const windowEvents = events.filter((event) => inWindow(event, now, window));
|
|
10975
|
+
const prompts = windowEvents.filter((event) => event.eventType === "user_prompt");
|
|
10976
|
+
const promptCount = prompts.length;
|
|
10977
|
+
const memoryCheckedPrompts = prompts.filter((prompt) => prompt.metadata?.adherence?.checked).length;
|
|
10978
|
+
const windowMs = windowToMs(window);
|
|
10979
|
+
const windowStart = now - windowMs;
|
|
10980
|
+
const windowTraces = traces.filter((trace) => {
|
|
10981
|
+
const ts = getTimestampMs(trace.createdAt);
|
|
10982
|
+
return ts > 0 && ts >= windowStart;
|
|
10983
|
+
});
|
|
10984
|
+
const oldestEventTimestamp = events.reduce((oldest, event) => {
|
|
10985
|
+
const timestamp = event.timestamp?.getTime?.() || 0;
|
|
10986
|
+
return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
|
|
10987
|
+
}, Number.POSITIVE_INFINITY);
|
|
10988
|
+
const oldestTraceTimestamp = traces.reduce((oldest, trace) => {
|
|
10989
|
+
const timestamp = getTimestampMs(trace.createdAt);
|
|
10990
|
+
return timestamp > 0 ? Math.min(oldest, timestamp) : oldest;
|
|
10991
|
+
}, Number.POSITIVE_INFINITY);
|
|
10992
|
+
const eventWindowTruncated = Boolean(
|
|
10993
|
+
limits.eventsLimit && events.length >= limits.eventsLimit && Number.isFinite(oldestEventTimestamp) && oldestEventTimestamp >= windowStart
|
|
10994
|
+
);
|
|
10995
|
+
const traceWindowTruncated = Boolean(
|
|
10996
|
+
limits.tracesLimit && traces.length >= limits.tracesLimit && Number.isFinite(oldestTraceTimestamp) && oldestTraceTimestamp >= windowStart
|
|
10997
|
+
);
|
|
10998
|
+
const retrievalQueries = windowTraces.length;
|
|
10999
|
+
const candidateCounts = windowTraces.map((trace) => Number(trace.candidateCount ?? trace.candidateEventIds?.length ?? 0));
|
|
11000
|
+
const selectedCounts = windowTraces.map((trace) => getTraceSelectedCount(trace));
|
|
11001
|
+
const totalCandidateCount = candidateCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
|
|
11002
|
+
const totalSelectedCount = selectedCounts.reduce((sum, count) => sum + (Number.isFinite(count) ? count : 0), 0);
|
|
11003
|
+
const queriesWithSelected = selectedCounts.filter((count) => Number.isFinite(count) && count > 0).length;
|
|
11004
|
+
const rewrittenTraces = windowTraces.filter(isRewrittenRetrievalTrace);
|
|
11005
|
+
const rawTraces = windowTraces.filter((trace) => !isRewrittenRetrievalTrace(trace));
|
|
11006
|
+
const rewrittenQueries = rewrittenTraces.length;
|
|
11007
|
+
const rawQueries = rawTraces.length;
|
|
11008
|
+
const rewrittenSelectedCount = rewrittenTraces.reduce((sum, trace) => {
|
|
11009
|
+
const selectedCount = getTraceSelectedCount(trace);
|
|
11010
|
+
return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
|
|
11011
|
+
}, 0);
|
|
11012
|
+
const rawSelectedCount = rawTraces.reduce((sum, trace) => {
|
|
11013
|
+
const selectedCount = getTraceSelectedCount(trace);
|
|
11014
|
+
return sum + (Number.isFinite(selectedCount) ? selectedCount : 0);
|
|
11015
|
+
}, 0);
|
|
11016
|
+
const rewrittenQueriesWithSelected = rewrittenTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
|
|
11017
|
+
const rawQueriesWithSelected = rawTraces.filter((trace) => getTraceSelectedCount(trace) > 0).length;
|
|
11018
|
+
const totalEvaluated = Number(helpfulness.totalEvaluated || 0);
|
|
11019
|
+
const totalRetrievals = Number(helpfulness.totalRetrievals || 0);
|
|
11020
|
+
const helpful = Number(helpfulness.helpful || 0);
|
|
11021
|
+
const neutral = Number(helpfulness.neutral || 0);
|
|
11022
|
+
const unhelpful = Number(helpfulness.unhelpful || 0);
|
|
11023
|
+
const retrievalsPerPrompt = safeRatio(retrievalQueries, promptCount);
|
|
11024
|
+
const metrics = {
|
|
11025
|
+
avgHelpfulnessScore: round(normalizeMetric(helpfulness.avgScore)),
|
|
11026
|
+
usefulRecallRate: round(safeRatio(helpful, totalEvaluated)),
|
|
11027
|
+
memoryHitRate: round(safeRatio(memoryCheckedPrompts, promptCount)),
|
|
11028
|
+
retrievalUsageRate: round(Math.min(1, retrievalsPerPrompt)),
|
|
11029
|
+
queryYieldRate: round(safeRatio(queriesWithSelected, retrievalQueries)),
|
|
11030
|
+
evaluationCoverage: round(safeRatio(totalEvaluated, totalRetrievals)),
|
|
11031
|
+
retrievalsPerPrompt: round(retrievalsPerPrompt),
|
|
11032
|
+
avgCandidatesPerQuery: round(safeRatio(totalCandidateCount, retrievalQueries), 2),
|
|
11033
|
+
avgSelectedPerQuery: round(safeRatio(totalSelectedCount, retrievalQueries), 2),
|
|
11034
|
+
selectionRate: round(safeRatio(totalSelectedCount, totalCandidateCount)),
|
|
11035
|
+
queryRewriteRate: round(safeRatio(rewrittenQueries, retrievalQueries)),
|
|
11036
|
+
rewrittenQueryYieldRate: round(safeRatio(rewrittenQueriesWithSelected, rewrittenQueries)),
|
|
11037
|
+
rawQueryYieldRate: round(safeRatio(rawQueriesWithSelected, rawQueries)),
|
|
11038
|
+
avgSelectedPerRewrittenQuery: round(safeRatio(rewrittenSelectedCount, rewrittenQueries), 2),
|
|
11039
|
+
avgSelectedPerRawQuery: round(safeRatio(rawSelectedCount, rawQueries), 2)
|
|
11040
|
+
};
|
|
11041
|
+
const counts = {
|
|
11042
|
+
promptCount,
|
|
11043
|
+
memoryCheckedPrompts,
|
|
11044
|
+
retrievalQueries,
|
|
11045
|
+
queriesWithSelected,
|
|
11046
|
+
rewrittenQueries,
|
|
11047
|
+
rawQueries,
|
|
11048
|
+
rewrittenQueriesWithSelected,
|
|
11049
|
+
rawQueriesWithSelected,
|
|
11050
|
+
selectedMemories: totalSelectedCount,
|
|
11051
|
+
candidateMemories: totalCandidateCount,
|
|
11052
|
+
totalEvaluated,
|
|
11053
|
+
totalRetrievals,
|
|
11054
|
+
helpful,
|
|
11055
|
+
neutral,
|
|
11056
|
+
unhelpful
|
|
11057
|
+
};
|
|
11058
|
+
const componentSpecs = [
|
|
11059
|
+
{ key: "avgHelpfulnessScore", label: "Average helpfulness score", value: metrics.avgHelpfulnessScore, weight: 0.3, available: totalEvaluated > 0 },
|
|
11060
|
+
{ key: "usefulRecallRate", label: "Useful recall rate", value: metrics.usefulRecallRate, weight: 0.25, available: totalEvaluated > 0 },
|
|
11061
|
+
{ key: "memoryHitRate", label: "Memory hit rate", value: metrics.memoryHitRate, weight: 0.2, available: promptCount > 0 },
|
|
11062
|
+
{ key: "retrievalUsageRate", label: "Retrieval usage rate", value: metrics.retrievalUsageRate, weight: 0.15, available: promptCount > 0 },
|
|
11063
|
+
{ key: "queryYieldRate", label: "Query yield rate", value: metrics.queryYieldRate, weight: 0.1, available: retrievalQueries > 0 }
|
|
11064
|
+
];
|
|
11065
|
+
const totalWeight = componentSpecs.reduce((sum, component) => sum + component.weight, 0);
|
|
11066
|
+
const availableWeight = componentSpecs.filter((component) => component.available).reduce((sum, component) => sum + component.weight, 0);
|
|
11067
|
+
const weightedScore = availableWeight > 0 ? componentSpecs.reduce((sum, component) => sum + (component.available ? component.value * component.weight : 0), 0) / availableWeight : 0;
|
|
11068
|
+
const scoreValue = round(weightedScore * 100, 1);
|
|
11069
|
+
const confidence = round(safeRatio(availableWeight, totalWeight), 2);
|
|
11070
|
+
const components = componentSpecs.map((component) => ({
|
|
11071
|
+
...component,
|
|
11072
|
+
contribution: component.available ? round(component.value * component.weight * 100, 2) : 0
|
|
11073
|
+
}));
|
|
11074
|
+
return {
|
|
11075
|
+
window,
|
|
11076
|
+
score: {
|
|
11077
|
+
value: scoreValue,
|
|
11078
|
+
label: usefulnessScoreLabel(scoreValue, confidence),
|
|
11079
|
+
confidence
|
|
11080
|
+
},
|
|
11081
|
+
metrics,
|
|
11082
|
+
counts,
|
|
11083
|
+
components,
|
|
11084
|
+
diagnostics: buildMemoryUsefulnessDiagnostics({ metrics, counts }),
|
|
11085
|
+
limits: {
|
|
11086
|
+
eventsLimit: limits.eventsLimit || events.length,
|
|
11087
|
+
tracesLimit: limits.tracesLimit || traces.length,
|
|
11088
|
+
eventWindowTruncated,
|
|
11089
|
+
traceWindowTruncated
|
|
11090
|
+
},
|
|
11091
|
+
generatedAt: new Date(now).toISOString()
|
|
11092
|
+
};
|
|
11093
|
+
}
|
|
10363
11094
|
function computeKpiMetrics(events, usefulRecallRate) {
|
|
10364
11095
|
const prompts = events.filter((e) => e.eventType === "user_prompt");
|
|
10365
11096
|
const promptCount = prompts.length;
|
|
@@ -10686,6 +11417,32 @@ statsRouter.get("/helpfulness", async (c) => {
|
|
|
10686
11417
|
await memoryService.shutdown();
|
|
10687
11418
|
}
|
|
10688
11419
|
});
|
|
11420
|
+
statsRouter.get("/usefulness", async (c) => {
|
|
11421
|
+
const rawWindow = c.req.query("window") || "7d";
|
|
11422
|
+
const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
|
|
11423
|
+
const memoryService = getLightweightServiceFromQuery(c);
|
|
11424
|
+
try {
|
|
11425
|
+
await memoryService.initialize();
|
|
11426
|
+
const now = Date.now();
|
|
11427
|
+
const eventLimit = 2e4;
|
|
11428
|
+
const traceLimit = 5e3;
|
|
11429
|
+
const windowStart = new Date(now - windowToMs(window));
|
|
11430
|
+
const [events, helpfulness, traces] = await Promise.all([
|
|
11431
|
+
memoryService.getRecentEvents(eventLimit),
|
|
11432
|
+
memoryService.getHelpfulnessStats(windowStart),
|
|
11433
|
+
memoryService.getRecentRetrievalTraces(traceLimit)
|
|
11434
|
+
]);
|
|
11435
|
+
return c.json(computeMemoryUsefulnessSummary(events, helpfulness, traces, now, window, {
|
|
11436
|
+
eventsLimit: eventLimit,
|
|
11437
|
+
tracesLimit: traceLimit
|
|
11438
|
+
}));
|
|
11439
|
+
} catch (error) {
|
|
11440
|
+
console.error("[stats/usefulness] failed to calculate dashboard metrics", error);
|
|
11441
|
+
return c.json({ error: "Unable to calculate memory usefulness statistics" }, 500);
|
|
11442
|
+
} finally {
|
|
11443
|
+
await memoryService.shutdown();
|
|
11444
|
+
}
|
|
11445
|
+
});
|
|
10689
11446
|
statsRouter.get("/retrieval-traces", async (c) => {
|
|
10690
11447
|
const limit = parseInt(c.req.query("limit") || "50", 10);
|
|
10691
11448
|
const memoryService = getServiceFromQuery(c);
|
|
@@ -10695,26 +11452,43 @@ statsRouter.get("/retrieval-traces", async (c) => {
|
|
|
10695
11452
|
const traceStats = await memoryService.getRetrievalTraceStats();
|
|
10696
11453
|
return c.json({
|
|
10697
11454
|
stats: traceStats,
|
|
10698
|
-
traces: traces.map((t) =>
|
|
10699
|
-
|
|
10700
|
-
|
|
10701
|
-
|
|
10702
|
-
|
|
10703
|
-
|
|
10704
|
-
|
|
10705
|
-
|
|
10706
|
-
|
|
10707
|
-
|
|
10708
|
-
|
|
10709
|
-
|
|
10710
|
-
|
|
10711
|
-
|
|
10712
|
-
|
|
10713
|
-
|
|
11455
|
+
traces: traces.map((t) => {
|
|
11456
|
+
const queryRewriteKind = normalizeQueryRewriteKind2(t.queryRewriteKind);
|
|
11457
|
+
return {
|
|
11458
|
+
traceId: t.traceId,
|
|
11459
|
+
sessionId: t.sessionId || null,
|
|
11460
|
+
projectHash: t.projectHash || null,
|
|
11461
|
+
queryRewriteKind,
|
|
11462
|
+
rewritten: queryRewriteKind !== "none",
|
|
11463
|
+
strategy: t.strategy || null,
|
|
11464
|
+
candidateEventIds: t.candidateEventIds,
|
|
11465
|
+
selectedEventIds: t.selectedEventIds,
|
|
11466
|
+
candidateDetails: t.candidateDetails || [],
|
|
11467
|
+
selectedDetails: t.selectedDetails || [],
|
|
11468
|
+
candidateCount: t.candidateCount,
|
|
11469
|
+
selectedCount: t.selectedCount,
|
|
11470
|
+
confidence: t.confidence || null,
|
|
11471
|
+
fallbackTrace: t.fallbackTrace,
|
|
11472
|
+
createdAt: t.createdAt.toISOString()
|
|
11473
|
+
};
|
|
11474
|
+
})
|
|
10714
11475
|
});
|
|
10715
11476
|
} catch (error) {
|
|
10716
11477
|
return c.json({
|
|
10717
|
-
stats: {
|
|
11478
|
+
stats: {
|
|
11479
|
+
totalQueries: 0,
|
|
11480
|
+
avgCandidateCount: 0,
|
|
11481
|
+
avgSelectedCount: 0,
|
|
11482
|
+
selectionRate: 0,
|
|
11483
|
+
rewrittenQueries: 0,
|
|
11484
|
+
rewriteRate: 0,
|
|
11485
|
+
rewrittenQueriesWithSelection: 0,
|
|
11486
|
+
rawQueriesWithSelection: 0,
|
|
11487
|
+
rewrittenSelectionRate: 0,
|
|
11488
|
+
rawSelectionRate: 0,
|
|
11489
|
+
avgSelectedCountForRewrittenQueries: 0,
|
|
11490
|
+
avgSelectedCountForRawQueries: 0
|
|
11491
|
+
},
|
|
10718
11492
|
traces: [],
|
|
10719
11493
|
error: error.message
|
|
10720
11494
|
}, 500);
|
|
@@ -10722,6 +11496,40 @@ statsRouter.get("/retrieval-traces", async (c) => {
|
|
|
10722
11496
|
await memoryService.shutdown();
|
|
10723
11497
|
}
|
|
10724
11498
|
});
|
|
11499
|
+
statsRouter.get("/retrieval-review-queue", async (c) => {
|
|
11500
|
+
const limit = parseStatsLimit(c.req.query("limit"), 10, 50);
|
|
11501
|
+
const scanLimit = parseStatsLimit(c.req.query("scanLimit"), 500, 5e3);
|
|
11502
|
+
const memoryService = getServiceFromQuery(c);
|
|
11503
|
+
try {
|
|
11504
|
+
await memoryService.initialize();
|
|
11505
|
+
const traces = await memoryService.getRecentRetrievalTraces(scanLimit);
|
|
11506
|
+
return c.json({
|
|
11507
|
+
...buildRetrievalReviewQueue(traces, limit),
|
|
11508
|
+
limits: {
|
|
11509
|
+
requestedLimit: limit,
|
|
11510
|
+
scanLimit,
|
|
11511
|
+
scannedTraces: traces.length
|
|
11512
|
+
}
|
|
11513
|
+
});
|
|
11514
|
+
} catch (error) {
|
|
11515
|
+
console.error("Failed to build retrieval review queue");
|
|
11516
|
+
return c.json({
|
|
11517
|
+
summary: {
|
|
11518
|
+
totalTraces: 0,
|
|
11519
|
+
reviewItems: 0,
|
|
11520
|
+
returnedItems: 0,
|
|
11521
|
+
candidateNoSelection: 0,
|
|
11522
|
+
emptyCandidateSet: 0,
|
|
11523
|
+
rewrittenNoSelection: 0,
|
|
11524
|
+
lowSelectionRate: 0
|
|
11525
|
+
},
|
|
11526
|
+
items: [],
|
|
11527
|
+
error: "Unable to build retrieval review queue"
|
|
11528
|
+
}, 500);
|
|
11529
|
+
} finally {
|
|
11530
|
+
await memoryService.shutdown();
|
|
11531
|
+
}
|
|
11532
|
+
});
|
|
10725
11533
|
statsRouter.get("/kpi", async (c) => {
|
|
10726
11534
|
const rawWindow = c.req.query("window") || "7d";
|
|
10727
11535
|
const window = rawWindow === "24h" || rawWindow === "30d" ? rawWindow : "7d";
|
|
@@ -11373,12 +12181,9 @@ healthRouter.get("/", async (c) => {
|
|
|
11373
12181
|
var apiRouter = new Hono10().route("/sessions", sessionsRouter).route("/events", eventsRouter).route("/search", searchRouter).route("/stats", statsRouter).route("/citations", citationsRouter).route("/turns", turnsRouter).route("/projects", projectsRouter).route("/chat", chatRouter).route("/health", healthRouter);
|
|
11374
12182
|
|
|
11375
12183
|
// src/apps/server/index.ts
|
|
11376
|
-
var app = new Hono11();
|
|
11377
12184
|
var moduleDir = path17.dirname(fileUrlToPath(import.meta.url));
|
|
11378
|
-
|
|
11379
|
-
|
|
11380
|
-
app.route("/api", apiRouter);
|
|
11381
|
-
app.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
12185
|
+
var DASHBOARD_SESSION_COOKIE = "cml_dashboard_session";
|
|
12186
|
+
var DEFAULT_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
|
|
11382
12187
|
function resolveUiPath() {
|
|
11383
12188
|
const candidates = [
|
|
11384
12189
|
// Built server: dist/server/index.js -> dist/ui
|
|
@@ -11391,28 +12196,230 @@ function resolveUiPath() {
|
|
|
11391
12196
|
];
|
|
11392
12197
|
return candidates.find((candidate) => fs15.existsSync(path17.join(candidate, "index.html"))) ?? candidates[0];
|
|
11393
12198
|
}
|
|
11394
|
-
|
|
11395
|
-
|
|
11396
|
-
|
|
12199
|
+
function normalizeDashboardHost(host = "localhost") {
|
|
12200
|
+
const normalized = host.trim().toLowerCase();
|
|
12201
|
+
if (normalized === "" || normalized === "localhost" || normalized === "127.0.0.1") {
|
|
12202
|
+
return "127.0.0.1";
|
|
12203
|
+
}
|
|
12204
|
+
if (normalized === "0.0.0.0") {
|
|
12205
|
+
return "0.0.0.0";
|
|
12206
|
+
}
|
|
12207
|
+
throw new Error("Invalid dashboard host: expected localhost, 127.0.0.1, or 0.0.0.0");
|
|
12208
|
+
}
|
|
12209
|
+
function displayHost(hostname2) {
|
|
12210
|
+
return hostname2 === "0.0.0.0" ? "0.0.0.0" : "localhost";
|
|
11397
12211
|
}
|
|
11398
|
-
|
|
11399
|
-
|
|
11400
|
-
|
|
11401
|
-
return c.html(fs15.readFileSync(indexPath, "utf-8"));
|
|
12212
|
+
function normalizeServerOptions(portOrOptions) {
|
|
12213
|
+
if (typeof portOrOptions === "number") {
|
|
12214
|
+
return { port: portOrOptions, host: "localhost" };
|
|
11402
12215
|
}
|
|
11403
|
-
return
|
|
11404
|
-
|
|
12216
|
+
return {
|
|
12217
|
+
port: portOrOptions?.port ?? 37777,
|
|
12218
|
+
host: portOrOptions?.host ?? "localhost",
|
|
12219
|
+
password: portOrOptions?.password,
|
|
12220
|
+
cookieMaxAgeSeconds: portOrOptions?.cookieMaxAgeSeconds,
|
|
12221
|
+
now: portOrOptions?.now
|
|
12222
|
+
};
|
|
12223
|
+
}
|
|
12224
|
+
function parseDashboardServerPort(portOption) {
|
|
12225
|
+
const normalized = (portOption ?? "37777").trim();
|
|
12226
|
+
if (!/^\d+$/.test(normalized)) {
|
|
12227
|
+
throw new Error("Invalid PORT: expected a positive integer");
|
|
12228
|
+
}
|
|
12229
|
+
const port = Number.parseInt(normalized, 10);
|
|
12230
|
+
if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
|
|
12231
|
+
throw new Error("Invalid PORT: expected a TCP port between 1 and 65535");
|
|
12232
|
+
}
|
|
12233
|
+
return port;
|
|
12234
|
+
}
|
|
12235
|
+
function resolveDashboardServerEnv(env) {
|
|
12236
|
+
const hostname2 = normalizeDashboardHost(env.DASHBOARD_HOST ?? "localhost");
|
|
12237
|
+
const password = env.DASHBOARD_PASSWORD || env.CLAUDE_MEMORY_LAYER_DASHBOARD_PASSWORD;
|
|
12238
|
+
return {
|
|
12239
|
+
port: parseDashboardServerPort(env.PORT),
|
|
12240
|
+
host: displayHost(hostname2),
|
|
12241
|
+
password: password || void 0
|
|
12242
|
+
};
|
|
12243
|
+
}
|
|
12244
|
+
function nowSeconds(now) {
|
|
12245
|
+
return Math.floor(now() / 1e3);
|
|
12246
|
+
}
|
|
12247
|
+
function signSessionPayload(payload, password) {
|
|
12248
|
+
return createHmac("sha256", password).update(`claude-memory-layer-dashboard:${payload}`).digest("base64url");
|
|
12249
|
+
}
|
|
12250
|
+
function createDashboardSessionToken(password, now) {
|
|
12251
|
+
const payload = String(nowSeconds(now));
|
|
12252
|
+
return `${payload}.${signSessionPayload(payload, password)}`;
|
|
12253
|
+
}
|
|
12254
|
+
function timingSafeStringEqual(a, b) {
|
|
12255
|
+
const left = Buffer.from(a);
|
|
12256
|
+
const right = Buffer.from(b);
|
|
12257
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
12258
|
+
}
|
|
12259
|
+
function verifyDashboardSessionToken(token, password, maxAgeSeconds, now) {
|
|
12260
|
+
if (!token)
|
|
12261
|
+
return false;
|
|
12262
|
+
const [payload, signature, extra] = token.split(".");
|
|
12263
|
+
if (!payload || !signature || extra !== void 0 || !/^\d+$/.test(payload))
|
|
12264
|
+
return false;
|
|
12265
|
+
const expectedSignature = signSessionPayload(payload, password);
|
|
12266
|
+
if (!timingSafeStringEqual(signature, expectedSignature))
|
|
12267
|
+
return false;
|
|
12268
|
+
const issuedAt = Number.parseInt(payload, 10);
|
|
12269
|
+
const age = nowSeconds(now) - issuedAt;
|
|
12270
|
+
return Number.isSafeInteger(issuedAt) && age >= 0 && age <= maxAgeSeconds;
|
|
12271
|
+
}
|
|
12272
|
+
function isDashboardAuthenticated(c, options) {
|
|
12273
|
+
if (!options.password)
|
|
12274
|
+
return true;
|
|
12275
|
+
return verifyDashboardSessionToken(
|
|
12276
|
+
getCookie(c, DASHBOARD_SESSION_COOKIE),
|
|
12277
|
+
options.password,
|
|
12278
|
+
options.cookieMaxAgeSeconds,
|
|
12279
|
+
options.now
|
|
12280
|
+
);
|
|
12281
|
+
}
|
|
12282
|
+
function isApiRequest(c) {
|
|
12283
|
+
return c.req.path.startsWith("/api/");
|
|
12284
|
+
}
|
|
12285
|
+
function wantsAuthJson(c) {
|
|
12286
|
+
const accept = c.req.header("accept") ?? "";
|
|
12287
|
+
const contentType = c.req.header("content-type") ?? "";
|
|
12288
|
+
return accept.includes("application/json") || contentType.includes("application/json");
|
|
12289
|
+
}
|
|
12290
|
+
function isSecureRequest(c) {
|
|
12291
|
+
const forwardedProto = c.req.header("x-forwarded-proto");
|
|
12292
|
+
return forwardedProto === "https" || c.req.url.startsWith("https://");
|
|
12293
|
+
}
|
|
12294
|
+
function renderLoginPage(message) {
|
|
12295
|
+
const errorBlock = message ? `<div class="error">${message}</div>` : "";
|
|
12296
|
+
return `<!DOCTYPE html>
|
|
12297
|
+
<html lang="en">
|
|
12298
|
+
<head>
|
|
12299
|
+
<meta charset="UTF-8">
|
|
12300
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
12301
|
+
<title>Dashboard Login</title>
|
|
12302
|
+
<style>
|
|
12303
|
+
:root { color-scheme: dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
|
12304
|
+
body { min-height: 100vh; margin: 0; display: grid; place-items: center; background: radial-gradient(circle at top, #243b55 0%, #141e30 42%, #070b12 100%); color: #f8fafc; }
|
|
12305
|
+
.card { width: min(420px, calc(100vw - 40px)); padding: 32px; border: 1px solid rgba(148,163,184,.25); border-radius: 20px; background: rgba(15,23,42,.78); box-shadow: 0 24px 80px rgba(0,0,0,.35); }
|
|
12306
|
+
h1 { margin: 0 0 8px; font-size: 28px; }
|
|
12307
|
+
p { margin: 0 0 24px; color: #cbd5e1; }
|
|
12308
|
+
label { display: block; margin-bottom: 8px; color: #e2e8f0; font-size: 14px; }
|
|
12309
|
+
input { width: 100%; box-sizing: border-box; padding: 12px 14px; border-radius: 12px; border: 1px solid rgba(148,163,184,.35); background: rgba(2,6,23,.72); color: #f8fafc; font-size: 16px; }
|
|
12310
|
+
button { width: 100%; margin-top: 16px; padding: 12px 14px; border: 0; border-radius: 12px; background: linear-gradient(135deg, #38bdf8, #818cf8); color: #020617; font-weight: 700; cursor: pointer; }
|
|
12311
|
+
.error { margin-bottom: 16px; padding: 10px 12px; border-radius: 10px; background: rgba(248,113,113,.14); color: #fecaca; border: 1px solid rgba(248,113,113,.35); }
|
|
12312
|
+
</style>
|
|
12313
|
+
</head>
|
|
12314
|
+
<body>
|
|
12315
|
+
<main class="card">
|
|
12316
|
+
<h1>Dashboard Login</h1>
|
|
12317
|
+
<p>Enter the dashboard password to continue.</p>
|
|
12318
|
+
${errorBlock}
|
|
12319
|
+
<form method="post" action="/api/auth/login">
|
|
12320
|
+
<label for="password">Password</label>
|
|
12321
|
+
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required>
|
|
12322
|
+
<button type="submit">Unlock dashboard</button>
|
|
12323
|
+
</form>
|
|
12324
|
+
</main>
|
|
12325
|
+
</body>
|
|
12326
|
+
</html>`;
|
|
12327
|
+
}
|
|
12328
|
+
async function readSubmittedPassword(c) {
|
|
12329
|
+
const contentType = c.req.header("content-type") ?? "";
|
|
12330
|
+
if (contentType.includes("application/json")) {
|
|
12331
|
+
const body2 = await c.req.json().catch(() => ({}));
|
|
12332
|
+
return typeof body2.password === "string" ? body2.password : "";
|
|
12333
|
+
}
|
|
12334
|
+
const body = await c.req.parseBody().catch(() => ({}));
|
|
12335
|
+
const password = body.password;
|
|
12336
|
+
return typeof password === "string" ? password : "";
|
|
12337
|
+
}
|
|
12338
|
+
function createAuthOptions(options) {
|
|
12339
|
+
return {
|
|
12340
|
+
password: options.password ?? "",
|
|
12341
|
+
cookieMaxAgeSeconds: options.cookieMaxAgeSeconds ?? DEFAULT_SESSION_MAX_AGE_SECONDS,
|
|
12342
|
+
now: options.now ?? Date.now
|
|
12343
|
+
};
|
|
12344
|
+
}
|
|
12345
|
+
function createDashboardApp(options = {}) {
|
|
12346
|
+
const app2 = new Hono11();
|
|
12347
|
+
const authOptions = createAuthOptions(options);
|
|
12348
|
+
app2.use("*", cors());
|
|
12349
|
+
app2.use("*", logger());
|
|
12350
|
+
app2.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
12351
|
+
app2.get("/api/auth/status", (c) => c.json({
|
|
12352
|
+
enabled: Boolean(authOptions.password),
|
|
12353
|
+
authenticated: isDashboardAuthenticated(c, authOptions)
|
|
12354
|
+
}));
|
|
12355
|
+
app2.post("/api/auth/login", async (c) => {
|
|
12356
|
+
if (!authOptions.password) {
|
|
12357
|
+
return c.json({ enabled: false, authenticated: true });
|
|
12358
|
+
}
|
|
12359
|
+
const submittedPassword = await readSubmittedPassword(c);
|
|
12360
|
+
if (!timingSafeStringEqual(submittedPassword, authOptions.password)) {
|
|
12361
|
+
if (wantsAuthJson(c))
|
|
12362
|
+
return c.json({ error: "Invalid password" }, 401);
|
|
12363
|
+
return c.html(renderLoginPage("Invalid password"), 401);
|
|
12364
|
+
}
|
|
12365
|
+
const token = createDashboardSessionToken(authOptions.password, authOptions.now);
|
|
12366
|
+
setCookie(c, DASHBOARD_SESSION_COOKIE, token, {
|
|
12367
|
+
httpOnly: true,
|
|
12368
|
+
sameSite: "Lax",
|
|
12369
|
+
secure: isSecureRequest(c),
|
|
12370
|
+
path: "/",
|
|
12371
|
+
maxAge: authOptions.cookieMaxAgeSeconds
|
|
12372
|
+
});
|
|
12373
|
+
if (wantsAuthJson(c))
|
|
12374
|
+
return c.json({ authenticated: true });
|
|
12375
|
+
return c.redirect("/", 303);
|
|
12376
|
+
});
|
|
12377
|
+
app2.post("/api/auth/logout", (c) => {
|
|
12378
|
+
deleteCookie(c, DASHBOARD_SESSION_COOKIE, { path: "/" });
|
|
12379
|
+
if (wantsAuthJson(c))
|
|
12380
|
+
return c.json({ authenticated: false });
|
|
12381
|
+
return c.redirect("/", 303);
|
|
12382
|
+
});
|
|
12383
|
+
if (authOptions.password) {
|
|
12384
|
+
app2.use("*", async (c, next) => {
|
|
12385
|
+
if (isDashboardAuthenticated(c, authOptions)) {
|
|
12386
|
+
await next();
|
|
12387
|
+
return;
|
|
12388
|
+
}
|
|
12389
|
+
if (isApiRequest(c))
|
|
12390
|
+
return c.json({ error: "Authentication required" }, 401);
|
|
12391
|
+
return c.html(renderLoginPage(), 401);
|
|
12392
|
+
});
|
|
12393
|
+
}
|
|
12394
|
+
app2.route("/api", apiRouter);
|
|
12395
|
+
const uiPath = resolveUiPath();
|
|
12396
|
+
if (fs15.existsSync(uiPath)) {
|
|
12397
|
+
app2.use("/*", serveStatic({ root: uiPath }));
|
|
12398
|
+
}
|
|
12399
|
+
app2.get("*", (c) => {
|
|
12400
|
+
const indexPath = path17.join(uiPath, "index.html");
|
|
12401
|
+
if (fs15.existsSync(indexPath)) {
|
|
12402
|
+
return c.html(fs15.readFileSync(indexPath, "utf-8"));
|
|
12403
|
+
}
|
|
12404
|
+
return c.text('UI not built. Run "npm run build:ui" first.', 404);
|
|
12405
|
+
});
|
|
12406
|
+
return app2;
|
|
12407
|
+
}
|
|
12408
|
+
var app = createDashboardApp();
|
|
11405
12409
|
var serverInstance = null;
|
|
11406
|
-
function startServer(
|
|
12410
|
+
function startServer(portOrOptions = 37777) {
|
|
11407
12411
|
if (serverInstance) {
|
|
11408
12412
|
return serverInstance;
|
|
11409
12413
|
}
|
|
12414
|
+
const options = normalizeServerOptions(portOrOptions);
|
|
12415
|
+
const hostname2 = normalizeDashboardHost(options.host);
|
|
12416
|
+
const port = options.port;
|
|
11410
12417
|
serverInstance = serve({
|
|
11411
|
-
fetch:
|
|
12418
|
+
fetch: createDashboardApp(options).fetch,
|
|
11412
12419
|
port,
|
|
11413
|
-
hostname:
|
|
12420
|
+
hostname: hostname2
|
|
11414
12421
|
});
|
|
11415
|
-
console.log(`\u{1F9E0} Code Memory viewer started at http
|
|
12422
|
+
console.log(`\u{1F9E0} Code Memory viewer started at http://${displayHost(hostname2)}:${port}`);
|
|
11416
12423
|
return serverInstance;
|
|
11417
12424
|
}
|
|
11418
12425
|
function stopServer() {
|
|
@@ -11431,8 +12438,7 @@ async function isServerRunning(port = 37777) {
|
|
|
11431
12438
|
}
|
|
11432
12439
|
var isMainModule = process.argv[1]?.includes("server/index") || process.argv[1]?.endsWith("server.js");
|
|
11433
12440
|
if (isMainModule) {
|
|
11434
|
-
|
|
11435
|
-
startServer(port);
|
|
12441
|
+
startServer(resolveDashboardServerEnv(process.env));
|
|
11436
12442
|
}
|
|
11437
12443
|
|
|
11438
12444
|
// src/core/mongo-sync-worker.ts
|
|
@@ -12327,6 +13333,32 @@ async function runHermesImportOnce(options, deps = realDeps2) {
|
|
|
12327
13333
|
}
|
|
12328
13334
|
}
|
|
12329
13335
|
|
|
13336
|
+
// src/apps/cli/dashboard-command.ts
|
|
13337
|
+
function parseDashboardPort(portOption) {
|
|
13338
|
+
const normalized = (portOption ?? "37777").trim();
|
|
13339
|
+
if (!/^\d+$/.test(normalized)) {
|
|
13340
|
+
throw new Error("Invalid --port: expected a positive integer");
|
|
13341
|
+
}
|
|
13342
|
+
const port = Number.parseInt(normalized, 10);
|
|
13343
|
+
if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
|
|
13344
|
+
throw new Error("Invalid --port: expected a TCP port between 1 and 65535");
|
|
13345
|
+
}
|
|
13346
|
+
return port;
|
|
13347
|
+
}
|
|
13348
|
+
function normalizeDashboardCommandHost(hostOption) {
|
|
13349
|
+
return normalizeDashboardHost(hostOption) === "0.0.0.0" ? "0.0.0.0" : "localhost";
|
|
13350
|
+
}
|
|
13351
|
+
function resolveDashboardCommandOptions(options) {
|
|
13352
|
+
const port = parseDashboardPort(options.port);
|
|
13353
|
+
const host = normalizeDashboardCommandHost(options.host ?? options.bind ?? "localhost");
|
|
13354
|
+
return {
|
|
13355
|
+
port,
|
|
13356
|
+
host,
|
|
13357
|
+
password: options.password,
|
|
13358
|
+
dashboardUrl: `http://localhost:${port}`
|
|
13359
|
+
};
|
|
13360
|
+
}
|
|
13361
|
+
|
|
12330
13362
|
// src/core/external-market-context.ts
|
|
12331
13363
|
var MAX_RENDERED_ITEMS = 8;
|
|
12332
13364
|
var MAX_FRED_SERIES = 10;
|
|
@@ -12937,7 +13969,7 @@ async function runMarketContextCommand(options) {
|
|
|
12937
13969
|
}
|
|
12938
13970
|
}
|
|
12939
13971
|
var program = new Command();
|
|
12940
|
-
program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.
|
|
13972
|
+
program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.33");
|
|
12941
13973
|
program.command("market-context").description("Fetch read-only DART/FRED/Finnhub context with structured MarketContextSnapshot bull/bear/risk/catalyst analysis").option("--company <name>", "Company name for DART fallback search and report subject").option("--dart-corp-code <code>", "Exact DART corp_code for issuer-specific filings").option("--symbol <ticker>", "Listed ticker for Finnhub company profile").option("--providers <list>", "Comma-separated providers: dart,fred,finnhub").option("--fred-series <list>", "Comma-separated FRED series IDs").option("--json", "Print structured JSON including analysis.marketSnapshot").option("--no-snapshot", "Disable MarketContextSnapshot and DART company snapshot analysis").action(async (options) => {
|
|
12942
13974
|
try {
|
|
12943
13975
|
await runMarketContextCommand(options);
|
|
@@ -13873,28 +14905,34 @@ Dry run only. No changes written to ${configPath}`);
|
|
|
13873
14905
|
process.exit(1);
|
|
13874
14906
|
}
|
|
13875
14907
|
});
|
|
13876
|
-
program.command("dashboard").description("Open memory dashboard in browser").option("-p, --port <port>", "Server port", "37777").option("--no-open", "Do not auto-open browser").action(async (options) => {
|
|
13877
|
-
const
|
|
14908
|
+
program.command("dashboard").description("Open memory dashboard in browser").option("-p, --port <port>", "Server port", "37777").option("--bind <host>", "Bind host: localhost (default) or 0.0.0.0").option("--host <host>", "Alias for --bind <host>").option("--password <password>", "Require this password before serving the dashboard").option("--no-open", "Do not auto-open browser").action(async (options) => {
|
|
14909
|
+
const dashboard = resolveDashboardCommandOptions(options);
|
|
14910
|
+
const { port, host, password, dashboardUrl } = dashboard;
|
|
13878
14911
|
try {
|
|
13879
14912
|
const running = await isServerRunning(port);
|
|
13880
14913
|
if (running) {
|
|
13881
14914
|
console.log(`
|
|
13882
|
-
\u{1F9E0} Dashboard already running at
|
|
14915
|
+
\u{1F9E0} Dashboard already running at ${dashboardUrl}
|
|
13883
14916
|
`);
|
|
13884
14917
|
if (options.open) {
|
|
13885
|
-
openBrowser(
|
|
14918
|
+
openBrowser(dashboardUrl);
|
|
13886
14919
|
}
|
|
13887
14920
|
return;
|
|
13888
14921
|
}
|
|
13889
14922
|
console.log("\n\u{1F9E0} Starting Code Memory Dashboard...\n");
|
|
13890
|
-
startServer(port);
|
|
14923
|
+
startServer({ port, host, password });
|
|
13891
14924
|
if (options.open) {
|
|
13892
14925
|
setTimeout(() => {
|
|
13893
|
-
openBrowser(
|
|
14926
|
+
openBrowser(dashboardUrl);
|
|
13894
14927
|
}, 500);
|
|
13895
14928
|
}
|
|
13896
14929
|
console.log(`
|
|
13897
|
-
\u{1F4CA} Dashboard:
|
|
14930
|
+
\u{1F4CA} Dashboard: ${dashboardUrl}`);
|
|
14931
|
+
console.log(`\u{1F50C} Bind: ${host}`);
|
|
14932
|
+
console.log(`\u{1F510} Password: ${password ? "enabled" : "disabled"}`);
|
|
14933
|
+
if (host === "0.0.0.0" && !password) {
|
|
14934
|
+
console.log("\u26A0\uFE0F Bound to 0.0.0.0 without --password; anyone on the reachable network can access it.");
|
|
14935
|
+
}
|
|
13898
14936
|
console.log("Press Ctrl+C to stop the server\n");
|
|
13899
14937
|
const shutdown = () => {
|
|
13900
14938
|
console.log("\n\n\u{1F44B} Shutting down dashboard...");
|