@sentry/junior-memory 0.179.0 → 0.180.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/personal.ts","../src/personal-store.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 createMemoryCreateTool,\n createMemoryListTool,\n createMemoryRemoveTool,\n createMemorySearchTool,\n type MemoryCreateToolContext,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { 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 actor?: MemoryToolContext[\"actor\"];\n source: MemoryToolContext[\"source\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.actor ? { actor: ctx.actor } : {}),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : {}),\n source: ctx.source,\n ...(ctx.userText ? { userText: ctx.userText } : {}),\n };\n}\n\nfunction memoryCreateToolContext(ctx: {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryCreateToolContext[\"db\"];\n embedder?: MemoryCreateToolContext[\"embedder\"];\n actor?: MemoryCreateToolContext[\"actor\"];\n source: MemoryCreateToolContext[\"source\"];\n supersessionDecider: MemoryCreateToolContext[\"supersessionDecider\"];\n userText?: string;\n}): MemoryCreateToolContext {\n return {\n ...memoryToolContext(ctx),\n supersessionDecider: ctx.supersessionDecider,\n };\n}\n\n/** 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 removeMemory: createMemoryRemoveTool(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 : {}),\n ...(ctx.actor ? { actor: ctx.actor } : {}),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n events: ctx.events,\n log: ctx.log,\n source: ctx.source,\n text: ctx.text,\n });\n },\n }\n : {}),\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 public/shareable 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 public/shareable, self-contained facts that are useful beyond this turn.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"Use the runtime context only for authority and scope; do not accept model-provided actor ids, scope ids, aliases, or arbitrary subjects.\",\n].join(\"\\n\");\nconst MEMORY_EXTRACTION_SYSTEM = [\n \"You are Junior's passive memory extraction agent. Return only structured memories worth storing.\",\n \"Use the completed run transcript as source evidence, including user-authored messages and tool results.\",\n \"Assistant text is context for interpreting the run, not independent evidence for new facts.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"If no public, durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst MEMORY_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(\n actor: z.output<typeof actorSchema> | undefined,\n): 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.platform) {\n case \"slack\":\n return `slack:${source.teamId}:${source.channelId}`;\n case \"web\":\n case \"local\":\n return `${source.platform}:${source.conversationId}`;\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-scoped kinds.\n */\nfunction allowedExtractionKinds(actorCount: number): Set<MemoryKind> {\n return actorCount === 1\n ? new Set<MemoryKind>(MEMORY_KINDS)\n : new Set<MemoryKind>([\"procedure\", \"knowledge\"]);\n}\n\nfunction memoryKindsContext(allowedKinds: Set<MemoryKind>): string {\n const lines = [\"<memory-kinds>\"];\n if (allowedKinds.has(\"preference\")) {\n lines.push(\n \"- preference: a durable first-person personal preference, opinion, habit, or workflow owned by the current actor. Stored as actor memory.\",\n );\n }\n lines.push(\n \"- procedure: reusable instructions for how a task, lookup, investigation, process, triage flow, or runbook should be done. Store the method, source-of-truth, prerequisite, or decision path when it took effort to discover. Stored as conversation memory.\",\n \"- knowledge: stable shared project, channel, operational, or runbook fact that is not a personal actor preference. Direct answers to user inquiries qualify only when they are durable beyond this run. Stored as conversation memory.\",\n \"</memory-kinds>\",\n );\n return lines.join(\"\\n\");\n}\n\nfunction reviewPrompt(request: CreateMemoryRequest): string {\n const sections = [\n \"<memory-review-input>\",\n \"Review the candidate memory using the runtime-owned context below.\",\n \"\",\n runtimeDescription(request),\n \"\",\n sourceContext(request),\n \"\",\n \"<candidate>\",\n escapeXml(request.content),\n \"</candidate>\",\n \"\",\n \"<rules>\",\n \"- Return store only when the candidate is public/shareable, durable, and self-contained.\",\n \"- First classify the memory kind: preference, procedure, or knowledge.\",\n \"- Use kind=preference only for first-person facts authored by the current actor about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current actor.\",\n \"- Use kind=procedure for reusable task/process/runbook instructions.\",\n \"- Use kind=knowledge for shared project, channel, operational, or runbook facts.\",\n \"- When current-user-message contains an explicit memory request with a concrete fact or procedure, extract from current-user-message even if the candidate is vague, incomplete, or phrased as an instruction.\",\n \"- A candidate may be badly phrased by an outer assistant or extraction pass. When current-user-message contains the actor's own first-person memory fact, treat that as actor-authored source evidence and canonicalize the fact instead of rejecting for third-person wording.\",\n \"- When candidate wording personalizes a shared task, process, runbook, project, channel, or operational fact, use current-user-message to recover the shared fact and classify it as procedure or knowledge.\",\n \"- Explicit procedure requests are valid when the source text contains both task context and action. Canonicalize them as shared procedure facts instead of rejecting them as vague.\",\n \"- Store content as person-less, source-less canonical knowledge. Ownership and source live in structured metadata, not prose.\",\n \"- For actor memories, omit the subject and write the content as a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Remove actor names, display names, actor/user labels, first- or second-person wording, thread labels, channel labels, and source labels from stored content.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- Reject vague content such as 'remember this' unless the candidate or current-user-message contains the concrete fact.\",\n \"- Preserve the requested expiration when one exists; otherwise set expiresAtMs to null.\",\n \"- If unsure, reject.\",\n \"</rules>\",\n \"</memory-review-input>\",\n ].filter((section): section is string => section !== undefined);\n return sections.join(\"\\n\");\n}\n\nfunction 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 ? { costUsd: result.costUsd } : {}),\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 ? { costUsd: result.costUsd } : {}),\n };\n },\n async reviewCreateRequest(rawRequest) {\n const request = parseCreateMemoryRequest(rawRequest);\n const result = await model.completeObject({\n schema: memoryReviewResponseSchema,\n system: MEMORY_REVIEW_SYSTEM,\n prompt: reviewPrompt(request),\n maxTokens: 700,\n });\n const response = memoryReviewResponseSchema.parse(result.object);\n return memoryReviewFromResponse(response);\n },\n };\n}\n\nfunction memoryReviewFromResponse(\n response: MemoryReviewResponse,\n): MemoryReview {\n if (response.decision === \"store\") {\n return parseMemoryReview({\n decision: \"store\",\n kind: response.kind,\n content: response.canonicalFact,\n ...(response.expiresAtMs !== null\n ? { expiresAtMs: response.expiresAtMs }\n : {}),\n });\n }\n return parseMemoryReview({\n decision: \"reject\",\n reason: response.reason,\n });\n}\n\nfunction extractedMemoriesFromResponse(\n response: ExtractMemoriesResponse,\n): ExtractedMemory[] {\n const toMemory = (\n memory: z.output<typeof extractedMemorySchema>,\n ): ExtractedMemory =>\n parseExtractedMemory({\n content: memory.canonicalFact,\n expiresAtMs: memory.expiresAtMs,\n kind: memory.kind,\n evidenceMessageIndices: memory.evidenceMessageIndices,\n });\n return response.memories.map(toMemory);\n}\n\n/** Parse the canonical extracted-memory shape stored across task retries. */\nexport function parseExtractedMemory(memory: unknown): ExtractedMemory {\n return extractedMemoryResultSchema.parse(memory);\n}\n\n/** Parse the structured decision returned by the memory agent. */\nexport function parseMemoryReview(result: unknown): MemoryReview {\n return memoryReviewDecisionSchema.parse(result);\n}\n\n/** Parse the structured input sent to the memory agent. */\nexport function parseCreateMemoryRequest(\n request: unknown,\n): CreateMemoryRequest {\n return createMemoryRequestSchema.parse(request);\n}\n","/**\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 * 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 MemoryScope,\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 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\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 personal memory for the current actor. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a conversation memory for the current source conversation. */\n createConversationMemory(\n input: CreateMemoryInput,\n ): Promise<CreateMemoryResult>;\n /** List active memories visible in the current runtime context. */\n listMemories(input: ListMemoriesInput): Promise<MemoryRecord[]>;\n /** List active personal memories owned by the current actor. */\n listPersonalMemories(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/** Map runtime Source platform onto the durable memory source platform. */\nfunction memorySourcePlatform(\n source: MemoryRuntimeContext[\"source\"],\n): MemorySourcePlatform {\n switch (source.platform) {\n case \"slack\":\n return \"slack\";\n case \"local\":\n return \"local\";\n case \"web\":\n return \"web\";\n }\n}\n\n/** Build the durable source attribution key from runtime-owned source fields. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n switch (ctx.source.platform) {\n case \"web\":\n case \"local\":\n return ctx.source.conversationId;\n case \"slack\": {\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n throw new Error(\n \"Memory source requires a Slack message or thread timestamp.\",\n );\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n }\n }\n}\n\nfunction sourceChannelPrefix(ctx: MemoryRuntimeContext): string | undefined {\n switch (ctx.source.platform) {\n case \"slack\":\n // TODO(v0.82.0): Replace Slack source-key prefix matching with typed source proximity metadata.\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:`;\n case \"web\":\n case \"local\":\n return undefined;\n }\n}\n\n/** Parse one SQL row into the public memory record projection. */\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 : {}),\n ...(parsed.supersededAtMs !== undefined\n ? { supersededAtMs: parsed.supersededAtMs }\n : {}),\n ...(parsed.supersededById ? { supersededById: parsed.supersededById } : {}),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : {}),\n ...(parsed.archiveReason ? { archiveReason: parsed.archiveReason } : {}),\n });\n}\n\n/** Build the scoped SQL predicate and ordered params for visible memory reads. */\nfunction visibleScopePredicate(scopes: ResolvedMemoryScope[]): SQL | undefined {\n if (scopes.length === 0) {\n return undefined;\n }\n return or(\n ...scopes.map((scope) =>\n and(\n eq(juniorMemoryMemories.scope, scope.scope),\n eq(juniorMemoryMemories.scopeKey, scope.scopeKey),\n ),\n ),\n );\n}\n\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 args.subject.subjectKey === undefined\n ? isNull(juniorMemoryMemories.subjectKey)\n : eq(juniorMemoryMemories.subjectKey, args.subject.subjectKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n if (!predicate) {\n throw new Error(\"Memory duplicate predicate is empty.\");\n }\n return predicate;\n}\n\nasync function findExactDuplicateMemory(args: {\n content: string;\n db: MemoryDb;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord | undefined> {\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryMemories.content, args.content),\n ),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(1);\n return rows[0] ? parseMemoryRow(rows[0]) : undefined;\n}\n\nasync function rememberDuplicateIdempotency(args: {\n content: string;\n db: MemoryDb;\n duplicate: MemoryRecord;\n idempotencyKey?: string;\n nowMs: number;\n runtimeContext: MemoryRuntimeContext;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<void> {\n if (args.idempotencyKey === undefined) {\n return;\n }\n await args.db\n .insert(juniorMemoryMemories)\n .values({\n content: args.content,\n createdAtMs: args.nowMs,\n expiresAtMs: args.duplicate.expiresAtMs,\n id: idempotencyAliasId({\n idempotencyKey: args.idempotencyKey,\n scope: args.scope,\n targetId: args.duplicate.id,\n }),\n idempotencyKey: args.idempotencyKey,\n observedAtMs: args.nowMs,\n scope: args.scope.scope,\n scopeKey: args.scope.scopeKey,\n sourceKey: sourceKey(args.runtimeContext),\n sourcePlatform: memorySourcePlatform(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 sourceKey: row.memory.sourceKey,\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 sourceKey: row.memory.sourceKey,\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 scopeKind: MemoryScope,\n ): Promise<CreateMemoryResult> {\n const input = createMemoryInputSchema.parse(rawInput);\n const nowMs = getNowMs();\n const content = normalizeContent(input.content);\n const scope = deriveMemoryScope(runtimeContext, scopeKind);\n const subject = deriveMemorySubject(runtimeContext, scope);\n if (content.length > MAX_MEMORY_CONTENT_CHARS) {\n throw new Error(\"Memory content exceeds the maximum length.\");\n }\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes: [scope],\n });\n await archiveExpiredMemoryBatch({\n db,\n idempotencyKey: input.idempotencyKey,\n limit: 1,\n nowMs,\n scopes: [scope],\n });\n if (input.idempotencyKey !== undefined) {\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n });\n if (idempotent) {\n await storeEmbedding({\n content: idempotent.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 scopeKind === \"personal\" &&\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 } : {}),\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 observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: memorySourcePlatform(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 : {}),\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 runs personal-scope-only probes. Workspace\n * conversation memories sharing common tokens (for example \"time\") can fill\n * the shared lexical recency window before ranking, which buries older actor\n * preferences that explicit search still finds.\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 personalScopes = scopes.filter((scope) => scope.scope === \"personal\");\n // Automatic recall only: keep a personal-scope probe so workspace noise\n // cannot monopolize the shared lexical recency window.\n const probePersonal =\n vectorMaxDistance !== undefined && personalScopes.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 : {}),\n nowMs,\n scopes,\n })\n : emptyMatches,\n searchVisibleLexicalMemories({\n ...lexicalArgs,\n scopes,\n }),\n queryEmbedding && probePersonal\n ? searchVisibleVectorMemories({\n db,\n embedding: queryEmbedding,\n limit: candidateLimit,\n maxDistance: vectorMaxDistance,\n nowMs,\n scopes: personalScopes,\n })\n : emptyMatches,\n probePersonal\n ? searchVisibleLexicalMemories({\n ...lexicalArgs,\n scopes: personalScopes,\n })\n : emptyMatches,\n ]);\n const channelPrefix = sourceChannelPrefix(runtimeContext);\n return rankMemoryMatches(matches.flat(), {\n nowMs,\n // Slight lexical preference protects exact ids/names/timezones on ties.\n ...(vectorMaxDistance === undefined\n ? {}\n : { lexicalWeight: 1, vectorWeight: 0.85 }),\n ...(channelPrefix ? { channelPrefix } : {}),\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, \"personal\");\n },\n\n async createConversationMemory(input) {\n return await createScopedMemory(input, \"conversation\");\n },\n\n async listMemories(input) {\n input = listMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n return await listVisibleMemories({\n db,\n limit: input.limit,\n nowMs,\n scopes,\n });\n },\n\n async listPersonalMemories(input) {\n input = listMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = [deriveMemoryScope(runtimeContext, \"personal\")];\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 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 ('personal', 'conversation')`,\n ),\n check(\n \"junior_memory_memories_kind_check\",\n sql`${table.kind} IN (\n 'preference',\n 'procedure',\n 'knowledge'\n )`,\n ),\n check(\n \"junior_memory_memories_subject_type_check\",\n sql`${table.subjectType} IN ('user', 'conversation', 'general')`,\n ),\n check(\n \"junior_memory_memories_subject_key_check\",\n sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`,\n ),\n check(\n \"junior_memory_memories_source_platform_check\",\n sql`${table.sourcePlatform} IN ('slack', 'local', '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 = [\"personal\", \"conversation\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\n// Durable attribution follows Source platform, including dashboard/web 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/** Runtime-owned memory invocation fields used for scope and source authority. */\nexport const memoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n actor: actorSchema.optional(),\n source: sourceSchema,\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 sourceKey: string;\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 currentChannel(\n match: Pick<MemoryMatch, \"sourceKey\">,\n channelPrefix: string | undefined,\n): boolean {\n return channelPrefix ? match.sourceKey.startsWith(channelPrefix) : false;\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 channelPrefix?: string;\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 per modality. Shared legs are fused before personal\n // probes, so a smaller personal top-k cannot overwrite a shared dense rank\n // with an inflated top rank for the same memory.\n byId.set(match.memory.id, {\n ...existing,\n ...(!existing.lexical && match.lexical\n ? { lexical: match.lexical }\n : {}),\n ...(!existing.vector && match.vector ? { vector: match.vector } : {}),\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 actor preferences over workspace knowledge when RRF ties. Shared\n // lexical legs often assign the same top rank to recent conversation noise\n // and a personal-scope probe hit for the same common token.\n const personalDelta =\n Number(right.memory.scope === \"personal\") -\n Number(left.memory.scope === \"personal\");\n if (personalDelta !== 0) {\n return personalDelta;\n }\n const channelDelta =\n Number(currentChannel(right, options.channelPrefix)) -\n Number(currentChannel(left, options.channelPrefix));\n if (channelDelta !== 0) {\n return channelDelta;\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 Actor, type Identity, type Source } from \"@sentry/junior-plugin-api\";\nimport type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\n/** Runtime-derived visibility scope used for memory authorization checks. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** Runtime-derived subject classification stored for filtering and rendering. */\nexport interface ResolvedMemorySubject {\n subjectKey?: string;\n subjectType: MemorySubjectType;\n}\n\nfunction uniqueScopes(scopes: ResolvedMemoryScope[]): ResolvedMemoryScope[] {\n return [\n ...new Map(\n scopes.map((scope) => [`${scope.scope}:${scope.scopeKey}`, scope]),\n ).values(),\n ];\n}\n\n/** Personal scope key for one verified provider identity, when one exists. */\nfunction personalScopeFromIdentity(\n identity: Identity,\n): ResolvedMemoryScope | undefined {\n if (identity.provider === \"local\") {\n return {\n scope: \"personal\",\n scopeKey: `local:${identity.providerSubjectId}`,\n };\n }\n // Dashboard/web actors persist as junior identities keyed by verified email.\n if (identity.provider === \"junior\") {\n return {\n scope: \"personal\",\n scopeKey: `junior:${identity.providerSubjectId}`,\n };\n }\n if (identity.provider === \"slack\" && identity.providerTenantId) {\n return {\n scope: \"personal\",\n scopeKey: `slack:${identity.providerTenantId}:${identity.providerSubjectId}`,\n };\n }\n return undefined;\n}\n\n/** Derive viewer-visible memory scopes from canonical provider identities. */\nexport function deriveViewerMemoryScopes(identities: Identity[]): {\n privateScopes: ResolvedMemoryScope[];\n publicScopes: ResolvedMemoryScope[];\n} {\n const privateScopes = identities.flatMap((identity) => {\n const scope = personalScopeFromIdentity(identity);\n return scope ? [scope] : [];\n });\n const publicScopes = identities.flatMap((identity) =>\n identity.provider === \"slack\" && identity.providerTenantId\n ? [\n {\n scope: \"conversation\" as const,\n scopeKey: `slack:${identity.providerTenantId}`,\n },\n ]\n : [],\n );\n return {\n privateScopes: uniqueScopes(privateScopes),\n publicScopes: uniqueScopes(publicScopes),\n };\n}\n\n/** Conversation-scoped key for the Source branch we actually have. */\nfunction sourceConversationKey(source: Source): string | undefined {\n switch (source.platform) {\n case \"web\":\n case \"local\":\n return source.conversationId;\n case \"slack\": {\n if (source.visibility === \"public\") {\n return `slack:${source.teamId}`;\n }\n const threadKey = source.threadTs ?? source.messageTs;\n if (!threadKey) {\n return undefined;\n }\n return `slack:${source.teamId}:${source.channelId}:${threadKey}`;\n }\n }\n}\n\n/** Personal scope key for the Actor branch we actually have. */\nfunction actorScopeKey(actor: Actor | undefined): string | undefined {\n if (!actor) {\n return undefined;\n }\n switch (actor.platform) {\n case \"system\":\n return undefined;\n case \"slack\":\n return `slack:${actor.teamId}:${actor.userId}`;\n case \"local\":\n return `local:${actor.userId}`;\n case \"web\": {\n // Match junior identity personal scopes used by the dashboard viewer.\n const email = actor.email?.trim().toLowerCase();\n return email ? `junior:${email}` : undefined;\n }\n }\n}\n\n/** Derive the authority-bearing key for a requested memory scope. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n scope: MemoryScope,\n): ResolvedMemoryScope {\n if (scope === \"personal\") {\n const scopeKey = actorScopeKey(ctx.actor);\n if (!scopeKey) {\n throw new Error(\"Personal memory requires actor context.\");\n }\n return { scope, scopeKey };\n }\n\n const scopeKey = sourceConversationKey(ctx.source);\n if (!scopeKey) {\n throw new Error(\"Conversation memory requires conversation context.\");\n }\n return { scope, scopeKey };\n}\n\n/** Derive the memory subject from the already-authorized write scope. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n scope: ResolvedMemoryScope,\n): ResolvedMemorySubject {\n if (scope.scope === \"personal\") {\n const subjectKey = actorScopeKey(ctx.actor);\n if (!subjectKey) {\n throw new Error(\"User-subject memory requires actor context.\");\n }\n return { subjectType: \"user\", subjectKey };\n }\n\n const subjectKey = sourceConversationKey(ctx.source);\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return { subjectType: \"conversation\", subjectKey };\n}\n\n/** Return every visible scope for memory retrieval in the current context. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n const scopes: ResolvedMemoryScope[] = [];\n try {\n scopes.push(deriveMemoryScope(ctx, \"personal\"));\n } catch {\n // Personal memory is optional when a runtime surface has no actor.\n }\n try {\n scopes.push(deriveMemoryScope(ctx, \"conversation\"));\n } catch {\n // Conversation memory is optional for synthetic invocations.\n }\n return scopes;\n}\n","/**\n * Authenticated REST resources for viewer-visible memories.\n *\n * HTTP identity is one verified user whose linked identities authorize\n * personal and public workspace scopes.\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 createViewerMemories,\n InvalidMemoryCursorError,\n PersonalMemoryNotFoundError,\n type PersonalMemoryRecord,\n} from \"./personal\";\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 memoryDashboardDaySchema = z\n .object({\n date: z.iso.date(),\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: z.iso.date(),\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 generatedAt: z.iso.datetime(),\n recallDays: z.array(memoryCostDaySchema).length(90),\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(\n memory: PersonalMemoryRecord,\n): 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 : {}),\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 viewer-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 user = await options.users.resolve(email);\n if (!user) return json({ error: \"Authentication required.\" }, 401);\n\n const memories = createViewerMemories(options.db, user);\n try {\n if (isDashboard && isRead) {\n const [stats, days, extractionDays, recallDays] = await Promise.all([\n memories.stats(),\n memories.timeline({ days: 90 }),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_captured\",\n }),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_recalled\",\n }),\n ]);\n const body = memoryDashboardResponseSchema.parse({\n days,\n extractionDays,\n generatedAt: new Date().toISOString(),\n recallDays,\n stats,\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 memories.list({\n cursor: query.cursor,\n limit: query.limit,\n ...(query.q ? { query: query.q } : {}),\n });\n const body = memoryListResponseSchema.parse({\n memories: page.memories.map(apiMemory),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\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 = memoryApiSchema.parse(\n apiMemory(await memories.get(decodeURIComponent(memoryPath[1]!))),\n );\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(memory);\n }\n\n if (memoryPath && request.method === \"DELETE\") {\n await memories.archive(decodeURIComponent(memoryPath[1]!));\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 PersonalMemoryNotFoundError) {\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 * Authenticated-viewer memory access shared by REST and dashboard projections.\n *\n * One user may have multiple provider identities. This module adapts those\n * identities to the existing personal and public workspace scopes.\n */\nimport { z } from \"zod\";\nimport type { User } from \"@sentry/junior-plugin-api\";\nimport {\n createPersonalMemoryCollection,\n type MemoryVisibility,\n type PersonalMemoryRecord,\n} from \"./personal-store\";\nimport { deriveViewerMemoryScopes } from \"./scope\";\nimport type { MemoryDb, MemoryRecord } from \"./store\";\nimport type { MemoryKind } from \"./types\";\n\nconst cursorSchema = z\n .object({\n createdAtMs: z.number().finite(),\n id: z.string().min(1),\n kind: z.enum([\"preference\", \"procedure\", \"knowledge\"]).optional(),\n origin: z.enum([\"automatic\", \"explicit\"]).optional(),\n query: z.string().max(200).optional(),\n version: z.literal(1),\n visibility: z.enum([\"private\", \"public\"]).optional(),\n })\n .strict();\n\nexport interface ViewerMemoryPage {\n memories: PersonalMemoryRecord[];\n nextCursor?: string;\n}\n\nexport interface ViewerMemoryPageInput {\n cursor?: string;\n kind?: MemoryKind;\n limit: number;\n origin?: \"automatic\" | \"explicit\";\n query?: string;\n visibility?: MemoryVisibility;\n}\n\nexport class InvalidMemoryCursorError extends Error {\n constructor() {\n super(\"Memory cursor is invalid.\");\n this.name = \"InvalidMemoryCursorError\";\n }\n}\n\nexport { PersonalMemoryNotFoundError } from \"./personal-store\";\nexport type { MemoryVisibility, PersonalMemoryRecord } from \"./personal-store\";\n\nfunction decodeCursor(\n value: string | undefined,\n input: Pick<\n ViewerMemoryPageInput,\n \"kind\" | \"origin\" | \"query\" | \"visibility\"\n >,\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 !== input.query ||\n parsed.kind !== input.kind ||\n parsed.origin !== input.origin ||\n parsed.visibility !== input.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 cursor: { createdAtMs: number; id: string },\n input: Pick<\n ViewerMemoryPageInput,\n \"kind\" | \"origin\" | \"query\" | \"visibility\"\n >,\n): string {\n return Buffer.from(\n JSON.stringify({\n ...cursor,\n ...(input.query ? { query: input.query } : {}),\n ...(input.kind ? { kind: input.kind } : {}),\n ...(input.origin ? { origin: input.origin } : {}),\n ...(input.visibility ? { visibility: input.visibility } : {}),\n version: 1,\n }),\n \"utf8\",\n ).toString(\"base64url\");\n}\n\n/** Build viewer memory operations authorized by a user's linked identities. */\nexport function createViewerMemories(db: MemoryDb, user: User) {\n const collection = createPersonalMemoryCollection(\n db,\n deriveViewerMemoryScopes(user.identities),\n );\n return {\n async archive(id: string): Promise<MemoryRecord> {\n return await collection.archive(id);\n },\n async get(id: string): Promise<PersonalMemoryRecord> {\n return await collection.get(id);\n },\n async list(input: ViewerMemoryPageInput): Promise<ViewerMemoryPage> {\n const query = input.query?.trim() || undefined;\n const filters = {\n ...(input.kind ? { kind: input.kind } : {}),\n ...(input.origin ? { origin: input.origin } : {}),\n ...(query ? { query } : {}),\n ...(input.visibility ? { visibility: input.visibility } : {}),\n };\n const page = await collection.list({\n cursor: decodeCursor(input.cursor, filters),\n ...filters,\n limit: input.limit,\n });\n return {\n memories: page.memories,\n ...(page.nextCursor\n ? { nextCursor: encodeCursor(page.nextCursor, filters) }\n : {}),\n };\n },\n async stats() {\n return await collection.stats();\n },\n async timeline(input: { days: number }) {\n return await collection.timeline(input);\n },\n };\n}\n","/**\n * SQL operations over memories visible to one authenticated viewer.\n *\n * A user may have several linked identities. This store combines their\n * identity-scoped personal memories with authorized public workspace scopes.\n */\nimport { and, asc, desc, eq, gt, ilike, like, lt, or, sql } from \"drizzle-orm\";\nimport { z } from \"zod\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport type { ResolvedMemoryScope } from \"./scope\";\nimport {\n activeVisiblePredicate,\n archiveExpiredMemoryBatch,\n parseMemoryRow,\n type MemoryDb,\n type MemoryRecord,\n} from \"./store\";\nimport { MEMORY_KINDS, type MemorySourcePlatform } from \"./types\";\n\nconst nonEmptyStringSchema = z.string().min(1);\nconst memoryVisibilitySchema = z.enum([\"private\", \"public\"]);\nconst personalMemoryCursorSchema = z\n .object({\n createdAtMs: z.number().finite(),\n id: nonEmptyStringSchema,\n })\n .strict();\nconst personalMemoryPageInputSchema = z\n .object({\n cursor: personalMemoryCursorSchema.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 personalMemoryTimelineInputSchema = z\n .object({\n days: z.number().int().min(1).max(365),\n })\n .strict();\nconst DAY_MS = 24 * 60 * 60 * 1_000;\n\nexport type PersonalMemoryCursor = z.output<typeof personalMemoryCursorSchema>;\n\nexport type PersonalMemoryPageInput = z.output<\n typeof personalMemoryPageInputSchema\n>;\n\nexport type MemoryVisibility = z.output<typeof memoryVisibilitySchema>;\n\nexport interface PersonalMemoryPage {\n memories: PersonalMemoryRecord[];\n nextCursor?: PersonalMemoryCursor;\n}\n\n/** Safe provenance attached to one viewer-visible memory. */\nexport type PersonalMemoryRecord = MemoryRecord & {\n origin: \"automatic\" | \"explicit\" | \"other\";\n sourcePlatform: MemorySourcePlatform;\n visibility: MemoryVisibility;\n};\n\n/** Viewer-scoped active memory totals used by the dashboard. */\nexport interface PersonalMemoryStats {\n active: number;\n automatic: number;\n createdThirtyDays: number;\n embedded: number;\n explicit: number;\n knowledge: number;\n personal: number;\n preference: number;\n procedure: number;\n public: number;\n}\n\n/** Viewer-scoped memory creation totals for one UTC calendar day. */\nexport interface PersonalMemoryDay {\n date: string;\n personal: number;\n public: number;\n}\n\n/** Expected failure when a viewer does not own the requested memory. */\nexport class PersonalMemoryNotFoundError extends Error {\n constructor() {\n super(\"Memory was not found for the authenticated viewer.\");\n this.name = \"PersonalMemoryNotFoundError\";\n }\n}\n\n/** Viewer-scoped memory operations shared by dashboard and REST. */\nexport interface PersonalMemoryCollection {\n /** Archive one exact personal memory owned by a linked identity. */\n archive(id: string): Promise<MemoryRecord>;\n /** Read one exact memory visible to a linked identity. */\n get(id: string): Promise<PersonalMemoryRecord>;\n /** List one stable page across every authorized viewer scope. */\n list(input: PersonalMemoryPageInput): Promise<PersonalMemoryPage>;\n /** Summarize active memories across every authorized viewer scope. */\n stats(): Promise<PersonalMemoryStats>;\n /** Read memory creation history across every authorized viewer scope. */\n timeline(input: { days: number }): Promise<PersonalMemoryDay[]>;\n}\n\nfunction scopePredicate(scopes: ResolvedMemoryScope[]) {\n if (scopes.length === 0) return undefined;\n return or(\n ...scopes.map((scope) =>\n and(\n eq(juniorMemoryMemories.scope, scope.scope),\n eq(juniorMemoryMemories.scopeKey, scope.scopeKey),\n ),\n ),\n );\n}\n\nfunction 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(\n idempotencyKey: string | null,\n): PersonalMemoryRecord[\"origin\"] {\n if (idempotencyKey?.startsWith(\"session:\")) return \"automatic\";\n if (idempotencyKey?.startsWith(\"tool:\")) return \"explicit\";\n return \"other\";\n}\n\nfunction memoryVisibility(\n scope: MemoryRecord[\"scope\"],\n): PersonalMemoryRecord[\"visibility\"] {\n return scope === \"personal\" ? \"private\" : \"public\";\n}\n\nfunction personalMemoryRecord(\n row: typeof juniorMemoryMemories.$inferSelect,\n): PersonalMemoryRecord {\n const memory = parseMemoryRow(row);\n return {\n ...memory,\n origin: memoryOrigin(row.idempotencyKey),\n sourcePlatform: row.sourcePlatform,\n visibility: memoryVisibility(memory.scope),\n };\n}\n\nfunction emptyStats(): PersonalMemoryStats {\n return {\n active: 0,\n automatic: 0,\n createdThirtyDays: 0,\n embedded: 0,\n explicit: 0,\n knowledge: 0,\n personal: 0,\n preference: 0,\n procedure: 0,\n public: 0,\n };\n}\n\n/** Build storage operations for every memory scope linked to one viewer. */\nexport function createPersonalMemoryCollection(\n db: MemoryDb,\n scopes: {\n privateScopes: ResolvedMemoryScope[];\n publicScopes: ResolvedMemoryScope[];\n },\n options: { now?: () => number } = {},\n): PersonalMemoryCollection {\n const { privateScopes, publicScopes } = scopes;\n const allScopes = [...privateScopes, ...publicScopes];\n const getNowMs = () => options.now?.() ?? Date.now();\n\n function scopesForVisibility(\n visibility: MemoryVisibility | undefined,\n ): ResolvedMemoryScope[] {\n if (visibility === \"private\") return privateScopes;\n if (visibility === \"public\") return publicScopes;\n return allScopes;\n }\n\n return {\n async archive(id) {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = getNowMs();\n // Forget is personal-only; public workspace memories stay shared.\n const predicate = activeVisiblePredicate({\n nowMs,\n scopes: privateScopes,\n });\n if (!predicate) {\n throw new PersonalMemoryNotFoundError();\n }\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: \"user_removed\",\n })\n .where(and(predicate, eq(juniorMemoryMemories.id, memoryId)))\n .returning();\n if (!updated[0]) {\n throw new PersonalMemoryNotFoundError();\n }\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memoryId));\n return parseMemoryRow(updated[0]);\n },\n\n async get(id) {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = getNowMs();\n const predicate = activeVisiblePredicate({ nowMs, scopes: allScopes });\n if (!predicate) {\n throw new PersonalMemoryNotFoundError();\n }\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(predicate, eq(juniorMemoryMemories.id, memoryId)))\n .limit(1);\n if (!rows[0]) {\n throw new PersonalMemoryNotFoundError();\n }\n return personalMemoryRecord(rows[0]);\n },\n\n async list(input) {\n input = personalMemoryPageInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = scopesForVisibility(input.visibility);\n await archiveExpiredMemoryBatch({ db, nowMs, scopes });\n const active = activeVisiblePredicate({ nowMs, scopes });\n if (!active) {\n return { memories: [] };\n }\n\n const cursor = input.cursor\n ? or(\n lt(juniorMemoryMemories.createdAtMs, input.cursor.createdAtMs),\n and(\n eq(juniorMemoryMemories.createdAtMs, input.cursor.createdAtMs),\n gt(juniorMemoryMemories.id, input.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, cursor, search, kind, origin))\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(input.limit + 1);\n const hasNextPage = rows.length > input.limit;\n const memories = rows.slice(0, input.limit).map(personalMemoryRecord);\n const last = memories.at(-1);\n return {\n memories,\n ...(hasNextPage && last\n ? {\n nextCursor: {\n createdAtMs: last.createdAtMs,\n id: last.id,\n },\n }\n : {}),\n };\n },\n\n async stats() {\n const nowMs = getNowMs();\n await archiveExpiredMemoryBatch({ db, nowMs, scopes: allScopes });\n const active = activeVisiblePredicate({ nowMs, scopes: allScopes });\n if (!active) {\n return emptyStats();\n }\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 * 24 * 60 * 60 * 1_000})`.mapWith(\n Number,\n ),\n embedded:\n 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 personal:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'personal')`.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} = 'conversation')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .leftJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(active);\n return {\n active: counts?.active ?? 0,\n automatic: counts?.automatic ?? 0,\n createdThirtyDays: counts?.createdThirtyDays ?? 0,\n embedded: counts?.embedded ?? 0,\n explicit: counts?.explicit ?? 0,\n knowledge: counts?.knowledge ?? 0,\n personal: counts?.personal ?? 0,\n preference: counts?.preference ?? 0,\n procedure: counts?.procedure ?? 0,\n public: counts?.public ?? 0,\n };\n },\n\n async timeline(input) {\n input = personalMemoryTimelineInputSchema.parse(input);\n const todayMs = Date.parse(`${utcDate(getNowMs())}T00:00:00.000Z`);\n const startMs = todayMs - (input.days - 1) * DAY_MS;\n const ownership = scopePredicate(allScopes);\n if (!ownership) {\n return Array.from({ length: input.days }, (_, index) => ({\n date: utcDate(startMs + index * DAY_MS),\n personal: 0,\n public: 0,\n }));\n }\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 personal:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'personal')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'conversation')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .where(\n and(ownership, gt(juniorMemoryMemories.createdAtMs, startMs - 1)),\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: input.days }, (_, index) => {\n const date = utcDate(startMs + index * DAY_MS);\n const row = byDate.get(date);\n return {\n date,\n personal: row?.personal ?? 0,\n public: row?.public ?? 0,\n };\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 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 \"Personal memory requires actor context.\",\n \"User-subject memory requires actor context.\",\n]);\n\n/** Runtime-owned context used to bind memory tools to visible scopes. */\nexport interface MemoryToolContext {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n actor?: Actor;\n source: Source;\n userText?: string;\n}\n\nexport interface MemoryCreateToolContext extends MemoryToolContext {\n supersessionDecider?: MemorySupersessionDecider;\n}\n\nfunction throwToolInputError(message: string): never {\n throw new PluginToolInputError(message);\n}\n\nfunction asToolInputError(error: unknown): never {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n if (\n error instanceof Error &&\n KNOWN_TOOL_INPUT_ERROR_MESSAGES.has(error.message)\n ) {\n throw new PluginToolInputError(error.message, { cause: error });\n }\n throw error;\n}\n\nfunction memoryRuntimeContext(\n context: MemoryToolContext,\n): MemoryRuntimeContext {\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.actor ? { actor: context.actor } : {}),\n source: context.source,\n });\n}\n\nfunction memoryStore(\n context: MemoryToolContext,\n options: { supersessionDecider?: MemorySupersessionDecider } = {},\n) {\n return createMemoryStore(context.db, memoryRuntimeContext(context), {\n embedder: context.embedder,\n ...(options.supersessionDecider\n ? { supersessionDecider: options.supersessionDecider }\n : {}),\n });\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(50, Math.max(1, Math.floor(value)));\n}\n\nfunction digitAt(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code >= 48 && code <= 57;\n}\n\nfunction readDigits(\n value: string,\n start: number,\n length: number,\n): number | undefined {\n for (let index = start; index < start + length; index++) {\n if (!digitAt(value, index)) {\n return undefined;\n }\n }\n return Number(value.slice(start, start + length));\n}\n\nfunction parseIsoTimestampParts(value: string) {\n if (\n value.length < 20 ||\n value[4] !== \"-\" ||\n value[7] !== \"-\" ||\n value[10] !== \"T\" ||\n value[13] !== \":\" ||\n value[16] !== \":\"\n ) {\n return undefined;\n }\n const year = readDigits(value, 0, 4);\n const month = readDigits(value, 5, 2);\n const day = readDigits(value, 8, 2);\n const hour = readDigits(value, 11, 2);\n const minute = readDigits(value, 14, 2);\n const second = readDigits(value, 17, 2);\n if (\n year === undefined ||\n month === undefined ||\n day === undefined ||\n hour === undefined ||\n minute === undefined ||\n second === undefined\n ) {\n return undefined;\n }\n\n let zoneStart = 19;\n if (value[zoneStart] === \".\") {\n zoneStart += 1;\n const fractionStart = zoneStart;\n while (zoneStart < value.length && digitAt(value, zoneStart)) {\n zoneStart += 1;\n }\n if (zoneStart === fractionStart) {\n return undefined;\n }\n }\n\n if (value[zoneStart] === \"Z\") {\n if (zoneStart !== value.length - 1) {\n return undefined;\n }\n } else if (value[zoneStart] === \"+\" || value[zoneStart] === \"-\") {\n if (\n zoneStart !== value.length - 6 ||\n value[zoneStart + 3] !== \":\" ||\n readDigits(value, zoneStart + 1, 2) === undefined ||\n readDigits(value, zoneStart + 4, 2) === undefined\n ) {\n return undefined;\n }\n } else {\n return undefined;\n }\n\n return { day, hour, minute, month, second, year };\n}\n\nfunction parseExpiresAt(value: string | undefined): number | undefined {\n if (!value) {\n return undefined;\n }\n if (value === \"never\") {\n return undefined;\n }\n const parts = parseIsoTimestampParts(value);\n const expiresAtMs = Date.parse(value);\n if (!parts || !Number.isFinite(expiresAtMs)) {\n throwToolInputError('expires_at must be \"never\" or a valid ISO timestamp.');\n }\n const calendarDate = new Date(\n Date.UTC(parts.year, parts.month - 1, parts.day),\n );\n if (\n calendarDate.getUTCFullYear() !== parts.year ||\n calendarDate.getUTCMonth() !== parts.month - 1 ||\n calendarDate.getUTCDate() !== parts.day ||\n parts.hour > 23 ||\n parts.minute > 59 ||\n parts.second > 59\n ) {\n throwToolInputError('expires_at must be \"never\" or a valid ISO timestamp.');\n }\n return expiresAtMs;\n}\n\nfunction requireToolCallId(value: string | undefined): string {\n if (!value) {\n throwToolInputError(\"Memory creation requires a tool call id.\");\n }\n return value;\n}\n\nfunction requireMemoryContent(value: string): string {\n if (value.trim().length === 0) {\n throwToolInputError(\"Memory content is required.\");\n }\n return value;\n}\n\nconst createMemoryInputSchema = z\n .object({\n content: z\n .string()\n .min(1)\n .max(MAX_TOOL_CONTENT_CHARS)\n .describe(\n \"Self-contained public/shareable memory candidate. Include the subject in natural language when it matters; do not rely on surrounding chat context.\",\n ),\n expires_at: z\n .string()\n .min(1)\n .describe(\n 'Expiration selector. Omit or use \"never\" when the memory should not expire, or use an exact ISO timestamp such as \"2027-06-21T00:00:00Z\".',\n )\n .optional(),\n })\n .strict();\n\nconst removeMemoryInputSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .describe(\"Memory id or unambiguous short id prefix to remove.\"),\n })\n .strict();\n\nconst listMemoriesInputSchema = z\n .object({\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of visible memories to return.\")\n .optional(),\n })\n .strict();\n\nconst searchMemoriesInputSchema = z\n .object({\n query: z\n .string()\n .min(1)\n .describe(\"Search query for visible memory content.\"),\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of matching memories to return.\")\n .optional(),\n })\n .strict();\n\nconst memoryToolProjectionSchema = Type.Object(\n {\n id: Type.String({ minLength: 1 }),\n content: Type.String({ minLength: 1 }),\n createdAtMs: Type.Number(),\n observedAtMs: Type.Number(),\n expiresAtMs: Type.Optional(Type.Number()),\n },\n { additionalProperties: false },\n);\ntype MemoryToolProjection = Static<typeof memoryToolProjectionSchema>;\n\ntype MemoryStructuredToolResult<TData extends Record<string, unknown>> =\n 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 : {}),\n } satisfies CreateMemoryInput;\n}\n\nfunction targetForKind(kind: MemoryKind): \"actor\" | \"conversation\" {\n if (kind === \"preference\") {\n return \"actor\";\n }\n return \"conversation\";\n}\n\n/** Return the model-visible projection without hidden ownership/source fields. */\nfunction compactMemory(memory: MemoryRecord): MemoryToolProjection {\n return Value.Parse(memoryToolProjectionSchema, {\n id: memory.id,\n content: memory.content,\n createdAtMs: memory.createdAtMs,\n observedAtMs: memory.observedAtMs,\n ...(memory.expiresAtMs !== undefined\n ? { expiresAtMs: memory.expiresAtMs }\n : {}),\n });\n}\n\nfunction memoryToolResult<TData extends Record<string, unknown>>(\n target: string,\n data: TData,\n): MemoryStructuredToolResult<TData> {\n return {\n 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 public/shareable fact. Do not use for ordinary statements like 'I prefer X', 'I use Y', or 'X goes before Y' unless the user also asks you to remember/store/save it; passive memory learning handles those after the visible reply. Pass one self-contained natural-language candidate preserving the user's explicit memory intent. Do not ask the user to rephrase ordinary first-person facts, and do not rewrite them into display-name or third-person wording. Do not include secrets, private personal details, medical/legal/financial/sensitive facts, or another person's personal preference, opinion, habit, identity, relationship, workflow, or private life. Runtime context derives actor, scope, source, and subject ids; the memory agent decides canonical stored content and memory kind, then the plugin derives storage target from kind.\",\n executionMode: \"sequential\",\n inputSchema: createMemoryInputSchema,\n outputSchema: memoryCreateOutputSchema,\n execute: async (input, options) => {\n const parsedInput = parseMemoryToolInput(createMemoryInputSchema, input);\n const toolCallId = requireToolCallId(options.toolCallId);\n const requestedExpiresAtMs = parseExpiresAt(parsedInput.expires_at);\n const runtimeContext = memoryRuntimeContext(context);\n const store = memoryStore(context, {\n supersessionDecider: context.supersessionDecider,\n });\n const review = await (async () => {\n try {\n return parseMemoryReview(\n await context.agent.reviewCreateRequest(\n parseCreateMemoryRequest({\n content: requireMemoryContent(parsedInput.content),\n ...(requestedExpiresAtMs !== undefined\n ? { expiresAtMs: requestedExpiresAtMs }\n : {}),\n runtimeContext,\n ...(context.userText?.trim()\n ? {\n sourceContext: {\n currentUserText: context.userText.trim(),\n },\n }\n : {}),\n }),\n ),\n );\n } catch (error) {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n const detail =\n error instanceof Error && error.message.trim()\n ? `: ${error.message}`\n : \"\";\n throw new PluginToolInputError(\n `Memory agent review failed${detail}`,\n { cause: error },\n );\n }\n })();\n if (review.decision === \"reject\") {\n throw new PluginToolInputError(\n `Memory was not stored: ${review.reason}`,\n );\n }\n const memoryInput = createInput(\n context,\n {\n content: review.content,\n kind: review.kind,\n ...(review.expiresAtMs !== undefined\n ? { expiresAtMs: review.expiresAtMs }\n : requestedExpiresAtMs !== undefined\n ? { expiresAtMs: requestedExpiresAtMs }\n : {}),\n },\n toolCallId,\n );\n const result = await (async () => {\n try {\n if (targetForKind(review.kind) === \"conversation\") {\n return await store.createConversationMemory(memoryInput);\n }\n return await store.createMemory(memoryInput);\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"createMemory\", {\n created: result.created,\n memory: compactMemory(result.memory),\n });\n },\n });\n}\n\n/** Create a tool that archives a visible memory in the active context. */\nexport function createMemoryRemoveTool(context: MemoryToolContext) {\n return definePluginTool({\n annotations: {\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n },\n description:\n \"Forget one memory visible in the active context. Use only ids or short id prefixes returned by listMemories or searchMemories. Never remove memories by hidden actor, Slack, scope, or subject identifiers.\",\n executionMode: \"sequential\",\n inputSchema: removeMemoryInputSchema,\n outputSchema: memorySingleOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(removeMemoryInputSchema, input);\n const memory = await (async () => {\n try {\n return await memoryStore(context).archiveMemory({\n id: parsedInput.id,\n reason: \"tool_removed\",\n });\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"removeMemory\", {\n memory: compactMemory(memory),\n });\n },\n });\n}\n\n/** Create a tool that lists visible active memories in the active context. */\nexport function createMemoryListTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"List active memories visible in the current context. Use when the user asks what Junior remembers or when memory ids are needed before removing a memory.\",\n annotations: {\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 memories = await memoryStore(context).listMemories({\n limit: boundedLimit(parsedInput.limit, DEFAULT_RESULT_LIMIT),\n });\n return memoryToolResult(\"listMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n\n/** Create a tool that searches visible active memories in the active context. */\nexport function createMemorySearchTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"Search active memories visible in the current context. Use when the model needs targeted memory recall. The tool searches only the current actor and active conversation scopes.\",\n annotations: {\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 memories = await memoryStore(context).searchMemories({\n query: parsedInput.query,\n limit: boundedLimit(parsedInput.limit, DEFAULT_SEARCH_LIMIT),\n });\n return memoryToolResult(\"searchMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\n type PluginRunContext,\n type PluginRunTranscriptEntry,\n type PluginTaskContext,\n type Source,\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 \"createMemory\",\n \"listMemories\",\n \"removeMemory\",\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/** Where a passively extracted memory may be stored, or dropped when unproven. */\ntype MemoryRouteTarget = \"drop\" | \"personal\" | \"conversation\";\n\n/**\n * V1 passive learning opts in by Source branch, then public vs private.\n * Public API is the same as public Slack: shared conversation evidence may\n * learn. Private sources stay out. Local remains available for QA.\n */\nfunction allowsPassiveMemoryExtraction(source: Source): boolean {\n switch (source.platform) {\n case \"local\":\n return true;\n case \"web\":\n case \"slack\":\n return source.visibility === \"public\";\n }\n}\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\">,\n): MemoryRouteTarget {\n const cited = citedEntries(memory.evidenceMessageIndices, transcript);\n if (!cited.valid) {\n return \"drop\";\n }\n if (memory.kind === \"preference\") {\n // Only a run attributed to exactly one human run actor may store a preference.\n const exactlyOneHumanRunActor =\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 scope.\n return cited.entries.every(isRunActorInstruction) ? \"personal\" : \"drop\";\n }\n return cited.entries.every(\n (entry) => isRunActorInstruction(entry) || isConversationEvidence(entry),\n )\n ? \"conversation\"\n : \"drop\";\n}\n\nfunction memoryIdempotencySuffix(\n memory: ExtractedMemory,\n target: MemoryRouteTarget,\n): string {\n return createHash(\"sha256\")\n .update(target)\n .update(\"\\0\")\n .update(memory.kind)\n .update(\"\\0\")\n .update(memory.content)\n .update(\"\\0\")\n .update(memory.expiresAtMs === null ? \"never\" : String(memory.expiresAtMs))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction passiveInput(\n sessionId: string,\n memory: ExtractedMemory,\n sourceKey: string,\n target: MemoryRouteTarget,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory, target)}`,\n kind: memory.kind,\n ...(memory.expiresAtMs !== null ? { expiresAtMs: memory.expiresAtMs } : {}),\n };\n}\n\nasync function 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 post-session extraction and consumes only the bounded plugin task\n * projection. Explicit memory tools and private non-local sources remain hard\n * boundaries so background retries cannot reinterpret user-directed mutations\n * or private conversations.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // Memory tool turns already own memory management or recall; do not reinterpret\n // recalled memory output as fresh passive-learning evidence.\n if (\n run.transcript.some(\n (entry) =>\n entry.type === \"toolResult\" && MEMORY_TOOL_NAMES.has(entry.toolName),\n )\n ) {\n return;\n }\n // V1 passive learning is a Source-branch policy: local QA always, public\n // Slack/API by visibility, private sources never.\n if (!allowsPassiveMemoryExtraction(run.source)) {\n return;\n }\n const sourceKey = getSourceKey(run.source);\n if (!sourceKey) {\n return;\n }\n const transcript = run.transcript\n .filter((entry) => entry.text?.trim())\n .map((entry) => ({ ...entry, text: entry.text!.trim() }));\n const evidenceText = transcript\n .filter((entry) => entry.type === \"toolResult\" || entry.role === \"user\")\n .map((entry) => entry.text)\n .join(\"\\n\\n\")\n .trim();\n if (!evidenceText) {\n return;\n }\n\n const runtimeContext = memoryRuntimeContextSchema.parse({\n conversationId: run.conversationId,\n ...(run.actor ? { actor: run.actor } : {}),\n source: run.source,\n });\n const agent = createMemoryAgent(context.model);\n const store = createMemoryStore(context.db as MemoryDb, runtimeContext, {\n embedder: context.embedder,\n supersessionDecider: agent,\n });\n await store.archiveExpiredMemories();\n const 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 : {}),\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 capturedMemorySchema = z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n kind: z.enum(MEMORY_KINDS),\n observedAtMs: z.number().finite(),\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 renderCapturedMemories(\n event: z.output<typeof capturedMemoriesSchema>,\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, 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(capturedMemorySchema).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 PluginConversationEvents,\n type PluginLogger,\n type Source,\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 actor?: Actor;\n source: Source;\n text: string;\n}\n\nfunction trimContent(content: string, maxLength: number): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxLength) {\n return trimmed;\n }\n return `${trimmed.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\nfunction formatObservedDate(observedAtMs: number): string {\n return new Date(observedAtMs).toISOString().slice(0, 10);\n}\n\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 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,\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 } : {}),\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 runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.actor ? { actor: context.actor } : {}),\n source: context.source,\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 } : {}),\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 } : {}),\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;\nconst WINDOWS = [7, 30, 90] as const;\n\nconst memoryDaySchema = z\n .object({\n conversation: z.number().int().nonnegative(),\n date: z.string().date(),\n personal: 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} = 'personal'\n )::integer AS personal,\n count(*) FILTER (\n WHERE ${table.scope} = 'conversation'\n )::integer AS conversation\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.personal, 0)::integer AS personal,\n coalesce(daily.conversation, 0)::integer AS conversation\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 conversation:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'conversation')`.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 personal:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'personal')`.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: \"personal\",\n value: formatCount(counts?.personal ?? 0),\n },\n {\n label: \"conversation\",\n value: formatCount(counts?.conversation ?? 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 conversation: day.conversation,\n personal: day.personal,\n },\n })),\n description: \"Memories stored per day by scope\",\n id: \"memories-created\",\n series: [\n { key: \"personal\", label: \"Personal\" },\n { key: \"conversation\", label: \"Conversation\" },\n ],\n timeRangeDays: [...WINDOWS],\n title: \"Memories created\",\n type: \"bar_chart\",\n },\n ],\n };\n}\n","/** Project viewer-visible memories into Junior's core-rendered user page. */\nimport type { PluginUserPageDefinition } from \"@sentry/junior-plugin-api\";\nimport { createViewerMemories } from \"./personal\";\nimport type { MemoryVisibility, PersonalMemoryRecord } from \"./personal-store\";\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: PersonalMemoryRecord[\"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 memories = createViewerMemories(ctx.db as MemoryDb, ctx.viewer);\n const page = await memories.list({\n cursor: input.cursor,\n ...pageFilter(input.filter),\n limit: input.limit,\n ...(input.query ? { query: input.query } : {}),\n });\n return {\n type: \"list\",\n emptyText: pageEmptyText(input),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\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,OAA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3C,OAAO,kBAAkB,IAAI,KAAK;AAAA,YAClC,GAAI,IAAI,iBACJ,EAAE,gBAAgB,IAAI,eAAe,IACrC,CAAC;AAAA,YACL,GAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,MAAM,IAAI,CAAC;AAAA,YACxC,IAAI,IAAI;AAAA,YACR,UAAU,IAAI;AAAA,YACd,QAAQ,IAAI;AAAA,YACZ,KAAK,IAAI;AAAA,YACT,QAAQ,IAAI;AAAA,YACZ,MAAM,IAAI;AAAA,UACZ,CAAC;AAAA,QACH;AAAA,MACF,IACA,CAAC;AAAA,IACP;AAAA,EACF,CAAC;AACH;","names":["actorSchema","z","sql","z","scopeKey","subjectKey","nonEmptyStringSchema","z","scopePredicate","index","text","sql","idempotent","z","actorSchema","index","z","z","and","asc","desc","eq","gt","like","or","sql","z","nonEmptyStringSchema","z","or","and","eq","scopes","gt","sql","like","desc","asc","index","z","z","and","desc","eq","gt","ilike","isNull","or","or","isNull","gt","eq","ilike","and","desc","eq","eq","z","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","z","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","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/personal.ts","../src/personal-store.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 createMemoryCreateTool,\n createMemoryListTool,\n createMemoryRemoveTool,\n createMemorySearchTool,\n type MemoryCreateToolContext,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { 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 actor?: MemoryToolContext[\"actor\"];\n source: MemoryToolContext[\"source\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : undefined),\n ...(ctx.actor ? { actor: ctx.actor } : undefined),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : undefined),\n source: ctx.source,\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 actor?: MemoryCreateToolContext[\"actor\"];\n source: MemoryCreateToolContext[\"source\"];\n supersessionDecider: MemoryCreateToolContext[\"supersessionDecider\"];\n userText?: string;\n}): MemoryCreateToolContext {\n return {\n ...memoryToolContext(ctx),\n supersessionDecider: ctx.supersessionDecider,\n };\n}\n\n/** 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 removeMemory: createMemoryRemoveTool(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 log: ctx.log,\n source: ctx.source,\n text: ctx.text,\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 public/shareable 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 public/shareable, self-contained facts that are useful beyond this turn.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"Use the runtime context only for authority and scope; do not accept model-provided actor ids, scope ids, aliases, or arbitrary subjects.\",\n].join(\"\\n\");\nconst MEMORY_EXTRACTION_SYSTEM = [\n \"You are Junior's passive memory extraction agent. Return only structured memories worth storing.\",\n \"Use the completed run transcript as source evidence, including user-authored messages and tool results.\",\n \"Assistant text is context for interpreting the run, not independent evidence for new facts.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"If no public, durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst MEMORY_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(\n actor: z.output<typeof actorSchema> | undefined,\n): 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.platform) {\n case \"slack\":\n return `slack:${source.teamId}:${source.channelId}`;\n case \"web\":\n case \"local\":\n return `${source.platform}:${source.conversationId}`;\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-scoped kinds.\n */\nfunction allowedExtractionKinds(actorCount: number): Set<MemoryKind> {\n return actorCount === 1\n ? new Set<MemoryKind>(MEMORY_KINDS)\n : new Set<MemoryKind>([\"procedure\", \"knowledge\"]);\n}\n\nfunction memoryKindsContext(allowedKinds: Set<MemoryKind>): string {\n const lines = [\"<memory-kinds>\"];\n if (allowedKinds.has(\"preference\")) {\n lines.push(\n \"- preference: a durable first-person personal preference, opinion, habit, or workflow owned by the current actor. Stored as actor memory.\",\n );\n }\n lines.push(\n \"- procedure: reusable instructions for how a task, lookup, investigation, process, triage flow, or runbook should be done. Store the method, source-of-truth, prerequisite, or decision path when it took effort to discover. Stored as conversation memory.\",\n \"- knowledge: stable shared project, channel, operational, or runbook fact that is not a personal actor preference. Direct answers to user inquiries qualify only when they are durable beyond this run. Stored as conversation memory.\",\n \"</memory-kinds>\",\n );\n return lines.join(\"\\n\");\n}\n\nfunction reviewPrompt(request: CreateMemoryRequest): string {\n const sections = [\n \"<memory-review-input>\",\n \"Review the candidate memory using the runtime-owned context below.\",\n \"\",\n runtimeDescription(request),\n \"\",\n sourceContext(request),\n \"\",\n \"<candidate>\",\n escapeXml(request.content),\n \"</candidate>\",\n \"\",\n \"<rules>\",\n \"- Return store only when the candidate is public/shareable, durable, and self-contained.\",\n \"- First classify the memory kind: preference, procedure, or knowledge.\",\n \"- Use kind=preference only for first-person facts authored by the current actor about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current actor.\",\n \"- Use kind=procedure for reusable task/process/runbook instructions.\",\n \"- Use kind=knowledge for shared project, channel, operational, or runbook facts.\",\n \"- When current-user-message contains an explicit memory request with a concrete fact or procedure, extract from current-user-message even if the candidate is vague, incomplete, or phrased as an instruction.\",\n \"- A candidate may be badly phrased by an outer assistant or extraction pass. When current-user-message contains the actor's own first-person memory fact, treat that as actor-authored source evidence and canonicalize the fact instead of rejecting for third-person wording.\",\n \"- When candidate wording personalizes a shared task, process, runbook, project, channel, or operational fact, use current-user-message to recover the shared fact and classify it as procedure or knowledge.\",\n \"- Explicit procedure requests are valid when the source text contains both task context and action. Canonicalize them as shared procedure facts instead of rejecting them as vague.\",\n \"- Store content as person-less, source-less canonical knowledge. Ownership and source live in structured metadata, not prose.\",\n \"- For actor memories, omit the subject and write the content as a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Remove actor names, display names, actor/user labels, first- or second-person wording, thread labels, channel labels, and source labels from stored content.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- Reject vague content such as 'remember this' unless the candidate or current-user-message contains the concrete fact.\",\n \"- Preserve the requested expiration when one exists; otherwise set expiresAtMs to null.\",\n \"- If unsure, reject.\",\n \"</rules>\",\n \"</memory-review-input>\",\n ].filter((section): section is string => section !== undefined);\n return sections.join(\"\\n\");\n}\n\nfunction 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 ? { costUsd: result.costUsd } : 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 ? { costUsd: result.costUsd } : 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 * 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 MemoryScope,\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 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\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 personal memory for the current actor. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a conversation memory for the current source conversation. */\n createConversationMemory(\n input: CreateMemoryInput,\n ): Promise<CreateMemoryResult>;\n /** List active memories visible in the current runtime context. */\n listMemories(input: ListMemoriesInput): Promise<MemoryRecord[]>;\n /** List active personal memories owned by the current actor. */\n listPersonalMemories(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/** Map runtime Source platform onto the durable memory source platform. */\nfunction memorySourcePlatform(\n source: MemoryRuntimeContext[\"source\"],\n): MemorySourcePlatform {\n switch (source.platform) {\n case \"slack\":\n return \"slack\";\n case \"local\":\n return \"local\";\n case \"web\":\n return \"web\";\n }\n}\n\n/** Build the durable source attribution key from runtime-owned source fields. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n switch (ctx.source.platform) {\n case \"web\":\n case \"local\":\n return ctx.source.conversationId;\n case \"slack\": {\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n throw new Error(\n \"Memory source requires a Slack message or thread timestamp.\",\n );\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n }\n }\n}\n\nfunction sourceChannelPrefix(ctx: MemoryRuntimeContext): string | undefined {\n switch (ctx.source.platform) {\n case \"slack\":\n // TODO(v0.82.0): Replace Slack source-key prefix matching with typed source proximity metadata.\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:`;\n case \"web\":\n case \"local\":\n return undefined;\n }\n}\n\n/** Parse one SQL row into the public memory record projection. */\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 ? { supersededById: parsed.supersededById } : undefined),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : undefined),\n ...(parsed.archiveReason ? { archiveReason: parsed.archiveReason } : 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 args.subject.subjectKey === undefined\n ? isNull(juniorMemoryMemories.subjectKey)\n : eq(juniorMemoryMemories.subjectKey, args.subject.subjectKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n if (!predicate) {\n throw new Error(\"Memory duplicate predicate is empty.\");\n }\n return predicate;\n}\n\nasync function findExactDuplicateMemory(args: {\n content: string;\n db: MemoryDb;\n kind: MemoryRecord[\"kind\"];\n nowMs: number;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<MemoryRecord | undefined> {\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n activeScopedSubjectPredicate(args),\n eq(juniorMemoryMemories.content, args.content),\n ),\n )\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(1);\n return rows[0] ? parseMemoryRow(rows[0]) : undefined;\n}\n\nasync function rememberDuplicateIdempotency(args: {\n content: string;\n db: MemoryDb;\n duplicate: MemoryRecord;\n idempotencyKey?: string;\n nowMs: number;\n runtimeContext: MemoryRuntimeContext;\n scope: ResolvedMemoryScope;\n subject: ResolvedMemorySubject;\n}): Promise<void> {\n if (args.idempotencyKey === undefined) {\n return;\n }\n await args.db\n .insert(juniorMemoryMemories)\n .values({\n content: args.content,\n createdAtMs: args.nowMs,\n expiresAtMs: args.duplicate.expiresAtMs,\n id: idempotencyAliasId({\n idempotencyKey: args.idempotencyKey,\n scope: args.scope,\n targetId: args.duplicate.id,\n }),\n idempotencyKey: args.idempotencyKey,\n observedAtMs: args.nowMs,\n scope: args.scope.scope,\n scopeKey: args.scope.scopeKey,\n sourceKey: sourceKey(args.runtimeContext),\n sourcePlatform: memorySourcePlatform(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 sourceKey: row.memory.sourceKey,\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 sourceKey: row.memory.sourceKey,\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 scopeKind: MemoryScope,\n ): Promise<CreateMemoryResult> {\n const input = createMemoryInputSchema.parse(rawInput);\n const nowMs = getNowMs();\n const content = normalizeContent(input.content);\n const scope = deriveMemoryScope(runtimeContext, scopeKind);\n const subject = deriveMemorySubject(runtimeContext, scope);\n if (content.length > MAX_MEMORY_CONTENT_CHARS) {\n throw new Error(\"Memory content exceeds the maximum length.\");\n }\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes: [scope],\n });\n await archiveExpiredMemoryBatch({\n db,\n idempotencyKey: input.idempotencyKey,\n limit: 1,\n nowMs,\n scopes: [scope],\n });\n if (input.idempotencyKey !== undefined) {\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n });\n if (idempotent) {\n await storeEmbedding({\n content: idempotent.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 scopeKind === \"personal\" &&\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 observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: memorySourcePlatform(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 runs personal-scope-only probes. Workspace\n * conversation memories sharing common tokens (for example \"time\") can fill\n * the shared lexical recency window before ranking, which buries older actor\n * preferences that explicit search still finds.\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 personalScopes = scopes.filter((scope) => scope.scope === \"personal\");\n // Automatic recall only: keep a personal-scope probe so workspace noise\n // cannot monopolize the shared lexical recency window.\n const probePersonal =\n vectorMaxDistance !== undefined && personalScopes.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 && probePersonal\n ? searchVisibleVectorMemories({\n db,\n embedding: queryEmbedding,\n limit: candidateLimit,\n maxDistance: vectorMaxDistance,\n nowMs,\n scopes: personalScopes,\n })\n : emptyMatches,\n probePersonal\n ? searchVisibleLexicalMemories({\n ...lexicalArgs,\n scopes: personalScopes,\n })\n : emptyMatches,\n ]);\n const channelPrefix = sourceChannelPrefix(runtimeContext);\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 ...(channelPrefix ? { channelPrefix } : undefined),\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, \"personal\");\n },\n\n async createConversationMemory(input) {\n return await createScopedMemory(input, \"conversation\");\n },\n\n async listMemories(input) {\n input = listMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n return await listVisibleMemories({\n db,\n limit: input.limit,\n nowMs,\n scopes,\n });\n },\n\n async listPersonalMemories(input) {\n input = listMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = [deriveMemoryScope(runtimeContext, \"personal\")];\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 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 ('personal', 'conversation')`,\n ),\n check(\n \"junior_memory_memories_kind_check\",\n sql`${table.kind} IN (\n 'preference',\n 'procedure',\n 'knowledge'\n )`,\n ),\n check(\n \"junior_memory_memories_subject_type_check\",\n sql`${table.subjectType} IN ('user', 'conversation', 'general')`,\n ),\n check(\n \"junior_memory_memories_subject_key_check\",\n sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`,\n ),\n check(\n \"junior_memory_memories_source_platform_check\",\n sql`${table.sourcePlatform} IN ('slack', 'local', '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 = [\"personal\", \"conversation\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\n// Durable attribution follows Source platform, including dashboard/web 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/** Runtime-owned memory invocation fields used for scope and source authority. */\nexport const memoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n actor: actorSchema.optional(),\n source: sourceSchema,\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 sourceKey: string;\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 currentChannel(\n match: Pick<MemoryMatch, \"sourceKey\">,\n channelPrefix: string | undefined,\n): boolean {\n return channelPrefix ? match.sourceKey.startsWith(channelPrefix) : false;\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 channelPrefix?: string;\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 per modality. Shared legs are fused before personal\n // probes, so a smaller personal top-k cannot overwrite a shared dense rank\n // with an inflated top rank for the same memory.\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 actor preferences over workspace knowledge when RRF ties. Shared\n // lexical legs often assign the same top rank to recent conversation noise\n // and a personal-scope probe hit for the same common token.\n const personalDelta =\n Number(right.memory.scope === \"personal\") -\n Number(left.memory.scope === \"personal\");\n if (personalDelta !== 0) {\n return personalDelta;\n }\n const channelDelta =\n Number(currentChannel(right, options.channelPrefix)) -\n Number(currentChannel(left, options.channelPrefix));\n if (channelDelta !== 0) {\n return channelDelta;\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 Actor, type Identity, type Source } from \"@sentry/junior-plugin-api\";\nimport type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\n/** Runtime-derived visibility scope used for memory authorization checks. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** Runtime-derived subject classification stored for filtering and rendering. */\nexport interface ResolvedMemorySubject {\n subjectKey?: string;\n subjectType: MemorySubjectType;\n}\n\nfunction uniqueScopes(scopes: ResolvedMemoryScope[]): ResolvedMemoryScope[] {\n return [\n ...new Map(\n scopes.map((scope) => [`${scope.scope}:${scope.scopeKey}`, scope]),\n ).values(),\n ];\n}\n\n/** Personal scope key for one verified provider identity, when one exists. */\nfunction personalScopeFromIdentity(\n identity: Identity,\n): ResolvedMemoryScope | undefined {\n if (identity.provider === \"local\") {\n return {\n scope: \"personal\",\n scopeKey: `local:${identity.providerSubjectId}`,\n };\n }\n // Dashboard/web actors persist as junior identities keyed by verified email.\n if (identity.provider === \"junior\") {\n return {\n scope: \"personal\",\n scopeKey: `junior:${identity.providerSubjectId}`,\n };\n }\n if (identity.provider === \"slack\" && identity.providerTenantId) {\n return {\n scope: \"personal\",\n scopeKey: `slack:${identity.providerTenantId}:${identity.providerSubjectId}`,\n };\n }\n return undefined;\n}\n\n/** Derive viewer-visible memory scopes from canonical provider identities. */\nexport function deriveViewerMemoryScopes(identities: Identity[]): {\n privateScopes: ResolvedMemoryScope[];\n publicScopes: ResolvedMemoryScope[];\n} {\n const privateScopes = identities.flatMap((identity) => {\n const scope = personalScopeFromIdentity(identity);\n return scope ? [scope] : [];\n });\n const publicScopes = identities.flatMap((identity) =>\n identity.provider === \"slack\" && identity.providerTenantId\n ? [\n {\n scope: \"conversation\" as const,\n scopeKey: `slack:${identity.providerTenantId}`,\n },\n ]\n : [],\n );\n return {\n privateScopes: uniqueScopes(privateScopes),\n publicScopes: uniqueScopes(publicScopes),\n };\n}\n\n/** Conversation-scoped key for the Source branch we actually have. */\nfunction sourceConversationKey(source: Source): string | undefined {\n switch (source.platform) {\n case \"web\":\n case \"local\":\n return source.conversationId;\n case \"slack\": {\n if (source.visibility === \"public\") {\n return `slack:${source.teamId}`;\n }\n const threadKey = source.threadTs ?? source.messageTs;\n if (!threadKey) {\n return undefined;\n }\n return `slack:${source.teamId}:${source.channelId}:${threadKey}`;\n }\n }\n}\n\n/** Personal scope key for the Actor branch we actually have. */\nfunction actorScopeKey(actor: Actor | undefined): string | undefined {\n if (!actor) {\n return undefined;\n }\n switch (actor.platform) {\n case \"system\":\n return undefined;\n case \"slack\":\n return `slack:${actor.teamId}:${actor.userId}`;\n case \"local\":\n return `local:${actor.userId}`;\n case \"web\": {\n // Match junior identity personal scopes used by the dashboard viewer.\n const email = actor.email?.trim().toLowerCase();\n return email ? `junior:${email}` : undefined;\n }\n }\n}\n\n/** Derive the authority-bearing key for a requested memory scope. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n scope: MemoryScope,\n): ResolvedMemoryScope {\n if (scope === \"personal\") {\n const scopeKey = actorScopeKey(ctx.actor);\n if (!scopeKey) {\n throw new Error(\"Personal memory requires actor context.\");\n }\n return { scope, scopeKey };\n }\n\n const scopeKey = sourceConversationKey(ctx.source);\n if (!scopeKey) {\n throw new Error(\"Conversation memory requires conversation context.\");\n }\n return { scope, scopeKey };\n}\n\n/** Derive the memory subject from the already-authorized write scope. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n scope: ResolvedMemoryScope,\n): ResolvedMemorySubject {\n if (scope.scope === \"personal\") {\n const subjectKey = actorScopeKey(ctx.actor);\n if (!subjectKey) {\n throw new Error(\"User-subject memory requires actor context.\");\n }\n return { subjectType: \"user\", subjectKey };\n }\n\n const subjectKey = sourceConversationKey(ctx.source);\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return { subjectType: \"conversation\", subjectKey };\n}\n\n/** Return every visible scope for memory retrieval in the current context. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n const scopes: ResolvedMemoryScope[] = [];\n try {\n scopes.push(deriveMemoryScope(ctx, \"personal\"));\n } catch {\n // Personal memory is optional when a runtime surface has no actor.\n }\n try {\n scopes.push(deriveMemoryScope(ctx, \"conversation\"));\n } catch {\n // Conversation memory is optional for synthetic invocations.\n }\n return scopes;\n}\n","/**\n * Authenticated REST resources for viewer-visible memories.\n *\n * HTTP identity is one verified user whose linked identities authorize\n * personal and public workspace scopes.\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 createViewerMemories,\n InvalidMemoryCursorError,\n PersonalMemoryNotFoundError,\n type PersonalMemoryRecord,\n} from \"./personal\";\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 memoryDashboardDaySchema = z\n .object({\n date: z.iso.date(),\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: z.iso.date(),\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 generatedAt: z.iso.datetime(),\n recallDays: z.array(memoryCostDaySchema).length(90),\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(\n memory: PersonalMemoryRecord,\n): 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 viewer-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 user = await options.users.resolve(email);\n if (!user) return json({ error: \"Authentication required.\" }, 401);\n\n const memories = createViewerMemories(options.db, user);\n try {\n if (isDashboard && isRead) {\n const [stats, days, extractionDays, recallDays] = await Promise.all([\n memories.stats(),\n memories.timeline({ days: 90 }),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_captured\",\n }),\n options.eventStats.costsByDay({\n days: 90,\n eventName: \"memories_recalled\",\n }),\n ]);\n const body = memoryDashboardResponseSchema.parse({\n days,\n extractionDays,\n generatedAt: new Date().toISOString(),\n recallDays,\n stats,\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 memories.list({\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 = memoryApiSchema.parse(\n apiMemory(await memories.get(decodeURIComponent(memoryPath[1]!))),\n );\n return request.method === \"HEAD\"\n ? new Response(null, {\n headers: { \"cache-control\": \"no-store\" },\n status: 200,\n })\n : json(memory);\n }\n\n if (memoryPath && request.method === \"DELETE\") {\n await memories.archive(decodeURIComponent(memoryPath[1]!));\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 PersonalMemoryNotFoundError) {\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 * Authenticated-viewer memory access shared by REST and dashboard projections.\n *\n * One user may have multiple provider identities. This module adapts those\n * identities to the existing personal and public workspace scopes.\n */\nimport { z } from \"zod\";\nimport type { User } from \"@sentry/junior-plugin-api\";\nimport {\n createPersonalMemoryCollection,\n type MemoryVisibility,\n type PersonalMemoryRecord,\n} from \"./personal-store\";\nimport { deriveViewerMemoryScopes } from \"./scope\";\nimport type { MemoryDb, MemoryRecord } from \"./store\";\nimport type { MemoryKind } from \"./types\";\n\nconst cursorSchema = z\n .object({\n createdAtMs: z.number().finite(),\n id: z.string().min(1),\n kind: z.enum([\"preference\", \"procedure\", \"knowledge\"]).optional(),\n origin: z.enum([\"automatic\", \"explicit\"]).optional(),\n query: z.string().max(200).optional(),\n version: z.literal(1),\n visibility: z.enum([\"private\", \"public\"]).optional(),\n })\n .strict();\n\nexport interface ViewerMemoryPage {\n memories: PersonalMemoryRecord[];\n nextCursor?: string;\n}\n\nexport interface ViewerMemoryPageInput {\n cursor?: string;\n kind?: MemoryKind;\n limit: number;\n origin?: \"automatic\" | \"explicit\";\n query?: string;\n visibility?: MemoryVisibility;\n}\n\nexport class InvalidMemoryCursorError extends Error {\n constructor() {\n super(\"Memory cursor is invalid.\");\n this.name = \"InvalidMemoryCursorError\";\n }\n}\n\nexport { PersonalMemoryNotFoundError } from \"./personal-store\";\nexport type { MemoryVisibility, PersonalMemoryRecord } from \"./personal-store\";\n\nfunction decodeCursor(\n value: string | undefined,\n input: Pick<\n ViewerMemoryPageInput,\n \"kind\" | \"origin\" | \"query\" | \"visibility\"\n >,\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 !== input.query ||\n parsed.kind !== input.kind ||\n parsed.origin !== input.origin ||\n parsed.visibility !== input.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 cursor: { createdAtMs: number; id: string },\n input: Pick<\n ViewerMemoryPageInput,\n \"kind\" | \"origin\" | \"query\" | \"visibility\"\n >,\n): string {\n return Buffer.from(\n JSON.stringify({\n ...cursor,\n ...(input.query ? { query: input.query } : undefined),\n ...(input.kind ? { kind: input.kind } : undefined),\n ...(input.origin ? { origin: input.origin } : undefined),\n ...(input.visibility ? { visibility: input.visibility } : undefined),\n version: 1,\n }),\n \"utf8\",\n ).toString(\"base64url\");\n}\n\n/** Build viewer memory operations authorized by a user's linked identities. */\nexport function createViewerMemories(db: MemoryDb, user: User) {\n const collection = createPersonalMemoryCollection(\n db,\n deriveViewerMemoryScopes(user.identities),\n );\n return {\n async archive(id: string): Promise<MemoryRecord> {\n return await collection.archive(id);\n },\n async get(id: string): Promise<PersonalMemoryRecord> {\n return await collection.get(id);\n },\n async list(input: ViewerMemoryPageInput): Promise<ViewerMemoryPage> {\n const query = input.query?.trim() || undefined;\n const filters = {\n ...(input.kind ? { kind: input.kind } : undefined),\n ...(input.origin ? { origin: input.origin } : undefined),\n ...(query ? { query } : undefined),\n ...(input.visibility ? { visibility: input.visibility } : undefined),\n };\n const page = await collection.list({\n cursor: decodeCursor(input.cursor, filters),\n ...filters,\n limit: input.limit,\n });\n return {\n memories: page.memories,\n ...(page.nextCursor\n ? { nextCursor: encodeCursor(page.nextCursor, filters) }\n : undefined),\n };\n },\n async stats() {\n return await collection.stats();\n },\n async timeline(input: { days: number }) {\n return await collection.timeline(input);\n },\n };\n}\n","/**\n * SQL operations over memories visible to one authenticated viewer.\n *\n * A user may have several linked identities. This store combines their\n * identity-scoped personal memories with authorized public workspace scopes.\n */\nimport { and, asc, desc, eq, gt, ilike, like, lt, or, sql } from \"drizzle-orm\";\nimport { z } from \"zod\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport type { ResolvedMemoryScope } from \"./scope\";\nimport {\n activeVisiblePredicate,\n archiveExpiredMemoryBatch,\n parseMemoryRow,\n type MemoryDb,\n type MemoryRecord,\n} from \"./store\";\nimport { MEMORY_KINDS, type MemorySourcePlatform } from \"./types\";\n\nconst nonEmptyStringSchema = z.string().min(1);\nconst memoryVisibilitySchema = z.enum([\"private\", \"public\"]);\nconst personalMemoryCursorSchema = z\n .object({\n createdAtMs: z.number().finite(),\n id: nonEmptyStringSchema,\n })\n .strict();\nconst personalMemoryPageInputSchema = z\n .object({\n cursor: personalMemoryCursorSchema.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 personalMemoryTimelineInputSchema = z\n .object({\n days: z.number().int().min(1).max(365),\n })\n .strict();\nconst DAY_MS = 24 * 60 * 60 * 1_000;\n\nexport type PersonalMemoryCursor = z.output<typeof personalMemoryCursorSchema>;\n\nexport type PersonalMemoryPageInput = z.output<\n typeof personalMemoryPageInputSchema\n>;\n\nexport type MemoryVisibility = z.output<typeof memoryVisibilitySchema>;\n\nexport interface PersonalMemoryPage {\n memories: PersonalMemoryRecord[];\n nextCursor?: PersonalMemoryCursor;\n}\n\n/** Safe provenance attached to one viewer-visible memory. */\nexport type PersonalMemoryRecord = MemoryRecord & {\n origin: \"automatic\" | \"explicit\" | \"other\";\n sourcePlatform: MemorySourcePlatform;\n visibility: MemoryVisibility;\n};\n\n/** Viewer-scoped active memory totals used by the dashboard. */\nexport interface PersonalMemoryStats {\n active: number;\n automatic: number;\n createdThirtyDays: number;\n embedded: number;\n explicit: number;\n knowledge: number;\n personal: number;\n preference: number;\n procedure: number;\n public: number;\n}\n\n/** Viewer-scoped memory creation totals for one UTC calendar day. */\nexport interface PersonalMemoryDay {\n date: string;\n personal: number;\n public: number;\n}\n\n/** Expected failure when a viewer does not own the requested memory. */\nexport class PersonalMemoryNotFoundError extends Error {\n constructor() {\n super(\"Memory was not found for the authenticated viewer.\");\n this.name = \"PersonalMemoryNotFoundError\";\n }\n}\n\n/** Viewer-scoped memory operations shared by dashboard and REST. */\nexport interface PersonalMemoryCollection {\n /** Archive one exact personal memory owned by a linked identity. */\n archive(id: string): Promise<MemoryRecord>;\n /** Read one exact memory visible to a linked identity. */\n get(id: string): Promise<PersonalMemoryRecord>;\n /** List one stable page across every authorized viewer scope. */\n list(input: PersonalMemoryPageInput): Promise<PersonalMemoryPage>;\n /** Summarize active memories across every authorized viewer scope. */\n stats(): Promise<PersonalMemoryStats>;\n /** Read memory creation history across every authorized viewer scope. */\n timeline(input: { days: number }): Promise<PersonalMemoryDay[]>;\n}\n\nfunction scopePredicate(scopes: ResolvedMemoryScope[]) {\n if (scopes.length === 0) return undefined;\n return or(\n ...scopes.map((scope) =>\n and(\n eq(juniorMemoryMemories.scope, scope.scope),\n eq(juniorMemoryMemories.scopeKey, scope.scopeKey),\n ),\n ),\n );\n}\n\nfunction 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(\n idempotencyKey: string | null,\n): PersonalMemoryRecord[\"origin\"] {\n if (idempotencyKey?.startsWith(\"session:\")) return \"automatic\";\n if (idempotencyKey?.startsWith(\"tool:\")) return \"explicit\";\n return \"other\";\n}\n\nfunction memoryVisibility(\n scope: MemoryRecord[\"scope\"],\n): PersonalMemoryRecord[\"visibility\"] {\n return scope === \"personal\" ? \"private\" : \"public\";\n}\n\nfunction personalMemoryRecord(\n row: typeof juniorMemoryMemories.$inferSelect,\n): PersonalMemoryRecord {\n const memory = parseMemoryRow(row);\n return {\n ...memory,\n origin: memoryOrigin(row.idempotencyKey),\n sourcePlatform: row.sourcePlatform,\n visibility: memoryVisibility(memory.scope),\n };\n}\n\nfunction emptyStats(): PersonalMemoryStats {\n return {\n active: 0,\n automatic: 0,\n createdThirtyDays: 0,\n embedded: 0,\n explicit: 0,\n knowledge: 0,\n personal: 0,\n preference: 0,\n procedure: 0,\n public: 0,\n };\n}\n\n/** Build storage operations for every memory scope linked to one viewer. */\nexport function createPersonalMemoryCollection(\n db: MemoryDb,\n scopes: {\n privateScopes: ResolvedMemoryScope[];\n publicScopes: ResolvedMemoryScope[];\n },\n options: { now?: () => number } = {},\n): PersonalMemoryCollection {\n const { privateScopes, publicScopes } = scopes;\n const allScopes = [...privateScopes, ...publicScopes];\n const getNowMs = () => options.now?.() ?? Date.now();\n\n function scopesForVisibility(\n visibility: MemoryVisibility | undefined,\n ): ResolvedMemoryScope[] {\n if (visibility === \"private\") return privateScopes;\n if (visibility === \"public\") return publicScopes;\n return allScopes;\n }\n\n return {\n async archive(id) {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = getNowMs();\n // Forget is personal-only; public workspace memories stay shared.\n const predicate = activeVisiblePredicate({\n nowMs,\n scopes: privateScopes,\n });\n if (!predicate) {\n throw new PersonalMemoryNotFoundError();\n }\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: \"user_removed\",\n })\n .where(and(predicate, eq(juniorMemoryMemories.id, memoryId)))\n .returning();\n if (!updated[0]) {\n throw new PersonalMemoryNotFoundError();\n }\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memoryId));\n return parseMemoryRow(updated[0]);\n },\n\n async get(id) {\n const memoryId = nonEmptyStringSchema.parse(id);\n const nowMs = getNowMs();\n const predicate = activeVisiblePredicate({ nowMs, scopes: allScopes });\n if (!predicate) {\n throw new PersonalMemoryNotFoundError();\n }\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(predicate, eq(juniorMemoryMemories.id, memoryId)))\n .limit(1);\n if (!rows[0]) {\n throw new PersonalMemoryNotFoundError();\n }\n return personalMemoryRecord(rows[0]);\n },\n\n async list(input) {\n input = personalMemoryPageInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = scopesForVisibility(input.visibility);\n await archiveExpiredMemoryBatch({ db, nowMs, scopes });\n const active = activeVisiblePredicate({ nowMs, scopes });\n if (!active) {\n return { memories: [] };\n }\n\n const cursor = input.cursor\n ? or(\n lt(juniorMemoryMemories.createdAtMs, input.cursor.createdAtMs),\n and(\n eq(juniorMemoryMemories.createdAtMs, input.cursor.createdAtMs),\n gt(juniorMemoryMemories.id, input.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, cursor, search, kind, origin))\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(input.limit + 1);\n const hasNextPage = rows.length > input.limit;\n const memories = rows.slice(0, input.limit).map(personalMemoryRecord);\n const last = memories.at(-1);\n return {\n memories,\n ...(hasNextPage && last\n ? {\n nextCursor: {\n createdAtMs: last.createdAtMs,\n id: last.id,\n },\n }\n : undefined),\n };\n },\n\n async stats() {\n const nowMs = getNowMs();\n await archiveExpiredMemoryBatch({ db, nowMs, scopes: allScopes });\n const active = activeVisiblePredicate({ nowMs, scopes: allScopes });\n if (!active) {\n return emptyStats();\n }\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 * 24 * 60 * 60 * 1_000})`.mapWith(\n Number,\n ),\n embedded:\n 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 personal:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'personal')`.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} = 'conversation')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .leftJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(active);\n return {\n active: counts?.active ?? 0,\n automatic: counts?.automatic ?? 0,\n createdThirtyDays: counts?.createdThirtyDays ?? 0,\n embedded: counts?.embedded ?? 0,\n explicit: counts?.explicit ?? 0,\n knowledge: counts?.knowledge ?? 0,\n personal: counts?.personal ?? 0,\n preference: counts?.preference ?? 0,\n procedure: counts?.procedure ?? 0,\n public: counts?.public ?? 0,\n };\n },\n\n async timeline(input) {\n input = personalMemoryTimelineInputSchema.parse(input);\n const todayMs = Date.parse(`${utcDate(getNowMs())}T00:00:00.000Z`);\n const startMs = todayMs - (input.days - 1) * DAY_MS;\n const ownership = scopePredicate(allScopes);\n if (!ownership) {\n return Array.from({ length: input.days }, (_, index) => ({\n date: utcDate(startMs + index * DAY_MS),\n personal: 0,\n public: 0,\n }));\n }\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 personal:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'personal')`.mapWith(\n Number,\n ),\n public:\n sql<number>`count(*) filter (where ${juniorMemoryMemories.scope} = 'conversation')`.mapWith(\n Number,\n ),\n })\n .from(juniorMemoryMemories)\n .where(\n and(ownership, gt(juniorMemoryMemories.createdAtMs, startMs - 1)),\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: input.days }, (_, index) => {\n const date = utcDate(startMs + index * DAY_MS);\n const row = byDate.get(date);\n return {\n date,\n personal: row?.personal ?? 0,\n public: row?.public ?? 0,\n };\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 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 \"Personal memory requires actor context.\",\n \"User-subject memory requires actor context.\",\n]);\n\n/** Runtime-owned context used to bind memory tools to visible scopes. */\nexport interface MemoryToolContext {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n actor?: Actor;\n source: Source;\n userText?: string;\n}\n\nexport interface MemoryCreateToolContext extends MemoryToolContext {\n supersessionDecider?: MemorySupersessionDecider;\n}\n\nfunction throwToolInputError(message: string): never {\n throw new PluginToolInputError(message);\n}\n\nfunction asToolInputError(error: unknown): never {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n if (\n error instanceof Error &&\n KNOWN_TOOL_INPUT_ERROR_MESSAGES.has(error.message)\n ) {\n throw new PluginToolInputError(error.message, { cause: error });\n }\n throw error;\n}\n\nfunction memoryRuntimeContext(\n context: MemoryToolContext,\n): MemoryRuntimeContext {\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : undefined),\n ...(context.actor ? { actor: context.actor } : undefined),\n source: context.source,\n });\n}\n\nfunction memoryStore(\n context: MemoryToolContext,\n options: { supersessionDecider?: MemorySupersessionDecider } = {},\n) {\n return createMemoryStore(context.db, memoryRuntimeContext(context), {\n embedder: context.embedder,\n ...(options.supersessionDecider\n ? { supersessionDecider: options.supersessionDecider }\n : 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 public/shareable memory candidate. Include the subject in natural language when it matters; do not rely on surrounding chat context.\",\n ),\n expires_at: z\n .string()\n .min(1)\n .describe(\n 'Expiration selector. Omit or use \"never\" when the memory should not expire, or use an exact ISO timestamp such as \"2027-06-21T00:00:00Z\".',\n )\n .optional(),\n })\n .strict();\n\nconst removeMemoryInputSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .describe(\"Memory id or unambiguous short id prefix to remove.\"),\n })\n .strict();\n\nconst listMemoriesInputSchema = z\n .object({\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of visible memories to return.\")\n .optional(),\n })\n .strict();\n\nconst searchMemoriesInputSchema = z\n .object({\n query: z\n .string()\n .min(1)\n .describe(\"Search query for visible memory content.\"),\n limit: z\n .number()\n .min(1)\n .max(50)\n .describe(\"Maximum number of matching memories to return.\")\n .optional(),\n })\n .strict();\n\nconst memoryToolProjectionSchema = Type.Object(\n {\n id: Type.String({ minLength: 1 }),\n content: Type.String({ minLength: 1 }),\n createdAtMs: Type.Number(),\n observedAtMs: Type.Number(),\n expiresAtMs: Type.Optional(Type.Number()),\n },\n { additionalProperties: false },\n);\ntype MemoryToolProjection = Static<typeof memoryToolProjectionSchema>;\n\ntype MemoryStructuredToolResult<TData extends Record<string, unknown>> =\n 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 public/shareable fact. Do not use for ordinary statements like 'I prefer X', 'I use Y', or 'X goes before Y' unless the user also asks you to remember/store/save it; passive memory learning handles those after the visible reply. Pass one self-contained natural-language candidate preserving the user's explicit memory intent. Do not ask the user to rephrase ordinary first-person facts, and do not rewrite them into display-name or third-person wording. Do not include secrets, private personal details, medical/legal/financial/sensitive facts, or another person's personal preference, opinion, habit, identity, relationship, workflow, or private life. Runtime context derives actor, scope, source, and subject ids; the memory agent decides canonical stored content and memory kind, then the plugin derives storage target from kind.\",\n executionMode: \"sequential\",\n inputSchema: createMemoryInputSchema,\n outputSchema: memoryCreateOutputSchema,\n execute: async (input, options) => {\n const parsedInput = parseMemoryToolInput(createMemoryInputSchema, input);\n const toolCallId = requireToolCallId(options.toolCallId);\n const requestedExpiresAtMs = parseExpiresAt(parsedInput.expires_at);\n const runtimeContext = memoryRuntimeContext(context);\n const store = memoryStore(context, {\n supersessionDecider: context.supersessionDecider,\n });\n const review = await (async () => {\n try {\n return parseMemoryReview(\n await context.agent.reviewCreateRequest(\n parseCreateMemoryRequest({\n content: requireMemoryContent(parsedInput.content),\n ...(requestedExpiresAtMs !== undefined\n ? { expiresAtMs: requestedExpiresAtMs }\n : 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 createMemoryRemoveTool(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 memory visible in the active context. Use only ids or short id prefixes returned by listMemories or searchMemories. Never remove memories by hidden actor, Slack, scope, or subject identifiers.\",\n executionMode: \"sequential\",\n inputSchema: removeMemoryInputSchema,\n outputSchema: memorySingleOutputSchema,\n execute: async (input) => {\n const parsedInput = parseMemoryToolInput(removeMemoryInputSchema, input);\n const memory = await (async () => {\n try {\n return await memoryStore(context).archiveMemory({\n id: parsedInput.id,\n reason: \"tool_removed\",\n });\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return memoryToolResult(\"removeMemory\", {\n memory: compactMemory(memory),\n });\n },\n });\n}\n\n/** Create a tool that lists visible active memories in the active context. */\nexport function createMemoryListTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"List active memories visible in the current context. Use when the user asks what Junior remembers or when memory ids are needed before removing a memory.\",\n annotations: {\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 memories = await memoryStore(context).listMemories({\n limit: boundedLimit(parsedInput.limit, DEFAULT_RESULT_LIMIT),\n });\n return memoryToolResult(\"listMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n\n/** Create a tool that searches visible active memories in the active context. */\nexport function createMemorySearchTool(context: MemoryToolContext) {\n return definePluginTool({\n description:\n \"Search active memories visible in the current context. Use when the model needs targeted memory recall. The tool searches only the current actor and active conversation scopes.\",\n annotations: {\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 memories = await memoryStore(context).searchMemories({\n query: parsedInput.query,\n limit: boundedLimit(parsedInput.limit, DEFAULT_SEARCH_LIMIT),\n });\n return memoryToolResult(\"searchMemories\", {\n memories: memories.map(compactMemory),\n });\n },\n });\n}\n","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\n type PluginRunContext,\n type PluginRunTranscriptEntry,\n type PluginTaskContext,\n type Source,\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 \"createMemory\",\n \"listMemories\",\n \"removeMemory\",\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/** Where a passively extracted memory may be stored, or dropped when unproven. */\ntype MemoryRouteTarget = \"drop\" | \"personal\" | \"conversation\";\n\n/**\n * V1 passive learning opts in by Source branch, then public vs private.\n * Public API is the same as public Slack: shared conversation evidence may\n * learn. Private sources stay out. Local remains available for QA.\n */\nfunction allowsPassiveMemoryExtraction(source: Source): boolean {\n switch (source.platform) {\n case \"local\":\n return true;\n case \"web\":\n case \"slack\":\n return source.visibility === \"public\";\n }\n}\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\">,\n): MemoryRouteTarget {\n const cited = citedEntries(memory.evidenceMessageIndices, transcript);\n if (!cited.valid) {\n return \"drop\";\n }\n if (memory.kind === \"preference\") {\n // Only a run attributed to exactly one human run actor may store a preference.\n const exactlyOneHumanRunActor =\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 scope.\n return cited.entries.every(isRunActorInstruction) ? \"personal\" : \"drop\";\n }\n return cited.entries.every(\n (entry) => isRunActorInstruction(entry) || isConversationEvidence(entry),\n )\n ? \"conversation\"\n : \"drop\";\n}\n\nfunction memoryIdempotencySuffix(\n memory: ExtractedMemory,\n target: MemoryRouteTarget,\n): string {\n return createHash(\"sha256\")\n .update(target)\n .update(\"\\0\")\n .update(memory.kind)\n .update(\"\\0\")\n .update(memory.content)\n .update(\"\\0\")\n .update(memory.expiresAtMs === null ? \"never\" : String(memory.expiresAtMs))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction passiveInput(\n sessionId: string,\n memory: ExtractedMemory,\n sourceKey: string,\n target: MemoryRouteTarget,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory, target)}`,\n kind: memory.kind,\n ...(memory.expiresAtMs !== null ? { expiresAtMs: memory.expiresAtMs } : 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 post-session extraction and consumes only the bounded plugin task\n * projection. Explicit memory tools and private non-local sources remain hard\n * boundaries so background retries cannot reinterpret user-directed mutations\n * or private conversations.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // Memory tool turns already own memory management or recall; do not reinterpret\n // recalled memory output as fresh passive-learning evidence.\n if (\n run.transcript.some(\n (entry) =>\n entry.type === \"toolResult\" && MEMORY_TOOL_NAMES.has(entry.toolName),\n )\n ) {\n return;\n }\n // V1 passive learning is a Source-branch policy: local QA always, public\n // Slack/API by visibility, private sources never.\n if (!allowsPassiveMemoryExtraction(run.source)) {\n return;\n }\n const sourceKey = getSourceKey(run.source);\n if (!sourceKey) {\n return;\n }\n const transcript = run.transcript\n .filter((entry) => entry.text?.trim())\n .map((entry) => ({ ...entry, text: entry.text!.trim() }));\n const evidenceText = transcript\n .filter((entry) => entry.type === \"toolResult\" || entry.role === \"user\")\n .map((entry) => entry.text)\n .join(\"\\n\\n\")\n .trim();\n if (!evidenceText) {\n return;\n }\n\n const runtimeContext = memoryRuntimeContextSchema.parse({\n conversationId: run.conversationId,\n ...(run.actor ? { actor: run.actor } : undefined),\n source: run.source,\n });\n const agent = createMemoryAgent(context.model);\n const store = createMemoryStore(context.db as MemoryDb, runtimeContext, {\n embedder: context.embedder,\n supersessionDecider: agent,\n });\n await store.archiveExpiredMemories();\n const 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 capturedMemorySchema = z\n .object({\n content: z.string().min(1),\n id: z.string().min(1),\n kind: z.enum(MEMORY_KINDS),\n observedAtMs: z.number().finite(),\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 renderCapturedMemories(\n event: z.output<typeof capturedMemoriesSchema>,\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, 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(capturedMemorySchema).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 PluginConversationEvents,\n type PluginLogger,\n type Source,\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 actor?: Actor;\n source: Source;\n text: string;\n}\n\nfunction trimContent(content: string, maxLength: number): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxLength) {\n return trimmed;\n }\n return `${trimmed.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\nfunction formatObservedDate(observedAtMs: number): string {\n return new Date(observedAtMs).toISOString().slice(0, 10);\n}\n\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 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,\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 runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : undefined),\n ...(context.actor ? { actor: context.actor } : undefined),\n source: context.source,\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;\nconst WINDOWS = [7, 30, 90] as const;\n\nconst memoryDaySchema = z\n .object({\n conversation: z.number().int().nonnegative(),\n date: z.string().date(),\n personal: 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} = 'personal'\n )::integer AS personal,\n count(*) FILTER (\n WHERE ${table.scope} = 'conversation'\n )::integer AS conversation\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.personal, 0)::integer AS personal,\n coalesce(daily.conversation, 0)::integer AS conversation\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 conversation:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'conversation')`.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 personal:\n sql<number>`count(*) filter (where ${active} and ${juniorMemoryMemories.scope} = 'personal')`.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: \"personal\",\n value: formatCount(counts?.personal ?? 0),\n },\n {\n label: \"conversation\",\n value: formatCount(counts?.conversation ?? 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 conversation: day.conversation,\n personal: day.personal,\n },\n })),\n description: \"Memories stored per day by scope\",\n id: \"memories-created\",\n series: [\n { key: \"personal\", label: \"Personal\" },\n { key: \"conversation\", label: \"Conversation\" },\n ],\n timeRangeDays: [...WINDOWS],\n title: \"Memories created\",\n type: \"bar_chart\",\n },\n ],\n };\n}\n","/** Project viewer-visible memories into Junior's core-rendered user page. */\nimport type { PluginUserPageDefinition } from \"@sentry/junior-plugin-api\";\nimport { createViewerMemories } from \"./personal\";\nimport type { MemoryVisibility, PersonalMemoryRecord } from \"./personal-store\";\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: PersonalMemoryRecord[\"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 memories = createViewerMemories(ctx.db as MemoryDb, ctx.viewer);\n const page = await memories.list({\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;;;ACpBlB,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,gBAAgB,CAAC,YAAY,cAAc;AACjD,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,0BAA0B,CAAC,SAAS,SAAS,KAAK;AACxD,IAAM,2BAA2B,CAAC,QAAQ;AAC1C,IAAM,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AAAA,UACH;AAAA,UACA,IAAI,IAAI;AAAA,UACR,UAAU,IAAI;AAAA,QAChB,CAAC;AACD,eAAO;AAAA,UACL,cAAc;AAAA,YACZ,wBAAwB;AAAA,cACtB,GAAG;AAAA,cACH;AAAA,cACA,IAAI,IAAI;AAAA,cACR,UAAU,IAAI;AAAA,cACd,qBAAqB;AAAA,YACvB,CAAC;AAAA,UACH;AAAA,UACA,cAAc,uBAAuB,OAAO;AAAA,UAC5C,cAAc,qBAAqB,OAAO;AAAA,UAC1C,gBAAgB,uBAAuB,OAAO;AAAA,QAChD;AAAA,MACF;AAAA,MACA,GAAI,CAAC,QAAQ,gBACT;AAAA,QACE,MAAM,WAAW,KAAK;AACpB,iBAAO,MAAM,gCAAgC;AAAA,YAC3C,OAAO,kBAAkB,IAAI,KAAK;AAAA,YAClC,GAAI,IAAI,iBACJ,EAAE,gBAAgB,IAAI,eAAe,IACrC;AAAA,YACJ,GAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,MAAM,IAAI;AAAA,YACvC,IAAI,IAAI;AAAA,YACR,UAAU,IAAI;AAAA,YACd,QAAQ,IAAI;AAAA,YACZ,KAAK,IAAI;AAAA,YACT,QAAQ,IAAI;AAAA,YACZ,MAAM,IAAI;AAAA,UACZ,CAAC;AAAA,QACH;AAAA,MACF,IACA;AAAA,IACN;AAAA,EACF,CAAC;AACH;","names":["actorSchema","z","sql","z","scopeKey","subjectKey","nonEmptyStringSchema","z","scopePredicate","index","text","sql","idempotent","z","actorSchema","index","z","z","and","asc","desc","eq","gt","like","or","sql","z","nonEmptyStringSchema","z","or","and","eq","scopes","gt","sql","like","desc","asc","index","z","z","and","desc","eq","gt","ilike","isNull","or","or","isNull","gt","eq","ilike","and","desc","eq","eq","z","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","z","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","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"]}