@codemem/mcp 0.44.0-beta.1 → 0.44.0

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as e, t } from "./server-C8Yl-9J0.js";
2
+ import { n as e, t } from "./server-D-jxqflv.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-C8Yl-9J0.js";
1
+ import { t as e } from "./server-D-jxqflv.js";
2
2
  export { e as createCodememMcpServer };
@@ -699,9 +699,9 @@ function $(e, t) {
699
699
  compact: e.compact ?? (e.compact_detail_count != null || void 0),
700
700
  compactDetailCount: e.compact_detail_count,
701
701
  compressionMode: e.compression_mode
702
- } : void 0, i = await r.buildMemoryPackAsync(e.context, e.limit ?? void 0, null, t, n);
702
+ } : void 0, i = await r.buildMemoryPackAsync(e.context, e.limit ?? void 0, null, t, n), { rendered_items: a, ...o } = i;
703
703
  return {
704
- value: i,
704
+ value: o,
705
705
  memoryIds: i.item_ids,
706
706
  filters: t
707
707
  };
@@ -854,4 +854,4 @@ function de(e, n = {}) {
854
854
  //#endregion
855
855
  export { x as n, de as t };
856
856
 
857
- //# sourceMappingURL=server-C8Yl-9J0.js.map
857
+ //# sourceMappingURL=server-D-jxqflv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-C8Yl-9J0.js","names":[],"sources":["../src/canonical-json.ts","../src/project-scope.ts","../src/content.ts","../src/schemas.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","export function jsonContent(data: unknown) {\n\treturn { content: [{ type: \"text\" as const, text: JSON.stringify(data) }] };\n}\n\nexport function errorContent(message: string) {\n\treturn { content: [{ type: \"text\" as const, text: JSON.stringify({ error: message }) }] };\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 { 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\";\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.tool(\n\t\t\"memory_distill_candidates\",\n\t\t\"Mine recurring memories into reviewable context candidates. Read-only; does not modify context files.\",\n\t\t{\n\t\t\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max candidates\"),\n\t\t\tmin_recurrence: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(1)\n\t\t\t\t.max(50)\n\t\t\t\t.default(2)\n\t\t\t\t.describe(\"Minimum member count per candidate\"),\n\t\t\tall_projects: z.boolean().default(false).describe(\"Mine memories across all projects\"),\n\t\t\tinclude_documented: z\n\t\t\t\t.boolean()\n\t\t\t\t.default(false)\n\t\t\t\t.describe(\"Include candidates already represented in context files\"),\n\t\t\tmax_evidence_items: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(1)\n\t\t\t\t.max(20)\n\t\t\t\t.default(5)\n\t\t\t\t.describe(\"Evidence snippets per candidate\"),\n\t\t\tjudge: z\n\t\t\t\t.boolean()\n\t\t\t\t.default(true)\n\t\t\t\t.describe(\n\t\t\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\t\t),\n\t\t\t...filterSchema,\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\";\n\nexport function registerItemTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { envProject, store } = context;\n\n\tserver.tool(\n\t\t\"memory_get\",\n\t\t\"Fetch a single memory item by ID.\",\n\t\t{\n\t\t\tmemory_id: z.number().int().describe(\"Memory ID\"),\n\t\t\t...filterSchema,\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(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\tserver.tool(\n\t\t\"memory_get_observations\",\n\t\t\"Fetch multiple memory items by their IDs.\",\n\t\t{\n\t\t\tids: z.array(z.number().int()).max(200).describe(\"Memory IDs to fetch\"),\n\t\t\t...filterSchema,\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(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\tserver.tool(\n\t\t\"memory_remember\",\n\t\t\"Create a new memory. Use for milestones, decisions, and notable facts.\",\n\t\t{\n\t\t\tkind: memoryKindSchema.describe(\"Memory kind\"),\n\t\t\ttitle: z.string().describe(\"Short title\"),\n\t\t\tbody: z.string().describe(\"Body text (high-signal content)\"),\n\t\t\tconfidence: z.number().min(0).max(1).default(0.5).describe(\"Confidence 0-1\"),\n\t\t\tproject: z.string().optional().describe(\"Project identifier\"),\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(store, args, {\n\t\t\t\t\tenvProject: envProject(),\n\t\t\t\t});\n\n\t\t\t\ttry {\n\t\t\t\t\tawait storeVectors(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\tserver.tool(\n\t\t\"memory_forget\",\n\t\t\"Soft-delete a memory item. Use for incorrect or sensitive data.\",\n\t\t{\n\t\t\tmemory_id: z.number().int().describe(\"Memory ID to forget\"),\n\t\t\t...filterSchema,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\tif (!forgetMemoryForMcp(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","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { jsonContent } from \"../content.js\";\n\nexport function registerLearnTools(server: McpServer): void {\n\tserver.tool(\n\t\t\"memory_learn\",\n\t\t\"Learn how to use codemem memory tools. Call this first if unfamiliar.\",\n\t\t{},\n\t\tasync () => {\n\t\t\treturn jsonContent({\n\t\t\t\tintro: \"Use this tool when you're new to codemem or unsure when to recall/persist.\",\n\t\t\t\tclient_hint: \"If you are unfamiliar with codemem, call memory.learn first.\",\n\t\t\t\trecall: {\n\t\t\t\t\twhen: [\n\t\t\t\t\t\t\"Start of a task or when the user references prior work.\",\n\t\t\t\t\t\t\"When you need background context, decisions, or recent changes.\",\n\t\t\t\t\t],\n\t\t\t\t\thow: [\n\t\t\t\t\t\t\"Use memory.search_index to get compact candidates.\",\n\t\t\t\t\t\t\"Use memory.timeline to expand around a promising memory.\",\n\t\t\t\t\t\t\"Use memory.get_observations for full details only when needed.\",\n\t\t\t\t\t\t\"Use memory.pack for quick one-shot context blocks.\",\n\t\t\t\t\t\t\"Use the project filter unless the user requests cross-project context.\",\n\t\t\t\t\t],\n\t\t\t\t\texamples: [\n\t\t\t\t\t\t'memory.search_index(\"billing cache bug\", limit=5)',\n\t\t\t\t\t\t\"memory.timeline(memory_id=123)\",\n\t\t\t\t\t\t\"memory.get_observations([123, 456])\",\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tpersistence: {\n\t\t\t\t\twhen: [\n\t\t\t\t\t\t\"Milestones (task done, key decision, new facts learned).\",\n\t\t\t\t\t\t\"Notable regressions or follow-ups that should be remembered.\",\n\t\t\t\t\t],\n\t\t\t\t\thow: [\n\t\t\t\t\t\t\"Use memory.remember with kind decision/discovery/change/exploration.\",\n\t\t\t\t\t\t\"Keep titles short and bodies high-signal.\",\n\t\t\t\t\t\t\"ALWAYS pass the project parameter if known.\",\n\t\t\t\t\t],\n\t\t\t\t\texamples: [\n\t\t\t\t\t\t'memory.remember(kind=\"decision\", title=\"Switch to async cache\", body=\"...why...\", project=\"my-service\")',\n\t\t\t\t\t\t'memory.remember(kind=\"change\", title=\"Fixed retry loop\", body=\"...impact...\", project=\"my-service\")',\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tforget: {\n\t\t\t\t\twhen: [\n\t\t\t\t\t\t\"Accidental or sensitive data stored in memory items.\",\n\t\t\t\t\t\t\"Obsolete or incorrect items that should no longer surface.\",\n\t\t\t\t\t],\n\t\t\t\t\thow: [\n\t\t\t\t\t\t\"Call memory.forget(id) to mark the item inactive.\",\n\t\t\t\t\t\t\"Prefer forgetting over overwriting to preserve auditability.\",\n\t\t\t\t\t],\n\t\t\t\t\texamples: [\"memory.forget(123)\"],\n\t\t\t\t},\n\t\t\t\tprompt_hint:\n\t\t\t\t\t\"At task start: call memory.search_index; during work: memory.timeline + memory.get_observations; at milestones: memory.remember.\",\n\t\t\t\trecommended_system_prompt: [\n\t\t\t\t\t\"Trigger policy (1-liner): If the user references prior work or starts a task,\",\n\t\t\t\t\t\"immediately call memory.search_index; then use memory.timeline + memory.get_observations;\",\n\t\t\t\t\t\"at milestones, call memory.remember; use memory.forget for incorrect/sensitive items.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"System prompt:\",\n\t\t\t\t\t\"You have access to codemem MCP tools. If unfamiliar, call memory.learn first.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Recall:\",\n\t\t\t\t\t\"- Start of any task: call memory.search_index with a concise task query.\",\n\t\t\t\t\t'- If prior work is referenced (\"as before\", \"last time\", \"we already did…\", \"regression\"),',\n\t\t\t\t\t\" call memory.search_index or memory.timeline.\",\n\t\t\t\t\t\"- Use memory.get_observations only after filtering IDs.\",\n\t\t\t\t\t\"- Prefer project-scoped queries unless the user asks for cross-project.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Persistence:\",\n\t\t\t\t\t\"- On milestones (task done, key decision, new facts learned), call memory.remember.\",\n\t\t\t\t\t\"- Use kind=decision for tradeoffs, kind=change for outcomes, kind=discovery/exploration for useful findings.\",\n\t\t\t\t\t\"- Keep titles short and bodies high-signal.\",\n\t\t\t\t\t\"- ALWAYS pass the project parameter if known.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Safety:\",\n\t\t\t\t\t\"- Use memory.forget(id) for incorrect or sensitive items.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Examples:\",\n\t\t\t\t\t'- memory.search_index(\"billing cache bug\")',\n\t\t\t\t\t\"- memory.timeline(memory_id=123)\",\n\t\t\t\t\t\"- memory.get_observations([123, 456])\",\n\t\t\t\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\t\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\t\t\t\"- memory.forget(123)\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t});\n\t\t},\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\";\n\nexport function registerSchemaTools(server: McpServer): void {\n\tserver.tool(\n\t\t\"memory_schema\",\n\t\t\"Return the memory schema — kinds, fields, and available filters.\",\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\";\n\nexport function registerSearchTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.tool(\n\t\t\"memory_search\",\n\t\t\"Search memories by text query. Returns full body text for each match.\",\n\t\t{\n\t\t\tquery: z.string().describe(\"Search query\"),\n\t\t\tlimit: z.number().int().min(1).max(50).default(5).describe(\"Max results\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_search_index\",\n\t\t\"Search memories by text query. Returns compact index entries (no body) for browsing.\",\n\t\t{\n\t\t\tquery: z.string().describe(\"Search query\"),\n\t\t\tlimit: z.number().int().min(1).max(50).default(8).describe(\"Max results\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_explain\",\n\t\t\"Explain search results with detailed scoring breakdown.\",\n\t\t{\n\t\t\tquery: z.string().optional().describe(\"Search query\"),\n\t\t\tids: z.array(z.number().int()).max(200).optional().describe(\"Specific memory IDs to explain\"),\n\t\t\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max results\"),\n\t\t\tinclude_pack_context: z.boolean().default(false).describe(\"Include formatted pack context\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_recent\",\n\t\t\"Return recent memories, newest first.\",\n\t\t{\n\t\t\tlimit: z.number().int().min(1).max(100).default(8).describe(\"Max results\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_pack\",\n\t\t\"Build a formatted memory pack from search results — quick one-shot context block.\",\n\t\t{\n\t\t\tcontext: z.string().describe(\"Context description to search for\"),\n\t\t\tlimit: z.number().int().min(1).max(50).optional().describe(\"Max items to include\"),\n\t\t\tcompact: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\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\t\t),\n\t\t\tcompact_detail_count: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(50)\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Number of items to show in full detail in compact mode (default 3)\"),\n\t\t\tcompression_mode: z\n\t\t\t\t.enum([\"off\", \"compact\", \"ids\"])\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\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\t\t),\n\t\t\t...filterSchema,\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\treturn { value: result, 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\";\n\nexport function registerTimelineTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.tool(\n\t\t\"memory_timeline\",\n\t\t\"Get a chronological window of memories around an anchor (by ID or query).\",\n\t\t{\n\t\t\tquery: z.string().optional().describe(\"Search query to find anchor\"),\n\t\t\tmemory_id: z.number().int().optional().describe(\"Anchor memory ID\"),\n\t\t\tdepth_before: z.number().int().min(0).default(3).describe(\"Items before anchor\"),\n\t\t\tdepth_after: z.number().int().min(0).default(3).describe(\"Items after anchor\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_expand\",\n\t\t\"Fetch memories by ID with surrounding timeline context.\",\n\t\t{\n\t\t\tids: z\n\t\t\t\t.array(z.union([z.number(), z.string()]))\n\t\t\t\t.max(200)\n\t\t\t\t.describe(\"Memory IDs to expand\"),\n\t\t\tdepth_before: z.number().int().min(0).default(3).describe(\"Timeline items before\"),\n\t\t\tdepth_after: z.number().int().min(0).default(3).describe(\"Timeline items after\"),\n\t\t\tinclude_observations: z.boolean().default(false).describe(\"Include full observation details\"),\n\t\t\t...filterSchema,\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,EAAoB,GAGlB;CACjB,OAAO,EAAa,EAAM,OAAO,KAAK,EAAa,EAAM,UAAU,KAAK;AACzE;AAEA,SAAgB,EACf,GACA,IAAiB,EAAsB,GACX;CAC5B,IAAM,IAAyB,CAAC,GAC5B,IAAS,IAGP,KADkB,OAAO,EAAI,WAAY,WAAW,EAAa,EAAI,OAAO,IAAI,KAAA,MAC3C,EAAa,CAAc,KAAK,KAAA;CAC3E,AAAI,MACH,EAAQ,UAAU,GAClB,IAAS;CAGV,KAAK,IAAM,KAAO;EACjB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,GAAY;EACX,IAAM,IAAM,EAAI;EAChB,AAAI,KAA6B,SAChC,EAAqC,KAAO,GAC5C,IA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AQ,CAAO,GACnC,GAAsB,GAAQ,CAAO,GACrC,GAAqB,GAAQ,CAAO,GACpC,GAAkB,GAAQ,CAAO,GACjC,GAAoB,CAAM,GAC1B,GAAmB,CAAM,GAElB;AACR"}
1
+ {"version":3,"file":"server-D-jxqflv.js","names":[],"sources":["../src/canonical-json.ts","../src/project-scope.ts","../src/content.ts","../src/schemas.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","export function jsonContent(data: unknown) {\n\treturn { content: [{ type: \"text\" as const, text: JSON.stringify(data) }] };\n}\n\nexport function errorContent(message: string) {\n\treturn { content: [{ type: \"text\" as const, text: JSON.stringify({ error: message }) }] };\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 { 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\";\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.tool(\n\t\t\"memory_distill_candidates\",\n\t\t\"Mine recurring memories into reviewable context candidates. Read-only; does not modify context files.\",\n\t\t{\n\t\t\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max candidates\"),\n\t\t\tmin_recurrence: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(1)\n\t\t\t\t.max(50)\n\t\t\t\t.default(2)\n\t\t\t\t.describe(\"Minimum member count per candidate\"),\n\t\t\tall_projects: z.boolean().default(false).describe(\"Mine memories across all projects\"),\n\t\t\tinclude_documented: z\n\t\t\t\t.boolean()\n\t\t\t\t.default(false)\n\t\t\t\t.describe(\"Include candidates already represented in context files\"),\n\t\t\tmax_evidence_items: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(1)\n\t\t\t\t.max(20)\n\t\t\t\t.default(5)\n\t\t\t\t.describe(\"Evidence snippets per candidate\"),\n\t\t\tjudge: z\n\t\t\t\t.boolean()\n\t\t\t\t.default(true)\n\t\t\t\t.describe(\n\t\t\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\t\t),\n\t\t\t...filterSchema,\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\";\n\nexport function registerItemTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { envProject, store } = context;\n\n\tserver.tool(\n\t\t\"memory_get\",\n\t\t\"Fetch a single memory item by ID.\",\n\t\t{\n\t\t\tmemory_id: z.number().int().describe(\"Memory ID\"),\n\t\t\t...filterSchema,\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(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\tserver.tool(\n\t\t\"memory_get_observations\",\n\t\t\"Fetch multiple memory items by their IDs.\",\n\t\t{\n\t\t\tids: z.array(z.number().int()).max(200).describe(\"Memory IDs to fetch\"),\n\t\t\t...filterSchema,\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(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\tserver.tool(\n\t\t\"memory_remember\",\n\t\t\"Create a new memory. Use for milestones, decisions, and notable facts.\",\n\t\t{\n\t\t\tkind: memoryKindSchema.describe(\"Memory kind\"),\n\t\t\ttitle: z.string().describe(\"Short title\"),\n\t\t\tbody: z.string().describe(\"Body text (high-signal content)\"),\n\t\t\tconfidence: z.number().min(0).max(1).default(0.5).describe(\"Confidence 0-1\"),\n\t\t\tproject: z.string().optional().describe(\"Project identifier\"),\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(store, args, {\n\t\t\t\t\tenvProject: envProject(),\n\t\t\t\t});\n\n\t\t\t\ttry {\n\t\t\t\t\tawait storeVectors(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\tserver.tool(\n\t\t\"memory_forget\",\n\t\t\"Soft-delete a memory item. Use for incorrect or sensitive data.\",\n\t\t{\n\t\t\tmemory_id: z.number().int().describe(\"Memory ID to forget\"),\n\t\t\t...filterSchema,\n\t\t},\n\t\tasync (args) => {\n\t\t\ttry {\n\t\t\t\tif (!forgetMemoryForMcp(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","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { jsonContent } from \"../content.js\";\n\nexport function registerLearnTools(server: McpServer): void {\n\tserver.tool(\n\t\t\"memory_learn\",\n\t\t\"Learn how to use codemem memory tools. Call this first if unfamiliar.\",\n\t\t{},\n\t\tasync () => {\n\t\t\treturn jsonContent({\n\t\t\t\tintro: \"Use this tool when you're new to codemem or unsure when to recall/persist.\",\n\t\t\t\tclient_hint: \"If you are unfamiliar with codemem, call memory.learn first.\",\n\t\t\t\trecall: {\n\t\t\t\t\twhen: [\n\t\t\t\t\t\t\"Start of a task or when the user references prior work.\",\n\t\t\t\t\t\t\"When you need background context, decisions, or recent changes.\",\n\t\t\t\t\t],\n\t\t\t\t\thow: [\n\t\t\t\t\t\t\"Use memory.search_index to get compact candidates.\",\n\t\t\t\t\t\t\"Use memory.timeline to expand around a promising memory.\",\n\t\t\t\t\t\t\"Use memory.get_observations for full details only when needed.\",\n\t\t\t\t\t\t\"Use memory.pack for quick one-shot context blocks.\",\n\t\t\t\t\t\t\"Use the project filter unless the user requests cross-project context.\",\n\t\t\t\t\t],\n\t\t\t\t\texamples: [\n\t\t\t\t\t\t'memory.search_index(\"billing cache bug\", limit=5)',\n\t\t\t\t\t\t\"memory.timeline(memory_id=123)\",\n\t\t\t\t\t\t\"memory.get_observations([123, 456])\",\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tpersistence: {\n\t\t\t\t\twhen: [\n\t\t\t\t\t\t\"Milestones (task done, key decision, new facts learned).\",\n\t\t\t\t\t\t\"Notable regressions or follow-ups that should be remembered.\",\n\t\t\t\t\t],\n\t\t\t\t\thow: [\n\t\t\t\t\t\t\"Use memory.remember with kind decision/discovery/change/exploration.\",\n\t\t\t\t\t\t\"Keep titles short and bodies high-signal.\",\n\t\t\t\t\t\t\"ALWAYS pass the project parameter if known.\",\n\t\t\t\t\t],\n\t\t\t\t\texamples: [\n\t\t\t\t\t\t'memory.remember(kind=\"decision\", title=\"Switch to async cache\", body=\"...why...\", project=\"my-service\")',\n\t\t\t\t\t\t'memory.remember(kind=\"change\", title=\"Fixed retry loop\", body=\"...impact...\", project=\"my-service\")',\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tforget: {\n\t\t\t\t\twhen: [\n\t\t\t\t\t\t\"Accidental or sensitive data stored in memory items.\",\n\t\t\t\t\t\t\"Obsolete or incorrect items that should no longer surface.\",\n\t\t\t\t\t],\n\t\t\t\t\thow: [\n\t\t\t\t\t\t\"Call memory.forget(id) to mark the item inactive.\",\n\t\t\t\t\t\t\"Prefer forgetting over overwriting to preserve auditability.\",\n\t\t\t\t\t],\n\t\t\t\t\texamples: [\"memory.forget(123)\"],\n\t\t\t\t},\n\t\t\t\tprompt_hint:\n\t\t\t\t\t\"At task start: call memory.search_index; during work: memory.timeline + memory.get_observations; at milestones: memory.remember.\",\n\t\t\t\trecommended_system_prompt: [\n\t\t\t\t\t\"Trigger policy (1-liner): If the user references prior work or starts a task,\",\n\t\t\t\t\t\"immediately call memory.search_index; then use memory.timeline + memory.get_observations;\",\n\t\t\t\t\t\"at milestones, call memory.remember; use memory.forget for incorrect/sensitive items.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"System prompt:\",\n\t\t\t\t\t\"You have access to codemem MCP tools. If unfamiliar, call memory.learn first.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Recall:\",\n\t\t\t\t\t\"- Start of any task: call memory.search_index with a concise task query.\",\n\t\t\t\t\t'- If prior work is referenced (\"as before\", \"last time\", \"we already did…\", \"regression\"),',\n\t\t\t\t\t\" call memory.search_index or memory.timeline.\",\n\t\t\t\t\t\"- Use memory.get_observations only after filtering IDs.\",\n\t\t\t\t\t\"- Prefer project-scoped queries unless the user asks for cross-project.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Persistence:\",\n\t\t\t\t\t\"- On milestones (task done, key decision, new facts learned), call memory.remember.\",\n\t\t\t\t\t\"- Use kind=decision for tradeoffs, kind=change for outcomes, kind=discovery/exploration for useful findings.\",\n\t\t\t\t\t\"- Keep titles short and bodies high-signal.\",\n\t\t\t\t\t\"- ALWAYS pass the project parameter if known.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Safety:\",\n\t\t\t\t\t\"- Use memory.forget(id) for incorrect or sensitive items.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Examples:\",\n\t\t\t\t\t'- memory.search_index(\"billing cache bug\")',\n\t\t\t\t\t\"- memory.timeline(memory_id=123)\",\n\t\t\t\t\t\"- memory.get_observations([123, 456])\",\n\t\t\t\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\t\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\t\t\t\"- memory.forget(123)\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t});\n\t\t},\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\";\n\nexport function registerSchemaTools(server: McpServer): void {\n\tserver.tool(\n\t\t\"memory_schema\",\n\t\t\"Return the memory schema — kinds, fields, and available filters.\",\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\";\n\nexport function registerSearchTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.tool(\n\t\t\"memory_search\",\n\t\t\"Search memories by text query. Returns full body text for each match.\",\n\t\t{\n\t\t\tquery: z.string().describe(\"Search query\"),\n\t\t\tlimit: z.number().int().min(1).max(50).default(5).describe(\"Max results\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_search_index\",\n\t\t\"Search memories by text query. Returns compact index entries (no body) for browsing.\",\n\t\t{\n\t\t\tquery: z.string().describe(\"Search query\"),\n\t\t\tlimit: z.number().int().min(1).max(50).default(8).describe(\"Max results\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_explain\",\n\t\t\"Explain search results with detailed scoring breakdown.\",\n\t\t{\n\t\t\tquery: z.string().optional().describe(\"Search query\"),\n\t\t\tids: z.array(z.number().int()).max(200).optional().describe(\"Specific memory IDs to explain\"),\n\t\t\tlimit: z.number().int().min(1).max(50).default(10).describe(\"Max results\"),\n\t\t\tinclude_pack_context: z.boolean().default(false).describe(\"Include formatted pack context\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_recent\",\n\t\t\"Return recent memories, newest first.\",\n\t\t{\n\t\t\tlimit: z.number().int().min(1).max(100).default(8).describe(\"Max results\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_pack\",\n\t\t\"Build a formatted memory pack from search results — quick one-shot context block.\",\n\t\t{\n\t\t\tcontext: z.string().describe(\"Context description to search for\"),\n\t\t\tlimit: z.number().int().min(1).max(50).optional().describe(\"Max items to include\"),\n\t\t\tcompact: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\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\t\t),\n\t\t\tcompact_detail_count: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(50)\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Number of items to show in full detail in compact mode (default 3)\"),\n\t\t\tcompression_mode: z\n\t\t\t\t.enum([\"off\", \"compact\", \"ids\"])\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\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\t\t),\n\t\t\t...filterSchema,\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\";\n\nexport function registerTimelineTools(server: McpServer, context: ToolRegistrationContext): void {\n\tconst { defaultProject, store } = context;\n\n\tserver.tool(\n\t\t\"memory_timeline\",\n\t\t\"Get a chronological window of memories around an anchor (by ID or query).\",\n\t\t{\n\t\t\tquery: z.string().optional().describe(\"Search query to find anchor\"),\n\t\t\tmemory_id: z.number().int().optional().describe(\"Anchor memory ID\"),\n\t\t\tdepth_before: z.number().int().min(0).default(3).describe(\"Items before anchor\"),\n\t\t\tdepth_after: z.number().int().min(0).default(3).describe(\"Items after anchor\"),\n\t\t\t...filterSchema,\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.tool(\n\t\t\"memory_expand\",\n\t\t\"Fetch memories by ID with surrounding timeline context.\",\n\t\t{\n\t\t\tids: z\n\t\t\t\t.array(z.union([z.number(), z.string()]))\n\t\t\t\t.max(200)\n\t\t\t\t.describe(\"Memory IDs to expand\"),\n\t\t\tdepth_before: z.number().int().min(0).default(3).describe(\"Timeline items before\"),\n\t\t\tdepth_after: z.number().int().min(0).default(3).describe(\"Timeline items after\"),\n\t\t\tinclude_observations: z.boolean().default(false).describe(\"Include full observation details\"),\n\t\t\t...filterSchema,\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,EAAoB,GAGlB;CACjB,OAAO,EAAa,EAAM,OAAO,KAAK,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AS,EAAK,EAAE,CAAC,CAElE;GAAW;EAAQ;CACpC,CACD,CAEF;AACD;;;AC9MA,SAAgB,GACf,GACA,IAAmC,CAAC,GACxB;CACZ,IAAM,IAAS,IAAI,EAAU;EAAE,MAAM;EAAW,SAAS;CAAQ,CAAC,GAC5D,IAAmC;EACxC;EAGA,sBACK,EAAQ,wBAA8B,EAAQ,sBAAsB,IACpE,EAAQ,mBAAmB,KAAA,IACxB,EAAsB,IADoB,EAAQ;EAG1D,kBACC,EAAQ,eAAe,KAAA,IAAkC,QAAQ,IAAI,mBAAmB,OAArD,EAAQ;EAC5C,wBAAwB,EAAQ,2BAA2B;EAC3D,wBAAwB,EAAQ,0BAA0B,EAAW;EACrE,6BAA6B,EAAQ,+BAA+B;CACrE;CASA,OAPA,EAAoB,GAAQ,CAAO,GACnC,GAAsB,GAAQ,CAAO,GACrC,GAAqB,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-C8Yl-9J0.js";
2
+ import { t as e } from "./server-D-jxqflv.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":"search.d.ts","sourceRoot":"","sources":["../../src/tools/search.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAKzE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAElE,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAgO7F"}
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/tools/search.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAKzE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAElE,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAkO7F"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codemem/mcp",
3
- "version": "0.44.0-beta.1",
3
+ "version": "0.44.0",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "exports": {
@@ -27,7 +27,7 @@
27
27
  "dist/"
28
28
  ],
29
29
  "dependencies": {
30
- "@codemem/core": "^0.44.0-beta.1",
30
+ "@codemem/core": "^0.44.0",
31
31
  "@modelcontextprotocol/sdk": "^1.30.0",
32
32
  "express": "^5.2.1",
33
33
  "express-rate-limit": "^8.7.0",