@sentry/junior-memory 0.91.0 → 0.92.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.d.ts +47 -5
- package/dist/index.js +165 -74
- package/dist/index.js.map +1 -1
- package/dist/recall.d.ts +2 -2
- package/dist/store.d.ts +1 -1
- package/dist/tools.d.ts +2 -2
- package/dist/types.d.ts +4 -4
- package/package.json +2 -2
- package/src/agent.ts +106 -31
- package/src/plugin.ts +6 -5
- package/src/process-session.ts +116 -18
- package/src/recall.ts +9 -17
- package/src/scope.ts +11 -11
- package/src/store.ts +1 -1
- package/src/tools.ts +8 -8
- package/src/types.ts +4 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugin.ts","../src/agent.ts","../src/types.ts","../src/cli/search.ts","../src/db/schema.ts","../src/cli/format.ts","../src/cli/show.ts","../src/cli/index.ts","../src/tools.ts","../src/store.ts","../src/scope.ts","../src/process-session.ts","../src/recall.ts"],"sourcesContent":["import { defineJuniorPlugin } from \"@sentry/junior-plugin-api\";\nimport { createMemoryAgent } from \"./agent\";\nimport { createMemoryCliCommand } from \"./cli\";\nimport {\n createMemoryCreateTool,\n createMemoryListTool,\n createMemoryRemoveTool,\n createMemorySearchTool,\n type MemoryCreateToolContext,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { createMemoryPromptMessages } from \"./recall\";\nimport type { MemoryDb } from \"./store\";\n\nconst MEMORY_MODEL_ENV = \"AI_MEMORY_MODEL\";\nconst MEMORY_RECALL_MAX_VECTOR_DISTANCE_ENV = \"MEMORY_RECALL_MAX_VECTOR_DISTANCE\";\nconst DEFAULT_RECALL_MAX_VECTOR_DISTANCE = 0.45;\n\nexport interface MemoryPluginOptions {\n modelId?: string;\n /** Maximum cosine distance for vector recall candidates. Defaults to MEMORY_RECALL_MAX_VECTOR_DISTANCE env or 0.45. */\n recallMaxVectorDistance?: number;\n}\n\nfunction memoryModelId(options: MemoryPluginOptions): string | undefined {\n const explicitModelId = options.modelId?.trim();\n if (explicitModelId) {\n return explicitModelId;\n }\n const envModelId = process.env[MEMORY_MODEL_ENV]?.trim();\n return envModelId || undefined;\n}\n\nfunction recallMaxVectorDistance(options: MemoryPluginOptions): number {\n if (options.recallMaxVectorDistance !== undefined) {\n return options.recallMaxVectorDistance;\n }\n const raw = process.env[MEMORY_RECALL_MAX_VECTOR_DISTANCE_ENV]?.trim();\n if (raw) {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed > 0) {\n return Math.min(parsed, 1);\n }\n }\n return DEFAULT_RECALL_MAX_VECTOR_DISTANCE;\n}\n\nfunction memoryToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryToolContext[\"db\"];\n embedder?: MemoryToolContext[\"embedder\"];\n requester?: MemoryToolContext[\"requester\"];\n source: MemoryToolContext[\"source\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.requester ? { requester: ctx.requester } : {}),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : {}),\n source: ctx.source,\n ...(ctx.userText ? { userText: ctx.userText } : {}),\n };\n}\n\nfunction memoryCreateToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryCreateToolContext[\"db\"];\n embedder?: MemoryCreateToolContext[\"embedder\"];\n requester?: MemoryCreateToolContext[\"requester\"];\n source: MemoryCreateToolContext[\"source\"];\n supersessionDecider: MemoryCreateToolContext[\"supersessionDecider\"];\n userText?: string;\n}): MemoryCreateToolContext {\n return {\n ...memoryToolContext(ctx),\n supersessionDecider: ctx.supersessionDecider,\n };\n}\n\n/** Create Junior's long-term memory plugin registration. */\nexport function createMemoryPlugin(options: MemoryPluginOptions = {}) {\n const modelId = memoryModelId(options);\n return defineJuniorPlugin({\n manifest: {\n name: \"memory\",\n displayName: \"Memory\",\n description: \"Long-term Junior memory storage and recall\",\n },\n model: modelId\n ? { structuredModelId: modelId }\n : { structuredModel: \"default\" },\n packageName: \"@sentry/junior-memory\",\n cli: {\n commands: [createMemoryCliCommand()],\n },\n tasks: {\n processSession: {\n async run(ctx) {\n await processMemorySession(ctx);\n },\n },\n },\n hooks: {\n tools(ctx) {\n const agent = createMemoryAgent(ctx.model);\n const context = memoryToolContext({\n ...ctx,\n agent,\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n });\n return {\n createMemory: createMemoryCreateTool(\n memoryCreateToolContext({\n ...ctx,\n agent,\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n supersessionDecider: agent,\n }),\n ),\n removeMemory: createMemoryRemoveTool(context),\n listMemories: createMemoryListTool(context),\n searchMemories: createMemorySearchTool(context),\n };\n },\n async userPrompt(ctx) {\n return await createMemoryPromptMessages({\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.requester ? { requester: ctx.requester } : {}),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n maxVectorDistance: recallMaxVectorDistance(options),\n source: ctx.source,\n text: ctx.text,\n });\n },\n },\n });\n}\n\nexport const memoryPlugin = createMemoryPlugin();\n","import type { PluginModel } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport type {\n MemorySupersessionDecision,\n MemorySupersessionInput,\n} from \"./store\";\nimport { MEMORY_KINDS, memoryRuntimeContextSchema } from \"./types\";\n\nconst memoryKindSchema = z.enum(MEMORY_KINDS);\nconst memoryRejectReasonSchema = z.enum([\n \"not_public_shareable\",\n \"secret_or_credential\",\n \"sensitive_personal\",\n \"third_party_personal\",\n \"vague_or_not_self_contained\",\n \"not_durable\",\n \"assistant_or_system_detail\",\n \"unsupported_scope\",\n]);\nconst createMemoryRequestSchema = z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n runtimeContext: memoryRuntimeContextSchema,\n sourceContext: z\n .object({\n currentUserText: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nconst extractSessionRequestSchema = z\n .object({\n existingMemories: z\n .array(\n z\n .object({\n content: z.string().min(1),\n })\n .strict(),\n )\n .max(10)\n .default([]),\n runtimeContext: memoryRuntimeContextSchema,\n transcript: z\n .array(\n z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"message\"),\n role: z.enum([\"user\", \"assistant\"]),\n text: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"toolResult\"),\n toolName: z.string().min(1),\n isError: z.boolean(),\n text: z.string().min(1),\n })\n .strict(),\n ]),\n )\n .min(1),\n })\n .strict();\nconst supersessionRequestSchema = z\n .object({\n candidate: z\n .object({\n content: z.string().min(1),\n kind: z.literal(\"preference\"),\n })\n .strict(),\n existingMemories: z\n .array(\n z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n })\n .strict(),\n )\n .min(1)\n .max(10),\n runtimeContext: memoryRuntimeContextSchema,\n })\n .strict();\n\nconst expiresAtMsSchema = z\n .number()\n .finite()\n .nullable()\n .describe(\n \"Expiration timestamp when the fact should expire, otherwise null.\",\n );\nconst memoryReviewDecisionSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n kind: memoryKindSchema,\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst memoryReviewResponseSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n kind: memoryKindSchema.describe(\n \"Use preference only for requester-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use knowledge for shared project, channel, operational, or runbook facts.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text. It must be self-contained and must not include requester names, requester/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst extractedMemorySchema = z\n .object({\n kind: memoryKindSchema.describe(\n \"Use preference only for requester-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use knowledge for shared project, channel, operational, or runbook facts.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text as one self-contained fact. It must not include requester names, requester/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n })\n .strict();\nconst extractedMemoryResultSchema = z\n .object({\n content: z.string().min(1),\n expiresAtMs: expiresAtMsSchema,\n kind: memoryKindSchema,\n })\n .strict();\nconst extractMemoriesResponseSchema = z\n .object({\n memories: z\n .array(extractedMemorySchema)\n .max(5)\n .describe(\n \"Accepted public/shareable durable memories from the completed run. Return one object per distinct source assertion and classify it with kind.\",\n ),\n })\n .strict();\nconst supersessionDecisionResponseSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"supersedes_old\"),\n supersededIds: z.array(z.string().min(1)).min(1).max(10),\n })\n .strict(),\n z\n .object({\n decision: z.enum([\"distinct\", \"uncertain\"]),\n })\n .strict(),\n]);\n\ntype MemoryReviewResponse = z.output<typeof memoryReviewResponseSchema>;\ntype ExtractMemoriesResponse = z.output<typeof extractMemoriesResponseSchema>;\n\nexport type MemoryReview = z.output<typeof memoryReviewDecisionSchema>;\n\nexport type CreateMemoryRequest = z.output<typeof createMemoryRequestSchema>;\nexport type ExtractSessionRequest = z.output<\n typeof extractSessionRequestSchema\n>;\nexport type ExtractedMemory = z.output<typeof extractedMemoryResultSchema>;\n\nexport interface MemoryAgent {\n /** Decide whether a new preference safely replaces active old preferences. */\n adjudicateSupersession(\n request: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n extractSessionMemories(\n request: ExtractSessionRequest,\n ): Promise<ExtractedMemory[]> | ExtractedMemory[];\n reviewCreateRequest(\n request: CreateMemoryRequest,\n ): Promise<MemoryReview> | MemoryReview;\n}\n\nconst MEMORY_REVIEW_SYSTEM = [\n \"You are Junior's memory review agent.\",\n \"Review one memory candidate and return one structured review decision.\",\n \"Store only public/shareable, self-contained facts that are useful beyond this turn.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"Use the runtime context only for authority and scope; do not accept model-provided actor ids, scope ids, aliases, or arbitrary subjects.\",\n].join(\"\\n\");\nconst MEMORY_EXTRACTION_SYSTEM = [\n \"You are Junior's passive memory extraction agent. Return only structured memories worth storing.\",\n \"Use the completed run transcript as source evidence, including user-authored messages and tool results.\",\n \"Assistant text is context for interpreting the run, not independent evidence for new facts.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"If no public, durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst MEMORY_SUPERSESSION_SYSTEM = [\n \"You are Junior's memory supersession agent.\",\n \"Decide whether a new requester preference clearly replaces existing active requester preferences.\",\n \"Return supersedes_old only for obvious changed preferences about the same mutable slot.\",\n \"If the facts are additive, different topics, duplicate, broader/narrower without direct replacement, or uncertain, do not supersede.\",\n].join(\"\\n\");\nconst CANONICAL_CONTENT_RULES = [\n \"- Stored memory text must be a rewritten fact, not copied user wording or a sentence about who said it.\",\n \"- Store the minimum useful assertion supported by source evidence; do not add adjacent steps, caveats, or generalized advice.\",\n \"- Do not return both concise and expanded variants of the same source assertion; keep the shortest self-contained canonical memory.\",\n \"- Put ownership in structured fields, not prose.\",\n \"- For requester memories, omit the subject and write a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Drop perspective/provenance markers while preserving useful context.\",\n \"- Remove requester names, display names, requester/user labels, first- or second-person wording, thread labels, channel labels, and source labels.\",\n];\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\");\n}\n\nfunction runtimeDescription(\n request: Pick<CreateMemoryRequest, \"expiresAtMs\" | \"runtimeContext\">,\n): string {\n const runtime = request.runtimeContext;\n const requester =\n runtime.requester?.platform === \"slack\"\n ? `slack:${runtime.requester.teamId}:${runtime.requester.userId}`\n : runtime.requester?.platform === \"local\"\n ? `local:${runtime.requester.userId}`\n : \"none\";\n const source =\n runtime.source.platform === \"slack\"\n ? `slack:${runtime.source.teamId}:${runtime.source.channelId}`\n : `local:${runtime.source.conversationId}`;\n const lines = [\n `- requester: ${escapeXml(requester)}`,\n `- source: ${escapeXml(source)}`,\n `- has_conversation: ${runtime.conversationId ? \"true\" : \"false\"}`,\n `- expires_at: ${\n request.expiresAtMs === undefined\n ? \"never\"\n : escapeXml(new Date(request.expiresAtMs).toISOString())\n }`,\n ];\n return [\"<runtime>\", ...lines, \"</runtime>\"].join(\"\\n\");\n}\n\nfunction sourceContext(request: CreateMemoryRequest): string | undefined {\n const currentUserText = request.sourceContext?.currentUserText?.trim();\n if (!currentUserText) {\n return undefined;\n }\n return [\n \"<source-context>\",\n \"The current user-authored text is source evidence for explicit memory requests. Use it to recover the concrete fact when the candidate is incomplete, vague, or over-personalized. Store only rewritten, self-contained memory content.\",\n \"<current-user-message>\",\n escapeXml(currentUserText),\n \"</current-user-message>\",\n \"</source-context>\",\n ].join(\"\\n\");\n}\n\nfunction existingMemoriesContext(request: ExtractSessionRequest): string {\n if (request.existingMemories.length === 0) {\n return \"<existing-memories>[]</existing-memories>\";\n }\n return [\n \"<existing-memories>\",\n \"Use these only to skip memories that are already covered or semantically redundant. They are not source evidence for new memories.\",\n escapeXml(JSON.stringify(request.existingMemories)),\n \"</existing-memories>\",\n ].join(\"\\n\");\n}\n\nfunction memoryKindsContext(): string {\n return [\n \"<memory-kinds>\",\n \"- preference: a durable first-person personal preference, opinion, habit, or workflow owned by the current requester. Stored as requester memory.\",\n \"- procedure: reusable instructions for how a task, lookup, investigation, process, triage flow, or runbook should be done. Store the method, source-of-truth, prerequisite, or decision path when it took effort to discover. Stored as conversation memory.\",\n \"- knowledge: stable shared project, channel, operational, or runbook fact that is not a personal requester preference. Direct answers to user inquiries qualify only when they are durable beyond this run. Stored as conversation memory.\",\n \"</memory-kinds>\",\n ].join(\"\\n\");\n}\n\nfunction reviewPrompt(request: CreateMemoryRequest): string {\n const sections = [\n \"<memory-review-input>\",\n \"Review the candidate memory using the runtime-owned context below.\",\n \"\",\n runtimeDescription(request),\n \"\",\n sourceContext(request),\n \"\",\n \"<candidate>\",\n escapeXml(request.content),\n \"</candidate>\",\n \"\",\n \"<rules>\",\n \"- Return store only when the candidate is public/shareable, durable, and self-contained.\",\n \"- First classify the memory kind: preference, procedure, or knowledge.\",\n \"- Use kind=preference only for first-person facts authored by the current requester about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current requester.\",\n \"- Use kind=procedure for reusable task/process/runbook instructions.\",\n \"- Use kind=knowledge for shared project, channel, operational, or runbook facts.\",\n \"- When current-user-message contains an explicit memory request with a concrete fact or procedure, extract from current-user-message even if the candidate is vague, incomplete, or phrased as an instruction.\",\n \"- A candidate may be badly phrased by an outer assistant or extraction pass. When current-user-message contains the requester's own first-person memory fact, treat that as requester-authored source evidence and canonicalize the fact instead of rejecting for third-person wording.\",\n \"- When candidate wording personalizes a shared task, process, runbook, project, channel, or operational fact, use current-user-message to recover the shared fact and classify it as procedure or knowledge.\",\n \"- Explicit procedure requests are valid when the source text contains both task context and action. Canonicalize them as shared procedure facts instead of rejecting them as vague.\",\n \"- Store content as person-less, source-less canonical knowledge. Ownership and source live in structured metadata, not prose.\",\n \"- For requester memories, omit the subject and write the content as a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Remove requester names, display names, requester/user labels, first- or second-person wording, thread labels, channel labels, and source labels from stored content.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- Reject vague content such as 'remember this' unless the candidate or current-user-message contains the concrete fact.\",\n \"- Preserve the requested expiration when one exists; otherwise set expiresAtMs to null.\",\n \"- If unsure, reject.\",\n \"</rules>\",\n \"</memory-review-input>\",\n ].filter((section): section is string => section !== undefined);\n return sections.join(\"\\n\");\n}\n\nfunction runTranscriptContext(request: ExtractSessionRequest): string {\n return [\n \"<run-transcript>\",\n ...request.transcript.map((entry, index) => {\n if (entry.type === \"toolResult\") {\n return [\n `<tool-result index=\"${index}\" tool=\"${escapeXml(entry.toolName)}\" is_error=\"${entry.isError ? \"true\" : \"false\"}\">`,\n escapeXml(entry.text),\n \"</tool-result>\",\n ].join(\"\\n\");\n }\n return [\n `<message index=\"${index}\" role=\"${entry.role}\">`,\n escapeXml(entry.text),\n \"</message>\",\n ].join(\"\\n\");\n }),\n \"</run-transcript>\",\n ].join(\"\\n\");\n}\n\nfunction sessionExtractionPrompt(request: ExtractSessionRequest): string {\n return [\n \"<memory-extraction-input>\",\n \"Extract durable memories from this completed agent run using the runtime-owned context below.\",\n \"\",\n runtimeDescription({\n runtimeContext: request.runtimeContext,\n }),\n \"\",\n existingMemoriesContext(request),\n \"\",\n memoryKindsContext(),\n \"\",\n runTranscriptContext(request),\n \"\",\n \"<rules>\",\n \"- Return at most five memories.\",\n \"- Use user messages and successful tool results as source evidence for storable facts.\",\n \"- Use failed tool results only when the failure reveals durable process knowledge, not transient errors.\",\n \"- Use assistant messages only as context; do not store the assistant's claims unless supported by user messages or tool results.\",\n \"- Return one memory per distinct fact.\",\n \"- Prefer storing how to achieve a result: stable source-of-truth, query location, workflow, prerequisite, caveat, or reusable decision path that took effort to discover.\",\n \"- Store direct answers to user inquiries only when they are stable operational/project knowledge, not values that naturally change over time.\",\n \"- Do not store point-in-time analytics, search, issue, metric, incident, availability, or status answers just because a tool produced them.\",\n \"- Do not store the fact that the user asked for advice, search, recall, planning, listing, inspection, or removal. Store only stable knowledge discovered in response, such as a reusable method or source-of-truth.\",\n \"- A user question asking how, what, where, or whether to do something is not source evidence for the answer. Store the answer only when supported by a user-authored factual statement or a tool result.\",\n \"- Set kind=procedure for reusable task/process/runbook instructions.\",\n \"- Set kind=knowledge for shared team, project, channel, runbook, or operational facts.\",\n \"- Set kind=preference only for clear durable first-person facts authored by the current requester about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current requester.\",\n \"- User-authored task instructions are procedures, not preferences, unless they explicitly describe the requester's personal preference or habit.\",\n \"- Procedural statements such as 'for X, do Y', 'when X, do Y', and 'to accomplish X, do Y' belong in procedures.\",\n ...CANONICAL_CONTENT_RULES,\n \"- Skip a candidate when existing-memories already cover the same durable fact.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- If unsure, return no memory for that candidate.\",\n \"</rules>\",\n \"</memory-extraction-input>\",\n ].join(\"\\n\");\n}\n\nfunction supersessionPrompt(request: MemorySupersessionInput): string {\n return [\n \"<memory-supersession-input>\",\n \"Decide whether the candidate preference clearly replaces one or more existing active preferences.\",\n \"\",\n runtimeDescription({\n runtimeContext: request.runtimeContext,\n }),\n \"\",\n \"<candidate>\",\n escapeXml(JSON.stringify(request.candidate)),\n \"</candidate>\",\n \"\",\n \"<existing-memories>\",\n escapeXml(JSON.stringify(request.existingMemories)),\n \"</existing-memories>\",\n \"\",\n \"<rules>\",\n \"- Return supersedes_old only when the candidate and old memory describe the same mutable preference slot and the candidate is the newer value.\",\n \"- Examples of same mutable slot: preferred programming language, preferred review style, preferred notification cadence, preferred tool for a task.\",\n \"- Do not supersede when the candidate is just more specific, an additional preference, a different task/context, or the same value phrased differently.\",\n \"- Do not supersede memories from different topics even if they are both preferences.\",\n \"- Only return ids that appear in existing-memories.\",\n \"- If unsure, return uncertain.\",\n \"</rules>\",\n \"</memory-supersession-input>\",\n ].join(\"\\n\");\n}\n\n/** Create the memory-owned agent that reviews and extracts memory candidates. */\nexport function createMemoryAgent(model: PluginModel): MemoryAgent {\n return {\n async adjudicateSupersession(rawRequest) {\n const request = supersessionRequestSchema.parse(\n rawRequest,\n ) as MemorySupersessionInput;\n const result = await model.completeObject({\n schema: supersessionDecisionResponseSchema,\n system: MEMORY_SUPERSESSION_SYSTEM,\n prompt: supersessionPrompt(request),\n maxTokens: 400,\n });\n return supersessionDecisionResponseSchema.parse(\n result.object,\n ) as MemorySupersessionDecision;\n },\n async extractSessionMemories(rawRequest) {\n const request = extractSessionRequestSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: extractMemoriesResponseSchema,\n system: MEMORY_EXTRACTION_SYSTEM,\n prompt: sessionExtractionPrompt(request),\n maxTokens: 1_000,\n });\n return extractedMemoriesFromResponse(\n extractMemoriesResponseSchema.parse(result.object),\n );\n },\n async reviewCreateRequest(rawRequest) {\n const request = parseCreateMemoryRequest(rawRequest);\n const result = await model.completeObject({\n schema: memoryReviewResponseSchema,\n system: MEMORY_REVIEW_SYSTEM,\n prompt: reviewPrompt(request),\n maxTokens: 700,\n });\n const response = memoryReviewResponseSchema.parse(result.object);\n return memoryReviewFromResponse(response);\n },\n };\n}\n\nfunction memoryReviewFromResponse(\n response: MemoryReviewResponse,\n): MemoryReview {\n if (response.decision === \"store\") {\n return parseMemoryReview({\n decision: \"store\",\n kind: response.kind,\n content: response.canonicalFact,\n ...(response.expiresAtMs !== null\n ? { expiresAtMs: response.expiresAtMs }\n : {}),\n });\n }\n return parseMemoryReview({\n decision: \"reject\",\n reason: response.reason,\n });\n}\n\nfunction extractedMemoriesFromResponse(\n response: ExtractMemoriesResponse,\n): ExtractedMemory[] {\n const toMemory = (\n memory: z.output<typeof extractedMemorySchema>,\n ): ExtractedMemory =>\n parseExtractedMemory({\n content: memory.canonicalFact,\n expiresAtMs: memory.expiresAtMs,\n kind: memory.kind,\n });\n return response.memories.map(toMemory);\n}\n\n/** Parse the canonical extracted-memory shape stored across task retries. */\nexport function parseExtractedMemory(memory: unknown): ExtractedMemory {\n return extractedMemoryResultSchema.parse(memory);\n}\n\n/** Parse the structured decision returned by the memory agent. */\nexport function parseMemoryReview(result: unknown): MemoryReview {\n return memoryReviewDecisionSchema.parse(result);\n}\n\n/** Parse the structured input sent to the memory agent. */\nexport function parseCreateMemoryRequest(\n request: unknown,\n): CreateMemoryRequest {\n return createMemoryRequestSchema.parse(request);\n}\n","import {\n localRequesterSchema,\n localSourceSchema,\n platformSchema,\n slackRequesterSchema,\n slackSourceSchema,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\n\nexport const MEMORY_KINDS = [\"preference\", \"procedure\", \"knowledge\"] as const;\n\nexport const MEMORY_SCOPES = [\"personal\", \"conversation\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\nexport const MEMORY_SOURCE_PLATFORMS = [\n \"slack\",\n \"local\",\n] as const satisfies readonly z.output<typeof platformSchema>[];\nexport const MEMORY_EMBEDDING_METRICS = [\"cosine\"] as const;\nexport const MEMORY_EMBEDDING_DIMENSIONS = 1536;\n\nexport type MemoryKind = (typeof MEMORY_KINDS)[number];\nexport type MemoryScope = (typeof MEMORY_SCOPES)[number];\nexport type MemorySubjectType = (typeof MEMORY_SUBJECT_TYPES)[number];\nexport type MemorySourcePlatform = (typeof MEMORY_SOURCE_PLATFORMS)[number];\nexport type MemoryEmbeddingMetric = (typeof MEMORY_EMBEDDING_METRICS)[number];\n\nconst nonEmptyStringSchema = z.string().min(1);\n\n/** Runtime-owned memory invocation fields used for scope and source authority. */\nexport const slackMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n requester: slackRequesterSchema.optional(),\n source: slackSourceSchema,\n })\n .strict();\n\n/** Runtime-owned local memory invocation fields used for scope and source authority. */\nexport const localMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n requester: localRequesterSchema.optional(),\n source: localSourceSchema,\n })\n .strict();\n\n/** Runtime-owned memory invocation fields accepted by memory store operations. */\nexport const memoryRuntimeContextSchema = z.union([\n slackMemoryRuntimeContextSchema,\n localMemoryRuntimeContextSchema,\n]);\n\nexport type MemoryRuntimeContext = z.output<typeof memoryRuntimeContextSchema>;\n","import { InvalidArgumentError, Option, type Command } from \"commander\";\nimport { and, desc, eq, gt, ilike, isNull, or, type SQL } from \"drizzle-orm\";\nimport type {\n PluginCliActionContext,\n PluginCliHost,\n} from \"@sentry/junior-plugin-api\";\nimport { juniorMemoryMemories } from \"../db/schema\";\nimport type { MemoryDb } from \"../store\";\nimport { MEMORY_SCOPES, type MemoryScope } from \"../types\";\nimport { formatMemory } from \"./format\";\n\ninterface SearchOptions {\n limit: number;\n scope: MemoryScope;\n scopeKey: string;\n showContent?: boolean;\n}\n\nfunction parseLimit(value: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed)) {\n throw new InvalidArgumentError(\"--limit must be a number\");\n }\n return Math.min(100, Math.max(1, Math.floor(parsed)));\n}\n\nasync function runSearch(\n ctx: PluginCliActionContext,\n queryParts: string[] | undefined,\n options: SearchOptions,\n): Promise<number> {\n const query = (queryParts ?? []).join(\" \").trim();\n const nowMs = Date.now();\n const terms = [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n\n const db = ctx.db as MemoryDb;\n const activeExpirationPredicate = or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, nowMs),\n );\n const predicates: SQL[] = [\n eq(juniorMemoryMemories.scope, options.scope),\n eq(juniorMemoryMemories.scopeKey, options.scopeKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n ];\n if (activeExpirationPredicate) {\n predicates.push(activeExpirationPredicate);\n }\n if (terms.length > 0) {\n const termPredicate = or(\n ...terms.map((term) => ilike(juniorMemoryMemories.content, `%${term}%`)),\n );\n if (termPredicate) {\n predicates.push(termPredicate);\n }\n }\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(...predicates))\n .orderBy(desc(juniorMemoryMemories.createdAtMs))\n .limit(options.limit);\n\n if (rows.length === 0) {\n await ctx.io.writeOutput(\"No memories matched.\\n\");\n return 0;\n }\n\n await ctx.io.writeOutput(\n `${rows\n .map((row) =>\n formatMemory(row, { showContent: Boolean(options.showContent) }),\n )\n .join(\"\\n\\n\")}\\n`,\n );\n return 0;\n}\n\n/** Wire the memory search admin subcommand under the plugin namespace. */\nexport function configureMemorySearchCommand(\n parent: Command,\n junior: PluginCliHost,\n): void {\n parent\n .command(\"search\")\n .description(\"Search visible memories\")\n .argument(\"[query...]\", \"Search query\")\n .addOption(\n new Option(\"--scope <scope>\", \"Memory scope\")\n .choices([...MEMORY_SCOPES])\n .makeOptionMandatory(),\n )\n .requiredOption(\"--scope-key <key>\", \"Scope key\")\n .addOption(\n new Option(\"--limit <n>\", \"Maximum rows\")\n .argParser(parseLimit)\n .default(20),\n )\n .option(\"--show-content\", \"Print raw memory content\")\n .action(\n junior.action(async (ctx, queryParts, options) => {\n return await runSearch(\n ctx,\n queryParts as string[] | undefined,\n options as SearchOptions,\n );\n }),\n );\n}\n","/**\n * Drizzle source of truth for memory plugin SQL migrations.\n *\n * Update this schema first, then regenerate packaged migrations with\n * `pnpm --filter @sentry/junior-memory db:generate`.\n */\nimport { sql } from \"drizzle-orm\";\nimport {\n bigint,\n check,\n index,\n integer,\n pgTable,\n text,\n uniqueIndex,\n vector,\n} from \"drizzle-orm/pg-core\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_EMBEDDING_METRICS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_KINDS,\n} from \"../types\";\n\nexport const juniorMemoryMemories = pgTable(\n \"junior_memory_memories\",\n {\n id: text(\"id\").primaryKey(),\n scope: text(\"scope\", { enum: MEMORY_SCOPES }).notNull(),\n scopeKey: text(\"scope_key\").notNull(),\n kind: text(\"type\", { enum: MEMORY_KINDS }).notNull(),\n subjectType: text(\"subject_type\", { enum: MEMORY_SUBJECT_TYPES }).notNull(),\n subjectKey: text(\"subject_key\"),\n content: text(\"content\").notNull(),\n sourcePlatform: text(\"source_platform\", {\n enum: MEMORY_SOURCE_PLATFORMS,\n }).notNull(),\n sourceKey: text(\"source_key\").notNull(),\n idempotencyKey: text(\"idempotency_key\"),\n observedAtMs: bigint(\"observed_at_ms\", { mode: \"number\" }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n expiresAtMs: bigint(\"expires_at_ms\", { mode: \"number\" }),\n supersededAtMs: bigint(\"superseded_at_ms\", { mode: \"number\" }),\n supersededById: text(\"superseded_by_id\"),\n archivedAtMs: bigint(\"archived_at_ms\", { mode: \"number\" }),\n archiveReason: text(\"archive_reason\"),\n },\n (table) => [\n index(\"junior_memory_memories_visible_idx\")\n .on(table.scope, table.scopeKey, table.createdAtMs.desc(), table.id)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n index(\"junior_memory_memories_expiration_idx\")\n .on(table.expiresAtMs)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`,\n ),\n uniqueIndex(\"junior_memory_memories_idempotency_idx\")\n .on(table.scope, table.scopeKey, table.idempotencyKey)\n .where(\n sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n check(\n \"junior_memory_memories_scope_check\",\n sql`${table.scope} IN ('personal', 'conversation')`,\n ),\n check(\n \"junior_memory_memories_kind_check\",\n sql`${table.kind} IN (\n 'preference',\n 'procedure',\n 'knowledge'\n )`,\n ),\n check(\n \"junior_memory_memories_subject_type_check\",\n sql`${table.subjectType} IN ('user', 'conversation', 'general')`,\n ),\n check(\n \"junior_memory_memories_subject_key_check\",\n sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`,\n ),\n check(\n \"junior_memory_memories_source_platform_check\",\n sql`${table.sourcePlatform} IN ('slack', 'local')`,\n ),\n ],\n);\n\nexport const juniorMemoryEmbeddings = pgTable(\n \"junior_memory_embeddings\",\n {\n memoryId: text(\"memory_id\")\n .primaryKey()\n .references(() => juniorMemoryMemories.id, { onDelete: \"cascade\" }),\n provider: text(\"provider\").notNull(),\n model: text(\"model\").notNull(),\n dimensions: integer(\"dimensions\").notNull(),\n metric: text(\"metric\", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),\n contentHash: text(\"content_hash\").notNull(),\n embedding: vector(\"embedding\", {\n dimensions: MEMORY_EMBEDDING_DIMENSIONS,\n }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n },\n (table) => [\n index(\"junior_memory_embeddings_model_idx\").on(\n table.provider,\n table.model,\n table.dimensions,\n table.metric,\n ),\n check(\n \"junior_memory_embeddings_metric_check\",\n sql`${table.metric} IN ('cosine')`,\n ),\n check(\n \"junior_memory_embeddings_dimensions_check\",\n sql`${table.dimensions} = ${sql.raw(String(MEMORY_EMBEDDING_DIMENSIONS))}`,\n ),\n ],\n);\n","import type { juniorMemoryMemories } from \"../db/schema\";\n\nfunction formatDate(ms: number | null): string {\n return ms === null ? \"-\" : new Date(ms).toISOString();\n}\n\n/** Format a memory row as an operator-safe CLI projection. */\nexport function formatMemory(\n row: typeof juniorMemoryMemories.$inferSelect,\n args: {\n showContent: boolean;\n },\n): string {\n const lines = [\n `id=${row.id}`,\n `scope=${row.scope}`,\n `scope_key=${row.scopeKey}`,\n `subject_type=${row.subjectType}`,\n ...(row.subjectKey ? [`subject_key=${row.subjectKey}`] : []),\n `kind=${row.kind}`,\n `created_at=${formatDate(row.createdAtMs)}`,\n `observed_at=${formatDate(row.observedAtMs)}`,\n `expires_at=${formatDate(row.expiresAtMs)}`,\n `archived_at=${formatDate(row.archivedAtMs)}`,\n ];\n if (args.showContent) {\n lines.push(`content=${row.content}`);\n }\n return lines.join(\"\\n\");\n}\n","import type { Command } from \"commander\";\nimport type {\n PluginCliActionContext,\n PluginCliHost,\n} from \"@sentry/junior-plugin-api\";\nimport { eq } from \"drizzle-orm\";\nimport { juniorMemoryMemories } from \"../db/schema\";\nimport type { MemoryDb } from \"../store\";\nimport { formatMemory } from \"./format\";\n\nasync function runShow(\n ctx: PluginCliActionContext,\n id: string,\n): Promise<number> {\n const db = ctx.db as MemoryDb;\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(eq(juniorMemoryMemories.id, id))\n .limit(1);\n if (!rows[0]) {\n await ctx.io.writeError(`Memory not found: ${id}\\n`);\n return 1;\n }\n\n await ctx.io.writeOutput(`${formatMemory(rows[0], { showContent: true })}\\n`);\n return 0;\n}\n\n/** Wire the explicit raw-content memory inspection subcommand. */\nexport function configureMemoryShowCommand(\n parent: Command,\n junior: PluginCliHost,\n): void {\n parent\n .command(\"show\")\n .description(\"Show one memory\")\n .argument(\"<id>\", \"Memory id\")\n .action(\n junior.action(async (ctx, id) => {\n return await runShow(ctx, id as string);\n }),\n );\n}\n","import type { PluginCliCommandDefinition } from \"@sentry/junior-plugin-api\";\nimport { configureMemorySearchCommand } from \"./search\";\nimport { configureMemoryShowCommand } from \"./show\";\n\n/** Create the plugin-owned memory admin CLI command. */\nexport function createMemoryCliCommand(): PluginCliCommandDefinition {\n return {\n name: \"memory\",\n summary: \"Inspect Junior memory state\",\n configure(command, junior) {\n configureMemorySearchCommand(command, junior);\n configureMemoryShowCommand(command, junior);\n },\n };\n}\n","import { Type, type Static } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport {\n definePluginTool,\n getSourceKey,\n PluginToolInputError,\n type PluginToolResult,\n type Source,\n type Requester,\n pluginToolResultSchema,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryEmbeddingProvider,\n type MemoryDb,\n type MemoryRecord,\n type MemorySupersessionDecider,\n} from \"./store\";\nimport {\n parseCreateMemoryRequest,\n parseMemoryReview,\n type MemoryAgent,\n} from \"./agent\";\nimport {\n memoryRuntimeContextSchema,\n type MemoryKind,\n type MemoryRuntimeContext,\n} from \"./types\";\n\nexport type MemoryReviewer = Pick<MemoryAgent, \"reviewCreateRequest\">;\n\nconst MAX_TOOL_CONTENT_CHARS = 4_000;\nconst DEFAULT_RESULT_LIMIT = 20;\nconst DEFAULT_SEARCH_LIMIT = 10;\n\nconst KNOWN_TOOL_INPUT_ERROR_MESSAGES = new Set([\n \"Conversation memory requires conversation context.\",\n \"Conversation-subject memory requires conversation context.\",\n \"Memory content is required.\",\n \"Memory content exceeds the maximum length.\",\n \"Memory id is required.\",\n \"Memory was not found in the current context.\",\n \"Memory id prefix is ambiguous.\",\n \"Personal memory requires requester context.\",\n \"User-subject memory requires requester context.\",\n]);\n\n/** Runtime-owned context used to bind memory tools to visible scopes. */\nexport interface MemoryToolContext {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n requester?: Requester;\n source: Source;\n userText?: string;\n}\n\nexport interface MemoryCreateToolContext extends MemoryToolContext {\n supersessionDecider?: MemorySupersessionDecider;\n}\n\nfunction throwToolInputError(message: string): never {\n throw new PluginToolInputError(message);\n}\n\nfunction asToolInputError(error: unknown): never {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n if (\n error instanceof Error &&\n KNOWN_TOOL_INPUT_ERROR_MESSAGES.has(error.message)\n ) {\n throw new PluginToolInputError(error.message, { cause: error });\n }\n throw error;\n}\n\nfunction memoryRuntimeContext(\n context: MemoryToolContext,\n): MemoryRuntimeContext {\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.requester ? { requester: context.requester } : {}),\n source: context.source,\n });\n}\n\nfunction memoryStore(\n context: MemoryToolContext,\n options: { supersessionDecider?: MemorySupersessionDecider } = {},\n) {\n return createMemoryStore(context.db, memoryRuntimeContext(context), {\n embedder: context.embedder,\n ...(options.supersessionDecider\n ? { supersessionDecider: options.supersessionDecider }\n : {}),\n });\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(50, Math.max(1, Math.floor(value)));\n}\n\nfunction digitAt(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code >= 48 && code <= 57;\n}\n\nfunction readDigits(\n value: string,\n start: number,\n length: number,\n): number | undefined {\n for (let index = start; index < start + length; index++) {\n if (!digitAt(value, index)) {\n return undefined;\n }\n }\n return Number(value.slice(start, start + length));\n}\n\nfunction parseIsoTimestampParts(value: string) {\n if (\n value.length < 20 ||\n value[4] !== \"-\" ||\n value[7] !== \"-\" ||\n value[10] !== \"T\" ||\n value[13] !== \":\" ||\n value[16] !== \":\"\n ) {\n return undefined;\n }\n const year = readDigits(value, 0, 4);\n const month = readDigits(value, 5, 2);\n const day = readDigits(value, 8, 2);\n const hour = readDigits(value, 11, 2);\n const minute = readDigits(value, 14, 2);\n const second = readDigits(value, 17, 2);\n if (\n year === undefined ||\n month === undefined ||\n day === undefined ||\n hour === undefined ||\n minute === undefined ||\n second === undefined\n ) {\n return undefined;\n }\n\n let zoneStart = 19;\n if (value[zoneStart] === \".\") {\n zoneStart += 1;\n const fractionStart = zoneStart;\n while (zoneStart < value.length && digitAt(value, zoneStart)) {\n zoneStart += 1;\n }\n if (zoneStart === fractionStart) {\n return undefined;\n }\n }\n\n if (value[zoneStart] === \"Z\") {\n if (zoneStart !== value.length - 1) {\n return undefined;\n }\n } else if (value[zoneStart] === \"+\" || value[zoneStart] === \"-\") {\n if (\n zoneStart !== value.length - 6 ||\n value[zoneStart + 3] !== \":\" ||\n readDigits(value, zoneStart + 1, 2) === undefined ||\n readDigits(value, zoneStart + 4, 2) === undefined\n ) {\n return undefined;\n }\n } else {\n return undefined;\n }\n\n return { day, hour, minute, month, second, year };\n}\n\nfunction parseExpiresAt(value: string | undefined): number | undefined {\n if (!value) {\n return undefined;\n }\n if (value === \"never\") {\n return undefined;\n }\n const parts = parseIsoTimestampParts(value);\n const expiresAtMs = Date.parse(value);\n if (!parts || !Number.isFinite(expiresAtMs)) {\n throwToolInputError('expires_at must be \"never\" or a valid ISO timestamp.');\n }\n const calendarDate = new Date(\n Date.UTC(parts.year, parts.month - 1, parts.day),\n );\n if (\n calendarDate.getUTCFullYear() !== parts.year ||\n calendarDate.getUTCMonth() !== parts.month - 1 ||\n calendarDate.getUTCDate() !== parts.day ||\n parts.hour > 23 ||\n parts.minute > 59 ||\n parts.second > 59\n ) {\n throwToolInputError('expires_at must be \"never\" or a valid ISO timestamp.');\n }\n return expiresAtMs;\n}\n\nfunction requireToolCallId(value: string | undefined): string {\n if (!value) {\n throwToolInputError(\"Memory creation requires a tool call id.\");\n }\n return value;\n}\n\nfunction requireMemoryContent(value: string): string {\n if (value.trim().length === 0) {\n throwToolInputError(\"Memory content is required.\");\n }\n return value;\n}\n\nconst createMemoryInputSchema = z\n .object({\n content: z\n .string()\n .min(1)\n .max(MAX_TOOL_CONTENT_CHARS)\n .describe(\n \"Self-contained public/shareable memory candidate. Include the subject in natural language when it matters; do not rely on surrounding chat context.\",\n ),\n expires_at: z\n .string()\n .min(1)\n .describe(\n 'Expiration selector. Omit or use \"never\" when the memory should not expire, or use an exact ISO timestamp such as \"2027-06-21T00:00:00Z\".',\n )\n .optional(),\n })\n .strict();\n\nconst removeMemoryInputSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .describe(\"Memory id or unambiguous short id prefix to remove.\"),\n })\n .strict();\n\nconst listMemoriesInputSchema = z\n .object({\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of visible memories to return.\")\n .optional(),\n })\n .strict();\n\nconst searchMemoriesInputSchema = z\n .object({\n query: z\n .string()\n .min(1)\n .describe(\"Search query for visible memory content.\"),\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of matching memories to return.\")\n .optional(),\n })\n .strict();\n\nconst memoryToolProjectionSchema = Type.Object(\n {\n id: Type.String({ minLength: 1 }),\n content: Type.String({ minLength: 1 }),\n createdAtMs: Type.Number(),\n observedAtMs: Type.Number(),\n expiresAtMs: Type.Optional(Type.Number()),\n },\n { additionalProperties: false },\n);\ntype MemoryToolProjection = Static<typeof memoryToolProjectionSchema>;\n\ntype MemoryStructuredToolResult<TData extends Record<string, unknown>> =\n PluginToolResult &\n TData & {\n ok: true;\n status: \"success\";\n target: string;\n data: TData;\n };\n\nconst memoryProjectionOutputSchema = z.object({\n id: z.string(),\n content: z.string(),\n createdAtMs: z.number(),\n observedAtMs: z.number(),\n expiresAtMs: z.number().optional(),\n});\n\nconst memoryCreateDataOutputSchema = z.object({\n created: z.boolean(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memorySingleDataOutputSchema = z.object({\n memory: memoryProjectionOutputSchema,\n});\n\nconst memoryManyDataOutputSchema = z.object({\n memories: z.array(memoryProjectionOutputSchema),\n});\n\nconst memoryCreateOutputSchema = pluginToolResultSchema.extend({\n ok: z.literal(true),\n status: z.literal(\"success\"),\n target: z.string(),\n data: memoryCreateDataOutputSchema,\n created: z.boolean(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memorySingleOutputSchema = pluginToolResultSchema.extend({\n ok: z.literal(true),\n status: z.literal(\"success\"),\n target: z.string(),\n data: memorySingleDataOutputSchema,\n memory: memoryProjectionOutputSchema,\n});\n\nconst memoryManyOutputSchema = pluginToolResultSchema.extend({\n ok: z.literal(true),\n status: z.literal(\"success\"),\n target: z.string(),\n data: memoryManyDataOutputSchema,\n memories: z.array(memoryProjectionOutputSchema),\n});\n\nfunction parseMemoryToolInput<T>(schema: z.ZodType<T>, input: unknown): T {\n const result = schema.safeParse(input);\n if (!result.success) {\n throw new PluginToolInputError(\"Invalid memory tool input.\", {\n cause: result.error,\n });\n }\n return result.data;\n}\n\nfunction sourceIdempotencyKey(context: MemoryToolContext): string {\n const sourceKey = getSourceKey(context.source);\n if (!sourceKey) {\n throwToolInputError(\"Memory creation requires source message context.\");\n }\n return sourceKey;\n}\n\nfunction createInput(\n context: MemoryToolContext,\n input: { content: string; expiresAtMs?: number; kind: MemoryKind },\n toolCallId: string,\n) {\n return {\n content: requireMemoryContent(input.content),\n idempotencyKey: `tool:${sourceIdempotencyKey(context)}:${toolCallId}`,\n kind: input.kind,\n ...(input.expiresAtMs !== undefined\n ? { expiresAtMs: input.expiresAtMs }\n : {}),\n } satisfies CreateMemoryInput;\n}\n\nfunction targetForKind(kind: MemoryKind): \"requester\" | \"conversation\" {\n if (kind === \"preference\") {\n return \"requester\";\n }\n return \"conversation\";\n}\n\n/** Return the model-visible projection without hidden ownership/source fields. */\nfunction compactMemory(memory: MemoryRecord): MemoryToolProjection {\n return Value.Parse(memoryToolProjectionSchema, {\n id: memory.id,\n content: memory.content,\n createdAtMs: memory.createdAtMs,\n observedAtMs: memory.observedAtMs,\n ...(memory.expiresAtMs !== undefined\n ? { expiresAtMs: memory.expiresAtMs }\n : {}),\n });\n}\n\nfunction memoryToolResult<TData extends Record<string, unknown>>(\n target: string,\n data: TData,\n): MemoryStructuredToolResult<TData> {\n return {\n ok: true,\n status: \"success\",\n target,\n data,\n ...data,\n };\n}\n\n/** Create a tool that submits an explicit memory candidate for storage. */\nexport function createMemoryCreateTool(context: MemoryCreateToolContext) {\n return definePluginTool({\n description:\n \"Explicit memory-write tool. Use only when the latest user message directly asks Junior to remember, store, save, or forget-and-replace a public/shareable fact. Do not use for ordinary statements like 'I prefer X', 'I use Y', or 'X goes before Y' unless the user also asks you to remember/store/save it; passive memory learning handles those after the visible reply. Pass one self-contained natural-language candidate preserving the user's explicit memory intent. Do not ask the user to rephrase ordinary first-person facts, and do not rewrite them into display-name or third-person wording. Do not include secrets, private personal details, medical/legal/financial/sensitive facts, or another person's personal preference, opinion, habit, identity, relationship, workflow, or private life. Runtime context derives actor, scope, source, and subject ids; the memory agent decides canonical stored content and memory kind, then the plugin derives storage target from kind.\",\n executionMode: \"sequential\",\n inputSchema: createMemoryInputSchema,\n outputSchema: memoryCreateOutputSchema,\n execute: async (input, options) => {\n const parsedInput = parseMemoryToolInput(createMemoryInputSchema, input);\n const toolCallId = requireToolCallId(options.toolCallId);\n const requestedExpiresAtMs = parseExpiresAt(parsedInput.expires_at);\n const runtimeContext = memoryRuntimeContext(context);\n const store = memoryStore(context, {\n supersessionDecider: context.supersessionDecider,\n });\n const review = await (async () => {\n try {\n return parseMemoryReview(\n await context.agent.reviewCreateRequest(\n parseCreateMemoryRequest({\n content: requireMemoryContent(parsedInput.content),\n ...(requestedExpiresAtMs !== undefined\n ? { expiresAtMs: requestedExpiresAtMs }\n : {}),\n runtimeContext,\n ...(context.userText?.trim()\n ? {\n sourceContext: {\n currentUserText: context.userText.trim(),\n },\n }\n : {}),\n }),\n ),\n );\n } catch (error) {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n const detail =\n error instanceof Error && error.message.trim()\n ? `: ${error.message}`\n : \"\";\n throw new PluginToolInputError(\n `Memory agent review failed${detail}`,\n { cause: error },\n );\n }\n })();\n if (review.decision === \"reject\") {\n throw new PluginToolInputError(\n `Memory was not stored: ${review.reason}`,\n );\n }\n const memoryInput = createInput(\n context,\n {\n content: review.content,\n kind: review.kind,\n ...(review.expiresAtMs !== undefined\n ? { expiresAtMs: review.expiresAtMs }\n : requestedExpiresAtMs !== undefined\n ? { expiresAtMs: requestedExpiresAtMs }\n : {}),\n },\n toolCallId,\n );\n const result = await (async () => {\n try {\n if (targetForKind(review.kind) === \"conversation\") {\n return await store.createConversationMemory(memoryInput);\n }\n return await store.createMemory(memoryInput);\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"createMemory\", {\n created: result.created,\n memory: compactMemory(result.memory),\n });\n },\n });\n}\n\n/** Create a tool that archives a visible memory in the active context. */\nexport function createMemoryRemoveTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"Forget one memory visible in the active context. Use only ids or short id prefixes returned by listMemories or searchMemories. Never remove memories by hidden actor, Slack, scope, or subject identifiers.\",\n executionMode: \"sequential\",\n inputSchema: removeMemoryInputSchema,\n outputSchema: memorySingleOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(removeMemoryInputSchema, input);\n const memory = await (async () => {\n try {\n return await memoryStore(context).archiveMemory({\n id: parsedInput.id,\n reason: \"tool_removed\",\n });\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"removeMemory\", {\n memory: compactMemory(memory),\n });\n },\n });\n}\n\n/** Create a tool that lists visible active memories in the active context. */\nexport function createMemoryListTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"List active memories visible in the current context. Use when the user asks what Junior remembers or when memory ids are needed before removing a memory.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: listMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(listMemoriesInputSchema, input);\n const memories = await memoryStore(context).listMemories({\n limit: boundedLimit(parsedInput.limit, DEFAULT_RESULT_LIMIT),\n });\n return memoryToolResult(\"listMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n\n/** Create a tool that searches visible active memories in the active context. */\nexport function createMemorySearchTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"Search active memories visible in the current context. Use when the model needs targeted memory recall. The tool searches only the current requester and active conversation scopes.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: searchMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(\n searchMemoriesInputSchema,\n input,\n );\n const memories = await memoryStore(context).searchMemories({\n query: parsedInput.query,\n limit: boundedLimit(parsedInput.limit, DEFAULT_SEARCH_LIMIT),\n });\n return memoryToolResult(\"searchMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n","/**\n * SQL-backed memory store boundary.\n *\n * This module owns row parsing plus visible create/list/search/archive\n * operations. Visibility, expiration, and supersession are enforced before\n * records leave the store.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n and,\n asc,\n desc,\n eq,\n gt,\n ilike,\n inArray,\n isNull,\n isNotNull,\n like,\n lte,\n or,\n sql,\n type SQL,\n} from \"drizzle-orm\";\nimport { cosineDistance } from \"drizzle-orm/sql/functions\";\nimport type { PgDatabase } from \"drizzle-orm/pg-core\";\nimport type { PgQueryResultHKT } from \"drizzle-orm/pg-core/session\";\nimport { z } from \"zod\";\nimport * as memorySqlSchema from \"./db/schema\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_KINDS,\n memoryRuntimeContextSchema,\n type MemoryRuntimeContext,\n type MemoryScope,\n} from \"./types\";\nimport {\n deriveMemoryScope,\n deriveMemorySubject,\n type ResolvedMemorySubject,\n deriveVisibleMemoryScopes,\n type ResolvedMemoryScope,\n} from \"./scope\";\n\nconst DEFAULT_LIST_LIMIT = 50;\nconst DEFAULT_SEARCH_LIMIT = 10;\nconst DEFAULT_EXPIRED_ARCHIVE_LIMIT = 100;\nconst HIGH_CONFIDENCE_DUPLICATE_DISTANCE = 0.015;\nconst SUPERSESSION_CANDIDATE_LIMIT = 10;\nconst VECTOR_SEARCH_OVERFETCH = 4;\nconst MAX_MEMORY_CONTENT_CHARS = 4_000;\nconst EMBEDDING_METRIC = \"cosine\";\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst RELEVANCE_NEAR_TIE_DELTA = 0.01;\nconst SOURCE_CHANNEL_BOOST = 0.05;\nconst SUPERSESSION_STOP_TERMS = new Set([\n \"and\",\n \"for\",\n \"prefer\",\n \"prefers\",\n \"preference\",\n \"the\",\n \"use\",\n \"uses\",\n \"with\",\n]);\n\nexport type MemoryDb = PgDatabase<PgQueryResultHKT, typeof memorySqlSchema>;\n\ninterface SearchCandidate {\n memory: MemoryRecord;\n score: number;\n sourceKey: string;\n}\n\ninterface MemoryEmbedding {\n model: string;\n provider: string;\n vector: number[];\n}\n\nconst nonEmptyStringSchema = z.string().min(1);\nconst memoryContentSchema = z\n .string()\n .refine((content) => content.trim().length > 0, {\n message: \"Memory content is required.\",\n });\nconst numberSchema = z.number().finite();\nconst createMemoryInputSchema = z\n .object({\n content: memoryContentSchema,\n expiresAtMs: numberSchema.optional(),\n idempotencyKey: nonEmptyStringSchema,\n kind: z.enum(MEMORY_KINDS),\n })\n .strict();\nconst listMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n })\n .strict();\nconst searchMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n query: nonEmptyStringSchema,\n })\n .strict();\nconst archiveMemoryInputSchema = z\n .object({\n id: nonEmptyStringSchema,\n reason: nonEmptyStringSchema.optional(),\n })\n .strict();\nconst archiveExpiredMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n })\n .strict();\nconst clockSchema = z.function({ input: [], output: numberSchema }).optional();\nconst memoryStoreOptionsSchema = z\n .object({\n now: clockSchema,\n })\n .strict();\nconst optionalNumberSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.coerce.number().optional(),\n);\nconst optionalStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().optional(),\n);\nconst optionalNonEmptyStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().min(1).optional(),\n);\nconst memoryRowSchema = z\n .object({\n archivedAtMs: optionalNumberSchema,\n archiveReason: optionalStringSchema,\n content: memoryContentSchema,\n createdAtMs: z.coerce.number(),\n expiresAtMs: optionalNumberSchema,\n id: z.string().min(1),\n idempotencyKey: optionalStringSchema,\n observedAtMs: z.coerce.number(),\n scope: z.enum(MEMORY_SCOPES),\n scopeKey: z.string().min(1),\n sourceKey: z.string().min(1),\n sourcePlatform: z.enum(MEMORY_SOURCE_PLATFORMS),\n subjectKey: optionalNonEmptyStringSchema,\n subjectType: z.enum(MEMORY_SUBJECT_TYPES),\n supersededAtMs: optionalNumberSchema,\n supersededById: optionalStringSchema,\n kind: z.enum(MEMORY_KINDS),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.subjectType === \"general\") {\n if (row.subjectKey !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n message: \"General-subject memory rows must not have a subject key.\",\n path: [\"subjectKey\"],\n });\n }\n return;\n }\n if (row.subjectKey === undefined) {\n ctx.addIssue({\n code: \"custom\",\n message: \"User and conversation memory rows require a subject key.\",\n path: [\"subjectKey\"],\n });\n }\n });\n\nconst memoryRecordSchema = z\n .object({\n archivedAtMs: numberSchema.optional(),\n archiveReason: nonEmptyStringSchema.optional(),\n content: memoryContentSchema,\n createdAtMs: numberSchema,\n expiresAtMs: numberSchema.optional(),\n id: nonEmptyStringSchema,\n observedAtMs: numberSchema,\n scope: z.enum(MEMORY_SCOPES),\n subjectType: z.enum(MEMORY_SUBJECT_TYPES),\n supersededAtMs: numberSchema.optional(),\n supersededById: nonEmptyStringSchema.optional(),\n kind: z.enum(MEMORY_KINDS),\n })\n .strict();\nconst embeddingVectorSchema = z\n .array(numberSchema)\n .length(MEMORY_EMBEDDING_DIMENSIONS);\nconst embeddingResultSchema = z\n .object({\n dimensions: z.literal(MEMORY_EMBEDDING_DIMENSIONS),\n model: nonEmptyStringSchema,\n provider: nonEmptyStringSchema,\n vectors: z.array(embeddingVectorSchema),\n })\n .strict();\n\nexport type MemoryRecord = z.output<typeof memoryRecordSchema>;\nexport type CreateMemoryInput = z.output<typeof createMemoryInputSchema>;\n\n/** Result of a memory write after idempotency checks. */\nexport interface CreateMemoryResult {\n created: boolean;\n memory: MemoryRecord;\n}\n\nexport type ListMemoriesInput = z.output<typeof listMemoriesInputSchema>;\n\nexport type SearchMemoriesInput = z.output<typeof searchMemoriesInputSchema>;\n\nexport type ArchiveMemoryInput = z.output<typeof archiveMemoryInputSchema>;\n\nexport type ArchiveExpiredMemoriesInput = z.output<\n typeof archiveExpiredMemoriesInputSchema\n>;\n\nexport interface ArchiveExpiredMemoriesResult {\n archivedCount: number;\n}\n\nexport interface MemoryEmbeddingProvider {\n /** Embed normalized memory text for derived vector retrieval. */\n embedTexts(input: { texts: string[] }): Promise<{\n dimensions: number;\n model: string;\n provider: string;\n vectors: number[][];\n }>;\n}\n\nexport interface MemorySupersessionInput {\n candidate: {\n content: string;\n kind: \"preference\";\n };\n existingMemories: [\n {\n content: string;\n id: string;\n },\n ...Array<{\n content: string;\n id: string;\n }>,\n ];\n runtimeContext: MemoryRuntimeContext;\n}\n\nexport type MemorySupersessionDecision =\n | {\n decision: \"supersedes_old\";\n supersededIds: [string, ...string[]];\n }\n | {\n decision: \"distinct\" | \"uncertain\";\n };\n\nexport interface MemorySupersessionDecider {\n /** Decide whether a new preference clearly replaces active old preferences. */\n adjudicateSupersession(\n input: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n}\n\nexport interface MemoryStoreOptions {\n embedder?: MemoryEmbeddingProvider;\n /** Maximum cosine distance for vector recall candidates. Model-dependent; tune when changing AI_EMBEDDING_MODEL. */\n maxVectorDistance?: number;\n now?: () => number;\n supersessionDecider?: MemorySupersessionDecider;\n}\n\n/** Context-bound storage operations for visible long-term memories. */\nexport interface MemoryStore {\n /** Archive expired memories visible in the current runtime context. */\n archiveExpiredMemories(\n input?: ArchiveExpiredMemoriesInput,\n ): Promise<ArchiveExpiredMemoriesResult>;\n /** Archive a visible memory in the current runtime context. */\n archiveMemory(input: ArchiveMemoryInput): Promise<MemoryRecord>;\n /** Store a personal memory for the current requester. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a conversation memory for the current source conversation. */\n createConversationMemory(\n input: CreateMemoryInput,\n ): Promise<CreateMemoryResult>;\n /** List active memories visible in the current runtime context. */\n listMemories(input: ListMemoriesInput): Promise<MemoryRecord[]>;\n /** Search active memories visible in the current runtime context. */\n searchMemories(input: SearchMemoriesInput): Promise<MemoryRecord[]>;\n}\n\nfunction normalizeContent(content: string): string {\n return content.replace(/\\s+/g, \" \").trim();\n}\n\nfunction hashEmbeddedContent(content: string): string {\n return createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nfunction idempotencyAliasId(args: {\n idempotencyKey: string;\n scope: ResolvedMemoryScope;\n targetId: string;\n}): string {\n return `alias:${createHash(\"sha256\")\n .update(args.scope.scope)\n .update(\"\\0\")\n .update(args.scope.scopeKey)\n .update(\"\\0\")\n .update(args.idempotencyKey)\n .update(\"\\0\")\n .update(args.targetId)\n .digest(\"hex\")}`;\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(200, Math.max(1, Math.floor(value)));\n}\n\n/** Build the durable source attribution key from runtime-owned source fields. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n throw new Error(\n \"Memory source requires a Slack message or thread timestamp.\",\n );\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\nfunction sourceChannelPrefix(ctx: MemoryRuntimeContext): string | undefined {\n if (ctx.source.platform !== \"slack\") {\n return undefined;\n }\n // TODO(v0.82.0): Replace Slack source-key prefix matching with typed source proximity metadata.\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:`;\n}\n\n/** Parse one SQL row into the public memory record projection. */\nfunction parseMemoryRow(row: unknown): MemoryRecord {\n const parsed = memoryRowSchema.parse(row);\n return memoryRecordSchema.parse({\n id: parsed.id,\n scope: parsed.scope,\n kind: parsed.kind,\n subjectType: parsed.subjectType,\n content: parsed.content,\n observedAtMs: parsed.observedAtMs,\n createdAtMs: parsed.createdAtMs,\n ...(parsed.expiresAtMs !== undefined\n ? { expiresAtMs: parsed.expiresAtMs }\n : {}),\n ...(parsed.supersededAtMs !== undefined\n ? { supersededAtMs: parsed.supersededAtMs }\n : {}),\n ...(parsed.supersededById ? { supersededById: parsed.supersededById } : {}),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : {}),\n ...(parsed.archiveReason ? { archiveReason: parsed.archiveReason } : {}),\n });\n}\n\n/** Build the scoped SQL predicate and ordered params for visible memory reads. */\nfunction visibleScopePredicate(scopes: ResolvedMemoryScope[]): SQL | undefined {\n if (scopes.length === 0) {\n return undefined;\n }\n return or(\n ...scopes.map((scope) =>\n and(\n eq(juniorMemoryMemories.scope, scope.scope),\n eq(juniorMemoryMemories.scopeKey, scope.scopeKey),\n ),\n ),\n );\n}\n\nfunction activeVisiblePredicate(args: {\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): SQL | undefined {\n const scopePredicate = visibleScopePredicate(args.scopes);\n if (!scopePredicate) {\n return undefined;\n }\n return and(\n scopePredicate,\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n}\n\n/** Resolve retry attempts for the same scoped write idempotency key. */\nasync function findByIdempotencyKey(args: {\n db: MemoryDb;\n idempotencyKey: string;\n nowMs: number;\n scope: ResolvedMemoryScope;\n}): Promise<MemoryRecord | undefined> {\n const activeRows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n eq(juniorMemoryMemories.idempotencyKey, args.idempotencyKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n ),\n )\n .limit(1);\n if (activeRows[0]) {\n return parseMemoryRow(activeRows[0]);\n }\n\n const aliasRows = await args.db\n .select({ supersededById: juniorMemoryMemories.supersededById })\n .from(juniorMemoryMemories)\n .where(\n and(\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n eq(juniorMemoryMemories.idempotencyKey, args.idempotencyKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNotNull(juniorMemoryMemories.supersededAtMs),\n isNotNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n ),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n );\n for (const alias of aliasRows) {\n if (!alias.supersededById) {\n continue;\n }\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n eq(juniorMemoryMemories.id, alias.supersededById),\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n ),\n )\n .limit(1);\n if (rows[0]) {\n return parseMemoryRow(rows[0]);\n }\n }\n return undefined;\n}\n\n/**\n * Archive a bounded batch of expired active rows and remove their derived vectors.\n */\nasync function archiveExpiredMemoryBatch(args: {\n db: MemoryDb;\n idempotencyKey?: string;\n limit?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<ArchiveExpiredMemoriesResult> {\n const scopePredicate = visibleScopePredicate(args.scopes);\n if (!scopePredicate) {\n return { archivedCount: 0 };\n }\n const predicates: SQL[] = [\n scopePredicate,\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n lte(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ];\n if (args.idempotencyKey !== undefined) {\n predicates.push(\n eq(juniorMemoryMemories.idempotencyKey, args.idempotencyKey),\n );\n }\n\n const archivedIds = await args.db.transaction(async (tx) => {\n const expired = await tx\n .select({ id: juniorMemoryMemories.id })\n .from(juniorMemoryMemories)\n .where(and(...predicates))\n .orderBy(\n asc(juniorMemoryMemories.expiresAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(boundedLimit(args.limit, DEFAULT_EXPIRED_ARCHIVE_LIMIT));\n const ids = expired.map((row) => row.id);\n if (ids.length === 0) {\n return [];\n }\n\n const archived = await tx\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: args.nowMs,\n archiveReason: \"expired\",\n })\n .where(and(inArray(juniorMemoryMemories.id, ids), ...predicates))\n .returning({ id: juniorMemoryMemories.id });\n const idsToClean = archived.map((row) => row.id);\n if (idsToClean.length > 0) {\n await tx\n .delete(juniorMemoryEmbeddings)\n .where(inArray(juniorMemoryEmbeddings.memoryId, idsToClean));\n }\n return idsToClean;\n });\n return { archivedCount: archivedIds.length };\n}\n\nfunction searchScore(memory: MemoryRecord, terms: string[]): number {\n const haystack = memory.content.toLowerCase();\n // Lexical score is a retrieval fallback signal, not a memory policy decision.\n return terms.reduce(\n (score, term) => score + (haystack.includes(term) ? 1 : 0),\n 0,\n );\n}\n\nfunction searchTerms(query: string): string[] {\n return [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n}\n\nasync function embedOne(\n embedder: MemoryEmbeddingProvider,\n text: string,\n): Promise<MemoryEmbedding> {\n const normalized = normalizeContent(text);\n if (!normalized) {\n throw new Error(\"Embedding text is required.\");\n }\n const result = embeddingResultSchema.parse(\n await embedder.embedTexts({ texts: [normalized] }),\n );\n if (result.vectors.length !== 1) {\n throw new Error(\"Embedding provider returned an unexpected vector count.\");\n }\n return {\n model: result.model,\n provider: result.provider,\n vector: result.vectors[0],\n };\n}\n\n/** Store the derived vector index; failures must not block memory persistence. */\nasync function storeEmbedding(args: {\n content: string;\n db: MemoryDb;\n embedder: MemoryEmbeddingProvider | undefined;\n embedding?: MemoryEmbedding;\n memoryId: string;\n nowMs: number;\n}): Promise<void> {\n if (!args.embedder && !args.embedding) {\n return;\n }\n try {\n const existing = await args.db\n .select({ memoryId: juniorMemoryEmbeddings.memoryId })\n .from(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, args.memoryId))\n .limit(1);\n if (existing[0]) {\n return;\n }\n } catch {\n return;\n }\n let embedding: Awaited<ReturnType<typeof embedOne>>;\n if (args.embedding) {\n embedding = args.embedding;\n } else {\n const embedder = args.embedder;\n if (!embedder) {\n return;\n }\n try {\n embedding = await embedOne(embedder, args.content);\n } catch {\n return;\n }\n }\n try {\n await args.db\n .insert(juniorMemoryEmbeddings)\n .values({\n contentHash: hashEmbeddedContent(args.content),\n createdAtMs: args.nowMs,\n dimensions: MEMORY_EMBEDDING_DIMENSIONS,\n embedding: embedding.vector,\n memoryId: args.memoryId,\n metric: EMBEDDING_METRIC,\n model: embedding.model,\n provider: embedding.provider,\n })\n .onConflictDoNothing();\n } catch {\n return;\n }\n}\n\nfunction activeScopedSubjectPredicate(args: {\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): SQL {\n const predicate = and(\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n eq(juniorMemoryMemories.kind, args.kind),\n eq(juniorMemoryMemories.subjectType, args.subject.subjectType),\n args.subject.subjectKey === undefined\n ? isNull(juniorMemoryMemories.subjectKey)\n : eq(juniorMemoryMemories.subjectKey, args.subject.subjectKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n if (!predicate) {\n throw new Error(\"Memory duplicate predicate is empty.\");\n }\n return predicate;\n}\n\nasync function findExactDuplicateMemory(args: {\n content: string;\n db: MemoryDb;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord | undefined> {\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryMemories.content, args.content),\n ),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(1);\n return rows[0] ? parseMemoryRow(rows[0]) : undefined;\n}\n\nasync function findVectorDuplicateMemory(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord | undefined> {\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n args.embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryEmbeddings.provider, args.embedding.provider),\n eq(juniorMemoryEmbeddings.model, args.embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n lte(distance, HIGH_CONFIDENCE_DUPLICATE_DISTANCE),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(1);\n const row = rows[0];\n if (!row || hashEmbeddedContent(row.memory.content) !== row.contentHash) {\n return undefined;\n }\n return parseMemoryRow(row.memory);\n}\n\nasync function rememberDuplicateIdempotency(args: {\n content: string;\n db: MemoryDb;\n duplicate: MemoryRecord;\n idempotencyKey?: string;\n nowMs: number;\n runtimeContext: MemoryRuntimeContext;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<void> {\n if (args.idempotencyKey === undefined) {\n return;\n }\n await args.db\n .insert(juniorMemoryMemories)\n .values({\n content: args.content,\n createdAtMs: args.nowMs,\n expiresAtMs: args.duplicate.expiresAtMs,\n id: idempotencyAliasId({\n idempotencyKey: args.idempotencyKey,\n scope: args.scope,\n targetId: args.duplicate.id,\n }),\n idempotencyKey: args.idempotencyKey,\n observedAtMs: args.nowMs,\n scope: args.scope.scope,\n scopeKey: args.scope.scopeKey,\n sourceKey: sourceKey(args.runtimeContext),\n sourcePlatform: args.runtimeContext.source.platform,\n subjectKey: args.subject.subjectKey,\n subjectType: args.subject.subjectType,\n supersededAtMs: args.nowMs,\n supersededById: args.duplicate.id,\n kind: args.duplicate.kind,\n })\n .onConflictDoNothing();\n}\n\nasync function listSupersessionCandidates(args: {\n content: string;\n db: MemoryDb;\n embedding?: MemoryEmbedding;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord[]> {\n const predicate = activeScopedSubjectPredicate(args);\n const terms = searchTerms(args.content).filter(\n (term) => !SUPERSESSION_STOP_TERMS.has(term),\n );\n const lexicalRows =\n terms.length > 0\n ? await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n ),\n ),\n )\n : [];\n const lexicalCandidates = lexicalRows\n .map(parseMemoryRow)\n .map((memory) => ({\n memory,\n score: searchScore(memory, terms),\n }))\n .filter((candidate) => candidate.score > 1)\n .sort(\n (left, right) =>\n right.score - left.score ||\n right.memory.createdAtMs - left.memory.createdAtMs ||\n left.memory.id.localeCompare(right.memory.id),\n )\n .map((candidate) => candidate.memory);\n\n const vectorCandidates = args.embedding\n ? await listVectorSupersessionCandidates({\n db: args.db,\n embedding: args.embedding,\n kind: args.kind,\n nowMs: args.nowMs,\n scope: args.scope,\n subject: args.subject,\n })\n : [];\n const byId = new Map<string, MemoryRecord>();\n for (const memory of [...lexicalCandidates, ...vectorCandidates]) {\n if (byId.size >= SUPERSESSION_CANDIDATE_LIMIT) {\n break;\n }\n byId.set(memory.id, memory);\n }\n return [...byId.values()];\n}\n\nasync function listVectorSupersessionCandidates(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord[]> {\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n args.embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryEmbeddings.provider, args.embedding.provider),\n eq(juniorMemoryEmbeddings.model, args.embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(SUPERSESSION_CANDIDATE_LIMIT);\n return rows.flatMap((row) => {\n if (hashEmbeddedContent(row.memory.content) !== row.contentHash) {\n return [];\n }\n return [parseMemoryRow(row.memory)];\n });\n}\n\nasync function decideSupersededIds(args: {\n candidates: MemoryRecord[];\n content: string;\n decider: MemorySupersessionDecider | undefined;\n kind: MemoryRecord[\"kind\"];\n runtimeContext: MemoryRuntimeContext;\n}): Promise<string[]> {\n // Supersession is conservative: model uncertainty or decider failure leaves\n // both memories active rather than hiding a possibly valid old preference.\n if (\n args.kind !== \"preference\" ||\n !args.decider ||\n args.candidates.length === 0\n ) {\n return [];\n }\n const existingMemories = args.candidates.map((memory) => ({\n content: memory.content,\n id: memory.id,\n })) as MemorySupersessionInput[\"existingMemories\"];\n const candidateIds = new Set(args.candidates.map((memory) => memory.id));\n try {\n const decision = await args.decider.adjudicateSupersession({\n candidate: {\n content: args.content,\n kind: \"preference\",\n },\n existingMemories,\n runtimeContext: args.runtimeContext,\n });\n if (decision.decision !== \"supersedes_old\") {\n return [];\n }\n return decision.supersededIds.filter((id) => candidateIds.has(id));\n } catch {\n return [];\n }\n}\n\n/** List active records for the runtime-derived visible scopes. */\nasync function listVisibleMemories(args: {\n db: MemoryDb;\n limit?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryRecord[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const limit = boundedLimit(args.limit, DEFAULT_LIST_LIMIT);\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(predicate)\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(limit);\n return rows.map(parseMemoryRow);\n}\n\n/** Search active visible records with the V1 lexical matcher. */\nasync function searchVisibleMemories(args: {\n db: MemoryDb;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<SearchCandidate[]> {\n const terms = searchTerms(args.query);\n if (terms.length === 0) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n ),\n ),\n );\n return rows.map((row) => ({\n memory: parseMemoryRow(row),\n score: 0,\n sourceKey: row.sourceKey,\n }));\n}\n\n/** Search active visible records with exact pgvector cosine distance. */\nasync function searchVisibleVectorMemories(args: {\n db: MemoryDb;\n embedder: MemoryEmbeddingProvider | undefined;\n limit: number;\n maxDistance?: number;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<SearchCandidate[]> {\n if (!args.embedder) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n let embedding: Awaited<ReturnType<typeof embedOne>>;\n try {\n embedding = await embedOne(args.embedder, args.query);\n } catch {\n return [];\n }\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n predicate,\n eq(juniorMemoryEmbeddings.provider, embedding.provider),\n eq(juniorMemoryEmbeddings.model, embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(args.limit);\n return rows.flatMap((row) => {\n const distanceValue = Number(row.distance);\n if (\n row.distance === null ||\n !Number.isFinite(distanceValue) ||\n hashEmbeddedContent(row.memory.content) !== row.contentHash\n ) {\n return [];\n }\n if (args.maxDistance !== undefined && distanceValue > args.maxDistance) {\n return [];\n }\n return [\n {\n memory: parseMemoryRow(row.memory),\n score: 1 / (1 + Math.max(0, distanceValue)),\n sourceKey: row.memory.sourceKey,\n },\n ];\n });\n}\n\nfunction sourceBoost(\n candidate: Pick<SearchCandidate, \"sourceKey\">,\n currentChannelPrefix: string | undefined,\n): number {\n if (!currentChannelPrefix) {\n return 0;\n }\n return candidate.sourceKey.startsWith(currentChannelPrefix)\n ? SOURCE_CHANNEL_BOOST\n : 0;\n}\n\n/** Score only observation age for near-tie reranking; this is not lifecycle decay. */\nfunction observedAgeBoost(memory: MemoryRecord, nowMs: number): number {\n const ageMs = Math.max(0, nowMs - memory.observedAtMs);\n if (ageMs <= 7 * ONE_DAY_MS) {\n return 0.15;\n }\n if (ageMs <= 30 * ONE_DAY_MS) {\n return 0.1;\n }\n if (ageMs <= 90 * ONE_DAY_MS) {\n return 0.05;\n }\n return 0;\n}\n\n/** Fuse retrieval candidates while keeping observed age to near-tie reranking. */\nfunction mergeSearchCandidates(\n candidates: SearchCandidate[],\n nowMs: number,\n currentChannelKey?: string,\n): MemoryRecord[] {\n const byId = new Map<\n string,\n {\n memory: MemoryRecord;\n score: number;\n sourceKey: string;\n }\n >();\n for (const candidate of candidates) {\n const existing = byId.get(candidate.memory.id);\n if (existing) {\n existing.score += candidate.score;\n continue;\n }\n byId.set(candidate.memory.id, {\n memory: candidate.memory,\n score: candidate.score,\n sourceKey: candidate.sourceKey,\n });\n }\n return [...byId.values()]\n .sort((left, right) => {\n const scoreDelta = right.score - left.score;\n if (Math.abs(scoreDelta) > RELEVANCE_NEAR_TIE_DELTA) {\n return scoreDelta;\n }\n const sourceDelta =\n sourceBoost(right, currentChannelKey) -\n sourceBoost(left, currentChannelKey);\n if (sourceDelta !== 0) {\n return sourceDelta;\n }\n return (\n observedAgeBoost(right.memory, nowMs) -\n observedAgeBoost(left.memory, nowMs) ||\n right.memory.observedAtMs - left.memory.observedAtMs ||\n left.memory.id.localeCompare(right.memory.id)\n );\n })\n .map((candidate) => candidate.memory);\n}\n\n/** Create a context-bound SQL-backed store for explicit memory operations. */\nexport function createMemoryStore(\n db: MemoryDb,\n context: MemoryRuntimeContext,\n options: MemoryStoreOptions = {},\n): MemoryStore {\n const runtimeContext = memoryRuntimeContextSchema.parse(context);\n const parsedOptions = memoryStoreOptionsSchema.parse({ now: options.now });\n const embedder = options.embedder;\n const maxVectorDistance = options.maxVectorDistance;\n const supersessionDecider = options.supersessionDecider;\n const getNowMs = parsedOptions.now ?? Date.now;\n\n async function archiveExpiredVisibleMemories(\n input: ArchiveExpiredMemoriesInput | undefined,\n nowMs: number,\n ): Promise<ArchiveExpiredMemoriesResult> {\n input = archiveExpiredMemoriesInputSchema.parse(input ?? {});\n return await archiveExpiredMemoryBatch({\n db,\n limit: input.limit,\n nowMs,\n scopes: deriveVisibleMemoryScopes(runtimeContext),\n });\n }\n\n /** Persist a memory under the plugin-derived scope and subject. */\n async function createScopedMemory(\n rawInput: CreateMemoryInput,\n scopeKind: MemoryScope,\n ): Promise<CreateMemoryResult> {\n const input = createMemoryInputSchema.parse(rawInput);\n const nowMs = getNowMs();\n const content = normalizeContent(input.content);\n const scope = deriveMemoryScope(runtimeContext, scopeKind);\n const subject = deriveMemorySubject(runtimeContext, scope);\n if (content.length > MAX_MEMORY_CONTENT_CHARS) {\n throw new Error(\"Memory content exceeds the maximum length.\");\n }\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes: [scope],\n });\n await archiveExpiredMemoryBatch({\n db,\n idempotencyKey: input.idempotencyKey,\n limit: 1,\n nowMs,\n scopes: [scope],\n });\n if (input.idempotencyKey !== undefined) {\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n });\n if (idempotent) {\n await storeEmbedding({\n content: idempotent.content,\n db,\n embedder,\n memoryId: idempotent.id,\n nowMs,\n });\n return { created: false, memory: idempotent };\n }\n }\n\n const exactDuplicate = await findExactDuplicateMemory({\n content,\n db,\n kind: input.kind,\n nowMs,\n scope,\n subject,\n });\n if (exactDuplicate) {\n await rememberDuplicateIdempotency({\n content,\n db,\n duplicate: exactDuplicate,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n runtimeContext,\n scope,\n subject,\n });\n await storeEmbedding({\n content: exactDuplicate.content,\n db,\n embedder,\n memoryId: exactDuplicate.id,\n nowMs,\n });\n return { created: false, memory: exactDuplicate };\n }\n\n let candidateEmbedding: MemoryEmbedding | undefined;\n if (embedder) {\n try {\n candidateEmbedding = await embedOne(embedder, content);\n } catch {\n candidateEmbedding = undefined;\n }\n }\n const vectorDuplicate = candidateEmbedding\n ? await findVectorDuplicateMemory({\n db,\n embedding: candidateEmbedding,\n kind: input.kind,\n nowMs,\n scope,\n subject,\n })\n : undefined;\n if (vectorDuplicate) {\n await rememberDuplicateIdempotency({\n content,\n db,\n duplicate: vectorDuplicate,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n runtimeContext,\n scope,\n subject,\n });\n await storeEmbedding({\n content: vectorDuplicate.content,\n db,\n embedder,\n memoryId: vectorDuplicate.id,\n nowMs,\n });\n return { created: false, memory: vectorDuplicate };\n }\n\n let supersededIds: string[] = [];\n if (\n scopeKind === \"personal\" &&\n input.kind === \"preference\" &&\n supersessionDecider &&\n (input.expiresAtMs === undefined || input.expiresAtMs > nowMs)\n ) {\n const supersessionCandidates = await listSupersessionCandidates({\n content,\n db,\n ...(candidateEmbedding ? { embedding: candidateEmbedding } : {}),\n kind: input.kind,\n nowMs,\n scope,\n subject,\n });\n supersededIds = await decideSupersededIds({\n candidates: supersessionCandidates,\n content,\n decider: supersessionDecider,\n kind: input.kind,\n runtimeContext,\n });\n }\n\n const id = randomUUID();\n const rows = await db.transaction(async (tx) => {\n const inserted = await tx\n .insert(juniorMemoryMemories)\n .values({\n content,\n createdAtMs: nowMs,\n expiresAtMs: input.expiresAtMs,\n id,\n idempotencyKey: input.idempotencyKey,\n observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: runtimeContext.source.platform,\n subjectKey: subject.subjectKey,\n subjectType: subject.subjectType,\n kind: input.kind,\n })\n .onConflictDoNothing({\n target: [\n juniorMemoryMemories.scope,\n juniorMemoryMemories.scopeKey,\n juniorMemoryMemories.idempotencyKey,\n ],\n where: sql`${juniorMemoryMemories.idempotencyKey} IS NOT NULL AND ${juniorMemoryMemories.archivedAtMs} IS NULL AND ${juniorMemoryMemories.supersededAtMs} IS NULL AND ${juniorMemoryMemories.supersededById} IS NULL`,\n })\n .returning();\n const insertedMemory = inserted[0];\n if (!insertedMemory || supersededIds.length === 0) {\n return inserted;\n }\n const superseded = await tx\n .update(juniorMemoryMemories)\n .set({\n supersededAtMs: nowMs,\n supersededById: insertedMemory.id,\n })\n .where(\n and(\n inArray(juniorMemoryMemories.id, supersededIds),\n activeScopedSubjectPredicate({\n kind: input.kind,\n nowMs,\n scope,\n subject,\n }),\n ),\n )\n .returning({ id: juniorMemoryMemories.id });\n const idsToClean = superseded.map((row) => row.id);\n if (idsToClean.length > 0) {\n await tx\n .delete(juniorMemoryEmbeddings)\n .where(inArray(juniorMemoryEmbeddings.memoryId, idsToClean));\n }\n return inserted;\n });\n if (rows[0]) {\n const memory = parseMemoryRow(rows[0]);\n await storeEmbedding({\n content: memory.content,\n db,\n embedder,\n embedding: candidateEmbedding,\n memoryId: memory.id,\n nowMs,\n });\n return { created: true, memory };\n }\n\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n });\n if (!idempotent) {\n throw new Error(\"Memory idempotency conflict did not resolve.\");\n }\n await storeEmbedding({\n content: idempotent.content,\n db,\n embedder,\n memoryId: idempotent.id,\n nowMs,\n });\n return { created: false, memory: idempotent };\n }\n\n return {\n async archiveExpiredMemories(input) {\n return await archiveExpiredVisibleMemories(input, getNowMs());\n },\n\n async createMemory(input) {\n return await createScopedMemory(input, \"personal\");\n },\n\n async createConversationMemory(input) {\n return await createScopedMemory(input, \"conversation\");\n },\n\n async listMemories(input) {\n input = listMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n return await listVisibleMemories({\n db,\n limit: input.limit,\n nowMs,\n scopes,\n });\n },\n\n async searchMemories(input) {\n input = searchMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n const limit = boundedLimit(input.limit, DEFAULT_SEARCH_LIMIT);\n const vectorCandidates = await searchVisibleVectorMemories({\n db,\n embedder,\n limit: limit * VECTOR_SEARCH_OVERFETCH,\n ...(maxVectorDistance !== undefined\n ? { maxDistance: maxVectorDistance }\n : {}),\n nowMs,\n query: input.query,\n scopes,\n });\n const candidates = await searchVisibleMemories({\n db,\n nowMs,\n query: input.query,\n scopes,\n });\n const terms = searchTerms(input.query);\n const lexicalCandidates = candidates\n .map((candidate) => ({\n ...candidate,\n score: searchScore(candidate.memory, terms),\n }))\n .filter((item) => item.score > 0);\n return mergeSearchCandidates(\n [...vectorCandidates, ...lexicalCandidates],\n nowMs,\n sourceChannelPrefix(runtimeContext),\n ).slice(0, limit);\n },\n\n async archiveMemory(input) {\n input = archiveMemoryInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n const predicate = activeVisiblePredicate({ nowMs, scopes });\n const idPrefix = input.id.trim();\n if (!idPrefix) {\n throw new Error(\"Memory id is required.\");\n }\n const rows = predicate\n ? await db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n eq(juniorMemoryMemories.id, idPrefix),\n like(juniorMemoryMemories.id, `${idPrefix}%`),\n ),\n ),\n )\n .orderBy(asc(juniorMemoryMemories.id))\n .limit(2)\n : [];\n if (rows.length === 0) {\n throw new Error(\"Memory was not found in the current context.\");\n }\n if (rows.length > 1) {\n throw new Error(\"Memory id prefix is ambiguous.\");\n }\n const memory = parseMemoryRow(rows[0]);\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: input.reason ?? \"user_removed\",\n })\n .where(eq(juniorMemoryMemories.id, memory.id))\n .returning();\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memory.id));\n return parseMemoryRow(updated[0]);\n },\n };\n}\n","import { isPrivateSource } from \"@sentry/junior-plugin-api\";\nimport type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\n/** Runtime-derived visibility scope used for memory authorization checks. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** Runtime-derived subject classification stored for filtering and rendering. */\nexport interface ResolvedMemorySubject {\n subjectKey?: string;\n subjectType: MemorySubjectType;\n}\n\nfunction sourceConversationKey(ctx: MemoryRuntimeContext): string | undefined {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n if (!isPrivateSource(ctx.source)) {\n return `slack:${ctx.source.teamId}`;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n return undefined;\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\nfunction requesterScopeKey(ctx: MemoryRuntimeContext): string | undefined {\n const requester = ctx.requester;\n if (!requester?.userId) {\n return undefined;\n }\n if (requester.platform === \"slack\") {\n return `slack:${requester.teamId}:${requester.userId}`;\n }\n return `local:${requester.userId}`;\n}\n\n/** Derive the authority-bearing key for a requested memory scope. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n scope: MemoryScope,\n): ResolvedMemoryScope {\n if (scope === \"personal\") {\n const scopeKey = requesterScopeKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Personal memory requires requester context.\");\n }\n return { scope, scopeKey };\n }\n\n const scopeKey = sourceConversationKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Conversation memory requires conversation context.\");\n }\n return { scope, scopeKey };\n}\n\n/** Derive the memory subject from the already-authorized write scope. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n scope: ResolvedMemoryScope,\n): ResolvedMemorySubject {\n if (scope.scope === \"personal\") {\n const subjectKey = requesterScopeKey(ctx);\n if (!subjectKey) {\n throw new Error(\"User-subject memory requires requester context.\");\n }\n return { subjectType: \"user\", subjectKey };\n }\n\n const subjectKey = sourceConversationKey(ctx);\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return { subjectType: \"conversation\", subjectKey };\n}\n\n/** Return every visible scope for memory retrieval in the current context. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n const scopes: ResolvedMemoryScope[] = [];\n try {\n scopes.push(deriveMemoryScope(ctx, \"personal\"));\n } catch {\n // Personal memory is optional when a runtime surface has no requester.\n }\n try {\n scopes.push(deriveMemoryScope(ctx, \"conversation\"));\n } catch {\n // Conversation memory is optional for synthetic invocations.\n }\n return scopes;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\n isPrivateSource,\n type PluginTaskContext,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryDb,\n} from \"./store\";\nimport {\n createMemoryAgent,\n parseExtractedMemory,\n type ExtractedMemory,\n} from \"./agent\";\nimport {\n MEMORY_KINDS,\n memoryRuntimeContextSchema,\n type MemoryKind,\n} from \"./types\";\n\nconst MEMORY_TOOL_NAMES = new Set([\n \"createMemory\",\n \"listMemories\",\n \"removeMemory\",\n \"searchMemories\",\n]);\nconst MEMORY_TASK_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst extractedMemoryCacheSchema = z.array(\n z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().nullable(),\n kind: z.enum(MEMORY_KINDS),\n })\n .strict()\n .transform(parseExtractedMemory),\n);\n\nfunction targetForKind(kind: MemoryKind): \"requester\" | \"conversation\" {\n if (kind === \"preference\") {\n return \"requester\";\n }\n return \"conversation\";\n}\n\nfunction memoryIdempotencySuffix(memory: ExtractedMemory): string {\n return createHash(\"sha256\")\n .update(targetForKind(memory.kind))\n .update(\"\\0\")\n .update(memory.kind)\n .update(\"\\0\")\n .update(memory.content)\n .update(\"\\0\")\n .update(memory.expiresAtMs === null ? \"never\" : String(memory.expiresAtMs))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction passiveInput(\n sessionId: string,\n memory: ExtractedMemory,\n sourceKey: string,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory)}`,\n kind: memory.kind,\n ...(memory.expiresAtMs !== null ? { expiresAtMs: memory.expiresAtMs } : {}),\n };\n}\n\nasync function getTaskMemories(\n context: PluginTaskContext,\n extract: () => Promise<ExtractedMemory[]>,\n): Promise<ExtractedMemory[]> {\n const cacheKey = `memory-extraction:${context.id}`;\n const cached = await context.state.get(cacheKey);\n if (cached !== undefined) {\n return extractedMemoryCacheSchema.parse(cached);\n }\n const memories = await extract();\n if (memories.length > 0) {\n await context.state.set(cacheKey, memories, MEMORY_TASK_STATE_TTL_MS);\n }\n return memories;\n}\n\n/**\n * Extract and store memories from a completed session plugin task.\n *\n * Memory owns post-session extraction and consumes only the bounded plugin task\n * projection. Explicit memory tools and private non-local sources remain hard\n * boundaries so background retries cannot reinterpret user-directed mutations\n * or private conversations.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // Memory tool turns already own memory management or recall; do not reinterpret\n // recalled memory output as fresh passive-learning evidence.\n if (\n run.transcript.some(\n (entry) =>\n entry.type === \"toolResult\" && MEMORY_TOOL_NAMES.has(entry.toolName),\n )\n ) {\n return;\n }\n // V1 passive learning only stores public channel facts outside local QA.\n if (run.source.platform !== \"local\" && isPrivateSource(run.source)) {\n return;\n }\n const sourceKey = getSourceKey(run.source);\n if (!sourceKey) {\n return;\n }\n const transcript = run.transcript\n .filter((entry) => entry.text?.trim())\n .map((entry) => ({ ...entry, text: entry.text!.trim() }));\n const evidenceText = transcript\n .filter((entry) => entry.type === \"toolResult\" || entry.role === \"user\")\n .map((entry) => entry.text)\n .join(\"\\n\\n\")\n .trim();\n if (!evidenceText) {\n return;\n }\n\n const runtimeContext = memoryRuntimeContextSchema.parse({\n conversationId: run.conversationId,\n ...(run.requester ? { requester: run.requester } : {}),\n source: run.source,\n });\n const agent = createMemoryAgent(context.model);\n const store = createMemoryStore(context.db as MemoryDb, runtimeContext, {\n embedder: context.embedder,\n supersessionDecider: agent,\n });\n await store.archiveExpiredMemories();\n const memories = await getTaskMemories(context, async () => {\n const existingMemories = await store.searchMemories({\n limit: 10,\n query: evidenceText,\n });\n return await agent.extractSessionMemories({\n existingMemories: existingMemories.map((memory) => ({\n content: memory.content,\n })),\n transcript,\n runtimeContext,\n });\n });\n if (memories.length === 0) {\n return;\n }\n\n for (const memory of memories) {\n const input = passiveInput(run.runId, memory, sourceKey);\n if (targetForKind(memory.kind) === \"conversation\") {\n await store.createConversationMemory(input);\n continue;\n }\n if (!run.requester) {\n continue;\n }\n await store.createMemory(input);\n }\n}\n","import type {\n PromptMessage,\n Requester,\n Source,\n} from \"@sentry/junior-plugin-api\";\nimport {\n createMemoryStore,\n type MemoryDb,\n type MemoryEmbeddingProvider,\n type MemoryRecord,\n} from \"./store\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst DEFAULT_RECALL_LIMIT = 5;\nconst MAX_PROMPT_CHARS = 4_000;\nconst MAX_MEMORY_LINE_CHARS = 600;\n\nexport interface MemoryRecallContext {\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n /** Maximum cosine distance for vector recall. Passed through to the memory store. */\n maxVectorDistance?: number;\n requester?: Requester;\n source: Source;\n text: string;\n}\n\nfunction trimContent(content: string, maxLength: number): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxLength) {\n return trimmed;\n }\n return `${trimmed.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\nfunction formatObservedDate(observedAtMs: number): string {\n return new Date(observedAtMs).toISOString().slice(0, 10);\n}\n\nfunction renderMemoryPrompt(memories: MemoryRecord[]): string | undefined {\n const header = \"Relevant memories for this request:\";\n const footer =\n \"Treat these as possibly stale context. Current user instructions and repository evidence take priority.\";\n const lines: string[] = [];\n let totalChars = header.length + footer.length + 2;\n\n for (const memory of memories) {\n const line = `- Observed ${formatObservedDate(memory.observedAtMs)}: ${trimContent(\n memory.content,\n MAX_MEMORY_LINE_CHARS,\n )}`;\n if (totalChars + line.length + 1 > MAX_PROMPT_CHARS) {\n break;\n }\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length === 0) {\n return undefined;\n }\n return `${header}\\n${lines.join(\"\\n\")}\\n\\n${footer}`;\n}\n\n/** Build the memory prompt contribution for active visible recall. */\nexport async function createMemoryPromptMessages(\n context: MemoryRecallContext,\n): Promise<PromptMessage[] | undefined> {\n if (!context.text.trim()) {\n return undefined;\n }\n const runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.requester ? { requester: context.requester } : {}),\n source: context.source,\n });\n const memories = await createMemoryStore(\n context.db,\n runtimeContext,\n {\n ...(context.embedder ? { embedder: context.embedder } : {}),\n ...(context.maxVectorDistance !== undefined\n ? { maxVectorDistance: context.maxVectorDistance }\n : {}),\n },\n ).searchMemories({\n query: context.text,\n limit: DEFAULT_RECALL_LIMIT,\n });\n const text = renderMemoryPrompt(memories);\n return text ? [{ text }]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A,UACA,cAAc,uBAAuB,OAAO;AAAA,UAC5C,cAAc,qBAAqB,OAAO;AAAA,UAC1C,gBAAgB,uBAAuB,OAAO;AAAA,QAChD;AAAA,MACF;AAAA,MACA,MAAM,WAAW,KAAK;AACpB,eAAO,MAAM,2BAA2B;AAAA,UACtC,GAAI,IAAI,iBAAiB,EAAE,gBAAgB,IAAI,eAAe,IAAI,CAAC;AAAA,UACnE,GAAI,IAAI,YAAY,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;AAAA,UACpD,IAAI,IAAI;AAAA,UACR,UAAU,IAAI;AAAA,UACd,mBAAmB,wBAAwB,OAAO;AAAA,UAClD,QAAQ,IAAI;AAAA,UACZ,MAAM,IAAI;AAAA,QACZ,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEO,IAAM,eAAe,mBAAmB;","names":["z","z","index","eq","eq","z","and","desc","eq","gt","ilike","isNull","or","sql","z","scopeKey","subjectKey","nonEmptyStringSchema","z","or","and","eq","isNull","gt","desc","text","ilike","idempotent","sql","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","z","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","createHash","getSourceKey","isPrivateSource","z","z","targetForKind","createHash","sourceKey","isPrivateSource","getSourceKey","text"]}
|
|
1
|
+
{"version":3,"sources":["../src/plugin.ts","../src/agent.ts","../src/types.ts","../src/cli/search.ts","../src/db/schema.ts","../src/cli/format.ts","../src/cli/show.ts","../src/cli/index.ts","../src/tools.ts","../src/store.ts","../src/scope.ts","../src/process-session.ts","../src/recall.ts"],"sourcesContent":["import { defineJuniorPlugin } from \"@sentry/junior-plugin-api\";\nimport { createMemoryAgent } from \"./agent\";\nimport { createMemoryCliCommand } from \"./cli\";\nimport {\n createMemoryCreateTool,\n createMemoryListTool,\n createMemoryRemoveTool,\n createMemorySearchTool,\n type MemoryCreateToolContext,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { createMemoryPromptMessages } from \"./recall\";\nimport type { MemoryDb } from \"./store\";\n\nconst MEMORY_MODEL_ENV = \"AI_MEMORY_MODEL\";\nconst MEMORY_RECALL_MAX_VECTOR_DISTANCE_ENV =\n \"MEMORY_RECALL_MAX_VECTOR_DISTANCE\";\nconst DEFAULT_RECALL_MAX_VECTOR_DISTANCE = 0.45;\n\nexport interface MemoryPluginOptions {\n modelId?: string;\n /** Maximum cosine distance for vector recall candidates. Defaults to MEMORY_RECALL_MAX_VECTOR_DISTANCE env or 0.45. */\n recallMaxVectorDistance?: number;\n}\n\nfunction memoryModelId(options: MemoryPluginOptions): string | undefined {\n const explicitModelId = options.modelId?.trim();\n if (explicitModelId) {\n return explicitModelId;\n }\n const envModelId = process.env[MEMORY_MODEL_ENV]?.trim();\n return envModelId || undefined;\n}\n\nfunction recallMaxVectorDistance(options: MemoryPluginOptions): number {\n if (options.recallMaxVectorDistance !== undefined) {\n return options.recallMaxVectorDistance;\n }\n const raw = process.env[MEMORY_RECALL_MAX_VECTOR_DISTANCE_ENV]?.trim();\n if (raw) {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed > 0) {\n return Math.min(parsed, 1);\n }\n }\n return DEFAULT_RECALL_MAX_VECTOR_DISTANCE;\n}\n\nfunction memoryToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryToolContext[\"db\"];\n embedder?: MemoryToolContext[\"embedder\"];\n actor?: MemoryToolContext[\"actor\"];\n source: MemoryToolContext[\"source\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.actor ? { actor: ctx.actor } : {}),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : {}),\n source: ctx.source,\n ...(ctx.userText ? { userText: ctx.userText } : {}),\n };\n}\n\nfunction memoryCreateToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryCreateToolContext[\"db\"];\n embedder?: MemoryCreateToolContext[\"embedder\"];\n actor?: MemoryCreateToolContext[\"actor\"];\n source: MemoryCreateToolContext[\"source\"];\n supersessionDecider: MemoryCreateToolContext[\"supersessionDecider\"];\n userText?: string;\n}): MemoryCreateToolContext {\n return {\n ...memoryToolContext(ctx),\n supersessionDecider: ctx.supersessionDecider,\n };\n}\n\n/** Create Junior's long-term memory plugin registration. */\nexport function createMemoryPlugin(options: MemoryPluginOptions = {}) {\n const modelId = memoryModelId(options);\n return defineJuniorPlugin({\n manifest: {\n name: \"memory\",\n displayName: \"Memory\",\n description: \"Long-term Junior memory storage and recall\",\n },\n model: modelId\n ? { structuredModelId: modelId }\n : { structuredModel: \"default\" },\n packageName: \"@sentry/junior-memory\",\n cli: {\n commands: [createMemoryCliCommand()],\n },\n tasks: {\n processSession: {\n async run(ctx) {\n await processMemorySession(ctx);\n },\n },\n },\n hooks: {\n tools(ctx) {\n const agent = createMemoryAgent(ctx.model);\n const context = memoryToolContext({\n ...ctx,\n agent,\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n });\n return {\n createMemory: createMemoryCreateTool(\n memoryCreateToolContext({\n ...ctx,\n agent,\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n supersessionDecider: agent,\n }),\n ),\n removeMemory: createMemoryRemoveTool(context),\n listMemories: createMemoryListTool(context),\n searchMemories: createMemorySearchTool(context),\n };\n },\n async userPrompt(ctx) {\n return await createMemoryPromptMessages({\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.actor ? { actor: ctx.actor } : {}),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n maxVectorDistance: recallMaxVectorDistance(options),\n source: ctx.source,\n text: ctx.text,\n });\n },\n },\n });\n}\n\nexport const memoryPlugin = createMemoryPlugin();\n","import { actorSchema, type PluginModel } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport type {\n MemorySupersessionDecision,\n MemorySupersessionInput,\n} from \"./store\";\nimport {\n MEMORY_KINDS,\n memoryRuntimeContextSchema,\n type MemoryKind,\n} from \"./types\";\n\nconst memoryKindSchema = z.enum(MEMORY_KINDS);\nconst memoryRejectReasonSchema = z.enum([\n \"not_public_shareable\",\n \"secret_or_credential\",\n \"sensitive_personal\",\n \"third_party_personal\",\n \"vague_or_not_self_contained\",\n \"not_durable\",\n \"assistant_or_system_detail\",\n \"unsupported_scope\",\n]);\nconst createMemoryRequestSchema = z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n runtimeContext: memoryRuntimeContextSchema,\n sourceContext: z\n .object({\n currentUserText: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nconst transcriptProvenanceSchema = z\n .object({\n authority: z.enum([\"instruction\", \"context\"]),\n actor: actorSchema.optional(),\n })\n .strict();\nconst evidenceMessageIndicesSchema = z\n .array(z.number().int().nonnegative())\n .min(1)\n .max(10)\n .describe(\"Indices from <run-transcript> that directly support this memory.\");\nconst extractSessionRequestSchema = z\n .object({\n existingMemories: z\n .array(\n z\n .object({\n content: z.string().min(1),\n })\n .strict(),\n )\n .max(10)\n .default([]),\n actors: z.array(actorSchema),\n runtimeContext: memoryRuntimeContextSchema,\n transcript: z\n .array(\n z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"message\"),\n role: z.enum([\"user\", \"assistant\"]),\n text: z.string().min(1),\n provenance: transcriptProvenanceSchema.optional(),\n isRunActor: z.boolean().optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"toolResult\"),\n toolName: z.string().min(1),\n isError: z.boolean(),\n text: z.string().min(1),\n })\n .strict(),\n ]),\n )\n .min(1),\n })\n .strict();\nconst supersessionRequestSchema = z\n .object({\n candidate: z\n .object({\n content: z.string().min(1),\n kind: z.literal(\"preference\"),\n })\n .strict(),\n existingMemories: z\n .array(\n z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n })\n .strict(),\n )\n .min(1)\n .max(10),\n runtimeContext: memoryRuntimeContextSchema,\n })\n .strict();\n\nconst expiresAtMsSchema = z\n .number()\n .finite()\n .nullable()\n .describe(\n \"Expiration timestamp when the fact should expire, otherwise null.\",\n );\nconst memoryReviewDecisionSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n kind: memoryKindSchema,\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst memoryReviewResponseSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n kind: memoryKindSchema.describe(\n \"Use preference only for actor-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use knowledge for shared project, channel, operational, or runbook facts.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text. It must be self-contained and must not include actor names, actor/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst extractedMemorySchema = z\n .object({\n kind: memoryKindSchema.describe(\n \"Use preference only for actor-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use knowledge for shared project, channel, operational, or runbook facts.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text as one self-contained fact. It must not include actor names, actor/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n evidenceMessageIndices: evidenceMessageIndicesSchema,\n })\n .strict();\nconst extractedMemoryResultSchema = z\n .object({\n content: z.string().min(1),\n expiresAtMs: expiresAtMsSchema,\n kind: memoryKindSchema,\n evidenceMessageIndices: evidenceMessageIndicesSchema,\n })\n .strict();\nconst extractMemoriesResponseSchema = z\n .object({\n memories: z\n .array(extractedMemorySchema)\n .max(5)\n .describe(\n \"Accepted public/shareable durable memories from the completed run. Return one object per distinct source assertion and classify it with kind.\",\n ),\n })\n .strict();\nconst supersessionDecisionResponseSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"supersedes_old\"),\n supersededIds: z.array(z.string().min(1)).min(1).max(10),\n })\n .strict(),\n z\n .object({\n decision: z.enum([\"distinct\", \"uncertain\"]),\n })\n .strict(),\n]);\n\ntype MemoryReviewResponse = z.output<typeof memoryReviewResponseSchema>;\ntype ExtractMemoriesResponse = z.output<typeof extractMemoriesResponseSchema>;\n\nexport type MemoryReview = z.output<typeof memoryReviewDecisionSchema>;\n\nexport type CreateMemoryRequest = z.output<typeof createMemoryRequestSchema>;\nexport type ExtractSessionRequest = z.output<\n typeof extractSessionRequestSchema\n>;\nexport type ExtractedMemory = z.output<typeof extractedMemoryResultSchema>;\n\nexport interface MemoryAgent {\n /** Decide whether a new preference safely replaces active old preferences. */\n adjudicateSupersession(\n request: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n extractSessionMemories(\n request: ExtractSessionRequest,\n ): Promise<ExtractedMemory[]> | ExtractedMemory[];\n reviewCreateRequest(\n request: CreateMemoryRequest,\n ): Promise<MemoryReview> | MemoryReview;\n}\n\nconst MEMORY_REVIEW_SYSTEM = [\n \"You are Junior's memory review agent.\",\n \"Review one memory candidate and return one structured review decision.\",\n \"Store only public/shareable, self-contained facts that are useful beyond this turn.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"Use the runtime context only for authority and scope; do not accept model-provided actor ids, scope ids, aliases, or arbitrary subjects.\",\n].join(\"\\n\");\nconst MEMORY_EXTRACTION_SYSTEM = [\n \"You are Junior's passive memory extraction agent. Return only structured memories worth storing.\",\n \"Use the completed run transcript as source evidence, including user-authored messages and tool results.\",\n \"Assistant text is context for interpreting the run, not independent evidence for new facts.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"If no public, durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst MEMORY_SUPERSESSION_SYSTEM = [\n \"You are Junior's memory supersession agent.\",\n \"Decide whether a new actor preference clearly replaces existing active actor preferences.\",\n \"Return supersedes_old only for obvious changed preferences about the same mutable slot.\",\n \"If the facts are additive, different topics, duplicate, broader/narrower without direct replacement, or uncertain, do not supersede.\",\n].join(\"\\n\");\nconst CANONICAL_CONTENT_RULES = [\n \"- Stored memory text must be a rewritten fact, not copied user wording or a sentence about who said it.\",\n \"- Store the minimum useful assertion supported by source evidence; do not add adjacent steps, caveats, or generalized advice.\",\n \"- Do not return both concise and expanded variants of the same source assertion; keep the shortest self-contained canonical memory.\",\n \"- Put ownership in structured fields, not prose.\",\n \"- For actor memories, omit the subject and write a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Drop perspective/provenance markers while preserving useful context.\",\n \"- Remove actor names, display names, actor/user labels, first- or second-person wording, thread labels, channel labels, and source labels.\",\n];\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\");\n}\n\nfunction runtimeDescription(\n request: Pick<CreateMemoryRequest, \"expiresAtMs\" | \"runtimeContext\">,\n): string {\n const runtime = request.runtimeContext;\n const actor =\n runtime.actor?.platform === \"slack\"\n ? `slack:${runtime.actor.teamId}:${runtime.actor.userId}`\n : runtime.actor?.platform === \"local\"\n ? `local:${runtime.actor.userId}`\n : \"none\";\n const source =\n runtime.source.platform === \"slack\"\n ? `slack:${runtime.source.teamId}:${runtime.source.channelId}`\n : `local:${runtime.source.conversationId}`;\n const lines = [\n `- actor: ${escapeXml(actor)}`,\n `- source: ${escapeXml(source)}`,\n `- has_conversation: ${runtime.conversationId ? \"true\" : \"false\"}`,\n `- expires_at: ${\n request.expiresAtMs === undefined\n ? \"never\"\n : escapeXml(new Date(request.expiresAtMs).toISOString())\n }`,\n ];\n return [\"<runtime>\", ...lines, \"</runtime>\"].join(\"\\n\");\n}\n\nfunction sourceContext(request: CreateMemoryRequest): string | undefined {\n const currentUserText = request.sourceContext?.currentUserText?.trim();\n if (!currentUserText) {\n return undefined;\n }\n return [\n \"<source-context>\",\n \"The current user-authored text is source evidence for explicit memory requests. Use it to recover the concrete fact when the candidate is incomplete, vague, or over-personalized. Store only rewritten, self-contained memory content.\",\n \"<current-user-message>\",\n escapeXml(currentUserText),\n \"</current-user-message>\",\n \"</source-context>\",\n ].join(\"\\n\");\n}\n\nfunction existingMemoriesContext(request: ExtractSessionRequest): string {\n if (request.existingMemories.length === 0) {\n return \"<existing-memories>[]</existing-memories>\";\n }\n return [\n \"<existing-memories>\",\n \"Use these only to skip memories that are already covered or semantically redundant. They are not source evidence for new memories.\",\n escapeXml(JSON.stringify(request.existingMemories)),\n \"</existing-memories>\",\n ].join(\"\\n\");\n}\n\n/**\n * Passive extraction offers personal preferences only on single-actor runs.\n * Multi-actor runs restrict extraction to conversation-scoped kinds.\n */\nfunction allowedExtractionKinds(actorCount: number): Set<MemoryKind> {\n return actorCount === 1\n ? new Set<MemoryKind>(MEMORY_KINDS)\n : new Set<MemoryKind>([\"procedure\", \"knowledge\"]);\n}\n\nfunction memoryKindsContext(allowedKinds: Set<MemoryKind>): string {\n const lines = [\"<memory-kinds>\"];\n if (allowedKinds.has(\"preference\")) {\n lines.push(\n \"- preference: a durable first-person personal preference, opinion, habit, or workflow owned by the current actor. Stored as actor memory.\",\n );\n }\n lines.push(\n \"- procedure: reusable instructions for how a task, lookup, investigation, process, triage flow, or runbook should be done. Store the method, source-of-truth, prerequisite, or decision path when it took effort to discover. Stored as conversation memory.\",\n \"- knowledge: stable shared project, channel, operational, or runbook fact that is not a personal actor preference. Direct answers to user inquiries qualify only when they are durable beyond this run. Stored as conversation memory.\",\n \"</memory-kinds>\",\n );\n return lines.join(\"\\n\");\n}\n\nfunction reviewPrompt(request: CreateMemoryRequest): string {\n const sections = [\n \"<memory-review-input>\",\n \"Review the candidate memory using the runtime-owned context below.\",\n \"\",\n runtimeDescription(request),\n \"\",\n sourceContext(request),\n \"\",\n \"<candidate>\",\n escapeXml(request.content),\n \"</candidate>\",\n \"\",\n \"<rules>\",\n \"- Return store only when the candidate is public/shareable, durable, and self-contained.\",\n \"- First classify the memory kind: preference, procedure, or knowledge.\",\n \"- Use kind=preference only for first-person facts authored by the current actor about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current actor.\",\n \"- Use kind=procedure for reusable task/process/runbook instructions.\",\n \"- Use kind=knowledge for shared project, channel, operational, or runbook facts.\",\n \"- When current-user-message contains an explicit memory request with a concrete fact or procedure, extract from current-user-message even if the candidate is vague, incomplete, or phrased as an instruction.\",\n \"- A candidate may be badly phrased by an outer assistant or extraction pass. When current-user-message contains the actor's own first-person memory fact, treat that as actor-authored source evidence and canonicalize the fact instead of rejecting for third-person wording.\",\n \"- When candidate wording personalizes a shared task, process, runbook, project, channel, or operational fact, use current-user-message to recover the shared fact and classify it as procedure or knowledge.\",\n \"- Explicit procedure requests are valid when the source text contains both task context and action. Canonicalize them as shared procedure facts instead of rejecting them as vague.\",\n \"- Store content as person-less, source-less canonical knowledge. Ownership and source live in structured metadata, not prose.\",\n \"- For actor memories, omit the subject and write the content as a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Remove actor names, display names, actor/user labels, first- or second-person wording, thread labels, channel labels, and source labels from stored content.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- Reject vague content such as 'remember this' unless the candidate or current-user-message contains the concrete fact.\",\n \"- Preserve the requested expiration when one exists; otherwise set expiresAtMs to null.\",\n \"- If unsure, reject.\",\n \"</rules>\",\n \"</memory-review-input>\",\n ].filter((section): section is string => section !== undefined);\n return sections.join(\"\\n\");\n}\n\nfunction transcriptActorLabel(\n actor: z.output<typeof actorSchema> | undefined,\n): string {\n if (!actor) {\n return \"none\";\n }\n if (actor.platform === \"system\") {\n return `system:${actor.name}`;\n }\n return actor.platform === \"slack\"\n ? `slack:${actor.teamId}:${actor.userId}`\n : `local:${actor.userId}`;\n}\n\nfunction runTranscriptContext(request: ExtractSessionRequest): string {\n return [\n \"<run-transcript>\",\n ...request.transcript.map((entry, index) => {\n if (entry.type === \"toolResult\") {\n return [\n `<tool-result index=\"${index}\" tool=\"${escapeXml(entry.toolName)}\" is_error=\"${entry.isError ? \"true\" : \"false\"}\">`,\n escapeXml(entry.text),\n \"</tool-result>\",\n ].join(\"\\n\");\n }\n const authority = entry.provenance?.authority ?? \"context\";\n const isRunActor = entry.isRunActor === true;\n const actor = transcriptActorLabel(entry.provenance?.actor);\n return [\n `<message index=\"${index}\" role=\"${entry.role}\" authority=\"${authority}\" is_run_actor=\"${isRunActor ? \"true\" : \"false\"}\" actor=\"${escapeXml(actor)}\">`,\n escapeXml(entry.text),\n \"</message>\",\n ].join(\"\\n\");\n }),\n \"</run-transcript>\",\n ].join(\"\\n\");\n}\n\nfunction sessionExtractionPrompt(request: ExtractSessionRequest): string {\n const allowedKinds = allowedExtractionKinds(request.actors.length);\n const allowsPreference = allowedKinds.has(\"preference\");\n return [\n \"<memory-extraction-input>\",\n \"Extract durable memories from this completed agent run using the runtime-owned context below.\",\n \"\",\n runtimeDescription({\n runtimeContext: request.runtimeContext,\n }),\n \"\",\n existingMemoriesContext(request),\n \"\",\n memoryKindsContext(allowedKinds),\n \"\",\n runTranscriptContext(request),\n \"\",\n \"<rules>\",\n \"- Return at most five memories.\",\n \"- Every returned memory must cite one or more evidenceMessageIndices from <run-transcript>.\",\n \"- Cite only indices that directly support the stored fact; do not cite assistant messages as independent evidence.\",\n \"- Each transcript message exposes authority (instruction or context), is_run_actor, and an actor id. Use these to classify evidence.\",\n ...(allowsPreference\n ? [\n \"- For a preference, cite only messages with authority=instruction and is_run_actor=true; a preference must be the run actor's own first-person fact.\",\n ]\n : []),\n \"- For a procedure or knowledge memory, cite run-actor instruction messages, public context messages, or successful tool results.\",\n \"- Use user messages and successful tool results as source evidence for storable facts.\",\n \"- Use failed tool results only when the failure reveals durable process knowledge, not transient errors.\",\n \"- Use assistant messages only as context; do not store the assistant's claims unless supported by user messages or tool results.\",\n \"- Return one memory per distinct fact.\",\n \"- Prefer storing how to achieve a result: stable source-of-truth, query location, workflow, prerequisite, caveat, or reusable decision path that took effort to discover.\",\n \"- Store direct answers to user inquiries only when they are stable operational/project knowledge, not values that naturally change over time.\",\n \"- Do not store point-in-time analytics, search, issue, metric, incident, availability, or status answers just because a tool produced them.\",\n \"- Do not store the fact that the user asked for advice, search, recall, planning, listing, inspection, or removal. Store only stable knowledge discovered in response, such as a reusable method or source-of-truth.\",\n \"- A user question asking how, what, where, or whether to do something is not source evidence for the answer. Store the answer only when supported by a user-authored factual statement or a tool result.\",\n \"- Set kind=procedure for reusable task/process/runbook instructions.\",\n \"- Set kind=knowledge for shared team, project, channel, runbook, or operational facts.\",\n ...(allowsPreference\n ? [\n \"- Set kind=preference only for clear durable first-person facts authored by the current actor about their own preference, opinion, habit, identity, or workflow.\",\n \"- A single task request or ask-for-help is never a durable preference, even when phrased as an ongoing action for this run (for example 'help me capture takeaways as we go'). Do not convert a one-off ask into a 'Prefers ...' memory.\",\n \"- A durable preference requires explicitly stated, generalizable first-person phrasing such as 'I prefer ...', 'I always ...', or 'I never ...' that describes how the actor wants things done in general, not just for the current task.\",\n ]\n : [\n \"- This completed run has multiple run actors. Return only conversation-scoped procedure or knowledge memories.\",\n \"- Do not return personal preferences, opinions, habits, identity facts, or workflow preferences from any actor in this run.\",\n \"- Do not convert a personal first-person statement into shared knowledge or procedure. Statements like 'I prefer ...', 'I use ...', 'I always ...', or 'I never ...' are not memory evidence in this run.\",\n \"- Shared team, channel, repository, or operational norms are eligible only when the source states them as collective practice or durable operational fact, not as one individual's preference.\",\n ]),\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current actor.\",\n \"- User-authored task instructions are procedures, not preferences, unless they explicitly describe the actor's personal preference or habit.\",\n \"- Procedural statements such as 'for X, do Y', 'when X, do Y', and 'to accomplish X, do Y' belong in procedures.\",\n ...CANONICAL_CONTENT_RULES,\n \"- Skip a candidate when existing-memories already cover the same durable fact.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- If unsure, return no memory for that candidate.\",\n \"</rules>\",\n \"</memory-extraction-input>\",\n ].join(\"\\n\");\n}\n\nfunction supersessionPrompt(request: MemorySupersessionInput): string {\n return [\n \"<memory-supersession-input>\",\n \"Decide whether the candidate preference clearly replaces one or more existing active preferences.\",\n \"\",\n runtimeDescription({\n runtimeContext: request.runtimeContext,\n }),\n \"\",\n \"<candidate>\",\n escapeXml(JSON.stringify(request.candidate)),\n \"</candidate>\",\n \"\",\n \"<existing-memories>\",\n escapeXml(JSON.stringify(request.existingMemories)),\n \"</existing-memories>\",\n \"\",\n \"<rules>\",\n \"- Return supersedes_old only when the candidate and old memory describe the same mutable preference slot and the candidate is the newer value.\",\n \"- Examples of same mutable slot: preferred programming language, preferred review style, preferred notification cadence, preferred tool for a task.\",\n \"- Do not supersede when the candidate is just more specific, an additional preference, a different task/context, or the same value phrased differently.\",\n \"- Do not supersede memories from different topics even if they are both preferences.\",\n \"- Only return ids that appear in existing-memories.\",\n \"- If unsure, return uncertain.\",\n \"</rules>\",\n \"</memory-supersession-input>\",\n ].join(\"\\n\");\n}\n\n/** Create the memory-owned agent that reviews and extracts memory candidates. */\nexport function createMemoryAgent(model: PluginModel): MemoryAgent {\n return {\n async adjudicateSupersession(rawRequest) {\n const request = supersessionRequestSchema.parse(\n rawRequest,\n ) as MemorySupersessionInput;\n const result = await model.completeObject({\n schema: supersessionDecisionResponseSchema,\n system: MEMORY_SUPERSESSION_SYSTEM,\n prompt: supersessionPrompt(request),\n maxTokens: 400,\n });\n return supersessionDecisionResponseSchema.parse(\n result.object,\n ) as MemorySupersessionDecision;\n },\n async extractSessionMemories(rawRequest) {\n const request = extractSessionRequestSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: extractMemoriesResponseSchema,\n system: MEMORY_EXTRACTION_SYSTEM,\n prompt: sessionExtractionPrompt(request),\n maxTokens: 1_000,\n });\n return extractedMemoriesFromResponse(\n extractMemoriesResponseSchema.parse(result.object),\n );\n },\n async reviewCreateRequest(rawRequest) {\n const request = parseCreateMemoryRequest(rawRequest);\n const result = await model.completeObject({\n schema: memoryReviewResponseSchema,\n system: MEMORY_REVIEW_SYSTEM,\n prompt: reviewPrompt(request),\n maxTokens: 700,\n });\n const response = memoryReviewResponseSchema.parse(result.object);\n return memoryReviewFromResponse(response);\n },\n };\n}\n\nfunction memoryReviewFromResponse(\n response: MemoryReviewResponse,\n): MemoryReview {\n if (response.decision === \"store\") {\n return parseMemoryReview({\n decision: \"store\",\n kind: response.kind,\n content: response.canonicalFact,\n ...(response.expiresAtMs !== null\n ? { expiresAtMs: response.expiresAtMs }\n : {}),\n });\n }\n return parseMemoryReview({\n decision: \"reject\",\n reason: response.reason,\n });\n}\n\nfunction extractedMemoriesFromResponse(\n response: ExtractMemoriesResponse,\n): ExtractedMemory[] {\n const toMemory = (\n memory: z.output<typeof extractedMemorySchema>,\n ): ExtractedMemory =>\n parseExtractedMemory({\n content: memory.canonicalFact,\n expiresAtMs: memory.expiresAtMs,\n kind: memory.kind,\n evidenceMessageIndices: memory.evidenceMessageIndices,\n });\n return response.memories.map(toMemory);\n}\n\n/** Parse the canonical extracted-memory shape stored across task retries. */\nexport function parseExtractedMemory(memory: unknown): ExtractedMemory {\n return extractedMemoryResultSchema.parse(memory);\n}\n\n/** Parse the structured decision returned by the memory agent. */\nexport function parseMemoryReview(result: unknown): MemoryReview {\n return memoryReviewDecisionSchema.parse(result);\n}\n\n/** Parse the structured input sent to the memory agent. */\nexport function parseCreateMemoryRequest(\n request: unknown,\n): CreateMemoryRequest {\n return createMemoryRequestSchema.parse(request);\n}\n","import {\n localActorSchema,\n localSourceSchema,\n platformSchema,\n slackActorSchema,\n slackSourceSchema,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\n\nexport const MEMORY_KINDS = [\"preference\", \"procedure\", \"knowledge\"] as const;\n\nexport const MEMORY_SCOPES = [\"personal\", \"conversation\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\nexport const MEMORY_SOURCE_PLATFORMS = [\n \"slack\",\n \"local\",\n] as const satisfies readonly z.output<typeof platformSchema>[];\nexport const MEMORY_EMBEDDING_METRICS = [\"cosine\"] as const;\nexport const MEMORY_EMBEDDING_DIMENSIONS = 1536;\n\nexport type MemoryKind = (typeof MEMORY_KINDS)[number];\nexport type MemoryScope = (typeof MEMORY_SCOPES)[number];\nexport type MemorySubjectType = (typeof MEMORY_SUBJECT_TYPES)[number];\nexport type MemorySourcePlatform = (typeof MEMORY_SOURCE_PLATFORMS)[number];\nexport type MemoryEmbeddingMetric = (typeof MEMORY_EMBEDDING_METRICS)[number];\n\nconst nonEmptyStringSchema = z.string().min(1);\n\n/** Runtime-owned memory invocation fields used for scope and source authority. */\nexport const slackMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n actor: slackActorSchema.optional(),\n source: slackSourceSchema,\n })\n .strict();\n\n/** Runtime-owned local memory invocation fields used for scope and source authority. */\nexport const localMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n actor: localActorSchema.optional(),\n source: localSourceSchema,\n })\n .strict();\n\n/** Runtime-owned memory invocation fields accepted by memory store operations. */\nexport const memoryRuntimeContextSchema = z.union([\n slackMemoryRuntimeContextSchema,\n localMemoryRuntimeContextSchema,\n]);\n\nexport type MemoryRuntimeContext = z.output<typeof memoryRuntimeContextSchema>;\n","import { InvalidArgumentError, Option, type Command } from \"commander\";\nimport { and, desc, eq, gt, ilike, isNull, or, type SQL } from \"drizzle-orm\";\nimport type {\n PluginCliActionContext,\n PluginCliHost,\n} from \"@sentry/junior-plugin-api\";\nimport { juniorMemoryMemories } from \"../db/schema\";\nimport type { MemoryDb } from \"../store\";\nimport { MEMORY_SCOPES, type MemoryScope } from \"../types\";\nimport { formatMemory } from \"./format\";\n\ninterface SearchOptions {\n limit: number;\n scope: MemoryScope;\n scopeKey: string;\n showContent?: boolean;\n}\n\nfunction parseLimit(value: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed)) {\n throw new InvalidArgumentError(\"--limit must be a number\");\n }\n return Math.min(100, Math.max(1, Math.floor(parsed)));\n}\n\nasync function runSearch(\n ctx: PluginCliActionContext,\n queryParts: string[] | undefined,\n options: SearchOptions,\n): Promise<number> {\n const query = (queryParts ?? []).join(\" \").trim();\n const nowMs = Date.now();\n const terms = [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n\n const db = ctx.db as MemoryDb;\n const activeExpirationPredicate = or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, nowMs),\n );\n const predicates: SQL[] = [\n eq(juniorMemoryMemories.scope, options.scope),\n eq(juniorMemoryMemories.scopeKey, options.scopeKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n ];\n if (activeExpirationPredicate) {\n predicates.push(activeExpirationPredicate);\n }\n if (terms.length > 0) {\n const termPredicate = or(\n ...terms.map((term) => ilike(juniorMemoryMemories.content, `%${term}%`)),\n );\n if (termPredicate) {\n predicates.push(termPredicate);\n }\n }\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(...predicates))\n .orderBy(desc(juniorMemoryMemories.createdAtMs))\n .limit(options.limit);\n\n if (rows.length === 0) {\n await ctx.io.writeOutput(\"No memories matched.\\n\");\n return 0;\n }\n\n await ctx.io.writeOutput(\n `${rows\n .map((row) =>\n formatMemory(row, { showContent: Boolean(options.showContent) }),\n )\n .join(\"\\n\\n\")}\\n`,\n );\n return 0;\n}\n\n/** Wire the memory search admin subcommand under the plugin namespace. */\nexport function configureMemorySearchCommand(\n parent: Command,\n junior: PluginCliHost,\n): void {\n parent\n .command(\"search\")\n .description(\"Search visible memories\")\n .argument(\"[query...]\", \"Search query\")\n .addOption(\n new Option(\"--scope <scope>\", \"Memory scope\")\n .choices([...MEMORY_SCOPES])\n .makeOptionMandatory(),\n )\n .requiredOption(\"--scope-key <key>\", \"Scope key\")\n .addOption(\n new Option(\"--limit <n>\", \"Maximum rows\")\n .argParser(parseLimit)\n .default(20),\n )\n .option(\"--show-content\", \"Print raw memory content\")\n .action(\n junior.action(async (ctx, queryParts, options) => {\n return await runSearch(\n ctx,\n queryParts as string[] | undefined,\n options as SearchOptions,\n );\n }),\n );\n}\n","/**\n * Drizzle source of truth for memory plugin SQL migrations.\n *\n * Update this schema first, then regenerate packaged migrations with\n * `pnpm --filter @sentry/junior-memory db:generate`.\n */\nimport { sql } from \"drizzle-orm\";\nimport {\n bigint,\n check,\n index,\n integer,\n pgTable,\n text,\n uniqueIndex,\n vector,\n} from \"drizzle-orm/pg-core\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_EMBEDDING_METRICS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_KINDS,\n} from \"../types\";\n\nexport const juniorMemoryMemories = pgTable(\n \"junior_memory_memories\",\n {\n id: text(\"id\").primaryKey(),\n scope: text(\"scope\", { enum: MEMORY_SCOPES }).notNull(),\n scopeKey: text(\"scope_key\").notNull(),\n kind: text(\"type\", { enum: MEMORY_KINDS }).notNull(),\n subjectType: text(\"subject_type\", { enum: MEMORY_SUBJECT_TYPES }).notNull(),\n subjectKey: text(\"subject_key\"),\n content: text(\"content\").notNull(),\n sourcePlatform: text(\"source_platform\", {\n enum: MEMORY_SOURCE_PLATFORMS,\n }).notNull(),\n sourceKey: text(\"source_key\").notNull(),\n idempotencyKey: text(\"idempotency_key\"),\n observedAtMs: bigint(\"observed_at_ms\", { mode: \"number\" }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n expiresAtMs: bigint(\"expires_at_ms\", { mode: \"number\" }),\n supersededAtMs: bigint(\"superseded_at_ms\", { mode: \"number\" }),\n supersededById: text(\"superseded_by_id\"),\n archivedAtMs: bigint(\"archived_at_ms\", { mode: \"number\" }),\n archiveReason: text(\"archive_reason\"),\n },\n (table) => [\n index(\"junior_memory_memories_visible_idx\")\n .on(table.scope, table.scopeKey, table.createdAtMs.desc(), table.id)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n index(\"junior_memory_memories_expiration_idx\")\n .on(table.expiresAtMs)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`,\n ),\n uniqueIndex(\"junior_memory_memories_idempotency_idx\")\n .on(table.scope, table.scopeKey, table.idempotencyKey)\n .where(\n sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n check(\n \"junior_memory_memories_scope_check\",\n sql`${table.scope} IN ('personal', 'conversation')`,\n ),\n check(\n \"junior_memory_memories_kind_check\",\n sql`${table.kind} IN (\n 'preference',\n 'procedure',\n 'knowledge'\n )`,\n ),\n check(\n \"junior_memory_memories_subject_type_check\",\n sql`${table.subjectType} IN ('user', 'conversation', 'general')`,\n ),\n check(\n \"junior_memory_memories_subject_key_check\",\n sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`,\n ),\n check(\n \"junior_memory_memories_source_platform_check\",\n sql`${table.sourcePlatform} IN ('slack', 'local')`,\n ),\n ],\n);\n\nexport const juniorMemoryEmbeddings = pgTable(\n \"junior_memory_embeddings\",\n {\n memoryId: text(\"memory_id\")\n .primaryKey()\n .references(() => juniorMemoryMemories.id, { onDelete: \"cascade\" }),\n provider: text(\"provider\").notNull(),\n model: text(\"model\").notNull(),\n dimensions: integer(\"dimensions\").notNull(),\n metric: text(\"metric\", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),\n contentHash: text(\"content_hash\").notNull(),\n embedding: vector(\"embedding\", {\n dimensions: MEMORY_EMBEDDING_DIMENSIONS,\n }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n },\n (table) => [\n index(\"junior_memory_embeddings_model_idx\").on(\n table.provider,\n table.model,\n table.dimensions,\n table.metric,\n ),\n check(\n \"junior_memory_embeddings_metric_check\",\n sql`${table.metric} IN ('cosine')`,\n ),\n check(\n \"junior_memory_embeddings_dimensions_check\",\n sql`${table.dimensions} = ${sql.raw(String(MEMORY_EMBEDDING_DIMENSIONS))}`,\n ),\n ],\n);\n","import type { juniorMemoryMemories } from \"../db/schema\";\n\nfunction formatDate(ms: number | null): string {\n return ms === null ? \"-\" : new Date(ms).toISOString();\n}\n\n/** Format a memory row as an operator-safe CLI projection. */\nexport function formatMemory(\n row: typeof juniorMemoryMemories.$inferSelect,\n args: {\n showContent: boolean;\n },\n): string {\n const lines = [\n `id=${row.id}`,\n `scope=${row.scope}`,\n `scope_key=${row.scopeKey}`,\n `subject_type=${row.subjectType}`,\n ...(row.subjectKey ? [`subject_key=${row.subjectKey}`] : []),\n `kind=${row.kind}`,\n `created_at=${formatDate(row.createdAtMs)}`,\n `observed_at=${formatDate(row.observedAtMs)}`,\n `expires_at=${formatDate(row.expiresAtMs)}`,\n `archived_at=${formatDate(row.archivedAtMs)}`,\n ];\n if (args.showContent) {\n lines.push(`content=${row.content}`);\n }\n return lines.join(\"\\n\");\n}\n","import type { Command } from \"commander\";\nimport type {\n PluginCliActionContext,\n PluginCliHost,\n} from \"@sentry/junior-plugin-api\";\nimport { eq } from \"drizzle-orm\";\nimport { juniorMemoryMemories } from \"../db/schema\";\nimport type { MemoryDb } from \"../store\";\nimport { formatMemory } from \"./format\";\n\nasync function runShow(\n ctx: PluginCliActionContext,\n id: string,\n): Promise<number> {\n const db = ctx.db as MemoryDb;\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(eq(juniorMemoryMemories.id, id))\n .limit(1);\n if (!rows[0]) {\n await ctx.io.writeError(`Memory not found: ${id}\\n`);\n return 1;\n }\n\n await ctx.io.writeOutput(`${formatMemory(rows[0], { showContent: true })}\\n`);\n return 0;\n}\n\n/** Wire the explicit raw-content memory inspection subcommand. */\nexport function configureMemoryShowCommand(\n parent: Command,\n junior: PluginCliHost,\n): void {\n parent\n .command(\"show\")\n .description(\"Show one memory\")\n .argument(\"<id>\", \"Memory id\")\n .action(\n junior.action(async (ctx, id) => {\n return await runShow(ctx, id as string);\n }),\n );\n}\n","import type { PluginCliCommandDefinition } from \"@sentry/junior-plugin-api\";\nimport { configureMemorySearchCommand } from \"./search\";\nimport { configureMemoryShowCommand } from \"./show\";\n\n/** Create the plugin-owned memory admin CLI command. */\nexport function createMemoryCliCommand(): PluginCliCommandDefinition {\n return {\n name: \"memory\",\n summary: \"Inspect Junior memory state\",\n configure(command, junior) {\n configureMemorySearchCommand(command, junior);\n configureMemoryShowCommand(command, junior);\n },\n };\n}\n","import { Type, type Static } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport {\n definePluginTool,\n getSourceKey,\n PluginToolInputError,\n type PluginToolResult,\n type Source,\n type Actor,\n pluginToolResultSchema,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryEmbeddingProvider,\n type MemoryDb,\n type MemoryRecord,\n type MemorySupersessionDecider,\n} from \"./store\";\nimport {\n parseCreateMemoryRequest,\n parseMemoryReview,\n type MemoryAgent,\n} from \"./agent\";\nimport {\n memoryRuntimeContextSchema,\n type MemoryKind,\n type MemoryRuntimeContext,\n} from \"./types\";\n\nexport type MemoryReviewer = Pick<MemoryAgent, \"reviewCreateRequest\">;\n\nconst MAX_TOOL_CONTENT_CHARS = 4_000;\nconst DEFAULT_RESULT_LIMIT = 20;\nconst DEFAULT_SEARCH_LIMIT = 10;\n\nconst KNOWN_TOOL_INPUT_ERROR_MESSAGES = new Set([\n \"Conversation memory requires conversation context.\",\n \"Conversation-subject memory requires conversation context.\",\n \"Memory content is required.\",\n \"Memory content exceeds the maximum length.\",\n \"Memory id is required.\",\n \"Memory was not found in the current context.\",\n \"Memory id prefix is ambiguous.\",\n \"Personal memory requires actor context.\",\n \"User-subject memory requires actor context.\",\n]);\n\n/** Runtime-owned context used to bind memory tools to visible scopes. */\nexport interface MemoryToolContext {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n actor?: Actor;\n source: Source;\n userText?: string;\n}\n\nexport interface MemoryCreateToolContext extends MemoryToolContext {\n supersessionDecider?: MemorySupersessionDecider;\n}\n\nfunction throwToolInputError(message: string): never {\n throw new PluginToolInputError(message);\n}\n\nfunction asToolInputError(error: unknown): never {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n if (\n error instanceof Error &&\n KNOWN_TOOL_INPUT_ERROR_MESSAGES.has(error.message)\n ) {\n throw new PluginToolInputError(error.message, { cause: error });\n }\n throw error;\n}\n\nfunction memoryRuntimeContext(\n context: MemoryToolContext,\n): MemoryRuntimeContext {\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.actor ? { actor: context.actor } : {}),\n source: context.source,\n });\n}\n\nfunction memoryStore(\n context: MemoryToolContext,\n options: { supersessionDecider?: MemorySupersessionDecider } = {},\n) {\n return createMemoryStore(context.db, memoryRuntimeContext(context), {\n embedder: context.embedder,\n ...(options.supersessionDecider\n ? { supersessionDecider: options.supersessionDecider }\n : {}),\n });\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(50, Math.max(1, Math.floor(value)));\n}\n\nfunction digitAt(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code >= 48 && code <= 57;\n}\n\nfunction readDigits(\n value: string,\n start: number,\n length: number,\n): number | undefined {\n for (let index = start; index < start + length; index++) {\n if (!digitAt(value, index)) {\n return undefined;\n }\n }\n return Number(value.slice(start, start + length));\n}\n\nfunction parseIsoTimestampParts(value: string) {\n if (\n value.length < 20 ||\n value[4] !== \"-\" ||\n value[7] !== \"-\" ||\n value[10] !== \"T\" ||\n value[13] !== \":\" ||\n value[16] !== \":\"\n ) {\n return undefined;\n }\n const year = readDigits(value, 0, 4);\n const month = readDigits(value, 5, 2);\n const day = readDigits(value, 8, 2);\n const hour = readDigits(value, 11, 2);\n const minute = readDigits(value, 14, 2);\n const second = readDigits(value, 17, 2);\n if (\n year === undefined ||\n month === undefined ||\n day === undefined ||\n hour === undefined ||\n minute === undefined ||\n second === undefined\n ) {\n return undefined;\n }\n\n let zoneStart = 19;\n if (value[zoneStart] === \".\") {\n zoneStart += 1;\n const fractionStart = zoneStart;\n while (zoneStart < value.length && digitAt(value, zoneStart)) {\n zoneStart += 1;\n }\n if (zoneStart === fractionStart) {\n return undefined;\n }\n }\n\n if (value[zoneStart] === \"Z\") {\n if (zoneStart !== value.length - 1) {\n return undefined;\n }\n } else if (value[zoneStart] === \"+\" || value[zoneStart] === \"-\") {\n if (\n zoneStart !== value.length - 6 ||\n value[zoneStart + 3] !== \":\" ||\n readDigits(value, zoneStart + 1, 2) === undefined ||\n readDigits(value, zoneStart + 4, 2) === undefined\n ) {\n return undefined;\n }\n } else {\n return undefined;\n }\n\n return { day, hour, minute, month, second, year };\n}\n\nfunction parseExpiresAt(value: string | undefined): number | undefined {\n if (!value) {\n return undefined;\n }\n if (value === \"never\") {\n return undefined;\n }\n const parts = parseIsoTimestampParts(value);\n const expiresAtMs = Date.parse(value);\n if (!parts || !Number.isFinite(expiresAtMs)) {\n throwToolInputError('expires_at must be \"never\" or a valid ISO timestamp.');\n }\n const calendarDate = new Date(\n Date.UTC(parts.year, parts.month - 1, parts.day),\n );\n if (\n calendarDate.getUTCFullYear() !== parts.year ||\n calendarDate.getUTCMonth() !== parts.month - 1 ||\n calendarDate.getUTCDate() !== parts.day ||\n parts.hour > 23 ||\n parts.minute > 59 ||\n parts.second > 59\n ) {\n throwToolInputError('expires_at must be \"never\" or a valid ISO timestamp.');\n }\n return expiresAtMs;\n}\n\nfunction requireToolCallId(value: string | undefined): string {\n if (!value) {\n throwToolInputError(\"Memory creation requires a tool call id.\");\n }\n return value;\n}\n\nfunction requireMemoryContent(value: string): string {\n if (value.trim().length === 0) {\n throwToolInputError(\"Memory content is required.\");\n }\n return value;\n}\n\nconst createMemoryInputSchema = z\n .object({\n content: z\n .string()\n .min(1)\n .max(MAX_TOOL_CONTENT_CHARS)\n .describe(\n \"Self-contained public/shareable memory candidate. Include the subject in natural language when it matters; do not rely on surrounding chat context.\",\n ),\n expires_at: z\n .string()\n .min(1)\n .describe(\n 'Expiration selector. Omit or use \"never\" when the memory should not expire, or use an exact ISO timestamp such as \"2027-06-21T00:00:00Z\".',\n )\n .optional(),\n })\n .strict();\n\nconst removeMemoryInputSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .describe(\"Memory id or unambiguous short id prefix to remove.\"),\n })\n .strict();\n\nconst listMemoriesInputSchema = z\n .object({\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of visible memories to return.\")\n .optional(),\n })\n .strict();\n\nconst searchMemoriesInputSchema = z\n .object({\n query: z\n .string()\n .min(1)\n .describe(\"Search query for visible memory content.\"),\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of matching memories to return.\")\n .optional(),\n })\n .strict();\n\nconst memoryToolProjectionSchema = Type.Object(\n {\n id: Type.String({ minLength: 1 }),\n content: Type.String({ minLength: 1 }),\n createdAtMs: Type.Number(),\n observedAtMs: Type.Number(),\n expiresAtMs: Type.Optional(Type.Number()),\n },\n { additionalProperties: false },\n);\ntype MemoryToolProjection = Static<typeof memoryToolProjectionSchema>;\n\ntype MemoryStructuredToolResult<TData extends Record<string, unknown>> =\n PluginToolResult &\n TData & {\n ok: true;\n status: \"success\";\n target: string;\n data: TData;\n };\n\nconst memoryProjectionOutputSchema = z.object({\n id: z.string(),\n content: z.string(),\n createdAtMs: z.number(),\n observedAtMs: z.number(),\n expiresAtMs: z.number().optional(),\n});\n\nconst memoryCreateDataOutputSchema = z.object({\n created: z.boolean(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memorySingleDataOutputSchema = z.object({\n memory: memoryProjectionOutputSchema,\n});\n\nconst memoryManyDataOutputSchema = z.object({\n memories: z.array(memoryProjectionOutputSchema),\n});\n\nconst memoryCreateOutputSchema = pluginToolResultSchema.extend({\n ok: z.literal(true),\n status: z.literal(\"success\"),\n target: z.string(),\n data: memoryCreateDataOutputSchema,\n created: z.boolean(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memorySingleOutputSchema = pluginToolResultSchema.extend({\n ok: z.literal(true),\n status: z.literal(\"success\"),\n target: z.string(),\n data: memorySingleDataOutputSchema,\n memory: memoryProjectionOutputSchema,\n});\n\nconst memoryManyOutputSchema = pluginToolResultSchema.extend({\n ok: z.literal(true),\n status: z.literal(\"success\"),\n target: z.string(),\n data: memoryManyDataOutputSchema,\n memories: z.array(memoryProjectionOutputSchema),\n});\n\nfunction parseMemoryToolInput<T>(schema: z.ZodType<T>, input: unknown): T {\n const result = schema.safeParse(input);\n if (!result.success) {\n throw new PluginToolInputError(\"Invalid memory tool input.\", {\n cause: result.error,\n });\n }\n return result.data;\n}\n\nfunction sourceIdempotencyKey(context: MemoryToolContext): string {\n const sourceKey = getSourceKey(context.source);\n if (!sourceKey) {\n throwToolInputError(\"Memory creation requires source message context.\");\n }\n return sourceKey;\n}\n\nfunction createInput(\n context: MemoryToolContext,\n input: { content: string; expiresAtMs?: number; kind: MemoryKind },\n toolCallId: string,\n) {\n return {\n content: requireMemoryContent(input.content),\n idempotencyKey: `tool:${sourceIdempotencyKey(context)}:${toolCallId}`,\n kind: input.kind,\n ...(input.expiresAtMs !== undefined\n ? { expiresAtMs: input.expiresAtMs }\n : {}),\n } satisfies CreateMemoryInput;\n}\n\nfunction targetForKind(kind: MemoryKind): \"actor\" | \"conversation\" {\n if (kind === \"preference\") {\n return \"actor\";\n }\n return \"conversation\";\n}\n\n/** Return the model-visible projection without hidden ownership/source fields. */\nfunction compactMemory(memory: MemoryRecord): MemoryToolProjection {\n return Value.Parse(memoryToolProjectionSchema, {\n id: memory.id,\n content: memory.content,\n createdAtMs: memory.createdAtMs,\n observedAtMs: memory.observedAtMs,\n ...(memory.expiresAtMs !== undefined\n ? { expiresAtMs: memory.expiresAtMs }\n : {}),\n });\n}\n\nfunction memoryToolResult<TData extends Record<string, unknown>>(\n target: string,\n data: TData,\n): MemoryStructuredToolResult<TData> {\n return {\n ok: true,\n status: \"success\",\n target,\n data,\n ...data,\n };\n}\n\n/** Create a tool that submits an explicit memory candidate for storage. */\nexport function createMemoryCreateTool(context: MemoryCreateToolContext) {\n return definePluginTool({\n description:\n \"Explicit memory-write tool. Use only when the latest user message directly asks Junior to remember, store, save, or forget-and-replace a public/shareable fact. Do not use for ordinary statements like 'I prefer X', 'I use Y', or 'X goes before Y' unless the user also asks you to remember/store/save it; passive memory learning handles those after the visible reply. Pass one self-contained natural-language candidate preserving the user's explicit memory intent. Do not ask the user to rephrase ordinary first-person facts, and do not rewrite them into display-name or third-person wording. Do not include secrets, private personal details, medical/legal/financial/sensitive facts, or another person's personal preference, opinion, habit, identity, relationship, workflow, or private life. Runtime context derives actor, scope, source, and subject ids; the memory agent decides canonical stored content and memory kind, then the plugin derives storage target from kind.\",\n executionMode: \"sequential\",\n inputSchema: createMemoryInputSchema,\n outputSchema: memoryCreateOutputSchema,\n execute: async (input, options) => {\n const parsedInput = parseMemoryToolInput(createMemoryInputSchema, input);\n const toolCallId = requireToolCallId(options.toolCallId);\n const requestedExpiresAtMs = parseExpiresAt(parsedInput.expires_at);\n const runtimeContext = memoryRuntimeContext(context);\n const store = memoryStore(context, {\n supersessionDecider: context.supersessionDecider,\n });\n const review = await (async () => {\n try {\n return parseMemoryReview(\n await context.agent.reviewCreateRequest(\n parseCreateMemoryRequest({\n content: requireMemoryContent(parsedInput.content),\n ...(requestedExpiresAtMs !== undefined\n ? { expiresAtMs: requestedExpiresAtMs }\n : {}),\n runtimeContext,\n ...(context.userText?.trim()\n ? {\n sourceContext: {\n currentUserText: context.userText.trim(),\n },\n }\n : {}),\n }),\n ),\n );\n } catch (error) {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n const detail =\n error instanceof Error && error.message.trim()\n ? `: ${error.message}`\n : \"\";\n throw new PluginToolInputError(\n `Memory agent review failed${detail}`,\n { cause: error },\n );\n }\n })();\n if (review.decision === \"reject\") {\n throw new PluginToolInputError(\n `Memory was not stored: ${review.reason}`,\n );\n }\n const memoryInput = createInput(\n context,\n {\n content: review.content,\n kind: review.kind,\n ...(review.expiresAtMs !== undefined\n ? { expiresAtMs: review.expiresAtMs }\n : requestedExpiresAtMs !== undefined\n ? { expiresAtMs: requestedExpiresAtMs }\n : {}),\n },\n toolCallId,\n );\n const result = await (async () => {\n try {\n if (targetForKind(review.kind) === \"conversation\") {\n return await store.createConversationMemory(memoryInput);\n }\n return await store.createMemory(memoryInput);\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"createMemory\", {\n created: result.created,\n memory: compactMemory(result.memory),\n });\n },\n });\n}\n\n/** Create a tool that archives a visible memory in the active context. */\nexport function createMemoryRemoveTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"Forget one memory visible in the active context. Use only ids or short id prefixes returned by listMemories or searchMemories. Never remove memories by hidden actor, Slack, scope, or subject identifiers.\",\n executionMode: \"sequential\",\n inputSchema: removeMemoryInputSchema,\n outputSchema: memorySingleOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(removeMemoryInputSchema, input);\n const memory = await (async () => {\n try {\n return await memoryStore(context).archiveMemory({\n id: parsedInput.id,\n reason: \"tool_removed\",\n });\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"removeMemory\", {\n memory: compactMemory(memory),\n });\n },\n });\n}\n\n/** Create a tool that lists visible active memories in the active context. */\nexport function createMemoryListTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"List active memories visible in the current context. Use when the user asks what Junior remembers or when memory ids are needed before removing a memory.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: listMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(listMemoriesInputSchema, input);\n const memories = await memoryStore(context).listMemories({\n limit: boundedLimit(parsedInput.limit, DEFAULT_RESULT_LIMIT),\n });\n return memoryToolResult(\"listMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n\n/** Create a tool that searches visible active memories in the active context. */\nexport function createMemorySearchTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"Search active memories visible in the current context. Use when the model needs targeted memory recall. The tool searches only the current actor and active conversation scopes.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: searchMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(\n searchMemoriesInputSchema,\n input,\n );\n const memories = await memoryStore(context).searchMemories({\n query: parsedInput.query,\n limit: boundedLimit(parsedInput.limit, DEFAULT_SEARCH_LIMIT),\n });\n return memoryToolResult(\"searchMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n","/**\n * SQL-backed memory store boundary.\n *\n * This module owns row parsing plus visible create/list/search/archive\n * operations. Visibility, expiration, and supersession are enforced before\n * records leave the store.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n and,\n asc,\n desc,\n eq,\n gt,\n ilike,\n inArray,\n isNull,\n isNotNull,\n like,\n lte,\n or,\n sql,\n type SQL,\n} from \"drizzle-orm\";\nimport { cosineDistance } from \"drizzle-orm/sql/functions\";\nimport type { PgDatabase } from \"drizzle-orm/pg-core\";\nimport type { PgQueryResultHKT } from \"drizzle-orm/pg-core/session\";\nimport { z } from \"zod\";\nimport * as memorySqlSchema from \"./db/schema\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_KINDS,\n memoryRuntimeContextSchema,\n type MemoryRuntimeContext,\n type MemoryScope,\n} from \"./types\";\nimport {\n deriveMemoryScope,\n deriveMemorySubject,\n type ResolvedMemorySubject,\n deriveVisibleMemoryScopes,\n type ResolvedMemoryScope,\n} from \"./scope\";\n\nconst DEFAULT_LIST_LIMIT = 50;\nconst DEFAULT_SEARCH_LIMIT = 10;\nconst DEFAULT_EXPIRED_ARCHIVE_LIMIT = 100;\nconst HIGH_CONFIDENCE_DUPLICATE_DISTANCE = 0.015;\nconst SUPERSESSION_CANDIDATE_LIMIT = 10;\nconst VECTOR_SEARCH_OVERFETCH = 4;\nconst MAX_MEMORY_CONTENT_CHARS = 4_000;\nconst EMBEDDING_METRIC = \"cosine\";\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst RELEVANCE_NEAR_TIE_DELTA = 0.01;\nconst SOURCE_CHANNEL_BOOST = 0.05;\nconst SUPERSESSION_STOP_TERMS = new Set([\n \"and\",\n \"for\",\n \"prefer\",\n \"prefers\",\n \"preference\",\n \"the\",\n \"use\",\n \"uses\",\n \"with\",\n]);\n\nexport type MemoryDb = PgDatabase<PgQueryResultHKT, typeof memorySqlSchema>;\n\ninterface SearchCandidate {\n memory: MemoryRecord;\n score: number;\n sourceKey: string;\n}\n\ninterface MemoryEmbedding {\n model: string;\n provider: string;\n vector: number[];\n}\n\nconst nonEmptyStringSchema = z.string().min(1);\nconst memoryContentSchema = z\n .string()\n .refine((content) => content.trim().length > 0, {\n message: \"Memory content is required.\",\n });\nconst numberSchema = z.number().finite();\nconst createMemoryInputSchema = z\n .object({\n content: memoryContentSchema,\n expiresAtMs: numberSchema.optional(),\n idempotencyKey: nonEmptyStringSchema,\n kind: z.enum(MEMORY_KINDS),\n })\n .strict();\nconst listMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n })\n .strict();\nconst searchMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n query: nonEmptyStringSchema,\n })\n .strict();\nconst archiveMemoryInputSchema = z\n .object({\n id: nonEmptyStringSchema,\n reason: nonEmptyStringSchema.optional(),\n })\n .strict();\nconst archiveExpiredMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n })\n .strict();\nconst clockSchema = z.function({ input: [], output: numberSchema }).optional();\nconst memoryStoreOptionsSchema = z\n .object({\n now: clockSchema,\n })\n .strict();\nconst optionalNumberSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.coerce.number().optional(),\n);\nconst optionalStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().optional(),\n);\nconst optionalNonEmptyStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().min(1).optional(),\n);\nconst memoryRowSchema = z\n .object({\n archivedAtMs: optionalNumberSchema,\n archiveReason: optionalStringSchema,\n content: memoryContentSchema,\n createdAtMs: z.coerce.number(),\n expiresAtMs: optionalNumberSchema,\n id: z.string().min(1),\n idempotencyKey: optionalStringSchema,\n observedAtMs: z.coerce.number(),\n scope: z.enum(MEMORY_SCOPES),\n scopeKey: z.string().min(1),\n sourceKey: z.string().min(1),\n sourcePlatform: z.enum(MEMORY_SOURCE_PLATFORMS),\n subjectKey: optionalNonEmptyStringSchema,\n subjectType: z.enum(MEMORY_SUBJECT_TYPES),\n supersededAtMs: optionalNumberSchema,\n supersededById: optionalStringSchema,\n kind: z.enum(MEMORY_KINDS),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.subjectType === \"general\") {\n if (row.subjectKey !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n message: \"General-subject memory rows must not have a subject key.\",\n path: [\"subjectKey\"],\n });\n }\n return;\n }\n if (row.subjectKey === undefined) {\n ctx.addIssue({\n code: \"custom\",\n message: \"User and conversation memory rows require a subject key.\",\n path: [\"subjectKey\"],\n });\n }\n });\n\nconst memoryRecordSchema = z\n .object({\n archivedAtMs: numberSchema.optional(),\n archiveReason: nonEmptyStringSchema.optional(),\n content: memoryContentSchema,\n createdAtMs: numberSchema,\n expiresAtMs: numberSchema.optional(),\n id: nonEmptyStringSchema,\n observedAtMs: numberSchema,\n scope: z.enum(MEMORY_SCOPES),\n subjectType: z.enum(MEMORY_SUBJECT_TYPES),\n supersededAtMs: numberSchema.optional(),\n supersededById: nonEmptyStringSchema.optional(),\n kind: z.enum(MEMORY_KINDS),\n })\n .strict();\nconst embeddingVectorSchema = z\n .array(numberSchema)\n .length(MEMORY_EMBEDDING_DIMENSIONS);\nconst embeddingResultSchema = z\n .object({\n dimensions: z.literal(MEMORY_EMBEDDING_DIMENSIONS),\n model: nonEmptyStringSchema,\n provider: nonEmptyStringSchema,\n vectors: z.array(embeddingVectorSchema),\n })\n .strict();\n\nexport type MemoryRecord = z.output<typeof memoryRecordSchema>;\nexport type CreateMemoryInput = z.output<typeof createMemoryInputSchema>;\n\n/** Result of a memory write after idempotency checks. */\nexport interface CreateMemoryResult {\n created: boolean;\n memory: MemoryRecord;\n}\n\nexport type ListMemoriesInput = z.output<typeof listMemoriesInputSchema>;\n\nexport type SearchMemoriesInput = z.output<typeof searchMemoriesInputSchema>;\n\nexport type ArchiveMemoryInput = z.output<typeof archiveMemoryInputSchema>;\n\nexport type ArchiveExpiredMemoriesInput = z.output<\n typeof archiveExpiredMemoriesInputSchema\n>;\n\nexport interface ArchiveExpiredMemoriesResult {\n archivedCount: number;\n}\n\nexport interface MemoryEmbeddingProvider {\n /** Embed normalized memory text for derived vector retrieval. */\n embedTexts(input: { texts: string[] }): Promise<{\n dimensions: number;\n model: string;\n provider: string;\n vectors: number[][];\n }>;\n}\n\nexport interface MemorySupersessionInput {\n candidate: {\n content: string;\n kind: \"preference\";\n };\n existingMemories: [\n {\n content: string;\n id: string;\n },\n ...Array<{\n content: string;\n id: string;\n }>,\n ];\n runtimeContext: MemoryRuntimeContext;\n}\n\nexport type MemorySupersessionDecision =\n | {\n decision: \"supersedes_old\";\n supersededIds: [string, ...string[]];\n }\n | {\n decision: \"distinct\" | \"uncertain\";\n };\n\nexport interface MemorySupersessionDecider {\n /** Decide whether a new preference clearly replaces active old preferences. */\n adjudicateSupersession(\n input: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n}\n\nexport interface MemoryStoreOptions {\n embedder?: MemoryEmbeddingProvider;\n /** Maximum cosine distance for vector recall candidates. Model-dependent; tune when changing AI_EMBEDDING_MODEL. */\n maxVectorDistance?: number;\n now?: () => number;\n supersessionDecider?: MemorySupersessionDecider;\n}\n\n/** Context-bound storage operations for visible long-term memories. */\nexport interface MemoryStore {\n /** Archive expired memories visible in the current runtime context. */\n archiveExpiredMemories(\n input?: ArchiveExpiredMemoriesInput,\n ): Promise<ArchiveExpiredMemoriesResult>;\n /** Archive a visible memory in the current runtime context. */\n archiveMemory(input: ArchiveMemoryInput): Promise<MemoryRecord>;\n /** Store a personal memory for the current actor. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a conversation memory for the current source conversation. */\n createConversationMemory(\n input: CreateMemoryInput,\n ): Promise<CreateMemoryResult>;\n /** List active memories visible in the current runtime context. */\n listMemories(input: ListMemoriesInput): Promise<MemoryRecord[]>;\n /** Search active memories visible in the current runtime context. */\n searchMemories(input: SearchMemoriesInput): Promise<MemoryRecord[]>;\n}\n\nfunction normalizeContent(content: string): string {\n return content.replace(/\\s+/g, \" \").trim();\n}\n\nfunction hashEmbeddedContent(content: string): string {\n return createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nfunction idempotencyAliasId(args: {\n idempotencyKey: string;\n scope: ResolvedMemoryScope;\n targetId: string;\n}): string {\n return `alias:${createHash(\"sha256\")\n .update(args.scope.scope)\n .update(\"\\0\")\n .update(args.scope.scopeKey)\n .update(\"\\0\")\n .update(args.idempotencyKey)\n .update(\"\\0\")\n .update(args.targetId)\n .digest(\"hex\")}`;\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(200, Math.max(1, Math.floor(value)));\n}\n\n/** Build the durable source attribution key from runtime-owned source fields. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n throw new Error(\n \"Memory source requires a Slack message or thread timestamp.\",\n );\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\nfunction sourceChannelPrefix(ctx: MemoryRuntimeContext): string | undefined {\n if (ctx.source.platform !== \"slack\") {\n return undefined;\n }\n // TODO(v0.82.0): Replace Slack source-key prefix matching with typed source proximity metadata.\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:`;\n}\n\n/** Parse one SQL row into the public memory record projection. */\nfunction parseMemoryRow(row: unknown): MemoryRecord {\n const parsed = memoryRowSchema.parse(row);\n return memoryRecordSchema.parse({\n id: parsed.id,\n scope: parsed.scope,\n kind: parsed.kind,\n subjectType: parsed.subjectType,\n content: parsed.content,\n observedAtMs: parsed.observedAtMs,\n createdAtMs: parsed.createdAtMs,\n ...(parsed.expiresAtMs !== undefined\n ? { expiresAtMs: parsed.expiresAtMs }\n : {}),\n ...(parsed.supersededAtMs !== undefined\n ? { supersededAtMs: parsed.supersededAtMs }\n : {}),\n ...(parsed.supersededById ? { supersededById: parsed.supersededById } : {}),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : {}),\n ...(parsed.archiveReason ? { archiveReason: parsed.archiveReason } : {}),\n });\n}\n\n/** Build the scoped SQL predicate and ordered params for visible memory reads. */\nfunction visibleScopePredicate(scopes: ResolvedMemoryScope[]): SQL | undefined {\n if (scopes.length === 0) {\n return undefined;\n }\n return or(\n ...scopes.map((scope) =>\n and(\n eq(juniorMemoryMemories.scope, scope.scope),\n eq(juniorMemoryMemories.scopeKey, scope.scopeKey),\n ),\n ),\n );\n}\n\nfunction activeVisiblePredicate(args: {\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): SQL | undefined {\n const scopePredicate = visibleScopePredicate(args.scopes);\n if (!scopePredicate) {\n return undefined;\n }\n return and(\n scopePredicate,\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n}\n\n/** Resolve retry attempts for the same scoped write idempotency key. */\nasync function findByIdempotencyKey(args: {\n db: MemoryDb;\n idempotencyKey: string;\n nowMs: number;\n scope: ResolvedMemoryScope;\n}): Promise<MemoryRecord | undefined> {\n const activeRows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n eq(juniorMemoryMemories.idempotencyKey, args.idempotencyKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n ),\n )\n .limit(1);\n if (activeRows[0]) {\n return parseMemoryRow(activeRows[0]);\n }\n\n const aliasRows = await args.db\n .select({ supersededById: juniorMemoryMemories.supersededById })\n .from(juniorMemoryMemories)\n .where(\n and(\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n eq(juniorMemoryMemories.idempotencyKey, args.idempotencyKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNotNull(juniorMemoryMemories.supersededAtMs),\n isNotNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n ),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n );\n for (const alias of aliasRows) {\n if (!alias.supersededById) {\n continue;\n }\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n eq(juniorMemoryMemories.id, alias.supersededById),\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n ),\n )\n .limit(1);\n if (rows[0]) {\n return parseMemoryRow(rows[0]);\n }\n }\n return undefined;\n}\n\n/**\n * Archive a bounded batch of expired active rows and remove their derived vectors.\n */\nasync function archiveExpiredMemoryBatch(args: {\n db: MemoryDb;\n idempotencyKey?: string;\n limit?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<ArchiveExpiredMemoriesResult> {\n const scopePredicate = visibleScopePredicate(args.scopes);\n if (!scopePredicate) {\n return { archivedCount: 0 };\n }\n const predicates: SQL[] = [\n scopePredicate,\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n lte(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ];\n if (args.idempotencyKey !== undefined) {\n predicates.push(\n eq(juniorMemoryMemories.idempotencyKey, args.idempotencyKey),\n );\n }\n\n const archivedIds = await args.db.transaction(async (tx) => {\n const expired = await tx\n .select({ id: juniorMemoryMemories.id })\n .from(juniorMemoryMemories)\n .where(and(...predicates))\n .orderBy(\n asc(juniorMemoryMemories.expiresAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(boundedLimit(args.limit, DEFAULT_EXPIRED_ARCHIVE_LIMIT));\n const ids = expired.map((row) => row.id);\n if (ids.length === 0) {\n return [];\n }\n\n const archived = await tx\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: args.nowMs,\n archiveReason: \"expired\",\n })\n .where(and(inArray(juniorMemoryMemories.id, ids), ...predicates))\n .returning({ id: juniorMemoryMemories.id });\n const idsToClean = archived.map((row) => row.id);\n if (idsToClean.length > 0) {\n await tx\n .delete(juniorMemoryEmbeddings)\n .where(inArray(juniorMemoryEmbeddings.memoryId, idsToClean));\n }\n return idsToClean;\n });\n return { archivedCount: archivedIds.length };\n}\n\nfunction searchScore(memory: MemoryRecord, terms: string[]): number {\n const haystack = memory.content.toLowerCase();\n // Lexical score is a retrieval fallback signal, not a memory policy decision.\n return terms.reduce(\n (score, term) => score + (haystack.includes(term) ? 1 : 0),\n 0,\n );\n}\n\nfunction searchTerms(query: string): string[] {\n return [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n}\n\nasync function embedOne(\n embedder: MemoryEmbeddingProvider,\n text: string,\n): Promise<MemoryEmbedding> {\n const normalized = normalizeContent(text);\n if (!normalized) {\n throw new Error(\"Embedding text is required.\");\n }\n const result = embeddingResultSchema.parse(\n await embedder.embedTexts({ texts: [normalized] }),\n );\n if (result.vectors.length !== 1) {\n throw new Error(\"Embedding provider returned an unexpected vector count.\");\n }\n return {\n model: result.model,\n provider: result.provider,\n vector: result.vectors[0],\n };\n}\n\n/** Store the derived vector index; failures must not block memory persistence. */\nasync function storeEmbedding(args: {\n content: string;\n db: MemoryDb;\n embedder: MemoryEmbeddingProvider | undefined;\n embedding?: MemoryEmbedding;\n memoryId: string;\n nowMs: number;\n}): Promise<void> {\n if (!args.embedder && !args.embedding) {\n return;\n }\n try {\n const existing = await args.db\n .select({ memoryId: juniorMemoryEmbeddings.memoryId })\n .from(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, args.memoryId))\n .limit(1);\n if (existing[0]) {\n return;\n }\n } catch {\n return;\n }\n let embedding: Awaited<ReturnType<typeof embedOne>>;\n if (args.embedding) {\n embedding = args.embedding;\n } else {\n const embedder = args.embedder;\n if (!embedder) {\n return;\n }\n try {\n embedding = await embedOne(embedder, args.content);\n } catch {\n return;\n }\n }\n try {\n await args.db\n .insert(juniorMemoryEmbeddings)\n .values({\n contentHash: hashEmbeddedContent(args.content),\n createdAtMs: args.nowMs,\n dimensions: MEMORY_EMBEDDING_DIMENSIONS,\n embedding: embedding.vector,\n memoryId: args.memoryId,\n metric: EMBEDDING_METRIC,\n model: embedding.model,\n provider: embedding.provider,\n })\n .onConflictDoNothing();\n } catch {\n return;\n }\n}\n\nfunction activeScopedSubjectPredicate(args: {\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): SQL {\n const predicate = and(\n eq(juniorMemoryMemories.scope, args.scope.scope),\n eq(juniorMemoryMemories.scopeKey, args.scope.scopeKey),\n eq(juniorMemoryMemories.kind, args.kind),\n eq(juniorMemoryMemories.subjectType, args.subject.subjectType),\n args.subject.subjectKey === undefined\n ? isNull(juniorMemoryMemories.subjectKey)\n : eq(juniorMemoryMemories.subjectKey, args.subject.subjectKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n if (!predicate) {\n throw new Error(\"Memory duplicate predicate is empty.\");\n }\n return predicate;\n}\n\nasync function findExactDuplicateMemory(args: {\n content: string;\n db: MemoryDb;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord | undefined> {\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryMemories.content, args.content),\n ),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(1);\n return rows[0] ? parseMemoryRow(rows[0]) : undefined;\n}\n\nasync function findVectorDuplicateMemory(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord | undefined> {\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n args.embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryEmbeddings.provider, args.embedding.provider),\n eq(juniorMemoryEmbeddings.model, args.embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n lte(distance, HIGH_CONFIDENCE_DUPLICATE_DISTANCE),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(1);\n const row = rows[0];\n if (!row || hashEmbeddedContent(row.memory.content) !== row.contentHash) {\n return undefined;\n }\n return parseMemoryRow(row.memory);\n}\n\nasync function rememberDuplicateIdempotency(args: {\n content: string;\n db: MemoryDb;\n duplicate: MemoryRecord;\n idempotencyKey?: string;\n nowMs: number;\n runtimeContext: MemoryRuntimeContext;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<void> {\n if (args.idempotencyKey === undefined) {\n return;\n }\n await args.db\n .insert(juniorMemoryMemories)\n .values({\n content: args.content,\n createdAtMs: args.nowMs,\n expiresAtMs: args.duplicate.expiresAtMs,\n id: idempotencyAliasId({\n idempotencyKey: args.idempotencyKey,\n scope: args.scope,\n targetId: args.duplicate.id,\n }),\n idempotencyKey: args.idempotencyKey,\n observedAtMs: args.nowMs,\n scope: args.scope.scope,\n scopeKey: args.scope.scopeKey,\n sourceKey: sourceKey(args.runtimeContext),\n sourcePlatform: args.runtimeContext.source.platform,\n subjectKey: args.subject.subjectKey,\n subjectType: args.subject.subjectType,\n supersededAtMs: args.nowMs,\n supersededById: args.duplicate.id,\n kind: args.duplicate.kind,\n })\n .onConflictDoNothing();\n}\n\nasync function listSupersessionCandidates(args: {\n content: string;\n db: MemoryDb;\n embedding?: MemoryEmbedding;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord[]> {\n const predicate = activeScopedSubjectPredicate(args);\n const terms = searchTerms(args.content).filter(\n (term) => !SUPERSESSION_STOP_TERMS.has(term),\n );\n const lexicalRows =\n terms.length > 0\n ? await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n ),\n ),\n )\n : [];\n const lexicalCandidates = lexicalRows\n .map(parseMemoryRow)\n .map((memory) => ({\n memory,\n score: searchScore(memory, terms),\n }))\n .filter((candidate) => candidate.score > 1)\n .sort(\n (left, right) =>\n right.score - left.score ||\n right.memory.createdAtMs - left.memory.createdAtMs ||\n left.memory.id.localeCompare(right.memory.id),\n )\n .map((candidate) => candidate.memory);\n\n const vectorCandidates = args.embedding\n ? await listVectorSupersessionCandidates({\n db: args.db,\n embedding: args.embedding,\n kind: args.kind,\n nowMs: args.nowMs,\n scope: args.scope,\n subject: args.subject,\n })\n : [];\n const byId = new Map<string, MemoryRecord>();\n for (const memory of [...lexicalCandidates, ...vectorCandidates]) {\n if (byId.size >= SUPERSESSION_CANDIDATE_LIMIT) {\n break;\n }\n byId.set(memory.id, memory);\n }\n return [...byId.values()];\n}\n\nasync function listVectorSupersessionCandidates(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord[]> {\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n args.embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryEmbeddings.provider, args.embedding.provider),\n eq(juniorMemoryEmbeddings.model, args.embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(SUPERSESSION_CANDIDATE_LIMIT);\n return rows.flatMap((row) => {\n if (hashEmbeddedContent(row.memory.content) !== row.contentHash) {\n return [];\n }\n return [parseMemoryRow(row.memory)];\n });\n}\n\nasync function decideSupersededIds(args: {\n candidates: MemoryRecord[];\n content: string;\n decider: MemorySupersessionDecider | undefined;\n kind: MemoryRecord[\"kind\"];\n runtimeContext: MemoryRuntimeContext;\n}): Promise<string[]> {\n // Supersession is conservative: model uncertainty or decider failure leaves\n // both memories active rather than hiding a possibly valid old preference.\n if (\n args.kind !== \"preference\" ||\n !args.decider ||\n args.candidates.length === 0\n ) {\n return [];\n }\n const existingMemories = args.candidates.map((memory) => ({\n content: memory.content,\n id: memory.id,\n })) as MemorySupersessionInput[\"existingMemories\"];\n const candidateIds = new Set(args.candidates.map((memory) => memory.id));\n try {\n const decision = await args.decider.adjudicateSupersession({\n candidate: {\n content: args.content,\n kind: \"preference\",\n },\n existingMemories,\n runtimeContext: args.runtimeContext,\n });\n if (decision.decision !== \"supersedes_old\") {\n return [];\n }\n return decision.supersededIds.filter((id) => candidateIds.has(id));\n } catch {\n return [];\n }\n}\n\n/** List active records for the runtime-derived visible scopes. */\nasync function listVisibleMemories(args: {\n db: MemoryDb;\n limit?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryRecord[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const limit = boundedLimit(args.limit, DEFAULT_LIST_LIMIT);\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(predicate)\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(limit);\n return rows.map(parseMemoryRow);\n}\n\n/** Search active visible records with the V1 lexical matcher. */\nasync function searchVisibleMemories(args: {\n db: MemoryDb;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<SearchCandidate[]> {\n const terms = searchTerms(args.query);\n if (terms.length === 0) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n ),\n ),\n );\n return rows.map((row) => ({\n memory: parseMemoryRow(row),\n score: 0,\n sourceKey: row.sourceKey,\n }));\n}\n\n/** Search active visible records with exact pgvector cosine distance. */\nasync function searchVisibleVectorMemories(args: {\n db: MemoryDb;\n embedder: MemoryEmbeddingProvider | undefined;\n limit: number;\n maxDistance?: number;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<SearchCandidate[]> {\n if (!args.embedder) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n let embedding: Awaited<ReturnType<typeof embedOne>>;\n try {\n embedding = await embedOne(args.embedder, args.query);\n } catch {\n return [];\n }\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n predicate,\n eq(juniorMemoryEmbeddings.provider, embedding.provider),\n eq(juniorMemoryEmbeddings.model, embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(args.limit);\n return rows.flatMap((row) => {\n const distanceValue = Number(row.distance);\n if (\n row.distance === null ||\n !Number.isFinite(distanceValue) ||\n hashEmbeddedContent(row.memory.content) !== row.contentHash\n ) {\n return [];\n }\n if (args.maxDistance !== undefined && distanceValue > args.maxDistance) {\n return [];\n }\n return [\n {\n memory: parseMemoryRow(row.memory),\n score: 1 / (1 + Math.max(0, distanceValue)),\n sourceKey: row.memory.sourceKey,\n },\n ];\n });\n}\n\nfunction sourceBoost(\n candidate: Pick<SearchCandidate, \"sourceKey\">,\n currentChannelPrefix: string | undefined,\n): number {\n if (!currentChannelPrefix) {\n return 0;\n }\n return candidate.sourceKey.startsWith(currentChannelPrefix)\n ? SOURCE_CHANNEL_BOOST\n : 0;\n}\n\n/** Score only observation age for near-tie reranking; this is not lifecycle decay. */\nfunction observedAgeBoost(memory: MemoryRecord, nowMs: number): number {\n const ageMs = Math.max(0, nowMs - memory.observedAtMs);\n if (ageMs <= 7 * ONE_DAY_MS) {\n return 0.15;\n }\n if (ageMs <= 30 * ONE_DAY_MS) {\n return 0.1;\n }\n if (ageMs <= 90 * ONE_DAY_MS) {\n return 0.05;\n }\n return 0;\n}\n\n/** Fuse retrieval candidates while keeping observed age to near-tie reranking. */\nfunction mergeSearchCandidates(\n candidates: SearchCandidate[],\n nowMs: number,\n currentChannelKey?: string,\n): MemoryRecord[] {\n const byId = new Map<\n string,\n {\n memory: MemoryRecord;\n score: number;\n sourceKey: string;\n }\n >();\n for (const candidate of candidates) {\n const existing = byId.get(candidate.memory.id);\n if (existing) {\n existing.score += candidate.score;\n continue;\n }\n byId.set(candidate.memory.id, {\n memory: candidate.memory,\n score: candidate.score,\n sourceKey: candidate.sourceKey,\n });\n }\n return [...byId.values()]\n .sort((left, right) => {\n const scoreDelta = right.score - left.score;\n if (Math.abs(scoreDelta) > RELEVANCE_NEAR_TIE_DELTA) {\n return scoreDelta;\n }\n const sourceDelta =\n sourceBoost(right, currentChannelKey) -\n sourceBoost(left, currentChannelKey);\n if (sourceDelta !== 0) {\n return sourceDelta;\n }\n return (\n observedAgeBoost(right.memory, nowMs) -\n observedAgeBoost(left.memory, nowMs) ||\n right.memory.observedAtMs - left.memory.observedAtMs ||\n left.memory.id.localeCompare(right.memory.id)\n );\n })\n .map((candidate) => candidate.memory);\n}\n\n/** Create a context-bound SQL-backed store for explicit memory operations. */\nexport function createMemoryStore(\n db: MemoryDb,\n context: MemoryRuntimeContext,\n options: MemoryStoreOptions = {},\n): MemoryStore {\n const runtimeContext = memoryRuntimeContextSchema.parse(context);\n const parsedOptions = memoryStoreOptionsSchema.parse({ now: options.now });\n const embedder = options.embedder;\n const maxVectorDistance = options.maxVectorDistance;\n const supersessionDecider = options.supersessionDecider;\n const getNowMs = parsedOptions.now ?? Date.now;\n\n async function archiveExpiredVisibleMemories(\n input: ArchiveExpiredMemoriesInput | undefined,\n nowMs: number,\n ): Promise<ArchiveExpiredMemoriesResult> {\n input = archiveExpiredMemoriesInputSchema.parse(input ?? {});\n return await archiveExpiredMemoryBatch({\n db,\n limit: input.limit,\n nowMs,\n scopes: deriveVisibleMemoryScopes(runtimeContext),\n });\n }\n\n /** Persist a memory under the plugin-derived scope and subject. */\n async function createScopedMemory(\n rawInput: CreateMemoryInput,\n scopeKind: MemoryScope,\n ): Promise<CreateMemoryResult> {\n const input = createMemoryInputSchema.parse(rawInput);\n const nowMs = getNowMs();\n const content = normalizeContent(input.content);\n const scope = deriveMemoryScope(runtimeContext, scopeKind);\n const subject = deriveMemorySubject(runtimeContext, scope);\n if (content.length > MAX_MEMORY_CONTENT_CHARS) {\n throw new Error(\"Memory content exceeds the maximum length.\");\n }\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes: [scope],\n });\n await archiveExpiredMemoryBatch({\n db,\n idempotencyKey: input.idempotencyKey,\n limit: 1,\n nowMs,\n scopes: [scope],\n });\n if (input.idempotencyKey !== undefined) {\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n });\n if (idempotent) {\n await storeEmbedding({\n content: idempotent.content,\n db,\n embedder,\n memoryId: idempotent.id,\n nowMs,\n });\n return { created: false, memory: idempotent };\n }\n }\n\n const exactDuplicate = await findExactDuplicateMemory({\n content,\n db,\n kind: input.kind,\n nowMs,\n scope,\n subject,\n });\n if (exactDuplicate) {\n await rememberDuplicateIdempotency({\n content,\n db,\n duplicate: exactDuplicate,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n runtimeContext,\n scope,\n subject,\n });\n await storeEmbedding({\n content: exactDuplicate.content,\n db,\n embedder,\n memoryId: exactDuplicate.id,\n nowMs,\n });\n return { created: false, memory: exactDuplicate };\n }\n\n let candidateEmbedding: MemoryEmbedding | undefined;\n if (embedder) {\n try {\n candidateEmbedding = await embedOne(embedder, content);\n } catch {\n candidateEmbedding = undefined;\n }\n }\n const vectorDuplicate = candidateEmbedding\n ? await findVectorDuplicateMemory({\n db,\n embedding: candidateEmbedding,\n kind: input.kind,\n nowMs,\n scope,\n subject,\n })\n : undefined;\n if (vectorDuplicate) {\n await rememberDuplicateIdempotency({\n content,\n db,\n duplicate: vectorDuplicate,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n runtimeContext,\n scope,\n subject,\n });\n await storeEmbedding({\n content: vectorDuplicate.content,\n db,\n embedder,\n memoryId: vectorDuplicate.id,\n nowMs,\n });\n return { created: false, memory: vectorDuplicate };\n }\n\n let supersededIds: string[] = [];\n if (\n scopeKind === \"personal\" &&\n input.kind === \"preference\" &&\n supersessionDecider &&\n (input.expiresAtMs === undefined || input.expiresAtMs > nowMs)\n ) {\n const supersessionCandidates = await listSupersessionCandidates({\n content,\n db,\n ...(candidateEmbedding ? { embedding: candidateEmbedding } : {}),\n kind: input.kind,\n nowMs,\n scope,\n subject,\n });\n supersededIds = await decideSupersededIds({\n candidates: supersessionCandidates,\n content,\n decider: supersessionDecider,\n kind: input.kind,\n runtimeContext,\n });\n }\n\n const id = randomUUID();\n const rows = await db.transaction(async (tx) => {\n const inserted = await tx\n .insert(juniorMemoryMemories)\n .values({\n content,\n createdAtMs: nowMs,\n expiresAtMs: input.expiresAtMs,\n id,\n idempotencyKey: input.idempotencyKey,\n observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: runtimeContext.source.platform,\n subjectKey: subject.subjectKey,\n subjectType: subject.subjectType,\n kind: input.kind,\n })\n .onConflictDoNothing({\n target: [\n juniorMemoryMemories.scope,\n juniorMemoryMemories.scopeKey,\n juniorMemoryMemories.idempotencyKey,\n ],\n where: sql`${juniorMemoryMemories.idempotencyKey} IS NOT NULL AND ${juniorMemoryMemories.archivedAtMs} IS NULL AND ${juniorMemoryMemories.supersededAtMs} IS NULL AND ${juniorMemoryMemories.supersededById} IS NULL`,\n })\n .returning();\n const insertedMemory = inserted[0];\n if (!insertedMemory || supersededIds.length === 0) {\n return inserted;\n }\n const superseded = await tx\n .update(juniorMemoryMemories)\n .set({\n supersededAtMs: nowMs,\n supersededById: insertedMemory.id,\n })\n .where(\n and(\n inArray(juniorMemoryMemories.id, supersededIds),\n activeScopedSubjectPredicate({\n kind: input.kind,\n nowMs,\n scope,\n subject,\n }),\n ),\n )\n .returning({ id: juniorMemoryMemories.id });\n const idsToClean = superseded.map((row) => row.id);\n if (idsToClean.length > 0) {\n await tx\n .delete(juniorMemoryEmbeddings)\n .where(inArray(juniorMemoryEmbeddings.memoryId, idsToClean));\n }\n return inserted;\n });\n if (rows[0]) {\n const memory = parseMemoryRow(rows[0]);\n await storeEmbedding({\n content: memory.content,\n db,\n embedder,\n embedding: candidateEmbedding,\n memoryId: memory.id,\n nowMs,\n });\n return { created: true, memory };\n }\n\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n });\n if (!idempotent) {\n throw new Error(\"Memory idempotency conflict did not resolve.\");\n }\n await storeEmbedding({\n content: idempotent.content,\n db,\n embedder,\n memoryId: idempotent.id,\n nowMs,\n });\n return { created: false, memory: idempotent };\n }\n\n return {\n async archiveExpiredMemories(input) {\n return await archiveExpiredVisibleMemories(input, getNowMs());\n },\n\n async createMemory(input) {\n return await createScopedMemory(input, \"personal\");\n },\n\n async createConversationMemory(input) {\n return await createScopedMemory(input, \"conversation\");\n },\n\n async listMemories(input) {\n input = listMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n return await listVisibleMemories({\n db,\n limit: input.limit,\n nowMs,\n scopes,\n });\n },\n\n async searchMemories(input) {\n input = searchMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n const limit = boundedLimit(input.limit, DEFAULT_SEARCH_LIMIT);\n const vectorCandidates = await searchVisibleVectorMemories({\n db,\n embedder,\n limit: limit * VECTOR_SEARCH_OVERFETCH,\n ...(maxVectorDistance !== undefined\n ? { maxDistance: maxVectorDistance }\n : {}),\n nowMs,\n query: input.query,\n scopes,\n });\n const candidates = await searchVisibleMemories({\n db,\n nowMs,\n query: input.query,\n scopes,\n });\n const terms = searchTerms(input.query);\n const lexicalCandidates = candidates\n .map((candidate) => ({\n ...candidate,\n score: searchScore(candidate.memory, terms),\n }))\n .filter((item) => item.score > 0);\n return mergeSearchCandidates(\n [...vectorCandidates, ...lexicalCandidates],\n nowMs,\n sourceChannelPrefix(runtimeContext),\n ).slice(0, limit);\n },\n\n async archiveMemory(input) {\n input = archiveMemoryInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n const predicate = activeVisiblePredicate({ nowMs, scopes });\n const idPrefix = input.id.trim();\n if (!idPrefix) {\n throw new Error(\"Memory id is required.\");\n }\n const rows = predicate\n ? await db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n eq(juniorMemoryMemories.id, idPrefix),\n like(juniorMemoryMemories.id, `${idPrefix}%`),\n ),\n ),\n )\n .orderBy(asc(juniorMemoryMemories.id))\n .limit(2)\n : [];\n if (rows.length === 0) {\n throw new Error(\"Memory was not found in the current context.\");\n }\n if (rows.length > 1) {\n throw new Error(\"Memory id prefix is ambiguous.\");\n }\n const memory = parseMemoryRow(rows[0]);\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: input.reason ?? \"user_removed\",\n })\n .where(eq(juniorMemoryMemories.id, memory.id))\n .returning();\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memory.id));\n return parseMemoryRow(updated[0]);\n },\n };\n}\n","import { isPrivateSource } from \"@sentry/junior-plugin-api\";\nimport type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\n/** Runtime-derived visibility scope used for memory authorization checks. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** Runtime-derived subject classification stored for filtering and rendering. */\nexport interface ResolvedMemorySubject {\n subjectKey?: string;\n subjectType: MemorySubjectType;\n}\n\nfunction sourceConversationKey(ctx: MemoryRuntimeContext): string | undefined {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n if (!isPrivateSource(ctx.source)) {\n return `slack:${ctx.source.teamId}`;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n return undefined;\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\nfunction actorScopeKey(ctx: MemoryRuntimeContext): string | undefined {\n const actor = ctx.actor;\n if (!actor?.userId) {\n return undefined;\n }\n if (actor.platform === \"slack\") {\n return `slack:${actor.teamId}:${actor.userId}`;\n }\n return `local:${actor.userId}`;\n}\n\n/** Derive the authority-bearing key for a requested memory scope. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n scope: MemoryScope,\n): ResolvedMemoryScope {\n if (scope === \"personal\") {\n const scopeKey = actorScopeKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Personal memory requires actor context.\");\n }\n return { scope, scopeKey };\n }\n\n const scopeKey = sourceConversationKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Conversation memory requires conversation context.\");\n }\n return { scope, scopeKey };\n}\n\n/** Derive the memory subject from the already-authorized write scope. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n scope: ResolvedMemoryScope,\n): ResolvedMemorySubject {\n if (scope.scope === \"personal\") {\n const subjectKey = actorScopeKey(ctx);\n if (!subjectKey) {\n throw new Error(\"User-subject memory requires actor context.\");\n }\n return { subjectType: \"user\", subjectKey };\n }\n\n const subjectKey = sourceConversationKey(ctx);\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return { subjectType: \"conversation\", subjectKey };\n}\n\n/** Return every visible scope for memory retrieval in the current context. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n const scopes: ResolvedMemoryScope[] = [];\n try {\n scopes.push(deriveMemoryScope(ctx, \"personal\"));\n } catch {\n // Personal memory is optional when a runtime surface has no actor.\n }\n try {\n scopes.push(deriveMemoryScope(ctx, \"conversation\"));\n } catch {\n // Conversation memory is optional for synthetic invocations.\n }\n return scopes;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\n isPrivateSource,\n type PluginRunContext,\n type PluginRunTranscriptEntry,\n type PluginTaskContext,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryDb,\n} from \"./store\";\nimport {\n createMemoryAgent,\n parseExtractedMemory,\n type ExtractedMemory,\n} from \"./agent\";\nimport { MEMORY_KINDS, memoryRuntimeContextSchema } from \"./types\";\n\nconst MEMORY_TOOL_NAMES = new Set([\n \"createMemory\",\n \"listMemories\",\n \"removeMemory\",\n \"searchMemories\",\n]);\nconst MEMORY_TASK_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst extractedMemoryCacheSchema = z.array(\n z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().nullable(),\n kind: z.enum(MEMORY_KINDS),\n evidenceMessageIndices: z\n .array(z.number().int().nonnegative())\n .min(1)\n .max(10),\n })\n .strict()\n .transform(parseExtractedMemory),\n);\n\n/** Where a passively extracted memory may be stored, or dropped when unproven. */\ntype MemoryRouteTarget = \"drop\" | \"personal\" | \"conversation\";\n\n/** A cited entry is a run-actor durable instruction evidence entry. */\nfunction isRunActorInstruction(entry: PluginRunTranscriptEntry): boolean {\n return (\n entry.type === \"message\" &&\n entry.role === \"user\" &&\n entry.provenance?.authority === \"instruction\" &&\n entry.isRunActor === true\n );\n}\n\n/** A cited entry is valid public conversation evidence for shared knowledge. */\nfunction isConversationEvidence(entry: PluginRunTranscriptEntry): boolean {\n if (entry.type === \"toolResult\") {\n return entry.isError === false && Boolean(entry.text?.trim());\n }\n if (\n entry.type === \"message\" &&\n entry.role === \"user\" &&\n entry.provenance?.authority === \"instruction\" &&\n entry.isRunActor === false\n ) {\n return Boolean(entry.provenance.actor);\n }\n return (\n entry.type === \"message\" &&\n entry.role === \"user\" &&\n entry.provenance?.authority === \"context\"\n );\n}\n\n/** Resolve the deduplicated cited transcript entries, failing on bad indices. */\nfunction citedEntries(\n indices: number[],\n transcript: PluginRunTranscriptEntry[],\n): { valid: boolean; entries: PluginRunTranscriptEntry[] } {\n const seen = new Set<number>();\n const entries: PluginRunTranscriptEntry[] = [];\n for (const index of indices) {\n if (seen.has(index)) {\n continue;\n }\n seen.add(index);\n const entry = transcript[index];\n if (!entry) {\n return { valid: false, entries: [] };\n }\n entries.push(entry);\n }\n return { valid: entries.length > 0, entries };\n}\n\n/**\n * Verify an extracted memory against runtime-owned provenance on its cited\n * evidence. This is a deterministic authority boundary, not a model decision:\n * personal preferences require a single-actor run whose citations are all\n * run-actor instructions, conversation knowledge requires run-actor instruction\n * or valid public conversation evidence, and anything unproven (including\n * missing provenance) is dropped. Multi-actor runs interleave first-person\n * statements from different people, so they never store a preference regardless\n * of citations; a personal preference can wait for a single-actor run.\n */\nfunction routeExtractedMemory(\n memory: ExtractedMemory,\n transcript: PluginRunTranscriptEntry[],\n run: Pick<PluginRunContext, \"actor\" | \"actors\">,\n): MemoryRouteTarget {\n const cited = citedEntries(memory.evidenceMessageIndices, transcript);\n if (!cited.valid) {\n return \"drop\";\n }\n if (memory.kind === \"preference\") {\n // Only a run attributed to exactly one run actor may store a preference; an\n // empty actor set (system runs) fails closed to \"drop\".\n const exactlyOneRunActor = Boolean(run.actor) && run.actors.length === 1;\n if (!exactlyOneRunActor) {\n return \"drop\";\n }\n // Never downgrade an unproven first-person preference to conversation scope.\n return cited.entries.every(isRunActorInstruction) ? \"personal\" : \"drop\";\n }\n return cited.entries.every(\n (entry) => isRunActorInstruction(entry) || isConversationEvidence(entry),\n )\n ? \"conversation\"\n : \"drop\";\n}\n\nfunction memoryIdempotencySuffix(\n memory: ExtractedMemory,\n target: MemoryRouteTarget,\n): string {\n return createHash(\"sha256\")\n .update(target)\n .update(\"\\0\")\n .update(memory.kind)\n .update(\"\\0\")\n .update(memory.content)\n .update(\"\\0\")\n .update(memory.expiresAtMs === null ? \"never\" : String(memory.expiresAtMs))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction passiveInput(\n sessionId: string,\n memory: ExtractedMemory,\n sourceKey: string,\n target: MemoryRouteTarget,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory, target)}`,\n kind: memory.kind,\n ...(memory.expiresAtMs !== null ? { expiresAtMs: memory.expiresAtMs } : {}),\n };\n}\n\nasync function getTaskMemories(\n context: PluginTaskContext,\n extract: () => Promise<ExtractedMemory[]>,\n): Promise<ExtractedMemory[]> {\n const cacheKey = `memory-extraction:${context.id}`;\n const cached = await context.state.get(cacheKey);\n if (cached !== undefined) {\n const parsed = extractedMemoryCacheSchema.safeParse(cached);\n if (parsed.success) {\n return parsed.data;\n }\n await context.state.delete(cacheKey);\n }\n const memories = await extract();\n if (memories.length > 0) {\n await context.state.set(cacheKey, memories, MEMORY_TASK_STATE_TTL_MS);\n }\n return memories;\n}\n\n/**\n * Extract and store memories from a completed session plugin task.\n *\n * Memory owns post-session extraction and consumes only the bounded plugin task\n * projection. Explicit memory tools and private non-local sources remain hard\n * boundaries so background retries cannot reinterpret user-directed mutations\n * or private conversations.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // Memory tool turns already own memory management or recall; do not reinterpret\n // recalled memory output as fresh passive-learning evidence.\n if (\n run.transcript.some(\n (entry) =>\n entry.type === \"toolResult\" && MEMORY_TOOL_NAMES.has(entry.toolName),\n )\n ) {\n return;\n }\n // V1 passive learning only stores public channel facts outside local QA.\n if (run.source.platform !== \"local\" && isPrivateSource(run.source)) {\n return;\n }\n const sourceKey = getSourceKey(run.source);\n if (!sourceKey) {\n return;\n }\n const transcript = run.transcript\n .filter((entry) => entry.text?.trim())\n .map((entry) => ({ ...entry, text: entry.text!.trim() }));\n const evidenceText = transcript\n .filter((entry) => entry.type === \"toolResult\" || entry.role === \"user\")\n .map((entry) => entry.text)\n .join(\"\\n\\n\")\n .trim();\n if (!evidenceText) {\n return;\n }\n\n const runtimeContext = memoryRuntimeContextSchema.parse({\n conversationId: run.conversationId,\n ...(run.actor ? { actor: run.actor } : {}),\n source: run.source,\n });\n const agent = createMemoryAgent(context.model);\n const store = createMemoryStore(context.db as MemoryDb, runtimeContext, {\n embedder: context.embedder,\n supersessionDecider: agent,\n });\n await store.archiveExpiredMemories();\n const memories = await getTaskMemories(context, async () => {\n const existingMemories = await store.searchMemories({\n limit: 10,\n query: evidenceText,\n });\n return await agent.extractSessionMemories({\n existingMemories: existingMemories.map((memory) => ({\n content: memory.content,\n })),\n actors: run.actors,\n transcript,\n runtimeContext,\n });\n });\n if (memories.length === 0) {\n return;\n }\n\n for (const memory of memories) {\n // The routing gate stays even though extraction is also actor-gated:\n // getTaskMemories caches extraction output for 7 days, so a retry can replay\n // preference proposals cached before this gate existed.\n const target = routeExtractedMemory(memory, transcript, run);\n if (target === \"drop\") {\n continue;\n }\n const input = passiveInput(run.runId, memory, sourceKey, target);\n if (target === \"conversation\") {\n await store.createConversationMemory(input);\n continue;\n }\n await store.createMemory(input);\n }\n}\n","import type { PromptMessage, Actor, Source } from \"@sentry/junior-plugin-api\";\nimport {\n createMemoryStore,\n type MemoryDb,\n type MemoryEmbeddingProvider,\n type MemoryRecord,\n} from \"./store\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst DEFAULT_RECALL_LIMIT = 5;\nconst MAX_PROMPT_CHARS = 4_000;\nconst MAX_MEMORY_LINE_CHARS = 600;\n\nexport interface MemoryRecallContext {\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n /** Maximum cosine distance for vector recall. Passed through to the memory store. */\n maxVectorDistance?: number;\n actor?: Actor;\n source: Source;\n text: string;\n}\n\nfunction trimContent(content: string, maxLength: number): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxLength) {\n return trimmed;\n }\n return `${trimmed.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\nfunction formatObservedDate(observedAtMs: number): string {\n return new Date(observedAtMs).toISOString().slice(0, 10);\n}\n\nfunction renderMemoryPrompt(memories: MemoryRecord[]): string | undefined {\n const header = \"Relevant memories for this request:\";\n const footer =\n \"Treat these as possibly stale context. Current user instructions and repository evidence take priority.\";\n const lines: string[] = [];\n let totalChars = header.length + footer.length + 2;\n\n for (const memory of memories) {\n const line = `- Observed ${formatObservedDate(memory.observedAtMs)}: ${trimContent(\n memory.content,\n MAX_MEMORY_LINE_CHARS,\n )}`;\n if (totalChars + line.length + 1 > MAX_PROMPT_CHARS) {\n break;\n }\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length === 0) {\n return undefined;\n }\n return `${header}\\n${lines.join(\"\\n\")}\\n\\n${footer}`;\n}\n\n/** Build the memory prompt contribution for active visible recall. */\nexport async function createMemoryPromptMessages(\n context: MemoryRecallContext,\n): Promise<PromptMessage[] | undefined> {\n if (!context.text.trim()) {\n return undefined;\n }\n const runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.actor ? { actor: context.actor } : {}),\n source: context.source,\n });\n const memories = await createMemoryStore(context.db, runtimeContext, {\n ...(context.embedder ? { embedder: context.embedder } : {}),\n ...(context.maxVectorDistance !== undefined\n ? { maxVectorDistance: context.maxVectorDistance }\n : {}),\n }).searchMemories({\n query: context.text,\n limit: DEFAULT_RECALL_LIMIT,\n });\n const text = renderMemoryPrompt(memories);\n return text ? [{ text }] : undefined;\n}\n"],"mappings":";AAAA,SAAS,0BAA0B;;;ACAnC,SAAS,mBAAqC;AAC9C,SAAS,KAAAA,UAAS;;;ACDlB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe,CAAC,cAAc,aAAa,WAAW;AAE5D,IAAM,gBAAgB,CAAC,YAAY,cAAc;AACjD,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AACF;AACO,IAAM,2BAA2B,CAAC,QAAQ;AAC1C,IAAM,8BAA8B;AAQ3C,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC;AAGtC,IAAM,kCAAkC,EAC5C,OAAO;AAAA,EACN,gBAAgB,qBAAqB,SAAS;AAAA,EAC9C,OAAO,iBAAiB,SAAS;AAAA,EACjC,QAAQ;AACV,CAAC,EACA,OAAO;AAGH,IAAM,kCAAkC,EAC5C,OAAO;AAAA,EACN,gBAAgB,qBAAqB,SAAS;AAAA,EAC9C,OAAO,iBAAiB,SAAS;AAAA,EACjC,QAAQ;AACV,CAAC,EACA,OAAO;AAGH,IAAM,6BAA6B,EAAE,MAAM;AAAA,EAChD;AAAA,EACA;AACF,CAAC;;;AD1CD,IAAM,mBAAmBC,GAAE,KAAK,YAAY;AAC5C,IAAM,2BAA2BA,GAAE,KAAK;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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c","eq","gt","ilike","isNull","or","sql","z","scopeKey","subjectKey","nonEmptyStringSchema","z","or","and","eq","isNull","gt","desc","text","ilike","idempotent","sql","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","z","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","createHash","getSourceKey","isPrivateSource","z","z","index","createHash","sourceKey","isPrivateSource","getSourceKey","text"]}
|