agentcache 0.4.0 → 0.4.2

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/README.md CHANGED
@@ -1,313 +1,163 @@
1
1
  # AgentCache
2
2
 
3
- **Knowledge cache for AI coding agents** learns how you work, remembers across sessions, works everywhere.
4
-
5
- AgentCache observes your coding sessions and compiles reusable knowledge (rules, lessons, architectural decisions, context) into a local database. Every future session — regardless of IDE or LLM — gets the benefit of everything you've learned before.
6
-
7
- ## Why
8
-
9
- Every AI coding session starts from zero. The agent doesn't know your team's conventions, past mistakes, or architectural decisions. You repeat yourself. Bugs recur. Context is lost.
10
-
11
- AgentCache fixes this. It's a persistent knowledge layer that:
12
- - **Learns** rules, lessons, and decisions from your sessions
13
- - **Injects** relevant knowledge at the start of every new session
14
- - **Works everywhere** — any IDE, any LLM, simultaneously
15
- - **Stays local** — SQLite database on your machine, nothing leaves your disk
16
-
17
- ## Install
3
+ **Your codebase learns.** AgentCache compiles what your AI agents discover into a `SKILL.md` that every future session — in any IDE, with any LLM — reads automatically.
18
4
 
19
5
  ```bash
20
6
  npm install -g agentcache
21
7
  ```
22
8
 
23
- Done. Start a new session in any IDE. AgentCache is already running.
24
-
25
- No `init`. No `setup`. No config. No second command. The install itself:
26
- 1. Creates `~/.agentcache/agentcache.db` (your knowledge store)
27
- 2. Detects installed IDEs (Claude Code, Cursor, Roo Code, Windsurf, Continue, Codex)
28
- 3. Registers itself as an MCP server in each
29
- 4. Sets up Claude Code hooks for automatic transcript recovery
30
- 5. Spawns `compile-all` in background — compiles your entire transcript history from all IDEs immediately
31
-
32
- ## How It Works
33
-
34
- ```
35
- ┌────────────────────────────────────────────────────────────────────────┐
36
- │ Your Machine │
37
- │ │
38
- │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
39
- │ │ Claude │ │ Cursor │ │ Roo │ │ Codex │ ... │
40
- │ │ Code │ │ │ │ Code │ │ │ │
41
- │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
42
- │ │ │ │ │ │
43
- │ └─────────────┴─────────────┴─────────────┘ │
44
- │ │ │
45
- │ MCP Protocol (stdio) │
46
- │ │ │
47
- │ ┌────────────┴────────────┐ ┌────────────────────┐ │
48
- │ │ AgentCache MCP Server │ │ agentcache │ │
49
- │ │ (agentcache serve) │ │ compile-all │ │
50
- │ │ │ │ (standalone CLI) │ │
51
- │ │ spawns compile-all ────┼────▶│ │ │
52
- │ │ when pending > 20 │ │ Uses: claude, │ │
53
- │ └────────────┬────────────┘ │ codex, gemini, │ │
54
- │ │ │ ollama, API keys │ │
55
- │ │ └─────────┬──────────┘ │
56
- │ │ │ │
57
- │ ┌─────────┴────────────────────────────┘ │
58
- │ │ │
59
- │ ▼ │
60
- │ ┌────────────────────┐ │
61
- │ │ ~/.agentcache/ │ │
62
- │ │ agentcache.db │ │
63
- │ │ compile-all.lock │ │
64
- │ │ (SQLite + WAL) │ │
65
- │ └────────────────────┘ │
66
- └────────────────────────────────────────────────────────────────────────┘
67
- ```
9
+ That's it. No config. No accounts. No sync server.
68
10
 
69
- ### The Cycle
11
+ ---
70
12
 
71
- 1. **Session starts** — agent calls `inject_context` → gets compiled rules, lessons, decisions
72
- 2. **During session** — agent calls `compile_submit` incrementally as it learns things
73
- 3. **Session ends** — knowledge is already saved. If agent didn't submit (abrupt exit), transcript recovery handles it next session.
13
+ ## The Problem
74
14
 
75
- ### Knowledge Types
15
+ You tell Claude "don't mock the database in integration tests." It forgets. You tell Cursor the same thing. You tell Codex. You repeat yourself across every IDE, every session, every project.
76
16
 
77
- | Type | Scope | Example |
78
- |------|-------|---------|
79
- | **Rule** | Global | "Always use snake_case for database columns" |
80
- | **Lesson** | Global | "Don't mock the database in integration tests — we got burned when mocked tests passed but prod migration failed" |
81
- | **Decision** | Project | "Using Drizzle ORM over Prisma because we need raw SQL escape hatches" |
82
- | **Context** | Project | "Currently migrating from REST to GraphQL, both coexist" |
17
+ Your agents are amnesiac. Your knowledge evaporates.
83
18
 
84
- Rules and lessons are **global** — they apply to all your projects. Decisions and context are **project-specific**.
19
+ ## What AgentCache Does
85
20
 
86
- ## MCP Tools
21
+ After a few sessions, AgentCache produces a `SKILL.md` in your repo:
87
22
 
88
- AgentCache exposes 8 tools via the Model Context Protocol (prefixed as `mcp--agentcache--<tool>` in IDEs):
23
+ ```markdown
24
+ # Project Knowledge
89
25
 
90
- | Tool | Purpose |
91
- |------|---------|
92
- | `inject_context` | Load compiled knowledge at session start |
93
- | `compile_submit` | Submit observations incrementally during session |
94
- | `compile_cluster` | Resolve clustering when observations overlap existing knowledge |
95
- | `compile_extract` | Process queued transcripts from previous sessions |
96
- | `enforce` | Check tool calls against enforced policy rules |
97
- | `save_observation` | Save a permanent observation (USER authority, never auto-deprecated) |
98
- | `get_knowledge` | Query the knowledge database |
99
- | `deprecate_knowledge` | Mark knowledge as deprecated when it's no longer valid |
26
+ ## Rules
27
+ - Never mock the database in integration tests — we got burned when mocks passed but prod migration failed
28
+ - Always use snake_case for database columns
29
+ - Run type-check before committing
100
30
 
101
- ## CLI Commands
31
+ ## Decisions
32
+ - Using Drizzle ORM over Prisma for raw SQL escape hatches
33
+ - PostgreSQL for all persistent state, Redis for ephemeral cache only
102
34
 
103
- ```bash
104
- agentcache status # Show knowledge stats for current project
105
- agentcache compile-all # Batch-compile all unprocessed transcripts
106
- agentcache setup # Re-register with IDEs (only if postinstall failed)
35
+ ## Context
36
+ - Migrating from REST to GraphQL, both coexist until Q3
37
+ - Auth service rewrite driven by compliance (not tech debt)
107
38
  ```
108
39
 
109
- ### `compile-all`Standalone Batch Compilation
40
+ This file lives at `<repo>/.agentcache/skills/project-knowledge/SKILL.md`. It's auto-discovered by **38+ tools** that support the Agent Skills spec no MCP connection required. Commit it. Every teammate gets your team's accumulated knowledge on clone.
110
41
 
111
- Processes all pending transcripts across every IDE without depending on MCP pipes or active sessions. Runs independently in a terminal.
42
+ **The database is local. The output is git.**
112
43
 
113
- ```bash
114
- agentcache compile-all
115
- ```
44
+ ## How It Works
116
45
 
117
- **LLM backend detection** (first available wins):
118
- 1. CLI tools with stored auth: `claude`, `codex`, `gemini`, `copilot`, `aider`, `goose`
119
- 2. Ollama running locally (`localhost:11434`)
120
- 3. `ANTHROPIC_API_KEY` environment variable
121
- 4. `OPENAI_API_KEY` environment variable
46
+ ```
47
+ Session 1 (Claude Code) Session 2 (Cursor) Session 3 (Codex)
48
+ │ │ │
49
+ └───────────────────────────┴───────────────────────┘
50
+
51
+ AgentCache (MCP Server)
52
+
53
+ ┌───────────────┴───────────────┐
54
+ │ │
55
+ ~/.agentcache/ <repo>/.agentcache/
56
+ agentcache.db skills/.../SKILL.md
57
+ (local SQLite) (committed to git)
58
+ ```
122
59
 
123
- No API keys needed if you have any coding CLI installed it uses their stored authentication.
60
+ 1. **Session starts** agent calls `inject_context` gets compiled rules, lessons, decisions
61
+ 2. **During session** → agent calls `compile_submit` as it learns things
62
+ 3. **Session ends** → knowledge compiles into the database
63
+ 4. **Periodically** → database projects into `SKILL.md` for git distribution
124
64
 
125
- **Automatic triggers:**
126
- - Runs as a background process after `npm install -g agentcache` (clears initial backlog)
127
- - Spawned by the MCP server when pending transcripts exceed 20 (ongoing janitor)
128
- - Lockfile (`~/.agentcache/compile-all.lock`) prevents concurrent runs
65
+ Knowledge compounds. One lesson stated once propagates to every future session across every IDE.
129
66
 
130
- **Transcript sources:** Claude Code, Continue, Codex, Roo Code, Goose
67
+ ## Install
131
68
 
132
- Internal commands (called by hooks automatically, never by users):
133
69
  ```bash
134
- agentcache serve # MCP server (IDEs spawn this)
135
- agentcache compile-session # Stop hook
136
- agentcache discover # SessionStart hook
137
- agentcache enforce # PreToolUse hook
70
+ npm install -g agentcache
138
71
  ```
139
72
 
140
- ## Design Principles
141
-
142
- ### Zero Config
143
-
144
- `npm install -g agentcache` is the only step. It detects your IDEs, registers itself, and starts working. No dotfiles in your project. No init commands. No config to maintain.
145
-
146
- ### Universal
147
-
148
- AgentCache uses MCP (Model Context Protocol) as its only interface. Any IDE that supports MCP works. Any LLM — Claude, GPT, Gemini, Qwen, Llama — can use the tools. No IDE-specific code paths. No LLM-specific logic.
149
-
150
- ### Developer-Scoped
151
-
152
- One database per developer (`~/.agentcache/agentcache.db`), not per project. Rules and lessons learned in one project benefit all your projects. Project-specific decisions stay scoped to their project.
153
-
154
- ### Resilient to Abrupt Exits
155
-
156
- Sessions can end without warning (crash, ctrl-c, network drop, MCP pipe death). AgentCache handles this through:
157
- - **Incremental submission** — observations are saved as they happen, not batched at the end
158
- - **Transcript recovery** — transcripts persist on disk across 5 IDEs (Claude Code, Continue, Codex, Roo Code, Goose) and are compiled by `compile-all`
159
- - **Pipe-independent compilation** — `compile-all` runs as a standalone process, not through MCP stdio pipes that can break during long operations
160
- - **Pending queue in SQLite** — concurrent access is safe, nothing lost to race conditions
161
-
162
- ### Anti-Bloat
73
+ The install automatically:
74
+ 1. Creates `~/.agentcache/agentcache.db`
75
+ 2. Detects your IDEs (Claude Code, Cursor, Roo Code, Windsurf, Continue, Codex)
76
+ 3. Registers as an MCP server in each — with auto-approve
77
+ 4. Sets up Claude Code hooks for transcript recovery
78
+ 5. Compiles your existing transcript history in the background
163
79
 
164
- AgentCache prevents knowledge from growing unbounded:
165
- - **Confidence promotion** — observations need repeated confirmation before becoming high-confidence
166
- - **Decay** — auto-compiled items not seen in 30 days get archived
167
- - **Budget caps** — max 20 rules, 10 lessons, 10 decisions, 5 context items injected per session
168
- - **Priority ranking** — USER authority first, then by confidence and recency
80
+ **Zero config. Zero setup. Start a session and it's working.**
169
81
 
170
82
  ## Supported IDEs
171
83
 
172
- | IDE | MCP | Auto-Approve | Transcript Recovery | Hooks |
173
- |-----|-----|-------------|--------------------|----|
174
- | Claude Code | Yes | Yes (automatic) | Full (JSONL) | Stop, SessionStart, PreToolUse |
175
- | Cursor | Yes | Yes (automatic) | Incremental only | |
176
- | Roo Code | Yes | Yes (automatic) | Full (JSON via compile-all) | — |
177
- | Windsurf | Yes | Yes (automatic) | Incremental only | |
178
- | Continue | Yes | Yes (automatic) | Full (JSON) | — |
179
- | Codex | Yes | Yes (automatic) | Full (JSONL via compile-all) | — |
180
- | Goose | — | — | Full (SQLite via compile-all) | — |
84
+ | IDE | MCP | Auto-Approve | Transcript Recovery |
85
+ |-----|-----|-------------|-------------------|
86
+ | Claude Code | | | Full (hooks + JSONL) |
87
+ | Cursor | | | Full (agent transcripts) |
88
+ | Roo Code (VS Code) | | | Full (task history) |
89
+ | Codex | | | Full (session JSONL) |
90
+ | Continue | | | Full (session JSON) |
91
+ | Windsurf | | | Incremental only |
92
+ | Goose | — | — | Full (SQLite) |
181
93
 
182
- All IDEs are fully auto-approved at install time no manual steps required.
94
+ All IDEs share the same knowledge database. A rule learned in Claude Code is injected in Cursor the next time you open it.
183
95
 
184
- "Incremental only" means if the agent submits observations during the session, they're saved. If the session terminates before any submission, those observations are lost (no transcript access).
96
+ ## Security Model
185
97
 
186
- "via compile-all" means `agentcache compile-all` discovers and processes these transcripts in batch, independent of any active MCP session.
98
+ AgentCache creates a feedback loop: agents write observations → observations compile knowledge injects into future sessions. This is the product's value **and** its attack surface.
187
99
 
188
- ## Skill Output (Agent Skills Spec)
100
+ **Quarantine gate**: Agent-submitted observations require confirmation across 2+ independent sessions before injection. A single prompt-injected `compile_submit` cannot poison your knowledge.
189
101
 
190
- Compiled knowledge is automatically projected to SKILL.md files the [Agent Skills open standard](https://agentskills.io) supported by 38+ tools (Claude Code, Cursor, Codex, Gemini CLI, Copilot, Roo Code, and more).
102
+ **Human-only enforcement**: Policy rules (that block tool calls) can only be created via CLI. No MCP tool can create policy.
191
103
 
192
- ```
193
- ~/.agentcache/skills/developer-knowledge/SKILL.md # Global: rules + lessons
194
- <repo>/.agentcache/skills/project-knowledge/SKILL.md # Project: decisions + context
195
- ```
196
-
197
- **Global skill** (`~/.agentcache/skills/`) — your developer identity. Rules and lessons learned across all projects. Auto-discovered by any Agent Skills-compatible tool without MCP.
198
-
199
- **Project skill** (`<repo>/.agentcache/skills/`) — project-specific decisions, context, and rules. Git-trackable. Team members get it on clone. **This is team knowledge sharing without a sync server — just git.**
200
-
201
- Skills auto-refresh on every compilation. Each file stays under 5,000 tokens (Agent Skills budget limit). High-confidence items appear first.
202
-
203
- Example output:
204
- ```markdown
205
- ---
206
- name: project-knowledge
207
- description: "Project-specific decisions, rules, context, and lessons — compiled automatically from coding sessions by AgentCache"
208
- ---
104
+ **Scope gate**: Agent-submitted observations are always project-scoped. Global requires explicit human action.
209
105
 
210
- ## Rules
106
+ ### Security Modes
211
107
 
212
- Follow these without exception:
108
+ ```json
109
+ { "security": "auto" }
110
+ ```
213
111
 
214
- - Always use path aliases in imports
215
- - Never commit .env files [ENFORCED]
112
+ | Mode | Behavior |
113
+ |------|----------|
114
+ | `auto` | Quarantine — new items inject after 2+ session confirmations |
115
+ | `review` | Nothing injects until `agentcache review` approves it |
116
+ | `locked` | `compile_submit` disabled. Human-triggered batch only |
216
117
 
217
- ## Decisions
118
+ ## CLI
218
119
 
219
- Architectural choices in effect — do not contradict:
220
-
221
- - Using Drizzle ORM over Prisma for raw SQL escape hatches
222
- - PostgreSQL for all persistent state, Redis for ephemeral cache only
120
+ ```bash
121
+ agentcache doctor # Diagnose installation
122
+ agentcache status # Knowledge stats
123
+ agentcache review # Approve/reject quarantined items
124
+ agentcache promote <id> # Approve a single item
125
+ agentcache add-rule "never force push" --enforce # Create policy (human-only)
126
+ agentcache compile-all # Batch-compile all transcripts
127
+ agentcache setup # Re-register with IDEs
128
+ ```
223
129
 
224
- ## Current Context
130
+ ## compile-all
225
131
 
226
- Active project state (may be temporal):
132
+ Processes all uncompiled transcripts from all IDEs using the first available LLM backend:
227
133
 
228
- - Migrating from REST to GraphQL, both coexist until Q3
229
- ```
134
+ 1. CLI tools: `claude`, `codex`, `gemini`, `copilot`, `aider`, `goose`
135
+ 2. Ollama at `localhost:11434`
136
+ 3. `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`
230
137
 
231
- ## Data Storage
138
+ Runs automatically on install and when pending transcripts exceed 20.
232
139
 
233
- All data lives in `~/.agentcache/` (SQLite with WAL mode for concurrent access).
140
+ ## Data
234
141
 
235
142
  ```
236
143
  ~/.agentcache/
237
- ├── agentcache.db # Knowledge, observations, sessions, pending queue
238
- ├── compile-all.lock # Prevents concurrent compilation
239
- └── skills/developer-knowledge/SKILL.md # Global skill (auto-generated)
240
- ```
241
-
242
- No data leaves your machine. No network calls. No telemetry. No accounts.
144
+ ├── agentcache.db # Knowledge database (SQLite + WAL)
145
+ ├── config.json # Security mode
146
+ └── compile-all.lock # Prevents concurrent compilation
243
147
 
244
- ## How Knowledge Compiles
245
-
246
- ```
247
- Observations (raw)
248
-
249
-
250
- Extract → Normalize → Canonicalize → Cluster → Detect Contradictions → Compile
251
- │ │
252
- │ "Always use ESLint" │
253
- │ "Always use ESLint" ──→ deduplicated, confidence promoted │
254
- │ "Use Prettier not ESLint" ──→ contradiction detected │
255
- │ ▼
256
- Knowledge Items (compiled)
257
- - status: active/deprecated/superseded
258
- - confidence: low/medium/high
259
- - authority: AUTO/USER
148
+ <repo>/.agentcache/
149
+ └── skills/project-knowledge/SKILL.md # Git-committed team knowledge
260
150
  ```
261
151
 
262
- **Two compilation paths:**
263
- - **In-session** — the agent in your IDE processes extraction prompts via MCP tools (no separate LLM calls needed)
264
- - **Batch (`compile-all`)** — runs independently using any available LLM CLI or API, processes the full backlog without depending on active sessions
265
-
266
- **Two output formats:**
267
- - **MCP injection** — structured context served to agents at session start via `inject_context`
268
- - **SKILL.md files** — Agent Skills spec-compliant files auto-discovered by 38+ tools without MCP
269
-
270
- ## Project Identity
271
-
272
- Projects are identified by a hash of their full filesystem path, not just the folder name. This means:
273
- - `/work/api` and `/personal/api` are different projects
274
- - Renaming a folder creates a new project identity
275
- - Knowledge doesn't leak between same-named projects
276
-
277
- ## Roadmap
278
-
279
- ### More IDEs & Coding Agents
280
-
281
- | Platform | Status |
282
- |----------|--------|
283
- | Claude Code | Supported |
284
- | Cursor | Supported |
285
- | Roo Code | Supported |
286
- | Windsurf | Supported |
287
- | Continue | Supported |
288
- | Codex | Supported |
289
- | Goose | Supported (transcript recovery via SQLite) |
290
- | Aider | Coming soon |
291
- | GitHub Copilot | Coming soon |
292
- | Zed AI | Coming soon |
293
-
294
- Any tool that supports MCP can use AgentCache today via `agentcache serve`. Native integrations for the above are planned to ensure zero-config setup.
295
-
296
- ### Native Plugins
297
-
298
- Marketplace listings and deeper UI integrations for all supported IDEs — surfacing knowledge inline, showing compilation status, and providing one-click management of rules and decisions.
299
-
300
- ### Team Knowledge Sharing
301
-
302
- Share compiled knowledge across your team. Rules and lessons that work for one developer benefit everyone.
303
-
304
- ### Cloud Sync
305
-
306
- Sync your knowledge database across machines. Same developer, different computers, same knowledge.
152
+ No network calls. No telemetry. No accounts. Everything stays on your machine (except what you choose to commit).
307
153
 
308
- ### Analytics Dashboard
154
+ ## Principles
309
155
 
310
- Visibility into what AgentCache is learning compilation stats, knowledge growth, most-referenced rules, and session coverage.
156
+ - **Zero config**`npm install -g` is the only step
157
+ - **Universal** — MCP protocol, any IDE, any LLM
158
+ - **Git-native output** — SKILL.md is the distribution mechanism
159
+ - **Secure by default** — quarantine gate, scope restrictions, human-only policy
160
+ - **Anti-bloat** — 30-day decay, budget caps, confidence promotion
311
161
 
312
162
  ## Contributing
313
163
 
@@ -316,7 +166,7 @@ git clone https://github.com/raghav-a21ai/agentcache
316
166
  cd agentcache
317
167
  npm install
318
168
  npm run build
319
- npm test
169
+ npm test # 205 tests
320
170
  ```
321
171
 
322
172
  ## License
@@ -0,0 +1,71 @@
1
+ // src/utils/ide-detector.ts
2
+ import { existsSync } from "fs";
3
+ import { join } from "path";
4
+ import { homedir } from "os";
5
+ function getRooConfigPath() {
6
+ const home = homedir();
7
+ if (process.platform === "darwin") {
8
+ return join(home, "Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json");
9
+ }
10
+ if (process.platform === "win32") {
11
+ return join(process.env.APPDATA || join(home, "AppData/Roaming"), "Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json");
12
+ }
13
+ return join(home, ".config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json");
14
+ }
15
+ function getWindsurfConfigPath() {
16
+ const home = homedir();
17
+ return join(home, ".codeium", "windsurf", "mcp_config.json");
18
+ }
19
+ function getContinueConfigPath() {
20
+ const home = homedir();
21
+ return join(home, ".continue", "mcpServers", "agentcache.json");
22
+ }
23
+ function getCodexConfigPath() {
24
+ const home = homedir();
25
+ return join(home, ".codex", "config.toml");
26
+ }
27
+ function detectInstalledIdes() {
28
+ const home = homedir();
29
+ return [
30
+ {
31
+ name: "Claude Code",
32
+ detected: existsSync(join(home, ".claude")),
33
+ mcpConfigPath: join(home, ".claude.json"),
34
+ mcpConfigFormat: "claude-settings"
35
+ },
36
+ {
37
+ name: "Cursor",
38
+ detected: existsSync(join(home, ".cursor")),
39
+ mcpConfigPath: join(home, ".cursor", "mcp.json"),
40
+ mcpConfigFormat: "mcp-json"
41
+ },
42
+ {
43
+ name: "Roo Code",
44
+ detected: existsSync(getRooConfigPath()),
45
+ mcpConfigPath: getRooConfigPath(),
46
+ mcpConfigFormat: "mcp-json"
47
+ },
48
+ {
49
+ name: "Windsurf",
50
+ detected: existsSync(join(home, ".codeium", "windsurf")) || existsSync(join(home, ".windsurf")),
51
+ mcpConfigPath: getWindsurfConfigPath(),
52
+ mcpConfigFormat: "mcp-json"
53
+ },
54
+ {
55
+ name: "Continue",
56
+ detected: existsSync(join(home, ".continue")),
57
+ mcpConfigPath: getContinueConfigPath(),
58
+ mcpConfigFormat: "continue-dir"
59
+ },
60
+ {
61
+ name: "Codex",
62
+ detected: existsSync(join(home, ".codex")),
63
+ mcpConfigPath: getCodexConfigPath(),
64
+ mcpConfigFormat: "codex-toml"
65
+ }
66
+ ];
67
+ }
68
+
69
+ export {
70
+ detectInstalledIdes
71
+ };
@@ -277,16 +277,17 @@ var SqliteKnowledgeRepository = class {
277
277
  if (!row) return null;
278
278
  return this.mapKnowledgeItem(row);
279
279
  }
280
- getKnowledgeForContext(project) {
280
+ getKnowledgeForContext(project, opts) {
281
281
  const decayThreshold = Date.now() - 30 * 24 * 60 * 60 * 1e3;
282
282
  this.db.prepare(
283
283
  `UPDATE knowledge_items SET status = 'archived', updated_at = ?
284
284
  WHERE status = 'active' AND authority = 'AUTO' AND last_seen_at < ?`
285
285
  ).run(Date.now(), decayThreshold);
286
+ const authorityFilter = opts?.userOnly ? `AND authority = 'USER'` : `AND (authority = 'USER' OR observation_count >= 2)`;
286
287
  const rows = this.db.prepare(
287
288
  `SELECT * FROM knowledge_items WHERE status = 'active'
288
289
  AND (scope = 'global' OR project = ?)
289
- AND (authority = 'USER' OR observation_count >= 2)
290
+ ${authorityFilter}
290
291
  ORDER BY
291
292
  CASE authority WHEN 'USER' THEN 0 ELSE 1 END,
292
293
  CASE confidence WHEN 'high' THEN 3 WHEN 'medium' THEN 2 ELSE 1 END DESC,
@@ -382,6 +383,11 @@ var SqliteKnowledgeRepository = class {
382
383
  const row = this.db.prepare("SELECT COUNT(*) as count FROM pending_transcripts").get();
383
384
  return row.count;
384
385
  }
386
+ grandfatherExistingItems() {
387
+ this.db.prepare(
388
+ `UPDATE knowledge_items SET observation_count = 2 WHERE authority = 'AUTO' AND observation_count < 2 AND status = 'active'`
389
+ ).run();
390
+ }
385
391
  getQuarantinedItems(project) {
386
392
  const sql = project ? `SELECT * FROM knowledge_items WHERE status = 'active' AND authority = 'AUTO' AND observation_count < 2 AND (scope = 'global' OR project = ?) ORDER BY created_at DESC` : `SELECT * FROM knowledge_items WHERE status = 'active' AND authority = 'AUTO' AND observation_count < 2 ORDER BY created_at DESC`;
387
393
  const rows = project ? this.db.prepare(sql).all(project) : this.db.prepare(sql).all();