Skip to content
Skills Library
AI & agents · Automation

memory-tidy

/memory-tidy

Tidy an agent's always-loaded memory index (MEMORY.md) on macOS or Linux: trim long lines, move closed entries to an archive, fold domains into hub files, restore dropped pins and add pointers for orphan memory files. Use when the index is over budget or has orphans. Triggers: /memory-tidy, /mt, tidy memory.

Licence
MIT
Last repository change
24.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
2
URLs in SKILL.md
7
Deprecation

No signals detected. Repository changed on 24.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What to check before installing
  • SKILL.md zawiera komentarze HTML (2). Nie widać ich w podglądzie Markdown, a model je czyta.

What it does and when to use it

Tidy an agent's always-loaded memory index (MEMORY.md) on macOS or Linux: trim long lines, move closed entries to an archive, fold domains into hub files, restore dropped pins and add pointers for orphan memory files. Use when the index is over budget or has orphans. Triggers: /memory-tidy, /mt, tidy memory.

Original author description

Tidy an agent's always-loaded memory index (MEMORY.md) on macOS or Linux: trim long lines, move closed entries to an archive, fold domains into hub files, restore dropped pins and add pointers for orphan memory files. Use when the index is over budget or has orphans. Triggers: /memory-tidy, /mt, tidy memory.

How it works

  1. Когда запускать
  2. Шаг 0 — ВЛАДЕНИЕ (пропустить = устроить sync-conflict)
  3. Шаг 1 — посмотреть, что вообще есть
  4. Шаг 2 — механическое, без модели (0 токенов)
  5. Шаг 2-бис — забрать память из сессионных папок (0 токенов, узлы с ворктри)
  6. Шаг 3 — свернуть домен в хаб (H2-мандат)
  7. Шаг 4 — суждение (это делаю я, не скрипт)
  8. Шаг 5 — проверка, и только потом «готово»
  9. Грабли, оплаченные на этой рельсе
  10. Тест
Original SKILL.md headings · 120 lines, 967 words
SKILL.md preview
---
name: memory-tidy
description: "Tidy an agent's always-loaded memory index (MEMORY.md) on macOS or Linux: trim long lines, move closed entries to an archive, fold domains into hub files, restore dropped pins and add pointers for orphan memory files. Use when the index is over budget or has orphans. Triggers: /memory-tidy, /mt, tidy memory."
license: MIT
version: 1.0.0
---

# Memory Tidy — уборка всегда-загружаемого индекса

`MEMORY.md` грузится в КАЖДУЮ сессию. Это не файл, это **аренда, которую платишь на каждом ходу**.
Харнес молча режет хвост за 25 КБ: распухший индекс не «чуть хуже» — он **теряет память без
единого сообщения об ошибке**. Поэтому уборка здесь — не гигиена, а сохранность.

Паспорт детали: `~/.claude/scripts/_doc_memory_tidy.md`. Тело рельсы: `memory_tidy.sh`.

## Когда запускать
* сторож сказал RED (`memory_guard.py`);
* индекс подошёл к мягкой черте (15 КБ / 110 строк);
* руками — когда захотелось порядка;
* ночью само: launchd `ai.paloalto.memory-tidy`, 01:10 и 05:40 по локальному времени.

## Шаг 0 — ВЛАДЕНИЕ (пропустить = устроить sync-conflict)
```bash
python3 ~/.claude/scripts/memory_tidy_scope.py --explain
```
`~/.claude/projects/` держит три разных вещи, и они выглядят одинаково:
свои индексы · **синкнутые байт-в-байт копии, которыми владеет другой узел** · одноразовые ворктри.
Написать в чужой = два писателя на один файл = потерянная чья-то память. Область объявляется в
`memory_tidy_scope.json`, никогда не угадывается. Незнакомый узел → выход 3 громко, не тишина.

## Шаг 1 — посмотреть, что вообще есть
```bash
sh ~/.claude/scripts/memory_tidy.sh --dry-run --force
```
Печатает вердикт детекторов и рендерит промпт, ничего не меняя. Промпт стоит прочитать глазами —
это то, по чему будет действовать модель.

## Шаг 2 — механическое, без модели (0 токенов)
```bash
python3 ~/.claude/scripts/memory_orphan_cover.py --dry-run   # сироты → указатели в архив
python3 ~/.claude/scripts/memory_orphan_cover.py
```
**Сирота — это не потерянные данные, это недостижимые данные**, что при recall одно и то же:
файл на диске есть, ссылки нет, ни одна сессия его никогда не поднимет. Указатели идут в
`MEMORY-archive.md`, который НЕ грузится, — покрытие стоит 0 живого бюджета.
Хук берётся из `description:` самой заметки, поэтому скрипт не выдумывает: он переписывает.

## Шаг 2-бис — забрать память из сессионных папок (0 токенов, узлы с ворктри)
```bash
python3 ~/.claude/scripts/memory_harvest.py --scan              # только читает
python3 ~/.claude/scripts/memory_harvest.py --harvest --dry-run # что бы записал
python3 ~/.claude/scripts/memory_harvest.py --harvest
```
Заметку, написанную сессией ворктри, кладут в ЕЁ папку проекта, и домашний индекс о ней не знает.
Для домашней сессии такой заметки просто не существует — это та же недостижимость, что и сирота,
только этажом выше. Жатка копирует её домой (оригинал остаётся на месте) и вешает указатель
в `MEMORY-archive.md`.

Выход 3 = **нужен человек, и ничего не потеряно**: тёзка с другими байтами припаркована рядом
как `<слаг>.from-<источник>.md`. Разбираешь руками — слей версии в `<слаг>.md` и удали парковки.
Удаление жатка слышит: парковки назад не приносит, и выход падает до 0.

⛔ На узле без ворктри-папок шаг печатает «records : 0» — это не ошибка, а пустой вход.

## Шаг 3 — свернуть домен в хаб (H2-мандат)
Домен с ≥3 связанными живыми строками и без хаба → строим хаб **в этот же заход**, без спроса:
архитектура утверждена 04.07.2026, применять утверждённое — исполнение, а не новое решение.
```bash
python3 ~/.claude/scripts/memory_fold.py --index <MEMORY.md> --map <mapping.json> --dry-run
```
Суждение (какой слаг в какой домен) — в mapping, его делает модель. Перенос байтов — скрипт.
Так закрыт документированный отказ **summary-grounding**: когда хук переписывают «заодно», и
различающая деталь испаряется. Скрипт не перефразирует — он переносит дословно и проверяет
находимость каждого свёрнутого слага; потеряли находимость → не записано вовсе.

## Шаг 4 — суждение (это делаю я, не скрипт)
* **LIVE** остаётся только standing-правило, которое может выстрелить в сессии, **не открывавшей хаб**.
* **В архив** — закрытые разовые вещи, законченные проекты, отменённые инструменты.
* Перед архивацией — скан хвостов `pending|BLOCKED|TODO|⚠`: недоделка уезжает на доску, не в могилу.
* Сомневаешься, живое ли → **оставь живым**. Пере-подрезать дороже, чем недо-подрезать.
* Обрубленный хук («…перед «X») — это дефект, а не компактность: чини по `description:` заметки.

## Шаг 5 — проверка, и только потом «готово»
```bash
MEMORY_GUARD_EXCLUDE="$(python3 ~/.claude/scripts/memory_tidy_scope.py --exclude)" \
  python3 ~/.claude/scripts/memory_guard.py --force   # обязан GREEN; --force = ночной guard уже
                                                      # отработал сегодня, maintenance_gate режет 2-й
                                                      # заход; в отчёте сказать, зачем форсил
python3 ~/.claude/scripts/memory_focus.py        # обязан 0 missing pins
```
Отчёт модели о собственной работе доказательством не является. Судья — сторож.

## Грабли, оплаченные на этой рельсе
* **Пин чужого узла.** `memory-pin.txt` общий на флот, а слаги в нём хабовые. На другом узле
  тревога «пин выпал» не гасится никогда, а «восстановление» создаёт мёртвую ссылку. Пин относится
  к индексу, только если файл темы лежит рядом с этим индексом.
* **Генерируемый файл в сиротах.** `memory-focus-hints.md` переписывается каждым прогоном детектора;
  считать его сиротой = выдать вечную задачу, которую нельзя закрыть.
* **Красный, который всегда красный**, учит игнорировать красное. Тревога без достижимого зелёного —
  это баг тревоги.
* **Строка-шапка тоже «entry».** Сторож меряет ЛЮБУЮ строку: длинный changelog в
  `<!-- MEMORY.md vX.Y ... -->` в одиночку делает индекс RED (14.09, Якорь).
* **CRLF съедает символ бюджета и подделывает диф.** Сторож срезает только `\n`, поэтому на CRLF-индексе
  каждая строка считается на 1 длиннее (бюджет 149). И читать «универсальными» переводами строк, а
  писать голым `\n` = молча переписать ВЕСЬ файл: для синкаемых копий это фальшивый диф в 80 строк.
* **Разлогиненный headless CLI.** `claude -p` без токена печатал ошибку и выходил НУЛЁМ; auth-гейт
  в `claude_run.py` делает из этого честный 126. Лечится один раз: `claude setup-token`.
* Пути проектов начинаются с `-`, и утилиты читают их как флаги: `md5 -q ./путь`, не `md5 -q путь`.

## Тест
```bash
python3 ~/.claude/scripts/_test_memory_tidy.py   # 11 проверок, ~1 с, без LLM
```

<!--kit-footer-->

---

**Like this skill?** It is part of [second-brain-starter-kit](https://github.com/tonydzi/second-brain-starter-kit): the second brain we built for ourselves and run every day at Palo Alto AI Research Lab. Install the whole set with `npx skills add tonydzi/second-brain-starter-kit`. Everything is open source and free, so take what you need.

Flagships worth a look on their own: [secondop-panel](https://github.com/tonydzi/secondop-panel) (a second opinion from a panel of external models), [claude-memory-tidy](https://github.com/tonydzi/claude-memory-tidy) (stop your agent's memory from rotting), [telegram-mcp-kit](https://github.com/tonydzi/telegram-mcp-kit) (your own Telegram over MCP in about 15 minutes).

Author: **Anton Dziatkovskii**, Palo Alto AI Research Lab. Telegram [@tonydzi](https://t.me/tonydzi) - WhatsApp [+1 341 222 9178](https://wa.me/13412229178) - X [@Tony_Stef_](https://x.com/Tony_Stef_)

**Engineers: want to test-drive this setup?** Message me. I hand out free starter seeds to engineers who test and report back, and custom skill requests are welcome.

Versions

RepositoryScoreLicence
This page · tonydzi/second-brain-starter-kit100MIT
dwarvesf/dwarves-kit90MIT
pzh-xsj/dsh-memory-with-soul90MIT

Database snapshot: 13.11.2026 · package version 777a15d155d9 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 2 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100agent-memory-implementation
    Restructures a chaotic or overgrown MEMORY.md into a clean 2-layer architecture based on how Claude Code's autoDream system organizes memory — a lightweight pointer index (always loaded) and topic files (loaded on demand). Stale or superseded memories are deleted or corrected in…
  • 90memory-clean
    Use when a human asks to audit memory, find stale or duplicate memories, or needs tidy''s ICM-state audit. Not for writing new memories: use memory-update.
  • 100memory-lint
    Use when saving or editing agent memory files, when MEMORY.md and the memory directory may have drifted (unindexed files, dangling index entries), when a recalled memory seems missing or duplicated, or for a periodic hygiene pass over a file-based memory store. Also use for…
  • 100memory-consolidate
    Reflective consolidation pass over Serena memory files. Separates durable context (preferences, working style, key relationships, recurring workflows) from dated context (projects, deadlines, one-off tasks), merges duplicate topic files onto the richer path, converts relative…
  • 100memory-cleanup
    Clean up stale entries - closed issues, merged MRs, expired ephemeral namespaces, old session logs. Use when user says "clean memory", "memory cleanup", or "remove stale entries".
  • 100memory-audit
    Runs a memory hygiene pass on the project memory/ directory. Reviews all active memory files against the current codebase and archives or supersedes stale entries. Use before major feature work or when memory files feel out of date. Trigger this when someone says: clean up…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.