@sentry/junior-memory 0.207.0 → 0.208.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/plugin.ts","../src/agent.ts","../src/store.ts","../src/db/schema.ts","../src/types.ts","../src/ranking.ts","../src/scope.ts","../src/api.ts","../src/viewer.ts","../src/cli/search.ts","../src/cli/format.ts","../src/cli/show.ts","../src/cli/index.ts","../src/tools.ts","../src/process-session.ts","../src/events.ts","../src/recall.ts","../src/operational-report.ts","../src/user-pages.ts"],"sourcesContent":["import { defineJuniorPlugin } from \"@sentry/junior-plugin-api\";\nimport { createMemoryAgent } from \"./agent\";\nimport { createMemoryApi } from \"./api\";\nimport { createMemoryCliCommand } from \"./cli\";\nimport {\n createMemoryArchiveTool,\n createMemoryCreateTool,\n createMemoryListTool,\n createMemorySearchTool,\n type MemoryCreateToolContext,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { createMemoryPromptContributions } from \"./recall\";\nimport { buildMemoryOperationalReport } from \"./operational-report\";\nimport {\n memoriesCapturedEvent,\n memoriesCapturedEventV1,\n memoriesRecalledEvent,\n} from \"./events\";\nimport type { MemoryDb } from \"./store\";\nimport { createMemoryUserPage } from \"./user-pages\";\n\nconst MEMORY_MODEL_ENV = \"AI_MEMORY_MODEL\";\n\nexport interface MemoryPluginOptions {\n /** Disable automatic prompt recall while keeping explicit memory tools available. */\n disableRecall?: boolean;\n /** Disable passive memory extraction from completed sessions. */\n disableExtraction?: boolean;\n modelId?: string;\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 memoryToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryToolContext[\"db\"];\n embedder?: MemoryToolContext[\"embedder\"];\n locationId?: string;\n actor?: MemoryToolContext[\"actor\"];\n source: MemoryToolContext[\"source\"];\n users: MemoryToolContext[\"users\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId\n ? { conversationId: ctx.conversationId }\n : undefined),\n ...(ctx.actor ? { actor: ctx.actor } : undefined),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : undefined),\n ...(ctx.locationId ? { locationId: ctx.locationId } : undefined),\n source: ctx.source,\n users: ctx.users,\n ...(ctx.userText ? { userText: ctx.userText } : undefined),\n };\n}\n\nfunction memoryCreateToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryCreateToolContext[\"db\"];\n embedder?: MemoryCreateToolContext[\"embedder\"];\n locationId?: string;\n actor?: MemoryCreateToolContext[\"actor\"];\n source: MemoryCreateToolContext[\"source\"];\n supersessionDecider: MemoryCreateToolContext[\"supersessionDecider\"];\n users: MemoryCreateToolContext[\"users\"];\n userText?: string;\n}): MemoryCreateToolContext {\n return {\n ...memoryToolContext(ctx),\n supersessionDecider: ctx.supersessionDecider,\n };\n}\n\n/** Register Junior's long-term memory plugin. */\nexport function memoryPlugin(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 conversationEvents: [\n memoriesCapturedEventV1,\n memoriesCapturedEvent,\n memoriesRecalledEvent,\n ],\n cli: {\n commands: [createMemoryCliCommand()],\n },\n tasks: options.disableExtraction\n ? {}\n : {\n processSession: {\n async run(ctx) {\n await processMemorySession(ctx);\n },\n },\n },\n userPages: [createMemoryUserPage()],\n hooks: {\n async operationalReport(ctx) {\n const extractionDays = await ctx.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_captured\",\n });\n return await buildMemoryOperationalReport({\n db: ctx.db as MemoryDb,\n extractionDays,\n nowMs: ctx.nowMs,\n });\n },\n apiRoutes(ctx) {\n return createMemoryApi({\n db: ctx.db as MemoryDb,\n eventStats: ctx.eventStats,\n users: ctx.users,\n });\n },\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 archiveMemory: createMemoryArchiveTool(context),\n listMemories: createMemoryListTool(context),\n searchMemories: createMemorySearchTool(context),\n };\n },\n ...(!options.disableRecall\n ? {\n async userPrompt(ctx) {\n return await createMemoryPromptContributions({\n agent: createMemoryAgent(ctx.model),\n ...(ctx.conversationId\n ? { conversationId: ctx.conversationId }\n : undefined),\n ...(ctx.actor ? { actor: ctx.actor } : undefined),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n events: ctx.events,\n ...(ctx.locationId\n ? { locationId: ctx.locationId }\n : undefined),\n log: ctx.log,\n source: ctx.source,\n text: ctx.text,\n users: ctx.users,\n });\n },\n }\n : undefined),\n },\n });\n}\n","import {\n actorSchema,\n sourceSchema,\n type PluginModel,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n memorySupersessionDecisionSchema,\n memorySupersessionInputSchema,\n type MemorySupersessionDecision,\n type 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 memoryRecallCandidateSchema = z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n })\n .strict();\nconst memoryRecallInputSchema = z\n .object({\n candidates: z.array(memoryRecallCandidateSchema).min(1).max(20),\n userRequest: z.string().min(1),\n })\n .strict();\nconst memoryRecallDecisionSchema = z\n .object({\n relevantIds: z\n .array(z.string().min(1))\n .max(20)\n .describe(\n \"Candidate ids whose memories directly help with the current request, ordered by relevance.\",\n ),\n })\n .strict();\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 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 durable memories from the completed run. Return one object per distinct source assertion and classify it with kind.\",\n ),\n })\n .strict();\ntype MemoryReviewResponse = z.output<typeof memoryReviewResponseSchema>;\ntype ExtractMemoriesResponse = z.output<typeof extractMemoriesResponseSchema>;\n\nexport type MemoryReview = z.output<typeof memoryReviewDecisionSchema>;\nexport type MemoryRecallInput = z.output<typeof memoryRecallInputSchema>;\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\n/** Memories proposed by passive extraction and the model cost of that pass. */\nexport type MemoryExtractionResult = {\n costUsd?: number;\n memories: ExtractedMemory[];\n};\n\n/** Memories admitted by automatic recall and the model cost of that decision. */\nexport type MemoryRecallResult = {\n costUsd?: number;\n relevantIds: string[];\n};\n\nexport interface MemoryAgent {\n /** Select candidate memories that directly help with the current request. */\n selectRelevantMemories(\n request: MemoryRecallInput,\n ): Promise<MemoryRecallResult> | MemoryRecallResult;\n /** Classify a new preference against related active preferences. */\n adjudicateSupersession(\n request: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n extractSessionMemories(\n request: ExtractSessionRequest,\n ): Promise<MemoryExtractionResult> | MemoryExtractionResult;\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 self-contained facts that are useful beyond this turn and safe for the current Source.\",\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 durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst MEMORY_RECALL_SYSTEM = [\n \"You are Junior's memory recall relevance agent.\",\n \"Select only memories that would directly help answer the user's current request.\",\n \"Reject memories that merely share a company, product family, repository vocabulary, programming language, or general engineering context.\",\n \"Prefer specific matches on the exact repository, workflow, command, test, CI setup, project, or user preference being asked about.\",\n \"An empty relevantIds array is correct when no candidate is directly helpful.\",\n].join(\"\\n\");\nconst MEMORY_PREFERENCE_ADJUDICATION_SYSTEM = [\n \"You are Junior's memory preference adjudication agent.\",\n \"Classify how one new actor preference relates to existing active actor preferences.\",\n \"Return duplicate when the same durable preference is merely phrased differently.\",\n \"Return supersedes_old only for an obvious changed value in the same mutable preference slot.\",\n \"Return distinct for additive preferences or different topics, and uncertain when the relationship is unclear.\",\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(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\");\n}\n\nfunction actorLabel(actor: z.output<typeof actorSchema> | undefined): string {\n if (!actor) {\n return \"none\";\n }\n switch (actor.platform) {\n case \"system\":\n return `system:${actor.name}`;\n case \"slack\":\n return `slack:${actor.teamId}:${actor.userId}`;\n case \"local\":\n return `local:${actor.userId}`;\n case \"web\":\n return `web:${actor.userId}`;\n }\n}\n\nfunction sourceLabel(source: z.output<typeof sourceSchema>): string {\n switch (source.kind) {\n case \"slack\":\n return `slack:${source.teamId}:${source.channelId}`;\n case \"web\":\n case \"local\":\n return `${source.kind}:${source.conversationId}`;\n case \"event\":\n return `event:${source.namespace}:${source.eventKey}`;\n case \"scheduled_automation\":\n case \"event_automation\":\n case \"plugin_dispatch\":\n case \"agent_invocation\":\n return source.kind;\n }\n}\n\nfunction runtimeDescription(\n request: Pick<CreateMemoryRequest, \"expiresAtMs\" | \"runtimeContext\">,\n): string {\n const runtime = request.runtimeContext;\n const lines = [\n `- actor: ${escapeXml(actorLabel(runtime.actor))}`,\n `- source: ${escapeXml(sourceLabel(runtime.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-subject 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 durable, self-contained, and safe for the current Source.\",\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 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 = actorLabel(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 recallRelevancePrompt(request: MemoryRecallInput): string {\n return [\n \"<memory-recall-input>\",\n \"<user-request>\",\n escapeXml(request.userRequest),\n \"</user-request>\",\n \"\",\n \"<candidate-memories>\",\n escapeXml(JSON.stringify(request.candidates)),\n \"</candidate-memories>\",\n \"\",\n \"Return only ids from candidate-memories. Preserve the most relevant candidates first.\",\n \"</memory-recall-input>\",\n ].join(\"\\n\");\n}\n\nfunction preferenceAdjudicationPrompt(\n request: MemorySupersessionInput,\n): string {\n return [\n \"<memory-preference-adjudication-input>\",\n \"Classify the candidate preference against the related 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 duplicate when the candidate and one existing memory express the same durable preference or value with different wording.\",\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 \"- Return distinct when the candidate is an additional preference or belongs to a different task or topic.\",\n \"- Return uncertain when broader or narrower wording makes equivalence or replacement unclear.\",\n \"- Do not supersede memories from different topics even if they are both preferences.\",\n \"- duplicateId and supersededIds may contain only ids from existing-memories.\",\n \"- If unsure, return uncertain.\",\n \"</rules>\",\n \"</memory-preference-adjudication-input>\",\n ].join(\"\\n\");\n}\n\n/** Create the memory-owned agent that reviews, extracts, and recalls memories. */\nexport function createMemoryAgent(model: PluginModel): MemoryAgent {\n return {\n async selectRelevantMemories(rawRequest) {\n const request = memoryRecallInputSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: memoryRecallDecisionSchema,\n system: MEMORY_RECALL_SYSTEM,\n prompt: recallRelevancePrompt(request),\n maxTokens: 400,\n });\n const decision = memoryRecallDecisionSchema.parse(result.object);\n const candidateIds = new Set(request.candidates.map(({ id }) => id));\n return {\n relevantIds: [...new Set(decision.relevantIds)].filter((id) =>\n candidateIds.has(id),\n ),\n ...(result.costUsd !== undefined\n ? { costUsd: result.costUsd }\n : undefined),\n };\n },\n async adjudicateSupersession(rawRequest) {\n const request = memorySupersessionInputSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: memorySupersessionDecisionSchema,\n system: MEMORY_PREFERENCE_ADJUDICATION_SYSTEM,\n prompt: preferenceAdjudicationPrompt(request),\n maxTokens: 400,\n });\n return memorySupersessionDecisionSchema.parse(result.object);\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 {\n memories: extractedMemoriesFromResponse(\n extractMemoriesResponseSchema.parse(result.object),\n ),\n ...(result.costUsd !== undefined\n ? { costUsd: result.costUsd }\n : undefined),\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 : undefined),\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","/**\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 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 { getSourceKey } from \"@sentry/junior-plugin-api\";\nimport * as memorySqlSchema from \"./db/schema\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport { rankMemoryMatches, type MemoryMatch } from \"./ranking\";\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 MemorySourcePlatform,\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 PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT = 10;\nconst PREFERENCE_ADJUDICATION_VECTOR_LIMIT = 5;\n/** Explicit search overfetch: keep a wider fusion window for tool/CLI search. */\nconst SEARCH_RETRIEVAL_OVERFETCH = 4;\n/**\n * Automatic recall overfetch. Recall already asks for ~20 candidates before the\n * relevance gate, so each hybrid leg only needs a small top-k probe.\n */\nconst RECALL_RETRIEVAL_OVERFETCH = 2;\n/**\n * Absolute ceiling per retrieval leg. Matches the store limit ceiling so a\n * single healthy leg can still fill the caller's requested result window.\n */\nconst MAX_RETRIEVAL_LEG_CANDIDATES = 200;\n/** Cap ts_rank_cd work after GIN filtering; ranking is not indexable. */\nconst MAX_LEXICAL_RANK_CANDIDATES = 200;\n/** Expand the GIN match window before ts_rank_cd, still under the hard cap. */\nconst LEXICAL_RANK_WINDOW_MULTIPLIER = 4;\n/** Bound query text before embedding / FTS construction. */\nconst MAX_RETRIEVAL_QUERY_CHARS = 1_500;\nconst MAX_MEMORY_CONTENT_CHARS = 4_000;\nconst EMBEDDING_METRIC = \"cosine\";\n/**\n * Cosine distance cutoff for automatic recall only (not explicit search).\n * Tuned for text-embedding-3-small; retune if the embedding model changes.\n */\nconst RECALL_MAX_VECTOR_DISTANCE = 0.45;\n\nexport type MemoryDb = PgDatabase<PgQueryResultHKT, typeof memorySqlSchema>;\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 locationId: optionalNonEmptyStringSchema,\n observedAtMs: z.coerce.number(),\n searchVector: z.string().optional(),\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\nfunction storedMemorySource(\n source: MemoryRuntimeContext[\"source\"],\n): MemorySourcePlatform {\n switch (source.kind) {\n case \"slack\":\n case \"local\":\n case \"web\":\n return source.kind;\n case \"event\":\n case \"scheduled_automation\":\n case \"event_automation\":\n case \"plugin_dispatch\":\n case \"agent_invocation\":\n throw new Error(`${source.kind} Source cannot own a Memory.`);\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 costUsd: z.number().finite().nonnegative().optional(),\n dimensions: z.literal(MEMORY_EMBEDDING_DIMENSIONS),\n model: nonEmptyStringSchema,\n provider: nonEmptyStringSchema,\n vectors: z.array(embeddingVectorSchema),\n })\n .strict();\nconst memorySupersessionCandidateSchema = z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n })\n .strict();\nconst memorySupersessionCandidatesSchema = z\n .array(memorySupersessionCandidateSchema)\n .min(1)\n .max(PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT);\nconst supersededIdsSchema = z\n .array(z.string().min(1))\n .min(1)\n .max(PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT);\n\n/** Validated preference comparison input supplied to a supersession decider. */\nexport const memorySupersessionInputSchema = z\n .object({\n candidate: z\n .object({\n content: z.string().min(1),\n kind: z.literal(\"preference\"),\n })\n .strict(),\n existingMemories: memorySupersessionCandidatesSchema,\n runtimeContext: memoryRuntimeContextSchema,\n })\n .strict();\n\n/**\n * Validated preference decision whose referenced ids must come from the\n * supplied existing memories.\n */\nexport const memorySupersessionDecisionSchema = z.discriminatedUnion(\n \"decision\",\n [\n z\n .object({\n decision: z.literal(\"duplicate\"),\n duplicateId: z.string().min(1),\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"supersedes_old\"),\n supersededIds: supersededIdsSchema,\n })\n .strict(),\n z\n .object({\n decision: z.enum([\"distinct\", \"uncertain\"]),\n })\n .strict(),\n ],\n);\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 /** True when this call found the memory previously written for the same input identity. */\n idempotent?: true;\n memory: MemoryRecord;\n /** Memory ids made inactive by this write. */\n supersededIds?: string[];\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 costUsd?: number;\n dimensions: number;\n model: string;\n provider: string;\n vectors: number[][];\n }>;\n}\n\nexport type MemorySupersessionInput = z.output<\n typeof memorySupersessionInputSchema\n>;\n\nexport type MemorySupersessionDecision = z.output<\n typeof memorySupersessionDecisionSchema\n>;\n\nexport interface MemorySupersessionDecider {\n /** Classify a new preference against related active preferences. */\n adjudicateSupersession(\n input: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n}\n\nexport interface MemoryStoreOptions {\n embedder?: MemoryEmbeddingProvider;\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 memory about the current User. The Source sets access. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a memory about the current Conversation. The Source sets access. */\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 /**\n * Retrieve a broad relevance-ranked candidate window for automatic recall.\n * Prompt admission remains owned by the recall boundary.\n */\n recallMemories(input: SearchMemoriesInput): 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 stored key for the Source. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n const key = getSourceKey(ctx.source);\n if (!key) {\n throw new Error(\"Memory Source has no stable key.\");\n }\n return key;\n}\n\n/** Parse one SQL row into the public memory projection. */\nexport function 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 : undefined),\n ...(parsed.supersededAtMs !== undefined\n ? { supersededAtMs: parsed.supersededAtMs }\n : undefined),\n ...(parsed.supersededById\n ? { supersededById: parsed.supersededById }\n : undefined),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : undefined),\n ...(parsed.archiveReason\n ? { archiveReason: parsed.archiveReason }\n : undefined),\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\n/** Build the active-row predicate for already-authorized memory scopes. */\nexport function 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. */\ninterface IdempotencyMatch {\n memory: MemoryRecord;\n outcome: \"created\" | \"duplicate\";\n}\n\nasync function findByIdempotencyKey(args: {\n db: MemoryDb;\n idempotencyKey: string;\n nowMs: number;\n scope: ResolvedMemoryScope;\n}): Promise<IdempotencyMatch | 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 { memory: parseMemoryRow(activeRows[0]), outcome: \"created\" };\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 { memory: parseMemoryRow(rows[0]), outcome: \"duplicate\" };\n }\n }\n return undefined;\n}\n\n/**\n * Archive a bounded batch of expired active rows and remove their derived vectors.\n */\nexport async 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 denseRanks<T>(\n values: T[],\n key: (value: T) => string | number,\n): number[] {\n let previous: string | number | undefined;\n let rank = 0;\n return values.map((value, index) => {\n const current = key(value);\n if (index === 0 || current !== previous) {\n rank = index + 1;\n previous = current;\n }\n return rank;\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 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 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 locationId: args.runtimeContext.locationId,\n observedAtMs: args.nowMs,\n scope: args.scope.scope,\n scopeKey: args.scope.scopeKey,\n sourceKey: sourceKey(args.runtimeContext),\n sourcePlatform: storedMemorySource(args.runtimeContext.source),\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\n/** Select semantic preferences, then fill the window by recency for unembedded records. */\nasync function listPreferenceAdjudicationCandidates(args: {\n db: MemoryDb;\n embedding?: MemoryEmbedding;\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord[]> {\n const vectorCandidates = args.embedding\n ? await listVectorPreferenceAdjudicationCandidates({\n db: args.db,\n embedding: args.embedding,\n nowMs: args.nowMs,\n scope: args.scope,\n subject: args.subject,\n })\n : [];\n const recentCandidates = (\n await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n activeScopedSubjectPredicate({\n ...args,\n kind: \"preference\",\n }),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT)\n ).map(parseMemoryRow);\n return [\n ...new Map(\n [...vectorCandidates, ...recentCandidates].map((memory) => [\n memory.id,\n memory,\n ]),\n ).values(),\n ].slice(0, PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT);\n}\n\nasync function listVectorPreferenceAdjudicationCandidates(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\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, kind: \"preference\" }),\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(PREFERENCE_ADJUDICATION_VECTOR_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\ntype PreferenceAdjudicationResult =\n | { decision: \"create\" }\n | { decision: \"duplicate\"; memory: MemoryRecord }\n | { decision: \"supersede\"; ids: [string, ...string[]] };\n\n/**\n * Normalize a preference decision to known duplicate or supersession targets.\n * Uncertainty, invalid ids, and model failure leave existing memories active.\n */\nasync function adjudicatePreferenceCandidate(args: {\n candidates: MemoryRecord[];\n content: string;\n decider: MemorySupersessionDecider;\n runtimeContext: MemoryRuntimeContext;\n}): Promise<PreferenceAdjudicationResult> {\n const [firstCandidate, ...remainingCandidates] = args.candidates;\n if (!firstCandidate) {\n return { decision: \"create\" };\n }\n const existingMemories = [\n { content: firstCandidate.content, id: firstCandidate.id },\n ...remainingCandidates.map((memory) => ({\n content: memory.content,\n id: memory.id,\n })),\n ];\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 === \"duplicate\") {\n const memory = args.candidates.find(\n (candidate) => candidate.id === decision.duplicateId,\n );\n return memory\n ? { decision: \"duplicate\", memory }\n : { decision: \"create\" };\n }\n if (decision.decision === \"supersedes_old\") {\n const ids = decision.supersededIds.filter((id) => candidateIds.has(id));\n const [firstId, ...remainingIds] = ids;\n return firstId\n ? { decision: \"supersede\", ids: [firstId, ...remainingIds] }\n : { decision: \"create\" };\n }\n return { decision: \"create\" };\n } catch {\n return { decision: \"create\" };\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\nfunction normalizeRetrievalQuery(query: string): string {\n const normalized = query.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= MAX_RETRIEVAL_QUERY_CHARS) {\n return normalized;\n }\n return normalized.slice(0, MAX_RETRIEVAL_QUERY_CHARS).trimEnd();\n}\n\nfunction retrievalLegLimit(limit: number, overfetch: number): number {\n const requested = Math.max(1, limit);\n const withOverfetch = requested * Math.max(1, overfetch);\n // Never return fewer candidates than the caller asked for. A hard overfetch\n // cap below `limit` under-fills when one modality is empty or both overlap.\n return Math.min(\n MAX_RETRIEVAL_LEG_CANDIDATES,\n Math.max(requested, withOverfetch),\n );\n}\n\n/** Search a bounded active candidate set with PostgreSQL full-text ranking. */\nasync function searchVisibleLexicalMemories(args: {\n db: MemoryDb;\n limit: number;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryMatch[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const query = normalizeRetrievalQuery(args.query);\n if (!query) {\n return [];\n }\n const queryVector = sql`to_tsvector('english', ${query})`;\n const tsquery = sql`(\n SELECT COALESCE(\n string_agg(quote_literal(term), ' | ')::tsquery,\n ''::tsquery\n )\n FROM unnest(tsvector_to_array(${queryVector})) AS query_terms(term)\n )`;\n // GIN filter first, then rank only a bounded recent match window.\n const candidateLimit = Math.min(\n MAX_LEXICAL_RANK_CANDIDATES,\n args.limit * LEXICAL_RANK_WINDOW_MULTIPLIER,\n );\n const candidates = args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(predicate, sql`${juniorMemoryMemories.searchVector} @@ ${tsquery}`),\n )\n .orderBy(\n desc(juniorMemoryMemories.observedAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(candidateLimit)\n .as(\"lexical_candidates\");\n const textRank = sql<number>`ts_rank_cd(${candidates.searchVector}, ${tsquery})`;\n const rows = await args.db\n .select({\n memory: {\n archiveReason: candidates.archiveReason,\n archivedAtMs: candidates.archivedAtMs,\n content: candidates.content,\n createdAtMs: candidates.createdAtMs,\n expiresAtMs: candidates.expiresAtMs,\n id: candidates.id,\n idempotencyKey: candidates.idempotencyKey,\n kind: candidates.kind,\n observedAtMs: candidates.observedAtMs,\n scope: candidates.scope,\n scopeKey: candidates.scopeKey,\n searchVector: candidates.searchVector,\n sourceKey: candidates.sourceKey,\n sourcePlatform: candidates.sourcePlatform,\n subjectKey: candidates.subjectKey,\n subjectType: candidates.subjectType,\n supersededAtMs: candidates.supersededAtMs,\n supersededById: candidates.supersededById,\n },\n textRank,\n })\n .from(candidates)\n .orderBy(desc(textRank), desc(candidates.observedAtMs), asc(candidates.id))\n .limit(args.limit);\n const ranks = denseRanks(rows, (row) => Number(row.textRank));\n return rows.map((row, index) => ({\n lexical: { rank: ranks[index] },\n memory: parseMemoryRow(row.memory),\n }));\n}\n\n/** Search active visible records with pgvector cosine distance. */\nasync function searchVisibleVectorMemories(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\n limit: number;\n maxDistance?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryMatch[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const embedding = args.embedding;\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n embedding.vector,\n );\n // Push distance cutoff into SQL so recall does not overfetch weak neighbors.\n const distancePredicate =\n args.maxDistance === undefined\n ? undefined\n : sql`${distance} <= ${args.maxDistance}`;\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 ...(distancePredicate ? [distancePredicate] : []),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(args.limit);\n const ranks = denseRanks(rows, (row) => Number(row.distance));\n return rows.flatMap((row, index) => {\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 return [\n {\n memory: parseMemoryRow(row.memory),\n vector: {\n rank: ranks[index],\n },\n },\n ];\n });\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 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 async function reuseDuplicateMemory(args: {\n content: string;\n duplicate: MemoryRecord;\n idempotencyKey?: string;\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n }): Promise<CreateMemoryResult> {\n await rememberDuplicateIdempotency({\n ...args,\n db,\n runtimeContext,\n });\n await storeEmbedding({\n content: args.duplicate.content,\n db,\n embedder,\n memoryId: args.duplicate.id,\n nowMs: args.nowMs,\n });\n return { created: false, memory: args.duplicate };\n }\n\n /** Persist a memory under the plugin-derived scope and subject. */\n async function createScopedMemory(\n rawInput: CreateMemoryInput,\n subjectType: ResolvedMemorySubject[\"subjectType\"],\n ): Promise<CreateMemoryResult> {\n const input = createMemoryInputSchema.parse(rawInput);\n const nowMs = getNowMs();\n const content = normalizeContent(input.content);\n const scope = deriveMemoryScope(runtimeContext);\n const subject = deriveMemorySubject(runtimeContext, subjectType);\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.memory.content,\n db,\n embedder,\n memoryId: idempotent.memory.id,\n nowMs,\n });\n return idempotent.outcome === \"created\"\n ? { created: false, idempotent: true, memory: idempotent.memory }\n : { created: false, memory: idempotent.memory };\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 return await reuseDuplicateMemory({\n content,\n duplicate: exactDuplicate,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n subject,\n });\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 let supersededIds: string[] = [];\n if (\n subjectType === \"user\" &&\n input.kind === \"preference\" &&\n supersessionDecider &&\n (input.expiresAtMs === undefined || input.expiresAtMs > nowMs)\n ) {\n const preferenceCandidates = await listPreferenceAdjudicationCandidates({\n db,\n ...(candidateEmbedding ? { embedding: candidateEmbedding } : undefined),\n nowMs,\n scope,\n subject,\n });\n const adjudication = await adjudicatePreferenceCandidate({\n candidates: preferenceCandidates,\n content,\n decider: supersessionDecider,\n runtimeContext,\n });\n if (adjudication.decision === \"duplicate\") {\n return await reuseDuplicateMemory({\n content,\n duplicate: adjudication.memory,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n subject,\n });\n }\n if (adjudication.decision === \"supersede\") {\n supersededIds = adjudication.ids;\n }\n }\n\n const id = randomUUID();\n const write = 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 locationId: runtimeContext.locationId,\n observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: storedMemorySource(runtimeContext.source),\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, supersededIds: [] };\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, supersededIds: idsToClean };\n });\n if (write.inserted[0]) {\n const memory = parseMemoryRow(write.inserted[0]);\n await storeEmbedding({\n content: memory.content,\n db,\n embedder,\n embedding: candidateEmbedding,\n memoryId: memory.id,\n nowMs,\n });\n return {\n created: true,\n memory,\n ...(write.supersededIds.length > 0\n ? { supersededIds: write.supersededIds }\n : undefined),\n };\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.memory.content,\n db,\n embedder,\n memoryId: idempotent.memory.id,\n nowMs,\n });\n return idempotent.outcome === \"created\"\n ? { created: false, idempotent: true, memory: idempotent.memory }\n : { created: false, memory: idempotent.memory };\n }\n\n /**\n * Hybrid retrieval for both automatic recall and explicit search.\n *\n * Keep both legs parallel and fuse ranks with RRF. Never skip lexical when\n * vectors already hit: that drops exact/token memories and serializes the\n * miss path. Each leg is a hard-capped top-k probe so Postgres work stays\n * bounded even on broad queries.\n *\n * Automatic recall also searches private memory by itself. This keeps newer\n * public memory with common words from hiding older private memory.\n */\n async function retrieveVisibleMemories(\n rawInput: SearchMemoriesInput,\n vectorMaxDistance: number | undefined,\n ): Promise<MemoryRecord[]> {\n const input = searchMemoriesInputSchema.parse(rawInput);\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 overfetch =\n vectorMaxDistance === undefined\n ? SEARCH_RETRIEVAL_OVERFETCH\n : RECALL_RETRIEVAL_OVERFETCH;\n const candidateLimit = retrievalLegLimit(limit, overfetch);\n const privateScopes = scopes.filter((scope) => scope.scope === \"private\");\n // Search private memory by itself during recall so public results cannot\n // fill both search windows.\n const probePrivate =\n vectorMaxDistance !== undefined && privateScopes.length > 0;\n const query = normalizeRetrievalQuery(input.query);\n let queryEmbedding: MemoryEmbedding | undefined;\n if (embedder && query) {\n try {\n queryEmbedding = await embedOne(embedder, query);\n } catch {\n queryEmbedding = undefined;\n }\n }\n const emptyMatches = Promise.resolve([] as MemoryMatch[]);\n const lexicalArgs = {\n db,\n limit: candidateLimit,\n nowMs,\n query: input.query,\n };\n // Always run both legs in parallel. Conditional lexical skip is unsafe:\n // one in-threshold vector distractor can hide a stronger lexical hit.\n // Embed once up front; vector probes only run when that embedding exists.\n const matches = await Promise.all([\n queryEmbedding\n ? searchVisibleVectorMemories({\n db,\n embedding: queryEmbedding,\n limit: candidateLimit,\n ...(vectorMaxDistance !== undefined\n ? { maxDistance: vectorMaxDistance }\n : undefined),\n nowMs,\n scopes,\n })\n : emptyMatches,\n searchVisibleLexicalMemories({\n ...lexicalArgs,\n scopes,\n }),\n queryEmbedding && probePrivate\n ? searchVisibleVectorMemories({\n db,\n embedding: queryEmbedding,\n limit: candidateLimit,\n maxDistance: vectorMaxDistance,\n nowMs,\n scopes: privateScopes,\n })\n : emptyMatches,\n probePrivate\n ? searchVisibleLexicalMemories({\n ...lexicalArgs,\n scopes: privateScopes,\n })\n : emptyMatches,\n ]);\n return rankMemoryMatches(matches.flat(), {\n nowMs,\n // Slight lexical preference protects exact ids/names/timezones on ties.\n ...(vectorMaxDistance === undefined\n ? undefined\n : { lexicalWeight: 1, vectorWeight: 0.85 }),\n })\n .slice(0, limit)\n .map(({ memory }) => memory);\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, \"user\");\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 recallMemories(input) {\n return await retrieveVisibleMemories(input, RECALL_MAX_VECTOR_DISTANCE);\n },\n\n async searchMemories(input) {\n return await retrieveVisibleMemories(input, undefined);\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","/**\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 customType,\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\nconst tsvector = customType<{ data: string }>({\n dataType() {\n return \"tsvector\";\n },\n});\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 searchVector: tsvector(\"search_vector\").generatedAlwaysAs(\n sql`to_tsvector('english', \"content\")`,\n ),\n sourcePlatform: text(\"source_platform\", {\n enum: MEMORY_SOURCE_PLATFORMS,\n }).notNull(),\n sourceKey: text(\"source_key\").notNull(),\n /** Location where Junior learned the memory, when known. */\n locationId: text(\"location_id\"),\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 index(\"junior_memory_memories_search_idx\")\n .using(\"gin\", table.scope, table.scopeKey, table.searchVector)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS 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 ('private', 'public')`,\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', 'web')`,\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 // Cosine ANN for vector recall/search. Ops must match cosineDistance (<=>).\n // Keep this unfiltered so planners can use HNSW before scope/status joins.\n index(\"junior_memory_embeddings_embedding_hnsw_idx\")\n .using(\"hnsw\", table.embedding.op(\"vector_cosine_ops\"))\n .with({ m: 16, ef_construction: 64 }),\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 { actorSchema, sourceSchema } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\n\nexport const MEMORY_KINDS = [\"preference\", \"procedure\", \"knowledge\"] as const;\n\nexport const MEMORY_SCOPES = [\"private\", \"public\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\n// Durable attribution follows Source kind, including dashboard roots.\nexport const MEMORY_SOURCE_PLATFORMS = [\"slack\", \"local\", \"web\"] as const;\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/** Host data used to set memory access, subject, and source. */\nexport const memoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n locationId: nonEmptyStringSchema.optional(),\n actor: actorSchema.optional(),\n source: sourceSchema,\n /** User linked to the active Actor. */\n userId: nonEmptyStringSchema.optional(),\n })\n .strict();\n\nexport type MemoryRuntimeContext = z.output<typeof memoryRuntimeContextSchema>;\n","import type { MemoryRecord } from \"./store\";\n\nconst RECIPROCAL_RANK_FUSION_K = 60;\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst DEFAULT_RRF_WEIGHT = 1;\n\nexport interface MemoryMatch {\n lexical?: {\n rank: number;\n };\n memory: MemoryRecord;\n vector?: {\n rank: number;\n };\n}\n\nfunction reciprocalRank(rank: number, weight: number): number {\n return weight / (RECIPROCAL_RANK_FUSION_K + rank);\n}\n\nfunction matchScore(\n match: MemoryMatch,\n weights: { lexicalWeight: number; vectorWeight: number },\n): number {\n return (\n (match.vector\n ? reciprocalRank(match.vector.rank, weights.vectorWeight)\n : 0) +\n (match.lexical\n ? reciprocalRank(match.lexical.rank, weights.lexicalWeight)\n : 0)\n );\n}\n\nfunction observedAgeRank(memory: MemoryRecord, nowMs: number): number {\n const ageMs = Math.max(0, nowMs - memory.observedAtMs);\n if (ageMs <= 7 * ONE_DAY_MS) {\n return 3;\n }\n if (ageMs <= 30 * ONE_DAY_MS) {\n return 2;\n }\n if (ageMs <= 90 * ONE_DAY_MS) {\n return 1;\n }\n return 0;\n}\n\nfunction positiveWeight(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isFinite(value) && value > 0\n ? value\n : fallback;\n}\n\n/** Fuse lexical and vector ranks without comparing provider raw scores. */\nexport function rankMemoryMatches(\n matches: MemoryMatch[],\n options: {\n /** Optional RRF weight for the lexical leg. Defaults to 1. */\n lexicalWeight?: number;\n nowMs: number;\n /** Optional RRF weight for the vector leg. Defaults to 1. */\n vectorWeight?: number;\n },\n): MemoryMatch[] {\n const weights = {\n lexicalWeight: positiveWeight(options.lexicalWeight, DEFAULT_RRF_WEIGHT),\n vectorWeight: positiveWeight(options.vectorWeight, DEFAULT_RRF_WEIGHT),\n };\n const byId = new Map<string, MemoryMatch>();\n for (const match of matches) {\n const existing = byId.get(match.memory.id);\n if (!existing) {\n byId.set(match.memory.id, match);\n continue;\n }\n // Keep the first rank from each search. The shared searches run first, so\n // the smaller private searches cannot replace their ranks.\n byId.set(match.memory.id, {\n ...existing,\n ...(!existing.lexical && match.lexical\n ? { lexical: match.lexical }\n : undefined),\n ...(!existing.vector && match.vector ? { vector: match.vector } : undefined),\n });\n }\n return [...byId.values()].sort((left, right) => {\n const scoreDelta = matchScore(right, weights) - matchScore(left, weights);\n if (scoreDelta !== 0) {\n return scoreDelta;\n }\n // Prefer private memory when RRF ties. Public and private searches can give\n // the same rank to common words.\n const privateDelta =\n Number(right.memory.scope === \"private\") -\n Number(left.memory.scope === \"private\");\n if (privateDelta !== 0) {\n return privateDelta;\n }\n return (\n observedAgeRank(right.memory, options.nowMs) -\n observedAgeRank(left.memory, options.nowMs) ||\n right.memory.observedAtMs - left.memory.observedAtMs ||\n left.memory.id.localeCompare(right.memory.id)\n );\n });\n}\n","import type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\nconst PUBLIC_SCOPE_KEY = \"public\";\n\n/** Stored memory access rule. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** What a stored memory is about. */\nexport interface ResolvedMemorySubject {\n subjectKey: string;\n subjectType: Extract<MemorySubjectType, \"user\" | \"conversation\">;\n}\n\n/** Public memories are visible everywhere. */\nexport const publicMemoryScope: ResolvedMemoryScope = {\n scope: \"public\",\n scopeKey: PUBLIC_SCOPE_KEY,\n};\n\nfunction privateMemoryScope(userId: string): ResolvedMemoryScope {\n return { scope: \"private\", scopeKey: userId };\n}\n\n/** Set memory access from the Source. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope {\n if (\"visibility\" in ctx.source && ctx.source.visibility === \"public\") {\n return publicMemoryScope;\n }\n if (!ctx.userId) {\n throw new Error(\"Private memory requires a User.\");\n }\n return privateMemoryScope(ctx.userId);\n}\n\n/** Set what a memory is about. Access is set separately. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n subjectType: Extract<MemorySubjectType, \"user\" | \"conversation\">,\n): ResolvedMemorySubject {\n if (subjectType === \"user\") {\n if (!ctx.userId) {\n throw new Error(\"User memory requires a User.\");\n }\n return { subjectType, subjectKey: ctx.userId };\n }\n const subjectKey = ctx.conversationId;\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return {\n subjectType,\n subjectKey,\n };\n}\n\n/** Return the memory scopes that the current User can access. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n if (!ctx.userId) {\n return [publicMemoryScope];\n }\n return [publicMemoryScope, privateMemoryScope(ctx.userId)];\n}\n","/**\n * Authenticated REST access to memory.\n *\n * The signed-in User can read public memory and private memory that they own.\n */\nimport { z } from \"zod\";\nimport {\n pluginApiRouteRequestContextSchema,\n type PluginConversationEventStats,\n type PluginRouteApp,\n type User,\n} from \"@sentry/junior-plugin-api\";\nimport type { MemoryDb } from \"./store\";\nimport {\n archiveMemory,\n getMemory,\n getMemoryStats,\n getMemoryTimeline,\n getMemoryTimelineHours,\n InvalidMemoryCursorError,\n listMemories,\n MemoryNotFoundError,\n type MemoryView,\n} from \"./viewer\";\nimport { MEMORY_SOURCE_PLATFORMS } from \"./types\";\n\nexport const memoryApiSchema = z\n .object({\n content: z.string().min(1),\n createdAt: z.iso.datetime(),\n expiresAt: z.iso.datetime().optional(),\n id: z.string().min(1),\n kind: z.enum([\"preference\", \"procedure\", \"knowledge\"]),\n observedAt: z.iso.datetime(),\n origin: z.enum([\"automatic\", \"explicit\", \"other\"]),\n sourcePlatform: z.enum(MEMORY_SOURCE_PLATFORMS),\n visibility: z.enum([\"private\", \"public\"]),\n })\n .strict();\n\nexport const memoryListResponseSchema = z\n .object({\n memories: z.array(memoryApiSchema),\n nextCursor: z.string().min(1).optional(),\n })\n .strict();\n\nconst memoryBucketSchema = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}(T\\d{2})?$/);\n\nconst memoryDashboardDaySchema = z\n .object({\n date: memoryBucketSchema,\n personal: z.number().int().min(0),\n public: z.number().int().min(0),\n })\n .strict();\n\nconst memoryCostDaySchema = z\n .object({\n costUsd: z.number().finite().nonnegative(),\n date: memoryBucketSchema,\n events: z.number().int().min(0),\n })\n .strict();\n\nexport const memoryDashboardResponseSchema = z\n .object({\n days: z.array(memoryDashboardDaySchema).length(90),\n extractionDays: z.array(memoryCostDaySchema).length(90),\n extractionHours: z.array(memoryCostDaySchema).min(24).optional(),\n generatedAt: z.iso.datetime(),\n hours: z.array(memoryDashboardDaySchema).min(24).optional(),\n recallDays: z.array(memoryCostDaySchema).length(90),\n recallHours: z.array(memoryCostDaySchema).min(24).optional(),\n stats: z\n .object({\n active: z.number().int().min(0),\n automatic: z.number().int().min(0),\n createdThirtyDays: z.number().int().min(0),\n embedded: z.number().int().min(0),\n explicit: z.number().int().min(0),\n knowledge: z.number().int().min(0),\n personal: z.number().int().min(0),\n preference: z.number().int().min(0),\n procedure: z.number().int().min(0),\n public: z.number().int().min(0),\n })\n .strict(),\n })\n .strict();\n\nexport type MemoryApi = z.output<typeof memoryApiSchema>;\nexport type MemoryDashboardResponse = z.output<\n typeof memoryDashboardResponseSchema\n>;\nexport type MemoryListResponse = z.output<typeof memoryListResponseSchema>;\n\nconst memoryListQuerySchema = z\n .object({\n cursor: z.string().min(1).max(1_000).optional(),\n limit: z.coerce.number().int().min(1).max(50).default(25),\n q: z.string().trim().max(200).optional(),\n })\n .strict();\n\ninterface MemoryApiOptions {\n db: MemoryDb;\n eventStats: PluginConversationEventStats;\n users: {\n resolve(email: string): Promise<User | undefined>;\n };\n}\n\nfunction json(body: unknown, status = 200): Response {\n return Response.json(body, {\n headers: { \"cache-control\": \"no-store\" },\n status,\n });\n}\n\nfunction apiMemory(memory: MemoryView): z.output<typeof memoryApiSchema> {\n return {\n content: memory.content,\n createdAt: new Date(memory.createdAtMs).toISOString(),\n ...(memory.expiresAtMs !== undefined\n ? { expiresAt: new Date(memory.expiresAtMs).toISOString() }\n : undefined),\n id: memory.id,\n kind: memory.kind,\n observedAt: new Date(memory.observedAtMs).toISOString(),\n origin: memory.origin,\n sourcePlatform: memory.sourcePlatform,\n visibility: memory.visibility,\n };\n}\n\nfunction viewerEmail(context: unknown): string | undefined {\n const parsed = pluginApiRouteRequestContextSchema.safeParse(context);\n if (!parsed.success || parsed.data.auth.user.emailVerified !== true) {\n return undefined;\n }\n return parsed.data.auth.user.email?.trim().toLowerCase() || undefined;\n}\n\n/** Create the authenticated memory REST app. */\nexport function createMemoryApi(options: MemoryApiOptions): PluginRouteApp {\n return {\n async fetch(request, context) {\n const email = viewerEmail(context);\n if (!email) {\n return json({ error: \"Authentication required.\" }, 401);\n }\n\n const url = new URL(request.url);\n const memoryPath = /^\\/memories\\/([^/]+)$/.exec(url.pathname);\n const isCollection = url.pathname === \"/memories\";\n const isDashboard = url.pathname === \"/dashboard\";\n if (!isCollection && !isDashboard && !memoryPath) {\n return json({ error: \"Not found.\" }, 404);\n }\n const isRead = request.method === \"GET\" || request.method === \"HEAD\";\n if (!isRead && !(memoryPath && request.method === \"DELETE\")) {\n return json({ error: \"Method not allowed.\" }, 405);\n }\n\n const viewer = await options.users.resolve(email);\n if (!viewer) return json({ error: \"Authentication required.\" }, 401);\n const userId = viewer.id;\n\n try {\n if (isDashboard && isRead) {\n const [\n stats,\n days,\n hours,\n extractionDays,\n extractionHours,\n recallDays,\n recallHours,\n ] = await Promise.all([\n getMemoryStats(options.db, userId),\n getMemoryTimeline(options.db, userId, 90),\n getMemoryTimelineHours(options.db, userId, 7 * 24),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_captured\",\n }),\n options.eventStats.costsByHour({\n eventName: \"memories_captured\",\n hours: 7 * 24,\n }),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_recalled\",\n }),\n options.eventStats.costsByHour({\n eventName: \"memories_recalled\",\n hours: 7 * 24,\n }),\n ]);\n const { private: personal, ...dashboardStats } = stats;\n const body = memoryDashboardResponseSchema.parse({\n days: days.map(({ private: personal, ...day }) => ({\n ...day,\n personal,\n })),\n extractionDays,\n extractionHours,\n generatedAt: new Date().toISOString(),\n hours: hours.map(({ private: personal, ...day }) => ({\n ...day,\n personal,\n })),\n recallDays,\n recallHours,\n stats: { ...dashboardStats, personal },\n });\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(body);\n }\n\n if (isCollection && isRead) {\n const query = memoryListQuerySchema.parse({\n cursor: url.searchParams.get(\"cursor\") ?? undefined,\n limit: url.searchParams.get(\"limit\") ?? undefined,\n q: url.searchParams.get(\"q\") ?? undefined,\n });\n const page = await listMemories(options.db, userId, {\n cursor: query.cursor,\n limit: query.limit,\n ...(query.q ? { query: query.q } : undefined),\n });\n const body = memoryListResponseSchema.parse({\n memories: page.memories.map(apiMemory),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : undefined),\n });\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(body);\n }\n\n if (memoryPath && isRead) {\n const memory = await getMemory(\n options.db,\n userId,\n decodeURIComponent(memoryPath[1]!),\n );\n const body = memoryApiSchema.parse(apiMemory(memory));\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(body);\n }\n\n if (memoryPath && request.method === \"DELETE\") {\n const id = decodeURIComponent(memoryPath[1]!);\n await archiveMemory(options.db, userId, id);\n return new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 204,\n });\n }\n } catch (error) {\n if (\n error instanceof z.ZodError ||\n error instanceof InvalidMemoryCursorError\n ) {\n return json({ error: \"Invalid memory request.\" }, 400);\n }\n if (error instanceof MemoryNotFoundError) {\n return json({ error: error.message }, 404);\n }\n throw error;\n }\n\n return json({ error: \"Method not allowed.\" }, 405);\n },\n };\n}\n","/**\n * Memory access for an authenticated User.\n *\n * Every User can read public memory and private memory that they own.\n */\nimport {\n and,\n asc,\n desc,\n eq,\n gt,\n ilike,\n isNull,\n like,\n lt,\n or,\n sql,\n} from \"drizzle-orm\";\nimport { z } from \"zod\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport { publicMemoryScope } from \"./scope\";\nimport { parseMemoryRow, type MemoryDb, type MemoryRecord } from \"./store\";\nimport { MEMORY_KINDS, type MemorySourcePlatform } from \"./types\";\n\nconst DAY_MS = 24 * 60 * 60 * 1_000;\nconst nonEmptyStringSchema = z.string().min(1);\nconst memoryVisibilitySchema = z.enum([\"private\", \"public\"]);\nconst cursorSchema = z\n .object({\n createdAtMs: z.number().finite(),\n id: nonEmptyStringSchema,\n kind: z.enum(MEMORY_KINDS).optional(),\n origin: z.enum([\"automatic\", \"explicit\"]).optional(),\n query: z.string().max(200).optional(),\n version: z.literal(1),\n visibility: memoryVisibilitySchema.optional(),\n })\n .strict();\nconst pageInputSchema = z\n .object({\n cursor: z.string().min(1).max(1_000).optional(),\n kind: z.enum(MEMORY_KINDS).optional(),\n limit: z.number().int().min(1).max(50),\n origin: z.enum([\"automatic\", \"explicit\"]).optional(),\n query: z.string().max(200).optional(),\n visibility: memoryVisibilitySchema.optional(),\n })\n .strict();\nconst timelineDaysSchema = z.number().int().min(1).max(365);\n\n/** Access label returned by dashboard and REST memory views. */\nexport type MemoryVisibility = z.output<typeof memoryVisibilitySchema>;\n\n/** Memory fields returned to an authenticated User. */\nexport type MemoryView = MemoryRecord & {\n origin: \"automatic\" | \"explicit\" | \"other\";\n sourcePlatform: MemorySourcePlatform;\n visibility: MemoryVisibility;\n};\n\ninterface MemoryPage {\n memories: MemoryView[];\n nextCursor?: string;\n}\n\ntype MemoryPageInput = z.output<typeof pageInputSchema>;\n\n/** Expected error for a malformed or mismatched page cursor. */\nexport class InvalidMemoryCursorError extends Error {\n constructor() {\n super(\"Memory cursor is invalid.\");\n this.name = \"InvalidMemoryCursorError\";\n }\n}\n\n/** Expected error when the current User cannot access a memory. */\nexport class MemoryNotFoundError extends Error {\n constructor() {\n super(\"Memory was not found for this user.\");\n this.name = \"MemoryNotFoundError\";\n }\n}\n\nfunction publicScopePredicate() {\n return and(\n eq(juniorMemoryMemories.scope, publicMemoryScope.scope),\n eq(juniorMemoryMemories.scopeKey, publicMemoryScope.scopeKey),\n );\n}\n\nfunction privateScopePredicate(userId: string) {\n return and(\n eq(juniorMemoryMemories.scope, \"private\"),\n eq(juniorMemoryMemories.scopeKey, userId),\n );\n}\n\nfunction visibleScopePredicate(userId: string, visibility?: MemoryVisibility) {\n if (visibility === \"public\") return publicScopePredicate();\n if (visibility === \"private\") return privateScopePredicate(userId);\n return or(publicScopePredicate(), privateScopePredicate(userId));\n}\n\nfunction activeMemoryPredicate(\n userId: string,\n nowMs: number,\n visibility?: MemoryVisibility,\n) {\n return and(\n visibleScopePredicate(userId, visibility),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, nowMs),\n ),\n );\n}\n\nfunction utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\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\nfunction memoryOrigin(idempotencyKey: string | null): MemoryView[\"origin\"] {\n if (idempotencyKey?.startsWith(\"session:\")) return \"automatic\";\n if (idempotencyKey?.startsWith(\"tool:\")) return \"explicit\";\n return \"other\";\n}\n\nfunction toMemoryView(\n row: typeof juniorMemoryMemories.$inferSelect,\n): MemoryView {\n const memory = parseMemoryRow(row);\n return {\n ...memory,\n origin: memoryOrigin(row.idempotencyKey),\n sourcePlatform: row.sourcePlatform,\n visibility: memory.scope,\n };\n}\n\nfunction cursorFilters(input: MemoryPageInput) {\n return {\n kind: input.kind,\n origin: input.origin,\n query: input.query?.trim() || undefined,\n visibility: input.visibility,\n };\n}\n\nfunction decodeCursor(\n value: string | undefined,\n filters: ReturnType<typeof cursorFilters>,\n) {\n if (!value) return undefined;\n try {\n const parsed = cursorSchema.parse(\n JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\")),\n );\n if (\n parsed.query !== filters.query ||\n parsed.kind !== filters.kind ||\n parsed.origin !== filters.origin ||\n parsed.visibility !== filters.visibility\n ) {\n throw new InvalidMemoryCursorError();\n }\n return { createdAtMs: parsed.createdAtMs, id: parsed.id };\n } catch {\n throw new InvalidMemoryCursorError();\n }\n}\n\nfunction encodeCursor(\n createdBefore: { createdAtMs: number; id: string },\n filters: ReturnType<typeof cursorFilters>,\n): string {\n return Buffer.from(\n JSON.stringify({ ...createdBefore, ...filters, version: 1 }),\n \"utf8\",\n ).toString(\"base64url\");\n}\n\n/** Archive one active memory visible to the authenticated User: public memory or private memory they own. */\nexport async function archiveMemory(db: MemoryDb, userId: string, id: string) {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = Date.now();\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: \"user_removed\",\n })\n .where(\n and(\n activeMemoryPredicate(userId, nowMs),\n eq(juniorMemoryMemories.id, memoryId),\n ),\n )\n .returning();\n if (!updated[0]) throw new MemoryNotFoundError();\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memoryId));\n return parseMemoryRow(updated[0]);\n}\n\n/** Read one active memory visible to the authenticated User. */\nexport async function getMemory(\n db: MemoryDb,\n userId: string,\n id: string,\n): Promise<MemoryView> {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = Date.now();\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n activeMemoryPredicate(userId, nowMs),\n eq(juniorMemoryMemories.id, memoryId),\n ),\n )\n .limit(1);\n if (!rows[0]) throw new MemoryNotFoundError();\n return toMemoryView(rows[0]);\n}\n\n/** List one stable page of active memory visible to the authenticated User. */\nexport async function listMemories(\n db: MemoryDb,\n userId: string,\n input: MemoryPageInput,\n): Promise<MemoryPage> {\n input = pageInputSchema.parse(input);\n const filters = cursorFilters(input);\n const cursor = decodeCursor(input.cursor, filters);\n const active = activeMemoryPredicate(userId, Date.now(), input.visibility);\n const createdBefore = cursor\n ? or(\n lt(juniorMemoryMemories.createdAtMs, cursor.createdAtMs),\n and(\n eq(juniorMemoryMemories.createdAtMs, cursor.createdAtMs),\n gt(juniorMemoryMemories.id, cursor.id),\n ),\n )\n : undefined;\n const terms = input.query ? searchTerms(input.query) : [];\n const search =\n input.query === undefined\n ? undefined\n : terms.length === 0\n ? sql`false`\n : or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n );\n const kind = input.kind\n ? eq(juniorMemoryMemories.kind, input.kind)\n : undefined;\n const origin =\n input.origin === \"automatic\"\n ? like(juniorMemoryMemories.idempotencyKey, \"session:%\")\n : input.origin === \"explicit\"\n ? like(juniorMemoryMemories.idempotencyKey, \"tool:%\")\n : undefined;\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(active, createdBefore, search, kind, origin))\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(input.limit + 1);\n const memories = rows.slice(0, input.limit).map(toMemoryView);\n const last = memories.at(-1);\n if (rows.length <= input.limit || !last) return { memories };\n const next = { createdAtMs: last.createdAtMs, id: last.id };\n return { memories, nextCursor: encodeCursor(next, filters) };\n}\n\n/** Summarize active memory visible to the authenticated User. */\nexport async function getMemoryStats(db: MemoryDb, userId: string) {\n const nowMs = Date.now();\n const [counts] = await db\n .select({\n active: sql<number>`count(*)`.mapWith(Number),\n automatic:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.idempotencyKey} like 'session:%')`.mapWith(\n Number,\n ),\n createdThirtyDays:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.createdAtMs} >= ${nowMs - 30 * DAY_MS})`.mapWith(\n Number,\n ),\n embedded: sql<number>`count(${juniorMemoryEmbeddings.memoryId})`.mapWith(\n Number,\n ),\n explicit:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.idempotencyKey} like 'tool:%')`.mapWith(\n Number,\n ),\n knowledge:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.kind} = 'knowledge')`.mapWith(\n Number,\n ),\n private:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n preference:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.kind} = 'preference')`.mapWith(\n Number,\n ),\n procedure:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.kind} = 'procedure')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .leftJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(activeMemoryPredicate(userId, nowMs));\n if (!counts) throw new Error(\"Memory stats query returned no row.\");\n return counts;\n}\n\n/** Read daily memory creation totals visible to the authenticated User in UTC. */\nexport async function getMemoryTimeline(\n db: MemoryDb,\n userId: string,\n days: number,\n) {\n days = timelineDaysSchema.parse(days);\n const todayMs = Date.parse(`${utcDate(Date.now())}T00:00:00.000Z`);\n const startMs = todayMs - (days - 1) * DAY_MS;\n const rows = await db\n .select({\n date: sql<string>`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD')`.as(\n \"date\",\n ),\n private:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .where(\n and(\n visibleScopePredicate(userId),\n gt(juniorMemoryMemories.createdAtMs, startMs - 1),\n ),\n )\n .groupBy(\n sql`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD')`,\n );\n const byDate = new Map(rows.map((row) => [row.date, row]));\n return Array.from({ length: days }, (_, index) => {\n const date = utcDate(startMs + index * DAY_MS);\n const row = byDate.get(date);\n return {\n date,\n private: row?.private ?? 0,\n public: row?.public ?? 0,\n };\n });\n}\n\n/** Read hourly memory creation totals visible to the authenticated User in UTC. */\nexport async function getMemoryTimelineHours(\n db: MemoryDb,\n userId: string,\n hours = 24,\n) {\n const end = new Date();\n end.setUTCMinutes(0, 0, 0);\n const startMs = end.getTime() - (hours - 1) * 60 * 60 * 1_000;\n const rows = await db\n .select({\n date: sql<string>`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24')`.as(\n \"date\",\n ),\n private:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .where(\n and(\n visibleScopePredicate(userId),\n gt(juniorMemoryMemories.createdAtMs, startMs - 1),\n ),\n )\n .groupBy(\n sql`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24')`,\n );\n const byHour = new Map(rows.map((row) => [row.date, row]));\n return Array.from({ length: hours }, (_, index) => {\n const date = new Date(startMs + index * 60 * 60 * 1_000)\n .toISOString()\n .slice(0, 13);\n const row = byHour.get(date);\n return {\n date,\n private: row?.private ?? 0,\n public: row?.public ?? 0,\n };\n });\n}\n\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","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 PluginToolOutput,\n type Source,\n type Actor,\n type Identity,\n type User,\n pluginToolOutputSchema,\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 \"Private memory requires a User.\",\n \"User memory requires a User.\",\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 locationId?: string;\n actor?: Actor;\n source: Source;\n users: {\n resolveActor(): Promise<{ identity: Identity; user?: User } | undefined>;\n };\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\nasync function memoryRuntimeContext(\n context: MemoryToolContext,\n): Promise<MemoryRuntimeContext> {\n const actorUser = (await context.users.resolveActor())?.user;\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : undefined),\n ...(context.actor ? { actor: context.actor } : undefined),\n ...(context.locationId ? { locationId: context.locationId } : undefined),\n source: context.source,\n ...(actorUser ? { userId: actorUser.id } : undefined),\n });\n}\n\nfunction memoryStore(\n context: MemoryToolContext,\n runtimeContext: MemoryRuntimeContext,\n options: { supersessionDecider?: MemorySupersessionDecider } = {},\n) {\n return createMemoryStore(context.db, runtimeContext, {\n embedder: context.embedder,\n ...(options.supersessionDecider\n ? { supersessionDecider: options.supersessionDecider }\n : undefined),\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 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 archiveMemoryInputSchema = 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 PluginToolOutput &\n TData & {\n target: string;\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 memoryCreateOutputSchema = pluginToolOutputSchema.extend({\n target: z.string(),\n created: z.boolean(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memorySingleOutputSchema = pluginToolOutputSchema.extend({\n target: z.string(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memoryManyOutputSchema = pluginToolOutputSchema.extend({\n target: z.string(),\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 : undefined),\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 : undefined),\n });\n}\n\nfunction memoryToolResult<TData extends Record<string, unknown>>(\n target: string,\n data: TData,\n): MemoryStructuredToolResult<TData> {\n return {\n target,\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 approvalMode: \"approve\",\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n },\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 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. Junior sets access, Location, Source, and subject. The memory agent rewrites the content and sets the memory 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 = await memoryRuntimeContext(context);\n const store = memoryStore(context, runtimeContext, {\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 : undefined),\n runtimeContext,\n ...(context.userText?.trim()\n ? {\n sourceContext: {\n currentUserText: context.userText.trim(),\n },\n }\n : undefined),\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 createMemoryArchiveTool(context: MemoryToolContext) {\n return definePluginTool({\n annotations: {\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n },\n description:\n \"Forget one active memory visible in the current context. This includes public memories and private memories owned by the current User. Use only ids or short id prefixes returned by listMemories or searchMemories. Never remove memories by hidden Actor, provider, scope, or subject ids.\",\n executionMode: \"sequential\",\n inputSchema: archiveMemoryInputSchema,\n outputSchema: memorySingleOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(\n archiveMemoryInputSchema,\n input,\n );\n const runtimeContext = await memoryRuntimeContext(context);\n const memory = await (async () => {\n try {\n return await memoryStore(context, runtimeContext).archiveMemory({\n id: parsedInput.id,\n reason: \"tool_removed\",\n });\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"archiveMemory\", {\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: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n },\n inputSchema: listMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(listMemoriesInputSchema, input);\n const runtimeContext = await memoryRuntimeContext(context);\n const memories = await memoryStore(context, runtimeContext).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. Public memories are visible everywhere. Private memories belong to the current User.\",\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n },\n inputSchema: searchMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(\n searchMemoriesInputSchema,\n input,\n );\n const runtimeContext = await memoryRuntimeContext(context);\n const memories = await memoryStore(\n context,\n runtimeContext,\n ).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","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\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 CreateMemoryResult,\n type MemoryDb,\n} from \"./store\";\nimport {\n createMemoryAgent,\n parseExtractedMemory,\n type ExtractedMemory,\n type MemoryExtractionResult,\n} from \"./agent\";\nimport { MEMORY_KINDS, memoryRuntimeContextSchema } from \"./types\";\nimport { capturedMemory, memoriesCapturedEvent } from \"./events\";\n\nconst MEMORY_TOOL_NAMES = new Set([\n \"archiveMemory\",\n \"createMemory\",\n \"listMemories\",\n \"searchMemories\",\n]);\nconst MEMORY_TASK_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst extractedMemorySchema = 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);\nconst extractedMemoryCacheSchema = z.union([\n z\n .object({\n costUsd: z.number().finite().nonnegative().optional(),\n memories: z.array(extractedMemorySchema).max(5),\n })\n .strict(),\n z\n .array(extractedMemorySchema)\n .max(5)\n .transform((memories) => ({ memories })),\n]);\n\n/** Subject for a passively extracted memory, or drop when unproven. */\ntype MemorySubjectTarget = \"drop\" | \"user\" | \"conversation\";\n\nfunction recordCapturedMemory(\n captured: ReturnType<typeof capturedMemory>[],\n result: CreateMemoryResult,\n): void {\n const supersededIds = new Set(result.supersededIds ?? []);\n for (let index = captured.length - 1; index >= 0; index -= 1) {\n if (supersededIds.has(captured[index]!.id)) {\n captured.splice(index, 1);\n }\n }\n if (result.created || result.idempotent) {\n captured.push(capturedMemory(result.memory));\n }\n}\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\" | \"actorUserId\">,\n): MemorySubjectTarget {\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 human run actor may store a preference.\n const exactlyOneHumanRunActor =\n run.actorUserId !== undefined &&\n run.actor !== undefined &&\n run.actor.platform !== \"system\" &&\n run.actors.length === 1 &&\n run.actors[0]?.platform !== \"system\";\n if (!exactlyOneHumanRunActor) {\n return \"drop\";\n }\n // Never downgrade an unproven first-person preference to conversation subject.\n return cited.entries.every(isRunActorInstruction) ? \"user\" : \"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: MemorySubjectTarget,\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: MemorySubjectTarget,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory, target)}`,\n kind: memory.kind,\n ...(memory.expiresAtMs !== null\n ? { expiresAtMs: memory.expiresAtMs }\n : undefined),\n };\n}\n\nasync function getTaskExtraction(\n context: PluginTaskContext,\n extract: () => Promise<MemoryExtractionResult>,\n): Promise<MemoryExtractionResult> {\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 extraction = await extract();\n await context.state.set(cacheKey, extraction, MEMORY_TASK_STATE_TTL_MS);\n return extraction;\n}\n\n/**\n * Extract and store memories from a completed session plugin task.\n *\n * Memory owns learning after a run and reads only the plugin run data.\n * Explicit memory tools stay separate so retries do not reinterpret user\n * requests.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // TODO(dcramer): Replace this hardcoded Source check when a plugin Run can\n // state whether passive memory extraction should run.\n if (run.source.kind !== \"slack\" && run.source.kind !== \"web\") {\n return;\n }\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 const sourceKey = getSourceKey(run.source);\n if (!sourceKey || (run.source.visibility === \"private\" && !run.actorUserId)) {\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.locationId ? { locationId: run.locationId } : undefined),\n ...(run.actor ? { actor: run.actor } : undefined),\n source: run.source,\n ...(run.actorUserId ? { userId: run.actorUserId } : undefined),\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 extraction = await getTaskExtraction(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\n const captured: ReturnType<typeof capturedMemory>[] = [];\n for (const memory of extraction.memories) {\n // The routing gate stays even though extraction is also actor-gated:\n // getTaskExtraction 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 const result = await store.createConversationMemory(input);\n recordCapturedMemory(captured, result);\n continue;\n }\n const result = await store.createMemory(input);\n recordCapturedMemory(captured, result);\n }\n await context.events.emit(\n memoriesCapturedEvent({\n memories: captured,\n ...(extraction.costUsd !== undefined\n ? { costUsd: extraction.costUsd }\n : undefined),\n }),\n );\n}\n","import { defineConversationEvent } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport { MEMORY_KINDS, MEMORY_SCOPES } from \"./types\";\nimport type { MemoryRecord } from \"./store\";\n\nconst capturedMemoryFields = {\n content: z.string().min(1),\n id: z.string().min(1),\n kind: z.enum(MEMORY_KINDS),\n observedAtMs: z.number().finite(),\n};\n\nconst legacyCapturedMemorySchema = z\n .object({\n ...capturedMemoryFields,\n scope: z.enum([\"personal\", \"conversation\"]),\n })\n .strict();\n\nconst capturedMemorySchema = z\n .object({\n ...capturedMemoryFields,\n scope: z.enum(MEMORY_SCOPES),\n })\n .strict();\n\nconst capturedMemoriesSchema = z\n .object({\n memories: z.array(capturedMemorySchema).max(100),\n costUsd: z.number().finite().nonnegative().optional(),\n })\n .strict();\n\nconst recalledMemoriesSchema = z\n .object({\n // Matches the automatic-recall candidate window; admission packs by char budget.\n memories: z.array(z.string().min(1)).max(20),\n costUsd: z.number().finite().nonnegative().optional(),\n })\n .strict();\n\nfunction currentScope(\n scope: \"personal\" | \"conversation\" | \"private\" | \"public\",\n) {\n if (scope === \"personal\") return \"private\";\n if (scope === \"conversation\") return \"public\";\n return scope;\n}\n\nfunction renderCapturedMemories(event: {\n memories: Array<\n | z.output<typeof legacyCapturedMemorySchema>\n | z.output<typeof capturedMemorySchema>\n >;\n}) {\n const count = event.memories.length;\n if (count === 0) return undefined;\n return {\n icon: \"brain\" as const,\n title: `${count} ${count === 1 ? \"memory\" : \"memories\"} captured`,\n details: event.memories.map((memory) => ({\n title: memory.content,\n metadata: [memory.kind, currentScope(memory.scope)],\n })),\n };\n}\n\n/** Previous stored memory-capture event shape retained for transcript rendering. */\nexport const memoriesCapturedEventV1 = defineConversationEvent({\n name: \"memories_captured\",\n version: 1,\n schema: z\n .object({\n memories: z.array(legacyCapturedMemorySchema).min(1).max(100),\n })\n .strict(),\n renderEvent: renderCapturedMemories,\n});\n\n/** Durable outcome emitted after every completed passive memory extraction. */\nexport const memoriesCapturedEvent = defineConversationEvent({\n name: \"memories_captured\",\n version: 2,\n schema: capturedMemoriesSchema,\n renderEvent: renderCapturedMemories,\n});\n\n/** Durable outcome emitted after one completed automatic recall attempt. */\nexport const memoriesRecalledEvent = defineConversationEvent({\n name: \"memories_recalled\",\n version: 1,\n schema: recalledMemoriesSchema,\n renderEvent() {\n return undefined;\n },\n});\n\n/** Select the stable, safe memory fields retained in conversation history. */\nexport function capturedMemory(memory: MemoryRecord) {\n return {\n content: memory.content,\n id: memory.id,\n kind: memory.kind,\n observedAtMs: memory.observedAtMs,\n scope: memory.scope,\n };\n}\n","import {\n definePromptContext,\n type UserPromptContribution,\n type Actor,\n type Identity,\n type PluginConversationEvents,\n type PluginLogger,\n type Source,\n type User,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport type { MemoryAgent, MemoryRecallResult } from \"./agent\";\nimport { memoriesRecalledEvent } from \"./events\";\nimport {\n createMemoryStore,\n type MemoryDb,\n type MemoryEmbeddingProvider,\n type MemoryRecord,\n} from \"./store\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst RECALL_CANDIDATE_LIMIT = 20;\nconst MAX_PROMPT_CHARS = 4_000;\nconst MAX_MEMORY_LINE_CHARS = 600;\n\nexport interface MemoryRecallContext {\n agent: Pick<MemoryAgent, \"selectRelevantMemories\">;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n events?: PluginConversationEvents;\n log: PluginLogger;\n locationId?: string;\n actor?: Actor;\n source: Source;\n text: string;\n users: {\n resolveActor(): Promise<{ identity: Identity; user?: User } | undefined>;\n };\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\nconst recalledMemorySchema = z\n .object({\n id: z.string().min(1),\n content: z.string().min(1).max(MAX_MEMORY_LINE_CHARS),\n observedAtMs: z.number().finite(),\n // Stored version 1 uses the old scope labels. Prompt rendering ignores them.\n scope: z.enum([\"personal\", \"conversation\"]),\n kind: z.enum([\"preference\", \"procedure\", \"knowledge\"]),\n })\n .strict();\n\n/** Structured snapshot retained for one automatic memory recall. */\nexport const memoryRecallContextSchema = z\n .object({\n // Count is a safety rail only. Admission packs by MAX_PROMPT_CHARS.\n memories: z.array(recalledMemorySchema).min(1).max(RECALL_CANDIDATE_LIMIT),\n })\n .strict();\n\ntype RecalledMemory = z.output<typeof recalledMemorySchema>;\n\nfunction selectPromptMemories(memories: MemoryRecord[]): RecalledMemory[] {\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 selected: RecalledMemory[] = [];\n let totalChars = header.length + footer.length + 2;\n\n for (const memory of memories) {\n const content = trimContent(memory.content, MAX_MEMORY_LINE_CHARS);\n const line = `- Observed ${formatObservedDate(memory.observedAtMs)}: ${content}`;\n if (totalChars + line.length + 1 > MAX_PROMPT_CHARS) {\n break;\n }\n selected.push({\n id: memory.id,\n content,\n observedAtMs: memory.observedAtMs,\n scope: memory.scope === \"private\" ? \"personal\" : \"conversation\",\n kind: memory.kind,\n });\n totalChars += line.length + 1;\n }\n return selected;\n}\n\nfunction renderMemoryPrompt(memories: RecalledMemory[]): string {\n return [\n \"Relevant memories for this request:\",\n ...memories.map(\n (memory) =>\n `- Observed ${formatObservedDate(memory.observedAtMs)}: ${memory.content}`,\n ),\n \"\",\n \"Treat these as possibly stale context. Current user instructions and repository evidence take priority.\",\n ].join(\"\\n\");\n}\n\nfunction addUsd(\n left: number | undefined,\n right: number | undefined,\n): number | undefined {\n if (left === undefined) return right;\n if (right === undefined) return left;\n return Math.round((left + right) * 1e12) / 1e12;\n}\n\nasync function emitRecallOutcome(args: {\n costUsd?: number;\n events?: PluginConversationEvents;\n memories: string[];\n}): Promise<void> {\n await args.events?.emit(\n memoriesRecalledEvent({\n memories: args.memories,\n ...(args.costUsd !== undefined ? { costUsd: args.costUsd } : undefined),\n }),\n );\n}\n\nconst memoryRecallContext = definePromptContext({\n kind: \"recall\",\n version: 1,\n schema: memoryRecallContextSchema,\n renderPrompt: (content) => renderMemoryPrompt(content.memories),\n});\n\n/** Build active memory recall contributions. */\nexport async function createMemoryPromptContributions(\n context: MemoryRecallContext,\n): Promise<UserPromptContribution[] | undefined> {\n if (!context.text.trim()) {\n return undefined;\n }\n const actorUser = (await context.users.resolveActor())?.user;\n const runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : undefined),\n ...(context.actor ? { actor: context.actor } : undefined),\n ...(context.locationId ? { locationId: context.locationId } : undefined),\n source: context.source,\n ...(actorUser ? { userId: actorUser.id } : undefined),\n });\n let embeddingCostUsd: number | undefined;\n const sourceEmbedder = context.embedder;\n const embedder = sourceEmbedder\n ? {\n async embedTexts(input: { texts: string[] }) {\n const result = await sourceEmbedder.embedTexts(input);\n embeddingCostUsd = addUsd(embeddingCostUsd, result.costUsd);\n return result;\n },\n }\n : undefined;\n const candidates = await createMemoryStore(context.db, runtimeContext, {\n embedder,\n }).recallMemories({\n query: context.text,\n limit: RECALL_CANDIDATE_LIMIT,\n });\n if (candidates.length === 0) {\n await emitRecallOutcome({\n ...(embeddingCostUsd !== undefined ? { costUsd: embeddingCostUsd } : undefined),\n events: context.events,\n memories: [],\n });\n return undefined;\n }\n let recall: MemoryRecallResult;\n try {\n recall = await context.agent.selectRelevantMemories({\n candidates: candidates.map(({ content, id }) => ({ content, id })),\n userRequest: context.text,\n });\n } catch {\n // Automatic recall is optional context; a relevance-model failure must not\n // prevent the user's turn from continuing without recalled memory.\n context.log.warn(\"memory_recall_selection_failed\");\n return undefined;\n }\n const candidatesById = new Map(\n candidates.map((memory) => [memory.id, memory]),\n );\n const relevant = recall.relevantIds\n .map((id) => candidatesById.get(id))\n .filter((memory): memory is MemoryRecord => memory !== undefined);\n const selected = selectPromptMemories(relevant);\n const costUsd = addUsd(embeddingCostUsd, recall.costUsd);\n await emitRecallOutcome({\n ...(costUsd !== undefined ? { costUsd } : undefined),\n events: context.events,\n memories: selected.map(({ id }) => id),\n });\n if (selected.length === 0) {\n return undefined;\n }\n return [memoryRecallContext({ memories: selected })];\n}\n","import type {\n PluginConversationEventCostDay,\n PluginOperationalReportContent,\n} from \"@sentry/junior-plugin-api\";\nimport { and, eq, gt, isNull, or, sql } from \"drizzle-orm\";\nimport { z } from \"zod\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport type { MemoryDb } from \"./store\";\n\nconst DAY_MS = 24 * 60 * 60 * 1_000;\n// TODO: add hour categories + `1` when these system widgets can plot 24h hourly.\nconst WINDOWS = [7, 30, 90] as const;\n\nconst memoryDaySchema = z\n .object({\n date: z.string().date(),\n private: z.number().int().nonnegative(),\n public: z.number().int().nonnegative(),\n })\n .strict();\n\nfunction queryRows(result: unknown): unknown[] {\n if (\n typeof result !== \"object\" ||\n result === null ||\n !(\"rows\" in result) ||\n !Array.isArray(result.rows)\n ) {\n throw new TypeError(\"Memory activity query did not return rows\");\n }\n return result.rows;\n}\n\nfunction startOfUtcDay(value: number): Date {\n const date = new Date(value);\n date.setUTCHours(0, 0, 0, 0);\n return date;\n}\n\nasync function aggregateMemoryDays(args: { db: MemoryDb; nowMs: number }) {\n const end = startOfUtcDay(args.nowMs);\n const start = startOfUtcDay(args.nowMs - (WINDOWS.at(-1)! - 1) * DAY_MS);\n const endExclusiveMs = end.getTime() + DAY_MS;\n const table = juniorMemoryMemories;\n const result = await args.db.execute(sql`\n WITH days AS (\n SELECT generate_series(\n date_trunc('day', ${start}::timestamptz AT TIME ZONE 'UTC'),\n date_trunc('day', ${end}::timestamptz AT TIME ZONE 'UTC'),\n interval '1 day'\n ) AS day\n ), daily AS (\n SELECT\n date_trunc(\n 'day',\n to_timestamp(${table.createdAtMs} / 1000.0) AT TIME ZONE 'UTC'\n ) AS day,\n count(*) FILTER (\n WHERE ${table.scope} = 'private'\n )::integer AS private,\n count(*) FILTER (\n WHERE ${table.scope} = 'public'\n )::integer AS public\n FROM ${table}\n WHERE ${table.createdAtMs} >= ${start.getTime()}\n AND ${table.createdAtMs} < ${endExclusiveMs}\n GROUP BY date_trunc(\n 'day',\n to_timestamp(${table.createdAtMs} / 1000.0) AT TIME ZONE 'UTC'\n )\n )\n SELECT\n to_char(days.day, 'YYYY-MM-DD') AS date,\n coalesce(daily.private, 0)::integer AS private,\n coalesce(daily.public, 0)::integer AS public\n FROM days\n LEFT JOIN daily ON daily.day = days.day\n ORDER BY days.day\n `);\n return z.array(memoryDaySchema).parse(queryRows(result));\n}\n\nfunction formatCount(value: number): string {\n return new Intl.NumberFormat(\"en-US\").format(value);\n}\n\nfunction formatPercent(value: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n maximumFractionDigits: 0,\n style: \"percent\",\n }).format(value);\n}\n\nfunction formatUsd(value: number): string {\n const maximumFractionDigits = value > 0 && value < 0.01 ? 4 : 2;\n return new Intl.NumberFormat(\"en-US\", {\n currency: \"USD\",\n maximumFractionDigits,\n minimumFractionDigits: 2,\n style: \"currency\",\n }).format(value);\n}\n\n/** Build aggregate memory storage and indexing diagnostics for the System page. */\nexport async function buildMemoryOperationalReport(args: {\n db: MemoryDb;\n extractionDays: PluginConversationEventCostDay[];\n nowMs: number;\n}): Promise<PluginOperationalReportContent> {\n const active = and(\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 const [[counts], memoryDays] = await Promise.all([\n args.db\n .select({\n active: sql<number>`count(*) filter (where ${active})`.mapWith(Number),\n public:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n createdThirtyDays:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.createdAtMs} >= ${args.nowMs - 30 * DAY_MS})`.mapWith(\n Number,\n ),\n embedded:\n sql<number>`count(${juniorMemoryEmbeddings.memoryId}) filter (where ${active})`.mapWith(\n Number,\n ),\n private:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .leftJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n ),\n aggregateMemoryDays(args),\n ]);\n\n const activeCount = counts?.active ?? 0;\n const embeddedCount = counts?.embedded ?? 0;\n const embeddingCoverage = activeCount === 0 ? 0 : embeddedCount / activeCount;\n const extractionThirtyDays = args.extractionDays.slice(-30);\n const extractionCostThirtyDays = extractionThirtyDays.reduce(\n (total, day) => total + day.costUsd,\n 0,\n );\n\n return {\n generatedAt: new Date(args.nowMs).toISOString(),\n title: \"Memory\",\n metrics: [\n {\n label: \"active memories\",\n tone: activeCount > 0 ? \"good\" : \"neutral\",\n value: formatCount(activeCount),\n },\n {\n label: \"extraction cost · 30d\",\n value: formatUsd(extractionCostThirtyDays),\n },\n {\n label: \"created · 30d\",\n value: formatCount(counts?.createdThirtyDays ?? 0),\n },\n {\n label: \"private\",\n value: formatCount(counts?.private ?? 0),\n },\n {\n label: \"public\",\n value: formatCount(counts?.public ?? 0),\n },\n {\n label: \"embedding coverage\",\n tone:\n activeCount === 0\n ? \"neutral\"\n : embeddedCount === activeCount\n ? \"good\"\n : \"warning\",\n value: formatPercent(embeddingCoverage),\n },\n ],\n widgets: [\n {\n categories: args.extractionDays.map((day) => ({\n id: day.date,\n label: day.date,\n values: { costUsd: day.costUsd },\n })),\n description: \"Estimated model cost of passive memory extraction\",\n id: \"extraction-cost\",\n series: [{ format: \"usd\", key: \"costUsd\", label: \"Cost\" }],\n timeRangeDays: [...WINDOWS],\n title: \"Extraction cost\",\n type: \"bar_chart\",\n },\n {\n categories: memoryDays.map((day) => ({\n id: day.date,\n label: day.date,\n values: {\n private: day.private,\n public: day.public,\n },\n })),\n description: \"Memories stored by scope\",\n id: \"memories-created\",\n series: [\n { key: \"private\", label: \"Private\" },\n { key: \"public\", label: \"Public\" },\n ],\n timeRangeDays: [...WINDOWS],\n title: \"Memories created\",\n type: \"bar_chart\",\n },\n ],\n };\n}\n","/** Render memory in Junior's User page format. */\nimport type { PluginUserPageDefinition } from \"@sentry/junior-plugin-api\";\nimport { listMemories, type MemoryVisibility, type MemoryView } from \"./viewer\";\nimport type { MemoryDb } from \"./store\";\n\nfunction titleCase(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nfunction rememberedDate(createdAtMs: number): string {\n return new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n timeZone: \"UTC\",\n }).format(new Date(createdAtMs));\n}\n\nfunction originLabel(origin: MemoryView[\"origin\"]): string {\n if (origin === \"automatic\") return \"Automatic\";\n if (origin === \"explicit\") return \"Explicit\";\n return \"Other\";\n}\n\nfunction visibilityLabel(visibility: MemoryVisibility): string {\n return visibility === \"public\" ? \"Public\" : \"Private\";\n}\n\nfunction pageFilter(filter: string | undefined): {\n visibility?: MemoryVisibility;\n} {\n if (filter === \"private\") return { visibility: \"private\" };\n if (filter === \"public\") return { visibility: \"public\" };\n return {};\n}\n\nfunction pageEmptyText(input: { filter?: string; query?: string }): string {\n if (input.query) return \"No memories matched your search.\";\n if (input.filter === \"private\") return \"No private memories yet.\";\n if (input.filter === \"public\") return \"No public memories yet.\";\n return \"No memories yet.\";\n}\n\n/** Create the interactive Memories dashboard page. */\nexport function createMemoryUserPage(): PluginUserPageDefinition {\n return {\n id: \"memories\",\n label: \"Memories\",\n navigation: \"primary\",\n description:\n \"Personal and public memories Junior can use across conversations.\",\n async read(ctx, input) {\n const page = await listMemories(ctx.db as MemoryDb, ctx.viewer.id, {\n cursor: input.cursor,\n ...pageFilter(input.filter),\n limit: input.limit,\n ...(input.query ? { query: input.query } : undefined),\n });\n return {\n type: \"list\",\n emptyText: pageEmptyText(input),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : undefined),\n searchPlaceholder: \"Search memories\",\n records: page.memories.map((memory) => ({\n actions:\n memory.visibility === \"private\"\n ? [\n {\n confirmation: \"Forget this memory?\",\n href: `/api/plugins/memory/memories/${encodeURIComponent(memory.id)}`,\n label: \"Forget\",\n method: \"DELETE\" as const,\n tone: \"danger\" as const,\n },\n ]\n : [],\n id: memory.id,\n title: memory.content,\n metadata: [\n { label: \"Type\", value: titleCase(memory.kind) },\n { label: \"Learned\", value: originLabel(memory.origin) },\n { label: \"Source\", value: titleCase(memory.sourcePlatform) },\n {\n label: \"Visibility\",\n value: visibilityLabel(memory.visibility),\n },\n { label: \"Remembered\", value: rememberedDate(memory.createdAtMs) },\n { label: \"Observed\", value: rememberedDate(memory.observedAtMs) },\n {\n label: \"Expires\",\n value: memory.expiresAtMs\n ? rememberedDate(memory.expiresAtMs)\n : \"Never\",\n },\n ],\n })),\n };\n },\n };\n}\n"],"mappings":";AAAA,SAAS,0BAA0B;;;ACAnC;AAAA,EACE,eAAAA;AAAA,OAGK;AACP,SAAS,KAAAC,UAAS;;;ACElB,SAAS,YAAY,kBAAkB;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAC;AAAA,OAEK;AACP,SAAS,sBAAsB;AAG/B,SAAS,KAAAC,UAAS;AAClB,SAAS,oBAAoB;;;ACrB7B,SAAS,WAAW;AACpB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACjBP,SAAS,aAAa,oBAAoB;AAC1C,SAAS,SAAS;AAEX,IAAM,eAAe,CAAC,cAAc,aAAa,WAAW;AAE5D,IAAM,gB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AAE,YAAY,IAAI,WAAW,IAC7B;AAAA,YACJ,KAAK,IAAI;AAAA,YACT,QAAQ,IAAI;AAAA,YACZ,MAAM,IAAI;AAAA,YACV,OAAO,IAAI;AAAA,UACb,CAAC;AAAA,QACH;AAAA,MACF,IACA;AAAA,IACN;AAAA,EACF,CAAC;AACH;","names":["actorSchema","z","sql","z","nonEmptyStringSchema","z","index","text","sql","idempotent","z","actorSchema","index","z","and","asc","desc","eq","gt","isNull","like","or","sql","z","nonEmptyStringSchema","z","and","eq","visibleScopePredicate","or","isNull","gt","sql","like","desc","asc","index","z","personal","and","desc","eq","gt","ilike","isNull","or","or","isNull","gt","eq","ilike","and","desc","eq","eq","getSourceKey","z","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","z","archiveMemoryInputSchema","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","getSourceKey","createHash","getSourceKey","z","z","z","extractedMemorySchema","z","index","createHash","sourceKey","getSourceKey","result","z","z","and","eq","gt","isNull","or","sql","z","DAY_MS","z","sql","and","isNull","or","gt","eq"]}
1
+ {"version":3,"sources":["../src/plugin.ts","../src/agent.ts","../src/store.ts","../src/db/schema.ts","../src/types.ts","../src/ranking.ts","../src/scope.ts","../src/api.ts","../src/viewer.ts","../src/events.ts","../src/cli/search.ts","../src/cli/format.ts","../src/cli/show.ts","../src/cli/index.ts","../src/tools.ts","../src/process-session.ts","../src/recall.ts","../src/operational-report.ts","../src/user-pages.ts"],"sourcesContent":["import { defineJuniorPlugin } from \"@sentry/junior-plugin-api\";\nimport { createMemoryAgent } from \"./agent\";\nimport { createMemoryApi } from \"./api\";\nimport { createMemoryCliCommand } from \"./cli\";\nimport {\n createMemoryArchiveTool,\n createMemoryCreateTool,\n createMemoryListTool,\n createMemorySearchTool,\n type MemoryCreateToolContext,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { createMemoryPromptContributions } from \"./recall\";\nimport { buildMemoryOperationalReport } from \"./operational-report\";\nimport {\n memoriesCapturedEvent,\n memoriesCapturedEventV1,\n memoriesRecalledEvent,\n} from \"./events\";\nimport type { MemoryDb } from \"./store\";\nimport { createMemoryUserPage } from \"./user-pages\";\n\nconst MEMORY_MODEL_ENV = \"AI_MEMORY_MODEL\";\n\nexport interface MemoryPluginOptions {\n /** Disable automatic prompt recall while keeping explicit memory tools available. */\n disableRecall?: boolean;\n /** Disable passive memory extraction from completed sessions. */\n disableExtraction?: boolean;\n modelId?: string;\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 memoryToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryToolContext[\"db\"];\n embedder?: MemoryToolContext[\"embedder\"];\n locationId?: string;\n actor?: MemoryToolContext[\"actor\"];\n source: MemoryToolContext[\"source\"];\n users: MemoryToolContext[\"users\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId\n ? { conversationId: ctx.conversationId }\n : undefined),\n ...(ctx.actor ? { actor: ctx.actor } : undefined),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : undefined),\n ...(ctx.locationId ? { locationId: ctx.locationId } : undefined),\n source: ctx.source,\n users: ctx.users,\n ...(ctx.userText ? { userText: ctx.userText } : undefined),\n };\n}\n\nfunction memoryCreateToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryCreateToolContext[\"db\"];\n embedder?: MemoryCreateToolContext[\"embedder\"];\n locationId?: string;\n actor?: MemoryCreateToolContext[\"actor\"];\n source: MemoryCreateToolContext[\"source\"];\n supersessionDecider: MemoryCreateToolContext[\"supersessionDecider\"];\n users: MemoryCreateToolContext[\"users\"];\n userText?: string;\n}): MemoryCreateToolContext {\n return {\n ...memoryToolContext(ctx),\n supersessionDecider: ctx.supersessionDecider,\n };\n}\n\n/** Register Junior's long-term memory plugin. */\nexport function memoryPlugin(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 conversationEvents: [\n memoriesCapturedEventV1,\n memoriesCapturedEvent,\n memoriesRecalledEvent,\n ],\n cli: {\n commands: [createMemoryCliCommand()],\n },\n tasks: options.disableExtraction\n ? {}\n : {\n processSession: {\n async run(ctx) {\n await processMemorySession(ctx);\n },\n },\n },\n userPages: [createMemoryUserPage()],\n hooks: {\n async operationalReport(ctx) {\n const extractionDays = await ctx.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_captured\",\n });\n return await buildMemoryOperationalReport({\n db: ctx.db as MemoryDb,\n extractionDays,\n nowMs: ctx.nowMs,\n });\n },\n apiRoutes(ctx) {\n return createMemoryApi({\n conversationEvents: ctx.conversationEvents,\n db: ctx.db as MemoryDb,\n eventStats: ctx.eventStats,\n users: ctx.users,\n });\n },\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 archiveMemory: createMemoryArchiveTool(context),\n listMemories: createMemoryListTool(context),\n searchMemories: createMemorySearchTool(context),\n };\n },\n ...(!options.disableRecall\n ? {\n async userPrompt(ctx) {\n return await createMemoryPromptContributions({\n agent: createMemoryAgent(ctx.model),\n ...(ctx.conversationId\n ? { conversationId: ctx.conversationId }\n : undefined),\n ...(ctx.actor ? { actor: ctx.actor } : undefined),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n events: ctx.events,\n ...(ctx.locationId\n ? { locationId: ctx.locationId }\n : undefined),\n log: ctx.log,\n source: ctx.source,\n text: ctx.text,\n users: ctx.users,\n });\n },\n }\n : undefined),\n },\n });\n}\n","import {\n actorSchema,\n sourceSchema,\n type PluginModel,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n memorySupersessionDecisionSchema,\n memorySupersessionInputSchema,\n type MemorySupersessionDecision,\n type 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 memoryRecallCandidateSchema = z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n })\n .strict();\nconst memoryRecallInputSchema = z\n .object({\n candidates: z.array(memoryRecallCandidateSchema).min(1).max(20),\n userRequest: z.string().min(1),\n })\n .strict();\nconst memoryRecallDecisionSchema = z\n .object({\n relevantIds: z\n .array(z.string().min(1))\n .max(20)\n .describe(\n \"Candidate ids whose memories directly help with the current request, ordered by relevance.\",\n ),\n })\n .strict();\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 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 durable memories from the completed run. Return one object per distinct source assertion and classify it with kind.\",\n ),\n })\n .strict();\ntype MemoryReviewResponse = z.output<typeof memoryReviewResponseSchema>;\ntype ExtractMemoriesResponse = z.output<typeof extractMemoriesResponseSchema>;\n\nexport type MemoryReview = z.output<typeof memoryReviewDecisionSchema>;\nexport type MemoryRecallInput = z.output<typeof memoryRecallInputSchema>;\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\n/** Memories proposed by passive extraction and the model cost of that pass. */\nexport type MemoryExtractionResult = {\n costUsd?: number;\n memories: ExtractedMemory[];\n};\n\n/** Memories admitted by automatic recall and the model cost of that decision. */\nexport type MemoryRecallResult = {\n costUsd?: number;\n relevantIds: string[];\n};\n\nexport interface MemoryAgent {\n /** Select candidate memories that directly help with the current request. */\n selectRelevantMemories(\n request: MemoryRecallInput,\n ): Promise<MemoryRecallResult> | MemoryRecallResult;\n /** Classify a new preference against related active preferences. */\n adjudicateSupersession(\n request: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n extractSessionMemories(\n request: ExtractSessionRequest,\n ): Promise<MemoryExtractionResult> | MemoryExtractionResult;\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 self-contained facts that are useful beyond this turn and safe for the current Source.\",\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 durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst MEMORY_RECALL_SYSTEM = [\n \"You are Junior's memory recall relevance agent.\",\n \"Select only memories that would directly help answer the user's current request.\",\n \"Reject memories that merely share a company, product family, repository vocabulary, programming language, or general engineering context.\",\n \"Prefer specific matches on the exact repository, workflow, command, test, CI setup, project, or user preference being asked about.\",\n \"An empty relevantIds array is correct when no candidate is directly helpful.\",\n].join(\"\\n\");\nconst MEMORY_PREFERENCE_ADJUDICATION_SYSTEM = [\n \"You are Junior's memory preference adjudication agent.\",\n \"Classify how one new actor preference relates to existing active actor preferences.\",\n \"Return duplicate when the same durable preference is merely phrased differently.\",\n \"Return supersedes_old only for an obvious changed value in the same mutable preference slot.\",\n \"Return distinct for additive preferences or different topics, and uncertain when the relationship is unclear.\",\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(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\");\n}\n\nfunction actorLabel(actor: z.output<typeof actorSchema> | undefined): string {\n if (!actor) {\n return \"none\";\n }\n switch (actor.platform) {\n case \"system\":\n return `system:${actor.name}`;\n case \"slack\":\n return `slack:${actor.teamId}:${actor.userId}`;\n case \"local\":\n return `local:${actor.userId}`;\n case \"web\":\n return `web:${actor.userId}`;\n }\n}\n\nfunction sourceLabel(source: z.output<typeof sourceSchema>): string {\n switch (source.kind) {\n case \"slack\":\n return `slack:${source.teamId}:${source.channelId}`;\n case \"web\":\n case \"local\":\n return `${source.kind}:${source.conversationId}`;\n case \"event\":\n return `event:${source.namespace}:${source.eventKey}`;\n case \"scheduled_automation\":\n case \"event_automation\":\n case \"plugin_dispatch\":\n case \"agent_invocation\":\n return source.kind;\n }\n}\n\nfunction runtimeDescription(\n request: Pick<CreateMemoryRequest, \"expiresAtMs\" | \"runtimeContext\">,\n): string {\n const runtime = request.runtimeContext;\n const lines = [\n `- actor: ${escapeXml(actorLabel(runtime.actor))}`,\n `- source: ${escapeXml(sourceLabel(runtime.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-subject 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 durable, self-contained, and safe for the current Source.\",\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 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 = actorLabel(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 recallRelevancePrompt(request: MemoryRecallInput): string {\n return [\n \"<memory-recall-input>\",\n \"<user-request>\",\n escapeXml(request.userRequest),\n \"</user-request>\",\n \"\",\n \"<candidate-memories>\",\n escapeXml(JSON.stringify(request.candidates)),\n \"</candidate-memories>\",\n \"\",\n \"Return only ids from candidate-memories. Preserve the most relevant candidates first.\",\n \"</memory-recall-input>\",\n ].join(\"\\n\");\n}\n\nfunction preferenceAdjudicationPrompt(\n request: MemorySupersessionInput,\n): string {\n return [\n \"<memory-preference-adjudication-input>\",\n \"Classify the candidate preference against the related 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 duplicate when the candidate and one existing memory express the same durable preference or value with different wording.\",\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 \"- Return distinct when the candidate is an additional preference or belongs to a different task or topic.\",\n \"- Return uncertain when broader or narrower wording makes equivalence or replacement unclear.\",\n \"- Do not supersede memories from different topics even if they are both preferences.\",\n \"- duplicateId and supersededIds may contain only ids from existing-memories.\",\n \"- If unsure, return uncertain.\",\n \"</rules>\",\n \"</memory-preference-adjudication-input>\",\n ].join(\"\\n\");\n}\n\n/** Create the memory-owned agent that reviews, extracts, and recalls memories. */\nexport function createMemoryAgent(model: PluginModel): MemoryAgent {\n return {\n async selectRelevantMemories(rawRequest) {\n const request = memoryRecallInputSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: memoryRecallDecisionSchema,\n system: MEMORY_RECALL_SYSTEM,\n prompt: recallRelevancePrompt(request),\n maxTokens: 400,\n });\n const decision = memoryRecallDecisionSchema.parse(result.object);\n const candidateIds = new Set(request.candidates.map(({ id }) => id));\n return {\n relevantIds: [...new Set(decision.relevantIds)].filter((id) =>\n candidateIds.has(id),\n ),\n ...(result.costUsd !== undefined\n ? { costUsd: result.costUsd }\n : undefined),\n };\n },\n async adjudicateSupersession(rawRequest) {\n const request = memorySupersessionInputSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: memorySupersessionDecisionSchema,\n system: MEMORY_PREFERENCE_ADJUDICATION_SYSTEM,\n prompt: preferenceAdjudicationPrompt(request),\n maxTokens: 400,\n });\n return memorySupersessionDecisionSchema.parse(result.object);\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 {\n memories: extractedMemoriesFromResponse(\n extractMemoriesResponseSchema.parse(result.object),\n ),\n ...(result.costUsd !== undefined\n ? { costUsd: result.costUsd }\n : undefined),\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 : undefined),\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","/**\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 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 { getSourceKey } from \"@sentry/junior-plugin-api\";\nimport * as memorySqlSchema from \"./db/schema\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport { rankMemoryMatches, type MemoryMatch } from \"./ranking\";\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 MemorySourcePlatform,\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 PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT = 10;\nconst PREFERENCE_ADJUDICATION_VECTOR_LIMIT = 5;\n/** Explicit search overfetch: keep a wider fusion window for tool/CLI search. */\nconst SEARCH_RETRIEVAL_OVERFETCH = 4;\n/**\n * Automatic recall overfetch. Recall already asks for ~20 candidates before the\n * relevance gate, so each hybrid leg only needs a small top-k probe.\n */\nconst RECALL_RETRIEVAL_OVERFETCH = 2;\n/**\n * Absolute ceiling per retrieval leg. Matches the store limit ceiling so a\n * single healthy leg can still fill the caller's requested result window.\n */\nconst MAX_RETRIEVAL_LEG_CANDIDATES = 200;\n/** Cap ts_rank_cd work after GIN filtering; ranking is not indexable. */\nconst MAX_LEXICAL_RANK_CANDIDATES = 200;\n/** Expand the GIN match window before ts_rank_cd, still under the hard cap. */\nconst LEXICAL_RANK_WINDOW_MULTIPLIER = 4;\n/** Bound query text before embedding / FTS construction. */\nconst MAX_RETRIEVAL_QUERY_CHARS = 1_500;\nconst MAX_MEMORY_CONTENT_CHARS = 4_000;\nconst EMBEDDING_METRIC = \"cosine\";\n/**\n * Cosine distance cutoff for automatic recall only (not explicit search).\n * Tuned for text-embedding-3-small; retune if the embedding model changes.\n */\nconst RECALL_MAX_VECTOR_DISTANCE = 0.45;\n\nexport type MemoryDb = PgDatabase<PgQueryResultHKT, typeof memorySqlSchema>;\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 locationId: optionalNonEmptyStringSchema,\n observedAtMs: z.coerce.number(),\n searchVector: z.string().optional(),\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\nfunction storedMemorySource(\n source: MemoryRuntimeContext[\"source\"],\n): MemorySourcePlatform {\n switch (source.kind) {\n case \"slack\":\n case \"local\":\n case \"web\":\n return source.kind;\n case \"event\":\n case \"scheduled_automation\":\n case \"event_automation\":\n case \"plugin_dispatch\":\n case \"agent_invocation\":\n throw new Error(`${source.kind} Source cannot own a Memory.`);\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 costUsd: z.number().finite().nonnegative().optional(),\n dimensions: z.literal(MEMORY_EMBEDDING_DIMENSIONS),\n model: nonEmptyStringSchema,\n provider: nonEmptyStringSchema,\n vectors: z.array(embeddingVectorSchema),\n })\n .strict();\nconst memorySupersessionCandidateSchema = z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n })\n .strict();\nconst memorySupersessionCandidatesSchema = z\n .array(memorySupersessionCandidateSchema)\n .min(1)\n .max(PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT);\nconst supersededIdsSchema = z\n .array(z.string().min(1))\n .min(1)\n .max(PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT);\n\n/** Validated preference comparison input supplied to a supersession decider. */\nexport const memorySupersessionInputSchema = z\n .object({\n candidate: z\n .object({\n content: z.string().min(1),\n kind: z.literal(\"preference\"),\n })\n .strict(),\n existingMemories: memorySupersessionCandidatesSchema,\n runtimeContext: memoryRuntimeContextSchema,\n })\n .strict();\n\n/**\n * Validated preference decision whose referenced ids must come from the\n * supplied existing memories.\n */\nexport const memorySupersessionDecisionSchema = z.discriminatedUnion(\n \"decision\",\n [\n z\n .object({\n decision: z.literal(\"duplicate\"),\n duplicateId: z.string().min(1),\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"supersedes_old\"),\n supersededIds: supersededIdsSchema,\n })\n .strict(),\n z\n .object({\n decision: z.enum([\"distinct\", \"uncertain\"]),\n })\n .strict(),\n ],\n);\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 /** True when this call found the memory previously written for the same input identity. */\n idempotent?: true;\n memory: MemoryRecord;\n /** Memory ids made inactive by this write. */\n supersededIds?: string[];\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 costUsd?: number;\n dimensions: number;\n model: string;\n provider: string;\n vectors: number[][];\n }>;\n}\n\nexport type MemorySupersessionInput = z.output<\n typeof memorySupersessionInputSchema\n>;\n\nexport type MemorySupersessionDecision = z.output<\n typeof memorySupersessionDecisionSchema\n>;\n\nexport interface MemorySupersessionDecider {\n /** Classify a new preference against related active preferences. */\n adjudicateSupersession(\n input: MemorySupersessionInput,\n ): Promise<MemorySupersessionDecision> | MemorySupersessionDecision;\n}\n\nexport interface MemoryStoreOptions {\n embedder?: MemoryEmbeddingProvider;\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 memory about the current User. The Source sets access. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a memory about the current Conversation. The Source sets access. */\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 /**\n * Retrieve a broad relevance-ranked candidate window for automatic recall.\n * Prompt admission remains owned by the recall boundary.\n */\n recallMemories(input: SearchMemoriesInput): 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 stored key for the Source. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n const key = getSourceKey(ctx.source);\n if (!key) {\n throw new Error(\"Memory Source has no stable key.\");\n }\n return key;\n}\n\n/** Parse one SQL row into the public memory projection. */\nexport function 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 : undefined),\n ...(parsed.supersededAtMs !== undefined\n ? { supersededAtMs: parsed.supersededAtMs }\n : undefined),\n ...(parsed.supersededById\n ? { supersededById: parsed.supersededById }\n : undefined),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : undefined),\n ...(parsed.archiveReason\n ? { archiveReason: parsed.archiveReason }\n : undefined),\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\n/** Build the active-row predicate for already-authorized memory scopes. */\nexport function 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. */\ninterface IdempotencyMatch {\n memory: MemoryRecord;\n outcome: \"created\" | \"duplicate\";\n}\n\nasync function findByIdempotencyKey(args: {\n db: MemoryDb;\n idempotencyKey: string;\n nowMs: number;\n scope: ResolvedMemoryScope;\n}): Promise<IdempotencyMatch | 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 { memory: parseMemoryRow(activeRows[0]), outcome: \"created\" };\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 { memory: parseMemoryRow(rows[0]), outcome: \"duplicate\" };\n }\n }\n return undefined;\n}\n\n/**\n * Archive a bounded batch of expired active rows and remove their derived vectors.\n */\nexport async 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 denseRanks<T>(\n values: T[],\n key: (value: T) => string | number,\n): number[] {\n let previous: string | number | undefined;\n let rank = 0;\n return values.map((value, index) => {\n const current = key(value);\n if (index === 0 || current !== previous) {\n rank = index + 1;\n previous = current;\n }\n return rank;\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 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 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 locationId: args.runtimeContext.locationId,\n observedAtMs: args.nowMs,\n scope: args.scope.scope,\n scopeKey: args.scope.scopeKey,\n sourceKey: sourceKey(args.runtimeContext),\n sourcePlatform: storedMemorySource(args.runtimeContext.source),\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\n/** Select semantic preferences, then fill the window by recency for unembedded records. */\nasync function listPreferenceAdjudicationCandidates(args: {\n db: MemoryDb;\n embedding?: MemoryEmbedding;\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord[]> {\n const vectorCandidates = args.embedding\n ? await listVectorPreferenceAdjudicationCandidates({\n db: args.db,\n embedding: args.embedding,\n nowMs: args.nowMs,\n scope: args.scope,\n subject: args.subject,\n })\n : [];\n const recentCandidates = (\n await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n activeScopedSubjectPredicate({\n ...args,\n kind: \"preference\",\n }),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT)\n ).map(parseMemoryRow);\n return [\n ...new Map(\n [...vectorCandidates, ...recentCandidates].map((memory) => [\n memory.id,\n memory,\n ]),\n ).values(),\n ].slice(0, PREFERENCE_ADJUDICATION_CANDIDATE_LIMIT);\n}\n\nasync function listVectorPreferenceAdjudicationCandidates(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\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, kind: \"preference\" }),\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(PREFERENCE_ADJUDICATION_VECTOR_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\ntype PreferenceAdjudicationResult =\n | { decision: \"create\" }\n | { decision: \"duplicate\"; memory: MemoryRecord }\n | { decision: \"supersede\"; ids: [string, ...string[]] };\n\n/**\n * Normalize a preference decision to known duplicate or supersession targets.\n * Uncertainty, invalid ids, and model failure leave existing memories active.\n */\nasync function adjudicatePreferenceCandidate(args: {\n candidates: MemoryRecord[];\n content: string;\n decider: MemorySupersessionDecider;\n runtimeContext: MemoryRuntimeContext;\n}): Promise<PreferenceAdjudicationResult> {\n const [firstCandidate, ...remainingCandidates] = args.candidates;\n if (!firstCandidate) {\n return { decision: \"create\" };\n }\n const existingMemories = [\n { content: firstCandidate.content, id: firstCandidate.id },\n ...remainingCandidates.map((memory) => ({\n content: memory.content,\n id: memory.id,\n })),\n ];\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 === \"duplicate\") {\n const memory = args.candidates.find(\n (candidate) => candidate.id === decision.duplicateId,\n );\n return memory\n ? { decision: \"duplicate\", memory }\n : { decision: \"create\" };\n }\n if (decision.decision === \"supersedes_old\") {\n const ids = decision.supersededIds.filter((id) => candidateIds.has(id));\n const [firstId, ...remainingIds] = ids;\n return firstId\n ? { decision: \"supersede\", ids: [firstId, ...remainingIds] }\n : { decision: \"create\" };\n }\n return { decision: \"create\" };\n } catch {\n return { decision: \"create\" };\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\nfunction normalizeRetrievalQuery(query: string): string {\n const normalized = query.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= MAX_RETRIEVAL_QUERY_CHARS) {\n return normalized;\n }\n return normalized.slice(0, MAX_RETRIEVAL_QUERY_CHARS).trimEnd();\n}\n\nfunction retrievalLegLimit(limit: number, overfetch: number): number {\n const requested = Math.max(1, limit);\n const withOverfetch = requested * Math.max(1, overfetch);\n // Never return fewer candidates than the caller asked for. A hard overfetch\n // cap below `limit` under-fills when one modality is empty or both overlap.\n return Math.min(\n MAX_RETRIEVAL_LEG_CANDIDATES,\n Math.max(requested, withOverfetch),\n );\n}\n\n/** Search a bounded active candidate set with PostgreSQL full-text ranking. */\nasync function searchVisibleLexicalMemories(args: {\n db: MemoryDb;\n limit: number;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryMatch[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const query = normalizeRetrievalQuery(args.query);\n if (!query) {\n return [];\n }\n const queryVector = sql`to_tsvector('english', ${query})`;\n const tsquery = sql`(\n SELECT COALESCE(\n string_agg(quote_literal(term), ' | ')::tsquery,\n ''::tsquery\n )\n FROM unnest(tsvector_to_array(${queryVector})) AS query_terms(term)\n )`;\n // GIN filter first, then rank only a bounded recent match window.\n const candidateLimit = Math.min(\n MAX_LEXICAL_RANK_CANDIDATES,\n args.limit * LEXICAL_RANK_WINDOW_MULTIPLIER,\n );\n const candidates = args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(predicate, sql`${juniorMemoryMemories.searchVector} @@ ${tsquery}`),\n )\n .orderBy(\n desc(juniorMemoryMemories.observedAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(candidateLimit)\n .as(\"lexical_candidates\");\n const textRank = sql<number>`ts_rank_cd(${candidates.searchVector}, ${tsquery})`;\n const rows = await args.db\n .select({\n memory: {\n archiveReason: candidates.archiveReason,\n archivedAtMs: candidates.archivedAtMs,\n content: candidates.content,\n createdAtMs: candidates.createdAtMs,\n expiresAtMs: candidates.expiresAtMs,\n id: candidates.id,\n idempotencyKey: candidates.idempotencyKey,\n kind: candidates.kind,\n observedAtMs: candidates.observedAtMs,\n scope: candidates.scope,\n scopeKey: candidates.scopeKey,\n searchVector: candidates.searchVector,\n sourceKey: candidates.sourceKey,\n sourcePlatform: candidates.sourcePlatform,\n subjectKey: candidates.subjectKey,\n subjectType: candidates.subjectType,\n supersededAtMs: candidates.supersededAtMs,\n supersededById: candidates.supersededById,\n },\n textRank,\n })\n .from(candidates)\n .orderBy(desc(textRank), desc(candidates.observedAtMs), asc(candidates.id))\n .limit(args.limit);\n const ranks = denseRanks(rows, (row) => Number(row.textRank));\n return rows.map((row, index) => ({\n lexical: { rank: ranks[index] },\n memory: parseMemoryRow(row.memory),\n }));\n}\n\n/** Search active visible records with pgvector cosine distance. */\nasync function searchVisibleVectorMemories(args: {\n db: MemoryDb;\n embedding: MemoryEmbedding;\n limit: number;\n maxDistance?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryMatch[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const embedding = args.embedding;\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n embedding.vector,\n );\n // Push distance cutoff into SQL so recall does not overfetch weak neighbors.\n const distancePredicate =\n args.maxDistance === undefined\n ? undefined\n : sql`${distance} <= ${args.maxDistance}`;\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 ...(distancePredicate ? [distancePredicate] : []),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(args.limit);\n const ranks = denseRanks(rows, (row) => Number(row.distance));\n return rows.flatMap((row, index) => {\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 return [\n {\n memory: parseMemoryRow(row.memory),\n vector: {\n rank: ranks[index],\n },\n },\n ];\n });\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 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 async function reuseDuplicateMemory(args: {\n content: string;\n duplicate: MemoryRecord;\n idempotencyKey?: string;\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n }): Promise<CreateMemoryResult> {\n await rememberDuplicateIdempotency({\n ...args,\n db,\n runtimeContext,\n });\n await storeEmbedding({\n content: args.duplicate.content,\n db,\n embedder,\n memoryId: args.duplicate.id,\n nowMs: args.nowMs,\n });\n return { created: false, memory: args.duplicate };\n }\n\n /** Persist a memory under the plugin-derived scope and subject. */\n async function createScopedMemory(\n rawInput: CreateMemoryInput,\n subjectType: ResolvedMemorySubject[\"subjectType\"],\n ): Promise<CreateMemoryResult> {\n const input = createMemoryInputSchema.parse(rawInput);\n const nowMs = getNowMs();\n const content = normalizeContent(input.content);\n const scope = deriveMemoryScope(runtimeContext);\n const subject = deriveMemorySubject(runtimeContext, subjectType);\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.memory.content,\n db,\n embedder,\n memoryId: idempotent.memory.id,\n nowMs,\n });\n return idempotent.outcome === \"created\"\n ? { created: false, idempotent: true, memory: idempotent.memory }\n : { created: false, memory: idempotent.memory };\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 return await reuseDuplicateMemory({\n content,\n duplicate: exactDuplicate,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n subject,\n });\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 let supersededIds: string[] = [];\n if (\n subjectType === \"user\" &&\n input.kind === \"preference\" &&\n supersessionDecider &&\n (input.expiresAtMs === undefined || input.expiresAtMs > nowMs)\n ) {\n const preferenceCandidates = await listPreferenceAdjudicationCandidates({\n db,\n ...(candidateEmbedding ? { embedding: candidateEmbedding } : undefined),\n nowMs,\n scope,\n subject,\n });\n const adjudication = await adjudicatePreferenceCandidate({\n candidates: preferenceCandidates,\n content,\n decider: supersessionDecider,\n runtimeContext,\n });\n if (adjudication.decision === \"duplicate\") {\n return await reuseDuplicateMemory({\n content,\n duplicate: adjudication.memory,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n subject,\n });\n }\n if (adjudication.decision === \"supersede\") {\n supersededIds = adjudication.ids;\n }\n }\n\n const id = randomUUID();\n const write = 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 locationId: runtimeContext.locationId,\n observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: storedMemorySource(runtimeContext.source),\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, supersededIds: [] };\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, supersededIds: idsToClean };\n });\n if (write.inserted[0]) {\n const memory = parseMemoryRow(write.inserted[0]);\n await storeEmbedding({\n content: memory.content,\n db,\n embedder,\n embedding: candidateEmbedding,\n memoryId: memory.id,\n nowMs,\n });\n return {\n created: true,\n memory,\n ...(write.supersededIds.length > 0\n ? { supersededIds: write.supersededIds }\n : undefined),\n };\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.memory.content,\n db,\n embedder,\n memoryId: idempotent.memory.id,\n nowMs,\n });\n return idempotent.outcome === \"created\"\n ? { created: false, idempotent: true, memory: idempotent.memory }\n : { created: false, memory: idempotent.memory };\n }\n\n /**\n * Hybrid retrieval for both automatic recall and explicit search.\n *\n * Keep both legs parallel and fuse ranks with RRF. Never skip lexical when\n * vectors already hit: that drops exact/token memories and serializes the\n * miss path. Each leg is a hard-capped top-k probe so Postgres work stays\n * bounded even on broad queries.\n *\n * Automatic recall also searches private memory by itself. This keeps newer\n * public memory with common words from hiding older private memory.\n */\n async function retrieveVisibleMemories(\n rawInput: SearchMemoriesInput,\n vectorMaxDistance: number | undefined,\n ): Promise<MemoryRecord[]> {\n const input = searchMemoriesInputSchema.parse(rawInput);\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 overfetch =\n vectorMaxDistance === undefined\n ? SEARCH_RETRIEVAL_OVERFETCH\n : RECALL_RETRIEVAL_OVERFETCH;\n const candidateLimit = retrievalLegLimit(limit, overfetch);\n const privateScopes = scopes.filter((scope) => scope.scope === \"private\");\n // Search private memory by itself during recall so public results cannot\n // fill both search windows.\n const probePrivate =\n vectorMaxDistance !== undefined && privateScopes.length > 0;\n const query = normalizeRetrievalQuery(input.query);\n let queryEmbedding: MemoryEmbedding | undefined;\n if (embedder && query) {\n try {\n queryEmbedding = await embedOne(embedder, query);\n } catch {\n queryEmbedding = undefined;\n }\n }\n const emptyMatches = Promise.resolve([] as MemoryMatch[]);\n const lexicalArgs = {\n db,\n limit: candidateLimit,\n nowMs,\n query: input.query,\n };\n // Always run both legs in parallel. Conditional lexical skip is unsafe:\n // one in-threshold vector distractor can hide a stronger lexical hit.\n // Embed once up front; vector probes only run when that embedding exists.\n const matches = await Promise.all([\n queryEmbedding\n ? searchVisibleVectorMemories({\n db,\n embedding: queryEmbedding,\n limit: candidateLimit,\n ...(vectorMaxDistance !== undefined\n ? { maxDistance: vectorMaxDistance }\n : undefined),\n nowMs,\n scopes,\n })\n : emptyMatches,\n searchVisibleLexicalMemories({\n ...lexicalArgs,\n scopes,\n }),\n queryEmbedding && probePrivate\n ? searchVisibleVectorMemories({\n db,\n embedding: queryEmbedding,\n limit: candidateLimit,\n maxDistance: vectorMaxDistance,\n nowMs,\n scopes: privateScopes,\n })\n : emptyMatches,\n probePrivate\n ? searchVisibleLexicalMemories({\n ...lexicalArgs,\n scopes: privateScopes,\n })\n : emptyMatches,\n ]);\n return rankMemoryMatches(matches.flat(), {\n nowMs,\n // Slight lexical preference protects exact ids/names/timezones on ties.\n ...(vectorMaxDistance === undefined\n ? undefined\n : { lexicalWeight: 1, vectorWeight: 0.85 }),\n })\n .slice(0, limit)\n .map(({ memory }) => memory);\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, \"user\");\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 recallMemories(input) {\n return await retrieveVisibleMemories(input, RECALL_MAX_VECTOR_DISTANCE);\n },\n\n async searchMemories(input) {\n return await retrieveVisibleMemories(input, undefined);\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","/**\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 customType,\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\nconst tsvector = customType<{ data: string }>({\n dataType() {\n return \"tsvector\";\n },\n});\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 searchVector: tsvector(\"search_vector\").generatedAlwaysAs(\n sql`to_tsvector('english', \"content\")`,\n ),\n sourcePlatform: text(\"source_platform\", {\n enum: MEMORY_SOURCE_PLATFORMS,\n }).notNull(),\n sourceKey: text(\"source_key\").notNull(),\n /** Location where Junior learned the memory, when known. */\n locationId: text(\"location_id\"),\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 index(\"junior_memory_memories_search_idx\")\n .using(\"gin\", table.scope, table.scopeKey, table.searchVector)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS 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 ('private', 'public')`,\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', 'web')`,\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 // Cosine ANN for vector recall/search. Ops must match cosineDistance (<=>).\n // Keep this unfiltered so planners can use HNSW before scope/status joins.\n index(\"junior_memory_embeddings_embedding_hnsw_idx\")\n .using(\"hnsw\", table.embedding.op(\"vector_cosine_ops\"))\n .with({ m: 16, ef_construction: 64 }),\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 { actorSchema, sourceSchema } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\n\nexport const MEMORY_KINDS = [\"preference\", \"procedure\", \"knowledge\"] as const;\n\nexport const MEMORY_SCOPES = [\"private\", \"public\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\n// Durable attribution follows Source kind, including dashboard roots.\nexport const MEMORY_SOURCE_PLATFORMS = [\"slack\", \"local\", \"web\"] as const;\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/** Host data used to set memory access, subject, and source. */\nexport const memoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n locationId: nonEmptyStringSchema.optional(),\n actor: actorSchema.optional(),\n source: sourceSchema,\n /** User linked to the active Actor. */\n userId: nonEmptyStringSchema.optional(),\n })\n .strict();\n\nexport type MemoryRuntimeContext = z.output<typeof memoryRuntimeContextSchema>;\n","import type { MemoryRecord } from \"./store\";\n\nconst RECIPROCAL_RANK_FUSION_K = 60;\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst DEFAULT_RRF_WEIGHT = 1;\n\nexport interface MemoryMatch {\n lexical?: {\n rank: number;\n };\n memory: MemoryRecord;\n vector?: {\n rank: number;\n };\n}\n\nfunction reciprocalRank(rank: number, weight: number): number {\n return weight / (RECIPROCAL_RANK_FUSION_K + rank);\n}\n\nfunction matchScore(\n match: MemoryMatch,\n weights: { lexicalWeight: number; vectorWeight: number },\n): number {\n return (\n (match.vector\n ? reciprocalRank(match.vector.rank, weights.vectorWeight)\n : 0) +\n (match.lexical\n ? reciprocalRank(match.lexical.rank, weights.lexicalWeight)\n : 0)\n );\n}\n\nfunction observedAgeRank(memory: MemoryRecord, nowMs: number): number {\n const ageMs = Math.max(0, nowMs - memory.observedAtMs);\n if (ageMs <= 7 * ONE_DAY_MS) {\n return 3;\n }\n if (ageMs <= 30 * ONE_DAY_MS) {\n return 2;\n }\n if (ageMs <= 90 * ONE_DAY_MS) {\n return 1;\n }\n return 0;\n}\n\nfunction positiveWeight(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isFinite(value) && value > 0\n ? value\n : fallback;\n}\n\n/** Fuse lexical and vector ranks without comparing provider raw scores. */\nexport function rankMemoryMatches(\n matches: MemoryMatch[],\n options: {\n /** Optional RRF weight for the lexical leg. Defaults to 1. */\n lexicalWeight?: number;\n nowMs: number;\n /** Optional RRF weight for the vector leg. Defaults to 1. */\n vectorWeight?: number;\n },\n): MemoryMatch[] {\n const weights = {\n lexicalWeight: positiveWeight(options.lexicalWeight, DEFAULT_RRF_WEIGHT),\n vectorWeight: positiveWeight(options.vectorWeight, DEFAULT_RRF_WEIGHT),\n };\n const byId = new Map<string, MemoryMatch>();\n for (const match of matches) {\n const existing = byId.get(match.memory.id);\n if (!existing) {\n byId.set(match.memory.id, match);\n continue;\n }\n // Keep the first rank from each search. The shared searches run first, so\n // the smaller private searches cannot replace their ranks.\n byId.set(match.memory.id, {\n ...existing,\n ...(!existing.lexical && match.lexical\n ? { lexical: match.lexical }\n : undefined),\n ...(!existing.vector && match.vector ? { vector: match.vector } : undefined),\n });\n }\n return [...byId.values()].sort((left, right) => {\n const scoreDelta = matchScore(right, weights) - matchScore(left, weights);\n if (scoreDelta !== 0) {\n return scoreDelta;\n }\n // Prefer private memory when RRF ties. Public and private searches can give\n // the same rank to common words.\n const privateDelta =\n Number(right.memory.scope === \"private\") -\n Number(left.memory.scope === \"private\");\n if (privateDelta !== 0) {\n return privateDelta;\n }\n return (\n observedAgeRank(right.memory, options.nowMs) -\n observedAgeRank(left.memory, options.nowMs) ||\n right.memory.observedAtMs - left.memory.observedAtMs ||\n left.memory.id.localeCompare(right.memory.id)\n );\n });\n}\n","import type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\nconst PUBLIC_SCOPE_KEY = \"public\";\n\n/** Stored memory access rule. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** What a stored memory is about. */\nexport interface ResolvedMemorySubject {\n subjectKey: string;\n subjectType: Extract<MemorySubjectType, \"user\" | \"conversation\">;\n}\n\n/** Public memories are visible everywhere. */\nexport const publicMemoryScope: ResolvedMemoryScope = {\n scope: \"public\",\n scopeKey: PUBLIC_SCOPE_KEY,\n};\n\nfunction privateMemoryScope(userId: string): ResolvedMemoryScope {\n return { scope: \"private\", scopeKey: userId };\n}\n\n/** Set memory access from the Source. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope {\n if (\"visibility\" in ctx.source && ctx.source.visibility === \"public\") {\n return publicMemoryScope;\n }\n if (!ctx.userId) {\n throw new Error(\"Private memory requires a User.\");\n }\n return privateMemoryScope(ctx.userId);\n}\n\n/** Set what a memory is about. Access is set separately. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n subjectType: Extract<MemorySubjectType, \"user\" | \"conversation\">,\n): ResolvedMemorySubject {\n if (subjectType === \"user\") {\n if (!ctx.userId) {\n throw new Error(\"User memory requires a User.\");\n }\n return { subjectType, subjectKey: ctx.userId };\n }\n const subjectKey = ctx.conversationId;\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return {\n subjectType,\n subjectKey,\n };\n}\n\n/** Return the memory scopes that the current User can access. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n if (!ctx.userId) {\n return [publicMemoryScope];\n }\n return [publicMemoryScope, privateMemoryScope(ctx.userId)];\n}\n","/**\n * Authenticated REST access to memory.\n *\n * The signed-in User can read public memory and private memory that they own.\n */\nimport { z } from \"zod\";\nimport {\n pluginApiRouteRequestContextSchema,\n type PluginConversationEventReader,\n type PluginConversationEventStats,\n type PluginRouteApp,\n type User,\n} from \"@sentry/junior-plugin-api\";\nimport type { MemoryDb } from \"./store\";\nimport {\n archiveMemory,\n getMemory,\n getMemoryStats,\n getMemoryTimeline,\n getMemoryTimelineHours,\n InvalidMemoryCursorError,\n listMemories,\n MemoryNotFoundError,\n type MemoryView,\n} from \"./viewer\";\nimport { parseCapturedMemories } from \"./events\";\nimport { MEMORY_SOURCE_PLATFORMS } from \"./types\";\n\nexport const memoryApiSchema = z\n .object({\n content: z.string().min(1),\n createdAt: z.iso.datetime(),\n expiresAt: z.iso.datetime().optional(),\n id: z.string().min(1),\n kind: z.enum([\"preference\", \"procedure\", \"knowledge\"]),\n observedAt: z.iso.datetime(),\n origin: z.enum([\"automatic\", \"explicit\", \"other\"]),\n sourcePlatform: z.enum(MEMORY_SOURCE_PLATFORMS),\n visibility: z.enum([\"private\", \"public\"]),\n })\n .strict();\n\nexport const memoryListResponseSchema = z\n .object({\n memories: z.array(memoryApiSchema),\n nextCursor: z.string().min(1).optional(),\n })\n .strict();\n\nexport const conversationMemorySchema = z\n .object({\n capturedAt: z.iso.datetime(),\n content: z.string().min(1),\n id: z.string().min(1),\n kind: z.enum([\"preference\", \"procedure\", \"knowledge\"]),\n visibility: z.enum([\"private\", \"public\"]),\n })\n .strict();\n\nexport const conversationMemoryListResponseSchema = z\n .object({ memories: z.array(conversationMemorySchema) })\n .strict();\n\nconst memoryBucketSchema = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}(T\\d{2})?$/);\n\nconst memoryDashboardDaySchema = z\n .object({\n date: memoryBucketSchema,\n personal: z.number().int().min(0),\n public: z.number().int().min(0),\n })\n .strict();\n\nconst memoryCostDaySchema = z\n .object({\n costUsd: z.number().finite().nonnegative(),\n date: memoryBucketSchema,\n events: z.number().int().min(0),\n })\n .strict();\n\nexport const memoryDashboardResponseSchema = z\n .object({\n days: z.array(memoryDashboardDaySchema).length(90),\n extractionDays: z.array(memoryCostDaySchema).length(90),\n extractionHours: z.array(memoryCostDaySchema).min(24).optional(),\n generatedAt: z.iso.datetime(),\n hours: z.array(memoryDashboardDaySchema).min(24).optional(),\n recallDays: z.array(memoryCostDaySchema).length(90),\n recallHours: z.array(memoryCostDaySchema).min(24).optional(),\n stats: z\n .object({\n active: z.number().int().min(0),\n automatic: z.number().int().min(0),\n createdThirtyDays: z.number().int().min(0),\n embedded: z.number().int().min(0),\n explicit: z.number().int().min(0),\n knowledge: z.number().int().min(0),\n personal: z.number().int().min(0),\n preference: z.number().int().min(0),\n procedure: z.number().int().min(0),\n public: z.number().int().min(0),\n })\n .strict(),\n })\n .strict();\n\nexport type MemoryApi = z.output<typeof memoryApiSchema>;\nexport type MemoryDashboardResponse = z.output<\n typeof memoryDashboardResponseSchema\n>;\nexport type MemoryListResponse = z.output<typeof memoryListResponseSchema>;\n\nconst memoryListQuerySchema = z\n .object({\n cursor: z.string().min(1).max(1_000).optional(),\n limit: z.coerce.number().int().min(1).max(50).default(25),\n q: z.string().trim().max(200).optional(),\n })\n .strict();\n\ninterface MemoryApiOptions {\n conversationEvents: PluginConversationEventReader;\n db: MemoryDb;\n eventStats: PluginConversationEventStats;\n users: {\n resolve(email: string): Promise<User | undefined>;\n };\n}\n\nfunction json(body: unknown, status = 200): Response {\n return Response.json(body, {\n headers: { \"cache-control\": \"no-store\" },\n status,\n });\n}\n\nfunction apiMemory(memory: MemoryView): z.output<typeof memoryApiSchema> {\n return {\n content: memory.content,\n createdAt: new Date(memory.createdAtMs).toISOString(),\n ...(memory.expiresAtMs !== undefined\n ? { expiresAt: new Date(memory.expiresAtMs).toISOString() }\n : undefined),\n id: memory.id,\n kind: memory.kind,\n observedAt: new Date(memory.observedAtMs).toISOString(),\n origin: memory.origin,\n sourcePlatform: memory.sourcePlatform,\n visibility: memory.visibility,\n };\n}\n\nfunction currentMemoryVisibility(\n scope: \"personal\" | \"conversation\" | \"private\" | \"public\",\n): \"private\" | \"public\" {\n return scope === \"personal\" || scope === \"private\" ? \"private\" : \"public\";\n}\n\nfunction viewerEmail(context: unknown): string | undefined {\n const parsed = pluginApiRouteRequestContextSchema.safeParse(context);\n if (!parsed.success || parsed.data.auth.user.emailVerified !== true) {\n return undefined;\n }\n return parsed.data.auth.user.email?.trim().toLowerCase() || undefined;\n}\n\n/** Create the authenticated memory REST app. */\nexport function createMemoryApi(options: MemoryApiOptions): PluginRouteApp {\n return {\n async fetch(request, context) {\n const email = viewerEmail(context);\n if (!email) {\n return json({ error: \"Authentication required.\" }, 401);\n }\n\n const url = new URL(request.url);\n const memoryPath = /^\\/memories\\/([^/]+)$/.exec(url.pathname);\n const conversationPath = /^\\/conversations\\/([^/]+)\\/memories$/.exec(\n url.pathname,\n );\n const isCollection = url.pathname === \"/memories\";\n const isDashboard = url.pathname === \"/dashboard\";\n if (!isCollection && !isDashboard && !memoryPath && !conversationPath) {\n return json({ error: \"Not found.\" }, 404);\n }\n const isRead = request.method === \"GET\" || request.method === \"HEAD\";\n if (!isRead && !(memoryPath && request.method === \"DELETE\")) {\n return json({ error: \"Method not allowed.\" }, 405);\n }\n\n const viewer = await options.users.resolve(email);\n if (!viewer) return json({ error: \"Authentication required.\" }, 401);\n const userId = viewer.id;\n\n try {\n if (isDashboard && isRead) {\n const [\n stats,\n days,\n hours,\n extractionDays,\n extractionHours,\n recallDays,\n recallHours,\n ] = await Promise.all([\n getMemoryStats(options.db, userId),\n getMemoryTimeline(options.db, userId, 90),\n getMemoryTimelineHours(options.db, userId, 7 * 24),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_captured\",\n }),\n options.eventStats.costsByHour({\n eventName: \"memories_captured\",\n hours: 7 * 24,\n }),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_recalled\",\n }),\n options.eventStats.costsByHour({\n eventName: \"memories_recalled\",\n hours: 7 * 24,\n }),\n ]);\n const { private: personal, ...dashboardStats } = stats;\n const body = memoryDashboardResponseSchema.parse({\n days: days.map(({ private: personal, ...day }) => ({\n ...day,\n personal,\n })),\n extractionDays,\n extractionHours,\n generatedAt: new Date().toISOString(),\n hours: hours.map(({ private: personal, ...day }) => ({\n ...day,\n personal,\n })),\n recallDays,\n recallHours,\n stats: { ...dashboardStats, personal },\n });\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(body);\n }\n\n if (conversationPath && isRead) {\n const events = await options.conversationEvents.list({\n conversationId: decodeURIComponent(conversationPath[1]!),\n eventName: \"memories_captured\",\n viewer,\n });\n if (!events) return json({ error: \"Conversation not found.\" }, 404);\n const memories = new Map<\n string,\n z.input<typeof conversationMemorySchema>\n >();\n for (const event of events) {\n for (const memory of parseCapturedMemories(\n event.version,\n event.content,\n )) {\n if (!memories.has(memory.id)) {\n memories.set(memory.id, {\n capturedAt: event.createdAt,\n content: memory.content,\n id: memory.id,\n kind: memory.kind,\n visibility: currentMemoryVisibility(memory.scope),\n });\n }\n }\n }\n const body = conversationMemoryListResponseSchema.parse({\n memories: [...memories.values()],\n });\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(body);\n }\n\n if (isCollection && isRead) {\n const query = memoryListQuerySchema.parse({\n cursor: url.searchParams.get(\"cursor\") ?? undefined,\n limit: url.searchParams.get(\"limit\") ?? undefined,\n q: url.searchParams.get(\"q\") ?? undefined,\n });\n const page = await listMemories(options.db, userId, {\n cursor: query.cursor,\n limit: query.limit,\n ...(query.q ? { query: query.q } : undefined),\n });\n const body = memoryListResponseSchema.parse({\n memories: page.memories.map(apiMemory),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : undefined),\n });\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(body);\n }\n\n if (memoryPath && isRead) {\n const memory = await getMemory(\n options.db,\n userId,\n decodeURIComponent(memoryPath[1]!),\n );\n const body = memoryApiSchema.parse(apiMemory(memory));\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(body);\n }\n\n if (memoryPath && request.method === \"DELETE\") {\n const id = decodeURIComponent(memoryPath[1]!);\n await archiveMemory(options.db, userId, id);\n return new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 204,\n });\n }\n } catch (error) {\n if (\n error instanceof z.ZodError ||\n error instanceof InvalidMemoryCursorError\n ) {\n return json({ error: \"Invalid memory request.\" }, 400);\n }\n if (error instanceof MemoryNotFoundError) {\n return json({ error: error.message }, 404);\n }\n throw error;\n }\n\n return json({ error: \"Method not allowed.\" }, 405);\n },\n };\n}\n","/**\n * Memory access for an authenticated User.\n *\n * Every User can read public memory and private memory that they own.\n */\nimport {\n and,\n asc,\n desc,\n eq,\n gt,\n ilike,\n isNull,\n like,\n lt,\n or,\n sql,\n} from \"drizzle-orm\";\nimport { z } from \"zod\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport { publicMemoryScope } from \"./scope\";\nimport { parseMemoryRow, type MemoryDb, type MemoryRecord } from \"./store\";\nimport { MEMORY_KINDS, type MemorySourcePlatform } from \"./types\";\n\nconst DAY_MS = 24 * 60 * 60 * 1_000;\nconst nonEmptyStringSchema = z.string().min(1);\nconst memoryVisibilitySchema = z.enum([\"private\", \"public\"]);\nconst cursorSchema = z\n .object({\n createdAtMs: z.number().finite(),\n id: nonEmptyStringSchema,\n kind: z.enum(MEMORY_KINDS).optional(),\n origin: z.enum([\"automatic\", \"explicit\"]).optional(),\n query: z.string().max(200).optional(),\n version: z.literal(1),\n visibility: memoryVisibilitySchema.optional(),\n })\n .strict();\nconst pageInputSchema = z\n .object({\n cursor: z.string().min(1).max(1_000).optional(),\n kind: z.enum(MEMORY_KINDS).optional(),\n limit: z.number().int().min(1).max(50),\n origin: z.enum([\"automatic\", \"explicit\"]).optional(),\n query: z.string().max(200).optional(),\n visibility: memoryVisibilitySchema.optional(),\n })\n .strict();\nconst timelineDaysSchema = z.number().int().min(1).max(365);\n\n/** Access label returned by dashboard and REST memory views. */\nexport type MemoryVisibility = z.output<typeof memoryVisibilitySchema>;\n\n/** Memory fields returned to an authenticated User. */\nexport type MemoryView = MemoryRecord & {\n origin: \"automatic\" | \"explicit\" | \"other\";\n sourcePlatform: MemorySourcePlatform;\n visibility: MemoryVisibility;\n};\n\ninterface MemoryPage {\n memories: MemoryView[];\n nextCursor?: string;\n}\n\ntype MemoryPageInput = z.output<typeof pageInputSchema>;\n\n/** Expected error for a malformed or mismatched page cursor. */\nexport class InvalidMemoryCursorError extends Error {\n constructor() {\n super(\"Memory cursor is invalid.\");\n this.name = \"InvalidMemoryCursorError\";\n }\n}\n\n/** Expected error when the current User cannot access a memory. */\nexport class MemoryNotFoundError extends Error {\n constructor() {\n super(\"Memory was not found for this user.\");\n this.name = \"MemoryNotFoundError\";\n }\n}\n\nfunction publicScopePredicate() {\n return and(\n eq(juniorMemoryMemories.scope, publicMemoryScope.scope),\n eq(juniorMemoryMemories.scopeKey, publicMemoryScope.scopeKey),\n );\n}\n\nfunction privateScopePredicate(userId: string) {\n return and(\n eq(juniorMemoryMemories.scope, \"private\"),\n eq(juniorMemoryMemories.scopeKey, userId),\n );\n}\n\nfunction visibleScopePredicate(userId: string, visibility?: MemoryVisibility) {\n if (visibility === \"public\") return publicScopePredicate();\n if (visibility === \"private\") return privateScopePredicate(userId);\n return or(publicScopePredicate(), privateScopePredicate(userId));\n}\n\nfunction activeMemoryPredicate(\n userId: string,\n nowMs: number,\n visibility?: MemoryVisibility,\n) {\n return and(\n visibleScopePredicate(userId, visibility),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, nowMs),\n ),\n );\n}\n\nfunction utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\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\nfunction memoryOrigin(idempotencyKey: string | null): MemoryView[\"origin\"] {\n if (idempotencyKey?.startsWith(\"session:\")) return \"automatic\";\n if (idempotencyKey?.startsWith(\"tool:\")) return \"explicit\";\n return \"other\";\n}\n\nfunction toMemoryView(\n row: typeof juniorMemoryMemories.$inferSelect,\n): MemoryView {\n const memory = parseMemoryRow(row);\n return {\n ...memory,\n origin: memoryOrigin(row.idempotencyKey),\n sourcePlatform: row.sourcePlatform,\n visibility: memory.scope,\n };\n}\n\nfunction cursorFilters(input: MemoryPageInput) {\n return {\n kind: input.kind,\n origin: input.origin,\n query: input.query?.trim() || undefined,\n visibility: input.visibility,\n };\n}\n\nfunction decodeCursor(\n value: string | undefined,\n filters: ReturnType<typeof cursorFilters>,\n) {\n if (!value) return undefined;\n try {\n const parsed = cursorSchema.parse(\n JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\")),\n );\n if (\n parsed.query !== filters.query ||\n parsed.kind !== filters.kind ||\n parsed.origin !== filters.origin ||\n parsed.visibility !== filters.visibility\n ) {\n throw new InvalidMemoryCursorError();\n }\n return { createdAtMs: parsed.createdAtMs, id: parsed.id };\n } catch {\n throw new InvalidMemoryCursorError();\n }\n}\n\nfunction encodeCursor(\n createdBefore: { createdAtMs: number; id: string },\n filters: ReturnType<typeof cursorFilters>,\n): string {\n return Buffer.from(\n JSON.stringify({ ...createdBefore, ...filters, version: 1 }),\n \"utf8\",\n ).toString(\"base64url\");\n}\n\n/** Archive one active memory visible to the authenticated User: public memory or private memory they own. */\nexport async function archiveMemory(db: MemoryDb, userId: string, id: string) {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = Date.now();\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: \"user_removed\",\n })\n .where(\n and(\n activeMemoryPredicate(userId, nowMs),\n eq(juniorMemoryMemories.id, memoryId),\n ),\n )\n .returning();\n if (!updated[0]) throw new MemoryNotFoundError();\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memoryId));\n return parseMemoryRow(updated[0]);\n}\n\n/** Read one active memory visible to the authenticated User. */\nexport async function getMemory(\n db: MemoryDb,\n userId: string,\n id: string,\n): Promise<MemoryView> {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = Date.now();\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n activeMemoryPredicate(userId, nowMs),\n eq(juniorMemoryMemories.id, memoryId),\n ),\n )\n .limit(1);\n if (!rows[0]) throw new MemoryNotFoundError();\n return toMemoryView(rows[0]);\n}\n\n/** List one stable page of active memory visible to the authenticated User. */\nexport async function listMemories(\n db: MemoryDb,\n userId: string,\n input: MemoryPageInput,\n): Promise<MemoryPage> {\n input = pageInputSchema.parse(input);\n const filters = cursorFilters(input);\n const cursor = decodeCursor(input.cursor, filters);\n const active = activeMemoryPredicate(userId, Date.now(), input.visibility);\n const createdBefore = cursor\n ? or(\n lt(juniorMemoryMemories.createdAtMs, cursor.createdAtMs),\n and(\n eq(juniorMemoryMemories.createdAtMs, cursor.createdAtMs),\n gt(juniorMemoryMemories.id, cursor.id),\n ),\n )\n : undefined;\n const terms = input.query ? searchTerms(input.query) : [];\n const search =\n input.query === undefined\n ? undefined\n : terms.length === 0\n ? sql`false`\n : or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n );\n const kind = input.kind\n ? eq(juniorMemoryMemories.kind, input.kind)\n : undefined;\n const origin =\n input.origin === \"automatic\"\n ? like(juniorMemoryMemories.idempotencyKey, \"session:%\")\n : input.origin === \"explicit\"\n ? like(juniorMemoryMemories.idempotencyKey, \"tool:%\")\n : undefined;\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(active, createdBefore, search, kind, origin))\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(input.limit + 1);\n const memories = rows.slice(0, input.limit).map(toMemoryView);\n const last = memories.at(-1);\n if (rows.length <= input.limit || !last) return { memories };\n const next = { createdAtMs: last.createdAtMs, id: last.id };\n return { memories, nextCursor: encodeCursor(next, filters) };\n}\n\n/** Summarize active memory visible to the authenticated User. */\nexport async function getMemoryStats(db: MemoryDb, userId: string) {\n const nowMs = Date.now();\n const [counts] = await db\n .select({\n active: sql<number>`count(*)`.mapWith(Number),\n automatic:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.idempotencyKey} like 'session:%')`.mapWith(\n Number,\n ),\n createdThirtyDays:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.createdAtMs} >= ${nowMs - 30 * DAY_MS})`.mapWith(\n Number,\n ),\n embedded: sql<number>`count(${juniorMemoryEmbeddings.memoryId})`.mapWith(\n Number,\n ),\n explicit:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.idempotencyKey} like 'tool:%')`.mapWith(\n Number,\n ),\n knowledge:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.kind} = 'knowledge')`.mapWith(\n Number,\n ),\n private:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n preference:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.kind} = 'preference')`.mapWith(\n Number,\n ),\n procedure:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.kind} = 'procedure')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .leftJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(activeMemoryPredicate(userId, nowMs));\n if (!counts) throw new Error(\"Memory stats query returned no row.\");\n return counts;\n}\n\n/** Read daily memory creation totals visible to the authenticated User in UTC. */\nexport async function getMemoryTimeline(\n db: MemoryDb,\n userId: string,\n days: number,\n) {\n days = timelineDaysSchema.parse(days);\n const todayMs = Date.parse(`${utcDate(Date.now())}T00:00:00.000Z`);\n const startMs = todayMs - (days - 1) * DAY_MS;\n const rows = await db\n .select({\n date: sql<string>`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD')`.as(\n \"date\",\n ),\n private:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .where(\n and(\n visibleScopePredicate(userId),\n gt(juniorMemoryMemories.createdAtMs, startMs - 1),\n ),\n )\n .groupBy(\n sql`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD')`,\n );\n const byDate = new Map(rows.map((row) => [row.date, row]));\n return Array.from({ length: days }, (_, index) => {\n const date = utcDate(startMs + index * DAY_MS);\n const row = byDate.get(date);\n return {\n date,\n private: row?.private ?? 0,\n public: row?.public ?? 0,\n };\n });\n}\n\n/** Read hourly memory creation totals visible to the authenticated User in UTC. */\nexport async function getMemoryTimelineHours(\n db: MemoryDb,\n userId: string,\n hours = 24,\n) {\n const end = new Date();\n end.setUTCMinutes(0, 0, 0);\n const startMs = end.getTime() - (hours - 1) * 60 * 60 * 1_000;\n const rows = await db\n .select({\n date: sql<string>`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24')`.as(\n \"date\",\n ),\n private:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .where(\n and(\n visibleScopePredicate(userId),\n gt(juniorMemoryMemories.createdAtMs, startMs - 1),\n ),\n )\n .groupBy(\n sql`to_char(to_timestamp(${juniorMemoryMemories.createdAtMs} / 1000.0) AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24')`,\n );\n const byHour = new Map(rows.map((row) => [row.date, row]));\n return Array.from({ length: hours }, (_, index) => {\n const date = new Date(startMs + index * 60 * 60 * 1_000)\n .toISOString()\n .slice(0, 13);\n const row = byHour.get(date);\n return {\n date,\n private: row?.private ?? 0,\n public: row?.public ?? 0,\n };\n });\n}\n\n","import { defineConversationEvent } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport { MEMORY_KINDS, MEMORY_SCOPES } from \"./types\";\nimport type { MemoryRecord } from \"./store\";\n\nconst capturedMemoryFields = {\n content: z.string().min(1),\n id: z.string().min(1),\n kind: z.enum(MEMORY_KINDS),\n observedAtMs: z.number().finite(),\n};\n\nconst legacyCapturedMemorySchema = z\n .object({\n ...capturedMemoryFields,\n scope: z.enum([\"personal\", \"conversation\"]),\n })\n .strict();\n\nconst capturedMemorySchema = z\n .object({\n ...capturedMemoryFields,\n scope: z.enum(MEMORY_SCOPES),\n })\n .strict();\n\nconst legacyCapturedMemoriesSchema = z\n .object({\n memories: z.array(legacyCapturedMemorySchema).min(1).max(100),\n })\n .strict();\n\nconst capturedMemoriesSchema = z\n .object({\n memories: z.array(capturedMemorySchema).max(100),\n costUsd: z.number().finite().nonnegative().optional(),\n })\n .strict();\n\nconst recalledMemoriesSchema = z\n .object({\n // Matches the automatic-recall candidate window; admission packs by char budget.\n memories: z.array(z.string().min(1)).max(20),\n costUsd: z.number().finite().nonnegative().optional(),\n })\n .strict();\n\nfunction currentScope(\n scope: \"personal\" | \"conversation\" | \"private\" | \"public\",\n) {\n if (scope === \"personal\") return \"private\";\n if (scope === \"conversation\") return \"public\";\n return scope;\n}\n\nfunction renderCapturedMemories(event: {\n memories: Array<\n | z.output<typeof legacyCapturedMemorySchema>\n | z.output<typeof capturedMemorySchema>\n >;\n}) {\n const count = event.memories.length;\n if (count === 0) return undefined;\n return {\n icon: \"brain\" as const,\n title: `${count} ${count === 1 ? \"memory\" : \"memories\"} captured`,\n details: event.memories.map((memory) => ({\n title: memory.content,\n metadata: [memory.kind, currentScope(memory.scope)],\n })),\n };\n}\n\n/** Previous stored memory-capture event shape retained for transcript rendering. */\nexport const memoriesCapturedEventV1 = defineConversationEvent({\n name: \"memories_captured\",\n version: 1,\n schema: legacyCapturedMemoriesSchema,\n renderEvent: renderCapturedMemories,\n});\n\n/** Durable outcome emitted after every completed passive memory extraction. */\nexport const memoriesCapturedEvent = defineConversationEvent({\n name: \"memories_captured\",\n version: 2,\n schema: capturedMemoriesSchema,\n renderEvent: renderCapturedMemories,\n});\n\n/** Durable outcome emitted after one completed automatic recall attempt. */\nexport const memoriesRecalledEvent = defineConversationEvent({\n name: \"memories_recalled\",\n version: 1,\n schema: recalledMemoriesSchema,\n renderEvent() {\n return undefined;\n },\n});\n\ntype CapturedMemory =\n | z.output<typeof legacyCapturedMemorySchema>\n | z.output<typeof capturedMemorySchema>;\n\n/** Parse one supported stored memory-capture event. */\nexport function parseCapturedMemories(\n version: number,\n content: unknown,\n): CapturedMemory[] {\n if (version === memoriesCapturedEventV1.version) {\n return legacyCapturedMemoriesSchema.parse(content).memories;\n }\n if (version === memoriesCapturedEvent.version) {\n return capturedMemoriesSchema.parse(content).memories;\n }\n return [];\n}\n\n/** Select the stable, safe memory fields retained in conversation history. */\nexport function capturedMemory(memory: MemoryRecord) {\n return {\n content: memory.content,\n id: memory.id,\n kind: memory.kind,\n observedAtMs: memory.observedAtMs,\n scope: memory.scope,\n };\n}\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","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 PluginToolOutput,\n type Source,\n type Actor,\n type Identity,\n type User,\n pluginToolOutputSchema,\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 \"Private memory requires a User.\",\n \"User memory requires a User.\",\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 locationId?: string;\n actor?: Actor;\n source: Source;\n users: {\n resolveActor(): Promise<{ identity: Identity; user?: User } | undefined>;\n };\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\nasync function memoryRuntimeContext(\n context: MemoryToolContext,\n): Promise<MemoryRuntimeContext> {\n const actorUser = (await context.users.resolveActor())?.user;\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : undefined),\n ...(context.actor ? { actor: context.actor } : undefined),\n ...(context.locationId ? { locationId: context.locationId } : undefined),\n source: context.source,\n ...(actorUser ? { userId: actorUser.id } : undefined),\n });\n}\n\nfunction memoryStore(\n context: MemoryToolContext,\n runtimeContext: MemoryRuntimeContext,\n options: { supersessionDecider?: MemorySupersessionDecider } = {},\n) {\n return createMemoryStore(context.db, runtimeContext, {\n embedder: context.embedder,\n ...(options.supersessionDecider\n ? { supersessionDecider: options.supersessionDecider }\n : undefined),\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 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 archiveMemoryInputSchema = 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 PluginToolOutput &\n TData & {\n target: string;\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 memoryCreateOutputSchema = pluginToolOutputSchema.extend({\n target: z.string(),\n created: z.boolean(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memorySingleOutputSchema = pluginToolOutputSchema.extend({\n target: z.string(),\n memory: memoryProjectionOutputSchema,\n});\n\nconst memoryManyOutputSchema = pluginToolOutputSchema.extend({\n target: z.string(),\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 : undefined),\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 : undefined),\n });\n}\n\nfunction memoryToolResult<TData extends Record<string, unknown>>(\n target: string,\n data: TData,\n): MemoryStructuredToolResult<TData> {\n return {\n target,\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 approvalMode: \"approve\",\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n },\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 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. Junior sets access, Location, Source, and subject. The memory agent rewrites the content and sets the memory 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 = await memoryRuntimeContext(context);\n const store = memoryStore(context, runtimeContext, {\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 : undefined),\n runtimeContext,\n ...(context.userText?.trim()\n ? {\n sourceContext: {\n currentUserText: context.userText.trim(),\n },\n }\n : undefined),\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 createMemoryArchiveTool(context: MemoryToolContext) {\n return definePluginTool({\n annotations: {\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n },\n description:\n \"Forget one active memory visible in the current context. This includes public memories and private memories owned by the current User. Use only ids or short id prefixes returned by listMemories or searchMemories. Never remove memories by hidden Actor, provider, scope, or subject ids.\",\n executionMode: \"sequential\",\n inputSchema: archiveMemoryInputSchema,\n outputSchema: memorySingleOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(\n archiveMemoryInputSchema,\n input,\n );\n const runtimeContext = await memoryRuntimeContext(context);\n const memory = await (async () => {\n try {\n return await memoryStore(context, runtimeContext).archiveMemory({\n id: parsedInput.id,\n reason: \"tool_removed\",\n });\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"archiveMemory\", {\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: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n },\n inputSchema: listMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(listMemoriesInputSchema, input);\n const runtimeContext = await memoryRuntimeContext(context);\n const memories = await memoryStore(context, runtimeContext).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. Public memories are visible everywhere. Private memories belong to the current User.\",\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n },\n inputSchema: searchMemoriesInputSchema,\n outputSchema: memoryManyOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(\n searchMemoriesInputSchema,\n input,\n );\n const runtimeContext = await memoryRuntimeContext(context);\n const memories = await memoryStore(\n context,\n runtimeContext,\n ).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","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\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 CreateMemoryResult,\n type MemoryDb,\n} from \"./store\";\nimport {\n createMemoryAgent,\n parseExtractedMemory,\n type ExtractedMemory,\n type MemoryExtractionResult,\n} from \"./agent\";\nimport { MEMORY_KINDS, memoryRuntimeContextSchema } from \"./types\";\nimport { capturedMemory, memoriesCapturedEvent } from \"./events\";\n\nconst MEMORY_TOOL_NAMES = new Set([\n \"archiveMemory\",\n \"createMemory\",\n \"listMemories\",\n \"searchMemories\",\n]);\nconst MEMORY_TASK_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst extractedMemorySchema = 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);\nconst extractedMemoryCacheSchema = z.union([\n z\n .object({\n costUsd: z.number().finite().nonnegative().optional(),\n memories: z.array(extractedMemorySchema).max(5),\n })\n .strict(),\n z\n .array(extractedMemorySchema)\n .max(5)\n .transform((memories) => ({ memories })),\n]);\n\n/** Subject for a passively extracted memory, or drop when unproven. */\ntype MemorySubjectTarget = \"drop\" | \"user\" | \"conversation\";\n\nfunction recordCapturedMemory(\n captured: ReturnType<typeof capturedMemory>[],\n result: CreateMemoryResult,\n): void {\n const supersededIds = new Set(result.supersededIds ?? []);\n for (let index = captured.length - 1; index >= 0; index -= 1) {\n if (supersededIds.has(captured[index]!.id)) {\n captured.splice(index, 1);\n }\n }\n if (result.created || result.idempotent) {\n captured.push(capturedMemory(result.memory));\n }\n}\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\" | \"actorUserId\">,\n): MemorySubjectTarget {\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 human run actor may store a preference.\n const exactlyOneHumanRunActor =\n run.actorUserId !== undefined &&\n run.actor !== undefined &&\n run.actor.platform !== \"system\" &&\n run.actors.length === 1 &&\n run.actors[0]?.platform !== \"system\";\n if (!exactlyOneHumanRunActor) {\n return \"drop\";\n }\n // Never downgrade an unproven first-person preference to conversation subject.\n return cited.entries.every(isRunActorInstruction) ? \"user\" : \"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: MemorySubjectTarget,\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: MemorySubjectTarget,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory, target)}`,\n kind: memory.kind,\n ...(memory.expiresAtMs !== null\n ? { expiresAtMs: memory.expiresAtMs }\n : undefined),\n };\n}\n\nasync function getTaskExtraction(\n context: PluginTaskContext,\n extract: () => Promise<MemoryExtractionResult>,\n): Promise<MemoryExtractionResult> {\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 extraction = await extract();\n await context.state.set(cacheKey, extraction, MEMORY_TASK_STATE_TTL_MS);\n return extraction;\n}\n\n/**\n * Extract and store memories from a completed session plugin task.\n *\n * Memory owns learning after a run and reads only the plugin run data.\n * Explicit memory tools stay separate so retries do not reinterpret user\n * requests.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // TODO(dcramer): Replace this hardcoded Source check when a plugin Run can\n // state whether passive memory extraction should run.\n if (run.source.kind !== \"slack\" && run.source.kind !== \"web\") {\n return;\n }\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 const sourceKey = getSourceKey(run.source);\n if (!sourceKey || (run.source.visibility === \"private\" && !run.actorUserId)) {\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.locationId ? { locationId: run.locationId } : undefined),\n ...(run.actor ? { actor: run.actor } : undefined),\n source: run.source,\n ...(run.actorUserId ? { userId: run.actorUserId } : undefined),\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 extraction = await getTaskExtraction(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\n const captured: ReturnType<typeof capturedMemory>[] = [];\n for (const memory of extraction.memories) {\n // The routing gate stays even though extraction is also actor-gated:\n // getTaskExtraction 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 const result = await store.createConversationMemory(input);\n recordCapturedMemory(captured, result);\n continue;\n }\n const result = await store.createMemory(input);\n recordCapturedMemory(captured, result);\n }\n await context.events.emit(\n memoriesCapturedEvent({\n memories: captured,\n ...(extraction.costUsd !== undefined\n ? { costUsd: extraction.costUsd }\n : undefined),\n }),\n );\n}\n","import {\n definePromptContext,\n type UserPromptContribution,\n type Actor,\n type Identity,\n type PluginConversationEvents,\n type PluginLogger,\n type Source,\n type User,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport type { MemoryAgent, MemoryRecallResult } from \"./agent\";\nimport { memoriesRecalledEvent } from \"./events\";\nimport {\n createMemoryStore,\n type MemoryDb,\n type MemoryEmbeddingProvider,\n type MemoryRecord,\n} from \"./store\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst RECALL_CANDIDATE_LIMIT = 20;\nconst MAX_PROMPT_CHARS = 4_000;\nconst MAX_MEMORY_LINE_CHARS = 600;\n\nexport interface MemoryRecallContext {\n agent: Pick<MemoryAgent, \"selectRelevantMemories\">;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n events?: PluginConversationEvents;\n log: PluginLogger;\n locationId?: string;\n actor?: Actor;\n source: Source;\n text: string;\n users: {\n resolveActor(): Promise<{ identity: Identity; user?: User } | undefined>;\n };\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\nconst recalledMemorySchema = z\n .object({\n id: z.string().min(1),\n content: z.string().min(1).max(MAX_MEMORY_LINE_CHARS),\n observedAtMs: z.number().finite(),\n // Stored version 1 uses the old scope labels. Prompt rendering ignores them.\n scope: z.enum([\"personal\", \"conversation\"]),\n kind: z.enum([\"preference\", \"procedure\", \"knowledge\"]),\n })\n .strict();\n\n/** Structured snapshot retained for one automatic memory recall. */\nexport const memoryRecallContextSchema = z\n .object({\n // Count is a safety rail only. Admission packs by MAX_PROMPT_CHARS.\n memories: z.array(recalledMemorySchema).min(1).max(RECALL_CANDIDATE_LIMIT),\n })\n .strict();\n\ntype RecalledMemory = z.output<typeof recalledMemorySchema>;\n\nfunction selectPromptMemories(memories: MemoryRecord[]): RecalledMemory[] {\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 selected: RecalledMemory[] = [];\n let totalChars = header.length + footer.length + 2;\n\n for (const memory of memories) {\n const content = trimContent(memory.content, MAX_MEMORY_LINE_CHARS);\n const line = `- Observed ${formatObservedDate(memory.observedAtMs)}: ${content}`;\n if (totalChars + line.length + 1 > MAX_PROMPT_CHARS) {\n break;\n }\n selected.push({\n id: memory.id,\n content,\n observedAtMs: memory.observedAtMs,\n scope: memory.scope === \"private\" ? \"personal\" : \"conversation\",\n kind: memory.kind,\n });\n totalChars += line.length + 1;\n }\n return selected;\n}\n\nfunction renderMemoryPrompt(memories: RecalledMemory[]): string {\n return [\n \"Relevant memories for this request:\",\n ...memories.map(\n (memory) =>\n `- Observed ${formatObservedDate(memory.observedAtMs)}: ${memory.content}`,\n ),\n \"\",\n \"Treat these as possibly stale context. Current user instructions and repository evidence take priority.\",\n ].join(\"\\n\");\n}\n\nfunction addUsd(\n left: number | undefined,\n right: number | undefined,\n): number | undefined {\n if (left === undefined) return right;\n if (right === undefined) return left;\n return Math.round((left + right) * 1e12) / 1e12;\n}\n\nasync function emitRecallOutcome(args: {\n costUsd?: number;\n events?: PluginConversationEvents;\n memories: string[];\n}): Promise<void> {\n await args.events?.emit(\n memoriesRecalledEvent({\n memories: args.memories,\n ...(args.costUsd !== undefined ? { costUsd: args.costUsd } : undefined),\n }),\n );\n}\n\nconst memoryRecallContext = definePromptContext({\n kind: \"recall\",\n version: 1,\n schema: memoryRecallContextSchema,\n renderPrompt: (content) => renderMemoryPrompt(content.memories),\n});\n\n/** Build active memory recall contributions. */\nexport async function createMemoryPromptContributions(\n context: MemoryRecallContext,\n): Promise<UserPromptContribution[] | undefined> {\n if (!context.text.trim()) {\n return undefined;\n }\n const actorUser = (await context.users.resolveActor())?.user;\n const runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : undefined),\n ...(context.actor ? { actor: context.actor } : undefined),\n ...(context.locationId ? { locationId: context.locationId } : undefined),\n source: context.source,\n ...(actorUser ? { userId: actorUser.id } : undefined),\n });\n let embeddingCostUsd: number | undefined;\n const sourceEmbedder = context.embedder;\n const embedder = sourceEmbedder\n ? {\n async embedTexts(input: { texts: string[] }) {\n const result = await sourceEmbedder.embedTexts(input);\n embeddingCostUsd = addUsd(embeddingCostUsd, result.costUsd);\n return result;\n },\n }\n : undefined;\n const candidates = await createMemoryStore(context.db, runtimeContext, {\n embedder,\n }).recallMemories({\n query: context.text,\n limit: RECALL_CANDIDATE_LIMIT,\n });\n if (candidates.length === 0) {\n await emitRecallOutcome({\n ...(embeddingCostUsd !== undefined ? { costUsd: embeddingCostUsd } : undefined),\n events: context.events,\n memories: [],\n });\n return undefined;\n }\n let recall: MemoryRecallResult;\n try {\n recall = await context.agent.selectRelevantMemories({\n candidates: candidates.map(({ content, id }) => ({ content, id })),\n userRequest: context.text,\n });\n } catch {\n // Automatic recall is optional context; a relevance-model failure must not\n // prevent the user's turn from continuing without recalled memory.\n context.log.warn(\"memory_recall_selection_failed\");\n return undefined;\n }\n const candidatesById = new Map(\n candidates.map((memory) => [memory.id, memory]),\n );\n const relevant = recall.relevantIds\n .map((id) => candidatesById.get(id))\n .filter((memory): memory is MemoryRecord => memory !== undefined);\n const selected = selectPromptMemories(relevant);\n const costUsd = addUsd(embeddingCostUsd, recall.costUsd);\n await emitRecallOutcome({\n ...(costUsd !== undefined ? { costUsd } : undefined),\n events: context.events,\n memories: selected.map(({ id }) => id),\n });\n if (selected.length === 0) {\n return undefined;\n }\n return [memoryRecallContext({ memories: selected })];\n}\n","import type {\n PluginConversationEventCostDay,\n PluginOperationalReportContent,\n} from \"@sentry/junior-plugin-api\";\nimport { and, eq, gt, isNull, or, sql } from \"drizzle-orm\";\nimport { z } from \"zod\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport type { MemoryDb } from \"./store\";\n\nconst DAY_MS = 24 * 60 * 60 * 1_000;\n// TODO: add hour categories + `1` when these system widgets can plot 24h hourly.\nconst WINDOWS = [7, 30, 90] as const;\n\nconst memoryDaySchema = z\n .object({\n date: z.string().date(),\n private: z.number().int().nonnegative(),\n public: z.number().int().nonnegative(),\n })\n .strict();\n\nfunction queryRows(result: unknown): unknown[] {\n if (\n typeof result !== \"object\" ||\n result === null ||\n !(\"rows\" in result) ||\n !Array.isArray(result.rows)\n ) {\n throw new TypeError(\"Memory activity query did not return rows\");\n }\n return result.rows;\n}\n\nfunction startOfUtcDay(value: number): Date {\n const date = new Date(value);\n date.setUTCHours(0, 0, 0, 0);\n return date;\n}\n\nasync function aggregateMemoryDays(args: { db: MemoryDb; nowMs: number }) {\n const end = startOfUtcDay(args.nowMs);\n const start = startOfUtcDay(args.nowMs - (WINDOWS.at(-1)! - 1) * DAY_MS);\n const endExclusiveMs = end.getTime() + DAY_MS;\n const table = juniorMemoryMemories;\n const result = await args.db.execute(sql`\n WITH days AS (\n SELECT generate_series(\n date_trunc('day', ${start}::timestamptz AT TIME ZONE 'UTC'),\n date_trunc('day', ${end}::timestamptz AT TIME ZONE 'UTC'),\n interval '1 day'\n ) AS day\n ), daily AS (\n SELECT\n date_trunc(\n 'day',\n to_timestamp(${table.createdAtMs} / 1000.0) AT TIME ZONE 'UTC'\n ) AS day,\n count(*) FILTER (\n WHERE ${table.scope} = 'private'\n )::integer AS private,\n count(*) FILTER (\n WHERE ${table.scope} = 'public'\n )::integer AS public\n FROM ${table}\n WHERE ${table.createdAtMs} >= ${start.getTime()}\n AND ${table.createdAtMs} < ${endExclusiveMs}\n GROUP BY date_trunc(\n 'day',\n to_timestamp(${table.createdAtMs} / 1000.0) AT TIME ZONE 'UTC'\n )\n )\n SELECT\n to_char(days.day, 'YYYY-MM-DD') AS date,\n coalesce(daily.private, 0)::integer AS private,\n coalesce(daily.public, 0)::integer AS public\n FROM days\n LEFT JOIN daily ON daily.day = days.day\n ORDER BY days.day\n `);\n return z.array(memoryDaySchema).parse(queryRows(result));\n}\n\nfunction formatCount(value: number): string {\n return new Intl.NumberFormat(\"en-US\").format(value);\n}\n\nfunction formatPercent(value: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n maximumFractionDigits: 0,\n style: \"percent\",\n }).format(value);\n}\n\nfunction formatUsd(value: number): string {\n const maximumFractionDigits = value > 0 && value < 0.01 ? 4 : 2;\n return new Intl.NumberFormat(\"en-US\", {\n currency: \"USD\",\n maximumFractionDigits,\n minimumFractionDigits: 2,\n style: \"currency\",\n }).format(value);\n}\n\n/** Build aggregate memory storage and indexing diagnostics for the System page. */\nexport async function buildMemoryOperationalReport(args: {\n db: MemoryDb;\n extractionDays: PluginConversationEventCostDay[];\n nowMs: number;\n}): Promise<PluginOperationalReportContent> {\n const active = and(\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 const [[counts], memoryDays] = await Promise.all([\n args.db\n .select({\n active: sql<number>`count(*) filter (where ${active})`.mapWith(Number),\n public:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'public')`.mapWith(\n Number,\n ),\n createdThirtyDays:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.createdAtMs} >= ${args.nowMs - 30 * DAY_MS})`.mapWith(\n Number,\n ),\n embedded:\n sql<number>`count(${juniorMemoryEmbeddings.memoryId}) filter (where ${active})`.mapWith(\n Number,\n ),\n private:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'private')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .leftJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n ),\n aggregateMemoryDays(args),\n ]);\n\n const activeCount = counts?.active ?? 0;\n const embeddedCount = counts?.embedded ?? 0;\n const embeddingCoverage = activeCount === 0 ? 0 : embeddedCount / activeCount;\n const extractionThirtyDays = args.extractionDays.slice(-30);\n const extractionCostThirtyDays = extractionThirtyDays.reduce(\n (total, day) => total + day.costUsd,\n 0,\n );\n\n return {\n generatedAt: new Date(args.nowMs).toISOString(),\n title: \"Memory\",\n metrics: [\n {\n label: \"active memories\",\n tone: activeCount > 0 ? \"good\" : \"neutral\",\n value: formatCount(activeCount),\n },\n {\n label: \"extraction cost · 30d\",\n value: formatUsd(extractionCostThirtyDays),\n },\n {\n label: \"created · 30d\",\n value: formatCount(counts?.createdThirtyDays ?? 0),\n },\n {\n label: \"private\",\n value: formatCount(counts?.private ?? 0),\n },\n {\n label: \"public\",\n value: formatCount(counts?.public ?? 0),\n },\n {\n label: \"embedding coverage\",\n tone:\n activeCount === 0\n ? \"neutral\"\n : embeddedCount === activeCount\n ? \"good\"\n : \"warning\",\n value: formatPercent(embeddingCoverage),\n },\n ],\n widgets: [\n {\n categories: args.extractionDays.map((day) => ({\n id: day.date,\n label: day.date,\n values: { costUsd: day.costUsd },\n })),\n description: \"Estimated model cost of passive memory extraction\",\n id: \"extraction-cost\",\n series: [{ format: \"usd\", key: \"costUsd\", label: \"Cost\" }],\n timeRangeDays: [...WINDOWS],\n title: \"Extraction cost\",\n type: \"bar_chart\",\n },\n {\n categories: memoryDays.map((day) => ({\n id: day.date,\n label: day.date,\n values: {\n private: day.private,\n public: day.public,\n },\n })),\n description: \"Memories stored by scope\",\n id: \"memories-created\",\n series: [\n { key: \"private\", label: \"Private\" },\n { key: \"public\", label: \"Public\" },\n ],\n timeRangeDays: [...WINDOWS],\n title: \"Memories created\",\n type: \"bar_chart\",\n },\n ],\n };\n}\n","/** Render memory in Junior's User page format. */\nimport type { PluginUserPageDefinition } from \"@sentry/junior-plugin-api\";\nimport { listMemories, type MemoryVisibility, type MemoryView } from \"./viewer\";\nimport type { MemoryDb } from \"./store\";\n\nfunction titleCase(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nfunction rememberedDate(createdAtMs: number): string {\n return new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n timeZone: \"UTC\",\n }).format(new Date(createdAtMs));\n}\n\nfunction originLabel(origin: MemoryView[\"origin\"]): string {\n if (origin === \"automatic\") return \"Automatic\";\n if (origin === \"explicit\") return \"Explicit\";\n return \"Other\";\n}\n\nfunction visibilityLabel(visibility: MemoryVisibility): string {\n return visibility === \"public\" ? \"Public\" : \"Private\";\n}\n\nfunction pageFilter(filter: string | undefined): {\n visibility?: MemoryVisibility;\n} {\n if (filter === \"private\") return { visibility: \"private\" };\n if (filter === \"public\") return { visibility: \"public\" };\n return {};\n}\n\nfunction pageEmptyText(input: { filter?: string; query?: string }): string {\n if (input.query) return \"No memories matched your search.\";\n if (input.filter === \"private\") return \"No private memories yet.\";\n if (input.filter === \"public\") return \"No public memories yet.\";\n return \"No memories yet.\";\n}\n\n/** Create the interactive Memories dashboard page. */\nexport function createMemoryUserPage(): PluginUserPageDefinition {\n return {\n id: \"memories\",\n label: \"Memories\",\n navigation: \"primary\",\n description:\n \"Personal and public memories Junior can use across conversations.\",\n async read(ctx, input) {\n const page = await listMemories(ctx.db as MemoryDb, ctx.viewer.id, {\n cursor: input.cursor,\n ...pageFilter(input.filter),\n limit: input.limit,\n ...(input.query ? { query: input.query } : undefined),\n });\n return {\n type: \"list\",\n emptyText: pageEmptyText(input),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : undefined),\n searchPlaceholder: \"Search memories\",\n records: page.memories.map((memory) => ({\n actions:\n memory.visibility === \"private\"\n ? [\n {\n confirmation: \"Forget this memory?\",\n href: `/api/plugins/memory/memories/${encodeURIComponent(memory.id)}`,\n label: \"Forget\",\n method: \"DELETE\" as const,\n tone: \"danger\" as const,\n },\n ]\n : [],\n id: memory.id,\n title: memory.content,\n metadata: [\n { label: \"Type\", value: titleCase(memory.kind) },\n { label: \"Learned\", value: originLabel(memory.origin) },\n { label: \"Source\", value: titleCase(memory.sourcePlatform) },\n {\n label: \"Visibility\",\n value: visibilityLabel(memory.visibility),\n },\n { label: \"Remembered\", value: rememberedDate(memory.createdAtMs) },\n { label: \"Observed\", value: rememberedDate(memory.observedAtMs) },\n {\n label: \"Expires\",\n value: memory.expiresAtMs\n ? rememberedDate(memory.expiresAtMs)\n : \"Never\",\n },\n ],\n })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ACF,IACA;AAAA,IACN;AAAA,EACF,CAAC;AACH;","names":["actorSchema","z","sql","z","nonEmptyStringSchema","z","index","text","sql","idempotent","z","actorSchema","index","z","and","asc","desc","eq","gt","isNull","like","or","sql","z","nonEmptyStringSchema","z","and","eq","visibleScopePredicate","or","isNull","gt","sql","like","desc","asc","index","z","z","z","personal","and","desc","eq","gt","ilike","isNull","or","or","isNull","gt","eq","ilike","and","desc","eq","eq","getSourceKey","z","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","z","archiveMemoryInputSchema","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","getSourceKey","createHash","getSourceKey","z","extractedMemorySchema","z","index","createHash","sourceKey","getSourceKey","result","z","z","and","eq","gt","isNull","or","sql","z","DAY_MS","z","sql","and","isNull","or","gt","eq"]}