### Library - Quick Start Source: https://github.com/memel06/mnemonio/blob/main/README.md Basic setup and usage of the Mnemonio library for creating a memory store and building prompts. ```APIDOC ## Library - Quick Start ### Installation ```bash npm install @memel06/mnemonio ``` ### Usage ```typescript import { createMnemonioStore } from '@memel06/mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', }); // Create the memory directory and MANIFEST.md if they don't exist await store.ensureDir(); // Inject memory context into your system prompt const memoryPrompt = await store.buildPrompt(); const systemPrompt = `You are a helpful assistant.\n\n${memoryPrompt}`; // List all memory files const headers = await store.scan(); console.log(store.formatManifest(headers)); // Get stats const stats = await store.stats(); console.log(`${stats.totalFiles} files, ${stats.totalBytes} bytes`); ``` ``` -------------------------------- ### Mnemonio Library Quick Start Source: https://github.com/memel06/mnemonio/blob/main/README.md Initialize the Mnemonio store, ensure the memory directory exists, and build a system prompt with memory context. This example demonstrates basic store operations without LLM integration. ```typescript import { createMnemonioStore } from '@memel06/mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', }); // Create the memory directory and MANIFEST.md if they don't exist await store.ensureDir(); // Inject memory context into your system prompt const memoryPrompt = await store.buildPrompt(); const systemPrompt = `You are a helpful assistant.\n\n${memoryPrompt}`; // List all memory files const headers = await store.scan(); console.log(store.formatManifest(headers)); // Get stats const stats = await store.stats(); console.log(`${stats.totalFiles} files, ${stats.totalBytes} bytes`); ``` -------------------------------- ### Install Mnemonio Library Source: https://github.com/memel06/mnemonio/blob/main/README.md Install the Mnemonio Node.js library using npm. ```bash npm install @memel06/mnemonio ``` -------------------------------- ### Install Mnemonio CLI Source: https://github.com/memel06/mnemonio/blob/main/README.md Install the Mnemonio command-line interface globally using npm. ```bash npm install -g @memel06/mnemonio ``` -------------------------------- ### Configure MCP Server with Global Install Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use this configuration if mnemonio is installed globally. It simplifies the command to 'mnemonio-mcp' and sets the memory directory. ```json { "mcpServers": { "mnemonio": { "command": "mnemonio-mcp", "env": { "MNEMONIO_DIR": "./.mnemonio" } } } } ``` -------------------------------- ### Memory File Format Example Source: https://github.com/memel06/mnemonio/blob/main/README.md Illustrates the structure of a memory file, including YAML frontmatter and the main content. Ensure frontmatter fields like 'name', 'description', 'type', and 'tags' are correctly populated. ```markdown --- name: testing-approach description: Team prefers integration tests with real DB over mocks type: directive tags: [testing, database] --- Always use the real database for integration tests. > reason: A prior incident where mocked tests passed but production broke on a > schema change. > scope: Use test containers or a dedicated test database. Never mock > the DB layer in integration suites. ``` -------------------------------- ### Get Memory Statistics with Team Directory via CLI Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md View statistics for both private and team memory directories by using the '--team-dir' flag with the 'stats' command. ```bash mnemonio stats .mnemonio --team-dir ./team-memory ``` -------------------------------- ### List Memories with Descriptions and Age (Filtered) Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use the `mnemonio list` command to show memories with descriptions and age, and filter by type. For example, `--type directive`. ```bash mnemonio list .mnemonio --type directive ``` -------------------------------- ### GET /stats Source: https://context7.com/memel06/mnemonio/llms.txt Retrieves aggregate statistics about the memory store. ```APIDOC ## GET /stats ### Description Returns aggregate statistics about the memory store including file counts, total size, type breakdown, and age range. ### Method GET ### Response #### Success Response (200) - **totalFiles** (number) - Total count of files. - **totalBytes** (number) - Total size in bytes. - **byType** (object) - Breakdown of memory types (identity, directive, context, bookmark, unknown). - **oldestMtimeMs** (number) - Timestamp of the oldest file. - **newestMtimeMs** (number) - Timestamp of the newest file. ``` -------------------------------- ### Get Memory Statistics with Mnemonio Source: https://context7.com/memel06/mnemonio/llms.txt The `stats` method returns aggregate statistics about the memory store, including file counts, total size, type breakdown, and age range. Ensure the store is initialized before calling. ```typescript import { createMnemonioStore } from 'mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio' }); const stats = await store.stats(); // Returns: MnemonioStats console.log(`Files: ${stats.totalFiles}`); console.log(`Size: ${stats.totalBytes} bytes`); console.log('Types:'); console.log(` identity: ${stats.byType.identity}`); console.log(` directive: ${stats.byType.directive}`); console.log(` context: ${stats.byType.context}`); console.log(` bookmark: ${stats.byType.bookmark}`); console.log(` unknown: ${stats.byType.unknown}`); if (stats.oldestMtimeMs) { console.log(`Oldest: ${new Date(stats.oldestMtimeMs).toISOString()}`); } if (stats.newestMtimeMs) { console.log(`Newest: ${new Date(stats.newestMtimeMs).toISOString()}`); } ``` -------------------------------- ### Override LLM Provider Detection Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Manually specify the LLM provider if auto-detection is not suitable, for example, when using a proxy. Valid providers include 'openai', 'anthropic', and 'openrouter'. ```json { "env": { "MNEMONIO_PROVIDER": "anthropic", "MNEMONIO_API_KEY": "sk-ant-...", "MNEMONIO_BASE_URL": "https://api.anthropic.com", "MNEMONIO_MODEL": "claude-sonnet-4-6-20250514" } } ``` -------------------------------- ### Initialize Mnemonio Directory via CLI Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Initialize the mnemonio memory directory and MANIFEST.md file using the command-line interface. ```bash mnemonio init .mnemonio ``` -------------------------------- ### Create a Memory Store Source: https://context7.com/memel06/mnemonio/llms.txt Initializes a store instance for managing memory files. Use the basic configuration for simple file operations or include an LLM callback for advanced features like search and extraction. ```typescript import { createMnemonioStore, resolveLlm } from 'mnemonio'; // Basic store without LLM (for listing, reading, stats) const basicStore = createMnemonioStore({ memoryDir: './.mnemonio', }); // Store with LLM for search, extract, distill operations const store = createMnemonioStore({ memoryDir: './.mnemonio', teamDir: './team-memory', // Optional shared read-only memories llm: resolveLlm(), // Auto-detects provider from env vars maxEntrypointLines: 200, // Truncation limits for MANIFEST.md maxEntrypointBytes: 25000, logger: (msg, level) => console.log(`[${level}] ${msg}`), }); // Initialize directory and MANIFEST.md await store.ensureDir(); // Output: Creates .mnemonio/MANIFEST.md if not exists ``` -------------------------------- ### Configure MCP Server Source: https://context7.com/memel06/mnemonio/llms.txt Integration settings for connecting Mnemonio to MCP-compatible AI coding assistants. ```json { "mcpServers": { "mnemonio": { "command": "npx", "args": ["-p", "@memel06/mnemonio", "mnemonio-mcp"], "env": { "MNEMONIO_DIR": "./.mnemonio", "MNEMONIO_TEAM_DIR": "./team-memory", "MNEMONIO_API_KEY": "sk-...", "MNEMONIO_BASE_URL": "https://api.openai.com/v1", "MNEMONIO_MODEL": "gpt-4o" } } } } ``` -------------------------------- ### Configure API Key and Provider for Semantic Search Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Set environment variables for API key, base URL, and model before running a semantic search. The search command targets a specific directory. ```bash export MNEMONIO_API_KEY=your-api-key export MNEMONIO_BASE_URL=https://api.openai.com/v1 # or anthropic.com, openrouter.ai export MNEMONIO_MODEL=gpt-4o mnemonio search "database testing" .mnemonio ``` -------------------------------- ### Create Mnemonio Store with Private and Team Directories Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Initialize the Mnemonio store with paths to both the private memory directory and the shared team memory directory. ```typescript const store = createMnemonioStore({ memoryDir: './.mnemonio', teamDir: './team-memory', }); ``` -------------------------------- ### Configure Mnemonio MCP Server Source: https://github.com/memel06/mnemonio/blob/main/README.md Add the Mnemonio MCP server to your client configuration with the required command and environment variables. ```json { "mcpServers": { "mnemonio": { "command": "npx", "args": ["-p", "@memel06/mnemonio", "mnemonio-mcp"], "env": { "MNEMONIO_DIR": "./.mnemonio" } } } } ``` ```json { "mcpServers": { "mnemonio": { "command": "npx", "args": ["-p", "@memel06/mnemonio", "mnemonio-mcp"], "env": { "MNEMONIO_DIR": "./.mnemonio", "MNEMONIO_BASE_URL": "https://your-llm-provider.com/v1", "MNEMONIO_MODEL": "your-model" } } } } ``` -------------------------------- ### Use Mnemonio TypeScript Library Source: https://github.com/memel06/mnemonio/blob/main/README.md Initialize the store and manage memory paths programmatically using the TypeScript library. ```typescript const store = createMnemonioStore({ memoryDir: './.mnemonio', teamDir: './team-memory', }); // Combined prompt includes both private and team memories const prompt = await store.buildCombinedPrompt(); // Path traversal protection for team writes const safePath = await store.validateTeamWritePath('notes.md'); ``` -------------------------------- ### Create Memory File with YAML Frontmatter Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Create a markdown file in your memory directory with YAML frontmatter to define memory properties like name, description, type, and tags. ```bash cat > .mnemonio/identity_role.md << 'EOF'--- name: role description: User is a backend engineer focused on observability type: identity tags: [team, background] --- Backend engineer working on the observability platform. Primary language is Go. Responsible for the logging pipeline and trace ingestion service. EOF ``` -------------------------------- ### Library - Configuration Source: https://github.com/memel06/mnemonio/blob/main/README.md Details on the configuration options available when creating a Mnemonio store. ```APIDOC ## Library - Configuration ### `MnemonioConfig` Interface ```typescript interface MnemonioConfig { /** Path to the memory directory */ memoryDir: string; /** Optional path to a shared team memory directory */ teamDir?: string; /** LLM callback -- required for search, extract, distill */ llm?: LlmCallback; /** Name of the entrypoint file (default: "MANIFEST.md") */ entrypointName?: string; /** Max lines to include from MANIFEST.md in prompts (default: 200) */ maxEntrypointLines?: number; /** Max bytes to include from MANIFEST.md in prompts (default: 25000) */ maxEntrypointBytes?: number; /** Optional structured logger */ logger?: (msg: string, level: 'debug' | 'info' | 'warn' | 'error') => void; } ``` ``` -------------------------------- ### CLI Commands Source: https://github.com/memel06/mnemonio/blob/main/README.md Overview of available commands for the Mnemonio Command Line Interface. ```APIDOC ## CLI Commands ### Installation ```bash npm install -g @memel06/mnemonio ``` ### Usage All commands default to the current directory if `[dir]` is omitted. Use `--team-dir` to include a shared team memory directory in listings, search, and stats. - **`mnemonio init [dir]`**: Create memory directory with MANIFEST.md - **`mnemonio scan [dir] [--team-dir ] [--json]`**: Display all memory file headers - **`mnemonio list [dir] [--type ] [--team-dir ] [--json]`**: List memories with descriptions + age - **`mnemonio search [dir] [--team-dir ] [--json]`**: Find relevant memories (LLM required) - **`mnemonio distill [dir] [--force] [--json]`**: Run consolidation pass (LLM required) - **`mnemonio stats [dir] [--team-dir ] [--json]`**: File count, size, type breakdown - **`mnemonio prune [dir] [--max-age ] [--dry-run]`**: Remove stale/empty files ``` -------------------------------- ### Define Mnemonio Environment Variables Source: https://github.com/memel06/mnemonio/blob/main/README.md Set API keys and provider details in a .env file or environment configuration. ```env MNEMONIO_API_KEY=your-api-key MNEMONIO_BASE_URL=https://your-llm-provider.com/v1 MNEMONIO_MODEL=your-model ``` ```env MNEMONIO_PROVIDER=anthropic MNEMONIO_API_KEY=sk-ant-... MNEMONIO_BASE_URL=https://api.anthropic.com MNEMONIO_MODEL=claude-sonnet-4-6-20250514 ``` -------------------------------- ### Inspect All Memory Files with Mnemonio CLI Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use the `mnemonio scan` command to display all memory files along with their metadata in the specified directory. ```bash mnemonio scan .mnemonio ``` -------------------------------- ### Mnemonio CLI Commands Overview Source: https://github.com/memel06/mnemonio/blob/main/README.md Overview of available Mnemonio CLI commands for managing memory directories, scanning, listing, searching, distilling, and pruning memories. LLM is required for search and distill commands. ```bash mnemonio init [dir] Create memory directory with MANIFEST.md mnemonio scan [dir] [--team-dir ] [--json] Display all memory file headers mnemonio list [dir] [--type ] [--team-dir ] [--json] List memories with descriptions + age mnemonio search [dir] [--team-dir ] [--json] Find relevant memories (LLM required) mnemonio distill [dir] [--force] [--json] Run consolidation pass (LLM required) mnemonio stats [dir] [--team-dir ] [--json] File count, size, type breakdown mnemonio prune [dir] [--max-age ] [--dry-run] Remove stale/empty files ``` -------------------------------- ### Build Memory Prompts with Mnemonio Source: https://context7.com/memel06/mnemonio/llms.txt Generates memory context strings for LLM system prompts. Content is automatically truncated to fit token budgets. Use `buildPrompt` for private memories and `buildCombinedPrompt` for private and team memories. ```typescript import { createMnemonioStore } from 'mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', teamDir: './team-memory', maxEntrypointLines: 200, maxEntrypointBytes: 25000, }); // Build prompt from private memories only const memoryPrompt = await store.buildPrompt(); // Build combined prompt including team memories const combinedPrompt = await store.buildCombinedPrompt(); // Use in chat loop async function chat(userMessage: string) { const memoryContext = await store.buildCombinedPrompt(); const systemPrompt = `You are a helpful engineering assistant. ${memoryContext}`; const response = await llmProvider.chat({ model: 'gpt-4o', messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: userMessage }, ], }); return response.text; } // Read entrypoint with truncation info const entry = await store.readEntrypoint(); console.log(`Kept ${entry.keptLines}/${entry.originalLines} lines`); console.log(`Truncated: ${entry.wasTruncated}`); // Output: Kept 150/200 lines, Truncated: false ``` -------------------------------- ### Frontmatter Utilities Source: https://context7.com/memel06/mnemonio/llms.txt Functions for parsing and building YAML frontmatter in memory files. ```APIDOC ## POST /parseFrontmatter ### Description Parses a raw string containing YAML frontmatter and returns the structured object and body content. ## POST /buildFrontmatter ### Description Constructs a YAML frontmatter string from a provided object. ``` -------------------------------- ### Set environment variables for CLI Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Configure API keys and provider settings for CLI operations. ```bash export MNEMONIO_API_KEY=your-api-key ``` ```bash # OpenAI export MNEMONIO_BASE_URL=https://api.openai.com/v1 export MNEMONIO_MODEL=gpt-4o # Anthropic export MNEMONIO_BASE_URL=https://api.anthropic.com export MNEMONIO_MODEL=claude-sonnet-4-6-20250514 # OpenRouter (default if MNEMONIO_BASE_URL is not set) export MNEMONIO_MODEL=auto # Override auto-detection if needed export MNEMONIO_PROVIDER=anthropic ``` -------------------------------- ### POST /distill Source: https://context7.com/memel06/mnemonio/llms.txt Runs a consolidation pass on the memory store to merge duplicates, remove obsolete entries, and rewrite the manifest. ```APIDOC ## POST /distill ### Description Runs a consolidation pass that merges duplicates, removes obsolete entries, tightens prose, and rewrites the manifest. Includes time gating and file locking for safety. ### Method POST ### Parameters #### Request Body - **force** (boolean) - Optional - If true, skips the 5-minute cooldown. - **minIdleMs** (number) - Optional - Custom cooldown duration in milliseconds. ### Response #### Success Response (200) - **consolidated** (boolean) - Indicates if consolidation occurred. - **filesModified** (array) - List of modified file names. - **filesRemoved** (array) - List of removed file names. - **reason** (string) - Reason for skipping if consolidated is false. ``` -------------------------------- ### Configure MCP Server for Mnemonio Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Add this JSON to your MCP client settings to enable mnemonio's memory tools. It specifies the command to run mnemonio and sets the memory directory. ```json { "mcpServers": { "mnemonio": { "command": "npx", "args": ["-p", "@memel06/mnemonio", "mnemonio-mcp"], "env": { "MNEMONIO_DIR": "./.mnemonio" } } } } ``` -------------------------------- ### List Memories in Machine-Readable JSON Format Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use the `mnemonio list` command with the `--json` flag for machine-readable output of memory information. ```bash mnemonio list .mnemonio --json ``` -------------------------------- ### Library - Methods (No LLM Required) Source: https://github.com/memel06/mnemonio/blob/main/README.md API reference for Mnemonio library methods that do not require an LLM. ```APIDOC ## Library - Methods (No LLM Required) ### Method Reference | Method | Returns | Description | |---|---|---| | `ensureDir()` | `Promise` | Create memory dir and MANIFEST.md if missing | | `scan(signal?)` | `Promise` | List all memory files with frontmatter metadata | | `readEntrypoint()` | `Promise` | Read MANIFEST.md with truncation info | | `buildPrompt()` | `Promise` | Build memory context string for system prompts | | `buildCombinedPrompt()` | `Promise` | Build prompt including team memory | | `stats(signal?)` | `Promise` | File count, total size, type breakdown, age range | | `formatManifest(headers)` | `string` | Format headers as a human-readable manifest | ``` -------------------------------- ### Initialize Mnemonio Store Programmatically Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Initialize the mnemonio store in your TypeScript project. This creates the memory directory and ensures it exists. ```typescript import { createMnemonioStore } from 'mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio' }); await store.ensureDir(); ``` -------------------------------- ### Mnemonio Configuration Interface Source: https://github.com/memel06/mnemonio/blob/main/README.md TypeScript interface defining the configuration options for creating a Mnemonio store. Includes memory directory path, LLM callback, and other settings. ```typescript interface MnemonioConfig { /** Path to the memory directory */ memoryDir: string; /** Optional path to a shared team memory directory */ teamDir?: string; /** LLM callback -- required for search, extract, distill */ llm?: LlmCallback; /** Name of the entrypoint file (default: "MANIFEST.md") */ entrypointName?: string; /** Max lines to include from MANIFEST.md in prompts (default: 200) */ maxEntrypointLines?: number; /** Max bytes to include from MANIFEST.md in prompts (default: 25000) */ maxEntrypointBytes?: number; /** Optional structured logger */ logger?: (msg: string, level: 'debug' | 'info' | 'warn' | 'error') => void; } ``` -------------------------------- ### Chat Loop with Memory Augmentation Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Build a memory-augmented system prompt using `store.buildPrompt()` and process user messages within a chat loop. Extract memories after each conversation turn using `store.extract()`. ```typescript async function chat(userMessage: string): Promise { // Build the memory-augmented system prompt const memoryContext = await store.buildPrompt(); const systemPrompt = [ 'You are a helpful engineering assistant.', '', memoryContext, ].join('\n'); const response = await yourProvider.chat.create({ model: 'your-preferred-model', max_tokens: 4096, messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: userMessage }, ], }); const assistantText = response.choices[0].message.content; // Extract memories from the conversation await store.extract({ messages: [ { role: 'user', content: userMessage }, { role: 'assistant', content: assistantText }, ], }); return assistantText; } ``` -------------------------------- ### Mnemonio Library with LLM Integration (resolveLlm) Source: https://github.com/memel06/mnemonio/blob/main/README.md Configure the Mnemonio store with an LLM resolved automatically from environment variables (MNEMONIO_API_KEY, MNEMONIO_BASE_URL, etc.). This is the quickest way to enable LLM-dependent features. ```typescript import { createMnemonioStore, resolveLlm } from '@memel06/mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm: resolveLlm(), }); ``` -------------------------------- ### Configure LLM for Mnemonio Tools Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Set environment variables for LLM-dependent tools like memory_search, memory_extract, and memory_distill. This includes API keys and base URLs. ```json { "env": { "MNEMONIO_DIR": "./.mnemonio", "MNEMONIO_API_KEY": "your-api-key", "MNEMONIO_BASE_URL": "https://api.openai.com/v1", "MNEMONIO_MODEL": "gpt-4o" } } ``` -------------------------------- ### Configure Mnemonio store with LLM callback Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Required when using operations like findRelevant, extract, or distill to provide the necessary LLM integration. ```typescript const store = createMnemonioStore({ memoryDir: './.mnemonio', llm: yourLlmCallback, }); ``` -------------------------------- ### CLI Memory Management Source: https://context7.com/memel06/mnemonio/llms.txt Commands for initializing, scanning, listing, searching, and maintaining memory directories via the terminal. ```bash # Install globally npm install -g @memel06/mnemonio # Initialize a memory directory mnemonio init .mnemonio # Output: Created .mnemonio/MANIFEST.md # Scan all memory files mnemonio scan .mnemonio # Output: # directive_testing.md [directive] (2h ago) — Use real DB for tests # identity_role.md [identity] (1d ago) — Backend engineer # List memories, optionally filtered by type mnemonio list .mnemonio --type directive mnemonio list .mnemonio --team-dir ./team-memory mnemonio list .mnemonio --json # Search memories (requires MNEMONIO_API_KEY) export MNEMONIO_API_KEY=sk-... export MNEMONIO_BASE_URL=https://api.openai.com/v1 export MNEMONIO_MODEL=gpt-4o mnemonio search "database testing" .mnemonio # Output: # 87% directive_testing.md # Directly addresses database testing approach # 42% context_auth_rewrite.md # Mentions test infrastructure changes # Get statistics mnemonio stats .mnemonio --team-dir ./team-memory # Output: # Files: 12 # Size: 8.3KB # Types: # identity: 2 # directive: 5 # context: 3 # bookmark: 2 # Run consolidation (requires MNEMONIO_API_KEY) mnemonio distill .mnemonio --force # Prune stale files mnemonio prune .mnemonio --max-age 60 --dry-run mnemonio prune .mnemonio --max-age 60 ``` -------------------------------- ### Display Memory Statistics Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use the 'stats' command to view the number of files, total size, file types, and age of memories in a directory. ```bash mnemonio stats .mnemonio ``` -------------------------------- ### Preview Files to be Pruned Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use the '--dry-run' flag with the 'prune' command to see which files older than a specified age would be removed without actually deleting them. ```bash # Preview what would be removed mnemonio prune .mnemonio --dry-run --max-age 60 ``` -------------------------------- ### Build Combined Prompt from Private and Team Memories Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Generate a combined prompt that includes context from both the private developer memory and the shared team memory directories. ```typescript // Includes both private and team memories const prompt = await store.buildCombinedPrompt(); ``` -------------------------------- ### Add Memory Pointer to MANIFEST.md Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Add a reference to your created memory file in the MANIFEST.md file to include it in the memory manifest. ```markdown # Memory Manifest - [Role](identity_role.md) -- backend engineer, observability team ``` -------------------------------- ### Memory Prompt Generation Source: https://context7.com/memel06/mnemonio/llms.txt Methods for generating memory context strings for system prompts, including automatic truncation to manage token budgets. ```APIDOC ## buildPrompt / buildCombinedPrompt ### Description Generates memory context strings for injection into system prompts. Content is automatically truncated based on configured token budgets. ### Methods - `store.buildPrompt()`: Builds prompt from private memories. - `store.buildCombinedPrompt()`: Builds prompt including team memories. ### Response - **string** - The formatted memory context string. ``` -------------------------------- ### Consolidate Memories with Mnemonio Source: https://context7.com/memel06/mnemonio/llms.txt Use the `distill` method to run a consolidation pass. It merges duplicates, removes obsolete entries, and tightens prose. Includes options for forcing distillation and custom cooldown periods. ```typescript import { createMnemonioStore, resolveLlm } from 'mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm: resolveLlm(), }); // Normal distillation (respects 5-minute cooldown) const result = await store.distill(); if (!result.consolidated) { console.log(`Skipped: ${result.reason}`); // Possible reasons: 'too soon since last distillation', // 'lock held by another process', // 'no memories to consolidate', // 'no changes needed' } else { console.log('Modified:', result.filesModified); console.log('Removed:', result.filesRemoved); } ``` ```typescript // Force distillation, skip cooldown const forced = await store.distill({ force: true }); ``` ```typescript // Custom cooldown (in milliseconds) const custom = await store.distill({ minIdleMs: 10 * 60 * 1000, // 10 minutes }); ``` ```typescript // Manual lock management const lockTime = await store.tryAcquireLock(); if (lockTime === null) { console.log('Lock held by another process'); } ``` ```typescript const lastDistilled = await store.readLastDistilledAt(); console.log(`Last distillation: ${new Date(lastDistilled).toISOString()}`); ``` -------------------------------- ### Parse and Build Frontmatter with Mnemonio Source: https://context7.com/memel06/mnemonio/llms.txt Use `parseFrontmatter` to extract YAML frontmatter and body from memory files, and `buildFrontmatter` to construct frontmatter strings for new memory entries. These functions are useful for custom memory file manipulation. ```typescript import { parseFrontmatter, buildFrontmatter } from 'mnemonio'; // Parse a memory file const rawContent = `--- name: testing-approach description: Team prefers integration tests with real DB type: directive tags: [testing, database] expires: 2024-12-31 --- Always use the real database for integration tests. > reason: Prior incident where mocked tests passed but production broke. > scope: All backend services.`; const { frontmatter, body } = parseFrontmatter(rawContent); console.log(frontmatter); // Output: // { // name: 'testing-approach', // description: 'Team prefers integration tests with real DB', // type: 'directive', // tags: ['testing', 'database'], // expires: '2024-12-31' // } console.log(body); // Output: "Always use the real database..." ``` ```typescript // Build frontmatter for a new memory const fm = buildFrontmatter({ name: 'new-memory', description: 'A new memory entry', type: 'context', tags: ['project', 'timeline'], expires: '2024-06-30', }); console.log(fm); ``` -------------------------------- ### Configure Team Memory in MCP Source: https://github.com/memel06/mnemonio/blob/main/README.md Enable shared team memory by setting the MNEMONIO_TEAM_DIR environment variable in the MCP configuration. ```json { "mcpServers": { "mnemonio": { "command": "npx", "args": ["-p", "@memel06/mnemonio", "mnemonio-mcp"], "env": { "MNEMONIO_DIR": "./.mnemonio", "MNEMONIO_TEAM_DIR": "./team-memory" } } } } ``` -------------------------------- ### Search Memories with Team Directory via CLI Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Perform a semantic search across both private and team memory directories by specifying the '--team-dir' option. ```bash mnemonio search "coding standards" .mnemonio --team-dir ./team-memory ``` -------------------------------- ### Integrate LLM with Custom Callback Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Implement a custom `LlmCallback` function for full control over LLM interactions. This function should accept system prompt, messages, and max tokens, returning the model's text response. ```typescript import { createMnemonioStore, type LlmCallback } from 'mnemonio'; const llm: LlmCallback = async ({ system, messages, maxTokens }) => { const response = await yourProvider.chat.create({ model: 'your-preferred-model', max_tokens: maxTokens, messages: [{ role: 'system', content: system }, ...messages], }); return response.choices[0].message.content; }; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm, }); await store.ensureDir(); ``` -------------------------------- ### Integrate LLM with Built-in Provider Resolution Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use the `resolveLlm` helper to automatically detect and configure the LLM provider based on environment variables. Ensure MNEMONIO_API_KEY, MNEMONIO_BASE_URL, and MNEMONIO_MODEL are set. ```typescript import { createMnemonioStore, resolveLlm } from 'mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm: resolveLlm(), }); await store.ensureDir(); ``` -------------------------------- ### Distill Memory Directory via CLI Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Force a distillation pass using the CLI command, overriding the default time-gating. ```bash mnemonio distill .mnemonio --force ``` -------------------------------- ### Mnemonio Library with Custom LLM Callback Source: https://github.com/memel06/mnemonio/blob/main/README.md Integrate a custom LLM callback function into the Mnemonio store for full control over LLM interactions. This allows using any LLM client or custom logic. ```typescript import { createMnemonioStore, type LlmCallback } from '@memel06/mnemonio'; const llm: LlmCallback = async ({ system, messages, maxTokens }) => { const response = await yourClient.chat({ model: 'your-model', max_tokens: maxTokens, system, messages, }); return response.text; }; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm, }); // Semantic search const results = await store.findRelevant('database testing approach'); // Extract memories from a conversation await store.extract({ messages: [ { role: 'user', content: "Don't mock the database in integration tests." }, { role: 'assistant', content: 'Understood, I will use the real database.' }, ], }); // Consolidate (merge duplicates, prune stale entries) await store.distill({ force: true }); ``` -------------------------------- ### List Memories Including Team Directory Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Use the `mnemonio list` command with the `--team-dir` option to include memories from a specified team memory directory. ```bash mnemonio list .mnemonio --team-dir ./team-memory ``` -------------------------------- ### Add Mnemonio Directory to .gitignore Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Optionally, add the mnemonio memory directory to your .gitignore file if memories should be per-developer and not tracked in version control. ```text .mnemonio/ ``` -------------------------------- ### LLM Required Methods Source: https://github.com/memel06/mnemonio/blob/main/README.md Methods that leverage Large Language Models for memory operations. ```APIDOC ## LLM Required Methods ### `findRelevant(query, opts?)` #### Description Performs a semantic search across memories. #### Method `findRelevant` #### Parameters - **query** (string) - Required - The search query. - **opts** (object) - Optional - Additional options for the search. #### Returns `Promise` - A promise that resolves to an array of relevant memories. ``` ```APIDOC ### `extract(config)` #### Description Extracts memories from a conversation. #### Method `extract` #### Parameters - **config** (object) - Required - Configuration for extraction. #### Returns `Promise` - A promise that resolves to the extraction result. ``` ```APIDOC ### `distill(config?)` #### Description Consolidates memories by merging duplicates and pruning stale entries. #### Method `distill` #### Parameters - **config** (object) - Optional - Configuration for distillation. #### Returns `Promise` - A promise that resolves to the distillation result. ``` -------------------------------- ### Manage Memory Types Source: https://context7.com/memel06/mnemonio/llms.txt Access and parse memory type definitions to understand how different memory categories are structured and used. ```typescript import { MEMORY_TYPES, parseMemoryType, getTypeDefinition, getTypeDefinitions } from 'mnemonio'; // Available types console.log(MEMORY_TYPES); // Output: ['identity', 'directive', 'context', 'bookmark'] // Parse a type string (case-insensitive) const type = parseMemoryType('DIRECTIVE'); console.log(type); // 'directive' const invalid = parseMemoryType('unknown'); console.log(invalid); // undefined // Get definition for a specific type const def = getTypeDefinition('directive'); console.log(def); // Output: // { // name: 'directive', // description: 'Behavioral guidance from the user...', // whenToSave: 'When the user corrects your approach...', // howToUse: "Follow these so the user doesn't repeat themselves.", // bodyStructure: 'State the rule, then add > reason: and > scope: lines', // examples: "user: don't mock the database..." // } // Get all type definitions const allDefs = getTypeDefinitions(); allDefs.forEach(d => { console.log(`${d.name}: ${d.description}`); }); ``` -------------------------------- ### Library - LLM Integration Source: https://github.com/memel06/mnemonio/blob/main/README.md Integrating with Large Language Models (LLMs) for advanced features like search, extraction, and distillation using the Mnemonio library. ```APIDOC ## Library - LLM Integration ### Automatic LLM Resolution The `resolveLlm` helper reads environment variables (`MNEMONIO_API_KEY`, `MNEMONIO_BASE_URL`, `MNEMONIO_MODEL`, `MNEMONIO_PROVIDER`) for automatic provider detection. ```typescript import { createMnemonioStore, resolveLlm } from '@memel06/mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm: resolveLlm(), }); ``` ### Custom LLM Callback For full control, you can provide a custom `LlmCallback`. ```typescript import { createMnemonioStore, type LlmCallback } from '@memel06/mnemonio'; const llm: LlmCallback = async ({ system, messages, maxTokens }) => { const response = await yourClient.chat({ model: 'your-model', max_tokens: maxTokens, system, messages, }); return response.text; }; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm, }); // Semantic search const results = await store.findRelevant('database testing approach'); // Extract memories from a conversation await store.extract({ messages: [ { role: 'user', content: "Don't mock the database in integration tests." }, { role: 'assistant', content: 'Understood, I will use the real database.' }, ], }); // Consolidate (merge duplicates, prune stale entries) await store.distill({ force: true }); ``` ### `LlmCallback` Type Definition ```typescript type LlmCallback = (params: { system: string; messages: ReadonlyArray<{ role: 'user' | 'assistant'; content: string }>; maxTokens: number; }) => Promise; ``` ``` -------------------------------- ### Vercel AI SDK Integration with Mnemonio Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Map Vercel AI SDK messages to Mnemonio's `{ role, content }` format when using a custom LLM callback. Extract memories after the conversation turn. ```typescript import { generateText } from 'ai'; import { createMnemonioStore, type LlmCallback } from 'mnemonio'; const llm: LlmCallback = async ({ system, messages, maxTokens }) => { const result = await generateText({ model: yourModel, maxTokens, system, messages, }); return result.text; }; const store = createMnemonioStore({ memoryDir: './.mnemonio', llm, }); await store.ensureDir(); // In your route handler or server action: async function handleChat(userMessage: string) { const memoryContext = await store.buildPrompt(); const result = await generateText({ model: yourModel, maxTokens: 4096, system: `You are a helpful assistant.\n\n${memoryContext}`, messages: [{ role: 'user', content: userMessage }], }); // Extract memories after the conversation turn await store.extract({ messages: [ { role: 'user', content: userMessage }, { role: 'assistant', content: result.text }, ], }); return result.text; } ``` -------------------------------- ### Access Team Memory via CLI Source: https://github.com/memel06/mnemonio/blob/main/README.md Use the --team-dir flag with CLI commands to interact with shared team memory. ```bash mnemonio list .mnemonio --team-dir ./team-memory mnemonio search "coding standards" .mnemonio --team-dir ./team-memory ``` -------------------------------- ### Distill Memory Directory Source: https://github.com/memel06/mnemonio/blob/main/docs/GUIDE.md Consolidate memory files by merging duplicates, removing obsolete entries, and rewriting MANIFEST.md using the 'distill' function. The result indicates if consolidation occurred and lists modified or removed files. ```typescript const result = await store.distill(); if (result.consolidated) { console.log('Modified:', result.filesModified); console.log('Removed:', result.filesRemoved); } else { console.log('Skipped:', result.reason); } ``` -------------------------------- ### Team Security Source: https://github.com/memel06/mnemonio/blob/main/README.md APIs for managing security within team directories. ```APIDOC ## Team Security ### `validateTeamWritePath(filePath)` #### Description Resolves and validates a file path within the team directory. #### Method `validateTeamWritePath` #### Parameters - **filePath** (string) - Required - The file path to validate. #### Returns `Promise` - A promise that resolves to the validated path. ``` ```APIDOC ### `isTeamPath(filePath)` #### Description Checks if a given file path is inside the team directory. #### Method `isTeamPath` #### Parameters - **filePath** (string) - Required - The file path to check. #### Returns `boolean` - True if the path is within the team directory, false otherwise. ``` -------------------------------- ### Lock Management Source: https://github.com/memel06/mnemonio/blob/main/README.md APIs for managing locks, primarily used for distillation processes. ```APIDOC ## Lock Management ### `readLastDistilledAt()` #### Description Retrieves the timestamp of the last distillation. #### Method `readLastDistilledAt` #### Returns `Promise` - A promise that resolves to the timestamp of the last distillation. ``` ```APIDOC ### `tryAcquireLock()` #### Description Attempts to acquire a distillation lock. Returns null if the lock is already held. #### Method `tryAcquireLock` #### Returns `Promise` - A promise that resolves to the lock timestamp if acquired, or null if the lock is held. ``` ```APIDOC ### `rollbackLock(priorMtime)` #### Description Restores the lock's modification time on failure. #### Method `rollbackLock` #### Parameters - **priorMtime** (number) - Required - The previous modification time of the lock. #### Returns `Promise` - A promise that resolves when the lock is rolled back. ``` -------------------------------- ### Scan Memory Files Source: https://context7.com/memel06/mnemonio/llms.txt Retrieves and formats memory file metadata. The scan method returns headers sorted by modification time, which can then be converted into a manifest string. ```typescript import { createMnemonioStore } from 'mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio' }); const headers = await store.scan(); // Returns: ReadonlyArray for (const h of headers) { console.log(`${h.filename} [${h.type}] - ${h.description}`); console.log(` Path: ${h.filePath}`); console.log(` Modified: ${new Date(h.mtimeMs).toISOString()}`); } // Output: // directive_testing.md [directive] - Use real DB for integration tests // Path: /project/.mnemonio/directive_testing.md // Modified: 2024-01-15T10:30:00.000Z // identity_role.md [identity] - Backend engineer on observability team // Path: /project/.mnemonio/identity_role.md // Modified: 2024-01-14T09:00:00.000Z // Format as manifest const manifest = store.formatManifest(headers); console.log(manifest); // Output: // - directive_testing.md [directive] (2h ago) — Use real DB for integration tests // - identity_role.md [identity] (1d ago) — Backend engineer on observability team ``` -------------------------------- ### Mnemonio LlmCallback Type Definition Source: https://github.com/memel06/mnemonio/blob/main/README.md Defines the signature for a custom LLM callback function used by the Mnemonio library. It accepts system messages, conversation history, and max tokens, returning the LLM's response as a string. ```typescript type LlmCallback = (params: { system: string; messages: ReadonlyArray<{ role: 'user' | 'assistant'; content: string }>; maxTokens: number; }) => Promise; ``` -------------------------------- ### Validate Team Memory Paths Source: https://context7.com/memel06/mnemonio/llms.txt Use these utilities to ensure file operations remain within designated team directories and prevent path traversal attacks. ```typescript import { createMnemonioStore, validateTeamPath, isTeamPath, PathTraversalError } from 'mnemonio'; const store = createMnemonioStore({ memoryDir: './.mnemonio', teamDir: './team-memory', }); // Check if a path is within the team directory const isTeam = store.isTeamPath('./team-memory/standards.md'); console.log(isTeam); // true // Validate a path for team writes (throws on traversal attempt) try { const safePath = await store.validateTeamWritePath('notes/standup.md'); console.log(`Safe to write: ${safePath}`); } catch (err) { if (err instanceof PathTraversalError) { console.error('Path traversal blocked:', err.message); } } // Blocked patterns: // - '../' segments that escape the directory // - Absolute paths outside the directory // - Symlinks resolving outside the directory // - Null bytes in paths // Low-level validation import { validateTeamPath as validatePath } from 'mnemonio'; const validated = await validatePath('./team-memory', 'docs/guide.md'); // Returns resolved absolute path or throws PathTraversalError ```