@sentry/junior-memory 0.78.0 → 0.80.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/types.ts","../src/cli/search.ts","../src/db/schema.ts","../src/cli/format.ts","../src/cli/show.ts","../src/cli/index.ts","../src/tools.ts","../src/store.ts","../src/scope.ts","../src/process-session.ts","../src/recall.ts"],"sourcesContent":["import { defineJuniorPlugin } from \"@sentry/junior-plugin-api\";\nimport { createMemoryAgent } from \"./agent\";\nimport { createMemoryCliCommand } from \"./cli\";\nimport {\n createMemoryCreateTool,\n createMemoryListTool,\n createMemoryRemoveTool,\n createMemorySearchTool,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { createMemoryPromptMessages } from \"./recall\";\nimport type { MemoryDb } from \"./store\";\n\nconst MEMORY_MODEL_ENV = \"AI_MEMORY_MODEL\";\n\nexport interface MemoryPluginOptions {\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 requester?: MemoryToolContext[\"requester\"];\n source: MemoryToolContext[\"source\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.requester ? { requester: ctx.requester } : {}),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : {}),\n source: ctx.source,\n ...(ctx.userText ? { userText: ctx.userText } : {}),\n };\n}\n\n/** Create Junior's long-term memory plugin registration. */\nexport function createMemoryPlugin(options: MemoryPluginOptions = {}) {\n const modelId = memoryModelId(options);\n return defineJuniorPlugin({\n manifest: {\n name: \"memory\",\n displayName: \"Memory\",\n description: \"Long-term Junior memory storage and recall\",\n },\n model: modelId\n ? { structuredModelId: modelId }\n : { structuredModel: \"default\" },\n packageName: \"@sentry/junior-memory\",\n cli: {\n commands: [createMemoryCliCommand()],\n },\n tasks: {\n processSession: {\n async run(ctx) {\n await processMemorySession(ctx);\n },\n },\n },\n hooks: {\n tools(ctx) {\n const context = memoryToolContext({\n ...ctx,\n agent: createMemoryAgent(ctx.model),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n });\n return {\n createMemory: createMemoryCreateTool(context),\n removeMemory: createMemoryRemoveTool(context),\n listMemories: createMemoryListTool(context),\n searchMemories: createMemorySearchTool(context),\n };\n },\n async userPrompt(ctx) {\n return await createMemoryPromptMessages({\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.requester ? { requester: ctx.requester } : {}),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n source: ctx.source,\n text: ctx.text,\n });\n },\n },\n });\n}\n\nexport const memoryPlugin = createMemoryPlugin();\n","import type { PluginModel } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst memoryTargetSchema = z.enum([\"requester\", \"conversation\"]);\nconst memoryKindSchema = z.enum([\"preference\", \"procedure\", \"fact\"]);\nconst memoryRejectReasonSchema = z.enum([\n \"not_public_shareable\",\n \"secret_or_credential\",\n \"sensitive_personal\",\n \"third_party_personal\",\n \"vague_or_not_self_contained\",\n \"not_durable\",\n \"assistant_or_system_detail\",\n \"unsupported_scope\",\n]);\nconst createMemoryRequestSchema = z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n runtimeContext: memoryRuntimeContextSchema,\n sourceContext: z\n .object({\n currentUserText: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nconst extractSessionRequestSchema = z\n .object({\n existingMemories: z\n .array(\n z\n .object({\n content: z.string().min(1),\n })\n .strict(),\n )\n .max(10)\n .default([]),\n runtimeContext: memoryRuntimeContextSchema,\n transcript: z\n .array(\n z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"message\"),\n role: z.enum([\"user\", \"assistant\"]),\n text: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"toolResult\"),\n toolName: z.string().min(1),\n isError: z.boolean(),\n text: z.string().min(1),\n })\n .strict(),\n ]),\n )\n .min(1),\n })\n .strict();\n\nconst expiresAtMsSchema = z\n .number()\n .finite()\n .nullable()\n .describe(\n \"Expiration timestamp when the fact should expire, otherwise null.\",\n );\nconst memoryReviewDecisionSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n target: memoryTargetSchema,\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst memoryReviewResponseSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n kind: memoryKindSchema.describe(\n \"Use preference only for requester-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use fact for shared project, channel, operational, or runbook knowledge.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text. It must be self-contained and must not include requester names, requester/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst extractedMemorySchema = z\n .object({\n kind: memoryKindSchema.describe(\n \"Use preference only for requester-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use fact for shared project, channel, operational, or runbook knowledge.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text as one self-contained fact. It must not include requester names, requester/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n })\n .strict();\nconst 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();\n\ntype MemoryReviewResponse = z.output<typeof memoryReviewResponseSchema>;\ntype ExtractMemoriesResponse = z.output<typeof extractMemoriesResponseSchema>;\n\nexport type MemoryTarget = z.output<typeof memoryTargetSchema>;\ntype MemoryKind = z.output<typeof memoryKindSchema>;\n\nexport type MemoryReview = z.output<typeof memoryReviewDecisionSchema>;\n\nexport type CreateMemoryRequest = z.output<typeof createMemoryRequestSchema>;\nexport type ExtractSessionRequest = z.output<\n typeof extractSessionRequestSchema\n>;\nexport interface ExtractedMemory {\n content: string;\n expiresAtMs: number | null;\n target: MemoryTarget;\n}\n\nexport interface MemoryAgent {\n extractSessionMemories(\n request: ExtractSessionRequest,\n ): Promise<ExtractedMemory[]> | ExtractedMemory[];\n reviewCreateRequest(\n request: CreateMemoryRequest,\n ): Promise<MemoryReview> | MemoryReview;\n}\n\nconst MEMORY_REVIEW_SYSTEM = [\n \"You are Junior's memory review agent.\",\n \"Review one memory candidate and return one structured review decision.\",\n \"Store only public/shareable, self-contained facts that are useful beyond this turn.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"Use the runtime context only for authority and scope; do not accept model-provided actor ids, scope ids, aliases, or arbitrary subjects.\",\n].join(\"\\n\");\nconst MEMORY_EXTRACTION_SYSTEM = [\n \"You are Junior's passive memory extraction agent. Return only structured memories worth storing.\",\n \"Use the completed run transcript as source evidence, including user-authored messages and tool results.\",\n \"Assistant text is context for interpreting the run, not independent evidence for new facts.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"If no public, durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst CANONICAL_CONTENT_RULES = [\n \"- Stored memory text must be a rewritten fact, not copied user wording or a sentence about who said it.\",\n \"- Store the minimum useful assertion supported by source evidence; do not add adjacent steps, caveats, or generalized advice.\",\n \"- Do not return both concise and expanded variants of the same source assertion; keep the shortest self-contained canonical memory.\",\n \"- Put ownership in structured fields, not prose.\",\n \"- For requester memories, omit the subject and write a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Drop perspective/provenance markers while preserving useful context.\",\n \"- Remove requester names, display names, requester/user labels, first- or second-person wording, thread labels, channel labels, and source labels.\",\n];\n\nfunction targetForKind(kind: MemoryKind): MemoryTarget {\n if (kind === \"preference\") {\n return \"requester\";\n }\n return \"conversation\";\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\");\n}\n\nfunction runtimeDescription(\n request: Pick<CreateMemoryRequest, \"expiresAtMs\" | \"runtimeContext\">,\n): string {\n const runtime = request.runtimeContext;\n const requester =\n runtime.requester?.platform === \"slack\"\n ? `slack:${runtime.requester.teamId}:${runtime.requester.userId}`\n : runtime.requester?.platform === \"local\"\n ? `local:${runtime.requester.userId}`\n : \"none\";\n const source =\n runtime.source.platform === \"slack\"\n ? `slack:${runtime.source.teamId}:${runtime.source.channelId}`\n : `local:${runtime.source.conversationId}`;\n const lines = [\n `- requester: ${escapeXml(requester)}`,\n `- source: ${escapeXml(source)}`,\n `- has_conversation: ${runtime.conversationId ? \"true\" : \"false\"}`,\n `- expires_at: ${\n request.expiresAtMs === undefined\n ? \"never\"\n : escapeXml(new Date(request.expiresAtMs).toISOString())\n }`,\n ];\n return [\"<runtime>\", ...lines, \"</runtime>\"].join(\"\\n\");\n}\n\nfunction sourceContext(request: CreateMemoryRequest): string | undefined {\n const currentUserText = request.sourceContext?.currentUserText?.trim();\n if (!currentUserText) {\n return undefined;\n }\n return [\n \"<source-context>\",\n \"The current user-authored text is source evidence for explicit memory requests. Use it to recover the concrete fact when the candidate is incomplete, vague, or over-personalized. Store only rewritten, self-contained memory content.\",\n \"<current-user-message>\",\n escapeXml(currentUserText),\n \"</current-user-message>\",\n \"</source-context>\",\n ].join(\"\\n\");\n}\n\nfunction existingMemoriesContext(request: ExtractSessionRequest): string {\n if (request.existingMemories.length === 0) {\n return \"<existing-memories>[]</existing-memories>\";\n }\n return [\n \"<existing-memories>\",\n \"Use these only to skip memories that are already covered or semantically redundant. They are not source evidence for new memories.\",\n escapeXml(JSON.stringify(request.existingMemories)),\n \"</existing-memories>\",\n ].join(\"\\n\");\n}\n\nfunction memoryKindsContext(): string {\n return [\n \"<memory-kinds>\",\n \"- preference: a durable first-person personal preference, opinion, habit, or workflow owned by the current requester. Stored as requester memory.\",\n \"- procedure: reusable instructions for how a task, lookup, investigation, process, triage flow, or runbook should be done. Store the method, source-of-truth, prerequisite, or decision path when it took effort to discover. Stored as conversation memory.\",\n \"- fact: stable shared project, channel, operational, or runbook knowledge that is not a personal requester preference. Direct answers to user inquiries qualify only when they are durable beyond this run. Stored as conversation memory.\",\n \"</memory-kinds>\",\n ].join(\"\\n\");\n}\n\nfunction reviewPrompt(request: CreateMemoryRequest): string {\n const sections = [\n \"<memory-review-input>\",\n \"Review the candidate memory using the runtime-owned context below.\",\n \"\",\n runtimeDescription(request),\n \"\",\n sourceContext(request),\n \"\",\n \"<candidate>\",\n escapeXml(request.content),\n \"</candidate>\",\n \"\",\n \"<rules>\",\n \"- Return store only when the candidate is public/shareable, durable, and self-contained.\",\n \"- First classify the memory kind: preference, procedure, or fact.\",\n \"- Use kind=preference only for first-person facts authored by the current requester about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current requester.\",\n \"- Use kind=procedure for reusable task/process/runbook instructions.\",\n \"- Use kind=fact for shared project, channel, operational, or runbook knowledge.\",\n \"- When current-user-message contains an explicit memory request with a concrete fact or procedure, extract from current-user-message even if the candidate is vague, incomplete, or phrased as an instruction.\",\n \"- A candidate may be badly phrased by an outer assistant or extraction pass. When current-user-message contains the requester's own first-person memory fact, treat that as requester-authored source evidence and canonicalize the fact instead of rejecting for third-person wording.\",\n \"- When candidate wording personalizes a shared task, process, runbook, project, channel, or operational fact, use current-user-message to recover the shared fact and classify it as procedure or fact.\",\n \"- Explicit procedure requests are valid when the source text contains both task context and action. Canonicalize them as shared procedure facts instead of rejecting them as vague.\",\n \"- Store content as person-less, source-less canonical knowledge. Ownership and source live in structured metadata, not prose.\",\n \"- For requester memories, omit the subject and write the content as a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Remove requester names, display names, requester/user labels, first- or second-person wording, thread labels, channel labels, and source labels from stored content.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- Reject vague content such as 'remember this' unless the candidate or current-user-message contains the concrete fact.\",\n \"- Preserve the requested expiration when one exists; otherwise set expiresAtMs to null.\",\n \"- If unsure, reject.\",\n \"</rules>\",\n \"</memory-review-input>\",\n ].filter((section): section is string => section !== undefined);\n return sections.join(\"\\n\");\n}\n\nfunction runTranscriptContext(request: ExtractSessionRequest): string {\n return [\n \"<run-transcript>\",\n ...request.transcript.map((entry, index) => {\n if (entry.type === \"toolResult\") {\n return [\n `<tool-result index=\"${index}\" tool=\"${escapeXml(entry.toolName)}\" is_error=\"${entry.isError ? \"true\" : \"false\"}\">`,\n escapeXml(entry.text),\n \"</tool-result>\",\n ].join(\"\\n\");\n }\n return [\n `<message index=\"${index}\" role=\"${entry.role}\">`,\n escapeXml(entry.text),\n \"</message>\",\n ].join(\"\\n\");\n }),\n \"</run-transcript>\",\n ].join(\"\\n\");\n}\n\nfunction sessionExtractionPrompt(request: ExtractSessionRequest): string {\n return [\n \"<memory-extraction-input>\",\n \"Extract durable memories from this completed agent run using the runtime-owned context below.\",\n \"\",\n runtimeDescription({\n runtimeContext: request.runtimeContext,\n }),\n \"\",\n existingMemoriesContext(request),\n \"\",\n memoryKindsContext(),\n \"\",\n runTranscriptContext(request),\n \"\",\n \"<rules>\",\n \"- Return at most five memories.\",\n \"- Use user messages and successful tool results as source evidence for storable facts.\",\n \"- Use failed tool results only when the failure reveals durable process knowledge, not transient errors.\",\n \"- Use assistant messages only as context; do not store the assistant's claims unless supported by user messages or tool results.\",\n \"- Return one memory per distinct fact.\",\n \"- Prefer storing how to achieve a result: stable source-of-truth, query location, workflow, prerequisite, caveat, or reusable decision path that took effort to discover.\",\n \"- Store direct answers to user inquiries only when they are stable operational/project knowledge, not values that naturally change over time.\",\n \"- Do not store point-in-time analytics, search, issue, metric, incident, availability, or status answers just because a tool produced them.\",\n \"- Do not store the fact that the user asked for advice, search, recall, planning, listing, inspection, or removal. Store only stable knowledge discovered in response, such as a reusable method or source-of-truth.\",\n \"- A user question asking how, what, where, or whether to do something is not source evidence for the answer. Store the answer only when supported by a user-authored factual statement or a tool result.\",\n \"- Set kind=procedure for reusable task/process/runbook instructions.\",\n \"- Set kind=fact for shared team, project, channel, runbook, or operational knowledge.\",\n \"- Set kind=preference only for clear durable first-person facts authored by the current requester about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current requester.\",\n \"- User-authored task instructions are procedures, not preferences, unless they explicitly describe the requester's personal preference or habit.\",\n \"- Procedural statements such as 'for X, do Y', 'when X, do Y', and 'to accomplish X, do Y' belong in procedures.\",\n ...CANONICAL_CONTENT_RULES,\n \"- Skip a candidate when existing-memories already cover the same durable fact.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- If unsure, return no memory for that candidate.\",\n \"</rules>\",\n \"</memory-extraction-input>\",\n ].join(\"\\n\");\n}\n\n/** Create the memory-owned agent that reviews and extracts memory candidates. */\nexport function createMemoryAgent(model: PluginModel): MemoryAgent {\n return {\n async extractSessionMemories(rawRequest) {\n const request = extractSessionRequestSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: extractMemoriesResponseSchema,\n system: MEMORY_EXTRACTION_SYSTEM,\n prompt: sessionExtractionPrompt(request),\n maxTokens: 1_000,\n });\n return extractedMemoriesFromResponse(\n extractMemoriesResponseSchema.parse(result.object),\n );\n },\n async reviewCreateRequest(rawRequest) {\n const request = parseCreateMemoryRequest(rawRequest);\n const result = await model.completeObject({\n schema: memoryReviewResponseSchema,\n system: MEMORY_REVIEW_SYSTEM,\n prompt: reviewPrompt(request),\n maxTokens: 700,\n });\n const response = memoryReviewResponseSchema.parse(result.object);\n return memoryReviewFromResponse(response);\n },\n };\n}\n\nfunction memoryReviewFromResponse(\n response: MemoryReviewResponse,\n): MemoryReview {\n if (response.decision === \"store\") {\n return parseMemoryReview({\n decision: \"store\",\n target: targetForKind(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 content: memory.canonicalFact,\n expiresAtMs: memory.expiresAtMs,\n target: targetForKind(memory.kind),\n });\n return response.memories.map(toMemory);\n}\n\n/** Parse the structured decision returned by the memory agent. */\nexport function parseMemoryReview(result: unknown): MemoryReview {\n return memoryReviewDecisionSchema.parse(result);\n}\n\n/** Parse the structured input sent to the memory agent. */\nexport function parseCreateMemoryRequest(\n request: unknown,\n): CreateMemoryRequest {\n return createMemoryRequestSchema.parse(request);\n}\n","import {\n localRequesterSchema,\n localSourceSchema,\n platformSchema,\n slackRequesterSchema,\n slackSourceSchema,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\n\nexport const MEMORY_TYPES = [\n \"preference\",\n \"identity\",\n \"relationship\",\n \"knowledge\",\n \"context\",\n \"event\",\n \"task\",\n \"observation\",\n] as const;\n\nexport const MEMORY_SCOPES = [\"personal\", \"conversation\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\nexport const MEMORY_SOURCE_PLATFORMS = [\n \"slack\",\n \"local\",\n] as const satisfies readonly z.output<typeof platformSchema>[];\nexport const MEMORY_EMBEDDING_METRICS = [\"cosine\"] as const;\nexport const MEMORY_EMBEDDING_DIMENSIONS = 1536;\n\nexport type MemoryType = (typeof MEMORY_TYPES)[number];\nexport type MemoryScope = (typeof MEMORY_SCOPES)[number];\nexport type MemorySubjectType = (typeof MEMORY_SUBJECT_TYPES)[number];\nexport type MemorySourcePlatform = (typeof MEMORY_SOURCE_PLATFORMS)[number];\nexport type MemoryEmbeddingMetric = (typeof MEMORY_EMBEDDING_METRICS)[number];\n\nconst nonEmptyStringSchema = z.string().min(1);\n\n/** Runtime-owned memory invocation fields used for scope and source authority. */\nexport const slackMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n requester: slackRequesterSchema.optional(),\n source: slackSourceSchema,\n })\n .strict();\n\n/** Runtime-owned local memory invocation fields used for scope and source authority. */\nexport const localMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n requester: localRequesterSchema.optional(),\n source: localSourceSchema,\n })\n .strict();\n\n/** Runtime-owned memory invocation fields accepted by memory store operations. */\nexport const memoryRuntimeContextSchema = z.union([\n slackMemoryRuntimeContextSchema,\n localMemoryRuntimeContextSchema,\n]);\n\nexport type MemoryRuntimeContext = z.output<typeof memoryRuntimeContextSchema>;\n","import { InvalidArgumentError, Option, type Command } from \"commander\";\nimport { and, desc, eq, gt, ilike, isNull, or, type SQL } from \"drizzle-orm\";\nimport type {\n PluginCliActionContext,\n PluginCliHost,\n} from \"@sentry/junior-plugin-api\";\nimport { juniorMemoryMemories } from \"../db/schema\";\nimport type { MemoryDb } from \"../store\";\nimport { MEMORY_SCOPES, type MemoryScope } from \"../types\";\nimport { formatMemory } from \"./format\";\n\ninterface SearchOptions {\n limit: number;\n scope: MemoryScope;\n scopeKey: string;\n showContent?: boolean;\n}\n\nfunction parseLimit(value: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed)) {\n throw new InvalidArgumentError(\"--limit must be a number\");\n }\n return Math.min(100, Math.max(1, Math.floor(parsed)));\n}\n\nasync function runSearch(\n ctx: PluginCliActionContext,\n queryParts: string[] | undefined,\n options: SearchOptions,\n): Promise<number> {\n const query = (queryParts ?? []).join(\" \").trim();\n const nowMs = Date.now();\n const terms = [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n\n const db = ctx.db as MemoryDb;\n const activeExpirationPredicate = or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, nowMs),\n );\n const predicates: SQL[] = [\n eq(juniorMemoryMemories.scope, options.scope),\n eq(juniorMemoryMemories.scopeKey, options.scopeKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n ];\n if (activeExpirationPredicate) {\n predicates.push(activeExpirationPredicate);\n }\n if (terms.length > 0) {\n const termPredicate = or(\n ...terms.map((term) => ilike(juniorMemoryMemories.content, `%${term}%`)),\n );\n if (termPredicate) {\n predicates.push(termPredicate);\n }\n }\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(...predicates))\n .orderBy(desc(juniorMemoryMemories.createdAtMs))\n .limit(options.limit);\n\n if (rows.length === 0) {\n await ctx.io.writeOutput(\"No memories matched.\\n\");\n return 0;\n }\n\n await ctx.io.writeOutput(\n `${rows\n .map((row) =>\n formatMemory(row, { showContent: Boolean(options.showContent) }),\n )\n .join(\"\\n\\n\")}\\n`,\n );\n return 0;\n}\n\n/** Wire the memory search admin subcommand under the plugin namespace. */\nexport function configureMemorySearchCommand(\n parent: Command,\n junior: PluginCliHost,\n): void {\n parent\n .command(\"search\")\n .description(\"Search visible memories\")\n .argument(\"[query...]\", \"Search query\")\n .addOption(\n new Option(\"--scope <scope>\", \"Memory scope\")\n .choices([...MEMORY_SCOPES])\n .makeOptionMandatory(),\n )\n .requiredOption(\"--scope-key <key>\", \"Scope key\")\n .addOption(\n new Option(\"--limit <n>\", \"Maximum rows\")\n .argParser(parseLimit)\n .default(20),\n )\n .option(\"--show-content\", \"Print raw memory content\")\n .action(\n junior.action(async (ctx, queryParts, options) => {\n return await runSearch(\n ctx,\n queryParts as string[] | undefined,\n options as SearchOptions,\n );\n }),\n );\n}\n","/**\n * Drizzle source of truth for memory plugin SQL migrations.\n *\n * Update this schema first, then regenerate packaged migrations with\n * `pnpm --filter @sentry/junior-memory db:generate`.\n */\nimport { sql } from \"drizzle-orm\";\nimport {\n bigint,\n check,\n index,\n integer,\n pgTable,\n text,\n uniqueIndex,\n vector,\n} from \"drizzle-orm/pg-core\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_EMBEDDING_METRICS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_TYPES,\n} from \"../types\";\n\nexport const juniorMemoryMemories = pgTable(\n \"junior_memory_memories\",\n {\n id: text(\"id\").primaryKey(),\n scope: text(\"scope\", { enum: MEMORY_SCOPES }).notNull(),\n scopeKey: text(\"scope_key\").notNull(),\n type: text(\"type\", { enum: MEMORY_TYPES }).notNull(),\n subjectType: text(\"subject_type\", { enum: MEMORY_SUBJECT_TYPES }).notNull(),\n subjectKey: text(\"subject_key\"),\n content: text(\"content\").notNull(),\n sourcePlatform: text(\"source_platform\", {\n enum: MEMORY_SOURCE_PLATFORMS,\n }).notNull(),\n sourceKey: text(\"source_key\").notNull(),\n idempotencyKey: text(\"idempotency_key\"),\n observedAtMs: bigint(\"observed_at_ms\", { mode: \"number\" }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n expiresAtMs: bigint(\"expires_at_ms\", { mode: \"number\" }),\n supersededAtMs: bigint(\"superseded_at_ms\", { mode: \"number\" }),\n supersededById: text(\"superseded_by_id\"),\n archivedAtMs: bigint(\"archived_at_ms\", { mode: \"number\" }),\n archiveReason: text(\"archive_reason\"),\n },\n (table) => [\n index(\"junior_memory_memories_visible_idx\")\n .on(table.scope, table.scopeKey, table.createdAtMs.desc(), table.id)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n index(\"junior_memory_memories_expiration_idx\")\n .on(table.expiresAtMs)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`,\n ),\n uniqueIndex(\"junior_memory_memories_idempotency_idx\")\n .on(table.scope, table.scopeKey, table.idempotencyKey)\n .where(\n sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n check(\n \"junior_memory_memories_scope_check\",\n sql`${table.scope} IN ('personal', 'conversation')`,\n ),\n check(\n \"junior_memory_memories_type_check\",\n sql`${table.type} IN (\n 'preference',\n 'identity',\n 'relationship',\n 'knowledge',\n 'context',\n 'event',\n 'task',\n 'observation'\n )`,\n ),\n check(\n \"junior_memory_memories_subject_type_check\",\n sql`${table.subjectType} IN ('user', 'conversation', 'general')`,\n ),\n check(\n \"junior_memory_memories_subject_key_check\",\n sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`,\n ),\n check(\n \"junior_memory_memories_source_platform_check\",\n sql`${table.sourcePlatform} IN ('slack', 'local')`,\n ),\n ],\n);\n\nexport const juniorMemoryEmbeddings = pgTable(\n \"junior_memory_embeddings\",\n {\n memoryId: text(\"memory_id\")\n .primaryKey()\n .references(() => juniorMemoryMemories.id, { onDelete: \"cascade\" }),\n provider: text(\"provider\").notNull(),\n model: text(\"model\").notNull(),\n dimensions: integer(\"dimensions\").notNull(),\n metric: text(\"metric\", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),\n contentHash: text(\"content_hash\").notNull(),\n embedding: vector(\"embedding\", {\n dimensions: MEMORY_EMBEDDING_DIMENSIONS,\n }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n },\n (table) => [\n index(\"junior_memory_embeddings_model_idx\").on(\n table.provider,\n table.model,\n table.dimensions,\n table.metric,\n ),\n check(\n \"junior_memory_embeddings_metric_check\",\n sql`${table.metric} IN ('cosine')`,\n ),\n check(\n \"junior_memory_embeddings_dimensions_check\",\n sql`${table.dimensions} = ${sql.raw(String(MEMORY_EMBEDDING_DIMENSIONS))}`,\n ),\n ],\n);\n","import type { juniorMemoryMemories } from \"../db/schema\";\n\nfunction formatDate(ms: number | null): string {\n return ms === null ? \"-\" : new Date(ms).toISOString();\n}\n\n/** Format a memory row as an operator-safe CLI projection. */\nexport function formatMemory(\n row: typeof juniorMemoryMemories.$inferSelect,\n args: {\n showContent: boolean;\n },\n): string {\n const lines = [\n `id=${row.id}`,\n `scope=${row.scope}`,\n `scope_key=${row.scopeKey}`,\n `subject_type=${row.subjectType}`,\n ...(row.subjectKey ? [`subject_key=${row.subjectKey}`] : []),\n `type=${row.type}`,\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 TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport {\n getSourceKey,\n PluginToolInputError,\n type PluginToolDefinition,\n type Source,\n type Requester,\n} from \"@sentry/junior-plugin-api\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryEmbeddingProvider,\n type MemoryDb,\n type MemoryRecord,\n} from \"./store\";\nimport {\n parseCreateMemoryRequest,\n parseMemoryReview,\n type MemoryAgent,\n} from \"./agent\";\nimport { memoryRuntimeContextSchema, type MemoryRuntimeContext } from \"./types\";\n\nexport type MemoryReviewer = Pick<MemoryAgent, \"reviewCreateRequest\">;\n\nconst MAX_TOOL_CONTENT_CHARS = 4_000;\nconst DEFAULT_RESULT_LIMIT = 20;\nconst DEFAULT_SEARCH_LIMIT = 10;\n\nconst KNOWN_TOOL_INPUT_ERROR_MESSAGES = new Set([\n \"Conversation memory requires conversation context.\",\n \"Conversation-subject memory requires conversation context.\",\n \"Memory content is required.\",\n \"Memory content exceeds the maximum length.\",\n \"Memory id is required.\",\n \"Memory was not found in the current context.\",\n \"Memory id prefix is ambiguous.\",\n \"Personal memory requires requester context.\",\n \"User-subject memory requires requester context.\",\n]);\n\n/** Runtime-owned context used to bind memory tools to visible scopes. */\nexport interface MemoryToolContext {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n requester?: Requester;\n source: Source;\n userText?: string;\n}\n\nfunction throwToolInputError(message: string): never {\n throw new PluginToolInputError(message);\n}\n\nfunction asToolInputError(error: unknown): never {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n if (\n error instanceof Error &&\n KNOWN_TOOL_INPUT_ERROR_MESSAGES.has(error.message)\n ) {\n throw new PluginToolInputError(error.message, { cause: error });\n }\n throw error;\n}\n\nfunction memoryRuntimeContext(\n context: MemoryToolContext,\n): MemoryRuntimeContext {\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.requester ? { requester: context.requester } : {}),\n source: context.source,\n });\n}\n\nfunction memoryStore(context: MemoryToolContext) {\n return createMemoryStore(context.db, memoryRuntimeContext(context), {\n embedder: context.embedder,\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\ntype MemoryWriteToolInput = {\n content: string;\n expires_at?: string;\n};\n\nconst createMemoryInputSchema = Type.Object(\n {\n content: Type.String({\n minLength: 1,\n maxLength: MAX_TOOL_CONTENT_CHARS,\n description:\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: Type.Optional(\n Type.String({\n minLength: 1,\n description:\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 ),\n },\n { additionalProperties: false },\n);\n\nconst removeMemoryInputSchema = Type.Object(\n {\n id: Type.String({\n minLength: 1,\n description: \"Memory id or unambiguous short id prefix to remove.\",\n }),\n },\n { additionalProperties: false },\n);\n\nconst listMemoriesInputSchema = Type.Object(\n {\n limit: Type.Optional(\n Type.Number({\n minimum: 1,\n maximum: 50,\n description: \"Maximum number of visible memories to return.\",\n }),\n ),\n },\n { additionalProperties: false },\n);\n\nconst searchMemoriesInputSchema = Type.Object(\n {\n query: Type.String({\n minLength: 1,\n description: \"Search query for visible memory content.\",\n }),\n limit: Type.Optional(\n Type.Number({\n minimum: 1,\n maximum: 50,\n description: \"Maximum number of matching memories to return.\",\n }),\n ),\n },\n { additionalProperties: false },\n);\n\nfunction parseToolInput<T>(schema: TSchema, input: unknown): T {\n try {\n if (!Value.Check(schema, input)) {\n throw new Error(\"Input does not match memory tool schema.\");\n }\n return Value.Parse(schema, input) as T;\n } catch (error) {\n throw new PluginToolInputError(\"Invalid memory tool input.\", {\n cause: error,\n });\n }\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 },\n toolCallId: string,\n) {\n return {\n content: requireMemoryContent(input.content),\n idempotencyKey: `tool:${sourceIdempotencyKey(context)}:${toolCallId}`,\n ...(input.expiresAtMs !== undefined\n ? { expiresAtMs: input.expiresAtMs }\n : {}),\n } satisfies CreateMemoryInput;\n}\n\n/** Return the model-visible projection without hidden ownership/source fields. */\nfunction compactMemory(memory: MemoryRecord) {\n return {\n id: memory.id,\n content: memory.content,\n createdAtMs: memory.createdAtMs,\n ...(memory.expiresAtMs !== undefined\n ? { expiresAtMs: memory.expiresAtMs }\n : {}),\n };\n}\n\n/** Create a tool that submits an explicit memory candidate for storage. */\nexport function createMemoryCreateTool(context: MemoryToolContext) {\n return {\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 the canonical stored content, subject, and target.\",\n executionMode: \"sequential\",\n inputSchema: createMemoryInputSchema,\n execute: async (input, options) => {\n const parsedInput = parseToolInput<MemoryWriteToolInput>(\n createMemoryInputSchema,\n input,\n );\n const toolCallId = requireToolCallId(options.toolCallId);\n const requestedExpiresAtMs = parseExpiresAt(parsedInput.expires_at);\n const runtimeContext = memoryRuntimeContext(context);\n const store = memoryStore(context);\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 ...(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 (review.target === \"conversation\") {\n return await store.createConversationMemory(memoryInput);\n }\n return await store.createMemory(memoryInput);\n } catch (error) {\n asToolInputError(error);\n }\n })();\n return {\n ok: true,\n created: result.created,\n memory: compactMemory(result.memory),\n };\n },\n } satisfies PluginToolDefinition<MemoryWriteToolInput>;\n}\n\n/** Create a tool that archives a visible memory in the active context. */\nexport function createMemoryRemoveTool(context: MemoryToolContext) {\n return {\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 execute: async (input) => {\n const parsedInput = parseToolInput<{ id: string }>(\n removeMemoryInputSchema,\n input,\n );\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 {\n ok: true,\n memory: compactMemory(memory),\n };\n },\n } satisfies PluginToolDefinition<{ id: string }>;\n}\n\n/** Create a tool that lists visible active memories in the active context. */\nexport function createMemoryListTool(context: MemoryToolContext) {\n return {\n description:\n \"List active memories visible in the current context. Use when the user asks what Junior remembers or when memory ids are needed before removing a memory.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: listMemoriesInputSchema,\n execute: async (input) => {\n const parsedInput = parseToolInput<{ limit?: number }>(\n listMemoriesInputSchema,\n input,\n );\n const memories = await memoryStore(context).listMemories({\n limit: boundedLimit(parsedInput.limit, DEFAULT_RESULT_LIMIT),\n });\n return {\n ok: true,\n memories: memories.map(compactMemory),\n };\n },\n } satisfies PluginToolDefinition<{ limit?: number }>;\n}\n\n/** Create a tool that searches visible active memories in the active context. */\nexport function createMemorySearchTool(context: MemoryToolContext) {\n return {\n description:\n \"Search active memories visible in the current context. Use when the model needs targeted memory recall. The tool searches only the current requester and active conversation scopes.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: searchMemoriesInputSchema,\n execute: async (input) => {\n const parsedInput = parseToolInput<{ limit?: number; query: string }>(\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 {\n ok: true,\n memories: memories.map(compactMemory),\n };\n },\n } satisfies PluginToolDefinition<{ limit?: number; query: string }>;\n}\n","/**\n * SQL-backed memory store boundary.\n *\n * This module owns row parsing plus visible create/list/search/archive\n * operations. Visibility, expiration, and supersession are enforced before\n * records leave the store.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n and,\n asc,\n desc,\n eq,\n gt,\n ilike,\n isNull,\n like,\n or,\n sql,\n type SQL,\n} from \"drizzle-orm\";\nimport { cosineDistance } from \"drizzle-orm/sql/functions\";\nimport type { PgDatabase } from \"drizzle-orm/pg-core\";\nimport type { PgQueryResultHKT } from \"drizzle-orm/pg-core/session\";\nimport { z } from \"zod\";\nimport * as memorySqlSchema from \"./db/schema\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_TYPES,\n memoryRuntimeContextSchema,\n type MemoryRuntimeContext,\n type MemoryScope,\n} from \"./types\";\nimport {\n deriveMemoryScope,\n deriveMemorySubject,\n deriveVisibleMemoryScopes,\n type ResolvedMemoryScope,\n} from \"./scope\";\n\nconst DEFAULT_LIST_LIMIT = 50;\nconst DEFAULT_SEARCH_LIMIT = 10;\nconst VECTOR_SEARCH_OVERFETCH = 4;\nconst MAX_MEMORY_CONTENT_CHARS = 4_000;\nconst EMBEDDING_METRIC = \"cosine\";\n\nexport type MemoryDb = PgDatabase<PgQueryResultHKT, typeof memorySqlSchema>;\n\ninterface SearchCandidate {\n memory: MemoryRecord;\n score: 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 })\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 clockSchema = z.function({ input: [], output: numberSchema }).optional();\nconst memoryStoreOptionsSchema = z\n .object({\n now: clockSchema,\n })\n .strict();\nconst optionalNumberSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.coerce.number().optional(),\n);\nconst optionalStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().optional(),\n);\nconst optionalNonEmptyStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().min(1).optional(),\n);\nconst memoryRowSchema = z\n .object({\n archivedAtMs: optionalNumberSchema,\n archiveReason: optionalStringSchema,\n content: memoryContentSchema,\n createdAtMs: z.coerce.number(),\n expiresAtMs: optionalNumberSchema,\n id: z.string().min(1),\n idempotencyKey: optionalStringSchema,\n observedAtMs: z.coerce.number(),\n scope: z.enum(MEMORY_SCOPES),\n scopeKey: z.string().min(1),\n sourceKey: z.string().min(1),\n sourcePlatform: z.enum(MEMORY_SOURCE_PLATFORMS),\n subjectKey: optionalNonEmptyStringSchema,\n subjectType: z.enum(MEMORY_SUBJECT_TYPES),\n supersededAtMs: optionalNumberSchema,\n supersededById: optionalStringSchema,\n type: z.enum(MEMORY_TYPES),\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 type: z.enum(MEMORY_TYPES),\n })\n .strict();\nconst embeddingVectorSchema = z\n .array(numberSchema)\n .length(MEMORY_EMBEDDING_DIMENSIONS);\nconst embeddingResultSchema = z\n .object({\n dimensions: z.literal(MEMORY_EMBEDDING_DIMENSIONS),\n model: nonEmptyStringSchema,\n provider: nonEmptyStringSchema,\n vectors: z.array(embeddingVectorSchema),\n })\n .strict();\n\nexport type MemoryRecord = z.output<typeof memoryRecordSchema>;\nexport type CreateMemoryInput = z.output<typeof createMemoryInputSchema>;\n\n/** Result of a memory write after idempotency checks. */\nexport interface CreateMemoryResult {\n created: boolean;\n memory: MemoryRecord;\n}\n\nexport type ListMemoriesInput = z.output<typeof listMemoriesInputSchema>;\n\nexport type SearchMemoriesInput = z.output<typeof searchMemoriesInputSchema>;\n\nexport type ArchiveMemoryInput = z.output<typeof archiveMemoryInputSchema>;\n\nexport interface MemoryEmbeddingProvider {\n /** Embed normalized memory text for derived vector retrieval. */\n embedTexts(input: { texts: string[] }): Promise<{\n dimensions: number;\n model: string;\n provider: string;\n vectors: number[][];\n }>;\n}\n\nexport interface MemoryStoreOptions {\n embedder?: MemoryEmbeddingProvider;\n now?: () => number;\n}\n\n/** Context-bound storage operations for visible long-term memories. */\nexport interface MemoryStore {\n /** Archive a visible memory in the current runtime context. */\n archiveMemory(input: ArchiveMemoryInput): Promise<MemoryRecord>;\n /** Store a personal memory for the current requester. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a conversation memory for the current source conversation. */\n createConversationMemory(\n input: CreateMemoryInput,\n ): Promise<CreateMemoryResult>;\n /** List active memories visible in the current runtime context. */\n listMemories(input: ListMemoriesInput): Promise<MemoryRecord[]>;\n /** Search active memories visible in the current runtime context. */\n searchMemories(input: SearchMemoriesInput): Promise<MemoryRecord[]>;\n}\n\nfunction normalizeContent(content: string): string {\n return content.replace(/\\s+/g, \" \").trim();\n}\n\nfunction hashEmbeddedContent(content: string): string {\n return createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(200, Math.max(1, Math.floor(value)));\n}\n\n/** Build the durable source attribution key from runtime-owned source fields. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n throw new Error(\n \"Memory source requires a Slack message or thread timestamp.\",\n );\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\n/** Parse one SQL row into the public memory record projection. */\nfunction parseMemoryRow(row: unknown): MemoryRecord {\n const parsed = memoryRowSchema.parse(row);\n return memoryRecordSchema.parse({\n id: parsed.id,\n scope: parsed.scope,\n type: parsed.type,\n subjectType: parsed.subjectType,\n content: parsed.content,\n observedAtMs: parsed.observedAtMs,\n createdAtMs: parsed.createdAtMs,\n ...(parsed.expiresAtMs !== undefined\n ? { expiresAtMs: parsed.expiresAtMs }\n : {}),\n ...(parsed.supersededAtMs !== undefined\n ? { supersededAtMs: parsed.supersededAtMs }\n : {}),\n ...(parsed.supersededById ? { supersededById: parsed.supersededById } : {}),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : {}),\n ...(parsed.archiveReason ? { archiveReason: parsed.archiveReason } : {}),\n });\n}\n\n/** Build the scoped SQL predicate and ordered params for visible memory reads. */\nfunction visibleScopePredicate(scopes: ResolvedMemoryScope[]): SQL | undefined {\n if (scopes.length === 0) {\n return undefined;\n }\n return or(\n ...scopes.map((scope) =>\n and(\n eq(juniorMemoryMemories.scope, scope.scope),\n eq(juniorMemoryMemories.scopeKey, scope.scopeKey),\n ),\n ),\n );\n}\n\nfunction activeVisiblePredicate(args: {\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): SQL | undefined {\n const scopePredicate = visibleScopePredicate(args.scopes);\n if (!scopePredicate) {\n return undefined;\n }\n return and(\n scopePredicate,\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n}\n\n/** Resolve retry attempts for the same scoped write idempotency key. */\nasync function findByIdempotencyKey(args: {\n db: MemoryDb;\n idempotencyKey: string;\n scope: ResolvedMemoryScope;\n}): Promise<MemoryRecord | undefined> {\n const rows = 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 ),\n )\n .limit(1);\n return rows[0] ? parseMemoryRow(rows[0]) : undefined;\n}\n\nfunction searchScore(memory: MemoryRecord, terms: string[]): number {\n const haystack = memory.content.toLowerCase();\n // Lexical score is a retrieval fallback signal, not a memory policy decision.\n return terms.reduce(\n (score, term) => score + (haystack.includes(term) ? 1 : 0),\n 0,\n );\n}\n\nfunction searchTerms(query: string): string[] {\n return [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n}\n\nasync function embedOne(\n embedder: MemoryEmbeddingProvider,\n text: string,\n): Promise<{\n model: string;\n provider: string;\n vector: number[];\n}> {\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 memoryId: string;\n nowMs: number;\n}): Promise<void> {\n if (!args.embedder) {\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 try {\n embedding = await embedOne(args.embedder, args.content);\n } catch {\n return;\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\n/** List active records for the runtime-derived visible scopes. */\nasync function listVisibleMemories(args: {\n db: MemoryDb;\n limit?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryRecord[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const limit = boundedLimit(args.limit, DEFAULT_LIST_LIMIT);\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(predicate)\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(limit);\n return rows.map(parseMemoryRow);\n}\n\n/** Search active visible records with the V1 lexical matcher. */\nasync function searchVisibleMemories(args: {\n db: MemoryDb;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryRecord[]> {\n const terms = searchTerms(args.query);\n if (terms.length === 0) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n ),\n ),\n );\n return rows.map(parseMemoryRow);\n}\n\n/** Search active visible records with exact pgvector cosine distance. */\nasync function searchVisibleVectorMemories(args: {\n db: MemoryDb;\n embedder: MemoryEmbeddingProvider | undefined;\n limit: number;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<SearchCandidate[]> {\n if (!args.embedder) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n let embedding: Awaited<ReturnType<typeof embedOne>>;\n try {\n embedding = await embedOne(args.embedder, args.query);\n } catch {\n return [];\n }\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n predicate,\n eq(juniorMemoryEmbeddings.provider, embedding.provider),\n eq(juniorMemoryEmbeddings.model, embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(args.limit);\n return rows.flatMap((row) => {\n const distanceValue = Number(row.distance);\n if (\n row.distance === null ||\n !Number.isFinite(distanceValue) ||\n hashEmbeddedContent(row.memory.content) !== row.contentHash\n ) {\n return [];\n }\n return [\n {\n memory: parseMemoryRow(row.memory),\n score: 1 / (1 + Math.max(0, distanceValue)),\n },\n ];\n });\n}\n\n/** Fuse higher-is-better retrieval candidates before applying the final limit. */\nfunction mergeSearchCandidates(candidates: SearchCandidate[]): MemoryRecord[] {\n const byId = new Map<\n string,\n {\n memory: MemoryRecord;\n score: number;\n }\n >();\n for (const candidate of candidates) {\n const existing = byId.get(candidate.memory.id);\n if (existing) {\n existing.score += candidate.score;\n continue;\n }\n byId.set(candidate.memory.id, {\n memory: candidate.memory,\n score: candidate.score,\n });\n }\n return [...byId.values()]\n .sort(\n (left, right) =>\n right.score - left.score ||\n right.memory.createdAtMs - left.memory.createdAtMs ||\n left.memory.id.localeCompare(right.memory.id),\n )\n .map((candidate) => candidate.memory);\n}\n\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 getNowMs = parsedOptions.now ?? Date.now;\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\n const id = randomUUID();\n const rows = await db\n .insert(juniorMemoryMemories)\n .values({\n content,\n createdAtMs: nowMs,\n expiresAtMs: input.expiresAtMs,\n id,\n idempotencyKey: input.idempotencyKey,\n observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: runtimeContext.source.platform,\n subjectKey: subject.subjectKey,\n subjectType: subject.subjectType,\n type: \"knowledge\",\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 if (rows[0]) {\n const memory = parseMemoryRow(rows[0]);\n await storeEmbedding({\n content: memory.content,\n db,\n embedder,\n memoryId: memory.id,\n nowMs,\n });\n return { created: true, memory };\n }\n\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n scope,\n });\n if (!idempotent) {\n throw new Error(\"Memory idempotency conflict did not resolve.\");\n }\n await storeEmbedding({\n content: idempotent.content,\n db,\n embedder,\n memoryId: idempotent.id,\n nowMs,\n });\n return { created: false, memory: idempotent };\n }\n\n return {\n async 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 return await listVisibleMemories({\n db,\n limit: input.limit,\n nowMs,\n scopes,\n });\n },\n\n async searchMemories(input) {\n input = searchMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n const limit = boundedLimit(input.limit, DEFAULT_SEARCH_LIMIT);\n const vectorCandidates = await searchVisibleVectorMemories({\n db,\n embedder,\n limit: limit * VECTOR_SEARCH_OVERFETCH,\n nowMs,\n query: input.query,\n scopes,\n });\n const candidates = await searchVisibleMemories({\n db,\n nowMs,\n query: input.query,\n scopes,\n });\n const terms = searchTerms(input.query);\n const lexicalCandidates = candidates\n .map((memory) => ({ memory, score: searchScore(memory, terms) }))\n .filter((item) => item.score > 0);\n return mergeSearchCandidates([\n ...vectorCandidates,\n ...lexicalCandidates,\n ]).slice(0, limit);\n },\n\n async archiveMemory(input) {\n input = archiveMemoryInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n const predicate = activeVisiblePredicate({ nowMs, scopes });\n const idPrefix = input.id.trim();\n if (!idPrefix) {\n throw new Error(\"Memory id is required.\");\n }\n const rows = predicate\n ? await db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n eq(juniorMemoryMemories.id, idPrefix),\n like(juniorMemoryMemories.id, `${idPrefix}%`),\n ),\n ),\n )\n .orderBy(asc(juniorMemoryMemories.id))\n .limit(2)\n : [];\n if (rows.length === 0) {\n throw new Error(\"Memory was not found in the current context.\");\n }\n if (rows.length > 1) {\n throw new Error(\"Memory id prefix is ambiguous.\");\n }\n const memory = parseMemoryRow(rows[0]);\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: input.reason ?? \"user_removed\",\n })\n .where(eq(juniorMemoryMemories.id, memory.id))\n .returning();\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memory.id));\n return parseMemoryRow(updated[0]);\n },\n };\n}\n","import { isPrivateSource } from \"@sentry/junior-plugin-api\";\nimport type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\n/** Runtime-derived visibility scope used for memory authorization checks. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** Runtime-derived subject classification stored for filtering and rendering. */\nexport interface ResolvedMemorySubject {\n subjectKey?: string;\n subjectType: MemorySubjectType;\n}\n\nfunction sourceConversationKey(ctx: MemoryRuntimeContext): string | undefined {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n if (!isPrivateSource(ctx.source)) {\n return `slack:${ctx.source.teamId}`;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n return undefined;\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\nfunction requesterScopeKey(ctx: MemoryRuntimeContext): string | undefined {\n const requester = ctx.requester;\n if (!requester?.userId) {\n return undefined;\n }\n if (requester.platform === \"slack\") {\n return `slack:${requester.teamId}:${requester.userId}`;\n }\n return `local:${requester.userId}`;\n}\n\n/** Derive the authority-bearing key for a requested memory scope. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n scope: MemoryScope,\n): ResolvedMemoryScope {\n if (scope === \"personal\") {\n const scopeKey = requesterScopeKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Personal memory requires requester context.\");\n }\n return { scope, scopeKey };\n }\n\n const scopeKey = sourceConversationKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Conversation memory requires conversation context.\");\n }\n return { scope, scopeKey };\n}\n\n/** Derive the memory subject from the already-authorized write scope. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n scope: ResolvedMemoryScope,\n): ResolvedMemorySubject {\n if (scope.scope === \"personal\") {\n const subjectKey = requesterScopeKey(ctx);\n if (!subjectKey) {\n throw new Error(\"User-subject memory requires requester context.\");\n }\n return { subjectType: \"user\", subjectKey };\n }\n\n const subjectKey = sourceConversationKey(ctx);\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return { subjectType: \"conversation\", subjectKey };\n}\n\n/** Return every visible scope for memory retrieval in the current context. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n const scopes: ResolvedMemoryScope[] = [];\n try {\n scopes.push(deriveMemoryScope(ctx, \"personal\"));\n } catch {\n // Personal memory is optional when a runtime surface has no requester.\n }\n try {\n scopes.push(deriveMemoryScope(ctx, \"conversation\"));\n } catch {\n // Conversation memory is optional for synthetic invocations.\n }\n return scopes;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\n isPrivateSource,\n type PluginTaskContext,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryDb,\n} from \"./store\";\nimport { createMemoryAgent, type ExtractedMemory } from \"./agent\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst MEMORY_TOOL_NAMES = new Set([\n \"createMemory\",\n \"listMemories\",\n \"removeMemory\",\n \"searchMemories\",\n]);\nconst MEMORY_TASK_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst extractedMemoryCacheSchema = z.array(\n z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().nullable(),\n target: z.enum([\"requester\", \"conversation\"]),\n })\n .strict(),\n);\n\nfunction memoryIdempotencySuffix(memory: ExtractedMemory): string {\n return createHash(\"sha256\")\n .update(memory.target)\n .update(\"\\0\")\n .update(memory.content)\n .update(\"\\0\")\n .update(memory.expiresAtMs === null ? \"never\" : String(memory.expiresAtMs))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction passiveInput(\n sessionId: string,\n memory: ExtractedMemory,\n sourceKey: string,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory)}`,\n ...(memory.expiresAtMs !== null ? { expiresAtMs: memory.expiresAtMs } : {}),\n };\n}\n\nasync function getTaskMemories(\n context: PluginTaskContext,\n extract: () => Promise<ExtractedMemory[]>,\n): Promise<ExtractedMemory[]> {\n const cacheKey = `memory-extraction:${context.id}`;\n const cached = await context.state.get(cacheKey);\n if (cached !== undefined) {\n return extractedMemoryCacheSchema.parse(cached);\n }\n const memories = await extract();\n if (memories.length > 0) {\n await context.state.set(cacheKey, memories, MEMORY_TASK_STATE_TTL_MS);\n }\n return memories;\n}\n\n/**\n * Extract and store memories from a completed session plugin task.\n *\n * Memory owns post-session extraction and consumes only the bounded plugin task\n * projection. Explicit memory tools and private non-local sources remain hard\n * boundaries so background retries cannot reinterpret user-directed mutations\n * or private conversations.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // Memory tool turns already own memory management or recall; do not reinterpret\n // recalled memory output as fresh passive-learning evidence.\n if (\n run.transcript.some(\n (entry) =>\n entry.type === \"toolResult\" && MEMORY_TOOL_NAMES.has(entry.toolName),\n )\n ) {\n return;\n }\n // V1 passive learning only stores public channel facts outside local QA.\n if (run.source.platform !== \"local\" && isPrivateSource(run.source)) {\n return;\n }\n const sourceKey = getSourceKey(run.source);\n if (!sourceKey) {\n return;\n }\n const transcript = run.transcript\n .filter((entry) => entry.text?.trim())\n .map((entry) => ({ ...entry, text: entry.text!.trim() }));\n const evidenceText = transcript\n .filter((entry) => entry.type === \"toolResult\" || entry.role === \"user\")\n .map((entry) => entry.text)\n .join(\"\\n\\n\")\n .trim();\n if (!evidenceText) {\n return;\n }\n\n const runtimeContext = memoryRuntimeContextSchema.parse({\n conversationId: run.conversationId,\n ...(run.requester ? { requester: run.requester } : {}),\n source: run.source,\n });\n const store = createMemoryStore(context.db as MemoryDb, runtimeContext, {\n embedder: context.embedder,\n });\n const memories = await getTaskMemories(context, async () => {\n const existingMemories = await store.searchMemories({\n limit: 10,\n query: evidenceText,\n });\n const agent = createMemoryAgent(context.model);\n return await agent.extractSessionMemories({\n existingMemories: existingMemories.map((memory) => ({\n content: memory.content,\n })),\n transcript,\n runtimeContext,\n });\n });\n if (memories.length === 0) {\n return;\n }\n\n for (const memory of memories) {\n const input = passiveInput(run.runId, memory, sourceKey);\n if (memory.target === \"conversation\") {\n await store.createConversationMemory(input);\n continue;\n }\n if (!run.requester) {\n continue;\n }\n await store.createMemory(input);\n }\n}\n","import type {\n PromptMessage,\n Requester,\n Source,\n} from \"@sentry/junior-plugin-api\";\nimport {\n createMemoryStore,\n type MemoryDb,\n type MemoryEmbeddingProvider,\n type MemoryRecord,\n} from \"./store\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst DEFAULT_RECALL_LIMIT = 5;\nconst MAX_PROMPT_CHARS = 1_600;\nconst MAX_MEMORY_LINE_CHARS = 320;\n\nexport interface MemoryRecallContext {\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n requester?: Requester;\n source: Source;\n text: string;\n}\n\nfunction trimContent(content: string, maxLength: number): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxLength) {\n return trimmed;\n }\n return `${trimmed.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\nfunction renderMemoryPrompt(memories: MemoryRecord[]): string | undefined {\n const header = \"Relevant memories for this request:\";\n const footer =\n \"Treat these as possibly stale context. Current user instructions and repository evidence take priority.\";\n const lines: string[] = [];\n let totalChars = header.length + footer.length + 2;\n\n for (const memory of memories) {\n const line = `- ${trimContent(memory.content, MAX_MEMORY_LINE_CHARS)}`;\n if (totalChars + line.length + 1 > MAX_PROMPT_CHARS) {\n break;\n }\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length === 0) {\n return undefined;\n }\n return `${header}\\n${lines.join(\"\\n\")}\\n\\n${footer}`;\n}\n\n/** Build the memory prompt contribution for active visible recall. */\nexport async function createMemoryPromptMessages(\n context: MemoryRecallContext,\n): Promise<PromptMessage[] | undefined> {\n if (!context.text.trim()) {\n return undefined;\n }\n const runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.requester ? { requester: context.requester } : {}),\n source: context.source,\n });\n const memories = await createMemoryStore(\n context.db,\n runtimeContext,\n context.embedder ? { embedder: context.embedder } : {},\n ).searchMemories({\n query: context.text,\n limit: DEFAULT_RECALL_LIMIT,\n });\n const text = renderMemoryPrompt(memories);\n return text ? [{ text }] : undefined;\n}\n"],"mappings":";AAAA,SAAS,0BAA0B;;;ACCnC,SAAS,KAAAA,UAAS;;;ACDlB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,gBAAgB,CAAC,YAAY,cAAc;AACjD,IAAM,uBAAuB;AAAA,EAClC;AAAA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AA,IACA,OAAO;AAAA,MACL,gBAAgB;AAAA,QACd,MAAM,IAAI,KAAK;AACb,gBAAM,qBAAqB,GAAG;AAAA,QAChC;AAAA,MACF;AAAA,IACF;AAAA,IACA,OAAO;AAAA,MACL,MAAM,KAAK;AACT,cAAM,UAAU,kBAAkB;AAAA,UAChC,GAAG;AAAA,UACH,OAAO,kBAAkB,IAAI,KAAK;AAAA,UAClC,IAAI,IAAI;AAAA,UACR,UAAU,IAAI;AAAA,QAChB,CAAC;AACD,eAAO;AAAA,UACL,cAAc,uBAAuB,OAAO;AAAA,UAC5C,cAAc,uBAAuB,OAAO;AAAA,UAC5C,cAAc,qBAAqB,OAAO;AAAA,UAC1C,gBAAgB,uBAAuB,OAAO;AAAA,QAChD;AAAA,MACF;AAAA,MACA,MAAM,WAAW,KAAK;AACpB,eAAO,MAAM,2BAA2B;AAAA,UACtC,GAAI,IAAI,iBAAiB,EAAE,gBAAgB,IAAI,eAAe,IAAI,CAAC;AAAA,UACnE,GAAI,IAAI,YAAY,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;AAAA,UACpD,IAAI,IAAI;AAAA,UACR,UAAU,IAAI;AAAA,UACd,QAAQ,IAAI;AAAA,UACZ,MAAM,IAAI;AAAA,QACZ,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEO,IAAM,eAAe,mBAAmB;","names":["z","z","index","eq","eq","and","desc","eq","gt","ilike","isNull","or","sql","z","scopeKey","subjectKey","nonEmptyStringSchema","z","or","and","eq","isNull","gt","text","desc","ilike","sql","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","createHash","getSourceKey","isPrivateSource","z","z","createHash","sourceKey","isPrivateSource","getSourceKey","text"]}
1
+ {"version":3,"sources":["../src/plugin.ts","../src/agent.ts","../src/types.ts","../src/cli/search.ts","../src/db/schema.ts","../src/cli/format.ts","../src/cli/show.ts","../src/cli/index.ts","../src/tools.ts","../src/store.ts","../src/scope.ts","../src/process-session.ts","../src/recall.ts"],"sourcesContent":["import { defineJuniorPlugin } from \"@sentry/junior-plugin-api\";\nimport { createMemoryAgent } from \"./agent\";\nimport { createMemoryCliCommand } from \"./cli\";\nimport {\n createMemoryCreateTool,\n createMemoryListTool,\n createMemoryRemoveTool,\n createMemorySearchTool,\n type MemoryReviewer,\n type MemoryToolContext,\n} from \"./tools\";\nimport { processMemorySession } from \"./process-session\";\nimport { createMemoryPromptMessages } from \"./recall\";\nimport type { MemoryDb } from \"./store\";\n\nconst MEMORY_MODEL_ENV = \"AI_MEMORY_MODEL\";\n\nexport interface MemoryPluginOptions {\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 requester?: MemoryToolContext[\"requester\"];\n source: MemoryToolContext[\"source\"];\n userText?: string;\n}): MemoryToolContext {\n return {\n agent: ctx.agent,\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.requester ? { requester: ctx.requester } : {}),\n db: ctx.db,\n ...(ctx.embedder ? { embedder: ctx.embedder } : {}),\n source: ctx.source,\n ...(ctx.userText ? { userText: ctx.userText } : {}),\n };\n}\n\n/** Create Junior's long-term memory plugin registration. */\nexport function createMemoryPlugin(options: MemoryPluginOptions = {}) {\n const modelId = memoryModelId(options);\n return defineJuniorPlugin({\n manifest: {\n name: \"memory\",\n displayName: \"Memory\",\n description: \"Long-term Junior memory storage and recall\",\n },\n model: modelId\n ? { structuredModelId: modelId }\n : { structuredModel: \"default\" },\n packageName: \"@sentry/junior-memory\",\n cli: {\n commands: [createMemoryCliCommand()],\n },\n tasks: {\n processSession: {\n async run(ctx) {\n await processMemorySession(ctx);\n },\n },\n },\n hooks: {\n tools(ctx) {\n const context = memoryToolContext({\n ...ctx,\n agent: createMemoryAgent(ctx.model),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n });\n return {\n createMemory: createMemoryCreateTool(context),\n removeMemory: createMemoryRemoveTool(context),\n listMemories: createMemoryListTool(context),\n searchMemories: createMemorySearchTool(context),\n };\n },\n async userPrompt(ctx) {\n return await createMemoryPromptMessages({\n ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),\n ...(ctx.requester ? { requester: ctx.requester } : {}),\n db: ctx.db as MemoryDb,\n embedder: ctx.embedder,\n source: ctx.source,\n text: ctx.text,\n });\n },\n },\n });\n}\n\nexport const memoryPlugin = createMemoryPlugin();\n","import type { PluginModel } from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport { MEMORY_KINDS, memoryRuntimeContextSchema } from \"./types\";\n\nconst memoryKindSchema = z.enum(MEMORY_KINDS);\nconst memoryRejectReasonSchema = z.enum([\n \"not_public_shareable\",\n \"secret_or_credential\",\n \"sensitive_personal\",\n \"third_party_personal\",\n \"vague_or_not_self_contained\",\n \"not_durable\",\n \"assistant_or_system_detail\",\n \"unsupported_scope\",\n]);\nconst createMemoryRequestSchema = z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n runtimeContext: memoryRuntimeContextSchema,\n sourceContext: z\n .object({\n currentUserText: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nconst extractSessionRequestSchema = z\n .object({\n existingMemories: z\n .array(\n z\n .object({\n content: z.string().min(1),\n })\n .strict(),\n )\n .max(10)\n .default([]),\n runtimeContext: memoryRuntimeContextSchema,\n transcript: z\n .array(\n z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"message\"),\n role: z.enum([\"user\", \"assistant\"]),\n text: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"toolResult\"),\n toolName: z.string().min(1),\n isError: z.boolean(),\n text: z.string().min(1),\n })\n .strict(),\n ]),\n )\n .min(1),\n })\n .strict();\n\nconst expiresAtMsSchema = z\n .number()\n .finite()\n .nullable()\n .describe(\n \"Expiration timestamp when the fact should expire, otherwise null.\",\n );\nconst memoryReviewDecisionSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n kind: memoryKindSchema,\n content: z.string().min(1),\n expiresAtMs: z.number().finite().optional(),\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst memoryReviewResponseSchema = z.discriminatedUnion(\"decision\", [\n z\n .object({\n decision: z.literal(\"store\"),\n kind: memoryKindSchema.describe(\n \"Use preference only for requester-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use knowledge for shared project, channel, operational, or runbook facts.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text. It must be self-contained and must not include requester names, requester/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n })\n .strict(),\n z\n .object({\n decision: z.literal(\"reject\"),\n reason: memoryRejectReasonSchema,\n })\n .strict(),\n]);\nconst extractedMemorySchema = z\n .object({\n kind: memoryKindSchema.describe(\n \"Use preference only for requester-owned personal preferences, opinions, habits, or workflows. Use procedure for reusable task or process instructions. Use knowledge for shared project, channel, operational, or runbook facts.\",\n ),\n canonicalFact: z\n .string()\n .min(1)\n .describe(\n \"Stored memory text as one self-contained fact. It must not include requester names, requester/user labels, source labels, or first- or second-person wording.\",\n ),\n expiresAtMs: expiresAtMsSchema,\n })\n .strict();\nconst extractedMemoryResultSchema = z\n .object({\n content: z.string().min(1),\n expiresAtMs: expiresAtMsSchema,\n kind: memoryKindSchema,\n })\n .strict();\nconst extractMemoriesResponseSchema = z\n .object({\n memories: z\n .array(extractedMemorySchema)\n .max(5)\n .describe(\n \"Accepted public/shareable durable memories from the completed run. Return one object per distinct source assertion and classify it with kind.\",\n ),\n })\n .strict();\n\ntype MemoryReviewResponse = z.output<typeof memoryReviewResponseSchema>;\ntype ExtractMemoriesResponse = z.output<typeof extractMemoriesResponseSchema>;\n\nexport type MemoryReview = z.output<typeof memoryReviewDecisionSchema>;\n\nexport type CreateMemoryRequest = z.output<typeof createMemoryRequestSchema>;\nexport type ExtractSessionRequest = z.output<\n typeof extractSessionRequestSchema\n>;\nexport type ExtractedMemory = z.output<typeof extractedMemoryResultSchema>;\n\nexport interface MemoryAgent {\n extractSessionMemories(\n request: ExtractSessionRequest,\n ): Promise<ExtractedMemory[]> | ExtractedMemory[];\n reviewCreateRequest(\n request: CreateMemoryRequest,\n ): Promise<MemoryReview> | MemoryReview;\n}\n\nconst MEMORY_REVIEW_SYSTEM = [\n \"You are Junior's memory review agent.\",\n \"Review one memory candidate and return one structured review decision.\",\n \"Store only public/shareable, self-contained facts that are useful beyond this turn.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"Use the runtime context only for authority and scope; do not accept model-provided actor ids, scope ids, aliases, or arbitrary subjects.\",\n].join(\"\\n\");\nconst MEMORY_EXTRACTION_SYSTEM = [\n \"You are Junior's passive memory extraction agent. Return only structured memories worth storing.\",\n \"Use the completed run transcript as source evidence, including user-authored messages and tool results.\",\n \"Assistant text is context for interpreting the run, not independent evidence for new facts.\",\n \"Reject secrets, credentials, private or sensitive personal details, gossip, speculative claims about other people, assistant/system implementation details, vague references, and low-durability chatter.\",\n \"If no public, durable, self-contained memory remains after rewriting, return an empty memories array.\",\n].join(\"\\n\");\nconst CANONICAL_CONTENT_RULES = [\n \"- Stored memory text must be a rewritten fact, not copied user wording or a sentence about who said it.\",\n \"- Store the minimum useful assertion supported by source evidence; do not add adjacent steps, caveats, or generalized advice.\",\n \"- Do not return both concise and expanded variants of the same source assertion; keep the shortest self-contained canonical memory.\",\n \"- Put ownership in structured fields, not prose.\",\n \"- For requester memories, omit the subject and write a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Drop perspective/provenance markers while preserving useful context.\",\n \"- Remove requester names, display names, requester/user labels, first- or second-person wording, thread labels, channel labels, and source labels.\",\n];\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\");\n}\n\nfunction runtimeDescription(\n request: Pick<CreateMemoryRequest, \"expiresAtMs\" | \"runtimeContext\">,\n): string {\n const runtime = request.runtimeContext;\n const requester =\n runtime.requester?.platform === \"slack\"\n ? `slack:${runtime.requester.teamId}:${runtime.requester.userId}`\n : runtime.requester?.platform === \"local\"\n ? `local:${runtime.requester.userId}`\n : \"none\";\n const source =\n runtime.source.platform === \"slack\"\n ? `slack:${runtime.source.teamId}:${runtime.source.channelId}`\n : `local:${runtime.source.conversationId}`;\n const lines = [\n `- requester: ${escapeXml(requester)}`,\n `- source: ${escapeXml(source)}`,\n `- has_conversation: ${runtime.conversationId ? \"true\" : \"false\"}`,\n `- expires_at: ${\n request.expiresAtMs === undefined\n ? \"never\"\n : escapeXml(new Date(request.expiresAtMs).toISOString())\n }`,\n ];\n return [\"<runtime>\", ...lines, \"</runtime>\"].join(\"\\n\");\n}\n\nfunction sourceContext(request: CreateMemoryRequest): string | undefined {\n const currentUserText = request.sourceContext?.currentUserText?.trim();\n if (!currentUserText) {\n return undefined;\n }\n return [\n \"<source-context>\",\n \"The current user-authored text is source evidence for explicit memory requests. Use it to recover the concrete fact when the candidate is incomplete, vague, or over-personalized. Store only rewritten, self-contained memory content.\",\n \"<current-user-message>\",\n escapeXml(currentUserText),\n \"</current-user-message>\",\n \"</source-context>\",\n ].join(\"\\n\");\n}\n\nfunction existingMemoriesContext(request: ExtractSessionRequest): string {\n if (request.existingMemories.length === 0) {\n return \"<existing-memories>[]</existing-memories>\";\n }\n return [\n \"<existing-memories>\",\n \"Use these only to skip memories that are already covered or semantically redundant. They are not source evidence for new memories.\",\n escapeXml(JSON.stringify(request.existingMemories)),\n \"</existing-memories>\",\n ].join(\"\\n\");\n}\n\nfunction memoryKindsContext(): string {\n return [\n \"<memory-kinds>\",\n \"- preference: a durable first-person personal preference, opinion, habit, or workflow owned by the current requester. Stored as requester memory.\",\n \"- procedure: reusable instructions for how a task, lookup, investigation, process, triage flow, or runbook should be done. Store the method, source-of-truth, prerequisite, or decision path when it took effort to discover. Stored as conversation memory.\",\n \"- knowledge: stable shared project, channel, operational, or runbook fact that is not a personal requester preference. Direct answers to user inquiries qualify only when they are durable beyond this run. Stored as conversation memory.\",\n \"</memory-kinds>\",\n ].join(\"\\n\");\n}\n\nfunction reviewPrompt(request: CreateMemoryRequest): string {\n const sections = [\n \"<memory-review-input>\",\n \"Review the candidate memory using the runtime-owned context below.\",\n \"\",\n runtimeDescription(request),\n \"\",\n sourceContext(request),\n \"\",\n \"<candidate>\",\n escapeXml(request.content),\n \"</candidate>\",\n \"\",\n \"<rules>\",\n \"- Return store only when the candidate is public/shareable, durable, and self-contained.\",\n \"- First classify the memory kind: preference, procedure, or knowledge.\",\n \"- Use kind=preference only for first-person facts authored by the current requester about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current requester.\",\n \"- Use kind=procedure for reusable task/process/runbook instructions.\",\n \"- Use kind=knowledge for shared project, channel, operational, or runbook facts.\",\n \"- When current-user-message contains an explicit memory request with a concrete fact or procedure, extract from current-user-message even if the candidate is vague, incomplete, or phrased as an instruction.\",\n \"- A candidate may be badly phrased by an outer assistant or extraction pass. When current-user-message contains the requester's own first-person memory fact, treat that as requester-authored source evidence and canonicalize the fact instead of rejecting for third-person wording.\",\n \"- When candidate wording personalizes a shared task, process, runbook, project, channel, or operational fact, use current-user-message to recover the shared fact and classify it as procedure or knowledge.\",\n \"- Explicit procedure requests are valid when the source text contains both task context and action. Canonicalize them as shared procedure facts instead of rejecting them as vague.\",\n \"- Store content as person-less, source-less canonical knowledge. Ownership and source live in structured metadata, not prose.\",\n \"- For requester memories, omit the subject and write the content as a stable fact such as 'Prefers X', 'Uses Y', or 'Thinks Z'.\",\n \"- Remove requester names, display names, requester/user labels, first- or second-person wording, thread labels, channel labels, and source labels from stored content.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- Reject vague content such as 'remember this' unless the candidate or current-user-message contains the concrete fact.\",\n \"- Preserve the requested expiration when one exists; otherwise set expiresAtMs to null.\",\n \"- If unsure, reject.\",\n \"</rules>\",\n \"</memory-review-input>\",\n ].filter((section): section is string => section !== undefined);\n return sections.join(\"\\n\");\n}\n\nfunction runTranscriptContext(request: ExtractSessionRequest): string {\n return [\n \"<run-transcript>\",\n ...request.transcript.map((entry, index) => {\n if (entry.type === \"toolResult\") {\n return [\n `<tool-result index=\"${index}\" tool=\"${escapeXml(entry.toolName)}\" is_error=\"${entry.isError ? \"true\" : \"false\"}\">`,\n escapeXml(entry.text),\n \"</tool-result>\",\n ].join(\"\\n\");\n }\n return [\n `<message index=\"${index}\" role=\"${entry.role}\">`,\n escapeXml(entry.text),\n \"</message>\",\n ].join(\"\\n\");\n }),\n \"</run-transcript>\",\n ].join(\"\\n\");\n}\n\nfunction sessionExtractionPrompt(request: ExtractSessionRequest): string {\n return [\n \"<memory-extraction-input>\",\n \"Extract durable memories from this completed agent run using the runtime-owned context below.\",\n \"\",\n runtimeDescription({\n runtimeContext: request.runtimeContext,\n }),\n \"\",\n existingMemoriesContext(request),\n \"\",\n memoryKindsContext(),\n \"\",\n runTranscriptContext(request),\n \"\",\n \"<rules>\",\n \"- Return at most five memories.\",\n \"- Use user messages and successful tool results as source evidence for storable facts.\",\n \"- Use failed tool results only when the failure reveals durable process knowledge, not transient errors.\",\n \"- Use assistant messages only as context; do not store the assistant's claims unless supported by user messages or tool results.\",\n \"- Return one memory per distinct fact.\",\n \"- Prefer storing how to achieve a result: stable source-of-truth, query location, workflow, prerequisite, caveat, or reusable decision path that took effort to discover.\",\n \"- Store direct answers to user inquiries only when they are stable operational/project knowledge, not values that naturally change over time.\",\n \"- Do not store point-in-time analytics, search, issue, metric, incident, availability, or status answers just because a tool produced them.\",\n \"- Do not store the fact that the user asked for advice, search, recall, planning, listing, inspection, or removal. Store only stable knowledge discovered in response, such as a reusable method or source-of-truth.\",\n \"- A user question asking how, what, where, or whether to do something is not source evidence for the answer. Store the answer only when supported by a user-authored factual statement or a tool result.\",\n \"- Set kind=procedure for reusable task/process/runbook instructions.\",\n \"- Set kind=knowledge for shared team, project, channel, runbook, or operational facts.\",\n \"- Set kind=preference only for clear durable first-person facts authored by the current requester about their own preference, opinion, habit, identity, or workflow.\",\n \"- Reject named third-person personal facts such as another person's preference, opinion, habit, identity, relationship, or workflow. Do not assume a named person is the current requester.\",\n \"- User-authored task instructions are procedures, not preferences, unless they explicitly describe the requester's personal preference or habit.\",\n \"- Procedural statements such as 'for X, do Y', 'when X, do Y', and 'to accomplish X, do Y' belong in procedures.\",\n ...CANONICAL_CONTENT_RULES,\n \"- Skip a candidate when existing-memories already cover the same durable fact.\",\n \"- Reject third-party personal profile facts, even if they mention a name.\",\n \"- If unsure, return no memory for that candidate.\",\n \"</rules>\",\n \"</memory-extraction-input>\",\n ].join(\"\\n\");\n}\n\n/** Create the memory-owned agent that reviews and extracts memory candidates. */\nexport function createMemoryAgent(model: PluginModel): MemoryAgent {\n return {\n async extractSessionMemories(rawRequest) {\n const request = extractSessionRequestSchema.parse(rawRequest);\n const result = await model.completeObject({\n schema: extractMemoriesResponseSchema,\n system: MEMORY_EXTRACTION_SYSTEM,\n prompt: sessionExtractionPrompt(request),\n maxTokens: 1_000,\n });\n return extractedMemoriesFromResponse(\n extractMemoriesResponseSchema.parse(result.object),\n );\n },\n async reviewCreateRequest(rawRequest) {\n const request = parseCreateMemoryRequest(rawRequest);\n const result = await model.completeObject({\n schema: memoryReviewResponseSchema,\n system: MEMORY_REVIEW_SYSTEM,\n prompt: reviewPrompt(request),\n maxTokens: 700,\n });\n const response = memoryReviewResponseSchema.parse(result.object);\n return memoryReviewFromResponse(response);\n },\n };\n}\n\nfunction memoryReviewFromResponse(\n response: MemoryReviewResponse,\n): MemoryReview {\n if (response.decision === \"store\") {\n return parseMemoryReview({\n decision: \"store\",\n kind: response.kind,\n content: response.canonicalFact,\n ...(response.expiresAtMs !== null\n ? { expiresAtMs: response.expiresAtMs }\n : {}),\n });\n }\n return parseMemoryReview({\n decision: \"reject\",\n reason: response.reason,\n });\n}\n\nfunction extractedMemoriesFromResponse(\n response: ExtractMemoriesResponse,\n): ExtractedMemory[] {\n const toMemory = (\n memory: z.output<typeof extractedMemorySchema>,\n ): ExtractedMemory =>\n parseExtractedMemory({\n content: memory.canonicalFact,\n expiresAtMs: memory.expiresAtMs,\n kind: memory.kind,\n });\n return response.memories.map(toMemory);\n}\n\n/** Parse the canonical extracted-memory shape stored across task retries. */\nexport function parseExtractedMemory(memory: unknown): ExtractedMemory {\n return extractedMemoryResultSchema.parse(memory);\n}\n\n/** Parse the structured decision returned by the memory agent. */\nexport function parseMemoryReview(result: unknown): MemoryReview {\n return memoryReviewDecisionSchema.parse(result);\n}\n\n/** Parse the structured input sent to the memory agent. */\nexport function parseCreateMemoryRequest(\n request: unknown,\n): CreateMemoryRequest {\n return createMemoryRequestSchema.parse(request);\n}\n","import {\n localRequesterSchema,\n localSourceSchema,\n platformSchema,\n slackRequesterSchema,\n slackSourceSchema,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\n\nexport const MEMORY_KINDS = [\"preference\", \"procedure\", \"knowledge\"] as const;\n\nexport const MEMORY_SCOPES = [\"personal\", \"conversation\"] as const;\nexport const MEMORY_SUBJECT_TYPES = [\n \"user\",\n \"conversation\",\n \"general\",\n] as const;\nexport const MEMORY_SOURCE_PLATFORMS = [\n \"slack\",\n \"local\",\n] as const satisfies readonly z.output<typeof platformSchema>[];\nexport const MEMORY_EMBEDDING_METRICS = [\"cosine\"] as const;\nexport const MEMORY_EMBEDDING_DIMENSIONS = 1536;\n\nexport type MemoryKind = (typeof MEMORY_KINDS)[number];\nexport type MemoryScope = (typeof MEMORY_SCOPES)[number];\nexport type MemorySubjectType = (typeof MEMORY_SUBJECT_TYPES)[number];\nexport type MemorySourcePlatform = (typeof MEMORY_SOURCE_PLATFORMS)[number];\nexport type MemoryEmbeddingMetric = (typeof MEMORY_EMBEDDING_METRICS)[number];\n\nconst nonEmptyStringSchema = z.string().min(1);\n\n/** Runtime-owned memory invocation fields used for scope and source authority. */\nexport const slackMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n requester: slackRequesterSchema.optional(),\n source: slackSourceSchema,\n })\n .strict();\n\n/** Runtime-owned local memory invocation fields used for scope and source authority. */\nexport const localMemoryRuntimeContextSchema = z\n .object({\n conversationId: nonEmptyStringSchema.optional(),\n requester: localRequesterSchema.optional(),\n source: localSourceSchema,\n })\n .strict();\n\n/** Runtime-owned memory invocation fields accepted by memory store operations. */\nexport const memoryRuntimeContextSchema = z.union([\n slackMemoryRuntimeContextSchema,\n localMemoryRuntimeContextSchema,\n]);\n\nexport type MemoryRuntimeContext = z.output<typeof memoryRuntimeContextSchema>;\n","import { InvalidArgumentError, Option, type Command } from \"commander\";\nimport { and, desc, eq, gt, ilike, isNull, or, type SQL } from \"drizzle-orm\";\nimport type {\n PluginCliActionContext,\n PluginCliHost,\n} from \"@sentry/junior-plugin-api\";\nimport { juniorMemoryMemories } from \"../db/schema\";\nimport type { MemoryDb } from \"../store\";\nimport { MEMORY_SCOPES, type MemoryScope } from \"../types\";\nimport { formatMemory } from \"./format\";\n\ninterface SearchOptions {\n limit: number;\n scope: MemoryScope;\n scopeKey: string;\n showContent?: boolean;\n}\n\nfunction parseLimit(value: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed)) {\n throw new InvalidArgumentError(\"--limit must be a number\");\n }\n return Math.min(100, Math.max(1, Math.floor(parsed)));\n}\n\nasync function runSearch(\n ctx: PluginCliActionContext,\n queryParts: string[] | undefined,\n options: SearchOptions,\n): Promise<number> {\n const query = (queryParts ?? []).join(\" \").trim();\n const nowMs = Date.now();\n const terms = [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n\n const db = ctx.db as MemoryDb;\n const activeExpirationPredicate = or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, nowMs),\n );\n const predicates: SQL[] = [\n eq(juniorMemoryMemories.scope, options.scope),\n eq(juniorMemoryMemories.scopeKey, options.scopeKey),\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n ];\n if (activeExpirationPredicate) {\n predicates.push(activeExpirationPredicate);\n }\n if (terms.length > 0) {\n const termPredicate = or(\n ...terms.map((term) => ilike(juniorMemoryMemories.content, `%${term}%`)),\n );\n if (termPredicate) {\n predicates.push(termPredicate);\n }\n }\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(and(...predicates))\n .orderBy(desc(juniorMemoryMemories.createdAtMs))\n .limit(options.limit);\n\n if (rows.length === 0) {\n await ctx.io.writeOutput(\"No memories matched.\\n\");\n return 0;\n }\n\n await ctx.io.writeOutput(\n `${rows\n .map((row) =>\n formatMemory(row, { showContent: Boolean(options.showContent) }),\n )\n .join(\"\\n\\n\")}\\n`,\n );\n return 0;\n}\n\n/** Wire the memory search admin subcommand under the plugin namespace. */\nexport function configureMemorySearchCommand(\n parent: Command,\n junior: PluginCliHost,\n): void {\n parent\n .command(\"search\")\n .description(\"Search visible memories\")\n .argument(\"[query...]\", \"Search query\")\n .addOption(\n new Option(\"--scope <scope>\", \"Memory scope\")\n .choices([...MEMORY_SCOPES])\n .makeOptionMandatory(),\n )\n .requiredOption(\"--scope-key <key>\", \"Scope key\")\n .addOption(\n new Option(\"--limit <n>\", \"Maximum rows\")\n .argParser(parseLimit)\n .default(20),\n )\n .option(\"--show-content\", \"Print raw memory content\")\n .action(\n junior.action(async (ctx, queryParts, options) => {\n return await runSearch(\n ctx,\n queryParts as string[] | undefined,\n options as SearchOptions,\n );\n }),\n );\n}\n","/**\n * Drizzle source of truth for memory plugin SQL migrations.\n *\n * Update this schema first, then regenerate packaged migrations with\n * `pnpm --filter @sentry/junior-memory db:generate`.\n */\nimport { sql } from \"drizzle-orm\";\nimport {\n bigint,\n check,\n index,\n integer,\n pgTable,\n text,\n uniqueIndex,\n vector,\n} from \"drizzle-orm/pg-core\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_EMBEDDING_METRICS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_KINDS,\n} from \"../types\";\n\nexport const juniorMemoryMemories = pgTable(\n \"junior_memory_memories\",\n {\n id: text(\"id\").primaryKey(),\n scope: text(\"scope\", { enum: MEMORY_SCOPES }).notNull(),\n scopeKey: text(\"scope_key\").notNull(),\n kind: text(\"type\", { enum: MEMORY_KINDS }).notNull(),\n subjectType: text(\"subject_type\", { enum: MEMORY_SUBJECT_TYPES }).notNull(),\n subjectKey: text(\"subject_key\"),\n content: text(\"content\").notNull(),\n sourcePlatform: text(\"source_platform\", {\n enum: MEMORY_SOURCE_PLATFORMS,\n }).notNull(),\n sourceKey: text(\"source_key\").notNull(),\n idempotencyKey: text(\"idempotency_key\"),\n observedAtMs: bigint(\"observed_at_ms\", { mode: \"number\" }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n expiresAtMs: bigint(\"expires_at_ms\", { mode: \"number\" }),\n supersededAtMs: bigint(\"superseded_at_ms\", { mode: \"number\" }),\n supersededById: text(\"superseded_by_id\"),\n archivedAtMs: bigint(\"archived_at_ms\", { mode: \"number\" }),\n archiveReason: text(\"archive_reason\"),\n },\n (table) => [\n index(\"junior_memory_memories_visible_idx\")\n .on(table.scope, table.scopeKey, table.createdAtMs.desc(), table.id)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n index(\"junior_memory_memories_expiration_idx\")\n .on(table.expiresAtMs)\n .where(\n sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`,\n ),\n uniqueIndex(\"junior_memory_memories_idempotency_idx\")\n .on(table.scope, table.scopeKey, table.idempotencyKey)\n .where(\n sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`,\n ),\n check(\n \"junior_memory_memories_scope_check\",\n sql`${table.scope} IN ('personal', 'conversation')`,\n ),\n check(\n \"junior_memory_memories_kind_check\",\n sql`${table.kind} IN (\n 'preference',\n 'procedure',\n 'knowledge'\n )`,\n ),\n check(\n \"junior_memory_memories_subject_type_check\",\n sql`${table.subjectType} IN ('user', 'conversation', 'general')`,\n ),\n check(\n \"junior_memory_memories_subject_key_check\",\n sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`,\n ),\n check(\n \"junior_memory_memories_source_platform_check\",\n sql`${table.sourcePlatform} IN ('slack', 'local')`,\n ),\n ],\n);\n\nexport const juniorMemoryEmbeddings = pgTable(\n \"junior_memory_embeddings\",\n {\n memoryId: text(\"memory_id\")\n .primaryKey()\n .references(() => juniorMemoryMemories.id, { onDelete: \"cascade\" }),\n provider: text(\"provider\").notNull(),\n model: text(\"model\").notNull(),\n dimensions: integer(\"dimensions\").notNull(),\n metric: text(\"metric\", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),\n contentHash: text(\"content_hash\").notNull(),\n embedding: vector(\"embedding\", {\n dimensions: MEMORY_EMBEDDING_DIMENSIONS,\n }).notNull(),\n createdAtMs: bigint(\"created_at_ms\", { mode: \"number\" }).notNull(),\n },\n (table) => [\n index(\"junior_memory_embeddings_model_idx\").on(\n table.provider,\n table.model,\n table.dimensions,\n table.metric,\n ),\n check(\n \"junior_memory_embeddings_metric_check\",\n sql`${table.metric} IN ('cosine')`,\n ),\n check(\n \"junior_memory_embeddings_dimensions_check\",\n sql`${table.dimensions} = ${sql.raw(String(MEMORY_EMBEDDING_DIMENSIONS))}`,\n ),\n ],\n);\n","import type { juniorMemoryMemories } from \"../db/schema\";\n\nfunction formatDate(ms: number | null): string {\n return ms === null ? \"-\" : new Date(ms).toISOString();\n}\n\n/** Format a memory row as an operator-safe CLI projection. */\nexport function formatMemory(\n row: typeof juniorMemoryMemories.$inferSelect,\n args: {\n showContent: boolean;\n },\n): string {\n const lines = [\n `id=${row.id}`,\n `scope=${row.scope}`,\n `scope_key=${row.scopeKey}`,\n `subject_type=${row.subjectType}`,\n ...(row.subjectKey ? [`subject_key=${row.subjectKey}`] : []),\n `kind=${row.kind}`,\n `created_at=${formatDate(row.createdAtMs)}`,\n `observed_at=${formatDate(row.observedAtMs)}`,\n `expires_at=${formatDate(row.expiresAtMs)}`,\n `archived_at=${formatDate(row.archivedAtMs)}`,\n ];\n if (args.showContent) {\n lines.push(`content=${row.content}`);\n }\n return lines.join(\"\\n\");\n}\n","import type { Command } from \"commander\";\nimport type {\n PluginCliActionContext,\n PluginCliHost,\n} from \"@sentry/junior-plugin-api\";\nimport { eq } from \"drizzle-orm\";\nimport { juniorMemoryMemories } from \"../db/schema\";\nimport type { MemoryDb } from \"../store\";\nimport { formatMemory } from \"./format\";\n\nasync function runShow(\n ctx: PluginCliActionContext,\n id: string,\n): Promise<number> {\n const db = ctx.db as MemoryDb;\n const rows = await db\n .select()\n .from(juniorMemoryMemories)\n .where(eq(juniorMemoryMemories.id, id))\n .limit(1);\n if (!rows[0]) {\n await ctx.io.writeError(`Memory not found: ${id}\\n`);\n return 1;\n }\n\n await ctx.io.writeOutput(`${formatMemory(rows[0], { showContent: true })}\\n`);\n return 0;\n}\n\n/** Wire the explicit raw-content memory inspection subcommand. */\nexport function configureMemoryShowCommand(\n parent: Command,\n junior: PluginCliHost,\n): void {\n parent\n .command(\"show\")\n .description(\"Show one memory\")\n .argument(\"<id>\", \"Memory id\")\n .action(\n junior.action(async (ctx, id) => {\n return await runShow(ctx, id as string);\n }),\n );\n}\n","import type { PluginCliCommandDefinition } from \"@sentry/junior-plugin-api\";\nimport { configureMemorySearchCommand } from \"./search\";\nimport { configureMemoryShowCommand } from \"./show\";\n\n/** Create the plugin-owned memory admin CLI command. */\nexport function createMemoryCliCommand(): PluginCliCommandDefinition {\n return {\n name: \"memory\",\n summary: \"Inspect Junior memory state\",\n configure(command, junior) {\n configureMemorySearchCommand(command, junior);\n configureMemoryShowCommand(command, junior);\n },\n };\n}\n","import { Type, type TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport {\n getSourceKey,\n PluginToolInputError,\n type PluginToolDefinition,\n type Source,\n type Requester,\n} from \"@sentry/junior-plugin-api\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryEmbeddingProvider,\n type MemoryDb,\n type MemoryRecord,\n} from \"./store\";\nimport {\n parseCreateMemoryRequest,\n parseMemoryReview,\n type MemoryAgent,\n} from \"./agent\";\nimport {\n memoryRuntimeContextSchema,\n type MemoryKind,\n type MemoryRuntimeContext,\n} from \"./types\";\n\nexport type MemoryReviewer = Pick<MemoryAgent, \"reviewCreateRequest\">;\n\nconst MAX_TOOL_CONTENT_CHARS = 4_000;\nconst DEFAULT_RESULT_LIMIT = 20;\nconst DEFAULT_SEARCH_LIMIT = 10;\n\nconst KNOWN_TOOL_INPUT_ERROR_MESSAGES = new Set([\n \"Conversation memory requires conversation context.\",\n \"Conversation-subject memory requires conversation context.\",\n \"Memory content is required.\",\n \"Memory content exceeds the maximum length.\",\n \"Memory id is required.\",\n \"Memory was not found in the current context.\",\n \"Memory id prefix is ambiguous.\",\n \"Personal memory requires requester context.\",\n \"User-subject memory requires requester context.\",\n]);\n\n/** Runtime-owned context used to bind memory tools to visible scopes. */\nexport interface MemoryToolContext {\n agent: MemoryReviewer;\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n requester?: Requester;\n source: Source;\n userText?: string;\n}\n\nfunction throwToolInputError(message: string): never {\n throw new PluginToolInputError(message);\n}\n\nfunction asToolInputError(error: unknown): never {\n if (error instanceof PluginToolInputError) {\n throw error;\n }\n if (\n error instanceof Error &&\n KNOWN_TOOL_INPUT_ERROR_MESSAGES.has(error.message)\n ) {\n throw new PluginToolInputError(error.message, { cause: error });\n }\n throw error;\n}\n\nfunction memoryRuntimeContext(\n context: MemoryToolContext,\n): MemoryRuntimeContext {\n return memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.requester ? { requester: context.requester } : {}),\n source: context.source,\n });\n}\n\nfunction memoryStore(context: MemoryToolContext) {\n return createMemoryStore(context.db, memoryRuntimeContext(context), {\n embedder: context.embedder,\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\ntype MemoryWriteToolInput = {\n content: string;\n expires_at?: string;\n};\n\nconst createMemoryInputSchema = Type.Object(\n {\n content: Type.String({\n minLength: 1,\n maxLength: MAX_TOOL_CONTENT_CHARS,\n description:\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: Type.Optional(\n Type.String({\n minLength: 1,\n description:\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 ),\n },\n { additionalProperties: false },\n);\n\nconst removeMemoryInputSchema = Type.Object(\n {\n id: Type.String({\n minLength: 1,\n description: \"Memory id or unambiguous short id prefix to remove.\",\n }),\n },\n { additionalProperties: false },\n);\n\nconst listMemoriesInputSchema = Type.Object(\n {\n limit: Type.Optional(\n Type.Number({\n minimum: 1,\n maximum: 50,\n description: \"Maximum number of visible memories to return.\",\n }),\n ),\n },\n { additionalProperties: false },\n);\n\nconst searchMemoriesInputSchema = Type.Object(\n {\n query: Type.String({\n minLength: 1,\n description: \"Search query for visible memory content.\",\n }),\n limit: Type.Optional(\n Type.Number({\n minimum: 1,\n maximum: 50,\n description: \"Maximum number of matching memories to return.\",\n }),\n ),\n },\n { additionalProperties: false },\n);\n\nfunction parseToolInput<T>(schema: TSchema, input: unknown): T {\n try {\n if (!Value.Check(schema, input)) {\n throw new Error(\"Input does not match memory tool schema.\");\n }\n return Value.Parse(schema, input) as T;\n } catch (error) {\n throw new PluginToolInputError(\"Invalid memory tool input.\", {\n cause: error,\n });\n }\n}\n\nfunction sourceIdempotencyKey(context: MemoryToolContext): string {\n const sourceKey = getSourceKey(context.source);\n if (!sourceKey) {\n throwToolInputError(\"Memory creation requires source message context.\");\n }\n return sourceKey;\n}\n\nfunction createInput(\n context: MemoryToolContext,\n input: { content: string; expiresAtMs?: number; kind: MemoryKind },\n toolCallId: string,\n) {\n return {\n content: requireMemoryContent(input.content),\n idempotencyKey: `tool:${sourceIdempotencyKey(context)}:${toolCallId}`,\n kind: input.kind,\n ...(input.expiresAtMs !== undefined\n ? { expiresAtMs: input.expiresAtMs }\n : {}),\n } satisfies CreateMemoryInput;\n}\n\nfunction targetForKind(kind: MemoryKind): \"requester\" | \"conversation\" {\n if (kind === \"preference\") {\n return \"requester\";\n }\n return \"conversation\";\n}\n\n/** Return the model-visible projection without hidden ownership/source fields. */\nfunction compactMemory(memory: MemoryRecord) {\n return {\n id: memory.id,\n content: memory.content,\n createdAtMs: memory.createdAtMs,\n ...(memory.expiresAtMs !== undefined\n ? { expiresAtMs: memory.expiresAtMs }\n : {}),\n };\n}\n\n/** Create a tool that submits an explicit memory candidate for storage. */\nexport function createMemoryCreateTool(context: MemoryToolContext) {\n return {\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 execute: async (input, options) => {\n const parsedInput = parseToolInput<MemoryWriteToolInput>(\n createMemoryInputSchema,\n input,\n );\n const toolCallId = requireToolCallId(options.toolCallId);\n const requestedExpiresAtMs = parseExpiresAt(parsedInput.expires_at);\n const runtimeContext = memoryRuntimeContext(context);\n const store = memoryStore(context);\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 {\n ok: true,\n created: result.created,\n memory: compactMemory(result.memory),\n };\n },\n } satisfies PluginToolDefinition<MemoryWriteToolInput>;\n}\n\n/** Create a tool that archives a visible memory in the active context. */\nexport function createMemoryRemoveTool(context: MemoryToolContext) {\n return {\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 execute: async (input) => {\n const parsedInput = parseToolInput<{ id: string }>(\n removeMemoryInputSchema,\n input,\n );\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 {\n ok: true,\n memory: compactMemory(memory),\n };\n },\n } satisfies PluginToolDefinition<{ id: string }>;\n}\n\n/** Create a tool that lists visible active memories in the active context. */\nexport function createMemoryListTool(context: MemoryToolContext) {\n return {\n description:\n \"List active memories visible in the current context. Use when the user asks what Junior remembers or when memory ids are needed before removing a memory.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: listMemoriesInputSchema,\n execute: async (input) => {\n const parsedInput = parseToolInput<{ limit?: number }>(\n listMemoriesInputSchema,\n input,\n );\n const memories = await memoryStore(context).listMemories({\n limit: boundedLimit(parsedInput.limit, DEFAULT_RESULT_LIMIT),\n });\n return {\n ok: true,\n memories: memories.map(compactMemory),\n };\n },\n } satisfies PluginToolDefinition<{ limit?: number }>;\n}\n\n/** Create a tool that searches visible active memories in the active context. */\nexport function createMemorySearchTool(context: MemoryToolContext) {\n return {\n description:\n \"Search active memories visible in the current context. Use when the model needs targeted memory recall. The tool searches only the current requester and active conversation scopes.\",\n annotations: { readOnlyHint: true, destructiveHint: false },\n inputSchema: searchMemoriesInputSchema,\n execute: async (input) => {\n const parsedInput = parseToolInput<{ limit?: number; query: string }>(\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 {\n ok: true,\n memories: memories.map(compactMemory),\n };\n },\n } satisfies PluginToolDefinition<{ limit?: number; query: string }>;\n}\n","/**\n * SQL-backed memory store boundary.\n *\n * This module owns row parsing plus visible create/list/search/archive\n * operations. Visibility, expiration, and supersession are enforced before\n * records leave the store.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n and,\n asc,\n desc,\n eq,\n gt,\n ilike,\n inArray,\n isNull,\n like,\n lte,\n or,\n sql,\n type SQL,\n} from \"drizzle-orm\";\nimport { cosineDistance } from \"drizzle-orm/sql/functions\";\nimport type { PgDatabase } from \"drizzle-orm/pg-core\";\nimport type { PgQueryResultHKT } from \"drizzle-orm/pg-core/session\";\nimport { z } from \"zod\";\nimport * as memorySqlSchema from \"./db/schema\";\nimport { juniorMemoryEmbeddings, juniorMemoryMemories } from \"./db/schema\";\nimport {\n MEMORY_EMBEDDING_DIMENSIONS,\n MEMORY_SCOPES,\n MEMORY_SOURCE_PLATFORMS,\n MEMORY_SUBJECT_TYPES,\n MEMORY_KINDS,\n memoryRuntimeContextSchema,\n type MemoryRuntimeContext,\n type MemoryScope,\n} from \"./types\";\nimport {\n deriveMemoryScope,\n deriveMemorySubject,\n 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 VECTOR_SEARCH_OVERFETCH = 4;\nconst MAX_MEMORY_CONTENT_CHARS = 4_000;\nconst EMBEDDING_METRIC = \"cosine\";\n\nexport type MemoryDb = PgDatabase<PgQueryResultHKT, typeof memorySqlSchema>;\n\ninterface SearchCandidate {\n memory: MemoryRecord;\n score: number;\n}\n\nconst nonEmptyStringSchema = z.string().min(1);\nconst memoryContentSchema = z\n .string()\n .refine((content) => content.trim().length > 0, {\n message: \"Memory content is required.\",\n });\nconst numberSchema = z.number().finite();\nconst createMemoryInputSchema = z\n .object({\n content: memoryContentSchema,\n expiresAtMs: numberSchema.optional(),\n idempotencyKey: nonEmptyStringSchema,\n kind: z.enum(MEMORY_KINDS),\n })\n .strict();\nconst listMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n })\n .strict();\nconst searchMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n query: nonEmptyStringSchema,\n })\n .strict();\nconst archiveMemoryInputSchema = z\n .object({\n id: nonEmptyStringSchema,\n reason: nonEmptyStringSchema.optional(),\n })\n .strict();\nconst archiveExpiredMemoriesInputSchema = z\n .object({\n limit: numberSchema.optional(),\n })\n .strict();\nconst clockSchema = z.function({ input: [], output: numberSchema }).optional();\nconst memoryStoreOptionsSchema = z\n .object({\n now: clockSchema,\n })\n .strict();\nconst optionalNumberSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.coerce.number().optional(),\n);\nconst optionalStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().optional(),\n);\nconst optionalNonEmptyStringSchema = z.preprocess(\n (value) => (value === null ? undefined : value),\n z.string().min(1).optional(),\n);\nconst memoryRowSchema = z\n .object({\n archivedAtMs: optionalNumberSchema,\n archiveReason: optionalStringSchema,\n content: memoryContentSchema,\n createdAtMs: z.coerce.number(),\n expiresAtMs: optionalNumberSchema,\n id: z.string().min(1),\n idempotencyKey: optionalStringSchema,\n observedAtMs: z.coerce.number(),\n scope: z.enum(MEMORY_SCOPES),\n scopeKey: z.string().min(1),\n sourceKey: z.string().min(1),\n sourcePlatform: z.enum(MEMORY_SOURCE_PLATFORMS),\n subjectKey: optionalNonEmptyStringSchema,\n subjectType: z.enum(MEMORY_SUBJECT_TYPES),\n supersededAtMs: optionalNumberSchema,\n supersededById: optionalStringSchema,\n kind: z.enum(MEMORY_KINDS),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.subjectType === \"general\") {\n if (row.subjectKey !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n message: \"General-subject memory rows must not have a subject key.\",\n path: [\"subjectKey\"],\n });\n }\n return;\n }\n if (row.subjectKey === undefined) {\n ctx.addIssue({\n code: \"custom\",\n message: \"User and conversation memory rows require a subject key.\",\n path: [\"subjectKey\"],\n });\n }\n });\n\nconst memoryRecordSchema = z\n .object({\n archivedAtMs: numberSchema.optional(),\n archiveReason: nonEmptyStringSchema.optional(),\n content: memoryContentSchema,\n createdAtMs: numberSchema,\n expiresAtMs: numberSchema.optional(),\n id: nonEmptyStringSchema,\n observedAtMs: numberSchema,\n scope: z.enum(MEMORY_SCOPES),\n subjectType: z.enum(MEMORY_SUBJECT_TYPES),\n supersededAtMs: numberSchema.optional(),\n supersededById: nonEmptyStringSchema.optional(),\n kind: z.enum(MEMORY_KINDS),\n })\n .strict();\nconst embeddingVectorSchema = z\n .array(numberSchema)\n .length(MEMORY_EMBEDDING_DIMENSIONS);\nconst embeddingResultSchema = z\n .object({\n dimensions: z.literal(MEMORY_EMBEDDING_DIMENSIONS),\n model: nonEmptyStringSchema,\n provider: nonEmptyStringSchema,\n vectors: z.array(embeddingVectorSchema),\n })\n .strict();\n\nexport type MemoryRecord = z.output<typeof memoryRecordSchema>;\nexport type CreateMemoryInput = z.output<typeof createMemoryInputSchema>;\n\n/** Result of a memory write after idempotency checks. */\nexport interface CreateMemoryResult {\n created: boolean;\n memory: MemoryRecord;\n}\n\nexport type ListMemoriesInput = z.output<typeof listMemoriesInputSchema>;\n\nexport type SearchMemoriesInput = z.output<typeof searchMemoriesInputSchema>;\n\nexport type ArchiveMemoryInput = z.output<typeof archiveMemoryInputSchema>;\n\nexport type ArchiveExpiredMemoriesInput = z.output<\n typeof archiveExpiredMemoriesInputSchema\n>;\n\nexport interface ArchiveExpiredMemoriesResult {\n archivedCount: number;\n}\n\nexport interface MemoryEmbeddingProvider {\n /** Embed normalized memory text for derived vector retrieval. */\n embedTexts(input: { texts: string[] }): Promise<{\n dimensions: number;\n model: string;\n provider: string;\n vectors: number[][];\n }>;\n}\n\nexport interface MemoryStoreOptions {\n embedder?: MemoryEmbeddingProvider;\n now?: () => number;\n}\n\n/** Context-bound storage operations for visible long-term memories. */\nexport interface MemoryStore {\n /** Archive expired memories visible in the current runtime context. */\n archiveExpiredMemories(\n input?: ArchiveExpiredMemoriesInput,\n ): Promise<ArchiveExpiredMemoriesResult>;\n /** Archive a visible memory in the current runtime context. */\n archiveMemory(input: ArchiveMemoryInput): Promise<MemoryRecord>;\n /** Store a personal memory for the current requester. */\n createMemory(input: CreateMemoryInput): Promise<CreateMemoryResult>;\n /** Store a conversation memory for the current source conversation. */\n createConversationMemory(\n input: CreateMemoryInput,\n ): Promise<CreateMemoryResult>;\n /** List active memories visible in the current runtime context. */\n listMemories(input: ListMemoriesInput): Promise<MemoryRecord[]>;\n /** Search active memories visible in the current runtime context. */\n searchMemories(input: SearchMemoriesInput): Promise<MemoryRecord[]>;\n}\n\nfunction normalizeContent(content: string): string {\n return content.replace(/\\s+/g, \" \").trim();\n}\n\nfunction hashEmbeddedContent(content: string): string {\n return createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(200, Math.max(1, Math.floor(value)));\n}\n\n/** Build the durable source attribution key from runtime-owned source fields. */\nfunction sourceKey(ctx: MemoryRuntimeContext): string {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n throw new Error(\n \"Memory source requires a Slack message or thread timestamp.\",\n );\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\n/** Parse one SQL row into the public memory record projection. */\nfunction parseMemoryRow(row: unknown): MemoryRecord {\n const parsed = memoryRowSchema.parse(row);\n return memoryRecordSchema.parse({\n id: parsed.id,\n scope: parsed.scope,\n kind: parsed.kind,\n subjectType: parsed.subjectType,\n content: parsed.content,\n observedAtMs: parsed.observedAtMs,\n createdAtMs: parsed.createdAtMs,\n ...(parsed.expiresAtMs !== undefined\n ? { expiresAtMs: parsed.expiresAtMs }\n : {}),\n ...(parsed.supersededAtMs !== undefined\n ? { supersededAtMs: parsed.supersededAtMs }\n : {}),\n ...(parsed.supersededById ? { supersededById: parsed.supersededById } : {}),\n ...(parsed.archivedAtMs !== undefined\n ? { archivedAtMs: parsed.archivedAtMs }\n : {}),\n ...(parsed.archiveReason ? { archiveReason: parsed.archiveReason } : {}),\n });\n}\n\n/** Build the scoped SQL predicate and ordered params for visible memory reads. */\nfunction visibleScopePredicate(scopes: ResolvedMemoryScope[]): SQL | undefined {\n if (scopes.length === 0) {\n return undefined;\n }\n return or(\n ...scopes.map((scope) =>\n and(\n eq(juniorMemoryMemories.scope, scope.scope),\n eq(juniorMemoryMemories.scopeKey, scope.scopeKey),\n ),\n ),\n );\n}\n\nfunction activeVisiblePredicate(args: {\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): SQL | undefined {\n const scopePredicate = visibleScopePredicate(args.scopes);\n if (!scopePredicate) {\n return undefined;\n }\n return and(\n scopePredicate,\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n or(\n isNull(juniorMemoryMemories.expiresAtMs),\n gt(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ),\n );\n}\n\n/** Resolve retry attempts for the same scoped write idempotency key. */\nasync function findByIdempotencyKey(args: {\n db: MemoryDb;\n idempotencyKey: string;\n nowMs: number;\n scope: ResolvedMemoryScope;\n}): Promise<MemoryRecord | undefined> {\n const rows = 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 return rows[0] ? parseMemoryRow(rows[0]) : undefined;\n}\n\n/**\n * Archive a bounded batch of expired active rows and remove their derived vectors.\n */\nasync function archiveExpiredMemoryBatch(args: {\n db: MemoryDb;\n idempotencyKey?: string;\n limit?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<ArchiveExpiredMemoriesResult> {\n const scopePredicate = visibleScopePredicate(args.scopes);\n if (!scopePredicate) {\n return { archivedCount: 0 };\n }\n const predicates: SQL[] = [\n scopePredicate,\n isNull(juniorMemoryMemories.archivedAtMs),\n isNull(juniorMemoryMemories.supersededAtMs),\n isNull(juniorMemoryMemories.supersededById),\n lte(juniorMemoryMemories.expiresAtMs, args.nowMs),\n ];\n if (args.idempotencyKey !== undefined) {\n predicates.push(\n eq(juniorMemoryMemories.idempotencyKey, args.idempotencyKey),\n );\n }\n\n const archivedIds = await args.db.transaction(async (tx) => {\n const expired = await tx\n .select({ id: juniorMemoryMemories.id })\n .from(juniorMemoryMemories)\n .where(and(...predicates))\n .orderBy(\n asc(juniorMemoryMemories.expiresAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(boundedLimit(args.limit, DEFAULT_EXPIRED_ARCHIVE_LIMIT));\n const ids = expired.map((row) => row.id);\n if (ids.length === 0) {\n return [];\n }\n\n const archived = await tx\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: args.nowMs,\n archiveReason: \"expired\",\n })\n .where(and(inArray(juniorMemoryMemories.id, ids), ...predicates))\n .returning({ id: juniorMemoryMemories.id });\n const idsToClean = archived.map((row) => row.id);\n if (idsToClean.length > 0) {\n await tx\n .delete(juniorMemoryEmbeddings)\n .where(inArray(juniorMemoryEmbeddings.memoryId, idsToClean));\n }\n return idsToClean;\n });\n return { archivedCount: archivedIds.length };\n}\n\nfunction searchScore(memory: MemoryRecord, terms: string[]): number {\n const haystack = memory.content.toLowerCase();\n // Lexical score is a retrieval fallback signal, not a memory policy decision.\n return terms.reduce(\n (score, term) => score + (haystack.includes(term) ? 1 : 0),\n 0,\n );\n}\n\nfunction searchTerms(query: string): string[] {\n return [\n ...new Set(\n query\n .toLowerCase()\n .split(/[^a-z0-9_'-]+/)\n .map((term) => term.trim())\n .filter((term) => term.length >= 2),\n ),\n ];\n}\n\nasync function embedOne(\n embedder: MemoryEmbeddingProvider,\n text: string,\n): Promise<{\n model: string;\n provider: string;\n vector: number[];\n}> {\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 memoryId: string;\n nowMs: number;\n}): Promise<void> {\n if (!args.embedder) {\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 try {\n embedding = await embedOne(args.embedder, args.content);\n } catch {\n return;\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\n/** List active records for the runtime-derived visible scopes. */\nasync function listVisibleMemories(args: {\n db: MemoryDb;\n limit?: number;\n nowMs: number;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryRecord[]> {\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const limit = boundedLimit(args.limit, DEFAULT_LIST_LIMIT);\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(predicate)\n .orderBy(\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(limit);\n return rows.map(parseMemoryRow);\n}\n\n/** Search active visible records with the V1 lexical matcher. */\nasync function searchVisibleMemories(args: {\n db: MemoryDb;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<MemoryRecord[]> {\n const terms = searchTerms(args.query);\n if (terms.length === 0) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n const rows = await args.db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n ...terms.map((term) =>\n ilike(juniorMemoryMemories.content, `%${term}%`),\n ),\n ),\n ),\n );\n return rows.map(parseMemoryRow);\n}\n\n/** Search active visible records with exact pgvector cosine distance. */\nasync function searchVisibleVectorMemories(args: {\n db: MemoryDb;\n embedder: MemoryEmbeddingProvider | undefined;\n limit: number;\n nowMs: number;\n query: string;\n scopes: ResolvedMemoryScope[];\n}): Promise<SearchCandidate[]> {\n if (!args.embedder) {\n return [];\n }\n const predicate = activeVisiblePredicate(args);\n if (!predicate) {\n return [];\n }\n let embedding: Awaited<ReturnType<typeof embedOne>>;\n try {\n embedding = await embedOne(args.embedder, args.query);\n } catch {\n return [];\n }\n const distance = cosineDistance(\n juniorMemoryEmbeddings.embedding,\n embedding.vector,\n );\n const rows = await args.db\n .select({\n contentHash: juniorMemoryEmbeddings.contentHash,\n distance,\n memory: juniorMemoryMemories,\n })\n .from(juniorMemoryMemories)\n .innerJoin(\n juniorMemoryEmbeddings,\n eq(juniorMemoryEmbeddings.memoryId, juniorMemoryMemories.id),\n )\n .where(\n and(\n predicate,\n eq(juniorMemoryEmbeddings.provider, embedding.provider),\n eq(juniorMemoryEmbeddings.model, embedding.model),\n eq(juniorMemoryEmbeddings.dimensions, MEMORY_EMBEDDING_DIMENSIONS),\n eq(juniorMemoryEmbeddings.metric, EMBEDDING_METRIC),\n ),\n )\n .orderBy(\n distance,\n desc(juniorMemoryMemories.createdAtMs),\n asc(juniorMemoryMemories.id),\n )\n .limit(args.limit);\n return rows.flatMap((row) => {\n const distanceValue = Number(row.distance);\n if (\n row.distance === null ||\n !Number.isFinite(distanceValue) ||\n hashEmbeddedContent(row.memory.content) !== row.contentHash\n ) {\n return [];\n }\n return [\n {\n memory: parseMemoryRow(row.memory),\n score: 1 / (1 + Math.max(0, distanceValue)),\n },\n ];\n });\n}\n\n/** Fuse higher-is-better retrieval candidates before applying the final limit. */\nfunction mergeSearchCandidates(candidates: SearchCandidate[]): MemoryRecord[] {\n const byId = new Map<\n string,\n {\n memory: MemoryRecord;\n score: number;\n }\n >();\n for (const candidate of candidates) {\n const existing = byId.get(candidate.memory.id);\n if (existing) {\n existing.score += candidate.score;\n continue;\n }\n byId.set(candidate.memory.id, {\n memory: candidate.memory,\n score: candidate.score,\n });\n }\n return [...byId.values()]\n .sort(\n (left, right) =>\n right.score - left.score ||\n right.memory.createdAtMs - left.memory.createdAtMs ||\n left.memory.id.localeCompare(right.memory.id),\n )\n .map((candidate) => candidate.memory);\n}\n\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 getNowMs = parsedOptions.now ?? Date.now;\n\n async function archiveExpiredVisibleMemories(\n input: ArchiveExpiredMemoriesInput | undefined,\n nowMs: number,\n ): Promise<ArchiveExpiredMemoriesResult> {\n input = archiveExpiredMemoriesInputSchema.parse(input ?? {});\n return await archiveExpiredMemoryBatch({\n db,\n limit: input.limit,\n nowMs,\n scopes: deriveVisibleMemoryScopes(runtimeContext),\n });\n }\n\n /** Persist a memory under the plugin-derived scope and subject. */\n async function createScopedMemory(\n rawInput: CreateMemoryInput,\n scopeKind: MemoryScope,\n ): Promise<CreateMemoryResult> {\n const input = createMemoryInputSchema.parse(rawInput);\n const nowMs = getNowMs();\n const content = normalizeContent(input.content);\n const scope = deriveMemoryScope(runtimeContext, scopeKind);\n const subject = deriveMemorySubject(runtimeContext, scope);\n if (content.length > MAX_MEMORY_CONTENT_CHARS) {\n throw new Error(\"Memory content exceeds the maximum length.\");\n }\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes: [scope],\n });\n await archiveExpiredMemoryBatch({\n db,\n idempotencyKey: input.idempotencyKey,\n limit: 1,\n nowMs,\n scopes: [scope],\n });\n\n const id = randomUUID();\n const rows = await db\n .insert(juniorMemoryMemories)\n .values({\n content,\n createdAtMs: nowMs,\n expiresAtMs: input.expiresAtMs,\n id,\n idempotencyKey: input.idempotencyKey,\n observedAtMs: nowMs,\n scope: scope.scope,\n scopeKey: scope.scopeKey,\n sourceKey: sourceKey(runtimeContext),\n sourcePlatform: runtimeContext.source.platform,\n subjectKey: subject.subjectKey,\n subjectType: subject.subjectType,\n kind: input.kind,\n })\n .onConflictDoNothing({\n target: [\n juniorMemoryMemories.scope,\n juniorMemoryMemories.scopeKey,\n juniorMemoryMemories.idempotencyKey,\n ],\n where: sql`${juniorMemoryMemories.idempotencyKey} IS NOT NULL AND ${juniorMemoryMemories.archivedAtMs} IS NULL AND ${juniorMemoryMemories.supersededAtMs} IS NULL AND ${juniorMemoryMemories.supersededById} IS NULL`,\n })\n .returning();\n if (rows[0]) {\n const memory = parseMemoryRow(rows[0]);\n await storeEmbedding({\n content: memory.content,\n db,\n embedder,\n memoryId: memory.id,\n nowMs,\n });\n return { created: true, memory };\n }\n\n const idempotent = await findByIdempotencyKey({\n db,\n idempotencyKey: input.idempotencyKey,\n nowMs,\n scope,\n });\n if (!idempotent) {\n throw new Error(\"Memory idempotency conflict did not resolve.\");\n }\n await storeEmbedding({\n content: idempotent.content,\n db,\n embedder,\n memoryId: idempotent.id,\n nowMs,\n });\n return { created: false, memory: idempotent };\n }\n\n return {\n async archiveExpiredMemories(input) {\n return await archiveExpiredVisibleMemories(input, getNowMs());\n },\n\n async createMemory(input) {\n return await createScopedMemory(input, \"personal\");\n },\n\n async createConversationMemory(input) {\n return await createScopedMemory(input, \"conversation\");\n },\n\n async listMemories(input) {\n input = listMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n return await listVisibleMemories({\n db,\n limit: input.limit,\n nowMs,\n scopes,\n });\n },\n\n async searchMemories(input) {\n input = searchMemoriesInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n await archiveExpiredMemoryBatch({\n db,\n nowMs,\n scopes,\n });\n const limit = boundedLimit(input.limit, DEFAULT_SEARCH_LIMIT);\n const vectorCandidates = await searchVisibleVectorMemories({\n db,\n embedder,\n limit: limit * VECTOR_SEARCH_OVERFETCH,\n nowMs,\n query: input.query,\n scopes,\n });\n const candidates = await searchVisibleMemories({\n db,\n nowMs,\n query: input.query,\n scopes,\n });\n const terms = searchTerms(input.query);\n const lexicalCandidates = candidates\n .map((memory) => ({ memory, score: searchScore(memory, terms) }))\n .filter((item) => item.score > 0);\n return mergeSearchCandidates([\n ...vectorCandidates,\n ...lexicalCandidates,\n ]).slice(0, limit);\n },\n\n async archiveMemory(input) {\n input = archiveMemoryInputSchema.parse(input);\n const nowMs = getNowMs();\n const scopes = deriveVisibleMemoryScopes(runtimeContext);\n const predicate = activeVisiblePredicate({ nowMs, scopes });\n const idPrefix = input.id.trim();\n if (!idPrefix) {\n throw new Error(\"Memory id is required.\");\n }\n const rows = predicate\n ? await db\n .select()\n .from(juniorMemoryMemories)\n .where(\n and(\n predicate,\n or(\n eq(juniorMemoryMemories.id, idPrefix),\n like(juniorMemoryMemories.id, `${idPrefix}%`),\n ),\n ),\n )\n .orderBy(asc(juniorMemoryMemories.id))\n .limit(2)\n : [];\n if (rows.length === 0) {\n throw new Error(\"Memory was not found in the current context.\");\n }\n if (rows.length > 1) {\n throw new Error(\"Memory id prefix is ambiguous.\");\n }\n const memory = parseMemoryRow(rows[0]);\n const updated = await db\n .update(juniorMemoryMemories)\n .set({\n archivedAtMs: nowMs,\n archiveReason: input.reason ?? \"user_removed\",\n })\n .where(eq(juniorMemoryMemories.id, memory.id))\n .returning();\n await db\n .delete(juniorMemoryEmbeddings)\n .where(eq(juniorMemoryEmbeddings.memoryId, memory.id));\n return parseMemoryRow(updated[0]);\n },\n };\n}\n","import { isPrivateSource } from \"@sentry/junior-plugin-api\";\nimport type {\n MemoryRuntimeContext,\n MemoryScope,\n MemorySubjectType,\n} from \"./types\";\n\n/** Runtime-derived visibility scope used for memory authorization checks. */\nexport interface ResolvedMemoryScope {\n scope: MemoryScope;\n scopeKey: string;\n}\n\n/** Runtime-derived subject classification stored for filtering and rendering. */\nexport interface ResolvedMemorySubject {\n subjectKey?: string;\n subjectType: MemorySubjectType;\n}\n\nfunction sourceConversationKey(ctx: MemoryRuntimeContext): string | undefined {\n if (ctx.source.platform === \"local\") {\n return ctx.source.conversationId;\n }\n if (!isPrivateSource(ctx.source)) {\n return `slack:${ctx.source.teamId}`;\n }\n const threadKey = ctx.source.threadTs ?? ctx.source.messageTs;\n if (!threadKey) {\n return undefined;\n }\n return `slack:${ctx.source.teamId}:${ctx.source.channelId}:${threadKey}`;\n}\n\nfunction requesterScopeKey(ctx: MemoryRuntimeContext): string | undefined {\n const requester = ctx.requester;\n if (!requester?.userId) {\n return undefined;\n }\n if (requester.platform === \"slack\") {\n return `slack:${requester.teamId}:${requester.userId}`;\n }\n return `local:${requester.userId}`;\n}\n\n/** Derive the authority-bearing key for a requested memory scope. */\nexport function deriveMemoryScope(\n ctx: MemoryRuntimeContext,\n scope: MemoryScope,\n): ResolvedMemoryScope {\n if (scope === \"personal\") {\n const scopeKey = requesterScopeKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Personal memory requires requester context.\");\n }\n return { scope, scopeKey };\n }\n\n const scopeKey = sourceConversationKey(ctx);\n if (!scopeKey) {\n throw new Error(\"Conversation memory requires conversation context.\");\n }\n return { scope, scopeKey };\n}\n\n/** Derive the memory subject from the already-authorized write scope. */\nexport function deriveMemorySubject(\n ctx: MemoryRuntimeContext,\n scope: ResolvedMemoryScope,\n): ResolvedMemorySubject {\n if (scope.scope === \"personal\") {\n const subjectKey = requesterScopeKey(ctx);\n if (!subjectKey) {\n throw new Error(\"User-subject memory requires requester context.\");\n }\n return { subjectType: \"user\", subjectKey };\n }\n\n const subjectKey = sourceConversationKey(ctx);\n if (!subjectKey) {\n throw new Error(\n \"Conversation-subject memory requires conversation context.\",\n );\n }\n return { subjectType: \"conversation\", subjectKey };\n}\n\n/** Return every visible scope for memory retrieval in the current context. */\nexport function deriveVisibleMemoryScopes(\n ctx: MemoryRuntimeContext,\n): ResolvedMemoryScope[] {\n const scopes: ResolvedMemoryScope[] = [];\n try {\n scopes.push(deriveMemoryScope(ctx, \"personal\"));\n } catch {\n // Personal memory is optional when a runtime surface has no requester.\n }\n try {\n scopes.push(deriveMemoryScope(ctx, \"conversation\"));\n } catch {\n // Conversation memory is optional for synthetic invocations.\n }\n return scopes;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n getSourceKey,\n isPrivateSource,\n type PluginTaskContext,\n} from \"@sentry/junior-plugin-api\";\nimport { z } from \"zod\";\nimport {\n createMemoryStore,\n type CreateMemoryInput,\n type MemoryDb,\n} from \"./store\";\nimport {\n createMemoryAgent,\n parseExtractedMemory,\n type ExtractedMemory,\n} from \"./agent\";\nimport {\n MEMORY_KINDS,\n memoryRuntimeContextSchema,\n type MemoryKind,\n} from \"./types\";\n\nconst MEMORY_TOOL_NAMES = new Set([\n \"createMemory\",\n \"listMemories\",\n \"removeMemory\",\n \"searchMemories\",\n]);\nconst MEMORY_TASK_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst extractedMemoryCacheSchema = z.array(\n z\n .object({\n content: z.string().min(1),\n expiresAtMs: z.number().finite().nullable(),\n kind: z.enum(MEMORY_KINDS),\n })\n .strict()\n .transform(parseExtractedMemory),\n);\n\nfunction targetForKind(kind: MemoryKind): \"requester\" | \"conversation\" {\n if (kind === \"preference\") {\n return \"requester\";\n }\n return \"conversation\";\n}\n\nfunction memoryIdempotencySuffix(memory: ExtractedMemory): string {\n return createHash(\"sha256\")\n .update(targetForKind(memory.kind))\n .update(\"\\0\")\n .update(memory.kind)\n .update(\"\\0\")\n .update(memory.content)\n .update(\"\\0\")\n .update(memory.expiresAtMs === null ? \"never\" : String(memory.expiresAtMs))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction passiveInput(\n sessionId: string,\n memory: ExtractedMemory,\n sourceKey: string,\n): CreateMemoryInput {\n return {\n content: memory.content,\n idempotencyKey: `session:${sourceKey}:${sessionId}:${memoryIdempotencySuffix(memory)}`,\n kind: memory.kind,\n ...(memory.expiresAtMs !== null ? { expiresAtMs: memory.expiresAtMs } : {}),\n };\n}\n\nasync function getTaskMemories(\n context: PluginTaskContext,\n extract: () => Promise<ExtractedMemory[]>,\n): Promise<ExtractedMemory[]> {\n const cacheKey = `memory-extraction:${context.id}`;\n const cached = await context.state.get(cacheKey);\n if (cached !== undefined) {\n return extractedMemoryCacheSchema.parse(cached);\n }\n const memories = await extract();\n if (memories.length > 0) {\n await context.state.set(cacheKey, memories, MEMORY_TASK_STATE_TTL_MS);\n }\n return memories;\n}\n\n/**\n * Extract and store memories from a completed session plugin task.\n *\n * Memory owns post-session extraction and consumes only the bounded plugin task\n * projection. Explicit memory tools and private non-local sources remain hard\n * boundaries so background retries cannot reinterpret user-directed mutations\n * or private conversations.\n */\nexport async function processMemorySession(\n context: PluginTaskContext,\n): Promise<void> {\n const run = await context.run.load();\n // Memory tool turns already own memory management or recall; do not reinterpret\n // recalled memory output as fresh passive-learning evidence.\n if (\n run.transcript.some(\n (entry) =>\n entry.type === \"toolResult\" && MEMORY_TOOL_NAMES.has(entry.toolName),\n )\n ) {\n return;\n }\n // V1 passive learning only stores public channel facts outside local QA.\n if (run.source.platform !== \"local\" && isPrivateSource(run.source)) {\n return;\n }\n const sourceKey = getSourceKey(run.source);\n if (!sourceKey) {\n return;\n }\n const transcript = run.transcript\n .filter((entry) => entry.text?.trim())\n .map((entry) => ({ ...entry, text: entry.text!.trim() }));\n const evidenceText = transcript\n .filter((entry) => entry.type === \"toolResult\" || entry.role === \"user\")\n .map((entry) => entry.text)\n .join(\"\\n\\n\")\n .trim();\n if (!evidenceText) {\n return;\n }\n\n const runtimeContext = memoryRuntimeContextSchema.parse({\n conversationId: run.conversationId,\n ...(run.requester ? { requester: run.requester } : {}),\n source: run.source,\n });\n const store = createMemoryStore(context.db as MemoryDb, runtimeContext, {\n embedder: context.embedder,\n });\n await store.archiveExpiredMemories();\n const memories = await getTaskMemories(context, async () => {\n const existingMemories = await store.searchMemories({\n limit: 10,\n query: evidenceText,\n });\n const agent = createMemoryAgent(context.model);\n return await agent.extractSessionMemories({\n existingMemories: existingMemories.map((memory) => ({\n content: memory.content,\n })),\n transcript,\n runtimeContext,\n });\n });\n if (memories.length === 0) {\n return;\n }\n\n for (const memory of memories) {\n const input = passiveInput(run.runId, memory, sourceKey);\n if (targetForKind(memory.kind) === \"conversation\") {\n await store.createConversationMemory(input);\n continue;\n }\n if (!run.requester) {\n continue;\n }\n await store.createMemory(input);\n }\n}\n","import type {\n PromptMessage,\n Requester,\n Source,\n} from \"@sentry/junior-plugin-api\";\nimport {\n createMemoryStore,\n type MemoryDb,\n type MemoryEmbeddingProvider,\n type MemoryRecord,\n} from \"./store\";\nimport { memoryRuntimeContextSchema } from \"./types\";\n\nconst DEFAULT_RECALL_LIMIT = 5;\nconst MAX_PROMPT_CHARS = 1_600;\nconst MAX_MEMORY_LINE_CHARS = 320;\n\nexport interface MemoryRecallContext {\n conversationId?: string;\n db: MemoryDb;\n embedder?: MemoryEmbeddingProvider;\n requester?: Requester;\n source: Source;\n text: string;\n}\n\nfunction trimContent(content: string, maxLength: number): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxLength) {\n return trimmed;\n }\n return `${trimmed.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\nfunction renderMemoryPrompt(memories: MemoryRecord[]): string | undefined {\n const header = \"Relevant memories for this request:\";\n const footer =\n \"Treat these as possibly stale context. Current user instructions and repository evidence take priority.\";\n const lines: string[] = [];\n let totalChars = header.length + footer.length + 2;\n\n for (const memory of memories) {\n const line = `- ${trimContent(memory.content, MAX_MEMORY_LINE_CHARS)}`;\n if (totalChars + line.length + 1 > MAX_PROMPT_CHARS) {\n break;\n }\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length === 0) {\n return undefined;\n }\n return `${header}\\n${lines.join(\"\\n\")}\\n\\n${footer}`;\n}\n\n/** Build the memory prompt contribution for active visible recall. */\nexport async function createMemoryPromptMessages(\n context: MemoryRecallContext,\n): Promise<PromptMessage[] | undefined> {\n if (!context.text.trim()) {\n return undefined;\n }\n const runtimeContext = memoryRuntimeContextSchema.parse({\n ...(context.conversationId\n ? { conversationId: context.conversationId }\n : {}),\n ...(context.requester ? { requester: context.requester } : {}),\n source: context.source,\n });\n const memories = await createMemoryStore(\n context.db,\n runtimeContext,\n context.embedder ? { embedder: context.embedder } : {},\n ).searchMemories({\n query: context.text,\n limit: DEFAULT_RECALL_LIMIT,\n });\n const text = renderMemoryPrompt(memories);\n return text ? [{ text }] : undefined;\n}\n"],"mappings":";AAAA,SAAS,0BAA0B;;;ACCnC,SAAS,KAAAA,UAAS;;;ACDlB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe,CAAC,cAAc,aAAa,WAAW;AAE5D,IAAM,gBAAgB,CAAC,YAAY,cAAc;AACjD,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AACF;AACO,IAAM,2BAA2B,CAAC,QAAQ;AAC1C,IAAM,8BAA8B;AAQ3C,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC;AAGtC,IAAM,kCAAkC,EAC5C,OAAO;AAAA,EACN,gBAAgB,qBAAqB,SAAS;AAAA,EAC9C,WAAW,qBAAqB,SAAS;AAAA,EACzC,QAAQ;AACV,CAAC,EACA,OAAO;AAGH,IAAM,kCAAkC,EAC5C,OAAO;AAAA,EACN,gBAAgB,qBAAqB,SAAS;AAAA,EAC9C,WAAW,qBAAqB,SAAS;AAAA,EACzC,QAAQ;AACV,CAAC,EACA,OAAO;AAG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AAAA,QAChB,CAAC;AACD,eAAO;AAAA,UACL,cAAc,uBAAuB,OAAO;AAAA,UAC5C,cAAc,uBAAuB,OAAO;AAAA,UAC5C,cAAc,qBAAqB,OAAO;AAAA,UAC1C,gBAAgB,uBAAuB,OAAO;AAAA,QAChD;AAAA,MACF;AAAA,MACA,MAAM,WAAW,KAAK;AACpB,eAAO,MAAM,2BAA2B;AAAA,UACtC,GAAI,IAAI,iBAAiB,EAAE,gBAAgB,IAAI,eAAe,IAAI,CAAC;AAAA,UACnE,GAAI,IAAI,YAAY,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;AAAA,UACpD,IAAI,IAAI;AAAA,UACR,UAAU,IAAI;AAAA,UACd,QAAQ,IAAI;AAAA,UACZ,MAAM,IAAI;AAAA,QACZ,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEO,IAAM,eAAe,mBAAmB;","names":["z","z","index","eq","eq","and","desc","eq","gt","ilike","isNull","or","sql","z","scopeKey","subjectKey","nonEmptyStringSchema","z","or","and","eq","isNull","gt","text","desc","ilike","sql","DEFAULT_SEARCH_LIMIT","boundedLimit","index","createMemoryInputSchema","listMemoriesInputSchema","searchMemoriesInputSchema","sourceKey","createHash","getSourceKey","isPrivateSource","z","z","targetForKind","createHash","sourceKey","isPrivateSource","getSourceKey","text"]}