agent-knowledge 1.9.2 → 1.9.4

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agent-knowledge",
3
3
  "description": "Cross-session memory for AI coding agents. Git-synced Markdown knowledge base with hybrid semantic + TF-IDF search, typed knowledge graph, and session auto-distillation with secrets scrubbing.",
4
- "version": "1.9.2",
4
+ "version": "1.9.3",
5
5
  "author": {
6
6
  "name": "keshrath"
7
7
  },
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.9.4 (2026-04-19) — visible knowledge-hook feedback + L0-only SessionStart
4
+
5
+ ### Changed
6
+
7
+ - **`scripts/hooks/first-prompt-inject.mjs` now emits a user-visible `systemMessage`** alongside the silent `additionalContext`. When the session's first real prompt triggers injection, the host renders a one-line summary like `knowledge: injected 4 hits (decisions/database-choice.md, sessions/odoo-sh/...md, +2 more)` in the transcript, so the user can see which entries the model received without having to diff context.
8
+ - **`scripts/hooks/session-start.js` now auto-loads L0 identity only**, not the full L0+L1 wakeup pack. L1 top-weighted facts are covered by `first-prompt-inject.mjs`, which runs query-targeted search against the KB on the session's first real prompt — a better-matched slice than any query-agnostic pre-load. Effect: ~600 fewer tokens pre-loaded per session on average, no loss of context quality because `first-prompt-inject.mjs` fills the same budget one turn later with relevance-ranked content.
9
+ - **`AGENT_KNOWLEDGE_WAKEUP_BUDGET` default changed from 800 → 200 tokens.** L0 identity is small; the legacy 800-token ceiling existed to accommodate the now-removed L1 pack. Users who want the full legacy L0+L1 injection can still call `knowledge(action="wakeup")` manually — the MCP tool is unchanged.
10
+ - **SessionStart `systemMessage`** now always appends a status suffix so the user can tell the hook ran: `identity: 312 chars` when an `identity.md` is loaded, `identity: placeholder (no identity.md)` when only the default placeholder was emitted, or `autowake off · <source>` when disabled. Previously the suffix was suppressed on the "no identity.md" path, which was visually indistinguishable from the pre-v1.9.4 URL-only line.
11
+
12
+ ### Fixed
13
+
14
+ - **`session-start.js` clears the `first-prompt-inject.mjs` marker on every SessionStart event.** Resumed sessions reuse the same `session_id`, so the marker from the prior run stayed on disk and the inject hook silently skipped the next user prompt. Now every `/exit`+resume (or `/clear`) re-arms query-targeted injection. When the marker is cleared, the SessionStart `systemMessage` appends `· inject rearmed`.
15
+
16
+ ### Added
17
+
18
+ - **Identity onboarding.** When no `identity.md` (or `IDENTITY.md`) exists in the memory dir AND no `.identity-declined` opt-out marker is present, `session-start.js` injects a short instruction into `additionalContext` telling the agent to ask the user three questions (name/role, stack, projects) and save the answers via the host's `Write` tool directly into `~/agent-knowledge/identity.md`. No manual file creation; the agent drives the flow. If the user says "skip" / "not now", the agent writes `~/agent-knowledge/.identity-declined` and the nag stops. Delete that file to re-enable. The SessionStart `systemMessage` reports `identity: onboarding pending` or `identity: declined` accordingly.
19
+
20
+ Neither change alters the model-facing MCP API. Fail-open behaviour unchanged: errors still produce a valid empty JSON response.
21
+
22
+ ### Tests
23
+
24
+ 563/563 passing. New assertions cover: `first-prompt-inject.mjs` `systemMessage` shape, `session-start.js` dashboard-URL line, identity-onboarding instruction when neither `identity.md` nor `.identity-declined` exist, opt-out path via `.identity-declined`, happy-path with an existing `identity.md`, and first-prompt-inject marker clear on resume. Existing hook tests only asserted `hookSpecificOutput`, which stays the same shape; the new `systemMessage` field is additive.
25
+
26
+ ## 1.9.3 (2026-04-19) — README showcase rewrite
27
+
28
+ ### Changed
29
+
30
+ - **README no longer carries inline version markers** (`(v1.8)`, `(v1.8.1)`, `(v1.8 lifecycle integration)`). The feature list now describes the current state as a single coherent surface — version history lives in this CHANGELOG where it belongs. Moves the README from "changelog-in-bullet-points" to "how it works today".
31
+ - **Section renames to match**: `### Scored promoter (v1.8)` → `### Scored promoter`, `### Hooks (v1.8 lifecycle integration)` → `### Hooks`, `v1.8 search knobs:` → `Search knobs:`.
32
+ - **Wakeup bullet now names the token budget** — 800 default, overridable via `token_budget` param or `AGENT_KNOWLEDGE_WAKEUP_BUDGET` env var. The number was previously only in the env-var table.
33
+ - **Testing block refreshed** — stale `352 tests across 20 files` replaced with the real `558 tests across 35 files`; added `typecheck` and `check` script references so the documented workflow matches what `npm run check` actually runs.
34
+
35
+ ### Tests
36
+
37
+ 558/558 passing. Docs + metadata only — no source changes.
38
+
3
39
  ## 1.9.2 (2026-04-19) — doc/setup drift cleanup + HOOKS.md rename
4
40
 
5
41
  ### Fixed
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
4
  [![Node >= 20](https://img.shields.io/badge/Node-%3E%3D%2020-brightgreen.svg)](https://nodejs.org)
5
- [![Tests: 558 passing](https://img.shields.io/badge/Tests-558%20passing-brightgreen.svg)]()
5
+ [![Tests: 563 passing](https://img.shields.io/badge/Tests-563%20passing-brightgreen.svg)]()
6
6
  [![MCP Tools: 6](https://img.shields.io/badge/MCP%20Tools-6-blueviolet.svg)]()
7
7
  [![LongMemEval R@5: 98.8%](https://img.shields.io/badge/LongMemEval%20R%405-98.8%25-brightgreen.svg)]()
8
8
 
@@ -51,17 +51,17 @@ No configuration needed. Additional session roots can be added via the `AGENT_KN
51
51
  - **Host-agnostic session search** -- unified search across every major AI coding assistant (Claude Code, Cursor, Codex CLI, Aider, Continue.dev, Cline, OpenCode). No host name is baked into configuration — the adapter registry probes installed host roots at startup.
52
52
  - **Hybrid search** -- semantic vector similarity blended with TF-IDF keyword ranking
53
53
  - **Git-synced knowledge base** -- markdown vault with YAML frontmatter, auto commit and push on writes
54
- - **Automatic staleness detection (v1.8.1)** -- `knowledge_analyze(action: "stale_by_code_activity")` cross-references file paths mentioned in each entry body against `filesModified` in recent session summaries. Pairs with a symbol-presence precision layer: identifiers the entry quotes (inline backticks + fenced blocks) are checked in the touched file; if they still exist, confidence downweights ×0.3. Entries with `evergreen: true` are exempt.
55
- - **Search-gap tracking (v1.8.1)** -- `knowledge_analyze(action: "search_gaps")` surfaces zero-result queries over the last `since_days`, grouped by token-Jaccard similarity. The clearest signal for "what entries should I write next?".
56
- - **Section-priority context packer (v1.8.1)** -- `knowledge(action: "wakeup")` assembles a multi-section bundle (`identity` → `active_tasks` → `recent_decisions` → `known_gotchas` → `last_session_summary` → `top_weighted` → `semantic_fallback`) within a token budget. Unused section budget redistributes to later sections.
57
- - **Scored + gated promoter (v1.8)** -- session insights promoted via a 6-signal weighted scorer with three independent gates (`minScore`, `minRecallCount`, `minUniqueQueries`). Runs automatically in background, on demand via `knowledge_admin(action: "promote")`, or benchable offline via `npm run bench:promote`. Emits an auditable `.dreams/YYYY-MM-DD.md` diary every run. Replaces the regex-only distiller.
54
+ - **Automatic staleness detection** -- `knowledge_analyze(action: "stale_by_code_activity")` cross-references file paths mentioned in each entry body against `filesModified` in recent session summaries. Pairs with a symbol-presence precision layer: identifiers the entry quotes (inline backticks + fenced blocks) are checked in the touched file; if they still exist, confidence downweights ×0.3. Entries with `evergreen: true` are exempt.
55
+ - **Search-gap tracking** -- `knowledge_analyze(action: "search_gaps")` surfaces zero-result queries over the last `since_days`, grouped by token-Jaccard similarity. The clearest signal for "what entries should I write next?".
56
+ - **Section-priority context packer** -- `knowledge(action: "wakeup")` assembles a multi-section bundle (`identity` → `active_tasks` → `recent_decisions` → `known_gotchas` → `last_session_summary` → `top_weighted` → `semantic_fallback`) within a token budget (default 800, override via `token_budget` or `AGENT_KNOWLEDGE_WAKEUP_BUDGET`). Unused section budget redistributes to later sections.
57
+ - **Scored + gated promoter** -- session insights promoted via a 6-signal weighted scorer with three independent gates (`minScore`, `minRecallCount`, `minUniqueQueries`). Runs automatically in background, on demand via `knowledge_admin(action: "promote")`, or benchable offline via `npm run bench:promote`. Emits an auditable `.dreams/YYYY-MM-DD.md` diary every run.
58
58
  - **Pluggable adapter system** -- add support for new tools by implementing the `SessionAdapter` interface
59
59
  - **Embeddings** -- local (Hugging Face), OpenAI, Claude/Voyage, or Gemini providers
60
60
  - **Fuzzy matching** -- typo-tolerant search using Levenshtein distance
61
61
  - **6 search scopes** -- errors, plans, configs, tools, files, decisions
62
62
  - **6 MCP tools** -- consolidated action-based interface (`knowledge`, `knowledge_search`, `knowledge_session`, `knowledge_graph`, `knowledge_analyze`, `knowledge_admin`)
63
- - **Evergreen entries (v1.8)** -- `evergreen: true` in frontmatter exempts an entry from decay in ranking AND makes it append-only under promotion. Dashboard renders a push-pin badge on these cards.
64
- - **Author attribution (v1.8.1)** -- optional `author: <string>` frontmatter surfaces as a muted chip on each card.
63
+ - **Evergreen entries** -- `evergreen: true` in frontmatter exempts an entry from decay in ranking AND makes it append-only under promotion. Dashboard renders a push-pin badge on these cards.
64
+ - **Author attribution** -- optional `author: <string>` frontmatter surfaces as a muted chip on each card.
65
65
  - **Code graph resolution** -- `calls`, `imports`, `inherits` edge types for code structure; directed BFS traversal (`outbound`/`inbound`/`both`); `bulk_link` for efficient ingestion; `unlink_by_origin` for clearing stale code edges before re-ingest; `code:` prefixed node IDs distinguish code from knowledge
66
66
  - **Temporal knowledge graph** -- edges support `valid_from` / `valid_to` validity windows; `as_of` queries return point-in-time snapshots; `invalidate` action marks facts as ended without deleting them
67
67
  - **Hybrid scoring boosts** -- proper-noun and temporal-proximity boosts on top of TF-IDF + semantic blend, capped at +66.7%, short-circuit when no signals are present
@@ -81,8 +81,8 @@ No configuration needed. Additional session roots can be added via the `AGENT_KN
81
81
  - **Knowledge brief** — `knowledge_analyze(action: "brief")` returns a cached ~200 token summary (core concepts, active projects, recent decisions, stale and gap counts) for session-start orientation
82
82
  - **Edge provenance** — graph edges track `origin` (manual, auto-link, distill, reflect) so analysis can distinguish user judgment from automated heuristics
83
83
  - **Deterministic pre-extraction in distillation** — session summaries now include git commits, error patterns, URLs accessed, and packages changed extracted via regex from bash/tool output (no LLM cost)
84
- - **Freshness metadata on every search hit (v1.8.1)** — every knowledge result carries `freshness: { body_age_days, last_accessed, access_count, verified_at, verification_age_days, evergreen }`. Agent reads the trust signal and decides; we impose no policy demotion.
85
- - **Per-category decay windows (v1.8.1)** — the "Unused" filter and bytype chart honor per-category thresholds (projects 180d, people 365d, decisions 90d, workflows 60d, notes 30d) so identity-shaped content doesn't look stale just because it isn't re-read weekly.
84
+ - **Freshness metadata on every search hit** — every knowledge result carries `freshness: { body_age_days, last_accessed, access_count, verified_at, verification_age_days, evergreen }`. Agent reads the trust signal and decides; we impose no policy demotion.
85
+ - **Per-category decay windows** — the "Unused" filter and bytype chart honor per-category thresholds (projects 180d, people 365d, decisions 90d, workflows 60d, notes 30d) so identity-shaped content doesn't look stale just because it isn't re-read weekly.
86
86
  - **Lifecycle hooks** — `SessionStart` auto-wakeup + ingest-freshness check, `UserPromptSubmit` first-prompt targeted injection, `PreCompact` memory-flush nudge + distill, `SessionEnd` distill. Six hook scripts total, all fail-open, each toggleable via an `AGENT_KNOWLEDGE_*` env var. See [`docs/HOOKS.md`](docs/HOOKS.md).
87
87
  - **Replaces host auto-memory** — on hosts with a per-session memory system (Claude Code's `~/.claude/projects/*/memory/`, similar in other IDEs), route durable user facts and feedback to agent-knowledge instead. Auto-memory is machine-local and invisible to other machines; agent-knowledge is git-synced, cross-machine, searchable, and surfaces in wakeup. See the Claude Code integration note in [`docs/USER-MANUAL.md`](docs/USER-MANUAL.md#persistent-memory--agent-knowledge-not-host-auto-memory).
88
88
 
@@ -163,10 +163,10 @@ Response shape: `{mode: "general" | "scoped", sessions, knowledge}`. Scoped mode
163
163
 
164
164
  Scopes: `errors`, `plans`, `configs`, `tools`, `files`, `decisions`, `all`.
165
165
 
166
- v1.8 search knobs:
166
+ Search knobs:
167
167
 
168
168
  - `mmr: true` applies Maximal Marginal Relevance re-ranking (kills near-duplicate clusters in top-K). `mmr_lambda` 0-1, default 0.7.
169
- - `category_mode: "boost"` (default) gives matching-category entries a 1.25× score multiplier instead of dropping non-matches. Pass `"filter"` for legacy hard-filter behavior.
169
+ - `category_mode: "boost"` (default) gives matching-category entries a 1.25× score multiplier instead of dropping non-matches. Pass `"filter"` for hard-filter behavior.
170
170
  - `explain: true` attaches `score_components: {bm25, decay, maturity, confidence, category_boost, mmr_penalty}` to every knowledge hit.
171
171
 
172
172
  ### Sessions
@@ -214,11 +214,11 @@ v1.8 search knobs:
214
214
  | | `rebuild_embeddings` | Re-embed all knowledge entries (useful on provider switch) | -- |
215
215
  | | `prune_orphans` | Delete embeddings for sessions no longer on disk | `vacuum?`, `force_vacuum?` |
216
216
  | | `vacuum` | Reclaim free pages in the vector store | -- |
217
- | | `promote` | Scored + gated promoter (v1.8) | `promote_mode?` (`apply`\|`explain`), `min_score?`, `min_recall_count?`, `min_unique_queries?` |
217
+ | | `promote` | Scored + gated promoter | `promote_mode?` (`apply`\|`explain`), `min_score?`, `min_recall_count?`, `min_unique_queries?` |
218
218
 
219
- ### Scored promoter (v1.8)
219
+ ### Scored promoter
220
220
 
221
- Session insights no longer drop into the knowledge base via regex distillation. Instead, every project-level candidate is scored on six signals (relevance 0.30, frequency 0.24, query-diversity 0.15, recency 0.15, consolidation 0.10, conceptual-richness 0.06) and gated on `minScore ≥ 0.5`, `minRecallCount ≥ 2`, `minUniqueQueries ≥ 2`. All three gates must pass. Background auto-promotion is controlled by the same `auto_distill` config flag; invoke on demand with `knowledge_admin(action: "promote")`.
221
+ Every project-level candidate is scored on six signals (relevance 0.30, frequency 0.24, query-diversity 0.15, recency 0.15, consolidation 0.10, conceptual-richness 0.06) and gated on `minScore ≥ 0.5`, `minRecallCount ≥ 2`, `minUniqueQueries ≥ 2`. All three gates must pass. Background auto-promotion is controlled by the same `auto_distill` config flag; invoke on demand with `knowledge_admin(action: "promote")`.
222
222
 
223
223
  - `promote_mode: "explain"` (default) — score + gate candidates, write diary, DO NOT touch the KB.
224
224
  - `promote_mode: "apply"` — promote candidates that pass, write diary, git-commit.
@@ -383,9 +383,11 @@ This enables HTTP-based writes from other services without an MCP connection.
383
383
  ## Testing
384
384
 
385
385
  ```bash
386
- npm test # 352 tests across 20 files
386
+ npm test # 563 tests across 35 files
387
387
  npm run test:watch # Watch mode
388
- npm run lint # Type-check (tsc --noEmit)
388
+ npm run lint # ESLint on src/ and tests/
389
+ npm run typecheck # tsc --noEmit
390
+ npm run check # typecheck + lint + format + test
389
391
  ```
390
392
 
391
393
  ## Environment Variables
@@ -424,7 +426,7 @@ Project-scoped overrides win over the standard keys. Set either; the scoped form
424
426
  | `AGENT_KNOWLEDGE_ANTHROPIC_API_KEY` | `ANTHROPIC_API_KEY` | Claude / Voyage embeddings |
425
427
  | `AGENT_KNOWLEDGE_GEMINI_API_KEY` | `GEMINI_API_KEY` | Gemini embeddings |
426
428
 
427
- ### Hooks (v1.8 lifecycle integration)
429
+ ### Hooks
428
430
 
429
431
  | Variable | Default | Description |
430
432
  | -------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -2,7 +2,7 @@
2
2
  "id": "agent-knowledge",
3
3
  "name": "Knowledge",
4
4
  "icon": "psychology",
5
- "version": "1.9.2",
5
+ "version": "1.9.4",
6
6
  "description": "Knowledge base — entries, sessions, search, graph relationships",
7
7
  "ui": "./dist/ui/app.js",
8
8
  "css": "./dist/ui/styles.css",
package/docs/HOOKS.md CHANGED
@@ -18,22 +18,61 @@ returns an empty JSON object so the user is never blocked.
18
18
 
19
19
  ## session-start.js
20
20
 
21
- Two jobs:
21
+ Four jobs:
22
22
 
23
23
  1. Prints the dashboard URL (`http://localhost:3423` by default, override via
24
24
  `AGENT_KNOWLEDGE_PORT`) and injects it into SessionStart `additionalContext`.
25
- 2. Auto-loads a token-budgeted **wakeup** payload (L0 identity + L1 top-weighted
26
- entries) into the same `additionalContext`, so the agent starts every session
27
- with a small world-model already in the prompt — no manual
28
- `knowledge(action="wakeup")` call required.
25
+ 2. Auto-loads the **L0 identity** section (who the user is — query-agnostic
26
+ facts from `~/agent-knowledge/identity.md`) into the same
27
+ `additionalContext`, so every session starts with that context without a
28
+ manual `knowledge(action="wakeup")` call.
29
+ 3. Clears the `first-prompt-inject.mjs` marker file for this `session_id` on
30
+ every SessionStart event (startup / resume / clear). Resumed sessions
31
+ reuse the same `session_id`, so without this the inject hook silently
32
+ skips on the next prompt because the prior run's marker is still on disk.
33
+ 4. **Identity onboarding**: if neither `identity.md` nor `IDENTITY.md` exists
34
+ in the memory dir AND there is no `.identity-declined` opt-out marker,
35
+ appends a short instruction to `additionalContext` telling the agent to
36
+ ask the user three questions (name/role, stack, projects) and save the
37
+ answers via the host's `Write` tool. The agent drives the conversation;
38
+ the user never has to manually create the file. If the user says "skip"
39
+ or "not now", the agent creates `~/agent-knowledge/.identity-declined` and
40
+ the onboarding prompt stops firing. Delete that file to re-enable.
41
+
42
+ L1 top-weighted facts are **not** auto-loaded here. The companion
43
+ `first-prompt-inject.mjs` runs a query-targeted KB search on the session's
44
+ first real prompt and injects a better-matched slice than any
45
+ query-agnostic pre-load would. Users who want the full legacy L0+L1 pack can
46
+ still call `knowledge(action="wakeup")` manually, or flip
47
+ `AGENT_KNOWLEDGE_WAKEUP_BUDGET` up to re-enable larger identity sections.
48
+
49
+ Also emits a user-visible `systemMessage` on every session start with a
50
+ status suffix so the user can always tell the hook ran:
51
+
52
+ - `agent-knowledge: http://localhost:3423 | identity: 312 chars` — when a
53
+ user-authored `identity.md` was loaded.
54
+ - `agent-knowledge: http://localhost:3423 | identity: onboarding pending` —
55
+ when no identity file exists and onboarding is queued (agent will ask
56
+ the user on the next prompt).
57
+ - `agent-knowledge: http://localhost:3423 | identity: declined (delete ~/agent-knowledge/.identity-declined to redo)` —
58
+ when the user previously opted out.
59
+ - `agent-knowledge: http://localhost:3423 | identity: placeholder (no identity.md) · inject rearmed` —
60
+ fallback for edge cases (e.g. stat errors), with `· inject rearmed` when
61
+ the first-prompt-inject marker was cleared.
62
+ - `agent-knowledge: http://localhost:3423 | autowake off · resume` — when
63
+ `AGENT_KNOWLEDGE_AUTOWAKE=0` disables auto-injection.
64
+
65
+ The model-facing context and the user-facing line are separate channels —
66
+ the `systemMessage` is purely a UX signal so the user can see what got
67
+ pre-loaded and whether the next prompt will trigger query-targeted injection.
29
68
 
30
69
  ### Environment variables
31
70
 
32
- | Variable | Default | Description |
33
- | ------------------------------- | ------- | --------------------------------------------------- |
34
- | `AGENT_KNOWLEDGE_PORT` | `3423` | Dashboard port announced in the context line |
35
- | `AGENT_KNOWLEDGE_AUTOWAKE` | `1` | Set `0` / `false` to skip the wakeup auto-injection |
36
- | `AGENT_KNOWLEDGE_WAKEUP_BUDGET` | `800` | Max tokens (chars/4 estimate) for the L0+L1 blob |
71
+ | Variable | Default | Description |
72
+ | ------------------------------- | ------- | ------------------------------------------------------- |
73
+ | `AGENT_KNOWLEDGE_PORT` | `3423` | Dashboard port announced in the context line |
74
+ | `AGENT_KNOWLEDGE_AUTOWAKE` | `1` | Set `0` / `false` to skip the identity auto-injection |
75
+ | `AGENT_KNOWLEDGE_WAKEUP_BUDGET` | `200` | Max tokens (chars/4 estimate) for the L0 identity slice |
37
76
 
38
77
  Requires `npm run build` to have succeeded — if `dist/wakeup.js` is missing,
39
78
  only the dashboard-URL line is emitted (fail-open).
@@ -67,6 +106,11 @@ The marker file (`{dataDir}/.first-prompt-seen/<session_id>`) is only written
67
106
  AFTER a real search has run — skip-gates like `/clear` do NOT burn the shot,
68
107
  so the user's next real question still gets injection.
69
108
 
109
+ When injection fires, the hook also emits a user-visible `systemMessage`:
110
+ `knowledge: injected 4 hits (decisions/database-choice.md, sessions/foo.md, +2 more)`.
111
+ This is separate from the model-facing `additionalContext` — the user sees a
112
+ one-line summary in the transcript, the model sees the full rendered hit list.
113
+
70
114
  ### Environment variables
71
115
 
72
116
  | Variable | Default | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-knowledge",
3
- "version": "1.9.2",
3
+ "version": "1.9.4",
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",
@@ -38,7 +38,7 @@ import { homedir } from 'os';
38
38
  const __filename = fileURLToPath(import.meta.url);
39
39
  const __dirname = dirname(__filename);
40
40
 
41
- function emit(additionalContext) {
41
+ function emit(additionalContext, systemMessage) {
42
42
  const payload = additionalContext
43
43
  ? {
44
44
  hookSpecificOutput: {
@@ -47,10 +47,22 @@ function emit(additionalContext) {
47
47
  },
48
48
  }
49
49
  : {};
50
+ if (systemMessage) payload.systemMessage = systemMessage;
50
51
  process.stdout.write(JSON.stringify(payload) + '\n');
51
52
  process.exit(0);
52
53
  }
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
+
54
66
  function warn(msg) {
55
67
  process.stderr.write(`[knowledge firstprompt] ${msg}\n`);
56
68
  }
@@ -221,7 +233,7 @@ async function main() {
221
233
  const budgetChars = tokenBudget() * 4;
222
234
  const rendered = renderHits(hits, budgetChars);
223
235
  if (!rendered) return emit(null);
224
- emit(rendered);
236
+ emit(rendered, summarizeHits(hits));
225
237
  }
226
238
 
227
239
  main().catch((err) => {
@@ -4,21 +4,31 @@
4
4
  // agent-knowledge SessionStart hook
5
5
  //
6
6
  // 1. Announces the knowledge dashboard URL.
7
- // 2. Auto-loads a token-budgeted wakeup payload (L0 identity + L1 top-weighted
8
- // entries) into the host's additionalContext so the agent starts each
9
- // session with a small, well-chosen window into the knowledge base — no
10
- // manual `knowledge action=wakeup` call required.
7
+ // 2. Auto-loads the L0 identity section into the host's additionalContext so
8
+ // the agent starts each session with "who the user is" already in the
9
+ // prompt — query-agnostic facts that apply regardless of the first question.
10
+ // 3. Clears the first-prompt-inject marker for this session_id so a resumed
11
+ // or cleared session gets another shot at query-targeted L1 injection.
12
+ // Without this, /exit + resume re-uses the session_id and the inject hook
13
+ // silently skips because the marker from the prior run is still on disk.
11
14
  //
12
- // Disable auto-wakeup by exporting AGENT_KNOWLEDGE_AUTOWAKE=0. Tune budget
13
- // with AGENT_KNOWLEDGE_WAKEUP_BUDGET (default 800 tokens).
15
+ // L1 top-weighted facts are NOT auto-injected here anymore. The companion
16
+ // `first-prompt-inject.mjs` hook runs query-targeted search against the KB
17
+ // on the session's first real prompt, which produces a better-matched slice
18
+ // than any query-agnostic pre-load.
19
+ //
20
+ // Disable auto-wakeup entirely by exporting AGENT_KNOWLEDGE_AUTOWAKE=0.
21
+ // Tune the identity slice with AGENT_KNOWLEDGE_WAKEUP_BUDGET (default 200
22
+ // tokens — L0 is small, doesn't need the legacy 800-token window).
14
23
  //
15
24
  // Fail-open: every error path still prints a valid JSON hook response so the
16
25
  // session never blocks on this hook.
17
26
  // =============================================================================
18
27
 
19
- import { existsSync } from 'fs';
20
- import { dirname, resolve } from 'path';
28
+ import { existsSync, rmSync } from 'fs';
29
+ import path, { dirname, resolve, join } from 'path';
21
30
  import { fileURLToPath } from 'url';
31
+ import { homedir } from 'os';
22
32
 
23
33
  const __filename = fileURLToPath(import.meta.url);
24
34
  const __dirname = dirname(__filename);
@@ -27,11 +37,13 @@ const knowledgePort = process.env.AGENT_KNOWLEDGE_PORT || '3423';
27
37
  const autoWakeEnabled =
28
38
  (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== '0' &&
29
39
  (process.env.AGENT_KNOWLEDGE_AUTOWAKE ?? '1').trim().toLowerCase() !== 'false';
30
- const wakeupBudget = Number.parseInt(process.env.AGENT_KNOWLEDGE_WAKEUP_BUDGET ?? '800', 10) || 800;
40
+ const wakeupBudget = Number.parseInt(process.env.AGENT_KNOWLEDGE_WAKEUP_BUDGET ?? '200', 10) || 200;
31
41
 
32
- function emit(additionalContext) {
42
+ function emit(additionalContext, statusSuffix) {
43
+ const base = `agent-knowledge: http://localhost:${knowledgePort}`;
44
+ const systemMessage = statusSuffix ? `${base} | ${statusSuffix}` : base;
33
45
  const msg = {
34
- systemMessage: `agent-knowledge: http://localhost:${knowledgePort}`,
46
+ systemMessage,
35
47
  hookSpecificOutput: {
36
48
  hookEventName: 'SessionStart',
37
49
  additionalContext,
@@ -41,43 +53,160 @@ function emit(additionalContext) {
41
53
  process.exit(0);
42
54
  }
43
55
 
44
- async function loadWakeup() {
56
+ async function readStdin() {
57
+ return new Promise((resolveP) => {
58
+ let data = '';
59
+ if (process.stdin.isTTY) return resolveP('');
60
+ process.stdin.setEncoding('utf-8');
61
+ process.stdin.on('data', (chunk) => (data += chunk));
62
+ process.stdin.on('end', () => resolveP(data));
63
+ setTimeout(() => resolveP(data), 1500);
64
+ });
65
+ }
66
+
67
+ // Keep in sync with first-prompt-inject.mjs dataDir().
68
+ function dataDir() {
69
+ if (process.env.AGENT_KNOWLEDGE_DATA_DIR) return process.env.AGENT_KNOWLEDGE_DATA_DIR;
70
+ if (process.platform === 'win32') {
71
+ return path.join(
72
+ process.env.APPDATA || path.join(homedir(), 'AppData', 'Roaming'),
73
+ 'knowledge',
74
+ );
75
+ }
76
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'), 'knowledge');
77
+ }
78
+
79
+ function memoryDir() {
80
+ return process.env.AGENT_KNOWLEDGE_MEMORY_DIR || join(homedir(), 'agent-knowledge');
81
+ }
82
+
83
+ function identityOnboardingState() {
84
+ const dir = memoryDir();
85
+ try {
86
+ if (existsSync(join(dir, 'identity.md')) || existsSync(join(dir, 'IDENTITY.md'))) {
87
+ return 'configured';
88
+ }
89
+ if (existsSync(join(dir, '.identity-declined'))) {
90
+ return 'declined';
91
+ }
92
+ } catch {
93
+ return 'unknown';
94
+ }
95
+ return 'pending';
96
+ }
97
+
98
+ const ONBOARDING_INSTRUCTION = [
99
+ '',
100
+ '--- Identity onboarding (no identity.md yet) ---',
101
+ `The user has no ~/agent-knowledge/identity.md. Before diving into their request, briefly ask:`,
102
+ ' 1. Name + primary role',
103
+ ' 2. Main stack / tech focus',
104
+ ' 3. Projects they maintain',
105
+ `Then use the Write tool to save their answers to \`~/agent-knowledge/identity.md\` as short markdown.`,
106
+ `If the user says "skip" / "not now" / declines, use Write to create an empty file at \`~/agent-knowledge/.identity-declined\` so this prompt stops appearing.`,
107
+ `Do not invent facts — only record what the user actually tells you.`,
108
+ ].join('\n');
109
+
110
+ function clearFirstPromptMarker(sessionId) {
111
+ if (!sessionId || typeof sessionId !== 'string') return false;
112
+ try {
113
+ const marker = path.join(dataDir(), '.first-prompt-seen', sessionId);
114
+ if (existsSync(marker)) {
115
+ rmSync(marker, { force: true });
116
+ return true;
117
+ }
118
+ } catch (err) {
119
+ process.stderr.write(`[knowledge session-start] marker clear failed: ${err?.message || err}\n`);
120
+ }
121
+ return false;
122
+ }
123
+
124
+ async function loadIdentitySection() {
45
125
  const distWakeup = resolve(__dirname, '..', '..', 'dist', 'wakeup.js');
46
- if (!existsSync(distWakeup)) return null;
126
+ if (!existsSync(distWakeup)) return { rendered: null, hasIdentity: false, bodyChars: 0 };
47
127
  try {
48
128
  const mod = await import(`file://${distWakeup.replace(/\\/g, '/')}`);
49
- if (typeof mod.wakeup !== 'function') return null;
50
- const result = mod.wakeup({ tokenBudget: wakeupBudget });
51
- if (result && typeof result.rendered === 'string') return result.rendered;
129
+ if (typeof mod.buildContextBundle !== 'function') {
130
+ return { rendered: null, hasIdentity: false, bodyChars: 0 };
131
+ }
132
+ const result = mod.buildContextBundle({
133
+ tokenBudget: wakeupBudget,
134
+ sections: ['identity'],
135
+ });
136
+ if (!result || typeof result.rendered !== 'string' || result.rendered.length === 0) {
137
+ return { rendered: null, hasIdentity: false, bodyChars: 0 };
138
+ }
139
+ const identitySection = (result.sections ?? []).find((s) => s.name === 'identity');
140
+ const hasIdentity = !!(identitySection && !identitySection.empty);
141
+ const bodyChars = identitySection?.content?.length ?? result.rendered.length;
142
+ return { rendered: result.rendered, hasIdentity, bodyChars };
52
143
  } catch (err) {
53
- process.stderr.write(`[knowledge session-start] wakeup failed: ${err?.message || err}\n`);
144
+ process.stderr.write(
145
+ `[knowledge session-start] identity load failed: ${err?.message || err}\n`,
146
+ );
54
147
  }
55
- return null;
148
+ return { rendered: null, hasIdentity: false, bodyChars: 0 };
56
149
  }
57
150
 
58
151
  async function main() {
152
+ const raw = await readStdin();
153
+ let payload = {};
154
+ if (raw) {
155
+ try {
156
+ payload = JSON.parse(raw);
157
+ } catch {
158
+ /* ignore — host may not pipe JSON */
159
+ }
160
+ }
161
+ const sessionId = payload.session_id || process.env.CLAUDE_SESSION_ID;
162
+ const source = payload.source || 'startup';
163
+
164
+ // Re-arm first-prompt-inject for this session_id. Resumed sessions reuse the
165
+ // session_id, so without this the inject hook's marker from the previous
166
+ // run would skip the very next user prompt.
167
+ const markerCleared = clearFirstPromptMarker(sessionId);
168
+
59
169
  const dashboardLine = `Knowledge: http://localhost:${knowledgePort}`;
60
170
 
171
+ const autowakeOffSuffix = markerCleared ? `${source} · inject rearmed` : source;
61
172
  if (!autoWakeEnabled) {
62
- return emit(dashboardLine);
173
+ return emit(dashboardLine, `autowake off · ${autowakeOffSuffix}`);
174
+ }
175
+
176
+ const { rendered, hasIdentity, bodyChars } = await loadIdentitySection();
177
+ const onboarding = hasIdentity ? 'configured' : identityOnboardingState();
178
+
179
+ let identityStatus;
180
+ if (hasIdentity) {
181
+ identityStatus = `identity: ${bodyChars} chars`;
182
+ } else if (onboarding === 'pending') {
183
+ identityStatus = 'identity: onboarding pending';
184
+ } else if (onboarding === 'declined') {
185
+ identityStatus = 'identity: declined (delete ~/agent-knowledge/.identity-declined to redo)';
186
+ } else {
187
+ identityStatus = 'identity: placeholder (no identity.md)';
63
188
  }
189
+ const rearmStatus = markerCleared ? ' · inject rearmed' : '';
190
+ const suffix = `${identityStatus}${rearmStatus}`;
191
+
192
+ const onboardingBlock = onboarding === 'pending' ? ONBOARDING_INSTRUCTION : '';
64
193
 
65
- const rendered = await loadWakeup();
66
194
  if (!rendered) {
67
- return emit(dashboardLine);
195
+ return emit(`${dashboardLine}${onboardingBlock}`, suffix);
68
196
  }
69
197
 
70
- const combined = [
198
+ const base = [
71
199
  dashboardLine,
72
200
  '',
73
- '--- Knowledge wakeup (auto-loaded; call `knowledge action=wakeup` to refresh) ---',
201
+ '--- Knowledge wakeup (identity only; call `knowledge action=wakeup` for L1 facts) ---',
74
202
  rendered,
75
203
  ].join('\n');
204
+ const combined = onboardingBlock ? `${base}\n${onboardingBlock}` : base;
76
205
 
77
- emit(combined);
206
+ emit(combined, suffix);
78
207
  }
79
208
 
80
209
  main().catch((err) => {
81
210
  process.stderr.write(`[knowledge session-start] ${err?.message || err}\n`);
82
- emit(`Knowledge: http://localhost:${knowledgePort}`);
211
+ emit(`Knowledge: http://localhost:${knowledgePort}`, null);
83
212
  });