docs: update documentation to Memory V2 architecture

- Replace four-tier architecture with three-layer Memory V2
- Remove references to non-existent tools (core_memory_*, working_memory_*)
- Update storage paths to ~/.local/share/opencode-working-memory/
- Update configuration to LONG_TERM_LIMITS and HOT_STATE_LIMITS
- Fix installation verification to check system prompt instead of tools
This commit is contained in:
Ralph Chang
2026-04-26 13:27:14 +08:00
parent ff4639d153
commit 802ef62636
5 changed files with 768 additions and 944 deletions
+252 -278
View File
@@ -2,374 +2,348 @@
## Overview
The Working Memory Plugin implements a **four-tier memory architecture** designed to maximize context efficiency for AI agents in OpenCode sessions.
The Working Memory Plugin implements a **three-layer memory architecture** designed to preserve context across OpenCode session compactions.
```
┌─────────────────────────────────────────────────────────────┐
TIER 1: CORE MEMORY
│ Persistent blocks: goal (1000) | progress (2000) | context (1500)
Survives compaction, always visible in system prompt
LAYER 1: WORKSPACE MEMORY (Long-term, cross-session)
Persistent storage: ~/.local/share/opencode-working-...
• Types: feedback | project | decision | reference
│ • Sources: explicit | compaction | manual │
│ • Limits: 5200 chars / 28 entries │
│ • Survives: session reset, workspace switch │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
TIER 2: WORKING MEMORY
│ Session-scoped slots + memory pool
Slots: error(3) | decision(5) | todo(3) | dependency(3)
Pool: Exponential decay (γ=0.85) + mention tracking
LAYER 2: HOT SESSION STATE (Short-term, per-session)
Session-scoped tracking: active files, open errors
• Storage: sessions/{sessionID}.json
• Auto-extracted from tool usage patterns
│ • Cleared: on new session start │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
TIER 3: SMART PRUNING
Filters tool outputs before adding to conversation │
Removes: file lists, verbose logs, repetitive content
Modes: normal → aggressive → hyper-aggressive
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ TIER 4: PRESSURE MONITORING │
│ Tracks context usage: safe → moderate → high │
│ Thresholds: 75% (moderate) | 90% (high) │
│ Intervention: Sends promptAsync() with full visible prompt │
LAYER 3: NATIVE OPENCODE STATE
• Uses OpenCode's built-in todos during compaction
• No additional storage required
• Delegated to OpenCode's native features
└─────────────────────────────────────────────────────────────┘
```
## Phase 1: Core Memory Foundation
## Layer 1: Workspace Memory
### Purpose
Provide persistent memory blocks that survive conversation compaction and are always injected into the system prompt.
Long-term memory that persists across sessions within the same workspace. Perfect for:
- Project conventions and patterns
- Important decisions that span sessions
- User preferences for this codebase
### Storage
- **Location**: `.opencode/memory-core/<sessionID>.json`
- **Location**: `~/.local/share/opencode-working-memory/workspaces/{workspaceKey}/workspace-memory.json`
- **Workspace Key**: First 16 chars of `sha256(realpath(workspaceRoot))`
- **Schema**:
```typescript
{
sessionID: string;
blocks: {
goal: { content: string; chars: number; maxChars: 1000; updatedAt: string };
progress: { content: string; chars: number; maxChars: 2000; updatedAt: string };
context: { content: string; chars: number; maxChars: 1500; updatedAt: string };
};
updatedAt: string;
version: 1,
workspace: { root: string, key: string },
limits: { maxRenderedChars: 5200, maxEntries: 28 },
entries: LongTermMemoryEntry[],
updatedAt: string
}
```
### Character Limits
- **goal**: 1000 chars (ONE specific task)
- **progress**: 2000 chars (done/in-progress/blocked checklist)
- **context**: 1500 chars (current working files + key patterns)
### Entry Types
### Operations
- **replace**: Completely replace block content
- **append**: Add content to end (auto-adds newline)
| Type | Purpose | Example |
|------|---------|---------|
| `feedback` | User preferences | "User prefers functional React components" |
| `project` | Project-level info | "This monorepo uses turborepo" |
| `decision` | Important decisions | "Use PostgreSQL for primary database" |
| `reference` | Key references | "API endpoints defined in `src/api/`" |
### Tools
- `core_memory_update`: Update or append to blocks
- `core_memory_read`: Read current state of all blocks
### Entry Sources
| Source | Confidence | How Added |
|--------|------------|-----------|
| `explicit` | 1.0 | User said "remember this" |
| `compaction` | 0.75 | Extracted during compaction |
| `manual` | varies | Programmatically added |
### Memory Extraction
During compaction, the plugin scans for `<workspace_memory_candidates>` blocks:
```
<workspace_memory_candidates>
- [decision] Use npm cache for plugin loading
- [project] This repo uses TypeScript with strict mode
</workspace_memory_candidates>
```
**Quality Gate**: Not all candidates become memories. The plugin rejects:
- Git commit hashes (e.g., `abc1234`)
- Raw errors (e.g., `Error: something failed`)
- Stack traces
- Path-heavy facts (>50% paths)
- Very short text (<20 chars)
### Deduplication
Memories are deduplicated using **canonical text matching**:
1. Normalize: lowercase, strip punctuation, collapse whitespace
2. Hash the canonical text
3. Keep the entry with highest confidence
### System Prompt Injection
Blocks are injected into every agent message as:
Workspace memory is injected at the top of every message:
```
<core_memory>
<goal chars="87/1000">...</goal>
<progress chars="560/2000">...</progress>
<context chars="479/1500">...</context>
</core_memory>
<workspace_memory>
- [decision] Use npm cache for plugin loading, not npm link
- [project] This repo uses opencode-agenthub plugin system
- [reference] Storage: ~/.local/share/opencode-working-memory/...
</workspace_memory>
```
## Phase 2: Smart Pruning
## Layer 2: Hot Session State
### Purpose
Reduce context bloat by filtering tool outputs before they enter the conversation history.
### Pruning Modes
#### Normal Mode (Pressure < 75%)
- Remove file/directory listings > 50 lines
- Truncate verbose tool outputs
- Keep first/last 30 lines of long outputs
- Preserve error messages and key information
#### Aggressive Mode (75% ≤ Pressure < 90%)
- Threshold drops to 30 lines
- More aggressive truncation (first/last 20 lines)
- Filter repetitive content
#### Hyper-Aggressive Mode (Pressure ≥ 90%)
- Threshold drops to 15 lines
- Keep only first/last 10 lines
- Maximum compression
### Pruning Heuristics
1. **File Listings**: Detect `ls`, `find`, `glob` outputs
2. **Directory Trees**: Detect tree-like structures with `/`
3. **Log Files**: Detect timestamp patterns, stack traces
4. **Repetitive Content**: Detect similar consecutive lines
5. **Synthetic Content**: Preserve `synthetic: true` markers
### Implementation
Pruning happens in `tool.execute.after` hook before tool output enters conversation.
## Phase 3: Working Memory
### Purpose
Provide session-scoped memory with structured slots and a general-purpose pool with intelligent decay.
Track current session context automatically:
- What files are you working on?
- What errors are currently open?
- What decisions were made recently?
### Storage
- **Location**: `.opencode/memory-working/<sessionID>.json`
- **Location**: `~/.local/share/opencode-working-memory/workspaces/{workspaceKey}/sessions/{hashedSessionID}.json`
- **Schema**:
```typescript
{
sessionID: string;
slots: {
error: Array<WorkingMemoryItem>; // Max 3
decision: Array<WorkingMemoryItem>; // Max 5
todo: Array<WorkingMemoryItem>; // Max 3
dependency: Array<WorkingMemoryItem>; // Max 3
};
pool: Array<WorkingMemoryItem>;
eventCounter: number;
updatedAt: string;
version: 1,
sessionID: string,
turn: number,
updatedAt: string,
activeFiles: ActiveFile[],
openErrors: OpenError[],
recentDecisions: SessionDecision[]
}
```
### Slot Types
### Active Files
| Slot | Max Items | Purpose |
|------|-----------|---------|
| **error** | 3 | Recent errors that need fixing |
| **decision** | 5 | Important decisions made |
| **todo** | 3 | Current task checklist |
| **dependency** | 3 | File/package dependencies |
Automatically tracked from `tool.execute.before` events:
### Memory Pool
| Action | Ranking Boost |
|--------|---------------|
| `write` | 4x |
| `edit` | 3x |
| `read` | 2x |
| `grep` | 1x |
General-purpose storage with **exponential decay**:
Files are ranked by: `count * action_weight * recency_decay`
```typescript
score = exp(-γ * age) + mentionCount
```
### Open Errors
Where:
- `γ = 0.85` (decay rate, 15% per event)
- `age = eventCounter - item.eventNumber`
- `mentionCount`: Number of times item mentioned in conversation
Tracked from `tool.execute.after` events when `exitCode !== 0`:
Items with `score < 0.01` are pruned.
| Category | Trigger Pattern |
|----------|-----------------|
| `typecheck` | `TS####:` or TypeScript errors |
| `test` | Test failures |
| `lint` | ESLint warnings/errors |
| `build` | Build failures |
| `runtime` | `Error:`, `TypeError:`, etc. |
### Auto-Extraction
**False Positive Guards**:
- Commands like `git log`, `cat` with "error" in output are ignored
- Only actual command failures (`exitCode !== 0`) trigger errors
- `exitCode === undefined` is treated as success (no error tracking)
Working memory items are **automatically extracted** from:
- Tool outputs (file paths, errors, dependencies)
- User messages (decisions, todos)
- Assistant responses (key information)
### Error Fingerprinting
### Manual Management
Errors are fingerprinted by:
1. Extract error message summary
2. Generate fingerprint: `first 12 chars of sha256(summary)`
3. Group similar errors by fingerprint
Tools:
- `working_memory_add`: Manually add item
- `working_memory_clear`: Clear all items
- `working_memory_clear_slot`: Clear specific slot (e.g., after fixing all errors)
- `working_memory_remove`: Remove specific item by content match
### recentDecisions
Short-term decisions made this session. Candidates for promotion to workspace memory during compaction.
### System Prompt Injection
Hot session state is injected after workspace memory:
```
<working_memory>
Recent session context (auto-managed, sorted by relevance):
---
<workspace_memory_candidates>
- [project] This repo uses TypeScript with strict mode
</workspace_memory_candidates>
⚠️ Errors:
- TypeError at line 42 in utils.ts
- Missing import in index.ts
Active Files:
- src/plugin.ts (edit, 18x)
- tests/plugin.test.ts (edit, 5x)
📁 Key Files:
- src/components/Button.tsx
- src/utils/helpers.ts
(15 items shown, updated: 9:46:47 AM)
</working_memory>
Open Errors: (none)
```
## Phase 4: Pressure Monitoring
## Layer 3: Native OpenCode State
### Purpose
Track conversation context usage and trigger interventions when approaching limits.
### Pressure Calculation
Delegate task tracking to OpenCode's native features.
### Behavior
- Uses OpenCode's built-in `todos` during compaction
- No additional storage or injection required
- Allows the agent to manage task lists natively
## Plugin Hooks
The plugin hooks into OpenCode lifecycle events:
### `prompt:before`
Injects workspace memory and hot session state into system prompt.
### `tool.execute.before`
Tracks active files (read, grep, edit, write actions).
### `tool.execute.after`
- Tracks open errors from failed commands
- Clears errors when commands succeed
- Ignores `exitCode === undefined` (successful commands without explicit exit codes)
### `compaction:before`
Extracts workspace memory candidates from conversation.
Applies quality gate, deduplication, and source priority.
## Quality Guarantees
### No False Positive Errors
```typescript
pressure = (visiblePromptChars / estimatedContextLimit) * 100
// Bad: Would create false positive
"Error: something failed" in output
// Good: Actually failed
exitCode === 1 && output.includes("Error")
// Good: Actually succeeded
exitCode === 0 (clears errors for that category)
// Good: Ignore ambiguous cases
exitCode === undefined → skip error tracking
```
Where:
- `visiblePromptChars`: Total characters in system prompt + tool outputs
- `estimatedContextLimit`: ~180,000 chars (conservative estimate)
### Pressure Levels
| Level | Threshold | Behavior |
|-------|-----------|----------|
| **safe** | < 75% | Normal operation |
| **moderate** | 75-89% | Warning in system prompt + aggressive pruning |
| **high** | ≥ 90% | Hyper-aggressive pruning + intervention |
### Pressure Storage
- **Location**: `.opencode/memory-working/<sessionID>_pressure.json`
- **Schema**:
```typescript
{
sessionID: string;
level: "safe" | "moderate" | "high";
percentage: number;
visiblePromptChars: number;
estimatedLimit: 180000;
lastChecked: string;
interventionsSent: number;
}
```
### Intervention Mechanism
When pressure reaches **high** (≥90%):
1. Plugin sends `promptAsync()` message to agent
2. Message includes full visible prompt for review
3. Agent can compress core memory, clear working memory, or continue
4. Intervention tracked in `interventionsSent` counter
### System Prompt Injection
```
[Memory Pressure: 87% (high) - 156,600/180,000 chars]
⚠️ High memory pressure detected. Consider:
- Compressing core_memory blocks (use core_memory_update)
- Clearing resolved errors (use working_memory_clear_slot)
- Removing old pool items (auto-pruned at score < 0.01)
```
## Phase 4.5: Storage Governance
### Purpose
Prevent `.opencode/` directory bloat from accumulating tool output caches and orphaned memory files.
### Layer 1: Session Deletion Cleanup
**Trigger**: `experimental.session.deleted` hook
**Actions**:
1. Remove `.opencode/memory-core/<sessionID>.json`
2. Remove `.opencode/memory-working/<sessionID>.json`
3. Remove `.opencode/memory-working/<sessionID>_pressure.json`
4. Remove `.opencode/memory-working/<sessionID>_compaction.json`
### Layer 2: Tool Output Cache Sweep
**Trigger**: Every 500 events (`eventCounter % 500 === 0`)
**Target**: `.opencode/cache/tool-outputs/` directory
**Policy**:
- Keep most recent **300 files** (sorted by mtime)
- Delete files older than **7 days** (TTL policy)
**Logging**: Write sweep results to `.opencode/memory-working/<sessionID>_sweep.json`
### Negative Memory Filtering
```typescript
{
sessionID: string;
timestamp: string;
eventCounter: number;
results: {
filesScanned: number;
filesDeleted: number;
bytesReclaimed: number;
errors: Array<string>;
};
}
// Correctly interpreted
"don't remember this" → NOT added to memory
"不要記住這個" → NOT added to memory
"remember this" → added to memory candidates
```
### Canonical Deduplication
```typescript
// Same memory (after normalization)
"Use npm cache for plugins"
"USE NPM CACHE for plugins!!"
"use npm cache for plugins."
// All map to same canonical key
canonical("Use npm cache for plugins") === "use npm cache for plugins"
```
### Compaction Quality Gate
```typescript
// Rejected (not valuable as long-term memory)
"4832b38 fix: something" // git hash
"Error: something failed" // raw error
"at Object.method (file.ts:42)" // stack trace
"/Users/x/project/file.ts /Users/x/project/other.ts" // path-heavy
// Accepted
"[decision] Use npm cache for plugin loading" // good pattern
```
## File System Layout
```
~/.local/share/opencode-working-memory/
└── workspaces/
└── {workspaceKey}/
├── workspace-memory.json # Long-term memory
└── sessions/
└── {hashedSessionID}.json # Session state
```
### Workspace Key
```typescript
// First 16 chars of SHA-256 hash of workspace root realpath
const workspaceKey = sha256(realpath(workspaceRoot)).slice(0, 16)
```
## Performance Considerations
### Memory Budgets
- **Core Memory**: 4,500 chars (injected every message)
- **Working Memory**: ~1,600 chars (injected every message)
- **Total Overhead**: ~6,100 chars per message
### Compaction Behavior
When OpenCode compacts conversation (clears old messages):
- Core memory: **Preserved** (persistent across compactions)
- Working memory: **Preserved** (session-scoped, cleared on session end)
- Pressure state: **Preserved** (tracks across compaction)
- Compaction log: Saved to `<sessionID>_compaction.json`
| Layer | Max Chars | Max Entries |
|-------|-----------|-------------|
| Workspace Memory | 5200 | 28 |
| Hot Session State | 1200 | 8 files, 3 errors |
### Injection Overhead
- Workspace memory: ~200-500 chars per message
- Hot session state: ~200-400 chars per message
- Total: ~400-900 chars per message (minimal)
### Storage Footprint
- Each session: 4 JSON files (~5-20 KB total)
- Tool output cache: Max 300 files (~10-50 MB depending on outputs)
- Sweep every 500 events keeps storage bounded
- Workspace memory: ~2-5 KB per workspace
- Session state: ~1-3 KB per session
- Auto-cleanup on workspace/session deletion
## Extension Points
### Custom Slot Types
To add new slot types:
1. Update `SlotType` union in types
2. Add to `SLOT_CONFIG` with max items
3. Update `formatWorkingMemoryForPrompt()` for display
4. Update extraction heuristics in `tool.execute.after`
### Custom Memory Types
### Custom Pruning Rules
To add pruning heuristics:
1. Update `shouldPrune()` with new detection logic
2. Add to `pruneToolOutput()` with filtering rules
3. Test with representative tool outputs
### Custom Pressure Thresholds
Adjust in constants:
Add new types in `src/types.ts`:
```typescript
const PRESSURE_THRESHOLDS = {
moderate: 70,
high: 85,
critical: 95,
};
export type LongTermType = "feedback" | "project" | "decision" | "reference" | "custom";
```
## Migration & Compatibility
### Custom Error Categories
### Old Format → New Format
Plugin automatically migrates from old format:
Add new categories in `src/types.ts`:
```typescript
// Old format (pre-Phase 3)
{ items: Array<Item> }
// New format (Phase 3+)
{ slots: Record<SlotType, Array<Item>>, pool: Array<Item> }
export type ErrorCategory = "typecheck" | "test" | "lint" | "build" | "runtime" | "custom";
```
Migration happens on first load of old format files.
### Custom Extraction Patterns
## File System Layout
Modify `src/extractors.ts` to add new extraction patterns.
```
.opencode/
├── memory-core/
│ └── <sessionID>.json # Core memory blocks
├── memory-working/
│ ├── <sessionID>.json # Working memory (slots + pool)
│ ├── <sessionID>_pressure.json # Pressure monitoring state
│ ├── <sessionID>_compaction.json # Compaction event log
│ └── <sessionID>_sweep.json # Storage sweep log
└── cache/
└── tool-outputs/
└── *.json # Tool output cache (auto-swept)
```
## Migration Notes
## Security Considerations
### Memory V1 to V2
- All files written with `0644` permissions (owner read/write, group/others read)
- Directories created with `0755` permissions (owner rwx, group/others rx)
- No sensitive data should be stored in memory blocks (user responsibility)
- Session IDs are opaque identifiers, not derived from sensitive data
The plugin automatically migrates old format files to the new three-layer architecture. No manual intervention needed.
---
**Last Updated**: February 2026
**Implementation**: `index.ts` (1700+ lines)
**Last Updated**: April 2026
**Implementation**: `src/plugin.ts`, `src/extractors.ts`, `src/workspace-memory.ts`, `src/session-state.ts`
+132 -302
View File
@@ -2,250 +2,120 @@
## Overview
The Working Memory Plugin works out-of-the-box with sensible defaults. Advanced users can customize behavior by modifying constants in `index.ts`.
The Working Memory Plugin works out-of-the-box with sensible defaults. Configuration is defined in `src/types.ts` as constants.
## Core Memory Limits
## Workspace Memory Limits
```typescript
const CORE_MEMORY_LIMITS = {
goal: 1000, // ONE specific task (not project-wide goals)
progress: 2000, // Checklist format (✅ done, ⏳ in-progress, ❌ blocked)
context: 1500, // Current working files + key patterns
const LONG_TERM_LIMITS = {
maxRenderedChars: 5200, // Maximum characters in system prompt
targetRenderedChars: 4200, // Target characters (leave buffer)
maxEntries: 28, // Maximum number of entries
maxEntryTextChars: 260, // Maximum characters per entry text
maxRationaleChars: 180, // Maximum characters per entry rationale
};
```
**Recommendations**:
- Keep **goal** focused on current task (clear when completed)
- Use **progress** for checklists (avoid line numbers, commit hashes, API signatures)
- Use **context** for files you're actively editing (avoid type definitions, function signatures)
- Keep `maxRenderedChars` under 5500 to avoid context bloat
- `maxEntries` of 28 provides good coverage without overwhelming
- Entry text limits ensure entries stay concise
## Working Memory Configuration
### Slot Limits
## Hot Session State Limits
```typescript
const SLOT_CONFIG: Record<SlotType, number> = {
error: 3, // Recent errors needing fixes
decision: 5, // Important decisions made
todo: 3, // Current task checklist
dependency: 3, // File/package dependencies
const HOT_STATE_LIMITS = {
maxRenderedChars: 1200, // Maximum characters in system prompt
maxActiveFilesStored: 20, // Maximum files tracked in state
maxActiveFilesRendered: 8, // Maximum files shown in prompt
maxOpenErrorsStored: 5, // Maximum errors tracked
maxOpenErrorsRendered: 3, // Maximum errors shown in prompt
maxRecentDecisionsStored: 8, // Maximum decisions tracked
};
```
**Tuning**:
- Increase slot limits if you need more items tracked
- Decrease for stricter memory budgets
- Total overhead: ~100-200 chars per item
**Recommendations**:
- Keep `maxRenderedChars` under 1500 for fast prompts
- `maxActiveFilesRendered` of 8 provides good context coverage
- `maxOpenErrorsRendered` of 3 avoids overwhelming error lists
### Memory Pool Decay
## Memory Types
```typescript
const POOL_DECAY_GAMMA = 0.85; // Exponential decay rate (15% per event)
const POOL_MIN_SCORE = 0.01; // Items below this score are pruned
### Long-Term Memory Types
| Type | Purpose | Stale After (days) |
|------|---------|---------------------|
| `feedback` | User preferences for workspace | 90 |
| `project` | Project-level information | 60 |
| `decision` | Important decisions | 45 |
| `reference` | Key references | 90 |
### Memory Sources
| Source | Confidence | Description |
|--------|------------|-------------|
| `explicit` | 1.0 | User explicitly said "remember this" |
| `compaction` | 0.75 | Extracted during conversation compaction |
| `manual` | varies | Added programmatically |
## Active File Scoring
Files are ranked by action type:
| Action | Weight | Description |
|--------|--------|-------------|
| `write` | 4 | File created/overwritten |
| `edit` | 3 | File modified |
| `read` | 2 | File read |
| `grep` | 1 | Grep searched in file |
Score formula: `count * action_weight * recency_decay`
## Error Categories
| Category | Recognition Pattern |
|----------|---------------------|
| `typecheck` | TS errors, TypeScript failures |
| `test` | Test failures |
| `lint` | ESLint warnings/errors |
| `build` | Build failures |
| `runtime` | Uncaught errors, Node exceptions |
| `tool` | Tool execution failures |
## Storage Paths
```
~/.local/share/opencode-working-memory/
└── workspaces/
└── {workspaceKey}/
├── workspace-memory.json # Long-term memory
└── sessions/
└── {sessionID}.json # Session state
```
**Formula**: `score = exp(-γ * age) + mentionCount`
**Tuning**:
- Lower `γ` (e.g., 0.75) → faster decay, more aggressive pruning
- Higher `γ` (e.g., 0.90) → slower decay, items stay longer
- Lower `POOL_MIN_SCORE` (e.g., 0.005) → more items retained
### Pool Size Limits
### Workspace Key
```typescript
const POOL_MAX_ITEMS = 50; // Hard limit on pool size
// First 16 characters of SHA-256 hash
const workspaceKey = sha256(realpath(workspaceRoot)).slice(0, 16);
```
**Tuning**:
- Increase for longer sessions with more context
- Decrease for stricter memory budgets
- Each item adds ~50-150 chars to system prompt
## Customization
## Pressure Monitoring
### Thresholds
To customize limits, edit the constants in `src/types.ts`:
```typescript
const PRESSURE_THRESHOLDS = {
moderate: 75, // Warning appears in system prompt
high: 90, // Aggressive pruning activates + intervention sent
// Example: Increase workspace memory limit
export const LONG_TERM_LIMITS = {
maxRenderedChars: 6000, // Increased from 5200
maxEntries: 35, // Increased from 28
// ...
};
```
**Tuning**:
- Increase thresholds for more relaxed monitoring
- Decrease for earlier warnings and interventions
### Context Limit Estimate
```typescript
const ESTIMATED_CONTEXT_LIMIT = 180000; // Conservative estimate (chars)
```
**Note**: OpenCode actual limit varies by model. Adjust based on your observations.
## Smart Pruning
### Line Thresholds
```typescript
// Normal mode (pressure < 75%)
const PRUNE_THRESHOLD_NORMAL = 50;
// Aggressive mode (75% ≤ pressure < 90%)
const PRUNE_THRESHOLD_AGGRESSIVE = 30;
// Hyper-aggressive mode (pressure ≥ 90%)
const PRUNE_THRESHOLD_HYPER = 15;
```
**Tuning**:
- Increase thresholds to keep more tool output
- Decrease for more aggressive pruning
### Keep Lines
```typescript
// Normal mode
const KEEP_LINES_NORMAL = 30; // Keep first/last 30 lines
// Aggressive mode
const KEEP_LINES_AGGRESSIVE = 20; // Keep first/last 20 lines
// Hyper-aggressive mode
const KEEP_LINES_HYPER = 10; // Keep first/last 10 lines
```
**Tuning**:
- Increase to preserve more context from tool outputs
- Decrease for stricter truncation
## Storage Governance
### Session Cleanup
Automatically triggered on `experimental.session.deleted` hook. No configuration needed.
### Tool Output Cache Sweep
```typescript
const SWEEP_INTERVAL = 500; // Trigger every N events
const SWEEP_MAX_FILES = 300; // Keep most recent N files
const SWEEP_TTL_DAYS = 7; // Delete files older than N days
```
**Tuning**:
- Increase `SWEEP_INTERVAL` for less frequent sweeps (lower overhead)
- Increase `SWEEP_MAX_FILES` to cache more tool outputs (more disk usage)
- Increase `SWEEP_TTL_DAYS` to keep older files longer
## Compaction Behavior
### Item Preservation
```typescript
const COMPACTION_KEEP_ITEMS = 10; // Preserve N most recent items on compaction
```
**Tuning**:
- Increase to preserve more working memory across compactions
- Decrease for stricter memory reset on compaction
## System Prompt Injection
### Core Memory Format
```typescript
// Injected as:
<core_memory>
<goal chars="87/1000">...</goal>
<progress chars="560/2000">...</progress>
<context chars="479/1500">...</context>
</core_memory>
```
**Customization**: Modify `formatCoreMemoryForPrompt()` in `index.ts` to change format.
### Working Memory Format
```typescript
// Injected as:
<working_memory>
Recent session context (auto-managed, sorted by relevance):
Errors:
- item content
📁 Key Files:
- file path
(N items shown, updated: HH:MM:SS AM)
</working_memory>
```
**Customization**: Modify `formatWorkingMemoryForPrompt()` in `index.ts` to change:
- Section emoji/icons
- Display format
- Item ordering
### Pressure Warning Format
```typescript
// Injected as:
[Memory Pressure: 87% (high) - 156,600/180,000 chars]
High memory pressure detected. Consider:
- Action item 1
- Action item 2
```
**Customization**: Modify `formatPressureWarning()` in `index.ts`.
## Auto-Extraction Heuristics
### File Path Detection
```typescript
// Detects:
- Absolute paths: /users/name/project/file.ts
- Relative paths: src/components/Button.tsx
- Dot paths: ./utils/helpers.ts
- Tilde paths: ~/project/file.ts
```
**Customization**: Modify regex in `extractFilePaths()`.
### Error Detection
```typescript
// Detects:
- "Error:", "ERROR:", "error:"
- Stack traces with "at " prefix
- TypeScript errors with "TS####:"
```
**Customization**: Modify `extractErrors()` heuristics.
### Decision Detection
```typescript
// Detects:
- "decided to...", "decision:", "chose to..."
- "using X instead of Y"
- "will use X approach"
```
**Customization**: Modify `extractDecisions()` heuristics.
## Environment Variables
Currently, the plugin does not support environment variables. All configuration is done via constants in `index.ts`.
**Future Enhancement**: Consider adding `.env` support for:
```
OPENCODE_WM_CORE_GOAL_LIMIT=1000
OPENCODE_WM_POOL_DECAY_GAMMA=0.85
OPENCODE_WM_SWEEP_INTERVAL=500
**Note**: After customization, rebuild the plugin:
```bash
npm run build
```
## Performance Tuning
@@ -253,123 +123,83 @@ OPENCODE_WM_SWEEP_INTERVAL=500
### High-Frequency Sessions (500+ messages)
```typescript
// Aggressive pruning
const PRUNE_THRESHOLD_NORMAL = 30;
const PRUNE_THRESHOLD_AGGRESSIVE = 20;
// Faster decay
const POOL_DECAY_GAMMA = 0.75;
// More frequent sweeps
const SWEEP_INTERVAL = 250;
// Reduce memory overhead
const HOT_STATE_LIMITS = {
maxRenderedChars: 800, // Reduced
maxActiveFilesRendered: 5, // Reduced
maxOpenErrorsRendered: 2, // Reduced
};
```
### Long-Running Sessions (Multi-day)
```typescript
// Preserve more context
const POOL_MAX_ITEMS = 100;
const COMPACTION_KEEP_ITEMS = 20;
// Slower decay
const POOL_DECAY_GAMMA = 0.90;
// Longer TTL
const SWEEP_TTL_DAYS = 14;
const LONG_TERM_LIMITS = {
maxEntries: 40, // Increased
targetRenderedChars: 5000, // Increased
};
```
### Memory-Constrained Environments
```typescript
// Strict limits
const CORE_MEMORY_LIMITS = {
goal: 500,
progress: 1000,
context: 800,
const LONG_TERM_LIMITS = {
maxRenderedChars: 3000,
maxEntries: 15,
};
const POOL_MAX_ITEMS = 20;
// Aggressive pruning
const PRUNE_THRESHOLD_NORMAL = 20;
const HOT_STATE_LIMITS = {
maxRenderedChars: 600,
maxActiveFilesRendered: 4,
};
```
## Debugging Configuration
### Enable Verbose Logging
Add `console.log()` statements in key functions:
```typescript
// In loadCoreMemory()
console.log("[Core Memory] Loaded:", memory);
// In applyDecay()
console.log("[Pool Decay] Pruned items:", prunedCount);
// In sweepToolOutputCache()
console.log("[Sweep] Deleted files:", deletedCount);
```
## Debugging
### Inspect Memory Files
```bash
# Core memory
cat .opencode/memory-core/<sessionID>.json | jq
# Workspace memory
cat ~/.local/share/opencode-working-memory/workspaces/*/workspace-memory.json | jq
# Working memory
cat .opencode/memory-working/<sessionID>.json | jq
# Pressure state
cat .opencode/memory-working/<sessionID>_pressure.json | jq
# Sweep log
cat .opencode/memory-working/<sessionID>_sweep.json | jq
# Session state
cat ~/.local/share/opencode-working-memory/workspaces/*/sessions/*.json | jq
```
## Migration Notes
### Clear Workspace Memory
### Upgrading from Pre-Phase 3
Old format files are automatically migrated:
```typescript
// Old format
{ items: Array<Item> }
// New format (auto-migrated)
{ slots: { error: [], decision: [], ... }, pool: [...] }
```bash
# Remove workspace memory (start fresh)
rm ~/.local/share/opencode-working-memory/workspaces/*/workspace-memory.json
```
No manual intervention required.
### Clear Session State
### Upgrading from Phase 3 to Phase 4.5
Storage governance is backward compatible. No migration needed.
```bash
# Remove all session states
rm ~/.local/share/opencode-working-memory/workspaces/*/sessions/*.json
```
## Best Practices
1. **Core Memory Discipline**:
- Clear `goal` immediately after task completion
- Keep `progress` concise (use checklist format)
- Only put actively edited files in `context`
1. **Workspace Memory Hygiene**:
- Let the plugin extract memories automatically
- Use explicit "remember this" for important information
- Don't manually edit memory files unless testing
2. **Working Memory Hygiene**:
- Clear `error` slot after fixing all errors (`working_memory_clear_slot`)
- Let pool decay naturally (avoid manual removal unless necessary)
- Review working memory periodically (use `working_memory_read`)
2. **Session State**:
- Let the plugin track active files automatically
- Errors are cleared when commands succeed
- No manual intervention needed
3. **Pressure Management**:
- Respond to "moderate" warnings proactively
- Compress core memory at "high" pressure
- Clear working memory at "critical" pressure
4. **Storage Maintenance**:
- Let sweep run automatically (no manual intervention)
- Delete old session files manually if needed
- Monitor `.opencode/` directory size periodically
3. **Memory Extraction**:
- Use `<workspace_memory_candidates>` during compaction
- Follow the pattern: `- [type] text`
- Quality gate rejects invalid candidates
---
**Last Updated**: February 2026
**Configuration File**: `index.ts` (constants section)
**Last Updated**: April 2026
**Configuration File**: `src/types.ts`
+76 -12
View File
@@ -10,7 +10,7 @@ Add to your `~/.config/opencode/opencode.json`:
}
```
Restart OpenCode. The plugin is downloaded and installed automatically — no `npm install` needed.
Restart OpenCode. The plugin activates automatically — no manual setup needed.
> **Note**: The correct key is `plugin` (singular), not `plugins`.
@@ -22,19 +22,44 @@ Restart OpenCode. The plugin is downloaded and installed automatically — no `n
## Verification
After restarting OpenCode, ask your agent:
After restarting OpenCode, memory context appears automatically in system prompts. You'll see:
```
Use core_memory_read to show me what you remember
<workspace_memory>
- [decision] ... (if any long-term memories exist)
</workspace_memory>
---
<workspace_memory_candidates>
- [project] ... (candidates for long-term memory)
</workspace_memory_candidates>
Active Files:
- path/to/file.ts (action, count)
Open Errors: (none, or listed)
```
If the tool responds, the plugin is active.
**No tools to call**. The plugin works automatically via hooks.
## How Memory Works
### Workspace Memory (Long-term)
Persists across sessions. Automatically extracted during compaction when you say "remember this" or when important decisions are made.
### Hot Session State (Short-term)
Tracks current session:
- Active files (what you're working on)
- Open errors (unresolved issues)
- Recent decisions (for compaction candidate promotion)
## Troubleshooting
### Plugin Not Loading
**Symptom**: No `core_memory_update` tool available
**Symptom**: No memory context in system prompt
**Solution**:
1. Check `~/.config/opencode/opencode.json` uses `"plugin"` (not `"plugins"`)
@@ -43,11 +68,21 @@ If the tool responds, the plugin is active.
### Memory Files Not Created
**Symptom**: No `.opencode/memory-core/` or `.opencode/memory-working/` directories
**Symptom**: No `~/.local/share/opencode-working-memory/` directory
**Solution**:
1. Ensure OpenCode has write permissions in project directory
2. Trigger memory operations (e.g., use `core_memory_update` tool)
1. Ensure OpenCode has write permissions in home directory
2. Trigger memory operations by working normally (plugin creates files on-demand)
3. Check that plugin is listed in config
### Memory Not Persisting
**Symptom**: Workspace memory empty after restart
**Solution**:
1. Verify you're in the same workspace (different workspace = different memory)
2. Ensure `<workspace_memory_candidates>` were captured during compaction
3. Check `workspace-memory.json` exists
### Type Errors During Development
@@ -56,16 +91,45 @@ If the tool responds, the plugin is active.
**Solution**:
1. Run `npm install` to install dev dependencies
2. Run `npm run typecheck` to check for errors
3. See [AGENTS.md](../AGENTS.md) for code style guidelines
3. Run `npm test` to verify functionality
## Uninstallation
Remove `"opencode-working-memory"` from the `plugin` array in `~/.config/opencode/opencode.json`.
Memory files in `.opencode/memory-*` will persist unless manually deleted.
Memory files in `~/.local/share/opencode-working-memory/` persist unless manually deleted.
## Manual Memory Management
### View Workspace Memory
```bash
cat ~/.local/share/opencode-working-memory/workspaces/*/workspace-memory.json | jq
```
### View Session State
```bash
cat ~/.local/share/opencode-working-memory/workspaces/*/sessions/*.json | jq
```
### Clear Workspace Memory
```bash
rm ~/.local/share/opencode-working-memory/workspaces/*/workspace-memory.json
```
### Clear All Session States
```bash
rm -rf ~/.local/share/opencode-working-memory/workspaces/*/sessions/*.json
```
## Next Steps
- Read [Architecture Documentation](./architecture.md) to understand how memory tiers work
- Read [Architecture Documentation](./architecture.md) to understand how the three layers work
- See [Configuration Guide](./configuration.md) for customization options
- Check [AGENTS.md](../AGENTS.md) for development guidelines
---
**Last Updated**: April 2026