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,33 +1,32 @@
1
1
  // =============================================================================
2
2
  // agent-knowledge opencode plugin
3
3
  //
4
- // Ports the Claude Code lifecycle hooks (session-start announce, first-prompt
5
- // knowledge injection, pre-compact save nudge, session-end distill) to
6
- // opencode's plugin API (@opencode-ai/plugin).
4
+ // The session lifecycle the Claude Code mod (plugin/hooks/register.tsx) gives,
5
+ // on opencode's plugin API (@opencode-ai/plugin):
6
+ // - session.created → names the knowledge base (toast)
7
+ // - chat.message → the first real prompt carries the matching entries
8
+ // - experimental.session.compacting → the summary is asked to keep what is still to be saved
9
+ // - session.deleted → the session snapshot (POST /api/sessions/:id/snapshot)
7
10
  //
8
- // Coverage vs. the Claude hook set:
9
- // - session.created → session-start.js (dashboard announce)
10
- // - chat.message → first-prompt-inject.mjs (first-prompt KB inject)
11
- // - experimental.session.compacting → precompact-flush.mjs (save-context nudge)
12
- // - session.deleted → sessionend-distill.mjs (session summary file)
11
+ // The snapshot is the server's, as for Claude Code: read from opencode's
12
+ // database by the session adapter, secrets scrubbed, committed under sessions/.
13
13
  //
14
- // Gaps (no opencode analog):
15
- // - session-start-ingest.mjs (paired with /knowledge-ingest skill)
16
- // - precompact-distill.mjs (opencode compaction doesn't expose the transcript)
17
- // - L0 identity auto-load (no additionalContext equivalent — use AGENTS.md)
14
+ // Not here (no opencode analog): the identity / onboarding and ingest-freshness
15
+ // context (use AGENTS.md), and the snapshot at compaction (opencode's compaction
16
+ // does not expose the transcript).
18
17
  //
19
18
  // Register via opencode.json:
20
19
  // {
21
20
  // "plugin": ["agent-knowledge/opencode"]
22
21
  // }
23
22
  //
24
- // Env vars (same as the Claude hooks):
23
+ // Env vars (as for the Claude Code mod):
25
24
  // AGENT_KNOWLEDGE_MEMORY_DIR — knowledge base root (default ~/agent-knowledge)
26
25
  // AGENT_KNOWLEDGE_DATA_DIR — marker/cache dir (default <memory>/.data)
27
- // AGENT_KNOWLEDGE_PORT — dashboard port for search (default 3423)
26
+ // AGENT_KNOWLEDGE_PORT — REST port for search (default 3423)
28
27
  // AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT — "0" / "false" / "off" to disable inject
29
28
  // AGENT_KNOWLEDGE_FIRSTPROMPT_BUDGET — max inject tokens (chars/4, clamped [100,8000])
30
- // AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS — max rendered hits (clamped [1,20])
29
+ // AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS — max rendered hits (clamped [1,2])
31
30
  //
32
31
  // Fails open on every hook — any error is swallowed, the user is never blocked.
33
32
  // =============================================================================
@@ -51,7 +50,7 @@ function markerDir(): string {
51
50
  return join(dataDir(), '.first-prompt-seen');
52
51
  }
53
52
 
54
- function dashboardUrl(): string {
53
+ function restUrl(): string {
55
54
  const port = process.env.AGENT_KNOWLEDGE_PORT || '3423';
56
55
  return `http://localhost:${port}`;
57
56
  }
@@ -66,8 +65,8 @@ function injectEnabled(): boolean {
66
65
  }
67
66
 
68
67
  function maxHits(): number {
69
- const raw = parseInt(process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS ?? '4', 10);
70
- return clamp(Number.isFinite(raw) && raw > 0 ? raw : 4, 1, 20);
68
+ const raw = parseInt(process.env.AGENT_KNOWLEDGE_FIRSTPROMPT_MAX_HITS ?? '2', 10);
69
+ return clamp(Number.isFinite(raw) && raw > 0 ? raw : 2, 1, 2);
71
70
  }
72
71
 
73
72
  function budgetChars(): number {
@@ -109,7 +108,7 @@ function shouldInject(text: string): boolean {
109
108
  return first !== '/' && first !== '!';
110
109
  }
111
110
 
112
- // ── Knowledge search via dashboard HTTP ─────────────────────────────────────
111
+ // ── Knowledge search via the REST server ─────────────────────────────────────
113
112
 
114
113
  type Hit = {
115
114
  entry?: { path?: string; category?: string; title?: string };
@@ -122,9 +121,14 @@ type Hit = {
122
121
 
123
122
  async function searchKnowledge(query: string): Promise<Hit[]> {
124
123
  try {
125
- const url = new URL(`${dashboardUrl()}/api/knowledge/search`);
124
+ const url = new URL(`${restUrl()}/api/knowledge/search`);
126
125
  url.searchParams.set('q', query);
127
126
  url.searchParams.set('max_results', String(maxHits()));
127
+ // As the Claude Code mod asks: near-copies once, no session snapshots, no hit on one word,
128
+ // the prompt searched for what it asks about (not "one line, no tools").
129
+ url.searchParams.set('mmr', 'true');
130
+ url.searchParams.set('skip', 'sessions');
131
+ url.searchParams.set('prompt', 'true');
128
132
  const resp = await fetch(url, { signal: AbortSignal.timeout(3000) });
129
133
  if (!resp.ok) return [];
130
134
  const data = (await resp.json()) as unknown;
@@ -154,12 +158,9 @@ function renderHits(hits: Hit[]): string {
154
158
  return out;
155
159
  }
156
160
 
157
- // ── Session-end distill ─────────────────────────────────────────────────────
161
+ // ── Session snapshot ────────────────────────────────────────────────────────
158
162
 
159
163
  type ClientLike = {
160
- session: {
161
- messages: (opts: { path: { id: string } }) => Promise<unknown>;
162
- };
163
164
  tui?: {
164
165
  showToast?: (opts: {
165
166
  body?: { title?: string; message: string; variant: string; duration?: number };
@@ -167,65 +168,15 @@ type ClientLike = {
167
168
  };
168
169
  };
169
170
 
170
- async function distillSession(sessionId: string, client: ClientLike): Promise<void> {
171
+ /** The session's snapshot, written (scrubbed) by the server from opencode's own records. */
172
+ async function snapshotSession(sessionId: string, cwd: string): Promise<void> {
171
173
  try {
172
- const raw = await client.session.messages({ path: { id: sessionId } });
173
- const list = Array.isArray((raw as { data?: unknown })?.data)
174
- ? ((raw as { data: unknown[] }).data as unknown[])
175
- : Array.isArray(raw)
176
- ? (raw as unknown[])
177
- : [];
178
- if (!list.length) return;
179
-
180
- let userTurns = 0;
181
- let assistantTurns = 0;
182
- let toolUses = 0;
183
- const userPrompts: string[] = [];
184
-
185
- for (const m of list) {
186
- const entry = m as { info?: { role?: string }; parts?: unknown[] };
187
- const role = entry.info?.role;
188
- const parts = Array.isArray(entry.parts) ? entry.parts : [];
189
- if (role === 'user') {
190
- userTurns++;
191
- const text = extractText(parts);
192
- if (text && userPrompts.length < 20) userPrompts.push(text);
193
- } else if (role === 'assistant') {
194
- assistantTurns++;
195
- for (const p of parts) {
196
- if (p && typeof p === 'object' && (p as { type?: unknown }).type === 'tool') {
197
- toolUses++;
198
- }
199
- }
200
- }
201
- }
202
-
203
- const slug = sessionId.slice(0, 8);
204
- const projectsDir = join(memoryDir(), 'projects');
205
- ensureDir(projectsDir);
206
- const outPath = join(projectsDir, `session-opencode-${slug}.md`);
207
- const body =
208
- [
209
- '---',
210
- 'type: session-end',
211
- `session: ${sessionId}`,
212
- 'host: opencode',
213
- `ended: ${new Date().toISOString()}`,
214
- `turns: ${userTurns}u/${assistantTurns}a`,
215
- `tool_uses: ${toolUses}`,
216
- '---',
217
- '',
218
- `# Session ${slug}`,
219
- '',
220
- '**Host**: opencode',
221
- `**Turns**: ${userTurns} user / ${assistantTurns} assistant`,
222
- `**Tool uses**: ${toolUses}`,
223
- '',
224
- '## First user prompts',
225
- '',
226
- ...userPrompts.map((p) => `- ${p.replace(/\s+/g, ' ').slice(0, 240)}`),
227
- ].join('\n') + '\n';
228
- writeFileSync(outPath, body);
174
+ await fetch(`${restUrl()}/api/sessions/${encodeURIComponent(sessionId)}/snapshot`, {
175
+ method: 'POST',
176
+ headers: { 'Content-Type': 'application/json' },
177
+ body: JSON.stringify({ event: 'end', ...(cwd ? { cwd } : {}) }),
178
+ signal: AbortSignal.timeout(10_000),
179
+ });
229
180
  } catch {
230
181
  /* fail open */
231
182
  }
@@ -233,7 +184,7 @@ async function distillSession(sessionId: string, client: ClientLike): Promise<vo
233
184
 
234
185
  // ── Plugin entry point ──────────────────────────────────────────────────────
235
186
 
236
- export const AgentKnowledgePlugin: Plugin = async ({ client }) => {
187
+ export const AgentKnowledgePlugin: Plugin = async ({ client, directory }) => {
237
188
  ensureDir(markerDir());
238
189
  const typedClient = client as unknown as ClientLike;
239
190
 
@@ -245,7 +196,7 @@ export const AgentKnowledgePlugin: Plugin = async ({ client }) => {
245
196
  const info = (event as { properties?: { info?: { id?: string } } }).properties?.info;
246
197
  if (info?.id) {
247
198
  // Resumed sessions reuse the same id — clear stale marker so first-prompt
248
- // inject re-arms, matching the Claude session-start.js behaviour.
199
+ // inject re-arms, as a restarted Claude Code session does.
249
200
  const p = markerPath(info.id);
250
201
  if (existsSync(p)) {
251
202
  try {
@@ -259,7 +210,7 @@ export const AgentKnowledgePlugin: Plugin = async ({ client }) => {
259
210
  await typedClient.tui?.showToast?.({
260
211
  body: {
261
212
  title: 'agent-knowledge',
262
- message: `dashboard: ${dashboardUrl()}`,
213
+ message: `knowledge base: ${memoryDir()}`,
263
214
  variant: 'info',
264
215
  duration: 3000,
265
216
  },
@@ -272,7 +223,7 @@ export const AgentKnowledgePlugin: Plugin = async ({ client }) => {
272
223
  (event as { properties?: { info?: { id?: string }; sessionID?: string } }).properties
273
224
  ?.info?.id ||
274
225
  (event as { properties?: { sessionID?: string } }).properties?.sessionID;
275
- if (id) await distillSession(id, typedClient);
226
+ if (id) await snapshotSession(id, directory);
276
227
  }
277
228
  } catch {
278
229
  /* fail open */
package/scripts/setup.js CHANGED
@@ -10,11 +10,15 @@
10
10
  //
11
11
  // What it does:
12
12
  // - Builds the project if dist/ is missing
13
- // - Registers the MCP server in the agent's config
14
- // - Adds lifecycle hooks for Claude Code (SessionStart banner, PreCompact
15
- // flush + distill, SessionEnd distill)
16
- // - Registers the opencode plugin ("agent-knowledge/opencode") in opencode.json
17
- // - Adds permission for mcp__agent-knowledge__* tools
13
+ // - Claude Code: says how to install the plugin (it runs the MCP server, the
14
+ // knowledge-ingest skill and the mod with the /knowledge pane and the session
15
+ // lifecycle), adds permission for mcp__agent-knowledge__* tools, and removes the
16
+ // command hooks agent-knowledge 2.x installed (the mod replaces them)
17
+ // - OpenCode: registers the MCP server and the opencode plugin
18
+ // ("agent-knowledge/opencode") in opencode.json
19
+ // - Any other client: prints the MCP config to add
20
+ // - Installs the knowledge-ingest skill to ~/.agents/skills (OpenCode, Cursor, Codex CLI,
21
+ // Gemini CLI)
18
22
  //
19
23
  // Usage: node scripts/setup.js [--host=claude|opencode|all|auto]
20
24
  // node scripts/setup.js [--agent claude|generic] # deprecated alias
@@ -86,22 +90,8 @@ if (!existsSync(join(PROJECT_DIR, 'dist', 'index.js'))) {
86
90
 
87
91
  const distPath = join(PROJECT_DIR, 'dist', 'index.js');
88
92
 
89
- console.log('Registering MCP server...');
90
- if (IS_CLAUDE && existsSync(CLAUDE_JSON)) {
91
- const config = JSON.parse(readFileSync(CLAUDE_JSON, 'utf-8'));
92
- if (!config.mcpServers) config.mcpServers = {};
93
-
94
- config.mcpServers['agent-knowledge'] = {
95
- type: 'stdio',
96
- command: 'node',
97
- args: [distPath],
98
- env: {},
99
- };
100
-
101
- writeFileSync(CLAUDE_JSON, JSON.stringify(config, null, 2));
102
- console.log(` Added agent-knowledge MCP server → ${distPath}`);
103
- } else if (!IS_OPENCODE) {
104
- console.log(' Add this to your MCP client config:');
93
+ if (!IS_CLAUDE && !IS_OPENCODE) {
94
+ console.log('Add this to your MCP client config:');
105
95
  console.log(' {');
106
96
  console.log(' "mcpServers": {');
107
97
  console.log(' "agent-knowledge": {');
@@ -175,13 +165,28 @@ if (IS_OPENCODE) {
175
165
  }
176
166
  }
177
167
 
168
+ // ---------------------------------------------------------------------------
169
+ // knowledge-ingest skill for every host reading ~/.agents/skills (OpenCode, Cursor,
170
+ // Codex CLI, Gemini CLI). Claude Code gets it from the plugin.
171
+ // ---------------------------------------------------------------------------
172
+
173
+ const skillSrc = join(PROJECT_DIR, 'plugin', 'skills', 'knowledge-ingest', 'SKILL.md');
174
+ const skillDest = join(HOME, '.agents', 'skills', 'knowledge-ingest', 'SKILL.md');
175
+ if (existsSync(skillSrc)) {
176
+ if (!existsSync(skillDest) || statSync(skillDest).mtimeMs < statSync(skillSrc).mtimeMs) {
177
+ mkdirSync(dirname(skillDest), { recursive: true });
178
+ cpSync(skillSrc, skillDest);
179
+ console.log(`
180
+ Installed the knowledge-ingest skill → ${skillDest}`);
181
+ }
182
+ }
183
+
178
184
  if (!IS_CLAUDE) {
179
185
  console.log(`
180
186
  Setup complete!
181
187
 
182
- Start the dashboard: node dist/server.js
183
188
  MCP server (stdio): node dist/index.js
184
- Dashboard URL: http://localhost:3423
189
+ REST API: http://localhost:3423 (served by the first MCP process)
185
190
  ${
186
191
  IS_OPENCODE
187
192
  ? 'OpenCode: the plugin loads automatically on next session start. See docs/SETUP.md#opencode-plugins for env-var tuning.\n'
@@ -190,139 +195,68 @@ ${
190
195
  process.exit(0);
191
196
  }
192
197
 
193
- console.log('Configuring Claude Code hooks...');
194
- if (!existsSync(SETTINGS_JSON)) {
195
- console.log(' Warning: settings.json not found. Configure hooks manually.');
196
- process.exit(0);
197
- }
198
+ console.log('Configuring Claude Code...');
199
+ if (existsSync(SETTINGS_JSON)) {
200
+ const settings = JSON.parse(readFileSync(SETTINGS_JSON, 'utf-8'));
198
201
 
199
- const settings = JSON.parse(readFileSync(SETTINGS_JSON, 'utf-8'));
200
-
201
- if (!settings.permissions) settings.permissions = {};
202
- if (!settings.permissions.allow) settings.permissions.allow = [];
203
- if (!settings.permissions.allow.includes('mcp__agent-knowledge__*')) {
204
- settings.permissions.allow.push('mcp__agent-knowledge__*');
205
- console.log(' Added mcp__agent-knowledge__* permission');
206
- }
207
-
208
- if (!settings.hooks) settings.hooks = {};
209
-
210
- const hookDir = join(PROJECT_DIR, 'scripts', 'hooks');
211
-
212
- function addUnmatchedHook(eventName, marker, command, timeout = 10) {
213
- if (!settings.hooks[eventName]) settings.hooks[eventName] = [];
214
- const groups = settings.hooks[eventName];
215
- const existing = groups.find(
216
- (g) => g.hooks && g.hooks.some((h) => h.command && h.command.includes(marker)),
217
- );
218
- if (existing) {
219
- console.log(` ${eventName} (${marker}): already configured`);
220
- return;
221
- }
222
- if (groups.length > 0 && groups[0].hooks && !groups[0].matcher) {
223
- groups[0].hooks.push({ type: 'command', command, timeout });
224
- } else {
225
- groups.push({ hooks: [{ type: 'command', command, timeout }] });
202
+ if (!settings.permissions) settings.permissions = {};
203
+ if (!settings.permissions.allow) settings.permissions.allow = [];
204
+ if (!settings.permissions.allow.includes('mcp__agent-knowledge__*')) {
205
+ settings.permissions.allow.push('mcp__agent-knowledge__*');
206
+ console.log(' Added mcp__agent-knowledge__* permission');
226
207
  }
227
- console.log(` ${eventName}: added ${marker} hook`);
228
- }
229
208
 
230
- // SessionStart: dashboard banner
231
- addUnmatchedHook(
232
- 'SessionStart',
233
- 'session-start.js',
234
- `node "${join(hookDir, 'session-start.js')}"`,
235
- 5,
236
- );
237
-
238
- // SessionStart: knowledge-ingest freshness check
239
- addUnmatchedHook(
240
- 'SessionStart',
241
- 'session-start-ingest.mjs',
242
- `node "${join(hookDir, 'session-start-ingest.mjs')}"`,
243
- 10,
244
- );
245
-
246
- // UserPromptSubmit: targeted knowledge injection on the session's first real prompt
247
- addUnmatchedHook(
248
- 'UserPromptSubmit',
249
- 'first-prompt-inject.mjs',
250
- `node "${join(hookDir, 'first-prompt-inject.mjs')}"`,
251
- 10,
252
- );
253
-
254
- // PreCompact: rich summary (library) + simple text distill (heuristic)
255
- addUnmatchedHook(
256
- 'PreCompact',
257
- 'precompact-flush.mjs',
258
- `node "${join(hookDir, 'precompact-flush.mjs')}"`,
259
- 10,
260
- );
261
- addUnmatchedHook(
262
- 'PreCompact',
263
- 'precompact-distill.mjs',
264
- `node "${join(hookDir, 'precompact-distill.mjs')}"`,
265
- 10,
266
- );
267
-
268
- // SessionEnd: simple text distill for cross-machine memory
269
- addUnmatchedHook(
270
- 'SessionEnd',
271
- 'sessionend-distill.mjs',
272
- `node "${join(hookDir, 'sessionend-distill.mjs')}"`,
273
- 10,
274
- );
275
-
276
- writeFileSync(SETTINGS_JSON, JSON.stringify(settings, null, 2));
277
- console.log(' Saved settings.json');
278
-
279
- // ---------------------------------------------------------------------------
280
- // Install knowledge-ingest skill
281
- // ---------------------------------------------------------------------------
282
-
283
- console.log('Installing knowledge-ingest skill...');
284
-
285
- const skillSrc = join(PROJECT_DIR, 'skills', 'knowledge-ingest', 'SKILL.md');
286
-
287
- const skillDests = [
288
- join(HOME, '.claude', 'skills', 'knowledge-ingest', 'SKILL.md'),
289
- join(HOME, '.agents', 'skills', 'knowledge-ingest', 'SKILL.md'),
290
- ];
291
-
292
- if (existsSync(skillSrc)) {
293
- const srcMtime = statSync(skillSrc).mtimeMs;
294
- for (const dest of skillDests) {
295
- mkdirSync(dirname(dest), { recursive: true });
296
- let shouldCopy = true;
297
- if (existsSync(dest)) {
298
- if (statSync(dest).mtimeMs >= srcMtime) {
299
- shouldCopy = false;
300
- }
301
- }
302
- if (shouldCopy) {
303
- cpSync(skillSrc, dest);
304
- console.log(` Installed → ${dest}`);
305
- } else {
306
- console.log(` Up to date → ${dest}`);
209
+ // The command hooks 2.x installed: the plugin's mod does their work now, and their
210
+ // scripts are gone, so each would fail at every session.
211
+ const OLD_HOOKS = [
212
+ 'session-start.js',
213
+ 'session-start-ingest.mjs',
214
+ 'first-prompt-inject.mjs',
215
+ 'precompact-flush.mjs',
216
+ 'precompact-distill.mjs',
217
+ 'sessionend-distill.mjs',
218
+ ];
219
+ const isOld = (h) =>
220
+ typeof h.command === 'string' &&
221
+ h.command.includes('agent-knowledge') &&
222
+ OLD_HOOKS.some((name) => h.command.includes(name));
223
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
224
+ for (const group of groups) {
225
+ const before = group.hooks?.length ?? 0;
226
+ group.hooks = (group.hooks ?? []).filter((h) => !isOld(h));
227
+ if (group.hooks.length < before)
228
+ console.log(
229
+ ` ${event}: removed ${before - group.hooks.length} agent-knowledge 2.x hook(s)`,
230
+ );
307
231
  }
232
+ settings.hooks[event] = groups.filter((g) => g.hooks.length > 0);
233
+ if (settings.hooks[event].length === 0) delete settings.hooks[event];
308
234
  }
309
- } else {
310
- console.log(' Warning: skills/knowledge-ingest/SKILL.md not found in repo');
235
+
236
+ writeFileSync(SETTINGS_JSON, JSON.stringify(settings, null, 2));
237
+ console.log(' Saved settings.json');
311
238
  }
312
239
 
240
+ const config = existsSync(CLAUDE_JSON) ? JSON.parse(readFileSync(CLAUDE_JSON, 'utf-8')) : {};
241
+ const handWritten = config.mcpServers?.['agent-knowledge'];
242
+
313
243
  console.log(`
314
244
  Setup complete!
315
245
 
316
- Restart Claude Code to load the new MCP server. Every session will now:
317
- - Show the knowledge dashboard URL + L0/L1 wakeup payload on start (session-start.js)
318
- - Report ingest freshness on start (session-start-ingest.mjs)
319
- - Inject query-targeted knowledge hits on the first real user prompt (first-prompt-inject.mjs)
320
- - Flush a rich session summary before compaction (precompact-flush.mjs)
321
- - Snapshot recent user prompts before compaction (precompact-distill.mjs)
322
- - Dump a final session summary on exit (sessionend-distill.mjs)
246
+ Install the plugin in Claude Code:
247
+ claude plugin marketplace add keshrath/agent-knowledge
248
+ claude plugin install agent-knowledge@agent-knowledge
323
249
 
324
- Dashboard: http://localhost:3423 (auto-starts on first MCP connection)
250
+ It runs the MCP server, adds the knowledge-ingest skill and a mod that
251
+ - names the knowledge base, who you are and the project's ingest state in each conversation
252
+ - adds the matching entries to the first real prompt
253
+ - snapshots the session into the knowledge base when it is compacted and when it ends
254
+ - opens the knowledge base beside the conversation: /knowledge
255
+ ${
256
+ handWritten
257
+ ? `\nRemove the hand-written "agent-knowledge" entry from ${CLAUDE_JSON} once the plugin is in,\nso the tools do not appear twice.\n`
258
+ : ''
259
+ }
325
260
  Knowledge base: ~/agent-knowledge/ (configurable via AGENT_KNOWLEDGE_MEMORY_DIR)
326
-
327
- See docs/HOOKS.md for details and docs/SETUP.md for manual configuration.
261
+ See docs/HOOKS.md for the lifecycle and docs/SETUP.md for other clients.
328
262
  `);
@@ -0,0 +1,12 @@
1
+ export declare const DEFAULT_EXCLUDE: string[];
2
+ export declare const DEFAULT_MAX_FILES: number;
3
+ export declare const EXTENSIONS: Map<string, string>;
4
+ export declare function walkSources(
5
+ dir: string,
6
+ options?: {
7
+ exclude?: string[];
8
+ includeExts?: string[];
9
+ maxFiles?: number;
10
+ maxEntries?: number;
11
+ },
12
+ ): Array<{ fullPath: string; ext: string; mtime: number }>;
@@ -0,0 +1,94 @@
1
+ // =============================================================================
2
+ // source-walk.mjs — the source files a knowledge ingest reads
3
+ //
4
+ // One walk for tree-sitter-extract.mjs (what is ingested) and the server's
5
+ // ingest freshness (src/knowledge/ingest-freshness.ts: what changed since), so
6
+ // both see the same files: the same folders skipped, the same extensions, the
7
+ // same cap.
8
+ // =============================================================================
9
+
10
+ import { readdirSync, statSync } from 'fs';
11
+ import { extname, join } from 'path';
12
+ import { buildExtensionMap } from './tree-sitter-lang.mjs';
13
+
14
+ export const DEFAULT_EXCLUDE = [
15
+ 'node_modules',
16
+ '.git',
17
+ 'dist',
18
+ 'build',
19
+ 'target',
20
+ 'vendor',
21
+ '__pycache__',
22
+ '.venv',
23
+ 'venv',
24
+ '.tox',
25
+ '.mypy_cache',
26
+ '.next',
27
+ '.nuxt',
28
+ 'coverage',
29
+ '.pytest_cache',
30
+ '.cargo',
31
+ 'bin',
32
+ 'obj',
33
+ '.gradle',
34
+ '.idea',
35
+ '.vscode',
36
+ ];
37
+
38
+ export const DEFAULT_MAX_FILES = 2000;
39
+
40
+ /** Extension (`.ts`) to the language that parses it. */
41
+ export const EXTENSIONS = buildExtensionMap();
42
+
43
+ /**
44
+ * The source files under `dir` in walk order, up to `maxFiles`, sorted newest first. The walk
45
+ * stops after `maxEntries` folder entries (files and folders seen), so a folder that is no
46
+ * project (a home folder) is not read through.
47
+ */
48
+ export function walkSources(
49
+ dir,
50
+ {
51
+ exclude = DEFAULT_EXCLUDE,
52
+ includeExts = [],
53
+ maxFiles = DEFAULT_MAX_FILES,
54
+ maxEntries = Infinity,
55
+ } = {},
56
+ ) {
57
+ const files = [];
58
+ let seen = 0;
59
+
60
+ function walk(currentDir) {
61
+ if (files.length >= maxFiles || seen >= maxEntries) return;
62
+ let entries;
63
+ try {
64
+ entries = readdirSync(currentDir, { withFileTypes: true });
65
+ } catch {
66
+ return;
67
+ }
68
+ for (const entry of entries) {
69
+ if (files.length >= maxFiles || ++seen > maxEntries) return;
70
+ const name = entry.name;
71
+ if (exclude.some((ex) => name === ex || name.startsWith(ex + '/'))) continue;
72
+ const fullPath = join(currentDir, name);
73
+ if (entry.isDirectory()) {
74
+ walk(fullPath);
75
+ } else if (entry.isFile()) {
76
+ const ext = extname(name).toLowerCase();
77
+ if (!EXTENSIONS.has(ext)) continue;
78
+ if (includeExts.length > 0 && !includeExts.some((ie) => name.endsWith(ie) || ext === ie))
79
+ continue;
80
+ let mtime;
81
+ try {
82
+ mtime = statSync(fullPath).mtimeMs;
83
+ } catch {
84
+ continue;
85
+ }
86
+ files.push({ fullPath, ext, mtime });
87
+ }
88
+ }
89
+ }
90
+
91
+ walk(dir);
92
+ files.sort((a, b) => b.mtime - a.mtime);
93
+ return files;
94
+ }