agent-knowledge 1.9.8 → 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.
Files changed (179) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +53 -52
  3. package/dist/events.d.ts +16 -0
  4. package/dist/events.d.ts.map +1 -0
  5. package/dist/events.js +31 -0
  6. package/dist/events.js.map +1 -0
  7. package/dist/index.js +31 -13
  8. package/dist/index.js.map +1 -1
  9. package/dist/knowledge/analyze.d.ts.map +1 -1
  10. package/dist/knowledge/analyze.js +18 -11
  11. package/dist/knowledge/analyze.js.map +1 -1
  12. package/dist/knowledge/consolidate.d.ts +2 -2
  13. package/dist/knowledge/consolidate.js +2 -2
  14. package/dist/knowledge/distill.d.ts.map +1 -1
  15. package/dist/knowledge/distill.js +28 -16
  16. package/dist/knowledge/distill.js.map +1 -1
  17. package/dist/knowledge/freshness.js +1 -1
  18. package/dist/knowledge/freshness.js.map +1 -1
  19. package/dist/knowledge/git.d.ts +3 -4
  20. package/dist/knowledge/git.d.ts.map +1 -1
  21. package/dist/knowledge/git.js +62 -49
  22. package/dist/knowledge/git.js.map +1 -1
  23. package/dist/knowledge/graph.d.ts +2 -0
  24. package/dist/knowledge/graph.d.ts.map +1 -1
  25. package/dist/knowledge/graph.js +8 -0
  26. package/dist/knowledge/graph.js.map +1 -1
  27. package/dist/knowledge/ingest-freshness.d.ts +22 -0
  28. package/dist/knowledge/ingest-freshness.d.ts.map +1 -0
  29. package/dist/knowledge/ingest-freshness.js +93 -0
  30. package/dist/knowledge/ingest-freshness.js.map +1 -0
  31. package/dist/knowledge/promote.js +1 -1
  32. package/dist/knowledge/promote.js.map +1 -1
  33. package/dist/knowledge/reflect.js +2 -2
  34. package/dist/knowledge/reflect.js.map +1 -1
  35. package/dist/knowledge/remove.d.ts +11 -0
  36. package/dist/knowledge/remove.d.ts.map +1 -0
  37. package/dist/knowledge/remove.js +24 -0
  38. package/dist/knowledge/remove.js.map +1 -0
  39. package/dist/knowledge/search.d.ts +76 -4
  40. package/dist/knowledge/search.d.ts.map +1 -1
  41. package/dist/knowledge/search.js +364 -37
  42. package/dist/knowledge/search.js.map +1 -1
  43. package/dist/knowledge/similar.d.ts +7 -0
  44. package/dist/knowledge/similar.d.ts.map +1 -0
  45. package/dist/knowledge/similar.js +51 -0
  46. package/dist/knowledge/similar.js.map +1 -0
  47. package/dist/knowledge/store.d.ts +20 -1
  48. package/dist/knowledge/store.d.ts.map +1 -1
  49. package/dist/knowledge/store.js +119 -84
  50. package/dist/knowledge/store.js.map +1 -1
  51. package/dist/lib.d.ts +1 -1
  52. package/dist/lib.d.ts.map +1 -1
  53. package/dist/lib.js.map +1 -1
  54. package/dist/package-meta.d.ts +4 -1
  55. package/dist/package-meta.d.ts.map +1 -1
  56. package/dist/package-meta.js +18 -9
  57. package/dist/package-meta.js.map +1 -1
  58. package/dist/rest-server.d.ts +31 -0
  59. package/dist/rest-server.d.ts.map +1 -0
  60. package/dist/rest-server.js +142 -0
  61. package/dist/rest-server.js.map +1 -0
  62. package/dist/search/bm25.d.ts +8 -0
  63. package/dist/search/bm25.d.ts.map +1 -1
  64. package/dist/search/bm25.js +32 -20
  65. package/dist/search/bm25.js.map +1 -1
  66. package/dist/search/excerpt.d.ts +1 -1
  67. package/dist/search/excerpt.d.ts.map +1 -1
  68. package/dist/search/excerpt.js +19 -1
  69. package/dist/search/excerpt.js.map +1 -1
  70. package/dist/search/lexicon.d.ts +37 -0
  71. package/dist/search/lexicon.d.ts.map +1 -0
  72. package/dist/search/lexicon.js +83 -0
  73. package/dist/search/lexicon.js.map +1 -0
  74. package/dist/search/mmr.d.ts +9 -3
  75. package/dist/search/mmr.d.ts.map +1 -1
  76. package/dist/search/mmr.js +21 -7
  77. package/dist/search/mmr.js.map +1 -1
  78. package/dist/search/types.d.ts +2 -0
  79. package/dist/search/types.d.ts.map +1 -1
  80. package/dist/server.d.ts +1 -5
  81. package/dist/server.d.ts.map +1 -1
  82. package/dist/server.js +1 -13
  83. package/dist/server.js.map +1 -1
  84. package/dist/sessions/human.d.ts +12 -0
  85. package/dist/sessions/human.d.ts.map +1 -0
  86. package/dist/sessions/human.js +52 -0
  87. package/dist/sessions/human.js.map +1 -0
  88. package/dist/sessions/indexer.d.ts +4 -0
  89. package/dist/sessions/indexer.d.ts.map +1 -1
  90. package/dist/sessions/indexer.js +6 -1
  91. package/dist/sessions/indexer.js.map +1 -1
  92. package/dist/sessions/parser.d.ts +39 -0
  93. package/dist/sessions/parser.d.ts.map +1 -1
  94. package/dist/sessions/parser.js +169 -15
  95. package/dist/sessions/parser.js.map +1 -1
  96. package/dist/sessions/search.d.ts +2 -0
  97. package/dist/sessions/search.d.ts.map +1 -1
  98. package/dist/sessions/search.js +147 -67
  99. package/dist/sessions/search.js.map +1 -1
  100. package/dist/sessions/snapshot.d.ts +19 -0
  101. package/dist/sessions/snapshot.d.ts.map +1 -0
  102. package/dist/sessions/snapshot.js +118 -0
  103. package/dist/sessions/snapshot.js.map +1 -0
  104. package/dist/sessions/summary.d.ts +24 -5
  105. package/dist/sessions/summary.d.ts.map +1 -1
  106. package/dist/sessions/summary.js +122 -146
  107. package/dist/sessions/summary.js.map +1 -1
  108. package/dist/slice.d.ts +5 -0
  109. package/dist/slice.d.ts.map +1 -0
  110. package/dist/slice.js +28 -0
  111. package/dist/slice.js.map +1 -0
  112. package/dist/text.d.ts +9 -0
  113. package/dist/text.d.ts.map +1 -0
  114. package/dist/text.js +16 -0
  115. package/dist/text.js.map +1 -0
  116. package/dist/tool-handlers.d.ts.map +1 -1
  117. package/dist/tool-handlers.js +6 -10
  118. package/dist/tool-handlers.js.map +1 -1
  119. package/dist/transport/guard.d.ts +5 -0
  120. package/dist/transport/guard.d.ts.map +1 -0
  121. package/dist/transport/guard.js +51 -0
  122. package/dist/transport/guard.js.map +1 -0
  123. package/dist/transport/http.d.ts +17 -0
  124. package/dist/transport/http.d.ts.map +1 -0
  125. package/dist/transport/http.js +97 -0
  126. package/dist/transport/http.js.map +1 -0
  127. package/dist/transport/rest.d.ts +4 -0
  128. package/dist/transport/rest.d.ts.map +1 -0
  129. package/dist/transport/rest.js +424 -0
  130. package/dist/transport/rest.js.map +1 -0
  131. package/dist/vectorstore/store.d.ts +9 -0
  132. package/dist/vectorstore/store.d.ts.map +1 -1
  133. package/dist/vectorstore/store.js +23 -0
  134. package/dist/vectorstore/store.js.map +1 -1
  135. package/dist/wakeup.d.ts +5 -0
  136. package/dist/wakeup.d.ts.map +1 -1
  137. package/dist/wakeup.js +10 -1
  138. package/dist/wakeup.js.map +1 -1
  139. package/docs/ARCHITECTURE.md +25 -39
  140. package/docs/HOOKS.md +138 -237
  141. package/docs/INGEST.md +1 -1
  142. package/docs/SETUP.md +87 -143
  143. package/docs/USER-MANUAL.md +169 -100
  144. package/package.json +20 -17
  145. package/{skills → plugin/skills}/knowledge-ingest/SKILL.md +1 -1
  146. package/{skills → plugin/skills}/knowledge-ingest/scripts/validate.mjs +2 -2
  147. package/scripts/plugins/opencode/agent-knowledge.ts +37 -86
  148. package/scripts/setup.js +80 -146
  149. package/scripts/source-walk.d.mts +12 -0
  150. package/scripts/source-walk.mjs +94 -0
  151. package/scripts/tree-sitter-extract.mjs +10 -76
  152. package/.claude-plugin/marketplace.json +0 -19
  153. package/.claude-plugin/plugin.json +0 -12
  154. package/.mcp.json +0 -8
  155. package/agent-desk-plugin.json +0 -20
  156. package/dist/dashboard.d.ts +0 -5
  157. package/dist/dashboard.d.ts.map +0 -1
  158. package/dist/dashboard.js +0 -666
  159. package/dist/dashboard.js.map +0 -1
  160. package/dist/ui/app.js +0 -1013
  161. package/dist/ui/index.html +0 -460
  162. package/dist/ui/morphdom.min.js +0 -1
  163. package/dist/ui/render-graph.js +0 -482
  164. package/dist/ui/render-knowledge.js +0 -288
  165. package/dist/ui/render-panel.js +0 -475
  166. package/dist/ui/render-search.js +0 -105
  167. package/dist/ui/render-sessions.js +0 -237
  168. package/dist/ui/styles.css +0 -2322
  169. package/dist/ui/template.js +0 -173
  170. package/dist/ui/ui-utils.js +0 -217
  171. package/dist/ui/vis-network.min.js +0 -34
  172. package/docs/DASHBOARD.md +0 -191
  173. package/scripts/copy-ui.js +0 -14
  174. package/scripts/hooks/first-prompt-inject.mjs +0 -242
  175. package/scripts/hooks/precompact-distill.mjs +0 -105
  176. package/scripts/hooks/precompact-flush.mjs +0 -192
  177. package/scripts/hooks/session-start-ingest.mjs +0 -238
  178. package/scripts/hooks/session-start.js +0 -212
  179. package/scripts/hooks/sessionend-distill.mjs +0 -198
@@ -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
- });
@@ -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,212 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // =============================================================================
4
- // agent-knowledge SessionStart hook
5
- //
6
- // 1. Announces the knowledge dashboard URL.
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 knowledgePort = process.env.AGENT_KNOWLEDGE_PORT || '3423';
37
- const autoWakeEnabled =
38
- (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== '0' &&
39
- (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== 'false';
40
- const wakeupBudget = Number.parseInt(process.env.AGENT_KNOWLEDGE_WAKEUP_BUDGET ?? '200', 10) || 200;
41
-
42
- function emit(additionalContext, statusSuffix) {
43
- const base = `agent-knowledge: http://localhost:${knowledgePort}`;
44
- const systemMessage = statusSuffix ? `${base} | ${statusSuffix}` : base;
45
- const msg = {
46
- systemMessage,
47
- hookSpecificOutput: {
48
- hookEventName: 'SessionStart',
49
- additionalContext,
50
- },
51
- };
52
- process.stdout.write(JSON.stringify(msg) + '\n');
53
- process.exit(0);
54
- }
55
-
56
- async function readStdin() {
57
- return new Promise((resolveP) => {
58
- let data = '';
59
- if (process.stdin.isTTY) return resolveP('');
60
- process.stdin.setEncoding('utf-8');
61
- process.stdin.on('data', (chunk) => (data += chunk));
62
- process.stdin.on('end', () => resolveP(data));
63
- setTimeout(() => resolveP(data), 1500);
64
- });
65
- }
66
-
67
- // Keep in sync with first-prompt-inject.mjs dataDir().
68
- function dataDir() {
69
- if (process.env.AGENT_KNOWLEDGE_DATA_DIR) return process.env.AGENT_KNOWLEDGE_DATA_DIR;
70
- if (process.platform === 'win32') {
71
- return path.join(
72
- process.env.APPDATA || path.join(homedir(), 'AppData', 'Roaming'),
73
- 'knowledge',
74
- );
75
- }
76
- return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'), 'knowledge');
77
- }
78
-
79
- function memoryDir() {
80
- return process.env.AGENT_KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
81
- }
82
-
83
- function identityOnboardingState() {
84
- const dir = memoryDir();
85
- try {
86
- if (existsSync(join(dir, 'identity.md')) || existsSync(join(dir, 'IDENTITY.md'))) {
87
- return 'configured';
88
- }
89
- if (existsSync(join(dir, '.identity-declined'))) {
90
- return 'declined';
91
- }
92
- } catch {
93
- return 'unknown';
94
- }
95
- return 'pending';
96
- }
97
-
98
- const ONBOARDING_INSTRUCTION = [
99
- '',
100
- '--- Identity onboarding (no identity.md yet) ---',
101
- `The user has no ~/agent-knowledge/identity.md. Before diving into their request, briefly ask:`,
102
- ' 1. Name + primary role',
103
- ' 2. Main stack / tech focus',
104
- ' 3. Projects they maintain',
105
- `Then use the Write tool to save their answers to \`~/agent-knowledge/identity.md\` as short markdown.`,
106
- `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.`,
107
- `Do not invent facts — only record what the user actually tells you.`,
108
- ].join('\n');
109
-
110
- function clearFirstPromptMarker(sessionId) {
111
- if (!sessionId || typeof sessionId !== 'string') return false;
112
- try {
113
- const marker = path.join(dataDir(), '.first-prompt-seen', sessionId);
114
- if (existsSync(marker)) {
115
- rmSync(marker, { force: true });
116
- return true;
117
- }
118
- } catch (err) {
119
- process.stderr.write(`[knowledge session-start] marker clear failed: ${err?.message || err}\n`);
120
- }
121
- return false;
122
- }
123
-
124
- async function loadIdentitySection() {
125
- const distWakeup = resolve(__dirname, '..', '..', 'dist', 'wakeup.js');
126
- if (!existsSync(distWakeup)) return { rendered: null, hasIdentity: false, bodyChars: 0 };
127
- try {
128
- const mod = await import(`file://${distWakeup.replace(/\\/g, '/')}`);
129
- if (typeof mod.buildContextBundle !== 'function') {
130
- return { rendered: null, hasIdentity: false, bodyChars: 0 };
131
- }
132
- const result = mod.buildContextBundle({
133
- tokenBudget: wakeupBudget,
134
- sections: ['identity'],
135
- });
136
- if (!result || typeof result.rendered !== 'string' || result.rendered.length === 0) {
137
- return { rendered: null, hasIdentity: false, bodyChars: 0 };
138
- }
139
- const identitySection = (result.sections ?? []).find((s) => s.name === 'identity');
140
- const hasIdentity = !!(identitySection && !identitySection.empty);
141
- const bodyChars = identitySection?.content?.length ?? result.rendered.length;
142
- return { rendered: result.rendered, hasIdentity, bodyChars };
143
- } catch (err) {
144
- process.stderr.write(
145
- `[knowledge session-start] identity load failed: ${err?.message || err}\n`,
146
- );
147
- }
148
- return { rendered: null, hasIdentity: false, bodyChars: 0 };
149
- }
150
-
151
- async function main() {
152
- const raw = await readStdin();
153
- let payload = {};
154
- if (raw) {
155
- try {
156
- payload = JSON.parse(raw);
157
- } catch {
158
- /* ignore — host may not pipe JSON */
159
- }
160
- }
161
- const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID;
162
- const source = payload.source || 'startup';
163
-
164
- // Re-arm first-prompt-inject for this session_id. Resumed sessions reuse the
165
- // session_id, so without this the inject hook's marker from the previous
166
- // run would skip the very next user prompt.
167
- const markerCleared = clearFirstPromptMarker(sessionId);
168
-
169
- const dashboardLine = `Knowledge: http://localhost:${knowledgePort}`;
170
-
171
- const autowakeOffSuffix = markerCleared ? `${source} · inject rearmed` : source;
172
- if (!autoWakeEnabled) {
173
- return emit(dashboardLine, `autowake off · ${autowakeOffSuffix}`);
174
- }
175
-
176
- const { rendered, hasIdentity, bodyChars } = await loadIdentitySection();
177
- const onboarding = hasIdentity ? 'configured' : identityOnboardingState();
178
-
179
- let identityStatus;
180
- if (hasIdentity) {
181
- identityStatus = `identity: ${bodyChars} chars`;
182
- } else if (onboarding === 'pending') {
183
- identityStatus = 'identity: onboarding pending';
184
- } else if (onboarding === 'declined') {
185
- identityStatus = 'identity: declined (delete ~/agent-knowledge/.identity-declined to redo)';
186
- } else {
187
- identityStatus = 'identity: placeholder (no identity.md)';
188
- }
189
- const rearmStatus = markerCleared ? ' · inject rearmed' : '';
190
- const suffix = `${identityStatus}${rearmStatus}`;
191
-
192
- const onboardingBlock = onboarding === 'pending' ? ONBOARDING_INSTRUCTION : '';
193
-
194
- if (!rendered) {
195
- return emit(`${dashboardLine}${onboardingBlock}`, suffix);
196
- }
197
-
198
- const base = [
199
- dashboardLine,
200
- '',
201
- '--- Knowledge wakeup (identity only; call `knowledge action=wakeup` for L1 facts) ---',
202
- rendered,
203
- ].join('\n');
204
- const combined = onboardingBlock ? `${base}\n${onboardingBlock}` : base;
205
-
206
- emit(combined, suffix);
207
- }
208
-
209
- main().catch((err) => {
210
- process.stderr.write(`[knowledge session-start] ${err?.message || err}\n`);
211
- emit(`Knowledge: http://localhost:${knowledgePort}`, null);
212
- });