Xpersona
M

Memory Optimization

CLAWHUB · Unverified

Comprehensive memory management optimization for AI agents. Use when: (1) Agent experiences context compression amnesia, (2) Need to rebuild context quickly... Skill: Memory Optimization Owner: richardiitse Summary: Comprehensive memory management optimization for AI agents. Use when: (1) Agent experiences context compression amnesia, (2) Need to rebuild context quickly... Tags: context:1.0.0, knowledge-graph:1.0.0, latest:1.0.4, memory:1.0.0, optimization:1.0.0, productivity:1.0.0 Version history: v1.0.4 | 2026-04-03T05:01:37.969Z | user Version 1.0.4: .gitignore update, d

62
Rank
84
Safety
1.3k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.3K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17ar90ttfrdyjn853eb0rmdcd83j8v2:memory-optimization
  1. Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-richardiitse-memory-optimization/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

150,980 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: memory-optimization
version: 1.0.4
license: MIT
description: |
  Comprehensive memory management optimization for AI agents. Use when: (1) Agent experiences context compression amnesia, (2) Need to rebuild context quickly after session restart, (3) Want structured memory system with TL;DR summaries, (4) Need automated daily memory maintenance, (5) Want to implement knowledge graph for entity management, or (6) Building agent memory system from scratch.
  
  Provides: TL;DR summary system, Three-file pattern (task_plan/findings/progress), Fixed tags system, Daily cleanup automation, HEARTBEAT integration, Rolling summary template, Testing framework, and Knowledge Graph integration.
---

# Memory Optimization Skill

Quickly implement a comprehensive memory management system for AI agents based on Moltbook community best practices.

## When to Use This Skill

- Context compression causes memory loss between sessions
- Need fast context recovery (currently 5-10 minutes, target <30 seconds)
- Want structured project tracking with clear separation of concerns
- Need automated daily memory maintenance
- Building knowledge graph for entity relationships
- Migrating from simple file-based memory to advanced system

## What This Skill Provides

1. **TL;DR Summary System** - 30-second context recovery
2. **Three-File Pattern** - Structured project tracking
3. **Fixed Tags System** - Quick grep search capability
4. **Daily Cleanup Script** - 3-minute automated maintenance
5. **HEARTBEAT Integration** - Mandatory memory checklist
6. **Rolling Summary Template** - Concise daily summaries
7. **Testing Framework** - 6 automated tests
8. **Knowledge Graph** - 18 entities, 15 relationships
9. **Skill Usage Tracker** - Track and analyze skill usage patterns

## Quick Start

### TL;DR Summary System

Add to each daily log (memory/YYYY-MM-DD.md):

```markdown
## ⚡ TL;DR Summary

**Core Achievements**:
- ✅ Achievement 1
- ✅ Achievement 2

**Today's Key Points**:
- Key point 1
- Key point 2

**Decisions**: Important decision made today
```

### Three-File Pattern

For complex projects, create:
- `memory/task_plan.md` - What to do (goals, phases, decisions)
- `memory/findings.md` - What discovered (research, key info)
- `memory/progress.md` - What done (timeline, errors)

### Fixed Tags

Use consistent tags across files:
- `#memory` - Memory-related content
- `#decision` - Important decisions
- `#improvement` - Optimization work
- `#daily-log` - Daily log entries

### Daily Cleanup

Run automated cleanup:
```bash
./memory/daily-cleanup.sh
```

### HEARTBEAT Integration

Add to HEARTBEAT.md:
```markdown
### 🧠 Memory Management Checklist

Every Session Start:
- [ ] Read SOUL.md (agent identity)
- [ ] Read USER.md (user preferences)
- [ ] Read memory/YYYY-MM-DD.md (today + yesterday)
- [ ] Read MEMORY.md (long-term memory)
```

## Scripts

See [scripts/README.md](scripts/README.md) for detailed usage:

- `daily-cleanup.sh` - 3-minute daily memory maintenance
- `

README.md

# Memory Optimization — Memory Evolution Foundation

A memory management system for AI agents that transforms from "meeting for the first time every session" to "like an old friend who knows you better over time."

## Vision

On day three of a repeating task, the agent **automatically executes using the approach that worked before**, without being reminded. Memory is alive: it grows, decays, forgets, and Consolidates into real intelligence.

## Three-Layer Memory Architecture

```
┌─────────────────────────────────────────────────────────────┐
│  Working Memory (Context Window)                             │
│  Full current session content — layered compression:        │
│  Full → Summary → Key Facts                                │
└─────────────────────────────────────────────────────────────┘
                          ↓ Consolidation (after N repetitions)
┌─────────────────────────────────────────────────────────────┐
│  Episodic Memory (KG Entities)                             │
│  Decision, Finding, LessonLearned, Commitment              │
│  + strength, decay_rate, provenance                        │
└─────────────────────────────────────────────────────────────┘
                          ↓ Consolidation
┌─────────────────────────────────────────────────────────────┐
│  Semantic Memory (SkillCards)                              │
│  Generalized patterns distilled from episodic memory        │
└─────────────────────────────────────────────────────────────┘
```

**Memory Decay**: strength decays over time, preventing low-value memories from consuming space.
**Poisoning Protection**: provenance tracks sources; Consolidation validates conflicts before merging.

## SkillCard - Knowledge Distillation

SkillCard is a high-value knowledge card distilled from entities (Decision, LessonLearned, etc.):

```json
{
  "title": "Adopt three-layer hybrid architecture (realtime/batch/heartbeat)",
  "confidence": 0.9,
  "strength": 1.0,
  "decay_rate": 0.99,
  "source_episodes": ["dec_xxx", "dec_yyy"],
  "provenance": ["consolidation:engine"]
}
```

### Purpose

1. **Quick Recall** - View key decisions without browsing all records
2. **Low Decay** - decay_rate=0.99 preserves core knowledge long-term
3. **High Confidence** - confidence=0.9 marks trusted knowledge
4. **Knowledge Sharing** - Can generate skills for ClawHub marketplace or publish to EvoMap marketplace

### Example

- Multiple "three-layer architecture" Decisions merged into one SkillCard
- decay_rate=0.99 ensures core knowledge is retained long-term

**Simply put**: Distill scattered findings into "one card" — this is the core output of memory optimization.

## Phase Build Status

| Phase | Feature | Status |
|-------|---------|--------|
| Phase 1 | KG Extractor (session → KG) | ✅ Done |
| Phase 1b | KG Schema (strength, decay, provenance) | ✅ Done |
| Phase 2 | Preference Engine + Entity Deduplication | ✅ Done |
| Phase 3 | Consolidation Engine (Episode → SkillCard) | ✅ Done |
| Phase 4 | Decay E

scripts/README.md

# Scripts - Memory Optimization Skill

This directory contains executable scripts for the memory optimization system.

## Scripts

### daily-cleanup.sh

Automated 3-minute daily memory maintenance script.

**Usage:**
```bash
./scripts/daily-cleanup.sh
```

**Features:**
- Verifies TL;DR exists
- Checks for bullet points
- Validates progress tracking
- Confirms MEMORY.md
- Reports file statistics

**Test Result:** 6/6 checks passed ✅

---

### test-memory-system.sh

Complete testing framework for memory improvements.

**Usage:**
```bash
./memory/test-memory-system.sh
```

**Tests:**
1. ✅ TL;DR Recovery - Content present and formatted
2. ✅ Tags Search - Grep for #memory, #decision, #improvement
3. ✅ Three-File Pattern - All 3 files exist
4. ✅ Progress Tracking - Tasks tracked correctly
5. ✅ HEARTBEAT Integration - Memory checklist present
6. ✅ File Size Check - Under 10KB target

**Test Result:** 6/6 passed ✅

---

### memory_ontology.py

Knowledge Graph management tool.

**Usage:**
```bash
python3 scripts/memory_ontology.py <command> [options]
```

**Commands:**
- `create` - Create new entity with validation
- `relate` - Establish relationships
- `query` - Search by type, tags, status
- `get` - Retrieve specific entity
- `related` - Find related entities
- `validate` - Verify graph integrity
- `list` - List all entities
- `export` - Export to Markdown
- `stats` - Show statistics
- `compact` - Compact graph.jsonl (dedup versions)
- `gate` - Phase 8: Evaluate entity gating score
- `archived` - Phase 8: List archived entities
- `retrieve` - Phase 6: Value-aware retrieval

**Examples:**

```bash
# Create a decision
python3 scripts/memory_ontology.py create --type Decision --props '{"title":"Use KG","rationale":"Based on Moltbook advice","made_at":"2026-03-12T23:00:00+08:00","confidence":0.9,"status":"final","tags":["#decision","#memory"]}'

# Query by tags
python3 scripts/memory_ontology.py query --tags "#memory" "#decision"

# Get related entities
python3 scripts/memory_ontology.py related --id dec_xxx

# Validate graph
python3 scripts/memory_ontology.py validate

# Show stats
python3 scripts/memory_ontology.py stats
```

---

### consolidation_engine.py

Phase 3: Consolidate similar Episode patterns into Semantic Memory (SkillCard).

**Usage:**
```bash
python3 scripts/consolidation_engine.py run --dry-run
python3 scripts/consolidation_engine.py status
```

**Commands:**
- `run` - Run consolidation cycle (use `--dry-run` to simulate)
- `status` - Show consolidation status and pending reviews

---

### preference_engine.py

Phase 2: User preference inference — determines if tasks are "substantially the same" using LLM.

**Usage:**
```bash
# Extract preferences from a session
python3 scripts/preference_engine.py extract --session-id <id>

# Determine if two tasks are similar
python3 scripts/preference_engine.py infer-preference --task-a "xxx" --task-b "yyy"

# List all inferred preferences
python3 scripts/preference_engine.py list

# Clear preference c

_meta.json

{
  "ownerId": "kn71vkkmmjpaawxtxfwdxbffxn80w56v",
  "slug": "memory-optimization",
  "version": "1.0.4",
  "publishedAt": 1775192497969
}

CHANGELOG.md

# Changelog

All notable changes to this project are documented in this file.

## [1.0.4] - 2026-04-03

### Changed

- **.gitignore**: Added `agents/` and `docs/` to prevent local-only directories from being committed.
- **Git history**: Removed `docs/` from git history for privacy. Local `docs/` folder preserved.

### Security

- **CSO Audit**: Completed first security audit with 3 findings (1 HIGH API key exposure, 1 HIGH prompt injection risk, 1 MEDIUM OAuth token storage).

## [1.0.3] - 2026-04-02

### Added

- **Benchmark Framework**: New `memory_bench/` tool comparing nanobot native memory vs nanobot + memory-optimization skill on response time. Includes CLI runner (`run.py`), subprocess-based agent runners, copytree with ignore_patterns for efficient skill copying, and 9 unit tests.

### Changed

- **.env.example**: Updated to reflect current EvoMap/ClawHub marketplace direction.

## [1.0.2] - 2026-03-27

### Added

- **Entity Deduplication Engine (Phase 2)**: Embedding-based duplicate detection and merging using cosine similarity. Keeps earliest timestamp as canonical entity, accumulates `frequency` property across duplicates, chain merge flattening (e3→e2→e1 → e3→e1), 24h embedding cache to avoid repeated API calls.

### Changed

- **KG_DIR environment variable support**: `memory_dashboard.py` now supports `KG_DIR` env var with path traversal validation.

## [1.0.1] - 2026-03-23

### Added

- **Memory Health Dashboard (Phase 7)**: CLI dashboard visualizing complete memory system state — Health Score (A-F), strength histogram, consolidation progress, storage stats, decay forecast, age distribution.

### Fixed

- LLM returns `None` without fallback causing silent failures.

## [1.0.0] - 2026-03-22

### Added

- **KG Schema Enhancement (Phase 1b)**: Added `strength`, `decay_rate`, `provenance` fields to KG entities for Decay Engine and Memory Health Dashboard support.
- **Preference Engine (Phase 2)**: User preference inference from conversation history and KG entities.
- **LLMClient Consolidation**: Refactored duplicate `LLMClient` implementations into `scripts/utils/llm_client.py` with unified `call()`, `call_with_retry()`, and new `embed()` methods.
- **Memory Loader (Phase 6)**: Proactive memory recovery with 3-stage staged loading — Stage 1 (core identity at startup), Stage 2 (episodic memory on demand), Stage 3 (semantic memory with proactive hints).
- **Working Memory (Phase 5)**: Context Window layered compression — 3 levels (完整/摘要/关键事实) for managing context overflow.
- **Consolidation Engine (Phase 3)**: Semantic memory consolidation — merges similar Episode patterns into SkillCards.
- **Decay Engine**: Batch decay engine for memory strength management with 30-day decay forecast.
- **Knowledge Graph Management Tool**: Full CLI for creating, querying, relating, validating KG entities.
- **KG Extractor**: LLM-driven entity extraction from agent session logs.
- **TL;DR Summary System**: 30-second context recovery at top of daily logs.

Sponsored

Ads related to Memory Optimization and adjacent AI workflows.