agent-knowledge 2.0.0 → 3.1.1

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 (129) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +35 -32
  3. package/dist/embeddings/local.d.ts.map +1 -1
  4. package/dist/embeddings/local.js +3 -1
  5. package/dist/embeddings/local.js.map +1 -1
  6. package/dist/events.d.ts +6 -0
  7. package/dist/events.d.ts.map +1 -1
  8. package/dist/events.js +10 -2
  9. package/dist/events.js.map +1 -1
  10. package/dist/index.js +12 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/knowledge/analyze.d.ts.map +1 -1
  13. package/dist/knowledge/analyze.js +18 -11
  14. package/dist/knowledge/analyze.js.map +1 -1
  15. package/dist/knowledge/distill.d.ts.map +1 -1
  16. package/dist/knowledge/distill.js +28 -16
  17. package/dist/knowledge/distill.js.map +1 -1
  18. package/dist/knowledge/git.d.ts +3 -4
  19. package/dist/knowledge/git.d.ts.map +1 -1
  20. package/dist/knowledge/git.js +60 -46
  21. package/dist/knowledge/git.js.map +1 -1
  22. package/dist/knowledge/graph.d.ts +2 -0
  23. package/dist/knowledge/graph.d.ts.map +1 -1
  24. package/dist/knowledge/graph.js +8 -0
  25. package/dist/knowledge/graph.js.map +1 -1
  26. package/dist/knowledge/ingest-freshness.d.ts +22 -0
  27. package/dist/knowledge/ingest-freshness.d.ts.map +1 -0
  28. package/dist/knowledge/ingest-freshness.js +93 -0
  29. package/dist/knowledge/ingest-freshness.js.map +1 -0
  30. package/dist/knowledge/remove.d.ts +11 -0
  31. package/dist/knowledge/remove.d.ts.map +1 -0
  32. package/dist/knowledge/remove.js +24 -0
  33. package/dist/knowledge/remove.js.map +1 -0
  34. package/dist/knowledge/search.d.ts +74 -8
  35. package/dist/knowledge/search.d.ts.map +1 -1
  36. package/dist/knowledge/search.js +321 -40
  37. package/dist/knowledge/search.js.map +1 -1
  38. package/dist/knowledge/similar.d.ts +7 -0
  39. package/dist/knowledge/similar.d.ts.map +1 -0
  40. package/dist/knowledge/similar.js +51 -0
  41. package/dist/knowledge/similar.js.map +1 -0
  42. package/dist/knowledge/store.d.ts +17 -0
  43. package/dist/knowledge/store.d.ts.map +1 -1
  44. package/dist/knowledge/store.js +117 -79
  45. package/dist/knowledge/store.js.map +1 -1
  46. package/dist/rest-server.d.ts +12 -2
  47. package/dist/rest-server.d.ts.map +1 -1
  48. package/dist/rest-server.js +75 -10
  49. package/dist/rest-server.js.map +1 -1
  50. package/dist/search/bm25.d.ts +8 -0
  51. package/dist/search/bm25.d.ts.map +1 -1
  52. package/dist/search/bm25.js +32 -20
  53. package/dist/search/bm25.js.map +1 -1
  54. package/dist/search/excerpt.d.ts +1 -1
  55. package/dist/search/excerpt.d.ts.map +1 -1
  56. package/dist/search/excerpt.js +19 -1
  57. package/dist/search/excerpt.js.map +1 -1
  58. package/dist/search/lexicon.d.ts +37 -0
  59. package/dist/search/lexicon.d.ts.map +1 -0
  60. package/dist/search/lexicon.js +83 -0
  61. package/dist/search/lexicon.js.map +1 -0
  62. package/dist/search/mmr.d.ts +9 -3
  63. package/dist/search/mmr.d.ts.map +1 -1
  64. package/dist/search/mmr.js +21 -7
  65. package/dist/search/mmr.js.map +1 -1
  66. package/dist/search/types.d.ts +2 -0
  67. package/dist/search/types.d.ts.map +1 -1
  68. package/dist/server.d.ts.map +1 -1
  69. package/dist/server.js +0 -5
  70. package/dist/server.js.map +1 -1
  71. package/dist/sessions/human.d.ts +12 -0
  72. package/dist/sessions/human.d.ts.map +1 -0
  73. package/dist/sessions/human.js +52 -0
  74. package/dist/sessions/human.js.map +1 -0
  75. package/dist/sessions/parser.d.ts +39 -0
  76. package/dist/sessions/parser.d.ts.map +1 -1
  77. package/dist/sessions/parser.js +142 -18
  78. package/dist/sessions/parser.js.map +1 -1
  79. package/dist/sessions/search.d.ts +2 -0
  80. package/dist/sessions/search.d.ts.map +1 -1
  81. package/dist/sessions/search.js +147 -67
  82. package/dist/sessions/search.js.map +1 -1
  83. package/dist/sessions/snapshot.d.ts +19 -0
  84. package/dist/sessions/snapshot.d.ts.map +1 -0
  85. package/dist/sessions/snapshot.js +118 -0
  86. package/dist/sessions/snapshot.js.map +1 -0
  87. package/dist/sessions/summary.d.ts +24 -5
  88. package/dist/sessions/summary.d.ts.map +1 -1
  89. package/dist/sessions/summary.js +106 -145
  90. package/dist/sessions/summary.js.map +1 -1
  91. package/dist/slice.d.ts +5 -0
  92. package/dist/slice.d.ts.map +1 -0
  93. package/dist/slice.js +28 -0
  94. package/dist/slice.js.map +1 -0
  95. package/dist/text.d.ts +9 -0
  96. package/dist/text.d.ts.map +1 -0
  97. package/dist/text.js +16 -0
  98. package/dist/text.js.map +1 -0
  99. package/dist/tool-handlers.d.ts.map +1 -1
  100. package/dist/tool-handlers.js +6 -10
  101. package/dist/tool-handlers.js.map +1 -1
  102. package/dist/transport/rest.d.ts.map +1 -1
  103. package/dist/transport/rest.js +152 -35
  104. package/dist/transport/rest.js.map +1 -1
  105. package/dist/vectorstore/store.d.ts +9 -0
  106. package/dist/vectorstore/store.d.ts.map +1 -1
  107. package/dist/vectorstore/store.js +23 -0
  108. package/dist/vectorstore/store.js.map +1 -1
  109. package/dist/wakeup.d.ts +5 -0
  110. package/dist/wakeup.d.ts.map +1 -1
  111. package/dist/wakeup.js +10 -1
  112. package/dist/wakeup.js.map +1 -1
  113. package/docs/ARCHITECTURE.md +6 -9
  114. package/docs/HOOKS.md +138 -237
  115. package/docs/SETUP.md +61 -122
  116. package/docs/USER-MANUAL.md +45 -31
  117. package/package.json +6 -6
  118. package/plugin/skills/knowledge-ingest/scripts/validate.mjs +2 -2
  119. package/scripts/plugins/opencode/agent-knowledge.ts +32 -81
  120. package/scripts/setup.js +78 -145
  121. package/scripts/source-walk.d.mts +12 -0
  122. package/scripts/source-walk.mjs +94 -0
  123. package/scripts/tree-sitter-extract.mjs +10 -76
  124. package/scripts/hooks/first-prompt-inject.mjs +0 -242
  125. package/scripts/hooks/precompact-distill.mjs +0 -105
  126. package/scripts/hooks/precompact-flush.mjs +0 -192
  127. package/scripts/hooks/session-start-ingest.mjs +0 -238
  128. package/scripts/hooks/session-start.js +0 -211
  129. package/scripts/hooks/sessionend-distill.mjs +0 -198
@@ -142,20 +142,18 @@ knowledge_admin with action "config", memory_dir "/custom/path/knowledge"
142
142
  knowledge_admin with action "config", auto_distill false
143
143
  ```
144
144
 
145
- ### Lifecycle Hooks
145
+ ### The session lifecycle
146
146
 
147
- agent-knowledge ships six lifecycle hook scripts that integrate with Claude Code's event system. Running `node scripts/setup.js` installs all six into `~/.claude/settings.json`; on other hosts that don't support lifecycle hooks (Cursor, Windsurf), the MCP tools still work — you just lose the automatic context injection.
147
+ With the Claude Code plugin installed, each session works with the knowledge base on its own; there is nothing to configure:
148
148
 
149
- | Script | Event | Purpose |
150
- | -------------------------- | ---------------- | ------------------------------------------------------------------------- |
151
- | `session-start.js` | SessionStart | Names the `/knowledge` pane + auto-loads the L0 identity into context |
152
- | `session-start-ingest.mjs` | SessionStart | Detects project + reports knowledge-ingest cache drift via SHA256 diff |
153
- | `first-prompt-inject.mjs` | UserPromptSubmit | Query-targeted knowledge hits injected on the session's first real prompt |
154
- | `precompact-flush.mjs` | PreCompact | Rich session summary on disk + save-unsaved-context nudge into context |
155
- | `precompact-distill.mjs` | PreCompact | Lightweight text snapshot of recent user prompts |
156
- | `sessionend-distill.mjs` | SessionEnd | Final summary (turn counts, tool uses, first 20 prompts) |
149
+ | When | What happens |
150
+ | -------------------------------- | --------------------------------------------------------------------------------------------------- |
151
+ | The conversation's first message | The model knows what the knowledge base holds, who you are (or asks you once), and the ingest state |
152
+ | Your first real prompt | The entries that match it ride beside it; one line in the transcript names them |
153
+ | A compaction | The session is snapshotted into `sessions/<project>/`; the summary keeps what is still to be saved |
154
+ | The session ending or `/clear` | The session's last snapshot; open `/knowledge` panes toast it |
157
155
 
158
- Every hook fails open — if a script errors, it logs to stderr and the session continues. Each hook has env-var toggles (`AGENT_KNOWLEDGE_AUTOWAKE`, `AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT`, `AGENT_KNOWLEDGE_PRECOMPACT_NUDGE`, etc.) — see [`docs/HOOKS.md`](HOOKS.md) for the full reference, test coverage, and budget/threshold knobs.
156
+ Every part fails open: with the server down the session goes on as without the plugin. Each has a switch (`AGENT_KNOWLEDGE_AUTOWAKE`, `AGENT_KNOWLEDGE_FIRSTPROMPT_INJECT`, `AGENT_KNOWLEDGE_PRECOMPACT_NUDGE`, budgets) — see [`docs/HOOKS.md`](HOOKS.md). Hosts without the plugin (Cursor, Windsurf) keep the MCP tools; OpenCode has its own plugin.
159
157
 
160
158
  ### Persistent Memory — agent-knowledge, not host auto-memory
161
159
 
@@ -200,7 +198,7 @@ Every picture below is from a recorded session in the real Claude Code CLI again
200
198
  | `/knowledge <words>` | Search, with the hits for the words (entries and past sessions) |
201
199
  | `/knowledge <path>` | that entry's page; `.md` may be left off (`/knowledge decisions/rest-only`) |
202
200
 
203
- The command answers in the conversation with the counts (`8 entries · 2 sessions`), how many hits a search found, which entry it opened (`opened REST only, no WebSocket`), or why nothing answers. The pane opens beside the conversation in the fullscreen layout, above the prompt otherwise.
201
+ The command's reply goes to the model too, so it says something only when something is wrong: nothing found for the words, no such entry, nothing answers at the port, or the pane could not be shown (then with the counts). Plain `/knowledge` shows every entry, clearing a Find or category left from before. The pane opens beside the conversation in the fullscreen layout, above the prompt otherwise; an open pane is opened afresh.
204
202
 
205
203
  ![Opening the pane](images/manual/open.gif)
206
204
 
@@ -224,7 +222,7 @@ The same line shows what an action is doing (`searching "zebrafish"…`) and how
224
222
 
225
223
  ![Browse](images/manual/browse.png)
226
224
 
227
- Every entry, newest first. Under each title: its category, `evergreen` for entries kept from decay, its maturity once it is past `candidate` (`established`, `proven`), its first tags and how long ago it was updated. Files at the top of the knowledge folder are under `other`. An entry another session writes or deletes shows on the next poll, without a key; the ring stays on the row it held.
225
+ Every entry, newest first. Under each title: its category, `evergreen` for entries kept from decay, its maturity once it is past `candidate` (`established`, `proven`), its first tags and how long ago it was updated. Files at the top of the knowledge folder are under `other`; the session snapshots are their own category, `snapshots`, last in the bar and not in `all`. An entry another session writes or deletes shows on the next poll, without a key; the ring stays on the row it held, and while the pane has the keyboard the rows keep their order (a new one comes at the end). An empty knowledge base offers the next step: **Ingest &lt;project&gt; ›** puts `/knowledge-ingest <folder>` in the prompt for you to run.
228
226
 
229
227
  ![Browse, the whole screen](images/manual/browse-full.png)
230
228
 
@@ -238,7 +236,7 @@ The category bar narrows the list; the counts are the knowledge base's.
238
236
 
239
237
  ![Finding by a tag](images/manual/find.gif)
240
238
 
241
- A long list comes 25 rows at a time: `▸ 25 more (n left)` adds the next page and puts the ring on its first row.
239
+ A long list comes 25 rows at a time: `▸ 25 more` adds the next page and puts the ring on its first row, shown whole.
242
240
 
243
241
  ### An entry
244
242
 
@@ -248,11 +246,11 @@ Its title, path, category, maturity, how often agents read it and when it was up
248
246
 
249
247
  ![Following a link and back](images/manual/entry.gif)
250
248
 
251
- The body is drawn as Markdown, without its frontmatter (those are the facts above) and without a first heading that only repeats the title. A long body folds after 30 lines: `▸ Show all n lines`.
249
+ The body is drawn as Markdown, without its frontmatter (those are the facts above) and without a first heading that only repeats the title. Code is drawn apart, a dim `│` before each line: a long command that wraps continues indented, with no bar, so it never reads as a second one. Links in the text are listed with the links (`→ mentions`); a table too wide for the pane reads a row a line, each value with its header (`Owner: alice`). A long body folds after 30 lines: `▸ Show all n lines`. The page follows its file: an edit from another session shows on the next poll, said (`! notes/x.md changed elsewhere`), and an entry deleted elsewhere takes you back to the list (`! notes/x.md was deleted elsewhere`).
252
250
 
253
251
  ![Folding a long body](images/manual/fold.gif)
254
252
 
255
- **Delete** is at the end of the page and asks first, with the ring on **Never mind**; the confirmation says what happens: without a git remote the file goes from this machine, with one the deletion is pushed too, and a remote that refuses is said with it (`✓ deleted notes/x.md (not pushed: …)`).
253
+ **Delete** is at the end of the page and asks first, with **Keep it** first and the ring on it, and **Delete notes/x.md** beside it. The question says what happens: without a git remote the file goes from this machine for good, with one the deletion is pushed too (its git history keeps it), and how many entries that link to it lose that link. A remote that refuses is said as a warning (`! deleted notes/x.md, not pushed: …`).
256
254
 
257
255
  ![Delete asks first](images/manual/confirm-delete.png)
258
256
 
@@ -262,13 +260,13 @@ The body is drawn as Markdown, without its frontmatter (those are the facts abov
262
260
 
263
261
  ![Search](images/manual/search.png)
264
262
 
265
- Search finds words, and close spellings, in every entry and in past sessions (Claude Code, Cursor, OpenCode). Best matches first: **Entries** with their category and a line of the text around the match, then **Sessions** with the project, when, whether you asked it or the agent answered, and the line. An excerpt is the entry's text without its headings and code blocks, paragraphs, list items and table rows joined with `·`. The ring lands on the best hit; `Enter` opens it. With no hit the line under the tabs says so: a search typed in the field keeps the ring there to try again, and one run as `/knowledge <words>` leaves the ring on a button, so the next command you type runs as a command.
263
+ Search finds words, and close spellings, in every entry and in past sessions (Claude Code, Cursor, OpenCode). Best matches first: **Entries** with their category and a line of the text around the match, then **In past sessions** with the project, when, whether you asked it or the agent answered, and the line. An excerpt is the entry's text without its headings and code blocks, paragraphs, list items and table rows joined with `·`. The ring lands on the best hit; `Enter` opens it. `2` again (or `Enter` on the tab) puts the ring in the field with the last search's words, to edit. With no hit the page says so: a search typed in the field keeps the ring there to try again, and one run as `/knowledge <words>` leaves the ring on a button, so the next command you type runs as a command.
266
264
 
267
265
  ![Searching and opening a hit](images/manual/search.gif)
268
266
 
269
267
  ### Sessions
270
268
 
271
- The recent sessions on this machine, newest first: project, when it started, how long it ran, the git branch and the first thing asked. A session opens on its summary: what was asked, files changed, commits, errors (in red) and the tools used.
269
+ The recent sessions on this machine, newest first: the project's folder name (this session marked `(this session)`), when it started, how long it ran, the git branch and the first thing asked (a slash command is not a question). Sessions where nothing was asked, a `/clear` alone say, are folded behind `▸ n more where nothing was asked`. `▸ 25 more` goes on past the newest 100, loading older sessions from the server. A session opens on its summary: how many prompts, its id and how to resume it (`claude --resume <id>`), what was asked, files changed, commits, errors (in red) and the tools used. A session snapshot's page opens its session when its transcript is on this machine, and back leads to the snapshot.
272
270
 
273
271
  ![A session's summary](images/manual/session.png)
274
272
 
@@ -278,15 +276,15 @@ The recent sessions on this machine, newest first: project, when it started, how
278
276
 
279
277
  ![Health](images/manual/health.png)
280
278
 
281
- How many entries (by category) and sessions there are, whether search uses meaning too (`words and meaning: n vectors`) or words only, where the knowledge folder is and whether a git remote syncs it. **Sync now** (shown with a remote) pulls and pushes. **Analyze links** lists the most linked entries (two links or more) and, apart from them, the ones with one link or none: those are the entries nothing much leads to. The folder is cut from the left to fit (`…\knowledge`). **Recent activity** lists what the hooks reported, such as a session distilled at its end.
279
+ How many entries (by category), session snapshots and sessions there are, whether search uses meaning too (`words and meaning: n vectors`) or words only, where the knowledge folder is and whether a git remote syncs it, and whether this project's code is ingested (**Ingest &lt;project&gt; ›** when it was never, or files changed since). **Sync now** (shown with a remote) pulls and pushes; the ring never lands on it by itself. **Recent activity** lists what was reported, such as a session saved or a sync that failed. **Analyze links** lists the most linked entries (two links or more) and, apart from them, the ones with one link or none, fewest first, 30 at a time (`▸ 30 more`): those are the entries nothing much leads to. The folder is shown whole, wrapped when long.
282
280
 
283
281
  ![Analyzing the links](images/manual/health.gif)
284
282
 
285
283
  ### Status line, toasts and what the model sees
286
284
 
287
- The status line under the prompt reads `agent-knowledge: 8 entries · 2 sessions`, from the moment a session starts; `offline` when nothing answers, `old server x on the port` when an agent-knowledge from before the pane does.
285
+ The status line under the prompt reads `agent-knowledge: 8 entries · 2 sessions`, from the moment a session starts; `offline` when nothing answers, `old server x on the port` when an agent-knowledge from before the pane does. While the pane is shown it says the last outcome for its 10 seconds (it may be scrolled out of view). Outcomes are marked: ✓ done, ✗ failed or refused, ! changed elsewhere, – nothing happened.
288
286
 
289
- A live event (a session distilled at its end) is toasted once, beside the conversation, and listed under Health.
287
+ A live event (a session saved at its end) is toasted once, beside the conversation (`Session saved: demo · 2026-11-13 · fix the sync`; three at most, then `+n more`), and listed under Health. A project never ingested, or files changed since its ingest, is toasted once with the conversation's first message.
290
288
 
291
289
  ![A toast](images/manual/toast.png)
292
290
 
@@ -300,9 +298,15 @@ Docked in the fullscreen layout the pane takes the right side of the window; on
300
298
 
301
299
  ![Above the prompt](images/manual/inline.png)
302
300
 
301
+ From 80 columns a row is one line: the title, its facts at the right.
302
+
303
+ ### In the desktop app
304
+
305
+ In the Claude desktop app the pane is drawn natively, laid out as the old web dashboard was: a head with the server's state, git sync, **Refresh** and **Sync now**, tiles for entries, sessions, snapshots and vectors; a side column with the tabs and the categories, each with its count; the view beside it. An entry's page shows its links as a graph of its neighbours above the list, and its body whole; Health adds charts of the entries per category and of those updated per week. A narrow dock (under 90 columns) stacks the side column above the view. Minimized to a widget, the pane is a glance: the counts, the categories as one bar, git and the latest activity, and a **Search** button.
306
+
303
307
  ### When the server is away
304
308
 
305
- One agent-knowledge MCP process serves the REST API on `127.0.0.1:3423`; when its session ends another one takes the port over within a few seconds. While nothing answers, the pane says so and offers only **Refresh**; it comes back by itself on the next poll.
309
+ One agent-knowledge MCP process serves the REST API on `127.0.0.1:3423`; when its session ends another one takes the port over within a few seconds. While nothing answers, the pane says so and **Refresh** tries again (`✗ still nothing answers at http://127.0.0.1:3423 (12:04:31)`); the tabs stay, so `1`–`4` never land in the prompt, and it comes back by itself on the next poll.
306
310
 
307
311
  ![The server away](images/manual/server-down.png)
308
312
 
@@ -835,40 +839,50 @@ knowledge_analyze with action "search_gaps", since_days 7, min_count 3
835
839
 
836
840
  ## 6. REST API Reference
837
841
 
838
- The first MCP process serves a local REST API on `127.0.0.1:3423` (`AGENT_KNOWLEDGE_PORT`); the other sessions retry the port and take it over when that process exits. It is what the `/knowledge` pane, the hook scripts, the opencode plugin and agent-tasks call. Loopback only: a foreign `Host` or any `Origin` header gets 403, request bodies must be `application/json`, no CORS. A `:path` with a slash is sent encoded (`projects%2Fbackend.md`).
842
+ The first MCP process serves a local REST API on `127.0.0.1:3423` (`AGENT_KNOWLEDGE_PORT`); the other sessions retry the port and take it over when that process exits. It is what the Claude Code plugin (the `/knowledge` pane and the session lifecycle), the opencode plugin and agent-tasks call. Loopback only: a foreign `Host` or any `Origin` header gets 403, request bodies must be `application/json`, no CORS. A `:path` with a slash is sent encoded (`projects%2Fbackend.md`).
839
843
 
840
844
  ### Health
841
845
 
842
846
  ```
843
- GET /health Status, version, uptime, knowledge entry count
847
+ GET /health Status, version, uptime, entries (curated) and snapshots
844
848
  ```
845
849
 
846
850
  ### Knowledge Entries
847
851
 
848
852
  ```
849
- GET /api/overview Counts, categories, recent events (the pane)
853
+ GET /api/overview entries (curated), snapshots, categories (curated), recent events (the pane)
850
854
  GET /api/knowledge List entries with scoring (?category=&tag=)
851
- GET /api/knowledge/search Search entries (?q=&category=&max_results=)
852
- GET /api/knowledge/:path Read entry content (enriched with score data); 404 when missing
855
+ GET /api/knowledge/search Search entries (?q=&category=&max_results=&mmr=true&skip=sessions&min_terms=2&prompt=true; prompt: q is a prompt, reply-format phrases dropped)
856
+ GET /api/knowledge/:path Read entry content (enriched with score data; a snapshot adds session_on_machine); 404 when missing
853
857
  GET /api/knowledge/:path/links Graph edges for an entry, each with the other end's title
854
858
  DELETE /api/knowledge/:path Delete an entry (git synced)
855
859
  POST /api/knowledge Write an entry: { category, filename, content } -> 201 { path, git, autoLinks?, duplicateWarnings? }
856
860
  POST /api/knowledge/sync git pull + push
857
- GET /api/analysis Hubs and isolated entries (the pane)
861
+ GET /api/analysis { hubs, sparse, sparse_total, offset } (?offset=&limit=30): sparse fewest links first, then by title
858
862
  ```
859
863
 
860
864
  ### Sessions
861
865
 
862
866
  ```
863
- GET /api/sessions Sessions, paged: { sessions, total } (?project=&limit=&offset=; limit default 50, max 500)
864
- GET /api/sessions/search Search sessions (?q=&role=&max_results=&ranked=&project=&semantic=)
867
+ GET /api/sessions Sessions, paged: { sessions, total } (?project=&limit=&offset=; limit default 50, max 500);
868
+ userMessageCount = real prompts (no /commands), preview '' without one
869
+ GET /api/sessions/search Search sessions (?q=&role=&max_results=&ranked=&project=&semantic=); hits carry name
865
870
  GET /api/sessions/:id/summary Session summary (?project=); 404 when unknown
871
+ POST /api/sessions/:id/snapshot { event: compact|end, cwd? } -> { path, prompts, messages, tools }: the session into
872
+ sessions/<project>/<day>-<id>.md (path null: nothing was asked); 404 when unknown
873
+ ```
874
+
875
+ ### Session lifecycle
876
+
877
+ ```
878
+ GET /api/wakeup The wakeup bundle (?sections=identity,...&budget=) and onboarding: configured|declined|pending
879
+ GET /api/ingest The folder's ingest freshness (?cwd=): state none|never|current|stale, project, counts
866
880
  ```
867
881
 
868
882
  ### Events
869
883
 
870
884
  ```
871
- POST /api/events { kind, message } -> 201 { id, ts }: a receipt the /knowledge pane shows (the sessionend hook)
885
+ POST /api/events { kind, message } -> 201 { id, ts }: a receipt the /knowledge pane toasts (any host)
872
886
  ```
873
887
 
874
888
  ### Example Requests
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-knowledge",
3
- "version": "2.0.0",
3
+ "version": "3.1.1",
4
4
  "description": "Cross-session memory and recall for AI agents — git-synced knowledge base, knowledge graph, confidence scoring, hybrid semantic+TF-IDF search, auto-distillation with secrets scrubbing",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -43,8 +43,8 @@
43
43
  "bench:longmemeval:matrix": "tsx bench/longmemeval-matrix.ts",
44
44
  "bench:promote": "tsx bench/promote-bench.ts",
45
45
  "test:coverage": "vitest run --coverage",
46
- "lint": "eslint src/ tests/",
47
- "lint:fix": "eslint src/ tests/ --fix",
46
+ "lint": "eslint src/ tests/ plugin/",
47
+ "lint:fix": "eslint src/ tests/ plugin/ --fix",
48
48
  "format": "prettier --write .",
49
49
  "format:check": "prettier --check .",
50
50
  "typecheck": "tsc --noEmit",
@@ -52,8 +52,8 @@
52
52
  "plugin:check": "claude plugin validate plugin && claude plugin test plugin",
53
53
  "clean": "rm -rf dist",
54
54
  "prepare": "husky",
55
- "e2e:claude": "npm run build && node tests/e2e-claude/run.mjs",
56
- "manual:record": "npm run build && tsx tests/e2e-claude/manual.ts"
55
+ "e2e:claude": "tsc --outDir dist-e2e && node tests/e2e-claude/run.mjs",
56
+ "manual:record": "tsc --outDir dist-e2e && tsx tests/e2e-claude/manual.ts"
57
57
  },
58
58
  "keywords": [
59
59
  "mcp",
@@ -117,7 +117,7 @@
117
117
  "@huggingface/transformers": "3.8.1"
118
118
  },
119
119
  "lint-staged": {
120
- "*.{ts,js}": [
120
+ "*.{ts,tsx,js,mjs}": [
121
121
  "prettier --write",
122
122
  "eslint --fix"
123
123
  ],
@@ -134,7 +134,7 @@ function main() {
134
134
  if (cache.files && typeof cache.files === 'object') {
135
135
  let missingHashes = 0;
136
136
  let missingEntryRefs = 0;
137
- for (const [filePath, meta] of Object.entries(cache.files)) {
137
+ for (const meta of Object.values(cache.files)) {
138
138
  if (!meta.sha256 || typeof meta.sha256 !== 'string' || meta.sha256.length !== 64) {
139
139
  missingHashes++;
140
140
  }
@@ -163,7 +163,7 @@ function main() {
163
163
  issues,
164
164
  };
165
165
 
166
- console.log(JSON.stringify(report, null, 2));
166
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
167
167
  process.exit(issues.length === 0 ? 0 : 1);
168
168
  }
169
169
 
@@ -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 (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
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
  // =============================================================================
@@ -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 {
@@ -125,6 +124,11 @@ async function searchKnowledge(query: string): Promise<Hit[]> {
125
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 {
@@ -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 */