A concise MCP server for capturing and retrieving universal working knowledge. Records meta-patterns about effective work with AI agents, tools, protocols, and processes - NOT task-specific code patterns.
Author: Jason Lusk [email protected] License: MIT Gist URL: https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86
- Hybrid Storage: User-level + optional project-level SQLite databases
- FTS5 Full-Text Search: Fast, ranked search across all experience fields
- Automatic Deduplication: No duplicate patterns across databases
- Zero Configuration: Works out-of-the-box with sensible defaults
- Export Capabilities: JSON and Markdown export formats
- Informed Reasoning: Multi-phase reasoning tool with context-aware guidance
MAJOR UPDATE: Complete v3.0 system with three-gate enforcement, installation automation, and enhanced protocol workflow.
Three-Gate Enforcement (TEACH → LEARN → REASON):
- TEACH Gate: Blocks new work if previous sessions have unrecorded experiences
- Ensures institutional memory by requiring
record_experiencebefore starting new tasks - 24-hour TTL on recording requirement tokens
- Proactive cleanup of expired tokens
- Ensures institutional memory by requiring
- LEARN Gate: Blocks file operations until
search_experiencescalled- Session-specific tokens:
.protocol-search-completed-{sessionId} - 5-minute TTL for search completion tokens
- Prevents agents from skipping past experience searches
- Session-specific tokens:
- REASON Gate: Blocks file operations until
informed_reasoningcalled- REQUEST-SCOPED tokens: Each user message requires new protocol flow
- Session-specific tokens:
.protocol-session-{sessionId}.json - 60-minute max TTL (tokens are per-request, not session-wide)
- Forces thoughtful analysis before modifications
Actionable Error Messages:
- Parameter Validation: All tools validate required parameters upfront
- Specific Error Messages: No generic "Internal error" - always explains what's wrong
- Copy-Paste Examples: Every error includes correct usage example
- Phase-Specific Guidance: informed_reasoning validates per-phase requirements
- Tool validations:
record_experience: Validates all 6 required fields (type, domain, situation, approach, outcome, reasoning)informed_reasoning analyze: Validates problem parameter exists and is non-emptyinformed_reasoning integrate: Validates problem parameterinformed_reasoning record: Validates problem and finalConclusion parametersinformed_reasoning reason: Validates thought parameter (existing from v2.1.2)
- Error format: (1) What's wrong, (2) What's required, (3) Example with correct usage
Installation:
- AI-agent guided installation via README documentation
- Analysis-driven approach: Agents analyze environment before installing
- No backward compatibility needed (clean v3 implementation)
- Comprehensive test coverage validates all functionality
Enhanced Token System:
- Session-Specific Naming: All tokens include session ID for concurrency support
- Persistent Session File:
.protocol-current-session-id(8-hour expiry) - Proactive Cleanup: user-prompt-submit hook removes tokens >24 hours old
- Loop Prevention: stop hook tracks reminders to prevent infinite loops
- Smart Task Detection: Distinguishes tasks from questions (no spam on "What is X?")
Hook Updates (All 6 Hooks):
- user-prompt-submit.cjs: Smart task detection + proactive cleanup
- pre-tool-use.cjs: Three-gate enforcement with session consistency
- post-tool-use.cjs: 24-hour TTL recording tokens + immediate reminders
- stop.cjs (NEW): TEACH phase reminders with loop prevention
- session-start.cjs (NEW): Minimal setup, no prompt injection
- pre-compact-handoff.cjs (ENHANCED): Last chance recording reminders
Session ID Consistency:
- 3-level priority chain: env var → persistent file → generate new
getSessionId()function unified across all hooks and MCP server- Session persistence across process restarts
- 8-hour session file expiry for security
Developer Experience:
- Simple Setup: Follow AI-agent installation guide or manual steps
- Clear Documentation: Every step explained with examples
- Idempotent Configuration: Safe to reconfigure multiple times
Breaking Changes from v2:
- Token naming changed (session-specific:
.protocol-*-{sessionId}) - Three gates instead of two (added TEACH gate)
- Recording tokens expire after 24 hours (not infinite)
- No backward compatibility in hooks (clean migration during install)
Migration Path:
- V3 uses new token format (session-specific naming)
- Old v2 tokens are incompatible and should be removed manually
- First v3 workflow establishes new token format
Works with: protocol-enforcer v3.0.0+
This guide is designed for AI agents to install and configure the MCP server automatically.
Agent must verify:
- Node.js: Run
node --version(require v14+) - npm: Run
npm --version - Build Tools (for better-sqlite3):
- macOS:
xcode-select --version - Linux:
dpkg -l | grep build-essential
- macOS:
- Workspace Path: Run
pwdto get absolute project path
# Detect OS
uname -s # Darwin (macOS), Linux, etc.
# Get absolute workspace path
WORKSPACE_PATH=$(pwd)
# Check Node.js version
node --version # Must be v14.0.0 or higher
# Check for existing configuration
ls ~/.claude.json 2>/dev/null && echo "Config exists" || echo "Config missing"
ls .mcp.json 2>/dev/null && echo ".mcp.json exists (WARN: known issues)" || echo "No .mcp.json"CRITICAL: Configure in ~/.claude.json, NOT .mcp.json
Reason: .mcp.json with enabledMcpjsonServers has known loading issues in Claude Code 2.1.17+
Configuration Location:
~/.claude.json → projects.{absolute_workspace_path}.mcpServers
Check if Already Configured:
# Read existing config
cat ~/.claude.json | grep -A 20 "$WORKSPACE_PATH"
# Look for existing mcpServers entryAgent should update existing configuration rather than duplicate:
// Pseudo-code for agent
const config = JSON.parse(fs.readFileSync('~/.claude.json'));
const projectPath = process.cwd();
if (!config.projects) config.projects = {};
if (!config.projects[projectPath]) {
config.projects[projectPath] = { mcpServers: {} };
}
// Update/add memory-augmented-reasoning
config.projects[projectPath].mcpServers['memory-augmented-reasoning'] = {
type: 'stdio',
command: 'npx',
args: ['-y', 'https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86'],
env: {
MEMORY_AUGMENTED_REASONING_USER_DB: '${HOME}/.cursor/memory-augmented-reasoning.db',
MEMORY_AUGMENTED_REASONING_PROJECT_DB: '${WORKSPACE_FOLDER}/.cursor/memory-augmented-reasoning.db'
}
};
// Write back
fs.writeFileSync('~/.claude.json', JSON.stringify(config, null, 2));Test 1: MCP Server Connection
// Agent calls this tool
await mcp__memory_augmented_reasoning__search_experiences({
query: "test"
});
// Expected: Returns results or empty array
// If fails: Check ~/.claude.json configurationTest 2: Token Creation
# Clear existing tokens
rm ~/.protocol-informed-reasoning-token 2>/dev/null
# Agent calls informed_reasoning
await mcp__memory_augmented_reasoning__informed_reasoning({
phase: 'analyze',
problem: 'verify token creation'
});
# Verify token exists
ls -la ~/.protocol-informed-reasoning-token && echo "✅ Token created" || echo "❌ FAILED"
# Check token content
cat ~/.protocol-informed-reasoning-token
# Expected: {"sessionId":"...","phase":"analyze","timestamp":"...","expires":"..."}Test 3: Experience Recording
# Record a test experience
await mcp__memory_augmented_reasoning__record_experience({
type: 'effective',
domain: 'Tools',
situation: 'Test installation',
approach: 'Used AI-Agent Installation Guide',
outcome: 'Successfully installed',
reasoning: 'Following automated installation procedure'
});
# Verify in database
sqlite3 ~/.cursor/memory-augmented-reasoning.db \
"SELECT situation FROM experiences ORDER BY id DESC LIMIT 1"
# Expected: Shows "Test installation"Issue: MCP Server Not Loading
Symptom: search_experiences returns "No such tool"
Diagnosis:
1. Check ~/.claude.json has project path entry
2. Verify mcpServers configuration exists
3. Check for .mcp.json conflicts (remove if exists)
4. Reload Claude Code (Cmd+Shift+P → Reload Window)
Resolution: Reconfigure in ~/.claude.json, reload
Issue: Tokens Not Created
Symptom: ~/.protocol-informed-reasoning-token doesn't exist after analyze
Diagnosis:
1. Check stderr logs for "✓ Token created" or "✗ FAILED"
2. Verify MAR server loaded (Test 1)
3. Check file permissions on home directory
Resolution: Check MCP server logs, verify home directory writable
Issue: Experience Recording Fails
Symptom: Database shows no new experiences
Diagnosis:
1. Check database file exists: ls ~/.cursor/memory-augmented-reasoning.db
2. Check file permissions
3. Verify better-sqlite3 compiled correctly
Resolution: Reinstall with npm install, check build tools
Issue: Running Old Cached Version (v3.3.1+)
Symptom: Agent shows old behavior despite v3.3.1 deployed
- Analyze output missing userIntent field
- Analyze output missing keyFactors array
- Queries are long mechanical echoes (50+ words) instead of focused (<20 words)
Root Cause: npx caches MCP servers - may run stale version
Diagnosis:
1. Check analyze output for v3.3.1 fields:
• userIntent object (goal, priority, expectedFormat, context)
• keyFactors array (search priorities)
• suggestedQueries.learningLibrary.query <20 words
2. If missing, you're running cached old version
Resolution Options:
Option 1: Clear npx cache
npx clear-npx-cache
rm -rf ~/.npm/_npx
# Then restart Claude Desktop/Code completely
Option 2: Force latest in configuration
# In Claude Desktop config.json:
{
"mcpServers": {
"memory-augmented-reasoning": {
"command": "npx",
"args": ["--yes", "gist:32e02b911a6dae5751053ad158fc0e86"]
}
}
}
# The --yes flag forces npx to fetch latest version
Option 3: Verify version manually
npx gist:32e02b911a6dae5751053ad158fc0e86 --version
# Should show: 3.3.1
Expected v3.3.1 Behavior:
When analyze phase called with problem "standup?":
✅ Correct (v3.3.1):
{
"userIntent": {
"goal": "Brief status update",
"priority": "Speed and clarity",
"expectedFormat": "Git log + current work",
"context": "Recurring informational"
},
"suggestedQueries": {
"learningLibrary": {
"query": "standup status brief", // <20 words, focused
"patterns": ["standup", "status"],
"domain": "Communication"
}
},
"keyFactors": ["recency", "brevity"]
}
❌ Wrong (v3.3.0 or earlier - cached):
{
"suggestedQueries": {
"learningLibrary": {
"query": "standup?" // Just lowercased problem
}
}
// Missing: userIntent, keyFactors, patterns, focused query
}
Agent should inform user:
✅ Installation Complete
MCP Server Configured:
- memory-augmented-reasoning (v2.0.7+)
Database Paths:
- User: ~/.cursor/memory-augmented-reasoning.db
- Project: ${WORKSPACE_FOLDER}/.cursor/memory-augmented-reasoning.db
Verification Tests: 3/3 passed
Next Steps:
1. Reload Claude Code (Cmd+Shift+P → Reload Window)
2. Test informed_reasoning tool
3. Start recording experiences with record_experience tool
For AI agents executing this installation:
-
Analyze Environment:
- Run:
pwd,uname -s,node --version,npm --version - Check:
~/.claude.json,.mcp.json, build tools
- Run:
-
Configure MCP Server:
- Read
~/.claude.json - Add/update
projects.{absolute_path}.mcpServers - Use npx remote execution URL
- Read
-
Verify Installation:
- Test 1: MCP connection
- Test 2: Token creation
- Test 3: Experience recording
-
Troubleshoot Failures:
- Use decision tree above
- Check logs and file permissions
- Reload after configuration changes
-
Inform User:
- Summarize what was installed
- Report test results
- Provide next steps
Complete setup in 5 steps - installs MCP server + instance identity system.
Add to .mcp.json (project-level) or ~/.claude.json (user-level):
{
"mcpServers": {
"memory-augmented-reasoning": {
"command": "npx",
"args": [
"-y",
"https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86"
],
"env": {
"MEMORY_AUGMENTED_REASONING_USER_DB": "${HOME}/.cursor/memory-augmented-reasoning.db"
}
}
}
}Optional: Add project-level database for project-specific experiences:
{
"mcpServers": {
"memory-augmented-reasoning": {
"command": "npx",
"args": [
"-y",
"https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86"
],
"env": {
"MEMORY_AUGMENTED_REASONING_USER_DB": "${HOME}/.cursor/memory-augmented-reasoning.db",
"MEMORY_AUGMENTED_REASONING_PROJECT_DB": "${WORKSPACE_FOLDER}/.cursor/memory-augmented-reasoning.db"
}
}
}
}The server uses better-sqlite3 which requires native compilation. Ensure you have the necessary build tools:
macOS:
xcode-select --installLinux (Debian/Ubuntu):
sudo apt-get install build-essential python3Windows:
- Install Visual Studio Build Tools
- Or use:
npm install --global windows-build-tools
Instance identity enables cross-session learning. Download the SessionStart hook:
# Create hooks directory
mkdir -p .cursor/hooks
# Download session-start hook
curl -o .cursor/hooks/session-start.cjs \
https://gist.githubusercontent.com/mpalpha/32e02b911a6dae5751053ad158fc0e86/raw/session-start.cjs
# Make executable
chmod +x .cursor/hooks/session-start.cjsConfigure in .claude/settings.json:
{
"hooks": {
"SessionStart": [{
"hooks": [{
"type": "command",
"command": "${workspaceFolder}/.cursor/hooks/session-start.cjs"
}]
}]
}
}What this does:
- Auto-creates
.cursor/claude-instance.jsonwith instance ID on first session - Tracks session count and timestamps
- Enables instance-specific experience tagging for targeted learning
To skip instance identity: Skip step 3. MCP tools will still work normally.
Claude Code / Cursor:
Cmd+Shift+P → "Developer: Reload Window"
On first run, better-sqlite3 will compile (takes ~30 seconds):
npx -y https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86 --helpExpected output:
> [email protected] install
> node-gyp rebuild
CXX(target) Release/obj.target/better_sqlite3/src/better_sqlite3.o
...
SOLINK_MODULE(target) Release/better_sqlite3.node
With instance identity hook installed:
✨ Instance identity created: my-project-claude
📁 Config: .cursor/claude-instance.json
💡 Edit config file to customize instance identity
Note: First run takes longer due to native compilation. Subsequent runs use npx cache and start instantly.
When used with protocol-enforcer-mcp, this server provides the core reasoning and memory system:
-
informed_reasoning tool - Multi-phase guided reasoning
- analyze phase: Creates
.protocol-informed-reasoning-token(required for file operations) - analyze phase: Creates
.protocol-search-required-tokenwhen suggesting searches - integrate phase: Synthesizes gathered context
- reason phase: Evaluates approaches and makes decisions
- record phase: Captures learnings as experiences
- analyze phase: Creates
-
search_experiences tool - Full-text search across experience library
- Consumes
.protocol-search-required-tokenwhen called - Prevents protocol violations from skipping suggested searches
- Consumes
-
record_experience tool - Manual experience recording
- Allows explicit experience capture
- Complements automatic recording
-
Automatic recording -
--record-last-sessionCLI flag- Triggered by PostToolUse hook after file operations
- Reads
.protocol-session-recording-tokenfor file context - Saves experiences with rich metadata
When called with phase="analyze", the informed_reasoning tool performs three critical token operations:
Deletes .protocol-informed-reasoning-required token (if exists):
- This token is created by user_prompt_submit hook when no session exists
- Deletion signals that the requirement has been satisfied
- Allows tools to proceed (pre_tool_use CHECK 0 will pass)
// Inside informed_reasoning analyze phase
const requirementFile = path.join(os.homedir(), '.protocol-informed-reasoning-required');
if (fs.existsSync(requirementFile)) {
fs.unlinkSync(requirementFile); // Requirement satisfied
}Creates .protocol-session-token with 10-minute TTL:
- Prevents requirement token creation for subsequent messages
- Optimizes multi-turn conversations
- Allows agent to use tools freely within session window
// Session token structure
{
"sessionId": "session_abc123",
"timestamp": 1769444349113,
"expires": 1769444949113, // 10 minutes later
"created": "2026-01-26T16:19:09.113Z"
}Creates .protocol-informed-reasoning-token with 60-second TTL:
- Used by pre_tool_use hook for secondary verification (CHECK 1)
- Short lifetime ensures recent analysis
- Part of two-factor verification system
Result: Agent can now use tools because:
- Requirement satisfied (no
.protocol-informed-reasoning-required) - Analysis verified (
.protocol-informed-reasoning-tokenexists) - Session active (
.protocol-session-tokenprevents future requirements)
IMPORTANT: Session tokens are REQUEST-SCOPED, not session-wide. Each new user message requires a new protocol flow.
Session tokens authorize multi-tool workflows within a SINGLE user request:
User: "Add feature X to the code"
↓
[NEW REQUEST - Protocol Required]
↓
Agent: search_experiences (LEARN gate)
Agent: informed_reasoning (REASON gate)
→ Creates REQUEST-SCOPED token for this request
↓
Agent: Read file → Write file → Edit file
(All authorized by same token - same request)
↓
Agent: record_experience (TEACH phase)
Each new user message is a NEW request requiring NEW protocol flow:
User: "Add feature X" [Request 1]
→ search_experiences
→ informed_reasoning → Token A created
→ Write/Edit (authorized by Token A)
→ record_experience
User: "Now update the docs" [Request 2 - NEW PROTOCOL REQUIRED]
→ search_experiences (must search again)
→ informed_reasoning → Token B created
→ Write (authorized by Token B)
→ record_experience
User: "Fix the typo" [Request 3 - NEW PROTOCOL REQUIRED]
→ search_experiences (must search again)
→ informed_reasoning → Token C created
→ Edit (authorized by Token C)
→ record_experience
❌ WRONG: "I ran informed_reasoning once → got 60-min token → can skip protocol for rest of session"
✅ CORRECT: "Each user message = new request = run protocol again"
- Relevance: Each request needs context search for that specific task
- Analysis: Each change requires fresh reasoning
- Institutional Memory: Each outcome must be recorded
- Security: Prevents agents from skipping protocol on subsequent requests
The 60-minute TTL is the maximum lifespan of a token, not a "session pass":
- Token authorizes tools for THIS request's workflow only
- Token expires OR is invalidated after Write/Edit
- Does NOT carry over to next user request
- Next user message = new request = new token required
Do NOT reuse tokens across different user requests. Even if a token hasn't expired yet, each new user message requires running the protocol again.
CRITICAL: AI agents must configure in ~/.claude.json, NOT .mcp.json
Agent must:
- Determine user's absolute project path:
pwd - Read/create
~/.claude.json - Add configuration under
projects.{absolute_project_path}.mcpServers
Example structure (agent must replace path):
{
"projects": {
"/Users/username/projects/myproject": {
"mcpServers": {
"memory-augmented-reasoning": {
"type": "stdio",
"command": "npx",
"args": ["-y", "https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86"],
"env": {
"MEMORY_AUGMENTED_REASONING_USER_DB": "${HOME}/.cursor/memory-augmented-reasoning.db",
"MEMORY_AUGMENTED_REASONING_PROJECT_DB": "${WORKSPACE_FOLDER}/.cursor/memory-augmented-reasoning.db"
}
},
"protocol-enforcer": {
"type": "stdio",
"command": "npx",
"args": ["-y", "https://gist.github.com/mpalpha/c2f1723868c86343e590ed38e80f264d"],
"env": {}
}
}
}
}
}Agent tasks:
- Run
pwdto get absolute project path - Read
~/.claude.json(create if missing:echo '{"projects":{}}' > ~/.claude.json) - Parse JSON structure
- Navigate to
projectsobject - Add/update entry for
{absolute_project_path} - Add
mcpServersconfiguration with both servers - Write back to
~/.claude.json - Instruct user to reload Claude Code
Note: ${HOME} and ${WORKSPACE_FOLDER} variables ARE supported in MCP server env configurations.
After installing the MCP server, add the following protocol to your project's CLAUDE.md file to ensure future agents understand the "learn/save" convention.
Add to Critical Override Rules section (as a numbered rule):
5. **Learn/Save Protocol**: When asked to "learn", "save information", "save patterns", or similar requests:
- **USE** `mcp__memory-augmented-reasoning__record_experience` to save knowledge to memory
- **DO NOT** create external documents, guides, or summary files unless explicitly requested
- Save effective patterns (what works), ineffective patterns (what fails), and reasoning processes
- Organize by domain: Tools, Protocol, Communication, Process, Debugging, Decision
- Include: situation, approach, outcome, reasoning, confidence level
- Memory persists across sessions and can be retrieved via `search_experiences`Why this is important:
- Users often say "learn this" or "save this pattern" expecting memory storage, not file creation
- Without this protocol, agents may create unnecessary documentation files instead of using the memory system
- This convention ensures consistent behavior across all agents working in the project
Example user requests that trigger this protocol:
- "Learn how to use CDP for browser testing"
- "Save this pattern for future reference"
- "Remember this approach"
- "Store this information"
All these mean: use record_experience tool, not Write/Edit tools.
Enables cross-session learning and targeted self-improvement for Claude instances.
The Instance Identity system gives each Claude instance a unique, persistent label (like my-project-claude) that enables:
- Cross-Session Learning - Experiences tagged with instance ID can be retrieved in future sessions
- Targeted Instructions - Provide instance-specific guidance in CLAUDE.md
- Multi-Instance Support - Different Claude instances for different projects
- Self-Improvement - Analyze patterns specific to this instance
- Zero-Configuration Setup - Automatically creates instance identity on first session
- Auto-Generated IDs - Derived from workspace name (e.g.,
smartpass-admin-ui-claude) - Session Tracking - Counts sessions and tracks last session timestamp
- Customizable - Edit
.cursor/claude-instance.jsonto add specializations, descriptions, and notes - Non-Breaking - No database schema changes required
Instance identity requires SessionStart hook installation (see Installation step 3 above).
Once the hook is installed, it automatically:
- Checks for
.cursor/claude-instance.json - Creates it if not found (auto-generated from workspace name)
- Loads the instance profile
- Increments session count
- Logs instance info to console
First session with hook installed:
✨ Instance identity created: my-project-claude
📁 Config: .cursor/claude-instance.json
💡 Edit config file to customize instance identity
Subsequent sessions:
✅ Instance: my-project-claude
📊 Session 47 started
Without hook: MCP tools work normally, but no automatic instance tracking.
Location: .cursor/claude-instance.json
Auto-generated structure:
{
"instance_id": "my-project-claude",
"workspace": "/path/to/my-project",
"created": "2026-01-24T00:00:00.000Z",
"auto_generated": true,
"sessions": 47,
"last_session": "2026-01-24T03:15:00.000Z",
"description": "Auto-generated instance identity. Edit this file to customize.",
"specializations": []
}Customization options:
{
"instance_id": "custom-name-here",
"description": "Describe this instance's purpose",
"specializations": ["list", "your", "focus", "areas"],
"learning_enabled": true,
"notes": "Any additional metadata you want"
}Convention: Include instance_id in the context field:
await mcp__memory-augmented-reasoning__record_experience({
type: "effective",
domain: "Process",
situation: "Deploying application to production",
approach: "Used containerized deployment with reverse proxy",
outcome: "Deployment successful, zero downtime",
reasoning: "Containers provide consistent environment across dev/prod",
context: "instance_id: my-project-claude", // ← Tag with instance
confidence: 0.9
});Find experiences for this instance:
const experiences = await mcp__memory-augmented-reasoning__search_experiences({
query: "instance_id: my-project-claude deployment"
});Filter by domain:
const processExperiences = await mcp__memory-augmented-reasoning__search_experiences({
query: "instance_id: my-project-claude",
domain: "Process",
type: "effective"
});Different projects automatically get different instance identities:
~/projects/
├─ website/
│ └─ .cursor/claude-instance.json → "website-claude"
├─ api/
│ └─ .cursor/claude-instance.json → "api-claude"
└─ mobile-app/
└─ .cursor/claude-instance.json → "mobile-app-claude"
Each instance maintains its own:
- Experience library (tagged with instance_id)
- Specializations
- Learning history
- Self-improvement rules
1. Record Patterns:
// After completing a task successfully:
await record_experience({
context: "instance_id: my-project-claude",
situation: "Need to update API schema",
approach: "1. Update schema definition, 2. Run codegen, 3. Update types",
outcome: "Types updated correctly, no compilation errors"
});2. Search Before Acting:
// Before starting similar task:
const patterns = await search_experiences({
query: "instance_id: my-project-claude API schema"
});
// Returns previous approach → Apply same pattern3. Analyze and Improve:
// Periodically review ineffective patterns:
const antiPatterns = await search_experiences({
query: "instance_id: my-project-claude",
type: "ineffective"
});
// Identify what NOT to do in futureTemporary (one session):
# Rename hook to disable
mv .cursor/hooks/session-start.cjs .cursor/hooks/session-start.cjs.disabledPermanent:
# Delete hook
rm .cursor/hooks/session-start.cjs
# Or add to config:
{
"instance_id": "my-project-claude",
"enabled": false
}Add instance-specific instructions to CLAUDE.md:
## Instance Identity: my-project-claude
### Specializations
- Web framework with TypeScript
- REST/GraphQL API integration
- Unit testing framework
### Self-Improvement Rules
- Always check API schema before proposing queries
- Search for existing utilities before creating new ones
- Run build/codegen commands after schema changes
### Known Patterns (Instance-Specific)
- This codebase uses modular styling conventions
- API operations organized in dedicated directory
- Strict typing enforced throughout
### Learning Targets
- Improve: Remembering to run build after API changes
- Focus: Better pattern recognition for reusable codeFor complete documentation, see: INSTANCE-IDENTITY-GUIDE.md
MEMORY_AUGMENTED_REASONING_USER_DB- User-level database path (default:~/.cursor/memory-augmented-reasoning.db)MEMORY_AUGMENTED_REASONING_PROJECT_DB- Optional project-level database pathLEARNING_LIBRARY_MAX_RESULTS- Max search results (default: 50)
NEW: Multi-phase reasoning with context-aware guidance. Replaces sequential thought with context synthesis from multiple sources.
Phases:
- analyze - Suggests queries based on available MCP tools
- integrate - Synthesizes context with priority-based merging
- reason - Evaluates thoughts against learned patterns
- record - Auto-captures experience from session
Parameters:
{
phase: 'analyze' | 'integrate' | 'reason' | 'record',
// ANALYZE phase
problem?: string,
availableTools?: string[], // e.g., ['memory-augmented-reasoning', 'context7', 'jira']
// INTEGRATE phase
gatheredContext?: {
experiences?: any[], // From search_experiences
localDocs?: any[], // From file reads
mcpData?: { // From other MCP servers
jira?: any,
figma?: any,
context7?: any
},
webResults?: any[]
},
// REASON phase
thought?: string,
thoughtNumber?: number,
totalThoughts?: number,
nextThoughtNeeded?: boolean,
isRevision?: boolean,
revisesThought?: number,
branchFromThought?: number,
branchId?: string,
needsMoreThoughts?: boolean,
// RECORD phase
finalConclusion?: string,
relatedLearnings?: number[] // IDs of related experiences
}Example Workflow:
// 1. ANALYZE: Get suggestions for what to query
const analysis = await mcp__learning_library__informed_reasoning({
phase: 'analyze',
problem: 'How do I implement user authentication in React?',
availableTools: ['memory-augmented-reasoning', 'context7', 'github']
});
// Returns: { suggestedQueries: { learningLibrary: {...}, context7: {...}, ... } }
// 2. Execute suggested queries (user/AI does this)
const experiences = await mcp__learning_library__search_experiences({
query: 'authentication React'
});
const docs = await mcp__context7__query_docs({
libraryId: '/facebook/react',
query: 'authentication patterns'
});
// 3. INTEGRATE: Synthesize context with token budget management
const context = await mcp__learning_library__informed_reasoning({
phase: 'integrate',
problem: 'How do I implement user authentication in React?',
gatheredContext: {
experiences,
localDocs: [{ path: 'CLAUDE.md', content: '...' }],
mcpData: { context7: docs }
}
});
// Returns: { synthesizedContext: 'markdown text', estimatedThoughts: 5, tokenBudget: {...} }
// 4. REASON: Evaluate each thought against context
const evaluation1 = await mcp__learning_library__informed_reasoning({
phase: 'reason',
problem: 'How do I implement user authentication in React?',
thought: 'I should use JWT tokens stored in localStorage',
thoughtNumber: 1,
totalThoughts: 5,
nextThoughtNeeded: true
});
// Returns: { evaluation: {...}, guidance: '...', revisionSuggestion: {...} }
// 5. Continue reasoning with multiple thoughts...
// 6. RECORD: Capture experience when complete
const recorded = await mcp__learning_library__informed_reasoning({
phase: 'record',
problem: 'How do I implement user authentication in React?',
finalConclusion: 'Use JWT tokens with httpOnly cookies, not localStorage',
relatedLearnings: [123, 456] // IDs from search results
});
// Returns: { recorded: true, learningId: 789, ... }Key Features:
- Dynamic Tool Discovery: Adapts suggestions based on
availableToolsparameter - Token Budget Management: 20K token limit with intelligent pruning
- 4-Tier Context Prioritization: Project rules → Effective experiences → Anti-patterns → External data
- Thought Evaluation: Detects scope creep, implementing-without-reading, protocol violations
- Auto-Experience Capture: Automatically records reasoning sessions for future use
Record a experience to the library.
Parameters:
{
scope: 'user' | 'project', // Default: 'user'
type: 'effective' | 'ineffective',
domain: 'Tools' | 'Protocol' | 'Communication' | 'Process' | 'Debugging' | 'Decision',
situation: string, // When this applies
approach: string, // What was done
outcome: string, // What happened
reasoning: string, // Why it worked/failed
alternative?: string // For ineffective: what to use instead
}Example:
await mcp__learning_library__record_experience({
scope: 'user',
type: 'effective',
domain: 'Protocol',
situation: 'Before any file write operation',
approach: 'Call mcp__protocol-enforcer__verify_protocol_compliance first',
outcome: 'File operation succeeds without blocking',
reasoning: 'Protocol enforcer requires authorization token before allowing writes'
});Search experiences with FTS5 full-text search.
Parameters:
{
query?: string, // FTS5 full-text search (optional)
domain?: 'Tools' | 'Protocol' | 'Communication' | 'Process' | 'Debugging' | 'Decision',
type?: 'effective' | 'ineffective',
limit?: number // Default: 50
}Example:
// Find all Protocol experiences
const protocolPatterns = await mcp__learning_library__search_experiences({
domain: 'Protocol',
type: 'effective'
});
// Full-text search
const reasoningRules = await mcp__learning_library__search_experiences({
query: 'informed_reasoning mandatory'
});Export experiences to JSON or Markdown.
Parameters:
{
scope: 'user' | 'project', // Default: 'user'
format: 'json' | 'markdown', // Default: 'json'
domain?: 'Tools' | 'Protocol' | 'Communication' | 'Process' | 'Debugging' | 'Decision',
type?: 'effective' | 'ineffective',
filename?: string // Auto-generated if not provided
}Example:
// Export all user-level experiences as JSON
await mcp__learning_library__export_experiences({
scope: 'user',
format: 'json'
});
// Export project Protocol experiences as Markdown
await mcp__learning_library__export_experiences({
scope: 'project',
format: 'markdown',
domain: 'Protocol'
});The --record-last-session flag enables automatic experience recording triggered by PostToolUse hooks after successful file operations.
1. PostToolUse hook creates recording token:
{
"sessionId": "08e2e62e-a02b-4018-91bc-148c45209523",
"toolName": "Edit",
"timestamp": "2026-01-26T16:20:26.938Z",
"context": {
"filePath": "/path/to/project/test.txt",
"cwd": "/path/to/project",
"transcriptPath": "/Users/name/.claude/projects/.../session.jsonl"
}
}File location: ~/.protocol-session-recording-token
2. Hook spawns recording process:
npx -y https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86 --record-last-sessionEnvironment variables passed:
CLAUDE_SESSION_ID: Session identifierMEMORY_AUGMENTED_REASONING_PROJECT_DB: Project database pathFORCE_COLOR=0: Disable color output
3. Recording script execution:
The --record-last-session handler (index.js:1340-1440):
// Read and consume recording token
const recordingTokenFile = path.join(os.homedir(), '.protocol-session-recording-token');
if (fs.existsSync(recordingTokenFile)) {
const tokenData = JSON.parse(fs.readFileSync(recordingTokenFile, 'utf8'));
sessionId = tokenData.sessionId;
toolName = tokenData.toolName || 'tool';
timestamp = tokenData.timestamp;
filePath = tokenData.context?.filePath || 'unknown';
cwd = tokenData.context?.cwd || process.cwd();
// Consume token
fs.unlinkSync(recordingTokenFile);
}
// Generate context-rich experience
const fileDisplayName = filePath !== 'unknown' ? path.basename(filePath) : 'unknown file';
const experience = {
type: 'effective',
domain: 'Tools',
situation: `${toolName} operation on ${fileDisplayName} at ${timestamp}`,
approach: `Protocol flow: informed_reasoning → verify → authorize → ${toolName}`,
outcome: `Successfully completed ${toolName} operation following protocol requirements`,
reasoning: 'Following protocol workflow with automatic experience recording',
context: `session: ${sessionId}, file: ${filePath}, cwd: ${cwd}`,
confidence: 0.8,
scope: 'project' // or 'user' based on config
};
// Save to database
recordExperience(dbs, experience);With file context (correct):
situation: "Edit operation on test.txt at 2026-01-26T16:20:26.938Z"
approach: "Protocol flow: informed_reasoning → verify → authorize → Edit"
outcome: "Successfully completed Edit operation following protocol requirements"
reasoning: "Following protocol workflow with automatic experience recording"
context: "session: 08e2e62e-a02b-4018-91bc-148c45209523, file: /path/to/test.txt, cwd: /path/to/project"
Without file context (broken - indicates hook issue):
situation: "tool operation on unknown file at 2026-01-26T16:20:26.938Z"
context: "session: ..., file: unknown, cwd: /path/to/project"
The recording token is separate from protocol enforcement tokens:
| Token File | Created By | Consumed By | Purpose |
|---|---|---|---|
.protocol-informed-reasoning-token |
informed_reasoning | PreToolUse hook | Proves analyze phase completed |
.protocol-enforcer-token |
authorize_file_operation | PreToolUse hook | Proves operation authorized |
.protocol-search-required-token |
informed_reasoning | search_experiences | Enforces suggested searches |
.protocol-session-recording-token |
PostToolUse hook | --record-last-session | Passes file context for recording |
Key difference: The recording token is NOT checked by PreToolUse hook - it's only consumed by the recording script.
Experiences are saved to:
- Project scope:
{project}/.cursor/memory-augmented-reasoning.db - User scope:
~/.cursor/memory-augmented-reasoning.db
Scope determined by .protocol-enforcer.json:
{
"automatic_experience_recording": {
"enabled": true,
"scope": "project" // or "user"
}
}Agent can test recording functionality:
# 1. Create test recording token
cat > ~/.protocol-session-recording-token << 'EOF'
{
"sessionId": "test-session-123",
"toolName": "Edit",
"timestamp": "2026-01-26T16:20:00.000Z",
"context": {
"filePath": "/path/to/test.txt",
"cwd": "/path/to/project",
"transcriptPath": null
}
}
EOF
# 2. Run recording script (agent must use actual project path)
cd /path/to/project
MEMORY_AUGMENTED_REASONING_PROJECT_DB="$(pwd)/.cursor/memory-augmented-reasoning.db" \
npx -y https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86 --record-last-session
# Expected output:
# [memory-augmented-reasoning-mcp] Experience recorded automatically: 1 (save)
# 3. Verify experience was saved
sqlite3 .cursor/memory-augmented-reasoning.db \
"SELECT id, situation, context FROM experiences ORDER BY id DESC LIMIT 1"
# Expected output:
# 1|Edit operation on test.txt at 2026-01-26T16:20:00.000Z|session: test-session-123, file: /path/to/test.txt, cwd: /path/to/project
# 4. Verify token was consumed
ls ~/.protocol-session-recording-token 2>/dev/null || echo "✅ Token consumed"Problem: Experiences show "unknown file"
# Check if PostToolUse hook is creating enhanced token
# After Edit operation, immediately check:
cat ~/.protocol-session-recording-token
# Should show:
# {"sessionId":"...","toolName":"Edit",...,"context":{"filePath":"/actual/path/..."}}
# If filePath is "unknown" or null, PostToolUse hook needs updateProblem: No experiences being recorded
# 1. Check if PostToolUse hook is configured
cat .claude/settings.json | grep -A 5 "PostToolUse"
# 2. Check if recording is enabled in config
cat .protocol-enforcer.json | grep -A 5 "automatic_experience_recording"
# 3. Check audit log to see if recording was triggered
tail ~/.protocol-enforcer-audit.log
# 4. Manually test recording (see testing section above)Problem: Recording script fails
# Check for errors in background process
# Look for npx error logs:
ls ~/.npm/_logs/
# Check database permissions
ls -la .cursor/memory-augmented-reasoning.db
# Manually run recording with stderr visible
npx -y https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86 --record-last-session
# (Create token first as shown in testing section)This server creates and manages three types of protocol tokens:
File: ~/.protocol-informed-reasoning-token
Created: After analyze phase completes successfully
Lifetime: 60 seconds
Code: index.js:1145-1169
Critical fix in v2.0.5: Token creation moved OUTSIDE if (dbs.user) block to ensure it's ALWAYS created, even when user database doesn't exist.
// CRITICAL: Token creation MUST happen regardless of database availability
const sessionId = getSessionId();
if (phase === 'analyze') {
const tokenFile = path.join(os.homedir(), '.protocol-informed-reasoning-token');
try {
const now = new Date();
const expires = new Date(now.getTime() + 60000);
const tokenData = {
sessionId,
phase,
timestamp: now.toISOString(),
expires: expires.toISOString()
};
fs.writeFileSync(tokenFile, JSON.stringify(tokenData), 'utf8');
console.error(`[memory-augmented-reasoning-mcp] ✓ Token created: ${tokenFile}`);
} catch (err) {
console.error('[memory-augmented-reasoning-mcp] ✗ FAILED to write token:', err.message);
console.error('[memory-augmented-reasoning-mcp] Stack:', err.stack);
}
}Debug logging: Added in v2.0.5 to diagnose token creation failures.
File: ~/.protocol-search-required-token
Created: When analyze phase suggests searching experiences
Consumed: By search_experiences tool
Lifetime: 5 minutes (300,000ms)
Code:
- Creation: index.js:1170-1182
- Consumption: index.js:576-586
- Cleanup: index.js:1094-1115
Purpose: Enforces that AI agents actually search experiences when informed_reasoning suggests it.
// Create search token when suggesting search
if (result && result.suggestedQueries && result.suggestedQueries.learningLibrary) {
const searchTokenPath = path.join(os.homedir(), '.protocol-search-required-token');
try {
const searchToken = {
timestamp: Date.now(),
sessionId,
suggestedQuery: result.suggestedQueries.learningLibrary.query,
domain: result.suggestedQueries.learningLibrary.domain,
phase: 'analyze'
};
fs.writeFileSync(searchTokenPath, JSON.stringify(searchToken), 'utf8');
console.error('[memory-augmented-reasoning-mcp] ✓ Search token created');
} catch (err) {
console.error('[memory-augmented-reasoning-mcp] ✗ Failed to write search token:', err.message);
}
}File: ~/.protocol-session-{session_id}.json
Created: When session_id parameter provided to informed_reasoning
Lifetime: 60 minutes maximum (REQUEST-SCOPED)
Purpose: Authorizes multi-tool workflows within a SINGLE user request
CRITICAL: Token is REQUEST-SCOPED - each new user message requires new protocol flow.
Usage: Reduces overhead within a single request (e.g., Read → Write → Edit for one task).
AI agents can guide users through these verification tests:
# Clear existing tokens
rm ~/.protocol-informed-reasoning-token 2>/dev/null
# Agent calls informed_reasoning in Claude session
# Example: informed_reasoning(phase="analyze", problem="verify token creation")
# Verify token exists
ls -la ~/.protocol-informed-reasoning-token && echo "✅ Token created" || echo "❌ FAILED"
# Check token content
cat ~/.protocol-informed-reasoning-token
# Expected: {"sessionId":"...","phase":"analyze","timestamp":"...","expires":"..."}
# Check for debug output
# Agent should see in stderr: "✓ Token created: /Users/.../.protocol-informed-reasoning-token"If token doesn't exist:
- Check MCP server loaded:
ps aux | grep memory-augmented-reasoning - Check
~/.claude.jsonconfiguration - Look for error in stderr: "✗ FAILED to write token"
- Reload Claude Code
# Clear search token
rm ~/.protocol-search-required-token 2>/dev/null
# Agent calls informed_reasoning (should suggest search)
# Check if search token created:
ls -la ~/.protocol-search-required-token && echo "✅ Search token created" || echo "❌ No search suggested"
# If token exists, read it:
cat ~/.protocol-search-required-token
# Expected: {"timestamp":...,"sessionId":"...","suggestedQuery":"...","domain":"..."}
# Agent calls search_experiences with suggested query
# Verify token consumed:
ls -la ~/.protocol-search-required-token 2>/dev/null || echo "✅ Token consumed by search_experiences"# After Edit operation, wait for background recording
sleep 5
# Check database
sqlite3 .cursor/memory-augmented-reasoning.db \
"SELECT id, situation FROM experiences ORDER BY id DESC LIMIT 1"
# Expected output:
# 1|Edit operation on test.txt at 2026-01-26T16:20:26.938Z
# NOT this (indicates broken recording):
# 1|tool operation on unknown file at ...
# Verify recording token was created and consumed:
ls ~/.protocol-session-recording-token 2>/dev/null || echo "✅ Recording token was consumed"# Agent can manually test recording:
# 1. Create test token
cat > ~/.protocol-session-recording-token << 'EOF'
{
"sessionId": "manual-test",
"toolName": "Edit",
"timestamp": "2026-01-26T16:00:00.000Z",
"context": {
"filePath": "/path/to/test.txt",
"cwd": "/path/to/project",
"transcriptPath": null
}
}
EOF
# 2. Run recording (agent must use actual project path)
MEMORY_AUGMENTED_REASONING_PROJECT_DB="/path/to/project/.cursor/memory-augmented-reasoning.db" \
npx -y https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86 --record-last-session
# 3. Check output
# Expected: "[memory-augmented-reasoning-mcp] Experience recorded automatically: 1 (save)"
# 4. Verify in database
sqlite3 /path/to/project/.cursor/memory-augmented-reasoning.db \
"SELECT situation FROM experiences WHERE situation LIKE '%test.txt%'"
# Expected: "Edit operation on test.txt at 2026-01-26T16:00:00.000Z"NEW: Automatically extract experiences from Claude Code session transcripts using LLM-based analysis.
- Automatic Trigger: SessionEnd hook automatically extracts experiences when sessions complete
- API Key Auto-Discovery: Reads Claude API key from macOS keychain (no manual setup)
- LLM-Based Analysis: Uses Claude 3.5 Haiku for cost-effective pattern extraction
- Confidence Scoring: Categorizes experiences by confidence (high ≥0.9, medium 0.5-0.9)
- Deduplication: Prevents duplicate experiences across databases
- Topic Segmentation: Groups messages by topic for better context analysis
First, install the MCP server following the instructions in the main Installation section above. Then configure the SessionEnd hook for automatic extraction.
Make the CLI commands globally available:
cd memory-augmented-reasoning-mcp
npm install # Install dependencies (better-sqlite3)
npm link # Create global symlinkVerify installation:
memory-augmented-reasoning --version
# Output: memory-augmented-reasoning-mcp v2.0.0The SessionEnd hook automatically triggers experience extraction when Claude Code sessions end.
Create hook file:
# Create hooks directory
mkdir -p .cursor/hooks
# Copy the session-end hook
cp .cursor/hooks/session-end-handoff.cjs .cursor/hooks/session-end-handoff.cjsHook file location: .cursor/hooks/session-end-handoff.cjs
The hook automatically:
- Detects when sessions end
- Reads API key from macOS keychain
- Triggers
memory-augmented-reasoning extract-experiences --session <id> --auto --notify - Runs in background (non-blocking)
Configure in .claude/settings.json:
{
"hooks": {
"sessionEnd": {
"command": ".cursor/hooks/session-end-handoff.cjs"
}
}
}Reload Claude Code:
Cmd+Shift+P → "Developer: Reload Window"
Disable auto-extraction (optional):
# Add to ~/.zshrc or ~/.bashrc
export AUTO_EXTRACT_LEARNINGS=falseWhen disabled, manually trigger extraction:
memory-augmented-reasoning extract-experiences --session <id> --autoList recent sessions with transcripts:
memory-augmented-reasoning list-sessions [--days N]
# Examples
memory-augmented-reasoning list-sessions # Last 7 days (default)
memory-augmented-reasoning list-sessions --days 1 # Last 24 hours
memory-augmented-reasoning list-sessions --days 30 # Last 30 daysOutput includes:
- Session ID
- Last modified date/time
- Transcript file size
- Full file path
Extract experiences from a specific session:
memory-augmented-reasoning extract-experiences --session <session-id> [--auto] [--notify]
# Options
--session <id> Session ID to analyze (required)
--auto Auto-save high confidence experiences (≥0.9) without review
--notify Send desktop notification when complete (macOS only)
# Examples
memory-augmented-reasoning extract-experiences --session abc123
memory-augmented-reasoning extract-experiences --session abc123 --auto
memory-augmented-reasoning extract-experiences --session abc123 --auto --notifyExtraction Process:
- Find Transcripts - Locates main and agent transcripts for session
- Parse Messages - Extracts all messages with role and content
- Segment by Topic - Groups related messages (general, tools, protocol, etc.)
- LLM Analysis - Claude 3.5 Haiku analyzes each segment for patterns
- Deduplicate - Checks against existing experiences to prevent duplicates
- Categorize - Sorts by confidence level:
- High (≥0.9): Auto-saved with
--autoflag - Medium (0.5-0.9): Requires manual review
- Duplicates: Skipped automatically
- High (≥0.9): Auto-saved with
API Key Setup:
The CLI automatically discovers the Claude API key from:
- macOS keychain (service: "Claude Code") - automatic, no setup needed
CLAUDE_API_KEYenvironment variable (fallback)ANTHROPIC_API_KEYenvironment variable (fallback)
If API key not found, you'll see:
⚠️ No API key found (checked keychain and env vars)
💡 Set CLAUDE_API_KEY or ANTHROPIC_API_KEY environment variable
View experience library statistics:
memory-augmented-reasoning stats [--domain <domain>]
# Examples
memory-augmented-reasoning stats # All domains
memory-augmented-reasoning stats --domain Tools # Tools domain onlyOutput includes:
- Total experiences count
- Breakdown by type (effective/ineffective)
- Breakdown by domain
- Average confidence score
- Recent experiences (last 5)
Interactive review of medium-confidence experiences (planned for future release):
memory-augmented-reasoning review-session <session-id>Note: Currently shows placeholder. Interactive review will be added in a future update.
Automatically record experience from the most recent informed_reasoning session (used by protocol-enforcer post-tool-use hook):
npx -y https://gist.github.com/mpalpha/32e02b911a6dae5751053ad158fc0e86 --record-last-sessionHow it works:
- Reads session token from
~/.protocol-informed-reasoning-token - Loads scope configuration from
.protocol-enforcer.json(defaults to 'project') - Auto-generates experience record:
- Type: effective
- Domain: Tools
- Situation: Task analyzed via informed_reasoning session
- Approach: Used informed_reasoning analyze phase before tool execution
- Outcome: Tool execution completed successfully after protocol compliance
- Reasoning: Following protocol workflow
- Confidence: 0.8
- Records to database (with automatic deduplication)
Called automatically by:
- protocol-enforcer v2.0.8+
post-tool-use.cjshook - Triggered after successful execution of Write, Edit, NotebookEdit, Task, WebSearch, or Grep tools
- Runs in background (detached, non-blocking)
Configuration:
{
"automatic_experience_recording": {
"enabled": true,
"scope": "project",
"trigger": "post_tool_use",
"record_for_tools": ["Write", "Edit", "NotebookEdit", "Task", "WebSearch", "Grep"]
}
}Audit logging:
All automatic recordings are logged to ~/.protocol-enforcer-audit.log for debugging.
The .cursor/hooks/session-end-handoff.cjs hook automatically triggers extraction when sessions end:
// Automatically runs on session end
memory-augmented-reasoning extract-experiences --session <id> --auto --notifyFeatures:
- Runs in background (detached process)
- Auto-discovers API key from keychain
- Notifies when complete (macOS)
- Can be disabled with
AUTO_EXTRACT_LEARNINGS=false
Manual Trigger:
To disable auto-extraction and trigger manually:
export AUTO_EXTRACT_LEARNINGS=false
# Sessions will not auto-extract
# Run manually: memory-augmented-reasoning extract-experiences --session <id> --auto# 1. List recent sessions
$ memory-augmented-reasoning list-sessions --days 1
📁 Sessions with transcripts (last 1 days):
1. abc123def456...
Modified: 2026-01-22 10:30:00
Size: 3813.4 KB
Path: /Users/.../.claude/projects/.../abc123def456.jsonl
# 2. Extract experiences
$ memory-augmented-reasoning extract-experiences --session abc123def456 --auto
🔍 Extracting experiences from session: abc123def456
📁 Finding transcripts...
Main: .../abc123def456.jsonl
Agents: 0 agent transcript(s)
📖 Parsing transcripts...
Main transcript: 2041 messages
Total: 2041 messages
🔖 Segmenting by topics...
Created 1 topic segments
Distribution: { general: 1 }
🤖 Extracting experiences with Claude...
Extracted 4 experiences from general segment
Extracted: 4 potential experiences
🔍 Deduplicating and categorizing...
High confidence (≥0.9): 0
Medium confidence (0.5-0.9): 4
Duplicates skipped: 0
⚠️ Medium confidence experiences require review:
4 experiences need manual review
Run: memory-augmented-reasoning review-session abc123def456
✅ Extraction complete!
# 3. View statistics
$ memory-augmented-reasoning stats
📊 Memory-Augmented Reasoning Statistics
Total Experiences: 42
By Type:
effective: 38
ineffective: 4
By Domain:
Process: 29
Protocol: 5
Communication: 3
Tools: 3
Debugging: 2
Average Confidence: 79.8%"API key not found"
# Verify keychain access (macOS)
security find-generic-password -s "Claude Code" -w
# Or set environment variable
export CLAUDE_API_KEY="sk-ant-api03-...""command not found: memory-augmented-reasoning"
# Re-link the CLI
cd memory-augmented-reasoning-mcp
npm link"Session already processed"
Sessions are cached to avoid re-processing. To re-analyze, use the review command (when implemented).
- Tools: Tool selection and usage patterns
- Protocol: Mandatory protocol and workflow requirements
- Communication: User communication preferences and styles
- Process: Standard operating procedures and workflows
- Debugging: Debugging approaches and troubleshooting methods
- Decision: Decision-making patterns and criteria
CREATE TABLE experiences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL CHECK(type IN ('effective', 'ineffective')),
domain TEXT NOT NULL CHECK(domain IN ('Tools', 'Protocol', 'Communication', 'Process', 'Debugging', 'Decision')),
situation TEXT NOT NULL,
approach TEXT NOT NULL,
outcome TEXT NOT NULL,
reasoning TEXT NOT NULL,
alternative TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
-- FTS5 virtual table for full-text search
CREATE VIRTUAL TABLE experiences_fts USING fts5(
situation, approach, outcome, reasoning, alternative,
content='experiences',
content_rowid='id'
);await mcp__learning_library__record_experience({
scope: 'user',
type: 'effective',
domain: 'Tools',
situation: 'Searching codebase for broad patterns',
approach: 'Use Task tool with Explore agent',
outcome: 'Found all relevant files efficiently',
reasoning: 'Explore agent optimized for codebase discovery'
});await mcp__learning_library__record_experience({
scope: 'user',
type: 'ineffective',
domain: 'Tools',
situation: 'Searching codebase for broad patterns',
approach: 'Use Grep tool repeatedly',
outcome: 'Slow, missed many relevant files',
reasoning: 'Grep requires knowing exact search terms',
alternative: 'Use Task tool with Explore agent for broad searches'
});// Before starting a task, query relevant patterns
const toolPatterns = await mcp__learning_library__search_experiences({
domain: 'Tools'
});
const protocolRules = await mcp__learning_library__search_experiences({
domain: 'Protocol',
type: 'effective'
});node index.js --version
# Output: memory-augmented-reasoning-mcp v2.0.0// From Claude Code
await mcp__learning_library__search_experiences({});- User-level database:
~/.cursor/memory-augmented-reasoning.db - Project-level database:
${WORKSPACE_FOLDER}/.cursor/memory-augmented-reasoning.db(if configured) - Export files:
.cursor/experience-exports/
- Single-file design: Entire MCP server in
index.js - SQLite + FTS5: Embedded database with full-text search
- Zero dependencies (except better-sqlite3)
- Environment variable configuration: No config files needed
MIT License - Copyright (c) 2025 Jason Lusk