compact-memory-implementation

compact-memory-implementation is a skill for Claude Code, Codex from simbajigege/book2skills. It costs 68 tokens per session (2,290 once invoked), scanned A, original, MIT.

An implementation guide for adding compact memory to an AI agent. Compact memory summarizes earlier conversation and task state so a later session can continue with less context.

In plain words
What is it for?
Designing compaction triggers, summary formats, memory restoration, and forked compactor agents for Claude or direct API systems.
Why use it?
It helps long-running agents avoid overflowing their context window while preserving important decisions and results.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one. Also seen: mentions subagents.

Good fit Designing compaction triggers, summary formats, memory restoration, and forked compactor agents for Claude or direct API systems.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/simbajigege/book2skills/compact-memory-implementation
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add simbajigege/book2skills --skill compact-memory-implementation
Clone the repo
git clone --depth 1 https://github.com/simbajigege/book2skills

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for compact-memory-implementation

README.md
[![agentmods](https://agentmods.dev/badge/skills/simbajigege/book2skills/compact-memory-implementation.svg)](https://agentmods.dev/skills/simbajigege/book2skills/compact-memory-implementation)
Your own site
<a href="https://agentmods.dev/skills/simbajigege/book2skills/compact-memory-implementation"><img src="https://agentmods.dev/badge/skills/simbajigege/book2skills/compact-memory-implementation.svg" alt="Measured on agentmods" height="20"></a>
Per session 68 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,290 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe. Third-party audits
  • NVIDIA SkillSpector warn 7 Sept 2026
SkillSpector: 2 findings, up to high

These are SkillSpector’s own severities. On a checked sample its high-severity flags on skills were ~96% false positives — a documented command, a public API, a “never do X” rule — so we show them as a caution to read, not a verdict. Why →

  • high Memory Poisoning · line 238
    Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.
    Fix: Protect agent memory and state from modification by untrusted content. Use read-only memory for critical instructions and validate all state changes.
  • medium Excessive Agency · line 109
    Skill enables autonomous high-impact decisions without human-in-the-loop verification. Critical operations (destructive commands, financial transactions, data deletion) should require explicit user confirmation.
    Fix: Add human-in-the-loop confirmation for destructive, irreversible, or high-impact operations. Never auto-execute commands that modify files, send data, or alter system state.
How audits are shown
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00068 $0.02290
Opus 5 $0.00034 $0.01145
Sonnet 5 $0.00014 $0.00458
Haiku 4.5 $0.00007 $0.00229

Measured 8d ago against content hash 42bf48ed608e, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-08, from the pricing page.

Security

Grade A, and why

compact-memory-implementation scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 8d ago.

The scan reads SKILL.md. This mod also ships 1 executable file (scripts/pre_compact_extract.py), listed below but not scanned — reading those needs a real analyzer, not pattern matching.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/compact-memory-implementation/SKILL.md · 301 lines

How it starts

The opening of the file, as written. The whole thing — 301 lines — stays where its author put it; the contents beside it link to each section on GitHub.

compact-memory-implementation

A developer guide for building compact memory into an Agent: detect when to compress, fork a compactor sub-agent, produce a structured summary, and restore it in the next session.

Step 1 — Understand the setup

Before designing anything, clarify:

  • SDK / language: Claude Agent SDK? Direct Anthropic API? Python or TypeScript?
  • Agent architecture: single-agent loop, multi-agent, tool-calling?
  • Session model: one long-running session or multiple short sessions?
  • What must survive compaction: task state, decisions, tool results, conversation history?

This determines which pattern fits.


Step 2 — When to trigger compact

Three strategies, pick based on your session model:

1. Token threshold (recommended) Check usage.input_tokens from the previous response. When it exceeds ~70–80% of your model's context limit, trigger compact.

COMPACT_THRESHOLD = 150_000  # adjust per model

if response.usage.input_tokens > COMPACT_THRESHOLD:
    compact = compact_memory(history)
    history = []  # reset — compact moves to system prompt

2. Turn count Compact every N turns. Simpler but less adaptive — misses sessions with a few very long turns.

COMPACT_EVERY_N = 30

if turn_count % COMPACT_EVERY_N == 0:
    compact = compact_memory(history)

3. Phase boundary Compact at natural task boundaries (after research, before implementation). Requires the agent to detect phases. Produces summaries that align with meaningful milestones, but harder to implement reliably.

Recommended default: token threshold at 70%, with turn-count fallback at N=40.


Step 3 — Fork agent for compaction

The compactor is a separate agent call whose only job is to read the current state and return a structured summary. Fork it synchronously — the main agent waits for the result before continuing.

def compact_memory(history: list[dict]) -> dict:
    response = client.messages.create(
        model="claude-haiku-4-5-20251001",  # cheaper model is fine for compaction
        max_tokens=4096,
        system=COMPACTOR_SYSTEM_PROMPT,
        messages=[
            {
                "role": "user",
                "content": format_history_for_compact(history),
            }
        ],
    )
    return json.loads(response.content[0].text)

Read the full file on GitHub · 301 lines

Files

What ships with it

2 files beside SKILL.md in the same directory: the scripts, references and assets a skill reads on demand. Not counted in the per-session cost; read them before you install if any of them is executable.

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 8d ago First seen · 301 lines · 68 tokens per session scan A 42bf48ed608e

Subscribe to this mod's changes

compact-memory-implementation is a skill published in the GitHub repository simbajigege/book2skills (160 stars, last pushed 13d ago), licensed MIT. It adds 68 tokens to every session and 2,290 once invoked, about $0.0003 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

crewai-multi-agent

Multi-agent orchestration framework for autonomous AI collaboration. Use when building teams of specialized agents working together on complex tasks, when you need role-based agent collaboration with memory, or for production workflows requiring sequential/hierarchical execution. Built without LangChain dependencies…

davila7/claude-code-templates · 61 tokens

langchain

Framework for building LLM-powered applications with agents, chains, and RAG. Supports multiple providers (OpenAI, Anthropic, Google), 500+ integrations, ReAct agents, tool calling, memory management, and vector store retrieval. Use for building chatbots, question-answering systems, autonomous agents, or RAG…

davila7/claude-code-templates · 79 tokens

memory-search

Search conversation history and semantic memory to recall previous discussions, decisions, and context. Use when the user asks to "search memory", "what did we discuss", "remember when", "find previous conversation", "check history", or before starting work to recall prior decisions.

davila7/claude-code-templates · 57 tokens

agent-memory-mcp

A hybrid memory system that provides persistent, searchable knowledge management for AI agents (Architecture, Patterns, Decisions).

davila7/claude-code-templates · 26 tokens

agent-memory-systems

Memory is the cornerstone of intelligent agents. Without it, every interaction starts from zero. This skill covers the architecture of agent memory: short-term (context window), long-term (vector stores), and the cognitive architectures that organize them. Key insight: Memory isn't just storage - it's retrieval. A…

davila7/claude-code-templates · 100 tokens

conversation-memory

Persistent memory systems for LLM conversations including short-term, long-term, and entity-based memory Use when: conversation memory, remember, memory persistence, long-term memory, chat history.

davila7/claude-code-templates · 39 tokens