The dataset is currently empty. Upload or create new data files. Then, you will be able to explore them in the Dataset Viewer.

Adaptive Memory Compression for AI Coding Assistants: Automatic Archiving with Index Preservation

Authors: Kiyoung (Independent Research, Concept Design) Contact: tjdrldud850@gmail.com Status: RFC / Proposal + Implementation Date: 2026-07-06


TL;DR

AI coding assistants accumulate memory files that grow indefinitely, wasting tokens on outdated context every session. This proposal implements automatic memory compression using a four-step pipeline: line count threshold check → similar entry merging → age-based archiving → index preservation in the main file. The system runs automatically via Claude Code hooks on every prompt submission. Anyone with basic Python knowledge can implement it in under 30 minutes.


Abstract

Claude Code and similar AI coding assistants maintain persistent memory files (MEMORY.md) that grow with every session. Without management, these files consume increasing token budgets with outdated, redundant, or irrelevant entries. We propose and implement Adaptive Memory Compression (AMC): a lightweight hook-based system that automatically compresses memory files when they exceed a configurable threshold, archives entries older than a configurable age, and preserves a navigable index of archived content. Unlike existing solutions that focus on session-to-session context injection, AMC focuses on long-term memory hygiene — ensuring the always-loaded memory file stays small while keeping historical context accessible.


1. Problem Definition

1.1 Memory Bloat in AI Coding Assistants

Claude Code's memory system stores project context, user preferences, and learned patterns in MEMORY.md. This file is loaded into every conversation, consuming tokens regardless of relevance. Over weeks and months of use:

  • Early project decisions remain in memory long after the project changed direction
  • Debugging notes from resolved issues continue to load
  • Duplicate entries accumulate as similar lessons get re-learned
  • The file grows linearly with usage, with no automatic pruning mechanism

A 200-line MEMORY.md wastes tokens on entries that have not been referenced in months.

1.2 The Index Preservation Gap

Existing memory management solutions (e.g., claude-mem) focus on session-to-session compression: summarizing long conversations before they exceed context limits. They do not address long-term memory file growth.

Critically, naive deletion of old entries destroys navigability: if an entry is removed entirely, the user cannot know it existed, cannot retrieve it, and cannot reference it in future conversations. Any compression system must preserve a lightweight index of what was archived and where.


2. Proposed Solution: Adaptive Memory Compression (AMC)

2.1 Core Pipeline

Every prompt submission (via hook):
  1. Count active lines in MEMORY.md
  2. If count ≤ threshold: exit (no action needed)
  3. If count > threshold:
     a. Identify entries older than age_threshold
     b. Move aged entries to archive.md (with datestamped section)
     c. Replace moved entries with index references in MEMORY.md
     d. (Optional) Merge similar remaining entries via LLM

2.2 Index Preservation

When entries are archived, MEMORY.md retains a compact reference:

## Archive Index
- [Archive] Entry Title — Short description...

This allows the AI assistant to know that context exists in archive.md and retrieve it on demand, without loading it by default.

2.3 Archive Structure

archive.md receives dated sections:

# Memory Archive

## 2026-07-06 Archive
- [Original entry with full content and date]
- [Original entry with full content and date]

This preserves full historical context while keeping it out of the default token budget.


3. Implementation

3.1 Configuration

MAX_LINES = 50          # Trigger threshold
ARCHIVE_THRESHOLD_DAYS = 180  # 6 months

3.2 Entry Parsing

Entries follow the format:

- [Title](file.md) — Description (YYYY-MM-DD)

The date field drives archiving decisions. Entries without dates are never auto-archived.

3.3 Hook Integration

Claude Code's UserPromptSubmit hook triggers the script on every prompt:

"hooks": {
  "UserPromptSubmit": [{
    "matcher": "",
    "hooks": [{
      "type": "command",
      "command": "python3 /path/to/compress_memory.py"
    }]
  }]
}

The script exits silently when no action is needed, adding zero perceptible latency.

3.4 Full Implementation

import os, re
from datetime import datetime
from pathlib import Path

MEMORY_DIR = Path(__file__).parent
MEMORY_FILE = MEMORY_DIR / "MEMORY.md"
ARCHIVE_FILE = MEMORY_DIR / "archive.md"
MAX_LINES = 50
ARCHIVE_THRESHOLD_DAYS = 180

def parse_entries(content):
    entries = []
    for line in content.split('\n'):
        m = re.match(r'^- \[(.+?)\]\((.+?)\) — (.+?)(?:\s*\((\d{4}-\d{2}-\d{2})\))?$', line)
        if m:
            title, file, desc, date = m.groups()
            entries.append({'line': line, 'title': title, 'file': file,
                           'desc': desc, 'date': date})
        else:
            entries.append({'line': line, 'title': None})
    return entries

def should_archive(entry):
    if not entry.get('date'):
        return False
    try:
        d = datetime.strptime(entry['date'], '%Y-%m-%d')
        return (datetime.now() - d).days > ARCHIVE_THRESHOLD_DAYS
    except:
        return False

def run():
    if not MEMORY_FILE.exists():
        return
    content = MEMORY_FILE.read_text(encoding='utf-8')
    lines = [l for l in content.split('\n') if l.strip()]
    if len(lines) <= MAX_LINES:
        return

    entries = parse_entries(content)
    to_archive = [e for e in entries if e['title'] and should_archive(e)]
    to_keep = [e for e in entries if not (e['title'] and should_archive(e))]

    if not to_archive:
        return

    # Write to archive
    arch = ARCHIVE_FILE.read_text('utf-8') if ARCHIVE_FILE.exists() else "# Memory Archive\n\n"
    arch += f"\n## {datetime.now().strftime('%Y-%m-%d')} Archive\n\n"
    for e in to_archive:
        arch += e['line'] + '\n'
    ARCHIVE_FILE.write_text(arch, 'utf-8')

    # Rewrite MEMORY.md with index
    new = '\n'.join(e['line'] for e in to_keep)
    new += "\n\n## Archive Index\n"
    for e in to_archive:
        new += f"- [Archive] {e['title']} — {e['desc'][:50]}...\n"
    MEMORY_FILE.write_text(new, 'utf-8')

if __name__ == "__main__":
    run()

4. Key Design Decisions

4.1 Why Age-Based Rather Than Importance-Based

Importance scoring requires LLM inference on every run, adding latency and cost. Age is a reliable proxy: entries that have survived in memory for 6+ months without triggering a "this is wrong" correction are either correct-but-outdated or genuinely stable. The former should be archived; the latter will persist because they haven't aged out yet.

4.2 Why Index Preservation Matters

A memory system that silently deletes entries teaches the AI assistant that context disappears. The index reference teaches it that context moves. This distinction matters: the assistant can proactively retrieve archived context when a relevant task arises, rather than re-deriving it from scratch.

4.3 Why Hooks Rather Than Manual Triggers

Manual execution requires user discipline. Hooks remove this requirement entirely. The script is designed to exit immediately when no action is needed, so the overhead on every prompt submission is negligible (single file read + line count).


5. Relationship to Existing Solutions

claude-mem

claude-mem is a well-built persistent memory system for Claude Code that handles session-to-session context injection. When a new session starts, claude-mem injects compressed context from previous sessions so Claude "remembers" what was discussed before. It also observes tool executions and user patterns across sessions.

AMC addresses a different problem that operates on a longer timescale. claude-mem ensures you don't lose work progress between sessions. AMC ensures the memory file itself doesn't grow unboundedly over months of use. These are complementary, not competing:

Recommended combined setup:

  • claude-mem handles short-term memory: session continuity and context injection
  • AMC handles long-term memory hygiene: preventing file bloat over months of usage
Layer Tool Problem Solved
Short-term (sessions) claude-mem "Claude forgot what we discussed last week"
Long-term (months) AMC (this work) "MEMORY.md has grown to 200 lines and wastes tokens"

Together, they form a complete memory lifecycle management system for AI coding assistants.


6. Limitations and Future Work

  1. Similar entry merging: The current implementation identifies aged entries but does not merge semantically similar active entries. LLM-based deduplication is planned as an optional enhancement.

  2. Date requirement: Entries without explicit dates are never archived. Consistent date-stamping discipline is required.

  3. No importance weighting: A frequently-referenced old entry should arguably not be archived. Future versions could track reference frequency.

  4. Single-file assumption: The current implementation manages one MEMORY.md. Multi-file memory systems require adaptation.


7. Conclusion

Memory bloat is an inevitable consequence of long-running AI assistant usage. Adaptive Memory Compression addresses this with a minimal implementation — approximately 50 lines of Python — that runs automatically, preserves navigability, and requires no LLM inference during normal operation. The core insight is simple: move old context out of the default token budget, but keep a map of where it went.

The system has been implemented and tested against Claude Code's memory format. The complete implementation is included in this repository.


Appendix: Setup Instructions

  1. Save compress_memory.py to your Claude Code memory directory
  2. Add the UserPromptSubmit hook to ~/.claude/settings.json
  3. Set MAX_LINES and ARCHIVE_THRESHOLD_DAYS to match your usage patterns
  4. The system runs automatically from the next prompt onward
Downloads last month
6