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
package/dist/wakeup.js CHANGED
@@ -1,27 +1,45 @@
1
1
  /**
2
- * wakeup — return a tiny "L0 + L1" context blob at session start.
2
+ * wakeup — return a token-budgeted context blob at session start.
3
3
  *
4
- * Exposed via the MCP `knowledge` tool as `action: "wakeup"` (no separate tool).
4
+ * v1.8.1: evolved from a flat top-K renderer into a section-priority
5
+ * context packer. `buildContextBundle` assembles a multi-section blob
6
+ * (identity, active_tasks, recent_decisions, known_gotchas,
7
+ * last_session_summary, top_weighted, semantic_fallback) where each
8
+ * section gets its own per-section budget and the packer greedily fills
9
+ * top-to-bottom until the global token budget is hit.
5
10
  *
6
- * Layered-memory model:
7
- * L0 = identity (~100 tokens, always loaded, plain text)
8
- * L1 = essential facts — top-N highest-weight knowledge entries
11
+ * `wakeup()` is retained as a thin backwards-compatibility wrapper: when
12
+ * called with only `tokenBudget` + `scope` (no `sections`), it routes to
13
+ * the `top_weighted` section alone, producing output shape-compatible
14
+ * with v1.8.0.
9
15
  *
10
- * The whole blob is bounded by a token budget (chars/4 estimate). Designed
11
- * to be called once at session start so the agent has a small but well-chosen
12
- * window into the user's world before it ever issues a real search.
16
+ * Exposed via the MCP `knowledge` tool as `action: "wakeup"`.
13
17
  */
14
18
  import fs from 'fs';
15
19
  import path from 'path';
16
20
  import { listEntries, readEntry } from './knowledge/store.js';
17
21
  import { getConfig } from './types.js';
22
+ import { listSessions } from './sessions/summary.js';
23
+ import { getEntryScoring } from './knowledge/scoring.js';
24
+ export const DEFAULT_SECTIONS = [
25
+ 'identity',
26
+ 'active_tasks',
27
+ 'recent_decisions',
28
+ 'known_gotchas',
29
+ 'last_session_summary',
30
+ 'top_weighted',
31
+ 'semantic_fallback',
32
+ ];
33
+ // ── Constants ───────────────────────────────────────────────────────────────
18
34
  const DEFAULT_BUDGET = 800;
19
35
  const CHARS_PER_TOKEN = 4;
20
36
  const L1_EXCERPT_CHARS = 240;
37
+ const SECTION_EXCERPT_CHARS = 200;
21
38
  const DEFAULT_IDENTITY = `## L0 — IDENTITY
22
39
  No identity configured.
23
40
  Create ~/agent-knowledge/identity.md to populate Layer 0.
24
41
  Suggested fields: who you are, your primary role, the people you work with, the projects you maintain.`;
42
+ // ── Identity ────────────────────────────────────────────────────────────────
25
43
  function loadIdentity(memoryDir) {
26
44
  const candidates = [path.join(memoryDir, 'identity.md'), path.join(memoryDir, 'IDENTITY.md')];
27
45
  for (const p of candidates) {
@@ -49,9 +67,8 @@ function weighEntries(memoryDir, scope) {
49
67
  try {
50
68
  const fullPath = path.join(memoryDir, entry.path);
51
69
  const stat = fs.statSync(fullPath);
52
- const { content } = readEntry(memoryDir, entry.path);
70
+ const { entry: parsed } = readEntry(memoryDir, entry.path);
53
71
  const ageDays = Math.max(1, (now - stat.mtimeMs) / (24 * 3600_000));
54
- // Recency factor decays over ~90 days; size factor uses log to avoid huge files dominating.
55
72
  const recency = Math.exp(-ageDays / 90);
56
73
  const sizeFactor = Math.log(stat.size + 1);
57
74
  const weight = recency * sizeFactor;
@@ -59,7 +76,7 @@ function weighEntries(memoryDir, scope) {
59
76
  path: entry.path,
60
77
  title: entry.title || entry.path,
61
78
  weight,
62
- content,
79
+ content: parsed.content ?? '',
63
80
  });
64
81
  }
65
82
  catch {
@@ -75,58 +92,404 @@ function shortExcerpt(content, maxChars) {
75
92
  return cleaned;
76
93
  return cleaned.slice(0, maxChars).trimEnd() + '…';
77
94
  }
95
+ // ── Entry helpers ───────────────────────────────────────────────────────────
96
+ function listEntriesSafely(memoryDir, category) {
97
+ try {
98
+ return listEntries(memoryDir, category);
99
+ }
100
+ catch {
101
+ return [];
102
+ }
103
+ }
78
104
  /**
79
- * Build the wakeup payload.
80
- * Greedily includes top-weighted entries until the token budget is hit.
105
+ * Return the frontmatter-stripped body of an entry. `readEntry` returns
106
+ * `{ entry, content }` where `content` is the raw file bytes (including the
107
+ * YAML frontmatter block) and `entry.content` is the body-only view — we
108
+ * want the latter so excerpts don't leak `---\ntitle: ...\n---` scaffolding.
81
109
  */
82
- export function wakeup(options = {}) {
83
- const tokenBudget = options.tokenBudget ?? DEFAULT_BUDGET;
84
- const charBudget = tokenBudget * CHARS_PER_TOKEN;
85
- const config = getConfig();
86
- const identity = loadIdentity(config.memoryDir);
87
- const identityChars = identity.length + 16; // header overhead
88
- let used = identityChars;
89
- const scored = weighEntries(config.memoryDir, options.scope);
90
- const included = [];
110
+ function readEntrySafely(memoryDir, entryPath) {
111
+ try {
112
+ const { entry } = readEntry(memoryDir, entryPath);
113
+ return entry.content ?? '';
114
+ }
115
+ catch {
116
+ return '';
117
+ }
118
+ }
119
+ /** Lexicographic descending on `updated` (YYYY-MM-DD) with path as tiebreaker. */
120
+ function sortByUpdatedDesc(a, b) {
121
+ const au = a.updated || '';
122
+ const bu = b.updated || '';
123
+ if (au !== bu)
124
+ return bu.localeCompare(au);
125
+ return a.path.localeCompare(b.path);
126
+ }
127
+ function renderIdentity(ctx) {
128
+ const identity = loadIdentity(ctx.memoryDir);
129
+ const isDefault = identity === DEFAULT_IDENTITY;
130
+ // Identity already carries its own `## L0 — IDENTITY` heading. If the user's
131
+ // file omits one, emit a heading ourselves.
132
+ const hasHeading = /^##\s+/m.test(identity.split('\n').slice(0, 2).join('\n'));
133
+ const body = hasHeading ? identity : `## L0 — IDENTITY\n${identity}`;
134
+ const truncated = body.length > ctx.charBudget;
135
+ const content = truncated ? body.slice(0, Math.max(0, ctx.charBudget - 1)).trimEnd() + '…' : body;
136
+ return { content, empty: isDefault, truncated };
137
+ }
138
+ function renderActiveTasks(_ctx) {
139
+ // No in-repo task data. Emit a placeholder pointing at agent-tasks (the
140
+ // upstream source of truth). Keeps the section-slot visible so downstream
141
+ // UIs don't silently collapse it.
142
+ const body = '## ACTIVE TASKS\n' +
143
+ '_No in-repo task data. Query agent-tasks (`task_list` stage=in_progress) for current work._';
144
+ return { content: body, empty: true, truncated: false };
145
+ }
146
+ function renderRecentDecisions(ctx, maxItems = 5) {
147
+ const entries = listEntriesSafely(ctx.memoryDir, 'decisions');
148
+ if (entries.length === 0) {
149
+ return {
150
+ content: '## RECENT DECISIONS\n_No entries in `decisions/` yet. Write one via `knowledge` action=write._',
151
+ empty: true,
152
+ truncated: false,
153
+ };
154
+ }
155
+ const sorted = [...entries].sort(sortByUpdatedDesc).slice(0, maxItems);
156
+ const lines = ['## RECENT DECISIONS'];
157
+ let used = lines[0].length + 1;
158
+ let truncated = false;
159
+ for (const e of sorted) {
160
+ const body = readEntrySafely(ctx.memoryDir, e.path);
161
+ const excerpt = shortExcerpt(body, SECTION_EXCERPT_CHARS);
162
+ const line = `- **${e.title || e.path}** (\`${e.path}\`) — ${excerpt}`;
163
+ if (used + line.length + 1 > ctx.charBudget) {
164
+ truncated = true;
165
+ break;
166
+ }
167
+ lines.push(line);
168
+ used += line.length + 1;
169
+ }
170
+ return { content: lines.join('\n'), empty: false, truncated };
171
+ }
172
+ function renderKnownGotchas(ctx, maxItems = 5) {
173
+ // Pull tagged `gotcha` from any category. listEntries supports a tag filter.
174
+ let entries;
175
+ try {
176
+ entries = listEntries(ctx.memoryDir, undefined, 'gotcha');
177
+ }
178
+ catch {
179
+ entries = [];
180
+ }
181
+ if (entries.length === 0) {
182
+ return {
183
+ content: '## KNOWN GOTCHAS\n_No entries tagged `gotcha`. Add `tags: [gotcha]` to frontmatter to surface pitfalls here._',
184
+ empty: true,
185
+ truncated: false,
186
+ };
187
+ }
188
+ const sorted = [...entries].sort(sortByUpdatedDesc).slice(0, maxItems);
189
+ const lines = ['## KNOWN GOTCHAS'];
190
+ let used = lines[0].length + 1;
191
+ let truncated = false;
192
+ for (const e of sorted) {
193
+ const body = readEntrySafely(ctx.memoryDir, e.path);
194
+ const excerpt = shortExcerpt(body, SECTION_EXCERPT_CHARS);
195
+ const line = `- **${e.title || e.path}** (\`${e.path}\`) — ${excerpt}`;
196
+ if (used + line.length + 1 > ctx.charBudget) {
197
+ truncated = true;
198
+ break;
199
+ }
200
+ lines.push(line);
201
+ used += line.length + 1;
202
+ }
203
+ return { content: lines.join('\n'), empty: false, truncated };
204
+ }
205
+ function renderLastSessionSummary(_ctx) {
206
+ let sessions;
207
+ try {
208
+ sessions = listSessions();
209
+ }
210
+ catch {
211
+ sessions = [];
212
+ }
213
+ if (!sessions || sessions.length === 0) {
214
+ return {
215
+ content: '## LAST SESSION\n_No prior sessions indexed._',
216
+ empty: true,
217
+ truncated: false,
218
+ };
219
+ }
220
+ const latest = sessions[0];
221
+ const lines = ['## LAST SESSION'];
222
+ lines.push(`- **Project:** ${latest.project}`);
223
+ lines.push(`- **Session:** ${latest.sessionId}`);
224
+ if (latest.startTime && latest.startTime !== 'unknown') {
225
+ lines.push(`- **Started:** ${latest.startTime}`);
226
+ }
227
+ if (typeof latest.messageCount === 'number') {
228
+ lines.push(`- **Messages:** ${latest.messageCount}`);
229
+ }
230
+ if (latest.preview && latest.preview !== 'N/A') {
231
+ lines.push(`- **Preview:** ${shortExcerpt(latest.preview, SECTION_EXCERPT_CHARS)}`);
232
+ }
233
+ const joined = lines.join('\n');
234
+ const truncated = joined.length > _ctx.charBudget;
235
+ const content = truncated
236
+ ? joined.slice(0, Math.max(0, _ctx.charBudget - 1)).trimEnd() + '…'
237
+ : joined;
238
+ return { content, empty: false, truncated };
239
+ }
240
+ function renderTopWeighted(ctx, heading = '## L1 — ESSENTIAL FACTS') {
241
+ const scored = weighEntries(ctx.memoryDir, ctx.scope);
242
+ const picks = [];
243
+ const lines = [heading];
244
+ let used = heading.length + 1;
91
245
  let truncated = false;
246
+ if (scored.length === 0) {
247
+ const body = heading +
248
+ '\n_No entries indexed. Write some via `knowledge` action=write to populate Layer 1._';
249
+ return {
250
+ rendered: { content: body, empty: true, truncated: false },
251
+ picks: [],
252
+ };
253
+ }
92
254
  for (const entry of scored) {
93
255
  const excerpt = shortExcerpt(entry.content, L1_EXCERPT_CHARS);
94
- const lineCost = excerpt.length + entry.title.length + entry.path.length + 12;
95
- if (used + lineCost > charBudget) {
256
+ const line = `- **${entry.title}** (\`${entry.path}\`) — ${excerpt}`;
257
+ if (used + line.length + 1 > ctx.charBudget) {
96
258
  truncated = true;
97
259
  break;
98
260
  }
99
- included.push({
261
+ lines.push(line);
262
+ used += line.length + 1;
263
+ picks.push({
100
264
  path: entry.path,
101
265
  title: entry.title,
102
266
  weight: Math.round(entry.weight * 100) / 100,
103
267
  excerpt,
104
268
  });
105
- used += lineCost;
106
- }
107
- const lines = [];
108
- lines.push(identity);
109
- lines.push('');
110
- lines.push('## L1 — ESSENTIAL FACTS');
111
- if (included.length === 0) {
112
- lines.push('_No entries indexed. Write some via `knowledge` action=write to populate Layer 1._');
113
- }
114
- else {
115
- for (const e of included) {
116
- lines.push(`- **${e.title}** (\`${e.path}\`) — ${e.excerpt}`);
117
- }
118
269
  }
119
270
  if (truncated) {
120
- lines.push('');
121
- lines.push('_(L1 truncated to fit token budget — call `knowledge_search` for the rest.)_');
271
+ const note = '_(truncated to fit budget — call `knowledge_search` for the rest.)_';
272
+ if (used + note.length + 1 <= ctx.charBudget) {
273
+ lines.push('');
274
+ lines.push(note);
275
+ }
276
+ }
277
+ return {
278
+ rendered: { content: lines.join('\n'), empty: false, truncated },
279
+ picks,
280
+ };
281
+ }
282
+ function renderSemanticFallback(ctx) {
283
+ // Pure top-weighted catch-all when earlier sections under-filled. Same
284
+ // scoring as top_weighted but marked as a distinct section for clarity.
285
+ const { rendered } = renderTopWeighted(ctx, '## SEMANTIC FALLBACK');
286
+ return rendered;
287
+ }
288
+ // ── Budget allocation ───────────────────────────────────────────────────────
289
+ /**
290
+ * Allocate a per-section character budget. Explicit overrides win; the
291
+ * remainder is split evenly among unspecified sections. Values are capped
292
+ * so explicit overrides never exceed the global budget.
293
+ */
294
+ function allocateBudgets(sections, totalChars, sectionBudgets) {
295
+ const out = new Map();
296
+ if (sections.length === 0)
297
+ return out;
298
+ if (!sectionBudgets || Object.keys(sectionBudgets).length === 0) {
299
+ const per = Math.max(1, Math.floor(totalChars / sections.length));
300
+ for (const s of sections)
301
+ out.set(s, per);
302
+ return out;
303
+ }
304
+ // Convert any provided overrides from tokens → chars, capped at total.
305
+ const explicit = new Map();
306
+ let explicitSum = 0;
307
+ for (const s of sections) {
308
+ const v = sectionBudgets[s];
309
+ if (typeof v === 'number' && v > 0) {
310
+ const chars = Math.min(totalChars, Math.floor(v * CHARS_PER_TOKEN));
311
+ explicit.set(s, chars);
312
+ explicitSum += chars;
313
+ }
314
+ }
315
+ const unspecified = sections.filter((s) => !explicit.has(s));
316
+ const remaining = Math.max(0, totalChars - explicitSum);
317
+ const perUnspec = unspecified.length > 0 ? Math.max(1, Math.floor(remaining / unspecified.length)) : 0;
318
+ for (const s of sections) {
319
+ if (explicit.has(s))
320
+ out.set(s, explicit.get(s));
321
+ else
322
+ out.set(s, perUnspec);
323
+ }
324
+ return out;
325
+ }
326
+ // ── Main assembler ──────────────────────────────────────────────────────────
327
+ function renderSection(name, ctx) {
328
+ switch (name) {
329
+ case 'identity':
330
+ return { render: renderIdentity(ctx) };
331
+ case 'active_tasks':
332
+ return { render: renderActiveTasks(ctx) };
333
+ case 'recent_decisions':
334
+ return { render: renderRecentDecisions(ctx) };
335
+ case 'known_gotchas':
336
+ return { render: renderKnownGotchas(ctx) };
337
+ case 'last_session_summary':
338
+ return { render: renderLastSessionSummary(ctx) };
339
+ case 'top_weighted': {
340
+ const { rendered, picks } = renderTopWeighted(ctx);
341
+ return { render: rendered, picks };
342
+ }
343
+ case 'semantic_fallback':
344
+ return { render: renderSemanticFallback(ctx) };
345
+ default: {
346
+ // Exhaustiveness guard — unknown section names render as no-ops.
347
+ const never = name;
348
+ void never;
349
+ return { render: { content: '', empty: true, truncated: false } };
350
+ }
351
+ }
352
+ }
353
+ /**
354
+ * Build the section-priority context bundle.
355
+ *
356
+ * Greedy-fill algorithm:
357
+ * 1. Allocate per-section char budget (defaults to an even split).
358
+ * 2. For each section in priority order, render up to its budget.
359
+ * 3. If a section under-uses its budget, redistribute the remainder
360
+ * to subsequent sections.
361
+ * 4. Stop once total rendered chars ≥ global budget.
362
+ * 5. Mark `truncated: true` if any emitted section was cut.
363
+ */
364
+ export function buildContextBundle(options = {}) {
365
+ const tokenBudget = options.tokenBudget ?? DEFAULT_BUDGET;
366
+ const charBudget = tokenBudget * CHARS_PER_TOKEN;
367
+ const sections = options.sections && options.sections.length > 0 ? options.sections : DEFAULT_SECTIONS;
368
+ const config = getConfig();
369
+ // Honour an explicit empty `sections: []` — caller is opting out of all
370
+ // rendering. Return an empty bundle instead of silently substituting the
371
+ // defaults (the previous behaviour surprised callers trying to emit
372
+ // nothing).
373
+ if (options.sections && options.sections.length === 0) {
374
+ return {
375
+ identity: '',
376
+ entries: [],
377
+ sections: [],
378
+ rendered: '',
379
+ token_estimate: 0,
380
+ truncated: false,
381
+ };
382
+ }
383
+ const budgets = allocateBudgets(sections, charBudget, options.sectionBudgets);
384
+ // Snapshot the original per-section allocation so that the emitted
385
+ // `budget` field reflects what the caller asked for, not the post-
386
+ // redistribution number (which can grow as earlier sections under-fill).
387
+ const originalBudgets = new Map(budgets);
388
+ // Load identity once — both the ContextBundleResult.identity field and
389
+ // renderIdentity() previously re-read it independently.
390
+ const identity = loadIdentity(config.memoryDir);
391
+ const emitted = [];
392
+ let allPicks = [];
393
+ let totalUsed = 0;
394
+ let anyTruncated = false;
395
+ for (let i = 0; i < sections.length; i++) {
396
+ const name = sections[i];
397
+ const remainingGlobal = charBudget - totalUsed;
398
+ if (remainingGlobal <= 0)
399
+ break;
400
+ const allocated = budgets.get(name) ?? 0;
401
+ // Step 3: allow this section to use any remainder handed down from earlier
402
+ // under-filled sections. We cap at the global remainder so we never bust
403
+ // the overall budget.
404
+ const effective = Math.max(0, Math.min(remainingGlobal, allocated));
405
+ if (effective === 0)
406
+ continue;
407
+ const ctx = {
408
+ memoryDir: config.memoryDir,
409
+ scope: options.scope,
410
+ charBudget: effective,
411
+ };
412
+ const { render, picks } = renderSection(name, ctx);
413
+ // Enforce the char cap defensively — renderers should already respect it.
414
+ const safe = render.content.length > effective
415
+ ? {
416
+ ...render,
417
+ content: render.content.slice(0, effective).trimEnd() + '…',
418
+ truncated: true,
419
+ }
420
+ : render;
421
+ const usedChars = safe.content.length;
422
+ const usedTokens = Math.ceil(usedChars / CHARS_PER_TOKEN);
423
+ const reportedBudgetChars = originalBudgets.get(name) ?? allocated;
424
+ emitted.push({
425
+ name,
426
+ content: safe.content,
427
+ budget: Math.ceil(reportedBudgetChars / CHARS_PER_TOKEN),
428
+ used: usedTokens,
429
+ truncated: safe.truncated,
430
+ empty: safe.empty,
431
+ });
432
+ // +2 accounts for the `\n\n` separator `buildContextBundle` uses when
433
+ // joining sections at line ~553. Previously undercounted by 1 per
434
+ // boundary, letting total rendered exceed the global budget by up to
435
+ // N-1 chars on an N-section bundle.
436
+ totalUsed += usedChars + 2;
437
+ if (safe.truncated)
438
+ anyTruncated = true;
439
+ if (picks && picks.length > 0)
440
+ allPicks = picks;
441
+ // Redistribute leftover budget from this section evenly across the
442
+ // remaining sections.
443
+ const leftover = allocated - usedChars;
444
+ const restCount = sections.length - (i + 1);
445
+ if (leftover > 0 && restCount > 0) {
446
+ const bonus = Math.floor(leftover / restCount);
447
+ for (let j = i + 1; j < sections.length; j++) {
448
+ const nxt = sections[j];
449
+ budgets.set(nxt, (budgets.get(nxt) ?? 0) + bonus);
450
+ }
451
+ }
452
+ }
453
+ const rendered = emitted.map((s) => s.content).join('\n\n');
454
+ // Mark access for every entry that actually made it into the bundle.
455
+ // Wakeup injection is the primary knowledge-consumption path (L1 facts
456
+ // packed into the first prompt on every session start). Before this,
457
+ // `last_accessed` only bumped on explicit `knowledge(action: read)` —
458
+ // so the scoring DB under-reported real usage and the bytype chart
459
+ // showed "mostly unused" even when wakeup was actively feeding content.
460
+ if (allPicks.length > 0) {
461
+ try {
462
+ const paths = allPicks.map((p) => p.path).filter((p) => !!p);
463
+ if (paths.length > 0)
464
+ getEntryScoring().recordBulkAccess(paths);
465
+ }
466
+ catch (err) {
467
+ // Non-fatal — scoring DB issues shouldn't block context rendering.
468
+ console.error('[wakeup] recordBulkAccess failed:', err instanceof Error ? err.message : err);
469
+ }
122
470
  }
123
- const rendered = lines.join('\n');
124
471
  return {
125
472
  identity,
126
- entries: included,
473
+ entries: allPicks,
474
+ sections: emitted,
127
475
  rendered,
128
476
  token_estimate: Math.ceil(rendered.length / CHARS_PER_TOKEN),
129
- truncated,
477
+ truncated: anyTruncated,
130
478
  };
131
479
  }
480
+ // ── Backwards-compat wrapper ────────────────────────────────────────────────
481
+ /**
482
+ * v1.8.0-compatible entry point.
483
+ *
484
+ * When invoked with only `tokenBudget` + `scope`, routes to the
485
+ * `top_weighted` section alone so the `rendered` output stays shape-
486
+ * compatible with pre-v1.8.1 callers (identity heading + L1 facts list).
487
+ */
488
+ export function wakeup(options = {}) {
489
+ return buildContextBundle({
490
+ tokenBudget: options.tokenBudget,
491
+ scope: options.scope,
492
+ sections: ['identity', 'top_weighted'],
493
+ });
494
+ }
132
495
  //# sourceMappingURL=wakeup.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"wakeup.js","sourceRoot":"","sources":["../src/wakeup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAsBvC,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAE7B,MAAM,gBAAgB,GAAG;;;uGAG8E,CAAC;AAExG,SAAS,YAAY,CAAC,SAAiB;IACrC,MAAM,UAAU,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,aAAa,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC,CAAC;IAC9F,KAAK,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC;QAC3B,IAAI,CAAC;YACH,IAAI,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;gBACrB,OAAO,EAAE,CAAC,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC5C,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,wBAAwB;QAC1B,CAAC;IACH,CAAC;IACD,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AASD;;;;GAIG;AACH,SAAS,YAAY,CAAC,SAAiB,EAAE,KAAc;IACrD,MAAM,OAAO,GAAG,WAAW,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IAC9C,MAAM,GAAG,GAAG,IAA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H,MAAM,UAAU,MAAM,CAAC,UAAyB,EAAE;IAChD,OAAO,kBAAkB,CAAC;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,QAAQ,EAAE,CAAC,UAAU,EAAE,cAAc,CAAC;KACvC,CAAC,CAAC;AACL,CAAC"}
@@ -41,23 +41,28 @@ graph TB
41
41
  src/
42
42
  index.ts Entry point — MCP stdio + dashboard auto-start
43
43
  server.ts 6 tool definitions, request routing, error handling
44
+ tool-handlers.ts Action dispatch for each MCP tool + the v1.8 `promote` action
44
45
  dashboard.ts HTTP + WebSocket server, REST API, file watcher
45
46
  package-meta.ts Cached name/version from package.json (used by getVersion / MCP / dashboard)
46
47
  types.ts KnowledgeConfig interface, getConfig(), getVersion()
48
+ wakeup.ts Token-budgeted L0 identity + L1 top-weighted entry renderer
47
49
  knowledge/
48
- store.ts CRUD for markdown entries with YAML frontmatter
49
- search.ts TF-IDF search over knowledge entries
50
- git.ts git pull/push/sync with execSync + timeouts
51
- graph.ts Knowledge graph — edges table, link/unlink/BFS traversal
52
- scoring.ts Confidence/decay scoring — entry_scores table, auto-promotion
50
+ store.ts CRUD for markdown entries with YAML frontmatter (incl. `evergreen` flag)
51
+ search.ts Hybrid TF-IDF search + optional MMR re-ranking + score_components explain
52
+ git.ts git pull/push/sync with execFileSync + timeouts
53
+ graph.ts Knowledge graph — edges table, link/unlink/BFS traversal, temporal validity
54
+ scoring.ts Confidence/decay scoring — entry_scores table, evergreen-exempt decay
53
55
  consolidate.ts Memory consolidation — TF-IDF duplicate detection, cluster grouping
54
56
  reflect.ts Reflection cycle — surfaces unconnected entries, generates prompts
55
57
  analyze.ts Graph analysis — god nodes, bridges, gaps, knowledge brief (deterministic, no LLM)
58
+ promote.ts v1.8 scored + gated promoter — 6-signal weights, 3 gates, grounded rehydration, dreams diary
59
+ distill.ts Legacy regex distiller (kept for bench baseline comparison; no longer default-wired)
56
60
  sessions/
57
61
  parser.ts Multi-format parsing with mtime cache + adapter dispatch
58
62
  search.ts TF-IDF ranked search with 60s global index cache
59
63
  scopes.ts 6 search scopes, post-filters cached index results
60
64
  summary.ts Topic extraction, tool/file detection
65
+ indexer.ts Background vector indexer + auto-promotion dispatch
61
66
  adapters/
62
67
  index.ts SessionAdapter interface, adapter registry, initAdapters()
63
68
  opencode.ts OpenCode adapter — reads SQLite database (better-sqlite3)
@@ -66,12 +71,32 @@ src/
66
71
  aider.ts Aider adapter — parses markdown chat + JSONL LLM history
67
72
  search/
68
73
  tfidf.ts TF-IDF scoring engine (tokenizer, stopwords, index)
74
+ bm25.ts BM25 ranking (v1.5+ default; replaced raw TF-IDF in session search)
75
+ boosts.ts v1.4 proper-noun + temporal proximity boosts
69
76
  fuzzy.ts Levenshtein distance, sliding window matching
77
+ excerpt.ts Query-centered excerpt builder
78
+ mmr.ts v1.8 MMR re-ranking, diversity@K metric, cosine + Jaccard sim helpers
70
79
  types.ts SearchResult, SearchOptions interfaces
80
+ vectorstore/ sqlite-vec wrapper + chunker
81
+ embeddings/ Pluggable embedding providers (openai / claude / gemini / local)
71
82
  ui/
72
83
  index.html Dashboard SPA
73
- styles.css MD3 design tokens (light + dark)
84
+ styles.css MD3 design tokens (light + dark)
74
85
  app.js Client-side JS (WebSocket, tabs, rendering)
86
+
87
+ scripts/
88
+ hooks/
89
+ session-start.js SessionStart — dashboard URL + auto-wakeup injection
90
+ first-prompt-inject.mjs UserPromptSubmit — v1.8 query-targeted knowledge inject on the first real prompt
91
+ precompact-flush.mjs PreCompact — disk dump + save-unsaved-context nudge
92
+ precompact-distill.mjs PreCompact — lightweight user-prompt snapshot
93
+ sessionend-distill.mjs SessionEnd — final summary breadcrumb
94
+
95
+ bench/
96
+ run.ts R@5 / R@10 + diversity@5 smoke bench over local ~/agent-knowledge/
97
+ longmemeval.ts Single-mode LongMemEval runner (500 Q, 6 question types)
98
+ longmemeval-matrix.ts v1.8 ablation harness — 4 sparse modes side-by-side on same corpus
99
+ promote-bench.ts v1.8 write bench — gated vs naive vs v1.7 regex distiller, self-labeled
75
100
  ```
76
101
 
77
102
  ## Knowledge Module