# opencode-mem - Doramagic AI Context Pack

> Positioning: a pre-install experience and judgment asset. It helps the host AI get off to a good start, but it does not mean the project has already been installed, run, or validated.

## Sufficiency Principle

- **Sufficiency over compression**: The AI Context Pack should be sufficient for the host AI to understand the project's value, capability boundaries, entrypoints, risks, and evidence sources before starting work; it may be layered, but it does not aim for the shortest possible summary.
- **Compression policy**: Compress only noise and duplication, never context that affects judgment or the quality of the work.

## How the Host AI Should Use This

You are reading the AI Context Pack that Doramagic compiled for opencode-mem. Treat it as pre-work context: help the user understand who it fits, what it can do, how to start, what must be verified after install, and where the risks are. Do not claim that you have already installed, run, or executed the target project.

## Claim Consumption Rules

- **Fact source**: Repo Evidence + Claim/Evidence Graph; the Human Wiki only supplies salience, terminology, and narrative structure.
- **Minimum status for a fact**: `supported`
- `supported`: May be used as a project fact, but the answer must cite the claim_id and evidence path.
- `weak`: Usable only as a low-confidence lead; the user must be asked to keep verifying.
- `inferred`: Usable only for risk notes or open questions; must not be packaged as a project fact.
- `unverified`: Must not be used as fact; state clearly that evidence is insufficient.
- `contradicted`: Must show the conflicting sources and must not force a single version on the user's behalf.

## Who It Fits Best

- **Developers already using host AIs such as Claude/Codex/Cursor/Gemini**: The README or plugin config mentions multiple host AIs. Evidence: `README.md` Claim: `clm_0002` supported 0.86

## What It Can Do

- **Project Knowledge Preview** (Previewable before install): The project can be read and explained, but current evidence is not enough to confirm installable capabilities or a runtime entrypoint. Evidence: `README.md`, `package.json`, `src/config.ts`, `src/index.ts` et al. Claim: `clm_0001` supported 0.86

## How to Start

- No stable Quick Start command in the project evidence; this should be left empty rather than fabricated by Doramagic.

## Continue-or-Stop Decision Card

- **Current recommendation**: Needs admin / security approval
- **Why**: Continuing may involve secrets, accounts, external services, or sensitive context; get admin or security approval first.

### 30-Second Read

- **What to do now**: Needs admin / security approval
- **Minimum safe next step**: Run Prompt Preview first; if credentials or an enterprise environment are involved, get approval before trialing
- **Do not trust yet**: Real output quality cannot be trusted before install.
- **Continuing will touch**: Environment variables / API keys, Host AI context

### What You Can Trust Now

- **Target-audience signal: Developers already using host AIs such as Claude/Codex/Cursor/Gemini** (supported): Backed by a supported claim or project evidence, but that still is not the same as real install results. Evidence: `README.md` Claim: `clm_0002` supported 0.86
- **Capability exists: Project Knowledge Preview** (supported): You can trust that the project contains signals of this capability; whether it fits your specific task still needs trial or after-install verification. Evidence: `README.md`, `package.json`, `src/config.ts`, `src/index.ts` et al. Claim: `clm_0001` supported 0.86

### What You Cannot Trust Yet

- **Real output quality cannot be trusted before install.** (unverified): Prompt Preview can only show how it guides you; it cannot prove result quality in the real project.
- **Host AI version compatibility cannot be trusted before install.** (unverified): Host loading rules and version differences across Claude, Cursor, Codex, Gemini, and others must be verified in a real environment.
- **That it will not pollute your existing host AI's behavior cannot be trusted directly.** (inferred): Skill, plugin, and AGENTS/CLAUDE/GEMINI instructions may change the host AI's default behavior.
- **Safe rollback cannot be assumed by default.** (unverified): Unless the project clearly provides uninstall and recovery instructions, verify in an isolated environment first.
- **After a real install, is it compatible with the user's current host AI version?** (unverified): Compatibility can only be verified in the actual host environment.
- **Does the project's output quality meet the user's specific task?** (unverified): The pre-install preview can only show flow and boundaries; it cannot replace real evaluation.

### What Continuing Will Touch

- **Environment variables / API keys**: Project entry docs explicitly showing API key, token, secret, or account credential configuration. Why: If a real install needs credentials, use test credentials first and go through a permission/compliance review. Evidence: `README.md`
- **Host AI context**: The AI Context Pack, Prompt Preview, Skill routing, risk rules, and project facts. Why: Importing context affects the host AI's later judgment, so avoid packaging unverified items as facts.

### Minimum Safe Next Steps

- **Run Prompt Preview first**: Use a pre-install interactive trial to judge whether the way of working fits; it needs no authorization or environment change. (applies when: Applies to any project, especially when output quality is unknown.)
- **Trial-install only in an isolated directory or a test account**: Avoid letting install commands pollute your primary host AI, real projects, or home directory. (applies when: When there are signals of command execution, plugin config, or local writes.)
- **Do not use real production credentials**: Once an environment variable / API key enters the host or toolchain, it can create account and compliance risk. (applies when: When environment signals like API, TOKEN, KEY, or SECRET appear.)
- **After install, verify just one minimal task**: Verify loading, compatibility, output quality, and rollback first, then decide whether to use it deeply. (applies when: When moving from a trial into a real workflow.)

### Exit Plan

- **Preserve the pre-install state**: Record the original host config and project state so you can later judge whether it is recoverable.
- **Be ready to revoke test API keys or tokens**: If test credentials leak or are misused, you can cut losses quickly.
- **If there is no rollback path, do not enter your primary environment**: No rollback is a blocker before continuing; do not proceed on trust or luck.

## What Can Only Be Previewed

- Explain who the project fits and what it can do
- Demonstrate a typical conversation flow based on project docs
- Help the user decide whether it is worth installing or researching further

## What Must Be Verified After Install

- Actually installing the Skill, plugin, or CLI
- Running scripts, modifying local files, or accessing external services
- Verifying real output quality, performance, and compatibility

## Boundary & Risk Decision Card

- **Mistaking the pre-install preview for a real run**: The user may overestimate how much configuration, permission, and compatibility verification the project has already done. Mitigation: Clearly separate prompt_preview_can_do from runtime_required. Claim: `clm_0003` inferred 0.45
- **To confirm**: After a real install, is it compatible with the user's current host AI version?. Why: Compatibility can only be verified in the actual host environment.
- **To confirm**: Does the project's output quality meet the user's specific task?. Why: The pre-install preview can only show flow and boundaries; it cannot replace real evaluation.

## Pre-Work Working Context

### Loading Order

- First read how_to_use.host_ai_instruction to establish the boundaries of this pre-install judgment asset.
- Read claim_graph_summary to confirm facts come from the Claim/Evidence Graph, not the Human Wiki narrative.
- Then read intended_users, capabilities, and quick_start_candidates to judge whether the user is a match.
- When you need to carry out a concrete task, check role_skill_index first, then evidence_index.
- For real install, file modification, network access, performance, or compatibility questions, turn to risk_card and boundaries.runtime_required.

### Task Routes

- **Project Knowledge Preview**: Use role_skill_index / evidence_index to help the user pick a usable role, Skill, or workflow first. Boundary: Can be experienced via a pre-install Prompt. Evidence: `README.md`, `package.json`, `src/config.ts`, `src/index.ts` et al. Claim: `clm_0001` supported 0.86

### Context Scale

- Total files: 63
- Important-file coverage: 40/63
- Evidence index entries: 48
- Role / Skill entries: 1

### Handling Insufficient Evidence

- **missing_evidence**: State that evidence is insufficient and ask the user for the target file, a README section, or after-install verification records; do not fill in facts.
- **out_of_scope_request**: State that the task is beyond the current AI Context Pack's evidence scope and suggest the user check the Human Manual or verify after a real install.
- **runtime_request**: Provide a pre-install checklist and command sources, but do not run commands for the user or claim they have been run.
- **source_conflict**: Show the conflicting sources side by side, mark them as unverified, and do not force a single version.

## Prompt Recipes

### Fit assessment

- Goal: Judge whether this project fits the user's current task.
- Expected output: A fit conclusion, key reasons, evidence citations, what can be previewed before install, what must be verified after install, and a next-step recommendation.

```text
Based on the AI Context Pack for opencode-mem, ask me 3 necessary questions first, then judge whether it fits my task. The answer must cover: who it fits, what it can do, what it cannot do, whether it is worth installing, and where the evidence comes from. Every project fact must cite evidence_refs, source_paths, or a claim_id.
```

### Pre-install experience

- Goal: Let the user feel the core workflow before installing, while avoiding packaging the preview as real capability or a marketing promise.
- Expected output: An experience script with boundary labels, an after-install verification checklist, and a cautious recommendation; with no real-run promises or strong marketing language.

```text
Treat opencode-mem as a pre-install experience asset, not an already-installed tool or a real runtime environment.

Output exactly four parts:
1. Ask me 3 necessary questions first.
2. Give an "experience script": use the three labels [Previewable before install], [Must verify after install], and [Insufficient evidence] to show how it might guide the workflow.
3. Give an after-install verification checklist: list which capabilities can only be confirmed after a real install, real host loading, and a real project run.
4. Give a cautious recommendation: only "worth researching/trialing further", "add information before deciding", or "not recommended to continue"; do not endorse the project.

Hard boundaries:
- Do not claim you have installed, run, executed tests, modified files, or produced real results.
- Do not write promise-like phrasing such as "auto-adapts", "guarantees passing", "perfect fit", or "strongly recommend installing".
- If you describe how it works after install, you must use a conditional such as "if installed successfully and the host loads the Skill correctly, it might...".
- The experience script may only be written as "example lines / hypothetical flow": use "might ask / might suggest / might show", not "has written, has generated, has passed, is running, is generating".
- Prompt Preview does not hand out install commands; if the user is ready to trial, only prompt them to read Quick Start and the Risk Card first and to verify in an isolated environment.
- Every project fact must come from a supported claim, evidence_refs, or source_paths; inferred/unverified items can only be risks or open questions.

```

### Role / Skill selection

- Goal: Pick the best-matching asset from the project's roles or Skills.
- Expected output: A list of candidate roles or Skills, each with an applicable scenario, evidence paths, risk boundary, and whether after-install verification is needed.

```text
Read role_skill_index and recommend 3-5 of the most relevant roles or Skills for my target task. For each recommendation, state the applicable scenario, likely output, risk boundary, and evidence_refs.
```

### Risk pre-check

- Goal: Identify environment, permission, rule-conflict, and quality risks before installing or adopting.
- Expected output: A checklist of environment, permission, dependency, license, host-conflict, quality risk, and unknown items.

```text
Based on risk_card, boundaries, and quick_start_candidates, give me a pre-install risk pre-check list. Do not run commands for me; only explain what I should check, why, and what impact a failure would have.
```

### Host AI kickoff instruction

- Goal: Turn the project context into a host AI instruction for the start of a conversation.
- Expected output: A pre-work instruction with clear boundaries and clear evidence citations, suitable to copy to a host AI.

```text
Based on the AI Context Pack for opencode-mem, generate a pre-work instruction I can paste to my host AI. This instruction must obey not_runtime=true and must not claim the project has been installed, run, or produced real results.
```

## Role / Skill Index

- Indexed 1 role / Skill / project-doc entries.

- **OpenCode Memory** (project_doc): ! npm version https://img.shields.io/npm/v/opencode-mem.svg https://www.npmjs.com/package/opencode-mem ! npm downloads https://img.shields.io/npm/dm/opencode-mem.svg https://www.npmjs.com/package/opencode-mem ! license https://img.shields.io/npm/l/opencode-mem.svg https://www.npmjs.com/package/opencode-mem Activation hint: Reference this when the user needs to understand the project's structure, install path, or boundaries. Evidence: `README.md`

## Evidence Index

- Indexed 48 evidence entries.

- **OpenCode Memory** (documentation): ! npm version https://img.shields.io/npm/v/opencode-mem.svg https://www.npmjs.com/package/opencode-mem ! npm downloads https://img.shields.io/npm/dm/opencode-mem.svg https://www.npmjs.com/package/opencode-mem ! license https://img.shields.io/npm/l/opencode-mem.svg https://www.npmjs.com/package/opencode-mem Evidence: `README.md`
- **Package** (package_manifest): { "name": "opencode-mem", "version": "2.17.4", "description": "OpenCode plugin that gives coding agents persistent memory using local vector database", "type": "module", "main": "dist/plugin.js", "types": "dist/index.d.ts", "exports": { ".": { "import": "./dist/plugin.js", "types": "./dist/index.d.ts" }, "./server": { "import": "./dist/plugin.js", "types": "./dist/index.d.ts" }, "./tags": { "import": "./dist/services/tags.js", "types": "./dist/services/tags.d.ts" } }, "scripts": { "build": "bunx tsc && bun scripts/copy-web-assets.mjs", "dev": "tsc --watch", "typecheck": "tsc --noEmit", "format": "prettier --write \"src/ / .{ts,js,css,html}\"", "format:check": "prettier --check \"src/ / .{ts… Evidence: `package.json`
- **Config** (source_file): import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { homedir } from "node:os"; import { stripJsoncComments } from "./services/jsonc.js"; import { resolveSecretValue } from "./services/secret-resolver.js"; import { isPlaceholderApiKey } from "./services/ai/api-key-placeholder.js"; ⋮---- interface OpenCodeMemConfig { storagePath?: string; userEmailOverride?: string; userNameOverride?: string; memory?: { defaultScope?: "project" "all-projects"; }; embeddingModel?: string; embeddingDimensions?: number; embeddingApiUrl?: string; embeddingApiKey?: string; similarityThreshold?: number; maxMemories?: number; maxProfileItems?: numbe… Evidence: `src/config.ts`
- **Index** (source_file): import type { Plugin, PluginInput } from "@opencode-ai/plugin"; import type { Part } from "@opencode-ai/sdk"; import { tool } from "@opencode-ai/plugin"; ⋮---- import { memoryClient } from "./services/client.js"; import { formatContextForPrompt } from "./services/context.js"; import { getTags } from "./services/tags.js"; import { stripPrivateContent, isFullyPrivate } from "./services/privacy.js"; import { performAutoCapture } from "./services/auto-capture.js"; import { performUserProfileLearning } from "./services/user-memory-learning.js"; import { userPromptManager } from "./services/user-prompt/user-prompt-manager.js"; import { startWebServer, WebServer } from "./services/web-server.js";… Evidence: `src/index.ts`
- **Plugin** (source_file): import type { PluginModule } from "@opencode-ai/plugin"; import pkg from "../package.json" with { type: "json" }; Evidence: `src/plugin.ts`
- **Ai Provider Factory** (source_file): import { BaseAIProvider, type ProviderConfig } from "./providers/base-provider.js"; import { OpenAIChatCompletionProvider } from "./providers/openai-chat-completion.js"; import { OpenAIResponsesProvider } from "./providers/openai-responses.js"; import { AnthropicMessagesProvider } from "./providers/anthropic-messages.js"; import { GoogleGeminiProvider } from "./providers/google-gemini.js"; import { aiSessionManager } from "./session/ai-session-manager.js"; import type { AIProviderType } from "./session/session-types.js"; ⋮---- export class AIProviderFactory ⋮---- static createProvider providerType: AIProviderType, config: ProviderConfig : BaseAIProvider ⋮---- static getSupportedProviders :… Evidence: `src/services/ai/ai-provider-factory.ts`
- **Opencode Provider** (source_file): import type { z } from "zod"; import { createOpencodeClient, type OpencodeClient } from "@opencode-ai/sdk/v2/client"; ⋮---- export function setConnectedProviders providers: string : void ⋮---- export function isProviderConnected providerName: string : boolean ⋮---- export function setV2Client client: OpencodeClient : void ⋮---- export function getV2Client : OpencodeClient undefined ⋮---- export function createV2Client serverUrl: URL string : OpencodeClient ⋮---- export interface StructuredOutputOptions { client: OpencodeClient; providerID: string; modelID: string; systemPrompt: string; userPrompt: string; schema: z.ZodType ; directory?: string; retryCount?: number; } ⋮---- export async func… Evidence: `src/services/ai/opencode-provider.ts`
- **Provider Config** (source_file): import type { ProviderConfig } from "./providers/base-provider.js"; import { isPlaceholderApiKey } from "./api-key-placeholder.js"; ⋮---- interface MemoryProviderRuntimeConfig { memoryModel?: string; memoryApiUrl?: string; memoryApiKey?: string; memoryTemperature?: number false; memoryExtraParams?: Record ; autoCaptureMaxIterations?: number; autoCaptureIterationTimeout?: number; } ⋮---- interface ProviderConfigOverrides { maxIterations?: number; iterationTimeout?: number; } ⋮---- export function buildMemoryProviderConfig config: MemoryProviderRuntimeConfig, overrides: ProviderConfigOverrides = {} : ProviderConfig Evidence: `src/services/ai/provider-config.ts`
- **Anthropic Messages** (source_file): import { BaseAIProvider, type ToolCallResult } from "./base-provider.js"; import { AISessionManager } from "../session/ai-session-manager.js"; import { ToolSchemaConverter, type ChatCompletionTool } from "../tools/tool-schema.js"; import { log } from "../../logger.js"; import { UserProfileValidator } from "../validators/user-profile-validator.js"; ⋮---- interface AnthropicMessage { role: "user" "assistant"; content: string Array ; } ⋮---- interface AnthropicResponse { id: string; type: string; role: string; content: Array ; model: string; stop reason: string; usage: { input tokens: number; output tokens: number; }; } ⋮---- export class AnthropicMessagesProvider extends BaseAIProvider ⋮----… Evidence: `src/services/ai/providers/anthropic-messages.ts`
- **Base Provider** (source_file): export interface ToolCallResult { success: boolean; data?: any; error?: string; iterations?: number; } ⋮---- export interface ProviderConfig { model: string; apiUrl: string; apiKey?: string; maxIterations?: number; iterationTimeout?: number; maxTokens?: number; memoryTemperature?: number false; extraParams?: Record ; } ⋮---- export function applySafeExtraParams requestBody: Record , extraParams: Record : void ⋮---- export abstract class BaseAIProvider ⋮---- constructor config: ProviderConfig ⋮---- abstract executeToolCall systemPrompt: string, userPrompt: string, toolSchema: any, sessionId: string : Promise ; ⋮---- abstract getProviderName : string; ⋮---- abstract supportsSession : boolean; Evidence: `src/services/ai/providers/base-provider.ts`
- **Openai Chat Completion** (source_file): import { BaseAIProvider, type ProviderConfig, type ToolCallResult, applySafeExtraParams, } from "./base-provider.js"; import type { AISessionManager } from "../session/ai-session-manager.js"; import type { AIMessage } from "../session/session-types.js"; import type { ChatCompletionTool } from "../tools/tool-schema.js"; import { log } from "../../logger.js"; import { UserProfileValidator } from "../validators/user-profile-validator.js"; ⋮---- interface ToolCallResponse { choices: Array ; }; finish reason?: string; } ; } ⋮---- type APIMessage = { role: AIMessage "role" ; content: string null; tool calls?: ToolCallResponse "choices" number "message" "tool calls" ; tool call id?: string; }; ⋮--… Evidence: `src/services/ai/providers/openai-chat-completion.ts`
- **Openai Responses** (source_file): import { BaseAIProvider, type ToolCallResult, applySafeExtraParams } from "./base-provider.js"; import { AISessionManager } from "../session/ai-session-manager.js"; import { ToolSchemaConverter, type ChatCompletionTool } from "../tools/tool-schema.js"; import { log } from "../../logger.js"; ⋮---- interface ResponsesAPIOutput { id: string; object: string; model: string; output: Array ; conversation?: string; usage?: { input tokens: number; output tokens: number; }; } ⋮---- export class OpenAIResponsesProvider extends BaseAIProvider ⋮---- constructor config: any, aiSessionManager: AISessionManager ⋮---- getProviderName : string ⋮---- supportsSession : boolean ⋮---- async executeToolCall syste… Evidence: `src/services/ai/providers/openai-responses.ts`
- **Session Types** (source_file): export type AIProviderType = "openai-chat" "openai-responses" "anthropic" "google-gemini"; ⋮---- export interface AIMessage { id?: number; aiSessionId: string; sequence: number; role: "system" "user" "assistant" "tool"; content: string; toolCalls?: Array ; toolCallId?: string; contentBlocks?: Array ; createdAt: number; } ⋮---- export interface AISession { id: string; provider: AIProviderType; sessionId: string; conversationId?: string; metadata?: Record ; createdAt: number; updatedAt: number; expiresAt: number; } ⋮---- export interface SessionCreateParams { provider: AIProviderType; sessionId: string; conversationId?: string; metadata?: Record ; } ⋮---- export interface SessionUpdateParams… Evidence: `src/services/ai/session/session-types.ts`
- **Tool Schema** (source_file): export interface ChatCompletionTool { type: "function"; function: { name: string; description: string; parameters: { type: string; properties: Record ; required: string ; }; }; } ⋮---- export interface ResponsesAPITool { type: "function"; name: string; description: string; parameters: { type: string; properties: Record ; required: string ; }; } ⋮---- export interface AnthropicTool { name: string; description: string; input schema: { type: string; properties: Record ; required: string ; }; } ⋮---- export class ToolSchemaConverter ⋮---- static toResponsesAPI chatCompletionTool: ChatCompletionTool : ResponsesAPITool ⋮---- static toAnthropic chatCompletionTool: ChatCompletionTool : AnthropicToo… Evidence: `src/services/ai/tools/tool-schema.ts`
- **User Profile Validator** (source_file): import type { UserProfileData } from "../../user-profile/types.js"; ⋮---- export interface ValidationResult { valid: boolean; errors: string ; data?: UserProfileData; } ⋮---- export class UserProfileValidator ⋮---- static validate data: any : ValidationResult ⋮---- private static validatePreferences preferences: any : string ⋮---- private static validatePatterns patterns: any : string ⋮---- private static validateWorkflows workflows: any : string Evidence: `src/services/ai/validators/user-profile-validator.ts`
- **Auto Capture** (source_file): import type { PluginInput } from "@opencode-ai/plugin"; import { memoryClient } from "./client.js"; import { getTags } from "./tags.js"; import { log } from "./logger.js"; import { CONFIG, hasAutoCaptureProviderConfig } from "../config.js"; import { userPromptManager } from "./user-prompt/user-prompt-manager.js"; ⋮---- interface ToolCallInfo { name: string; input: string; } ⋮---- export async function performAutoCapture ctx: PluginInput, sessionID: string, directory: string : Promise ⋮---- function extractAIContent messages: any : ⋮---- async function getLatestProjectMemory containerTag: string : Promise ⋮---- function buildMarkdownContext userPrompt: string, textResponses: string , toolCal… Evidence: `src/services/auto-capture.ts`
- **Cleanup Service** (source_file): import { shardManager } from "./sqlite/shard-manager.js"; import { vectorSearch } from "./sqlite/vector-search.js"; import { connectionManager } from "./sqlite/connection-manager.js"; import { CONFIG } from "../config.js"; import { log } from "./logger.js"; import { userPromptManager } from "./user-prompt/user-prompt-manager.js"; ⋮---- interface CleanupResult { deletedCount: number; userCount: number; projectCount: number; promptsDeleted: number; linkedMemoriesDeleted: number; pinnedMemoriesSkipped: number; } ⋮---- export class CleanupService ⋮---- async shouldRunCleanup : Promise ⋮---- async runCleanup : Promise ⋮---- getStatus Evidence: `src/services/cleanup-service.ts`
- **Context** (source_file): import { CONFIG } from "../config.js"; import { getUserProfileContext } from "./user-profile/profile-context.js"; ⋮---- interface MemoryResultMinimal { similarity: number; memory?: string; chunk?: string; } ⋮---- interface MemoriesResponseMinimal { results?: MemoryResultMinimal ; } ⋮---- export function formatContextForPrompt userId: string null, projectMemories: MemoriesResponseMinimal : string Evidence: `src/services/context.ts`
- **Deduplication Service** (source_file): import { shardManager } from "./sqlite/shard-manager.js"; import { vectorSearch } from "./sqlite/vector-search.js"; import { connectionManager } from "./sqlite/connection-manager.js"; import { CONFIG } from "../config.js"; import { log } from "./logger.js"; ⋮---- interface DuplicateGroup { representative: { id: string; content: string; containerTag: string; createdAt: number; }; duplicates: Array ; } ⋮---- interface DeduplicationResult { exactDuplicatesDeleted: number; nearDuplicateGroups: DuplicateGroup ; } ⋮---- export class DeduplicationService ⋮---- async detectAndRemoveDuplicates : Promise ⋮---- private cosineSimilarity a: Float32Array, b: Float32Array : number ⋮---- getStatus Evidence: `src/services/deduplication-service.ts`
- **Embedding** (source_file): import { CONFIG } from "../config.js"; import { log } from "./logger.js"; import { join } from "node:path"; ⋮---- type HfTransformers = typeof import "@huggingface/transformers" ; ⋮---- function getTransformersPackageSpecifier : string ⋮---- async function ensureTransformersLoaded : Promise ⋮---- function withTimeout promise: Promise , ms: number : Promise ⋮---- export class EmbeddingService ⋮---- static getInstance : EmbeddingService ⋮---- async warmup progressCallback?: progress: any = void : Promise ⋮---- private async initializeModel progressCallback?: progress: any = void : Promise ⋮---- async embed text: string : Promise ⋮---- async embedWithTimeout text: string : Promise ⋮---- clearC… Evidence: `src/services/embedding.ts`
- **Jsonc** (source_file): export function stripJsoncComments content: string : string ⋮---- // Quote is escaped only if preceded by ODD number of backslashes // e.g., \" = escaped, \\" = not escaped escaped backslash + quote Evidence: `src/services/jsonc.ts`
- **Language Detector** (source_file): import { franc } from "franc-min"; import { iso6393, iso6393To1 } from "iso-639-3"; ⋮---- export function detectLanguage text: string : string ⋮---- export function getLanguageName code: string : string Evidence: `src/services/language-detector.ts`
- **Privacy** (source_file): export function stripPrivateContent content: string : string ⋮---- export function isFullyPrivate content: string : boolean Evidence: `src/services/privacy.ts`
- **Secret Resolver** (source_file): import { existsSync, readFileSync, statSync } from "node:fs"; import { join } from "node:path"; import { homedir, platform } from "node:os"; ⋮---- function expandPath path: string : string ⋮---- function checkFilePermissions filePath: string : void ⋮---- export function resolveSecretValue value: string undefined : string undefined Evidence: `src/services/secret-resolver.ts`
- **Connection Manager** (source_file): import { getDatabase } from "./sqlite-bootstrap.js"; import { existsSync, mkdirSync } from "node:fs"; import { dirname } from "node:path"; import { log } from "../logger.js"; import { CONFIG } from "../../config.js"; ⋮---- export class ConnectionManager ⋮---- private initDatabase db: typeof Database.prototype : void ⋮---- private migrateSchema db: typeof Database.prototype : void ⋮---- getConnection dbPath: string : typeof Database.prototype ⋮---- closeConnection dbPath: string : void ⋮---- closeAll : void ⋮---- checkpointAll : void Evidence: `src/services/sqlite/connection-manager.ts`
- **Shard Manager** (source_file): import { getDatabase } from "./sqlite-bootstrap.js"; import { join, basename } from "node:path"; import { existsSync } from "node:fs"; import { CONFIG } from "../../config.js"; import { connectionManager } from "./connection-manager.js"; import { log } from "../logger.js"; import { vectorSearch } from "./vector-search.js"; import type { ShardInfo } from "./types.js"; ⋮---- type DatabaseType = typeof Database.prototype; ⋮---- export class ShardManager ⋮---- constructor ⋮---- private initMetadataDb : void ⋮---- private getShardPath scope: "user" "project", scopeHash: string, shardIndex: number : string ⋮---- private resolveStoredPath storedPath: string, scope: string : string ⋮---- getActiveS… Evidence: `src/services/sqlite/shard-manager.ts`
- **Sqlite Bootstrap** (source_file): import { createRequire } from "node:module"; ⋮---- type DatabaseCtor = new filename?: string, options?: unknown = unknown; ⋮---- export function getDatabase : DatabaseCtor ⋮---- interface NodeStatementSync { run ...params: unknown : unknown; all ...params: unknown : unknown ; get ...params: unknown : unknown; } ⋮---- run ...params: unknown : unknown; all ...params: unknown : unknown ; get ...params: unknown : unknown; ⋮---- interface NodeDatabaseSync { exec sql: string : unknown; prepare sql: string : NodeStatementSync; close : void; } ⋮---- exec sql: string : unknown; prepare sql: string : NodeStatementSync; close : void; ⋮---- type NodeDatabaseSyncCtor = new filename?: string, options?: u… Evidence: `src/services/sqlite/sqlite-bootstrap.ts`
- **Types** (source_file): export interface ShardInfo { id: number; scope: "user" "project"; scopeHash: string; shardIndex: number; dbPath: string; vectorCount: number; isActive: boolean; createdAt: number; } ⋮---- export interface MemoryRecord { id: string; content: string; vector: Float32Array; tagsVector?: Float32Array; containerTag: string; tags?: string; type?: string; createdAt: number; updatedAt: number; metadata?: string; displayName?: string; userName?: string; userEmail?: string; projectPath?: string; projectName?: string; gitRepoUrl?: string; } ⋮---- export interface SearchResult { id: string; memory: string; similarity: number; tags?: string ; metadata?: Record ; displayName?: string; userName?: string; u… Evidence: `src/services/sqlite/types.ts`
- **Tags** (source_file): import { createHash } from "node:crypto"; import { execSync } from "node:child process"; import { CONFIG } from "../config.js"; import { normalize, resolve, isAbsolute, basename, dirname } from "node:path"; import { realpathSync, existsSync } from "node:fs"; ⋮---- function sha256 input: string : string ⋮---- export interface TagInfo { tag: string; displayName: string; userName?: string; userEmail?: string; projectPath?: string; projectName?: string; gitRepoUrl?: string; } ⋮---- export function getGitEmail : string null ⋮---- export function getGitName : string null ⋮---- export function getGitRepoUrl directory: string : string null ⋮---- export function getGitCommonDir directory: string : s… Evidence: `src/services/tags.ts`
- **User Memory Learning** (source_file): import type { PluginInput } from "@opencode-ai/plugin"; import { getTags } from "./tags.js"; import { log } from "./logger.js"; import { CONFIG } from "../config.js"; import { userPromptManager } from "./user-prompt/user-prompt-manager.js"; import type { UserPrompt } from "./user-prompt/user-prompt-manager.js"; import { userProfileManager } from "./user-profile/user-profile-manager.js"; import type { UserProfile, UserProfileData } from "./user-profile/types.js"; ⋮---- export async function performUserProfileLearning ctx: PluginInput, directory: string : Promise ⋮---- function generateChangeSummary oldProfile: UserProfileData, newProfile: UserProfileData : string ⋮---- function buildUserAnal… Evidence: `src/services/user-memory-learning.ts`
- **Profile Context** (source_file): import { userProfileManager } from "./user-profile-manager.js"; import type { UserProfileData } from "./types.js"; ⋮---- export function getUserProfileContext userId: string : string null Evidence: `src/services/user-profile/profile-context.ts`
- **Profile Utils** (source_file): export const safeArray = arr: any : T = ⋮---- const walk = item: any = ⋮---- export const safeObject = obj: any, fallback: T : T = Evidence: `src/services/user-profile/profile-utils.ts`
- **Types** (source_file): export interface UserProfilePreference { category: string; description: string; confidence: number; evidence: string ; lastUpdated: number; } ⋮---- export interface UserProfilePattern { category: string; description: string; frequency: number; lastSeen: number; } ⋮---- export interface UserProfileWorkflow { description: string; steps: string ; frequency: number; } ⋮---- export interface UserProfileData { preferences: UserProfilePreference ; patterns: UserProfilePattern ; workflows: UserProfileWorkflow ; } ⋮---- export interface UserProfile { id: string; userId: string; displayName: string; userName: string; userEmail: string; profileData: string; version: number; createdAt: number; lastAnal… Evidence: `src/services/user-profile/types.ts`
- **User Profile Manager** (source_file): import { getDatabase } from "../sqlite/sqlite-bootstrap.js"; import { join } from "node:path"; import { connectionManager } from "../sqlite/connection-manager.js"; import { CONFIG } from "../../config.js"; import type { UserProfile, UserProfileChangelog, UserProfileData } from "./types.js"; import { safeArray, safeObject } from "./profile-utils.js"; ⋮---- type DatabaseType = typeof Database.prototype; ⋮---- export class UserProfileManager ⋮---- constructor ⋮---- private initDatabase : void ⋮---- getActiveProfile userId: string : UserProfile null ⋮---- createProfile userId: string, displayName: string, userName: string, userEmail: string, profileData: UserProfileData, promptsAnalyzed: number… Evidence: `src/services/user-profile/user-profile-manager.ts`
- **User Prompt Manager** (source_file): import { getDatabase } from "../sqlite/sqlite-bootstrap.js"; import { join } from "node:path"; import { connectionManager } from "../sqlite/connection-manager.js"; import { CONFIG } from "../../config.js"; ⋮---- type DatabaseType = typeof Database.prototype; ⋮---- export interface UserPrompt { id: string; sessionId: string; messageId: string; projectPath: string null; content: string; createdAt: number; captured: boolean; userLearningCaptured: boolean; linkedMemoryId: string null; capture attempts: number; } ⋮---- export class UserPromptManager ⋮---- constructor ⋮---- private initDatabase : void ⋮---- savePrompt sessionId: string, messageId: string, projectPath: string, content: string : st… Evidence: `src/services/user-prompt/user-prompt-manager.ts`
- **Backend Factory** (source_file): import { CONFIG } from "../../config.js"; import { log } from "../logger.js"; import { ExactScanBackend } from "./exact-scan-backend.js"; import type { VectorBackend, VectorBackendFactoryOptions } from "./types.js"; import { USearchBackend } from "./usearch-backend.js"; ⋮---- class FallbackAwareBackend implements VectorBackend ⋮---- constructor private readonly strategy: "usearch-first" "usearch", private readonly primary: VectorBackend, private readonly fallback: VectorBackend ⋮---- getBackendName : string ⋮---- async insert args: Parameters 0 : Promise ⋮---- async insertBatch args: Parameters 0 : Promise ⋮---- async delete args: Parameters 0 : Promise ⋮---- async search args: Parameters 0… Evidence: `src/services/vector-backends/backend-factory.ts`
- **Exact Scan Backend** (source_file): import type { BackendInsertItem, BackendSearchResult, VectorBackend, VectorBackendSearchParams, VectorKind, } from "./types.js"; import type { ShardInfo } from "../sqlite/types.js"; ⋮---- interface RankedRow { id: string; vector: Float32Array; } ⋮---- interface VectorRow { id: string; vector?: Uint8Array ArrayBuffer null; tags vector?: Uint8Array ArrayBuffer null; } ⋮---- export class ExactScanBackend implements VectorBackend ⋮---- getBackendName : string ⋮---- rankVectors rows: RankedRow , queryVector: Float32Array, limit: number : BackendSearchResult ⋮---- async insert args: ⋮---- async insertBatch args: ⋮---- async delete args: ⋮---- async search args: VectorBackendSearchParams : Promise… Evidence: `src/services/vector-backends/exact-scan-backend.ts`
- **Types** (source_file): import type { ShardInfo } from "../sqlite/types.js"; ⋮---- export type VectorKind = "content" "tags"; ⋮---- export interface BackendSearchResult { id: string; distance: number; } ⋮---- export interface BackendInsertItem { id: string; vector: Float32Array; } ⋮---- export interface VectorBackendSearchParams { db: unknown; shard: ShardInfo; kind: VectorKind; queryVector: Float32Array; limit: number; } ⋮---- export interface VectorBackend { getBackendName : string; insert args: { id: string; vector: Float32Array; shard: ShardInfo; kind: VectorKind; } : Promise ; insertBatch args: { items: BackendInsertItem ; shard: ShardInfo; kind: VectorKind; } : Promise ; delete args: { id: string; shard: Sha… Evidence: `src/services/vector-backends/types.ts`
- **Usearch Backend** (source_file): import type { BackendInsertItem, BackendSearchResult, VectorBackend, VectorBackendSearchParams, VectorKind, } from "./types.js"; import type { ShardInfo } from "../sqlite/types.js"; ⋮---- type USearchModule = typeof import "usearch" ; type USearchIndex = InstanceType ; ⋮---- interface CachedIndex { index: USearchIndex; idToKey: Map ; keyToId: Map ; nextKey: bigint; indexKey: string; initialized: boolean; } ⋮---- export class USearchBackend implements VectorBackend ⋮---- constructor private readonly options: { baseDir: string; dimensions: number; } ⋮---- getBackendName : string ⋮---- async insert args: { id: string; vector: Float32Array; shard: ShardInfo; kind: VectorKind; } : Promise ⋮----… Evidence: `src/services/vector-backends/usearch-backend.ts`
- **Web Server** (source_file): import { readFileSync } from "node:fs"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { Readable } from "node:stream"; import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { log } from "./logger.js"; import { handleListTags, handleListMemories, handleAddMemory, handleDeleteMemory, handleBulkDelete, handleUpdateMemory, handleSearch, handleStats, handlePinMemory, handleUnpinMemory, handleRunCleanup, handleRunDeduplication, handleDetectMigration, handleRunMigration, handleDetectTagMigration, handleRunTagMigrationBatch, handleGetTagMigrationProgress, handleDeletePrompt, handleBulkDeletePrompts, handleGetUserPro… Evidence: `src/services/web-server.ts`
- **Index** (source_file): export type MemoryType = string; ⋮---- export interface MemoryMetadata { type?: MemoryType; source?: "manual" "auto-capture" "import" "api"; tool?: string; sessionID?: string; reasoning?: string; captureTimestamp?: number; promptId?: string; displayName?: string; userName?: string; userEmail?: string; projectPath?: string; projectName?: string; gitRepoUrl?: string; key: string : unknown; } ⋮---- export type AIProviderType = "openai-chat" "openai-responses" "anthropic"; Evidence: `src/types/index.ts`
- **Tsconfig** (structured_config): { "compilerOptions": { "lib": "ESNext" , "target": "ESNext", "module": "ESNext", "moduleDetection": "force", "allowJs": true, Evidence: `tsconfig.json`
- **dependencies bun install** (source_file): dependencies bun install node modules Evidence: `.gitignore`
- **Pre Commit** (source_file): bun run typecheck && bunx lint-staged Evidence: `.husky/pre-commit`
- **.npmrc** (source_file): //registry.npmjs.org/: authToken=${NODE AUTH TOKEN} Evidence: `.npmrc`
- **.prettierignore** (source_file): node modules dist build coverage .lock bun.lock package-lock.json yarn.lock .git .github .min.js .min.css Evidence: `.prettierignore`
- **.prettierrc** (source_file): { "semi": true, "singleQuote": false, "tabWidth": 2, "useTabs": false, "printWidth": 100, "trailingComma": "es5", "bracketSpacing": true, "arrowParens": "always", "endOfLine": "lf" } Evidence: `.prettierrc`
- **Verify Embedding Backend** (source_file): / Embedding-backend smoke test — verifies the local @huggingface/transformers feature-extraction path loads and runs the native ONNX runtime without crashing on the host platform. This is the reproducible form of the manual checks requested when migrating off @xenova/transformers: the prior revert 8fb0836 was motivated by native ONNX runtime crashes under Windows + Bun, so this runs in CI across ubuntu / macOS / windows to catch a regression before merge. Uses a tiny model all-MiniLM-L6-v2, ~25 MB — the goal is to exercise the runtime load + a real embedding call, not to validate any specific model. Run with either bun scripts/verify-embedding-backend.mjs or node scripts/verify-embedding-ba… Evidence: `scripts/verify-embedding-backend.mjs`

## Rules the Host AI Must Follow

- **Treat this asset as pre-work context, not a runtime environment.**: The AI Context Pack contains only an evidence-backed understanding of the project, not the project's executable state. Evidence: `README.md`, `package.json`, `src/config.ts`
- **When answering the user, distinguish what can be previewed from what can only be verified after install.**: The consumer value of the pre-install experience comes from reducing bad installs and misjudgments, not from pretending to be a real run. Evidence: `README.md`, `package.json`, `src/config.ts`

## Questions the User Should Answer First

- Which host AI or local environment do you plan to use it in?
- Do you just want to experience the workflow first, or are you ready to actually install?
- What matters most to you: install cost, output quality, or conflicts with your existing rules?

## Acceptance Checks

- Every capability claim can be traced back to a file path in evidence_refs.
- AI_CONTEXT_PACK.md does not package previews as a real run.
- The user can understand who it fits, what it can do, how to start, and the risk boundaries within 3 minutes.

---

## Doramagic Context Augmentation

The following sections strengthen the repository context for a host AI. Human Manual data is a reading route, and pitfall notes become operating constraints.

## Human Manual Outline

Usage rule: this is only a reading route and salience signal, not factual authority. Concrete claims must still return to repo evidence or Claim Graph.

Host AI hard rules:
- Do not treat page titles, section order, summaries, or importance values as factual project evidence.
- When explaining the Human Manual outline, state that it is only a reading route or salience signal.
- Capability, installation, compatibility, runtime state, and risk claims must cite repo evidence, source paths, or Claim Graph.

- **Overview and Installation**: importance `high`
  - source_paths: README.md, package.json, src/index.ts, src/plugin.ts
- **System Architecture**: importance `high`
  - source_paths: src/index.ts, src/plugin.ts, src/config.ts, src/types/index.ts, src/services/context.ts
- **Configuration Reference**: importance `high`
  - source_paths: src/config.ts, src/services/jsonc.ts, src/services/secret-resolver.ts, src/services/ai/provider-config.ts, README.md
- **Storage: SQLite, Sharding, and Tag Conventions**: importance `high`
  - source_paths: src/services/sqlite/connection-manager.ts, src/services/sqlite/shard-manager.ts, src/services/sqlite/sqlite-bootstrap.ts, src/services/sqlite/types.ts, src/services/tags.ts
- **Vector Search and Embedding Models**: importance `high`
  - source_paths: src/services/vector-backends/backend-factory.ts, src/services/vector-backends/usearch-backend.ts, src/services/vector-backends/exact-scan-backend.ts, src/services/vector-backends/types.ts, src/services/embedding.ts
- **Auto-Capture Pipeline**: importance `high`
  - source_paths: src/services/auto-capture.ts, src/services/user-prompt/user-prompt-manager.ts, src/services/deduplication-service.ts, src/services/cleanup-service.ts, src/services/privacy.ts
- **User Profile Learning System**: importance `medium`
  - source_paths: src/services/user-profile/user-profile-manager.ts, src/services/user-profile/profile-context.ts, src/services/user-profile/profile-utils.ts, src/services/user-profile/types.ts, src/services/user-memory-learning.ts
- **AI Integration, Web UI, and Operational Concerns**: importance `medium`
  - source_paths: src/services/ai/ai-provider-factory.ts, src/services/ai/opencode-provider.ts, src/services/ai/providers/base-provider.ts, src/services/ai/providers/anthropic-messages.ts, src/services/ai/providers/openai-chat-completion.ts

## Repo Inspection Evidence

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `2605abd6aa0c02f88e36f81cce699c66e8c6edcc`
- inspected_files: `README.md`, `package.json`, `src/config.ts`, `src/index.ts`, `src/plugin.ts`, `src/services/ai/ai-provider-factory.ts`, `src/services/ai/api-key-placeholder.ts`, `src/services/ai/opencode-provider.ts`, `src/services/ai/provider-config.ts`, `src/services/ai/providers/anthropic-messages.ts`, `src/services/ai/providers/base-provider.ts`, `src/services/ai/providers/google-gemini.ts`, `src/services/ai/providers/openai-chat-completion.ts`, `src/services/ai/providers/openai-responses.ts`, `src/services/ai/session/ai-session-manager.ts`, `src/services/ai/session/session-types.ts`, `src/services/ai/tools/tool-schema.ts`, `src/services/ai/validators/user-profile-validator.ts`, `src/services/api-handlers.ts`, `src/services/auto-capture.ts`

Host AI hard rules:
- Without repo_clone_verified=true, do not claim that the source code has been read.
- Without repo_inspection_verified=true, do not write README, docs, or package-file conclusions as facts.
- Without quick_start_verified=true, do not claim that the Quick Start path has run successfully.

## Doramagic Pitfall Constraints

These rules come from Doramagic discovery, validation, or compilation findings. The host AI must treat them as operating constraints, not background notes.

### Constraint 1: Capability evidence risk requires verification

- Trigger: README/documentation is current enough for a first validation pass.
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: capability.assumptions | https://github.com/tickernelz/opencode-mem
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.

### Constraint 2: Security or permission risk requires verification

- Trigger: no_demo
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: downstream_validation.risk_items | https://github.com/tickernelz/opencode-mem
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.

### Constraint 3: Security or permission risk requires verification

- Trigger: no_demo
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: risks.scoring_risks | https://github.com/tickernelz/opencode-mem
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.
