agent-knowledge 1.5.2 → 1.6.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.
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env node
2
+
3
+ // =============================================================================
4
+ // agent-knowledge SessionStart ingest hook
5
+ //
6
+ // On session start, detects the current project and checks whether a
7
+ // knowledge-ingest cache exists. If no cache: suggests bootstrapping.
8
+ // If cache exists: runs a quick SHA256 diff against the current files
9
+ // to report how many files changed since last ingest.
10
+ //
11
+ // Zero LLM tokens — only reads files and computes hashes.
12
+ // Fail-open: errors logged to stderr, always outputs valid JSON.
13
+ // =============================================================================
14
+
15
+ import { readFileSync, readdirSync, statSync, existsSync } from 'fs';
16
+ import { join, extname, resolve, dirname } from 'path';
17
+ import { createHash } from 'crypto';
18
+ import { fileURLToPath } from 'url';
19
+
20
+ const __filename = fileURLToPath(import.meta.url);
21
+ const __dirname = dirname(__filename);
22
+
23
+ process.on('uncaughtException', (err) => {
24
+ process.stderr.write(`[session-start-ingest] fatal: ${err.message}\n`);
25
+ console.log(JSON.stringify({}));
26
+ process.exit(0);
27
+ });
28
+
29
+ const SUPPORTED_EXTENSIONS = new Set([
30
+ '.ts',
31
+ '.tsx',
32
+ '.js',
33
+ '.jsx',
34
+ '.mjs',
35
+ '.cjs',
36
+ '.py',
37
+ '.go',
38
+ '.rs',
39
+ '.java',
40
+ '.c',
41
+ '.h',
42
+ '.cpp',
43
+ '.cc',
44
+ '.cxx',
45
+ '.hpp',
46
+ '.hh',
47
+ '.hxx',
48
+ ]);
49
+
50
+ const DEFAULT_EXCLUDE = new Set([
51
+ 'node_modules',
52
+ '.git',
53
+ 'dist',
54
+ 'build',
55
+ 'target',
56
+ 'vendor',
57
+ '__pycache__',
58
+ '.venv',
59
+ 'venv',
60
+ '.tox',
61
+ '.mypy_cache',
62
+ '.next',
63
+ '.nuxt',
64
+ 'coverage',
65
+ '.pytest_cache',
66
+ '.cargo',
67
+ 'bin',
68
+ 'obj',
69
+ '.gradle',
70
+ '.idea',
71
+ '.vscode',
72
+ ]);
73
+
74
+ function sha256(content) {
75
+ return createHash('sha256').update(content).digest('hex');
76
+ }
77
+
78
+ function countFiles(dir, maxFiles = 500) {
79
+ const hashes = new Map();
80
+ let count = 0;
81
+
82
+ function walk(currentDir) {
83
+ if (count >= maxFiles) return;
84
+ let entries;
85
+ try {
86
+ entries = readdirSync(currentDir, { withFileTypes: true });
87
+ } catch {
88
+ return;
89
+ }
90
+ for (const entry of entries) {
91
+ if (count >= maxFiles) return;
92
+ if (DEFAULT_EXCLUDE.has(entry.name)) continue;
93
+ const fullPath = join(currentDir, entry.name);
94
+ if (entry.isDirectory()) {
95
+ walk(fullPath);
96
+ } else if (entry.isFile()) {
97
+ const ext = extname(entry.name).toLowerCase();
98
+ if (!SUPPORTED_EXTENSIONS.has(ext)) continue;
99
+ count++;
100
+ try {
101
+ const content = readFileSync(fullPath, 'utf-8');
102
+ const relPath = fullPath.slice(dir.length + 1).replace(/\\/g, '/');
103
+ hashes.set(relPath, sha256(content));
104
+ } catch {
105
+ // skip unreadable files
106
+ }
107
+ }
108
+ }
109
+ }
110
+
111
+ walk(dir);
112
+ return { hashes, totalFiles: count };
113
+ }
114
+
115
+ function detectProjectName(dir) {
116
+ const checks = [
117
+ { file: 'package.json', extract: (c) => JSON.parse(c).name },
118
+ { file: 'Cargo.toml', extract: (c) => c.match(/name\s*=\s*"([^"]+)"/)?.[1] },
119
+ {
120
+ file: 'go.mod',
121
+ extract: (c) =>
122
+ c
123
+ .match(/module\s+(\S+)/)?.[1]
124
+ ?.split('/')
125
+ .pop(),
126
+ },
127
+ { file: 'pyproject.toml', extract: (c) => c.match(/name\s*=\s*"([^"]+)"/)?.[1] },
128
+ ];
129
+ for (const { file, extract } of checks) {
130
+ const p = join(dir, file);
131
+ if (existsSync(p)) {
132
+ try {
133
+ return extract(readFileSync(p, 'utf-8'));
134
+ } catch {
135
+ // continue
136
+ }
137
+ }
138
+ }
139
+ return dir.split(/[\\/]/).pop();
140
+ }
141
+
142
+ async function main() {
143
+ let input = '';
144
+ for await (const chunk of process.stdin) input += chunk;
145
+
146
+ let hookData = {};
147
+ try {
148
+ hookData = JSON.parse(input);
149
+ } catch {
150
+ // no stdin data
151
+ }
152
+
153
+ const cwd = hookData?.cwd || hookData?.workspace?.current_dir || process.cwd();
154
+ const projectDir = resolve(cwd);
155
+
156
+ const cachePath = join(projectDir, '.knowledge-ingest-cache.json');
157
+
158
+ if (!existsSync(cachePath)) {
159
+ const { totalFiles } = countFiles(projectDir, 100);
160
+ if (totalFiles < 3) {
161
+ console.log(JSON.stringify({}));
162
+ return;
163
+ }
164
+
165
+ const projectName = detectProjectName(projectDir);
166
+ console.log(
167
+ JSON.stringify({
168
+ hookSpecificOutput: {
169
+ hookEventName: 'SessionStart',
170
+ additionalContext: `knowledge-ingest: Project "${projectName}" (${totalFiles}+ source files) has not been ingested yet. Run \`/knowledge-ingest ${projectDir}\` to bootstrap the knowledge base.`,
171
+ },
172
+ }),
173
+ );
174
+ return;
175
+ }
176
+
177
+ let cache;
178
+ try {
179
+ cache = JSON.parse(readFileSync(cachePath, 'utf-8'));
180
+ } catch {
181
+ console.log(JSON.stringify({}));
182
+ return;
183
+ }
184
+
185
+ const cachedFiles = cache.files || {};
186
+ const { hashes: currentHashes } = countFiles(projectDir);
187
+
188
+ let changed = 0;
189
+ let added = 0;
190
+ let removed = 0;
191
+
192
+ for (const [path, hash] of currentHashes) {
193
+ if (!cachedFiles[path]) {
194
+ added++;
195
+ } else if (cachedFiles[path].sha256 !== hash) {
196
+ changed++;
197
+ }
198
+ }
199
+
200
+ for (const path of Object.keys(cachedFiles)) {
201
+ if (!currentHashes.has(path)) {
202
+ removed++;
203
+ }
204
+ }
205
+
206
+ const total = changed + added + removed;
207
+
208
+ if (total === 0) {
209
+ console.log(
210
+ JSON.stringify({
211
+ hookSpecificOutput: {
212
+ hookEventName: 'SessionStart',
213
+ additionalContext: `knowledge-ingest: Project "${cache.project}" knowledge is up to date (${Object.keys(cachedFiles).length} files, ${(cache.entries_created || []).length} entries).`,
214
+ },
215
+ }),
216
+ );
217
+ return;
218
+ }
219
+
220
+ const parts = [];
221
+ if (changed > 0) parts.push(`${changed} changed`);
222
+ if (added > 0) parts.push(`${added} new`);
223
+ if (removed > 0) parts.push(`${removed} deleted`);
224
+
225
+ console.log(
226
+ JSON.stringify({
227
+ hookSpecificOutput: {
228
+ hookEventName: 'SessionStart',
229
+ additionalContext: `knowledge-ingest: Project "${cache.project}" has ${total} file changes since last ingest (${parts.join(', ')}). Run \`/knowledge-ingest ${projectDir}\` to update.`,
230
+ },
231
+ }),
232
+ );
233
+ }
234
+
235
+ main().catch((err) => {
236
+ process.stderr.write(`[session-start-ingest] ${err.message}\n`);
237
+ console.log(JSON.stringify({}));
238
+ });
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+
3
+ // =============================================================================
4
+ // agent-knowledge SessionEnd distill hook
5
+ //
6
+ // Dumps a final session summary (turn counts, tool uses, first 20 user
7
+ // prompts) into the knowledge base when the host ends the conversation.
8
+ // Lightweight heuristic snapshot — the richer distillation happens via
9
+ // the library on next agent-knowledge startup.
10
+ //
11
+ // Fail-open.
12
+ // =============================================================================
13
+
14
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
15
+ import { join } from 'path';
16
+ import { homedir } from 'os';
17
+
18
+ process.on('uncaughtException', (err) => {
19
+ process.stderr.write(`[sessionend-distill] fatal: ${err.message}\n`);
20
+ console.log(JSON.stringify({}));
21
+ process.exit(0);
22
+ });
23
+
24
+ const MEMORY_DIR = process.env.KNOWLEDGE_MEMORY_DIR || join(homedir(), 'claude-memory');
25
+
26
+ async function main() {
27
+ let input = '';
28
+ for await (const chunk of process.stdin) input += chunk;
29
+
30
+ let hookData = {};
31
+ try {
32
+ hookData = JSON.parse(input);
33
+ } catch {
34
+ // ignore
35
+ }
36
+
37
+ const transcriptPath = hookData?.transcript_path;
38
+ const sessionId = hookData?.session_id || 'unknown';
39
+ const cwd = hookData?.workspace?.current_dir || process.cwd();
40
+
41
+ if (!transcriptPath || !existsSync(transcriptPath)) {
42
+ console.log(JSON.stringify({}));
43
+ return;
44
+ }
45
+
46
+ let raw = '';
47
+ try {
48
+ raw = readFileSync(transcriptPath, 'utf8');
49
+ } catch {
50
+ // ignore
51
+ }
52
+
53
+ const lines = raw.split(/\r?\n/).filter(Boolean);
54
+ let userTurns = 0;
55
+ let assistantTurns = 0;
56
+ let toolUses = 0;
57
+ const userMsgs = [];
58
+ for (const line of lines) {
59
+ try {
60
+ const obj = JSON.parse(line);
61
+ if (obj?.type === 'user') {
62
+ userTurns++;
63
+ if (typeof obj.message?.content === 'string') {
64
+ userMsgs.push(obj.message.content.slice(0, 300));
65
+ }
66
+ } else if (obj?.type === 'assistant') {
67
+ assistantTurns++;
68
+ const content = obj.message?.content;
69
+ if (Array.isArray(content)) {
70
+ toolUses += content.filter((c) => c.type === 'tool_use').length;
71
+ }
72
+ }
73
+ } catch {
74
+ // ignore non-JSON lines
75
+ }
76
+ }
77
+
78
+ const memDir = join(MEMORY_DIR, 'projects');
79
+ try {
80
+ mkdirSync(memDir, { recursive: true });
81
+ } catch {
82
+ // ignore
83
+ }
84
+
85
+ const slug = cwd.replace(/[^a-zA-Z0-9]+/g, '-').slice(0, 64);
86
+ const file = join(memDir, `session-${slug}-${sessionId.slice(0, 8)}.md`);
87
+ const body = `---
88
+ type: session-end
89
+ session: ${sessionId}
90
+ cwd: ${cwd}
91
+ ended: ${new Date().toISOString()}
92
+ turns: ${userTurns}u/${assistantTurns}a
93
+ tool_uses: ${toolUses}
94
+ ---
95
+
96
+ # Session ${sessionId.slice(0, 8)}
97
+
98
+ **cwd**: ${cwd}
99
+ **Turns**: ${userTurns} user / ${assistantTurns} assistant
100
+ **Tool uses**: ${toolUses}
101
+
102
+ ## User prompts (first 20)
103
+
104
+ ${userMsgs
105
+ .slice(0, 20)
106
+ .map((m, i) => `${i + 1}. ${m}`)
107
+ .join('\n')}
108
+ `;
109
+
110
+ try {
111
+ writeFileSync(file, body, 'utf8');
112
+ } catch {
113
+ // ignore
114
+ }
115
+
116
+ console.log(JSON.stringify({}));
117
+ }
118
+
119
+ main().catch((err) => {
120
+ process.stderr.write(`[sessionend-distill] ${err.message}\n`);
121
+ console.log(JSON.stringify({}));
122
+ });
@@ -0,0 +1,217 @@
1
+ #!/usr/bin/env node
2
+
3
+ // =============================================================================
4
+ // agent-knowledge setup script
5
+ //
6
+ // Configures an MCP-compatible AI agent to use agent-knowledge.
7
+ // Currently supports: Claude Code (auto-detected via ~/.claude.json)
8
+ //
9
+ // What it does:
10
+ // - Builds the project if dist/ is missing
11
+ // - Registers the MCP server in the agent's config
12
+ // - Adds lifecycle hooks for Claude Code (SessionStart banner, PreCompact
13
+ // flush + distill, SessionEnd distill)
14
+ // - Adds permission for mcp__agent-knowledge__* tools
15
+ //
16
+ // Usage: node scripts/setup.js [--agent claude|generic]
17
+ // =============================================================================
18
+
19
+ import { readFileSync, writeFileSync, existsSync, statSync, cpSync, mkdirSync } from 'fs';
20
+ import { join, resolve, dirname } from 'path';
21
+ import { homedir } from 'os';
22
+ import { execSync } from 'child_process';
23
+ import { fileURLToPath } from 'url';
24
+
25
+ const __dirname = dirname(fileURLToPath(import.meta.url));
26
+ const PROJECT_DIR = resolve(join(__dirname, '..'));
27
+ const HOME = homedir();
28
+ const CLAUDE_JSON = join(HOME, '.claude.json');
29
+ const SETTINGS_JSON = join(HOME, '.claude', 'settings.json');
30
+
31
+ const AGENT_FLAG = process.argv.find((_a, i, arr) => arr[i - 1] === '--agent') ?? 'auto';
32
+ const IS_CLAUDE = AGENT_FLAG === 'claude' || (AGENT_FLAG === 'auto' && existsSync(CLAUDE_JSON));
33
+
34
+ console.log('agent-knowledge setup\n');
35
+ console.log(`Agent type: ${IS_CLAUDE ? 'Claude Code' : 'Generic (manual MCP config)'}`);
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // Build if needed
39
+ // ---------------------------------------------------------------------------
40
+
41
+ if (!existsSync(join(PROJECT_DIR, 'dist', 'index.js'))) {
42
+ console.log('Building agent-knowledge...');
43
+ execSync('npm run build', { cwd: PROJECT_DIR, stdio: 'inherit' });
44
+ console.log('');
45
+ }
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Register MCP server
49
+ // ---------------------------------------------------------------------------
50
+
51
+ const distPath = join(PROJECT_DIR, 'dist', 'index.js');
52
+
53
+ console.log('Registering MCP server...');
54
+ if (IS_CLAUDE && existsSync(CLAUDE_JSON)) {
55
+ const config = JSON.parse(readFileSync(CLAUDE_JSON, 'utf-8'));
56
+ if (!config.mcpServers) config.mcpServers = {};
57
+
58
+ config.mcpServers['agent-knowledge'] = {
59
+ type: 'stdio',
60
+ command: 'node',
61
+ args: [distPath],
62
+ env: {},
63
+ };
64
+
65
+ writeFileSync(CLAUDE_JSON, JSON.stringify(config, null, 2));
66
+ console.log(` Added agent-knowledge MCP server → ${distPath}`);
67
+ } else {
68
+ console.log(' Add this to your MCP client config:');
69
+ console.log(' {');
70
+ console.log(' "mcpServers": {');
71
+ console.log(' "agent-knowledge": {');
72
+ console.log(' "command": "node",');
73
+ console.log(` "args": ["${distPath.replace(/\\/g, '/')}"]`);
74
+ console.log(' }');
75
+ console.log(' }');
76
+ console.log(' }');
77
+ }
78
+
79
+ // ---------------------------------------------------------------------------
80
+
81
+ if (!IS_CLAUDE) {
82
+ console.log(`
83
+ Setup complete!
84
+
85
+ Start the dashboard: node dist/server.js
86
+ MCP server (stdio): node dist/index.js
87
+ Dashboard URL: http://localhost:3423
88
+ `);
89
+ process.exit(0);
90
+ }
91
+
92
+ console.log('Configuring Claude Code hooks...');
93
+ if (!existsSync(SETTINGS_JSON)) {
94
+ console.log(' Warning: settings.json not found. Configure hooks manually.');
95
+ process.exit(0);
96
+ }
97
+
98
+ const settings = JSON.parse(readFileSync(SETTINGS_JSON, 'utf-8'));
99
+
100
+ if (!settings.permissions) settings.permissions = {};
101
+ if (!settings.permissions.allow) settings.permissions.allow = [];
102
+ if (!settings.permissions.allow.includes('mcp__agent-knowledge__*')) {
103
+ settings.permissions.allow.push('mcp__agent-knowledge__*');
104
+ console.log(' Added mcp__agent-knowledge__* permission');
105
+ }
106
+
107
+ if (!settings.hooks) settings.hooks = {};
108
+
109
+ const hookDir = join(PROJECT_DIR, 'scripts', 'hooks');
110
+
111
+ function addUnmatchedHook(eventName, marker, command, timeout = 10) {
112
+ if (!settings.hooks[eventName]) settings.hooks[eventName] = [];
113
+ const groups = settings.hooks[eventName];
114
+ const existing = groups.find(
115
+ (g) => g.hooks && g.hooks.some((h) => h.command && h.command.includes(marker)),
116
+ );
117
+ if (existing) {
118
+ console.log(` ${eventName} (${marker}): already configured`);
119
+ return;
120
+ }
121
+ if (groups.length > 0 && groups[0].hooks && !groups[0].matcher) {
122
+ groups[0].hooks.push({ type: 'command', command, timeout });
123
+ } else {
124
+ groups.push({ hooks: [{ type: 'command', command, timeout }] });
125
+ }
126
+ console.log(` ${eventName}: added ${marker} hook`);
127
+ }
128
+
129
+ // SessionStart: dashboard banner
130
+ addUnmatchedHook(
131
+ 'SessionStart',
132
+ 'session-start.js',
133
+ `node "${join(hookDir, 'session-start.js')}"`,
134
+ 5,
135
+ );
136
+
137
+ // SessionStart: knowledge-ingest freshness check
138
+ addUnmatchedHook(
139
+ 'SessionStart',
140
+ 'session-start-ingest.mjs',
141
+ `node "${join(hookDir, 'session-start-ingest.mjs')}"`,
142
+ 10,
143
+ );
144
+
145
+ // PreCompact: rich summary (library) + simple text distill (heuristic)
146
+ addUnmatchedHook(
147
+ 'PreCompact',
148
+ 'precompact-flush.mjs',
149
+ `node "${join(hookDir, 'precompact-flush.mjs')}"`,
150
+ 10,
151
+ );
152
+ addUnmatchedHook(
153
+ 'PreCompact',
154
+ 'precompact-distill.mjs',
155
+ `node "${join(hookDir, 'precompact-distill.mjs')}"`,
156
+ 10,
157
+ );
158
+
159
+ // SessionEnd: simple text distill for cross-machine memory
160
+ addUnmatchedHook(
161
+ 'SessionEnd',
162
+ 'sessionend-distill.mjs',
163
+ `node "${join(hookDir, 'sessionend-distill.mjs')}"`,
164
+ 10,
165
+ );
166
+
167
+ writeFileSync(SETTINGS_JSON, JSON.stringify(settings, null, 2));
168
+ console.log(' Saved settings.json');
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // Install knowledge-ingest skill
172
+ // ---------------------------------------------------------------------------
173
+
174
+ console.log('Installing knowledge-ingest skill...');
175
+
176
+ const skillSrc = join(PROJECT_DIR, 'skills', 'knowledge-ingest', 'SKILL.md');
177
+
178
+ const skillDests = [
179
+ join(HOME, '.claude', 'skills', 'knowledge-ingest', 'SKILL.md'),
180
+ join(HOME, '.agents', 'skills', 'knowledge-ingest', 'SKILL.md'),
181
+ ];
182
+
183
+ if (existsSync(skillSrc)) {
184
+ const srcMtime = statSync(skillSrc).mtimeMs;
185
+ for (const dest of skillDests) {
186
+ mkdirSync(dirname(dest), { recursive: true });
187
+ let shouldCopy = true;
188
+ if (existsSync(dest)) {
189
+ if (statSync(dest).mtimeMs >= srcMtime) {
190
+ shouldCopy = false;
191
+ }
192
+ }
193
+ if (shouldCopy) {
194
+ cpSync(skillSrc, dest);
195
+ console.log(` Installed → ${dest}`);
196
+ } else {
197
+ console.log(` Up to date → ${dest}`);
198
+ }
199
+ }
200
+ } else {
201
+ console.log(' Warning: skills/knowledge-ingest/SKILL.md not found in repo');
202
+ }
203
+
204
+ console.log(`
205
+ Setup complete!
206
+
207
+ Restart Claude Code to load the new MCP server. Every session will now:
208
+ - Show the knowledge dashboard URL on start (SessionStart hook)
209
+ - Flush a rich session summary before compaction (precompact-flush)
210
+ - Snapshot recent user prompts before compaction (precompact-distill)
211
+ - Dump a final session summary on exit (sessionend-distill)
212
+
213
+ Dashboard: http://localhost:3423 (auto-starts on first MCP connection)
214
+ Knowledge base: ~/claude-memory/ (configurable via KNOWLEDGE_MEMORY_DIR)
215
+
216
+ See docs/hooks.md for details and docs/SETUP.md for manual configuration.
217
+ `);