@lotargo/memory_plugin 1.6.3 → 1.6.5

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.
@@ -2,7 +2,8 @@ import * as z from "zod/v4";
2
2
  import { optStr, defBool, defNum, optNum } from "./helpers.js";
3
3
  import { MEMORY_DIR } from "../memory.js";
4
4
  import { registerSnapshotDir } from "../admin/snapshot.js";
5
- import { ensureExportsDir } from "../ingest/exporter.js";
5
+ import { ensureExportsDir } from "../ingest/exporter.js";
6
+ import { resolveRagScopeKey, resolveRagScopeKeys, resolveManageRagScopeKeys, removeDocumentScopes } from "../rag_scope.js";
6
7
 
7
8
  export function registerRagTools(server) {
8
9
  // Restrict snapshot export/import paths to the plugin's own data directories.
@@ -12,245 +13,282 @@ export function registerRagTools(server) {
12
13
  server.registerTool(
13
14
  "ingest_document",
14
15
  {
15
- description:
16
- "Ingest a document into the RAG knowledge base. " +
17
- "Accepts local file paths, web URLs, or raw Markdown/text content. " +
18
- "For type='file' the file is read from disk and indexed with a code-block wrapper. " +
19
- "For type='url' the page is fetched and its content is indexed (not just the URL). " +
20
- "Processes document through 3-tier hierarchy chunking (Big/Medium/Small), " +
21
- "computes dense vectors, and extracts GraphRAG code symbols.",
22
- inputSchema: z.object({
23
- content: z
24
- .string()
25
- .describe(
26
- "Raw text content, file path, or web URL. For type='file' this can be the file path (reads from disk) or the file content directly"
27
- ),
28
- type: z
29
- .enum(["text", "file", "url"])
30
- .nullish()
31
- .transform((v) => v || "text")
32
- .describe("Input content type: 'text' (raw content), 'file' (reads from disk, wraps in code block), or 'url' (fetches page content)"),
33
- title: optStr().describe("Document title"),
34
- path: optStr().describe("Original document file path"),
35
- generateEmbeddings: defBool(true).describe("Compute dense vector embeddings"),
36
- }),
37
- },
38
- async ({ content, type, title, path, generateEmbeddings }) => {
39
- const { ingestDocument } = await import("../ingest/pipeline.js");
40
- const result = await ingestDocument({
41
- content,
42
- type,
43
- title: title || null,
44
- path: path || null,
45
- generateEmbeddings,
46
- });
47
- return {
48
- content: [
49
- {
50
- type: "text",
51
- text: JSON.stringify(
52
- {
53
- status: "success",
54
- docId: result.docId,
55
- title: result.title,
56
- sectionsCount: result.sectionsCount,
57
- microChunksCount: result.microChunksCount,
58
- deduplicated: result.deduplicated,
59
- },
60
- null,
61
- 2
62
- ),
63
- },
64
- ],
65
- };
66
- }
67
- );
68
-
69
- server.registerTool(
70
- "query_knowledge_base",
71
- {
72
- description:
73
- "Perform hybrid search (RSF/RRF BM25 full-text + dense vector similarity) across the RAG knowledge base. " +
74
- "Returns top-ranked candidate document sections with breadcrumbs, GraphRAG defined code symbols, and relevance scores.",
75
- inputSchema: z.object({
76
- query: z.string().describe("Search query in natural language or symbol name"),
77
- limit: defNum(5).describe("Maximum number of sections to return"),
78
- instruction: optStr().describe(
79
- "Optional task-specific retrieval instruction shaping embedding focus (e.g. 'Retrieve code snippets', 'Find user preferences'). " +
80
- "Recommended when using E5/BGE models for domain-specific queries."
81
- ),
82
- generateEmbeddings: defBool(true).describe("Use vector search alongside BM25"),
83
- }),
84
- },
85
- async ({ query, limit, instruction, generateEmbeddings }) => {
86
- const { hybridQuery } = await import("../retrieval/retriever.js");
87
- const { getConfig } = await import("../config/config_manager.js");
88
- const activeConfig = getConfig();
89
-
90
- const results = await hybridQuery({
91
- query,
92
- limit,
93
- generateEmbeddings,
94
- instruction: instruction || null,
95
- });
96
-
97
- if (!results || results.length === 0) {
98
- return {
99
- content: [
100
- {
101
- type: "text",
102
- text: `[Active Model: ${activeConfig.embeddingModel}]\nNo matching knowledge found for query.`,
103
- },
104
- ],
105
- };
106
- }
107
-
108
- const headerNote = `[Active Model: ${activeConfig.embeddingModel} | Fusion: ${activeConfig.fusionAlgorithm.toUpperCase()}]\n\n`;
109
-
110
- const formatted = results
111
- .map((r, i) => {
112
- let header = `### [${i + 1}] ${r.doc_title || "Untitled"}`;
113
- if (r.heading) header += ` > ${r.heading}`;
114
- if (r.breadcrumbs) header += ` (${r.breadcrumbs})`;
115
- let body = `Score: ${(r.score || 0).toFixed(4)}\n`;
116
- if (r.defined_symbols && r.defined_symbols.length > 0) {
117
- body += `Defined Symbols: ${r.defined_symbols.join(", ")}\n`;
118
- }
119
- body += `\n${r.snippet || r.full_section_content || ""}`;
120
- return `${header}\n${body}`;
121
- })
122
- .join("\n\n---\n\n");
123
-
124
- return { content: [{ type: "text", text: headerNote + formatted }] };
125
- }
126
- );
127
-
128
- server.registerTool(
129
- "batch_query_knowledge_base",
130
- {
131
- description:
132
- "Execute multiple hybrid search queries in a single batch call. " +
133
- "More efficient than separate query_knowledge_base calls: all query embeddings computed in one ONNX pass. " +
134
- "Returns one result set per query, in the same order as input.",
135
- inputSchema: z.object({
136
- queries: z
137
- .array(z.string())
138
- .describe("Array of search queries to execute in batch"),
139
- limit: defNum(5).describe("Maximum number of sections to return per query"),
140
- instruction: optStr().describe(
141
- "Optional task-specific retrieval instruction shaping embedding focus. Applied to all queries."
142
- ),
143
- generateEmbeddings: defBool(true).describe("Use vector search alongside BM25"),
144
- }),
145
- },
146
- async ({ queries, limit, instruction, generateEmbeddings }) => {
147
- const { batchHybridQuery } = await import("../retrieval/retriever.js");
148
- const { getConfig } = await import("../config/config_manager.js");
149
- const activeConfig = getConfig();
150
-
151
- const allResults = await batchHybridQuery(queries, {
152
- limit,
153
- generateEmbeddings,
154
- instruction: instruction || null,
155
- });
156
-
157
- const formatted = allResults
158
- .map((results, qi) => {
159
- const header = `## Query ${qi + 1}: "${queries[qi]}"\n`;
160
- if (!results || results.length === 0) {
161
- return header + "_No results found._";
162
- }
163
- const items = results
164
- .map((r, i) => {
165
- let h = `### [${i + 1}] ${r.doc_title || "Untitled"}`;
166
- if (r.heading) h += ` > ${r.heading}`;
167
- if (r.breadcrumbs) h += ` (${r.breadcrumbs})`;
168
- let body = `Score: ${(r.score || 0).toFixed(4)}`;
169
- if (r.retrieval_policy && r.retrieval_policy !== "micro_chunk") {
170
- body += ` [${r.retrieval_policy}]`;
171
- }
172
- if (r.defined_symbols && r.defined_symbols.length > 0) {
173
- body += `\nDefined Symbols: ${r.defined_symbols.join(", ")}`;
174
- }
175
- body += `\n\n${r.snippet || r.full_section_content || ""}`;
176
- return `${h}\n${body}`;
177
- })
178
- .join("\n\n---\n\n");
179
- return header + items;
180
- })
181
- .join("\n\n===\n\n");
182
-
183
- const headerNote = `[Active Model: ${activeConfig.embeddingModel} | Fusion: ${activeConfig.fusionAlgorithm.toUpperCase()} | ${queries.length} queries]\n\n`;
184
-
185
- return { content: [{ type: "text", text: headerNote + formatted }] };
186
- }
187
- );
188
-
189
- server.registerTool(
190
- "reindex_knowledge_base",
191
- {
192
- description:
193
- "Re-embed all existing documents in the RAG knowledge base with the active (or specified) embedding model and vector dimension. " +
194
- "Use after switching the embedding model or vector dimension so previously stored vectors match the new configuration. " +
195
- "Preserves documents, sections, FTS index, graph edges, and fact links.",
196
- inputSchema: z.object({
197
- model: optStr().describe("Embedding model to use (defaults to active config.embeddingModel)"),
198
- dimension: optNum().describe(
199
- "Fixed vector dimension (defaults to active config.vectorDimension; auto-detect if unset)"
200
- ),
201
- }),
202
- },
203
- async ({ model, dimension }) => {
204
- const { reindexEmbeddings } = await import("../ingest/pipeline.js");
205
- const result = await reindexEmbeddings({
206
- model: model || null,
207
- dimension: dimension !== undefined && dimension !== null ? dimension : null,
208
- });
209
- return {
210
- content: [
211
- {
212
- type: "text",
213
- text: JSON.stringify(
214
- {
215
- status: "success",
216
- reindexed: result.reindexed,
217
- documentsAffected: result.documentsAffected,
218
- model: result.model,
219
- dimension: result.dimension || "auto",
220
- },
221
- null,
222
- 2
223
- ),
224
- },
225
- ],
226
- };
227
- }
228
- );
229
-
230
- server.registerTool(
231
- "manage_knowledge_base",
232
- {
233
- description:
234
- "Manage the RAG knowledge base: inspect stats, list documents, read full raw document, delete documents, or export/import snapshots.",
235
- inputSchema: z.object({
236
- action: z.enum(["stats", "list", "read_document", "delete", "export_snapshot", "import_snapshot"]).describe("Management action"),
237
- docId: optStr().describe("Document ID, title, or path (required for read_document and delete)"),
238
- snapshotPath: optStr().describe("File path for snapshot export/import"),
239
- }),
240
- },
241
- async ({ action, docId, snapshotPath }) => {
242
- const { getDatabase } = await import("../db/database.js");
243
- const db = await getDatabase();
244
-
245
- if (action === "stats") {
246
- const docCountRow = await db.prepare("SELECT COUNT(*) as cnt FROM documents").get();
247
- const docCount = docCountRow ? docCountRow.cnt : 0;
248
- const secCountRow = await db.prepare("SELECT COUNT(*) as cnt FROM sections").get();
249
- const secCount = secCountRow ? secCountRow.cnt : 0;
250
- const chunkCountRow = await db.prepare("SELECT COUNT(*) as cnt FROM micro_chunks").get();
251
- const chunkCount = chunkCountRow ? chunkCountRow.cnt : 0;
252
- const edgeCountRow = await db.prepare("SELECT COUNT(*) as cnt FROM graph_edges").get();
253
- const edgeCount = edgeCountRow ? edgeCountRow.cnt : 0;
16
+ description:
17
+ "Selectively preserve a reliable, reusable source in the RAG knowledge base; do not ingest everything encountered. " +
18
+ "Accepts local file paths, web URLs, or raw Markdown/text content. " +
19
+ "For type='file' the file is read from disk and indexed with a code-block wrapper. " +
20
+ "For type='url' the page is fetched and its content is indexed (not just the URL). " +
21
+ "Processes document through 3-tier hierarchy chunking (Big/Medium/Small), " +
22
+ "computes dense vectors, and extracts GraphRAG code symbols.",
23
+ inputSchema: z.object({
24
+ content: z
25
+ .string()
26
+ .describe(
27
+ "Raw text content, file path, or web URL. For type='file' this can be the file path (reads from disk) or the file content directly"
28
+ ),
29
+ type: z
30
+ .enum(["text", "file", "url"])
31
+ .nullish()
32
+ .transform((v) => v || "text")
33
+ .describe("Input content type: 'text' (raw content), 'file' (reads from disk, wraps in code block), or 'url' (fetches page content)"),
34
+ title: optStr().describe("Document title"),
35
+ path: optStr().describe("Original document file path"),
36
+ scope: z.enum(["project", "global"]).nullish().transform((v) => v || "project").describe("RAG visibility: current Git project (default) or global"),
37
+ directory: optStr().describe("Optional workspace/project directory path to target"),
38
+ project: optStr().describe("Alias for directory"),
39
+ generateEmbeddings: defBool(true).describe("Compute dense vector embeddings"),
40
+ }),
41
+ },
42
+ async ({ content, type, title, path, scope, directory, project, generateEmbeddings }) => {
43
+ const { ingestDocument } = await import("../ingest/pipeline.js");
44
+ const projectScope = await resolveRagScopeKey(scope, { directory, project });
45
+ const result = await ingestDocument({
46
+ content,
47
+ type,
48
+ title: title || null,
49
+ path: path || null,
50
+ generateEmbeddings,
51
+ projectScope,
52
+ });
53
+ return {
54
+ content: [
55
+ {
56
+ type: "text",
57
+ text: JSON.stringify(
58
+ {
59
+ status: "success",
60
+ docId: result.docId,
61
+ title: result.title,
62
+ sectionsCount: result.sectionsCount,
63
+ microChunksCount: result.microChunksCount,
64
+ deduplicated: result.deduplicated,
65
+ scope: result.projectScope,
66
+ },
67
+ null,
68
+ 2
69
+ ),
70
+ },
71
+ ],
72
+ };
73
+ }
74
+ );
75
+
76
+ server.registerTool(
77
+ "query_knowledge_base",
78
+ {
79
+ description:
80
+ "Perform project-isolated hybrid search (RSF/RRF BM25 full-text + dense vector similarity) across the RAG knowledge base. " +
81
+ "Returns top-ranked candidate document sections with breadcrumbs, GraphRAG defined code symbols, and relevance scores.",
82
+ inputSchema: z.object({
83
+ query: z.string().describe("Search query in natural language or symbol name"),
84
+ limit: defNum(5).describe("Maximum number of sections to return"),
85
+ instruction: optStr().describe(
86
+ "Optional task-specific retrieval instruction shaping embedding focus (e.g. 'Retrieve code snippets', 'Find user preferences'). " +
87
+ "Recommended when using E5/BGE models for domain-specific queries."
88
+ ),
89
+ generateEmbeddings: defBool(true).describe("Use vector search alongside BM25"),
90
+ scope: z.enum(["all", "project", "global"]).nullish().transform((v) => v || "all").describe("Search global + current project (default), project only, or global only"),
91
+ directory: optStr().describe("Optional workspace/project directory path to target"),
92
+ project: optStr().describe("Alias for directory"),
93
+ }),
94
+ },
95
+ async ({ query, limit, instruction, generateEmbeddings, scope, directory, project }) => {
96
+ const { hybridQuery } = await import("../retrieval/retriever.js");
97
+ const { getConfig } = await import("../config/config_manager.js");
98
+ const activeConfig = getConfig();
99
+ const scopeKeys = await resolveRagScopeKeys(scope, { directory, project });
100
+
101
+ const results = await hybridQuery({
102
+ query,
103
+ limit,
104
+ generateEmbeddings,
105
+ instruction: instruction || null,
106
+ scopeKeys,
107
+ });
108
+
109
+ if (!results || results.length === 0) {
110
+ return {
111
+ content: [
112
+ {
113
+ type: "text",
114
+ text: `[Active Model: ${activeConfig.embeddingModel}]\nNo matching knowledge found for query.`,
115
+ },
116
+ ],
117
+ };
118
+ }
119
+
120
+ const headerNote = `[Active Model: ${activeConfig.embeddingModel} | Fusion: ${activeConfig.fusionAlgorithm.toUpperCase()}]\n\n`;
121
+
122
+ const formatted = results
123
+ .map((r, i) => {
124
+ let header = `### [${i + 1}] ${r.doc_title || "Untitled"}`;
125
+ if (r.heading) header += ` > ${r.heading}`;
126
+ if (r.breadcrumbs) header += ` (${r.breadcrumbs})`;
127
+ let body = `Score: ${(r.score || 0).toFixed(4)}\n`;
128
+ if (r.defined_symbols && r.defined_symbols.length > 0) {
129
+ body += `Defined Symbols: ${r.defined_symbols.join(", ")}\n`;
130
+ }
131
+ body += `\n${r.snippet || r.full_section_content || ""}`;
132
+ return `${header}\n${body}`;
133
+ })
134
+ .join("\n\n---\n\n");
135
+
136
+ return { content: [{ type: "text", text: headerNote + formatted }] };
137
+ }
138
+ );
139
+
140
+ server.registerTool(
141
+ "batch_query_knowledge_base",
142
+ {
143
+ description:
144
+ "Execute multiple hybrid search queries in a single batch call. " +
145
+ "Search is isolated to global plus the current project unless another scope is requested. " +
146
+ "More efficient than separate query_knowledge_base calls: all query embeddings computed in one ONNX pass. " +
147
+ "Returns one result set per query, in the same order as input.",
148
+ inputSchema: z.object({
149
+ queries: z
150
+ .array(z.string())
151
+ .describe("Array of search queries to execute in batch"),
152
+ limit: defNum(5).describe("Maximum number of sections to return per query"),
153
+ instruction: optStr().describe(
154
+ "Optional task-specific retrieval instruction shaping embedding focus. Applied to all queries."
155
+ ),
156
+ generateEmbeddings: defBool(true).describe("Use vector search alongside BM25"),
157
+ scope: z.enum(["all", "project", "global"]).nullish().transform((v) => v || "all").describe("Search global + current project (default), project only, or global only"),
158
+ directory: optStr().describe("Optional workspace/project directory path to target"),
159
+ project: optStr().describe("Alias for directory"),
160
+ }),
161
+ },
162
+ async ({ queries, limit, instruction, generateEmbeddings, scope, directory, project }) => {
163
+ const { batchHybridQuery } = await import("../retrieval/retriever.js");
164
+ const { getConfig } = await import("../config/config_manager.js");
165
+ const activeConfig = getConfig();
166
+ const scopeKeys = await resolveRagScopeKeys(scope, { directory, project });
167
+
168
+ const allResults = await batchHybridQuery(queries, {
169
+ limit,
170
+ generateEmbeddings,
171
+ instruction: instruction || null,
172
+ scopeKeys,
173
+ });
174
+
175
+ const formatted = allResults
176
+ .map((results, qi) => {
177
+ const header = `### Query [${qi + 1}]: "${queries[qi]}"\n\n`;
178
+ if (!results || results.length === 0) {
179
+ return header + "No matching knowledge found for this query.";
180
+ }
181
+ const items = results
182
+ .map((item, j) => {
183
+ let title = `#### [${j + 1}] ${item.doc_title || "Untitled"}`;
184
+ if (item.heading) title += ` > ${item.heading}`;
185
+ if (item.breadcrumbs) title += ` (${item.breadcrumbs})`;
186
+ let body = `Score: ${(item.score || 0).toFixed(4)}\n`;
187
+ if (item.defined_symbols && item.defined_symbols.length > 0) {
188
+ body += `Defined Symbols: ${item.defined_symbols.join(", ")}\n`;
189
+ }
190
+ body += `\n${item.snippet || item.full_section_content || ""}`;
191
+ return `${title}\n${body}`;
192
+ })
193
+ .join("\n\n---\n\n");
194
+ return header + items;
195
+ })
196
+ .join("\n\n===\n\n");
197
+
198
+ const headerNote = `[Active Model: ${activeConfig.embeddingModel} | Fusion: ${activeConfig.fusionAlgorithm.toUpperCase()} | ${queries.length} queries]\n\n`;
199
+
200
+ return { content: [{ type: "text", text: headerNote + formatted }] };
201
+ }
202
+ );
203
+
204
+ server.registerTool(
205
+ "reindex_knowledge_base",
206
+ {
207
+ description:
208
+ "Re-embed all existing documents in the RAG knowledge base with the active (or specified) embedding model and vector dimension. " +
209
+ "Use after switching the embedding model or vector dimension so previously stored vectors match the new configuration. " +
210
+ "Preserves documents, sections, FTS index, graph edges, and fact links.",
211
+ inputSchema: z.object({
212
+ model: optStr().describe("Embedding model to use (defaults to active config.embeddingModel)"),
213
+ dimension: optNum().describe(
214
+ "Fixed vector dimension (defaults to active config.vectorDimension; auto-detect if unset)"
215
+ ),
216
+ }),
217
+ },
218
+ async ({ model, dimension }) => {
219
+ const { reindexEmbeddings } = await import("../ingest/pipeline.js");
220
+ const result = await reindexEmbeddings({
221
+ model: model || null,
222
+ dimension: dimension !== undefined && dimension !== null ? dimension : null,
223
+ });
224
+ return {
225
+ content: [
226
+ {
227
+ type: "text",
228
+ text: JSON.stringify(
229
+ {
230
+ status: "success",
231
+ reindexed: result.reindexed,
232
+ documentsAffected: result.documentsAffected,
233
+ model: result.model,
234
+ dimension: result.dimension || "auto",
235
+ },
236
+ null,
237
+ 2
238
+ ),
239
+ },
240
+ ],
241
+ };
242
+ }
243
+ );
244
+
245
+ server.registerTool(
246
+ "manage_knowledge_base",
247
+ {
248
+ description:
249
+ "Manage the project-isolated RAG knowledge base: inspect stats, list documents, read full raw document, unlink/delete documents, or export/import complete snapshots.",
250
+ inputSchema: z.object({
251
+ action: z.enum(["stats", "list", "read_document", "delete", "export_snapshot", "import_snapshot"]).describe("Management action"),
252
+ docId: optStr().describe("Document ID, title, or path (required for read_document and delete)"),
253
+ snapshotPath: optStr().describe("File path for snapshot export/import"),
254
+ scope: z.enum(["all", "project", "global"]).nullish().describe("For stats/list/read: global + current project by default. Delete defaults to the current project (or global outside Git); pass all/global explicitly for broader removal"),
255
+ directory: optStr().describe("Optional workspace/project directory path to target"),
256
+ project: optStr().describe("Alias for directory"),
257
+ }),
258
+ },
259
+ async ({ action, docId, snapshotPath, scope, directory, project }) => {
260
+ const { getDatabase } = await import("../db/database.js");
261
+ const db = await getDatabase();
262
+ const scopeKeys = ["stats", "list", "read_document", "delete"].includes(action)
263
+ ? await resolveManageRagScopeKeys(action, scope, { directory, project })
264
+ : null;
265
+ const placeholders = scopeKeys ? scopeKeys.map(() => "?").join(",") : "";
266
+ const visibleDocWhere = scopeKeys
267
+ ? `EXISTS (SELECT 1 FROM document_scopes ds WHERE ds.doc_id = d.id AND ds.scope_key IN (${placeholders}))`
268
+ : "1=1";
269
+
270
+ if (action === "stats") {
271
+ const docCountRow = await db.prepare(`SELECT COUNT(*) as cnt FROM documents d WHERE ${visibleDocWhere}`).get(...scopeKeys);
272
+ const docCount = docCountRow ? docCountRow.cnt : 0;
273
+ const secCountRow = await db.prepare(`SELECT COUNT(*) as cnt FROM sections s JOIN documents d ON d.id = s.doc_id WHERE ${visibleDocWhere}`).get(...scopeKeys);
274
+ const secCount = secCountRow ? secCountRow.cnt : 0;
275
+ const chunkCountRow = await db.prepare(`SELECT COUNT(*) as cnt FROM micro_chunks m JOIN documents d ON d.id = m.doc_id WHERE ${visibleDocWhere}`).get(...scopeKeys);
276
+ const chunkCount = chunkCountRow ? chunkCountRow.cnt : 0;
277
+ const visibleDocIds = await db.prepare(`SELECT d.id FROM documents d WHERE ${visibleDocWhere}`).all(...scopeKeys);
278
+ let edgeCount = 0;
279
+ if (visibleDocIds.length > 0) {
280
+ const docIds = visibleDocIds.map((row) => row.id);
281
+ const docPlaceholders = docIds.map(() => "?").join(",");
282
+ const ownedRows = await db.prepare(`
283
+ SELECT id FROM sections WHERE doc_id IN (${docPlaceholders})
284
+ UNION SELECT id FROM medium_chunks WHERE doc_id IN (${docPlaceholders})
285
+ UNION SELECT id FROM micro_chunks WHERE doc_id IN (${docPlaceholders})
286
+ `).all(...docIds, ...docIds, ...docIds);
287
+ const ownedIds = [...docIds, ...ownedRows.map((row) => row.id)];
288
+ const edgePlaceholders = ownedIds.map(() => "?").join(",");
289
+ const edgeCountRow = await db.prepare(`SELECT COUNT(*) as cnt FROM graph_edges WHERE source_id IN (${edgePlaceholders}) OR target_id IN (${edgePlaceholders})`).get(...ownedIds, ...ownedIds);
290
+ edgeCount = edgeCountRow ? edgeCountRow.cnt : 0;
291
+ }
254
292
  return {
255
293
  content: [
256
294
  {
@@ -270,8 +308,15 @@ export function registerRagTools(server) {
270
308
  };
271
309
  }
272
310
 
273
- if (action === "list") {
274
- const docs = await db.prepare("SELECT id, title, path, blob_hash, created_at FROM documents ORDER BY created_at DESC").all();
311
+ if (action === "list") {
312
+ const docs = await db.prepare(`
313
+ SELECT d.id, d.title, d.path, d.blob_hash, d.created_at,
314
+ GROUP_CONCAT(ds.scope_key) AS scopes
315
+ FROM documents d
316
+ JOIN document_scopes ds ON ds.doc_id = d.id AND ds.scope_key IN (${placeholders})
317
+ GROUP BY d.id, d.title, d.path, d.blob_hash, d.created_at
318
+ ORDER BY d.created_at DESC
319
+ `).all(...scopeKeys);
275
320
  return {
276
321
  content: [{ type: "text", text: JSON.stringify(docs, null, 2) }],
277
322
  };
@@ -279,9 +324,9 @@ export function registerRagTools(server) {
279
324
 
280
325
  if (action === "read_document") {
281
326
  if (!docId) throw new Error("docId parameter is required for read_document action");
282
- const doc = await db
283
- .prepare("SELECT id, title, path, blob_hash, created_at FROM documents WHERE id = ? OR path = ? OR title = ?")
284
- .get(docId, docId, docId);
327
+ const doc = await db
328
+ .prepare(`SELECT d.id, d.title, d.path, d.blob_hash, d.created_at FROM documents d WHERE (d.id = ? OR d.path = ? OR d.title = ?) AND ${visibleDocWhere}`)
329
+ .get(docId, docId, docId, ...scopeKeys);
285
330
  if (!doc) {
286
331
  throw new Error(`Document not found in knowledge base for docId: ${docId}`);
287
332
  }
@@ -307,10 +352,29 @@ export function registerRagTools(server) {
307
352
  };
308
353
  }
309
354
 
310
- if (action === "delete") {
311
- if (!docId) throw new Error("docId parameter is required for delete action");
312
- const { deleteDocument } = await import("../ingest/pipeline.js");
313
- const result = await deleteDocument(docId, db);
355
+ if (action === "delete") {
356
+ if (!docId) throw new Error("docId parameter is required for delete action");
357
+ const visible = await db
358
+ .prepare(`SELECT d.id FROM documents d WHERE (d.id = ? OR d.path = ? OR d.title = ?) AND ${visibleDocWhere}`)
359
+ .get(docId, docId, docId, ...scopeKeys);
360
+ if (!visible) throw new Error(`Document not found in the selected RAG scope for docId: ${docId}`);
361
+ const scopeRemoval = await removeDocumentScopes(db, visible.id, scopeKeys);
362
+ if (scopeRemoval.remainingScopes > 0) {
363
+ return {
364
+ content: [{
365
+ type: "text",
366
+ text: JSON.stringify({
367
+ deleted: false,
368
+ unlinked: true,
369
+ docId: visible.id,
370
+ removedScopes: scopeRemoval.removedScopes,
371
+ remainingScopes: scopeRemoval.remainingScopes,
372
+ }, null, 2),
373
+ }],
374
+ };
375
+ }
376
+ const { deleteDocument } = await import("../ingest/pipeline.js");
377
+ const result = await deleteDocument(visible.id, db);
314
378
  return {
315
379
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
316
380
  };