### Install Dependencies and Build Project Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Standard npm commands to install project dependencies and build the plugin for production or development with watch mode. ```bash # Install dependencies npm install # Build for production npm run build # Watch mode for development npm run dev ``` -------------------------------- ### Local Development Installation Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Instructions for cloning, building, and installing the plugin locally using a file path in your `opencode.jsonc` configuration. This bypasses npm publishing. ```bash # Clone and build git clone https://github.com/mark-hingston/opencode-elf.git cd opencode-elf npm install npm run build # Add to your opencode.jsonc using local path { "plugin": ["file:///absolute/path/to/opencode-elf"] } ``` -------------------------------- ### Agent Tool - Metrics Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Example of invoking the 'metrics' mode of the ELF agent tool to view performance metrics. ```shell "metrics" ``` -------------------------------- ### Verify Installation with Simulation Test Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Run this command to verify that the plugin is installed correctly and all components are functioning as expected. It simulates various scenarios including context injection and learning retrieval. ```bash npm run test:simulate ``` -------------------------------- ### Agent Tool - List Heuristics Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Example of invoking the 'list-heuristics' mode of the ELF agent tool to retrieve heuristics, with an option to specify scope. ```shell "list-heuristics" ``` -------------------------------- ### Context Injection Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Demonstrates how context injection displays both global and project-specific memories, with project memories clearly tagged. ```text Golden Rules: - Always validate user inputs - This API requires JWT authentication [project] ``` -------------------------------- ### Agent Tool - List Learnings Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Example of using the 'list-learnings' mode for the ELF agent tool to view recent learnings, with optional parameters for limit and scope. ```shell "List all learnings from this project" ``` -------------------------------- ### Agent Tool - Search Learnings Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Example of using the 'search' mode for the ELF agent tool to perform a hybrid search across learnings, requiring a query and optionally a limit. ```shell "Search learnings for error code ENOENT" ``` -------------------------------- ### Run Performance Benchmark Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Execute the performance benchmark tests for the project. Ensure all dependencies are installed before running. ```bash npm run test:benchmark ``` -------------------------------- ### Agent Tool - Add Heuristic Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Example of using the 'add-heuristic' mode for the ELF agent tool to add a new heuristic pattern, with an option for scope. ```shell "add-heuristic" ``` -------------------------------- ### Install OpenCode ELF Plugin Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Configuration snippet for `opencode.jsonc` to install the OpenCode ELF plugin using the latest version. Ensure OpenCode is restarted after adding this configuration. ```jsonc // opencode.jsonc { "plugin": ["opencode-elf@latest"] } ``` -------------------------------- ### Context Injection Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Illustrates the context injected into the system prompt before each message, including golden rules, past experiences, and heuristics. ```text [ELF MEMORY] Golden Rules: - Always validate user inputs before processing - Use TypeScript strict mode for type safety - This project requires JWT authentication [project] Relevant Past Experiences: ✗ [85%] Tool 'bash' failed: command not found - npm ✗ [78%] API authentication failed without JWT token [project] Applicable Heuristics: - When working with npm, always check if node_modules exists ``` -------------------------------- ### Agent Tool - List Rules Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Example of invoking the 'list-rules' mode of the ELF agent tool to retrieve golden rules, with an option to specify scope. ```shell "Show me project-specific golden rules" ``` -------------------------------- ### Agent Tool - Add Rule Example Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Example of using the 'add-rule' mode for the ELF agent tool to add a new golden rule, with options for global or project scope. ```shell "Add a global rule: Always use async/await" ``` ```shell "Add a project rule: This API requires authentication tokens" ``` -------------------------------- ### Example Usage of ELF Slash Commands Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Once configured, use these slash commands in OpenCode to interact with the ELF plugin for quick inspection and management. ```text /elf ``` ```text /elf rules list ``` ```text /elf search "error code 503" ``` ```text /elf metrics ``` -------------------------------- ### Query Database Directly Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Use the `sqlite3` command-line tool to query the plugin's database. This example shows how to select all entries from the `golden_rules` table. ```bash sqlite3 ~/.opencode/elf/memory.db "SELECT * FROM golden_rules" ``` -------------------------------- ### Get Context with QueryService Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieve relevant context for a user prompt, including golden rules, learnings, and heuristics. Initialize with a project path. ```typescript import { QueryService } from "./services/query.js"; const queryService = new QueryService("/path/to/project"); // Get context for a user message const context = await queryService.getContext("How do I fix npm install errors?"); ``` ```json { "goldenRules": [ { "id": "a1b2c3d4", "content": "Always validate user inputs before processing", "embedding": [0.123, -0.456, ...], "created_at": 1705312200000, "hit_count": 42, "scope": "global" } ], "relevantLearnings": [ { "item": { "id": "e5f67890", "content": "Tool 'bash' failed running 'npm install': ENOENT", "category": "failure", "embedding": [0.234, -0.567, ...], "created_at": 1705852500000, "context_hash": "abc123", "utility_score": 0.9, "scope": "project" }, "score": 0.87 } ], "heuristics": [ { "id": "c3d4e5f6", "pattern": "npm install", "suggestion": "Ensure package.json exists before running npm install", "created_at": 1704873600000, "scope": "global" } ] } ``` ```typescript // Format context for injection into system prompt const elfMemory = queryService.formatContextForPrompt(context); ``` ```plaintext // Output: // [ELF MEMORY] // // Golden Rules: // - Always validate user inputs before processing // // Relevant Past Experiences: // ✗ [87%] Tool 'bash' failed running 'npm install': ENOENT [project] // // Applicable Heuristics: // - Ensure package.json exists before running npm install ``` -------------------------------- ### Search Learnings with Hybrid Search Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Examples of using the elf tool for hybrid search, combining semantic and keyword matching to find relevant learnings. ```shell "Search my learnings for error code ENOENT" ``` ```shell "Find learnings about authentication failures" ``` -------------------------------- ### QueryService - Get Context Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieves relevant context for a user prompt, including golden rules, learnings, and heuristics. Also provides a method to format this context for system prompts. ```APIDOC ## QueryService - Get Context ### Description Core service method that retrieves relevant context for a user prompt, including golden rules, learnings, and heuristics. ### Method `getContext` and `formatContextForPrompt` methods of the `QueryService` class. ### Endpoint N/A (Class method invocation) ### Parameters #### `getContext` Method Parameters - **userPrompt** (string) - Required - The user's input prompt. #### `QueryService` Constructor Parameters - **projectPath** (string) - Required - The path to the project directory. ### Request Example (getContext) ```typescript import { QueryService } from "./services/query.js"; const queryService = new QueryService("/path/to/project"); const context = await queryService.getContext("How do I fix npm install errors?"); ``` ### Response (getContext) #### Success Response Returns an `ELFContext` object containing: - **goldenRules** (array) - List of golden rules relevant to the prompt. - **id** (string) - Unique identifier. - **content** (string) - Rule description. - **embedding** (array) - Vector embedding of the rule. - **created_at** (number) - Timestamp (milliseconds). - **hit_count** (integer) - Number of times this rule was applied. - **scope** (string) - Scope of the rule (e.g., "global"). - **relevantLearnings** (array) - List of relevant past learnings. - **item** (object) - The learning object itself. - **id** (string) - Unique identifier. - **content** (string) - Learning description. - **category** (string) - 'success' or 'failure'. - **embedding** (array) - Vector embedding. - **created_at** (number) - Timestamp (milliseconds). - **context_hash** (string) - Hash of the context. - **utility_score** (number) - Score indicating usefulness. - **scope** (string) - Scope of the learning. - **score** (number) - Relevance score of the learning. - **heuristics** (array) - List of applicable heuristics. - **id** (string) - Unique identifier. - **pattern** (string) - Pattern the heuristic applies to. - **suggestion** (string) - Suggested action. - **created_at** (number) - Timestamp (milliseconds). - **scope** (string) - Scope of the heuristic. #### Response Example (getContext) ```json { "goldenRules": [ { "id": "a1b2c3d4", "content": "Always validate user inputs before processing", "embedding": [0.123, -0.456, ...], "created_at": 1705312200000, "hit_count": 42, "scope": "global" } ], "relevantLearnings": [ { "item": { "id": "e5f67890", "content": "Tool 'bash' failed running 'npm install': ENOENT", "category": "failure", "embedding": [0.234, -0.567, ...], "created_at": 1705852500000, "context_hash": "abc123", "utility_score": 0.9, "scope": "project" }, "score": 0.87 } ], "heuristics": [ { "id": "c3d4e5f6", "pattern": "npm install", "suggestion": "Ensure package.json exists before running npm install", "created_at": 1704873600000, "scope": "global" } ] } ``` ### Request Example (formatContextForPrompt) ```typescript const elfMemory = queryService.formatContextForPrompt(context); ``` ### Response (formatContextForPrompt) Returns a formatted string suitable for injection into a system prompt. #### Response Example ```text [ELF MEMORY] Golden Rules: - Always validate user inputs before processing Relevant Past Experiences: ✗ [87%] Tool 'bash' failed running 'npm install': ENOENT [project] Applicable Heuristics: - Ensure package.json exists before running npm install ``` ``` -------------------------------- ### Build Project Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Compile and build the project. This step is necessary after making changes and before committing them. ```bash npm run build ``` -------------------------------- ### View All Learnings Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Display all recorded learnings. This command provides a comprehensive view of the system's learned data. ```bash npm run learnings:view ``` -------------------------------- ### Add Global and Project Rules Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Use these commands to add global rules that apply to all projects or project-specific rules. Project rules are prioritized. ```shell "Add a global rule: Always validate user inputs" ``` ```shell "Add a project rule: This API requires JWT authentication" ``` -------------------------------- ### List Heuristics Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Use this command to list all currently defined heuristics within the system. ```bash npm run heuristics:list ``` -------------------------------- ### Run Project Tests Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Execute various test suites for the OpenCode Elf plugin, including end-to-end simulations, hybrid storage tests, and performance benchmarks. ```bash # Run end-to-end simulation npm run test:simulate # Test hybrid storage functionality npm run test:hybrid # Run performance benchmarks npm run test:benchmark ``` -------------------------------- ### CLI Command for Viewing Performance Metrics Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Monitor the performance and usage of the ELF plugin by running this npm script. It provides insights into latency, injection counts, and failures. ```bash npm run metrics:view ``` -------------------------------- ### ELF Tool - List Heuristics Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Lists all pattern-based heuristics that trigger suggestions when matched against user prompts. ```APIDOC ## ELF Tool - List Heuristics ### Description List all pattern-based heuristics that trigger suggestions when matched against user prompts. ### Method `elf({ mode: "heuristics-list", scope: "global" | "project" | undefined }) ### Parameters #### Query Parameters - **mode** (string) - Required - The operation mode, must be "heuristics-list". - **scope** (string) - Optional - The scope of the heuristics to list. Can be "global" or "project". If omitted, both scopes are considered. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **heuristics** (array) - An array of heuristic objects. - **id** (string) - The unique identifier for the heuristic. - **pattern** (string) - The regex pattern to match against user prompts. - **suggestion** (string) - The suggestion to provide when the pattern is matched. - **created** (string) - The timestamp when the heuristic was created (ISO 8601 format). - **scope** (string) - The scope of the heuristic ("global" or "project"). - **count** (integer) - The total number of heuristics returned. ### Response Example ```json { "success": true, "heuristics": [ { "id": "c3d4e5f678901234", "pattern": "npm install", "suggestion": "Ensure package.json exists before running npm install", "created": "2024-01-10T08:00:00.000Z", "scope": "global" }, { "id": "d4e5f67890123456", "pattern": "git push.*rejected", "suggestion": "Pull latest changes with 'git pull' before pushing", "created": "2024-01-10T08:00:00.000Z", "scope": "global" } ], "count": 2 } ``` ``` -------------------------------- ### Find Emergent Patterns with ConsolidationService Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Employ ConsolidationService to detect clusters of similar learnings, which can then be promoted to golden rules. This involves specifying a similarity threshold and a minimum count for cluster formation. ```typescript import { ConsolidationService } from "./services/consolidation.js"; const consolidation = new ConsolidationService("/path/to/project"); // Find clusters of similar learnings const clusters = await consolidation.findEmergentPatterns( 0.85, // similarity threshold (default: 0.85) 3 // minimum count to form cluster (default: 3) ); // Each cluster contains similar learnings clusters.forEach(cluster => { console.log(`Cluster with ${cluster.ids.length} learnings:`); cluster.content.forEach(c => console.log(` - ${c}`)); }); // Promote a cluster to a new golden rule if (clusters.length > 0) { const newRule = await consolidation.promoteToRule( clusters[0], "project" // scope: "global" | "project" ); console.log(`Created rule: ${newRule}`); } ``` -------------------------------- ### CLI Commands for Viewing Learnings Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Access recorded successes and failures in the ELF plugin's memory using these npm scripts. You can view all learnings or filter by success or failure. ```bash # View all learnings npm run learnings:view ``` ```bash # View only failures npm run learnings:view failure ``` ```bash # View only successes npm run learnings:view success ``` -------------------------------- ### Configure Query and Performance Settings Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Adjust these constants in `src/config.ts` to control query limits and relevance thresholds. Ensure to rebuild the project after changes. ```typescript // Query limits export const MAX_GOLDEN_RULES = 5; // Max rules to inject per message export const MAX_RELEVANT_LEARNINGS = 10; // Max learnings to inject export const SIMILARITY_THRESHOLD = 0.7; // Min similarity for relevance // Embedding model export const EMBEDDING_MODEL = "Xenova/all-MiniLM-L6-v2"; // Hybrid storage export const ENABLE_HYBRID_STORAGE = true; // Enable project-scoped memories ``` -------------------------------- ### Test Hybrid Storage Functionality Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Run tests specifically designed to validate the hybrid storage capabilities of the plugin. ```bash npm run test:hybrid ``` -------------------------------- ### Configure OpenCode for ELF Slash Commands Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Add slash commands to your OpenCode configuration file to quickly access ELF functionalities. This requires modifying `opencode.jsonc` or `~/.config/opencode/opencode.jsonc`. ```jsonc // opencode.jsonc or ~/.config/opencode/opencode.jsonc { "plugin": ["opencode-elf@latest"], "command": { "elf": { "template": "Use the elf tool. Arguments: $ARGUMENTS", "description": "ELF memory system. Commands: rules list, heuristics list, learnings list, search, metrics, rules add, heuristics add" } } } ``` -------------------------------- ### Natural Language Commands for Data Management Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Interact with the ELF plugin using natural language prompts to manage golden rules, heuristics, and learnings. This is the recommended method for everyday use. ```text "Add a golden rule: Always use async/await instead of callbacks" ``` ```text "Add a project-specific rule: This API requires JWT authentication" ``` ```text "Show me my current golden rules" ``` ```text "Show me project-specific learnings" ``` ```text "Add a heuristic for npm errors" ``` ```text "What have I learned recently?" ``` -------------------------------- ### Direct Database Access with DB Client Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Access the database directly for advanced queries and custom operations using the provided DB client. This includes initializing the database, checking if it's empty, and executing custom SQL queries. ```typescript import { getDbClient, initDatabase, isDatabaseEmpty } from "./db/client.js"; import { GLOBAL_DB_PATH, getDbPaths } from "./config.js"; // Get database paths const paths = getDbPaths("/path/to/project"); // { global: "~/.opencode/elf/memory.db", project: "/path/to/project/.opencode/elf/memory.db" } // Initialize database with schema await initDatabase(GLOBAL_DB_PATH); // Check if database needs seeding const isEmpty = await isDatabaseEmpty(GLOBAL_DB_PATH); // Get database client for direct queries const db = getDbClient(GLOBAL_DB_PATH); // Execute custom queries const result = await db.execute({ sql: "SELECT * FROM learnings WHERE category = ? ORDER BY created_at DESC LIMIT ?", args: ["failure", 10] }); result.rows.forEach(row => { console.log(`${row.category}: ${row.content}`); }); ``` -------------------------------- ### Manage Heuristics via CLI Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Command-line interface commands for managing pattern-based heuristics. Allows adding new heuristics by specifying a pattern and a corresponding suggestion. ```bash # Add a new heuristic (pattern + suggestion) npm run heuristics:add "npm install" "Check package.json exists first" ``` -------------------------------- ### CLI Commands for Managing Heuristics Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Manage heuristics using npm scripts, which allows adding new pattern-based suggestions, listing them, and re-seeding defaults. ```bash # Add a new heuristic npm run heuristics:add "npm install" "Check package.json exists first" ``` ```bash # List all heuristics npm run heuristics:list ``` ```bash # Re-seed default heuristics (if you deleted them) npm run heuristics:seed ``` -------------------------------- ### Preview Data Cleanup Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Perform a dry run of the data cleanup process to see what expired data would be deleted without actually removing it. ```bash npm run cleanup:preview ``` -------------------------------- ### Configure OpenCode ELF Plugin Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Add the ELF plugin to your OpenCode configuration file to enable its functionality. ```jsonc // opencode.jsonc { "plugin": ["opencode-elf@latest"], "command": { "elf": { "template": "Use the elf tool. Arguments: $ARGUMENTS", "description": "ELF memory system. Commands: rules list, heuristics list, learnings list, search, metrics, rules add, heuristics add" } } } ``` -------------------------------- ### Manage Golden Rules via CLI Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Command-line interface commands for managing golden rules. Includes options to add new rules, list existing rules, and re-seed default rules. ```bash # Add a new golden rule npm run rules:add "Always validate user inputs before processing" # List all golden rules npm run rules:list # Re-seed default rules npm run rules:seed ``` -------------------------------- ### List Heuristics via ELF Tool Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieve all pattern-based heuristics that trigger suggestions when matched against user prompts. You can optionally filter by scope. ```typescript // Via agent tool invocation const result = await elf({ mode: "heuristics-list", scope: "project" // optional: filter by scope }); // Response: { "success": true, "heuristics": [ { "id": "c3d4e5f678901234", "pattern": "npm install", "suggestion": "Ensure package.json exists before running npm install", "created": "2024-01-10T08:00:00.000Z", "scope": "global" }, { "id": "d4e5f67890123456", "pattern": "git push.*rejected", "suggestion": "Pull latest changes with 'git pull' before pushing", "created": "2024-01-10T08:00:00.000Z", "scope": "global" } ], "count": 2 } ``` -------------------------------- ### CLI Commands for Managing Golden Rules Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Use these npm scripts for advanced management of golden rules, including adding new rules, listing existing ones, and re-seeding defaults. ```bash # Add a new rule npm run rules:add "Always validate inputs before processing" ``` ```bash # List all rules npm run rules:list ``` ```bash # Re-seed default rules (if you deleted them) npm run rules:seed ``` -------------------------------- ### ELF Tool - View Metrics Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieves performance metrics, including injection counts, latency statistics, and learning failure rates. ```APIDOC ## ELF Tool - View Metrics ### Description View performance metrics including latency, injection counts, and failure statistics. ### Method Not explicitly defined, but implied as an invocation of the `elf` tool with `mode: "metrics"`. ### Endpoint N/A (Tool invocation) ### Parameters This endpoint does not accept any parameters. ### Request Example ```typescript const result = await elf({ mode: "metrics" }); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **metrics** (array) - A list of metric objects. - **type** (string) - The type of metric (e.g., "injection", "latency", "learning_failure"). - **count** (integer) - The total count for this metric type. - **average** (number) - The average value for this metric. - **min** (number) - The minimum value recorded for this metric. - **max** (number) - The maximum value recorded for this metric. #### Response Example ```json { "success": true, "metrics": [ { "type": "injection", "count": 156, "average": 1, "min": 1, "max": 1 }, { "type": "latency", "count": 156, "average": 245.5, "min": 102, "max": 512 }, { "type": "learning_failure", "count": 23, "average": 1, "min": 1, "max": 1 } ] } ``` ``` -------------------------------- ### Record Learnings with QueryService Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Use QueryService to record new learnings from tool executions. It automatically handles deduplication and privacy filtering. Learnings can be categorized as 'failure' or 'success' with associated context and utility scores. ```typescript import { QueryService } from "./services/query.js"; const queryService = new QueryService("/path/to/project"); // Record a failure learning await queryService.recordLearning( "Tool 'bash' failed running 'git push': rejected, remote contains work", "failure", JSON.stringify({ args: { command: "git push" }, result: { stderr: "rejected" } }), "project", // scope: "global" | "project" 1.0 // initial utility score ); // Record a success learning await queryService.recordLearning( "Tool 'bash' succeeded running 'npm run build'", "success", JSON.stringify({ args: { command: "npm run build" }, result: { exitCode: 0 } }), "project" ); // Privacy: Content with tags is automatically filtered await queryService.recordLearning( "API key is sk-abc123", "failure", "context", "project" ); // Result: Learning is skipped due to private tag ``` -------------------------------- ### Configuration Options for OpenCode ELF Source: https://context7.com/mark-hingston/opencode-elf/llms.txt TypeScript configuration constants for customizing storage paths, hybrid storage, embedding models, query limits, and expiration settings. ```typescript // Storage paths export const GLOBAL_ELF_DIR = join(homedir(), ".opencode", "elf"); export const GLOBAL_DB_PATH = join(GLOBAL_ELF_DIR, "memory.db"); // Enable/disable hybrid (global + project) storage export const ENABLE_HYBRID_STORAGE = true; // Embedding model configuration export const EMBEDDING_MODEL = "Xenova/all-MiniLM-L6-v2"; export const EMBEDDING_DIM = 384; // Query limits export const MAX_GOLDEN_RULES = 5; // Max rules injected per message export const MAX_RELEVANT_LEARNINGS = 10; // Max learnings injected export const SIMILARITY_THRESHOLD = 0.7; // Min cosine similarity for relevance // Expiration settings export const RULE_EXPIRATION_DAYS = 90; // Delete unused rules after 90 days export const RULE_MIN_HITS_TO_KEEP = 1; // Rules with 0 hits are candidates export const LEARNING_EXPIRATION_DAYS = 60; // Delete learnings after 60 days export const HEURISTIC_EXPIRATION_DAYS = 180; // Delete heuristics after 180 days export const AUTO_CLEANUP_ENABLED = true; // Enable automatic cleanup ``` -------------------------------- ### OpenCode ELF Plugin Architecture Diagram Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Visual representation of the OpenCode ELF plugin's components and data flow, including initialization, hooks, consolidation, storage, and embeddings. ```text ┌──────────────────────────────────────────────────────┐ │ OpenCode ELF Plugin │ ├──────────────────────────────────────────────────────┤ │ │ │ Initialization: LAZY LOADING │ │ ┌────────────────────────────────────────────────┐ │ │ │ Background: DB init + Model load + Seeding │ │ │ │ Returns hooks immediately (non-blocking) │ │ │ │ First interaction waits for init completion │ │ │ └────────────────────────────────────────────────┘ │ │ │ │ Hooks: │ │ ┌─────────────────┐ ┌────────────────────┐ │ │ │ chat.params │─────▶│ Context Injection │ │ │ │ (pre-LLM) │ │ - Golden Rules │ │ │ │ │ │ - Past Learnings │ │ │ │ │ │ - Heuristics │ │ │ └─────────────────┘ └────────────────────┘ │ │ │ │ ┌─────────────────┐ ┌────────────────────┐ │ │ │ event │─────▶│ Learning Loop │ │ │ │ (post-tool) │ │ - Record failures │ │ │ │ │ │ - Record successes │ │ │ │ │ │ - Utility Feedback │ │ │ └─────────────────┘ └────────────────────┘ │ │ │ │ Consolidation: │ │ ┌─────────────────┐ ┌────────────────────┐ │ │ │ Emergence Loop │─────▶│ Memory Promotion │ │ │ │ (Periodic) │ │ Cluster Learnings │ │ │ └─────────────────┘ └────────────────────┘ │ │ │ │ Storage: │ │ ┌──────────────────────────────────────────────┐ │ │ │ libsql (SQLite) │ │ │ │ ~/.opencode/elf/memory.db │ │ │ └──────────────────────────────────────────────┘ │ │ │ │ Embeddings: │ │ ┌──────────────────────────────────────────────┐ │ │ │ @xenova/transformers │ │ │ │ Model: Xenova/all-MiniLM-L6-v2 │ │ │ └──────────────────────────────────────────────┘ │ │ │ └──────────────────────────────────────────────────────┘ ``` -------------------------------- ### List Learnings with ELF Tool Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieve recent successes and failures from tool executions. Optional parameters include 'limit' and 'scope'. ```typescript const result = await elf({ mode: "learnings-list", limit: 10, // optional: defaults to 20 scope: "project" // optional: filter by scope }); ``` ```json { "success": true, "learnings": [ { "id": "e5f6789012345678", "category": "failure", "content": "Tool 'bash' failed running 'npm install': ENOENT: no such file or directory, package.json", "created": "2024-01-21T16:45:00.000Z", "scope": "project" }, { "id": "f67890123456789a", "category": "success", "content": "Tool 'bash' succeeded running 'npm run build'", "created": "2024-01-21T16:50:00.000Z", "scope": "project" } ], "count": 2 } ``` -------------------------------- ### Configure Data Expiration Settings Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Customize the data retention policies for golden rules, learnings, and heuristics by editing the configuration file. Ensure to rebuild the project after changes. ```typescript export const RULE_EXPIRATION_DAYS = 90; // Delete unused rules export const RULE_MIN_HITS_TO_KEEP = 1; // Rules with < 1 hits export const LEARNING_EXPIRATION_DAYS = 60; // Delete old learnings export const HEURISTIC_EXPIRATION_DAYS = 180; // Delete old heuristics export const AUTO_CLEANUP_ENABLED = true; // Enable/disable auto-cleanup ``` -------------------------------- ### Test Feature Parity Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Run tests to ensure feature parity across different environments or versions. ```bash npm run test:parity ``` -------------------------------- ### Hybrid Search Learnings with ELF Tool Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Perform a search across learnings using a combination of semantic and keyword matching. An optional 'limit' parameter can be set. ```typescript const result = await elf({ mode: "search", query: "error code ENOENT", limit: 5 // optional: defaults to 10 }); ``` ```json { "success": true, "query": "error code ENOENT", "count": 3, "results": [ { "id": "e5f6789012345678", "content": "Tool 'bash' failed running 'npm install': ENOENT: no such file or directory", "category": "failure", "score": 0.923, "matchType": "hybrid", // "semantic" | "keyword" | "hybrid" "scope": "project", "created": "2024-01-21T16:45:00.000Z" }, { "id": "789012345678abcd", "content": "File not found error when accessing config.json", "category": "failure", "score": 0.812, "matchType": "semantic", "scope": "global", "created": "2024-01-20T10:30:00.000Z" } ] } ``` -------------------------------- ### CLI Commands for Manual Data Cleanup Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Perform manual cleanup of expired data within the ELF plugin's database. Use `cleanup:preview` to see what would be deleted before running `cleanup:clean`. ```bash # Preview what would be deleted npm run cleanup:preview ``` ```bash # Delete expired data npm run cleanup:clean ``` -------------------------------- ### List Golden Rules via ELF Tool Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieve all golden rules from global and/or project-scoped databases. The response includes hit counts and creation timestamps for each rule. ```typescript // Via agent tool invocation const result = await elf({ mode: "rules-list", scope: "global" // optional: "global" | "project" | undefined (both) }); // Response: { "success": true, "rules": [ { "id": "a1b2c3d4e5f67890", "content": "Always validate user inputs before processing", "hitCount": 42, "created": "2024-01-15T10:30:00.000Z", "scope": "global" }, { "id": "b2c3d4e5f6789012", "content": "This API requires JWT authentication", "hitCount": 15, "created": "2024-01-20T14:22:00.000Z", "scope": "project" } ], "count": 2 } ``` -------------------------------- ### View Metrics with ELF Tool Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieve performance metrics including injection counts, latency, and failure statistics. This function requires no parameters. ```typescript const result = await elf({ mode: "metrics" }); ``` ```json { "success": true, "metrics": [ { "type": "injection", "count": 156, "average": 1, "min": 1, "max": 1 }, { "type": "latency", "count": 156, "average": 245.5, "min": 102, "max": 512 }, { "type": "learning_failure", "count": 23, "average": 1, "min": 1, "max": 1 } ] } ``` -------------------------------- ### Seed Default Heuristics Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Re-seed the system with default heuristics. This is useful for resetting or initializing heuristics. ```bash npm run heuristics:seed ``` -------------------------------- ### Reset All Plugin Data Source: https://github.com/mark-hingston/opencode-elf/blob/main/README.md Remove all stored data for the OpenCode Elf plugin by recursively deleting the configuration directory. Use with caution. ```bash rm -rf ~/.opencode/elf/ ``` -------------------------------- ### ELF Tool - List Learnings Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Retrieves a list of recent successes and failures recorded from tool executions. Supports optional limit and scope filtering. ```APIDOC ## ELF Tool - List Learnings ### Description View recent learnings (successes and failures) recorded from tool executions. ### Method Not explicitly defined, but implied as an invocation of the `elf` tool with `mode: "learnings-list"`. ### Endpoint N/A (Tool invocation) ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of learnings to return. Defaults to 20. - **scope** (string) - Optional - Filters learnings by scope (e.g., "project"). ### Request Example ```typescript const result = await elf({ mode: "learnings-list", limit: 10, scope: "project" }); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **learnings** (array) - A list of learning objects. - **id** (string) - Unique identifier for the learning. - **category** (string) - Type of learning ('success' or 'failure'). - **content** (string) - Detailed description of the learning. - **created** (string) - Timestamp of when the learning was recorded (ISO 8601 format). - **scope** (string) - The scope associated with the learning. - **count** (integer) - The total number of learnings returned. #### Response Example ```json { "success": true, "learnings": [ { "id": "e5f6789012345678", "category": "failure", "content": "Tool 'bash' failed running 'npm install': ENOENT: no such file or directory, package.json", "created": "2024-01-21T16:45:00.000Z", "scope": "project" }, { "id": "f67890123456789a", "category": "success", "content": "Tool 'bash' succeeded running 'npm run build'", "created": "2024-01-21T16:50:00.000Z", "scope": "project" } ], "count": 2 } ``` ``` -------------------------------- ### ELF Tool - Add Heuristic Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Adds a new regex-based heuristic pattern with an associated suggestion. ```APIDOC ## ELF Tool - Add Heuristic ### Description Add a new regex-based heuristic pattern with an associated suggestion. ### Method `elf({ mode: "heuristics-add", pattern: string, suggestion: string, scope: "global" | "project" }) ### Parameters #### Request Body - **mode** (string) - Required - The operation mode, must be "heuristics-add". - **pattern** (string) - Required - The regex pattern to match. - **suggestion** (string) - Required - The suggestion to provide when the pattern is matched. - **scope** (string) - Optional - The scope for the new heuristic. Defaults to "global". Can be "global" or "project". ### Request Example ```typescript // Via agent tool invocation const result = await elf({ mode: "heuristics-add", pattern: "docker.*not found", suggestion: "Ensure Docker daemon is running with 'docker ps'", scope: "global" // optional: defaults to "global" }); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A confirmation message. - **pattern** (string) - The added regex pattern. - **suggestion** (string) - The added suggestion. - **scope** (string) - The scope where the heuristic was added. ### Response Example ```json { "success": true, "message": "Heuristic added successfully to global scope", "pattern": "docker.*not found", "suggestion": "Ensure Docker daemon is running with 'docker ps'", "scope": "global" } ``` ``` -------------------------------- ### View Specific Learnings Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Filter and view learnings based on their status, such as 'failure' or 'success'. ```bash npm run learnings:view failure ``` ```bash npm run learnings:view success ``` -------------------------------- ### ELF Tool - List Golden Rules Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Lists all golden rules from global and/or project-scoped databases, including hit counts and creation timestamps. ```APIDOC ## ELF Tool - List Golden Rules ### Description List all golden rules from global and/or project-scoped databases with hit counts and creation timestamps. ### Method `elf({ mode: "rules-list", scope: "global" | "project" | undefined }) ### Parameters #### Query Parameters - **mode** (string) - Required - The operation mode, must be "rules-list". - **scope** (string) - Optional - The scope of the rules to list. Can be "global" or "project". If omitted, both scopes are considered. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **rules** (array) - An array of golden rule objects. - **id** (string) - The unique identifier for the rule. - **content** (string) - The content of the golden rule. - **hitCount** (integer) - The number of times this rule has been hit. - **created** (string) - The timestamp when the rule was created (ISO 8601 format). - **scope** (string) - The scope of the rule ("global" or "project"). - **count** (integer) - The total number of rules returned. ### Response Example ```json { "success": true, "rules": [ { "id": "a1b2c3d4e5f67890", "content": "Always validate user inputs before processing", "hitCount": 42, "created": "2024-01-15T10:30:00.000Z", "scope": "global" }, { "id": "b2c3d4e5f6789012", "content": "This API requires JWT authentication", "hitCount": 15, "created": "2024-01-20T14:22:00.000Z", "scope": "project" } ], "count": 2 } ``` ``` -------------------------------- ### ELF Tool - Hybrid Search Learnings Source: https://context7.com/mark-hingston/opencode-elf/llms.txt Performs a search across learnings using a combination of semantic and keyword matching. Supports optional limit filtering. ```APIDOC ## ELF Tool - Hybrid Search ### Description Search learnings using combined vector (semantic) and FTS5 (keyword) search for best results. ### Method Not explicitly defined, but implied as an invocation of the `elf` tool with `mode: "search"`. ### Endpoint N/A (Tool invocation) ### Parameters #### Query Parameters - **query** (string) - Required - The search query string. - **limit** (integer) - Optional - The maximum number of results to return. Defaults to 10. ### Request Example ```typescript const result = await elf({ mode: "search", query: "error code ENOENT", limit: 5 }); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **query** (string) - The original search query. - **count** (integer) - The total number of results found. - **results** (array) - A list of search result objects. - **id** (string) - Unique identifier for the learning. - **content** (string) - The content of the learning that matched the query. - **category** (string) - Type of learning ('success' or 'failure'). - **score** (number) - Relevance score of the result (0.0 to 1.0). - **matchType** (string) - The type of match ('semantic', 'keyword', or 'hybrid'). - **scope** (string) - The scope associated with the learning. - **created** (string) - Timestamp of when the learning was recorded (ISO 8601 format). #### Response Example ```json { "success": true, "query": "error code ENOENT", "count": 3, "results": [ { "id": "e5f6789012345678", "content": "Tool 'bash' failed running 'npm install': ENOENT: no such file or directory", "category": "failure", "score": 0.923, "matchType": "hybrid", "scope": "project", "created": "2024-01-21T16:45:00.000Z" }, { "id": "789012345678abcd", "content": "File not found error when accessing config.json", "category": "failure", "score": 0.812, "matchType": "semantic", "scope": "global", "created": "2024-01-20T10:30:00.000Z" } ] } ``` ```