К основному содержанию
плагин

memory-engineering — плагин для Claude Code: аудит памяти

Плагин проверяет стоимость, структуру и правила забывания памяти ИИ-агента. Пригодится, чтобы оценить хранилище и найти проблемы в его политике.

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add alirezarezvani/claude-skills
/plugin install memory-engineering@claude-code-skills
Открыть на GitHub

Что делает memory-engineering

Плагин запускает четыре проверки памяти агента. Профайлер разделяет затраты на создание записей и запросы, а также считает стоимость правильного ответа. Подборщик архитектуры сравнивает четыре подхода с заданными ограничениями и не выбирает победителя при ничьей.

Аудитор классифицирует записи как FACT, SKILL, LOG или PROSE, находит близкие дубликаты и помечает устаревшие формулировки. Линтер проверяет правила забывания: политика должна задавать удаление или ограничение хранения, а противоречивые записи нельзя сливать автоматически. Без явного правила забывания проверка блокирует проектирование хранилища.

Команды /cs-memory-engineering и /cs-forgetting-audit запускают полный разбор и отдельную проверку политики. Скрипты написаны только на стандартной библиотеке Python; они работают с каталогом памяти или экспортом JSONL. Плагин проверяет хранилище, а не цикл задач агента.

Какие задачи решает

  • разделить затраты на запись и запросы к памяти
  • сравнить архитектуры памяти с заданными ограничениями
  • найти дубликаты и устаревшие записи в хранилище
  • проверить, задано ли правило забывания
  • не допустить автоматического слияния противоречивых записей

Примеры запросов агенту

  • Проверь память агента в ~/.claude/memory по всем четырём направлениям.
  • Проведи только проверку правил забывания в design.json.
  • Найди дубликаты и устаревшие записи в экспорте JSONL.

Как установить memory-engineering

Через маркетплейс плагинов

/plugin marketplace add alirezarezvani/claude-skills
/plugin install memory-engineering@claude-code-skills

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Вопросы о memory-engineering

Как установить memory-engineering в Claude Code?

Сначала добавьте маркетплейс командой /plugin marketplace add alirezarezvani/claude-skills, затем установите плагин: /plugin install memory-engineering@claude-code-skills.

Что делает memory-engineering?

Плагин анализирует затраты и архитектуру памяти, проверяет плотность записей и ищет проблемы в правилах забывания. Для полного разбора есть команда /cs-memory-engineering.

Какие форматы памяти проверяет плагин?

Аудитор работает с каталогом памяти или экспортом JSONL. Он классифицирует записи как FACT, SKILL, LOG или PROSE, а также ищет близкие дубликаты.

Исходный текст

memory-engineering · MIT
# memory-engineering

> Your agent's problem was never that it forgets. It's that it never forgets
> **on purpose**.

A storer optimizes what a system remembers. A memory engineer optimizes what it
forgets. This plugin makes that shift executable: four deterministic stdlib
scripts that price the write path, choose which cost to pay, audit what a store
actually holds, and **refuse a design with no forgetting policy**.

## Why this exists

Everyone building agent memory optimizes retrieval. Almost nobody engineers
what it costs to build, what is worth keeping, who can delete it, and where it
lands on the hardware. Stanford's systems characterization of ten memory systems
found the gap concretely:

- **Construction energy exceeds total query-phase energy across 300 queries** —
  the bill is paid on the write path you never watch.
- Energy per correct answer **spreads more than 47×** across systems (BM25 at
  4,145 J; MIRIX at ~197 kJ).
- At 1M tokens, footprint varies **up to 9×** — and **"none of the evaluated
  systems prune or forget by default."**

If you did not build forgetting, you do not have it.

## Install

```bash
/plugin marketplace add alirezarezvani/claude-skills
/plugin install memory-engineering
```

## Use

```bash
/cs-memory-engineering ~/.claude/memory      # full four-lens pass
/cs-forgetting-audit design.json             # just the blocking gate
```

Or run the scripts directly — each has `--help`, `--sample`, and `--output json`:

```bash
cd skills/memory-engineering

python scripts/memory_cost_profiler.py --sample
python scripts/memory_architecture_picker.py --sample
python scripts/memory_density_auditor.py --dir ~/.claude/memory
python scripts/forgetting_policy_linter.py --sample-failing
```

## The four scripts

| Script | Lens | What it does | Exit codes |
|---|---|---|---|
| `memory_cost_profiler.py` | Stanford — *what does it cost?* | Splits construction vs query spend, computes **cost per correct answer**, flags under-amortized writes and construction co-located with live queries | 0 · 2 finding · 3 bad input |
| `memory_architecture_picker.py` | Stanford — *which cost to pay?* | Scores long-context / flat RAG / structure-augmented RAG / agentic against constraints, disqualifies on hard limits, **names the cost you're choosing**, refuses to pick on a tie | 0 · 2 ambiguous · 3 bad input · 4 none viable |
| `memory_density_auditor.py` | Microsoft — *what's worth keeping?* | Classifies records **FACT / SKILL / LOG / PROSE**, finds near-duplicates, flags stale and time-relative wording, scores knowledge density. Runs on a real directory or JSONL | 0 dense · 2 finding · 3 bad input |
| `forgetting_policy_linter.py` | Anthropic + the gate | 8 checks; **F1** (explicit forgetting rule) and **F4** (contradictions surfaced, never auto-merged) are **blocking** | 0 PASS · 2 CONDITIONAL · **4 FAIL** |

Stdlib only. No network, no LLM calls, no dependencies.

## The gate

```
$ python scripts/forgetting_policy_linter.py --sample-failing

VERDICT: FAIL  (0/8 checks pass)
This design does not forget on purpose. F1 failed. F4 failed.

  FAIL  F1  explicit forgetting rule [BLOCKING]
        No TTL, no capacity bound, no decay. The store only grows.
  FAIL  F4  contradictions surfaced, never auto-merged [BLOCKING]
        Contradiction policy is 'newest_wins', which resolves conflicts silently.
```

**F4 is blocking on purpose.** Two memories that disagree may both have been
true in different contexts — "deploys go through Jenkins" and "deploys go
through GitHub Actions" is not a contradiction to resolve, it is a migration to
record. Auto-merging destroys the only evidence the conflict existed.

## Evidence discipline

The four-lens framing synthesizes *"How to be a Memory Engineer, from the
perspective of Stanford, Microsoft, Anthropic and Nvidia"* by
[@N01ennn](https://x.com/N01ennn/status/2083971749079581120).

**Every quantitative claim is cited to the primary source, not to that
article,** and each carries an explicit confidence level. Two of the article's
paraphrases are corrected in the references:

- The **47×** energy figure is the spread across ten evaluated systems, not
  "two systems with identical accuracy" (`memory_cost_canon.md` §2).
- The **97%** first-pass-error reduction is Rakuten's named, vendor-published
  customer testimonial — not a controlled study or a general property of
  building memory this way (`memory_control_and_governance.md` §4).

## Not this plugin

| You want | Use |
|---|---|
| Build and maintain one markdown knowledge vault | `llm-wiki` |
| A nightly self-improvement loop over transcripts | `skillopt-sleep` |
| Bound an agent's *task loop* | `agent-harness` |
| Price inference generally | `llm-cost-optimizer` |

This bounds a **store**, not a loop and not a vault.

## Primary sources

- Omri, Y. et al. — *Agent Memory: Characterization and System Implications of Stateful Long-Horizon Workloads*, [arXiv:2606.06448](https://arxiv.org/abs/2606.06448)
- Microsoft Research — [*PlugMem: A Task-Agnostic Plugin Memory Module for LLM Agents*](https://www.microsoft.com/en-us/research/publication/plugmem-a-task-agnostic-plugin-memory-module-for-llm-agents/)
- Kontonis, V. et al. — *MEMENTO: Teaching LLMs to Manage Their Own Context*, [arXiv:2604.09852](https://arxiv.org/abs/2604.09852)
- Anthropic — [*Built-in memory for Claude Managed Agents*](https://claude.com/blog/claude-managed-agents-memory)

Full citation lists (7 sources each) are in
[`skills/memory-engineering/references/`](skills/memory-engineering/references/).

## License

MIT.

© Alireza Rezvani · MIT · alirezarezvani/claude-skills

Похожие плагины

Все плагины по теме «Настройка агента: память, контекст, субагенты» →
ponytail DietrichGebert Плагин настраивает агента на короткие решения без лишних абстракций. Сгодится, когда нужно использовать возможности уже имеющегося кода и не усложнять задачу. ★ 176 443звёзд репо impeccable pbakaus Даёт агенту словарь дизайнера: 24 команды вроде polish, audit и bolder, чтобы правки интерфейса не сводились к «сделай красиво». ★ 88 212звёзд репо last-30-days-skill mvanhorn Собирает свежие посты, комментарии и транскрипты по любой теме за последний месяц и укладывает их в один отчёт. ★ 65 508звёзд репо claude-hud jarrodwatts Показывает под строкой ввода, сколько контекста занято, какие инструменты работают и как идут задачи. Пригодится, когда сессия длинная и надо видеть расход. ★ 28 841звёзд репо understand-anything Egonex-AI Плагин сканирует проект и строит интерактивный граф файлов, классов и зависимостей с веб-дашбордом. Пригодится при знакомстве с чужим или крупным кодом. ★ 88 314звёзд репо mem0 mem0ai Подключает долговременную память к Claude Code, сохраняя контекст проектов и привычки между сессиями. ★ 67 829звёзд репо

Из того же набора463

Весь набор →
email-pair Организует разбор почты в связке из двух скиллов: интервью для настройки базы знаний и регулярная сортировка входящих. Никогда не отправляет письма автоматически. ★ 28 733звёзд репо capture-skill Плагин превращает неструктурированный поток мыслей, задач и идей в список действий. Подходит для разбора brain dump прямо в рабочем пространстве. ★ 28 733звёзд репо handoff-engineering Сжимает текущую сессию в markdown-хендофф, чтобы свежий агент продолжил работу. Ссылается на артефакты по пути или URL, а не копирует их. ★ 28 733звёзд репо skill-doctor Оценивает настройку агента по реальной истории сессий Claude Code и Codex в репозитории. Формирует локальный HTML-отчёт с оценками и безопасными правками скиллов. ★ 28 733звёзд репо agent-harness Превращает папку со скиллами в ограниченный цикл: агент берёт цель, разбивает её на задачи, выполняет, проверяет и закрывает только после проверки. ★ 28 733звёзд репо zero-hallucination-coder Плагин выстраивает строгий процесс разработки перед написанием файлов: обсуждение, карта проекта, декомпозиция, запуск и проверка. Нужен для задач, где недопустимы выдуманные API. ★ 28 733звёзд репо hivemind Отдаёт рутинную работу воркерам opencode на дешёвых или открытых моделях, а планирование и слияние оставляет Claude. По умолчанию код уходит на сторонний сервис. ★ 28 733звёзд репо caveman Режим ответов без воды: агент выбрасывает вводные слова и вежливости, оставляя техническую суть. Токенов уходит меньше. ★ 28 733звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой