- Home
- Skills
- Agents & Orchestration
- Memory Folding with Invariants
More screenshots
Works with the AI Agents you already use
Memory Folding with Invariants
Three-tier memory folding system for long-horizon agents that prevents rule loss via deterministic invariant checks.
$12
Memory Folding with Invariants
Example session with this skill installed
My agent's 'recent' memory tier is full with 20 notes from cycles 26-45. Two of them contain rules under [INVARIANTS & CONDITIONAL GATES]: "ABORT the cycle if the database connection check fails" and "NEVER post without a title". Fold the tier using the memory-folding-invariants skill. For this demo use a stub compressor that produces a plausible summary but drops the database rule, so I can see the enforcer catch it. Show me the fold report, the resulting compressed entry, and the invariant ids.
- Read your context and instructions
- Compiled the memory folding
The fold ran, and the enforcer caught the dropped database rule and restored it verbatim. The demo lives in demo_fold.py.
Setup. Twenty raw notes for cycles 26 through 45 filled the recent tier. The database rule sat in the cycle 28 note and the title rule in cycle 33, so both were inside the oldest ten that fold. The stub compressor wrote a plausible two-section summary that kept the title rule and softened the Postgres incident into past-tense narrative, which is exactly the failure the skill warns about.
Fold report
{
"tier": "recent",
"folded": 10,
"ok": true,
"inputs": 2,
"kept": 2,
"restored": ["ABORT the cycle if the database connection check fails"],
"retired_removed": [],
"block_chars": 144,
"warn": false
}
Resulting compressed entry (cycles 26-35)
[INVARIANTS & CONDITIONAL GATES]
- [inv:0cdd35] NEVER post without a title
- [inv:5df079] ABORT the cycle if the database connection check fails
[EPISODIC TRAJECTORY]
- Weekly digest pipeline ran issues #14 through #16. Engagement-weighted ranking surfaced the infra outage retro as the top performer; open rates moved 27% -> 31% -> 29% (after the #15 re-send).
- A mid-cycle Postgres outage once forced a redraft against stale data; a connection check was added at cycle start.
- #15 shipped with a blank subject (title template rendered empty), costing three unsubscribes; re-sent with the fix.
- Shorter intro paragraph trialled, no signal yet. Theme grouping replaced score ordering after positive reader feedback. Feed cache pruned from 1.8 GB to 640 MB (60-day window). Per-theme click tracking started.
Invariant ids
| id | rule | origin |
|---|---|---|
inv:0cdd35 | NEVER post without a title | cycle 33, kept by the compressor |
inv:5df079 | ABORT the cycle if the database connection check fails | cycle 28, restored by the enforcer |
Both ids are the hash of the normalised rule text, so the agent can retire either one with retire_invariant. After the fold the tier state is ten recent notes for cycles 36 through 45, one compressed entry, and two active invariants.
Next steps. Replace the stub with your real compressor via with_fallback(primary, backup), call MemoryTiers.add_note() each cycle, and wire list_invariants / retire_invariant from tool_specs() into your tool loop. The skill's test suite passed (12 tests).
Connects securely to your tools. The creator never sees your data.
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
- Tiered Rotation: The system monitors the
recentnote stack and triggers a fold into thecompressedtier once capacity is reached, eventually cascading into thedeeptier. - Dual-Section Compression: Every fold uses a specific prompt architecture that separates
[INVARIANTS & CONDITIONAL GATES]from the[EPISODIC TRAJECTORY]. - Post-Fold Verification: A Python-based enforcer compares the input invariants against the generated summary and restores missing content based on a survival threshold.
- 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.
How to use
Skills on Agensi run inside your AI agent. Copy the prompt, paste it into your agent, and it connects to Agensi and installs this skill for you. If a payment is needed, your agent shows it to you first.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill passes our trust checks below.
Security scanned
Passed our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scanned
Verified clean today
- Passed all security checks, Safe to install
Requires