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.
- package/CHANGELOG.md +82 -0
- package/README.md +53 -52
- package/dist/events.d.ts +16 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +31 -0
- package/dist/events.js.map +1 -0
- package/dist/index.js +31 -13
- 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/consolidate.d.ts +2 -2
- package/dist/knowledge/consolidate.js +2 -2
- 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/freshness.js +1 -1
- package/dist/knowledge/freshness.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 +62 -49
- 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/promote.js +1 -1
- package/dist/knowledge/promote.js.map +1 -1
- package/dist/knowledge/reflect.js +2 -2
- package/dist/knowledge/reflect.js.map +1 -1
- 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 +76 -4
- package/dist/knowledge/search.d.ts.map +1 -1
- package/dist/knowledge/search.js +364 -37
- 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 +20 -1
- package/dist/knowledge/store.d.ts.map +1 -1
- package/dist/knowledge/store.js +119 -84
- package/dist/knowledge/store.js.map +1 -1
- package/dist/lib.d.ts +1 -1
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js.map +1 -1
- package/dist/package-meta.d.ts +4 -1
- package/dist/package-meta.d.ts.map +1 -1
- package/dist/package-meta.js +18 -9
- package/dist/package-meta.js.map +1 -1
- package/dist/rest-server.d.ts +31 -0
- package/dist/rest-server.d.ts.map +1 -0
- package/dist/rest-server.js +142 -0
- package/dist/rest-server.js.map +1 -0
- 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 +1 -5
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +1 -13
- 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/indexer.d.ts +4 -0
- package/dist/sessions/indexer.d.ts.map +1 -1
- package/dist/sessions/indexer.js +6 -1
- package/dist/sessions/indexer.js.map +1 -1
- package/dist/sessions/parser.d.ts +39 -0
- package/dist/sessions/parser.d.ts.map +1 -1
- package/dist/sessions/parser.js +169 -15
- 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 +122 -146
- 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/guard.d.ts +5 -0
- package/dist/transport/guard.d.ts.map +1 -0
- package/dist/transport/guard.js +51 -0
- package/dist/transport/guard.js.map +1 -0
- package/dist/transport/http.d.ts +17 -0
- package/dist/transport/http.d.ts.map +1 -0
- package/dist/transport/http.js +97 -0
- package/dist/transport/http.js.map +1 -0
- package/dist/transport/rest.d.ts +4 -0
- package/dist/transport/rest.d.ts.map +1 -0
- package/dist/transport/rest.js +424 -0
- package/dist/transport/rest.js.map +1 -0
- 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 +25 -39
- package/docs/HOOKS.md +138 -237
- package/docs/INGEST.md +1 -1
- package/docs/SETUP.md +87 -143
- package/docs/USER-MANUAL.md +169 -100
- package/package.json +20 -17
- package/{skills → plugin/skills}/knowledge-ingest/SKILL.md +1 -1
- package/{skills → plugin/skills}/knowledge-ingest/scripts/validate.mjs +2 -2
- package/scripts/plugins/opencode/agent-knowledge.ts +37 -86
- package/scripts/setup.js +80 -146
- package/scripts/source-walk.d.mts +12 -0
- package/scripts/source-walk.mjs +94 -0
- package/scripts/tree-sitter-extract.mjs +10 -76
- package/.claude-plugin/marketplace.json +0 -19
- package/.claude-plugin/plugin.json +0 -12
- package/.mcp.json +0 -8
- package/agent-desk-plugin.json +0 -20
- package/dist/dashboard.d.ts +0 -5
- package/dist/dashboard.d.ts.map +0 -1
- package/dist/dashboard.js +0 -666
- package/dist/dashboard.js.map +0 -1
- package/dist/ui/app.js +0 -1013
- package/dist/ui/index.html +0 -460
- package/dist/ui/morphdom.min.js +0 -1
- package/dist/ui/render-graph.js +0 -482
- package/dist/ui/render-knowledge.js +0 -288
- package/dist/ui/render-panel.js +0 -475
- package/dist/ui/render-search.js +0 -105
- package/dist/ui/render-sessions.js +0 -237
- package/dist/ui/styles.css +0 -2322
- package/dist/ui/template.js +0 -173
- package/dist/ui/ui-utils.js +0 -217
- package/dist/ui/vis-network.min.js +0 -34
- package/docs/DASHBOARD.md +0 -191
- package/scripts/copy-ui.js +0 -14
- 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 -212
- package/scripts/hooks/sessionend-distill.mjs +0 -198
package/docs/DASHBOARD.md
DELETED
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
# Dashboard
|
|
2
|
-
|
|
3
|
-
The dashboard runs at **http://localhost:3423** and auto-starts with the MCP server.
|
|
4
|
-
|
|
5
|
-
## Tabs
|
|
6
|
-
|
|
7
|
-
| Tab | Purpose |
|
|
8
|
-
| ------------- | --------------------------------------------------------------- |
|
|
9
|
-
| **Knowledge** | Browse knowledge base entries by category |
|
|
10
|
-
| **Search** | TF-IDF ranked search across session transcripts |
|
|
11
|
-
| **Sessions** | Browse and read session conversation logs |
|
|
12
|
-
| **Recall** | Scoped search (errors, plans, configs, tools, files, decisions) |
|
|
13
|
-
|
|
14
|
-
## Knowledge Tab
|
|
15
|
-
|
|
16
|
-
Card grid of knowledge entries. Each card shows:
|
|
17
|
-
|
|
18
|
-
- Category badge with color: projects (blue), people (purple), decisions (orange), workflows (green), notes (yellow)
|
|
19
|
-
- **Maturity badge**: candidate (gray), established (blue), proven (green) — based on access frequency
|
|
20
|
-
- **Pin badge** (Material Symbols `push_pin`) when the entry has `evergreen: true` frontmatter — these entries are exempt from decay in ranking and append-only under promotion.
|
|
21
|
-
- **Author chip** (muted, footer row) when the entry has `author: <string>` frontmatter — surfaces who wrote or owns it.
|
|
22
|
-
- Title and tag pills
|
|
23
|
-
- Last updated date
|
|
24
|
-
|
|
25
|
-

|
|
26
|
-
|
|
27
|
-
Category filter chips at the top: All, Projects, People, Decisions, Workflows, Notes. Search bar for filtering entries by title.
|
|
28
|
-
|
|
29
|
-
**Unused filter chip** (top-right of the header): shows `Unused (N)` where `N` is the count of entries past their per-category staleness threshold. Click to filter the grid to just those entries; click again to clear. Auto-hides when the count is zero.
|
|
30
|
-
|
|
31
|
-
**By Type access chart** (between the tabs and the grid): a horizontal bar per canonical category, row-normalized so each bar fills its own track. Green share = accessed within the per-category recent window, orange = unused. Volume comparison via the right-side `accessed/unused` counts. Per-category thresholds: `projects` 180/365d, `people` 365/730d, `decisions` 90/180d, `workflows` 60/120d, `notes` 30/90d.
|
|
32
|
-
|
|
33
|
-
**Header action buttons:**
|
|
34
|
-
|
|
35
|
-
- **Duplicates** — scans all entries for near-duplicates using TF-IDF similarity. Entries in duplicate clusters get a warning icon on their card. Opens a side panel showing clusters with pairwise similarity scores. Click any entry in a cluster to view it.
|
|
36
|
-
- **Reflect** — finds entries with no graph connections. Opens a side panel listing unconnected entries with content summaries and instructions for creating new links.
|
|
37
|
-
- **God Nodes** — opens a side panel showing the most-connected entries (top degree centrality) with edge counts. These are your core concepts.
|
|
38
|
-
- **Bridges** — shows entries that connect different categories, ranked by betweenness centrality. Each row includes a `why` explanation of which categories it bridges.
|
|
39
|
-
- **Gaps** — lists isolated entries (0-1 edges) grouped by maturity, with `proven` entries listed first as the most concerning gaps.
|
|
40
|
-
- **Brief** — displays the cached ~200 token knowledge base summary in a code block plus card sections for core concepts and recent decisions. Suitable for session-start orientation.
|
|
41
|
-
|
|
42
|
-
Click a card to open the side panel with rendered markdown content, score details, and related entries.
|
|
43
|
-
|
|
44
|
-
## Search Tab
|
|
45
|
-
|
|
46
|
-
Full-text search across all session transcripts.
|
|
47
|
-
|
|
48
|
-
**Controls:**
|
|
49
|
-
|
|
50
|
-
- Search input with debounce (300ms)
|
|
51
|
-
- Role filter chips: All, User, Assistant
|
|
52
|
-
- Mode toggle: Ranked (TF-IDF) vs Regex
|
|
53
|
-
|
|
54
|
-
**Results show:**
|
|
55
|
-
|
|
56
|
-
- Role badge (user/assistant)
|
|
57
|
-
- Project name
|
|
58
|
-
- Relative timestamp
|
|
59
|
-
- Score bar with numeric value
|
|
60
|
-
- Excerpt with highlighted matching terms
|
|
61
|
-
|
|
62
|
-
Click a result to open the session in the side panel.
|
|
63
|
-
|
|
64
|
-
## Sessions Tab
|
|
65
|
-
|
|
66
|
-
Lists sessions from all detected AI coding tools with metadata:
|
|
67
|
-
|
|
68
|
-
- Source tool indicator (Claude Code, Cursor, OpenCode, Cline, Continue.dev, Aider)
|
|
69
|
-
- Project name
|
|
70
|
-
- Git branch (when available)
|
|
71
|
-
- Message count
|
|
72
|
-
- Date
|
|
73
|
-
- Preview of first user message
|
|
74
|
-
|
|
75
|
-
Project filter dropdown at the top. Sessions from all tools are merged into a single unified list.
|
|
76
|
-
|
|
77
|
-
Click a session to open the side panel with the full conversation rendered as chat bubbles.
|
|
78
|
-
|
|
79
|
-
## Recall Tab
|
|
80
|
-
|
|
81
|
-
Scoped search that pre-filters results by category:
|
|
82
|
-
|
|
83
|
-
| Scope | What it finds |
|
|
84
|
-
| ----------- | ----------------------------------------- |
|
|
85
|
-
| `errors` | Stack traces, exceptions, failed commands |
|
|
86
|
-
| `plans` | Architecture, TODOs, implementation steps |
|
|
87
|
-
| `configs` | Settings, env vars, configuration files |
|
|
88
|
-
| `tools` | MCP tool calls, CLI commands |
|
|
89
|
-
| `files` | File paths, modifications |
|
|
90
|
-
| `decisions` | Trade-offs, rationale, choices |
|
|
91
|
-
|
|
92
|
-
Results use the same format as the Search tab.
|
|
93
|
-
|
|
94
|
-
## Side Panel
|
|
95
|
-
|
|
96
|
-
- Width: 560px, resizable by dragging the left edge
|
|
97
|
-
- Close: X button or press Escape
|
|
98
|
-
- Knowledge entries: rendered as markdown via marked + DOMPurify + highlight.js
|
|
99
|
-
- **Related entries**: linked entries shown with colored relationship-type pills (related_to, depends_on, supersedes, etc.) — clickable to navigate
|
|
100
|
-
- **Score details**: maturity level, access count, decay factor, and maturity multiplier
|
|
101
|
-
- Sessions: chat bubbles (user = right/accent, assistant = left/surface)
|
|
102
|
-
|
|
103
|
-
## Theming
|
|
104
|
-
|
|
105
|
-
- Toggle: sun/moon button in header
|
|
106
|
-
- Persisted in `localStorage('agent-knowledge-theme')`
|
|
107
|
-
- MD3 design tokens matching agent-comm and agent-tasks dashboards
|
|
108
|
-
- CSS custom properties on `:root`, switched via `data-theme` attribute
|
|
109
|
-
|
|
110
|
-
## Live Reload
|
|
111
|
-
|
|
112
|
-
File watcher monitors `src/ui/` for `.html`, `.css`, `.js` changes. On change, broadcasts `{type: "reload"}` via WebSocket. Connected browsers auto-refresh.
|
|
113
|
-
|
|
114
|
-
## Keyboard Shortcuts
|
|
115
|
-
|
|
116
|
-
| Shortcut | Action |
|
|
117
|
-
| --------------- | ------------------ |
|
|
118
|
-
| `/` or `Ctrl+K` | Focus search input |
|
|
119
|
-
| `Escape` | Close side panel |
|
|
120
|
-
|
|
121
|
-
## REST API
|
|
122
|
-
|
|
123
|
-
| Method | Endpoint | Description |
|
|
124
|
-
| ------ | --------------------------------------- | ---------------------------- |
|
|
125
|
-
| GET | `/api/knowledge` | List entries |
|
|
126
|
-
| GET | `/api/knowledge/search?q=` | Search knowledge |
|
|
127
|
-
| GET | `/api/knowledge/:path` | Read entry (with score data) |
|
|
128
|
-
| GET | `/api/knowledge/:path/links` | Graph edges for entry |
|
|
129
|
-
| GET | `/api/knowledge/consolidate?threshold=` | Duplicate cluster analysis |
|
|
130
|
-
| GET | `/api/knowledge/reflect?max_entries=` | Unconnected entries + prompt |
|
|
131
|
-
| GET | `/api/knowledge/god-nodes?top_n=` | Most-connected entries |
|
|
132
|
-
| GET | `/api/knowledge/bridges?top_n=` | Cross-category connectors |
|
|
133
|
-
| GET | `/api/knowledge/gaps?max_entries=` | Isolated entries by maturity |
|
|
134
|
-
| GET | `/api/knowledge/brief` | Cached knowledge base brief |
|
|
135
|
-
| GET | `/api/sessions` | List sessions |
|
|
136
|
-
| GET | `/api/sessions/search?q=&role=&ranked=` | Search sessions |
|
|
137
|
-
| GET | `/api/sessions/recall?scope=&q=` | Scoped recall |
|
|
138
|
-
| GET | `/api/sessions/:id` | Read session |
|
|
139
|
-
| GET | `/api/sessions/:id/summary` | Session summary |
|
|
140
|
-
| POST | `/api/knowledge` | Write entry (JSON body) |
|
|
141
|
-
| GET | `/health` | Health check |
|
|
142
|
-
|
|
143
|
-
### POST /api/knowledge
|
|
144
|
-
|
|
145
|
-
Write a knowledge entry via REST. Runs the same pipeline as the MCP `knowledge(action: "write")` tool: git pull, file write, embedding index, auto-link (cosine > 0.7), git push, duplicate check.
|
|
146
|
-
|
|
147
|
-
**Request:**
|
|
148
|
-
|
|
149
|
-
```json
|
|
150
|
-
{
|
|
151
|
-
"category": "decisions",
|
|
152
|
-
"filename": "my-entry.md",
|
|
153
|
-
"content": "---\ntitle: My Entry\ntags: [foo]\n---\n\nContent here."
|
|
154
|
-
}
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
**Response (201):**
|
|
158
|
-
|
|
159
|
-
```json
|
|
160
|
-
{
|
|
161
|
-
"path": "decisions/my-entry.md",
|
|
162
|
-
"git": { "success": true, "message": "pushed" },
|
|
163
|
-
"autoLinks": [{ "target": "decisions/related.md", "similarity": 0.82 }],
|
|
164
|
-
"duplicateWarnings": []
|
|
165
|
-
}
|
|
166
|
-
```
|
|
167
|
-
|
|
168
|
-
Valid categories: `projects`, `people`, `decisions`, `workflows`, `notes`. POST is restricted to `/api/` paths; non-API POST returns 405.
|
|
169
|
-
|
|
170
|
-
Used by agent-tasks `KnowledgeBridge` to push learning/decision artifacts on task completion.
|
|
171
|
-
|
|
172
|
-
## WebSocket
|
|
173
|
-
|
|
174
|
-
Connects to `ws://localhost:3423` on page load.
|
|
175
|
-
|
|
176
|
-
**State message** (on connect):
|
|
177
|
-
|
|
178
|
-
```json
|
|
179
|
-
{
|
|
180
|
-
"type": "state",
|
|
181
|
-
"knowledge": [...],
|
|
182
|
-
"sessions": [...],
|
|
183
|
-
"stats": { "knowledge_entries": 12, "session_count": 247 }
|
|
184
|
-
}
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
**Reload message** (on file change):
|
|
188
|
-
|
|
189
|
-
```json
|
|
190
|
-
{ "type": "reload" }
|
|
191
|
-
```
|
package/scripts/copy-ui.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { cpSync, copyFileSync } from 'fs';
|
|
2
|
-
import { fileURLToPath } from 'url';
|
|
3
|
-
import { dirname, join } from 'path';
|
|
4
|
-
|
|
5
|
-
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
6
|
-
cpSync(join(root, 'src', 'ui'), join(root, 'dist', 'ui'), { recursive: true });
|
|
7
|
-
copyFileSync(
|
|
8
|
-
join(root, 'node_modules', 'morphdom', 'dist', 'morphdom-umd.min.js'),
|
|
9
|
-
join(root, 'dist', 'ui', 'morphdom.min.js'),
|
|
10
|
-
);
|
|
11
|
-
copyFileSync(
|
|
12
|
-
join(root, 'node_modules', 'vis-network', 'standalone', 'umd', 'vis-network.min.js'),
|
|
13
|
-
join(root, 'dist', 'ui', 'vis-network.min.js'),
|
|
14
|
-
);
|
|
@@ -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
|
-
});
|