# Memory Folding with Invariants

> Three-tier memory folding system for long-horizon agents that prevents rule loss via deterministic invariant checks.

Memory Folding with Invariants is a paid AI agent skill on Agensi by Phil Marcus, in Agents & Orchestration. It loads into your AI agent through the Agensi MCP server, always in its latest approved version.

- Price: $12 (one-time purchase)
- Creator: [Phil Marcus](https://www.agensi.io/creators/phil-marcus)
- Category: [Agents & Orchestration](https://www.agensi.io/skills/agents-orchestration)
- Version: 1.0
- Last updated: 2026-10-19
- Security: scan passed (2026-10-19); every new listing is also reviewed by a person
- Listing: https://www.agensi.io/skills/memory-folding-with-invariants
- Tags: ai-agents, python, llm-ops, state-management, context-optimization

## About this skill

Long-running agents often suffer from "context drift" where critical rules and learned lessons are summarized away as "past events" or deleted entirely during context compaction. Standard LLM summarization tends to convert hard constraints into soft narrative history, causing agents to repeat costly mistakes.

### What it does
- **Three-tier memory folding** implements a structured hierarchy (recent, compressed, and deep) to manage long-horizon state without data loss.
- **Deterministic invariant enforcement** uses a token-overlap check to verify that mandatory rules and conditional gates survive every compression cycle.
- **Automated rule restoration** appends any dropped or weakened invariant back to the summary verbatim without requiring an additional LLM call.
- **Contradiction Reservoir management** maintains an append-only log of prediction errors and failed hypotheses that bypass the summarization pipeline.
- **Self-managed retirement** allows the agent to explicitly retire obsolete rules through specific tool calls to prevent invariant block bloat.

### How it works
1. **Tiered Rotation**: The system monitors the `recent` note stack and triggers a fold into the `compressed` tier once capacity is reached, eventually cascading into the `deep` tier.
2. **Dual-Section Compression**: Every fold uses a specific prompt architecture that separates `[INVARIANTS & CONDITIONAL GATES]` from the `[EPISODIC TRAJECTORY]`.
3. **Post-Fold Verification**: A Python-based enforcer compares the input invariants against the generated summary and restores missing content based on a survival threshold.
4. **Context Injection**: The agent renders the current memory tiers and the most recent contradiction entries into the head of every new prompt.

### Frameworks & tools
This skill is provider-neutral and requires Python 3.9+. It uses standard library components for the core logic and is compatible with any LLM (OpenAI, Anthropic, Gemini) via a simple chat function wrapper.

### Why this beats prompting it yourself
Writing a "remember this" prompt is not enough for agents running hundreds of cycles; LLMs naturally prioritize narrative over constraints during summarization. This skill provides a deterministic safety net that physically prevents rule loss, ensuring an "ABORT if X" instruction never softens into a historical anecdote.

### Use cases
- Preventing agents from repeating technical mistakes in long-running coding tasks.
- Maintaining strict safety protocols and negative constraints in autonomous operations.
- Building agents that require a permanent "lessons learned" audit trail.
- Managing high-frequency cycle notes without overflowing context windows.

### Known limitations
The system requires the agent to produce a single-paragraph memory note per cycle. Invariant restoration relies on token overlap, which may cause duplicate entries if the compressor rewords rules significantly.

## Requires

- Python 3.9+

## How to use this skill

1. Connect your AI agent to Agensi once: add the MCP server https://mcp.agensi.io/mcp/auth and sign in with your Agensi account (OAuth, no API key). Steps for Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and other agents: https://www.agensi.io/docs/mcp-setup
2. Ask your agent: "Use the Memory Folding with Invariants skill from Agensi" and describe your task.
3. Buy it on the listing or let your agent ask you first; your agent then loads it from Agensi when it needs it. Every paid skill has a money-back guarantee: https://www.agensi.io/docs/money-back-guarantee

## Frequently asked questions

### How does this skill prevent my agent from forgetting its original instructions over time?

This skill solves 'context drift,' where agents gradually forget strict rules or safety constraints during long-running tasks. It uses a three-tier folding system and deterministic checks to ensure your agent's core instructions never get 'summarized away' or softened into narrative history.

### Is 'memory folding invariants' compatible with specific LLM providers or frameworks?

The skill is provider-neutral and works with any LLM (including OpenAI, Anthropic, and Gemini) that supports basic chat completions. It is written in Python 3.9+ and can be integrated into most custom agentic frameworks via a simple function wrapper.

### What exactly is included in the purchase of this skill?

Three standard-library Python modules: memory_tiers.py (the three tiers, the compressor prompt, with_fallback, tool specs and dispatch), invariants.py (parse, enforce, retire, stable ids) and contradictions.py (the append-only Contradiction Reservoir with prompt projection and tool specs). Plus a 12-test offline suite and three reference docs: the two-section compressor prompt with suggested agent-side wording, the documented failure modes each guard catches, and tool wiring for Anthropic, OpenAI and Gemini. SKILL.md walks through the seven integration steps.

### How does the 'deterministic invariant enforcement' work without increasing API costs?

The system uses a Python-based token-overlap check that compares the pre-fold rules against the post-fold summary. If a mandatory invariant is missing or weakened, the system automatically appends the original text back to the memory without needing a second, costly LLM call.

### Are there specific agent architectures that benefit most from this memory system?

This skill works best for agents that generate a memory note or summary at the end of every cycle. It is particularly effective for agents performing 50+ consecutive steps where standard context windows would normally lead to information loss.

---

Source: [Agensi](https://www.agensi.io), the marketplace of skills for AI agents. Any MCP-compatible agent (Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and more) connects at https://mcp.agensi.io/mcp/auth and signs in with an Agensi account; setup for every agent: https://www.agensi.io/docs/mcp-setup. Append .md to any skill, guide or docs address on agensi.io for its markdown version.
