@theokit/sdk-memory 0.6.1 → 0.6.3
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/CHANGELOG.md +19 -0
- package/dist/index.cjs +42 -650
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -645
- package/dist/index.js.map +1 -1
- package/dist/internal/index/index-manager-dispatch.d.ts +1 -35
- package/dist/internal/index/index-manager-dispatch.d.ts.map +1 -1
- package/dist/internal/index/index-manager.d.ts +1 -130
- package/dist/internal/index/index-manager.d.ts.map +1 -1
- package/dist/internal/index/lance-index.d.ts +1 -91
- package/dist/internal/index/lance-index.d.ts.map +1 -1
- package/dist/internal/index/lance-memory-adapter.d.ts +16 -115
- package/dist/internal/index/lance-memory-adapter.d.ts.map +1 -1
- package/dist/internal/index/memory-index.d.ts +2 -2
- package/dist/internal/index/migrate-sqlite-to-lance.d.ts +1 -65
- package/dist/internal/index/migrate-sqlite-to-lance.d.ts.map +1 -1
- package/dist/internal/index/migration.d.ts +1 -35
- package/dist/internal/index/migration.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/in-memory-provider.ts","../src/internal/store/markdown-store.ts","../src/internal/active-memory/active-memory.ts","../src/internal/circuit-breaker.ts","../src/internal/embedding/azure-openai-embedding.ts","../src/internal/embedding/cohere-embedding.ts","../src/internal/embedding/deepinfra-embedding.ts","../src/internal/embedding/gemini-embedding.ts","../src/internal/embedding/jina-embedding.ts","../src/internal/embedding/mistral-embedding.ts","../src/internal/embedding/ollama-embedding.ts","../src/internal/embedding/openai-embedding.ts","../src/internal/embedding/openrouter-embedding.ts","../src/internal/embedding/voyage-embedding.ts","../src/internal/adapter-catalog.ts","../src/internal/memory-types.ts","../src/internal/adapter-http-error.ts","../src/internal/categorized-memory.ts","../src/internal/index/lance-index.ts","../src/internal/index/lance-memory-adapter.ts","../src/internal/index/index-manager-dispatch.ts","../src/internal/index/sqlite-vec-loader.ts","../src/internal/index/index-manager.ts","../src/internal/index/migrate-sqlite-to-lance.ts","../src/internal/index/migration.ts","../src/internal/tools.ts"],"names":["ceilingReachedError","ConfigurationError","Security","sessionsDir","join","readdir","readFile","resolveMaxFacts","mkdir","replaceFileAtomic","notesDir","resolveMemoryRoot","finalized","persistActiveMemoryTranscript","createOpenAiCompatibleRuntime","DIMENSION_BY_MODEL","resolvePath","sanitizeIdentifier","safePathJoin","AuthenticationError","RateLimitError","NetworkError","UnknownAgentError","withCwdMutex","createRequire","lanceStoragePath","mkdirSync","parseSearchOptions","defaultIndexPath","projectMemoryDir","openMemoryDb","loadSqliteVecExtension","readEmbeddingIdentity","identityMatches","dropVectorIndex","createVectorIndex","writeEmbeddingIdentity","collectMarkdownFiles","stat","chunkMarkdown","embedMissingChunks","sanitizeFts5Query","vectorSearch","createHash","existsSync","rmSync","readAllSqliteFacts","renameSync","access","appendFactToMarkdown","unlink","memoryMdPath","readMemoryFileBounded"],"mappings":";;;;;;;;;;;;;;;;AA8CA,IAAM,UAAA,GAAa,cAAA;AAwBnB,IAAM,gBAAA,GAAmB,wEAAA;AAqBzB,IAAM,cAAA,0BAAwB,4BAA4B,CAAA;AAE1D,SAAS,iBAAA,GAA+C;AACtD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,QAAA,EAAU,KAAA;AAAA,IACV,OAAA,EAAS,KAAA;AAAA,IACT,SAAA,EAAW,KAAA;AAAA,IACX,WAAA,EAAa,KAAA;AAAA,IACb,QAAA,EAAU;AAAA,GACZ;AACF;AAOA,SAAS,aAAa,KAAA,EAAkC;AACtD,EAAA,IAAI,MAAM,QAAA,KAAa,MAAA,IAAa,MAAM,KAAA,CAAM,IAAA,IAAQ,MAAM,QAAA,EAAU;AACtE,IAAA,MAAMA,+BAAA;AAAA,MACJ,qBAAA;AAAA,MACA,MAAM,KAAA,CAAM,IAAA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AM,IAAA,EAAM,SAAA,EAAW,KAAA,EAAM;AACxC;AAEA,SAAS,YAAA,CAAa,MAAc,SAAA,EAA4B;AAC9D,EAAA,MAAM,iBAAiB,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA,GAAI,IAAA,GAAO,GAAG,IAAI,CAAA,CAAA,CAAA;AAC1D,EAAA,OAAO,SAAA,KAAc,IAAA,IAAQ,SAAA,CAAU,UAAA,CAAW,cAAc,CAAA;AAClE","file":"index.cjs","sourcesContent":["/**\n * `createInMemoryMarkdownProvider` — first concrete `MemoryProvider`\n * impl shipped in `@theokit/sdk-memory` (SDK 2.0 Phase 1 / T1.6).\n *\n * Goal: prove the contract works end-to-end with a real (non-no-op)\n * impl WITHOUT pulling LanceDB / embedding / circuit-breaker infrastructure.\n * That richer impl lands in subsequent iters.\n *\n * Semantics:\n * - Stores recalled facts in a per-agent in-process Map.\n * - `runActivePass()` returns the facts plus a `systemPromptAdditions`\n * string that joins fact contents with newlines (so the LLM sees\n * them in the system slot).\n * - `buildTools()` surfaces a `memory_remember(content)` tool the LLM\n * can call to persist a fact mid-conversation.\n * - `recordSessionSummary()` writes a markdown summary to\n * `${cwd}/.theokit/memory/sessions/${runId}.md` (real disk write\n * via `@theokit/sdk/persistence` per ADR-008).\n * - `dispose()` clears the handle's per-agent map (releases memory).\n *\n * @public\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n ActiveMemoryPassArgs,\n ActiveMemoryPassResult,\n CustomTool,\n MemoryAdapter,\n MemoryAdapterCapabilities,\n MemoryContext,\n MemoryFact,\n MemoryId,\n MemoryProvider,\n MemoryProviderHandle,\n MemoryProviderInitOptions,\n MemoryTurnMessage,\n RecordSessionSummaryArgs,\n SDKAgent,\n} from \"@theokit/sdk\";\nimport { ConfigurationError, Security } from \"@theokit/sdk\";\nimport { ceilingReachedError, resolveMaxFacts } from \"@theokit/sdk/internal/memory-store\";\nimport { replaceFileAtomic } from \"@theokit/sdk/persistence\";\n\n/** Adapter id prefix — namespaces minted MemoryIds so cross-adapter delete is safe (EC-B). */\nconst ADAPTER_ID = \"in-memory-md\";\n\n/**\n * Options for {@link createInMemoryMarkdownProvider}.\n *\n * @public\n */\nexport interface InMemoryMarkdownProviderOptions {\n /**\n * The most facts one handle may hold. Default: no ceiling.\n *\n * Each handle counts only its own facts, so two agents on one provider each get the full\n * ceiling.\n *\n * At the ceiling a new fact is refused on both write paths: the adapter's `write` rejects with a\n * `ConfigurationError` whose code is `memory_ceiling_reached`, and the `memory_remember` tool\n * replies `{ ok: false, code, error }`. Nothing is stored either way, and `delete(id)` frees a\n * slot. A value that is not a positive integer throws `invalid_memory_ceiling` when the provider\n * is created.\n */\n maxFacts?: number;\n}\n\n/** How the in-memory store tells a caller to make room under its ceiling. */\nconst IN_MEMORY_REMEDY = \"merge or delete facts with the adapter's delete(id), or raise maxFacts\";\n\n/** Per-agent state holder. Stored on the handle via the opaque symbol slot. */\ninterface InMemoryHandleState {\n readonly facts: Map<string, MemoryFact>;\n /** The declared ceiling, validated when the provider was created; absent means none. */\n readonly maxFacts: number | undefined;\n readonly counter: { next: number };\n /**\n * Workspace cwd captured at `init()` time. Used by `runActivePass()`\n * to read previously-written session summaries from disk for recall\n * (iter 34 — closes the \"write but never read\" gap from iter 33).\n */\n readonly cwd: string;\n /**\n * `sessions: true` capability is set when cwd is available (always),\n * so future Stage 3 work can mark this provider as the canonical\n * sessions-recall path (vs. the no-op default).\n */\n}\n\nconst INTERNAL_STATE = Symbol(\"sdk-memory.in-memory.state\");\n\nfunction buildCapabilities(): MemoryAdapterCapabilities {\n return {\n history: false,\n sessions: false,\n tenancy: false,\n reasoning: false,\n toolSchemas: false,\n prefetch: false,\n };\n}\n\n/**\n * Refuse a new fact at the handle's ceiling. Called synchronously right before each `facts.set`,\n * with no `await` between the check and the set, so two racing writes cannot both pass: the event\n * loop runs each synchronous block to completion.\n */\nfunction admitNewFact(state: InMemoryHandleState): void {\n if (state.maxFacts !== undefined && state.facts.size >= state.maxFacts) {\n throw ceilingReachedError(\n \"the in-memory store\",\n state.facts.size,\n state.maxFacts,\n IN_MEMORY_REMEDY,\n );\n }\n}\n\nfunction isCeilingRefusal(cause: unknown): cause is ConfigurationError {\n return cause instanceof ConfigurationError && cause.code === \"memory_ceiling_reached\";\n}\n\nfunction buildAdapter(state: InMemoryHandleState): MemoryAdapter {\n return {\n id: ADAPTER_ID,\n capabilities: buildCapabilities(),\n isAvailable(): boolean {\n return true;\n },\n async write(content: string | MemoryTurnMessage[], _ctx: MemoryContext): Promise<MemoryId> {\n const text = typeof content === \"string\" ? content : content.map((m) => m.content).join(\"\\n\");\n // Iter 43: redact secrets before persisting. Same posture as\n // memory_remember tool handler — secret-containing payloads\n // submitted to MemoryAdapter.write directly should never\n // surface verbatim in subsequent recall.\n const safeText = Security.redact(text);\n admitNewFact(state);\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeText,\n createdAt: new Date().toISOString(),\n });\n return id;\n },\n async recall(_query: string, _ctx: MemoryContext, k?: number): Promise<MemoryFact[]> {\n // Naive recall — return everything (cap at k). Real impls in\n // subsequent iters add semantic similarity via embeddings.\n const all = Array.from(state.facts.values());\n const limit = k !== undefined && k >= 0 ? k : all.length;\n return all.slice(0, limit);\n },\n async delete(id: MemoryId): Promise<void> {\n if (!String(id).startsWith(`${ADAPTER_ID}:`)) {\n throw new Error(\n `MemoryAdapter.delete: id \"${String(id)}\" was not minted by adapter \"${ADAPTER_ID}\"`,\n );\n }\n state.facts.delete(id);\n },\n };\n}\n\n/** Truncate session-summary text fields to bound disk size. */\nconst MAX_SUMMARY_TURN_CHARS = 2000;\n\nfunction truncate(text: string): string {\n if (text.length <= MAX_SUMMARY_TURN_CHARS) return text;\n return `${text.slice(0, MAX_SUMMARY_TURN_CHARS)}…`;\n}\n\n/**\n * Sanitize a runId for use as a filename. Strip path separators +\n * traversal patterns; keep `[a-zA-Z0-9_-]`; cap at 128 chars.\n * Mirrors sdk-core's legacy `writeSessionSummary` sanitizer so the\n * file-path semantics are identical across paths.\n */\nfunction sanitizeRunId(runId: string): string {\n return runId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 128);\n}\n\n/** Render the session-summary markdown body. */\nfunction renderSessionSummaryMarkdown(args: RecordSessionSummaryArgs): string {\n const iso = new Date(args.at).toISOString();\n // Iter 42: redact secrets from User + Assistant text via the public\n // `Security.redact()` API (sdk-core's ADR D68 canonical redactor —\n // 12 built-in patterns: OpenAI, Anthropic, GitHub PAT, AWS, etc.).\n // Mirrors sdk-core's legacy writeSessionSummary behavior so the\n // disk artefact never leaks API keys typed by the user.\n const safeUser = Security.redact(truncate(args.userText));\n const safeAssistant = Security.redact(truncate(args.assistantText));\n return [\n \"---\",\n `runId: ${args.runId}`,\n `agentId: ${args.agentId}`,\n `at: ${iso}`,\n `status: ${args.status}`,\n \"---\",\n \"\",\n \"## User\",\n \"\",\n safeUser,\n \"\",\n \"## Assistant\",\n \"\",\n safeAssistant,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Extract `agentId:` value from a session-summary YAML frontmatter.\n * Returns undefined when the file is malformed or has no agentId.\n *\n * The frontmatter shape is:\n * ---\n * runId: ...\n * agentId: ...\n * ...\n * ---\n *\n * Parsing is intentionally simple (regex line-match) — full YAML parse\n * is overkill for the 5-field frontmatter we emit. A malformed file\n * shows up as undefined → falls out of the optional agentId filter.\n */\nfunction extractAgentIdFromFrontmatter(content: string): string | undefined {\n // Match `agentId: <value>` within the leading frontmatter block.\n const match = content.match(/^agentId:\\s*(.+)$/m);\n if (match === null || match[1] === undefined) return undefined;\n return match[1].trim();\n}\n\n/**\n * Read previously-written session summaries from disk + substring-\n * match against the user message. Best-effort: errors degrade to\n * empty recall (no throw — matches the non-throwing-on-hot-path\n * contract).\n *\n * Iter 34: this is the SUBSTRING-match version. Future iters can\n * upgrade to embedding-based semantic similarity (LanceDB ANN)\n * without changing the public surface.\n *\n * Cap: returns at most 5 hits to bound the systemPromptAdditions size.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: session recall has branching on multiple storage modes\nasync function recallSessionSummaries(\n cwd: string,\n userMessage: string,\n agentIdFilter?: string,\n): Promise<ReadonlyArray<MemoryFact>> {\n const RECALL_CAP = 5;\n const sessionsDir = join(cwd, \".theokit\", \"memory\", \"sessions\");\n let files: string[];\n try {\n files = await readdir(sessionsDir);\n } catch {\n return [];\n }\n const query = userMessage.toLowerCase().trim();\n if (query.length === 0) return [];\n const hits: MemoryFact[] = [];\n for (const file of files) {\n if (!file.endsWith(\".md\")) continue;\n if (hits.length >= RECALL_CAP) break;\n const filePath = join(sessionsDir, file);\n let content: string;\n try {\n content = await readFile(filePath, \"utf-8\");\n } catch {\n continue;\n }\n // Iter 36: agentId scope filter. When set, skip summaries whose\n // frontmatter `agentId:` field doesn't match. Prevents cross-agent\n // data leakage in multi-agent setups.\n if (agentIdFilter !== undefined) {\n const fileAgentId = extractAgentIdFromFrontmatter(content);\n if (fileAgentId !== agentIdFilter) continue;\n }\n if (content.toLowerCase().includes(query)) {\n // Extract a short snippet — the User section (first 200 chars).\n const userIdx = content.indexOf(\"## User\");\n const snippet =\n userIdx >= 0 ? content.slice(userIdx, userIdx + 200).replace(/\\s+/g, \" \") : file;\n const id = `${ADAPTER_ID}:session:${file}` as MemoryId;\n hits.push({\n id,\n content: snippet,\n score: 0.5, // substring-match has no real score; placeholder\n });\n }\n }\n return hits;\n}\n\n/**\n * Build the LLM-facing `memory_search` tool (iter 35). The LLM calls\n * this when the user asks about something it might have learned in a\n * previous session. Queries the disk-backed sessions corpus via the\n * same `recallSessionSummaries` helper used by `runActivePass`.\n */\nfunction buildMemorySearchTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_search\",\n description:\n \"Search past session summaries for content related to a query. Use when the user asks about something they mentioned in a previous conversation. Returns up to 5 short snippets.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"What to search for (a topic, fact, or keyword).\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const query = typeof input.query === \"string\" ? input.query : \"\";\n if (query.length === 0) {\n return JSON.stringify({ ok: false, results: [], error: \"empty query\" });\n }\n const hits = await recallSessionSummaries(state.cwd, query);\n return JSON.stringify({\n ok: true,\n count: hits.length,\n results: hits.map((h) => ({ id: String(h.id), snippet: h.content })),\n });\n },\n };\n}\n\nfunction buildMemoryRememberTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_remember\",\n description:\n \"Persist a short fact about the user/conversation to memory so it can be recalled in future turns. Pass a single concise sentence as `content`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"The fact to remember (one sentence).\" },\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const content = typeof input.content === \"string\" ? input.content : \"\";\n if (content.length === 0) {\n return JSON.stringify({ ok: false, error: \"empty content\" });\n }\n // Iter 43: redact secrets from the LLM-supplied content BEFORE\n // storing in the Map. The LLM may quote a key from the user\n // verbatim (e.g., \"user said their key is sk-proj-...\"); without\n // this, that secret would persist + leak into systemPromptAdditions\n // on subsequent runActivePass calls. Mirrors the iter 42\n // recordSessionSummary redaction posture.\n const safeContent = Security.redact(content);\n try {\n admitNewFact(state);\n } catch (cause) {\n // Only the ceiling is a reply the model can act on; anything else is a defect and rises.\n if (!isCeilingRefusal(cause)) throw cause;\n return JSON.stringify({ ok: false, code: cause.code, error: cause.message });\n }\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeContent,\n createdAt: new Date().toISOString(),\n });\n return JSON.stringify({ ok: true, id });\n },\n };\n}\n\n/**\n * Build a fresh `MemoryProvider` whose facts live in-process. The\n * returned provider is independent — call `createInMemoryMarkdownProvider()`\n * per agent OR share across agents (each `init()` gets its own state).\n *\n * Iter 33: `recordSessionSummary()` writes session-summary markdown\n * files to disk under `${cwd}/.theokit/memory/sessions/`.\n * Iter 34: `runActivePass()` reads back those summaries + substring-\n * matches against the user message for genuine cross-session recall.\n *\n * Future LanceDB-backed impl will replace the substring match with\n * semantic-similarity ANN over embedding vectors.\n */\nexport function createInMemoryMarkdownProvider(\n options: InMemoryMarkdownProviderOptions = {},\n): MemoryProvider {\n const maxFacts = resolveMaxFacts(options.maxFacts);\n return {\n async init(opts: MemoryProviderInitOptions): Promise<MemoryProviderHandle> {\n const state: InMemoryHandleState = {\n facts: new Map(),\n maxFacts,\n counter: { next: 0 },\n cwd: opts.cwd,\n };\n const adapter = buildAdapter(state);\n return {\n adapter,\n [INTERNAL_STATE]: state,\n };\n },\n buildTools(handle: MemoryProviderHandle, _agent: SDKAgent): ReadonlyArray<CustomTool> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return [];\n return [buildMemoryRememberTool(state), buildMemorySearchTool(state)];\n },\n async runActivePass(\n handle: MemoryProviderHandle,\n args: ActiveMemoryPassArgs,\n ): Promise<ActiveMemoryPassResult> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return { facts: [] };\n // (1) In-process facts (from memory_remember tool calls this turn).\n const inProcessFacts = Array.from(state.facts.values());\n // (2) Persisted session-summary recall — iter 34. Read previously-\n // written summaries from disk + substring-match against the user\n // message. Best-effort: read errors degrade to empty recall.\n //\n // Iter 36: scope the disk recall to args.agentId so a session\n // summary written by agent-A never bleeds into agent-B's recall.\n // This is the multi-agent privacy invariant.\n const persistedHits = await recallSessionSummaries(state.cwd, args.userMessage, args.agentId);\n const allFacts = [...inProcessFacts, ...persistedHits];\n if (allFacts.length === 0) return { facts: [] };\n const systemPromptAdditions = [\n \"Known facts about the user/session (recall):\",\n ...allFacts.map((f) => `- ${f.content}`),\n ].join(\"\\n\");\n return { facts: allFacts, systemPromptAdditions };\n },\n sync(_handle: MemoryProviderHandle): void {\n // No-op for the in-memory impl — facts are written synchronously to\n // the Map at handler-call time; nothing to re-index post-run. Future\n // LanceDB-backed impl will fire IndexManager.sync() here.\n return;\n },\n async recordSessionSummary(args: RecordSessionSummaryArgs): Promise<void> {\n // Real filesystem write via `@theokit/sdk/persistence`'s\n // `replaceFileAtomic`. ADR-008 sub-path resolution guarantees the\n // same process-level write lock as sdk-core's legacy\n // `writeSessionSummary`. Future LanceDB-backed impl additionally\n // triggers IndexManager re-sync after the write.\n if (args.status !== \"finished\") return;\n const sessionsPath = join(args.cwd, \".theokit\", \"memory\", \"sessions\");\n const filePath = join(sessionsPath, `${sanitizeRunId(args.runId)}.md`);\n await mkdir(sessionsPath, { recursive: true });\n const body = renderSessionSummaryMarkdown(args);\n await replaceFileAtomic(filePath, body);\n },\n dispose(handle: MemoryProviderHandle): void {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return;\n state.facts.clear();\n },\n };\n}\n","import { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { notesDir, resolveMemoryRoot } from \"@theokit/sdk/internal/memory-store\";\n\n/**\n * Markdown-first memory storage — re-exported from `@theokit/sdk`, not reimplemented here.\n *\n * This file used to be a full copy (iter 56, Stage 3 source-move #13). The copy went stale: `#389`\n * moved the layout from bullets under `MEMORY.md ## Facts` to a file per memory, and the\n * Claude Code compatibility work added two more read roots — both landed in the SDK's copy and\n * neither in this one. Because `Memory.runDreamingSweep` routes through this package whenever it is\n * installed, **the copy that ran was not the copy anyone had updated**: installing\n * `@theokit/sdk-memory` made every memory the SDK had written unreadable, reported as\n * `factsBefore: 0` — a number that reads exactly like an empty store (#430).\n *\n * theokit#160 fixed the identical shape for the embedding runtime, in this same package pair, by\n * importing one implementation instead of syncing two. Same remedy here. Re-syncing the copy would\n * have fixed today's divergence and left tomorrow's free to happen.\n *\n * The re-exported signatures are supersets of what this package used to expose — the added\n * parameters are optional — so nothing that called them before has to change.\n *\n * @internal\n */\nexport {\n appendFact,\n appendFactToMarkdown,\n asMemoryRoot,\n ceilingReachedError,\n claudeProjectMemoryDir,\n collectMarkdownFiles,\n type DiscoveredFile,\n defaultIndexPath,\n indexBudgetWarning,\n lanceStoragePath,\n MEMORY_INDEX_MAX_BYTES,\n MEMORY_INDEX_MAX_LINES,\n type MemoryLocationConfig,\n type MemoryRoot,\n memoryIndexRoot,\n memoryMdPath,\n memoryReadRoots,\n notesDir,\n projectMemoryDir,\n readAllSqliteFacts,\n readFacts,\n readFactsFromMarkdown,\n resolveMaxFacts,\n resolveMemoryRoot,\n type SqliteFactRow,\n} from \"@theokit/sdk/internal/memory-store\";\n\n/** One note discovered under `notes/`: its file name without the `.md` suffix, and its absolute path. */\nexport interface NoteFile {\n slug: string;\n path: string;\n}\n\n/**\n * List the `.md` files directly under `notes/`. Returns `[]` when the directory does not exist, so\n * a workspace that has never written a note is not an error. Does not recurse into sub-directories.\n *\n * Stays here rather than moving to the shared store: notes are this package's concept, and only\n * this package reads them.\n */\nexport async function listNotes(cwd: string): Promise<NoteFile[]> {\n let entries: string[] = [];\n try {\n entries = await readdir(notesDir(resolveMemoryRoot(cwd)));\n } catch {\n return [];\n }\n return entries\n .filter((name) => name.endsWith(\".md\"))\n .map((name) => ({\n slug: name.replace(/\\.md$/, \"\"),\n path: join(notesDir(resolveMemoryRoot(cwd)), name),\n }));\n}\n","/**\n * Active Memory blocking recall (ADR D6 of memory-system-peer-project-parity).\n *\n * Runs BEFORE `agent.send()` assembles the system prompt. Issues a direct\n * call to `IndexManager.search` with the user message (and optional recent\n * turns per `queryMode`).\n *\n * Returns a `summary` string capped at `maxSummaryChars` (default 220 to\n * match peer-project's `DEFAULT_MAX_SUMMARY_CHARS`) which the system-prompt\n * pipeline prepends as a `<active-memory>` block (priority 5).\n *\n * Iter 75 (Stage 3 source-move #38, FINAL move): hybrid copy from\n * sdk-core's `internal/memory/active-memory.ts`. sdk-core retains its\n * copy as the v1.x runtime that `Memory` class delegates to;\n * sdk-memory ships the canonical copy that future Stage 4 port-based\n * composition will consume.\n *\n * **CLOSES the Stage 3 source-move stage in sdk-memory.** Every\n * memory-related concept under sdk-core's internal/memory/ is now\n * canonical in @theokit/sdk-memory (38 source files moved across\n * iter 44-75; 2 inlined adapters added: adapter-http-error iter 73\n * + adapter-catalog renamed iter 74).\n *\n * **Cross-package telemetry contract:** `OTelSpan` and `TelemetryHandle`\n * are now imported from `@theokit/sdk`, which exports them since #295.\n * This file previously inlined structural mirrors of both, with a note\n * that they MUST be replaced once sdk-core made them public — and by\n * the time anyone looked, the mirrors had drifted: they narrowed\n * `setAttributes` to reject the `undefined` values the canonical type\n * accepts, and declared `end()` without its `endTime` parameter. That\n * is how a structural mirror fails: quietly, with both sides compiling.\n *\n * The 2 constant strings (`memory.recall` span name +\n * `theokit_memory_recall_duration_ms` histogram name) are still inlined\n * below, because sdk-core's `span-names.ts` remains private. They are\n * values rather than types, so exporting them is a separate decision\n * with a real bundle cost — unlike these two, which erase at build time.\n *\n * @internal\n */\n\nimport type { OTelSpan, TelemetryHandle } from \"@theokit/sdk\";\n\nimport type { CircuitBreaker } from \"../circuit-breaker.js\";\nimport type { MemorySearchHit } from \"../index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"../index/memory-index.js\";\nimport { resolveMemoryRoot } from \"../store/markdown-store.js\";\nimport { persistActiveMemoryTranscript } from \"../store/transcript-store.js\";\nimport type { ActiveMemoryCache, TenantContext } from \"./active-memory-cache.js\";\n// T4.1 / D438 — `ActiveMemoryResult` and its helpers moved to `./active-memory-types.ts`\n// so `./active-memory-cache.ts` can reach them without cycling back here (cycle #10).\n// Re-exported below for back-compat with in-tree consumers.\nimport type {\n ActiveMemoryQueryMode,\n ActiveMemoryResult,\n ActiveMemoryStatus,\n} from \"./active-memory-types.js\";\n\nexport type { ActiveMemoryQueryMode, ActiveMemoryResult, ActiveMemoryStatus };\n\n// Iter 75 inlined constants — sdk-core's telemetry/span-names.ts is\n// not public. These two are the only ones this file uses.\nconst SPAN_MEMORY_RECALL = \"memory.recall\";\nconst HISTOGRAM_MEMORY_RECALL_DURATION_MS = \"theokit_memory_recall_duration_ms\";\n\n// #295 — the canonical types, not a copy of them.\n//\n// Iter 75 inlined structural mirrors here because sdk-core's telemetry/tracer.ts\n// was not public, with a note that they MUST be replaced once it was. They had\n// already drifted by the time anyone checked: the mirror narrowed `setAttributes`\n// to reject the `undefined` values the canonical type accepts, and declared\n// `end()` without the `endTime` parameter. Neither broke a build — a structural\n// mirror fails by being quietly wrong, not by being loudly missing.\n//\n// `@theokit/sdk` is already a peerDependency of this package, and both types are\n// erased at build time, so this costs nothing at runtime.\n\n/**\n * Tuning for one recall attempt. Recall is off unless `enabled` is exactly\n * `true`, so an options object that omits it disables recall rather than\n * enabling it with defaults.\n */\nexport interface ActiveMemoryOptions {\n /** Whether active recall is enabled. Default `false`. */\n enabled?: boolean;\n /** Query construction strategy. Default `\"recent\"`. */\n queryMode?: ActiveMemoryQueryMode;\n /** Hard timeout in ms. Default `15000`. */\n timeoutMs?: number;\n /** Max chars in the summary. Default `220`. */\n maxSummaryChars?: number;\n /** Number of recent user turns to include in `queryMode === \"recent\"`. Default `2`. */\n recentUserTurns?: number;\n}\n\n/**\n * Everything {@link runActiveMemory} needs for one attempt. Only `userText`,\n * `priorMessages`, `index` and `options` are required; the rest add breaker,\n * cache, transcript persistence and telemetry, each of which is inert when\n * omitted.\n *\n * `index` is accepted as `undefined` on purpose — an agent with memory\n * configured but no index open is a normal state, and it produces a `skipped`\n * result rather than an error.\n */\nexport interface RunActiveMemoryArgs {\n userText: string;\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>;\n index: MemoryIndex | undefined;\n options: ActiveMemoryOptions;\n /** Per-agent circuit breaker (Phase 8). */\n breaker?: CircuitBreaker;\n /** Per-agent result cache (Phase 8). */\n cache?: ActiveMemoryCache;\n /** Workspace root for transcript persistence. */\n cwd?: string;\n /** When true, write transcript JSON under .theokit/memory/transcripts/active-memory/. */\n persistTranscripts?: boolean;\n /** Stable key the breaker + cache key by (default `default`). */\n agentKey?: string;\n /** Run id for transcript file naming. */\n runId?: string;\n /**\n * T0.1 — optional telemetry handle. When provided AND telemetry is enabled,\n * `memory.recall` span is emitted with `{ userId, namespace, scope, queryMode,\n * hits, status }` attrs and `theokit_memory_recall_duration_ms` histogram is\n * recorded with the same dimension keys.\n */\n telemetry?: TelemetryHandle;\n /** User id surfaced as a memory.recall span attr for cross-tenant tracing. */\n userId?: string;\n /** Memory namespace (e.g. `default`, `<orgId>`) for span/histogram dimensions. */\n namespace?: string;\n /** Memory scope (`session` / `user` / `global`) for span/histogram dimensions. */\n scope?: string;\n}\n\nconst DEFAULTS: Required<Omit<ActiveMemoryOptions, \"enabled\">> = {\n queryMode: \"recent\",\n timeoutMs: 15000,\n maxSummaryChars: 220,\n recentUserTurns: 2,\n};\n\n/**\n * Run one blocking recall before the system prompt is assembled, and report what\n * happened. Never throws for a recall failure: a search that times out or\n * rejects comes back as a `timeout` or `error` status with no summary, and the\n * agent run continues without memory.\n *\n * The order of the short-circuits decides what a caller sees. Recall disabled or\n * no index gives `skipped` with no search. An open circuit breaker gives\n * `skipped` too. A cache hit returns the earlier result as-is, which means it\n * also returns that result's `status` and `durationMs` — a cached `no-recall`\n * looks exactly like a fresh one. An empty query gives `no-recall`.\n *\n * Only a real search reaches the breaker: `timeout` records a timeout, `ok` and\n * `no-recall` record a success, and `error` records neither, so a provider that\n * keeps throwing will not trip the breaker.\n *\n * `timeoutMs` bounds how long this waits, not how long the search runs — the\n * underlying `index.search` is left running when the timer wins. The search asks\n * the index for at most 5 hits regardless of options.\n *\n * Cache entries are keyed by tenant as well as by query text, so two callers\n * with the same question and different `userId` / `namespace` / `scope` never\n * share an entry.\n */\nexport async function runActiveMemory(args: RunActiveMemoryArgs): Promise<ActiveMemoryResult> {\n const started = Date.now();\n // T0.1 — `memory.recall` span emitted around the entire body so skipped /\n // cached / no-recall paths still surface in telemetry with the correct status.\n const span = startMemoryRecallSpan(args);\n try {\n if (args.options.enabled !== true || args.index === undefined) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n const cfg = { ...DEFAULTS, ...args.options };\n const breakerKey = args.agentKey ?? \"default\";\n if (args.breaker?.shouldSkip(breakerKey) === true) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n // #56 (GAP-B) — key the cache read by tenant identity so two callers with\n // the same query text but different identity never share a cache entry.\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n const cached = args.cache?.get(args.userText, cfg.queryMode, tenantCtx);\n if (cached !== undefined) return endRecallSpan(span, args, cached);\n\n const query = buildQuery(args.userText, args.priorMessages, cfg.queryMode, cfg.recentUserTurns);\n if (query.trim().length === 0) {\n const finalized = await finalize(args, cfg.queryMode, {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n });\n return endRecallSpan(span, args, finalized);\n }\n const result = await searchOnce(args, cfg, query, started);\n notifyBreaker(args.breaker, breakerKey, result.status);\n const finalized = await finalize(args, cfg.queryMode, result);\n return endRecallSpan(span, args, finalized);\n } catch (cause) {\n span.recordException(cause);\n span.setStatus({ code: 2, message: cause instanceof Error ? cause.message : String(cause) });\n span.end();\n throw cause;\n }\n}\n\nfunction startMemoryRecallSpan(args: RunActiveMemoryArgs): OTelSpan {\n const telemetry: TelemetryHandle | undefined = args.telemetry;\n if (telemetry === undefined) {\n // No-op span identical to the runtime no-op when telemetry is disabled.\n return {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n setStatus: () => {},\n recordException: () => {},\n end: () => {},\n spanContext: () => ({ traceId: \"0\".repeat(32), spanId: \"0\".repeat(16) }),\n isRecording: () => false,\n };\n }\n return telemetry.startSpan(SPAN_MEMORY_RECALL, {\n queryMode: args.options.queryMode ?? \"recent\",\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n}\n\nfunction endRecallSpan(\n span: OTelSpan,\n args: RunActiveMemoryArgs,\n result: ActiveMemoryResult,\n): ActiveMemoryResult {\n span.setAttributes({\n hits: result.hits.length,\n status: result.status,\n durationMs: result.durationMs,\n });\n span.end();\n args.telemetry?.recordHistogram(HISTOGRAM_MEMORY_RECALL_DURATION_MS, result.durationMs, {\n status: result.status,\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n return result;\n}\n\ninterface ResolvedConfig {\n queryMode: ActiveMemoryQueryMode;\n timeoutMs: number;\n maxSummaryChars: number;\n recentUserTurns: number;\n}\n\nasync function searchOnce(\n args: RunActiveMemoryArgs,\n cfg: ResolvedConfig,\n query: string,\n started: number,\n): Promise<ActiveMemoryResult> {\n if (args.index === undefined) {\n return { summary: undefined, durationMs: 0, status: \"skipped\", hits: [] };\n }\n try {\n const hits = await withTimeout(args.index.search(query, { maxResults: 5 }), cfg.timeoutMs);\n if (hits === \"timeout\") {\n return { summary: undefined, durationMs: Date.now() - started, status: \"timeout\", hits: [] };\n }\n if (hits.length === 0) {\n return {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n };\n }\n const summary = formatSummary(hits, cfg.maxSummaryChars);\n return { summary, durationMs: Date.now() - started, status: \"ok\", hits };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(`[theokit-sdk] active-memory recall failed: ${message}\\n`);\n return { summary: undefined, durationMs: Date.now() - started, status: \"error\", hits: [] };\n }\n}\n\nfunction notifyBreaker(\n breaker: CircuitBreaker | undefined,\n key: string,\n status: ActiveMemoryStatus,\n): void {\n if (breaker === undefined) return;\n if (status === \"timeout\") breaker.recordTimeout(key);\n else if (status === \"ok\" || status === \"no-recall\") breaker.recordSuccess(key);\n}\n\nasync function finalize(\n args: RunActiveMemoryArgs,\n queryMode: ActiveMemoryQueryMode,\n result: ActiveMemoryResult,\n): Promise<ActiveMemoryResult> {\n // #56 (GAP-B) — key the cache write by tenant identity (mirrors the get side).\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n args.cache?.set(args.userText, queryMode, result, tenantCtx);\n if (args.persistTranscripts === true && args.cwd !== undefined) {\n await persistActiveMemoryTranscript(resolveMemoryRoot(args.cwd), {\n runId: args.runId ?? `run-${Date.now()}`,\n startedAtMs: Date.now() - result.durationMs,\n userText: args.userText,\n queryMode,\n status: result.status,\n durationMs: result.durationMs,\n summary: result.summary,\n hits: result.hits.map((h) => ({\n path: h.path,\n startLine: h.startLine,\n endLine: h.endLine,\n score: h.score,\n snippet: h.snippet,\n })),\n });\n }\n return result;\n}\n\nfunction buildQuery(\n userText: string,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n queryMode: ActiveMemoryQueryMode,\n recentUserTurns: number,\n): string {\n if (queryMode === \"message\") return userText;\n if (queryMode === \"full\") {\n const allUserTurns = priorMessages.filter((m) => m.role === \"user\").map((m) => m.text);\n return [...allUserTurns, userText].join(\"\\n\");\n }\n // recent\n const recent = priorMessages\n .filter((m) => m.role === \"user\")\n .slice(-recentUserTurns)\n .map((m) => m.text);\n return [...recent, userText].join(\"\\n\");\n}\n\nfunction formatSummary(hits: ReadonlyArray<MemorySearchHit>, maxChars: number): string {\n const lines = hits.map((h) => `- ${h.citation}: ${h.snippet}`);\n let summary = lines.join(\"\\n\");\n if (summary.length > maxChars) summary = `${summary.slice(0, maxChars - 1)}…`;\n return summary;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n const winner = await Promise.race([promise, timeout]);\n return winner;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * Consecutive-timeout circuit breaker for Active Memory recall.\n *\n * Mirrors peer-project's `circuitBreakerMaxTimeouts` + `circuitBreakerCooldownMs`\n * config: after N consecutive timeouts the breaker trips and `shouldSkip`\n * returns `true` until `cooldownMs` has elapsed. A successful recall resets\n * the counter immediately.\n *\n * Per-key isolation so two agents in the same process don't share a counter.\n *\n * @internal\n */\n\nexport interface CircuitBreakerOptions {\n maxTimeouts?: number;\n cooldownMs?: number;\n /** Injectable clock for tests. */\n now?: () => number;\n}\n\ninterface KeyState {\n consecutiveTimeouts: number;\n cooldownUntilMs: number;\n}\n\nconst DEFAULT_MAX_TIMEOUTS = 3;\nconst DEFAULT_COOLDOWN_MS = 60_000;\n\n/**\n * Stops calling a recall path that keeps timing out.\n *\n * After `maxTimeouts` consecutive timeouts on a key (default 3) the breaker\n * opens and {@link CircuitBreaker.shouldSkip} reports `true` until `cooldownMs`\n * has elapsed (default 60s). The first `shouldSkip` after the cooldown closes\n * the breaker and resets the counter, so it re-opens only after another full run\n * of timeouts.\n *\n * It counts timeouts, not failures. An error recorded by neither\n * `recordTimeout` nor `recordSuccess` leaves the counter where it was, so a call\n * path that throws rather than hanging will never trip it.\n *\n * State is per key and held in this instance, which is what keeps two agents in\n * one process from sharing a counter. Construct one per agent and pass a stable\n * key.\n */\nexport class CircuitBreaker {\n private readonly states = new Map<string, KeyState>();\n\n constructor(private readonly opts: CircuitBreakerOptions = {}) {}\n\n /** @returns true when the breaker is open and the call should be skipped. */\n shouldSkip(key: string): boolean {\n const state = this.states.get(key);\n if (state === undefined) return false;\n if (state.cooldownUntilMs === 0) return false;\n if (this.now() < state.cooldownUntilMs) return true;\n // Cooldown elapsed — close the breaker.\n state.cooldownUntilMs = 0;\n state.consecutiveTimeouts = 0;\n return false;\n }\n\n recordSuccess(key: string): void {\n const state = this.states.get(key);\n if (state === undefined) return;\n state.consecutiveTimeouts = 0;\n state.cooldownUntilMs = 0;\n }\n\n recordTimeout(key: string): void {\n const state = this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n state.consecutiveTimeouts += 1;\n if (state.consecutiveTimeouts >= (this.opts.maxTimeouts ?? DEFAULT_MAX_TIMEOUTS)) {\n state.cooldownUntilMs = this.now() + (this.opts.cooldownMs ?? DEFAULT_COOLDOWN_MS);\n }\n this.states.set(key, state);\n }\n\n /** @internal — tests inspect counter state. */\n inspect(key: string): Readonly<KeyState> {\n return this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n }\n\n private now(): number {\n return this.opts.now?.() ?? Date.now();\n }\n}\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Azure OpenAI embedding adapter.\n *\n * Azure addresses the DEPLOYMENT in the path rather than the model in the body:\n * `https://{resource}.openai.azure.com/openai/deployments/{deployment}/embeddings?api-version=...`.\n * `{model}` in `embeddingsPath` is substituted by `createOpenAiCompatibleRuntime`, so `model` here\n * names the Azure deployment.\n *\n * `AZURE_OPENAI_ENDPOINT` supplies the resource URL (without the `/openai/...` suffix);\n * `AZURE_OPENAI_API_KEY` the credential.\n *\n * theokit#128 (catalog parity): sdk-core gained this adapter in T4.10 and the peer never mirrored\n * it, so a `sdk-memory` user asking for `azure-openai` was rejected by a provider the SDK's own\n * `Theokit.inspect.embeddingAdapters()` advertised.\n *\n * @internal\n */\n\nexport const DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\n/**\n * Azure OpenAI embeddings. Same models as the OpenAI adapter, addressed the\n * Azure way, and the one adapter whose configuration is not just \"set a key\".\n *\n * Two things differ from every other adapter here. `model` names your Azure\n * DEPLOYMENT, not an OpenAI model id — it is substituted into the path\n * (`/openai/deployments/{model}/embeddings`) rather than sent in the body. And\n * `AZURE_OPENAI_ENDPOINT` must be set to your resource URL, without the\n * `/openai/...` suffix; the built-in default is a placeholder that resolves\n * nowhere, so leaving it unset fails at the network rather than at\n * configuration.\n *\n * Authentication uses the `api-key` header, which is what an Azure resource key\n * expects; Entra ID bearer tokens are not supported by this adapter. Reads\n * `AZURE_OPENAI_API_KEY`. The API version is pinned to `2024-02-01`.\n *\n * The deployment name still has to appear in the dimension table\n * (`text-embedding-3-small`, `-3-large`, `ada-002`), so a deployment named\n * anything else is refused with `embedding_unknown_model` — pass `model` as the\n * matching id and point the base URL at the right deployment, or add the name to\n * the table.\n */\nexport const azureOpenAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"azure-openai\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"azure-openai\",\n autoSelectPriority: 25,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"azure-openai\",\n defaultBaseUrl: \"https://your-resource.openai.azure.com\",\n apiKeyEnv: \"AZURE_OPENAI_API_KEY\",\n baseUrlEnv: \"AZURE_OPENAI_ENDPOINT\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n embeddingsPath: \"/openai/deployments/{model}/embeddings?api-version=2024-02-01\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — Azure is NOT OpenAI on the wire, despite the name. It authenticates an API\n // key with the `api-key` header (`Authorization: Bearer` is for Entra ID tokens, not for\n // AZURE_OPENAI_API_KEY), and the deployment already rides in the path, so `model` has no\n // place in the body. Sending the OpenAI shape meant every request was rejected.\n dialect: {\n authHeaders: (apiKey: string) => ({ \"api-key\": apiKey }),\n body: (_model: string, inputs: ReadonlyArray<string>) => ({ input: inputs }),\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Cohere embedding adapter — `POST /v2/embed` at `https://api.cohere.com`. Despite living beside\n * the OpenAI-compatible adapters, this endpoint is NOT OpenAI-shaped in either direction; the\n * `dialect` below is what makes it work.\n *\n * Honors `COHERE_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_COHERE_EMBEDDING_MODEL = \"embed-english-v3.0\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"embed-english-v3.0\": 1024,\n \"embed-multilingual-v3.0\": 1024,\n \"embed-english-light-v3.0\": 384,\n \"embed-multilingual-light-v3.0\": 384,\n};\n\n/**\n * Cohere embeddings. Priority 30, so it is auto-selected ahead of OpenAI when\n * both keys are present.\n *\n * Cohere does not speak the OpenAI wire, and this adapter supplies a dialect for\n * it: the request names its payload `texts`, the response returns\n * `{embeddings: {float: [...]}}`, and `input_type` is sent as\n * `search_document`. That last choice matters — Cohere's v3 models embed\n * documents and queries into different spaces, and this runtime always embeds as\n * a document, including the query side of a search. Expect somewhat weaker\n * retrieval than a Cohere-native setup that embeds queries as `search_query`.\n *\n * Reads `COHERE_API_KEY`; no base-URL environment override is declared. The\n * light models are 384 dimensions and the others 1024.\n */\nexport const cohereMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"cohere\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"cohere\",\n autoSelectPriority: 30,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"cohere\",\n defaultBaseUrl: \"https://api.cohere.com\",\n apiKeyEnv: \"COHERE_API_KEY\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n embeddingsPath: \"/v2/embed\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — `/v2/embed` diverges in BOTH directions: it names the payload `texts`, requires\n // `input_type`, and answers `{embeddings:{float:[[...]]}}` rather than `{data:[{embedding}]}`.\n // `search_document` is the right default here because this runtime embeds material for\n // storage; a query-side embedder would use `search_query`.\n dialect: {\n body: (model: string, inputs: ReadonlyArray<string>) => ({\n model,\n texts: [...inputs],\n input_type: \"search_document\",\n embedding_types: [\"float\"],\n }),\n vectors: (json: unknown) =>\n (json as { embeddings?: { float?: number[][] } }).embeddings?.float,\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * DeepInfra embedding adapter — hosts open-source embedding models\n * (BGE, E5, Jina, etc.) at pay-per-token. OpenAI-compatible REST at\n * `POST /v1/openai/embeddings` (note the `/openai` segment; not the\n * canonical `/v1/embeddings`). The `embeddingsPath` override on\n * `OpenAiCompatibleConfig` REPLACES the default suffix (EC-2).\n *\n * Honors `DEEPINFRA_API_KEY` and `DEEPINFRA_API_BASE_URL`.\n *\n * Iter 74 (Stage 3 source-move #33): hybrid copy from sdk-core's\n * `internal/memory/adapters/deepinfra-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_DEEPINFRA_EMBEDDING_MODEL = \"BAAI/bge-large-en-v1.5\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"BAAI/bge-large-en-v1.5\": 1024,\n \"BAAI/bge-base-en-v1.5\": 768,\n \"BAAI/bge-small-en-v1.5\": 384,\n \"BAAI/bge-m3\": 1024,\n \"intfloat/e5-large-v2\": 1024,\n \"intfloat/e5-base-v2\": 768,\n \"intfloat/multilingual-e5-large\": 1024,\n \"sentence-transformers/all-MiniLM-L6-v2\": 384,\n \"thenlper/gte-large\": 1024,\n \"thenlper/gte-base\": 768,\n};\n\n/**\n * Open-weight embedding models (BGE, E5, GTE, MiniLM) hosted by DeepInfra.\n * Reach for it when you want a specific open model — particularly a multilingual\n * one — behind a hosted API rather than running it yourself.\n *\n * Its endpoint is `/v1/openai/embeddings`, not the canonical `/v1/embeddings`;\n * the wire format is otherwise OpenAI-shaped. Reads `DEEPINFRA_API_KEY` and\n * honours `DEEPINFRA_API_BASE_URL`. Priority 13.\n *\n * Dimensions vary sharply across the ten models it knows (384 to 1024), and\n * switching between them invalidates an existing vector index — the index drops\n * every vector and re-embeds on the next sync.\n */\nexport const deepinfraMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"deepinfra\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"deepinfra\",\n autoSelectPriority: 13,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"deepinfra\",\n defaultBaseUrl: \"https://api.deepinfra.com\",\n apiKeyEnv: \"DEEPINFRA_API_KEY\",\n baseUrlEnv: \"DEEPINFRA_API_BASE_URL\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n embeddingsPath: \"/v1/openai/embeddings\",\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Google Gemini embedding adapter — the OpenAI-compatible surface at\n * `https://generativelanguage.googleapis.com/v1/embeddings`.\n *\n * Gemini's NATIVE embedding endpoint has a different shape\n * (`POST /v1beta/models/{model}:embedContent`); this adapter deliberately targets the\n * OpenAI-compatible one so it composes with the shared runtime.\n *\n * Honors `GEMINI_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_GEMINI_EMBEDDING_MODEL = \"text-embedding-004\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-004\": 768,\n \"embedding-001\": 768,\n};\n\n/**\n * Google Gemini embeddings through Google's OpenAI-compatible surface at\n * `/v1beta/openai/embeddings`. Gemini's native embedding endpoint\n * (`/v1beta/models/{model}:embedContent`) has a different shape and is\n * deliberately not used, so this composes with the shared runtime like the rest.\n *\n * Both known models are 768 dimensions. Reads `GEMINI_API_KEY`; no base-URL\n * environment override is declared. Priority 30.\n */\nexport const geminiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"gemini\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"gemini\",\n autoSelectPriority: 30,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"gemini\",\n defaultBaseUrl: \"https://generativelanguage.googleapis.com\",\n apiKeyEnv: \"GEMINI_API_KEY\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n // theokit#159 — the compat surface is under `/v1beta/openai/`, not the default\n // `/v1/embeddings`; the previous path 404'd on every call.\n embeddingsPath: \"/v1beta/openai/embeddings\",\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Jina AI embedding adapter — OpenAI-compatible at `https://api.jina.ai/v1/embeddings`.\n *\n * Honors `JINA_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_JINA_EMBEDDING_MODEL = \"jina-embeddings-v3\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"jina-embeddings-v3\": 1024,\n \"jina-embeddings-v2-base-en\": 768,\n \"jina-embeddings-v2-small-en\": 512,\n};\n\n/**\n * Jina AI embeddings, over the standard OpenAI wire. Highest auto-select\n * priority in the catalog (35), so it wins over OpenAI when both keys are\n * present.\n *\n * Default `jina-embeddings-v3` at 1024 dimensions; the v2 models are 768 and\n * 512. Reads `JINA_API_KEY`. No base-URL environment override is declared —\n * point it elsewhere by passing `baseUrl` to `create`.\n */\nexport const jinaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"jina\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"jina\",\n autoSelectPriority: 35,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"jina\",\n defaultBaseUrl: \"https://api.jina.ai\",\n apiKeyEnv: \"JINA_API_KEY\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Mistral embedding adapter — OpenAI-compatible REST surface\n * (`POST /v1/embeddings` against `https://api.mistral.ai`). Default model\n * `mistral-embed` (1024 dims).\n *\n * Mirrors `reference/peer-project/extensions/mistral/memory-embedding-adapter.ts`.\n *\n * Iter 74 (Stage 3 source-move #32): hybrid copy from sdk-core's\n * `internal/memory/adapters/mistral-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_MISTRAL_EMBEDDING_MODEL = \"mistral-embed\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"mistral-embed\": 1024,\n};\n\n/**\n * Mistral embeddings, over the standard OpenAI wire. One model only,\n * `mistral-embed` at 1024 dimensions; any other id is refused with\n * `embedding_unknown_model`.\n *\n * Reads `MISTRAL_API_KEY` and honours `MISTRAL_API_BASE_URL`. Priority 18, just\n * below OpenAI.\n */\nexport const mistralMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"mistral\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"mistral\",\n autoSelectPriority: 18,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"mistral\",\n defaultBaseUrl: \"https://api.mistral.ai\",\n apiKeyEnv: \"MISTRAL_API_KEY\",\n baseUrlEnv: \"MISTRAL_API_BASE_URL\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","/**\n * Ollama embedding adapter (T3.1, ADR D183).\n *\n * Targets Ollama's OpenAI-compatible `/v1/embeddings` endpoint and reuses\n * the shared `createOpenAiCompatibleRuntime` factory. The differentiating\n * bits:\n *\n * - `authType: \"none\"` — Ollama local ignores `Authorization`. Sentinel\n * `\"ollama-local\"` is passed as apiKey to satisfy the factory contract\n * (mirrors peer-project `OLLAMA_DEFAULT_API_KEY = \"ollama-local\"`).\n * - `OLLAMA_HOST` overrides the default `http://localhost:11434`.\n * - `OLLAMA_API_KEY` (optional) overrides the sentinel for Ollama Cloud\n * or reverse-proxy auth setups.\n * - Default model: `nomic-embed-text` (768 dim, ~274MB). User can opt\n * into `all-minilm` (384 dim, ~45MB) or any other locally-installed\n * embedding model.\n *\n * EC-B MUST FIX (edge-case review 2026-05-21): empty text is rejected\n * upstream in the shared factory (`classifyEntry` short-circuits to a\n * zero vector). That behavior is acceptable here because the zero\n * vector is identical for any empty input — downstream similarity\n * calcs ignore zero-norm vectors via the existing `cosineSimilarity`\n * guard. No additional fail-fast needed.\n *\n * EC-A MUST FIX (edge-case review 2026-05-21): dimension is locked\n * by the `DIMENSION_BY_MODEL` table; an unknown model id throws\n * `ConfigurationError(code: \"embedding_unknown_model\")` per the\n * factory's EC-4 contract. Future model versions with different\n * dimensions are added to the table here without breaking changes.\n *\n * Iter 74 (Stage 3 source-move #36): hybrid copy from sdk-core's\n * `internal/memory/adapters/ollama-embedding.ts`. The only\n * `transport: \"local\"` adapter in the cluster — enables 100%-local\n * RAG with no remote API key.\n *\n * @internal\n */\n\nimport type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Model used when the caller names none: `nomic-embed-text`, 768 dimensions,\n * roughly 274MB to pull. `all-minilm` is the smaller alternative at 384\n * dimensions and roughly 45MB.\n */\nexport const DEFAULT_OLLAMA_EMBEDDING_MODEL = \"nomic-embed-text\";\n\n/** Sentinel forwarded as Bearer token; Ollama local ignores Authorization. */\nconst OLLAMA_LOCAL_SENTINEL_KEY = \"ollama-local\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n // Nomic — local default, recommended quality/size balance.\n \"nomic-embed-text\": 768,\n \"nomic-embed-text:latest\": 768,\n // Sentence-transformers MiniLM — smaller, faster, lower quality.\n \"all-minilm\": 384,\n \"all-minilm:latest\": 384,\n // BGE family.\n \"bge-large\": 1024,\n \"bge-large:latest\": 1024,\n \"bge-m3\": 1024,\n \"bge-m3:latest\": 1024,\n // mxbai-embed-large.\n \"mxbai-embed-large\": 1024,\n \"mxbai-embed-large:latest\": 1024,\n};\n\n/**\n * Embeddings from a local Ollama instance — the only adapter in the catalog with\n * `transport: \"local\"`, and the one to choose when the corpus must not leave the\n * machine or when there is no API key to spend.\n *\n * It needs an Ollama server reachable at `OLLAMA_HOST` (default\n * `http://localhost:11434`) with the chosen embedding model already pulled;\n * nothing here starts a server or downloads a model, so a missing model surfaces\n * as an HTTP error from Ollama rather than a configuration error.\n *\n * No credential is required: a sentinel key is sent and local Ollama ignores it.\n * Set `OLLAMA_API_KEY` for Ollama Cloud or an authenticating reverse proxy.\n *\n * Auto-select priority is 10, the lowest in the catalog, so a configured remote\n * provider wins over it. Request it explicitly to prefer local.\n */\nexport const ollamaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"ollama\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n transport: \"local\" as const,\n authProviderId: \"ollama\",\n // Lower than remote providers — chosen only when explicitly requested\n // OR when no remote provider key is configured (local-first developer).\n autoSelectPriority: 10,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) => {\n // Honor OLLAMA_API_KEY (Ollama Cloud / reverse-proxy auth), else use\n // sentinel that local Ollama silently ignores. This mirrors\n // `sentinelForNoAuth` in router.ts and peer-project's `resolveSyntheticAuth`.\n const apiKey = options.apiKey ?? process.env.OLLAMA_API_KEY ?? OLLAMA_LOCAL_SENTINEL_KEY;\n return createOpenAiCompatibleRuntime(\n {\n id: \"ollama\",\n defaultBaseUrl: \"http://localhost:11434\",\n apiKeyEnv: \"OLLAMA_API_KEY\",\n baseUrlEnv: \"OLLAMA_HOST\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n { ...options, apiKey },\n );\n },\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// **Iter 74 rollup-plugin-dts workaround:** importing\n// `MemoryEmbeddingProviderAdapter` from sibling `./embedding-adapter.js`\n// fails dts emit because no public type reaches it transitively yet\n// (same iter 48/53/55/66/67/69/72 class). Fix: drop the explicit\n// type annotation on the exported adapter; TS infers the structural\n// shape from the literal, and the catalog (iter 37 / this same iter)\n// pin assignability against the canonical interface via its own\n// `Record<string, MemoryEmbeddingProviderAdapter>` constraint.\n\n/**\n * OpenAI embedding adapter (ADR D3) — built on the shared OpenAI-compatible\n * factory. Native fetch only.\n *\n * Iter 74 (Stage 3 source-move #31): hybrid copy from sdk-core's\n * `internal/memory/adapters/openai-embedding.ts`. Composes iter 45's\n * `MemoryEmbeddingProviderAdapter` + iter 73's\n * `createOpenAiCompatibleRuntime`.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\n/**\n * OpenAI embeddings — `text-embedding-3-small` (1536), `text-embedding-3-large` (3072) and\n * `text-embedding-ada-002` (1536).\n *\n * It is NOT selected for you. The provider is whatever the caller names in\n * `embedding: { provider }`; omit that and no embedding runtime is built at all. Its\n * `autoSelectPriority` of `20` is metadata no code path reads today, and it is not the highest\n * value in the catalog either — `jina` is 35, `cohere` and `gemini` are 30, `azure-openai` is 25.\n * The 3072-wide `text-embedding-3-large` is reachable through `azure-openai` and, as\n * `openai/text-embedding-3-large`, through `openrouter` as well.\n *\n * Reads `OPENAI_API_KEY`; `OPENAI_API_BASE_URL` redirects it at a compatible\n * gateway. `create` rejects with an `AuthenticationError`\n * (`embedding_missing_api_key`) when no key is found, and with a\n * `ConfigurationError` (`embedding_unknown_model`) for a model outside\n * `text-embedding-3-small`, `text-embedding-3-large` and\n * `text-embedding-ada-002` — the dimension has to be known before any vector\n * table is created, so an unlisted model is refused rather than probed.\n */\nexport const openAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openai\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"openai\",\n autoSelectPriority: 20,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openai\",\n defaultBaseUrl: \"https://api.openai.com\",\n apiKeyEnv: \"OPENAI_API_KEY\",\n baseUrlEnv: \"OPENAI_API_BASE_URL\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * OpenRouter embedding adapter — routes through OpenRouter's\n * `POST /api/v1/embeddings` endpoint (OpenAI-compatible request/response\n * shape). The provider id strings follow OpenRouter's catalog\n * (e.g. `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Honors `OPENROUTER_API_KEY` and `OPENROUTER_API_BASE_URL`. Default base\n * URL is `https://openrouter.ai/api`.\n *\n * Iter 74 (Stage 3 source-move #35): hybrid copy from sdk-core's\n * `internal/memory/adapters/openrouter-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENROUTER_EMBEDDING_MODEL = \"openai/text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"openai/text-embedding-3-small\": 1536,\n \"openai/text-embedding-3-large\": 3072,\n \"openai/text-embedding-ada-002\": 1536,\n \"mistralai/mistral-embed\": 1024,\n};\n\n/**\n * Embeddings routed through OpenRouter, which lets one key reach several\n * upstream providers. Use it when you want to switch provider without changing\n * credentials; use the provider's own adapter when you want its full model\n * range, since only the four ids in this adapter's dimension table are\n * accepted.\n *\n * Model ids carry the upstream prefix, for example\n * `openai/text-embedding-3-small` or `mistralai/mistral-embed`. The endpoint is\n * `/v1/embeddings` under the base `https://openrouter.ai/api`. Reads\n * `OPENROUTER_API_KEY` and honours `OPENROUTER_API_BASE_URL`. Priority 15.\n */\nexport const openRouterMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openrouter\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"openrouter\",\n autoSelectPriority: 15,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openrouter\",\n defaultBaseUrl: \"https://openrouter.ai/api\",\n apiKeyEnv: \"OPENROUTER_API_KEY\",\n baseUrlEnv: \"OPENROUTER_API_BASE_URL\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Voyage AI embedding adapter — `POST /v1/embeddings` at\n * `https://api.voyageai.com` with the OpenAI-compatible `{ model, input }`\n * request shape. Free tier (200M tokens/month) covers most SDK use.\n *\n * Honors `VOYAGE_API_KEY` and `VOYAGE_API_BASE_URL`.\n *\n * Iter 74 (Stage 3 source-move #34): hybrid copy from sdk-core's\n * `internal/memory/adapters/voyage-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_VOYAGE_EMBEDDING_MODEL = \"voyage-3-lite\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"voyage-3-lite\": 512,\n \"voyage-3\": 1024,\n \"voyage-3-large\": 1024,\n \"voyage-code-3\": 1024,\n \"voyage-multilingual-2\": 1024,\n};\n\n/**\n * Voyage AI embeddings, over the standard OpenAI wire. Default model\n * `voyage-3-lite` at 512 dimensions — the narrowest in the catalog, which makes\n * the index smaller and the search cheaper at some cost in quality; `voyage-3`\n * and `voyage-3-large` are 1024, and `voyage-code-3` is the one to pick for\n * source code.\n *\n * Reads `VOYAGE_API_KEY` and honours `VOYAGE_API_BASE_URL`. Priority 14.\n */\nexport const voyageMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"voyage\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"voyage\",\n autoSelectPriority: 14,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"voyage\",\n defaultBaseUrl: \"https://api.voyageai.com\",\n apiKeyEnv: \"VOYAGE_API_KEY\",\n baseUrlEnv: \"VOYAGE_API_BASE_URL\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import { azureOpenAiMemoryEmbeddingProviderAdapter } from \"./embedding/azure-openai-embedding.js\";\nimport { cohereMemoryEmbeddingProviderAdapter } from \"./embedding/cohere-embedding.js\";\nimport { deepinfraMemoryEmbeddingProviderAdapter } from \"./embedding/deepinfra-embedding.js\";\nimport { geminiMemoryEmbeddingProviderAdapter } from \"./embedding/gemini-embedding.js\";\nimport { jinaMemoryEmbeddingProviderAdapter } from \"./embedding/jina-embedding.js\";\nimport { mistralMemoryEmbeddingProviderAdapter } from \"./embedding/mistral-embedding.js\";\nimport { ollamaMemoryEmbeddingProviderAdapter } from \"./embedding/ollama-embedding.js\";\nimport { openAiMemoryEmbeddingProviderAdapter } from \"./embedding/openai-embedding.js\";\nimport { openRouterMemoryEmbeddingProviderAdapter } from \"./embedding/openrouter-embedding.js\";\nimport { voyageMemoryEmbeddingProviderAdapter } from \"./embedding/voyage-embedding.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n// Catalog value type is inferred from the literal record; canonical\n// assignability is checked at consumer call sites that destructure into\n// the canonical `MemoryEmbeddingProviderAdapter` shape.\n\n/**\n * Memory embedding adapter catalog, indexed by provider id.\n *\n * Only adapters with full, tested implementations are exposed. The\n * `openrouter` provider proxies through OpenRouter to whichever embedding\n * model the caller selects via `model` (e.g.\n * `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Locked by ADR D11: `openai`, `mistral`, `openrouter`, `voyage`, `deepinfra`\n * ship in v1.0. ADR D183: `ollama` added — first `transport: \"local\"`\n * adapter, enables 100%-local RAG (no remote API key needed).\n * `lmstudio`, `google`, `bedrock` are deferred to v1.1.\n *\n * Iter 74 (Stage 3 source-move #37): hybrid copy from sdk-core's\n * `internal/memory/adapters/catalog.ts`. Filename renamed to\n * `adapter-catalog.ts` in sdk-memory to disambiguate from the broader\n * \"catalog\" notion at the package barrel level.\n *\n * **This catalog must serve every provider sdk-core ADVERTISES** (theokit#128). When the peer is\n * installed it REPLACES core's catalog in the routing path (`sdk/src/memory.ts`), while the public\n * `Theokit.inspect.embeddingAdapters()` keeps listing core's — so any id core has and this one\n * lacks is a provider the SDK promises and then rejects. That is what happened to `azure-openai`,\n * `cohere`, `jina` and `gemini` for the two months between core's T4.10 and the parity fix.\n * The invariant is enforced by `@theokit/sdk-peer-integration-tests` (`peer-parity.test.ts`).\n *\n * **CLOSES the embedding-adapter cluster in sdk-memory.** The provider adapters + the shared\n * OpenAI-compatible runtime + the inlined HTTP error mapper are canonical here:\n * - iter 45: embedding-adapter (types)\n * - iter 46: embedding-cache (LRU) — REMOVED by theokit#160: the shared runtime owns caching now\n * - iter 73: openai-compatible (shared factory) + adapter-http-error\n * (inlined mapper)\n * - iter 74: openai-embedding + mistral-embedding + deepinfra-embedding\n * + voyage-embedding + openrouter-embedding + ollama-embedding +\n * adapter-catalog (THIS)\n * - theokit#128: azure-openai + cohere + jina + gemini (parity with core's T4.10)\n *\n * @internal\n */\nexport const MEMORY_EMBEDDING_ADAPTERS = {\n openai: openAiMemoryEmbeddingProviderAdapter,\n mistral: mistralMemoryEmbeddingProviderAdapter,\n openrouter: openRouterMemoryEmbeddingProviderAdapter,\n voyage: voyageMemoryEmbeddingProviderAdapter,\n deepinfra: deepinfraMemoryEmbeddingProviderAdapter,\n ollama: ollamaMemoryEmbeddingProviderAdapter,\n // theokit#128 — mirrors sdk-core's T4.10 additions, which the peer had drifted behind.\n \"azure-openai\": azureOpenAiMemoryEmbeddingProviderAdapter,\n cohere: cohereMemoryEmbeddingProviderAdapter,\n jina: jinaMemoryEmbeddingProviderAdapter,\n gemini: geminiMemoryEmbeddingProviderAdapter,\n};\n","/**\n * Public memory types (used by runtime + storage + migration + future index).\n *\n * Leaf module — depends only on `node:path` + the public\n * `@theokit/sdk/path-safety` re-exports (`safePathJoin`,\n * `sanitizeIdentifier`) + `@theokit/sdk`'s `Security` for the\n * canonical `redactSecrets` 12-pattern list (ADR D68).\n *\n * Iter 52 (Stage 3 source-move #9): hybrid copy from sdk-core's\n * `internal/memory/types.ts`. sdk-core retains its copy for v1.x\n * back-compat; sdk-memory ships the canonical copy that future\n * `storage/*`, `migration`, and `tools` moves will target as siblings.\n *\n * **Sub-path-import contract:** sdk-core copy imports\n * `safePathJoin`/`sanitizeIdentifier` from `../security/path-guard.js`\n * (internal path); sdk-memory copy imports them from\n * `@theokit/sdk/path-safety` (public sub-path stable per this\n * iter — sanitizeIdentifier was promoted to the public surface to\n * unblock this move). Same runtime, same grammar.\n *\n * @internal\n */\nimport { resolve as resolvePath } from \"node:path\";\n\nimport { Security } from \"@theokit/sdk\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\n\n/**\n * Per-agent memory configuration. `enabled` gates the configuration-aware\n * accessors (`readFacts`, `appendFact`) — with it `false` they resolve without\n * touching disk, while the lower-level markdown functions ignore it.\n *\n * `namespace`, `scope` and `userId` are only consulted for the legacy JSON path\n * (see {@link legacyMemoryJsonPath}); the markdown store keeps one `MEMORY.md`\n * per workspace and does not partition by them. They are treated as\n * user-supplied and sanitised before they reach a path. `storePath` is treated\n * as trusted and resolved as given.\n */\nexport interface MemoryConfig {\n enabled: boolean;\n namespace?: string;\n userId?: string;\n scope?: \"agent\" | \"user\" | \"team\";\n storePath?: string;\n}\n\n/**\n * One remembered statement. `text` is what gets written, embedded and searched;\n * it passes through secret redaction on the way to disk, so what is stored may\n * differ from what was passed in.\n */\nexport interface MemoryFact {\n text: string;\n /**\n * Optional taxonomy bucket (M4-3). Backward-compatible — flat-store facts\n * omit it; the categorized store (`createCategorizedMemory`) always sets it.\n */\n category?: string;\n}\n\n/**\n * Canonical credential-redaction primitive (ADR D68).\n *\n * sdk-core's copy re-exports `redactSecrets` directly from\n * `../security/index.js` (internal path). sdk-core's PUBLIC surface\n * (`@theokit/sdk`) doesn't expose a bare `redactSecrets` symbol —\n * it ships `Security.redact()` instead (T2.1, by design — the\n * namespace also carries `Security.addPattern()`). sdk-memory's\n * canonical `redactSecrets` re-export wraps `Security.redact` 1-to-1\n * so consumers continue to see the same symbol name without sdk-memory\n * having to import sdk-core's internal subpath. Same 12-pattern\n * list, same two-bucket mask shape, same disable-via-env behavior.\n */\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n return Security.redact(text, opts);\n}\n\n/**\n * Resolve the legacy JSON memory path used pre-ADR-D8 (kept for migration\n * helpers + tests). Centralized here so `migration.ts` and the legacy-aware\n * `runtime/memory-store.ts` don't duplicate the path logic (jscpd cleanup).\n */\nexport function legacyMemoryJsonPath(cwd: string, config: MemoryConfig): string {\n // ADRs D79-D81: storePath is programmatic (trusted); namespace/scope/userId\n // are user-shaped and pass sanitizeIdentifier. EC-7 (edge-case review):\n // realistic userIds (UUIDs, hash IDs, \"default\") pass; \"user@example.com\"\n // and similar need to be normalized by the caller before passing.\n if (config.storePath !== undefined) {\n return resolvePath(cwd, config.storePath);\n }\n const namespace = sanitizeIdentifier(config.namespace ?? \"default\");\n const scope = sanitizeIdentifier(config.scope ?? \"agent\", { maxLen: 16 });\n const userId = sanitizeIdentifier(config.userId ?? \"default\");\n return safePathJoin(cwd, \".theokit\", \"memory\", namespace, `${scope}-${userId}.json`);\n}\n\n/**\n * A semantically meaningful slice of a markdown memory file, produced by\n * `chunkMarkdown`. Each chunk carries stable line numbers + a content hash\n * used downstream by the embedding cache.\n *\n * Mirrors peer-project's `MemoryChunk` shape\n * (`reference/peer-project/packages/memory-host-sdk/src/host/engine-storage.ts`).\n *\n * @internal\n */\nexport interface MemoryChunk {\n /** 1-indexed starting line in the source file. */\n startLine: number;\n /** 1-indexed ending line (inclusive). */\n endLine: number;\n /** Slice of markdown source text. */\n text: string;\n /** sha256 of `text`; stable across runs for identical inputs. */\n hash: string;\n /** Optional nearest heading text (without the `#` markers). */\n heading?: string;\n}\n\n/**\n * Result of `reader.readFile`. Contains the bounded slice plus truncation\n * + provenance info.\n *\n * Mirrors peer-project's `MemoryReadResult` shape.\n *\n * @internal\n */\nexport interface MemoryReadResult {\n path: string;\n /** Requested starting line (1-indexed, defaults to 1). */\n from: number;\n /** Number of lines actually returned (may be less than `lines` near EOF). */\n linesReturned: number;\n /** Total lines in the file (after the read). */\n totalLines: number;\n /** True when content remains after the returned slice, i.e. `remainingLines > 0`. */\n truncated: boolean;\n /** Lines past the returned slice that remain in the file. */\n remainingLines: number;\n /** Slice text (joined with `\\n`). */\n text: string;\n}\n\n/**\n * Lightweight reference to a markdown file in the memory corpus.\n *\n * Mirrors peer-project's `MemoryFileEntry`.\n *\n * @internal\n */\nexport interface MemoryFileEntry {\n /** Absolute path on disk. */\n path: string;\n /** Path relative to the memory root (e.g. \"MEMORY.md\", \"notes/foo.md\"). */\n relPath: string;\n /** ms-since-epoch mtime. */\n mtime: number;\n /** sha256 of the file content; recomputed on each read. */\n hash: string;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67) — sdk-memory inlined copy.\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * Iter 73 (Stage 3 source-move #30): inlined adaptation of sdk-core's\n * `internal/errors/mappers/openai-compatible.ts` + `shared.ts`. sdk-core's\n * mapper is internal — not part of the public errors surface — so sdk-memory\n * carries its own minimal copy here. Behavior MUST stay byte-equivalent\n * with sdk-core's so consumers consuming hits via either package surface\n * see identical error shape.\n *\n * The 4 helpers (`parseRetryAfter`, `truncateRaw`, `buildErrorMetadata`,\n * `mapOpenAICompatibleError`) are intentionally co-located in this single\n * file so all 8 embedding adapter moves (catalog + 7 providers) share one\n * import target.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n type ErrorMetadata,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"@theokit/sdk/errors\";\n\nimport { redactSecrets } from \"./memory-types.js\";\n\nconst RAW_MAX_BYTES = 2048;\nconst PROVIDER_DETAIL_MAX_CHARS = 512;\n// OpenRouter answers a model it does not serve with HTTP 404 and a numeric `error.code`,\n// so only the message tells it apart from a 404 for a wrong path.\nconst MISSING_MODEL_MESSAGE = /no endpoints found/i;\n\n/**\n * Parse `retry-after` header in numeric-seconds form. HTTP-date form\n * (RFC 7231) returns `undefined` to avoid NaN propagation downstream.\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n // Redact before the cut so a key straddling the limit cannot slip past the patterns.\n const redacted = redactSecrets(s);\n return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}…`;\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output).\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\n/**\n * Turn a failed OpenAI-shaped HTTP response into the typed error the SDK throws.\n * Builds the error, it does not throw it.\n *\n * The HTTP status picks the class: 401 and 403 give an `AuthenticationError`,\n * 429 a `RateLimitError`, 400 a `ConfigurationError`, 408 and 5xx a\n * `NetworkError`, and anything else an `UnknownAgentError`.\n *\n * The `code` on the metadata is finer than the class and is read from\n * `body.error.code` (or `.type`) first, so a 400 that names a context-window\n * problem carries `context_too_long` rather than `invalid_request`. A body code\n * naming an exhausted quota, and HTTP 402, both map to `quota_exceeded` — note\n * that a 402 keeps that code while still producing an `UnknownAgentError`,\n * because no status branch claims it.\n *\n * The raw body rides along on the metadata, truncated to about 2KB and passed\n * through secret redaction, so it is safe to log.\n */\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 404 && code === \"model_unavailable\") {\n // The model id lives only in the provider's text, so this case carries it.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, {\n code: `${providerId}_model_unavailable`,\n metadata,\n });\n }\n if (status === 400) {\n // A 400 is fixed by changing the request, and only the provider's text says what to change.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { message?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n return typeof err.message === \"string\" ? err.message : undefined;\n}\n\n// Redaction runs before the cut so a key cut short cannot slip past the credential patterns.\nfunction boundedProviderDetail(body: unknown): string | undefined {\n const raw = extractOpenAiErrorMessage(body);\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const redacted = redactSecrets(raw);\n return redacted.length <= PROVIDER_DETAIL_MAX_CHARS\n ? redacted\n : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}…`;\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — 402 / Insufficient credits / insufficient_quota body code flow\n // to canonical `quota_exceeded` (ADR-spec'd in ErrorCode union).\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? \"\")) {\n return \"model_unavailable\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(\n providerId: string,\n status: number,\n code: ErrorCode,\n detail?: string,\n): string {\n const base = `${providerId} API error: ${code} (HTTP ${status})`;\n return detail === undefined || detail === \"\" ? base : `${base}: ${detail}`;\n}\n","import { mkdir, readFile } from \"node:fs/promises\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\nimport { replaceFileAtomic, withCwdMutex } from \"@theokit/sdk/persistence\";\n\nimport { type MemoryFact, redactSecrets } from \"./memory-types.js\";\n\n/**\n * A fact stored under a typed category. Unlike the flat {@link MemoryFact}, the\n * `category` is always present in the categorized store's read shape.\n *\n * @public\n */\nexport interface CategorizedFact extends MemoryFact {\n category: string;\n}\n\n/**\n * Options for {@link createCategorizedMemory}.\n *\n * @public\n */\nexport interface CreateCategorizedMemoryOptions {\n /** Directory holding one markdown file per category (`<root>/<category>.md`). */\n root: string;\n /**\n * The closed category taxonomy. This list IS the schema: an `add`/`list`\n * with a category not in it is rejected. Must be non-empty, unique, each\n * sanitizable to a distinct filename.\n */\n categories: readonly string[];\n}\n\n/**\n * A typed, category-partitioned markdown memory store.\n *\n * @public\n */\nexport interface CategorizedMemory {\n /** The declared (frozen) category taxonomy. */\n readonly categories: readonly string[];\n /**\n * Append a fact under `category` (validated against the taxonomy). The text\n * is secret-redacted before persistence. Concurrent adds to the same category\n * are serialized (no lost update). Throws `ConfigurationError(unknown_category)`\n * for an undeclared category (before any I/O).\n */\n add(category: string, text: string): Promise<void>;\n /**\n * Read facts for one category (or every category when omitted). Never throws —\n * a missing/unreadable category file yields no facts.\n */\n list(category?: string): Promise<CategorizedFact[]>;\n}\n\nconst FACTS_HEADING = \"## Facts\";\n\n/**\n * Create a typed categorized memory store over the closed `categories`\n * taxonomy. Composes the shipped `safePathJoin`/`sanitizeIdentifier` path\n * guard, `redactSecrets`, and the atomic `replaceFileAtomic` + `withCwdMutex`\n * persistence primitives — zero new dependencies.\n *\n * @public\n */\nexport function createCategorizedMemory(\n options: CreateCategorizedMemoryOptions,\n): CategorizedMemory {\n const { root, categories } = options;\n validateCategories(categories);\n const allowed = new Set(categories);\n\n function assertKnown(category: string): void {\n if (!allowed.has(category)) {\n throw new ConfigurationError(\n `createCategorizedMemory: unknown category ${JSON.stringify(category)} (declared: ${categories.join(\", \")})`,\n { code: \"unknown_category\" },\n );\n }\n }\n\n function categoryPath(category: string): string {\n return safePathJoin(root, `${sanitizeIdentifier(category)}.md`);\n }\n\n async function add(category: string, text: string): Promise<void> {\n assertKnown(category);\n // Redact secrets, THEN encode newlines/backslashes so a multiline fact (or\n // one containing a `- ` / `## ` line) stays a single bullet and round-trips\n // faithfully — `list` decodes it back. Without this, the `## Facts` bullet\n // parse would split or truncate the fact (silent data loss).\n const encoded = encodeFact(redactSecrets(text));\n const sane = sanitizeIdentifier(category);\n await withCwdMutex(`catmem:${root}:${sane}`, async () => {\n const path = safePathJoin(root, `${sane}.md`);\n const raw = (await readFileOrEmpty(path)) || header(category);\n await mkdir(root, { recursive: true });\n await replaceFileAtomic(path, appendBullet(raw, encoded));\n });\n }\n\n async function list(category?: string): Promise<CategorizedFact[]> {\n if (category !== undefined) {\n assertKnown(category);\n return readCategory(categoryPath(category), category);\n }\n const out: CategorizedFact[] = [];\n for (const c of categories) {\n out.push(...(await readCategory(categoryPath(c), c)));\n }\n return out;\n }\n\n return { categories: [...categories], add, list };\n}\n\nfunction validateCategories(categories: readonly string[]): void {\n if (categories.length === 0) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be non-empty\", {\n code: \"invalid_categories\",\n });\n }\n if (new Set(categories).size !== categories.length) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be unique\", {\n code: \"invalid_categories\",\n });\n }\n const sanitized = categories.map((c) => trySanitize(c));\n if (new Set(sanitized).size !== categories.length) {\n throw new ConfigurationError(\n \"createCategorizedMemory: categories must map to distinct filenames after sanitization\",\n { code: \"invalid_categories\" },\n );\n }\n}\n\nfunction trySanitize(category: string): string {\n try {\n return sanitizeIdentifier(category);\n } catch (cause) {\n throw new ConfigurationError(\n `createCategorizedMemory: category ${JSON.stringify(category)} is not a valid identifier`,\n { code: \"invalid_categories\", cause },\n );\n }\n}\n\nfunction header(category: string): string {\n return `---\\ncategory: ${category}\\n---\\n\\n${FACTS_HEADING}\\n`;\n}\n\nasync function readFileOrEmpty(path: string): Promise<string> {\n try {\n return await readFile(path, \"utf8\");\n } catch {\n return \"\";\n }\n}\n\nasync function readCategory(path: string, category: string): Promise<CategorizedFact[]> {\n const raw = await readFileOrEmpty(path);\n return parseFactBullets(raw).map((text) => ({ text: decodeFact(text), category }));\n}\n\n/**\n * Encode a fact for single-bullet storage: escape `\\` first, then `\\r`/`\\n`, so\n * the text occupies exactly one `- ` line (no split, no `## ` heading injection).\n * Pure + reversible by {@link decodeFact}.\n */\nfunction encodeFact(text: string): string {\n return text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\r/g, \"\\\\r\").replace(/\\n/g, \"\\\\n\");\n}\n\n/**\n * Reverse {@link encodeFact}. A single left-to-right pass over each `\\<char>`\n * escape: `\\n`→newline, `\\r`→CR, and any other escaped char (notably `\\\\`)→the\n * literal char. Non-overlapping matching makes this exact for encoded input.\n */\nfunction decodeFact(text: string): string {\n return text.replace(/\\\\(.)/g, (_match, char: string) =>\n char === \"n\" ? \"\\n\" : char === \"r\" ? \"\\r\" : char,\n );\n}\n\n/** Parse `- text` bullets under the `## Facts` heading. Pure. */\nfunction parseFactBullets(raw: string): string[] {\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) return [];\n const tail = raw.slice(idx + FACTS_HEADING.length);\n const nextHeading = tail.search(/\\n#{1,2}\\s/);\n const block = nextHeading === -1 ? tail : tail.slice(0, nextHeading);\n return block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2).trim());\n}\n\n/** Append a `- text` bullet under the `## Facts` heading. Pure. */\nfunction appendBullet(raw: string, text: string): string {\n const bullet = `- ${text}`;\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) {\n const sep = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${sep}${FACTS_HEADING}\\n\\n${bullet}\\n`;\n }\n const after = idx + FACTS_HEADING.length;\n const nextHeading = raw.slice(after).search(/\\n#{1,2}\\s/);\n if (nextHeading === -1) {\n const trailing = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${trailing}${bullet}\\n`;\n }\n const insertAt = after + nextHeading;\n return `${raw.slice(0, insertAt)}\\n${bullet}${raw.slice(insertAt)}`;\n}\n","import { existsSync, mkdirSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\n\nimport type { EmbeddingRuntime } from \"../embedding/embedding-adapter.js\";\nimport { lanceStoragePath, type MemoryRoot, resolveMemoryRoot } from \"../store/markdown-store.js\";\n\n/**\n * LanceDB-backed memory index (ADR D43). Implements the same logical\n * interface as `IndexManager` but stores embeddings in Lance's columnar\n * vector-aware file format — scalable to 100k+ facts.\n *\n * Opt-in via `Memory.create({ index: { backend: \"lance\" } })`. SQLite\n * remains the default; this code path only activates when explicitly\n * requested AND `@lancedb/lancedb` is installed.\n *\n * EC-1 MUST FIX: filters use Lance's SQL string predicate API — bind\n * parameters are not supported; single-quote escape (`'` → `''`) is the\n * only injection-safe option. Backed by integration test (lancedb-backend-ship-v1-1).\n *\n * EC-8: embedding dimension is validated when opening an existing table.\n *\n * Iter 68 (Stage 3 source-move #25): hybrid copy from sdk-core's\n * `internal/memory/lance-index.ts`. sdk-core retains its copy for v1.x\n * Lance back-compat; sdk-memory ships the canonical copy that future\n * `lance-memory-adapter.ts` move will compose with as a sibling.\n * Dependency chain (all resolved):\n * - `@theokit/sdk/errors` for `ConfigurationError` (public)\n * - sibling `./embedding-adapter.js` for `EmbeddingRuntime` (moved iter 45)\n * - dynamic-required `@lancedb/lancedb` (optional peer — typed\n * ConfigurationError on missing module per EC of the\n * lancedb-backend-ship plan)\n *\n * @internal\n */\n\ninterface LanceModule {\n connect: (uri: string) => Promise<LanceConnection>;\n}\n\ninterface LanceConnection {\n openTable: (name: string) => Promise<LanceTable>;\n createTable: (name: string, data: ReadonlyArray<LanceFactRecord>) => Promise<LanceTable>;\n tableNames: () => Promise<string[]>;\n}\n\ninterface LanceTable {\n add: (rows: ReadonlyArray<LanceFactRecord>) => Promise<void>;\n search: (vector: ReadonlyArray<number>) => LanceQuery;\n delete: (predicate: string) => Promise<void>;\n countRows: () => Promise<number>;\n // EC-8: schema introspection for dimension check.\n schema: () => Promise<{\n fields: ReadonlyArray<{\n name: string;\n // Lance 0.30 returns Apache Arrow Field. FixedSizeList type has\n // `listSize`, not `fixedSize`. typeId=16 = FixedSizeList in Arrow.\n type: { listSize?: number; fixedSize?: number };\n }>;\n }>;\n}\n\ninterface LanceQuery {\n where: (filter: string | Record<string, unknown>) => LanceQuery;\n limit: (n: number) => LanceQuery;\n toArray: () => Promise<ReadonlyArray<LanceFactRecord & { _distance?: number }>>;\n}\n\n/**\n * One row of the Lance `facts` table, as it is stored. Field names are the\n * on-disk column names, which is why `user_id` is snake_case here while the\n * search result reports `userId`.\n *\n * `embedding` must be exactly as wide as the table was created with; the width\n * is fixed by the embedding runtime on the first open and checked on every\n * later one.\n */\nexport interface LanceFactRecord {\n id: string;\n text: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n embedding: ReadonlyArray<number>;\n namespace: string;\n scope: string;\n user_id: string;\n timestamp: number;\n}\n\n/**\n * Options for `LanceIndex.open`. The embedding runtime is required, not\n * optional: Lance here is vector-only, so there is no text-search fallback to\n * open without one.\n */\nexport interface OpenLanceOptions {\n cwd: string;\n /** The resolved memory root. Defaults to `<cwd>/.theokit/memory` (#463). */\n memoryRoot?: MemoryRoot;\n embedding: EmbeddingRuntime;\n /** Override storage location. Default: `<cwd>/.theokit/memory/lance/`. */\n storagePath?: string;\n}\n\n/**\n * Filters for `LanceIndex.search`. `namespace` is required and `scope` is\n * optional; both are applied as a SQL predicate inside Lance. `sources` is\n * applied in this process, after the rows come back, so it narrows the result\n * without narrowing what `limit` counted.\n */\nexport interface LanceSearchOptions {\n namespace: string;\n scope?: string;\n limit?: number;\n sources?: ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\">;\n}\n\n/**\n * One Lance search result. `score` is a similarity in `(0, 1]` derived from\n * Lance's distance as `1 / (1 + distance)`, so higher is better — the opposite\n * direction from the raw distance Lance returns.\n */\nexport interface LanceSearchHit {\n id: string;\n text: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n namespace: string;\n scope: string;\n userId: string;\n score: number;\n}\n\n/**\n * Lazily load `@lancedb/lancedb`. Throws typed error when absent.\n *\n * @internal\n */\nfunction requireLance(): LanceModule {\n try {\n const r = createRequire(import.meta.url);\n return r(\"@lancedb/lancedb\") as LanceModule;\n } catch (cause) {\n throw new ConfigurationError(\n \"Lance backend selected but `@lancedb/lancedb` is not installed. \" +\n 'Install with: `pnpm add @lancedb/lancedb`. SQLite remains available as the default (omit `backend: \"lance\"`).',\n { code: \"lance_backend_unavailable\", cause },\n );\n }\n}\n\n/**\n * Lance-backed memory index. Public API mirrors the SQLite one logically:\n * `addFacts`, `search`, `countFacts`, `removeFacts`, `close`.\n *\n * @internal\n */\nexport class LanceIndex {\n private constructor(\n private readonly table: LanceTable,\n private readonly embedding: EmbeddingRuntime,\n private readonly embeddingDim: number,\n ) {}\n\n static async open(opts: OpenLanceOptions): Promise<LanceIndex> {\n const lance = requireLance();\n const storagePath =\n opts.storagePath ?? lanceStoragePath(opts.memoryRoot ?? resolveMemoryRoot(opts.cwd));\n mkdirSync(storagePath, { recursive: true });\n const conn = await lance.connect(storagePath);\n const dim = opts.embedding.dimension;\n const tableName = \"facts\";\n const existing = await conn.tableNames();\n let table: LanceTable;\n if (existing.includes(tableName)) {\n table = await conn.openTable(tableName);\n // EC-8: validate embedding dimension matches what's in storage.\n // Lance 0.30 uses Apache Arrow FixedSizeList type — the size lives\n // in `type.listSize` (older API used `fixedSize`; we read both for\n // forward/backward safety).\n const schema = await table.schema();\n const embField = schema.fields.find((f) => f.name === \"embedding\");\n const existingDim = embField?.type?.listSize ?? embField?.type?.fixedSize;\n if (typeof existingDim === \"number\" && existingDim !== dim) {\n throw new ConfigurationError(\n `Embedding dimension mismatch in Lance index: storage has ${existingDim}-dim vectors, current provider yields ${dim}-dim. Re-embed with \\`migrateSqliteToLance\\` after switching providers, or use a different storagePath.`,\n { code: \"embedding_dimension_mismatch\" },\n );\n }\n } else {\n // Create with one bootstrap record. Lance requires an initial row to\n // infer schema; we delete the bootstrap immediately.\n const bootstrap: LanceFactRecord = {\n id: \"__bootstrap__\",\n text: \"\",\n source: \"memory\",\n embedding: new Array(dim).fill(0),\n namespace: \"__bootstrap__\",\n scope: \"__bootstrap__\",\n user_id: \"__bootstrap__\",\n timestamp: 0,\n };\n table = await conn.createTable(tableName, [bootstrap]);\n await table.delete(\"namespace = '__bootstrap__'\");\n }\n return new LanceIndex(table, opts.embedding, dim);\n }\n\n async addFacts(facts: ReadonlyArray<Omit<LanceFactRecord, \"embedding\">>): Promise<void> {\n if (facts.length === 0) return;\n const texts = facts.map((f) => f.text);\n const embeddings = await this.embedding.embed(texts);\n const rows: LanceFactRecord[] = facts.map((f, i) => ({\n ...f,\n embedding: embeddings[i] ?? new Array(this.embeddingDim).fill(0),\n }));\n await this.table.add(rows);\n }\n\n /**\n * Search facts by semantic similarity. EC-1: filters use Lance's\n * SQL string predicate with `'` → `''` escape — bind parameters are\n * not supported by Lance 0.30.\n */\n async search(query: string, opts: LanceSearchOptions): Promise<LanceSearchHit[]> {\n const [embedding] = await this.embedding.embed([query]);\n if (embedding === undefined) return [];\n // EC-1 (lancedb-backend-ship-v1-1 integration test caught this 2026-05-31):\n // Lance 0.30.0's `.where()` accepts SQL STRING only, NOT object filter —\n // contrary to D43's original assumption. We build the SQL string with\n // single-quote escaping (`'` → `''`) to neutralize injection. This is\n // the standard SQL string-literal escape; bind parameters are not\n // supported in Lance's predicate API. Backed by integration test\n // `injection attempt in namespace does not break filter` (test 7).\n const predicates: string[] = [`namespace = '${escapeSqlValue(opts.namespace)}'`];\n if (opts.scope !== undefined) {\n predicates.push(`scope = '${escapeSqlValue(opts.scope)}'`);\n }\n let q = this.table.search(embedding).where(predicates.join(\" AND \"));\n if (opts.limit !== undefined) q = q.limit(opts.limit);\n const results = await q.toArray();\n return results\n .filter((r) => opts.sources === undefined || opts.sources.includes(r.source))\n .map((r) => ({\n id: r.id,\n text: r.text,\n source: r.source,\n namespace: r.namespace,\n scope: r.scope,\n userId: r.user_id,\n // Lower _distance = better match; normalize to 0..1 (1=best).\n score: 1 / (1 + (r._distance ?? 1)),\n }));\n }\n\n async countFacts(namespace: string): Promise<number> {\n // Total count, regardless of namespace, used by migration validation.\n // For per-namespace count, callers can do a where() + countRows() if\n // Lance supports it; v1.2 ships with global count only.\n void namespace;\n return this.table.countRows();\n }\n\n async removeFacts(ids: ReadonlyArray<string>): Promise<void> {\n if (ids.length === 0) return;\n // Build a parameterized-style delete predicate. Lance's delete still\n // takes a string predicate, so we explicitly quote-escape each id —\n // ids in our system are content-hashed (alphanumeric), so the risk\n // is low, but we belt-and-suspenders.\n const escaped = ids.map((id) => `'${id.replace(/'/g, \"''\")}'`).join(\", \");\n await this.table.delete(`id IN (${escaped})`);\n }\n\n async close(): Promise<void> {\n // Lance auto-closes on GC; no explicit shutdown needed.\n }\n}\n\n/**\n * Escape a value for safe SQL string interpolation in Lance predicates.\n * Lance does not support bind parameters — string-quote escape is the\n * only injection-safe option. Standard SQL: replace single quotes with\n * doubled single quotes.\n *\n * @internal\n */\nfunction escapeSqlValue(value: string): string {\n // T5.2 — Harden SQL value escaping for Lance `.where()` predicates.\n // Pre-T5.2 this only escaped single quotes (`'` → `''`). T5.2 adds:\n // - NUL byte rejection (NUL truncates the string in some SQL engines)\n // - C0 control char rejection (prevents invisible payload injection)\n // - Backslash escaping (`\\` → `\\\\` — some engines interpret `\\'` as\n // a single-quote escape, bypassing the `''` defense)\n // Synced from sdk-core per ADR 0002 byte-equivalence (iter 115).\n // Reject NUL + C0/DEL control chars (T5.5 pattern adapted for SQL).\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code === 0x00 || (code >= 0x01 && code <= 0x1f) || code === 0x7f) {\n throw new ConfigurationError(\n `SQL filter value contains control character at position ${i} (0x${code.toString(16)}). ` +\n \"This may indicate an injection attempt.\",\n { code: \"sql_injection_blocked\" },\n );\n }\n }\n // Escape both single-quote and backslash.\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"''\");\n}\n\n/**\n * Test helper for {@link LanceIndex}: indicates whether the Lance module\n * is loadable in the current environment. Allows tests to gracefully skip\n * when the optional dep is absent.\n *\n * @internal\n */\nexport function isLanceAvailable(): boolean {\n try {\n const r = createRequire(import.meta.url);\n r(\"@lancedb/lancedb\");\n return true;\n } catch {\n return false;\n }\n}\n\nvoid existsSync; // imported but only used conditionally via mkdirSync\n","/**\n * `LanceMemoryAdapter` — wraps `LanceIndex` to expose the common\n * `MemoryIndex` interface (sync/search/status/close) so consumers of\n * `IndexManager.open({ backend: \"lance\" })` get a drop-in replacement\n * for the SQLite-backed `IndexManager`.\n *\n * Semantic deltas vs SQLite (documented so callers know what to expect):\n *\n * - `sync()` is a NO-OP. Lance is a pure vector store — there is no\n * markdown corpus to crawl. Returns zero counts. Consumers writing\n * facts use `LanceIndex.addFacts` directly (exposed via the index\n * object returned to advanced callers).\n * - `search()` performs vector-only retrieval. `MemorySearchHit.textScore`\n * is 0 on every hit (no FTS5 layer); `vectorScore === score`.\n * - `status()` always reports `backend: \"hybrid\"` — embedding is required\n * at open, so there is no text-only Lance index. Both counts are 0: the\n * Lance row count is only available asynchronously and `status()` is\n * synchronous, so callers needing a real count call\n * `unwrap().countFacts()`. Lance does not track file provenance per row,\n * so `filesIndexed` has nothing to report either way.\n *\n * Ships with the lancedb-backend-ship-v1-1 plan (close D12, supersede via\n * D43). v1.4.0 of `@theokit/sdk`.\n *\n * Iter 69 (Stage 3 source-move #26): hybrid copy from sdk-core's\n * `internal/memory/lance-memory-adapter.ts`. sdk-core retains its\n * copy for v1.x Lance back-compat; sdk-memory ships the canonical\n * copy that the future `index-manager-dispatch.ts` move will compose\n * with as a sibling. Dependency chain (all sibling, all moved):\n * - `IndexStatus`, `MemorySearchHit`, `SearchOptions` from\n * `./index-manager-contract.js` (moved iter 47)\n * - `LanceIndex` from `./lance-index.js` (moved iter 68)\n * - `MemoryIndex`, `parseSearchOptions`, `SyncResult` from\n * `./memory-index.js` (moved iter 50)\n *\n * @internal\n */\n\nimport type { IndexStatus, MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\nimport { type MemoryIndex, parseSearchOptions, type SyncResult } from \"./memory-index.js\";\n\n/**\n * **Iter 69 rollup-plugin-dts workaround** (mirrors iter 48/53/55/66/67 pattern).\n * Importing `LanceIndex` from sibling `./lance-index.js` fails dts\n * emit with `\"LanceIndex\" is not exported by \"src/internal/lance-index.ts\"`\n * because rollup-dts treeshakes the class when it has no public\n * type reaching it transitively — even though the barrel `export *`\n * makes it publicly callable. Same class as iter 66/67's MemoryDb.\n *\n * Fix: inline a structural mirror of the minimal LanceIndex surface\n * the adapter actually uses (search + close + identity for unwrap()\n * via `inner === actual LanceIndex`). The mirror is purely a TYPE —\n * the runtime continues to receive the real LanceIndex instance\n * unchanged. When a future move surfaces LanceIndex through a\n * different publicly-reachable path, this mirror MUST be deleted +\n * the canonical type import restored.\n *\n * @internal\n */\ninterface LanceIndex {\n addFacts(\n facts: ReadonlyArray<{\n id: string;\n text: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n namespace: string;\n scope: string;\n user_id: string;\n timestamp: number;\n }>,\n ): Promise<void>;\n search(\n query: string,\n opts: {\n namespace: string;\n scope?: string;\n limit?: number;\n sources?: ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\">;\n },\n ): Promise<\n ReadonlyArray<{\n id: string;\n text: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n namespace: string;\n scope: string;\n userId: string;\n score: number;\n }>\n >;\n countFacts(namespace: string): Promise<number>;\n removeFacts(ids: ReadonlyArray<string>): Promise<void>;\n close(): Promise<void>;\n}\n\n/**\n * Default namespace used when consumers call `search()` without specifying\n * one. The SQLite `IndexManager` does not surface namespace in its public\n * `search()` signature either — both backends therefore behave consistently\n * under the \"single-workspace, single-namespace\" assumption that v1.4 ships.\n *\n * v1.5 candidate: surface `namespace` in `SearchOptions` (additive — no\n * breaking change) so multi-tenant Lance consumers can scope queries.\n */\nconst DEFAULT_NAMESPACE = \"default\";\n\n/** Empty sync result — Lance has no corpus to walk. */\nconst EMPTY_SYNC_RESULT: SyncResult = Object.freeze({\n filesScanned: 0,\n filesUpdated: 0,\n chunksWritten: 0,\n chunksEmbedded: 0,\n});\n\n/**\n * Presents a `LanceIndex` as a {@link MemoryIndex}, so a consumer written\n * against the SQLite index runs unchanged on `backend: \"lance\"`.\n *\n * Choose it when the corpus is large enough that SQLite plus sqlite-vec is the\n * bottleneck and you are willing to feed the index yourself. Stay on the SQLite\n * default when you want the markdown corpus crawled for you, or text matching on\n * exact terms: this adapter's `sync()` does nothing and its `search()` is\n * vector-only, so a query that would have matched by keyword now has to match by\n * meaning.\n *\n * Requires `@lancedb/lancedb`, an optional peer dependency. It is loaded when\n * the index is opened, not here.\n *\n * Two behaviours are worth knowing before switching. Facts only enter the index\n * through `unwrap().addFacts(...)` — nothing else writes to it. And `search()`\n * always queries the `default` namespace, because `SearchOptions` has no\n * namespace field to pass through, so a multi-tenant caller must open one index\n * per tenant rather than relying on the filter.\n */\nexport class LanceMemoryAdapter implements MemoryIndex {\n constructor(private readonly inner: LanceIndex) {}\n\n /**\n * No-op for Lance — see file header. Returns zero counts so callers'\n * existing logging (`filesScanned: X`) does not break.\n */\n async sync(): Promise<SyncResult> {\n return EMPTY_SYNC_RESULT;\n }\n\n // jscpd:ignore-start — search signature + early-out is idiomatic\n // overlap with IndexManager.search; further factoring would hurt\n // readability (the bodies diverge sharply right after).\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n // jscpd:ignore-end\n const lanceHits = await this.inner.search(query, {\n namespace: DEFAULT_NAMESPACE,\n limit: maxResults * 2,\n ...(options.sources !== undefined ? { sources: options.sources } : {}),\n });\n return lanceHits\n .filter((h) => h.score >= minScore)\n .slice(0, maxResults)\n .map((h) => translateLanceHit(h));\n }\n\n status(): IndexStatus {\n // chunksIndexed via a synchronous best-effort — Lance API is async so\n // we surface zero here and document that consumers needing exact counts\n // should call `inner.countFacts()` directly.\n return {\n backend: \"hybrid\",\n filesIndexed: 0,\n chunksIndexed: 0,\n };\n }\n\n async close(): Promise<void> {\n await this.inner.close();\n }\n\n /**\n * Escape hatch for advanced callers (migration tool, benchmark script)\n * that need direct access to addFacts/countFacts/removeFacts.\n */\n unwrap(): LanceIndex {\n return this.inner;\n }\n}\n\n/**\n * Translate `LanceSearchHit` to `MemorySearchHit`. Field mapping:\n *\n * - `id` → `path` (Lance has no file-system provenance; use opaque id)\n * - `text` → `snippet` (truncated to 200 chars matching IndexManager convention)\n * - `score` → `score` AND `vectorScore` (Lance is vector-only)\n * - `source` → `source`\n * - synthetic `startLine: 0, endLine: 0` (Lance has no line info)\n * - synthetic `citation: id` (no path:line citation available)\n * - `textScore` set to 0 (Lance does NOT do FTS5)\n */\nfunction translateLanceHit(hit: {\n id: string;\n text: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n score: number;\n}): MemorySearchHit {\n return {\n path: hit.id,\n startLine: 0,\n endLine: 0,\n score: hit.score,\n textScore: 0,\n vectorScore: hit.score,\n snippet: hit.text.slice(0, 200),\n source: hit.source,\n citation: hit.id,\n };\n}\n","/**\n * Dispatch helpers for `IndexManager.open`. Extracted to keep\n * `index-manager.ts` under the G8 400-LoC budget (lancedb-backend-ship-v1-1).\n *\n * Iter 70 (Stage 3 source-move #27): hybrid copy from sdk-core's\n * `internal/memory/index-manager-dispatch.ts`. sdk-core retains\n * its copy for v1.x back-compat; sdk-memory ships the canonical\n * copy that the future `index-manager.ts` move will compose with\n * as a sibling. Dependency chain (all sibling, all moved):\n * - `@theokit/sdk/errors` for `ConfigurationError` (public)\n * - `./index-manager-contract.js` for `MemoryBackend` +\n * `OpenIndexOptions` (moved iter 47)\n * - `./lance-index.js` for `LanceIndex` (moved iter 68)\n * - `./lance-memory-adapter.js` for `LanceMemoryAdapter` (moved iter 69)\n * - `./memory-index.js` for `MemoryIndex` (moved iter 50)\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\n\nimport type { MemoryBackend, OpenIndexOptions } from \"./index-manager-contract.js\";\nimport { LanceIndex } from \"./lance-index.js\";\nimport { LanceMemoryAdapter } from \"./lance-memory-adapter.js\";\nimport type { MemoryIndex } from \"./memory-index.js\";\n\n/** Valid backend identifiers — runtime guard against TS-narrowing escapes (EC-1). */\nexport const VALID_BACKENDS: readonly MemoryBackend[] = [\"sqlite-vec\", \"lance\"];\n\n/**\n * EC-1: runtime guard for `opts.backend`. TS union is compile-time only;\n * consumers passing JS `as any` typos must hit a typed error, not silent\n * SQLite fallback.\n */\nexport function assertValidBackend(backend: string): asserts backend is MemoryBackend {\n if (!VALID_BACKENDS.includes(backend as MemoryBackend)) {\n throw new ConfigurationError(\n `Invalid memory backend \"${backend}\". Valid values: ${VALID_BACKENDS.join(\", \")}.`,\n { code: \"invalid_memory_backend\" },\n );\n }\n}\n\n/**\n * Lance-path open. Throws `lance_requires_embedding` when no embedding\n * runtime is provided (Lance is vector-only — no FTS fallback).\n * Surfaces `lance_backend_unavailable` from LanceIndex.open when peer\n * dep is absent.\n */\nexport async function openLanceIndex(opts: OpenIndexOptions): Promise<MemoryIndex> {\n if (opts.embedding === undefined) {\n throw new ConfigurationError(\n \"Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).\",\n { code: \"lance_requires_embedding\" },\n );\n }\n const lance = await LanceIndex.open({\n cwd: opts.cwd,\n embedding: opts.embedding,\n ...(opts.filePath !== undefined ? { storagePath: opts.filePath } : {}),\n });\n return new LanceMemoryAdapter(lance);\n}\n","import type { MemoryDb } from \"@theokit/sdk/internal/memory-store\";\n\n// `isSqliteVecLoaded` has no SDK counterpart yet, so it stays here; the loader is the SDK's.\nexport { loadSqliteVecExtension } from \"@theokit/sdk/internal/memory-store\";\n\n/** Check whether sqlite-vec is loaded by running a tiny version query. */\nexport function isSqliteVecLoaded(db: MemoryDb): boolean {\n try {\n const row = db.prepare(\"SELECT vec_version() as v\").get();\n return row !== undefined && row.v !== undefined;\n } catch {\n return false;\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile, stat } from \"node:fs/promises\";\n\nimport { sanitizeFts5Query } from \"@theokit/sdk/persistence\";\nimport type { EmbeddingRuntime } from \"../embedding/embedding-adapter.js\";\nimport { chunkMarkdown } from \"../store/chunk-markdown.js\";\nimport {\n collectMarkdownFiles,\n defaultIndexPath,\n type MemoryRoot,\n projectMemoryDir,\n resolveMemoryRoot,\n} from \"../store/markdown-store.js\";\nimport { type MemoryDb, openMemoryDb } from \"./index-db.js\";\nimport { assertValidBackend, openLanceIndex } from \"./index-manager-dispatch.js\";\nimport { type MemoryIndex, parseSearchOptions } from \"./memory-index.js\";\nimport { loadSqliteVecExtension } from \"./sqlite-vec-loader.js\";\nimport {\n createVectorIndex,\n dropVectorIndex,\n embedMissingChunks,\n identityMatches,\n readEmbeddingIdentity,\n vectorSearch,\n writeEmbeddingIdentity,\n} from \"./vec-index.js\";\n\n/**\n * Memory index manager (ADR D2). FTS5-only at Phase 3; vector index lands in\n * Phase 5.\n *\n * Lifecycle:\n * const idx = await IndexManager.open({ cwd });\n * await idx.sync();\n * const hits = await idx.search(\"query\");\n * idx.close();\n *\n * Iter 72 (Stage 3 source-move #29): hybrid copy from sdk-core's\n * `internal/memory/index-manager.ts`. sdk-core retains its copy for\n * v1.x back-compat; sdk-memory ships the canonical orchestrator\n * composing every prior Stage 3 move (sqlite-vec stack iter 47/49/50/53/55-57/62/65-67,\n * lance stack iter 68-70, storage iter 56). The biggest move of the\n * stage at 446 LOC — closes the index/ cluster.\n *\n * @internal\n */\n\n// T2.1 / ADR D433 — these types live in `index-manager-contract.ts`\n// (iter 47). The canonical sdk-core copy re-exports them here for\n// back-compat. In sdk-memory the public barrel already does\n// `export * from \"./internal/index-manager-contract.js\"` so a second\n// re-export from this file confuses rollup-dts and triggers\n// \"is not exported\" emit errors. Mirrors iter 50 memory-index NOTE.\n//\n// **Iter 72 rollup-plugin-dts workaround** (mirrors iter 48/53/55/66/67/69):\n// the canonical sdk-core copy imports `MemorySearchHit` (et al.) from\n// sibling. rollup-dts treeshakes the inner type declarations because\n// no PUBLIC type reaches them transitively yet within this file's\n// bundling pass. Fix: declare structural mirrors of the index-manager-contract\n// types inline so the index-manager.ts file's emit is self-contained.\n// When a future move surfaces these through a different\n// publicly-reachable path, these mirrors MUST be deleted + the\n// canonical type imports restored.\n\ninterface MemorySearchHit {\n readonly path: string;\n readonly startLine: number;\n readonly endLine: number;\n readonly score: number;\n readonly textScore: number;\n readonly vectorScore?: number;\n readonly snippet: string;\n readonly source: \"memory\" | \"sessions\" | \"wiki\";\n readonly citation: string;\n}\n\ninterface IndexStatus {\n backend: \"fts-only\" | \"hybrid\";\n filesIndexed: number;\n chunksIndexed: number;\n lastSyncMs?: number;\n}\n\ninterface SearchOptions {\n maxResults?: number;\n minScore?: number;\n vectorWeight?: number;\n textWeight?: number;\n sources?: ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\">;\n}\n\ninterface OpenIndexOptions {\n cwd: string;\n /**\n * The memory root to index and to place the database under. Defaults to `<cwd>/.theokit/memory`.\n *\n * Optional here and required below: this is the entry point a caller reaches with a workspace in\n * hand, while every path helper under it demands a resolved root (#463).\n */\n memoryRoot?: MemoryRoot;\n filePath?: string;\n embedding?: EmbeddingRuntime;\n backend?: \"sqlite-vec\" | \"lance\";\n}\n\n/**\n * The default memory index: SQLite for storage, FTS5 for text matching, and\n * sqlite-vec for vectors when an embedding runtime is supplied.\n *\n * Open it with the static `open`, which is also the dispatch point for\n * `backend: \"lance\"` — that overload returns a `LanceMemoryAdapter`, not an\n * `IndexManager`, so hold the result as {@link MemoryIndex} unless you need this\n * class specifically.\n *\n * Storage needs `better-sqlite3` unless the running Node exposes `node:sqlite`,\n * and vectors additionally need `sqlite-vec`. Both are optional peer\n * dependencies of this package. Without an embedding runtime the index opens\n * text-only and reports `backend: \"fts-only\"`; no vector table is created and\n * search degrades to BM25 rather than failing.\n *\n * `sync()` crawls the markdown corpus — `MEMORY.md`, `notes/`, `wiki/` and\n * `sessions/` — skipping files whose content hash has not moved, and re-chunking\n * the rest. Nothing is indexed until it runs.\n *\n * If the embedding provider, model or dimension differs from what the database\n * recorded, opening drops the whole vector table so the next `sync()` re-embeds\n * from scratch. Switching embedding models is therefore safe but not cheap.\n *\n * `search()` runs both halves and blends them per chunk, so a chunk found only\n * by vector still appears with a text score of 0 and the other way round.\n * `close()` releases the database handle; it is synchronous here, unlike the\n * Lance adapter's, so a caller holding the {@link MemoryIndex} type must await\n * it either way.\n */\nexport class IndexManager implements MemoryIndex {\n private lastSyncMs: number | undefined;\n private vectorReady = false;\n\n private constructor(\n private readonly memoryRoot: MemoryRoot,\n private readonly db: MemoryDb,\n private readonly embedding: EmbeddingRuntime | undefined,\n ) {}\n\n /**\n * Open a memory index. Dispatches to SQLite (default) or Lance (opt-in\n * via `backend: \"lance\"`). See `openLanceIndex` for Lance-specific\n * preconditions + typed errors.\n */\n static async open(opts: OpenIndexOptions & { backend: \"lance\" }): Promise<MemoryIndex>;\n static async open(\n opts: Omit<OpenIndexOptions, \"backend\"> | (OpenIndexOptions & { backend?: \"sqlite-vec\" }),\n ): Promise<IndexManager>;\n static async open(opts: OpenIndexOptions): Promise<MemoryIndex> {\n const backend = opts.backend ?? \"sqlite-vec\";\n assertValidBackend(backend);\n if (backend === \"lance\") return await openLanceIndex(opts);\n return await IndexManager.openSqliteInternal(opts);\n }\n\n /** Internal SQLite-path open. Renamed from previous public `open`. */\n private static async openSqliteInternal(opts: OpenIndexOptions): Promise<IndexManager> {\n const memoryRoot = opts.memoryRoot ?? resolveMemoryRoot(opts.cwd);\n // Corpus and database diverge on purpose — see `defaultIndexPath` for why (#463).\n const filePath = opts.filePath ?? defaultIndexPath(projectMemoryDir(opts.cwd));\n const db = await openMemoryDb({ filePath });\n const manager = new IndexManager(memoryRoot, db, opts.embedding);\n if (opts.embedding !== undefined) await manager.initVectorBackend(opts.embedding);\n return manager;\n }\n\n private async initVectorBackend(runtime: EmbeddingRuntime): Promise<void> {\n await loadSqliteVecExtension(this.db);\n const currentIdentity = {\n providerId: runtime.id,\n model: runtime.model,\n dimension: runtime.dimension,\n };\n const persisted = readEmbeddingIdentity(this.db);\n if (persisted !== undefined && !identityMatches(persisted, currentIdentity)) {\n // EC-1: dimension/model/provider changed — drop the vector index and\n // force a full re-embed on next sync.\n dropVectorIndex(this.db);\n }\n createVectorIndex(this.db, runtime.dimension);\n writeEmbeddingIdentity(this.db, currentIdentity);\n this.vectorReady = true;\n }\n\n /** Walk the memory corpus + (re)index changed files. */\n async sync(): Promise<{\n filesScanned: number;\n filesUpdated: number;\n chunksWritten: number;\n chunksEmbedded: number;\n }> {\n const files = await collectMarkdownFiles(this.memoryRoot);\n let filesUpdated = 0;\n let chunksWritten = 0;\n const existingByPath = this.loadFilesIndex();\n for (const entry of files) {\n const raw = await readFile(entry.absolutePath, \"utf8\");\n const hash = sha256(raw);\n const existing = existingByPath.get(entry.absolutePath);\n if (existing !== undefined && existing.hash === hash) continue;\n const stats = await stat(entry.absolutePath);\n const fileId = this.upsertFile(\n entry.absolutePath,\n entry.relPath,\n hash,\n stats.mtimeMs,\n entry.source,\n );\n this.deleteChunksForFile(fileId);\n const chunks = chunkMarkdown(raw);\n for (const chunk of chunks) {\n this.insertChunk(fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);\n }\n filesUpdated += 1;\n chunksWritten += chunks.length;\n }\n let chunksEmbedded = 0;\n if (this.vectorReady && this.embedding !== undefined) {\n chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });\n }\n this.lastSyncMs = Date.now();\n return { filesScanned: files.length, filesUpdated, chunksWritten, chunksEmbedded };\n }\n\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n const textHits = this.ftsSearch(query, maxResults * 2);\n const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);\n const combined = this.combineHybridScores(textHits, vectorHitsById, options);\n return combined\n .filter((h) => h.score >= minScore)\n .filter((h) => options.sources === undefined || options.sources.includes(h.source))\n .slice(0, maxResults);\n }\n\n status(): IndexStatus {\n const files = this.db.prepare(\"SELECT COUNT(*) as n FROM files\").get() ?? { n: 0 };\n const chunks = this.db.prepare(\"SELECT COUNT(*) as n FROM chunks\").get() ?? { n: 0 };\n const status: IndexStatus = {\n backend: this.vectorReady ? \"hybrid\" : \"fts-only\",\n filesIndexed: Number(files.n ?? 0),\n chunksIndexed: Number(chunks.n ?? 0),\n };\n if (this.lastSyncMs !== undefined) status.lastSyncMs = this.lastSyncMs;\n return status;\n }\n\n // ───── search internals ──────────────────────────────────────────────\n\n private ftsSearch(query: string, limit: number): Array<MemorySearchHit & { chunkId: number }> {\n // EC-3: short-circuit when sanitizer reduces input to empty string.\n // Calling `MATCH ''` would error inside FTS5 on some SQLite versions.\n const sanitized = sanitizeFts5Query(query);\n if (sanitized.length === 0) return [];\n const stmt = this.db.prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text, bm25(chunks_fts) as bm25_score\n FROM chunks_fts\n JOIN chunks ON chunks_fts.rowid = chunks.id\n JOIN files ON chunks.file_id = files.id\n WHERE chunks_fts MATCH ?\n ORDER BY bm25_score\n LIMIT ?`,\n );\n let rows: Array<Record<string, unknown>> = [];\n try {\n rows = stmt.all(sanitized, limit);\n } catch {\n return [];\n }\n return rows.map((row) => {\n const bm25 = Number(row.bm25_score ?? 0);\n const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n path,\n startLine,\n endLine,\n score: textScore,\n textScore,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n // sneak the chunk id through for the hybrid join below\n // (cast away later)\n chunkId: Number(row.id),\n } as MemorySearchHit & { chunkId: number };\n });\n }\n\n private async vectorSearchById(\n query: string,\n limit: number,\n ): Promise<Map<number, { vectorScore: number; snippet?: string }>> {\n if (!this.vectorReady || this.embedding === undefined) return new Map();\n const [queryVec] = await this.embedding.embed([query]);\n if (queryVec === undefined) return new Map();\n const rows = vectorSearch(this.db, queryVec, limit);\n // sqlite-vec distance: lower = closer. Normalize to 0..1 with higher = better.\n const out = new Map<number, { vectorScore: number }>();\n for (const row of rows) {\n const score = 1 / (1 + Math.max(0, row.distance));\n out.set(row.chunk_id, { vectorScore: score });\n }\n return out;\n }\n\n private combineHybridScores(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n options: SearchOptions,\n ): MemorySearchHit[] {\n const weights = resolveWeights(options);\n const merged = this.mergeHits(textHits, vectorHitsById);\n const combined = [...merged.values()].map((hit) =>\n blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights),\n );\n return combined.sort((a, b) => b.score - a.score);\n }\n\n private mergeHits(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n ): Map<number, MemorySearchHit & { chunkId: number }> {\n const merged = new Map<number, MemorySearchHit & { chunkId: number }>();\n for (const hit of textHits) merged.set(hit.chunkId, hit);\n const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));\n if (missingIds.length > 0) {\n for (const hit of this.fetchChunksByIds(missingIds)) {\n merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });\n }\n }\n return merged;\n }\n\n private fetchChunksByIds(\n ids: ReadonlyArray<number>,\n ): Array<MemorySearchHit & { chunkId: number }> {\n if (ids.length === 0) return [];\n const placeholders = ids.map(() => \"?\").join(\",\");\n const rows = this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text\n FROM chunks JOIN files ON chunks.file_id = files.id\n WHERE chunks.id IN (${placeholders})`,\n )\n .all(...ids);\n return rows.map((row) => {\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n chunkId: Number(row.id),\n path,\n startLine,\n endLine,\n score: 0,\n textScore: 0,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n };\n });\n }\n\n // ───── persistence helpers ─────────────────────────────────────────\n\n private loadFilesIndex(): Map<string, { id: number; hash: string }> {\n const rows = this.db.prepare(\"SELECT id, path, hash FROM files\").all() as Array<{\n id: number;\n path: string;\n hash: string;\n }>;\n return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));\n }\n\n private upsertFile(\n absPath: string,\n relPath: string,\n hash: string,\n mtimeMs: number,\n source: \"memory\" | \"wiki\" | \"sessions\" = \"memory\",\n ): number {\n const stmt = this.db.prepare(\n `INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source\n RETURNING id`,\n );\n const row = stmt.get(absPath, relPath, Math.floor(mtimeMs), hash, source) as { id: number };\n return row.id;\n }\n\n private deleteChunksForFile(fileId: number): void {\n this.db.prepare(\"DELETE FROM chunks WHERE file_id = ?\").run(fileId);\n }\n\n private insertChunk(\n fileId: number,\n startLine: number,\n endLine: number,\n text: string,\n hash: string,\n ): void {\n this.db\n .prepare(\n \"INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(fileId, startLine, endLine, text, hash);\n }\n\n close(): void {\n this.db.close();\n }\n}\n\n// ───── module-level helpers (hybrid scoring) ─────────────────────────────\n\ninterface HybridWeights {\n vectorWeight: number;\n textWeight: number;\n total: number;\n}\n\nfunction resolveWeights(options: SearchOptions): HybridWeights {\n const vectorWeight = options.vectorWeight ?? 0.6;\n const textWeight = options.textWeight ?? 0.4;\n const total = vectorWeight + textWeight || 1;\n return { vectorWeight, textWeight, total };\n}\n\nfunction blendScores(\n hit: MemorySearchHit & { chunkId: number },\n vectorScore: number,\n weights: HybridWeights,\n): MemorySearchHit {\n const score =\n (vectorScore * weights.vectorWeight + hit.textScore * weights.textWeight) / weights.total;\n return {\n path: hit.path,\n startLine: hit.startLine,\n endLine: hit.endLine,\n score,\n textScore: hit.textScore,\n snippet: hit.snippet,\n source: hit.source,\n citation: hit.citation,\n ...(vectorScore > 0 ? { vectorScore } : {}),\n };\n}\n\nfunction sha256(text: string): string {\n return createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\nfunction truncateSnippet(text: string): string {\n const max = 500;\n return text.length <= max ? text : `${text.slice(0, max)}…`;\n}\n\n// Replaced by `sanitizeFts5Query` from `@theokit/sdk/persistence`\n// (T5.2, ADR D64). The new sanitizer is the 6-step port of Hermes'\n// `_sanitize_fts5_query` and handles hyphens/dots/underscores correctly\n// without quoting every token.\n","import { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\nimport { redactSecrets } from \"../memory-types.js\";\nimport {\n lanceStoragePath,\n readAllSqliteFacts,\n resolveMemoryRoot,\n} from \"../store/markdown-store.js\";\nimport { LanceIndex } from \"./lance-index.js\";\n\n/**\n * Migrate Memory.index from SQLite to LanceDB (ADR D44).\n *\n * EC-3 MUST FIX: validation uses NFC unicode normalization on both sides.\n *\n * Iter 71 (Stage 3 source-move #28): hybrid copy from sdk-core's\n * `internal/memory/migrate-sqlite-to-lance.ts`. sdk-core retains its\n * copy for v1.x migration back-compat; sdk-memory ships the canonical\n * copy.\n *\n * Dependency chain (all resolved):\n * - `@theokit/sdk/errors` for `ConfigurationError` (public)\n * - sibling `./memory-types.js` for `redactSecrets` (moved iter 52)\n * - sibling `./index-db.js` for `defaultIndexPath` + `openMemoryDb` (moved iter 65)\n * - sibling `./lance-index.js` for `LanceIndex` + `lanceStoragePath` (moved iter 68)\n *\n * @internal\n */\n\nexport interface MigrateOptions {\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to migrate, when the agent that wrote it\n * set `memory.directory`. Defaults to `<cwd>/.theokit/memory` (#463).\n */\n directory?: string;\n dryRun?: boolean;\n batchSize?: number;\n /** Inject for tests; defaults to console.log. */\n logger?: (msg: string) => void;\n}\n\n/**\n * Outcome of {@link migrateSqliteToLance}.\n *\n * Read `committed` first: it is `false` for a dry run and for a failed\n * validation, and only `true` when the staging directory was promoted to\n * `lance/`. `validated` reports whether the counts matched and the sampled facts\n * compared equal; `sampleComparisons` holds up to ten of those comparisons so a\n * failure can be inspected rather than merely counted.\n *\n * The SQLite database is left in place either way — this migration copies, it\n * does not move.\n */\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n /** Set when validation succeeded (or dryRun); false on validation failure. */\n validated: boolean;\n /** Per-fact compare results (size = sample count, up to 10). */\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n /** Lance storage location (final, after migration). */\n lancePath: string;\n /** Was the migration committed (false for dry-run). */\n committed: boolean;\n}\n\n/**\n * Compare two strings via NFC normalization (EC-3 MUST FIX). Required\n * because SQLite/Lance native bindings can normalize unicode differently\n * (NFC vs NFD), producing false negatives on facts with accents/emojis.\n *\n * @internal\n */\nfunction nfcEqual(a: string, b: string): boolean {\n return a.normalize(\"NFC\") === b.normalize(\"NFC\");\n}\n\n/**\n * Run the migration. Writes Lance to `<cwd>/.theokit/memory/lance-new/`\n * first, validates round-trip, then renames to `lance/` on success.\n * SQLite db is preserved (CLI prompts user to delete).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: migration is a single transaction (read → write → validate → commit-or-rollback); splitting harms atomicity reasoning.\nexport async function migrateSqliteToLance(opts: MigrateOptions): Promise<MigrateResult> {\n const cwd = opts.cwd;\n // One resolution, reused by every path this migration touches (#463).\n const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });\n const finalPath = lanceStoragePath(memoryRoot);\n const newPath = join(memoryRoot, \"lance-new\");\n // T1.4 (ADR D68): wrap logger so any fact text containing secrets is\n // masked before reaching the destination (console or user-supplied sink).\n // Caller-supplied loggers cannot bypass — by design (D70).\n const rawLog = opts.logger ?? ((m: string) => console.log(m));\n const log = (m: string) => rawLog(redactSecrets(m));\n\n // EC: destination exists → typed error.\n if (existsSync(finalPath)) {\n throw new ConfigurationError(\n `Destination already exists: ${finalPath}. Remove it manually (\\`rm -rf ${finalPath}\\`) and re-run.`,\n { code: \"migration_destination_exists\" },\n );\n }\n if (existsSync(newPath)) {\n // Leftover from a previous failed/interrupted migration. Safe to delete.\n log(`Removing stale ${newPath} from a previous run...`);\n rmSync(newPath, { recursive: true, force: true });\n }\n\n log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);\n const sqliteFacts = await readAllSqliteFacts(memoryRoot);\n log(`SQLite has ${sqliteFacts.length} facts.`);\n if (sqliteFacts.length === 0) {\n return {\n countSqlite: 0,\n countLance: 0,\n validated: true,\n sampleComparisons: [],\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Reuse the embedding runtime configured in the workspace? For v1.2 we\n // require the caller to pass embedding explicitly via env. The migration\n // path is documented as: \"set OPENAI_API_KEY (or similar) before running.\"\n // Here we ship a placeholder embedder that uses a deterministic\n // content-hash — sufficient for migration validation; consumers should\n // re-embed on first real query after migration if needed.\n const placeholderEmbedding = {\n id: \"migration-placeholder\",\n model: \"deterministic-hash\",\n dimension: 8,\n embed: async (texts: ReadonlyArray<string>) => {\n // Simple deterministic hash → 8-dim vector (migration validation only).\n return texts.map((t) => {\n const arr = new Array(8).fill(0);\n for (let i = 0; i < t.length; i += 1) {\n arr[i % 8] += t.charCodeAt(i);\n }\n return arr.map((x) => x / 1000);\n });\n },\n stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 }),\n };\n\n mkdirSync(newPath, { recursive: true });\n log(`Writing Lance index to ${newPath} ...`);\n\n const lance = await LanceIndex.open({\n cwd,\n embedding: placeholderEmbedding,\n storagePath: newPath,\n });\n\n const batchSize = opts.batchSize ?? 100;\n for (let i = 0; i < sqliteFacts.length; i += batchSize) {\n const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({\n id: f.id,\n text: f.text,\n source: f.source,\n namespace: f.namespace ?? \"default\",\n scope: f.scope ?? \"agent\",\n user_id: f.user_id ?? \"default\",\n timestamp: 0,\n }));\n await lance.addFacts(batch);\n log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);\n }\n\n // Validation: count + sample compare (10 random) with NFC normalization.\n const lanceCount = await lance.countFacts(\"default\");\n log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);\n\n const sampleSize = Math.min(10, sqliteFacts.length);\n const sampleComparisons: { id: string; match: boolean }[] = [];\n for (let i = 0; i < sampleSize; i += 1) {\n const sqliteFact = sqliteFacts[Math.floor((i * sqliteFacts.length) / sampleSize)];\n if (sqliteFact === undefined) continue;\n // Search Lance for this fact's text — best-effort round-trip.\n const hits = await lance.search(sqliteFact.text, {\n namespace: sqliteFact.namespace ?? \"default\",\n limit: 1,\n });\n // EC-3: compare with NFC normalization.\n const hit = hits[0];\n const match = hit !== undefined && nfcEqual(hit.text, sqliteFact.text);\n sampleComparisons.push({ id: sqliteFact.id, match });\n }\n\n const allMatch = sampleComparisons.every((c) => c.match);\n const countMatch = lanceCount === sqliteFacts.length;\n const validated = allMatch && countMatch;\n\n await lance.close();\n\n if (opts.dryRun === true) {\n log(\"Dry-run mode — discarding Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n if (!validated) {\n log(\"Validation FAILED — leaving SQLite intact, removing Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: false,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Atomic commit via rename.\n renameSync(newPath, finalPath);\n log(`Migration committed to ${finalPath}.`);\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: true,\n sampleComparisons,\n lancePath: finalPath,\n committed: true,\n };\n}\n","import { access, readFile, unlink } from \"node:fs/promises\";\nimport { legacyMemoryJsonPath, type MemoryConfig, type MemoryFact } from \"../memory-types.js\";\nimport { appendFactToMarkdown, memoryMdPath, resolveMemoryRoot } from \"../store/markdown-store.js\";\n\n/**\n * One-shot legacy-JSON → markdown migration (ADR D8 of memory-system-peer-project-parity).\n *\n * Triggers when `.theokit/memory/<namespace>/<scope>-<userId>.json` exists AND\n * `.theokit/memory/MEMORY.md` does not. Reads the JSON facts, writes each\n * bullet to MEMORY.md, then deletes the JSON file. Idempotent.\n *\n * Iter 63 (Stage 3 source-move #20): hybrid copy from sdk-core's\n * `internal/memory/migration.ts`. sdk-core retains its copy for v1.x\n * legacy migration back-compat; sdk-memory ships the canonical copy.\n *\n * **Process-global migration flag map (`migrationRun`) is per-package.**\n * sdk-core's copy and sdk-memory's copy each maintain their own\n * `Set<string>` so the same key migrated through one package's copy\n * is NOT recorded in the other's. In v1.x active-memory-mode this\n * runs only via sdk-core; once sdk-core's runtime swaps to consume\n * sdk-memory's exports (later Stage 4), only sdk-memory's flag map\n * matters. Stage 3 source-move alone doesn't switch consumers.\n *\n * Dependency chain (sibling, all moved):\n * - `appendFactToMarkdown`, `memoryMdPath` → ./markdown-store.js (iter 56)\n * - `legacyMemoryJsonPath`, `MemoryConfig`, `MemoryFact` → ./memory-types.js (iter 52)\n *\n * @internal\n */\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readLegacyFacts(jsonPath: string): Promise<MemoryFact[] | undefined> {\n try {\n const raw = await readFile(jsonPath, \"utf8\");\n const parsed = JSON.parse(raw) as { facts?: MemoryFact[] };\n return Array.isArray(parsed.facts) ? parsed.facts : [];\n } catch {\n return undefined;\n }\n}\n\nasync function writeMigratedFacts(\n cwd: string,\n jsonPath: string,\n facts: MemoryFact[],\n): Promise<MigrationResult> {\n try {\n for (const fact of facts) await appendFactToMarkdown(cwd, fact);\n await unlink(jsonPath).catch(() => undefined);\n process.stderr.write(\n `[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md\\n`,\n );\n return { migrated: true, factCount: facts.length };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(`[theokit-sdk] memory migration failed (readonly fs?): ${message}\\n`);\n return { migrated: false, factCount: 0, reason: \"readonly-fs\" };\n }\n}\n\nconst migrationRun = new Set<string>();\n\n/**\n * Outcome of {@link migrateLegacyJson}. `reason` is present on every non-migrated\n * result and says which guard stopped it: `already-migrated` (this key was\n * attempted earlier in this process), `no-legacy-json` (nothing to migrate, or\n * the file could not be read or parsed), `markdown-exists` (both files present,\n * so neither was touched), `readonly-fs` (the write failed).\n */\nexport interface MigrationResult {\n migrated: boolean;\n factCount: number;\n reason?: \"already-migrated\" | \"no-legacy-json\" | \"markdown-exists\" | \"readonly-fs\";\n}\n\n/**\n * Move facts from the pre-markdown JSON store into `MEMORY.md`, once.\n *\n * It runs only when the legacy file exists and `MEMORY.md` does not. When both\n * exist it stops and leaves both alone — merging would need a conflict rule\n * nobody has picked, and losing hand-written notes is worse than skipping. On\n * success each fact is appended as a `## Facts` bullet and the JSON file is\n * deleted.\n *\n * Guarded by a per-process set keyed on cwd, namespace, scope and user id, so\n * the second call for the same key returns `already-migrated` without touching\n * disk — including after a genuine failure. That set is per module instance, so\n * a process that loads both this package's copy and the one inside\n * `@theokit/sdk` has two independent sets.\n *\n * Never throws: a JSON file that cannot be read or parsed reports\n * `no-legacy-json`, and a failed write reports `readonly-fs` after a warning on\n * stderr.\n */\nexport async function migrateLegacyJson(\n cwd: string,\n config: MemoryConfig,\n): Promise<MigrationResult> {\n const key = `${cwd}::${config.namespace ?? \"default\"}::${config.scope ?? \"agent\"}::${config.userId ?? \"default\"}`;\n if (migrationRun.has(key)) return { migrated: false, factCount: 0, reason: \"already-migrated\" };\n migrationRun.add(key);\n\n const jsonPath = legacyMemoryJsonPath(cwd, config);\n if (!(await fileExists(jsonPath))) {\n return { migrated: false, factCount: 0, reason: \"no-legacy-json\" };\n }\n if (await fileExists(memoryMdPath(resolveMemoryRoot(cwd)))) {\n process.stderr.write(\n `[theokit-sdk] memory migration skipped: both MEMORY.md and legacy JSON exist at ${jsonPath}; leaving both intact\\n`,\n );\n return { migrated: false, factCount: 0, reason: \"markdown-exists\" };\n }\n\n const facts = await readLegacyFacts(jsonPath);\n if (facts === undefined) return { migrated: false, factCount: 0, reason: \"no-legacy-json\" };\n return writeMigratedFacts(cwd, jsonPath, facts);\n}\n\n/** Test-only — reset the in-process migration flag map. */\nexport function resetMigrationStateForTests(): void {\n migrationRun.clear();\n}\n","import { resolve as resolvePath } from \"node:path\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\n\nimport type { MemorySearchHit } from \"./index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"./index/memory-index.js\";\nimport type { MemoryRoot } from \"./store/markdown-store.js\";\nimport { readMemoryFileBounded } from \"./store/reader.js\";\n\n/**\n * Memory tools (`memory_search` + `memory_get`) — ADR D5 of\n * memory-system-peer-project-parity. Tool schemas mirror peer-project\n * (`reference/peer-project/extensions/memory-core/src/tools.ts:228-475`).\n *\n * Each tool is exposed as a `MemoryTool` (name + description + JSON schema +\n * async execute). The agent-loop integration wires them via the existing\n * `ResolvedTool` interface in `tool-dispatch.ts`.\n *\n * Iter 64 (Stage 3 source-move #21): hybrid copy from sdk-core's\n * `internal/memory/tools.ts`. sdk-core retains its copy for v1.x\n * memory-tools back-compat; sdk-memory ships the canonical copy.\n * Dependency chain (all resolved):\n * - `@theokit/sdk/errors` for `ConfigurationError` (public)\n * - sibling `./index-manager-contract.js` for `MemorySearchHit`\n * (moved iter 47 — note: sdk-core copy imports from\n * `./index-manager.js`; sdk-memory uses the contract leaf\n * directly since the canonical type lives there)\n * - sibling `./memory-index.js` for `MemoryIndex` (moved iter 50)\n * - sibling `./markdown-store.js` for `memoryDir` (moved iter 56)\n * - sibling `./reader.js` for `readMemoryFileBounded` (moved iter 55)\n *\n * @internal\n */\n\nexport interface MemoryToolJson {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\n/**\n * A memory tool ready to hand to the agent loop: the JSON-serialisable\n * description an LLM sees, plus the `execute` that runs it. `execute` resolves\n * to a JSON string — the tool layer does no further encoding.\n */\nexport interface MemoryTool extends MemoryToolJson {\n execute(input: Record<string, unknown>): Promise<string>;\n}\n\nconst SEARCH_DESCRIPTION =\n \"Mandatory recall step: semantically search MEMORY.md + memory/notes/*.md (and optional wiki supplements) before answering questions about prior work, decisions, dates, people, preferences, or todos. `corpus=memory` (default) restricts to indexed memory files; `corpus=wiki` restricts to read-only wiki supplements; `corpus=all` returns both. Returns ranked `{ path, startLine, endLine, score, snippet, citation }` hits.\";\n\nconst GET_DESCRIPTION =\n \"Safe exact excerpt read from MEMORY.md or memory/notes/*.md. Defaults to a bounded excerpt (200 lines). Returns `{ path, from, linesReturned, totalLines, truncated, remainingLines, text }`. Paths are resolved against the memory root — attempts to read outside `.theokit/memory/` are rejected.\";\n\nconst MEMORY_SEARCH_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"query\"],\n properties: {\n query: { type: \"string\", description: \"Natural-language query.\" },\n maxResults: { type: \"integer\", minimum: 1, maximum: 50 },\n minScore: { type: \"number\", minimum: 0, maximum: 1 },\n corpus: { type: \"string\", enum: [\"memory\", \"sessions\", \"wiki\", \"all\"] },\n },\n additionalProperties: false,\n};\n\nconst MEMORY_GET_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"path\"],\n properties: {\n path: { type: \"string\", description: \"Path relative to .theokit/memory/\" },\n from: { type: \"integer\", minimum: 1 },\n lines: { type: \"integer\", minimum: 1, maximum: 2000 },\n },\n additionalProperties: false,\n};\n\nconst DEFAULT_MAX_TOTAL_CHARS = 16384;\n\n/** Options for {@link createMemorySearchTool}. */\nexport interface MemorySearchToolOptions {\n index: MemoryIndex;\n /** Cap on the JSON response size (EC-10 of edge-case review). Default 16384. */\n maxTotalChars?: number;\n}\n\n/**\n * Build the `memory_search` tool over an index that is already open. The tool\n * never opens or syncs anything: if `index.sync()` has not run, the search runs\n * against whatever the index last recorded, and a freshly created index returns\n * no hits.\n *\n * The tool accepts `query` (required), `maxResults` (default 10), `minScore`,\n * and `corpus`, where `corpus` maps to the index's source filter: `memory`,\n * `sessions`, `wiki`, or `all` (the default, which applies no filter). An\n * unrecognised `corpus` value is treated as `all` rather than rejected.\n *\n * `execute` returns `{\"hits\": [...], \"truncated\": bool}`. Hits are dropped from\n * the tail once their estimated size would exceed `maxTotalChars`, except that\n * the first hit is always kept even when it alone exceeds the cap.\n *\n * Use this for recall by meaning across the whole corpus, and\n * {@link createMemoryGetTool} when the model already knows the file and wants\n * exact lines.\n */\nexport function createMemorySearchTool(opts: MemorySearchToolOptions): MemoryTool {\n const cap = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;\n return {\n name: \"memory_search\",\n description: SEARCH_DESCRIPTION,\n inputSchema: MEMORY_SEARCH_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const query = readString(input.query, \"query is required\");\n const maxResults = readNumber(input.maxResults) ?? 10;\n const minScore = readNumber(input.minScore);\n const corpus = readString(input.corpus, undefined, true);\n const sources = mapCorpusToSources(corpus);\n const searchOptions = {\n maxResults,\n ...(minScore !== undefined ? { minScore } : {}),\n ...(sources !== undefined ? { sources } : {}),\n };\n const hits = await opts.index.search(query, searchOptions);\n return JSON.stringify(capByTotalChars(hits, cap));\n },\n };\n}\n\n/** Options for {@link createMemoryGetTool}. `cwd` is the workspace root, not the memory directory. */\nexport interface MemoryGetToolOptions {\n /** The RESOLVED memory root the tool may read inside — not a cwd (#463). */\n root: MemoryRoot;\n}\n\n/**\n * Build the `memory_get` tool, which reads an exact excerpt from a file under\n * `<cwd>/.theokit/memory`. Needs no index and no embedding runtime — it is\n * plain file reading, so it works in a workspace where search is not configured.\n *\n * The tool accepts `path` (required, relative to the memory root), `from`\n * (1-indexed, default 1) and `lines` (default 200). A `path` whose resolved\n * location falls outside the memory root is rejected with a\n * `ConfigurationError` carrying the code `memory_path_escapes_root`. A path that\n * stays inside but does not exist is not caught here: the underlying read\n * rejects with the filesystem error.\n */\nexport function createMemoryGetTool(opts: MemoryGetToolOptions): MemoryTool {\n const memoryRoot = resolvePath(opts.root);\n return {\n name: \"memory_get\",\n description: GET_DESCRIPTION,\n inputSchema: MEMORY_GET_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const relPath = readString(input.path, \"path is required\");\n const from = readNumber(input.from);\n const lines = readNumber(input.lines);\n // EC-2: enforce that the resolved path stays inside the memory root.\n const resolved = resolvePath(memoryRoot, relPath);\n if (!isPathInside(memoryRoot, resolved)) {\n throw new ConfigurationError(\n `memory_get rejected path that escapes memory root: ${relPath}`,\n { code: \"memory_path_escapes_root\" },\n );\n }\n const readArgs: { cwd: string; relPath: string; from?: number; lines?: number } = {\n cwd: memoryRoot,\n relPath,\n };\n if (from !== undefined) readArgs.from = from;\n if (lines !== undefined) readArgs.lines = lines;\n const result = await readMemoryFileBounded(readArgs);\n return JSON.stringify(result);\n },\n };\n}\n\n// ───── helpers ──────────────────────────────────────────────────────────\n\nfunction readString(value: unknown, errorIfMissing?: string, allowUndefined = false): string {\n if (typeof value === \"string\") return value;\n if (allowUndefined && (value === undefined || value === null)) return \"\";\n if (errorIfMissing !== undefined) {\n throw new ConfigurationError(errorIfMissing, { code: \"memory_tool_bad_args\" });\n }\n return \"\";\n}\n\nfunction readNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim().length > 0) {\n const n = Number(value);\n if (Number.isFinite(n)) return n;\n }\n return undefined;\n}\n\nfunction mapCorpusToSources(\n corpus: string,\n): ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\"> | undefined {\n if (corpus === \"\" || corpus === \"all\") return undefined;\n if (corpus === \"memory\") return [\"memory\"];\n if (corpus === \"wiki\") return [\"wiki\"];\n if (corpus === \"sessions\") return [\"sessions\"];\n return undefined;\n}\n\nfunction capByTotalChars(\n hits: ReadonlyArray<MemorySearchHit>,\n maxTotalChars: number,\n): { hits: MemorySearchHit[]; truncated: boolean } {\n if (hits.length === 0) return { hits: [], truncated: false };\n const kept: MemorySearchHit[] = [];\n let runningChars = 0;\n for (const hit of hits) {\n const snippetLen = hit.snippet.length + (hit.citation?.length ?? 0) + 32; // overhead estimate\n if (kept.length > 0 && runningChars + snippetLen > maxTotalChars) {\n return { hits: kept, truncated: true };\n }\n kept.push(hit);\n runningChars += snippetLen;\n }\n return { hits: kept, truncated: false };\n}\n\nfunction isPathInside(root: string, candidate: string): boolean {\n const normalizedRoot = root.endsWith(\"/\") ? root : `${root}/`;\n return candidate === root || candidate.startsWith(normalizedRoot);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/in-memory-provider.ts","../src/internal/store/markdown-store.ts","../src/internal/active-memory/active-memory.ts","../src/internal/circuit-breaker.ts","../src/internal/embedding/azure-openai-embedding.ts","../src/internal/embedding/cohere-embedding.ts","../src/internal/embedding/deepinfra-embedding.ts","../src/internal/embedding/gemini-embedding.ts","../src/internal/embedding/jina-embedding.ts","../src/internal/embedding/mistral-embedding.ts","../src/internal/embedding/ollama-embedding.ts","../src/internal/embedding/openai-embedding.ts","../src/internal/embedding/openrouter-embedding.ts","../src/internal/embedding/voyage-embedding.ts","../src/internal/adapter-catalog.ts","../src/internal/memory-types.ts","../src/internal/adapter-http-error.ts","../src/internal/categorized-memory.ts","../src/internal/index/lance-memory-adapter.ts","../src/internal/index/sqlite-vec-loader.ts","../src/internal/tools.ts"],"names":["ceilingReachedError","ConfigurationError","Security","sessionsDir","join","readdir","readFile","resolveMaxFacts","mkdir","replaceFileAtomic","notesDir","resolveMemoryRoot","finalized","persistActiveMemoryTranscript","createOpenAiCompatibleRuntime","DIMENSION_BY_MODEL","resolvePath","sanitizeIdentifier","safePathJoin","AuthenticationError","RateLimitError","NetworkError","UnknownAgentError","withCwdMutex","SharedLanceMemoryAdapter","readMemoryFileBounded"],"mappings":";;;;;;;;;;;;AA8CA,IAAM,UAAA,GAAa,cAAA;AAwBnB,IAAM,gBAAA,GAAmB,wEAAA;AAqBzB,IAAM,cAAA,0BAAwB,4BAA4B,CAAA;AAE1D,SAAS,iBAAA,GAA+C;AACtD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,QAAA,EAAU,KAAA;AAAA,IACV,OAAA,EAAS,KAAA;AAAA,IACT,SAAA,EAAW,KAAA;AAAA,IACX,WAAA,EAAa,KAAA;AAAA,IACb,QAAA,EAAU;AAAA,GACZ;AACF;AAOA,SAAS,aAAa,KAAA,EAAkC;AACtD,EAAA,IAAI,MAAM,QAAA,KAAa,MAAA,IAAa,MAAM,KAAA,CAAM,IAAA,IAAQ,MAAM,QAAA,EAAU;AACtE,IAAA,MAAMA,+BAAA;AAAA,MACJ,qBAAA;AAAA,MACA,MAAM,KAAA,CAAM,IAAA;AAAA,MACZ,KAAA,CAAM,QAAA;AAAA,MACN;AAAA,KACF;AAAA,EACF;AACF;AAEA,SAAS,iBAAiB,KAAA,EAA6C;AACrE,EAAA,OAAO,KAAA,YAAiBC,sBAAA,IAAsB,KAAA,CAAM,IAAA,KAAS,wBAAA;AAC/D;AAEA,SAAS,aAAa,KAAA,EAA2C;AAC/D,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,UAAA;AAAA,IACJ,cAAc,iBAAA,EAAkB;AAAA,IAChC,WAAA,GAAuB;AACrB,MAAA,OAAO,IAAA;AAAA,IACT,CAAA;AAAA,IACA,MAAM,KAAA,CAAM,OAAA,EAAuC,IAAA,EAAwC;AACzF,MAAA,MAAM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M,IAAA,EAAM,SAAA,EAAW,KAAA,EAAM;AACxC;AAEA,SAAS,YAAA,CAAa,MAAc,SAAA,EAA4B;AAC9D,EAAA,MAAM,iBAAiB,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA,GAAI,IAAA,GAAO,GAAG,IAAI,CAAA,CAAA,CAAA;AAC1D,EAAA,OAAO,SAAA,KAAc,IAAA,IAAQ,SAAA,CAAU,UAAA,CAAW,cAAc,CAAA;AAClE","file":"index.cjs","sourcesContent":["/**\n * `createInMemoryMarkdownProvider` — first concrete `MemoryProvider`\n * impl shipped in `@theokit/sdk-memory` (SDK 2.0 Phase 1 / T1.6).\n *\n * Goal: prove the contract works end-to-end with a real (non-no-op)\n * impl WITHOUT pulling LanceDB / embedding / circuit-breaker infrastructure.\n * That richer impl lands in subsequent iters.\n *\n * Semantics:\n * - Stores recalled facts in a per-agent in-process Map.\n * - `runActivePass()` returns the facts plus a `systemPromptAdditions`\n * string that joins fact contents with newlines (so the LLM sees\n * them in the system slot).\n * - `buildTools()` surfaces a `memory_remember(content)` tool the LLM\n * can call to persist a fact mid-conversation.\n * - `recordSessionSummary()` writes a markdown summary to\n * `${cwd}/.theokit/memory/sessions/${runId}.md` (real disk write\n * via `@theokit/sdk/persistence` per ADR-008).\n * - `dispose()` clears the handle's per-agent map (releases memory).\n *\n * @public\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n ActiveMemoryPassArgs,\n ActiveMemoryPassResult,\n CustomTool,\n MemoryAdapter,\n MemoryAdapterCapabilities,\n MemoryContext,\n MemoryFact,\n MemoryId,\n MemoryProvider,\n MemoryProviderHandle,\n MemoryProviderInitOptions,\n MemoryTurnMessage,\n RecordSessionSummaryArgs,\n SDKAgent,\n} from \"@theokit/sdk\";\nimport { ConfigurationError, Security } from \"@theokit/sdk\";\nimport { ceilingReachedError, resolveMaxFacts } from \"@theokit/sdk/internal/memory-store\";\nimport { replaceFileAtomic } from \"@theokit/sdk/persistence\";\n\n/** Adapter id prefix — namespaces minted MemoryIds so cross-adapter delete is safe (EC-B). */\nconst ADAPTER_ID = \"in-memory-md\";\n\n/**\n * Options for {@link createInMemoryMarkdownProvider}.\n *\n * @public\n */\nexport interface InMemoryMarkdownProviderOptions {\n /**\n * The most facts one handle may hold. Default: no ceiling.\n *\n * Each handle counts only its own facts, so two agents on one provider each get the full\n * ceiling.\n *\n * At the ceiling a new fact is refused on both write paths: the adapter's `write` rejects with a\n * `ConfigurationError` whose code is `memory_ceiling_reached`, and the `memory_remember` tool\n * replies `{ ok: false, code, error }`. Nothing is stored either way, and `delete(id)` frees a\n * slot. A value that is not a positive integer throws `invalid_memory_ceiling` when the provider\n * is created.\n */\n maxFacts?: number;\n}\n\n/** How the in-memory store tells a caller to make room under its ceiling. */\nconst IN_MEMORY_REMEDY = \"merge or delete facts with the adapter's delete(id), or raise maxFacts\";\n\n/** Per-agent state holder. Stored on the handle via the opaque symbol slot. */\ninterface InMemoryHandleState {\n readonly facts: Map<string, MemoryFact>;\n /** The declared ceiling, validated when the provider was created; absent means none. */\n readonly maxFacts: number | undefined;\n readonly counter: { next: number };\n /**\n * Workspace cwd captured at `init()` time. Used by `runActivePass()`\n * to read previously-written session summaries from disk for recall\n * (iter 34 — closes the \"write but never read\" gap from iter 33).\n */\n readonly cwd: string;\n /**\n * `sessions: true` capability is set when cwd is available (always),\n * so future Stage 3 work can mark this provider as the canonical\n * sessions-recall path (vs. the no-op default).\n */\n}\n\nconst INTERNAL_STATE = Symbol(\"sdk-memory.in-memory.state\");\n\nfunction buildCapabilities(): MemoryAdapterCapabilities {\n return {\n history: false,\n sessions: false,\n tenancy: false,\n reasoning: false,\n toolSchemas: false,\n prefetch: false,\n };\n}\n\n/**\n * Refuse a new fact at the handle's ceiling. Called synchronously right before each `facts.set`,\n * with no `await` between the check and the set, so two racing writes cannot both pass: the event\n * loop runs each synchronous block to completion.\n */\nfunction admitNewFact(state: InMemoryHandleState): void {\n if (state.maxFacts !== undefined && state.facts.size >= state.maxFacts) {\n throw ceilingReachedError(\n \"the in-memory store\",\n state.facts.size,\n state.maxFacts,\n IN_MEMORY_REMEDY,\n );\n }\n}\n\nfunction isCeilingRefusal(cause: unknown): cause is ConfigurationError {\n return cause instanceof ConfigurationError && cause.code === \"memory_ceiling_reached\";\n}\n\nfunction buildAdapter(state: InMemoryHandleState): MemoryAdapter {\n return {\n id: ADAPTER_ID,\n capabilities: buildCapabilities(),\n isAvailable(): boolean {\n return true;\n },\n async write(content: string | MemoryTurnMessage[], _ctx: MemoryContext): Promise<MemoryId> {\n const text = typeof content === \"string\" ? content : content.map((m) => m.content).join(\"\\n\");\n // Iter 43: redact secrets before persisting. Same posture as\n // memory_remember tool handler — secret-containing payloads\n // submitted to MemoryAdapter.write directly should never\n // surface verbatim in subsequent recall.\n const safeText = Security.redact(text);\n admitNewFact(state);\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeText,\n createdAt: new Date().toISOString(),\n });\n return id;\n },\n async recall(_query: string, _ctx: MemoryContext, k?: number): Promise<MemoryFact[]> {\n // Naive recall — return everything (cap at k). Real impls in\n // subsequent iters add semantic similarity via embeddings.\n const all = Array.from(state.facts.values());\n const limit = k !== undefined && k >= 0 ? k : all.length;\n return all.slice(0, limit);\n },\n async delete(id: MemoryId): Promise<void> {\n if (!String(id).startsWith(`${ADAPTER_ID}:`)) {\n throw new Error(\n `MemoryAdapter.delete: id \"${String(id)}\" was not minted by adapter \"${ADAPTER_ID}\"`,\n );\n }\n state.facts.delete(id);\n },\n };\n}\n\n/** Truncate session-summary text fields to bound disk size. */\nconst MAX_SUMMARY_TURN_CHARS = 2000;\n\nfunction truncate(text: string): string {\n if (text.length <= MAX_SUMMARY_TURN_CHARS) return text;\n return `${text.slice(0, MAX_SUMMARY_TURN_CHARS)}…`;\n}\n\n/**\n * Sanitize a runId for use as a filename. Strip path separators +\n * traversal patterns; keep `[a-zA-Z0-9_-]`; cap at 128 chars.\n * Mirrors sdk-core's legacy `writeSessionSummary` sanitizer so the\n * file-path semantics are identical across paths.\n */\nfunction sanitizeRunId(runId: string): string {\n return runId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 128);\n}\n\n/** Render the session-summary markdown body. */\nfunction renderSessionSummaryMarkdown(args: RecordSessionSummaryArgs): string {\n const iso = new Date(args.at).toISOString();\n // Iter 42: redact secrets from User + Assistant text via the public\n // `Security.redact()` API (sdk-core's ADR D68 canonical redactor —\n // 12 built-in patterns: OpenAI, Anthropic, GitHub PAT, AWS, etc.).\n // Mirrors sdk-core's legacy writeSessionSummary behavior so the\n // disk artefact never leaks API keys typed by the user.\n const safeUser = Security.redact(truncate(args.userText));\n const safeAssistant = Security.redact(truncate(args.assistantText));\n return [\n \"---\",\n `runId: ${args.runId}`,\n `agentId: ${args.agentId}`,\n `at: ${iso}`,\n `status: ${args.status}`,\n \"---\",\n \"\",\n \"## User\",\n \"\",\n safeUser,\n \"\",\n \"## Assistant\",\n \"\",\n safeAssistant,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Extract `agentId:` value from a session-summary YAML frontmatter.\n * Returns undefined when the file is malformed or has no agentId.\n *\n * The frontmatter shape is:\n * ---\n * runId: ...\n * agentId: ...\n * ...\n * ---\n *\n * Parsing is intentionally simple (regex line-match) — full YAML parse\n * is overkill for the 5-field frontmatter we emit. A malformed file\n * shows up as undefined → falls out of the optional agentId filter.\n */\nfunction extractAgentIdFromFrontmatter(content: string): string | undefined {\n // Match `agentId: <value>` within the leading frontmatter block.\n const match = content.match(/^agentId:\\s*(.+)$/m);\n if (match === null || match[1] === undefined) return undefined;\n return match[1].trim();\n}\n\n/**\n * Read previously-written session summaries from disk + substring-\n * match against the user message. Best-effort: errors degrade to\n * empty recall (no throw — matches the non-throwing-on-hot-path\n * contract).\n *\n * Iter 34: this is the SUBSTRING-match version. Future iters can\n * upgrade to embedding-based semantic similarity (LanceDB ANN)\n * without changing the public surface.\n *\n * Cap: returns at most 5 hits to bound the systemPromptAdditions size.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: session recall has branching on multiple storage modes\nasync function recallSessionSummaries(\n cwd: string,\n userMessage: string,\n agentIdFilter?: string,\n): Promise<ReadonlyArray<MemoryFact>> {\n const RECALL_CAP = 5;\n const sessionsDir = join(cwd, \".theokit\", \"memory\", \"sessions\");\n let files: string[];\n try {\n files = await readdir(sessionsDir);\n } catch {\n return [];\n }\n const query = userMessage.toLowerCase().trim();\n if (query.length === 0) return [];\n const hits: MemoryFact[] = [];\n for (const file of files) {\n if (!file.endsWith(\".md\")) continue;\n if (hits.length >= RECALL_CAP) break;\n const filePath = join(sessionsDir, file);\n let content: string;\n try {\n content = await readFile(filePath, \"utf-8\");\n } catch {\n continue;\n }\n // Iter 36: agentId scope filter. When set, skip summaries whose\n // frontmatter `agentId:` field doesn't match. Prevents cross-agent\n // data leakage in multi-agent setups.\n if (agentIdFilter !== undefined) {\n const fileAgentId = extractAgentIdFromFrontmatter(content);\n if (fileAgentId !== agentIdFilter) continue;\n }\n if (content.toLowerCase().includes(query)) {\n // Extract a short snippet — the User section (first 200 chars).\n const userIdx = content.indexOf(\"## User\");\n const snippet =\n userIdx >= 0 ? content.slice(userIdx, userIdx + 200).replace(/\\s+/g, \" \") : file;\n const id = `${ADAPTER_ID}:session:${file}` as MemoryId;\n hits.push({\n id,\n content: snippet,\n score: 0.5, // substring-match has no real score; placeholder\n });\n }\n }\n return hits;\n}\n\n/**\n * Build the LLM-facing `memory_search` tool (iter 35). The LLM calls\n * this when the user asks about something it might have learned in a\n * previous session. Queries the disk-backed sessions corpus via the\n * same `recallSessionSummaries` helper used by `runActivePass`.\n */\nfunction buildMemorySearchTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_search\",\n description:\n \"Search past session summaries for content related to a query. Use when the user asks about something they mentioned in a previous conversation. Returns up to 5 short snippets.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"What to search for (a topic, fact, or keyword).\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const query = typeof input.query === \"string\" ? input.query : \"\";\n if (query.length === 0) {\n return JSON.stringify({ ok: false, results: [], error: \"empty query\" });\n }\n const hits = await recallSessionSummaries(state.cwd, query);\n return JSON.stringify({\n ok: true,\n count: hits.length,\n results: hits.map((h) => ({ id: String(h.id), snippet: h.content })),\n });\n },\n };\n}\n\nfunction buildMemoryRememberTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_remember\",\n description:\n \"Persist a short fact about the user/conversation to memory so it can be recalled in future turns. Pass a single concise sentence as `content`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"The fact to remember (one sentence).\" },\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const content = typeof input.content === \"string\" ? input.content : \"\";\n if (content.length === 0) {\n return JSON.stringify({ ok: false, error: \"empty content\" });\n }\n // Iter 43: redact secrets from the LLM-supplied content BEFORE\n // storing in the Map. The LLM may quote a key from the user\n // verbatim (e.g., \"user said their key is sk-proj-...\"); without\n // this, that secret would persist + leak into systemPromptAdditions\n // on subsequent runActivePass calls. Mirrors the iter 42\n // recordSessionSummary redaction posture.\n const safeContent = Security.redact(content);\n try {\n admitNewFact(state);\n } catch (cause) {\n // Only the ceiling is a reply the model can act on; anything else is a defect and rises.\n if (!isCeilingRefusal(cause)) throw cause;\n return JSON.stringify({ ok: false, code: cause.code, error: cause.message });\n }\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeContent,\n createdAt: new Date().toISOString(),\n });\n return JSON.stringify({ ok: true, id });\n },\n };\n}\n\n/**\n * Build a fresh `MemoryProvider` whose facts live in-process. The\n * returned provider is independent — call `createInMemoryMarkdownProvider()`\n * per agent OR share across agents (each `init()` gets its own state).\n *\n * Iter 33: `recordSessionSummary()` writes session-summary markdown\n * files to disk under `${cwd}/.theokit/memory/sessions/`.\n * Iter 34: `runActivePass()` reads back those summaries + substring-\n * matches against the user message for genuine cross-session recall.\n *\n * Future LanceDB-backed impl will replace the substring match with\n * semantic-similarity ANN over embedding vectors.\n */\nexport function createInMemoryMarkdownProvider(\n options: InMemoryMarkdownProviderOptions = {},\n): MemoryProvider {\n const maxFacts = resolveMaxFacts(options.maxFacts);\n return {\n async init(opts: MemoryProviderInitOptions): Promise<MemoryProviderHandle> {\n const state: InMemoryHandleState = {\n facts: new Map(),\n maxFacts,\n counter: { next: 0 },\n cwd: opts.cwd,\n };\n const adapter = buildAdapter(state);\n return {\n adapter,\n [INTERNAL_STATE]: state,\n };\n },\n buildTools(handle: MemoryProviderHandle, _agent: SDKAgent): ReadonlyArray<CustomTool> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return [];\n return [buildMemoryRememberTool(state), buildMemorySearchTool(state)];\n },\n async runActivePass(\n handle: MemoryProviderHandle,\n args: ActiveMemoryPassArgs,\n ): Promise<ActiveMemoryPassResult> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return { facts: [] };\n // (1) In-process facts (from memory_remember tool calls this turn).\n const inProcessFacts = Array.from(state.facts.values());\n // (2) Persisted session-summary recall — iter 34. Read previously-\n // written summaries from disk + substring-match against the user\n // message. Best-effort: read errors degrade to empty recall.\n //\n // Iter 36: scope the disk recall to args.agentId so a session\n // summary written by agent-A never bleeds into agent-B's recall.\n // This is the multi-agent privacy invariant.\n const persistedHits = await recallSessionSummaries(state.cwd, args.userMessage, args.agentId);\n const allFacts = [...inProcessFacts, ...persistedHits];\n if (allFacts.length === 0) return { facts: [] };\n const systemPromptAdditions = [\n \"Known facts about the user/session (recall):\",\n ...allFacts.map((f) => `- ${f.content}`),\n ].join(\"\\n\");\n return { facts: allFacts, systemPromptAdditions };\n },\n sync(_handle: MemoryProviderHandle): void {\n // No-op for the in-memory impl — facts are written synchronously to\n // the Map at handler-call time; nothing to re-index post-run. Future\n // LanceDB-backed impl will fire IndexManager.sync() here.\n return;\n },\n async recordSessionSummary(args: RecordSessionSummaryArgs): Promise<void> {\n // Real filesystem write via `@theokit/sdk/persistence`'s\n // `replaceFileAtomic`. ADR-008 sub-path resolution guarantees the\n // same process-level write lock as sdk-core's legacy\n // `writeSessionSummary`. Future LanceDB-backed impl additionally\n // triggers IndexManager re-sync after the write.\n if (args.status !== \"finished\") return;\n const sessionsPath = join(args.cwd, \".theokit\", \"memory\", \"sessions\");\n const filePath = join(sessionsPath, `${sanitizeRunId(args.runId)}.md`);\n await mkdir(sessionsPath, { recursive: true });\n const body = renderSessionSummaryMarkdown(args);\n await replaceFileAtomic(filePath, body);\n },\n dispose(handle: MemoryProviderHandle): void {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return;\n state.facts.clear();\n },\n };\n}\n","import { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { notesDir, resolveMemoryRoot } from \"@theokit/sdk/internal/memory-store\";\n\n/**\n * Markdown-first memory storage — re-exported from `@theokit/sdk`, not reimplemented here.\n *\n * This file used to be a full copy (iter 56, Stage 3 source-move #13). The copy went stale: `#389`\n * moved the layout from bullets under `MEMORY.md ## Facts` to a file per memory, and the\n * Claude Code compatibility work added two more read roots — both landed in the SDK's copy and\n * neither in this one. Because `Memory.runDreamingSweep` routes through this package whenever it is\n * installed, **the copy that ran was not the copy anyone had updated**: installing\n * `@theokit/sdk-memory` made every memory the SDK had written unreadable, reported as\n * `factsBefore: 0` — a number that reads exactly like an empty store (#430).\n *\n * theokit#160 fixed the identical shape for the embedding runtime, in this same package pair, by\n * importing one implementation instead of syncing two. Same remedy here. Re-syncing the copy would\n * have fixed today's divergence and left tomorrow's free to happen.\n *\n * The re-exported signatures are supersets of what this package used to expose — the added\n * parameters are optional — so nothing that called them before has to change.\n *\n * @internal\n */\nexport {\n appendFact,\n appendFactToMarkdown,\n asMemoryRoot,\n ceilingReachedError,\n claudeProjectMemoryDir,\n collectMarkdownFiles,\n type DiscoveredFile,\n defaultIndexPath,\n indexBudgetWarning,\n lanceStoragePath,\n MEMORY_INDEX_MAX_BYTES,\n MEMORY_INDEX_MAX_LINES,\n type MemoryLocationConfig,\n type MemoryRoot,\n memoryIndexRoot,\n memoryMdPath,\n memoryReadRoots,\n notesDir,\n projectMemoryDir,\n readAllSqliteFacts,\n readFacts,\n readFactsFromMarkdown,\n resolveMaxFacts,\n resolveMemoryRoot,\n type SqliteFactRow,\n} from \"@theokit/sdk/internal/memory-store\";\n\n/** One note discovered under `notes/`: its file name without the `.md` suffix, and its absolute path. */\nexport interface NoteFile {\n slug: string;\n path: string;\n}\n\n/**\n * List the `.md` files directly under `notes/`. Returns `[]` when the directory does not exist, so\n * a workspace that has never written a note is not an error. Does not recurse into sub-directories.\n *\n * Stays here rather than moving to the shared store: notes are this package's concept, and only\n * this package reads them.\n */\nexport async function listNotes(cwd: string): Promise<NoteFile[]> {\n let entries: string[] = [];\n try {\n entries = await readdir(notesDir(resolveMemoryRoot(cwd)));\n } catch {\n return [];\n }\n return entries\n .filter((name) => name.endsWith(\".md\"))\n .map((name) => ({\n slug: name.replace(/\\.md$/, \"\"),\n path: join(notesDir(resolveMemoryRoot(cwd)), name),\n }));\n}\n","/**\n * Active Memory blocking recall (ADR D6 of memory-system-peer-project-parity).\n *\n * Runs BEFORE `agent.send()` assembles the system prompt. Issues a direct\n * call to `IndexManager.search` with the user message (and optional recent\n * turns per `queryMode`).\n *\n * Returns a `summary` string capped at `maxSummaryChars` (default 220 to\n * match peer-project's `DEFAULT_MAX_SUMMARY_CHARS`) which the system-prompt\n * pipeline prepends as a `<active-memory>` block (priority 5).\n *\n * Iter 75 (Stage 3 source-move #38, FINAL move): hybrid copy from\n * sdk-core's `internal/memory/active-memory.ts`. sdk-core retains its\n * copy as the v1.x runtime that `Memory` class delegates to;\n * sdk-memory ships the canonical copy that future Stage 4 port-based\n * composition will consume.\n *\n * **CLOSES the Stage 3 source-move stage in sdk-memory.** Every\n * memory-related concept under sdk-core's internal/memory/ is now\n * canonical in @theokit/sdk-memory (38 source files moved across\n * iter 44-75; 2 inlined adapters added: adapter-http-error iter 73\n * + adapter-catalog renamed iter 74).\n *\n * **Cross-package telemetry contract:** `OTelSpan` and `TelemetryHandle`\n * are now imported from `@theokit/sdk`, which exports them since #295.\n * This file previously inlined structural mirrors of both, with a note\n * that they MUST be replaced once sdk-core made them public — and by\n * the time anyone looked, the mirrors had drifted: they narrowed\n * `setAttributes` to reject the `undefined` values the canonical type\n * accepts, and declared `end()` without its `endTime` parameter. That\n * is how a structural mirror fails: quietly, with both sides compiling.\n *\n * The 2 constant strings (`memory.recall` span name +\n * `theokit_memory_recall_duration_ms` histogram name) are still inlined\n * below, because sdk-core's `span-names.ts` remains private. They are\n * values rather than types, so exporting them is a separate decision\n * with a real bundle cost — unlike these two, which erase at build time.\n *\n * @internal\n */\n\nimport type { OTelSpan, TelemetryHandle } from \"@theokit/sdk\";\n\nimport type { CircuitBreaker } from \"../circuit-breaker.js\";\nimport type { MemorySearchHit } from \"../index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"../index/memory-index.js\";\nimport { resolveMemoryRoot } from \"../store/markdown-store.js\";\nimport { persistActiveMemoryTranscript } from \"../store/transcript-store.js\";\nimport type { ActiveMemoryCache, TenantContext } from \"./active-memory-cache.js\";\n// T4.1 / D438 — `ActiveMemoryResult` and its helpers moved to `./active-memory-types.ts`\n// so `./active-memory-cache.ts` can reach them without cycling back here (cycle #10).\n// Re-exported below for back-compat with in-tree consumers.\nimport type {\n ActiveMemoryQueryMode,\n ActiveMemoryResult,\n ActiveMemoryStatus,\n} from \"./active-memory-types.js\";\n\nexport type { ActiveMemoryQueryMode, ActiveMemoryResult, ActiveMemoryStatus };\n\n// Iter 75 inlined constants — sdk-core's telemetry/span-names.ts is\n// not public. These two are the only ones this file uses.\nconst SPAN_MEMORY_RECALL = \"memory.recall\";\nconst HISTOGRAM_MEMORY_RECALL_DURATION_MS = \"theokit_memory_recall_duration_ms\";\n\n// #295 — the canonical types, not a copy of them.\n//\n// Iter 75 inlined structural mirrors here because sdk-core's telemetry/tracer.ts\n// was not public, with a note that they MUST be replaced once it was. They had\n// already drifted by the time anyone checked: the mirror narrowed `setAttributes`\n// to reject the `undefined` values the canonical type accepts, and declared\n// `end()` without the `endTime` parameter. Neither broke a build — a structural\n// mirror fails by being quietly wrong, not by being loudly missing.\n//\n// `@theokit/sdk` is already a peerDependency of this package, and both types are\n// erased at build time, so this costs nothing at runtime.\n\n/**\n * Tuning for one recall attempt. Recall is off unless `enabled` is exactly\n * `true`, so an options object that omits it disables recall rather than\n * enabling it with defaults.\n */\nexport interface ActiveMemoryOptions {\n /** Whether active recall is enabled. Default `false`. */\n enabled?: boolean;\n /** Query construction strategy. Default `\"recent\"`. */\n queryMode?: ActiveMemoryQueryMode;\n /** Hard timeout in ms. Default `15000`. */\n timeoutMs?: number;\n /** Max chars in the summary. Default `220`. */\n maxSummaryChars?: number;\n /** Number of recent user turns to include in `queryMode === \"recent\"`. Default `2`. */\n recentUserTurns?: number;\n}\n\n/**\n * Everything {@link runActiveMemory} needs for one attempt. Only `userText`,\n * `priorMessages`, `index` and `options` are required; the rest add breaker,\n * cache, transcript persistence and telemetry, each of which is inert when\n * omitted.\n *\n * `index` is accepted as `undefined` on purpose — an agent with memory\n * configured but no index open is a normal state, and it produces a `skipped`\n * result rather than an error.\n */\nexport interface RunActiveMemoryArgs {\n userText: string;\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>;\n index: MemoryIndex | undefined;\n options: ActiveMemoryOptions;\n /** Per-agent circuit breaker (Phase 8). */\n breaker?: CircuitBreaker;\n /** Per-agent result cache (Phase 8). */\n cache?: ActiveMemoryCache;\n /** Workspace root for transcript persistence. */\n cwd?: string;\n /** When true, write transcript JSON under .theokit/memory/transcripts/active-memory/. */\n persistTranscripts?: boolean;\n /** Stable key the breaker + cache key by (default `default`). */\n agentKey?: string;\n /** Run id for transcript file naming. */\n runId?: string;\n /**\n * T0.1 — optional telemetry handle. When provided AND telemetry is enabled,\n * `memory.recall` span is emitted with `{ userId, namespace, scope, queryMode,\n * hits, status }` attrs and `theokit_memory_recall_duration_ms` histogram is\n * recorded with the same dimension keys.\n */\n telemetry?: TelemetryHandle;\n /** User id surfaced as a memory.recall span attr for cross-tenant tracing. */\n userId?: string;\n /** Memory namespace (e.g. `default`, `<orgId>`) for span/histogram dimensions. */\n namespace?: string;\n /** Memory scope (`session` / `user` / `global`) for span/histogram dimensions. */\n scope?: string;\n}\n\nconst DEFAULTS: Required<Omit<ActiveMemoryOptions, \"enabled\">> = {\n queryMode: \"recent\",\n timeoutMs: 15000,\n maxSummaryChars: 220,\n recentUserTurns: 2,\n};\n\n/**\n * Run one blocking recall before the system prompt is assembled, and report what\n * happened. Never throws for a recall failure: a search that times out or\n * rejects comes back as a `timeout` or `error` status with no summary, and the\n * agent run continues without memory.\n *\n * The order of the short-circuits decides what a caller sees. Recall disabled or\n * no index gives `skipped` with no search. An open circuit breaker gives\n * `skipped` too. A cache hit returns the earlier result as-is, which means it\n * also returns that result's `status` and `durationMs` — a cached `no-recall`\n * looks exactly like a fresh one. An empty query gives `no-recall`.\n *\n * Only a real search reaches the breaker: `timeout` records a timeout, `ok` and\n * `no-recall` record a success, and `error` records neither, so a provider that\n * keeps throwing will not trip the breaker.\n *\n * `timeoutMs` bounds how long this waits, not how long the search runs — the\n * underlying `index.search` is left running when the timer wins. The search asks\n * the index for at most 5 hits regardless of options.\n *\n * Cache entries are keyed by tenant as well as by query text, so two callers\n * with the same question and different `userId` / `namespace` / `scope` never\n * share an entry.\n */\nexport async function runActiveMemory(args: RunActiveMemoryArgs): Promise<ActiveMemoryResult> {\n const started = Date.now();\n // T0.1 — `memory.recall` span emitted around the entire body so skipped /\n // cached / no-recall paths still surface in telemetry with the correct status.\n const span = startMemoryRecallSpan(args);\n try {\n if (args.options.enabled !== true || args.index === undefined) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n const cfg = { ...DEFAULTS, ...args.options };\n const breakerKey = args.agentKey ?? \"default\";\n if (args.breaker?.shouldSkip(breakerKey) === true) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n // #56 (GAP-B) — key the cache read by tenant identity so two callers with\n // the same query text but different identity never share a cache entry.\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n const cached = args.cache?.get(args.userText, cfg.queryMode, tenantCtx);\n if (cached !== undefined) return endRecallSpan(span, args, cached);\n\n const query = buildQuery(args.userText, args.priorMessages, cfg.queryMode, cfg.recentUserTurns);\n if (query.trim().length === 0) {\n const finalized = await finalize(args, cfg.queryMode, {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n });\n return endRecallSpan(span, args, finalized);\n }\n const result = await searchOnce(args, cfg, query, started);\n notifyBreaker(args.breaker, breakerKey, result.status);\n const finalized = await finalize(args, cfg.queryMode, result);\n return endRecallSpan(span, args, finalized);\n } catch (cause) {\n span.recordException(cause);\n span.setStatus({ code: 2, message: cause instanceof Error ? cause.message : String(cause) });\n span.end();\n throw cause;\n }\n}\n\nfunction startMemoryRecallSpan(args: RunActiveMemoryArgs): OTelSpan {\n const telemetry: TelemetryHandle | undefined = args.telemetry;\n if (telemetry === undefined) {\n // No-op span identical to the runtime no-op when telemetry is disabled.\n return {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n setStatus: () => {},\n recordException: () => {},\n end: () => {},\n spanContext: () => ({ traceId: \"0\".repeat(32), spanId: \"0\".repeat(16) }),\n isRecording: () => false,\n };\n }\n return telemetry.startSpan(SPAN_MEMORY_RECALL, {\n queryMode: args.options.queryMode ?? \"recent\",\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n}\n\nfunction endRecallSpan(\n span: OTelSpan,\n args: RunActiveMemoryArgs,\n result: ActiveMemoryResult,\n): ActiveMemoryResult {\n span.setAttributes({\n hits: result.hits.length,\n status: result.status,\n durationMs: result.durationMs,\n });\n span.end();\n args.telemetry?.recordHistogram(HISTOGRAM_MEMORY_RECALL_DURATION_MS, result.durationMs, {\n status: result.status,\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n return result;\n}\n\ninterface ResolvedConfig {\n queryMode: ActiveMemoryQueryMode;\n timeoutMs: number;\n maxSummaryChars: number;\n recentUserTurns: number;\n}\n\nasync function searchOnce(\n args: RunActiveMemoryArgs,\n cfg: ResolvedConfig,\n query: string,\n started: number,\n): Promise<ActiveMemoryResult> {\n if (args.index === undefined) {\n return { summary: undefined, durationMs: 0, status: \"skipped\", hits: [] };\n }\n try {\n const hits = await withTimeout(args.index.search(query, { maxResults: 5 }), cfg.timeoutMs);\n if (hits === \"timeout\") {\n return { summary: undefined, durationMs: Date.now() - started, status: \"timeout\", hits: [] };\n }\n if (hits.length === 0) {\n return {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n };\n }\n const summary = formatSummary(hits, cfg.maxSummaryChars);\n return { summary, durationMs: Date.now() - started, status: \"ok\", hits };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(`[theokit-sdk] active-memory recall failed: ${message}\\n`);\n return { summary: undefined, durationMs: Date.now() - started, status: \"error\", hits: [] };\n }\n}\n\nfunction notifyBreaker(\n breaker: CircuitBreaker | undefined,\n key: string,\n status: ActiveMemoryStatus,\n): void {\n if (breaker === undefined) return;\n if (status === \"timeout\") breaker.recordTimeout(key);\n else if (status === \"ok\" || status === \"no-recall\") breaker.recordSuccess(key);\n}\n\nasync function finalize(\n args: RunActiveMemoryArgs,\n queryMode: ActiveMemoryQueryMode,\n result: ActiveMemoryResult,\n): Promise<ActiveMemoryResult> {\n // #56 (GAP-B) — key the cache write by tenant identity (mirrors the get side).\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n args.cache?.set(args.userText, queryMode, result, tenantCtx);\n if (args.persistTranscripts === true && args.cwd !== undefined) {\n await persistActiveMemoryTranscript(resolveMemoryRoot(args.cwd), {\n runId: args.runId ?? `run-${Date.now()}`,\n startedAtMs: Date.now() - result.durationMs,\n userText: args.userText,\n queryMode,\n status: result.status,\n durationMs: result.durationMs,\n summary: result.summary,\n hits: result.hits.map((h) => ({\n path: h.path,\n startLine: h.startLine,\n endLine: h.endLine,\n score: h.score,\n snippet: h.snippet,\n })),\n });\n }\n return result;\n}\n\nfunction buildQuery(\n userText: string,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n queryMode: ActiveMemoryQueryMode,\n recentUserTurns: number,\n): string {\n if (queryMode === \"message\") return userText;\n if (queryMode === \"full\") {\n const allUserTurns = priorMessages.filter((m) => m.role === \"user\").map((m) => m.text);\n return [...allUserTurns, userText].join(\"\\n\");\n }\n // recent\n const recent = priorMessages\n .filter((m) => m.role === \"user\")\n .slice(-recentUserTurns)\n .map((m) => m.text);\n return [...recent, userText].join(\"\\n\");\n}\n\nfunction formatSummary(hits: ReadonlyArray<MemorySearchHit>, maxChars: number): string {\n const lines = hits.map((h) => `- ${h.citation}: ${h.snippet}`);\n let summary = lines.join(\"\\n\");\n if (summary.length > maxChars) summary = `${summary.slice(0, maxChars - 1)}…`;\n return summary;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n const winner = await Promise.race([promise, timeout]);\n return winner;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * Consecutive-timeout circuit breaker for Active Memory recall.\n *\n * Mirrors peer-project's `circuitBreakerMaxTimeouts` + `circuitBreakerCooldownMs`\n * config: after N consecutive timeouts the breaker trips and `shouldSkip`\n * returns `true` until `cooldownMs` has elapsed. A successful recall resets\n * the counter immediately.\n *\n * Per-key isolation so two agents in the same process don't share a counter.\n *\n * @internal\n */\n\nexport interface CircuitBreakerOptions {\n maxTimeouts?: number;\n cooldownMs?: number;\n /** Injectable clock for tests. */\n now?: () => number;\n}\n\ninterface KeyState {\n consecutiveTimeouts: number;\n cooldownUntilMs: number;\n}\n\nconst DEFAULT_MAX_TIMEOUTS = 3;\nconst DEFAULT_COOLDOWN_MS = 60_000;\n\n/**\n * Stops calling a recall path that keeps timing out.\n *\n * After `maxTimeouts` consecutive timeouts on a key (default 3) the breaker\n * opens and {@link CircuitBreaker.shouldSkip} reports `true` until `cooldownMs`\n * has elapsed (default 60s). The first `shouldSkip` after the cooldown closes\n * the breaker and resets the counter, so it re-opens only after another full run\n * of timeouts.\n *\n * It counts timeouts, not failures. An error recorded by neither\n * `recordTimeout` nor `recordSuccess` leaves the counter where it was, so a call\n * path that throws rather than hanging will never trip it.\n *\n * State is per key and held in this instance, which is what keeps two agents in\n * one process from sharing a counter. Construct one per agent and pass a stable\n * key.\n */\nexport class CircuitBreaker {\n private readonly states = new Map<string, KeyState>();\n\n constructor(private readonly opts: CircuitBreakerOptions = {}) {}\n\n /** @returns true when the breaker is open and the call should be skipped. */\n shouldSkip(key: string): boolean {\n const state = this.states.get(key);\n if (state === undefined) return false;\n if (state.cooldownUntilMs === 0) return false;\n if (this.now() < state.cooldownUntilMs) return true;\n // Cooldown elapsed — close the breaker.\n state.cooldownUntilMs = 0;\n state.consecutiveTimeouts = 0;\n return false;\n }\n\n recordSuccess(key: string): void {\n const state = this.states.get(key);\n if (state === undefined) return;\n state.consecutiveTimeouts = 0;\n state.cooldownUntilMs = 0;\n }\n\n recordTimeout(key: string): void {\n const state = this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n state.consecutiveTimeouts += 1;\n if (state.consecutiveTimeouts >= (this.opts.maxTimeouts ?? DEFAULT_MAX_TIMEOUTS)) {\n state.cooldownUntilMs = this.now() + (this.opts.cooldownMs ?? DEFAULT_COOLDOWN_MS);\n }\n this.states.set(key, state);\n }\n\n /** @internal — tests inspect counter state. */\n inspect(key: string): Readonly<KeyState> {\n return this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n }\n\n private now(): number {\n return this.opts.now?.() ?? Date.now();\n }\n}\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Azure OpenAI embedding adapter.\n *\n * Azure addresses the DEPLOYMENT in the path rather than the model in the body:\n * `https://{resource}.openai.azure.com/openai/deployments/{deployment}/embeddings?api-version=...`.\n * `{model}` in `embeddingsPath` is substituted by `createOpenAiCompatibleRuntime`, so `model` here\n * names the Azure deployment.\n *\n * `AZURE_OPENAI_ENDPOINT` supplies the resource URL (without the `/openai/...` suffix);\n * `AZURE_OPENAI_API_KEY` the credential.\n *\n * theokit#128 (catalog parity): sdk-core gained this adapter in T4.10 and the peer never mirrored\n * it, so a `sdk-memory` user asking for `azure-openai` was rejected by a provider the SDK's own\n * `Theokit.inspect.embeddingAdapters()` advertised.\n *\n * @internal\n */\n\nexport const DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\n/**\n * Azure OpenAI embeddings. Same models as the OpenAI adapter, addressed the\n * Azure way, and the one adapter whose configuration is not just \"set a key\".\n *\n * Two things differ from every other adapter here. `model` names your Azure\n * DEPLOYMENT, not an OpenAI model id — it is substituted into the path\n * (`/openai/deployments/{model}/embeddings`) rather than sent in the body. And\n * `AZURE_OPENAI_ENDPOINT` must be set to your resource URL, without the\n * `/openai/...` suffix; the built-in default is a placeholder that resolves\n * nowhere, so leaving it unset fails at the network rather than at\n * configuration.\n *\n * Authentication uses the `api-key` header, which is what an Azure resource key\n * expects; Entra ID bearer tokens are not supported by this adapter. Reads\n * `AZURE_OPENAI_API_KEY`. The API version is pinned to `2024-02-01`.\n *\n * The deployment name still has to appear in the dimension table\n * (`text-embedding-3-small`, `-3-large`, `ada-002`), so a deployment named\n * anything else is refused with `embedding_unknown_model` — pass `model` as the\n * matching id and point the base URL at the right deployment, or add the name to\n * the table.\n */\nexport const azureOpenAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"azure-openai\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"azure-openai\",\n autoSelectPriority: 25,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"azure-openai\",\n defaultBaseUrl: \"https://your-resource.openai.azure.com\",\n apiKeyEnv: \"AZURE_OPENAI_API_KEY\",\n baseUrlEnv: \"AZURE_OPENAI_ENDPOINT\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n embeddingsPath: \"/openai/deployments/{model}/embeddings?api-version=2024-02-01\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — Azure is NOT OpenAI on the wire, despite the name. It authenticates an API\n // key with the `api-key` header (`Authorization: Bearer` is for Entra ID tokens, not for\n // AZURE_OPENAI_API_KEY), and the deployment already rides in the path, so `model` has no\n // place in the body. Sending the OpenAI shape meant every request was rejected.\n dialect: {\n authHeaders: (apiKey: string) => ({ \"api-key\": apiKey }),\n body: (_model: string, inputs: ReadonlyArray<string>) => ({ input: inputs }),\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Cohere embedding adapter — `POST /v2/embed` at `https://api.cohere.com`. Despite living beside\n * the OpenAI-compatible adapters, this endpoint is NOT OpenAI-shaped in either direction; the\n * `dialect` below is what makes it work.\n *\n * Honors `COHERE_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_COHERE_EMBEDDING_MODEL = \"embed-english-v3.0\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"embed-english-v3.0\": 1024,\n \"embed-multilingual-v3.0\": 1024,\n \"embed-english-light-v3.0\": 384,\n \"embed-multilingual-light-v3.0\": 384,\n};\n\n/**\n * Cohere embeddings. Priority 30, so it is auto-selected ahead of OpenAI when\n * both keys are present.\n *\n * Cohere does not speak the OpenAI wire, and this adapter supplies a dialect for\n * it: the request names its payload `texts`, the response returns\n * `{embeddings: {float: [...]}}`, and `input_type` is sent as\n * `search_document`. That last choice matters — Cohere's v3 models embed\n * documents and queries into different spaces, and this runtime always embeds as\n * a document, including the query side of a search. Expect somewhat weaker\n * retrieval than a Cohere-native setup that embeds queries as `search_query`.\n *\n * Reads `COHERE_API_KEY`; no base-URL environment override is declared. The\n * light models are 384 dimensions and the others 1024.\n */\nexport const cohereMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"cohere\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"cohere\",\n autoSelectPriority: 30,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"cohere\",\n defaultBaseUrl: \"https://api.cohere.com\",\n apiKeyEnv: \"COHERE_API_KEY\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n embeddingsPath: \"/v2/embed\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — `/v2/embed` diverges in BOTH directions: it names the payload `texts`, requires\n // `input_type`, and answers `{embeddings:{float:[[...]]}}` rather than `{data:[{embedding}]}`.\n // `search_document` is the right default here because this runtime embeds material for\n // storage; a query-side embedder would use `search_query`.\n dialect: {\n body: (model: string, inputs: ReadonlyArray<string>) => ({\n model,\n texts: [...inputs],\n input_type: \"search_document\",\n embedding_types: [\"float\"],\n }),\n vectors: (json: unknown) =>\n (json as { embeddings?: { float?: number[][] } }).embeddings?.float,\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * DeepInfra embedding adapter — hosts open-source embedding models\n * (BGE, E5, Jina, etc.) at pay-per-token. OpenAI-compatible REST at\n * `POST /v1/openai/embeddings` (note the `/openai` segment; not the\n * canonical `/v1/embeddings`). The `embeddingsPath` override on\n * `OpenAiCompatibleConfig` REPLACES the default suffix (EC-2).\n *\n * Honors `DEEPINFRA_API_KEY` and `DEEPINFRA_API_BASE_URL`.\n *\n * Iter 74 (Stage 3 source-move #33): hybrid copy from sdk-core's\n * `internal/memory/adapters/deepinfra-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_DEEPINFRA_EMBEDDING_MODEL = \"BAAI/bge-large-en-v1.5\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"BAAI/bge-large-en-v1.5\": 1024,\n \"BAAI/bge-base-en-v1.5\": 768,\n \"BAAI/bge-small-en-v1.5\": 384,\n \"BAAI/bge-m3\": 1024,\n \"intfloat/e5-large-v2\": 1024,\n \"intfloat/e5-base-v2\": 768,\n \"intfloat/multilingual-e5-large\": 1024,\n \"sentence-transformers/all-MiniLM-L6-v2\": 384,\n \"thenlper/gte-large\": 1024,\n \"thenlper/gte-base\": 768,\n};\n\n/**\n * Open-weight embedding models (BGE, E5, GTE, MiniLM) hosted by DeepInfra.\n * Reach for it when you want a specific open model — particularly a multilingual\n * one — behind a hosted API rather than running it yourself.\n *\n * Its endpoint is `/v1/openai/embeddings`, not the canonical `/v1/embeddings`;\n * the wire format is otherwise OpenAI-shaped. Reads `DEEPINFRA_API_KEY` and\n * honours `DEEPINFRA_API_BASE_URL`. Priority 13.\n *\n * Dimensions vary sharply across the ten models it knows (384 to 1024), and\n * switching between them invalidates an existing vector index — the index drops\n * every vector and re-embeds on the next sync.\n */\nexport const deepinfraMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"deepinfra\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"deepinfra\",\n autoSelectPriority: 13,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"deepinfra\",\n defaultBaseUrl: \"https://api.deepinfra.com\",\n apiKeyEnv: \"DEEPINFRA_API_KEY\",\n baseUrlEnv: \"DEEPINFRA_API_BASE_URL\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n embeddingsPath: \"/v1/openai/embeddings\",\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Google Gemini embedding adapter — the OpenAI-compatible surface at\n * `https://generativelanguage.googleapis.com/v1/embeddings`.\n *\n * Gemini's NATIVE embedding endpoint has a different shape\n * (`POST /v1beta/models/{model}:embedContent`); this adapter deliberately targets the\n * OpenAI-compatible one so it composes with the shared runtime.\n *\n * Honors `GEMINI_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_GEMINI_EMBEDDING_MODEL = \"text-embedding-004\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-004\": 768,\n \"embedding-001\": 768,\n};\n\n/**\n * Google Gemini embeddings through Google's OpenAI-compatible surface at\n * `/v1beta/openai/embeddings`. Gemini's native embedding endpoint\n * (`/v1beta/models/{model}:embedContent`) has a different shape and is\n * deliberately not used, so this composes with the shared runtime like the rest.\n *\n * Both known models are 768 dimensions. Reads `GEMINI_API_KEY`; no base-URL\n * environment override is declared. Priority 30.\n */\nexport const geminiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"gemini\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"gemini\",\n autoSelectPriority: 30,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"gemini\",\n defaultBaseUrl: \"https://generativelanguage.googleapis.com\",\n apiKeyEnv: \"GEMINI_API_KEY\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n // theokit#159 — the compat surface is under `/v1beta/openai/`, not the default\n // `/v1/embeddings`; the previous path 404'd on every call.\n embeddingsPath: \"/v1beta/openai/embeddings\",\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Jina AI embedding adapter — OpenAI-compatible at `https://api.jina.ai/v1/embeddings`.\n *\n * Honors `JINA_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_JINA_EMBEDDING_MODEL = \"jina-embeddings-v3\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"jina-embeddings-v3\": 1024,\n \"jina-embeddings-v2-base-en\": 768,\n \"jina-embeddings-v2-small-en\": 512,\n};\n\n/**\n * Jina AI embeddings, over the standard OpenAI wire. Highest auto-select\n * priority in the catalog (35), so it wins over OpenAI when both keys are\n * present.\n *\n * Default `jina-embeddings-v3` at 1024 dimensions; the v2 models are 768 and\n * 512. Reads `JINA_API_KEY`. No base-URL environment override is declared —\n * point it elsewhere by passing `baseUrl` to `create`.\n */\nexport const jinaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"jina\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"jina\",\n autoSelectPriority: 35,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"jina\",\n defaultBaseUrl: \"https://api.jina.ai\",\n apiKeyEnv: \"JINA_API_KEY\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Mistral embedding adapter — OpenAI-compatible REST surface\n * (`POST /v1/embeddings` against `https://api.mistral.ai`). Default model\n * `mistral-embed` (1024 dims).\n *\n * Mirrors `reference/peer-project/extensions/mistral/memory-embedding-adapter.ts`.\n *\n * Iter 74 (Stage 3 source-move #32): hybrid copy from sdk-core's\n * `internal/memory/adapters/mistral-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_MISTRAL_EMBEDDING_MODEL = \"mistral-embed\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"mistral-embed\": 1024,\n};\n\n/**\n * Mistral embeddings, over the standard OpenAI wire. One model only,\n * `mistral-embed` at 1024 dimensions; any other id is refused with\n * `embedding_unknown_model`.\n *\n * Reads `MISTRAL_API_KEY` and honours `MISTRAL_API_BASE_URL`. Priority 18, just\n * below OpenAI.\n */\nexport const mistralMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"mistral\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"mistral\",\n autoSelectPriority: 18,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"mistral\",\n defaultBaseUrl: \"https://api.mistral.ai\",\n apiKeyEnv: \"MISTRAL_API_KEY\",\n baseUrlEnv: \"MISTRAL_API_BASE_URL\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","/**\n * Ollama embedding adapter (T3.1, ADR D183).\n *\n * Targets Ollama's OpenAI-compatible `/v1/embeddings` endpoint and reuses\n * the shared `createOpenAiCompatibleRuntime` factory. The differentiating\n * bits:\n *\n * - `authType: \"none\"` — Ollama local ignores `Authorization`. Sentinel\n * `\"ollama-local\"` is passed as apiKey to satisfy the factory contract\n * (mirrors peer-project `OLLAMA_DEFAULT_API_KEY = \"ollama-local\"`).\n * - `OLLAMA_HOST` overrides the default `http://localhost:11434`.\n * - `OLLAMA_API_KEY` (optional) overrides the sentinel for Ollama Cloud\n * or reverse-proxy auth setups.\n * - Default model: `nomic-embed-text` (768 dim, ~274MB). User can opt\n * into `all-minilm` (384 dim, ~45MB) or any other locally-installed\n * embedding model.\n *\n * EC-B MUST FIX (edge-case review 2026-05-21): empty text is rejected\n * upstream in the shared factory (`classifyEntry` short-circuits to a\n * zero vector). That behavior is acceptable here because the zero\n * vector is identical for any empty input — downstream similarity\n * calcs ignore zero-norm vectors via the existing `cosineSimilarity`\n * guard. No additional fail-fast needed.\n *\n * EC-A MUST FIX (edge-case review 2026-05-21): dimension is locked\n * by the `DIMENSION_BY_MODEL` table; an unknown model id throws\n * `ConfigurationError(code: \"embedding_unknown_model\")` per the\n * factory's EC-4 contract. Future model versions with different\n * dimensions are added to the table here without breaking changes.\n *\n * Iter 74 (Stage 3 source-move #36): hybrid copy from sdk-core's\n * `internal/memory/adapters/ollama-embedding.ts`. The only\n * `transport: \"local\"` adapter in the cluster — enables 100%-local\n * RAG with no remote API key.\n *\n * @internal\n */\n\nimport type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Model used when the caller names none: `nomic-embed-text`, 768 dimensions,\n * roughly 274MB to pull. `all-minilm` is the smaller alternative at 384\n * dimensions and roughly 45MB.\n */\nexport const DEFAULT_OLLAMA_EMBEDDING_MODEL = \"nomic-embed-text\";\n\n/** Sentinel forwarded as Bearer token; Ollama local ignores Authorization. */\nconst OLLAMA_LOCAL_SENTINEL_KEY = \"ollama-local\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n // Nomic — local default, recommended quality/size balance.\n \"nomic-embed-text\": 768,\n \"nomic-embed-text:latest\": 768,\n // Sentence-transformers MiniLM — smaller, faster, lower quality.\n \"all-minilm\": 384,\n \"all-minilm:latest\": 384,\n // BGE family.\n \"bge-large\": 1024,\n \"bge-large:latest\": 1024,\n \"bge-m3\": 1024,\n \"bge-m3:latest\": 1024,\n // mxbai-embed-large.\n \"mxbai-embed-large\": 1024,\n \"mxbai-embed-large:latest\": 1024,\n};\n\n/**\n * Embeddings from a local Ollama instance — the only adapter in the catalog with\n * `transport: \"local\"`, and the one to choose when the corpus must not leave the\n * machine or when there is no API key to spend.\n *\n * It needs an Ollama server reachable at `OLLAMA_HOST` (default\n * `http://localhost:11434`) with the chosen embedding model already pulled;\n * nothing here starts a server or downloads a model, so a missing model surfaces\n * as an HTTP error from Ollama rather than a configuration error.\n *\n * No credential is required: a sentinel key is sent and local Ollama ignores it.\n * Set `OLLAMA_API_KEY` for Ollama Cloud or an authenticating reverse proxy.\n *\n * Auto-select priority is 10, the lowest in the catalog, so a configured remote\n * provider wins over it. Request it explicitly to prefer local.\n */\nexport const ollamaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"ollama\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n transport: \"local\" as const,\n authProviderId: \"ollama\",\n // Lower than remote providers — chosen only when explicitly requested\n // OR when no remote provider key is configured (local-first developer).\n autoSelectPriority: 10,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) => {\n // Honor OLLAMA_API_KEY (Ollama Cloud / reverse-proxy auth), else use\n // sentinel that local Ollama silently ignores. This mirrors\n // `sentinelForNoAuth` in router.ts and peer-project's `resolveSyntheticAuth`.\n const apiKey = options.apiKey ?? process.env.OLLAMA_API_KEY ?? OLLAMA_LOCAL_SENTINEL_KEY;\n return createOpenAiCompatibleRuntime(\n {\n id: \"ollama\",\n defaultBaseUrl: \"http://localhost:11434\",\n apiKeyEnv: \"OLLAMA_API_KEY\",\n baseUrlEnv: \"OLLAMA_HOST\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n { ...options, apiKey },\n );\n },\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// **Iter 74 rollup-plugin-dts workaround:** importing\n// `MemoryEmbeddingProviderAdapter` from sibling `./embedding-adapter.js`\n// fails dts emit because no public type reaches it transitively yet\n// (same iter 48/53/55/66/67/69/72 class). Fix: drop the explicit\n// type annotation on the exported adapter; TS infers the structural\n// shape from the literal, and the catalog (iter 37 / this same iter)\n// pin assignability against the canonical interface via its own\n// `Record<string, MemoryEmbeddingProviderAdapter>` constraint.\n\n/**\n * OpenAI embedding adapter (ADR D3) — built on the shared OpenAI-compatible\n * factory. Native fetch only.\n *\n * Iter 74 (Stage 3 source-move #31): hybrid copy from sdk-core's\n * `internal/memory/adapters/openai-embedding.ts`. Composes iter 45's\n * `MemoryEmbeddingProviderAdapter` + iter 73's\n * `createOpenAiCompatibleRuntime`.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\n/**\n * OpenAI embeddings — `text-embedding-3-small` (1536), `text-embedding-3-large` (3072) and\n * `text-embedding-ada-002` (1536).\n *\n * It is NOT selected for you. The provider is whatever the caller names in\n * `embedding: { provider }`; omit that and no embedding runtime is built at all. Its\n * `autoSelectPriority` of `20` is metadata no code path reads today, and it is not the highest\n * value in the catalog either — `jina` is 35, `cohere` and `gemini` are 30, `azure-openai` is 25.\n * The 3072-wide `text-embedding-3-large` is reachable through `azure-openai` and, as\n * `openai/text-embedding-3-large`, through `openrouter` as well.\n *\n * Reads `OPENAI_API_KEY`; `OPENAI_API_BASE_URL` redirects it at a compatible\n * gateway. `create` rejects with an `AuthenticationError`\n * (`embedding_missing_api_key`) when no key is found, and with a\n * `ConfigurationError` (`embedding_unknown_model`) for a model outside\n * `text-embedding-3-small`, `text-embedding-3-large` and\n * `text-embedding-ada-002` — the dimension has to be known before any vector\n * table is created, so an unlisted model is refused rather than probed.\n */\nexport const openAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openai\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"openai\",\n autoSelectPriority: 20,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openai\",\n defaultBaseUrl: \"https://api.openai.com\",\n apiKeyEnv: \"OPENAI_API_KEY\",\n baseUrlEnv: \"OPENAI_API_BASE_URL\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * OpenRouter embedding adapter — routes through OpenRouter's\n * `POST /api/v1/embeddings` endpoint (OpenAI-compatible request/response\n * shape). The provider id strings follow OpenRouter's catalog\n * (e.g. `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Honors `OPENROUTER_API_KEY` and `OPENROUTER_API_BASE_URL`. Default base\n * URL is `https://openrouter.ai/api`.\n *\n * Iter 74 (Stage 3 source-move #35): hybrid copy from sdk-core's\n * `internal/memory/adapters/openrouter-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENROUTER_EMBEDDING_MODEL = \"openai/text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"openai/text-embedding-3-small\": 1536,\n \"openai/text-embedding-3-large\": 3072,\n \"openai/text-embedding-ada-002\": 1536,\n \"mistralai/mistral-embed\": 1024,\n};\n\n/**\n * Embeddings routed through OpenRouter, which lets one key reach several\n * upstream providers. Use it when you want to switch provider without changing\n * credentials; use the provider's own adapter when you want its full model\n * range, since only the four ids in this adapter's dimension table are\n * accepted.\n *\n * Model ids carry the upstream prefix, for example\n * `openai/text-embedding-3-small` or `mistralai/mistral-embed`. The endpoint is\n * `/v1/embeddings` under the base `https://openrouter.ai/api`. Reads\n * `OPENROUTER_API_KEY` and honours `OPENROUTER_API_BASE_URL`. Priority 15.\n */\nexport const openRouterMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openrouter\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"openrouter\",\n autoSelectPriority: 15,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openrouter\",\n defaultBaseUrl: \"https://openrouter.ai/api\",\n apiKeyEnv: \"OPENROUTER_API_KEY\",\n baseUrlEnv: \"OPENROUTER_API_BASE_URL\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Voyage AI embedding adapter — `POST /v1/embeddings` at\n * `https://api.voyageai.com` with the OpenAI-compatible `{ model, input }`\n * request shape. Free tier (200M tokens/month) covers most SDK use.\n *\n * Honors `VOYAGE_API_KEY` and `VOYAGE_API_BASE_URL`.\n *\n * Iter 74 (Stage 3 source-move #34): hybrid copy from sdk-core's\n * `internal/memory/adapters/voyage-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_VOYAGE_EMBEDDING_MODEL = \"voyage-3-lite\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"voyage-3-lite\": 512,\n \"voyage-3\": 1024,\n \"voyage-3-large\": 1024,\n \"voyage-code-3\": 1024,\n \"voyage-multilingual-2\": 1024,\n};\n\n/**\n * Voyage AI embeddings, over the standard OpenAI wire. Default model\n * `voyage-3-lite` at 512 dimensions — the narrowest in the catalog, which makes\n * the index smaller and the search cheaper at some cost in quality; `voyage-3`\n * and `voyage-3-large` are 1024, and `voyage-code-3` is the one to pick for\n * source code.\n *\n * Reads `VOYAGE_API_KEY` and honours `VOYAGE_API_BASE_URL`. Priority 14.\n */\nexport const voyageMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"voyage\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"voyage\",\n autoSelectPriority: 14,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"voyage\",\n defaultBaseUrl: \"https://api.voyageai.com\",\n apiKeyEnv: \"VOYAGE_API_KEY\",\n baseUrlEnv: \"VOYAGE_API_BASE_URL\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import { azureOpenAiMemoryEmbeddingProviderAdapter } from \"./embedding/azure-openai-embedding.js\";\nimport { cohereMemoryEmbeddingProviderAdapter } from \"./embedding/cohere-embedding.js\";\nimport { deepinfraMemoryEmbeddingProviderAdapter } from \"./embedding/deepinfra-embedding.js\";\nimport { geminiMemoryEmbeddingProviderAdapter } from \"./embedding/gemini-embedding.js\";\nimport { jinaMemoryEmbeddingProviderAdapter } from \"./embedding/jina-embedding.js\";\nimport { mistralMemoryEmbeddingProviderAdapter } from \"./embedding/mistral-embedding.js\";\nimport { ollamaMemoryEmbeddingProviderAdapter } from \"./embedding/ollama-embedding.js\";\nimport { openAiMemoryEmbeddingProviderAdapter } from \"./embedding/openai-embedding.js\";\nimport { openRouterMemoryEmbeddingProviderAdapter } from \"./embedding/openrouter-embedding.js\";\nimport { voyageMemoryEmbeddingProviderAdapter } from \"./embedding/voyage-embedding.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n// Catalog value type is inferred from the literal record; canonical\n// assignability is checked at consumer call sites that destructure into\n// the canonical `MemoryEmbeddingProviderAdapter` shape.\n\n/**\n * Memory embedding adapter catalog, indexed by provider id.\n *\n * Only adapters with full, tested implementations are exposed. The\n * `openrouter` provider proxies through OpenRouter to whichever embedding\n * model the caller selects via `model` (e.g.\n * `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Locked by ADR D11: `openai`, `mistral`, `openrouter`, `voyage`, `deepinfra`\n * ship in v1.0. ADR D183: `ollama` added — first `transport: \"local\"`\n * adapter, enables 100%-local RAG (no remote API key needed).\n * `lmstudio`, `google`, `bedrock` are deferred to v1.1.\n *\n * Iter 74 (Stage 3 source-move #37): hybrid copy from sdk-core's\n * `internal/memory/adapters/catalog.ts`. Filename renamed to\n * `adapter-catalog.ts` in sdk-memory to disambiguate from the broader\n * \"catalog\" notion at the package barrel level.\n *\n * **This catalog must serve every provider sdk-core ADVERTISES** (theokit#128). When the peer is\n * installed it REPLACES core's catalog in the routing path (`sdk/src/memory.ts`), while the public\n * `Theokit.inspect.embeddingAdapters()` keeps listing core's — so any id core has and this one\n * lacks is a provider the SDK promises and then rejects. That is what happened to `azure-openai`,\n * `cohere`, `jina` and `gemini` for the two months between core's T4.10 and the parity fix.\n * The invariant is enforced by `@theokit/sdk-peer-integration-tests` (`peer-parity.test.ts`).\n *\n * **CLOSES the embedding-adapter cluster in sdk-memory.** The provider adapters + the shared\n * OpenAI-compatible runtime + the inlined HTTP error mapper are canonical here:\n * - iter 45: embedding-adapter (types)\n * - iter 46: embedding-cache (LRU) — REMOVED by theokit#160: the shared runtime owns caching now\n * - iter 73: openai-compatible (shared factory) + adapter-http-error\n * (inlined mapper)\n * - iter 74: openai-embedding + mistral-embedding + deepinfra-embedding\n * + voyage-embedding + openrouter-embedding + ollama-embedding +\n * adapter-catalog (THIS)\n * - theokit#128: azure-openai + cohere + jina + gemini (parity with core's T4.10)\n *\n * @internal\n */\nexport const MEMORY_EMBEDDING_ADAPTERS = {\n openai: openAiMemoryEmbeddingProviderAdapter,\n mistral: mistralMemoryEmbeddingProviderAdapter,\n openrouter: openRouterMemoryEmbeddingProviderAdapter,\n voyage: voyageMemoryEmbeddingProviderAdapter,\n deepinfra: deepinfraMemoryEmbeddingProviderAdapter,\n ollama: ollamaMemoryEmbeddingProviderAdapter,\n // theokit#128 — mirrors sdk-core's T4.10 additions, which the peer had drifted behind.\n \"azure-openai\": azureOpenAiMemoryEmbeddingProviderAdapter,\n cohere: cohereMemoryEmbeddingProviderAdapter,\n jina: jinaMemoryEmbeddingProviderAdapter,\n gemini: geminiMemoryEmbeddingProviderAdapter,\n};\n","/**\n * Public memory types (used by runtime + storage + migration + future index).\n *\n * Leaf module — depends only on `node:path` + the public\n * `@theokit/sdk/path-safety` re-exports (`safePathJoin`,\n * `sanitizeIdentifier`) + `@theokit/sdk`'s `Security` for the\n * canonical `redactSecrets` 12-pattern list (ADR D68).\n *\n * Iter 52 (Stage 3 source-move #9): hybrid copy from sdk-core's\n * `internal/memory/types.ts`. sdk-core retains its copy for v1.x\n * back-compat; sdk-memory ships the canonical copy that future\n * `storage/*`, `migration`, and `tools` moves will target as siblings.\n *\n * **Sub-path-import contract:** sdk-core copy imports\n * `safePathJoin`/`sanitizeIdentifier` from `../security/path-guard.js`\n * (internal path); sdk-memory copy imports them from\n * `@theokit/sdk/path-safety` (public sub-path stable per this\n * iter — sanitizeIdentifier was promoted to the public surface to\n * unblock this move). Same runtime, same grammar.\n *\n * @internal\n */\nimport { resolve as resolvePath } from \"node:path\";\n\nimport { Security } from \"@theokit/sdk\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\n\n/**\n * Per-agent memory configuration. `enabled` gates the configuration-aware\n * accessors (`readFacts`, `appendFact`) — with it `false` they resolve without\n * touching disk, while the lower-level markdown functions ignore it.\n *\n * `namespace`, `scope` and `userId` are only consulted for the legacy JSON path\n * (see {@link legacyMemoryJsonPath}); the markdown store keeps one `MEMORY.md`\n * per workspace and does not partition by them. They are treated as\n * user-supplied and sanitised before they reach a path. `storePath` is treated\n * as trusted and resolved as given.\n */\nexport interface MemoryConfig {\n enabled: boolean;\n namespace?: string;\n userId?: string;\n scope?: \"agent\" | \"user\" | \"team\";\n storePath?: string;\n}\n\n/**\n * One remembered statement. `text` is what gets written, embedded and searched;\n * it passes through secret redaction on the way to disk, so what is stored may\n * differ from what was passed in.\n */\nexport interface MemoryFact {\n text: string;\n /**\n * Optional taxonomy bucket (M4-3). Backward-compatible — flat-store facts\n * omit it; the categorized store (`createCategorizedMemory`) always sets it.\n */\n category?: string;\n}\n\n/**\n * Canonical credential-redaction primitive (ADR D68).\n *\n * sdk-core's copy re-exports `redactSecrets` directly from\n * `../security/index.js` (internal path). sdk-core's PUBLIC surface\n * (`@theokit/sdk`) doesn't expose a bare `redactSecrets` symbol —\n * it ships `Security.redact()` instead (T2.1, by design — the\n * namespace also carries `Security.addPattern()`). sdk-memory's\n * canonical `redactSecrets` re-export wraps `Security.redact` 1-to-1\n * so consumers continue to see the same symbol name without sdk-memory\n * having to import sdk-core's internal subpath. Same 12-pattern\n * list, same two-bucket mask shape, same disable-via-env behavior.\n */\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n return Security.redact(text, opts);\n}\n\n/**\n * Resolve the legacy JSON memory path used pre-ADR-D8 (kept for migration\n * helpers + tests). Centralized here so `migration.ts` and the legacy-aware\n * `runtime/memory-store.ts` don't duplicate the path logic (jscpd cleanup).\n */\nexport function legacyMemoryJsonPath(cwd: string, config: MemoryConfig): string {\n // ADRs D79-D81: storePath is programmatic (trusted); namespace/scope/userId\n // are user-shaped and pass sanitizeIdentifier. EC-7 (edge-case review):\n // realistic userIds (UUIDs, hash IDs, \"default\") pass; \"user@example.com\"\n // and similar need to be normalized by the caller before passing.\n if (config.storePath !== undefined) {\n return resolvePath(cwd, config.storePath);\n }\n const namespace = sanitizeIdentifier(config.namespace ?? \"default\");\n const scope = sanitizeIdentifier(config.scope ?? \"agent\", { maxLen: 16 });\n const userId = sanitizeIdentifier(config.userId ?? \"default\");\n return safePathJoin(cwd, \".theokit\", \"memory\", namespace, `${scope}-${userId}.json`);\n}\n\n/**\n * A semantically meaningful slice of a markdown memory file, produced by\n * `chunkMarkdown`. Each chunk carries stable line numbers + a content hash\n * used downstream by the embedding cache.\n *\n * Mirrors peer-project's `MemoryChunk` shape\n * (`reference/peer-project/packages/memory-host-sdk/src/host/engine-storage.ts`).\n *\n * @internal\n */\nexport interface MemoryChunk {\n /** 1-indexed starting line in the source file. */\n startLine: number;\n /** 1-indexed ending line (inclusive). */\n endLine: number;\n /** Slice of markdown source text. */\n text: string;\n /** sha256 of `text`; stable across runs for identical inputs. */\n hash: string;\n /** Optional nearest heading text (without the `#` markers). */\n heading?: string;\n}\n\n/**\n * Result of `reader.readFile`. Contains the bounded slice plus truncation\n * + provenance info.\n *\n * Mirrors peer-project's `MemoryReadResult` shape.\n *\n * @internal\n */\nexport interface MemoryReadResult {\n path: string;\n /** Requested starting line (1-indexed, defaults to 1). */\n from: number;\n /** Number of lines actually returned (may be less than `lines` near EOF). */\n linesReturned: number;\n /** Total lines in the file (after the read). */\n totalLines: number;\n /** True when content remains after the returned slice, i.e. `remainingLines > 0`. */\n truncated: boolean;\n /** Lines past the returned slice that remain in the file. */\n remainingLines: number;\n /** Slice text (joined with `\\n`). */\n text: string;\n}\n\n/**\n * Lightweight reference to a markdown file in the memory corpus.\n *\n * Mirrors peer-project's `MemoryFileEntry`.\n *\n * @internal\n */\nexport interface MemoryFileEntry {\n /** Absolute path on disk. */\n path: string;\n /** Path relative to the memory root (e.g. \"MEMORY.md\", \"notes/foo.md\"). */\n relPath: string;\n /** ms-since-epoch mtime. */\n mtime: number;\n /** sha256 of the file content; recomputed on each read. */\n hash: string;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67) — sdk-memory inlined copy.\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * Iter 73 (Stage 3 source-move #30): inlined adaptation of sdk-core's\n * `internal/errors/mappers/openai-compatible.ts` + `shared.ts`. sdk-core's\n * mapper is internal — not part of the public errors surface — so sdk-memory\n * carries its own minimal copy here. Behavior MUST stay byte-equivalent\n * with sdk-core's so consumers consuming hits via either package surface\n * see identical error shape.\n *\n * The 4 helpers (`parseRetryAfter`, `truncateRaw`, `buildErrorMetadata`,\n * `mapOpenAICompatibleError`) are intentionally co-located in this single\n * file so all 8 embedding adapter moves (catalog + 7 providers) share one\n * import target.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n type ErrorMetadata,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"@theokit/sdk/errors\";\n\nimport { redactSecrets } from \"./memory-types.js\";\n\nconst RAW_MAX_BYTES = 2048;\nconst PROVIDER_DETAIL_MAX_CHARS = 512;\n// OpenRouter answers a model it does not serve with HTTP 404 and a numeric `error.code`,\n// so only the message tells it apart from a 404 for a wrong path.\nconst MISSING_MODEL_MESSAGE = /no endpoints found/i;\n\n/**\n * Parse `retry-after` header in numeric-seconds form. HTTP-date form\n * (RFC 7231) returns `undefined` to avoid NaN propagation downstream.\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n // Redact before the cut so a key straddling the limit cannot slip past the patterns.\n const redacted = redactSecrets(s);\n return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}…`;\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output).\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\n/**\n * Turn a failed OpenAI-shaped HTTP response into the typed error the SDK throws.\n * Builds the error, it does not throw it.\n *\n * The HTTP status picks the class: 401 and 403 give an `AuthenticationError`,\n * 429 a `RateLimitError`, 400 a `ConfigurationError`, 408 and 5xx a\n * `NetworkError`, and anything else an `UnknownAgentError`.\n *\n * The `code` on the metadata is finer than the class and is read from\n * `body.error.code` (or `.type`) first, so a 400 that names a context-window\n * problem carries `context_too_long` rather than `invalid_request`. A body code\n * naming an exhausted quota, and HTTP 402, both map to `quota_exceeded` — note\n * that a 402 keeps that code while still producing an `UnknownAgentError`,\n * because no status branch claims it.\n *\n * The raw body rides along on the metadata, truncated to about 2KB and passed\n * through secret redaction, so it is safe to log.\n */\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 404 && code === \"model_unavailable\") {\n // The model id lives only in the provider's text, so this case carries it.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, {\n code: `${providerId}_model_unavailable`,\n metadata,\n });\n }\n if (status === 400) {\n // A 400 is fixed by changing the request, and only the provider's text says what to change.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { message?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n return typeof err.message === \"string\" ? err.message : undefined;\n}\n\n// Redaction runs before the cut so a key cut short cannot slip past the credential patterns.\nfunction boundedProviderDetail(body: unknown): string | undefined {\n const raw = extractOpenAiErrorMessage(body);\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const redacted = redactSecrets(raw);\n return redacted.length <= PROVIDER_DETAIL_MAX_CHARS\n ? redacted\n : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}…`;\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — 402 / Insufficient credits / insufficient_quota body code flow\n // to canonical `quota_exceeded` (ADR-spec'd in ErrorCode union).\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? \"\")) {\n return \"model_unavailable\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(\n providerId: string,\n status: number,\n code: ErrorCode,\n detail?: string,\n): string {\n const base = `${providerId} API error: ${code} (HTTP ${status})`;\n return detail === undefined || detail === \"\" ? base : `${base}: ${detail}`;\n}\n","import { mkdir, readFile } from \"node:fs/promises\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\nimport { replaceFileAtomic, withCwdMutex } from \"@theokit/sdk/persistence\";\n\nimport { type MemoryFact, redactSecrets } from \"./memory-types.js\";\n\n/**\n * A fact stored under a typed category. Unlike the flat {@link MemoryFact}, the\n * `category` is always present in the categorized store's read shape.\n *\n * @public\n */\nexport interface CategorizedFact extends MemoryFact {\n category: string;\n}\n\n/**\n * Options for {@link createCategorizedMemory}.\n *\n * @public\n */\nexport interface CreateCategorizedMemoryOptions {\n /** Directory holding one markdown file per category (`<root>/<category>.md`). */\n root: string;\n /**\n * The closed category taxonomy. This list IS the schema: an `add`/`list`\n * with a category not in it is rejected. Must be non-empty, unique, each\n * sanitizable to a distinct filename.\n */\n categories: readonly string[];\n}\n\n/**\n * A typed, category-partitioned markdown memory store.\n *\n * @public\n */\nexport interface CategorizedMemory {\n /** The declared (frozen) category taxonomy. */\n readonly categories: readonly string[];\n /**\n * Append a fact under `category` (validated against the taxonomy). The text\n * is secret-redacted before persistence. Concurrent adds to the same category\n * are serialized (no lost update). Throws `ConfigurationError(unknown_category)`\n * for an undeclared category (before any I/O).\n */\n add(category: string, text: string): Promise<void>;\n /**\n * Read facts for one category (or every category when omitted). Never throws —\n * a missing/unreadable category file yields no facts.\n */\n list(category?: string): Promise<CategorizedFact[]>;\n}\n\nconst FACTS_HEADING = \"## Facts\";\n\n/**\n * Create a typed categorized memory store over the closed `categories`\n * taxonomy. Composes the shipped `safePathJoin`/`sanitizeIdentifier` path\n * guard, `redactSecrets`, and the atomic `replaceFileAtomic` + `withCwdMutex`\n * persistence primitives — zero new dependencies.\n *\n * @public\n */\nexport function createCategorizedMemory(\n options: CreateCategorizedMemoryOptions,\n): CategorizedMemory {\n const { root, categories } = options;\n validateCategories(categories);\n const allowed = new Set(categories);\n\n function assertKnown(category: string): void {\n if (!allowed.has(category)) {\n throw new ConfigurationError(\n `createCategorizedMemory: unknown category ${JSON.stringify(category)} (declared: ${categories.join(\", \")})`,\n { code: \"unknown_category\" },\n );\n }\n }\n\n function categoryPath(category: string): string {\n return safePathJoin(root, `${sanitizeIdentifier(category)}.md`);\n }\n\n async function add(category: string, text: string): Promise<void> {\n assertKnown(category);\n // Redact secrets, THEN encode newlines/backslashes so a multiline fact (or\n // one containing a `- ` / `## ` line) stays a single bullet and round-trips\n // faithfully — `list` decodes it back. Without this, the `## Facts` bullet\n // parse would split or truncate the fact (silent data loss).\n const encoded = encodeFact(redactSecrets(text));\n const sane = sanitizeIdentifier(category);\n await withCwdMutex(`catmem:${root}:${sane}`, async () => {\n const path = safePathJoin(root, `${sane}.md`);\n const raw = (await readFileOrEmpty(path)) || header(category);\n await mkdir(root, { recursive: true });\n await replaceFileAtomic(path, appendBullet(raw, encoded));\n });\n }\n\n async function list(category?: string): Promise<CategorizedFact[]> {\n if (category !== undefined) {\n assertKnown(category);\n return readCategory(categoryPath(category), category);\n }\n const out: CategorizedFact[] = [];\n for (const c of categories) {\n out.push(...(await readCategory(categoryPath(c), c)));\n }\n return out;\n }\n\n return { categories: [...categories], add, list };\n}\n\nfunction validateCategories(categories: readonly string[]): void {\n if (categories.length === 0) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be non-empty\", {\n code: \"invalid_categories\",\n });\n }\n if (new Set(categories).size !== categories.length) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be unique\", {\n code: \"invalid_categories\",\n });\n }\n const sanitized = categories.map((c) => trySanitize(c));\n if (new Set(sanitized).size !== categories.length) {\n throw new ConfigurationError(\n \"createCategorizedMemory: categories must map to distinct filenames after sanitization\",\n { code: \"invalid_categories\" },\n );\n }\n}\n\nfunction trySanitize(category: string): string {\n try {\n return sanitizeIdentifier(category);\n } catch (cause) {\n throw new ConfigurationError(\n `createCategorizedMemory: category ${JSON.stringify(category)} is not a valid identifier`,\n { code: \"invalid_categories\", cause },\n );\n }\n}\n\nfunction header(category: string): string {\n return `---\\ncategory: ${category}\\n---\\n\\n${FACTS_HEADING}\\n`;\n}\n\nasync function readFileOrEmpty(path: string): Promise<string> {\n try {\n return await readFile(path, \"utf8\");\n } catch {\n return \"\";\n }\n}\n\nasync function readCategory(path: string, category: string): Promise<CategorizedFact[]> {\n const raw = await readFileOrEmpty(path);\n return parseFactBullets(raw).map((text) => ({ text: decodeFact(text), category }));\n}\n\n/**\n * Encode a fact for single-bullet storage: escape `\\` first, then `\\r`/`\\n`, so\n * the text occupies exactly one `- ` line (no split, no `## ` heading injection).\n * Pure + reversible by {@link decodeFact}.\n */\nfunction encodeFact(text: string): string {\n return text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\r/g, \"\\\\r\").replace(/\\n/g, \"\\\\n\");\n}\n\n/**\n * Reverse {@link encodeFact}. A single left-to-right pass over each `\\<char>`\n * escape: `\\n`→newline, `\\r`→CR, and any other escaped char (notably `\\\\`)→the\n * literal char. Non-overlapping matching makes this exact for encoded input.\n */\nfunction decodeFact(text: string): string {\n return text.replace(/\\\\(.)/g, (_match, char: string) =>\n char === \"n\" ? \"\\n\" : char === \"r\" ? \"\\r\" : char,\n );\n}\n\n/** Parse `- text` bullets under the `## Facts` heading. Pure. */\nfunction parseFactBullets(raw: string): string[] {\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) return [];\n const tail = raw.slice(idx + FACTS_HEADING.length);\n const nextHeading = tail.search(/\\n#{1,2}\\s/);\n const block = nextHeading === -1 ? tail : tail.slice(0, nextHeading);\n return block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2).trim());\n}\n\n/** Append a `- text` bullet under the `## Facts` heading. Pure. */\nfunction appendBullet(raw: string, text: string): string {\n const bullet = `- ${text}`;\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) {\n const sep = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${sep}${FACTS_HEADING}\\n\\n${bullet}\\n`;\n }\n const after = idx + FACTS_HEADING.length;\n const nextHeading = raw.slice(after).search(/\\n#{1,2}\\s/);\n if (nextHeading === -1) {\n const trailing = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${trailing}${bullet}\\n`;\n }\n const insertAt = after + nextHeading;\n return `${raw.slice(0, insertAt)}\\n${bullet}${raw.slice(insertAt)}`;\n}\n","import {\n type LanceIndex,\n LanceMemoryAdapter as SharedLanceMemoryAdapter,\n} from \"@theokit/sdk/internal/memory-store\";\n\n/**\n * Presents a `LanceIndex` as a `MemoryIndex`, so a consumer written against the SQLite index runs\n * unchanged on `backend: \"lance\"`.\n *\n * `sync`, `search`, `status` and `close` are the SDK's adapter, inherited rather than copied\n * (#1068), so they behave the same whether or not this package is installed: `sync()` walks\n * nothing and says so with `supported: false`, `search()` blends Lance's vector score with a\n * term-overlap text score through the caller's `vectorWeight` / `textWeight`, and `status()`\n * reports zero counts with `countsExact: false`. It always queries the `default` namespace.\n *\n * The one member this class adds is {@link LanceMemoryAdapter.unwrap}. The SDK's adapter\n * deliberately has no such member; this package published one, so it stays here. An index opened\n * with `IndexManager.open({ backend: \"lance\" })` is the SDK's adapter and does not have it: to\n * write facts, open a `LanceIndex` and either use it directly or wrap it with this class.\n *\n * Requires `@lancedb/lancedb`, an optional peer dependency, loaded when the index is opened.\n */\nexport class LanceMemoryAdapter extends SharedLanceMemoryAdapter {\n readonly #lance: LanceIndex;\n\n constructor(inner: LanceIndex) {\n super(inner);\n this.#lance = inner;\n }\n\n /** The wrapped `LanceIndex`, for `addFacts`, `countFacts` and `removeFacts`. */\n unwrap(): LanceIndex {\n return this.#lance;\n }\n}\n","import type { MemoryDb } from \"@theokit/sdk/internal/memory-store\";\n\n// `isSqliteVecLoaded` has no SDK counterpart yet, so it stays here; the loader is the SDK's.\nexport { loadSqliteVecExtension } from \"@theokit/sdk/internal/memory-store\";\n\n/** Check whether sqlite-vec is loaded by running a tiny version query. */\nexport function isSqliteVecLoaded(db: MemoryDb): boolean {\n try {\n const row = db.prepare(\"SELECT vec_version() as v\").get();\n return row !== undefined && row.v !== undefined;\n } catch {\n return false;\n }\n}\n","import { resolve as resolvePath } from \"node:path\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\n\nimport type { MemorySearchHit } from \"./index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"./index/memory-index.js\";\nimport type { MemoryRoot } from \"./store/markdown-store.js\";\nimport { readMemoryFileBounded } from \"./store/reader.js\";\n\n/**\n * Memory tools (`memory_search` + `memory_get`) — ADR D5 of\n * memory-system-peer-project-parity. Tool schemas mirror peer-project\n * (`reference/peer-project/extensions/memory-core/src/tools.ts:228-475`).\n *\n * Each tool is exposed as a `MemoryTool` (name + description + JSON schema +\n * async execute). The agent-loop integration wires them via the existing\n * `ResolvedTool` interface in `tool-dispatch.ts`.\n *\n * Iter 64 (Stage 3 source-move #21): hybrid copy from sdk-core's\n * `internal/memory/tools.ts`. sdk-core retains its copy for v1.x\n * memory-tools back-compat; sdk-memory ships the canonical copy.\n * Dependency chain (all resolved):\n * - `@theokit/sdk/errors` for `ConfigurationError` (public)\n * - sibling `./index-manager-contract.js` for `MemorySearchHit`\n * (moved iter 47 — note: sdk-core copy imports from\n * `./index-manager.js`; sdk-memory uses the contract leaf\n * directly since the canonical type lives there)\n * - sibling `./memory-index.js` for `MemoryIndex` (moved iter 50)\n * - sibling `./markdown-store.js` for `memoryDir` (moved iter 56)\n * - sibling `./reader.js` for `readMemoryFileBounded` (moved iter 55)\n *\n * @internal\n */\n\nexport interface MemoryToolJson {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\n/**\n * A memory tool ready to hand to the agent loop: the JSON-serialisable\n * description an LLM sees, plus the `execute` that runs it. `execute` resolves\n * to a JSON string — the tool layer does no further encoding.\n */\nexport interface MemoryTool extends MemoryToolJson {\n execute(input: Record<string, unknown>): Promise<string>;\n}\n\nconst SEARCH_DESCRIPTION =\n \"Mandatory recall step: semantically search MEMORY.md + memory/notes/*.md (and optional wiki supplements) before answering questions about prior work, decisions, dates, people, preferences, or todos. `corpus=memory` (default) restricts to indexed memory files; `corpus=wiki` restricts to read-only wiki supplements; `corpus=all` returns both. Returns ranked `{ path, startLine, endLine, score, snippet, citation }` hits.\";\n\nconst GET_DESCRIPTION =\n \"Safe exact excerpt read from MEMORY.md or memory/notes/*.md. Defaults to a bounded excerpt (200 lines). Returns `{ path, from, linesReturned, totalLines, truncated, remainingLines, text }`. Paths are resolved against the memory root — attempts to read outside `.theokit/memory/` are rejected.\";\n\nconst MEMORY_SEARCH_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"query\"],\n properties: {\n query: { type: \"string\", description: \"Natural-language query.\" },\n maxResults: { type: \"integer\", minimum: 1, maximum: 50 },\n minScore: { type: \"number\", minimum: 0, maximum: 1 },\n corpus: { type: \"string\", enum: [\"memory\", \"sessions\", \"wiki\", \"all\"] },\n },\n additionalProperties: false,\n};\n\nconst MEMORY_GET_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"path\"],\n properties: {\n path: { type: \"string\", description: \"Path relative to .theokit/memory/\" },\n from: { type: \"integer\", minimum: 1 },\n lines: { type: \"integer\", minimum: 1, maximum: 2000 },\n },\n additionalProperties: false,\n};\n\nconst DEFAULT_MAX_TOTAL_CHARS = 16384;\n\n/** Options for {@link createMemorySearchTool}. */\nexport interface MemorySearchToolOptions {\n index: MemoryIndex;\n /** Cap on the JSON response size (EC-10 of edge-case review). Default 16384. */\n maxTotalChars?: number;\n}\n\n/**\n * Build the `memory_search` tool over an index that is already open. The tool\n * never opens or syncs anything: if `index.sync()` has not run, the search runs\n * against whatever the index last recorded, and a freshly created index returns\n * no hits.\n *\n * The tool accepts `query` (required), `maxResults` (default 10), `minScore`,\n * and `corpus`, where `corpus` maps to the index's source filter: `memory`,\n * `sessions`, `wiki`, or `all` (the default, which applies no filter). An\n * unrecognised `corpus` value is treated as `all` rather than rejected.\n *\n * `execute` returns `{\"hits\": [...], \"truncated\": bool}`. Hits are dropped from\n * the tail once their estimated size would exceed `maxTotalChars`, except that\n * the first hit is always kept even when it alone exceeds the cap.\n *\n * Use this for recall by meaning across the whole corpus, and\n * {@link createMemoryGetTool} when the model already knows the file and wants\n * exact lines.\n */\nexport function createMemorySearchTool(opts: MemorySearchToolOptions): MemoryTool {\n const cap = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;\n return {\n name: \"memory_search\",\n description: SEARCH_DESCRIPTION,\n inputSchema: MEMORY_SEARCH_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const query = readString(input.query, \"query is required\");\n const maxResults = readNumber(input.maxResults) ?? 10;\n const minScore = readNumber(input.minScore);\n const corpus = readString(input.corpus, undefined, true);\n const sources = mapCorpusToSources(corpus);\n const searchOptions = {\n maxResults,\n ...(minScore !== undefined ? { minScore } : {}),\n ...(sources !== undefined ? { sources } : {}),\n };\n const hits = await opts.index.search(query, searchOptions);\n return JSON.stringify(capByTotalChars(hits, cap));\n },\n };\n}\n\n/** Options for {@link createMemoryGetTool}. `cwd` is the workspace root, not the memory directory. */\nexport interface MemoryGetToolOptions {\n /** The RESOLVED memory root the tool may read inside — not a cwd (#463). */\n root: MemoryRoot;\n}\n\n/**\n * Build the `memory_get` tool, which reads an exact excerpt from a file under\n * `<cwd>/.theokit/memory`. Needs no index and no embedding runtime — it is\n * plain file reading, so it works in a workspace where search is not configured.\n *\n * The tool accepts `path` (required, relative to the memory root), `from`\n * (1-indexed, default 1) and `lines` (default 200). A `path` whose resolved\n * location falls outside the memory root is rejected with a\n * `ConfigurationError` carrying the code `memory_path_escapes_root`. A path that\n * stays inside but does not exist is not caught here: the underlying read\n * rejects with the filesystem error.\n */\nexport function createMemoryGetTool(opts: MemoryGetToolOptions): MemoryTool {\n const memoryRoot = resolvePath(opts.root);\n return {\n name: \"memory_get\",\n description: GET_DESCRIPTION,\n inputSchema: MEMORY_GET_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const relPath = readString(input.path, \"path is required\");\n const from = readNumber(input.from);\n const lines = readNumber(input.lines);\n // EC-2: enforce that the resolved path stays inside the memory root.\n const resolved = resolvePath(memoryRoot, relPath);\n if (!isPathInside(memoryRoot, resolved)) {\n throw new ConfigurationError(\n `memory_get rejected path that escapes memory root: ${relPath}`,\n { code: \"memory_path_escapes_root\" },\n );\n }\n const readArgs: { cwd: string; relPath: string; from?: number; lines?: number } = {\n cwd: memoryRoot,\n relPath,\n };\n if (from !== undefined) readArgs.from = from;\n if (lines !== undefined) readArgs.lines = lines;\n const result = await readMemoryFileBounded(readArgs);\n return JSON.stringify(result);\n },\n };\n}\n\n// ───── helpers ──────────────────────────────────────────────────────────\n\nfunction readString(value: unknown, errorIfMissing?: string, allowUndefined = false): string {\n if (typeof value === \"string\") return value;\n if (allowUndefined && (value === undefined || value === null)) return \"\";\n if (errorIfMissing !== undefined) {\n throw new ConfigurationError(errorIfMissing, { code: \"memory_tool_bad_args\" });\n }\n return \"\";\n}\n\nfunction readNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim().length > 0) {\n const n = Number(value);\n if (Number.isFinite(n)) return n;\n }\n return undefined;\n}\n\nfunction mapCorpusToSources(\n corpus: string,\n): ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\"> | undefined {\n if (corpus === \"\" || corpus === \"all\") return undefined;\n if (corpus === \"memory\") return [\"memory\"];\n if (corpus === \"wiki\") return [\"wiki\"];\n if (corpus === \"sessions\") return [\"sessions\"];\n return undefined;\n}\n\nfunction capByTotalChars(\n hits: ReadonlyArray<MemorySearchHit>,\n maxTotalChars: number,\n): { hits: MemorySearchHit[]; truncated: boolean } {\n if (hits.length === 0) return { hits: [], truncated: false };\n const kept: MemorySearchHit[] = [];\n let runningChars = 0;\n for (const hit of hits) {\n const snippetLen = hit.snippet.length + (hit.citation?.length ?? 0) + 32; // overhead estimate\n if (kept.length > 0 && runningChars + snippetLen > maxTotalChars) {\n return { hits: kept, truncated: true };\n }\n kept.push(hit);\n runningChars += snippetLen;\n }\n return { hits: kept, truncated: false };\n}\n\nfunction isPathInside(root: string, candidate: string): boolean {\n const normalizedRoot = root.endsWith(\"/\") ? root : `${root}/`;\n return candidate === root || candidate.startsWith(normalizedRoot);\n}\n"]}
|