agent-knowledge 1.7.3 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.mcp.json +1 -1
  3. package/CHANGELOG.md +101 -0
  4. package/README.md +43 -18
  5. package/agent-desk-plugin.json +1 -1
  6. package/dist/dashboard.d.ts.map +1 -1
  7. package/dist/dashboard.js +28 -1
  8. package/dist/dashboard.js.map +1 -1
  9. package/dist/knowledge/analyze.d.ts +18 -0
  10. package/dist/knowledge/analyze.d.ts.map +1 -1
  11. package/dist/knowledge/analyze.js +22 -0
  12. package/dist/knowledge/analyze.js.map +1 -1
  13. package/dist/knowledge/freshness.d.ts +99 -0
  14. package/dist/knowledge/freshness.d.ts.map +1 -0
  15. package/dist/knowledge/freshness.js +303 -0
  16. package/dist/knowledge/freshness.js.map +1 -0
  17. package/dist/knowledge/promote.d.ts +145 -0
  18. package/dist/knowledge/promote.d.ts.map +1 -0
  19. package/dist/knowledge/promote.js +532 -0
  20. package/dist/knowledge/promote.js.map +1 -0
  21. package/dist/knowledge/query-log.d.ts +88 -0
  22. package/dist/knowledge/query-log.d.ts.map +1 -0
  23. package/dist/knowledge/query-log.js +207 -0
  24. package/dist/knowledge/query-log.js.map +1 -0
  25. package/dist/knowledge/scoring.d.ts +22 -2
  26. package/dist/knowledge/scoring.d.ts.map +1 -1
  27. package/dist/knowledge/scoring.js +51 -3
  28. package/dist/knowledge/scoring.js.map +1 -1
  29. package/dist/knowledge/search.d.ts +56 -5
  30. package/dist/knowledge/search.d.ts.map +1 -1
  31. package/dist/knowledge/search.js +88 -10
  32. package/dist/knowledge/search.js.map +1 -1
  33. package/dist/knowledge/store.d.ts +12 -0
  34. package/dist/knowledge/store.d.ts.map +1 -1
  35. package/dist/knowledge/store.js +18 -0
  36. package/dist/knowledge/store.js.map +1 -1
  37. package/dist/search/mmr.d.ts +54 -0
  38. package/dist/search/mmr.d.ts.map +1 -0
  39. package/dist/search/mmr.js +138 -0
  40. package/dist/search/mmr.js.map +1 -0
  41. package/dist/server.d.ts +334 -0
  42. package/dist/server.d.ts.map +1 -1
  43. package/dist/server.js +378 -301
  44. package/dist/server.js.map +1 -1
  45. package/dist/sessions/indexer.d.ts.map +1 -1
  46. package/dist/sessions/indexer.js +13 -11
  47. package/dist/sessions/indexer.js.map +1 -1
  48. package/dist/tool-handlers.d.ts +10 -3
  49. package/dist/tool-handlers.d.ts.map +1 -1
  50. package/dist/tool-handlers.js +150 -21
  51. package/dist/tool-handlers.js.map +1 -1
  52. package/dist/ui/app.js +271 -1
  53. package/dist/ui/render-knowledge.js +3 -3
  54. package/dist/ui/styles.css +209 -0
  55. package/dist/wakeup.d.ts +59 -14
  56. package/dist/wakeup.d.ts.map +1 -1
  57. package/dist/wakeup.js +406 -43
  58. package/dist/wakeup.js.map +1 -1
  59. package/docs/ARCHITECTURE.md +31 -6
  60. package/docs/SETUP.md +20 -8
  61. package/docs/USER-MANUAL.md +205 -59
  62. package/docs/hooks.md +81 -21
  63. package/package.json +4 -1
  64. package/scripts/hooks/first-prompt-inject.mjs +230 -0
  65. package/scripts/hooks/precompact-flush.mjs +89 -60
  66. package/scripts/hooks/session-start.js +73 -9
@@ -0,0 +1,532 @@
1
+ /**
2
+ * Scored-and-gated promotion pass.
3
+ *
4
+ * Replaces the regex-only auto-distillation with a scored candidate pipeline.
5
+ * Each project-level insight (extracted by existing distill.ts machinery) is
6
+ * scored on six weighted signals and held against three independent gates.
7
+ * Only candidates that clear ALL gates are promoted to durable knowledge
8
+ * entries.
9
+ *
10
+ * Signal weights (v1.8 starting point — tune against the self-labeled write
11
+ * bench, not by intuition):
12
+ * Relevance 0.30
13
+ * Frequency 0.24
14
+ * Query diversity 0.15
15
+ * Recency 0.15
16
+ * Consolidation 0.10
17
+ * Conceptual richness 0.06
18
+ *
19
+ * Gates (default thresholds; overridable per call):
20
+ * minScore ≥ 0.5
21
+ * minRecallCount ≥ 2 (number of source sessions)
22
+ * minUniqueQueries ≥ 2 (number of distinct topic fingerprints)
23
+ *
24
+ * Grounded rehydration: before promoting, every source session file is
25
+ * checked to still exist on disk. Missing sources ⇒ skip + diary entry.
26
+ * Prevents promoting content the user has since deleted.
27
+ *
28
+ * Evergreen exemption: entries with `evergreen: true` frontmatter are never
29
+ * OVERWRITTEN by promotion — the merger appends a fresh Recent-Activity
30
+ * block below the existing content instead of replacing it.
31
+ *
32
+ * Diary: every run writes `~/agent-knowledge/.dreams/YYYY-MM-DD.md` with per-
33
+ * candidate score breakdown and gate outcomes. The `.`-prefixed directory is
34
+ * git-tracked (audit trail) but excluded from listEntries/search (not part
35
+ * of the retrievable corpus).
36
+ */
37
+ import fs from 'fs';
38
+ import path from 'path';
39
+ import { getProjectDirs, getSessionFiles, parseSessionFile, getSessionMeta, } from '../sessions/parser.js';
40
+ import { getSessionSummary } from '../sessions/summary.js';
41
+ import { listEntries, readEntry, writeEntry, parseFrontmatter } from './store.js';
42
+ import { gitPull, gitPush } from './git.js';
43
+ import { getConfig } from '../types.js';
44
+ import { scrubContent, normalizeProjectName } from './distill.js';
45
+ import { getEntryScoring } from './scoring.js';
46
+ // ── Signal weights ──────────────────────────────────────────────────────────
47
+ export const SIGNAL_WEIGHTS = {
48
+ relevance: 0.3,
49
+ frequency: 0.24,
50
+ queryDiversity: 0.15,
51
+ recency: 0.15,
52
+ consolidation: 0.1,
53
+ conceptualRichness: 0.06,
54
+ };
55
+ export const DEFAULT_GATES = {
56
+ minScore: 0.5,
57
+ minRecallCount: 2,
58
+ minUniqueQueries: 2,
59
+ };
60
+ // ── Cursor (tracks "since when" — reused across runs) ───────────────────────
61
+ function cursorPath() {
62
+ return path.join(getConfig().dataDir, '.knowledge-promote-cursor');
63
+ }
64
+ function readCursor() {
65
+ const p = cursorPath();
66
+ if (!fs.existsSync(p))
67
+ return null;
68
+ try {
69
+ return fs.readFileSync(p, 'utf-8').trim() || null;
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ function writeCursor(iso) {
76
+ try {
77
+ fs.mkdirSync(path.dirname(cursorPath()), { recursive: true });
78
+ fs.writeFileSync(cursorPath(), iso, 'utf-8');
79
+ }
80
+ catch (err) {
81
+ console.error('[promote] failed to write cursor:', err instanceof Error ? err.message : err);
82
+ }
83
+ }
84
+ /**
85
+ * Lowercase + first-3-content-words fingerprint. Used to count unique
86
+ * "queries" (topic openers) that surface the same content.
87
+ */
88
+ function fingerprint(topic) {
89
+ const words = topic
90
+ .toLowerCase()
91
+ .replace(/[^a-z0-9\s]/g, ' ')
92
+ .split(/\s+/)
93
+ .filter((w) => w.length > 2)
94
+ .slice(0, 3);
95
+ return words.join(' ');
96
+ }
97
+ function aggregateSessions(sinceIso) {
98
+ const projects = getProjectDirs();
99
+ const agg = new Map();
100
+ for (const proj of projects) {
101
+ const sessions = getSessionFiles(proj.path);
102
+ for (const sess of sessions) {
103
+ try {
104
+ const entries = parseSessionFile(sess.file);
105
+ if (entries.length === 0)
106
+ continue;
107
+ const meta = getSessionMeta(entries);
108
+ if (meta.startTime === 'unknown')
109
+ continue;
110
+ if (sinceIso && meta.startTime <= sinceIso)
111
+ continue;
112
+ const summary = getSessionSummary(sess.id, proj.name);
113
+ if (!summary)
114
+ continue;
115
+ const humanTopics = summary.topics
116
+ .map((t) => scrubContent(t.content))
117
+ .filter((t) => t.length > 15 && t.length < 500);
118
+ if (humanTopics.length === 0 && summary.toolsUsed.length === 0)
119
+ continue;
120
+ const id = normalizeProjectName(proj.name);
121
+ let a = agg.get(id);
122
+ if (!a) {
123
+ a = {
124
+ id,
125
+ sessionIds: [],
126
+ topics: [],
127
+ topicFingerprints: new Set(),
128
+ tools: new Set(),
129
+ files: new Set(),
130
+ errorPatterns: new Set(),
131
+ gitCommits: new Set(),
132
+ firstSeen: meta.startTime,
133
+ lastSeen: meta.startTime,
134
+ latestSessionFile: sess.file,
135
+ };
136
+ agg.set(id, a);
137
+ }
138
+ a.sessionIds.push(sess.id);
139
+ a.topics.push(...humanTopics.slice(0, 5));
140
+ for (const t of humanTopics)
141
+ a.topicFingerprints.add(fingerprint(t));
142
+ for (const t of summary.toolsUsed)
143
+ a.tools.add(t);
144
+ for (const f of summary.filesModified)
145
+ a.files.add(f);
146
+ for (const e of summary.errorPatterns ?? [])
147
+ a.errorPatterns.add(e);
148
+ for (const c of summary.gitCommits ?? [])
149
+ a.gitCommits.add(c);
150
+ if (meta.startTime < a.firstSeen)
151
+ a.firstSeen = meta.startTime;
152
+ if (meta.startTime > a.lastSeen) {
153
+ a.lastSeen = meta.startTime;
154
+ a.latestSessionFile = sess.file;
155
+ }
156
+ }
157
+ catch (err) {
158
+ console.error('[promote] session aggregate failed:', err instanceof Error ? err.message : err);
159
+ }
160
+ }
161
+ }
162
+ return agg;
163
+ }
164
+ // ── Signal scoring ──────────────────────────────────────────────────────────
165
+ const CODE_FENCE_RE = /```/;
166
+ const DECISION_RE = /\b(decided|chose|chosen|because|rationale|trade.?off|alternative|going\s+with)\b/i;
167
+ const FILE_REF_RE = /(?:\/|\\)[\w.-]+\.(?:ts|tsx|js|jsx|py|rs|go|java|vue|svelte|md|json|yaml|yml)\b/;
168
+ export function computeSignals(a, now) {
169
+ const sessions = a.sessionIds.length;
170
+ // Relevance: proxy via topic-to-tool ratio — candidates with real content
171
+ // relative to tool noise score higher. Normalized by sigmoid-ish cap.
172
+ const toolWeight = Math.max(1, a.tools.size);
173
+ const relevanceRaw = a.topics.length / (a.topics.length + toolWeight);
174
+ const relevance = Math.max(0, Math.min(1, relevanceRaw * 1.5));
175
+ // Frequency: saturates at 5+ contributing sessions.
176
+ const frequency = Math.min(1, sessions / 5);
177
+ // Query diversity: distinct topic-opener fingerprints, saturates at 5+.
178
+ const queryDiversity = Math.min(1, a.topicFingerprints.size / 5);
179
+ // Recency: exponential decay with ~30-day characteristic length.
180
+ const lastMs = new Date(a.lastSeen).getTime();
181
+ const daysAgo = isNaN(lastMs) ? 999 : Math.max(0, (now - lastMs) / (24 * 3600_000));
182
+ const recency = Math.exp(-daysAgo / 30);
183
+ // Consolidation: richness of extracted metadata — files + tools + commits
184
+ // + errors. 20+ distinct items ⇒ max. Noisy single-shot sessions score low.
185
+ const metadataCount = a.files.size + a.tools.size + a.gitCommits.size + a.errorPatterns.size;
186
+ const consolidation = Math.min(1, metadataCount / 20);
187
+ // Conceptual richness: does the topic content look like durable knowledge?
188
+ // Heuristics: code blocks, decision phrases, file references.
189
+ let richScore = 0;
190
+ let richChecks = 0;
191
+ for (const topic of a.topics.slice(0, 10)) {
192
+ richChecks++;
193
+ let hits = 0;
194
+ if (CODE_FENCE_RE.test(topic))
195
+ hits++;
196
+ if (DECISION_RE.test(topic))
197
+ hits++;
198
+ if (FILE_REF_RE.test(topic))
199
+ hits++;
200
+ richScore += Math.min(1, hits / 2); // 2+ hits in a single topic = max
201
+ }
202
+ const conceptualRichness = richChecks === 0 ? 0 : richScore / richChecks;
203
+ return { relevance, frequency, queryDiversity, recency, consolidation, conceptualRichness };
204
+ }
205
+ export function compositeScore(s) {
206
+ return (SIGNAL_WEIGHTS.relevance * s.relevance +
207
+ SIGNAL_WEIGHTS.frequency * s.frequency +
208
+ SIGNAL_WEIGHTS.queryDiversity * s.queryDiversity +
209
+ SIGNAL_WEIGHTS.recency * s.recency +
210
+ SIGNAL_WEIGHTS.consolidation * s.consolidation +
211
+ SIGNAL_WEIGHTS.conceptualRichness * s.conceptualRichness);
212
+ }
213
+ export function evaluateGates(agg, score, thresholds) {
214
+ const minScore = {
215
+ value: score,
216
+ threshold: thresholds.minScore,
217
+ passed: score >= thresholds.minScore,
218
+ };
219
+ const minRecallCount = {
220
+ value: agg.sessionIds.length,
221
+ threshold: thresholds.minRecallCount,
222
+ passed: agg.sessionIds.length >= thresholds.minRecallCount,
223
+ };
224
+ const minUniqueQueries = {
225
+ value: agg.topicFingerprints.size,
226
+ threshold: thresholds.minUniqueQueries,
227
+ passed: agg.topicFingerprints.size >= thresholds.minUniqueQueries,
228
+ };
229
+ return { minScore, minRecallCount, minUniqueQueries };
230
+ }
231
+ // ── Promotion ──────────────────────────────────────────────────────────────
232
+ function buildPromotionBody(agg) {
233
+ const latest = agg.lastSeen.split('T')[0];
234
+ const lines = [];
235
+ lines.push('## Recent Activity');
236
+ lines.push('');
237
+ lines.push(`_Promoted from ${agg.sessionIds.length} session(s) — latest ${latest}. Gates: score, recall, unique-queries — all passed._`);
238
+ lines.push('');
239
+ if (agg.topics.length > 0) {
240
+ lines.push('### Topics Discussed');
241
+ const unique = [...new Set(agg.topics)].slice(0, 15);
242
+ for (const topic of unique) {
243
+ const short = topic.length > 150 ? topic.slice(0, 150) + '...' : topic;
244
+ const safe = scrubContent(short);
245
+ if (safe.length > 10)
246
+ lines.push(`- ${safe}`);
247
+ }
248
+ lines.push('');
249
+ }
250
+ if (agg.tools.size > 0) {
251
+ lines.push('### Tools Used');
252
+ lines.push([...agg.tools].sort().join(', '));
253
+ lines.push('');
254
+ }
255
+ if (agg.files.size > 0) {
256
+ lines.push('### Files Touched');
257
+ const fileList = [...agg.files].sort().slice(0, 30);
258
+ for (const f of fileList)
259
+ lines.push(`- \`${f}\``);
260
+ if (agg.files.size > 30)
261
+ lines.push(`- _...and ${agg.files.size - 30} more_`);
262
+ lines.push('');
263
+ }
264
+ if (agg.gitCommits.size > 0) {
265
+ lines.push('### Commits');
266
+ const commits = [...agg.gitCommits].slice(0, 10);
267
+ lines.push(commits.map((c) => `\`${c}\``).join(', '));
268
+ lines.push('');
269
+ }
270
+ if (agg.errorPatterns.size > 0) {
271
+ lines.push('### Errors Encountered');
272
+ const errors = [...agg.errorPatterns].slice(0, 5);
273
+ for (const e of errors) {
274
+ const safe = scrubContent(e);
275
+ if (safe.length > 10)
276
+ lines.push(`- ${safe}`);
277
+ }
278
+ lines.push('');
279
+ }
280
+ return lines.join('\n');
281
+ }
282
+ function mergeIntoExisting(existingContent, activity) {
283
+ const marker = '## Recent Activity';
284
+ const idx = existingContent.indexOf(marker);
285
+ if (idx >= 0) {
286
+ const nextH2 = existingContent.indexOf('\n## ', idx + marker.length);
287
+ if (nextH2 >= 0) {
288
+ return existingContent.slice(0, idx) + activity + existingContent.slice(nextH2);
289
+ }
290
+ return existingContent.slice(0, idx) + activity;
291
+ }
292
+ return existingContent.trimEnd() + '\n\n' + activity;
293
+ }
294
+ /**
295
+ * Grounded rehydration check: source session file must still exist.
296
+ */
297
+ function sourceStillExists(agg) {
298
+ if (!agg.latestSessionFile)
299
+ return false;
300
+ // Virtual adapter paths (opencode://…) skip the FS check.
301
+ if (!/^[a-zA-Z]+:\/\//.test(agg.latestSessionFile)) {
302
+ if (!fs.existsSync(agg.latestSessionFile))
303
+ return false;
304
+ }
305
+ return true;
306
+ }
307
+ /**
308
+ * Parse the evergreen frontmatter flag. Evergreen entries are never
309
+ * overwritten by promotion — the activity section is appended instead.
310
+ */
311
+ function isEvergreen(memoryDir, entryPath) {
312
+ try {
313
+ const full = path.join(memoryDir, entryPath);
314
+ if (!fs.existsSync(full))
315
+ return false;
316
+ const raw = fs.readFileSync(full, 'utf-8');
317
+ const { meta } = parseFrontmatter(raw);
318
+ const val = meta.evergreen;
319
+ if (typeof val === 'string')
320
+ return val.toLowerCase() === 'true' || val === '1';
321
+ return false;
322
+ }
323
+ catch {
324
+ return false;
325
+ }
326
+ }
327
+ async function applyPromotion(memoryDir, agg) {
328
+ const activity = buildPromotionBody(agg);
329
+ const existing = listEntries(memoryDir, 'projects');
330
+ const entryMap = new Map(existing.map((e) => [
331
+ e.path
332
+ .replace(/^projects\//, '')
333
+ .replace(/\.md$/, '')
334
+ .toLowerCase(),
335
+ e.path,
336
+ ]));
337
+ const existingPath = entryMap.get(agg.id.toLowerCase());
338
+ let writtenPath;
339
+ if (existingPath) {
340
+ const { content } = readEntry(memoryDir, existingPath);
341
+ const merged = isEvergreen(memoryDir, existingPath)
342
+ ? content.trimEnd() + '\n\n' + activity
343
+ : mergeIntoExisting(content, activity);
344
+ const filename = existingPath.replace(/^projects\//, '');
345
+ writeEntry(memoryDir, 'projects', filename, merged);
346
+ writtenPath = existingPath;
347
+ }
348
+ else {
349
+ const filename = `${agg.id}.md`;
350
+ const body = [
351
+ '---',
352
+ `title: ${agg.id}`,
353
+ `tags: [auto-distilled, promoted]`,
354
+ `updated: ${new Date().toISOString().split('T')[0]}`,
355
+ `confidence: inferred`,
356
+ `confidence_score: 0.75`,
357
+ '---',
358
+ '',
359
+ `# ${agg.id}`,
360
+ '',
361
+ activity,
362
+ ].join('\n');
363
+ writeEntry(memoryDir, 'projects', filename, body);
364
+ writtenPath = `projects/${filename}`;
365
+ }
366
+ // v1.8.1: auto-verify promoter output. The promoter writes from CURRENT
367
+ // session activity — by construction the content reflects fresh signal,
368
+ // so the timestamp is the point of promotion itself. This gives retrieval
369
+ // + dashboard a trust anchor without requiring any agent-facing action.
370
+ try {
371
+ getEntryScoring().markVerified(writtenPath);
372
+ }
373
+ catch (err) {
374
+ console.error('[promote] markVerified failed (non-fatal):', err instanceof Error ? err.message : err);
375
+ }
376
+ return writtenPath;
377
+ }
378
+ // ── Diary ──────────────────────────────────────────────────────────────────
379
+ function writeDiary(memoryDir, result, thresholds) {
380
+ const dir = path.join(memoryDir, '.dreams');
381
+ fs.mkdirSync(dir, { recursive: true });
382
+ const date = result.runStartedAt.split('T')[0];
383
+ const file = path.join(dir, `${date}.md`);
384
+ const header = [
385
+ `# Promotion run — ${date}`,
386
+ '',
387
+ `- Started: ${result.runStartedAt}`,
388
+ `- Finished: ${result.runFinishedAt}`,
389
+ `- Mode: **${result.mode}**`,
390
+ `- Thresholds: minScore=${thresholds.minScore}, minRecallCount=${thresholds.minRecallCount}, minUniqueQueries=${thresholds.minUniqueQueries}`,
391
+ `- Totals: ${result.totals.candidates} candidates, ${result.totals.passed} passed, ${result.totals.promoted} promoted, ${result.totals.skipped} skipped`,
392
+ '',
393
+ '## Signal weights',
394
+ '',
395
+ `Relevance ${SIGNAL_WEIGHTS.relevance} · Frequency ${SIGNAL_WEIGHTS.frequency} · QueryDiversity ${SIGNAL_WEIGHTS.queryDiversity} · Recency ${SIGNAL_WEIGHTS.recency} · Consolidation ${SIGNAL_WEIGHTS.consolidation} · ConceptualRichness ${SIGNAL_WEIGHTS.conceptualRichness}`,
396
+ '',
397
+ '## Candidates',
398
+ '',
399
+ ].join('\n');
400
+ const lines = [];
401
+ for (const c of result.candidates) {
402
+ const status = c.promotedPath
403
+ ? `PROMOTED → \`${c.promotedPath}\``
404
+ : c.passed
405
+ ? 'PASSED (mode=explain, not written)'
406
+ : `SKIPPED${c.skipReason ? ' — ' + c.skipReason : ''}`;
407
+ lines.push(`### \`${c.id}\` — score **${c.score.toFixed(3)}** — ${status}`);
408
+ lines.push('');
409
+ lines.push(`- Sessions: ${c.sessionIds.length} (first ${c.firstSeen.split('T')[0]}, last ${c.lastSeen.split('T')[0]})`);
410
+ lines.push(`- Signals: relevance ${c.signals.relevance.toFixed(2)}, frequency ${c.signals.frequency.toFixed(2)}, queryDiversity ${c.signals.queryDiversity.toFixed(2)}, recency ${c.signals.recency.toFixed(2)}, consolidation ${c.signals.consolidation.toFixed(2)}, conceptualRichness ${c.signals.conceptualRichness.toFixed(2)}`);
411
+ const gates = c.gates;
412
+ lines.push(`- Gates: minScore ${gates.minScore.passed ? '✓' : '✗'} (${gates.minScore.value.toFixed(2)}/${gates.minScore.threshold}), minRecallCount ${gates.minRecallCount.passed ? '✓' : '✗'} (${gates.minRecallCount.value}/${gates.minRecallCount.threshold}), minUniqueQueries ${gates.minUniqueQueries.passed ? '✓' : '✗'} (${gates.minUniqueQueries.value}/${gates.minUniqueQueries.threshold})`);
413
+ lines.push('');
414
+ }
415
+ const content = header + lines.join('\n');
416
+ fs.writeFileSync(file, content, 'utf-8');
417
+ return file;
418
+ }
419
+ // ── Main entry point ────────────────────────────────────────────────────────
420
+ export async function promote(options = {}) {
421
+ const mode = options.mode ?? 'explain';
422
+ const thresholds = {
423
+ minScore: options.minScore ?? DEFAULT_GATES.minScore,
424
+ minRecallCount: options.minRecallCount ?? DEFAULT_GATES.minRecallCount,
425
+ minUniqueQueries: options.minUniqueQueries ?? DEFAULT_GATES.minUniqueQueries,
426
+ };
427
+ const writeDiaryEnabled = options.writeDiary ?? true;
428
+ const advanceCursor = options.advanceCursor ?? mode === 'apply';
429
+ const config = getConfig();
430
+ const runStart = new Date();
431
+ const runStartedAt = runStart.toISOString();
432
+ const since = options.sinceIso !== undefined ? options.sinceIso : readCursor();
433
+ const aggregates = aggregateSessions(since);
434
+ if (mode === 'apply') {
435
+ await gitPull(config.memoryDir);
436
+ }
437
+ const now = runStart.getTime();
438
+ const candidates = [];
439
+ const promotedPaths = [];
440
+ const skippedIds = [];
441
+ let maxLastSeen = since ?? '';
442
+ for (const agg of aggregates.values()) {
443
+ if (agg.lastSeen > maxLastSeen)
444
+ maxLastSeen = agg.lastSeen;
445
+ const signals = computeSignals(agg, now);
446
+ const score = compositeScore(signals);
447
+ const gates = evaluateGates(agg, score, thresholds);
448
+ const passed = gates.minScore.passed && gates.minRecallCount.passed && gates.minUniqueQueries.passed;
449
+ const candidate = {
450
+ id: agg.id,
451
+ label: agg.topics[0]?.slice(0, 80) ?? agg.id,
452
+ sessionIds: [...agg.sessionIds],
453
+ firstSeen: agg.firstSeen,
454
+ lastSeen: agg.lastSeen,
455
+ signals,
456
+ score,
457
+ gates,
458
+ passed,
459
+ };
460
+ if (!passed) {
461
+ const reasons = [];
462
+ if (!gates.minScore.passed)
463
+ reasons.push(`score ${score.toFixed(2)} < ${thresholds.minScore}`);
464
+ if (!gates.minRecallCount.passed)
465
+ reasons.push(`sessions ${agg.sessionIds.length} < ${thresholds.minRecallCount}`);
466
+ if (!gates.minUniqueQueries.passed)
467
+ reasons.push(`unique-queries ${agg.topicFingerprints.size} < ${thresholds.minUniqueQueries}`);
468
+ candidate.skipReason = reasons.join('; ');
469
+ candidates.push(candidate);
470
+ skippedIds.push(agg.id);
471
+ continue;
472
+ }
473
+ if (!sourceStillExists(agg)) {
474
+ candidate.skipReason = 'grounded-rehydration: source session file no longer present';
475
+ candidates.push(candidate);
476
+ skippedIds.push(agg.id);
477
+ continue;
478
+ }
479
+ if (mode === 'apply') {
480
+ try {
481
+ const writtenPath = await applyPromotion(config.memoryDir, agg);
482
+ candidate.promotedPath = writtenPath;
483
+ promotedPaths.push(writtenPath);
484
+ }
485
+ catch (err) {
486
+ candidate.skipReason = `write failed: ${err instanceof Error ? err.message : String(err)}`;
487
+ skippedIds.push(agg.id);
488
+ }
489
+ }
490
+ candidates.push(candidate);
491
+ }
492
+ candidates.sort((a, b) => b.score - a.score);
493
+ const runFinishedAt = new Date().toISOString();
494
+ const passedCount = candidates.filter((c) => c.passed).length;
495
+ const result = {
496
+ runStartedAt,
497
+ runFinishedAt,
498
+ mode,
499
+ candidates,
500
+ promotedPaths,
501
+ skippedIds,
502
+ diaryPath: null,
503
+ totals: {
504
+ candidates: candidates.length,
505
+ passed: passedCount,
506
+ promoted: promotedPaths.length,
507
+ skipped: skippedIds.length,
508
+ },
509
+ };
510
+ if (writeDiaryEnabled) {
511
+ try {
512
+ const diary = writeDiary(config.memoryDir, result, thresholds);
513
+ result.diaryPath = diary;
514
+ }
515
+ catch (err) {
516
+ console.error('[promote] diary write failed:', err instanceof Error ? err.message : err);
517
+ }
518
+ }
519
+ if (mode === 'apply' && promotedPaths.length > 0) {
520
+ try {
521
+ await gitPush(config.memoryDir, `promote: ${promotedPaths.length} candidate(s)`);
522
+ }
523
+ catch (err) {
524
+ console.error('[promote] git push failed:', err instanceof Error ? err.message : err);
525
+ }
526
+ }
527
+ if (advanceCursor && maxLastSeen) {
528
+ writeCursor(maxLastSeen);
529
+ }
530
+ return result;
531
+ }
532
+ //# sourceMappingURL=promote.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promote.js","sourceRoot":"","sources":["../../src/knowledge/promote.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI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,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Query log — records every `knowledge_search` call so we can surface
3
+ * zero-result queries as "gap" signals. The single best hint for "what
4
+ * knowledge entries are missing?" is the set of things the agent keeps
5
+ * searching for and not finding.
6
+ *
7
+ * Storage: a `query_log` table inside the existing `knowledge-scores.db`
8
+ * SQLite database (same DB path pattern as `EntryScoring`).
9
+ */
10
+ export interface QueryLogRow {
11
+ id: number;
12
+ query: string;
13
+ project: string | null;
14
+ results_count: number;
15
+ created_at: string;
16
+ }
17
+ export interface SearchGap {
18
+ query: string;
19
+ count: number;
20
+ last_seen: string;
21
+ similar_queries?: string[];
22
+ }
23
+ export interface LogQueryArgs {
24
+ query: string;
25
+ project?: string | null;
26
+ resultsCount: number;
27
+ }
28
+ export interface GetSearchGapsArgs {
29
+ /** ISO timestamp; only queries at or after this time are considered. */
30
+ since?: string;
31
+ /** Minimum occurrence count per group (after similarity merging). Default: 1. */
32
+ minCount?: number;
33
+ /**
34
+ * Jaccard token similarity threshold for merging queries. Default: 0.35.
35
+ *
36
+ * Lower than one might expect because Jaccard on short queries is small:
37
+ * "gitlab credentials" vs "gitlab token" shares 1 content token out of 3,
38
+ * giving 0.33. A threshold of 0.7 would force every zero-result query
39
+ * into its own group — defeating the feature. 0.35 captures obvious
40
+ * topic-overlap while rejecting unrelated queries (Jaccard=0).
41
+ */
42
+ groupSimilarity?: number;
43
+ }
44
+ /**
45
+ * SQLite-backed query log. Tracks `{query, project, results_count,
46
+ * created_at}` for every `knowledge_search` call and exposes a grouped
47
+ * view of zero-result queries.
48
+ */
49
+ export declare class QueryLog {
50
+ private db;
51
+ private dbPath;
52
+ private initialized;
53
+ constructor(dbPath?: string);
54
+ private init;
55
+ /**
56
+ * Insert a single query entry. The query string is scrubbed via
57
+ * `scrubContent` BEFORE insertion to keep secrets out of the log.
58
+ */
59
+ logQuery(args: LogQueryArgs): void;
60
+ /**
61
+ * Return zero-result queries grouped by similarity.
62
+ *
63
+ * Rows are considered zero-result when `results_count == 0`. Groups are
64
+ * formed greedily — iterate rows ordered by most-recent first, and merge
65
+ * into an existing group when `jaccardTokenSim(query, representative) >
66
+ * threshold`.
67
+ *
68
+ * Each returned group carries:
69
+ * - `query`: the most-recent query text in the group
70
+ * - `count`: total number of rows collapsed into the group
71
+ * - `last_seen`: ISO timestamp of the most-recent row
72
+ * - `similar_queries`: other query texts in the group (may be empty)
73
+ */
74
+ getSearchGaps(args?: GetSearchGapsArgs): SearchGap[];
75
+ /** Close the database connection. */
76
+ close(): void;
77
+ }
78
+ export declare function getQueryLog(dbPath?: string): QueryLog;
79
+ /** Reset the singleton (for tests). */
80
+ export declare function resetQueryLog(): void;
81
+ /**
82
+ * Best-effort logging. A log failure must never fail the caller; errors
83
+ * are swallowed and written to stderr.
84
+ */
85
+ export declare function logQuery(args: LogQueryArgs): void;
86
+ /** Thin wrapper around the singleton. */
87
+ export declare function getSearchGaps(args?: GetSearchGapsArgs): SearchGap[];
88
+ //# sourceMappingURL=query-log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-log.d.ts","sourceRoot":"","sources":["../../src/knowledge/query-log.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAcH,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,GA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