memory-engineering

$npx mdskill add alirezarezvani/claude-skills/memory-engineering

Audits and prices agent memory systems, enforcing a forgetting policy.

  • Solves unbounded memory growth and unclear retention decisions.
  • Uses four deterministic stdlib scripts, no APIs or network.
  • Classifies records as facts, skills, or logs to pick costs.
  • Refuses designs lacking a forgetting policy, delivering actionable audit.

SKILL.md

.github/skills/memory-engineeringView on GitHub ↗
---
name: memory-engineering
description: Use when designing, reviewing, or paying for an agent memory system — adding memory to an agent, choosing between long-context / RAG / graph / agentic memory, auditing what a CLAUDE.md or memory directory actually holds, deciding what to keep and what to expire, or when a memory store keeps growing and nobody has said what leaves it. Prices the write path, picks which cost to pay, classifies records as facts / skills / logs, and refuses a design that has no forgetting policy.
argument-hint: "[optional: path to a memory dir, design spec JSON, or a question]"
license: MIT
metadata:
  version: 1.0.0
  build_pattern: "Four-lens synthesis (Stanford / Microsoft / Anthropic / Nvidia) + 4 deterministic stdlib scripts, with a blocking forgetting gate"
  distinct_from: "llm-wiki (maintains one specific markdown vault; this audits and prices any memory system); skillopt-sleep (runs a nightly consolidation loop; this decides whether that loop's output is worth keeping); agent-harness (bounds a task loop; this bounds a store)"
---

# Memory Engineering — engineer the forgetting, not just the remembering

> **Portability:** 4 stdlib scripts, no APIs/LLM calls/network. They measure and gate; you decide.

## What this does

Anyone can give an agent memory: vector store, pipe in the history, retrieve
top-k. That works until the history outgrows the context window, the write path
costs more than every query it serves, and the store fills with stale state
nobody removes. Memory is not a bucket — it is a system with a metabolism.

**The shift:** a storer optimizes what a system remembers; a memory engineer
optimizes what it forgets. The problem was never that an agent forgets — it is
that it never forgets *on purpose*.

## The four lenses

| Lens | Question | The finding that hurts |
|---|---|---|
| **Stanford** | What does remembering cost? | Construction energy exceeds total query energy across 300 queries. The tuned half is the smaller half. |
| **Microsoft** | What is worth keeping? | More raw memory can make an agent *worse*. Keep facts and skills; drop the events. |
| **Anthropic** | Who controls what it keeps? | A wrong memory does not fail once — it persists into every future session that reads it. |
| **Nvidia** | Where does it hit hardware? | It is all KV cache in HBM. Construction is prefill-heavy and stalls the query a user is waiting on. |

## Workflow

```bash
# 1 - Price it first. Never quote a quality number without a cost number.
python scripts/memory_cost_profiler.py --print-sample-spec > workload.json
python scripts/memory_cost_profiler.py --spec workload.json
# 2 - Pick which cost to pay. No "best" verdict; on a tie it asks, exit 2.
python scripts/memory_architecture_picker.py --constraints workload.json
# 3 - Audit what the store actually holds (skip if greenfield).
python scripts/memory_density_auditor.py --dir ~/.claude/memory
# 4 - Gate on forgetting. Exit 4 is a stop, not a suggestion.
python scripts/forgetting_policy_linter.py --policy design.json
# 5 - No command. Prove each pass by hand before scheduling it.
```

Step 1 reports the construction/query split, **cost per correct answer**, and
amortization — if construction dominates, cut construction tokens *before*
touching retrieval. Step 2 names the cost the winning family makes you pay.
Step 3 classifies records FACT / SKILL / LOG / PROSE (`LOG-HEAVY` = archiving
events; `PROSE-HEAVY` = docs, not memory).

Step 4 is the gate: **F1** (explicit forgetting rule) and **F4** (contradictions
surfaced, never auto-merged) are blocking. Retrofitting forgetting onto two
years of records is a migration nobody does; auto-merging disagreeing memories
destroys the evidence the conflict existed.

Step 5 has no script — prove each pass by hand, then automate. Run it once
against real history and ask whether it changed a decision. If not, scheduling
it only makes noise. Ship order: `forgetting_policy_design.md` §7.

## Hard rules

1. **Never quote accuracy without cost per correct answer.**
2. **Never return a "best" memory system** — name the cost the choice makes you pay.
3. **Never auto-merge contradictions.** The system surfaces; the human decides.
4. **Never call a design done without a forgetting rule.** No evaluated system provides one by default.
5. **Never schedule a pass not yet run by hand.**
6. **Report findings as findings.** A non-zero exit is a result to surface, not an error to swallow.
7. **Attribute every number** with its confidence level. Vendor customer figures are testimonials, not benchmarks.

## Scripts

| Script | Role | Exit codes |
|---|---|---|
| `scripts/memory_cost_profiler.py` | Construction vs query split, cost per correct answer, amortization, co-location warning | 0 · 2 finding · 3 bad input |
| `scripts/memory_architecture_picker.py` | Scores 4 families, disqualifies, names the cost, refuses to pick on a tie | 0 · 2 ambiguous · 3 bad input · 4 none viable |
| `scripts/memory_density_auditor.py` | FACT/SKILL/LOG/PROSE, duplicates, staleness, density (`--dir` or `--jsonl`) | 0 dense · 2 finding · 3 bad input |
| `scripts/forgetting_policy_linter.py` | The gate: 8 checks, F1 and F4 blocking | 0 PASS · 2 CONDITIONAL · 4 FAIL |

All support `--output json` and `--sample` (no input file needed).

## References and assets

- [`references/memory_cost_canon.md`](references/memory_cost_canon.md) — construction dominance, energy per correct answer, the four families, ten recommendations (7 sources)
- [`references/what_to_keep.md`](references/what_to_keep.md) — PlugMem and MEMENTO: facts over logs, density over volume (7 sources)
- [`references/memory_control_and_governance.md`](references/memory_control_and_governance.md) — memory as files, scope/audit/rollback, poisoning, reading vendor numbers (7 sources)
- [`references/forgetting_policy_design.md`](references/forgetting_policy_design.md) — forgetting mechanisms, contradiction discipline, KV cache, ship order (7 sources)
- [`assets/memory_engineer_worksheet.md`](assets/memory_engineer_worksheet.md) — seven forcing questions with recommended answers + citations; walk one at a time
- [`assets/memory_design_spec.example.json`](assets/memory_design_spec.example.json) — one file covering every script's input
- [`assets/forgetting_policy_template.md`](assets/forgetting_policy_template.md) — fillable policy covering F1–F8

## Provenance

Framing from *"How to be a Memory Engineer"* by [@N01ennn](https://x.com/N01ennn/status/2083971749079581120); every
number is cited to a primary source instead, and two paraphrases are corrected — `memory_cost_canon.md` §2, `memory_control_and_governance.md` §4.

More from alirezarezvani/claude-skills

SkillDescription
a11y-auditAccessibility audit skill for scanning, fixing, and verifying WCAG 2.2 Level A and AA compliance across React, Next.js, Vue, Angular, Svelte, and plain HTML codebases. Use when auditing accessibility, fixing a11y violations, checking color contrast, generating compliance reports, or integrating accessibility checks into CI/CD pipelines.
ab-test-setupWhen the user wants to plan, design, or implement an A/B test or experiment. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "conversion experiment," "statistical significance," or "test this." For tracking implementation, see analytics-tracking.
ad-creativeWhen the user needs to generate, iterate, or scale ad creative for paid advertising. Use when they say 'write ad copy,' 'generate headlines,' 'create ad variations,' 'bulk creative,' 'iterate on ads,' 'ad copy validation,' 'RSA headlines,' 'Meta ad copy,' 'LinkedIn ad,' or 'creative testing.' This is pure creative production — distinct from paid-ads (campaign strategy). Use ad-creative when you need the copy, not the campaign plan.
adversarial-reviewerAdversarial code review that breaks the self-review monoculture. Use when you want a genuinely critical review of recent changes, before merging a PR, or when you suspect Claude is being too agreeable about code quality. Forces perspective shifts through hostile reviewer personas that catch blind spots the author's mental model shares with the reviewer.
aeoAnswer Engine Optimization (AEO) skill — optimize content to be cited by AI language models (ChatGPT, Perplexity, Claude, Gemini, Mistral) as authoritative sources. Distinct from SEO — AEO optimizes for citation in LLM-generated responses, not search rankings. Use when planning content for AI-first search audiences, auditing existing content for E-E-A-T signals, tracking which pages get cited by which LLMs, or building a citation-friendly content strategy. Triggers — 'AEO audit', 'optimize for ChatGPT', 'get cited by Perplexity', 'LLM citation strategy', 'answer engine optimization', 'content for AI search', 'E-E-A-T audit'. Output is a markdown audit report (default) or JSON for pipeline integration. Stdlib-only Python tools.
agent-decision-receiptsMint a tamper-evident, post-quantum-signed receipt for a consequential agent action (deploy, delete, pay, grant-access, model decision) so it can be verified later from the certificate alone. Use when an autonomous agent takes a side-effecting action that may need to be proven later, or when satisfying EU AI Act Article 12 record-keeping. Three decisions: whether an action needs a receipt, minting it, verifying it. Signing is delegated to the open-source OpenAgentOntology package. Not after-the-fact log analysis; not a hosted notary; not a legal opinion.
agent-designerUse when the user asks to design a multi-agent system, pick an orchestration pattern (supervisor/swarm/pipeline), generate tool schemas for agents, or evaluate agent execution logs for cost, latency, and failure bottlenecks. Examples: 'design an agent architecture for research automation', 'generate Anthropic tool schemas from these tool descriptions', 'analyze these agent run logs for bottlenecks'. NOT for Claude Code workflow files (use workflow-builder) or single-agent prompt design (use agent-workflow-designer).
agent-harnessTurn any domain folder of skills into a bounded agentic loop: compile a goal into a verifiable task plan, execute tasks with the domain's own tools, verify every task with machine-run checks, retry with caps, escalate to a human when budgets exhaust, and refuse to close until everything is verified or explicitly waived. Use when you want an agent or subagent to pick up a goal and drive it to a verified close across one of this repo's 18 domains ('run this goal through the engineering harness', 'set up an agentic loop for marketing work', 'make the finance domain self-verifying'). NOT for authoring Claude Code Workflow-tool .js scripts (workflow-builder), N-agent tournaments on one task (agenthub), single-file metric optimization (autoresearch-agent), or discovering published loop recipes (loop-library).
agent-launcher-orchestratorUse when a user wants to build, launch, grade, or schedule a Claude Managed Agent (CMA) in their own Anthropic account — "build me an agent", "launch this as a managed agent", "run this on a schedule", "grade my agent against a rubric", "set up a nightly worker". Reads the per-session goal (./my-agent/goal.json), routes deterministically to one of five phase sub-skills (interview → stage-launch → grade-iterate → run-without-you → wrap-up) via goal_router.py, and compiles the goal+phase into an execution shape (single-pass workflow / bounded grade→iterate loop / recurring cron deployment loop) via loop_compiler.py. Forks context so heavy intake (build sheets, payloads, eval cases) stays out of the parent thread. All launches are emitted as BYOK curl the user runs with their own key; no tool makes API calls. Inspired by anthropics/launch-your-agent (Apache-2.0). Distinct from engineering/agent-harness (generic domain loop) and engineering/write-a-skill (authors Claude Code skills, not CMAs).
agent-memoryUse when a project's CLAUDE.md has grown past what anyone reads and you want the agent to learn durable facts from its own sessions instead — or when asking why the agent keeps re-learning the same correction, why a remembered rule is wrong, or where a memory line came from. Implements a four-tier store (L0 transcripts / L1 candidates / L2 project context / L3 stable persona) where promotion is earned by recurrence across sessions and days, never by one confident statement, and nothing reaches a committed file without a human adopting it.