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,242 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// =============================================================================
|
|
4
|
-
// agent-knowledge UserPromptSubmit hook — first-prompt knowledge injection
|
|
5
|
-
//
|
|
6
|
-
// When the user sends the FIRST real prompt of a session, run the prompt text
|
|
7
|
-
// through knowledge_search and inject the top-K hits as additionalContext
|
|
8
|
-
// before the model sees the prompt. Complements the SessionStart wakeup
|
|
9
|
-
// (which is query-agnostic) by pulling in entries that are directly relevant
|
|
10
|
-
// to whatever the user is about to ask.
|
|
11
|
-
//
|
|
12
|
-
// Gates (all must pass to fire):
|
|
13
|
-
// - AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT != 0 / false / off
|
|
14
|
-
// - Prompt is >= 10 chars
|
|
15
|
-
// - Prompt does not start with `/` (skip slash commands)
|
|
16
|
-
// - No marker file exists yet for this session id
|
|
17
|
-
//
|
|
18
|
-
// Fires once per session. Subsequent prompts see only the wakeup pack and
|
|
19
|
-
// whatever they search for themselves. A marker file at
|
|
20
|
-
// `{dataDir}/.first-prompt-seen/<session_id>` records "already fired".
|
|
21
|
-
//
|
|
22
|
-
// Envs:
|
|
23
|
-
// AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT (default "1") — set "0" to disable
|
|
24
|
-
// AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET (default "600") — max chars/4 tokens
|
|
25
|
-
// AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS (default "4") — cap on rendered hits
|
|
26
|
-
// AGENT_KNOWLEDGE_MEMORY_DIR — resolves memory dir (same as core)
|
|
27
|
-
//
|
|
28
|
-
// Fail-open: every error path prints `{}` so the host never blocks on this
|
|
29
|
-
// hook. Log-only stderr for diagnostics.
|
|
30
|
-
// =============================================================================
|
|
31
|
-
|
|
32
|
-
import fs from 'fs';
|
|
33
|
-
import path from 'path';
|
|
34
|
-
import { dirname, resolve } from 'path';
|
|
35
|
-
import { fileURLToPath } from 'url';
|
|
36
|
-
import { homedir } from 'os';
|
|
37
|
-
|
|
38
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
39
|
-
const __dirname = dirname(__filename);
|
|
40
|
-
|
|
41
|
-
function emit(additionalContext, systemMessage) {
|
|
42
|
-
const payload = additionalContext
|
|
43
|
-
? {
|
|
44
|
-
hookSpecificOutput: {
|
|
45
|
-
hookEventName: 'UserPromptSubmit',
|
|
46
|
-
additionalContext,
|
|
47
|
-
},
|
|
48
|
-
}
|
|
49
|
-
: {};
|
|
50
|
-
if (systemMessage) payload.systemMessage = systemMessage;
|
|
51
|
-
process.stdout.write(JSON.stringify(payload) + '\n');
|
|
52
|
-
process.exit(0);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function summarizeHits(hits) {
|
|
56
|
-
if (!hits || hits.length === 0) return null;
|
|
57
|
-
const paths = hits
|
|
58
|
-
.map((h) => h.entry?.path)
|
|
59
|
-
.filter(Boolean)
|
|
60
|
-
.slice(0, 2);
|
|
61
|
-
const suffix = hits.length > paths.length ? `, +${hits.length - paths.length} more` : '';
|
|
62
|
-
const list = paths.length ? ` (${paths.join(', ')}${suffix})` : '';
|
|
63
|
-
return `knowledge: injected ${hits.length} hit${hits.length === 1 ? '' : 's'}${list}`;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function warn(msg) {
|
|
67
|
-
process.stderr.write(`[knowledge firstprompt] ${msg}\n`);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function isEnabled() {
|
|
71
|
-
const raw = (process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT ?? '1').trim().toLowerCase();
|
|
72
|
-
return raw !== '0' && raw !== 'false' && raw !== 'off';
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function tokenBudget() {
|
|
76
|
-
const raw = process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET ?? '600';
|
|
77
|
-
const n = Number.parseInt(raw, 10);
|
|
78
|
-
if (Number.isFinite(n) && n >= 100 && n <= 8000) return n;
|
|
79
|
-
return 600;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function maxHits() {
|
|
83
|
-
const raw = process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS ?? '4';
|
|
84
|
-
const n = Number.parseInt(raw, 10);
|
|
85
|
-
if (Number.isFinite(n) && n >= 1 && n <= 20) return n;
|
|
86
|
-
return 4;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
function memoryDir() {
|
|
90
|
-
return process.env.AGENT_KNOWLEDGE_MEMORY_DIR || path.join(homedir(), 'agent-knowledge');
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
function dataDir() {
|
|
94
|
-
if (process.env.AGENT_KNOWLEDGE_DATA_DIR) return process.env.AGENT_KNOWLEDGE_DATA_DIR;
|
|
95
|
-
if (process.platform === 'win32') {
|
|
96
|
-
return path.join(
|
|
97
|
-
process.env.APPDATA || path.join(homedir(), 'AppData', 'Roaming'),
|
|
98
|
-
'knowledge',
|
|
99
|
-
);
|
|
100
|
-
}
|
|
101
|
-
return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'), 'knowledge');
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
async function readStdin() {
|
|
105
|
-
return new Promise((resolveP) => {
|
|
106
|
-
let data = '';
|
|
107
|
-
if (process.stdin.isTTY) return resolveP('');
|
|
108
|
-
process.stdin.setEncoding('utf-8');
|
|
109
|
-
process.stdin.on('data', (chunk) => (data += chunk));
|
|
110
|
-
process.stdin.on('end', () => resolveP(data));
|
|
111
|
-
setTimeout(() => resolveP(data), 1500);
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function markerPath(sessionId) {
|
|
116
|
-
return path.join(dataDir(), '.first-prompt-seen', sessionId);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
function hasFired(sessionId) {
|
|
120
|
-
try {
|
|
121
|
-
return fs.existsSync(markerPath(sessionId));
|
|
122
|
-
} catch {
|
|
123
|
-
return false;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function recordFired(sessionId) {
|
|
128
|
-
try {
|
|
129
|
-
const file = markerPath(sessionId);
|
|
130
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
131
|
-
fs.writeFileSync(file, new Date().toISOString(), 'utf-8');
|
|
132
|
-
} catch (err) {
|
|
133
|
-
warn(`marker write failed: ${err?.message || err}`);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function isSkippablePrompt(prompt) {
|
|
138
|
-
const trimmed = (prompt ?? '').trim();
|
|
139
|
-
if (trimmed.length < 10) return true;
|
|
140
|
-
if (trimmed.startsWith('/')) return true;
|
|
141
|
-
if (trimmed.startsWith('!')) return true;
|
|
142
|
-
return false;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
async function loadSearch() {
|
|
146
|
-
const distSearch = resolve(__dirname, '..', '..', 'dist', 'knowledge', 'search.js');
|
|
147
|
-
if (!fs.existsSync(distSearch)) {
|
|
148
|
-
warn(`dist not built: ${distSearch} (run \`npm run build\`)`);
|
|
149
|
-
return null;
|
|
150
|
-
}
|
|
151
|
-
try {
|
|
152
|
-
const mod = await import(`file://${distSearch.replace(/\\/g, '/')}`);
|
|
153
|
-
if (typeof mod.searchKnowledge !== 'function') {
|
|
154
|
-
warn('searchKnowledge not exported');
|
|
155
|
-
return null;
|
|
156
|
-
}
|
|
157
|
-
return mod.searchKnowledge;
|
|
158
|
-
} catch (err) {
|
|
159
|
-
warn(`import failed: ${err?.message || err}`);
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function renderHits(hits, budgetChars) {
|
|
165
|
-
if (!hits || hits.length === 0) return null;
|
|
166
|
-
|
|
167
|
-
const header =
|
|
168
|
-
'## Knowledge — top hits for your first prompt\n' +
|
|
169
|
-
'\n' +
|
|
170
|
-
'_Injected automatically by agent-knowledge. Query these entries with `knowledge` (action=read, path=…) before deciding whether to issue a wider `knowledge_search`._\n' +
|
|
171
|
-
'\n';
|
|
172
|
-
|
|
173
|
-
let used = header.length;
|
|
174
|
-
const lines = [];
|
|
175
|
-
for (const hit of hits) {
|
|
176
|
-
const title = hit.entry?.title || hit.entry?.path || '(untitled)';
|
|
177
|
-
const pathStr = hit.entry?.path ?? '';
|
|
178
|
-
const score = typeof hit.score === 'number' ? hit.score.toFixed(2) : '?';
|
|
179
|
-
const excerpt = (hit.excerpt ?? '').replace(/\s+/g, ' ').trim().slice(0, 220);
|
|
180
|
-
const line = `- **${title}** (\`${pathStr}\`, score ${score}) — ${excerpt}`;
|
|
181
|
-
if (used + line.length + 1 > budgetChars) break;
|
|
182
|
-
lines.push(line);
|
|
183
|
-
used += line.length + 1;
|
|
184
|
-
}
|
|
185
|
-
if (lines.length === 0) return null;
|
|
186
|
-
|
|
187
|
-
return header + lines.join('\n') + '\n';
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
async function main() {
|
|
191
|
-
if (!isEnabled()) return emit(null);
|
|
192
|
-
|
|
193
|
-
const raw = await readStdin();
|
|
194
|
-
let payload = {};
|
|
195
|
-
if (raw) {
|
|
196
|
-
try {
|
|
197
|
-
payload = JSON.parse(raw);
|
|
198
|
-
} catch {
|
|
199
|
-
/* ignore — host may not pipe JSON */
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID;
|
|
204
|
-
const prompt = payload.prompt;
|
|
205
|
-
|
|
206
|
-
if (!sessionId || typeof prompt !== 'string') return emit(null);
|
|
207
|
-
if (hasFired(sessionId)) return emit(null);
|
|
208
|
-
|
|
209
|
-
// IMPORTANT: don't burn the marker on skip-gates. If the user starts with
|
|
210
|
-
// `/clear`, `!bash`, or "hi", we want the NEXT real prompt to still get
|
|
211
|
-
// injection. Same for missing-dist / missing-memoryDir: those are setup
|
|
212
|
-
// states that might be fixed before the agent's next turn. Only burn the
|
|
213
|
-
// marker once a real search has actually run against a real KB.
|
|
214
|
-
if (isSkippablePrompt(prompt)) return emit(null);
|
|
215
|
-
|
|
216
|
-
const searchFn = await loadSearch();
|
|
217
|
-
if (!searchFn) return emit(null);
|
|
218
|
-
|
|
219
|
-
const dir = memoryDir();
|
|
220
|
-
if (!fs.existsSync(dir)) return emit(null);
|
|
221
|
-
|
|
222
|
-
let hits;
|
|
223
|
-
try {
|
|
224
|
-
hits = searchFn(dir, prompt.trim(), { maxResults: maxHits(), mmr: true });
|
|
225
|
-
} catch (err) {
|
|
226
|
-
warn(`search failed: ${err?.message || err}`);
|
|
227
|
-
recordFired(sessionId);
|
|
228
|
-
return emit(null);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
recordFired(sessionId);
|
|
232
|
-
|
|
233
|
-
const budgetChars = tokenBudget() * 4;
|
|
234
|
-
const rendered = renderHits(hits, budgetChars);
|
|
235
|
-
if (!rendered) return emit(null);
|
|
236
|
-
emit(rendered, summarizeHits(hits));
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
main().catch((err) => {
|
|
240
|
-
warn(err?.message || String(err));
|
|
241
|
-
emit(null);
|
|
242
|
-
});
|
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// =============================================================================
|
|
4
|
-
// agent-knowledge PreCompact distill hook
|
|
5
|
-
//
|
|
6
|
-
// Dumps the tail of the current session transcript into the knowledge base
|
|
7
|
-
// right before the host compacts the conversation, so cross-machine memory
|
|
8
|
-
// survives the summarization. This is a lightweight heuristic snapshot —
|
|
9
|
-
// the companion `precompact-flush.mjs` hook does a richer summary via the
|
|
10
|
-
// compiled agent-knowledge library when available. Running both is fine;
|
|
11
|
-
// they write to distinct files.
|
|
12
|
-
//
|
|
13
|
-
// Fail-open: any error logs to stderr and emits `{}` so it never blocks.
|
|
14
|
-
// =============================================================================
|
|
15
|
-
|
|
16
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
|
|
17
|
-
import { join } from 'path';
|
|
18
|
-
import { homedir } from 'os';
|
|
19
|
-
|
|
20
|
-
process.on('uncaughtException', (err) => {
|
|
21
|
-
process.stderr.write(`[precompact-distill] fatal: ${err.message}\n`);
|
|
22
|
-
console.log(JSON.stringify({}));
|
|
23
|
-
process.exit(0);
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
const MEMORY_DIR = process.env.AGENT_KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
|
|
27
|
-
|
|
28
|
-
async function main() {
|
|
29
|
-
let input = '';
|
|
30
|
-
for await (const chunk of process.stdin) input += chunk;
|
|
31
|
-
|
|
32
|
-
let hookData = {};
|
|
33
|
-
try {
|
|
34
|
-
hookData = JSON.parse(input);
|
|
35
|
-
} catch {
|
|
36
|
-
// ignore
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const transcriptPath = hookData?.transcript_path;
|
|
40
|
-
const sessionId = hookData?.session_id || 'unknown';
|
|
41
|
-
const cwd = hookData?.workspace?.current_dir || process.cwd();
|
|
42
|
-
|
|
43
|
-
if (!transcriptPath || !existsSync(transcriptPath)) {
|
|
44
|
-
console.log(JSON.stringify({}));
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
let recent = '';
|
|
49
|
-
try {
|
|
50
|
-
const buf = readFileSync(transcriptPath);
|
|
51
|
-
recent = buf.slice(Math.max(0, buf.length - 200_000)).toString('utf8');
|
|
52
|
-
} catch {
|
|
53
|
-
// ignore
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const lines = recent.split(/\r?\n/).filter(Boolean);
|
|
57
|
-
const userMsgs = [];
|
|
58
|
-
for (const line of lines) {
|
|
59
|
-
try {
|
|
60
|
-
const obj = JSON.parse(line);
|
|
61
|
-
if (obj?.type === 'user' && typeof obj.message?.content === 'string') {
|
|
62
|
-
userMsgs.push(obj.message.content.slice(0, 500));
|
|
63
|
-
}
|
|
64
|
-
} catch {
|
|
65
|
-
// ignore non-JSON lines
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
const summary = userMsgs.slice(-10).join('\n---\n');
|
|
69
|
-
|
|
70
|
-
const memDir = join(MEMORY_DIR, 'projects');
|
|
71
|
-
try {
|
|
72
|
-
mkdirSync(memDir, { recursive: true });
|
|
73
|
-
} catch {
|
|
74
|
-
// ignore
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const slug = cwd.replace(/[^a-zA-Z0-9]+/g, '-').slice(0, 64);
|
|
78
|
-
const file = join(memDir, `precompact-${slug}-${sessionId.slice(0, 8)}.md`);
|
|
79
|
-
const body = `---
|
|
80
|
-
type: precompact-snapshot
|
|
81
|
-
session: ${sessionId}
|
|
82
|
-
cwd: ${cwd}
|
|
83
|
-
created: ${new Date().toISOString()}
|
|
84
|
-
---
|
|
85
|
-
|
|
86
|
-
# Pre-compact snapshot
|
|
87
|
-
|
|
88
|
-
Last ${userMsgs.length} user prompts (most recent ${Math.min(10, userMsgs.length)}):
|
|
89
|
-
|
|
90
|
-
${summary}
|
|
91
|
-
`;
|
|
92
|
-
|
|
93
|
-
try {
|
|
94
|
-
writeFileSync(file, body, 'utf8');
|
|
95
|
-
} catch {
|
|
96
|
-
// ignore — don't block on write failure
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
console.log(JSON.stringify({}));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
main().catch((err) => {
|
|
103
|
-
process.stderr.write(`[precompact-distill] ${err.message}\n`);
|
|
104
|
-
console.log(JSON.stringify({}));
|
|
105
|
-
});
|
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// =============================================================================
|
|
4
|
-
// agent-knowledge PreCompact / Stop hook — memory-flush
|
|
5
|
-
//
|
|
6
|
-
// Two jobs, both best-effort:
|
|
7
|
-
//
|
|
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.
|
|
11
|
-
//
|
|
12
|
-
// 2. Emit a short "save-your-context" nudge as a top-level `systemMessage`.
|
|
13
|
-
// The compaction pass is about to summarize — anything important and
|
|
14
|
-
// unsaved should be written to the knowledge base NOW via
|
|
15
|
-
// `knowledge(action="write", …)`. Pre-compaction memory-flush primitive.
|
|
16
|
-
// (PreCompact rejects `hookSpecificOutput.additionalContext` — only
|
|
17
|
-
// UserPromptSubmit/PostToolUse accept that shape — so the nudge rides
|
|
18
|
-
// in `systemMessage`, which lands in the transcript and survives
|
|
19
|
-
// compaction.)
|
|
20
|
-
//
|
|
21
|
-
// Disable the nudge by exporting AGENT_KNOWLEDGE_PRECOMPACT_NUDGE=0 (the disk
|
|
22
|
-
// dump still runs). Set AGENT_KNOWLEDGE_PRECOMPACT_NUDGE=off to suppress both.
|
|
23
|
-
//
|
|
24
|
-
// Fail-open: every error path prints a valid JSON response so the host never
|
|
25
|
-
// blocks on this hook.
|
|
26
|
-
//
|
|
27
|
-
// Reads hook JSON from stdin (the host pipes it). Fields used:
|
|
28
|
-
// { session_id, hook_event_name, cwd? }
|
|
29
|
-
// =============================================================================
|
|
30
|
-
|
|
31
|
-
import { fileURLToPath } from 'url';
|
|
32
|
-
import { dirname, join, resolve } from 'path';
|
|
33
|
-
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
|
|
34
|
-
import { homedir } from 'os';
|
|
35
|
-
|
|
36
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
37
|
-
const __dirname = dirname(__filename);
|
|
38
|
-
|
|
39
|
-
const NUDGE_MODE = (process.env.AGENT_KNOWLEDGE_PRECOMPACT_NUDGE ?? '1').trim().toLowerCase();
|
|
40
|
-
const nudgeEnabled = NUDGE_MODE !== '0' && NUDGE_MODE !== 'false' && NUDGE_MODE !== 'off';
|
|
41
|
-
const diskDumpEnabled = NUDGE_MODE !== 'off';
|
|
42
|
-
|
|
43
|
-
const NUDGE_TEXT = [
|
|
44
|
-
'knowledge: PreCompact — flush durable facts to the KB before summary replaces the transcript.',
|
|
45
|
-
'Write architectural decisions, non-obvious gotchas, hard-won commands, people/ownership facts, project state via',
|
|
46
|
-
'`knowledge(action="write", category="decisions"|"notes"|"workflows", filename=..., content=...)`.',
|
|
47
|
-
'Skip transient things (file diffs, TODO lists, in-flight plans — plan/task systems own those).',
|
|
48
|
-
].join(' ');
|
|
49
|
-
|
|
50
|
-
function emitResult(nudge) {
|
|
51
|
-
const payload = nudge ? { systemMessage: nudge } : {};
|
|
52
|
-
process.stdout.write(JSON.stringify(payload) + '\n');
|
|
53
|
-
process.exit(0);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function warn(msg) {
|
|
57
|
-
process.stderr.write(`[precompact-flush] ${msg}\n`);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async function readStdin() {
|
|
61
|
-
return new Promise((resolveP) => {
|
|
62
|
-
let data = '';
|
|
63
|
-
if (process.stdin.isTTY) return resolveP('');
|
|
64
|
-
process.stdin.setEncoding('utf-8');
|
|
65
|
-
process.stdin.on('data', (chunk) => (data += chunk));
|
|
66
|
-
process.stdin.on('end', () => resolveP(data));
|
|
67
|
-
setTimeout(() => resolveP(data), 2000);
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function slugify(input) {
|
|
72
|
-
return (input || 'session')
|
|
73
|
-
.toLowerCase()
|
|
74
|
-
.replace(/[^a-z0-9]+/g, '-')
|
|
75
|
-
.replace(/^-+|-+$/g, '')
|
|
76
|
-
.slice(0, 60);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function memoryDir() {
|
|
80
|
-
return process.env.AGENT_KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
async function dumpSummaryToDisk({ sessionId, event, cwd, projectSlug }) {
|
|
84
|
-
const distSummary = resolve(__dirname, '..', '..', 'dist', 'sessions', 'summary.js');
|
|
85
|
-
if (!existsSync(distSummary)) {
|
|
86
|
-
warn(`dist not built: ${distSummary} (run \`npm run build\`)`);
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
let summaryFn;
|
|
91
|
-
try {
|
|
92
|
-
const mod = await import(`file://${distSummary.replace(/\\/g, '/')}`);
|
|
93
|
-
summaryFn = mod.getSessionSummary;
|
|
94
|
-
} catch (err) {
|
|
95
|
-
warn(`import failed: ${err?.message || err}`);
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
98
|
-
if (typeof summaryFn !== 'function') {
|
|
99
|
-
warn('getSessionSummary not exported from dist/sessions/summary.js');
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
let summary;
|
|
104
|
-
try {
|
|
105
|
-
summary = summaryFn(sessionId);
|
|
106
|
-
} catch (err) {
|
|
107
|
-
warn(`getSessionSummary threw: ${err?.message || err}`);
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
if (!summary) {
|
|
111
|
-
warn(`session ${sessionId} not found — nothing to flush`);
|
|
112
|
-
return;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
const outDir = join(memoryDir(), 'sessions', projectSlug);
|
|
116
|
-
try {
|
|
117
|
-
mkdirSync(outDir, { recursive: true });
|
|
118
|
-
} catch (err) {
|
|
119
|
-
warn(`mkdir ${outDir}: ${err?.message || err}`);
|
|
120
|
-
return;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
124
|
-
const outPath = join(outDir, `${event}-${stamp}-${sessionId.slice(0, 8)}.md`);
|
|
125
|
-
|
|
126
|
-
const body = [
|
|
127
|
-
'---',
|
|
128
|
-
`session_id: ${sessionId}`,
|
|
129
|
-
`event: ${event}`,
|
|
130
|
-
`flushed_at: ${new Date().toISOString()}`,
|
|
131
|
-
`cwd: ${cwd}`,
|
|
132
|
-
'---',
|
|
133
|
-
'',
|
|
134
|
-
`# Session ${sessionId}`,
|
|
135
|
-
'',
|
|
136
|
-
typeof summary === 'string'
|
|
137
|
-
? summary
|
|
138
|
-
: '```json\n' + JSON.stringify(summary, null, 2) + '\n```',
|
|
139
|
-
'',
|
|
140
|
-
].join('\n');
|
|
141
|
-
|
|
142
|
-
try {
|
|
143
|
-
writeFileSync(outPath, body, 'utf-8');
|
|
144
|
-
warn(`wrote ${outPath}`);
|
|
145
|
-
} catch (err) {
|
|
146
|
-
warn(`write ${outPath}: ${err?.message || err}`);
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// Best-effort: append a breadcrumb readable later by `knowledge` action=list
|
|
151
|
-
try {
|
|
152
|
-
const breadcrumb = join(memoryDir(), 'sessions', 'index.md');
|
|
153
|
-
const existing = existsSync(breadcrumb)
|
|
154
|
-
? readFileSync(breadcrumb, 'utf-8')
|
|
155
|
-
: '# Session flushes\n';
|
|
156
|
-
writeFileSync(
|
|
157
|
-
breadcrumb,
|
|
158
|
-
existing + `- ${event} ${stamp} ${sessionId} → ${outPath}\n`,
|
|
159
|
-
'utf-8',
|
|
160
|
-
);
|
|
161
|
-
} catch {
|
|
162
|
-
/* ignore */
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
async function main() {
|
|
167
|
-
const raw = await readStdin();
|
|
168
|
-
let payload = {};
|
|
169
|
-
if (raw) {
|
|
170
|
-
try {
|
|
171
|
-
payload = JSON.parse(raw);
|
|
172
|
-
} catch {
|
|
173
|
-
/* ignore — host may not pipe JSON */
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID || 'unknown';
|
|
178
|
-
const event = payload.hook_event_name || 'precompact';
|
|
179
|
-
const cwd = payload.cwd || process.cwd();
|
|
180
|
-
const projectSlug = slugify(cwd.split(/[\\/]/).filter(Boolean).pop() || 'project');
|
|
181
|
-
|
|
182
|
-
if (diskDumpEnabled) {
|
|
183
|
-
await dumpSummaryToDisk({ sessionId, event, cwd, projectSlug });
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
emitResult(nudgeEnabled ? NUDGE_TEXT : undefined);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
main().catch((err) => {
|
|
190
|
-
warn(err?.message || String(err));
|
|
191
|
-
emitResult(nudgeEnabled ? NUDGE_TEXT : undefined);
|
|
192
|
-
});
|