Codumentor logo Codumentor

Agentic Memory Plugin

The Agentic Memory Plugin automatically stores agent responses as organizational knowledge in the background without blocking the main agent workflow. This plugin leverages the AgenticMemoryStoreTool to create a comprehensive knowledge base from conversational interactions.

Overview

This plugin:

  1. Hooks into agent responses: Listens to the onResponsePersist event
  2. Runs in background: Spawns asynchronous tasks that don't block the main agent
  3. Stores memories automatically: Uses AgenticMemoryStoreTool to classify and persist knowledge
  4. Logs results: Provides visibility into memory storage success/failure
  5. Graceful failure handling: Continues operation even if memory storage fails

Configuration

Basic Configuration

Add the following to your codumentor.yaml configuration file:

# Configure the plugin in the plugins section
plugins:
  - module: "codumentor.plugins.agenticmemory"
    class: "AgenticMemoryPlugin"
    priority: 90  # Run after most plugins but before final persistence
    args:
      enabled: true
      repo_name: "your-knowledge-repo"  # Repository to store memories
      kb_base_dir: "knowledge"          # Directory within repo for knowledge
      facets_hint:                      # Default classification hints
        environment: "production"
        audience: "team"

Advanced Configuration

All plugin configuration is done through the args section:

plugins:
  - module: "codumentor.plugins.agenticmemory" 
    class: "AgenticMemoryPlugin"
    priority: 90
    args:
      enabled: true
      repo_name: "custom-repo"
      kb_base_dir: "custom-knowledge"
      retrieval_cue_char_limit: 800     # Max characters from each cue (default 1000)
      facets_hint:
        type: "conversation"
        sensitivity: "internal"
        environment: "development"

Configuration Options

All configuration is done through the plugin args section:

OptionTypeDefaultDescription
enabledbooleantrueEnable/disable the agentic memory plugin
repo_namestringnullRepository for storing memories (required)
kb_base_dirstring"knowledge"Base directory within repo for knowledge storage
facets_hintobject{}Default facet hints for classification
retrieval_cue_char_limitinteger1000Max characters to include from each retrieved cue
storage_max_iterationsintegernullMaximum iterations for the memory storage subagent. If not set, uses global agent.max_iterations
commit_enabledbooleantrueWhen false, the storage subagent only writes KB files — no git add / git commit step. Set to false for non-git workspaces (e.g. the scaffolded marketing sample project) so storage doesn't fail on missing .git. When false, push_enabled is implicitly a no-op.
push_enabledbooleantruePush to git remote after committing stored memories. Ignored when commit_enabled is false. On a non-fast-forward failure (another writer pushed first), the plugin automatically runs git pull --rebase --autostash and retries the push once.
push_timeoutinteger30Seconds to wait for git push (and the recovery git pull --rebase) before timing out (handles credential prompts)
push_max_consecutive_failuresinteger5Suspend push after this many consecutive failures (counted per push attempt — pull + retry is one attempt; resets on server restart)

How It Works

Event Flow

  1. Agent completes response: Main agent finishes generating a response
  2. onResponsePersist triggered: Plugin receives the response text
  3. Background task created: Plugin spawns async task without blocking
  4. Memory tool execution: AgenticMemoryStoreTool classifies and stores the response
  5. Result logging: Success/failure is logged for monitoring

Background Execution

The plugin uses Python's asyncio.create_task() to run memory storage in the background:

# Create background task (non-blocking)
task = asyncio.create_task(
    self._store_memory_background(assistant_text, session_id, run_id)
)

# Track task for cleanup but don't await
self._background_tasks.add(task)

This ensures the main agent can continue immediately while memories are processed asynchronously.

Memory Classification

The plugin leverages the existing AgenticMemoryStoreTool which:

Repository Setup

Before using the plugin, ensure you have a repository configured for knowledge storage:

  1. Create or clone a repository: ```bash # Create new repo mkdir my-knowledge-repo cd my-knowledge-repo git init

# Or clone existing repo
git clone https://github.com/yourorg/knowledge-repo.git
```

  1. Add repository to configuration: ``yaml repos: - "my-knowledge-repo" repos_dir: "repos" # Directory containing repositories ``
  1. Create knowledge directory structure: ``bash mkdir -p knowledge echo "# Knowledge Base" > knowledge/README.md git add . && git commit -m "Initialize knowledge base" ``

Monitoring and Logging

Log Levels

The plugin logs at different levels:

Log Categories

Configure specific logging for the plugin:

logging:
  logger_levels:
    "codumentor.plugins.agentic_memory": "DEBUG"

Example Log Output

INFO - AgenticMemoryPlugin initialized (enabled=True, repo=my-repo)
INFO - AgenticMemoryPlugin registered for onResponsePersist hook  
DEBUG - AgenticMemoryPlugin: Triggering background memory storage for session abc123
DEBUG - AgenticMemoryPlugin: Background task created for run xyz789
INFO - AgenticMemoryPlugin: Successfully stored memory for run xyz789

Error Handling

The plugin is designed to fail gracefully:

Repository Not Found

WARNING - AgenticMemoryPlugin: Failed to store memory for run xyz: Repository 'missing-repo' not found

Tool Execution Failure

ERROR - AgenticMemoryPlugin: Background memory storage failed for run xyz: [detailed error]

Configuration Issues

WARNING - AgenticMemoryPlugin: No config provided, cannot register handlers

Performance Considerations

Background Execution

Resource Usage

Cleanup

The plugin automatically cleans up completed background tasks and provides a cleanup() method for graceful shutdown.

Git Repository Tuning for Large Knowledge Bases

Optional: The Agentic Memory Plugin works without any Git tuning. This section is for long-running deployments where the knowledge base accumulates a large number of commits over time. If you experience slowing Git operations, the recommendations below can help maintain performance.

When Tuning May Be Needed

Consider Git tuning if you observe any of the following:

What Affects Git Performance

Git performance depends on the combination of:

  1. Number of commits — deep history impacts history queries more than new commits
  2. Number of files in the working tree — tens of thousands is fine; hundreds of thousands may need tuning
  3. Directory layout — flat directories with many entries are slower than sharded subdirectories
  4. Number of branches/tags/refs — many refs slow down graph walks
  5. Git maintenance — repositories without regular maintenance degrade over time

For knowledge base repositories with extensive history, enable these Git features:

cd /path/to/your-knowledge-repo

# Enable commit-graph for faster history operations
git config core.commitGraph true
git config gc.writeCommitGraph true
git config fetch.writeCommitGraph true

# Enable changed-path Bloom filters for faster path-specific queries
git config commitGraph.changedPaths true

# Enable incremental maintenance strategy
git config maintenance.strategy incremental
SettingPurpose
core.commitGraphStores commit graph structure to speed up graph walks
gc.writeCommitGraphAutomatically writes commit-graph during garbage collection
fetch.writeCommitGraphUpdates commit-graph after fetching
commitGraph.changedPathsBloom filters for path-specific history queries
maintenance.strategyRuns incremental maintenance automatically

Periodic Maintenance Commands

Run these commands periodically to keep the repository healthy:

# Start automatic background maintenance (recommended)
git maintenance start

# Or run manually when needed
git maintenance run
git gc
git commit-graph write --reachable --changed-paths

Directory Layout

The plugin stores knowledge files in subdirectories under kb_base_dir (e.g., knowledge/cues/, knowledge/conventions/). This sharded layout is already optimal for Git performance. Avoid placing thousands of files in a single flat directory.

Clone Strategies for CI and Developers

For systems that do not need full history, use lightweight clone strategies:

# Shallow clone for CI pipelines (recommended)
git clone --depth=1 <repository-url>

# Partial clone for developers (lazy-loads historical blobs on demand)
git clone --filter=blob:none <repository-url>

Monitoring Repository Health

Use git-sizer to assess repository characteristics and identify potential issues:

git-sizer --verbose

This helps you understand clone size, object counts, and maintenance requirements before they become problems.

Integration Examples

Basic Setup

# Minimal configuration
plugins:
  - module: "codumentor.plugins.agenticmemory"
    class: "AgenticMemoryPlugin"
    args:
      enabled: true
      repo_name: "team-knowledge"

Team Environment

# Team-focused configuration
plugins:
  - module: "codumentor.plugins.agenticmemory"
    class: "AgenticMemoryPlugin"
    priority: 80
    args:
      enabled: true
      repo_name: "team-knowledge-base"
      kb_base_dir: "conversations"
      storage_max_iterations: 15  # Limit memory storage subagent to 15 iterations
      facets_hint:
        audience: "team"
        environment: "production"
        owner: "engineering"

Development Environment

# Development configuration with detailed logging
plugins:
  - module: "codumentor.plugins.agenticmemory"
    class: "AgenticMemoryPlugin"
    args:
      enabled: true
      repo_name: "dev-knowledge"
      facets_hint:
        environment: "development"
    
logging:
  logger_levels:
    "codumentor.plugins.agentic_memory": "DEBUG"

Troubleshooting

Plugin Not Working

  1. Check configuration: Ensure enabled: true in memory_store section
  2. Verify repository: Confirm repository exists and is accessible
  3. Check logs: Look for plugin registration and execution messages
  4. Test manually: Try running AgenticMemoryStoreTool directly

Background Tasks Not Running

  1. Check event hooks: Verify onResponsePersist is being triggered
  2. Monitor background tasks: Look for task creation in DEBUG logs
  3. Asyncio issues: Ensure proper async/await usage in your environment

Memory Storage Failures

  1. Repository access: Verify git repository is writable
  2. Tool configuration: Check AgenticMemoryStoreTool requirements
  3. LLM availability: Ensure models are accessible for classification

API Reference

AgenticMemoryPlugin

Constructor

AgenticMemoryPlugin(config: Optional[Config] = None, **kwargs)

Methods

Configuration Parameters

Memory Retrieval

The Agentic Memory Plugin includes automatic retrieval of relevant knowledge from the knowledge base to enhance agent responses. This feature provides "Rapid Direction Cues" that give context without overwhelming the conversation.

How Retrieval Works

  1. Query Extraction: Uses the latest user message content directly as the search query
  2. Vector Search: Searches the knowledge base semantically using the raw user query
  3. Repository Filtering: Results are filtered to the configured repository for relevance
  4. Cue Formatting: Top results are formatted as concise cues with file paths and content previews
  5. Context Injection: Cues are injected as system messages before the user query

Retrieval Configuration

Add retrieval settings to the plugin configuration:

plugins:
  - module: "codumentor.plugins.agenticmemory"
    class: "AgenticMemoryPlugin"
    args:
      enabled: true
      repo_name: "your-knowledge-repo"
      retrieval_enabled: true          # Enable retrieval (default: true)
      retrieval_num_results: 3         # Number of cues to retrieve (default: 3)

Retrieval Parameters

OptionTypeDefaultDescription
retrieval_enabledbooleantrueEnable/disable memory retrieval
retrieval_num_resultsinteger3Number of rapid direction cues to retrieve

Rapid Direction Cues (RDCs)

Rapid Direction Cues are small, actionable hints that help agents navigate the codebase efficiently. The plugin automatically detects and stores RDCs from:

RDC Examples:

Each RDC is stored in its own minimal file with:

Retrieved RDCs Format:

Rapid Direction Cues (Results of a quick kb search, use only the relevant ones, if any):
relative/path/to/file1.py:
Content preview (first 500 chars)...

relative/path/to/file2.md:
Another content preview...

Example Retrieval Flow

  1. User Query: "How do I implement user authentication?"
  2. Retrieval Search: Plugin searches knowledge base for "user authentication"
  3. Results Found: Returns relevant docs about auth patterns, security, etc.
  4. Context Injection: Cues added before user message:
System: Rapid Direction Cues (Results of a quick kb search, use only the relevant ones, if any):
auth/auth_service.py:
Implements JWT token validation and user session management...

security/oauth_config.md:
OAuth2 configuration for third-party authentication providers...
  1. Enhanced Response: Agent now has contextual knowledge for more accurate answers

Retrieval Benefits

Retrieval Limitations

Web UI Integration

The Agentic Memory Plugin includes a custom UI component that renders memory events in the web interface.

UI Events

The plugin emits the following events to the web UI:

Event TypeStatusDescription
plugin.agentic_memory.storage_startedpendingMemory storage has begun
plugin.agentic_memory.storedsuccessMemory was stored successfully
plugin.agentic_memory.storage_failederrorMemory storage failed
plugin.agentic_memory.retrievedsuccessMemory was retrieved (future)

Event Grouping

The agentic memory plugin uses event grouping to correlate related events into a single UI card. All events in a storage operation share the same event_group_id, causing them to update a single card rather than creating multiple cards.

Event Data Fields:

All events include explicit status and event_group_id in their data payload:

await emit_ui_event("plugin.agentic_memory.storage_started", {
    "status": "pending",       # Required: explicit status
    "event_group_id": run_id,  # Correlation key for grouping
    "text_length": len(assistant_text),
    "repo_name": self.repo_name,
})

await emit_ui_event("plugin.agentic_memory.stored", {
    "status": "success",       # Required: explicit status
    "event_group_id": run_id,  # Same key updates existing card
    "success": True,
    "reasoning": reasoning,
    "stored_items": stored_items,
    "summary": summary,
})

See Event Grouping in the UI documentation for more details.

Custom Element

The plugin provides a custom web component <x-agentic-memory-card> that renders with:

See ui/plugins/agentic_memory/index.js for the full implementation.

Enabling the UI

The plugin's UI is enabled by default. To disable:

ui:
  disabled_extensions:
    - agentic_memory

When the UI is disabled, events still appear in the transcript using the generic fallback renderer.

Memory Feedback Review

The Agentic Memory Plugin includes a feedback review system that allows users and administrators to manage memory quality based on user feedback from the RDC review cards.

Overview

When users vote on retrieved RDCs (using the thumbs up/down buttons), they can mark memories as:

These feedback entries can be reviewed and acted upon through the Memory Feedback Review page.

Permission Model

The review system supports two access levels:

PermissionAccess LevelCapabilities
memory_feedback:reviewAdminView all feedback, delete memory files, ignore feedback
(authenticated)UserView own reports, edit/delete own reports

Users without the memory_feedback:review permission automatically see their own submitted reports instead.

Welcome Page Widget

The plugin provides a welcome page widget that displays:

The widget automatically refreshes every 60 seconds to show current counts.

Review Page

The full review page is accessible at /plugins/agentic_memory/review and provides different views based on permissions:

Admin View (with memory_feedback:review permission):

For each feedback entry:

Available actions:

User View (own reports only):

For each of the user's own reports:

API Endpoints

The feedback review system provides the following API endpoints:

Admin Endpoints (require memory_feedback:review permission):

EndpointMethodDescription
/votes/review-summaryGETGet counts for the welcome widget
/votes/feedback-entriesGETGet all feedback entries for review
/votes/pending-reviewsGETGet all RDCs pending review (grouped by file)
/votes/pending-reviews/summaryGETLightweight summary for welcome widget
/votes/{vote_id}/ignorePOSTMark a feedback entry as ignored
/memory/{file_path}DELETEPermanently delete a memory file

User Endpoints (authenticated users, own reports only):

EndpointMethodDescription
/votes/my-reports-summaryGETGet counts for user's own reports
/votes/my-reportsGETGet user's own feedback entries
/votes/report/{vote_id}PUTUpdate user's own report
/votes/report/{vote_id}DELETEDelete user's own report

Review Summary Response

{
  "unhelpful_count": 3,
  "review_requested_count": 5,
  "total_feedback_count": 7,
  "own_reports_only": false
}

The own_reports_only field indicates whether the counts are filtered to the current user's reports only (true for /votes/my-reports-summary).

Feedback Entry Response

{
  "entries": [
    {
      "vote_id": "abc123",
      "conversation_id": "conv456",
      "event_id": "evt789",
      "rdc_file_path": "my-repo/knowledge/cues/naming-history.md",
      "vote_type": "dislike",
      "reason": "This information is outdated",
      "is_generally_bad": true,
      "request_review": false,
      "created_at": "2024-01-15T10:30:00Z",
      "ignored": false,
      "user_id": "user-uuid-123",
      "user_display_name": "Jane Developer",
      "rdc_content": "---\ntitle: Naming History\n---\n\nContent of the memory file...",
      "query": "What is the billing module called?"
    }
  ],
  "own_reports_only": false
}

Response fields:

FieldDescription
vote_idUnique identifier for the vote
conversation_idID of the conversation where feedback was given
event_idPlugin event ID containing the RDC
rdc_file_pathPath to the memory file (may include repo name prefix)
vote_typeAlways "dislike" for feedback entries
reasonUser's explanation for the feedback
is_generally_badWhether the memory is generally unhelpful (not just context-specific)
request_reviewWhether the user requested human review
created_atISO timestamp of when feedback was submitted
ignoredWhether this entry has been ignored by an admin
user_idUUID of the user who submitted the feedback
user_display_nameHuman-readable name of the user (if available)
rdc_contentFull content of the memory file (for review)
queryThe search query that retrieved this RDC
own_reports_only(on response) Whether results are filtered to user's own reports

Update Report Request

{
  "reason": "Updated reason for feedback",
  "is_generally_bad": true,
  "request_review": false
}

All fields are optional; only provided fields are updated.

Delete Memory Behavior

When a memory file is deleted:

  1. The file is permanently removed from the knowledge base directory
  2. The deletion is committed to git
  3. All associated votes/feedback for that file are also deleted
  4. The feedback entry is removed from the review list

Security: The delete endpoint validates that the file path is within an allowed knowledge base directory to prevent directory traversal attacks.

Ignore Feedback Behavior

When feedback is ignored:

  1. The feedback entry is marked with ignored=true in the database
  2. The entry no longer appears in future review listings
  3. The memory file remains unchanged
  4. Counts in the welcome widget exclude ignored entries

Use "Ignore Feedback" when:

Configuration

The feedback review feature is enabled by default when the Agentic Memory plugin is active. No additional configuration is required.

To grant admin review access, assign the memory_feedback:review permission to users or roles in your RBAC configuration.

Workflow Examples

Admin Workflow:

  1. User provides feedback: During a conversation, user clicks thumbs down on an RDC and checks "This memory is generally unhelpful"
  2. Feedback recorded: The vote is stored with is_generally_bad=true
  3. Widget shows count: Welcome page widget shows "1 unhelpful"
  4. Admin reviews: Admin clicks "Review Feedback" to open the review page
  5. Context visible: Admin sees the search query, user name, and full memory content
  6. Action taken: Admin either: - Clicks "Delete Memory" to remove the file permanently - Clicks "Ignore Feedback" if the memory should remain
  7. Widget updates: Count decreases after action is taken

User Self-Service Workflow:

  1. User submits feedback: User marks an RDC as unhelpful with a reason
  2. User reviews own reports: User opens the review page (sees only their own reports)
  3. User can edit: If the reason was incomplete, user clicks "Edit Report" to update
  4. User can retract: If feedback was a mistake, user clicks "Delete Report"