@codemem/mcp 0.46.2 → 0.47.0-beta.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/dist/http.js +1 -1
- package/dist/index.js +1 -1
- package/dist/memory-access.d.ts.map +1 -1
- package/dist/{server-DmdZAo6k.js → server-C-Z_tmAr.js} +103 -102
- package/dist/server-C-Z_tmAr.js.map +1 -0
- package/dist/stdio.js +1 -1
- package/dist/tools/items.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/server-DmdZAo6k.js.map +0 -1
package/dist/http.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { n as e, t } from "./server-
|
|
2
|
+
import { n as e, t } from "./server-C-Z_tmAr.js";
|
|
3
3
|
import { createHash as n, createHmac as r, createPublicKey as i, randomBytes as a, randomUUID as o, timingSafeEqual as s, verify as c } from "node:crypto";
|
|
4
4
|
import { createServer as l } from "node:http";
|
|
5
5
|
import { isIP as u, isIPv6 as d } from "node:net";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as e } from "./server-
|
|
1
|
+
import { t as e } from "./server-C-Z_tmAr.js";
|
|
2
2
|
export { e as createCodememMcpServer };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory-access.d.ts","sourceRoot":"","sources":["../src/memory-access.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"memory-access.d.ts","sourceRoot":"","sources":["../src/memory-access.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,KAAK,WAAW,EAEhB,MAAM,eAAe,CAAC;AAGvB,wBAAgB,eAAe,CAC9B,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,aAAa,GACrB,kBAAkB,GAAG,IAAI,CAG3B;AAED,wBAAgB,aAAa,CAC5B,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,MAAM,EAAE,EACb,OAAO,CAAC,EAAE,aAAa,GACrB,kBAAkB,EAAE,CAQtB;AAED,wBAAgB,kBAAkB,CACjC,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,aAAa,GACrB,OAAO,CAIT;AAED,MAAM,WAAW,yBAAyB;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,2BAA2B;IAC3C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACnB;AAED,wBAAgB,oBAAoB,CACnC,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,yBAAyB,EAChC,OAAO,GAAE,2BAAgC,GACvC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAyChD"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createHash as e, randomUUID as t } from "node:crypto";
|
|
2
|
-
import { MEMORY_KIND_DESCRIPTIONS as n, ObserverClient as r, REMEMBER_MEMORY_KINDS as i, VERSION as a, buildDistillReport as o, dedupeOrderedIds as s, judgeDistillReport as c, projectMatchesFilter as l, reconcileFailedRetrievalSurface as u, recordRetrievalSurface as d, resolveProject as f, resolveProjectRoot as p,
|
|
3
|
-
import { existsSync as
|
|
4
|
-
import { homedir as
|
|
2
|
+
import { MEMORY_KIND_DESCRIPTIONS as n, ObserverClient as r, REMEMBER_MEMORY_KINDS as i, VERSION as a, buildDistillReport as o, dedupeOrderedIds as s, judgeDistillReport as c, projectMatchesFilter as l, reconcileFailedRetrievalSurface as u, recordRetrievalSurface as d, resolveProject as f, resolveProjectRoot as p, toJson as m } from "@codemem/core";
|
|
3
|
+
import { existsSync as h, readFileSync as g } from "node:fs";
|
|
4
|
+
import { homedir as ee } from "node:os";
|
|
5
5
|
import { join as _ } from "node:path";
|
|
6
|
-
import { McpServer as
|
|
6
|
+
import { McpServer as te } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
7
7
|
import { z as v } from "zod";
|
|
8
8
|
//#region src/canonical-json.ts
|
|
9
9
|
function y(e) {
|
|
@@ -17,7 +17,7 @@ function b(e) {
|
|
|
17
17
|
function x() {
|
|
18
18
|
return b(process.env.CODEMEM_PROJECT) ?? f(process.cwd());
|
|
19
19
|
}
|
|
20
|
-
function
|
|
20
|
+
function ne(e) {
|
|
21
21
|
return b(e.project) ?? b(e.envProject) ?? null;
|
|
22
22
|
}
|
|
23
23
|
function S(e, t = x()) {
|
|
@@ -53,7 +53,7 @@ function S(e, t = x()) {
|
|
|
53
53
|
}
|
|
54
54
|
//#endregion
|
|
55
55
|
//#region src/content.ts
|
|
56
|
-
function
|
|
56
|
+
function re(e) {
|
|
57
57
|
let t = JSON.parse(e);
|
|
58
58
|
if (!t || typeof t != "object" || Array.isArray(t)) throw TypeError("MCP structured content must be a JSON object");
|
|
59
59
|
return t;
|
|
@@ -66,7 +66,7 @@ function C(e) {
|
|
|
66
66
|
type: "text",
|
|
67
67
|
text: t
|
|
68
68
|
}],
|
|
69
|
-
structuredContent:
|
|
69
|
+
structuredContent: re(t)
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
72
|
function w(e) {
|
|
@@ -80,14 +80,14 @@ function w(e) {
|
|
|
80
80
|
}
|
|
81
81
|
//#endregion
|
|
82
82
|
//#region src/schemas.ts
|
|
83
|
-
var
|
|
83
|
+
var ie = {
|
|
84
84
|
scope_id: v.string().optional().describe("Filter by a single sharing domain scope_id"),
|
|
85
85
|
include_scope_ids: v.array(v.string()).optional().describe("Sharing domain scope_ids to include"),
|
|
86
86
|
exclude_scope_ids: v.array(v.string()).optional().describe("Sharing domain scope_ids to exclude")
|
|
87
|
-
},
|
|
87
|
+
}, T = {
|
|
88
88
|
kind: v.string().optional().describe("Filter by memory kind"),
|
|
89
89
|
project: v.string().optional().describe("Filter by project scope (matches sessions.project)"),
|
|
90
|
-
...
|
|
90
|
+
...ie,
|
|
91
91
|
visibility: v.array(v.string()).optional(),
|
|
92
92
|
include_visibility: v.array(v.string()).optional(),
|
|
93
93
|
exclude_visibility: v.array(v.string()).optional(),
|
|
@@ -105,39 +105,39 @@ var T = {
|
|
|
105
105
|
widen_shared_when_weak: v.union([v.boolean(), v.string()]).optional(),
|
|
106
106
|
widen_shared_min_personal_results: v.number().int().optional(),
|
|
107
107
|
widen_shared_min_personal_score: v.number().optional()
|
|
108
|
-
}, ae = v.enum(i), oe = Object.keys(
|
|
108
|
+
}, ae = v.enum(i), oe = Object.keys(T).toSorted(), E = v.record(v.string(), v.unknown()), D = v.number().nullable(), O = v.object({
|
|
109
109
|
id: v.number().int(),
|
|
110
110
|
kind: v.string(),
|
|
111
111
|
title: v.string(),
|
|
112
112
|
body_text: v.string(),
|
|
113
113
|
session_id: v.number().int().optional(),
|
|
114
|
-
confidence:
|
|
114
|
+
confidence: D.optional(),
|
|
115
115
|
created_at: v.string().optional(),
|
|
116
116
|
updated_at: v.string().optional(),
|
|
117
|
-
metadata_json:
|
|
118
|
-
}).passthrough(),
|
|
117
|
+
metadata_json: E.optional()
|
|
118
|
+
}).passthrough(), k = v.object({
|
|
119
119
|
id: v.number().int(),
|
|
120
120
|
kind: v.string(),
|
|
121
121
|
title: v.string(),
|
|
122
122
|
body: v.string(),
|
|
123
|
-
confidence:
|
|
123
|
+
confidence: D.optional(),
|
|
124
124
|
score: v.number().optional(),
|
|
125
125
|
session_id: v.number().int().optional(),
|
|
126
|
-
metadata:
|
|
127
|
-
}).passthrough(),
|
|
126
|
+
metadata: E.optional()
|
|
127
|
+
}).passthrough(), se = v.object({
|
|
128
128
|
id: v.number().int(),
|
|
129
129
|
kind: v.string(),
|
|
130
130
|
title: v.string(),
|
|
131
131
|
score: v.number(),
|
|
132
132
|
created_at: v.string(),
|
|
133
133
|
session_id: v.number().int(),
|
|
134
|
-
metadata:
|
|
134
|
+
metadata: E
|
|
135
135
|
}).passthrough(), A = v.object({
|
|
136
136
|
code: v.string(),
|
|
137
137
|
field: v.string(),
|
|
138
138
|
message: v.string(),
|
|
139
139
|
ids: v.array(v.union([v.string(), v.number()])).optional()
|
|
140
|
-
}).passthrough(),
|
|
140
|
+
}).passthrough(), ce = v.object({
|
|
141
141
|
id: v.number().int(),
|
|
142
142
|
kind: v.string(),
|
|
143
143
|
title: v.string(),
|
|
@@ -169,22 +169,22 @@ var T = {
|
|
|
169
169
|
included: v.boolean().nullable(),
|
|
170
170
|
section: v.string().nullable()
|
|
171
171
|
}).passthrough().nullable()
|
|
172
|
-
}).passthrough(),
|
|
172
|
+
}).passthrough(), le = v.object({
|
|
173
173
|
id: v.number().int(),
|
|
174
174
|
kind: v.string(),
|
|
175
175
|
title: v.string(),
|
|
176
176
|
body: v.string(),
|
|
177
|
-
confidence:
|
|
178
|
-
metadata:
|
|
177
|
+
confidence: D,
|
|
178
|
+
metadata: E
|
|
179
179
|
}).passthrough(), j = v.object({
|
|
180
180
|
when: v.array(v.string()),
|
|
181
181
|
how: v.array(v.string()),
|
|
182
182
|
examples: v.array(v.string())
|
|
183
183
|
}).passthrough(), M = {
|
|
184
|
-
memory_search: v.object({ items: v.array(
|
|
185
|
-
memory_search_index: v.object({ items: v.array(
|
|
184
|
+
memory_search: v.object({ items: v.array(k) }),
|
|
185
|
+
memory_search_index: v.object({ items: v.array(se) }),
|
|
186
186
|
memory_explain: v.object({
|
|
187
|
-
items: v.array(
|
|
187
|
+
items: v.array(ce),
|
|
188
188
|
missing_ids: v.array(v.number().int()),
|
|
189
189
|
errors: v.array(A),
|
|
190
190
|
metadata: v.object({
|
|
@@ -196,10 +196,10 @@ var T = {
|
|
|
196
196
|
sanitized_query: v.string().optional()
|
|
197
197
|
}).passthrough()
|
|
198
198
|
}),
|
|
199
|
-
memory_recent: v.object({ items: v.array(
|
|
199
|
+
memory_recent: v.object({ items: v.array(O) }),
|
|
200
200
|
memory_pack: v.object({
|
|
201
201
|
context: v.string(),
|
|
202
|
-
items: v.array(
|
|
202
|
+
items: v.array(le),
|
|
203
203
|
item_ids: v.array(v.number().int()),
|
|
204
204
|
pack_text: v.string(),
|
|
205
205
|
metrics: v.object({
|
|
@@ -211,11 +211,11 @@ var T = {
|
|
|
211
211
|
pack_item_ids: v.array(v.number().int())
|
|
212
212
|
}).passthrough()
|
|
213
213
|
}),
|
|
214
|
-
memory_timeline: v.object({ items: v.array(
|
|
214
|
+
memory_timeline: v.object({ items: v.array(O) }),
|
|
215
215
|
memory_expand: v.object({
|
|
216
|
-
anchors: v.array(
|
|
217
|
-
timeline: v.array(
|
|
218
|
-
observations: v.array(
|
|
216
|
+
anchors: v.array(O),
|
|
217
|
+
timeline: v.array(O),
|
|
218
|
+
observations: v.array(O),
|
|
219
219
|
missing_ids: v.array(v.number().int()),
|
|
220
220
|
errors: v.array(A),
|
|
221
221
|
metadata: v.object({
|
|
@@ -226,8 +226,8 @@ var T = {
|
|
|
226
226
|
include_observations: v.boolean()
|
|
227
227
|
}).passthrough()
|
|
228
228
|
}),
|
|
229
|
-
memory_get:
|
|
230
|
-
memory_get_observations: v.object({ items: v.array(
|
|
229
|
+
memory_get: O,
|
|
230
|
+
memory_get_observations: v.object({ items: v.array(O) }),
|
|
231
231
|
memory_remember: v.object({ id: v.number().int() }),
|
|
232
232
|
memory_forget: v.object({ status: v.literal("ok") }),
|
|
233
233
|
memory_distill_candidates: v.object({
|
|
@@ -302,18 +302,18 @@ var T = {
|
|
|
302
302
|
memory_distill_candidates: P,
|
|
303
303
|
memory_schema: N,
|
|
304
304
|
memory_learn: N
|
|
305
|
-
},
|
|
305
|
+
}, ue = {
|
|
306
306
|
limit: v.number().int().min(1).max(50).default(10).describe("Max candidates"),
|
|
307
307
|
min_recurrence: v.number().int().min(1).max(50).default(2).describe("Minimum member count per candidate"),
|
|
308
308
|
all_projects: v.boolean().default(!1).describe("Mine memories across all projects"),
|
|
309
309
|
include_documented: v.boolean().default(!1).describe("Include candidates already represented in context files"),
|
|
310
310
|
max_evidence_items: v.number().int().min(1).max(20).default(5).describe("Evidence snippets per candidate"),
|
|
311
311
|
judge: v.boolean().default(!0).describe("Judge candidates with the observer model and drop routine-activity clusters (on by default; falls back to unjudged output when no observer model is configured)"),
|
|
312
|
-
...
|
|
312
|
+
...T
|
|
313
313
|
};
|
|
314
314
|
function I(e, t, n) {
|
|
315
|
-
if (!
|
|
316
|
-
let r =
|
|
315
|
+
if (!h(e)) return null;
|
|
316
|
+
let r = g(e, "utf8");
|
|
317
317
|
return r.trim() ? {
|
|
318
318
|
path: t,
|
|
319
319
|
text: r,
|
|
@@ -322,7 +322,7 @@ function I(e, t, n) {
|
|
|
322
322
|
}
|
|
323
323
|
function L(e, t = process.cwd()) {
|
|
324
324
|
let n = p(t) ?? t;
|
|
325
|
-
return [e ? I(_(n, "AGENTS.md"), "AGENTS.md", "project") : null, I(_(
|
|
325
|
+
return [e ? I(_(n, "AGENTS.md"), "AGENTS.md", "project") : null, I(_(ee(), ".config", "opencode", "AGENTS.md"), "~/.config/opencode/AGENTS.md", "user")].filter((e) => e != null);
|
|
326
326
|
}
|
|
327
327
|
function R(e, t) {
|
|
328
328
|
if (e.all_projects) return !1;
|
|
@@ -339,7 +339,7 @@ function B(e, t) {
|
|
|
339
339
|
let { defaultProject: n, store: i } = t;
|
|
340
340
|
e.registerTool("memory_distill_candidates", {
|
|
341
341
|
description: "Mine recurring memories into reviewable context candidates. Reads project/user context files without modifying them and can call the optional observer when judge=true.",
|
|
342
|
-
inputSchema:
|
|
342
|
+
inputSchema: ue,
|
|
343
343
|
outputSchema: M.memory_distill_candidates,
|
|
344
344
|
annotations: F.memory_distill_candidates
|
|
345
345
|
}, async (e) => {
|
|
@@ -403,7 +403,7 @@ function K(e) {
|
|
|
403
403
|
let r = n.join("");
|
|
404
404
|
return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
|
|
405
405
|
}
|
|
406
|
-
function
|
|
406
|
+
function de(t, n) {
|
|
407
407
|
if (n.requestId == null) return null;
|
|
408
408
|
let r = e("sha256").update(y({
|
|
409
409
|
method: "tools/call",
|
|
@@ -449,7 +449,7 @@ function J(e, t) {
|
|
|
449
449
|
--e.pendingFailureCount, r.length === 0 && e.pendingFailures.delete(t);
|
|
450
450
|
}
|
|
451
451
|
}
|
|
452
|
-
function
|
|
452
|
+
function fe(e, t) {
|
|
453
453
|
let n = e.pendingFailures.get(t);
|
|
454
454
|
if (!n) return;
|
|
455
455
|
let r = n.shift();
|
|
@@ -484,7 +484,7 @@ function he() {
|
|
|
484
484
|
}
|
|
485
485
|
}
|
|
486
486
|
function ge(t, n) {
|
|
487
|
-
let r =
|
|
487
|
+
let r = de(t, n);
|
|
488
488
|
if (t.retrievalLedgerIdentityMode === "stateless" || r == null) return {
|
|
489
489
|
baseRequestId: r,
|
|
490
490
|
requestId: r,
|
|
@@ -494,7 +494,7 @@ function ge(t, n) {
|
|
|
494
494
|
J(i, Date.now());
|
|
495
495
|
let a = n.invocationIdentity ? i.byInvocation.get(n.invocationIdentity) : void 0, o = a?.baseRequestId === r ? a : void 0;
|
|
496
496
|
if (!o) {
|
|
497
|
-
let a = (i.activeByRequest.get(r) ?? 0) === 0 ?
|
|
497
|
+
let a = (i.activeByRequest.get(r) ?? 0) === 0 ? fe(i, r) : void 0;
|
|
498
498
|
if (a) o = a;
|
|
499
499
|
else {
|
|
500
500
|
let n = i.nextInvocationSequence;
|
|
@@ -526,12 +526,12 @@ function ve(e, t, n) {
|
|
|
526
526
|
let r = q(e), i = r.activeByRequest.get(t.baseRequestId) ?? 0;
|
|
527
527
|
i <= 1 ? r.activeByRequest.delete(t.baseRequestId) : r.activeByRequest.set(t.baseRequestId, i - 1), n === "failed" ? me(r, t.baseRequestId, t, Date.now()) : pe(r, t.baseRequestId, t.attemptId);
|
|
528
528
|
}
|
|
529
|
-
function
|
|
529
|
+
function Y(e, t, n) {
|
|
530
530
|
try {
|
|
531
531
|
ve(e, t, n);
|
|
532
532
|
} catch {}
|
|
533
533
|
}
|
|
534
|
-
async function
|
|
534
|
+
async function X(e, t, n) {
|
|
535
535
|
let r = _e(e, t), i = r.requestId, a = r.attemptId, o = /* @__PURE__ */ new Date(), s;
|
|
536
536
|
try {
|
|
537
537
|
s = t.resolveFilters?.();
|
|
@@ -558,7 +558,7 @@ async function Z(e, t, n) {
|
|
|
558
558
|
limitRequested: t.limit,
|
|
559
559
|
failureCode: m ? "tool_failed" : void 0,
|
|
560
560
|
failureStage: m ? "retrieval" : void 0
|
|
561
|
-
}, !m),
|
|
561
|
+
}, !m), Y(e, r, m ? "failed" : "completed"), u;
|
|
562
562
|
} catch (n) {
|
|
563
563
|
let c = /* @__PURE__ */ new Date(), l = t.sourceSessionId ?? e.retrievalLedgerScopeId;
|
|
564
564
|
return G(e, {
|
|
@@ -582,48 +582,49 @@ async function Z(e, t, n) {
|
|
|
582
582
|
filters: s,
|
|
583
583
|
failureCode: "tool_failed",
|
|
584
584
|
failureStage: "retrieval"
|
|
585
|
-
}, !1),
|
|
585
|
+
}, !1), Y(e, r, "failed"), w(n instanceof Error ? n.message : String(n));
|
|
586
586
|
}
|
|
587
587
|
}
|
|
588
588
|
//#endregion
|
|
589
589
|
//#region src/memory-access.ts
|
|
590
|
-
function
|
|
590
|
+
function Z(e, t, n) {
|
|
591
591
|
return e.timeline(null, t, 0, 0, n ?? null).find((e) => e.id === t) ?? null;
|
|
592
592
|
}
|
|
593
|
-
function
|
|
593
|
+
function Q(e, t, n) {
|
|
594
594
|
if (t.length === 0) return [];
|
|
595
595
|
let r = [];
|
|
596
596
|
for (let i of t) {
|
|
597
|
-
let t =
|
|
597
|
+
let t = Z(e, i, n);
|
|
598
598
|
t && r.push(t);
|
|
599
599
|
}
|
|
600
600
|
return r;
|
|
601
601
|
}
|
|
602
602
|
function ye(e, t, n) {
|
|
603
|
-
return
|
|
603
|
+
return Z(e, t, n) ? e.forgetForUser(t) : !1;
|
|
604
604
|
}
|
|
605
|
-
function be(e,
|
|
606
|
-
|
|
607
|
-
let
|
|
608
|
-
project:
|
|
609
|
-
envProject:
|
|
610
|
-
}),
|
|
611
|
-
if (!
|
|
612
|
-
return e.db.prepare("UPDATE sessions SET ended_at = ?, metadata_json = ? WHERE id = ?").run(
|
|
613
|
-
memId:
|
|
614
|
-
title:
|
|
615
|
-
body:
|
|
605
|
+
function be(e, n, r = {}) {
|
|
606
|
+
let i = [], a = e.db.transaction(() => {
|
|
607
|
+
let a = r.now?.() ?? (/* @__PURE__ */ new Date()).toISOString(), o = r.user ?? process.env.USER ?? "unknown", s = r.cwd ?? process.cwd(), c = ne({
|
|
608
|
+
project: n.project,
|
|
609
|
+
envProject: r.envProject
|
|
610
|
+
}), l = e.db.prepare("INSERT INTO sessions(started_at, ended_at, cwd, project, user, tool_version, metadata_json, import_key)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(a, a, s, c, o, "mcp-ts", m({ mcp: !0 }), t()), u = Number(l.lastInsertRowid), d = e.rememberForUser(u, n.kind, n.title, n.body, n.confidence, void 0, void 0, { createdMemories: i });
|
|
611
|
+
if (!Z(e, d)) throw Error("unauthorized_scope");
|
|
612
|
+
return e.db.prepare("UPDATE sessions SET ended_at = ?, metadata_json = ? WHERE id = ?").run(r.now?.() ?? (/* @__PURE__ */ new Date()).toISOString(), m({ mcp: !0 }), u), {
|
|
613
|
+
memId: d,
|
|
614
|
+
title: n.title,
|
|
615
|
+
body: n.body
|
|
616
616
|
};
|
|
617
617
|
})();
|
|
618
|
+
return e.enqueueCommittedVectorWrites(i), a;
|
|
618
619
|
}
|
|
619
620
|
//#endregion
|
|
620
621
|
//#region src/tools/items.ts
|
|
621
622
|
var xe = {
|
|
622
623
|
memory_id: v.number().int().describe("Memory ID"),
|
|
623
|
-
...
|
|
624
|
+
...T
|
|
624
625
|
}, Se = {
|
|
625
626
|
ids: v.array(v.number().int()).max(200).describe("Memory IDs to fetch"),
|
|
626
|
-
...
|
|
627
|
+
...T
|
|
627
628
|
}, Ce = {
|
|
628
629
|
kind: ae.describe("Memory kind"),
|
|
629
630
|
title: v.string().describe("Short title"),
|
|
@@ -632,7 +633,7 @@ var xe = {
|
|
|
632
633
|
project: v.string().optional().describe("Project identifier")
|
|
633
634
|
}, we = {
|
|
634
635
|
memory_id: v.number().int().describe("Memory ID to forget"),
|
|
635
|
-
...
|
|
636
|
+
...T
|
|
636
637
|
};
|
|
637
638
|
function Te(e, t) {
|
|
638
639
|
e.registerTool("memory_get", {
|
|
@@ -640,7 +641,7 @@ function Te(e, t) {
|
|
|
640
641
|
inputSchema: xe,
|
|
641
642
|
outputSchema: M.memory_get,
|
|
642
643
|
annotations: F.memory_get
|
|
643
|
-
}, async (e, n) =>
|
|
644
|
+
}, async (e, n) => X(t, {
|
|
644
645
|
surface: "mcp_get",
|
|
645
646
|
toolName: "memory_get",
|
|
646
647
|
toolArguments: e,
|
|
@@ -650,7 +651,7 @@ function Te(e, t) {
|
|
|
650
651
|
sourceSessionId: n?.sessionId,
|
|
651
652
|
invocationIdentity: n?.signal
|
|
652
653
|
}, (n) => {
|
|
653
|
-
let r =
|
|
654
|
+
let r = Z(t.store, e.memory_id, n);
|
|
654
655
|
return r ? {
|
|
655
656
|
value: r,
|
|
656
657
|
memoryIds: [r.id],
|
|
@@ -669,7 +670,7 @@ function Ee(e, t) {
|
|
|
669
670
|
inputSchema: Se,
|
|
670
671
|
outputSchema: M.memory_get_observations,
|
|
671
672
|
annotations: F.memory_get_observations
|
|
672
|
-
}, async (e, n) =>
|
|
673
|
+
}, async (e, n) => X(t, {
|
|
673
674
|
surface: "mcp_get_observations",
|
|
674
675
|
toolName: "memory_get_observations",
|
|
675
676
|
toolArguments: e,
|
|
@@ -679,7 +680,7 @@ function Ee(e, t) {
|
|
|
679
680
|
sourceSessionId: n?.sessionId,
|
|
680
681
|
invocationIdentity: n?.signal
|
|
681
682
|
}, (n) => {
|
|
682
|
-
let r =
|
|
683
|
+
let r = Q(t.store, e.ids, n);
|
|
683
684
|
return {
|
|
684
685
|
value: { items: r },
|
|
685
686
|
memoryIds: r.map((e) => e.id),
|
|
@@ -697,7 +698,7 @@ function De(e, t) {
|
|
|
697
698
|
try {
|
|
698
699
|
let n = be(t.store, e, { envProject: t.envProject() });
|
|
699
700
|
try {
|
|
700
|
-
await
|
|
701
|
+
await t.store.flushPendingVectorWrites();
|
|
701
702
|
} catch {}
|
|
702
703
|
return C({ id: n.memId });
|
|
703
704
|
} catch (e) {
|
|
@@ -835,21 +836,21 @@ function Me(e) {
|
|
|
835
836
|
var Ne = {
|
|
836
837
|
query: v.string().describe("Search query"),
|
|
837
838
|
limit: v.number().int().min(1).max(50).default(5).describe("Max results"),
|
|
838
|
-
...
|
|
839
|
+
...T
|
|
839
840
|
}, Pe = {
|
|
840
841
|
query: v.string().describe("Search query"),
|
|
841
842
|
limit: v.number().int().min(1).max(50).default(8).describe("Max results"),
|
|
842
|
-
...
|
|
843
|
-
},
|
|
843
|
+
...T
|
|
844
|
+
}, $ = {
|
|
844
845
|
query: v.string().optional().describe("Search query"),
|
|
845
846
|
ids: v.array(v.number().int()).max(200).optional().describe("Specific memory IDs to explain"),
|
|
846
847
|
limit: v.number().int().min(1).max(50).default(10).describe("Max results"),
|
|
847
848
|
include_pack_context: v.boolean().default(!1).describe("Include formatted pack context"),
|
|
848
|
-
...
|
|
849
|
-
},
|
|
849
|
+
...T
|
|
850
|
+
}, Fe = {
|
|
850
851
|
limit: v.number().int().min(1).max(100).default(8).describe("Max results"),
|
|
851
|
-
...
|
|
852
|
-
},
|
|
852
|
+
...T
|
|
853
|
+
}, Ie = {
|
|
853
854
|
context: v.string().describe("Context description to search for"),
|
|
854
855
|
limit: v.number().int().min(1).max(50).optional().describe("Max items to include"),
|
|
855
856
|
compact: v.boolean().optional().describe("When true, render a scannable index of all items with full detail only for the top N (default 3). Saves tokens when broad overview matters more than per-item detail."),
|
|
@@ -859,16 +860,16 @@ var Ne = {
|
|
|
859
860
|
"compact",
|
|
860
861
|
"ids"
|
|
861
862
|
]).optional().describe("Near-related compression mode: off disables it, compact applies only to compact rendering, ids applies in all modes. Defaults to CODEMEM_PACK_COMPRESSION or compact."),
|
|
862
|
-
...
|
|
863
|
+
...T
|
|
863
864
|
};
|
|
864
|
-
function
|
|
865
|
+
function Le(e, t) {
|
|
865
866
|
let { defaultProject: n, store: r } = t;
|
|
866
867
|
e.registerTool("memory_search", {
|
|
867
868
|
description: "Keyword-search memories when you know exact terms or identifiers. Returns full body text for each match; use memory_search_index when you only need compact candidates.",
|
|
868
869
|
inputSchema: Ne,
|
|
869
870
|
outputSchema: M.memory_search,
|
|
870
871
|
annotations: F.memory_search
|
|
871
|
-
}, async (e, i) =>
|
|
872
|
+
}, async (e, i) => X(t, {
|
|
872
873
|
surface: "mcp_search",
|
|
873
874
|
toolName: "memory_search",
|
|
874
875
|
toolArguments: e,
|
|
@@ -899,7 +900,7 @@ function Re(e, t) {
|
|
|
899
900
|
inputSchema: Pe,
|
|
900
901
|
outputSchema: M.memory_search_index,
|
|
901
902
|
annotations: F.memory_search_index
|
|
902
|
-
}, async (e, i) =>
|
|
903
|
+
}, async (e, i) => X(t, {
|
|
903
904
|
surface: "mcp_search_index",
|
|
904
905
|
toolName: "memory_search_index",
|
|
905
906
|
toolArguments: e,
|
|
@@ -926,10 +927,10 @@ function Re(e, t) {
|
|
|
926
927
|
};
|
|
927
928
|
})), e.registerTool("memory_explain", {
|
|
928
929
|
description: "Explain search results with detailed scoring breakdown.",
|
|
929
|
-
inputSchema:
|
|
930
|
+
inputSchema: $,
|
|
930
931
|
outputSchema: M.memory_explain,
|
|
931
932
|
annotations: F.memory_explain
|
|
932
|
-
}, async (e, i) =>
|
|
933
|
+
}, async (e, i) => X(t, {
|
|
933
934
|
surface: "mcp_explain",
|
|
934
935
|
toolName: "memory_explain",
|
|
935
936
|
toolArguments: e,
|
|
@@ -949,10 +950,10 @@ function Re(e, t) {
|
|
|
949
950
|
};
|
|
950
951
|
})), e.registerTool("memory_recent", {
|
|
951
952
|
description: "Return recent memories, newest first.",
|
|
952
|
-
inputSchema:
|
|
953
|
+
inputSchema: Fe,
|
|
953
954
|
outputSchema: M.memory_recent,
|
|
954
955
|
annotations: F.memory_recent
|
|
955
|
-
}, async (e, i) =>
|
|
956
|
+
}, async (e, i) => X(t, {
|
|
956
957
|
surface: "mcp_recent",
|
|
957
958
|
toolName: "memory_recent",
|
|
958
959
|
toolArguments: e,
|
|
@@ -970,10 +971,10 @@ function Re(e, t) {
|
|
|
970
971
|
};
|
|
971
972
|
})), e.registerTool("memory_pack", {
|
|
972
973
|
description: "Build a formatted context block for a concept or task using keyword and semantic search when embeddings are available, with automatic keyword-only fallback. Use for conceptually relevant context; use memory_search or memory_search_index for exact identifiers.",
|
|
973
|
-
inputSchema:
|
|
974
|
+
inputSchema: Ie,
|
|
974
975
|
outputSchema: M.memory_pack,
|
|
975
976
|
annotations: F.memory_pack
|
|
976
|
-
}, async (e, i) =>
|
|
977
|
+
}, async (e, i) => X(t, {
|
|
977
978
|
surface: "mcp_pack",
|
|
978
979
|
toolName: "memory_pack",
|
|
979
980
|
toolArguments: e,
|
|
@@ -998,27 +999,27 @@ function Re(e, t) {
|
|
|
998
999
|
}
|
|
999
1000
|
//#endregion
|
|
1000
1001
|
//#region src/tools/timeline.ts
|
|
1001
|
-
var
|
|
1002
|
+
var Re = {
|
|
1002
1003
|
query: v.string().optional().describe("Search query to find anchor"),
|
|
1003
1004
|
memory_id: v.number().int().optional().describe("Anchor memory ID"),
|
|
1004
1005
|
depth_before: v.number().int().min(0).default(3).describe("Items before anchor"),
|
|
1005
1006
|
depth_after: v.number().int().min(0).default(3).describe("Items after anchor"),
|
|
1006
|
-
...
|
|
1007
|
-
},
|
|
1007
|
+
...T
|
|
1008
|
+
}, ze = {
|
|
1008
1009
|
ids: v.array(v.union([v.number(), v.string()])).max(200).describe("Memory IDs to expand"),
|
|
1009
1010
|
depth_before: v.number().int().min(0).default(3).describe("Timeline items before"),
|
|
1010
1011
|
depth_after: v.number().int().min(0).default(3).describe("Timeline items after"),
|
|
1011
1012
|
include_observations: v.boolean().default(!1).describe("Include full observation details"),
|
|
1012
|
-
...
|
|
1013
|
+
...T
|
|
1013
1014
|
};
|
|
1014
|
-
function
|
|
1015
|
+
function Be(e, t) {
|
|
1015
1016
|
let { defaultProject: n, store: r } = t;
|
|
1016
1017
|
e.registerTool("memory_timeline", {
|
|
1017
1018
|
description: "Get a chronological window of memories around an anchor (by ID or query).",
|
|
1018
|
-
inputSchema:
|
|
1019
|
+
inputSchema: Re,
|
|
1019
1020
|
outputSchema: M.memory_timeline,
|
|
1020
1021
|
annotations: F.memory_timeline
|
|
1021
|
-
}, async (e, i) =>
|
|
1022
|
+
}, async (e, i) => X(t, {
|
|
1022
1023
|
surface: "mcp_timeline",
|
|
1023
1024
|
toolName: "memory_timeline",
|
|
1024
1025
|
toolArguments: e,
|
|
@@ -1037,10 +1038,10 @@ function Ve(e, t) {
|
|
|
1037
1038
|
};
|
|
1038
1039
|
})), e.registerTool("memory_expand", {
|
|
1039
1040
|
description: "Fetch memories by ID with surrounding timeline context.",
|
|
1040
|
-
inputSchema:
|
|
1041
|
+
inputSchema: ze,
|
|
1041
1042
|
outputSchema: M.memory_expand,
|
|
1042
1043
|
annotations: F.memory_expand
|
|
1043
|
-
}, async (e, i) =>
|
|
1044
|
+
}, async (e, i) => X(t, {
|
|
1044
1045
|
surface: "mcp_expand",
|
|
1045
1046
|
toolName: "memory_expand",
|
|
1046
1047
|
toolArguments: e,
|
|
@@ -1109,7 +1110,7 @@ function Ve(e, t) {
|
|
|
1109
1110
|
if (e.include_observations) {
|
|
1110
1111
|
let e = /* @__PURE__ */ new Set(), n = [];
|
|
1111
1112
|
for (let t of [...f, ...p]) t.id > 0 && !e.has(t.id) && (e.add(t.id), n.push(t.id));
|
|
1112
|
-
g =
|
|
1113
|
+
g = Q(r, n, t);
|
|
1113
1114
|
}
|
|
1114
1115
|
return {
|
|
1115
1116
|
value: {
|
|
@@ -1137,8 +1138,8 @@ function Ve(e, t) {
|
|
|
1137
1138
|
}
|
|
1138
1139
|
//#endregion
|
|
1139
1140
|
//#region src/server.ts
|
|
1140
|
-
function
|
|
1141
|
-
let r = new
|
|
1141
|
+
function Ve(e, n = {}) {
|
|
1142
|
+
let r = new te({
|
|
1142
1143
|
name: "codemem",
|
|
1143
1144
|
version: a
|
|
1144
1145
|
}), i = {
|
|
@@ -1149,9 +1150,9 @@ function He(e, n = {}) {
|
|
|
1149
1150
|
retrievalLedgerScopeId: n.retrievalLedgerScopeId ?? t(),
|
|
1150
1151
|
retrievalLedgerIdentityMode: n.retrievalLedgerIdentityMode ?? "session"
|
|
1151
1152
|
};
|
|
1152
|
-
return
|
|
1153
|
+
return Le(r, i), Be(r, i), B(r, i), ke(r, i), Me(r), je(r), r;
|
|
1153
1154
|
}
|
|
1154
1155
|
//#endregion
|
|
1155
|
-
export { y as n,
|
|
1156
|
+
export { y as n, Ve as t };
|
|
1156
1157
|
|
|
1157
|
-
//# sourceMappingURL=server-
|
|
1158
|
+
//# sourceMappingURL=server-C-Z_tmAr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-C-Z_tmAr.js","names":[],"sources":["../src/canonical-json.ts","../src/project-scope.ts","../src/content.ts","../src/schemas.ts","../src/tool-contracts.ts","../src/tools/distill.ts","../src/mcp-retrieval-ledger.ts","../src/memory-access.ts","../src/tools/items.ts","../src/tools/learn.ts","../src/tools/schema.ts","../src/tools/search.ts","../src/tools/timeline.ts","../src/server.ts"],"sourcesContent":["export function canonicalJson(value: unknown): string {\n\treturn (\n\t\tJSON.stringify(value, (_key, nestedValue) => {\n\t\t\tif (nestedValue === null || typeof nestedValue !== \"object\" || Array.isArray(nestedValue)) {\n\t\t\t\treturn nestedValue;\n\t\t\t}\n\t\t\treturn Object.fromEntries(\n\t\t\t\tObject.entries(nestedValue as Record<string, unknown>).toSorted(([left], [right]) =>\n\t\t\t\t\tleft < right ? -1 : left > right ? 1 : 0,\n\t\t\t\t),\n\t\t\t);\n\t\t}) ?? \"undefined\"\n\t);\n}\n","import { type MemoryFilters, resolveProject } from \"@codemem/core\";\n\nfunction cleanProject(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nexport function resolveDefaultProject(): string | null {\n\treturn cleanProject(process.env.CODEMEM_PROJECT) ?? resolveProject(process.cwd());\n}\n\nexport function resolveWriteProject(input: {\n\tproject?: string | null;\n\tenvProject?: string | null;\n}): string | null {\n\treturn cleanProject(input.project) ?? cleanProject(input.envProject) ?? null;\n}\n\nexport function buildFilters(\n\traw: Record<string, unknown>,\n\tdefaultProject = resolveDefaultProject(),\n): MemoryFilters | undefined {\n\tconst filters: MemoryFilters = {};\n\tlet hasAny = false;\n\n\tconst explicitProject = typeof raw.project === \"string\" ? cleanProject(raw.project) : undefined;\n\tconst resolvedProject = explicitProject || cleanProject(defaultProject) || undefined;\n\tif (resolvedProject) {\n\t\tfilters.project = resolvedProject;\n\t\thasAny = true;\n\t}\n\n\tfor (const key of [\n\t\t\"kind\",\n\t\t\"visibility\",\n\t\t\"scope_id\",\n\t\t\"include_scope_ids\",\n\t\t\"exclude_scope_ids\",\n\t\t\"include_visibility\",\n\t\t\"exclude_visibility\",\n\t\t\"include_workspace_ids\",\n\t\t\"exclude_workspace_ids\",\n\t\t\"include_workspace_kinds\",\n\t\t\"exclude_workspace_kinds\",\n\t\t\"include_actor_ids\",\n\t\t\"exclude_actor_ids\",\n\t\t\"include_trust_states\",\n\t\t\"exclude_trust_states\",\n\t\t\"ownership_scope\",\n\t\t\"personal_first\",\n\t\t\"trust_bias\",\n\t\t\"widen_shared_when_weak\",\n\t\t\"widen_shared_min_personal_results\",\n\t\t\"widen_shared_min_personal_score\",\n\t] as const) {\n\t\tconst val = raw[key];\n\t\tif (val !== undefined && val !== null) {\n\t\t\t(filters as Record<string, unknown>)[key] = val;\n\t\t\thasAny = true;\n\t\t}\n\t}\n\n\treturn hasAny ? filters : undefined;\n}\n","function parseStructuredObject(text: string): Record<string, unknown> {\n\tconst value: unknown = JSON.parse(text);\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new TypeError(\"MCP structured content must be a JSON object\");\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nexport function jsonContent(data: unknown) {\n\tconst text = JSON.stringify(data);\n\tif (text === undefined) throw new TypeError(\"MCP structured content must be JSON serializable\");\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text }],\n\t\tstructuredContent: parseStructuredObject(text),\n\t};\n}\n\nexport function errorContent(message: string) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text: JSON.stringify({ error: message }) }],\n\t\tisError: true,\n\t};\n}\n","import { REMEMBER_MEMORY_KINDS } from \"@codemem/core\";\nimport { z } from \"zod\";\n\nconst scopeFilterSchema = {\n\tscope_id: z.string().optional().describe(\"Filter by a single sharing domain scope_id\"),\n\tinclude_scope_ids: z.array(z.string()).optional().describe(\"Sharing domain scope_ids to include\"),\n\texclude_scope_ids: z.array(z.string()).optional().describe(\"Sharing domain scope_ids to exclude\"),\n};\n\nexport const filterSchema = {\n\tkind: z.string().optional().describe(\"Filter by memory kind\"),\n\tproject: z.string().optional().describe(\"Filter by project scope (matches sessions.project)\"),\n\t...scopeFilterSchema,\n\tvisibility: z.array(z.string()).optional(),\n\tinclude_visibility: z.array(z.string()).optional(),\n\texclude_visibility: z.array(z.string()).optional(),\n\tinclude_workspace_ids: z.array(z.string()).optional(),\n\texclude_workspace_ids: z.array(z.string()).optional(),\n\tinclude_workspace_kinds: z.array(z.string()).optional(),\n\texclude_workspace_kinds: z.array(z.string()).optional(),\n\tinclude_actor_ids: z.array(z.string()).optional(),\n\texclude_actor_ids: z.array(z.string()).optional(),\n\tinclude_trust_states: z.array(z.string()).optional(),\n\texclude_trust_states: z.array(z.string()).optional(),\n\townership_scope: z.string().optional(),\n\tpersonal_first: z.union([z.boolean(), z.string()]).optional(),\n\ttrust_bias: z.string().optional(),\n\twiden_shared_when_weak: z.union([z.boolean(), z.string()]).optional(),\n\twiden_shared_min_personal_results: z.number().int().optional(),\n\twiden_shared_min_personal_score: z.number().optional(),\n};\n\nexport const memoryKindSchema = z.enum(REMEMBER_MEMORY_KINDS);\n\nexport const filterNames = Object.keys(filterSchema).toSorted();\n","import type { ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\n\nconst metadataSchema = z.record(z.string(), z.unknown());\n// The column has a default but no NOT NULL constraint, and legacy rows can emit null.\nconst confidenceSchema = z.number().nullable();\n\nconst storedMemorySchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tbody_text: z.string(),\n\t\tsession_id: z.number().int().optional(),\n\t\tconfidence: confidenceSchema.optional(),\n\t\tcreated_at: z.string().optional(),\n\t\tupdated_at: z.string().optional(),\n\t\tmetadata_json: metadataSchema.optional(),\n\t})\n\t.passthrough();\n\nconst searchMemorySchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tbody: z.string(),\n\t\tconfidence: confidenceSchema.optional(),\n\t\tscore: z.number().optional(),\n\t\tsession_id: z.number().int().optional(),\n\t\tmetadata: metadataSchema.optional(),\n\t})\n\t.passthrough();\n\nconst indexMemorySchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tscore: z.number(),\n\t\tcreated_at: z.string(),\n\t\tsession_id: z.number().int(),\n\t\tmetadata: metadataSchema,\n\t})\n\t.passthrough();\n\nconst errorDetailSchema = z\n\t.object({\n\t\tcode: z.string(),\n\t\tfield: z.string(),\n\t\tmessage: z.string(),\n\t\tids: z.array(z.union([z.string(), z.number()])).optional(),\n\t})\n\t.passthrough();\n\nconst explainItemSchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tcreated_at: z.string(),\n\t\tproject: z.string().nullable(),\n\t\tretrieval: z.object({ source: z.string(), rank: z.number().int().nullable() }).passthrough(),\n\t\tscore: z\n\t\t\t.object({\n\t\t\t\ttotal: z.number().nullable(),\n\t\t\t\tcomponents: z\n\t\t\t\t\t.object({\n\t\t\t\t\t\tbase: z.number().nullable(),\n\t\t\t\t\t\trecency: z.number(),\n\t\t\t\t\t\tkind_bonus: z.number(),\n\t\t\t\t\t\tpersonal_bias: z.number(),\n\t\t\t\t\t\tsemantic_boost: z.number().nullable(),\n\t\t\t\t\t})\n\t\t\t\t\t.passthrough(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t\trole: z.object({ inferred: z.string(), reason: z.string() }).passthrough(),\n\t\tmatches: z\n\t\t\t.object({ query_terms: z.array(z.string()), project_match: z.boolean().nullable() })\n\t\t\t.passthrough(),\n\t\tpack_context: z\n\t\t\t.object({ included: z.boolean().nullable(), section: z.string().nullable() })\n\t\t\t.passthrough()\n\t\t\t.nullable(),\n\t})\n\t.passthrough();\n\nconst packItemSchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tbody: z.string(),\n\t\tconfidence: confidenceSchema,\n\t\tmetadata: metadataSchema,\n\t})\n\t.passthrough();\n\nconst stringListSectionSchema = z\n\t.object({\n\t\twhen: z.array(z.string()),\n\t\thow: z.array(z.string()),\n\t\texamples: z.array(z.string()),\n\t})\n\t.passthrough();\n\nexport const toolOutputSchemas = {\n\tmemory_search: z.object({ items: z.array(searchMemorySchema) }),\n\tmemory_search_index: z.object({ items: z.array(indexMemorySchema) }),\n\tmemory_explain: z.object({\n\t\titems: z.array(explainItemSchema),\n\t\tmissing_ids: z.array(z.number().int()),\n\t\terrors: z.array(errorDetailSchema),\n\t\tmetadata: z\n\t\t\t.object({\n\t\t\t\tquery: z.string().nullable(),\n\t\t\t\tproject: z.string().nullable(),\n\t\t\t\trequested_ids_count: z.number().int(),\n\t\t\t\treturned_items_count: z.number().int(),\n\t\t\t\tinclude_pack_context: z.boolean(),\n\t\t\t\tsanitized_query: z.string().optional(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_recent: z.object({ items: z.array(storedMemorySchema) }),\n\tmemory_pack: z.object({\n\t\tcontext: z.string(),\n\t\titems: z.array(packItemSchema),\n\t\titem_ids: z.array(z.number().int()),\n\t\tpack_text: z.string(),\n\t\tmetrics: z\n\t\t\t.object({\n\t\t\t\ttotal_items: z.number().int(),\n\t\t\t\tpack_tokens: z.number().int(),\n\t\t\t\tfallback_used: z.boolean(),\n\t\t\t\tlimit: z.number().int(),\n\t\t\t\tproject: z.string().nullable(),\n\t\t\t\tpack_item_ids: z.array(z.number().int()),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_timeline: z.object({ items: z.array(storedMemorySchema) }),\n\tmemory_expand: z.object({\n\t\tanchors: z.array(storedMemorySchema),\n\t\ttimeline: z.array(storedMemorySchema),\n\t\tobservations: z.array(storedMemorySchema),\n\t\tmissing_ids: z.array(z.number().int()),\n\t\terrors: z.array(errorDetailSchema),\n\t\tmetadata: z\n\t\t\t.object({\n\t\t\t\tproject: z.string().nullable(),\n\t\t\t\trequested_ids_count: z.number().int(),\n\t\t\t\treturned_anchor_count: z.number().int(),\n\t\t\t\ttimeline_count: z.number().int(),\n\t\t\t\tinclude_observations: z.boolean(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_get: storedMemorySchema,\n\tmemory_get_observations: z.object({ items: z.array(storedMemorySchema) }),\n\tmemory_remember: z.object({ id: z.number().int() }),\n\tmemory_forget: z.object({ status: z.literal(\"ok\") }),\n\tmemory_distill_candidates: z.object({\n\t\tversion: z.literal(1),\n\t\tcandidates: z.array(\n\t\t\tz\n\t\t\t\t.object({\n\t\t\t\t\tscope: z.enum([\"project\", \"user\"]),\n\t\t\t\t\tsuggested_target: z.string().nullable(),\n\t\t\t\t\tscore: z.number(),\n\t\t\t\t\trecurrence: z.number().int(),\n\t\t\t\t\tprojects: z.array(z.string()),\n\t\t\t\t\tmember_ids: z.array(z.number().int()),\n\t\t\t\t\trepresentative_id: z.number().int(),\n\t\t\t\t\tconcepts: z.array(z.string()),\n\t\t\t\t\tartifact_kind: z.enum([\"context_fact\", \"skill\"]),\n\t\t\t\t\tevidence: z.array(z.string()),\n\t\t\t\t\tdraft_text: z.string().nullable(),\n\t\t\t\t})\n\t\t\t\t.passthrough(),\n\t\t),\n\t\tmetadata: z\n\t\t\t.object({\n\t\t\t\tcandidate_count: z.number().int(),\n\t\t\t\tcluster_count: z.number().int(),\n\t\t\t\tcontext_document_count: z.number().int(),\n\t\t\t\tcorpus_count: z.number().int(),\n\t\t\t\tcorpus_limit: z.number().int(),\n\t\t\t\tdocumented_cluster_count: z.number().int(),\n\t\t\t\tinclude_documented: z.boolean(),\n\t\t\t\tmin_recurrence: z.number().int(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_schema: z.object({\n\t\tkinds: z.array(z.string()),\n\t\tkind_descriptions: z.record(z.string(), z.string()),\n\t\tfields: z.record(z.string(), z.string()),\n\t\tfilters: z.array(z.string()),\n\t}),\n\tmemory_learn: z.object({\n\t\tintro: z.string(),\n\t\tclient_hint: z.string(),\n\t\trecall: stringListSectionSchema,\n\t\tpersistence: stringListSectionSchema,\n\t\tforget: stringListSectionSchema,\n\t\tprompt_hint: z.string(),\n\t\trecommended_system_prompt: z.string(),\n\t}),\n} as const;\n\n// Incidental diagnostics and caches do not change the primary read operation.\nconst localReadAnnotations = {\n\treadOnlyHint: true,\n\topenWorldHint: false,\n} satisfies ToolAnnotations;\n\n// Pack/distill remain read-only while model loading or observer calls may access\n// entities outside the local store.\nconst externalReadAnnotations = {\n\treadOnlyHint: true,\n\topenWorldHint: true,\n} satisfies ToolAnnotations;\n\nexport const toolAnnotations = {\n\tmemory_search: localReadAnnotations,\n\tmemory_search_index: localReadAnnotations,\n\tmemory_explain: localReadAnnotations,\n\tmemory_recent: localReadAnnotations,\n\tmemory_pack: externalReadAnnotations,\n\tmemory_timeline: localReadAnnotations,\n\tmemory_expand: localReadAnnotations,\n\tmemory_get: localReadAnnotations,\n\tmemory_get_observations: localReadAnnotations,\n\t// Remember is additive, but embedding generation can load external model assets.\n\tmemory_remember: {\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: false,\n\t\tidempotentHint: false,\n\t\topenWorldHint: true,\n\t},\n\t// Repeating a soft delete has no additional environmental effect.\n\tmemory_forget: {\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false,\n\t},\n\tmemory_distill_candidates: externalReadAnnotations,\n\tmemory_schema: localReadAnnotations,\n\tmemory_learn: localReadAnnotations,\n} as const satisfies Record<keyof typeof toolOutputSchemas, ToolAnnotations>;\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n\tbuildDistillReport,\n\ttype DistillContextDocument,\n\tjudgeDistillReport,\n\ttype MemoryFilters,\n\tObserverClient,\n\tprojectMatchesFilter,\n\tresolveProject,\n\tresolveProjectRoot,\n} from \"@codemem/core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { errorContent, jsonContent } from \"../content.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst distillInputSchema = {\n\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max candidates\"),\n\tmin_recurrence: z\n\t\t.number()\n\t\t.int()\n\t\t.min(1)\n\t\t.max(50)\n\t\t.default(2)\n\t\t.describe(\"Minimum member count per candidate\"),\n\tall_projects: z.boolean().default(false).describe(\"Mine memories across all projects\"),\n\tinclude_documented: z\n\t\t.boolean()\n\t\t.default(false)\n\t\t.describe(\"Include candidates already represented in context files\"),\n\tmax_evidence_items: z\n\t\t.number()\n\t\t.int()\n\t\t.min(1)\n\t\t.max(20)\n\t\t.default(5)\n\t\t.describe(\"Evidence snippets per candidate\"),\n\tjudge: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe(\n\t\t\t\"Judge candidates with the observer model and drop routine-activity clusters (on by default; falls back to unjudged output when no observer model is configured)\",\n\t\t),\n\t...filterSchema,\n};\n\nfunction readContextFile(\n\tpath: string,\n\tdisplayPath: string,\n\tscope: DistillContextDocument[\"scope\"],\n): DistillContextDocument | null {\n\tif (!existsSync(path)) return null;\n\tconst text = readFileSync(path, \"utf8\");\n\treturn text.trim() ? { path: displayPath, text, scope } : null;\n}\n\nfunction loadDefaultContextDocuments(\n\tincludeProjectContext: boolean,\n\tcwd = process.cwd(),\n): DistillContextDocument[] {\n\t// The repo-root AGENTS.md describes the current repo (scope \"project\") and is\n\t// gated to current-project runs; the user-global context (scope \"user\")\n\t// always applies and never suppresses other projects' candidates. Resolve the\n\t// repo root so running from a subdirectory still finds the project context.\n\tconst projectRoot = resolveProjectRoot(cwd) ?? cwd;\n\tconst documents = [\n\t\tincludeProjectContext\n\t\t\t? readContextFile(join(projectRoot, \"AGENTS.md\"), \"AGENTS.md\", \"project\")\n\t\t\t: null,\n\t\treadContextFile(\n\t\t\tjoin(homedir(), \".config\", \"opencode\", \"AGENTS.md\"),\n\t\t\t\"~/.config/opencode/AGENTS.md\",\n\t\t\t\"user\",\n\t\t),\n\t];\n\treturn documents.filter((document): document is DistillContextDocument => document != null);\n}\n\nfunction shouldIncludeProjectContext(\n\targs: { all_projects?: boolean; project?: unknown },\n\tdefaultProject: string | null,\n): boolean {\n\tif (args.all_projects) return false;\n\tconst currentProject = resolveProject(process.cwd());\n\tif (!currentProject) return false;\n\tconst explicitProject = typeof args.project === \"string\" ? args.project.trim() : \"\";\n\t// Match the corpus filter: the cwd AGENTS.md is only valid when the mined\n\t// project (explicit arg or the server default project) is this repo.\n\tconst targetProject = explicitProject\n\t\t? resolveProject(process.cwd(), explicitProject)\n\t\t: defaultProject;\n\tif (!targetProject) return false;\n\treturn projectMatchesFilter(targetProject, currentProject);\n}\n\nfunction buildDistillFilters(\n\targs: { all_projects?: boolean } & Record<string, unknown>,\n\tdefaultProject: string | null,\n): MemoryFilters | undefined {\n\tif (args.all_projects && typeof args.project === \"string\" && args.project.trim()) {\n\t\tthrow new Error(\"project cannot be combined with all_projects\");\n\t}\n\treturn buildFilters(args, args.all_projects ? null : defaultProject);\n}\n\nexport function registerDistillTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.registerTool(\n\t\t\"memory_distill_candidates\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Mine recurring memories into reviewable context candidates. Reads project/user context files without modifying them and can call the optional observer when judge=true.\",\n\t\t\tinputSchema: distillInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_distill_candidates,\n\t\t\tannotations: toolAnnotations.memory_distill_candidates,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\tconst resolvedDefaultProject = defaultProject();\n\t\t\t\tconst filters = buildDistillFilters(args, resolvedDefaultProject);\n\t\t\t\tconst kinds = args.kind ? [args.kind] : undefined;\n\t\t\t\t// When judging, mine extra candidates so routine drops are backfilled\n\t\t\t\t// from the next-ranked clusters instead of shrinking the caller's limit.\n\t\t\t\tconst fetchLimit = args.judge ? Math.min(args.limit * 3, args.limit + 20) : args.limit;\n\t\t\t\tlet result = await buildDistillReport(store, {\n\t\t\t\t\tcandidate: {\n\t\t\t\t\t\tincludeDocumented: args.include_documented,\n\t\t\t\t\t\tmaxEvidenceItems: args.max_evidence_items,\n\t\t\t\t\t},\n\t\t\t\t\tcontextDocuments: loadDefaultContextDocuments(\n\t\t\t\t\t\tshouldIncludeProjectContext(args, resolvedDefaultProject),\n\t\t\t\t\t),\n\t\t\t\t\tcorpus: { filters: filters ?? null, kinds },\n\t\t\t\t\tlimit: fetchLimit,\n\t\t\t\t\tminRecurrence: args.min_recurrence,\n\t\t\t\t});\n\t\t\t\tif (args.judge) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst client = new ObserverClient();\n\t\t\t\t\t\tresult = await judgeDistillReport(result, async (system, user) => {\n\t\t\t\t\t\t\tconst response = await client.observe(system, user);\n\t\t\t\t\t\t\treturn response.raw;\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t// Fall back to unjudged output rather than failing the tool —\n\t\t\t\t\t\t// the caller sees judged:false + judge_error and can decide.\n\t\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\tresult = {\n\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\tmetadata: { ...result.metadata, judged: false, judge_error: message },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tif (result.candidates.length > args.limit) {\n\t\t\t\t\t\tresult = {\n\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\tcandidates: result.candidates.slice(0, args.limit),\n\t\t\t\t\t\t\tmetadata: { ...result.metadata, candidate_count: args.limit },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonContent(result);\n\t\t\t} catch (err) {\n\t\t\t\treturn errorContent(err instanceof Error ? err.message : String(err));\n\t\t\t}\n\t\t},\n\t);\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n\ttype MemoryFilters,\n\ttype RetrievalStatus,\n\ttype RetrievalSurface,\n\treconcileFailedRetrievalSurface,\n\trecordRetrievalSurface,\n} from \"@codemem/core\";\nimport { canonicalJson } from \"./canonical-json.js\";\nimport { errorContent, jsonContent } from \"./content.js\";\nimport type { ToolRegistrationContext } from \"./tool-context.js\";\n\nexport interface McpRetrievalResult<T> {\n\tvalue: T;\n\tmemoryIds: number[];\n\tcandidateCount?: number;\n\tfilters?: MemoryFilters;\n\tretrievalStatus?: RetrievalStatus;\n\terror?: string;\n}\n\ninterface McpRetrievalInput {\n\tsurface: RetrievalSurface;\n\ttoolName: string;\n\ttoolArguments: unknown;\n\tquery?: string | null;\n\tlimit?: number | null;\n\tresolveFilters?: () => MemoryFilters | undefined;\n\trequestId?: string | number;\n\tsourceSessionId?: string | null;\n\tinvocationIdentity?: object;\n}\n\nconst MCP_SESSION_RETRY_TTL_MS = 5 * 60 * 1000;\nconst MCP_SESSION_RETRY_MAX_ENTRIES = 2000;\n\ninterface InvocationLedgerIdentity {\n\tbaseRequestId: string | null;\n\trequestId: string | null;\n\tattemptId: string;\n}\n\ninterface PendingFailure {\n\tidentity: InvocationLedgerIdentity;\n\texpiresAt: number;\n\torder: number;\n}\n\ninterface SessionIdentityTracker {\n\tbyInvocation: WeakMap<object, InvocationLedgerIdentity>;\n\tactiveByRequest: Map<string, number>;\n\tpendingFailures: Map<string, PendingFailure[]>;\n\tpendingFailureCount: number;\n\tnextPendingFailureOrder: number;\n\tnextInvocationSequence: number;\n}\n\n// Track only live invocation objects and per-base FIFO failure queues. Pending\n// identities expire after five minutes and are capped at 2,000 entries total.\n// The outer WeakMap releases the whole tracker with its server registration context.\nconst sessionIdentityTrackers = new WeakMap<ToolRegistrationContext, SessionIdentityTracker>();\nlet fallbackAttemptSequence = 0;\n\nfunction recordMcpRetrieval(\n\tcontext: ToolRegistrationContext,\n\tinput: Parameters<typeof recordRetrievalSurface>[1],\n\treconcileTransientFailure: boolean,\n): void {\n\tif (!context.captureRetrievalLedger) return;\n\ttry {\n\t\tconst outcome = recordRetrievalSurface(context.store.db, input);\n\t\tif (\n\t\t\treconcileTransientFailure &&\n\t\t\t!outcome.ok &&\n\t\t\toutcome.reason === \"idempotency_conflict\" &&\n\t\t\t((input.retrievalStatus === \"succeeded\" && input.deliveryStatus === \"handed_off\") ||\n\t\t\t\t(input.retrievalStatus === \"no_results\" && input.deliveryStatus === \"not_attempted\"))\n\t\t) {\n\t\t\treconcileFailedRetrievalSurface(context.store.db, input);\n\t\t}\n\t} catch {\n\t\t// MCP responses must remain independent from local diagnostics.\n\t}\n}\n\nfunction requestAttemptId(requestId: string | null): string {\n\tif (requestId == null) return randomUUID();\n\tconst hex = requestId.slice(0, 32).split(\"\");\n\thex[12] = \"5\";\n\thex[16] = ((Number.parseInt(hex[16] ?? \"0\", 16) & 0x3) | 0x8).toString(16);\n\tconst value = hex.join(\"\");\n\treturn `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;\n}\n\nfunction baseRequestIdentity(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n): string | null {\n\tif (input.requestId == null) return null;\n\tconst callContentDigest = createHash(\"sha256\")\n\t\t.update(\n\t\t\tcanonicalJson({\n\t\t\t\tmethod: \"tools/call\",\n\t\t\t\tparams: { name: input.toolName, arguments: input.toolArguments },\n\t\t\t}),\n\t\t)\n\t\t.digest(\"hex\");\n\treturn createHash(\"sha256\")\n\t\t.update(\n\t\t\tJSON.stringify([\n\t\t\t\tinput.sourceSessionId ?? context.retrievalLedgerScopeId,\n\t\t\t\tinput.requestId,\n\t\t\t\tcallContentDigest,\n\t\t\t]),\n\t\t)\n\t\t.digest(\"hex\");\n}\n\nfunction sessionIdentityTracker(context: ToolRegistrationContext): SessionIdentityTracker {\n\tlet tracker = sessionIdentityTrackers.get(context);\n\tif (!tracker) {\n\t\ttracker = {\n\t\t\tbyInvocation: new WeakMap(),\n\t\t\tactiveByRequest: new Map(),\n\t\t\tpendingFailures: new Map(),\n\t\t\tpendingFailureCount: 0,\n\t\t\tnextPendingFailureOrder: 0,\n\t\t\tnextInvocationSequence: 0,\n\t\t};\n\t\tsessionIdentityTrackers.set(context, tracker);\n\t}\n\treturn tracker;\n}\n\nfunction prunePendingFailures(tracker: SessionIdentityTracker, now: number): void {\n\tfor (const [requestId, pending] of tracker.pendingFailures) {\n\t\tconst retained = pending.filter((entry) => entry.expiresAt > now);\n\t\ttracker.pendingFailureCount -= pending.length - retained.length;\n\t\tif (retained.length === 0) tracker.pendingFailures.delete(requestId);\n\t\telse if (retained.length !== pending.length) tracker.pendingFailures.set(requestId, retained);\n\t}\n\twhile (tracker.pendingFailureCount > MCP_SESSION_RETRY_MAX_ENTRIES) {\n\t\tlet oldestRequestId: string | undefined;\n\t\tlet oldestOrder = Number.POSITIVE_INFINITY;\n\t\tfor (const [requestId, pending] of tracker.pendingFailures) {\n\t\t\tconst order = pending[0]?.order;\n\t\t\tif (order != null && order < oldestOrder) {\n\t\t\t\toldestRequestId = requestId;\n\t\t\t\toldestOrder = order;\n\t\t\t}\n\t\t}\n\t\tif (oldestRequestId === undefined) break;\n\t\tconst pending = tracker.pendingFailures.get(oldestRequestId);\n\t\tconst removed = pending?.shift();\n\t\tif (!pending || !removed) {\n\t\t\ttracker.pendingFailures.delete(oldestRequestId);\n\t\t\tcontinue;\n\t\t}\n\t\ttracker.pendingFailureCount -= 1;\n\t\tif (pending.length === 0) tracker.pendingFailures.delete(oldestRequestId);\n\t}\n}\n\nfunction takePendingFailure(\n\ttracker: SessionIdentityTracker,\n\tbaseRequestId: string,\n): InvocationLedgerIdentity | undefined {\n\tconst pending = tracker.pendingFailures.get(baseRequestId);\n\tif (!pending) return undefined;\n\tconst failure = pending.shift();\n\tif (!failure) return undefined;\n\ttracker.pendingFailureCount -= 1;\n\tif (pending.length === 0) tracker.pendingFailures.delete(baseRequestId);\n\treturn failure.identity;\n}\n\nfunction removePendingFailure(\n\ttracker: SessionIdentityTracker,\n\tbaseRequestId: string,\n\tattemptId: string,\n): void {\n\tconst pending = tracker.pendingFailures.get(baseRequestId);\n\tconst index = pending?.findIndex((entry) => entry.identity.attemptId === attemptId) ?? -1;\n\tif (!pending || index < 0) return;\n\tpending.splice(index, 1);\n\ttracker.pendingFailureCount -= 1;\n\tif (pending.length === 0) tracker.pendingFailures.delete(baseRequestId);\n}\n\nfunction enqueuePendingFailure(\n\ttracker: SessionIdentityTracker,\n\tbaseRequestId: string,\n\tidentity: InvocationLedgerIdentity,\n\tnow: number,\n): void {\n\tconst pending = tracker.pendingFailures.get(baseRequestId) ?? [];\n\tif (pending.some((entry) => entry.identity.attemptId === identity.attemptId)) return;\n\tpending.push({\n\t\tidentity,\n\t\texpiresAt: now + MCP_SESSION_RETRY_TTL_MS,\n\t\torder: tracker.nextPendingFailureOrder,\n\t});\n\ttracker.nextPendingFailureOrder += 1;\n\ttracker.pendingFailures.set(baseRequestId, pending);\n\ttracker.pendingFailureCount += 1;\n\tprunePendingFailures(tracker, now);\n}\n\nfunction fallbackInvocationIdentity(): InvocationLedgerIdentity {\n\ttry {\n\t\treturn { baseRequestId: null, requestId: null, attemptId: randomUUID() };\n\t} catch {\n\t\tconst timestamp = Date.now().toString(16).slice(-8).padStart(8, \"0\");\n\t\tconst sequence = fallbackAttemptSequence.toString(16).slice(-4).padStart(4, \"0\");\n\t\tfallbackAttemptSequence = (fallbackAttemptSequence + 1) % 0x1_0000;\n\t\treturn {\n\t\t\tbaseRequestId: null,\n\t\t\trequestId: null,\n\t\t\tattemptId: `00000000-0000-4000-8000-${timestamp}${sequence}`,\n\t\t};\n\t}\n}\n\nfunction beginInvocation(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n): InvocationLedgerIdentity {\n\tconst baseRequestId = baseRequestIdentity(context, input);\n\tif (context.retrievalLedgerIdentityMode === \"stateless\" || baseRequestId == null) {\n\t\treturn {\n\t\t\tbaseRequestId,\n\t\t\trequestId: baseRequestId,\n\t\t\tattemptId: requestAttemptId(baseRequestId),\n\t\t};\n\t}\n\n\tconst tracker = sessionIdentityTracker(context);\n\tprunePendingFailures(tracker, Date.now());\n\tconst candidateInvocation = input.invocationIdentity\n\t\t? tracker.byInvocation.get(input.invocationIdentity)\n\t\t: undefined;\n\tconst knownInvocation =\n\t\tcandidateInvocation?.baseRequestId === baseRequestId ? candidateInvocation : undefined;\n\tlet identity = knownInvocation;\n\tif (!identity) {\n\t\tconst activeCount = tracker.activeByRequest.get(baseRequestId) ?? 0;\n\t\tconst pending = activeCount === 0 ? takePendingFailure(tracker, baseRequestId) : undefined;\n\t\tif (pending) {\n\t\t\tidentity = pending;\n\t\t} else {\n\t\t\tconst invocationSequence = tracker.nextInvocationSequence;\n\t\t\ttracker.nextInvocationSequence += 1;\n\t\t\tconst requestId = createHash(\"sha256\")\n\t\t\t\t.update(JSON.stringify([baseRequestId, context.retrievalLedgerScopeId, invocationSequence]))\n\t\t\t\t.digest(\"hex\");\n\t\t\tidentity = {\n\t\t\t\tbaseRequestId,\n\t\t\t\trequestId,\n\t\t\t\tattemptId: requestAttemptId(requestId),\n\t\t\t};\n\t\t}\n\t\tif (input.invocationIdentity) tracker.byInvocation.set(input.invocationIdentity, identity);\n\t}\n\ttracker.activeByRequest.set(baseRequestId, (tracker.activeByRequest.get(baseRequestId) ?? 0) + 1);\n\treturn identity;\n}\n\nfunction safeBeginInvocation(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n): InvocationLedgerIdentity {\n\ttry {\n\t\treturn beginInvocation(context, input);\n\t} catch {\n\t\treturn fallbackInvocationIdentity();\n\t}\n}\n\nfunction completeInvocation(\n\tcontext: ToolRegistrationContext,\n\tidentity: InvocationLedgerIdentity,\n\tstatus: \"completed\" | \"failed\",\n): void {\n\tif (context.retrievalLedgerIdentityMode === \"stateless\" || identity.baseRequestId == null) return;\n\tconst tracker = sessionIdentityTracker(context);\n\tconst activeCount = tracker.activeByRequest.get(identity.baseRequestId) ?? 0;\n\tif (activeCount <= 1) tracker.activeByRequest.delete(identity.baseRequestId);\n\telse tracker.activeByRequest.set(identity.baseRequestId, activeCount - 1);\n\n\tif (status === \"failed\") {\n\t\tenqueuePendingFailure(tracker, identity.baseRequestId, identity, Date.now());\n\t} else {\n\t\tremovePendingFailure(tracker, identity.baseRequestId, identity.attemptId);\n\t}\n}\n\nfunction safeCompleteInvocation(\n\tcontext: ToolRegistrationContext,\n\tidentity: InvocationLedgerIdentity,\n\tstatus: \"completed\" | \"failed\",\n): void {\n\ttry {\n\t\tcompleteInvocation(context, identity, status);\n\t} catch {\n\t\t// Retrieval diagnostics must never alter the MCP tool result.\n\t}\n}\n\nexport async function withMcpRetrieval<T>(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n\tretrieve: (\n\t\tfilters: MemoryFilters | undefined,\n\t) => McpRetrievalResult<T> | Promise<McpRetrievalResult<T>>,\n) {\n\tconst invocation = safeBeginInvocation(context, input);\n\tconst ledgerRequestId = invocation.requestId;\n\tconst attemptId = invocation.attemptId;\n\tconst startedAt = new Date();\n\tlet filters: MemoryFilters | undefined;\n\ttry {\n\t\tfilters = input.resolveFilters?.();\n\t\tconst output = await retrieve(filters);\n\t\tconst completedAt = new Date();\n\t\tconst response = output.error ? errorContent(output.error) : jsonContent(output.value);\n\t\tconst streamId = input.sourceSessionId ?? context.retrievalLedgerScopeId;\n\t\tconst hasResults = output.memoryIds.length > 0;\n\t\tconst isNotFoundCompletion = output.error === \"not_found\" && !hasResults;\n\t\tconst isFailedResult =\n\t\t\t(output.error != null && !isNotFoundCompletion) ||\n\t\t\t(output.retrievalStatus === \"failed\" && !hasResults);\n\t\tconst recordedMemoryIds = isFailedResult ? [] : output.memoryIds;\n\t\tconst deliveredRetrievalStatus = output.retrievalStatus === \"unknown\" ? \"unknown\" : \"succeeded\";\n\t\trecordMcpRetrieval(\n\t\t\tcontext,\n\t\t\t{\n\t\t\t\tattemptId,\n\t\t\t\tsurface: input.surface,\n\t\t\t\ttrigger: \"explicit\",\n\t\t\t\tstartedAt: startedAt.toISOString(),\n\t\t\t\tcompletedAt: completedAt.toISOString(),\n\t\t\t\tretrievalStatus: isFailedResult\n\t\t\t\t\t? \"failed\"\n\t\t\t\t\t: hasResults\n\t\t\t\t\t\t? deliveredRetrievalStatus\n\t\t\t\t\t\t: \"no_results\",\n\t\t\t\tdeliveryStatus: isFailedResult || !hasResults ? \"not_attempted\" : \"handed_off\",\n\t\t\t\tcandidateIds: recordedMemoryIds,\n\t\t\t\tselectedIds: recordedMemoryIds,\n\t\t\t\tcandidateCount: hasResults && !isFailedResult ? output.candidateCount : 0,\n\t\t\t\trecorderVersion: \"mcp-retrieval-v1\",\n\t\t\t\tsource: \"mcp\",\n\t\t\t\tstreamId,\n\t\t\t\tsourceSessionId: input.sourceSessionId ?? null,\n\t\t\t\trequestId: ledgerRequestId,\n\t\t\t\tlatencyMs: Math.max(0, completedAt.getTime() - startedAt.getTime()),\n\t\t\t\tfilters: output.filters ?? filters,\n\t\t\t\tquery: input.query,\n\t\t\t\tlimitRequested: input.limit,\n\t\t\t\tfailureCode: isFailedResult ? \"tool_failed\" : undefined,\n\t\t\t\tfailureStage: isFailedResult ? \"retrieval\" : undefined,\n\t\t\t},\n\t\t\t!isFailedResult,\n\t\t);\n\t\tsafeCompleteInvocation(context, invocation, isFailedResult ? \"failed\" : \"completed\");\n\t\treturn response;\n\t} catch (error) {\n\t\tconst completedAt = new Date();\n\t\tconst streamId = input.sourceSessionId ?? context.retrievalLedgerScopeId;\n\t\trecordMcpRetrieval(\n\t\t\tcontext,\n\t\t\t{\n\t\t\t\tattemptId,\n\t\t\t\tsurface: input.surface,\n\t\t\t\ttrigger: \"explicit\",\n\t\t\t\tstartedAt: startedAt.toISOString(),\n\t\t\t\tcompletedAt: completedAt.toISOString(),\n\t\t\t\tretrievalStatus: \"failed\",\n\t\t\t\tdeliveryStatus: \"not_attempted\",\n\t\t\t\tcandidateIds: [],\n\t\t\t\tselectedIds: [],\n\t\t\t\trecorderVersion: \"mcp-retrieval-v1\",\n\t\t\t\tsource: \"mcp\",\n\t\t\t\tstreamId,\n\t\t\t\tsourceSessionId: input.sourceSessionId ?? null,\n\t\t\t\trequestId: ledgerRequestId,\n\t\t\t\tlatencyMs: Math.max(0, completedAt.getTime() - startedAt.getTime()),\n\t\t\t\tquery: input.query,\n\t\t\t\tlimitRequested: input.limit,\n\t\t\t\tfilters,\n\t\t\t\tfailureCode: \"tool_failed\",\n\t\t\t\tfailureStage: \"retrieval\",\n\t\t\t},\n\t\t\tfalse,\n\t\t);\n\t\tsafeCompleteInvocation(context, invocation, \"failed\");\n\t\treturn errorContent(error instanceof Error ? error.message : String(error));\n\t}\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n\ttype CreatedMemory,\n\ttype MemoryFilters,\n\ttype MemoryItemResponse,\n\ttype MemoryStore,\n\ttoJson,\n} from \"@codemem/core\";\nimport { resolveWriteProject } from \"./project-scope.js\";\n\nexport function getMemoryForMcp(\n\tstore: MemoryStore,\n\tmemoryId: number,\n\tfilters?: MemoryFilters,\n): MemoryItemResponse | null {\n\tconst rows = store.timeline(null, memoryId, 0, 0, filters ?? null);\n\treturn rows.find((row) => row.id === memoryId) ?? null;\n}\n\nexport function getManyForMcp(\n\tstore: MemoryStore,\n\tids: number[],\n\tfilters?: MemoryFilters,\n): MemoryItemResponse[] {\n\tif (ids.length === 0) return [];\n\tconst results: MemoryItemResponse[] = [];\n\tfor (const id of ids) {\n\t\tconst item = getMemoryForMcp(store, id, filters);\n\t\tif (item) results.push(item);\n\t}\n\treturn results;\n}\n\nexport function forgetMemoryForMcp(\n\tstore: MemoryStore,\n\tmemoryId: number,\n\tfilters?: MemoryFilters,\n): boolean {\n\tconst item = getMemoryForMcp(store, memoryId, filters);\n\tif (!item) return false;\n\treturn store.forgetForUser(memoryId);\n}\n\nexport interface RememberMemoryForMcpInput {\n\tkind: string;\n\ttitle: string;\n\tbody: string;\n\tconfidence: number;\n\tproject?: string | null;\n}\n\nexport interface RememberMemoryForMcpContext {\n\tcwd?: string;\n\tuser?: string;\n\tenvProject?: string | null;\n\tnow?: () => string;\n}\n\nexport function rememberMemoryForMcp(\n\tstore: MemoryStore,\n\tinput: RememberMemoryForMcpInput,\n\tcontext: RememberMemoryForMcpContext = {},\n): { memId: number; title: string; body: string } {\n\tconst createdMemories: CreatedMemory[] = [];\n\tconst result = store.db.transaction(() => {\n\t\tconst now = context.now?.() ?? new Date().toISOString();\n\t\tconst user = context.user ?? process.env.USER ?? \"unknown\";\n\t\tconst cwd = context.cwd ?? process.cwd();\n\t\tconst project = resolveWriteProject({\n\t\t\tproject: input.project,\n\t\t\tenvProject: context.envProject,\n\t\t});\n\n\t\tconst sessionInfo = store.db\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO sessions(started_at, ended_at, cwd, project, user, tool_version, metadata_json, import_key)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t)\n\t\t\t.run(now, now, cwd, project, user, \"mcp-ts\", toJson({ mcp: true }), randomUUID());\n\t\tconst sessionId = Number(sessionInfo.lastInsertRowid);\n\n\t\tconst memId = store.rememberForUser(\n\t\t\tsessionId,\n\t\t\tinput.kind,\n\t\t\tinput.title,\n\t\t\tinput.body,\n\t\t\tinput.confidence,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\t{ createdMemories },\n\t\t);\n\t\tif (!getMemoryForMcp(store, memId)) {\n\t\t\tthrow new Error(\"unauthorized_scope\");\n\t\t}\n\n\t\tstore.db\n\t\t\t.prepare(\"UPDATE sessions SET ended_at = ?, metadata_json = ? WHERE id = ?\")\n\t\t\t.run(context.now?.() ?? new Date().toISOString(), toJson({ mcp: true }), sessionId);\n\n\t\treturn { memId, title: input.title, body: input.body };\n\t})();\n\tstore.enqueueCommittedVectorWrites(createdMemories);\n\treturn result;\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { errorContent, jsonContent } from \"../content.js\";\nimport { withMcpRetrieval } from \"../mcp-retrieval-ledger.js\";\nimport {\n\tforgetMemoryForMcp,\n\tgetManyForMcp,\n\tgetMemoryForMcp,\n\trememberMemoryForMcp,\n} from \"../memory-access.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema, memoryKindSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst getInputSchema = {\n\tmemory_id: z.number().int().describe(\"Memory ID\"),\n\t...filterSchema,\n};\n\nconst getObservationsInputSchema = {\n\tids: z.array(z.number().int()).max(200).describe(\"Memory IDs to fetch\"),\n\t...filterSchema,\n};\n\nconst rememberInputSchema = {\n\tkind: memoryKindSchema.describe(\"Memory kind\"),\n\ttitle: z.string().describe(\"Short title\"),\n\tbody: z.string().describe(\"Body text (high-signal content)\"),\n\tconfidence: z.number().min(0).max(1).default(0.5).describe(\"Confidence 0-1\"),\n\tproject: z.string().optional().describe(\"Project identifier\"),\n};\n\nconst forgetInputSchema = {\n\tmemory_id: z.number().int().describe(\"Memory ID to forget\"),\n\t...filterSchema,\n};\n\nfunction registerGetTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_get\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Fetch one memory by exact ID. Does not inherit the default project; optional filters constrain the lookup, and a mismatch returns not_found.\",\n\t\t\tinputSchema: getInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_get,\n\t\t\tannotations: toolAnnotations.memory_get,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\t// Direct-ID ops do not inherit the server default project. Callers already\n\t\t\t// have an exact ID; cwd/env should not silently scope the lookup.\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_get\",\n\t\t\t\t\ttoolName: \"memory_get\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: 1,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, null),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst item = getMemoryForMcp(context.store, args.memory_id, filters);\n\t\t\t\t\treturn item\n\t\t\t\t\t\t? { value: item, memoryIds: [item.id], filters }\n\t\t\t\t\t\t: { value: null, memoryIds: [], error: \"not_found\", filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n\nfunction registerGetObservationsTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_get_observations\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Fetch multiple memories by exact IDs. Does not inherit the default project. Missing or filtered-out IDs are omitted from results, not reported as not_found.\",\n\t\t\tinputSchema: getObservationsInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_get_observations,\n\t\t\tannotations: toolAnnotations.memory_get_observations,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_get_observations\",\n\t\t\t\t\ttoolName: \"memory_get_observations\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: args.ids.length,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, null),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = getManyForMcp(context.store, args.ids, filters);\n\t\t\t\t\treturn { value: { items }, memoryIds: items.map((item) => item.id), filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n\nfunction registerRememberTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_remember\",\n\t\t{\n\t\t\tdescription: \"Create a new memory. Use for milestones, decisions, and notable facts.\",\n\t\t\tinputSchema: rememberInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_remember,\n\t\t\tannotations: toolAnnotations.memory_remember,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\t// Writes never inherit the server default project. They only honor an\n\t\t\t\t// explicit `project` input or CODEMEM_PROJECT; otherwise project stays null.\n\t\t\t\tconst result = rememberMemoryForMcp(context.store, args, {\n\t\t\t\t\tenvProject: context.envProject(),\n\t\t\t\t});\n\n\t\t\t\ttry {\n\t\t\t\t\tawait context.store.flushPendingVectorWrites();\n\t\t\t\t} catch {\n\t\t\t\t\t// Memory writes should succeed even if embeddings are unavailable.\n\t\t\t\t}\n\n\t\t\t\treturn jsonContent({ id: result.memId });\n\t\t\t} catch (err) {\n\t\t\t\treturn errorContent(err instanceof Error ? err.message : String(err));\n\t\t\t}\n\t\t},\n\t);\n}\n\nfunction registerForgetTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_forget\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Soft-delete a memory by exact ID so it no longer appears in normal retrieval; this is not secure erasure. Does not inherit the default project; optional filters must match or the tool returns not_found.\",\n\t\t\tinputSchema: forgetInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_forget,\n\t\t\tannotations: toolAnnotations.memory_forget,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\tif (!forgetMemoryForMcp(context.store, args.memory_id, buildFilters(args, null))) {\n\t\t\t\t\treturn errorContent(\"not_found\");\n\t\t\t\t}\n\t\t\t\treturn jsonContent({ status: \"ok\" });\n\t\t\t} catch (err) {\n\t\t\t\treturn errorContent(err instanceof Error ? err.message : String(err));\n\t\t\t}\n\t\t},\n\t);\n}\n\nexport function registerItemTools(server: McpServer, context: ToolRegistrationContext): void {\n\tregisterGetTool(server, context);\n\tregisterGetObservationsTool(server, context);\n\tregisterRememberTool(server, context);\n\tregisterForgetTool(server, context);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { jsonContent } from \"../content.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst MEMORY_LEARN_GUIDANCE = {\n\tintro: \"Use this tool when you're new to codemem or unsure when to recall/persist.\",\n\tclient_hint: \"If you are unfamiliar with codemem, call memory_learn first.\",\n\trecall: {\n\t\twhen: [\n\t\t\t\"Start of a task or when the user references prior work.\",\n\t\t\t\"When you need background context, decisions, or recent changes.\",\n\t\t],\n\t\thow: [\n\t\t\t\"Use memory_search or memory_search_index for exact terms and identifiers; memory_search returns bodies, while memory_search_index returns compact candidates.\",\n\t\t\t\"Use memory_pack for conceptually relevant context; it combines keyword and semantic search when embeddings are available and falls back to keyword search when they are not.\",\n\t\t\t\"Use memory_timeline to expand around a promising memory.\",\n\t\t\t\"Use memory_get or memory_get_observations for full details only when needed.\",\n\t\t\t\"Use the project filter unless the user requests cross-project context.\",\n\t\t\t\"Project, trust, and ownership filters organize and select memories; they are not authentication or tenant-isolation controls.\",\n\t\t],\n\t\texamples: [\n\t\t\t'memory_search_index(query=\"billing cache bug\", limit=5)',\n\t\t\t\"memory_timeline(memory_id=123)\",\n\t\t\t\"memory_get_observations(ids=[123, 456])\",\n\t\t],\n\t},\n\tpersistence: {\n\t\twhen: [\n\t\t\t\"Milestones (task done, key decision, new facts learned).\",\n\t\t\t\"Notable regressions or follow-ups that should be remembered.\",\n\t\t],\n\t\thow: [\n\t\t\t\"Use memory_remember with kind decision/discovery/change/exploration.\",\n\t\t\t\"Keep titles short and bodies high-signal.\",\n\t\t\t\"ALWAYS pass the project parameter if known.\",\n\t\t],\n\t\texamples: [\n\t\t\t'memory_remember(kind=\"decision\", title=\"Switch to async cache\", body=\"...why...\", project=\"my-service\")',\n\t\t\t'memory_remember(kind=\"change\", title=\"Fixed retry loop\", body=\"...impact...\", project=\"my-service\")',\n\t\t],\n\t},\n\tforget: {\n\t\twhen: [\n\t\t\t\"Obsolete or incorrect items that should no longer surface.\",\n\t\t\t\"Items that should be soft-deleted; soft deletion is not secure erasure.\",\n\t\t],\n\t\thow: [\n\t\t\t\"Call memory_forget(memory_id) to mark the item inactive.\",\n\t\t\t\"Optional filters constrain the exact-ID lookup; a filter mismatch returns not_found.\",\n\t\t\t\"Do not treat memory_forget as secure erasure or a user-data erasure guarantee.\",\n\t\t],\n\t\texamples: [\"memory_forget(memory_id=123)\"],\n\t},\n\tprompt_hint:\n\t\t\"At task start: call memory_search_index for exact terms or memory_pack for conceptual context; during work: memory_timeline + memory_get_observations; at milestones: memory_remember.\",\n\trecommended_system_prompt: [\n\t\t\"Trigger policy (1-liner): If the user references prior work or starts a task,\",\n\t\t\"call memory_search_index for exact terms or memory_pack for conceptual context; then use\",\n\t\t\"memory_timeline + memory_get_observations; at milestones, call memory_remember.\",\n\t\t\"\",\n\t\t\"System prompt:\",\n\t\t\"You have access to codemem MCP tools. If unfamiliar, call memory_learn first.\",\n\t\t\"\",\n\t\t\"Recall:\",\n\t\t\"- For exact terms or identifiers, use memory_search_index for compact candidates or memory_search for bodies.\",\n\t\t\"- For conceptually relevant context, use memory_pack; it falls back to keyword search without embeddings.\",\n\t\t'- If prior work is referenced (\"as before\", \"last time\", \"we already did…\", \"regression\"),',\n\t\t\" call memory_search_index, memory_pack, or memory_timeline as appropriate.\",\n\t\t\"- Use memory_get or memory_get_observations only after filtering IDs.\",\n\t\t\"- Prefer project-scoped queries unless the user asks for cross-project.\",\n\t\t\"- Project, trust, and ownership filters select memories; they do not authenticate or isolate tenants.\",\n\t\t\"\",\n\t\t\"Persistence:\",\n\t\t\"- On milestones (task done, key decision, new facts learned), call memory_remember.\",\n\t\t\"- Use kind=decision for tradeoffs, kind=change for outcomes, kind=discovery/exploration for useful findings.\",\n\t\t\"- Keep titles short and bodies high-signal.\",\n\t\t\"- ALWAYS pass the project parameter if known.\",\n\t\t\"\",\n\t\t\"Safety:\",\n\t\t\"- Use memory_forget(memory_id) to soft-delete incorrect or obsolete items; this is not secure erasure.\",\n\t\t\"\",\n\t\t\"Examples:\",\n\t\t'- memory_search_index(query=\"billing cache bug\")',\n\t\t\"- memory_timeline(memory_id=123)\",\n\t\t\"- memory_get_observations(ids=[123, 456])\",\n\t\t'- memory_remember(kind=\"decision\", title=\"Use async cache\", body=\"Chose async cache to avoid lock contention in X.\", project=\"my-service\")',\n\t\t'- memory_remember(kind=\"change\", title=\"Fixed retry loop\", body=\"Root cause was Y; added guard in Z.\", project=\"my-service\")',\n\t\t\"- memory_forget(memory_id=123)\",\n\t].join(\"\\n\"),\n} as const;\n\nexport function registerLearnTools(server: McpServer): void {\n\tserver.registerTool(\n\t\t\"memory_learn\",\n\t\t{\n\t\t\tdescription: \"Learn how to use codemem memory tools. Call this first if unfamiliar.\",\n\t\t\tinputSchema: {},\n\t\t\toutputSchema: toolOutputSchemas.memory_learn,\n\t\t\tannotations: toolAnnotations.memory_learn,\n\t\t},\n\t\tasync () => jsonContent(MEMORY_LEARN_GUIDANCE),\n\t);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { jsonContent } from \"../content.js\";\nimport { MEMORY_KINDS } from \"../memory-kinds.js\";\nimport { filterNames } from \"../schemas.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nexport function registerSchemaTools(server: McpServer): void {\n\tserver.registerTool(\n\t\t\"memory_schema\",\n\t\t{\n\t\t\tdescription: \"Return the memory schema — kinds, fields, and available filters.\",\n\t\t\tinputSchema: {},\n\t\t\toutputSchema: toolOutputSchemas.memory_schema,\n\t\t\tannotations: toolAnnotations.memory_schema,\n\t\t},\n\t\tasync () => {\n\t\t\treturn jsonContent({\n\t\t\t\tkinds: Object.keys(MEMORY_KINDS),\n\t\t\t\tkind_descriptions: MEMORY_KINDS,\n\t\t\t\tfields: {\n\t\t\t\t\ttitle: \"short text\",\n\t\t\t\t\tbody: \"long text\",\n\t\t\t\t\tsubtitle: \"short text\",\n\t\t\t\t\tfacts: \"list<string>\",\n\t\t\t\t\tnarrative: \"long text\",\n\t\t\t\t\tconcepts: \"list<string>\",\n\t\t\t\t\tfiles_read: \"list<string>\",\n\t\t\t\t\tfiles_modified: \"list<string>\",\n\t\t\t\t\tprompt_number: \"int\",\n\t\t\t\t},\n\t\t\t\tfilters: filterNames,\n\t\t\t});\n\t\t},\n\t);\n}\n","import type { MemoryResult } from \"@codemem/core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { withMcpRetrieval } from \"../mcp-retrieval-ledger.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst searchInputSchema = {\n\tquery: z.string().describe(\"Search query\"),\n\tlimit: z.number().int().min(1).max(50).default(5).describe(\"Max results\"),\n\t...filterSchema,\n};\n\nconst searchIndexInputSchema = {\n\tquery: z.string().describe(\"Search query\"),\n\tlimit: z.number().int().min(1).max(50).default(8).describe(\"Max results\"),\n\t...filterSchema,\n};\n\nconst explainInputSchema = {\n\tquery: z.string().optional().describe(\"Search query\"),\n\tids: z.array(z.number().int()).max(200).optional().describe(\"Specific memory IDs to explain\"),\n\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max results\"),\n\tinclude_pack_context: z.boolean().default(false).describe(\"Include formatted pack context\"),\n\t...filterSchema,\n};\n\nconst recentInputSchema = {\n\tlimit: z.number().int().min(1).max(100).default(8).describe(\"Max results\"),\n\t...filterSchema,\n};\n\nconst packInputSchema = {\n\tcontext: z.string().describe(\"Context description to search for\"),\n\tlimit: z.number().int().min(1).max(50).optional().describe(\"Max items to include\"),\n\tcompact: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"When true, render a scannable index of all items with full detail only for the top N (default 3). Saves tokens when broad overview matters more than per-item detail.\",\n\t\t),\n\tcompact_detail_count: z\n\t\t.number()\n\t\t.int()\n\t\t.min(0)\n\t\t.max(50)\n\t\t.optional()\n\t\t.describe(\"Number of items to show in full detail in compact mode (default 3)\"),\n\tcompression_mode: z\n\t\t.enum([\"off\", \"compact\", \"ids\"])\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Near-related compression mode: off disables it, compact applies only to compact rendering, ids applies in all modes. Defaults to CODEMEM_PACK_COMPRESSION or compact.\",\n\t\t),\n\t...filterSchema,\n};\n\nexport function registerSearchTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.registerTool(\n\t\t\"memory_search\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Keyword-search memories when you know exact terms or identifiers. Returns full body text for each match; use memory_search_index when you only need compact candidates.\",\n\t\t\tinputSchema: searchInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_search,\n\t\t\tannotations: toolAnnotations.memory_search,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_search\",\n\t\t\t\t\ttoolName: \"memory_search\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.search(args.query, args.limit, filters);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\titems: items.map((m: MemoryResult) => ({\n\t\t\t\t\t\t\t\tid: m.id,\n\t\t\t\t\t\t\t\ttitle: m.title,\n\t\t\t\t\t\t\t\tkind: m.kind,\n\t\t\t\t\t\t\t\tbody: m.body_text,\n\t\t\t\t\t\t\t\tconfidence: m.confidence,\n\t\t\t\t\t\t\t\tscore: m.score,\n\t\t\t\t\t\t\t\tsession_id: m.session_id,\n\t\t\t\t\t\t\t\tmetadata: m.metadata,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmemoryIds: items.map((item) => item.id),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_search_index\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Keyword-search memories when you know exact terms or identifiers. Returns compact entries with IDs and titles, without bodies; expand selected IDs with memory_get or memory_get_observations.\",\n\t\t\tinputSchema: searchIndexInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_search_index,\n\t\t\tannotations: toolAnnotations.memory_search_index,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_search_index\",\n\t\t\t\t\ttoolName: \"memory_search_index\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.search(args.query, args.limit, filters);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\titems: items.map((m: MemoryResult) => ({\n\t\t\t\t\t\t\t\tid: m.id,\n\t\t\t\t\t\t\t\tkind: m.kind,\n\t\t\t\t\t\t\t\ttitle: m.title,\n\t\t\t\t\t\t\t\tscore: m.score,\n\t\t\t\t\t\t\t\tcreated_at: m.created_at,\n\t\t\t\t\t\t\t\tsession_id: m.session_id,\n\t\t\t\t\t\t\t\tmetadata: m.metadata,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmemoryIds: items.map((item) => item.id),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_explain\",\n\t\t{\n\t\t\tdescription: \"Explain search results with detailed scoring breakdown.\",\n\t\t\tinputSchema: explainInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_explain,\n\t\t\tannotations: toolAnnotations.memory_explain,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_explain\",\n\t\t\t\t\ttoolName: \"memory_explain\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst result = store.explain(args.query ?? null, args.ids ?? null, args.limit, filters, {\n\t\t\t\t\t\tincludePackContext: args.include_pack_context,\n\t\t\t\t\t});\n\t\t\t\t\tconst fatalInputError = result.errors.some(\n\t\t\t\t\t\t(error) => error.code === \"INVALID_ARGUMENT\" && error.field === \"query\",\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tvalue: result,\n\t\t\t\t\t\tmemoryIds: result.items.map((item) => item.id),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\tretrievalStatus: fatalInputError ? (\"failed\" as const) : undefined,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_recent\",\n\t\t{\n\t\t\tdescription: \"Return recent memories, newest first.\",\n\t\t\tinputSchema: recentInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_recent,\n\t\t\tannotations: toolAnnotations.memory_recent,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_recent\",\n\t\t\t\t\ttoolName: \"memory_recent\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.recent(args.limit, filters);\n\t\t\t\t\treturn { value: { items }, memoryIds: items.map((item) => item.id), filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_pack\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Build a formatted context block for a concept or task using keyword and semantic search when embeddings are available, with automatic keyword-only fallback. Use for conceptually relevant context; use memory_search or memory_search_index for exact identifiers.\",\n\t\t\tinputSchema: packInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_pack,\n\t\t\tannotations: toolAnnotations.memory_pack,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_pack\",\n\t\t\t\t\ttoolName: \"memory_pack\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.context,\n\t\t\t\t\tlimit: args.limit ?? null,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\tasync (filters) => {\n\t\t\t\t\tconst renderOptions =\n\t\t\t\t\t\targs.compact || args.compact_detail_count != null || args.compression_mode != null\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tcompact: args.compact ?? (args.compact_detail_count != null ? true : undefined),\n\t\t\t\t\t\t\t\t\tcompactDetailCount: args.compact_detail_count,\n\t\t\t\t\t\t\t\t\tcompressionMode: args.compression_mode,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst result = await store.buildMemoryPackAsync(\n\t\t\t\t\t\targs.context,\n\t\t\t\t\t\targs.limit ?? undefined,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\trenderOptions,\n\t\t\t\t\t);\n\t\t\t\t\t// Renderer spans and fingerprints belong to automatic recall, not model context.\n\t\t\t\t\tconst { rendered_items: _renderedItems, ...value } = result;\n\t\t\t\t\treturn { value, memoryIds: result.item_ids, filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n","import { dedupeOrderedIds, type MemoryItemResponse, projectMatchesFilter } from \"@codemem/core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { withMcpRetrieval } from \"../mcp-retrieval-ledger.js\";\nimport { getManyForMcp } from \"../memory-access.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst timelineInputSchema = {\n\tquery: z.string().optional().describe(\"Search query to find anchor\"),\n\tmemory_id: z.number().int().optional().describe(\"Anchor memory ID\"),\n\tdepth_before: z.number().int().min(0).default(3).describe(\"Items before anchor\"),\n\tdepth_after: z.number().int().min(0).default(3).describe(\"Items after anchor\"),\n\t...filterSchema,\n};\n\nconst expandInputSchema = {\n\tids: z\n\t\t.array(z.union([z.number(), z.string()]))\n\t\t.max(200)\n\t\t.describe(\"Memory IDs to expand\"),\n\tdepth_before: z.number().int().min(0).default(3).describe(\"Timeline items before\"),\n\tdepth_after: z.number().int().min(0).default(3).describe(\"Timeline items after\"),\n\tinclude_observations: z.boolean().default(false).describe(\"Include full observation details\"),\n\t...filterSchema,\n};\n\nexport function registerTimelineTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.registerTool(\n\t\t\"memory_timeline\",\n\t\t{\n\t\t\tdescription: \"Get a chronological window of memories around an anchor (by ID or query).\",\n\t\t\tinputSchema: timelineInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_timeline,\n\t\t\tannotations: toolAnnotations.memory_timeline,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_timeline\",\n\t\t\t\t\ttoolName: \"memory_timeline\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.depth_before + args.depth_after + 1,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.timeline(\n\t\t\t\t\t\targs.query ?? null,\n\t\t\t\t\t\targs.memory_id ?? null,\n\t\t\t\t\t\targs.depth_before,\n\t\t\t\t\t\targs.depth_after,\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t);\n\t\t\t\t\treturn { value: { items }, memoryIds: items.map((item) => item.id), filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_expand\",\n\t\t{\n\t\t\tdescription: \"Fetch memories by ID with surrounding timeline context.\",\n\t\t\tinputSchema: expandInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_expand,\n\t\t\tannotations: toolAnnotations.memory_expand,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_expand\",\n\t\t\t\t\ttoolName: \"memory_expand\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: args.ids.length,\n\t\t\t\t\tresolveFilters: () => {\n\t\t\t\t\t\t// Explicit blank `project` clears scoping for cross-project expansion.\n\t\t\t\t\t\t// Only fall back to the server default when `project` is omitted entirely.\n\t\t\t\t\t\tconst filterDefaultProject =\n\t\t\t\t\t\t\targs.project !== undefined && !args.project.trim() ? null : defaultProject();\n\t\t\t\t\t\treturn buildFilters(args, filterDefaultProject);\n\t\t\t\t\t},\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst resolvedProject = filters?.project ?? null;\n\t\t\t\t\tconst { ordered: orderedIds, invalid: invalidIds } = dedupeOrderedIds(args.ids);\n\t\t\t\t\tconst errors: Array<Record<string, unknown>> = [];\n\n\t\t\t\t\tif (invalidIds.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"INVALID_ARGUMENT\",\n\t\t\t\t\t\t\tfield: \"ids\",\n\t\t\t\t\t\t\tmessage: \"some ids are not valid integers\",\n\t\t\t\t\t\t\tids: invalidIds,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tconst missingNotFound: number[] = [];\n\t\t\t\t\tconst missingProjectMismatch: number[] = [];\n\t\t\t\t\tconst missingFilterMismatch: number[] = [];\n\t\t\t\t\tconst anchors: MemoryItemResponse[] = [];\n\t\t\t\t\tconst timelineItems: MemoryItemResponse[] = [];\n\t\t\t\t\tconst timelineSeen = new Set<number>();\n\t\t\t\t\tconst sessionProjects = new Map<number, string | null>();\n\n\t\t\t\t\tfor (const memoryId of orderedIds) {\n\t\t\t\t\t\tconst item = store.get(memoryId);\n\t\t\t\t\t\tif (!item?.active) {\n\t\t\t\t\t\t\tmissingNotFound.push(memoryId);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst sessionId = item.session_id;\n\t\t\t\t\t\tif (resolvedProject && sessionId > 0) {\n\t\t\t\t\t\t\tif (!sessionProjects.has(sessionId)) {\n\t\t\t\t\t\t\t\tconst row = store.db\n\t\t\t\t\t\t\t\t\t.prepare(\"SELECT project FROM sessions WHERE id = ? LIMIT 1\")\n\t\t\t\t\t\t\t\t\t.get(sessionId) as { project: string | null } | undefined;\n\t\t\t\t\t\t\t\tsessionProjects.set(\n\t\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\t\ttypeof row?.project === \"string\" ? row.project : null,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!projectMatchesFilter(resolvedProject, sessionProjects.get(sessionId) ?? null)) {\n\t\t\t\t\t\t\t\tmissingProjectMismatch.push(memoryId);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (resolvedProject && sessionId <= 0) {\n\t\t\t\t\t\t\tmissingProjectMismatch.push(memoryId);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst expanded = store.timeline(\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\t\targs.depth_before,\n\t\t\t\t\t\t\targs.depth_after,\n\t\t\t\t\t\t\tfilters,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst anchor = expanded.find((expandedItem) => expandedItem.id === memoryId);\n\t\t\t\t\t\tif (!anchor) {\n\t\t\t\t\t\t\tmissingFilterMismatch.push(memoryId);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tanchors.push(anchor);\n\t\t\t\t\t\tfor (const expandedItem of expanded) {\n\t\t\t\t\t\t\tconst expandedId = expandedItem.id;\n\t\t\t\t\t\t\tif (expandedId <= 0 || timelineSeen.has(expandedId)) continue;\n\t\t\t\t\t\t\ttimelineSeen.add(expandedId);\n\t\t\t\t\t\t\ttimelineItems.push(expandedItem);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (missingNotFound.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\t\t\tfield: \"ids\",\n\t\t\t\t\t\t\tmessage: \"some requested ids were not found\",\n\t\t\t\t\t\t\tids: missingNotFound,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (missingProjectMismatch.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"PROJECT_MISMATCH\",\n\t\t\t\t\t\t\tfield: \"project\",\n\t\t\t\t\t\t\tmessage: \"some requested ids are outside the requested project scope\",\n\t\t\t\t\t\t\tids: missingProjectMismatch,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (missingFilterMismatch.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"FILTER_MISMATCH\",\n\t\t\t\t\t\t\tfield: \"filters\",\n\t\t\t\t\t\t\tmessage: \"some requested ids are outside the requested filters\",\n\t\t\t\t\t\t\tids: missingFilterMismatch,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlet observations: MemoryItemResponse[] = [];\n\t\t\t\t\tif (args.include_observations) {\n\t\t\t\t\t\tconst observationSeen = new Set<number>();\n\t\t\t\t\t\tconst observationIds: number[] = [];\n\t\t\t\t\t\tfor (const item of [...anchors, ...timelineItems]) {\n\t\t\t\t\t\t\tif (item.id > 0 && !observationSeen.has(item.id)) {\n\t\t\t\t\t\t\t\tobservationSeen.add(item.id);\n\t\t\t\t\t\t\t\tobservationIds.push(item.id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tobservations = getManyForMcp(store, observationIds, filters);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst value = {\n\t\t\t\t\t\tanchors,\n\t\t\t\t\t\ttimeline: timelineItems,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t\tmissing_ids: orderedIds.filter(\n\t\t\t\t\t\t\t(memoryId: number) =>\n\t\t\t\t\t\t\t\tmissingNotFound.includes(memoryId) ||\n\t\t\t\t\t\t\t\tmissingProjectMismatch.includes(memoryId) ||\n\t\t\t\t\t\t\t\tmissingFilterMismatch.includes(memoryId),\n\t\t\t\t\t\t),\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tproject: resolvedProject,\n\t\t\t\t\t\t\trequested_ids_count: orderedIds.length,\n\t\t\t\t\t\t\treturned_anchor_count: anchors.length,\n\t\t\t\t\t\t\ttimeline_count: timelineItems.length,\n\t\t\t\t\t\t\tinclude_observations: args.include_observations,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tconst memoryIds = [\n\t\t\t\t\t\t...new Set([...anchors, ...timelineItems, ...observations].map((item) => item.id)),\n\t\t\t\t\t];\n\t\t\t\t\treturn { value, memoryIds, filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { type MemoryStore, VERSION } from \"@codemem/core\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { resolveDefaultProject } from \"./project-scope.js\";\nimport type { CodememMcpServerOptions, ToolRegistrationContext } from \"./tool-context.js\";\nimport { registerDistillTools } from \"./tools/distill.js\";\nimport { registerItemTools } from \"./tools/items.js\";\nimport { registerLearnTools } from \"./tools/learn.js\";\nimport { registerSchemaTools } from \"./tools/schema.js\";\nimport { registerSearchTools } from \"./tools/search.js\";\nimport { registerTimelineTools } from \"./tools/timeline.js\";\n\nexport function createCodememMcpServer(\n\tstore: MemoryStore,\n\toptions: CodememMcpServerOptions = {},\n): McpServer {\n\tconst server = new McpServer({ name: \"codemem\", version: VERSION });\n\tconst context: ToolRegistrationContext = {\n\t\tstore,\n\t\t// Resolve lazily per call so long-running servers pick up the current\n\t\t// CODEMEM_PROJECT / process.cwd() rather than the value at construction.\n\t\tdefaultProject: () => {\n\t\t\tif (options.resolveDefaultProject) return options.resolveDefaultProject();\n\t\t\tif (options.defaultProject !== undefined) return options.defaultProject;\n\t\t\treturn resolveDefaultProject();\n\t\t},\n\t\tenvProject: () =>\n\t\t\toptions.envProject !== undefined ? options.envProject : (process.env.CODEMEM_PROJECT ?? null),\n\t\tcaptureRetrievalLedger: options.captureRetrievalLedger !== false,\n\t\tretrievalLedgerScopeId: options.retrievalLedgerScopeId ?? randomUUID(),\n\t\tretrievalLedgerIdentityMode: options.retrievalLedgerIdentityMode ?? \"session\",\n\t};\n\n\tregisterSearchTools(server, context);\n\tregisterTimelineTools(server, context);\n\tregisterDistillTools(server, context);\n\tregisterItemTools(server, context);\n\tregisterSchemaTools(server);\n\tregisterLearnTools(server);\n\n\treturn server;\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,EAAc,GAAwB;CACrD,OACC,KAAK,UAAU,IAAQ,GAAM,MACA,OAAO,KAAgB,aAA/C,KAA2D,MAAM,QAAQ,CAAW,IAChF,IAED,OAAO,YACb,OAAO,QAAQ,CAAsC,CAAC,CAAC,UAAU,CAAC,IAAO,CAAC,OACzE,IAAO,IAAQ,KAAK,MAAO,EAC5B,CACD,CACA,KAAK;AAER;;;ACXA,SAAS,EAAa,GAAiD;CAEtE,OADgB,GAAO,KAAK,KACD;AAC5B;AAEA,SAAgB,IAAuC;CACtD,OAAO,EAAa,QAAQ,IAAI,eAAe,KAAK,EAAe,QAAQ,IAAI,CAAC;AACjF;AAEA,SAAgB,GAAoB,GAGlB;CACjB,OAAO,EAAa,EAAM,OAA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AAO,GACnC,GAAsB,GAAQ,CAAO,GACrC,EAAqB,GAAQ,CAAO,GACpC,GAAkB,GAAQ,CAAO,GACjC,GAAoB,CAAM,GAC1B,GAAmB,CAAM,GAElB;AACR"}
|
package/dist/stdio.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { t as e } from "./server-
|
|
2
|
+
import { t as e } from "./server-C-Z_tmAr.js";
|
|
3
3
|
import { MemoryStore as t, probeCodememViewerLiveness as n, resolveDbPath as r } from "@codemem/core";
|
|
4
4
|
import { existsSync as i } from "node:fs";
|
|
5
5
|
import { dirname as a, join as o } from "node:path";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"items.d.ts","sourceRoot":"","sources":["../../src/tools/items.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"items.d.ts","sourceRoot":"","sources":["../../src/tools/items.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAYzE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAoJlE,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAK3F"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codemem/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0-beta.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"exports": {
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"dist/"
|
|
28
28
|
],
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@codemem/core": "^0.
|
|
31
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
30
|
+
"@codemem/core": "^0.47.0-beta.2",
|
|
31
|
+
"@modelcontextprotocol/sdk": "^1.32.0",
|
|
32
32
|
"express": "^5.2.1",
|
|
33
33
|
"express-rate-limit": "^8.7.0",
|
|
34
34
|
"zod": "^4.5.4"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server-DmdZAo6k.js","names":[],"sources":["../src/canonical-json.ts","../src/project-scope.ts","../src/content.ts","../src/schemas.ts","../src/tool-contracts.ts","../src/tools/distill.ts","../src/mcp-retrieval-ledger.ts","../src/memory-access.ts","../src/tools/items.ts","../src/tools/learn.ts","../src/tools/schema.ts","../src/tools/search.ts","../src/tools/timeline.ts","../src/server.ts"],"sourcesContent":["export function canonicalJson(value: unknown): string {\n\treturn (\n\t\tJSON.stringify(value, (_key, nestedValue) => {\n\t\t\tif (nestedValue === null || typeof nestedValue !== \"object\" || Array.isArray(nestedValue)) {\n\t\t\t\treturn nestedValue;\n\t\t\t}\n\t\t\treturn Object.fromEntries(\n\t\t\t\tObject.entries(nestedValue as Record<string, unknown>).toSorted(([left], [right]) =>\n\t\t\t\t\tleft < right ? -1 : left > right ? 1 : 0,\n\t\t\t\t),\n\t\t\t);\n\t\t}) ?? \"undefined\"\n\t);\n}\n","import { type MemoryFilters, resolveProject } from \"@codemem/core\";\n\nfunction cleanProject(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nexport function resolveDefaultProject(): string | null {\n\treturn cleanProject(process.env.CODEMEM_PROJECT) ?? resolveProject(process.cwd());\n}\n\nexport function resolveWriteProject(input: {\n\tproject?: string | null;\n\tenvProject?: string | null;\n}): string | null {\n\treturn cleanProject(input.project) ?? cleanProject(input.envProject) ?? null;\n}\n\nexport function buildFilters(\n\traw: Record<string, unknown>,\n\tdefaultProject = resolveDefaultProject(),\n): MemoryFilters | undefined {\n\tconst filters: MemoryFilters = {};\n\tlet hasAny = false;\n\n\tconst explicitProject = typeof raw.project === \"string\" ? cleanProject(raw.project) : undefined;\n\tconst resolvedProject = explicitProject || cleanProject(defaultProject) || undefined;\n\tif (resolvedProject) {\n\t\tfilters.project = resolvedProject;\n\t\thasAny = true;\n\t}\n\n\tfor (const key of [\n\t\t\"kind\",\n\t\t\"visibility\",\n\t\t\"scope_id\",\n\t\t\"include_scope_ids\",\n\t\t\"exclude_scope_ids\",\n\t\t\"include_visibility\",\n\t\t\"exclude_visibility\",\n\t\t\"include_workspace_ids\",\n\t\t\"exclude_workspace_ids\",\n\t\t\"include_workspace_kinds\",\n\t\t\"exclude_workspace_kinds\",\n\t\t\"include_actor_ids\",\n\t\t\"exclude_actor_ids\",\n\t\t\"include_trust_states\",\n\t\t\"exclude_trust_states\",\n\t\t\"ownership_scope\",\n\t\t\"personal_first\",\n\t\t\"trust_bias\",\n\t\t\"widen_shared_when_weak\",\n\t\t\"widen_shared_min_personal_results\",\n\t\t\"widen_shared_min_personal_score\",\n\t] as const) {\n\t\tconst val = raw[key];\n\t\tif (val !== undefined && val !== null) {\n\t\t\t(filters as Record<string, unknown>)[key] = val;\n\t\t\thasAny = true;\n\t\t}\n\t}\n\n\treturn hasAny ? filters : undefined;\n}\n","function parseStructuredObject(text: string): Record<string, unknown> {\n\tconst value: unknown = JSON.parse(text);\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new TypeError(\"MCP structured content must be a JSON object\");\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nexport function jsonContent(data: unknown) {\n\tconst text = JSON.stringify(data);\n\tif (text === undefined) throw new TypeError(\"MCP structured content must be JSON serializable\");\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text }],\n\t\tstructuredContent: parseStructuredObject(text),\n\t};\n}\n\nexport function errorContent(message: string) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text: JSON.stringify({ error: message }) }],\n\t\tisError: true,\n\t};\n}\n","import { REMEMBER_MEMORY_KINDS } from \"@codemem/core\";\nimport { z } from \"zod\";\n\nconst scopeFilterSchema = {\n\tscope_id: z.string().optional().describe(\"Filter by a single sharing domain scope_id\"),\n\tinclude_scope_ids: z.array(z.string()).optional().describe(\"Sharing domain scope_ids to include\"),\n\texclude_scope_ids: z.array(z.string()).optional().describe(\"Sharing domain scope_ids to exclude\"),\n};\n\nexport const filterSchema = {\n\tkind: z.string().optional().describe(\"Filter by memory kind\"),\n\tproject: z.string().optional().describe(\"Filter by project scope (matches sessions.project)\"),\n\t...scopeFilterSchema,\n\tvisibility: z.array(z.string()).optional(),\n\tinclude_visibility: z.array(z.string()).optional(),\n\texclude_visibility: z.array(z.string()).optional(),\n\tinclude_workspace_ids: z.array(z.string()).optional(),\n\texclude_workspace_ids: z.array(z.string()).optional(),\n\tinclude_workspace_kinds: z.array(z.string()).optional(),\n\texclude_workspace_kinds: z.array(z.string()).optional(),\n\tinclude_actor_ids: z.array(z.string()).optional(),\n\texclude_actor_ids: z.array(z.string()).optional(),\n\tinclude_trust_states: z.array(z.string()).optional(),\n\texclude_trust_states: z.array(z.string()).optional(),\n\townership_scope: z.string().optional(),\n\tpersonal_first: z.union([z.boolean(), z.string()]).optional(),\n\ttrust_bias: z.string().optional(),\n\twiden_shared_when_weak: z.union([z.boolean(), z.string()]).optional(),\n\twiden_shared_min_personal_results: z.number().int().optional(),\n\twiden_shared_min_personal_score: z.number().optional(),\n};\n\nexport const memoryKindSchema = z.enum(REMEMBER_MEMORY_KINDS);\n\nexport const filterNames = Object.keys(filterSchema).toSorted();\n","import type { ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\n\nconst metadataSchema = z.record(z.string(), z.unknown());\n// The column has a default but no NOT NULL constraint, and legacy rows can emit null.\nconst confidenceSchema = z.number().nullable();\n\nconst storedMemorySchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tbody_text: z.string(),\n\t\tsession_id: z.number().int().optional(),\n\t\tconfidence: confidenceSchema.optional(),\n\t\tcreated_at: z.string().optional(),\n\t\tupdated_at: z.string().optional(),\n\t\tmetadata_json: metadataSchema.optional(),\n\t})\n\t.passthrough();\n\nconst searchMemorySchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tbody: z.string(),\n\t\tconfidence: confidenceSchema.optional(),\n\t\tscore: z.number().optional(),\n\t\tsession_id: z.number().int().optional(),\n\t\tmetadata: metadataSchema.optional(),\n\t})\n\t.passthrough();\n\nconst indexMemorySchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tscore: z.number(),\n\t\tcreated_at: z.string(),\n\t\tsession_id: z.number().int(),\n\t\tmetadata: metadataSchema,\n\t})\n\t.passthrough();\n\nconst errorDetailSchema = z\n\t.object({\n\t\tcode: z.string(),\n\t\tfield: z.string(),\n\t\tmessage: z.string(),\n\t\tids: z.array(z.union([z.string(), z.number()])).optional(),\n\t})\n\t.passthrough();\n\nconst explainItemSchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tcreated_at: z.string(),\n\t\tproject: z.string().nullable(),\n\t\tretrieval: z.object({ source: z.string(), rank: z.number().int().nullable() }).passthrough(),\n\t\tscore: z\n\t\t\t.object({\n\t\t\t\ttotal: z.number().nullable(),\n\t\t\t\tcomponents: z\n\t\t\t\t\t.object({\n\t\t\t\t\t\tbase: z.number().nullable(),\n\t\t\t\t\t\trecency: z.number(),\n\t\t\t\t\t\tkind_bonus: z.number(),\n\t\t\t\t\t\tpersonal_bias: z.number(),\n\t\t\t\t\t\tsemantic_boost: z.number().nullable(),\n\t\t\t\t\t})\n\t\t\t\t\t.passthrough(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t\trole: z.object({ inferred: z.string(), reason: z.string() }).passthrough(),\n\t\tmatches: z\n\t\t\t.object({ query_terms: z.array(z.string()), project_match: z.boolean().nullable() })\n\t\t\t.passthrough(),\n\t\tpack_context: z\n\t\t\t.object({ included: z.boolean().nullable(), section: z.string().nullable() })\n\t\t\t.passthrough()\n\t\t\t.nullable(),\n\t})\n\t.passthrough();\n\nconst packItemSchema = z\n\t.object({\n\t\tid: z.number().int(),\n\t\tkind: z.string(),\n\t\ttitle: z.string(),\n\t\tbody: z.string(),\n\t\tconfidence: confidenceSchema,\n\t\tmetadata: metadataSchema,\n\t})\n\t.passthrough();\n\nconst stringListSectionSchema = z\n\t.object({\n\t\twhen: z.array(z.string()),\n\t\thow: z.array(z.string()),\n\t\texamples: z.array(z.string()),\n\t})\n\t.passthrough();\n\nexport const toolOutputSchemas = {\n\tmemory_search: z.object({ items: z.array(searchMemorySchema) }),\n\tmemory_search_index: z.object({ items: z.array(indexMemorySchema) }),\n\tmemory_explain: z.object({\n\t\titems: z.array(explainItemSchema),\n\t\tmissing_ids: z.array(z.number().int()),\n\t\terrors: z.array(errorDetailSchema),\n\t\tmetadata: z\n\t\t\t.object({\n\t\t\t\tquery: z.string().nullable(),\n\t\t\t\tproject: z.string().nullable(),\n\t\t\t\trequested_ids_count: z.number().int(),\n\t\t\t\treturned_items_count: z.number().int(),\n\t\t\t\tinclude_pack_context: z.boolean(),\n\t\t\t\tsanitized_query: z.string().optional(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_recent: z.object({ items: z.array(storedMemorySchema) }),\n\tmemory_pack: z.object({\n\t\tcontext: z.string(),\n\t\titems: z.array(packItemSchema),\n\t\titem_ids: z.array(z.number().int()),\n\t\tpack_text: z.string(),\n\t\tmetrics: z\n\t\t\t.object({\n\t\t\t\ttotal_items: z.number().int(),\n\t\t\t\tpack_tokens: z.number().int(),\n\t\t\t\tfallback_used: z.boolean(),\n\t\t\t\tlimit: z.number().int(),\n\t\t\t\tproject: z.string().nullable(),\n\t\t\t\tpack_item_ids: z.array(z.number().int()),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_timeline: z.object({ items: z.array(storedMemorySchema) }),\n\tmemory_expand: z.object({\n\t\tanchors: z.array(storedMemorySchema),\n\t\ttimeline: z.array(storedMemorySchema),\n\t\tobservations: z.array(storedMemorySchema),\n\t\tmissing_ids: z.array(z.number().int()),\n\t\terrors: z.array(errorDetailSchema),\n\t\tmetadata: z\n\t\t\t.object({\n\t\t\t\tproject: z.string().nullable(),\n\t\t\t\trequested_ids_count: z.number().int(),\n\t\t\t\treturned_anchor_count: z.number().int(),\n\t\t\t\ttimeline_count: z.number().int(),\n\t\t\t\tinclude_observations: z.boolean(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_get: storedMemorySchema,\n\tmemory_get_observations: z.object({ items: z.array(storedMemorySchema) }),\n\tmemory_remember: z.object({ id: z.number().int() }),\n\tmemory_forget: z.object({ status: z.literal(\"ok\") }),\n\tmemory_distill_candidates: z.object({\n\t\tversion: z.literal(1),\n\t\tcandidates: z.array(\n\t\t\tz\n\t\t\t\t.object({\n\t\t\t\t\tscope: z.enum([\"project\", \"user\"]),\n\t\t\t\t\tsuggested_target: z.string().nullable(),\n\t\t\t\t\tscore: z.number(),\n\t\t\t\t\trecurrence: z.number().int(),\n\t\t\t\t\tprojects: z.array(z.string()),\n\t\t\t\t\tmember_ids: z.array(z.number().int()),\n\t\t\t\t\trepresentative_id: z.number().int(),\n\t\t\t\t\tconcepts: z.array(z.string()),\n\t\t\t\t\tartifact_kind: z.enum([\"context_fact\", \"skill\"]),\n\t\t\t\t\tevidence: z.array(z.string()),\n\t\t\t\t\tdraft_text: z.string().nullable(),\n\t\t\t\t})\n\t\t\t\t.passthrough(),\n\t\t),\n\t\tmetadata: z\n\t\t\t.object({\n\t\t\t\tcandidate_count: z.number().int(),\n\t\t\t\tcluster_count: z.number().int(),\n\t\t\t\tcontext_document_count: z.number().int(),\n\t\t\t\tcorpus_count: z.number().int(),\n\t\t\t\tcorpus_limit: z.number().int(),\n\t\t\t\tdocumented_cluster_count: z.number().int(),\n\t\t\t\tinclude_documented: z.boolean(),\n\t\t\t\tmin_recurrence: z.number().int(),\n\t\t\t})\n\t\t\t.passthrough(),\n\t}),\n\tmemory_schema: z.object({\n\t\tkinds: z.array(z.string()),\n\t\tkind_descriptions: z.record(z.string(), z.string()),\n\t\tfields: z.record(z.string(), z.string()),\n\t\tfilters: z.array(z.string()),\n\t}),\n\tmemory_learn: z.object({\n\t\tintro: z.string(),\n\t\tclient_hint: z.string(),\n\t\trecall: stringListSectionSchema,\n\t\tpersistence: stringListSectionSchema,\n\t\tforget: stringListSectionSchema,\n\t\tprompt_hint: z.string(),\n\t\trecommended_system_prompt: z.string(),\n\t}),\n} as const;\n\n// Incidental diagnostics and caches do not change the primary read operation.\nconst localReadAnnotations = {\n\treadOnlyHint: true,\n\topenWorldHint: false,\n} satisfies ToolAnnotations;\n\n// Pack/distill remain read-only while model loading or observer calls may access\n// entities outside the local store.\nconst externalReadAnnotations = {\n\treadOnlyHint: true,\n\topenWorldHint: true,\n} satisfies ToolAnnotations;\n\nexport const toolAnnotations = {\n\tmemory_search: localReadAnnotations,\n\tmemory_search_index: localReadAnnotations,\n\tmemory_explain: localReadAnnotations,\n\tmemory_recent: localReadAnnotations,\n\tmemory_pack: externalReadAnnotations,\n\tmemory_timeline: localReadAnnotations,\n\tmemory_expand: localReadAnnotations,\n\tmemory_get: localReadAnnotations,\n\tmemory_get_observations: localReadAnnotations,\n\t// Remember is additive, but embedding generation can load external model assets.\n\tmemory_remember: {\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: false,\n\t\tidempotentHint: false,\n\t\topenWorldHint: true,\n\t},\n\t// Repeating a soft delete has no additional environmental effect.\n\tmemory_forget: {\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false,\n\t},\n\tmemory_distill_candidates: externalReadAnnotations,\n\tmemory_schema: localReadAnnotations,\n\tmemory_learn: localReadAnnotations,\n} as const satisfies Record<keyof typeof toolOutputSchemas, ToolAnnotations>;\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n\tbuildDistillReport,\n\ttype DistillContextDocument,\n\tjudgeDistillReport,\n\ttype MemoryFilters,\n\tObserverClient,\n\tprojectMatchesFilter,\n\tresolveProject,\n\tresolveProjectRoot,\n} from \"@codemem/core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { errorContent, jsonContent } from \"../content.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst distillInputSchema = {\n\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max candidates\"),\n\tmin_recurrence: z\n\t\t.number()\n\t\t.int()\n\t\t.min(1)\n\t\t.max(50)\n\t\t.default(2)\n\t\t.describe(\"Minimum member count per candidate\"),\n\tall_projects: z.boolean().default(false).describe(\"Mine memories across all projects\"),\n\tinclude_documented: z\n\t\t.boolean()\n\t\t.default(false)\n\t\t.describe(\"Include candidates already represented in context files\"),\n\tmax_evidence_items: z\n\t\t.number()\n\t\t.int()\n\t\t.min(1)\n\t\t.max(20)\n\t\t.default(5)\n\t\t.describe(\"Evidence snippets per candidate\"),\n\tjudge: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe(\n\t\t\t\"Judge candidates with the observer model and drop routine-activity clusters (on by default; falls back to unjudged output when no observer model is configured)\",\n\t\t),\n\t...filterSchema,\n};\n\nfunction readContextFile(\n\tpath: string,\n\tdisplayPath: string,\n\tscope: DistillContextDocument[\"scope\"],\n): DistillContextDocument | null {\n\tif (!existsSync(path)) return null;\n\tconst text = readFileSync(path, \"utf8\");\n\treturn text.trim() ? { path: displayPath, text, scope } : null;\n}\n\nfunction loadDefaultContextDocuments(\n\tincludeProjectContext: boolean,\n\tcwd = process.cwd(),\n): DistillContextDocument[] {\n\t// The repo-root AGENTS.md describes the current repo (scope \"project\") and is\n\t// gated to current-project runs; the user-global context (scope \"user\")\n\t// always applies and never suppresses other projects' candidates. Resolve the\n\t// repo root so running from a subdirectory still finds the project context.\n\tconst projectRoot = resolveProjectRoot(cwd) ?? cwd;\n\tconst documents = [\n\t\tincludeProjectContext\n\t\t\t? readContextFile(join(projectRoot, \"AGENTS.md\"), \"AGENTS.md\", \"project\")\n\t\t\t: null,\n\t\treadContextFile(\n\t\t\tjoin(homedir(), \".config\", \"opencode\", \"AGENTS.md\"),\n\t\t\t\"~/.config/opencode/AGENTS.md\",\n\t\t\t\"user\",\n\t\t),\n\t];\n\treturn documents.filter((document): document is DistillContextDocument => document != null);\n}\n\nfunction shouldIncludeProjectContext(\n\targs: { all_projects?: boolean; project?: unknown },\n\tdefaultProject: string | null,\n): boolean {\n\tif (args.all_projects) return false;\n\tconst currentProject = resolveProject(process.cwd());\n\tif (!currentProject) return false;\n\tconst explicitProject = typeof args.project === \"string\" ? args.project.trim() : \"\";\n\t// Match the corpus filter: the cwd AGENTS.md is only valid when the mined\n\t// project (explicit arg or the server default project) is this repo.\n\tconst targetProject = explicitProject\n\t\t? resolveProject(process.cwd(), explicitProject)\n\t\t: defaultProject;\n\tif (!targetProject) return false;\n\treturn projectMatchesFilter(targetProject, currentProject);\n}\n\nfunction buildDistillFilters(\n\targs: { all_projects?: boolean } & Record<string, unknown>,\n\tdefaultProject: string | null,\n): MemoryFilters | undefined {\n\tif (args.all_projects && typeof args.project === \"string\" && args.project.trim()) {\n\t\tthrow new Error(\"project cannot be combined with all_projects\");\n\t}\n\treturn buildFilters(args, args.all_projects ? null : defaultProject);\n}\n\nexport function registerDistillTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.registerTool(\n\t\t\"memory_distill_candidates\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Mine recurring memories into reviewable context candidates. Reads project/user context files without modifying them and can call the optional observer when judge=true.\",\n\t\t\tinputSchema: distillInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_distill_candidates,\n\t\t\tannotations: toolAnnotations.memory_distill_candidates,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\tconst resolvedDefaultProject = defaultProject();\n\t\t\t\tconst filters = buildDistillFilters(args, resolvedDefaultProject);\n\t\t\t\tconst kinds = args.kind ? [args.kind] : undefined;\n\t\t\t\t// When judging, mine extra candidates so routine drops are backfilled\n\t\t\t\t// from the next-ranked clusters instead of shrinking the caller's limit.\n\t\t\t\tconst fetchLimit = args.judge ? Math.min(args.limit * 3, args.limit + 20) : args.limit;\n\t\t\t\tlet result = await buildDistillReport(store, {\n\t\t\t\t\tcandidate: {\n\t\t\t\t\t\tincludeDocumented: args.include_documented,\n\t\t\t\t\t\tmaxEvidenceItems: args.max_evidence_items,\n\t\t\t\t\t},\n\t\t\t\t\tcontextDocuments: loadDefaultContextDocuments(\n\t\t\t\t\t\tshouldIncludeProjectContext(args, resolvedDefaultProject),\n\t\t\t\t\t),\n\t\t\t\t\tcorpus: { filters: filters ?? null, kinds },\n\t\t\t\t\tlimit: fetchLimit,\n\t\t\t\t\tminRecurrence: args.min_recurrence,\n\t\t\t\t});\n\t\t\t\tif (args.judge) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst client = new ObserverClient();\n\t\t\t\t\t\tresult = await judgeDistillReport(result, async (system, user) => {\n\t\t\t\t\t\t\tconst response = await client.observe(system, user);\n\t\t\t\t\t\t\treturn response.raw;\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t// Fall back to unjudged output rather than failing the tool —\n\t\t\t\t\t\t// the caller sees judged:false + judge_error and can decide.\n\t\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\tresult = {\n\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\tmetadata: { ...result.metadata, judged: false, judge_error: message },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tif (result.candidates.length > args.limit) {\n\t\t\t\t\t\tresult = {\n\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\tcandidates: result.candidates.slice(0, args.limit),\n\t\t\t\t\t\t\tmetadata: { ...result.metadata, candidate_count: args.limit },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonContent(result);\n\t\t\t} catch (err) {\n\t\t\t\treturn errorContent(err instanceof Error ? err.message : String(err));\n\t\t\t}\n\t\t},\n\t);\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n\ttype MemoryFilters,\n\ttype RetrievalStatus,\n\ttype RetrievalSurface,\n\treconcileFailedRetrievalSurface,\n\trecordRetrievalSurface,\n} from \"@codemem/core\";\nimport { canonicalJson } from \"./canonical-json.js\";\nimport { errorContent, jsonContent } from \"./content.js\";\nimport type { ToolRegistrationContext } from \"./tool-context.js\";\n\nexport interface McpRetrievalResult<T> {\n\tvalue: T;\n\tmemoryIds: number[];\n\tcandidateCount?: number;\n\tfilters?: MemoryFilters;\n\tretrievalStatus?: RetrievalStatus;\n\terror?: string;\n}\n\ninterface McpRetrievalInput {\n\tsurface: RetrievalSurface;\n\ttoolName: string;\n\ttoolArguments: unknown;\n\tquery?: string | null;\n\tlimit?: number | null;\n\tresolveFilters?: () => MemoryFilters | undefined;\n\trequestId?: string | number;\n\tsourceSessionId?: string | null;\n\tinvocationIdentity?: object;\n}\n\nconst MCP_SESSION_RETRY_TTL_MS = 5 * 60 * 1000;\nconst MCP_SESSION_RETRY_MAX_ENTRIES = 2000;\n\ninterface InvocationLedgerIdentity {\n\tbaseRequestId: string | null;\n\trequestId: string | null;\n\tattemptId: string;\n}\n\ninterface PendingFailure {\n\tidentity: InvocationLedgerIdentity;\n\texpiresAt: number;\n\torder: number;\n}\n\ninterface SessionIdentityTracker {\n\tbyInvocation: WeakMap<object, InvocationLedgerIdentity>;\n\tactiveByRequest: Map<string, number>;\n\tpendingFailures: Map<string, PendingFailure[]>;\n\tpendingFailureCount: number;\n\tnextPendingFailureOrder: number;\n\tnextInvocationSequence: number;\n}\n\n// Track only live invocation objects and per-base FIFO failure queues. Pending\n// identities expire after five minutes and are capped at 2,000 entries total.\n// The outer WeakMap releases the whole tracker with its server registration context.\nconst sessionIdentityTrackers = new WeakMap<ToolRegistrationContext, SessionIdentityTracker>();\nlet fallbackAttemptSequence = 0;\n\nfunction recordMcpRetrieval(\n\tcontext: ToolRegistrationContext,\n\tinput: Parameters<typeof recordRetrievalSurface>[1],\n\treconcileTransientFailure: boolean,\n): void {\n\tif (!context.captureRetrievalLedger) return;\n\ttry {\n\t\tconst outcome = recordRetrievalSurface(context.store.db, input);\n\t\tif (\n\t\t\treconcileTransientFailure &&\n\t\t\t!outcome.ok &&\n\t\t\toutcome.reason === \"idempotency_conflict\" &&\n\t\t\t((input.retrievalStatus === \"succeeded\" && input.deliveryStatus === \"handed_off\") ||\n\t\t\t\t(input.retrievalStatus === \"no_results\" && input.deliveryStatus === \"not_attempted\"))\n\t\t) {\n\t\t\treconcileFailedRetrievalSurface(context.store.db, input);\n\t\t}\n\t} catch {\n\t\t// MCP responses must remain independent from local diagnostics.\n\t}\n}\n\nfunction requestAttemptId(requestId: string | null): string {\n\tif (requestId == null) return randomUUID();\n\tconst hex = requestId.slice(0, 32).split(\"\");\n\thex[12] = \"5\";\n\thex[16] = ((Number.parseInt(hex[16] ?? \"0\", 16) & 0x3) | 0x8).toString(16);\n\tconst value = hex.join(\"\");\n\treturn `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;\n}\n\nfunction baseRequestIdentity(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n): string | null {\n\tif (input.requestId == null) return null;\n\tconst callContentDigest = createHash(\"sha256\")\n\t\t.update(\n\t\t\tcanonicalJson({\n\t\t\t\tmethod: \"tools/call\",\n\t\t\t\tparams: { name: input.toolName, arguments: input.toolArguments },\n\t\t\t}),\n\t\t)\n\t\t.digest(\"hex\");\n\treturn createHash(\"sha256\")\n\t\t.update(\n\t\t\tJSON.stringify([\n\t\t\t\tinput.sourceSessionId ?? context.retrievalLedgerScopeId,\n\t\t\t\tinput.requestId,\n\t\t\t\tcallContentDigest,\n\t\t\t]),\n\t\t)\n\t\t.digest(\"hex\");\n}\n\nfunction sessionIdentityTracker(context: ToolRegistrationContext): SessionIdentityTracker {\n\tlet tracker = sessionIdentityTrackers.get(context);\n\tif (!tracker) {\n\t\ttracker = {\n\t\t\tbyInvocation: new WeakMap(),\n\t\t\tactiveByRequest: new Map(),\n\t\t\tpendingFailures: new Map(),\n\t\t\tpendingFailureCount: 0,\n\t\t\tnextPendingFailureOrder: 0,\n\t\t\tnextInvocationSequence: 0,\n\t\t};\n\t\tsessionIdentityTrackers.set(context, tracker);\n\t}\n\treturn tracker;\n}\n\nfunction prunePendingFailures(tracker: SessionIdentityTracker, now: number): void {\n\tfor (const [requestId, pending] of tracker.pendingFailures) {\n\t\tconst retained = pending.filter((entry) => entry.expiresAt > now);\n\t\ttracker.pendingFailureCount -= pending.length - retained.length;\n\t\tif (retained.length === 0) tracker.pendingFailures.delete(requestId);\n\t\telse if (retained.length !== pending.length) tracker.pendingFailures.set(requestId, retained);\n\t}\n\twhile (tracker.pendingFailureCount > MCP_SESSION_RETRY_MAX_ENTRIES) {\n\t\tlet oldestRequestId: string | undefined;\n\t\tlet oldestOrder = Number.POSITIVE_INFINITY;\n\t\tfor (const [requestId, pending] of tracker.pendingFailures) {\n\t\t\tconst order = pending[0]?.order;\n\t\t\tif (order != null && order < oldestOrder) {\n\t\t\t\toldestRequestId = requestId;\n\t\t\t\toldestOrder = order;\n\t\t\t}\n\t\t}\n\t\tif (oldestRequestId === undefined) break;\n\t\tconst pending = tracker.pendingFailures.get(oldestRequestId);\n\t\tconst removed = pending?.shift();\n\t\tif (!pending || !removed) {\n\t\t\ttracker.pendingFailures.delete(oldestRequestId);\n\t\t\tcontinue;\n\t\t}\n\t\ttracker.pendingFailureCount -= 1;\n\t\tif (pending.length === 0) tracker.pendingFailures.delete(oldestRequestId);\n\t}\n}\n\nfunction takePendingFailure(\n\ttracker: SessionIdentityTracker,\n\tbaseRequestId: string,\n): InvocationLedgerIdentity | undefined {\n\tconst pending = tracker.pendingFailures.get(baseRequestId);\n\tif (!pending) return undefined;\n\tconst failure = pending.shift();\n\tif (!failure) return undefined;\n\ttracker.pendingFailureCount -= 1;\n\tif (pending.length === 0) tracker.pendingFailures.delete(baseRequestId);\n\treturn failure.identity;\n}\n\nfunction removePendingFailure(\n\ttracker: SessionIdentityTracker,\n\tbaseRequestId: string,\n\tattemptId: string,\n): void {\n\tconst pending = tracker.pendingFailures.get(baseRequestId);\n\tconst index = pending?.findIndex((entry) => entry.identity.attemptId === attemptId) ?? -1;\n\tif (!pending || index < 0) return;\n\tpending.splice(index, 1);\n\ttracker.pendingFailureCount -= 1;\n\tif (pending.length === 0) tracker.pendingFailures.delete(baseRequestId);\n}\n\nfunction enqueuePendingFailure(\n\ttracker: SessionIdentityTracker,\n\tbaseRequestId: string,\n\tidentity: InvocationLedgerIdentity,\n\tnow: number,\n): void {\n\tconst pending = tracker.pendingFailures.get(baseRequestId) ?? [];\n\tif (pending.some((entry) => entry.identity.attemptId === identity.attemptId)) return;\n\tpending.push({\n\t\tidentity,\n\t\texpiresAt: now + MCP_SESSION_RETRY_TTL_MS,\n\t\torder: tracker.nextPendingFailureOrder,\n\t});\n\ttracker.nextPendingFailureOrder += 1;\n\ttracker.pendingFailures.set(baseRequestId, pending);\n\ttracker.pendingFailureCount += 1;\n\tprunePendingFailures(tracker, now);\n}\n\nfunction fallbackInvocationIdentity(): InvocationLedgerIdentity {\n\ttry {\n\t\treturn { baseRequestId: null, requestId: null, attemptId: randomUUID() };\n\t} catch {\n\t\tconst timestamp = Date.now().toString(16).slice(-8).padStart(8, \"0\");\n\t\tconst sequence = fallbackAttemptSequence.toString(16).slice(-4).padStart(4, \"0\");\n\t\tfallbackAttemptSequence = (fallbackAttemptSequence + 1) % 0x1_0000;\n\t\treturn {\n\t\t\tbaseRequestId: null,\n\t\t\trequestId: null,\n\t\t\tattemptId: `00000000-0000-4000-8000-${timestamp}${sequence}`,\n\t\t};\n\t}\n}\n\nfunction beginInvocation(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n): InvocationLedgerIdentity {\n\tconst baseRequestId = baseRequestIdentity(context, input);\n\tif (context.retrievalLedgerIdentityMode === \"stateless\" || baseRequestId == null) {\n\t\treturn {\n\t\t\tbaseRequestId,\n\t\t\trequestId: baseRequestId,\n\t\t\tattemptId: requestAttemptId(baseRequestId),\n\t\t};\n\t}\n\n\tconst tracker = sessionIdentityTracker(context);\n\tprunePendingFailures(tracker, Date.now());\n\tconst candidateInvocation = input.invocationIdentity\n\t\t? tracker.byInvocation.get(input.invocationIdentity)\n\t\t: undefined;\n\tconst knownInvocation =\n\t\tcandidateInvocation?.baseRequestId === baseRequestId ? candidateInvocation : undefined;\n\tlet identity = knownInvocation;\n\tif (!identity) {\n\t\tconst activeCount = tracker.activeByRequest.get(baseRequestId) ?? 0;\n\t\tconst pending = activeCount === 0 ? takePendingFailure(tracker, baseRequestId) : undefined;\n\t\tif (pending) {\n\t\t\tidentity = pending;\n\t\t} else {\n\t\t\tconst invocationSequence = tracker.nextInvocationSequence;\n\t\t\ttracker.nextInvocationSequence += 1;\n\t\t\tconst requestId = createHash(\"sha256\")\n\t\t\t\t.update(JSON.stringify([baseRequestId, context.retrievalLedgerScopeId, invocationSequence]))\n\t\t\t\t.digest(\"hex\");\n\t\t\tidentity = {\n\t\t\t\tbaseRequestId,\n\t\t\t\trequestId,\n\t\t\t\tattemptId: requestAttemptId(requestId),\n\t\t\t};\n\t\t}\n\t\tif (input.invocationIdentity) tracker.byInvocation.set(input.invocationIdentity, identity);\n\t}\n\ttracker.activeByRequest.set(baseRequestId, (tracker.activeByRequest.get(baseRequestId) ?? 0) + 1);\n\treturn identity;\n}\n\nfunction safeBeginInvocation(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n): InvocationLedgerIdentity {\n\ttry {\n\t\treturn beginInvocation(context, input);\n\t} catch {\n\t\treturn fallbackInvocationIdentity();\n\t}\n}\n\nfunction completeInvocation(\n\tcontext: ToolRegistrationContext,\n\tidentity: InvocationLedgerIdentity,\n\tstatus: \"completed\" | \"failed\",\n): void {\n\tif (context.retrievalLedgerIdentityMode === \"stateless\" || identity.baseRequestId == null) return;\n\tconst tracker = sessionIdentityTracker(context);\n\tconst activeCount = tracker.activeByRequest.get(identity.baseRequestId) ?? 0;\n\tif (activeCount <= 1) tracker.activeByRequest.delete(identity.baseRequestId);\n\telse tracker.activeByRequest.set(identity.baseRequestId, activeCount - 1);\n\n\tif (status === \"failed\") {\n\t\tenqueuePendingFailure(tracker, identity.baseRequestId, identity, Date.now());\n\t} else {\n\t\tremovePendingFailure(tracker, identity.baseRequestId, identity.attemptId);\n\t}\n}\n\nfunction safeCompleteInvocation(\n\tcontext: ToolRegistrationContext,\n\tidentity: InvocationLedgerIdentity,\n\tstatus: \"completed\" | \"failed\",\n): void {\n\ttry {\n\t\tcompleteInvocation(context, identity, status);\n\t} catch {\n\t\t// Retrieval diagnostics must never alter the MCP tool result.\n\t}\n}\n\nexport async function withMcpRetrieval<T>(\n\tcontext: ToolRegistrationContext,\n\tinput: McpRetrievalInput,\n\tretrieve: (\n\t\tfilters: MemoryFilters | undefined,\n\t) => McpRetrievalResult<T> | Promise<McpRetrievalResult<T>>,\n) {\n\tconst invocation = safeBeginInvocation(context, input);\n\tconst ledgerRequestId = invocation.requestId;\n\tconst attemptId = invocation.attemptId;\n\tconst startedAt = new Date();\n\tlet filters: MemoryFilters | undefined;\n\ttry {\n\t\tfilters = input.resolveFilters?.();\n\t\tconst output = await retrieve(filters);\n\t\tconst completedAt = new Date();\n\t\tconst response = output.error ? errorContent(output.error) : jsonContent(output.value);\n\t\tconst streamId = input.sourceSessionId ?? context.retrievalLedgerScopeId;\n\t\tconst hasResults = output.memoryIds.length > 0;\n\t\tconst isNotFoundCompletion = output.error === \"not_found\" && !hasResults;\n\t\tconst isFailedResult =\n\t\t\t(output.error != null && !isNotFoundCompletion) ||\n\t\t\t(output.retrievalStatus === \"failed\" && !hasResults);\n\t\tconst recordedMemoryIds = isFailedResult ? [] : output.memoryIds;\n\t\tconst deliveredRetrievalStatus = output.retrievalStatus === \"unknown\" ? \"unknown\" : \"succeeded\";\n\t\trecordMcpRetrieval(\n\t\t\tcontext,\n\t\t\t{\n\t\t\t\tattemptId,\n\t\t\t\tsurface: input.surface,\n\t\t\t\ttrigger: \"explicit\",\n\t\t\t\tstartedAt: startedAt.toISOString(),\n\t\t\t\tcompletedAt: completedAt.toISOString(),\n\t\t\t\tretrievalStatus: isFailedResult\n\t\t\t\t\t? \"failed\"\n\t\t\t\t\t: hasResults\n\t\t\t\t\t\t? deliveredRetrievalStatus\n\t\t\t\t\t\t: \"no_results\",\n\t\t\t\tdeliveryStatus: isFailedResult || !hasResults ? \"not_attempted\" : \"handed_off\",\n\t\t\t\tcandidateIds: recordedMemoryIds,\n\t\t\t\tselectedIds: recordedMemoryIds,\n\t\t\t\tcandidateCount: hasResults && !isFailedResult ? output.candidateCount : 0,\n\t\t\t\trecorderVersion: \"mcp-retrieval-v1\",\n\t\t\t\tsource: \"mcp\",\n\t\t\t\tstreamId,\n\t\t\t\tsourceSessionId: input.sourceSessionId ?? null,\n\t\t\t\trequestId: ledgerRequestId,\n\t\t\t\tlatencyMs: Math.max(0, completedAt.getTime() - startedAt.getTime()),\n\t\t\t\tfilters: output.filters ?? filters,\n\t\t\t\tquery: input.query,\n\t\t\t\tlimitRequested: input.limit,\n\t\t\t\tfailureCode: isFailedResult ? \"tool_failed\" : undefined,\n\t\t\t\tfailureStage: isFailedResult ? \"retrieval\" : undefined,\n\t\t\t},\n\t\t\t!isFailedResult,\n\t\t);\n\t\tsafeCompleteInvocation(context, invocation, isFailedResult ? \"failed\" : \"completed\");\n\t\treturn response;\n\t} catch (error) {\n\t\tconst completedAt = new Date();\n\t\tconst streamId = input.sourceSessionId ?? context.retrievalLedgerScopeId;\n\t\trecordMcpRetrieval(\n\t\t\tcontext,\n\t\t\t{\n\t\t\t\tattemptId,\n\t\t\t\tsurface: input.surface,\n\t\t\t\ttrigger: \"explicit\",\n\t\t\t\tstartedAt: startedAt.toISOString(),\n\t\t\t\tcompletedAt: completedAt.toISOString(),\n\t\t\t\tretrievalStatus: \"failed\",\n\t\t\t\tdeliveryStatus: \"not_attempted\",\n\t\t\t\tcandidateIds: [],\n\t\t\t\tselectedIds: [],\n\t\t\t\trecorderVersion: \"mcp-retrieval-v1\",\n\t\t\t\tsource: \"mcp\",\n\t\t\t\tstreamId,\n\t\t\t\tsourceSessionId: input.sourceSessionId ?? null,\n\t\t\t\trequestId: ledgerRequestId,\n\t\t\t\tlatencyMs: Math.max(0, completedAt.getTime() - startedAt.getTime()),\n\t\t\t\tquery: input.query,\n\t\t\t\tlimitRequested: input.limit,\n\t\t\t\tfilters,\n\t\t\t\tfailureCode: \"tool_failed\",\n\t\t\t\tfailureStage: \"retrieval\",\n\t\t\t},\n\t\t\tfalse,\n\t\t);\n\t\tsafeCompleteInvocation(context, invocation, \"failed\");\n\t\treturn errorContent(error instanceof Error ? error.message : String(error));\n\t}\n}\n","import {\n\ttype MemoryFilters,\n\ttype MemoryItemResponse,\n\ttype MemoryStore,\n\ttoJson,\n} from \"@codemem/core\";\nimport { resolveWriteProject } from \"./project-scope.js\";\n\nexport function getMemoryForMcp(\n\tstore: MemoryStore,\n\tmemoryId: number,\n\tfilters?: MemoryFilters,\n): MemoryItemResponse | null {\n\tconst rows = store.timeline(null, memoryId, 0, 0, filters ?? null);\n\treturn rows.find((row) => row.id === memoryId) ?? null;\n}\n\nexport function getManyForMcp(\n\tstore: MemoryStore,\n\tids: number[],\n\tfilters?: MemoryFilters,\n): MemoryItemResponse[] {\n\tif (ids.length === 0) return [];\n\tconst results: MemoryItemResponse[] = [];\n\tfor (const id of ids) {\n\t\tconst item = getMemoryForMcp(store, id, filters);\n\t\tif (item) results.push(item);\n\t}\n\treturn results;\n}\n\nexport function forgetMemoryForMcp(\n\tstore: MemoryStore,\n\tmemoryId: number,\n\tfilters?: MemoryFilters,\n): boolean {\n\tconst item = getMemoryForMcp(store, memoryId, filters);\n\tif (!item) return false;\n\tstore.forget(memoryId);\n\treturn true;\n}\n\nexport interface RememberMemoryForMcpInput {\n\tkind: string;\n\ttitle: string;\n\tbody: string;\n\tconfidence: number;\n\tproject?: string | null;\n}\n\nexport interface RememberMemoryForMcpContext {\n\tcwd?: string;\n\tuser?: string;\n\tenvProject?: string | null;\n\tnow?: () => string;\n}\n\nexport function rememberMemoryForMcp(\n\tstore: MemoryStore,\n\tinput: RememberMemoryForMcpInput,\n\tcontext: RememberMemoryForMcpContext = {},\n): { memId: number; title: string; body: string } {\n\treturn store.db.transaction(() => {\n\t\tconst now = context.now?.() ?? new Date().toISOString();\n\t\tconst user = context.user ?? process.env.USER ?? \"unknown\";\n\t\tconst cwd = context.cwd ?? process.cwd();\n\t\tconst project = resolveWriteProject({\n\t\t\tproject: input.project,\n\t\t\tenvProject: context.envProject,\n\t\t});\n\n\t\tconst sessionInfo = store.db\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO sessions(started_at, ended_at, cwd, project, user, tool_version, metadata_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t)\n\t\t\t.run(now, now, cwd, project, user, \"mcp-ts\", toJson({ mcp: true }));\n\t\tconst sessionId = Number(sessionInfo.lastInsertRowid);\n\n\t\tconst memId = store.remember(sessionId, input.kind, input.title, input.body, input.confidence);\n\t\tif (!getMemoryForMcp(store, memId)) {\n\t\t\tthrow new Error(\"unauthorized_scope\");\n\t\t}\n\n\t\tstore.db\n\t\t\t.prepare(\"UPDATE sessions SET ended_at = ?, metadata_json = ? WHERE id = ?\")\n\t\t\t.run(context.now?.() ?? new Date().toISOString(), toJson({ mcp: true }), sessionId);\n\n\t\treturn { memId, title: input.title, body: input.body };\n\t})();\n}\n","import { storeVectors } from \"@codemem/core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { errorContent, jsonContent } from \"../content.js\";\nimport { withMcpRetrieval } from \"../mcp-retrieval-ledger.js\";\nimport {\n\tforgetMemoryForMcp,\n\tgetManyForMcp,\n\tgetMemoryForMcp,\n\trememberMemoryForMcp,\n} from \"../memory-access.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema, memoryKindSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst getInputSchema = {\n\tmemory_id: z.number().int().describe(\"Memory ID\"),\n\t...filterSchema,\n};\n\nconst getObservationsInputSchema = {\n\tids: z.array(z.number().int()).max(200).describe(\"Memory IDs to fetch\"),\n\t...filterSchema,\n};\n\nconst rememberInputSchema = {\n\tkind: memoryKindSchema.describe(\"Memory kind\"),\n\ttitle: z.string().describe(\"Short title\"),\n\tbody: z.string().describe(\"Body text (high-signal content)\"),\n\tconfidence: z.number().min(0).max(1).default(0.5).describe(\"Confidence 0-1\"),\n\tproject: z.string().optional().describe(\"Project identifier\"),\n};\n\nconst forgetInputSchema = {\n\tmemory_id: z.number().int().describe(\"Memory ID to forget\"),\n\t...filterSchema,\n};\n\nfunction registerGetTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_get\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Fetch one memory by exact ID. Does not inherit the default project; optional filters constrain the lookup, and a mismatch returns not_found.\",\n\t\t\tinputSchema: getInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_get,\n\t\t\tannotations: toolAnnotations.memory_get,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\t// Direct-ID ops do not inherit the server default project. Callers already\n\t\t\t// have an exact ID; cwd/env should not silently scope the lookup.\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_get\",\n\t\t\t\t\ttoolName: \"memory_get\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: 1,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, null),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst item = getMemoryForMcp(context.store, args.memory_id, filters);\n\t\t\t\t\treturn item\n\t\t\t\t\t\t? { value: item, memoryIds: [item.id], filters }\n\t\t\t\t\t\t: { value: null, memoryIds: [], error: \"not_found\", filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n\nfunction registerGetObservationsTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_get_observations\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Fetch multiple memories by exact IDs. Does not inherit the default project. Missing or filtered-out IDs are omitted from results, not reported as not_found.\",\n\t\t\tinputSchema: getObservationsInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_get_observations,\n\t\t\tannotations: toolAnnotations.memory_get_observations,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_get_observations\",\n\t\t\t\t\ttoolName: \"memory_get_observations\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: args.ids.length,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, null),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = getManyForMcp(context.store, args.ids, filters);\n\t\t\t\t\treturn { value: { items }, memoryIds: items.map((item) => item.id), filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n\nfunction registerRememberTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_remember\",\n\t\t{\n\t\t\tdescription: \"Create a new memory. Use for milestones, decisions, and notable facts.\",\n\t\t\tinputSchema: rememberInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_remember,\n\t\t\tannotations: toolAnnotations.memory_remember,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\t// Writes never inherit the server default project. They only honor an\n\t\t\t\t// explicit `project` input or CODEMEM_PROJECT; otherwise project stays null.\n\t\t\t\tconst result = rememberMemoryForMcp(context.store, args, {\n\t\t\t\t\tenvProject: context.envProject(),\n\t\t\t\t});\n\n\t\t\t\ttry {\n\t\t\t\t\tawait storeVectors(context.store.db, result.memId, result.title, result.body);\n\t\t\t\t} catch {\n\t\t\t\t\t// Memory writes should succeed even if embeddings are unavailable.\n\t\t\t\t}\n\n\t\t\t\treturn jsonContent({ id: result.memId });\n\t\t\t} catch (err) {\n\t\t\t\treturn errorContent(err instanceof Error ? err.message : String(err));\n\t\t\t}\n\t\t},\n\t);\n}\n\nfunction registerForgetTool(server: McpServer, context: ToolRegistrationContext): void {\n\tserver.registerTool(\n\t\t\"memory_forget\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Soft-delete a memory by exact ID so it no longer appears in normal retrieval; this is not secure erasure. Does not inherit the default project; optional filters must match or the tool returns not_found.\",\n\t\t\tinputSchema: forgetInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_forget,\n\t\t\tannotations: toolAnnotations.memory_forget,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\tif (!forgetMemoryForMcp(context.store, args.memory_id, buildFilters(args, null))) {\n\t\t\t\t\treturn errorContent(\"not_found\");\n\t\t\t\t}\n\t\t\t\treturn jsonContent({ status: \"ok\" });\n\t\t\t} catch (err) {\n\t\t\t\treturn errorContent(err instanceof Error ? err.message : String(err));\n\t\t\t}\n\t\t},\n\t);\n}\n\nexport function registerItemTools(server: McpServer, context: ToolRegistrationContext): void {\n\tregisterGetTool(server, context);\n\tregisterGetObservationsTool(server, context);\n\tregisterRememberTool(server, context);\n\tregisterForgetTool(server, context);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { jsonContent } from \"../content.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst MEMORY_LEARN_GUIDANCE = {\n\tintro: \"Use this tool when you're new to codemem or unsure when to recall/persist.\",\n\tclient_hint: \"If you are unfamiliar with codemem, call memory_learn first.\",\n\trecall: {\n\t\twhen: [\n\t\t\t\"Start of a task or when the user references prior work.\",\n\t\t\t\"When you need background context, decisions, or recent changes.\",\n\t\t],\n\t\thow: [\n\t\t\t\"Use memory_search or memory_search_index for exact terms and identifiers; memory_search returns bodies, while memory_search_index returns compact candidates.\",\n\t\t\t\"Use memory_pack for conceptually relevant context; it combines keyword and semantic search when embeddings are available and falls back to keyword search when they are not.\",\n\t\t\t\"Use memory_timeline to expand around a promising memory.\",\n\t\t\t\"Use memory_get or memory_get_observations for full details only when needed.\",\n\t\t\t\"Use the project filter unless the user requests cross-project context.\",\n\t\t\t\"Project, trust, and ownership filters organize and select memories; they are not authentication or tenant-isolation controls.\",\n\t\t],\n\t\texamples: [\n\t\t\t'memory_search_index(query=\"billing cache bug\", limit=5)',\n\t\t\t\"memory_timeline(memory_id=123)\",\n\t\t\t\"memory_get_observations(ids=[123, 456])\",\n\t\t],\n\t},\n\tpersistence: {\n\t\twhen: [\n\t\t\t\"Milestones (task done, key decision, new facts learned).\",\n\t\t\t\"Notable regressions or follow-ups that should be remembered.\",\n\t\t],\n\t\thow: [\n\t\t\t\"Use memory_remember with kind decision/discovery/change/exploration.\",\n\t\t\t\"Keep titles short and bodies high-signal.\",\n\t\t\t\"ALWAYS pass the project parameter if known.\",\n\t\t],\n\t\texamples: [\n\t\t\t'memory_remember(kind=\"decision\", title=\"Switch to async cache\", body=\"...why...\", project=\"my-service\")',\n\t\t\t'memory_remember(kind=\"change\", title=\"Fixed retry loop\", body=\"...impact...\", project=\"my-service\")',\n\t\t],\n\t},\n\tforget: {\n\t\twhen: [\n\t\t\t\"Obsolete or incorrect items that should no longer surface.\",\n\t\t\t\"Items that should be soft-deleted; soft deletion is not secure erasure.\",\n\t\t],\n\t\thow: [\n\t\t\t\"Call memory_forget(memory_id) to mark the item inactive.\",\n\t\t\t\"Optional filters constrain the exact-ID lookup; a filter mismatch returns not_found.\",\n\t\t\t\"Do not treat memory_forget as secure erasure or a user-data erasure guarantee.\",\n\t\t],\n\t\texamples: [\"memory_forget(memory_id=123)\"],\n\t},\n\tprompt_hint:\n\t\t\"At task start: call memory_search_index for exact terms or memory_pack for conceptual context; during work: memory_timeline + memory_get_observations; at milestones: memory_remember.\",\n\trecommended_system_prompt: [\n\t\t\"Trigger policy (1-liner): If the user references prior work or starts a task,\",\n\t\t\"call memory_search_index for exact terms or memory_pack for conceptual context; then use\",\n\t\t\"memory_timeline + memory_get_observations; at milestones, call memory_remember.\",\n\t\t\"\",\n\t\t\"System prompt:\",\n\t\t\"You have access to codemem MCP tools. If unfamiliar, call memory_learn first.\",\n\t\t\"\",\n\t\t\"Recall:\",\n\t\t\"- For exact terms or identifiers, use memory_search_index for compact candidates or memory_search for bodies.\",\n\t\t\"- For conceptually relevant context, use memory_pack; it falls back to keyword search without embeddings.\",\n\t\t'- If prior work is referenced (\"as before\", \"last time\", \"we already did…\", \"regression\"),',\n\t\t\" call memory_search_index, memory_pack, or memory_timeline as appropriate.\",\n\t\t\"- Use memory_get or memory_get_observations only after filtering IDs.\",\n\t\t\"- Prefer project-scoped queries unless the user asks for cross-project.\",\n\t\t\"- Project, trust, and ownership filters select memories; they do not authenticate or isolate tenants.\",\n\t\t\"\",\n\t\t\"Persistence:\",\n\t\t\"- On milestones (task done, key decision, new facts learned), call memory_remember.\",\n\t\t\"- Use kind=decision for tradeoffs, kind=change for outcomes, kind=discovery/exploration for useful findings.\",\n\t\t\"- Keep titles short and bodies high-signal.\",\n\t\t\"- ALWAYS pass the project parameter if known.\",\n\t\t\"\",\n\t\t\"Safety:\",\n\t\t\"- Use memory_forget(memory_id) to soft-delete incorrect or obsolete items; this is not secure erasure.\",\n\t\t\"\",\n\t\t\"Examples:\",\n\t\t'- memory_search_index(query=\"billing cache bug\")',\n\t\t\"- memory_timeline(memory_id=123)\",\n\t\t\"- memory_get_observations(ids=[123, 456])\",\n\t\t'- memory_remember(kind=\"decision\", title=\"Use async cache\", body=\"Chose async cache to avoid lock contention in X.\", project=\"my-service\")',\n\t\t'- memory_remember(kind=\"change\", title=\"Fixed retry loop\", body=\"Root cause was Y; added guard in Z.\", project=\"my-service\")',\n\t\t\"- memory_forget(memory_id=123)\",\n\t].join(\"\\n\"),\n} as const;\n\nexport function registerLearnTools(server: McpServer): void {\n\tserver.registerTool(\n\t\t\"memory_learn\",\n\t\t{\n\t\t\tdescription: \"Learn how to use codemem memory tools. Call this first if unfamiliar.\",\n\t\t\tinputSchema: {},\n\t\t\toutputSchema: toolOutputSchemas.memory_learn,\n\t\t\tannotations: toolAnnotations.memory_learn,\n\t\t},\n\t\tasync () => jsonContent(MEMORY_LEARN_GUIDANCE),\n\t);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { jsonContent } from \"../content.js\";\nimport { MEMORY_KINDS } from \"../memory-kinds.js\";\nimport { filterNames } from \"../schemas.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nexport function registerSchemaTools(server: McpServer): void {\n\tserver.registerTool(\n\t\t\"memory_schema\",\n\t\t{\n\t\t\tdescription: \"Return the memory schema — kinds, fields, and available filters.\",\n\t\t\tinputSchema: {},\n\t\t\toutputSchema: toolOutputSchemas.memory_schema,\n\t\t\tannotations: toolAnnotations.memory_schema,\n\t\t},\n\t\tasync () => {\n\t\t\treturn jsonContent({\n\t\t\t\tkinds: Object.keys(MEMORY_KINDS),\n\t\t\t\tkind_descriptions: MEMORY_KINDS,\n\t\t\t\tfields: {\n\t\t\t\t\ttitle: \"short text\",\n\t\t\t\t\tbody: \"long text\",\n\t\t\t\t\tsubtitle: \"short text\",\n\t\t\t\t\tfacts: \"list<string>\",\n\t\t\t\t\tnarrative: \"long text\",\n\t\t\t\t\tconcepts: \"list<string>\",\n\t\t\t\t\tfiles_read: \"list<string>\",\n\t\t\t\t\tfiles_modified: \"list<string>\",\n\t\t\t\t\tprompt_number: \"int\",\n\t\t\t\t},\n\t\t\t\tfilters: filterNames,\n\t\t\t});\n\t\t},\n\t);\n}\n","import type { MemoryResult } from \"@codemem/core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { withMcpRetrieval } from \"../mcp-retrieval-ledger.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst searchInputSchema = {\n\tquery: z.string().describe(\"Search query\"),\n\tlimit: z.number().int().min(1).max(50).default(5).describe(\"Max results\"),\n\t...filterSchema,\n};\n\nconst searchIndexInputSchema = {\n\tquery: z.string().describe(\"Search query\"),\n\tlimit: z.number().int().min(1).max(50).default(8).describe(\"Max results\"),\n\t...filterSchema,\n};\n\nconst explainInputSchema = {\n\tquery: z.string().optional().describe(\"Search query\"),\n\tids: z.array(z.number().int()).max(200).optional().describe(\"Specific memory IDs to explain\"),\n\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max results\"),\n\tinclude_pack_context: z.boolean().default(false).describe(\"Include formatted pack context\"),\n\t...filterSchema,\n};\n\nconst recentInputSchema = {\n\tlimit: z.number().int().min(1).max(100).default(8).describe(\"Max results\"),\n\t...filterSchema,\n};\n\nconst packInputSchema = {\n\tcontext: z.string().describe(\"Context description to search for\"),\n\tlimit: z.number().int().min(1).max(50).optional().describe(\"Max items to include\"),\n\tcompact: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"When true, render a scannable index of all items with full detail only for the top N (default 3). Saves tokens when broad overview matters more than per-item detail.\",\n\t\t),\n\tcompact_detail_count: z\n\t\t.number()\n\t\t.int()\n\t\t.min(0)\n\t\t.max(50)\n\t\t.optional()\n\t\t.describe(\"Number of items to show in full detail in compact mode (default 3)\"),\n\tcompression_mode: z\n\t\t.enum([\"off\", \"compact\", \"ids\"])\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Near-related compression mode: off disables it, compact applies only to compact rendering, ids applies in all modes. Defaults to CODEMEM_PACK_COMPRESSION or compact.\",\n\t\t),\n\t...filterSchema,\n};\n\nexport function registerSearchTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.registerTool(\n\t\t\"memory_search\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Keyword-search memories when you know exact terms or identifiers. Returns full body text for each match; use memory_search_index when you only need compact candidates.\",\n\t\t\tinputSchema: searchInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_search,\n\t\t\tannotations: toolAnnotations.memory_search,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_search\",\n\t\t\t\t\ttoolName: \"memory_search\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.search(args.query, args.limit, filters);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\titems: items.map((m: MemoryResult) => ({\n\t\t\t\t\t\t\t\tid: m.id,\n\t\t\t\t\t\t\t\ttitle: m.title,\n\t\t\t\t\t\t\t\tkind: m.kind,\n\t\t\t\t\t\t\t\tbody: m.body_text,\n\t\t\t\t\t\t\t\tconfidence: m.confidence,\n\t\t\t\t\t\t\t\tscore: m.score,\n\t\t\t\t\t\t\t\tsession_id: m.session_id,\n\t\t\t\t\t\t\t\tmetadata: m.metadata,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmemoryIds: items.map((item) => item.id),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_search_index\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Keyword-search memories when you know exact terms or identifiers. Returns compact entries with IDs and titles, without bodies; expand selected IDs with memory_get or memory_get_observations.\",\n\t\t\tinputSchema: searchIndexInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_search_index,\n\t\t\tannotations: toolAnnotations.memory_search_index,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_search_index\",\n\t\t\t\t\ttoolName: \"memory_search_index\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.search(args.query, args.limit, filters);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\titems: items.map((m: MemoryResult) => ({\n\t\t\t\t\t\t\t\tid: m.id,\n\t\t\t\t\t\t\t\tkind: m.kind,\n\t\t\t\t\t\t\t\ttitle: m.title,\n\t\t\t\t\t\t\t\tscore: m.score,\n\t\t\t\t\t\t\t\tcreated_at: m.created_at,\n\t\t\t\t\t\t\t\tsession_id: m.session_id,\n\t\t\t\t\t\t\t\tmetadata: m.metadata,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmemoryIds: items.map((item) => item.id),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_explain\",\n\t\t{\n\t\t\tdescription: \"Explain search results with detailed scoring breakdown.\",\n\t\t\tinputSchema: explainInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_explain,\n\t\t\tannotations: toolAnnotations.memory_explain,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_explain\",\n\t\t\t\t\ttoolName: \"memory_explain\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst result = store.explain(args.query ?? null, args.ids ?? null, args.limit, filters, {\n\t\t\t\t\t\tincludePackContext: args.include_pack_context,\n\t\t\t\t\t});\n\t\t\t\t\tconst fatalInputError = result.errors.some(\n\t\t\t\t\t\t(error) => error.code === \"INVALID_ARGUMENT\" && error.field === \"query\",\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tvalue: result,\n\t\t\t\t\t\tmemoryIds: result.items.map((item) => item.id),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\tretrievalStatus: fatalInputError ? (\"failed\" as const) : undefined,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_recent\",\n\t\t{\n\t\t\tdescription: \"Return recent memories, newest first.\",\n\t\t\tinputSchema: recentInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_recent,\n\t\t\tannotations: toolAnnotations.memory_recent,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_recent\",\n\t\t\t\t\ttoolName: \"memory_recent\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: args.limit,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.recent(args.limit, filters);\n\t\t\t\t\treturn { value: { items }, memoryIds: items.map((item) => item.id), filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_pack\",\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Build a formatted context block for a concept or task using keyword and semantic search when embeddings are available, with automatic keyword-only fallback. Use for conceptually relevant context; use memory_search or memory_search_index for exact identifiers.\",\n\t\t\tinputSchema: packInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_pack,\n\t\t\tannotations: toolAnnotations.memory_pack,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_pack\",\n\t\t\t\t\ttoolName: \"memory_pack\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.context,\n\t\t\t\t\tlimit: args.limit ?? null,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\tasync (filters) => {\n\t\t\t\t\tconst renderOptions =\n\t\t\t\t\t\targs.compact || args.compact_detail_count != null || args.compression_mode != null\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tcompact: args.compact ?? (args.compact_detail_count != null ? true : undefined),\n\t\t\t\t\t\t\t\t\tcompactDetailCount: args.compact_detail_count,\n\t\t\t\t\t\t\t\t\tcompressionMode: args.compression_mode,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst result = await store.buildMemoryPackAsync(\n\t\t\t\t\t\targs.context,\n\t\t\t\t\t\targs.limit ?? undefined,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\trenderOptions,\n\t\t\t\t\t);\n\t\t\t\t\t// Renderer spans and fingerprints belong to automatic recall, not model context.\n\t\t\t\t\tconst { rendered_items: _renderedItems, ...value } = result;\n\t\t\t\t\treturn { value, memoryIds: result.item_ids, filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n","import { dedupeOrderedIds, type MemoryItemResponse, projectMatchesFilter } from \"@codemem/core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { withMcpRetrieval } from \"../mcp-retrieval-ledger.js\";\nimport { getManyForMcp } from \"../memory-access.js\";\nimport { buildFilters } from \"../project-scope.js\";\nimport { filterSchema } from \"../schemas.js\";\nimport type { ToolRegistrationContext } from \"../tool-context.js\";\nimport { toolAnnotations, toolOutputSchemas } from \"../tool-contracts.js\";\n\nconst timelineInputSchema = {\n\tquery: z.string().optional().describe(\"Search query to find anchor\"),\n\tmemory_id: z.number().int().optional().describe(\"Anchor memory ID\"),\n\tdepth_before: z.number().int().min(0).default(3).describe(\"Items before anchor\"),\n\tdepth_after: z.number().int().min(0).default(3).describe(\"Items after anchor\"),\n\t...filterSchema,\n};\n\nconst expandInputSchema = {\n\tids: z\n\t\t.array(z.union([z.number(), z.string()]))\n\t\t.max(200)\n\t\t.describe(\"Memory IDs to expand\"),\n\tdepth_before: z.number().int().min(0).default(3).describe(\"Timeline items before\"),\n\tdepth_after: z.number().int().min(0).default(3).describe(\"Timeline items after\"),\n\tinclude_observations: z.boolean().default(false).describe(\"Include full observation details\"),\n\t...filterSchema,\n};\n\nexport function registerTimelineTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.registerTool(\n\t\t\"memory_timeline\",\n\t\t{\n\t\t\tdescription: \"Get a chronological window of memories around an anchor (by ID or query).\",\n\t\t\tinputSchema: timelineInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_timeline,\n\t\t\tannotations: toolAnnotations.memory_timeline,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_timeline\",\n\t\t\t\t\ttoolName: \"memory_timeline\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tquery: args.query,\n\t\t\t\t\tlimit: args.depth_before + args.depth_after + 1,\n\t\t\t\t\tresolveFilters: () => buildFilters(args, defaultProject()),\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst items = store.timeline(\n\t\t\t\t\t\targs.query ?? null,\n\t\t\t\t\t\targs.memory_id ?? null,\n\t\t\t\t\t\targs.depth_before,\n\t\t\t\t\t\targs.depth_after,\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t);\n\t\t\t\t\treturn { value: { items }, memoryIds: items.map((item) => item.id), filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerTool(\n\t\t\"memory_expand\",\n\t\t{\n\t\t\tdescription: \"Fetch memories by ID with surrounding timeline context.\",\n\t\t\tinputSchema: expandInputSchema,\n\t\t\toutputSchema: toolOutputSchemas.memory_expand,\n\t\t\tannotations: toolAnnotations.memory_expand,\n\t\t},\n\t\tasync (args, extra) => {\n\t\t\treturn withMcpRetrieval(\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tsurface: \"mcp_expand\",\n\t\t\t\t\ttoolName: \"memory_expand\",\n\t\t\t\t\ttoolArguments: args,\n\t\t\t\t\tlimit: args.ids.length,\n\t\t\t\t\tresolveFilters: () => {\n\t\t\t\t\t\t// Explicit blank `project` clears scoping for cross-project expansion.\n\t\t\t\t\t\t// Only fall back to the server default when `project` is omitted entirely.\n\t\t\t\t\t\tconst filterDefaultProject =\n\t\t\t\t\t\t\targs.project !== undefined && !args.project.trim() ? null : defaultProject();\n\t\t\t\t\t\treturn buildFilters(args, filterDefaultProject);\n\t\t\t\t\t},\n\t\t\t\t\trequestId: extra?.requestId,\n\t\t\t\t\tsourceSessionId: extra?.sessionId,\n\t\t\t\t\tinvocationIdentity: extra?.signal,\n\t\t\t\t},\n\t\t\t\t(filters) => {\n\t\t\t\t\tconst resolvedProject = filters?.project ?? null;\n\t\t\t\t\tconst { ordered: orderedIds, invalid: invalidIds } = dedupeOrderedIds(args.ids);\n\t\t\t\t\tconst errors: Array<Record<string, unknown>> = [];\n\n\t\t\t\t\tif (invalidIds.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"INVALID_ARGUMENT\",\n\t\t\t\t\t\t\tfield: \"ids\",\n\t\t\t\t\t\t\tmessage: \"some ids are not valid integers\",\n\t\t\t\t\t\t\tids: invalidIds,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tconst missingNotFound: number[] = [];\n\t\t\t\t\tconst missingProjectMismatch: number[] = [];\n\t\t\t\t\tconst missingFilterMismatch: number[] = [];\n\t\t\t\t\tconst anchors: MemoryItemResponse[] = [];\n\t\t\t\t\tconst timelineItems: MemoryItemResponse[] = [];\n\t\t\t\t\tconst timelineSeen = new Set<number>();\n\t\t\t\t\tconst sessionProjects = new Map<number, string | null>();\n\n\t\t\t\t\tfor (const memoryId of orderedIds) {\n\t\t\t\t\t\tconst item = store.get(memoryId);\n\t\t\t\t\t\tif (!item?.active) {\n\t\t\t\t\t\t\tmissingNotFound.push(memoryId);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst sessionId = item.session_id;\n\t\t\t\t\t\tif (resolvedProject && sessionId > 0) {\n\t\t\t\t\t\t\tif (!sessionProjects.has(sessionId)) {\n\t\t\t\t\t\t\t\tconst row = store.db\n\t\t\t\t\t\t\t\t\t.prepare(\"SELECT project FROM sessions WHERE id = ? LIMIT 1\")\n\t\t\t\t\t\t\t\t\t.get(sessionId) as { project: string | null } | undefined;\n\t\t\t\t\t\t\t\tsessionProjects.set(\n\t\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\t\ttypeof row?.project === \"string\" ? row.project : null,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!projectMatchesFilter(resolvedProject, sessionProjects.get(sessionId) ?? null)) {\n\t\t\t\t\t\t\t\tmissingProjectMismatch.push(memoryId);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (resolvedProject && sessionId <= 0) {\n\t\t\t\t\t\t\tmissingProjectMismatch.push(memoryId);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst expanded = store.timeline(\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\tmemoryId,\n\t\t\t\t\t\t\targs.depth_before,\n\t\t\t\t\t\t\targs.depth_after,\n\t\t\t\t\t\t\tfilters,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst anchor = expanded.find((expandedItem) => expandedItem.id === memoryId);\n\t\t\t\t\t\tif (!anchor) {\n\t\t\t\t\t\t\tmissingFilterMismatch.push(memoryId);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tanchors.push(anchor);\n\t\t\t\t\t\tfor (const expandedItem of expanded) {\n\t\t\t\t\t\t\tconst expandedId = expandedItem.id;\n\t\t\t\t\t\t\tif (expandedId <= 0 || timelineSeen.has(expandedId)) continue;\n\t\t\t\t\t\t\ttimelineSeen.add(expandedId);\n\t\t\t\t\t\t\ttimelineItems.push(expandedItem);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (missingNotFound.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\t\t\tfield: \"ids\",\n\t\t\t\t\t\t\tmessage: \"some requested ids were not found\",\n\t\t\t\t\t\t\tids: missingNotFound,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (missingProjectMismatch.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"PROJECT_MISMATCH\",\n\t\t\t\t\t\t\tfield: \"project\",\n\t\t\t\t\t\t\tmessage: \"some requested ids are outside the requested project scope\",\n\t\t\t\t\t\t\tids: missingProjectMismatch,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (missingFilterMismatch.length > 0) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"FILTER_MISMATCH\",\n\t\t\t\t\t\t\tfield: \"filters\",\n\t\t\t\t\t\t\tmessage: \"some requested ids are outside the requested filters\",\n\t\t\t\t\t\t\tids: missingFilterMismatch,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tlet observations: MemoryItemResponse[] = [];\n\t\t\t\t\tif (args.include_observations) {\n\t\t\t\t\t\tconst observationSeen = new Set<number>();\n\t\t\t\t\t\tconst observationIds: number[] = [];\n\t\t\t\t\t\tfor (const item of [...anchors, ...timelineItems]) {\n\t\t\t\t\t\t\tif (item.id > 0 && !observationSeen.has(item.id)) {\n\t\t\t\t\t\t\t\tobservationSeen.add(item.id);\n\t\t\t\t\t\t\t\tobservationIds.push(item.id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tobservations = getManyForMcp(store, observationIds, filters);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst value = {\n\t\t\t\t\t\tanchors,\n\t\t\t\t\t\ttimeline: timelineItems,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t\tmissing_ids: orderedIds.filter(\n\t\t\t\t\t\t\t(memoryId: number) =>\n\t\t\t\t\t\t\t\tmissingNotFound.includes(memoryId) ||\n\t\t\t\t\t\t\t\tmissingProjectMismatch.includes(memoryId) ||\n\t\t\t\t\t\t\t\tmissingFilterMismatch.includes(memoryId),\n\t\t\t\t\t\t),\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tproject: resolvedProject,\n\t\t\t\t\t\t\trequested_ids_count: orderedIds.length,\n\t\t\t\t\t\t\treturned_anchor_count: anchors.length,\n\t\t\t\t\t\t\ttimeline_count: timelineItems.length,\n\t\t\t\t\t\t\tinclude_observations: args.include_observations,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tconst memoryIds = [\n\t\t\t\t\t\t...new Set([...anchors, ...timelineItems, ...observations].map((item) => item.id)),\n\t\t\t\t\t];\n\t\t\t\t\treturn { value, memoryIds, filters };\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { type MemoryStore, VERSION } from \"@codemem/core\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { resolveDefaultProject } from \"./project-scope.js\";\nimport type { CodememMcpServerOptions, ToolRegistrationContext } from \"./tool-context.js\";\nimport { registerDistillTools } from \"./tools/distill.js\";\nimport { registerItemTools } from \"./tools/items.js\";\nimport { registerLearnTools } from \"./tools/learn.js\";\nimport { registerSchemaTools } from \"./tools/schema.js\";\nimport { registerSearchTools } from \"./tools/search.js\";\nimport { registerTimelineTools } from \"./tools/timeline.js\";\n\nexport function createCodememMcpServer(\n\tstore: MemoryStore,\n\toptions: CodememMcpServerOptions = {},\n): McpServer {\n\tconst server = new McpServer({ name: \"codemem\", version: VERSION });\n\tconst context: ToolRegistrationContext = {\n\t\tstore,\n\t\t// Resolve lazily per call so long-running servers pick up the current\n\t\t// CODEMEM_PROJECT / process.cwd() rather than the value at construction.\n\t\tdefaultProject: () => {\n\t\t\tif (options.resolveDefaultProject) return options.resolveDefaultProject();\n\t\t\tif (options.defaultProject !== undefined) return options.defaultProject;\n\t\t\treturn resolveDefaultProject();\n\t\t},\n\t\tenvProject: () =>\n\t\t\toptions.envProject !== undefined ? options.envProject : (process.env.CODEMEM_PROJECT ?? null),\n\t\tcaptureRetrievalLedger: options.captureRetrievalLedger !== false,\n\t\tretrievalLedgerScopeId: options.retrievalLedgerScopeId ?? randomUUID(),\n\t\tretrievalLedgerIdentityMode: options.retrievalLedgerIdentityMode ?? \"session\",\n\t};\n\n\tregisterSearchTools(server, context);\n\tregisterTimelineTools(server, context);\n\tregisterDistillTools(server, context);\n\tregisterItemTools(server, context);\n\tregisterSchemaTools(server);\n\tregisterLearnTools(server);\n\n\treturn server;\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,EAAc,GAAwB;CACrD,OACC,KAAK,UAAU,IAAQ,GAAM,MACA,OAAO,KAAgB,aAA/C,KAA2D,MAAM,QAAQ,CAAW,IAChF,IAED,OAAO,YACb,OAAO,QAAQ,CAAsC,CAAC,CAAC,UAAU,CAAC,IAAO,CAAC,OACzE,IAAO,IAAQ,KAAK,MAAO,EAC5B,CACD,CACA,KA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