@codemem/mcp 0.40.0-alpha.1 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,876 @@
1
+ import { createHash as e, randomUUID as t } from "node:crypto";
2
+ import { ObserverClient as n, VERSION as r, buildDistillReport as i, dedupeOrderedIds as a, judgeDistillReport as o, projectMatchesFilter as s, reconcileFailedRetrievalSurface as c, recordRetrievalSurface as l, resolveProject as u, resolveProjectRoot as d, storeVectors as f, toJson as p } from "@codemem/core";
3
+ import { existsSync as m, readFileSync as h } from "node:fs";
4
+ import { homedir as g } from "node:os";
5
+ import { join as _ } from "node:path";
6
+ import { McpServer as v } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { z as y } from "zod";
8
+ //#region src/canonical-json.ts
9
+ function b(e) {
10
+ return JSON.stringify(e, (e, t) => typeof t != "object" || !t || Array.isArray(t) ? t : Object.fromEntries(Object.entries(t).toSorted(([e], [t]) => e < t ? -1 : +(e > t)))) ?? "undefined";
11
+ }
12
+ //#endregion
13
+ //#region src/project-scope.ts
14
+ function x(e) {
15
+ return e?.trim() || null;
16
+ }
17
+ function S() {
18
+ return x(process.env.CODEMEM_PROJECT) ?? u(process.cwd());
19
+ }
20
+ function C(e) {
21
+ return x(e.project) ?? x(e.envProject) ?? null;
22
+ }
23
+ function w(e, t = S()) {
24
+ let n = {}, r = !1, i = (typeof e.project == "string" ? x(e.project) : void 0) || x(t) || void 0;
25
+ i && (n.project = i, r = !0);
26
+ for (let t of [
27
+ "kind",
28
+ "visibility",
29
+ "scope_id",
30
+ "include_scope_ids",
31
+ "exclude_scope_ids",
32
+ "include_visibility",
33
+ "exclude_visibility",
34
+ "include_workspace_ids",
35
+ "exclude_workspace_ids",
36
+ "include_workspace_kinds",
37
+ "exclude_workspace_kinds",
38
+ "include_actor_ids",
39
+ "exclude_actor_ids",
40
+ "include_trust_states",
41
+ "exclude_trust_states",
42
+ "ownership_scope",
43
+ "personal_first",
44
+ "trust_bias",
45
+ "widen_shared_when_weak",
46
+ "widen_shared_min_personal_results",
47
+ "widen_shared_min_personal_score"
48
+ ]) {
49
+ let i = e[t];
50
+ i != null && (n[t] = i, r = !0);
51
+ }
52
+ return r ? n : void 0;
53
+ }
54
+ //#endregion
55
+ //#region src/content.ts
56
+ function T(e) {
57
+ return { content: [{
58
+ type: "text",
59
+ text: JSON.stringify(e)
60
+ }] };
61
+ }
62
+ function E(e) {
63
+ return { content: [{
64
+ type: "text",
65
+ text: JSON.stringify({ error: e })
66
+ }] };
67
+ }
68
+ //#endregion
69
+ //#region src/schemas.ts
70
+ var ee = {
71
+ scope_id: y.string().optional().describe("Filter by a single sharing domain scope_id"),
72
+ include_scope_ids: y.array(y.string()).optional().describe("Sharing domain scope_ids to include"),
73
+ exclude_scope_ids: y.array(y.string()).optional().describe("Sharing domain scope_ids to exclude")
74
+ }, D = {
75
+ kind: y.string().optional().describe("Filter by memory kind"),
76
+ project: y.string().optional().describe("Filter by project scope (matches sessions.project)"),
77
+ ...ee,
78
+ visibility: y.array(y.string()).optional(),
79
+ include_visibility: y.array(y.string()).optional(),
80
+ exclude_visibility: y.array(y.string()).optional(),
81
+ include_workspace_ids: y.array(y.string()).optional(),
82
+ exclude_workspace_ids: y.array(y.string()).optional(),
83
+ include_workspace_kinds: y.array(y.string()).optional(),
84
+ exclude_workspace_kinds: y.array(y.string()).optional(),
85
+ include_actor_ids: y.array(y.string()).optional(),
86
+ exclude_actor_ids: y.array(y.string()).optional(),
87
+ include_trust_states: y.array(y.string()).optional(),
88
+ exclude_trust_states: y.array(y.string()).optional(),
89
+ ownership_scope: y.string().optional(),
90
+ personal_first: y.union([y.boolean(), y.string()]).optional(),
91
+ trust_bias: y.string().optional(),
92
+ widen_shared_when_weak: y.union([y.boolean(), y.string()]).optional(),
93
+ widen_shared_min_personal_results: y.number().int().optional(),
94
+ widen_shared_min_personal_score: y.number().optional()
95
+ }, O = y.enum([
96
+ "discovery",
97
+ "change",
98
+ "feature",
99
+ "bugfix",
100
+ "refactor",
101
+ "decision",
102
+ "exploration"
103
+ ]), k = Object.keys(D).toSorted();
104
+ //#endregion
105
+ //#region src/tools/distill.ts
106
+ function A(e, t, n) {
107
+ if (!m(e)) return null;
108
+ let r = h(e, "utf8");
109
+ return r.trim() ? {
110
+ path: t,
111
+ text: r,
112
+ scope: n
113
+ } : null;
114
+ }
115
+ function j(e, t = process.cwd()) {
116
+ let n = d(t) ?? t;
117
+ return [e ? A(_(n, "AGENTS.md"), "AGENTS.md", "project") : null, A(_(g(), ".config", "opencode", "AGENTS.md"), "~/.config/opencode/AGENTS.md", "user")].filter((e) => e != null);
118
+ }
119
+ function M(e, t) {
120
+ if (e.all_projects) return !1;
121
+ let n = u(process.cwd());
122
+ if (!n) return !1;
123
+ let r = typeof e.project == "string" ? e.project.trim() : "", i = r ? u(process.cwd(), r) : t;
124
+ return i ? s(i, n) : !1;
125
+ }
126
+ function N(e, t) {
127
+ if (e.all_projects && typeof e.project == "string" && e.project.trim()) throw Error("project cannot be combined with all_projects");
128
+ return w(e, e.all_projects ? null : t);
129
+ }
130
+ function te(e, t) {
131
+ let { defaultProject: r, store: a } = t;
132
+ e.tool("memory_distill_candidates", "Mine recurring memories into reviewable context candidates. Read-only; does not modify context files.", {
133
+ limit: y.number().int().min(1).max(50).default(10).describe("Max candidates"),
134
+ min_recurrence: y.number().int().min(1).max(50).default(2).describe("Minimum member count per candidate"),
135
+ all_projects: y.boolean().default(!1).describe("Mine memories across all projects"),
136
+ include_documented: y.boolean().default(!1).describe("Include candidates already represented in context files"),
137
+ max_evidence_items: y.number().int().min(1).max(20).default(5).describe("Evidence snippets per candidate"),
138
+ judge: y.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)"),
139
+ ...D
140
+ }, async (e) => {
141
+ try {
142
+ let t = r(), s = N(e, t), c = e.kind ? [e.kind] : void 0, l = e.judge ? Math.min(e.limit * 3, e.limit + 20) : e.limit, u = await i(a, {
143
+ candidate: {
144
+ includeDocumented: e.include_documented,
145
+ maxEvidenceItems: e.max_evidence_items
146
+ },
147
+ contextDocuments: j(M(e, t)),
148
+ corpus: {
149
+ filters: s ?? null,
150
+ kinds: c
151
+ },
152
+ limit: l,
153
+ minRecurrence: e.min_recurrence
154
+ });
155
+ if (e.judge) {
156
+ try {
157
+ let e = new n();
158
+ u = await o(u, async (t, n) => (await e.observe(t, n)).raw);
159
+ } catch (e) {
160
+ let t = e instanceof Error ? e.message : String(e);
161
+ u = {
162
+ ...u,
163
+ metadata: {
164
+ ...u.metadata,
165
+ judged: !1,
166
+ judge_error: t
167
+ }
168
+ };
169
+ }
170
+ u.candidates.length > e.limit && (u = {
171
+ ...u,
172
+ candidates: u.candidates.slice(0, e.limit),
173
+ metadata: {
174
+ ...u.metadata,
175
+ candidate_count: e.limit
176
+ }
177
+ });
178
+ }
179
+ return T(u);
180
+ } catch (e) {
181
+ return E(e instanceof Error ? e.message : String(e));
182
+ }
183
+ });
184
+ }
185
+ //#endregion
186
+ //#region src/mcp-retrieval-ledger.ts
187
+ var ne = 300 * 1e3, re = 2e3, P = /* @__PURE__ */ new WeakMap(), F = 0;
188
+ function I(e, t, n) {
189
+ if (e.captureRetrievalLedger) try {
190
+ let r = l(e.store.db, t);
191
+ n && !r.ok && r.reason === "idempotency_conflict" && (t.retrievalStatus === "succeeded" && t.deliveryStatus === "handed_off" || t.retrievalStatus === "no_results" && t.deliveryStatus === "not_attempted") && c(e.store.db, t);
192
+ } catch {}
193
+ }
194
+ function L(e) {
195
+ if (e == null) return t();
196
+ let n = e.slice(0, 32).split("");
197
+ n[12] = "5", n[16] = (Number.parseInt(n[16] ?? "0", 16) & 3 | 8).toString(16);
198
+ let r = n.join("");
199
+ return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
200
+ }
201
+ function R(t, n) {
202
+ if (n.requestId == null) return null;
203
+ let r = e("sha256").update(b({
204
+ method: "tools/call",
205
+ params: {
206
+ name: n.toolName,
207
+ arguments: n.toolArguments
208
+ }
209
+ })).digest("hex");
210
+ return e("sha256").update(JSON.stringify([
211
+ n.sourceSessionId ?? t.retrievalLedgerScopeId,
212
+ n.requestId,
213
+ r
214
+ ])).digest("hex");
215
+ }
216
+ function z(e) {
217
+ let t = P.get(e);
218
+ return t || (t = {
219
+ byInvocation: /* @__PURE__ */ new WeakMap(),
220
+ activeByRequest: /* @__PURE__ */ new Map(),
221
+ pendingFailures: /* @__PURE__ */ new Map(),
222
+ pendingFailureCount: 0,
223
+ nextPendingFailureOrder: 0,
224
+ nextInvocationSequence: 0
225
+ }, P.set(e, t)), t;
226
+ }
227
+ function B(e, t) {
228
+ for (let [n, r] of e.pendingFailures) {
229
+ let i = r.filter((e) => e.expiresAt > t);
230
+ e.pendingFailureCount -= r.length - i.length, i.length === 0 ? e.pendingFailures.delete(n) : i.length !== r.length && e.pendingFailures.set(n, i);
231
+ }
232
+ for (; e.pendingFailureCount > re;) {
233
+ let t, n = Infinity;
234
+ for (let [r, i] of e.pendingFailures) {
235
+ let e = i[0]?.order;
236
+ e != null && e < n && (t = r, n = e);
237
+ }
238
+ if (t === void 0) break;
239
+ let r = e.pendingFailures.get(t), i = r?.shift();
240
+ if (!r || !i) {
241
+ e.pendingFailures.delete(t);
242
+ continue;
243
+ }
244
+ --e.pendingFailureCount, r.length === 0 && e.pendingFailures.delete(t);
245
+ }
246
+ }
247
+ function V(e, t) {
248
+ let n = e.pendingFailures.get(t);
249
+ if (!n) return;
250
+ let r = n.shift();
251
+ if (r) return --e.pendingFailureCount, n.length === 0 && e.pendingFailures.delete(t), r.identity;
252
+ }
253
+ function H(e, t, n) {
254
+ let r = e.pendingFailures.get(t), i = r?.findIndex((e) => e.identity.attemptId === n) ?? -1;
255
+ !r || i < 0 || (r.splice(i, 1), --e.pendingFailureCount, r.length === 0 && e.pendingFailures.delete(t));
256
+ }
257
+ function U(e, t, n, r) {
258
+ let i = e.pendingFailures.get(t) ?? [];
259
+ i.some((e) => e.identity.attemptId === n.attemptId) || (i.push({
260
+ identity: n,
261
+ expiresAt: r + ne,
262
+ order: e.nextPendingFailureOrder
263
+ }), e.nextPendingFailureOrder += 1, e.pendingFailures.set(t, i), e.pendingFailureCount += 1, B(e, r));
264
+ }
265
+ function W() {
266
+ try {
267
+ return {
268
+ baseRequestId: null,
269
+ requestId: null,
270
+ attemptId: t()
271
+ };
272
+ } catch {
273
+ let e = Date.now().toString(16).slice(-8).padStart(8, "0"), t = F.toString(16).slice(-4).padStart(4, "0");
274
+ return F = (F + 1) % 65536, {
275
+ baseRequestId: null,
276
+ requestId: null,
277
+ attemptId: `00000000-0000-4000-8000-${e}${t}`
278
+ };
279
+ }
280
+ }
281
+ function G(t, n) {
282
+ let r = R(t, n);
283
+ if (t.retrievalLedgerIdentityMode === "stateless" || r == null) return {
284
+ baseRequestId: r,
285
+ requestId: r,
286
+ attemptId: L(r)
287
+ };
288
+ let i = z(t);
289
+ B(i, Date.now());
290
+ let a = n.invocationIdentity ? i.byInvocation.get(n.invocationIdentity) : void 0, o = a?.baseRequestId === r ? a : void 0;
291
+ if (!o) {
292
+ let a = (i.activeByRequest.get(r) ?? 0) === 0 ? V(i, r) : void 0;
293
+ if (a) o = a;
294
+ else {
295
+ let n = i.nextInvocationSequence;
296
+ i.nextInvocationSequence += 1;
297
+ let a = e("sha256").update(JSON.stringify([
298
+ r,
299
+ t.retrievalLedgerScopeId,
300
+ n
301
+ ])).digest("hex");
302
+ o = {
303
+ baseRequestId: r,
304
+ requestId: a,
305
+ attemptId: L(a)
306
+ };
307
+ }
308
+ n.invocationIdentity && i.byInvocation.set(n.invocationIdentity, o);
309
+ }
310
+ return i.activeByRequest.set(r, (i.activeByRequest.get(r) ?? 0) + 1), o;
311
+ }
312
+ function K(e, t) {
313
+ try {
314
+ return G(e, t);
315
+ } catch {
316
+ return W();
317
+ }
318
+ }
319
+ function q(e, t, n) {
320
+ if (e.retrievalLedgerIdentityMode === "stateless" || t.baseRequestId == null) return;
321
+ let r = z(e), i = r.activeByRequest.get(t.baseRequestId) ?? 0;
322
+ i <= 1 ? r.activeByRequest.delete(t.baseRequestId) : r.activeByRequest.set(t.baseRequestId, i - 1), n === "failed" ? U(r, t.baseRequestId, t, Date.now()) : H(r, t.baseRequestId, t.attemptId);
323
+ }
324
+ function J(e, t, n) {
325
+ try {
326
+ q(e, t, n);
327
+ } catch {}
328
+ }
329
+ async function Y(e, t, n) {
330
+ let r = K(e, t), i = r.requestId, a = r.attemptId, o = /* @__PURE__ */ new Date(), s;
331
+ try {
332
+ s = t.resolveFilters?.();
333
+ let c = await n(s), l = /* @__PURE__ */ new Date(), u = c.error ? E(c.error) : T(c.value), d = t.sourceSessionId ?? e.retrievalLedgerScopeId, f = c.memoryIds.length > 0, p = c.error === "not_found" && !f, m = c.error != null && !p || c.retrievalStatus === "failed" && !f, h = m ? [] : c.memoryIds, g = c.retrievalStatus === "unknown" ? "unknown" : "succeeded";
334
+ return I(e, {
335
+ attemptId: a,
336
+ surface: t.surface,
337
+ trigger: "explicit",
338
+ startedAt: o.toISOString(),
339
+ completedAt: l.toISOString(),
340
+ retrievalStatus: m ? "failed" : f ? g : "no_results",
341
+ deliveryStatus: m || !f ? "not_attempted" : "handed_off",
342
+ candidateIds: h,
343
+ selectedIds: h,
344
+ candidateCount: f && !m ? c.candidateCount : 0,
345
+ recorderVersion: "mcp-retrieval-v1",
346
+ source: "mcp",
347
+ streamId: d,
348
+ sourceSessionId: t.sourceSessionId ?? null,
349
+ requestId: i,
350
+ latencyMs: Math.max(0, l.getTime() - o.getTime()),
351
+ filters: c.filters ?? s,
352
+ query: t.query,
353
+ limitRequested: t.limit,
354
+ failureCode: m ? "tool_failed" : void 0,
355
+ failureStage: m ? "retrieval" : void 0
356
+ }, !m), J(e, r, m ? "failed" : "completed"), u;
357
+ } catch (n) {
358
+ let c = /* @__PURE__ */ new Date(), l = t.sourceSessionId ?? e.retrievalLedgerScopeId;
359
+ return I(e, {
360
+ attemptId: a,
361
+ surface: t.surface,
362
+ trigger: "explicit",
363
+ startedAt: o.toISOString(),
364
+ completedAt: c.toISOString(),
365
+ retrievalStatus: "failed",
366
+ deliveryStatus: "not_attempted",
367
+ candidateIds: [],
368
+ selectedIds: [],
369
+ recorderVersion: "mcp-retrieval-v1",
370
+ source: "mcp",
371
+ streamId: l,
372
+ sourceSessionId: t.sourceSessionId ?? null,
373
+ requestId: i,
374
+ latencyMs: Math.max(0, c.getTime() - o.getTime()),
375
+ query: t.query,
376
+ limitRequested: t.limit,
377
+ filters: s,
378
+ failureCode: "tool_failed",
379
+ failureStage: "retrieval"
380
+ }, !1), J(e, r, "failed"), E(n instanceof Error ? n.message : String(n));
381
+ }
382
+ }
383
+ //#endregion
384
+ //#region src/memory-access.ts
385
+ function X(e, t, n) {
386
+ return e.timeline(null, t, 0, 0, n ?? null).find((e) => e.id === t) ?? null;
387
+ }
388
+ function Z(e, t, n) {
389
+ if (t.length === 0) return [];
390
+ let r = [];
391
+ for (let i of t) {
392
+ let t = X(e, i, n);
393
+ t && r.push(t);
394
+ }
395
+ return r;
396
+ }
397
+ function ie(e, t, n) {
398
+ return X(e, t, n) ? (e.forget(t), !0) : !1;
399
+ }
400
+ function ae(e, t, n = {}) {
401
+ return e.db.transaction(() => {
402
+ let r = n.now?.() ?? (/* @__PURE__ */ new Date()).toISOString(), i = n.user ?? process.env.USER ?? "unknown", a = n.cwd ?? process.cwd(), o = C({
403
+ project: t.project,
404
+ envProject: n.envProject
405
+ }), s = e.db.prepare("INSERT INTO sessions(started_at, ended_at, cwd, project, user, tool_version, metadata_json)\n VALUES (?, ?, ?, ?, ?, ?, ?)").run(r, r, a, o, i, "mcp-ts", p({ mcp: !0 })), c = Number(s.lastInsertRowid), l = e.remember(c, t.kind, t.title, t.body, t.confidence);
406
+ if (!X(e, l)) throw Error("unauthorized_scope");
407
+ return e.db.prepare("UPDATE sessions SET ended_at = ?, metadata_json = ? WHERE id = ?").run(n.now?.() ?? (/* @__PURE__ */ new Date()).toISOString(), p({ mcp: !0 }), c), {
408
+ memId: l,
409
+ title: t.title,
410
+ body: t.body
411
+ };
412
+ })();
413
+ }
414
+ //#endregion
415
+ //#region src/tools/items.ts
416
+ function oe(e, t) {
417
+ let { envProject: n, store: r } = t;
418
+ e.tool("memory_get", "Fetch a single memory item by ID.", {
419
+ memory_id: y.number().int().describe("Memory ID"),
420
+ ...D
421
+ }, async (e, n) => Y(t, {
422
+ surface: "mcp_get",
423
+ toolName: "memory_get",
424
+ toolArguments: e,
425
+ limit: 1,
426
+ resolveFilters: () => w(e, null),
427
+ requestId: n?.requestId,
428
+ sourceSessionId: n?.sessionId,
429
+ invocationIdentity: n?.signal
430
+ }, (t) => {
431
+ let n = X(r, e.memory_id, t);
432
+ return n ? {
433
+ value: n,
434
+ memoryIds: [n.id],
435
+ filters: t
436
+ } : {
437
+ value: null,
438
+ memoryIds: [],
439
+ error: "not_found",
440
+ filters: t
441
+ };
442
+ })), e.tool("memory_get_observations", "Fetch multiple memory items by their IDs.", {
443
+ ids: y.array(y.number().int()).max(200).describe("Memory IDs to fetch"),
444
+ ...D
445
+ }, async (e, n) => Y(t, {
446
+ surface: "mcp_get_observations",
447
+ toolName: "memory_get_observations",
448
+ toolArguments: e,
449
+ limit: e.ids.length,
450
+ resolveFilters: () => w(e, null),
451
+ requestId: n?.requestId,
452
+ sourceSessionId: n?.sessionId,
453
+ invocationIdentity: n?.signal
454
+ }, (t) => {
455
+ let n = Z(r, e.ids, t);
456
+ return {
457
+ value: { items: n },
458
+ memoryIds: n.map((e) => e.id),
459
+ filters: t
460
+ };
461
+ })), e.tool("memory_remember", "Create a new memory. Use for milestones, decisions, and notable facts.", {
462
+ kind: O.describe("Memory kind"),
463
+ title: y.string().describe("Short title"),
464
+ body: y.string().describe("Body text (high-signal content)"),
465
+ confidence: y.number().min(0).max(1).default(.5).describe("Confidence 0-1"),
466
+ project: y.string().optional().describe("Project identifier")
467
+ }, async (e) => {
468
+ try {
469
+ let t = ae(r, e, { envProject: n() });
470
+ try {
471
+ await f(r.db, t.memId, t.title, t.body);
472
+ } catch {}
473
+ return T({ id: t.memId });
474
+ } catch (e) {
475
+ return E(e instanceof Error ? e.message : String(e));
476
+ }
477
+ }), e.tool("memory_forget", "Soft-delete a memory item. Use for incorrect or sensitive data.", {
478
+ memory_id: y.number().int().describe("Memory ID to forget"),
479
+ ...D
480
+ }, async (e) => {
481
+ try {
482
+ return ie(r, e.memory_id, w(e, null)) ? T({ status: "ok" }) : E("not_found");
483
+ } catch (e) {
484
+ return E(e instanceof Error ? e.message : String(e));
485
+ }
486
+ });
487
+ }
488
+ //#endregion
489
+ //#region src/tools/learn.ts
490
+ function se(e) {
491
+ e.tool("memory_learn", "Learn how to use codemem memory tools. Call this first if unfamiliar.", {}, async () => T({
492
+ intro: "Use this tool when you're new to codemem or unsure when to recall/persist.",
493
+ client_hint: "If you are unfamiliar with codemem, call memory.learn first.",
494
+ recall: {
495
+ when: ["Start of a task or when the user references prior work.", "When you need background context, decisions, or recent changes."],
496
+ how: [
497
+ "Use memory.search_index to get compact candidates.",
498
+ "Use memory.timeline to expand around a promising memory.",
499
+ "Use memory.get_observations for full details only when needed.",
500
+ "Use memory.pack for quick one-shot context blocks.",
501
+ "Use the project filter unless the user requests cross-project context."
502
+ ],
503
+ examples: [
504
+ "memory.search_index(\"billing cache bug\", limit=5)",
505
+ "memory.timeline(memory_id=123)",
506
+ "memory.get_observations([123, 456])"
507
+ ]
508
+ },
509
+ persistence: {
510
+ when: ["Milestones (task done, key decision, new facts learned).", "Notable regressions or follow-ups that should be remembered."],
511
+ how: [
512
+ "Use memory.remember with kind decision/discovery/change/exploration.",
513
+ "Keep titles short and bodies high-signal.",
514
+ "ALWAYS pass the project parameter if known."
515
+ ],
516
+ examples: ["memory.remember(kind=\"decision\", title=\"Switch to async cache\", body=\"...why...\", project=\"my-service\")", "memory.remember(kind=\"change\", title=\"Fixed retry loop\", body=\"...impact...\", project=\"my-service\")"]
517
+ },
518
+ forget: {
519
+ when: ["Accidental or sensitive data stored in memory items.", "Obsolete or incorrect items that should no longer surface."],
520
+ how: ["Call memory.forget(id) to mark the item inactive.", "Prefer forgetting over overwriting to preserve auditability."],
521
+ examples: ["memory.forget(123)"]
522
+ },
523
+ prompt_hint: "At task start: call memory.search_index; during work: memory.timeline + memory.get_observations; at milestones: memory.remember.",
524
+ recommended_system_prompt: [
525
+ "Trigger policy (1-liner): If the user references prior work or starts a task,",
526
+ "immediately call memory.search_index; then use memory.timeline + memory.get_observations;",
527
+ "at milestones, call memory.remember; use memory.forget for incorrect/sensitive items.",
528
+ "",
529
+ "System prompt:",
530
+ "You have access to codemem MCP tools. If unfamiliar, call memory.learn first.",
531
+ "",
532
+ "Recall:",
533
+ "- Start of any task: call memory.search_index with a concise task query.",
534
+ "- If prior work is referenced (\"as before\", \"last time\", \"we already did…\", \"regression\"),",
535
+ " call memory.search_index or memory.timeline.",
536
+ "- Use memory.get_observations only after filtering IDs.",
537
+ "- Prefer project-scoped queries unless the user asks for cross-project.",
538
+ "",
539
+ "Persistence:",
540
+ "- On milestones (task done, key decision, new facts learned), call memory.remember.",
541
+ "- Use kind=decision for tradeoffs, kind=change for outcomes, kind=discovery/exploration for useful findings.",
542
+ "- Keep titles short and bodies high-signal.",
543
+ "- ALWAYS pass the project parameter if known.",
544
+ "",
545
+ "Safety:",
546
+ "- Use memory.forget(id) for incorrect or sensitive items.",
547
+ "",
548
+ "Examples:",
549
+ "- memory.search_index(\"billing cache bug\")",
550
+ "- memory.timeline(memory_id=123)",
551
+ "- memory.get_observations([123, 456])",
552
+ "- memory.remember(kind=\"decision\", title=\"Use async cache\", body=\"Chose async cache to avoid lock contention in X.\", project=\"my-service\")",
553
+ "- memory.remember(kind=\"change\", title=\"Fixed retry loop\", body=\"Root cause was Y; added guard in Z.\", project=\"my-service\")",
554
+ "- memory.forget(123)"
555
+ ].join("\n")
556
+ }));
557
+ }
558
+ //#endregion
559
+ //#region src/memory-kinds.ts
560
+ var Q = {
561
+ discovery: "Something learned about the codebase, architecture, or tools",
562
+ change: "A code change that was made",
563
+ feature: "A new feature that was implemented",
564
+ bugfix: "A bug that was found and fixed",
565
+ refactor: "Code that was refactored or restructured",
566
+ decision: "A design or architecture decision",
567
+ exploration: "An experiment or investigation (may not have shipped)"
568
+ };
569
+ //#endregion
570
+ //#region src/tools/schema.ts
571
+ function ce(e) {
572
+ e.tool("memory_schema", "Return the memory schema — kinds, fields, and available filters.", {}, async () => T({
573
+ kinds: Object.keys(Q),
574
+ kind_descriptions: Q,
575
+ fields: {
576
+ title: "short text",
577
+ body: "long text",
578
+ subtitle: "short text",
579
+ facts: "list<string>",
580
+ narrative: "long text",
581
+ concepts: "list<string>",
582
+ files_read: "list<string>",
583
+ files_modified: "list<string>",
584
+ prompt_number: "int"
585
+ },
586
+ filters: k
587
+ }));
588
+ }
589
+ //#endregion
590
+ //#region src/tools/search.ts
591
+ function le(e, t) {
592
+ let { defaultProject: n, store: r } = t;
593
+ e.tool("memory_search", "Search memories by text query. Returns full body text for each match.", {
594
+ query: y.string().describe("Search query"),
595
+ limit: y.number().int().min(1).max(50).default(5).describe("Max results"),
596
+ ...D
597
+ }, async (e, i) => Y(t, {
598
+ surface: "mcp_search",
599
+ toolName: "memory_search",
600
+ toolArguments: e,
601
+ query: e.query,
602
+ limit: e.limit,
603
+ resolveFilters: () => w(e, n()),
604
+ requestId: i?.requestId,
605
+ sourceSessionId: i?.sessionId,
606
+ invocationIdentity: i?.signal
607
+ }, (t) => {
608
+ let n = r.search(e.query, e.limit, t);
609
+ return {
610
+ value: { items: n.map((e) => ({
611
+ id: e.id,
612
+ title: e.title,
613
+ kind: e.kind,
614
+ body: e.body_text,
615
+ confidence: e.confidence,
616
+ score: e.score,
617
+ session_id: e.session_id,
618
+ metadata: e.metadata
619
+ })) },
620
+ memoryIds: n.map((e) => e.id),
621
+ filters: t
622
+ };
623
+ })), e.tool("memory_search_index", "Search memories by text query. Returns compact index entries (no body) for browsing.", {
624
+ query: y.string().describe("Search query"),
625
+ limit: y.number().int().min(1).max(50).default(8).describe("Max results"),
626
+ ...D
627
+ }, async (e, i) => Y(t, {
628
+ surface: "mcp_search_index",
629
+ toolName: "memory_search_index",
630
+ toolArguments: e,
631
+ query: e.query,
632
+ limit: e.limit,
633
+ resolveFilters: () => w(e, n()),
634
+ requestId: i?.requestId,
635
+ sourceSessionId: i?.sessionId,
636
+ invocationIdentity: i?.signal
637
+ }, (t) => {
638
+ let n = r.search(e.query, e.limit, t);
639
+ return {
640
+ value: { items: n.map((e) => ({
641
+ id: e.id,
642
+ kind: e.kind,
643
+ title: e.title,
644
+ score: e.score,
645
+ created_at: e.created_at,
646
+ session_id: e.session_id,
647
+ metadata: e.metadata
648
+ })) },
649
+ memoryIds: n.map((e) => e.id),
650
+ filters: t
651
+ };
652
+ })), e.tool("memory_explain", "Explain search results with detailed scoring breakdown.", {
653
+ query: y.string().optional().describe("Search query"),
654
+ ids: y.array(y.number().int()).max(200).optional().describe("Specific memory IDs to explain"),
655
+ limit: y.number().int().min(1).max(50).default(10).describe("Max results"),
656
+ include_pack_context: y.boolean().default(!1).describe("Include formatted pack context"),
657
+ ...D
658
+ }, async (e, i) => Y(t, {
659
+ surface: "mcp_explain",
660
+ toolName: "memory_explain",
661
+ toolArguments: e,
662
+ query: e.query,
663
+ limit: e.limit,
664
+ resolveFilters: () => w(e, n()),
665
+ requestId: i?.requestId,
666
+ sourceSessionId: i?.sessionId,
667
+ invocationIdentity: i?.signal
668
+ }, (t) => {
669
+ let n = r.explain(e.query ?? null, e.ids ?? null, e.limit, t, { includePackContext: e.include_pack_context }), i = n.errors.some((e) => e.code === "INVALID_ARGUMENT" && e.field === "query");
670
+ return {
671
+ value: n,
672
+ memoryIds: n.items.map((e) => e.id),
673
+ filters: t,
674
+ retrievalStatus: i ? "failed" : void 0
675
+ };
676
+ })), e.tool("memory_recent", "Return recent memories, newest first.", {
677
+ limit: y.number().int().min(1).max(100).default(8).describe("Max results"),
678
+ ...D
679
+ }, async (e, i) => Y(t, {
680
+ surface: "mcp_recent",
681
+ toolName: "memory_recent",
682
+ toolArguments: e,
683
+ limit: e.limit,
684
+ resolveFilters: () => w(e, n()),
685
+ requestId: i?.requestId,
686
+ sourceSessionId: i?.sessionId,
687
+ invocationIdentity: i?.signal
688
+ }, (t) => {
689
+ let n = r.recent(e.limit, t);
690
+ return {
691
+ value: { items: n },
692
+ memoryIds: n.map((e) => e.id),
693
+ filters: t
694
+ };
695
+ })), e.tool("memory_pack", "Build a formatted memory pack from search results — quick one-shot context block.", {
696
+ context: y.string().describe("Context description to search for"),
697
+ limit: y.number().int().min(1).max(50).optional().describe("Max items to include"),
698
+ compact: y.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."),
699
+ compact_detail_count: y.number().int().min(0).max(50).optional().describe("Number of items to show in full detail in compact mode (default 3)"),
700
+ compression_mode: y.enum([
701
+ "off",
702
+ "compact",
703
+ "ids"
704
+ ]).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."),
705
+ ...D
706
+ }, async (e, i) => Y(t, {
707
+ surface: "mcp_pack",
708
+ toolName: "memory_pack",
709
+ toolArguments: e,
710
+ query: e.context,
711
+ limit: e.limit ?? null,
712
+ resolveFilters: () => w(e, n()),
713
+ requestId: i?.requestId,
714
+ sourceSessionId: i?.sessionId,
715
+ invocationIdentity: i?.signal
716
+ }, async (t) => {
717
+ let n = e.compact || e.compact_detail_count != null || e.compression_mode != null ? {
718
+ compact: e.compact ?? (e.compact_detail_count == null ? void 0 : !0),
719
+ compactDetailCount: e.compact_detail_count,
720
+ compressionMode: e.compression_mode
721
+ } : void 0, i = await r.buildMemoryPackAsync(e.context, e.limit ?? void 0, null, t, n);
722
+ return {
723
+ value: i,
724
+ memoryIds: i.item_ids,
725
+ filters: t
726
+ };
727
+ }));
728
+ }
729
+ //#endregion
730
+ //#region src/tools/timeline.ts
731
+ function $(e, t) {
732
+ let { defaultProject: n, store: r } = t;
733
+ e.tool("memory_timeline", "Get a chronological window of memories around an anchor (by ID or query).", {
734
+ query: y.string().optional().describe("Search query to find anchor"),
735
+ memory_id: y.number().int().optional().describe("Anchor memory ID"),
736
+ depth_before: y.number().int().min(0).default(3).describe("Items before anchor"),
737
+ depth_after: y.number().int().min(0).default(3).describe("Items after anchor"),
738
+ ...D
739
+ }, async (e, i) => Y(t, {
740
+ surface: "mcp_timeline",
741
+ toolName: "memory_timeline",
742
+ toolArguments: e,
743
+ query: e.query,
744
+ limit: e.depth_before + e.depth_after + 1,
745
+ resolveFilters: () => w(e, n()),
746
+ requestId: i?.requestId,
747
+ sourceSessionId: i?.sessionId,
748
+ invocationIdentity: i?.signal
749
+ }, (t) => {
750
+ let n = r.timeline(e.query ?? null, e.memory_id ?? null, e.depth_before, e.depth_after, t);
751
+ return {
752
+ value: { items: n },
753
+ memoryIds: n.map((e) => e.id),
754
+ filters: t
755
+ };
756
+ })), e.tool("memory_expand", "Fetch memories by ID with surrounding timeline context.", {
757
+ ids: y.array(y.union([y.number(), y.string()])).max(200).describe("Memory IDs to expand"),
758
+ depth_before: y.number().int().min(0).default(3).describe("Timeline items before"),
759
+ depth_after: y.number().int().min(0).default(3).describe("Timeline items after"),
760
+ include_observations: y.boolean().default(!1).describe("Include full observation details"),
761
+ ...D
762
+ }, async (e, i) => Y(t, {
763
+ surface: "mcp_expand",
764
+ toolName: "memory_expand",
765
+ toolArguments: e,
766
+ limit: e.ids.length,
767
+ resolveFilters: () => w(e, e.project !== void 0 && !e.project.trim() ? null : n()),
768
+ requestId: i?.requestId,
769
+ sourceSessionId: i?.sessionId,
770
+ invocationIdentity: i?.signal
771
+ }, (t) => {
772
+ let n = t?.project ?? null, { ordered: i, invalid: o } = a(e.ids), c = [];
773
+ o.length > 0 && c.push({
774
+ code: "INVALID_ARGUMENT",
775
+ field: "ids",
776
+ message: "some ids are not valid integers",
777
+ ids: o
778
+ });
779
+ let l = [], u = [], d = [], f = [], p = [], m = /* @__PURE__ */ new Set(), h = /* @__PURE__ */ new Map();
780
+ for (let a of i) {
781
+ let i = r.get(a);
782
+ if (!i?.active) {
783
+ l.push(a);
784
+ continue;
785
+ }
786
+ let o = i.session_id;
787
+ if (n && o > 0) {
788
+ if (!h.has(o)) {
789
+ let e = r.db.prepare("SELECT project FROM sessions WHERE id = ? LIMIT 1").get(o);
790
+ h.set(o, typeof e?.project == "string" ? e.project : null);
791
+ }
792
+ if (!s(n, h.get(o) ?? null)) {
793
+ u.push(a);
794
+ continue;
795
+ }
796
+ } else if (n && o <= 0) {
797
+ u.push(a);
798
+ continue;
799
+ }
800
+ let c = r.timeline(null, a, e.depth_before, e.depth_after, t), g = c.find((e) => e.id === a);
801
+ if (!g) {
802
+ d.push(a);
803
+ continue;
804
+ }
805
+ f.push(g);
806
+ for (let e of c) {
807
+ let t = e.id;
808
+ t <= 0 || m.has(t) || (m.add(t), p.push(e));
809
+ }
810
+ }
811
+ l.length > 0 && c.push({
812
+ code: "NOT_FOUND",
813
+ field: "ids",
814
+ message: "some requested ids were not found",
815
+ ids: l
816
+ }), u.length > 0 && c.push({
817
+ code: "PROJECT_MISMATCH",
818
+ field: "project",
819
+ message: "some requested ids are outside the requested project scope",
820
+ ids: u
821
+ }), d.length > 0 && c.push({
822
+ code: "FILTER_MISMATCH",
823
+ field: "filters",
824
+ message: "some requested ids are outside the requested filters",
825
+ ids: d
826
+ });
827
+ let g = [];
828
+ if (e.include_observations) {
829
+ let e = /* @__PURE__ */ new Set(), n = [];
830
+ for (let t of [...f, ...p]) t.id > 0 && !e.has(t.id) && (e.add(t.id), n.push(t.id));
831
+ g = Z(r, n, t);
832
+ }
833
+ return {
834
+ value: {
835
+ anchors: f,
836
+ timeline: p,
837
+ observations: g,
838
+ missing_ids: i.filter((e) => l.includes(e) || u.includes(e) || d.includes(e)),
839
+ errors: c,
840
+ metadata: {
841
+ project: n,
842
+ requested_ids_count: i.length,
843
+ returned_anchor_count: f.length,
844
+ timeline_count: p.length,
845
+ include_observations: e.include_observations
846
+ }
847
+ },
848
+ memoryIds: [...new Set([
849
+ ...f,
850
+ ...p,
851
+ ...g
852
+ ].map((e) => e.id))],
853
+ filters: t
854
+ };
855
+ }));
856
+ }
857
+ //#endregion
858
+ //#region src/server.ts
859
+ function ue(e, n = {}) {
860
+ let i = new v({
861
+ name: "codemem",
862
+ version: r
863
+ }), a = {
864
+ store: e,
865
+ defaultProject: () => n.resolveDefaultProject ? n.resolveDefaultProject() : n.defaultProject === void 0 ? S() : n.defaultProject,
866
+ envProject: () => n.envProject === void 0 ? process.env.CODEMEM_PROJECT ?? null : n.envProject,
867
+ captureRetrievalLedger: n.captureRetrievalLedger !== !1,
868
+ retrievalLedgerScopeId: n.retrievalLedgerScopeId ?? t(),
869
+ retrievalLedgerIdentityMode: n.retrievalLedgerIdentityMode ?? "session"
870
+ };
871
+ return le(i, a), $(i, a), te(i, a), oe(i, a), ce(i), se(i), i;
872
+ }
873
+ //#endregion
874
+ export { b as n, ue as t };
875
+
876
+ //# sourceMappingURL=server-BshtPXit.js.map