agent-knowledge 1.7.3 → 1.8.0

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 (44) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.mcp.json +1 -1
  3. package/CHANGELOG.md +43 -0
  4. package/README.md +43 -18
  5. package/agent-desk-plugin.json +1 -1
  6. package/dist/knowledge/promote.d.ts +145 -0
  7. package/dist/knowledge/promote.d.ts.map +1 -0
  8. package/dist/knowledge/promote.js +517 -0
  9. package/dist/knowledge/promote.js.map +1 -0
  10. package/dist/knowledge/scoring.d.ts +6 -2
  11. package/dist/knowledge/scoring.d.ts.map +1 -1
  12. package/dist/knowledge/scoring.js +7 -3
  13. package/dist/knowledge/scoring.js.map +1 -1
  14. package/dist/knowledge/search.d.ts +32 -5
  15. package/dist/knowledge/search.d.ts.map +1 -1
  16. package/dist/knowledge/search.js +60 -10
  17. package/dist/knowledge/search.js.map +1 -1
  18. package/dist/knowledge/store.d.ts +6 -0
  19. package/dist/knowledge/store.d.ts.map +1 -1
  20. package/dist/knowledge/store.js +10 -0
  21. package/dist/knowledge/store.js.map +1 -1
  22. package/dist/search/mmr.d.ts +54 -0
  23. package/dist/search/mmr.d.ts.map +1 -0
  24. package/dist/search/mmr.js +138 -0
  25. package/dist/search/mmr.js.map +1 -0
  26. package/dist/server.d.ts +307 -0
  27. package/dist/server.d.ts.map +1 -1
  28. package/dist/server.js +336 -301
  29. package/dist/server.js.map +1 -1
  30. package/dist/sessions/indexer.d.ts.map +1 -1
  31. package/dist/sessions/indexer.js +13 -11
  32. package/dist/sessions/indexer.js.map +1 -1
  33. package/dist/tool-handlers.d.ts +10 -3
  34. package/dist/tool-handlers.d.ts.map +1 -1
  35. package/dist/tool-handlers.js +56 -17
  36. package/dist/tool-handlers.js.map +1 -1
  37. package/docs/ARCHITECTURE.md +31 -6
  38. package/docs/SETUP.md +20 -8
  39. package/docs/USER-MANUAL.md +146 -39
  40. package/docs/hooks.md +81 -21
  41. package/package.json +4 -1
  42. package/scripts/hooks/first-prompt-inject.mjs +230 -0
  43. package/scripts/hooks/precompact-flush.mjs +89 -60
  44. package/scripts/hooks/session-start.js +73 -9
@@ -1,34 +1,27 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // =============================================================================
4
- // agent-knowledge PreCompact / Stop hook
4
+ // agent-knowledge PreCompact / Stop hook — memory-flush
5
5
  //
6
- // Flushes a session summary to ~/agent-knowledge/sessions/ before the host
7
- // (Claude Code, Cursor, Codex CLI, etc.) compacts or ends the conversation,
8
- // so the verbatim distillation has something to anchor against later.
6
+ // Two jobs, both best-effort:
9
7
  //
10
- // Fail-open: any error
11
- // is logged to stderr and the hook still prints `{}` so it never blocks the host.
8
+ // 1. Dump the session summary to ~/agent-knowledge/sessions/<project>/ so
9
+ // later distillation/promotion has a durable anchor even if the host
10
+ // garbage-collects the transcript.
12
11
  //
13
- // Wire-up (host-specific — examples):
12
+ // 2. Inject a short "save-your-context" nudge into the host's PreCompact
13
+ // response (`hookSpecificOutput.additionalContext`). The compaction pass
14
+ // is about to summarize — anything important and unsaved should be
15
+ // written to the knowledge base NOW via `knowledge(action="write", …)`.
16
+ // Pre-compaction memory-flush primitive.
14
17
  //
15
- // Claude Code (~/.claude/settings.json):
16
- // {
17
- // "hooks": {
18
- // "PreCompact": [{"matcher": "", "hooks": [
19
- // {"type": "command",
20
- // "command": "node \"$HOME/.claude/mcp-servers/agent-knowledge/scripts/hooks/precompact-flush.mjs\"",
21
- // "timeout": 10}
22
- // ]}],
23
- // "Stop": [{"matcher": "", "hooks": [
24
- // {"type": "command",
25
- // "command": "node \"$HOME/.claude/mcp-servers/agent-knowledge/scripts/hooks/precompact-flush.mjs\"",
26
- // "timeout": 10}
27
- // ]}]
28
- // }
29
- // }
18
+ // Disable the nudge by exporting AGENT_KNOWLEDGE_PRECOMPACT_NUDGE=0 (the disk
19
+ // dump still runs). Set AGENT_KNOWLEDGE_PRECOMPACT_NUDGE=off to suppress both.
30
20
  //
31
- // Reads hook JSON from stdin (the host pipes it). The fields we look at:
21
+ // Fail-open: every error path prints a valid JSON response so the host never
22
+ // blocks on this hook.
23
+ //
24
+ // Reads hook JSON from stdin (the host pipes it). Fields used:
32
25
  // { session_id, hook_event_name, cwd? }
33
26
  // =============================================================================
34
27
 
@@ -40,15 +33,39 @@ import { homedir } from 'os';
40
33
  const __filename = fileURLToPath(import.meta.url);
41
34
  const __dirname = dirname(__filename);
42
35
 
43
- function fail(msg) {
44
- process.stderr.write(`[precompact-flush] ${msg}\n`);
45
- process.stdout.write('{}\n');
36
+ const NUDGE_MODE = (process.env.AGENT_KNOWLEDGE_PRECOMPACT_NUDGE ?? '1').trim().toLowerCase();
37
+ const nudgeEnabled = NUDGE_MODE !== '0' && NUDGE_MODE !== 'false' && NUDGE_MODE !== 'off';
38
+ const diskDumpEnabled = NUDGE_MODE !== 'off';
39
+
40
+ const NUDGE_TEXT = [
41
+ '## PreCompact — memory-flush nudge',
42
+ '',
43
+ 'The host is about to compact the conversation. Anything you learned this',
44
+ 'turn that the next session will need MUST be written to the knowledge base',
45
+ 'before the summary replaces the transcript. Use:',
46
+ '',
47
+ ' `knowledge(action="write", category="decisions"|"notes"|"workflows", filename=..., content=...)`',
48
+ '',
49
+ 'Candidates worth a write: architectural decisions, non-obvious gotchas,',
50
+ 'hard-won commands, people/ownership facts, project state. Skip transient',
51
+ 'things (file diffs, TODO lists, in-flight plans — plan/task systems own those).',
52
+ ].join('\n');
53
+
54
+ function emitResult(additionalContext) {
55
+ const payload = additionalContext
56
+ ? {
57
+ hookSpecificOutput: {
58
+ hookEventName: 'PreCompact',
59
+ additionalContext,
60
+ },
61
+ }
62
+ : {};
63
+ process.stdout.write(JSON.stringify(payload) + '\n');
46
64
  process.exit(0);
47
65
  }
48
66
 
49
- function ok() {
50
- process.stdout.write('{}\n');
51
- process.exit(0);
67
+ function warn(msg) {
68
+ process.stderr.write(`[precompact-flush] ${msg}\n`);
52
69
  }
53
70
 
54
71
  async function readStdin() {
@@ -58,7 +75,6 @@ async function readStdin() {
58
75
  process.stdin.setEncoding('utf-8');
59
76
  process.stdin.on('data', (chunk) => (data += chunk));
60
77
  process.stdin.on('end', () => resolveP(data));
61
- // Don't hang forever if the host doesn't pipe anything
62
78
  setTimeout(() => resolveP(data), 2000);
63
79
  });
64
80
  }
@@ -75,27 +91,11 @@ function memoryDir() {
75
91
  return process.env.KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
76
92
  }
77
93
 
78
- async function main() {
79
- const raw = await readStdin();
80
- let payload = {};
81
- if (raw) {
82
- try {
83
- payload = JSON.parse(raw);
84
- } catch {
85
- // Ignore — host may not have piped JSON
86
- }
87
- }
88
-
89
- const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID || 'unknown';
90
- const event = payload.hook_event_name || 'precompact';
91
- const cwd = payload.cwd || process.cwd();
92
- const projectSlug = slugify(cwd.split(/[\\/]/).filter(Boolean).pop() || 'project');
93
-
94
- // Try to import the agent-knowledge summary helper directly (ESM dynamic import).
95
- // The compiled output lives next to this script: ../../dist/sessions/summary.js
94
+ async function dumpSummaryToDisk({ sessionId, event, cwd, projectSlug }) {
96
95
  const distSummary = resolve(__dirname, '..', '..', 'dist', 'sessions', 'summary.js');
97
96
  if (!existsSync(distSummary)) {
98
- return fail(`dist not built: ${distSummary} (run \`npm run build\`)`);
97
+ warn(`dist not built: ${distSummary} (run \`npm run build\`)`);
98
+ return;
99
99
  }
100
100
 
101
101
  let summaryFn;
@@ -103,27 +103,32 @@ async function main() {
103
103
  const mod = await import(`file://${distSummary.replace(/\\/g, '/')}`);
104
104
  summaryFn = mod.getSessionSummary;
105
105
  } catch (err) {
106
- return fail(`import failed: ${err?.message || err}`);
106
+ warn(`import failed: ${err?.message || err}`);
107
+ return;
107
108
  }
108
109
  if (typeof summaryFn !== 'function') {
109
- return fail('getSessionSummary not exported from dist/sessions/summary.js');
110
+ warn('getSessionSummary not exported from dist/sessions/summary.js');
111
+ return;
110
112
  }
111
113
 
112
114
  let summary;
113
115
  try {
114
116
  summary = summaryFn(sessionId);
115
117
  } catch (err) {
116
- return fail(`getSessionSummary threw: ${err?.message || err}`);
118
+ warn(`getSessionSummary threw: ${err?.message || err}`);
119
+ return;
117
120
  }
118
121
  if (!summary) {
119
- return fail(`session ${sessionId} not found — nothing to flush`);
122
+ warn(`session ${sessionId} not found — nothing to flush`);
123
+ return;
120
124
  }
121
125
 
122
126
  const outDir = join(memoryDir(), 'sessions', projectSlug);
123
127
  try {
124
128
  mkdirSync(outDir, { recursive: true });
125
129
  } catch (err) {
126
- return fail(`mkdir ${outDir}: ${err?.message || err}`);
130
+ warn(`mkdir ${outDir}: ${err?.message || err}`);
131
+ return;
127
132
  }
128
133
 
129
134
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
@@ -147,13 +152,13 @@ async function main() {
147
152
 
148
153
  try {
149
154
  writeFileSync(outPath, body, 'utf-8');
155
+ warn(`wrote ${outPath}`);
150
156
  } catch (err) {
151
- return fail(`write ${outPath}: ${err?.message || err}`);
157
+ warn(`write ${outPath}: ${err?.message || err}`);
158
+ return;
152
159
  }
153
160
 
154
- process.stderr.write(`[precompact-flush] wrote ${outPath}\n`);
155
-
156
- // Best-effort: append a one-line breadcrumb readable later by `knowledge` action=list
161
+ // Best-effort: append a breadcrumb readable later by `knowledge` action=list
157
162
  try {
158
163
  const breadcrumb = join(memoryDir(), 'sessions', 'index.md');
159
164
  const existing = existsSync(breadcrumb)
@@ -167,8 +172,32 @@ async function main() {
167
172
  } catch {
168
173
  /* ignore */
169
174
  }
175
+ }
176
+
177
+ async function main() {
178
+ const raw = await readStdin();
179
+ let payload = {};
180
+ if (raw) {
181
+ try {
182
+ payload = JSON.parse(raw);
183
+ } catch {
184
+ /* ignore — host may not pipe JSON */
185
+ }
186
+ }
187
+
188
+ const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID || 'unknown';
189
+ const event = payload.hook_event_name || 'precompact';
190
+ const cwd = payload.cwd || process.cwd();
191
+ const projectSlug = slugify(cwd.split(/[\\/]/).filter(Boolean).pop() || 'project');
192
+
193
+ if (diskDumpEnabled) {
194
+ await dumpSummaryToDisk({ sessionId, event, cwd, projectSlug });
195
+ }
170
196
 
171
- ok();
197
+ emitResult(nudgeEnabled ? NUDGE_TEXT : undefined);
172
198
  }
173
199
 
174
- main().catch((err) => fail(err?.message || String(err)));
200
+ main().catch((err) => {
201
+ warn(err?.message || String(err));
202
+ emitResult(nudgeEnabled ? NUDGE_TEXT : undefined);
203
+ });
@@ -3,17 +3,81 @@
3
3
  // =============================================================================
4
4
  // agent-knowledge SessionStart hook
5
5
  //
6
- // Announces the knowledge dashboard URL.
6
+ // 1. Announces the knowledge dashboard URL.
7
+ // 2. Auto-loads a token-budgeted wakeup payload (L0 identity + L1 top-weighted
8
+ // entries) into the host's additionalContext so the agent starts each
9
+ // session with a small, well-chosen window into the knowledge base — no
10
+ // manual `knowledge action=wakeup` call required.
11
+ //
12
+ // Disable auto-wakeup by exporting AGENT_KNOWLEDGE_AUTOWAKE=0. Tune budget
13
+ // with AGENT_KNOWLEDGE_WAKEUP_BUDGET (default 800 tokens).
14
+ //
15
+ // Fail-open: every error path still prints a valid JSON hook response so the
16
+ // session never blocks on this hook.
7
17
  // =============================================================================
8
18
 
19
+ import { existsSync } from 'fs';
20
+ import { dirname, resolve } from 'path';
21
+ import { fileURLToPath } from 'url';
22
+
23
+ const __filename = fileURLToPath(import.meta.url);
24
+ const __dirname = dirname(__filename);
25
+
9
26
  const knowledgePort = process.env.AGENT_KNOWLEDGE_PORT || '3423';
27
+ const autoWakeEnabled =
28
+ (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== '0' &&
29
+ (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== 'false';
30
+ const wakeupBudget = Number.parseInt(process.env.AGENT_KNOWLEDGE_WAKEUP_BUDGET ?? '800', 10) || 800;
31
+
32
+ function emit(additionalContext) {
33
+ const msg = {
34
+ systemMessage: `agent-knowledge: http://localhost:${knowledgePort}`,
35
+ hookSpecificOutput: {
36
+ hookEventName: 'SessionStart',
37
+ additionalContext,
38
+ },
39
+ };
40
+ process.stdout.write(JSON.stringify(msg) + '\n');
41
+ process.exit(0);
42
+ }
43
+
44
+ async function loadWakeup() {
45
+ const distWakeup = resolve(__dirname, '..', '..', 'dist', 'wakeup.js');
46
+ if (!existsSync(distWakeup)) return null;
47
+ try {
48
+ const mod = await import(`file://${distWakeup.replace(/\\/g, '/')}`);
49
+ if (typeof mod.wakeup !== 'function') return null;
50
+ const result = mod.wakeup({ tokenBudget: wakeupBudget });
51
+ if (result && typeof result.rendered === 'string') return result.rendered;
52
+ } catch (err) {
53
+ process.stderr.write(`[knowledge session-start] wakeup failed: ${err?.message || err}\n`);
54
+ }
55
+ return null;
56
+ }
57
+
58
+ async function main() {
59
+ const dashboardLine = `Knowledge: http://localhost:${knowledgePort}`;
60
+
61
+ if (!autoWakeEnabled) {
62
+ return emit(dashboardLine);
63
+ }
64
+
65
+ const rendered = await loadWakeup();
66
+ if (!rendered) {
67
+ return emit(dashboardLine);
68
+ }
69
+
70
+ const combined = [
71
+ dashboardLine,
72
+ '',
73
+ '--- Knowledge wakeup (auto-loaded; call `knowledge action=wakeup` to refresh) ---',
74
+ rendered,
75
+ ].join('\n');
10
76
 
11
- const msg = {
12
- systemMessage: `agent-knowledge: http://localhost:${knowledgePort}`,
13
- hookSpecificOutput: {
14
- hookEventName: 'SessionStart',
15
- additionalContext: `Knowledge: http://localhost:${knowledgePort}`,
16
- },
17
- };
77
+ emit(combined);
78
+ }
18
79
 
19
- console.log(JSON.stringify(msg));
80
+ main().catch((err) => {
81
+ process.stderr.write(`[knowledge session-start] ${err?.message || err}\n`);
82
+ emit(`Knowledge: http://localhost:${knowledgePort}`);
83
+ });