agent-knowledge 2.0.0 → 3.0.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.
- package/CHANGELOG.md +48 -0
- package/README.md +35 -32
- package/dist/events.d.ts +6 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +10 -2
- package/dist/events.js.map +1 -1
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -1
- package/dist/knowledge/analyze.d.ts.map +1 -1
- package/dist/knowledge/analyze.js +18 -11
- package/dist/knowledge/analyze.js.map +1 -1
- package/dist/knowledge/distill.d.ts.map +1 -1
- package/dist/knowledge/distill.js +28 -16
- package/dist/knowledge/distill.js.map +1 -1
- package/dist/knowledge/git.d.ts +3 -4
- package/dist/knowledge/git.d.ts.map +1 -1
- package/dist/knowledge/git.js +60 -46
- package/dist/knowledge/git.js.map +1 -1
- package/dist/knowledge/graph.d.ts +2 -0
- package/dist/knowledge/graph.d.ts.map +1 -1
- package/dist/knowledge/graph.js +8 -0
- package/dist/knowledge/graph.js.map +1 -1
- package/dist/knowledge/ingest-freshness.d.ts +22 -0
- package/dist/knowledge/ingest-freshness.d.ts.map +1 -0
- package/dist/knowledge/ingest-freshness.js +93 -0
- package/dist/knowledge/ingest-freshness.js.map +1 -0
- package/dist/knowledge/remove.d.ts +11 -0
- package/dist/knowledge/remove.d.ts.map +1 -0
- package/dist/knowledge/remove.js +24 -0
- package/dist/knowledge/remove.js.map +1 -0
- package/dist/knowledge/search.d.ts +74 -8
- package/dist/knowledge/search.d.ts.map +1 -1
- package/dist/knowledge/search.js +321 -40
- package/dist/knowledge/search.js.map +1 -1
- package/dist/knowledge/similar.d.ts +7 -0
- package/dist/knowledge/similar.d.ts.map +1 -0
- package/dist/knowledge/similar.js +51 -0
- package/dist/knowledge/similar.js.map +1 -0
- package/dist/knowledge/store.d.ts +17 -0
- package/dist/knowledge/store.d.ts.map +1 -1
- package/dist/knowledge/store.js +117 -79
- package/dist/knowledge/store.js.map +1 -1
- package/dist/rest-server.d.ts +12 -2
- package/dist/rest-server.d.ts.map +1 -1
- package/dist/rest-server.js +75 -10
- package/dist/rest-server.js.map +1 -1
- package/dist/search/bm25.d.ts +8 -0
- package/dist/search/bm25.d.ts.map +1 -1
- package/dist/search/bm25.js +32 -20
- package/dist/search/bm25.js.map +1 -1
- package/dist/search/excerpt.d.ts +1 -1
- package/dist/search/excerpt.d.ts.map +1 -1
- package/dist/search/excerpt.js +19 -1
- package/dist/search/excerpt.js.map +1 -1
- package/dist/search/lexicon.d.ts +37 -0
- package/dist/search/lexicon.d.ts.map +1 -0
- package/dist/search/lexicon.js +83 -0
- package/dist/search/lexicon.js.map +1 -0
- package/dist/search/mmr.d.ts +9 -3
- package/dist/search/mmr.d.ts.map +1 -1
- package/dist/search/mmr.js +21 -7
- package/dist/search/mmr.js.map +1 -1
- package/dist/search/types.d.ts +2 -0
- package/dist/search/types.d.ts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +0 -5
- package/dist/server.js.map +1 -1
- package/dist/sessions/human.d.ts +12 -0
- package/dist/sessions/human.d.ts.map +1 -0
- package/dist/sessions/human.js +52 -0
- package/dist/sessions/human.js.map +1 -0
- package/dist/sessions/parser.d.ts +39 -0
- package/dist/sessions/parser.d.ts.map +1 -1
- package/dist/sessions/parser.js +142 -18
- package/dist/sessions/parser.js.map +1 -1
- package/dist/sessions/search.d.ts +2 -0
- package/dist/sessions/search.d.ts.map +1 -1
- package/dist/sessions/search.js +147 -67
- package/dist/sessions/search.js.map +1 -1
- package/dist/sessions/snapshot.d.ts +19 -0
- package/dist/sessions/snapshot.d.ts.map +1 -0
- package/dist/sessions/snapshot.js +118 -0
- package/dist/sessions/snapshot.js.map +1 -0
- package/dist/sessions/summary.d.ts +24 -5
- package/dist/sessions/summary.d.ts.map +1 -1
- package/dist/sessions/summary.js +106 -145
- package/dist/sessions/summary.js.map +1 -1
- package/dist/slice.d.ts +5 -0
- package/dist/slice.d.ts.map +1 -0
- package/dist/slice.js +28 -0
- package/dist/slice.js.map +1 -0
- package/dist/text.d.ts +9 -0
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +16 -0
- package/dist/text.js.map +1 -0
- package/dist/tool-handlers.d.ts.map +1 -1
- package/dist/tool-handlers.js +6 -10
- package/dist/tool-handlers.js.map +1 -1
- package/dist/transport/rest.d.ts.map +1 -1
- package/dist/transport/rest.js +152 -35
- package/dist/transport/rest.js.map +1 -1
- package/dist/vectorstore/store.d.ts +9 -0
- package/dist/vectorstore/store.d.ts.map +1 -1
- package/dist/vectorstore/store.js +23 -0
- package/dist/vectorstore/store.js.map +1 -1
- package/dist/wakeup.d.ts +5 -0
- package/dist/wakeup.d.ts.map +1 -1
- package/dist/wakeup.js +10 -1
- package/dist/wakeup.js.map +1 -1
- package/docs/ARCHITECTURE.md +6 -9
- package/docs/HOOKS.md +138 -237
- package/docs/SETUP.md +61 -122
- package/docs/USER-MANUAL.md +39 -31
- package/package.json +6 -6
- package/plugin/skills/knowledge-ingest/scripts/validate.mjs +2 -2
- package/scripts/plugins/opencode/agent-knowledge.ts +32 -81
- package/scripts/setup.js +78 -145
- package/scripts/source-walk.d.mts +12 -0
- package/scripts/source-walk.mjs +94 -0
- package/scripts/tree-sitter-extract.mjs +10 -76
- package/scripts/hooks/first-prompt-inject.mjs +0 -242
- package/scripts/hooks/precompact-distill.mjs +0 -105
- package/scripts/hooks/precompact-flush.mjs +0 -192
- package/scripts/hooks/session-start-ingest.mjs +0 -238
- package/scripts/hooks/session-start.js +0 -211
- package/scripts/hooks/sessionend-distill.mjs +0 -198
|
@@ -1,238 +0,0 @@
|
|
|
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
|
-
});
|
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// =============================================================================
|
|
4
|
-
// agent-knowledge SessionStart hook
|
|
5
|
-
//
|
|
6
|
-
// 1. Says where the person browses the knowledge base (the /knowledge pane).
|
|
7
|
-
// 2. Auto-loads the L0 identity section into the host's additionalContext so
|
|
8
|
-
// the agent starts each session with "who the user is" already in the
|
|
9
|
-
// prompt — query-agnostic facts that apply regardless of the first question.
|
|
10
|
-
// 3. Clears the first-prompt-inject marker for this session_id so a resumed
|
|
11
|
-
// or cleared session gets another shot at query-targeted L1 injection.
|
|
12
|
-
// Without this, /exit + resume re-uses the session_id and the inject hook
|
|
13
|
-
// silently skips because the marker from the prior run is still on disk.
|
|
14
|
-
//
|
|
15
|
-
// L1 top-weighted facts are NOT auto-injected here anymore. The companion
|
|
16
|
-
// `first-prompt-inject.mjs` hook runs query-targeted search against the KB
|
|
17
|
-
// on the session's first real prompt, which produces a better-matched slice
|
|
18
|
-
// than any query-agnostic pre-load.
|
|
19
|
-
//
|
|
20
|
-
// Disable auto-wakeup entirely by exporting AGENT_KNOWLEDGE_AUTOWAKE=0.
|
|
21
|
-
// Tune the identity slice with AGENT_KNOWLEDGE_WAKEUP_BUDGET (default 200
|
|
22
|
-
// tokens — L0 is small, doesn't need the legacy 800-token window).
|
|
23
|
-
//
|
|
24
|
-
// Fail-open: every error path still prints a valid JSON hook response so the
|
|
25
|
-
// session never blocks on this hook.
|
|
26
|
-
// =============================================================================
|
|
27
|
-
|
|
28
|
-
import { existsSync, rmSync } from 'fs';
|
|
29
|
-
import path, { dirname, resolve, join } from 'path';
|
|
30
|
-
import { fileURLToPath } from 'url';
|
|
31
|
-
import { homedir } from 'os';
|
|
32
|
-
|
|
33
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
34
|
-
const __dirname = dirname(__filename);
|
|
35
|
-
|
|
36
|
-
const autoWakeEnabled =
|
|
37
|
-
(process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== '0' &&
|
|
38
|
-
(process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== 'false';
|
|
39
|
-
const wakeupBudget = Number.parseInt(process.env.AGENT_KNOWLEDGE_WAKEUP_BUDGET ?? '200', 10) || 200;
|
|
40
|
-
|
|
41
|
-
function emit(additionalContext, statusSuffix) {
|
|
42
|
-
const base = 'agent-knowledge: /knowledge';
|
|
43
|
-
const systemMessage = statusSuffix ? `${base} | ${statusSuffix}` : base;
|
|
44
|
-
const msg = {
|
|
45
|
-
systemMessage,
|
|
46
|
-
hookSpecificOutput: {
|
|
47
|
-
hookEventName: 'SessionStart',
|
|
48
|
-
additionalContext,
|
|
49
|
-
},
|
|
50
|
-
};
|
|
51
|
-
process.stdout.write(JSON.stringify(msg) + '\n');
|
|
52
|
-
process.exit(0);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
async function readStdin() {
|
|
56
|
-
return new Promise((resolveP) => {
|
|
57
|
-
let data = '';
|
|
58
|
-
if (process.stdin.isTTY) return resolveP('');
|
|
59
|
-
process.stdin.setEncoding('utf-8');
|
|
60
|
-
process.stdin.on('data', (chunk) => (data += chunk));
|
|
61
|
-
process.stdin.on('end', () => resolveP(data));
|
|
62
|
-
setTimeout(() => resolveP(data), 1500);
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Keep in sync with first-prompt-inject.mjs dataDir().
|
|
67
|
-
function dataDir() {
|
|
68
|
-
if (process.env.AGENT_KNOWLEDGE_DATA_DIR) return process.env.AGENT_KNOWLEDGE_DATA_DIR;
|
|
69
|
-
if (process.platform === 'win32') {
|
|
70
|
-
return path.join(
|
|
71
|
-
process.env.APPDATA || path.join(homedir(), 'AppData', 'Roaming'),
|
|
72
|
-
'knowledge',
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'), 'knowledge');
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function memoryDir() {
|
|
79
|
-
return process.env.AGENT_KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function identityOnboardingState() {
|
|
83
|
-
const dir = memoryDir();
|
|
84
|
-
try {
|
|
85
|
-
if (existsSync(join(dir, 'identity.md')) || existsSync(join(dir, 'IDENTITY.md'))) {
|
|
86
|
-
return 'configured';
|
|
87
|
-
}
|
|
88
|
-
if (existsSync(join(dir, '.identity-declined'))) {
|
|
89
|
-
return 'declined';
|
|
90
|
-
}
|
|
91
|
-
} catch {
|
|
92
|
-
return 'unknown';
|
|
93
|
-
}
|
|
94
|
-
return 'pending';
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const ONBOARDING_INSTRUCTION = [
|
|
98
|
-
'',
|
|
99
|
-
'--- Identity onboarding (no identity.md yet) ---',
|
|
100
|
-
`The user has no ~/agent-knowledge/identity.md. Before diving into their request, briefly ask:`,
|
|
101
|
-
' 1. Name + primary role',
|
|
102
|
-
' 2. Main stack / tech focus',
|
|
103
|
-
' 3. Projects they maintain',
|
|
104
|
-
`Then use the Write tool to save their answers to \`~/agent-knowledge/identity.md\` as short markdown.`,
|
|
105
|
-
`If the user says "skip" / "not now" / declines, use Write to create an empty file at \`~/agent-knowledge/.identity-declined\` so this prompt stops appearing.`,
|
|
106
|
-
`Do not invent facts — only record what the user actually tells you.`,
|
|
107
|
-
].join('\n');
|
|
108
|
-
|
|
109
|
-
function clearFirstPromptMarker(sessionId) {
|
|
110
|
-
if (!sessionId || typeof sessionId !== 'string') return false;
|
|
111
|
-
try {
|
|
112
|
-
const marker = path.join(dataDir(), '.first-prompt-seen', sessionId);
|
|
113
|
-
if (existsSync(marker)) {
|
|
114
|
-
rmSync(marker, { force: true });
|
|
115
|
-
return true;
|
|
116
|
-
}
|
|
117
|
-
} catch (err) {
|
|
118
|
-
process.stderr.write(`[knowledge session-start] marker clear failed: ${err?.message || err}\n`);
|
|
119
|
-
}
|
|
120
|
-
return false;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async function loadIdentitySection() {
|
|
124
|
-
const distWakeup = resolve(__dirname, '..', '..', 'dist', 'wakeup.js');
|
|
125
|
-
if (!existsSync(distWakeup)) return { rendered: null, hasIdentity: false, bodyChars: 0 };
|
|
126
|
-
try {
|
|
127
|
-
const mod = await import(`file://${distWakeup.replace(/\\/g, '/')}`);
|
|
128
|
-
if (typeof mod.buildContextBundle !== 'function') {
|
|
129
|
-
return { rendered: null, hasIdentity: false, bodyChars: 0 };
|
|
130
|
-
}
|
|
131
|
-
const result = mod.buildContextBundle({
|
|
132
|
-
tokenBudget: wakeupBudget,
|
|
133
|
-
sections: ['identity'],
|
|
134
|
-
});
|
|
135
|
-
if (!result || typeof result.rendered !== 'string' || result.rendered.length === 0) {
|
|
136
|
-
return { rendered: null, hasIdentity: false, bodyChars: 0 };
|
|
137
|
-
}
|
|
138
|
-
const identitySection = (result.sections ?? []).find((s) => s.name === 'identity');
|
|
139
|
-
const hasIdentity = !!(identitySection && !identitySection.empty);
|
|
140
|
-
const bodyChars = identitySection?.content?.length ?? result.rendered.length;
|
|
141
|
-
return { rendered: result.rendered, hasIdentity, bodyChars };
|
|
142
|
-
} catch (err) {
|
|
143
|
-
process.stderr.write(
|
|
144
|
-
`[knowledge session-start] identity load failed: ${err?.message || err}\n`,
|
|
145
|
-
);
|
|
146
|
-
}
|
|
147
|
-
return { rendered: null, hasIdentity: false, bodyChars: 0 };
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
async function main() {
|
|
151
|
-
const raw = await readStdin();
|
|
152
|
-
let payload = {};
|
|
153
|
-
if (raw) {
|
|
154
|
-
try {
|
|
155
|
-
payload = JSON.parse(raw);
|
|
156
|
-
} catch {
|
|
157
|
-
/* ignore — host may not pipe JSON */
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID;
|
|
161
|
-
const source = payload.source || 'startup';
|
|
162
|
-
|
|
163
|
-
// Re-arm first-prompt-inject for this session_id. Resumed sessions reuse the
|
|
164
|
-
// session_id, so without this the inject hook's marker from the previous
|
|
165
|
-
// run would skip the very next user prompt.
|
|
166
|
-
const markerCleared = clearFirstPromptMarker(sessionId);
|
|
167
|
-
|
|
168
|
-
const paneLine = 'Knowledge: the person browses the knowledge base in the /knowledge pane.';
|
|
169
|
-
|
|
170
|
-
const autowakeOffSuffix = markerCleared ? `${source} · inject rearmed` : source;
|
|
171
|
-
if (!autoWakeEnabled) {
|
|
172
|
-
return emit(paneLine, `autowake off · ${autowakeOffSuffix}`);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const { rendered, hasIdentity, bodyChars } = await loadIdentitySection();
|
|
176
|
-
const onboarding = hasIdentity ? 'configured' : identityOnboardingState();
|
|
177
|
-
|
|
178
|
-
let identityStatus;
|
|
179
|
-
if (hasIdentity) {
|
|
180
|
-
identityStatus = `identity: ${bodyChars} chars`;
|
|
181
|
-
} else if (onboarding === 'pending') {
|
|
182
|
-
identityStatus = 'identity: onboarding pending';
|
|
183
|
-
} else if (onboarding === 'declined') {
|
|
184
|
-
identityStatus = 'identity: declined (delete ~/agent-knowledge/.identity-declined to redo)';
|
|
185
|
-
} else {
|
|
186
|
-
identityStatus = 'identity: placeholder (no identity.md)';
|
|
187
|
-
}
|
|
188
|
-
const rearmStatus = markerCleared ? ' · inject rearmed' : '';
|
|
189
|
-
const suffix = `${identityStatus}${rearmStatus}`;
|
|
190
|
-
|
|
191
|
-
const onboardingBlock = onboarding === 'pending' ? ONBOARDING_INSTRUCTION : '';
|
|
192
|
-
|
|
193
|
-
if (!rendered) {
|
|
194
|
-
return emit(`${paneLine}${onboardingBlock}`, suffix);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
const base = [
|
|
198
|
-
paneLine,
|
|
199
|
-
'',
|
|
200
|
-
'--- Knowledge wakeup (identity only; call `knowledge action=wakeup` for L1 facts) ---',
|
|
201
|
-
rendered,
|
|
202
|
-
].join('\n');
|
|
203
|
-
const combined = onboardingBlock ? `${base}\n${onboardingBlock}` : base;
|
|
204
|
-
|
|
205
|
-
emit(combined, suffix);
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
main().catch((err) => {
|
|
209
|
-
process.stderr.write(`[knowledge session-start] ${err?.message || err}\n`);
|
|
210
|
-
emit(`Knowledge: http://localhost:${knowledgePort}`, null);
|
|
211
|
-
});
|
|
@@ -1,198 +0,0 @@
|
|
|
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
|
-
// Emits a top-level `systemMessage` so the user can see the hook actually
|
|
12
|
-
// fired (receipt of what was distilled, or reason for skipping). Also
|
|
13
|
-
// appends a one-line breadcrumb to `~/agent-knowledge/sessions/index.md`
|
|
14
|
-
// so the receipt is durable even if the host tears the transcript down
|
|
15
|
-
// before painting the message.
|
|
16
|
-
//
|
|
17
|
-
// Fail-open.
|
|
18
|
-
// =============================================================================
|
|
19
|
-
|
|
20
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync } from 'fs';
|
|
21
|
-
import { join } from 'path';
|
|
22
|
-
import { homedir } from 'os';
|
|
23
|
-
import { request } from 'http';
|
|
24
|
-
|
|
25
|
-
process.on('uncaughtException', (err) => {
|
|
26
|
-
process.stderr.write(`[sessionend-distill] fatal: ${err.message}\n`);
|
|
27
|
-
emit();
|
|
28
|
-
process.exit(0);
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
const MEMORY_DIR = process.env.AGENT_KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
|
|
32
|
-
|
|
33
|
-
function emit(systemMessage) {
|
|
34
|
-
const payload = systemMessage ? { systemMessage } : {};
|
|
35
|
-
process.stdout.write(JSON.stringify(payload) + '\n');
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function appendBreadcrumb(line) {
|
|
39
|
-
try {
|
|
40
|
-
const dir = join(MEMORY_DIR, 'sessions');
|
|
41
|
-
mkdirSync(dir, { recursive: true });
|
|
42
|
-
const file = join(dir, 'index.md');
|
|
43
|
-
const header = existsSync(file) ? '' : '# Session flushes\n';
|
|
44
|
-
appendFileSync(file, header + line + '\n', 'utf8');
|
|
45
|
-
} catch {
|
|
46
|
-
// ignore — breadcrumb is best-effort
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Best-effort POST to the agent-knowledge REST server so the /knowledge pane
|
|
51
|
-
// shows the receipt when the session ends. Silently drops on any failure (server
|
|
52
|
-
// not running, network error, timeout) — the disk receipts are authoritative.
|
|
53
|
-
function postEvent(kind, message) {
|
|
54
|
-
return new Promise((resolve) => {
|
|
55
|
-
if (process.env.AGENT_KNOWLEDGE_EVENTS === '0') {
|
|
56
|
-
resolve();
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
const port = Number(process.env.AGENT_KNOWLEDGE_PORT || 3423);
|
|
60
|
-
if (!Number.isFinite(port) || port <= 0 || port > 65535) {
|
|
61
|
-
resolve();
|
|
62
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
const payload = JSON.stringify({ kind, message });
|
|
65
|
-
const req = request(
|
|
66
|
-
{
|
|
67
|
-
host: '127.0.0.1',
|
|
68
|
-
port,
|
|
69
|
-
path: '/api/events',
|
|
70
|
-
method: 'POST',
|
|
71
|
-
headers: {
|
|
72
|
-
'Content-Type': 'application/json',
|
|
73
|
-
'Content-Length': Buffer.byteLength(payload),
|
|
74
|
-
},
|
|
75
|
-
timeout: 1500,
|
|
76
|
-
},
|
|
77
|
-
(res) => {
|
|
78
|
-
res.on('data', () => {});
|
|
79
|
-
res.on('end', resolve);
|
|
80
|
-
},
|
|
81
|
-
);
|
|
82
|
-
req.on('timeout', () => {
|
|
83
|
-
req.destroy();
|
|
84
|
-
resolve();
|
|
85
|
-
});
|
|
86
|
-
req.on('error', () => resolve());
|
|
87
|
-
req.write(payload);
|
|
88
|
-
req.end();
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
async function main() {
|
|
93
|
-
let input = '';
|
|
94
|
-
for await (const chunk of process.stdin) input += chunk;
|
|
95
|
-
|
|
96
|
-
let hookData = {};
|
|
97
|
-
try {
|
|
98
|
-
hookData = JSON.parse(input);
|
|
99
|
-
} catch {
|
|
100
|
-
// ignore
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
const transcriptPath = hookData?.transcript_path;
|
|
104
|
-
const sessionId = hookData?.session_id || 'unknown';
|
|
105
|
-
const cwd = hookData?.workspace?.current_dir || process.cwd();
|
|
106
|
-
|
|
107
|
-
if (!transcriptPath || !existsSync(transcriptPath)) {
|
|
108
|
-
emit('knowledge: SessionEnd skipped — transcript unavailable');
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
let raw = '';
|
|
113
|
-
try {
|
|
114
|
-
raw = readFileSync(transcriptPath, 'utf8');
|
|
115
|
-
} catch {
|
|
116
|
-
// ignore
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const lines = raw.split(/\r?\n/).filter(Boolean);
|
|
120
|
-
let userTurns = 0;
|
|
121
|
-
let assistantTurns = 0;
|
|
122
|
-
let toolUses = 0;
|
|
123
|
-
const userMsgs = [];
|
|
124
|
-
for (const line of lines) {
|
|
125
|
-
try {
|
|
126
|
-
const obj = JSON.parse(line);
|
|
127
|
-
if (obj?.type === 'user') {
|
|
128
|
-
userTurns++;
|
|
129
|
-
if (typeof obj.message?.content === 'string') {
|
|
130
|
-
userMsgs.push(obj.message.content.slice(0, 300));
|
|
131
|
-
}
|
|
132
|
-
} else if (obj?.type === 'assistant') {
|
|
133
|
-
assistantTurns++;
|
|
134
|
-
const content = obj.message?.content;
|
|
135
|
-
if (Array.isArray(content)) {
|
|
136
|
-
toolUses += content.filter((c) => c.type === 'tool_use').length;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
} catch {
|
|
140
|
-
// ignore non-JSON lines
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
const memDir = join(MEMORY_DIR, 'projects');
|
|
145
|
-
try {
|
|
146
|
-
mkdirSync(memDir, { recursive: true });
|
|
147
|
-
} catch {
|
|
148
|
-
// ignore
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const slug = cwd.replace(/[^a-zA-Z0-9]+/g, '-').slice(0, 64);
|
|
152
|
-
const file = join(memDir, `session-${slug}-${sessionId.slice(0, 8)}.md`);
|
|
153
|
-
const endedAt = new Date().toISOString();
|
|
154
|
-
const body = `---
|
|
155
|
-
type: session-end
|
|
156
|
-
session: ${sessionId}
|
|
157
|
-
cwd: ${cwd}
|
|
158
|
-
ended: ${endedAt}
|
|
159
|
-
turns: ${userTurns}u/${assistantTurns}a
|
|
160
|
-
tool_uses: ${toolUses}
|
|
161
|
-
---
|
|
162
|
-
|
|
163
|
-
# Session ${sessionId.slice(0, 8)}
|
|
164
|
-
|
|
165
|
-
**cwd**: ${cwd}
|
|
166
|
-
**Turns**: ${userTurns} user / ${assistantTurns} assistant
|
|
167
|
-
**Tool uses**: ${toolUses}
|
|
168
|
-
|
|
169
|
-
## User prompts (first 20)
|
|
170
|
-
|
|
171
|
-
${userMsgs
|
|
172
|
-
.slice(0, 20)
|
|
173
|
-
.map((m, i) => `${i + 1}. ${m}`)
|
|
174
|
-
.join('\n')}
|
|
175
|
-
`;
|
|
176
|
-
|
|
177
|
-
let wrote = false;
|
|
178
|
-
try {
|
|
179
|
-
writeFileSync(file, body, 'utf8');
|
|
180
|
-
wrote = true;
|
|
181
|
-
} catch (err) {
|
|
182
|
-
process.stderr.write(`[sessionend-distill] write failed: ${err?.message || err}\n`);
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
if (wrote) {
|
|
186
|
-
appendBreadcrumb(`- SessionEnd ${endedAt} ${sessionId} → ${file}`);
|
|
187
|
-
const receipt = `${userTurns}u/${assistantTurns}a turns, ${toolUses} tool uses → ${file}`;
|
|
188
|
-
await postEvent('session-end', receipt);
|
|
189
|
-
emit(`knowledge: SessionEnd — ${receipt}`);
|
|
190
|
-
} else {
|
|
191
|
-
emit(`knowledge: SessionEnd — write failed for ${file}`);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
main().catch((err) => {
|
|
196
|
-
process.stderr.write(`[sessionend-distill] ${err.message}\n`);
|
|
197
|
-
emit('knowledge: SessionEnd — hook crashed (fail-open)');
|
|
198
|
-
});
|