Ключевое положение
Правила, skills, агенты и команды для AI-ассистента представляют собой инженерные артефакты, аналогичные коду: им необходимы единый источник истины, версионирование, слои, автоматические проверки и история изменений.
AI Context (AIC) Engineering - от стихийного контекста к системному управлению
Правила, skills, агенты и команды для AI-ассистента представляют собой инженерные артефакты, аналогичные коду: им необходимы единый источник истины, версионирование, слои, автоматические проверки и история изменений.
Инженеры, тимлиды и платформенные команды, которые ведут несколько репозиториев с AI-контекстом.
Подход инструмент-агностичен: имена файлов и каталогов подставляются под используемый стек (например .cursor/, AGENTS.md, slash-команды IDE).
Современные агентные среды читают контекст из файлов рядом с кодом. Для одного репозитория такой подход работоспособен. В пяти, десяти или пятнадцати репозиториях без дисциплины накапливаются дубли, расхождения и недокументированные инструкции, происхождение которых невозможно установить.
Этот playbook описывает универсальную архитектуру, не зависящую от конкретного вендора IDE или облака. Cursor, Claude Code, Copilot и аналоги представляют собой примеры носителей контекста.
Авторитетная версия правил и skills располагается рядом с кодом. Разработчик вносит изменения в рабочем репозитории - без «деплоя из центра» для повседневной работы.
Отдельный git-репозиторий: зеркало всех проектов, журнал эволюции, архив вместо удаления, кросс-проектный индекс.
Явные типы артефактов (skills, rules, agents) и слои владения (проект, общий стек, внешний). Политика default-deny для чужого контекста.
Генерируемая карта возможностей, инспекторы дрейфа и владения, поведенческие сценарии - аналог CI для контекста.
Отдача от подхода резко нелинейна по числу репозиториев. Три из восьми проблем раздела 1 (дубли, дрейф индексов, невидимые слои) не возникают на одном-двух репозиториях.
| Масштаб (репозитории) | Что окупается | Что не окупается |
|---|---|---|
| 1-2 | Ориентационный документ, критический минимум rules, skills-first | Библиотека, зеркала, инспекторы, снимки, evals |
| 3-5 | То же + библиотека с историей и архивацией | Полная пирамида тестов, системные показатели |
| 5+ | Весь контур: синк, карта, инспекторы, default-deny | - |
| 10+ или команда | То же + Server-надстройка, регулярные прогоны | - |
Контур не следует разворачивать заранее, без подтверждённой потребности. Библиотеку вводят при масштабе 3-5 репозиториев и первом реальном дублировании.
При увеличении числа репозиториев возникают восемь системных сбоев:
| Проблема | Механизм ответа | Раздел |
|---|---|---|
| Дублирование | Общие слои + overlap-анализ (retire / adopt / hybrid) | → 5 |
| Дрейф индексов | Генерируемые карты + drift-чекер | → 6 |
| Нет истории | Журнал эволюции, archive вместо delete | → 4 |
| Невидимые слои | Карта возможностей по всем слоям | → 6 |
| Двунаправленный хаос | Один источник истины, push-only синхронизация | → 3 |
| Чужой контекст | Default-deny + снимки версий + gate | → 5, → прил. |
| Непроверяемость | Пирамида тестов: статика → smoke → evals | → 6 |
| Хрупкость | Git remote, правило 3-2-1, тестовое восстановление | → 4 |
Без дисциплины AI-контекст на многих репозиториях деградирует по восьми направлениям: дубли, дрейф индексов, отсутствие истории, невидимые слои, двунаправленный хаос, чужой контекст, непроверяемое поведение, хрупкость. Механизм ответа - home-канон, library-зеркало, слои с default-deny и измеримый контроль (карта, инспекторы, тесты).
Общий словарь документа: без него одни и те же слова в разных разделах могут интерпретироваться по-разному. Узкие термины подключения репозитория к контуру (регистрация sync, снимок MCP и аналогичные понятия) собраны отдельно - в глоссарии интеграции.
| Термин | Определение |
|---|---|
| Home | Рабочий репозиторий проекта: авторитетный слой AI-контекста рядом с кодом (например .cursor/). Единственное место правок project overlay. |
| Library | Отдельный git-репозиторий: зеркало проектов, Evolution-Log, archive и кросс-проектный индекс. Не заменяет home. |
| SSOT | Единственная авторитетная версия артефакта: для overlay - в home; для core/shared - в library. |
| Overlay | Контекст-слой проекта: skills, agents, rules, commands и ориентация (AGENTS.md / аналог). |
| Push-only | Односторонняя публикация overlay: home → library. Обратный поток правок «из library за проект» запрещён. |
| Core / shared | Общие слои стека: размещаются в library и материализуются в проекты как pull; локальные правки в home запрещены. |
| Default-deny | Внешний контекст (MCP, плагины, marketplace) не входит в production workflow без явного adopt через gate. |
| Capability map | Генерируемая инвентаризация skills / rules / agents / commands по слоям; не ведётся вручную. |
| Drift | Расхождение заявленных индексов (README / AGENTS / карта) с файлами на диске. |
| Evolution-Log | Журнал изменений агентной инфраструктуры: кто, когда и почему менял стек. |
| Archive | Хранилище retired-артефактов с датой и метаданными; удаление «без следа» запрещено. |
| Skill / Rule / Agent / Command | Типы артефактов: многошаговый workflow; всегда-on ограничение; узкая делегируемая роль; атомарная операция без skill-обёртки. |
| 3-2-1 | Правило резервного копирования: ≥3 копий, ≥2 носителя, ≥1 off-site; подтверждается фактическим backup-push и test restore. |
Концептуальный каркас: home = SSOT overlay; library = зеркало + журнал + archive; слои push/pull не смешиваются; внешнее - default-deny; карта и drift измеряют здоровье контекста.
Каждый проект ведёт AI-контекст локально - в каталоге, который IDE читает по умолчанию (например .cursor/ или аналог). Это не «копия из центра», а авторитетная версия для данного репозитория.
AGENTS.md, CLAUDE.md или эквивалент: назначение проекта, перечень skills, точки навигации.Изменения вносятся только в рабочем репозитории, затем односторонне публикуются в центральную библиотеку. Обратный поток (правка в библиотеке «за проект») запрещён - иначе вновь возникают два источника истины.
Пояснение
| Артефакт | Назначение |
|---|---|
AGENTS.md | Политика агента: MCP, skills-first, done criteria |
skills/<name>/SKILL.md | Один workflow = один skill с явным триггером |
rules/*.mdc | Непереговорные правила (всегда в контексте) |
| Скрипт синхронизации | Копирование home → library с timestamp в history/ |
Каждый файл контекста принадлежит ровно одному каналу - иначе вновь возникают два источника истины:
Namespace-инвариант: pull-слои разворачиваются в отдельный префикс/каталог, изолированно от project overlay. Совпадение относительного пути между каналами - ошибка модели, а не ситуация, в которой «более специфичный слой автоматически перекрывает другой на диске».
Un-retire: восстановление из archive/ выполняется воссозданием файла в home (SSOT), затем стандартным push-синком - не правкой зеркала.
Рабочий репозиторий - единственное место правки project overlay. Push-only в library; core/shared - pull из library. Каналы не пересекаются по путям. Un-retire - только через home.
Отдельный git-репозиторий, который не заменяет home, а дополняет его четырьмя функциями:
projects/<slug>/skills/).archive/ с датой.ai-context-library/
├── projects/
│ ├── backend-api/
│ │ ├── skills/
│ │ ├── agents/
│ │ └── docs/AGENTS.md
│ ├── mobile-app/
│ │ └── ...
│ └── shared/
│ ├── register/ # pack: prose / workers (pull в homes)
│ └── svelte/ # pack: cross-Svelte stack (pull в homes)
├── Evolution-Log.md
├── history/ # timestamp-снимки после каждого sync
└── archive/ # retired skills с контекстом
Правило 3-2-1: три копии данных, два носителя, одна off-site. Минимальное требование - remote git и периодический экспорт в object storage. Раз в квартал выполняется тестовое восстановление в чистой среде.
Одна команда синка должна быть идемпотентной и давать предсказуемый результат:
projects/<slug>/ (класс синка: full_overlay или skills_only - зафиксировать в wiring).history/<timestamp>/, записать diff в Evolution-Log.archive/<slug>/<timestamp>/ с метафайлом (кто, когда, откуда) - не удалять безвозвратно.manifest.json на каждый прогон.git pull --rebase (единственный писатель или git-примирение).Restore-сценарий (DoD бэкапа): clone library → clone home → развернуть overlay из зеркала на чистой машине. Без успешного тестового restore бэкап не считается доказанным.
Библиотека концентрирует чувствительные данные. Секреты (токены, ключи, внутренние URL) не включаются в контекст-файлы. При росте команд доступ следует сегментировать (отдельные remotes / ACL), сохраняя запрет на секреты.
Библиотека: зеркало + Evolution-Log + archive + индекс. Синк идемпотентен, создаёт manifest, поддерживает full_overlay / skills_only. Соответствие правилу 3-2-1 обеспечивается только фактическим backup-push и проверенным restore.
Контекст представляет собой не плоский список файлов, а слои с различными владельцами и политиками включения.
| Тип | Когда использовать | Анти-паттерн |
|---|---|---|
| Skill | Многошаговый workflow с ветвлениями | Дублировать rule внутри skill |
| Rule | Всегда активное ограничение | 100-строчный rule вместо skill |
| Agent | Делегирование узкой экспертизы | Агент без ограничения области ответственности |
| Command | Одна операция без skill-обёртки | Command, дублирующий skill |
Skills-first. Workflow в skills; commands - только для атомарных операций без skill-обёртки. Общие pack'и стека размещаются в library projects/shared/… и материализуются pull'ом, без копирования в каждый overlay.
Ортогонально слоям владения. Формула: (skills + agents + commands + rules) + (contexts + hooks) + (memory + navigation + inventory).
| Группа | Блок | Роль при интеграции |
|---|---|---|
| Примитивы | skills / agents / commands / rules | Что агент делает; инвентаризируется картой |
| Режимы | contexts / hooks | В каком режиме; наращиваются после must-have |
| Управление | memory (AGENTS.md), navigation (AI-GUIDE), inventory (карта) | Точка входа, роутер, контроль дрейфа |
Пояснение
projects/shared/<pack>/.Когда в проекте и в projects/shared/ присутствуют сходные skills, выбирается один из трёх вариантов:
Каждый MCP-сервер, плагин и marketplace-skill проходит gate: устанавливаются обоснование подключения, владелец, зафиксированная версия и состав данных, поступающих в промпт. Без записи в реестре подключение к production-воркфлоу запрещено.
Минимальные требования для подключения репо к контуру. Полный копируемый чек-лист - в → B. Кратко:
Companion к пункту 10 (не отдельный must-have). Меню / чрезмерно расширяется (project, user, plugins, MCP, built-ins). Рядом со справочником требуется human-слой: полный снимок входов и явный порядок приоритетного вызова. AI-GUIDE остаётся situation → primitive и ссылается на этот слой, не дублируя priority lists. Схемы и детали - → C.
Состояние всех репо фиксируется в матрице репозиторий × пункт (Y/-) - иначе состояние «примерно настроено» не поддаётся измерению.
Слои + AIC-блоки + must-have из 10 пунктов. Приоритет: project > shared > core. Внешнее - default-deny через gate. Overlap: retire / adopt / hybrid. Интеграция репо = выполнение must-have и wiring в sync.
Контекст без измерения деградирует столь же предсказуемо, как код без CI. Три инструмента образуют «инспекторский контур».
Генерируемый документ или JSON, содержащий все skills, rules, agents и commands по слоям. Обновляется скриптом при каждом sync - не вручную. Отражает:
| Инспектор | Что выявляет | Частота |
|---|---|---|
| Drift checker | Индексы в README/AGENTS не совпадают с файлами на диске | pre-commit / CI |
| Ownership check | Skill без владельца, rule без триггера | еженедельно |
| Mirror diff | Home изменён, sync не выполнен | после merge в main |
| External gate | Новый MCP без записи в реестре | при добавлении |
Следует начинать со статики и одного smoke для критичного skill (например «safe-commit»). Evals добавляются по мере зрелости системы.
--fail-on-drift)[planned] - рекомендации; не must-have и не CI-гейт.
Файловый SSOT (разделы 3-5) управляет артефактами на диске. Runtime управляет окном контекста в длинной сессии:
NOTES.md / memory), извлекать по требованию.Соотношение: пирамида тестов (§6.3) проверяет поведение; данная гигиена снижает context rot во время сессии.
Карта генерируется при sync. Инспекторы: drift, ownership, mirror, external gate, AI-GUIDE. Тесты: статика → smoke → evals. CI библиотеки блокирует merge при дрейфе и падении scored-audit.
Любое изменение AI-контекста следует тому же циклу, что и изменение кода:
Пояснение
Skills не подлежат удалению без следа: archive/<date>-<name>/ + запись в Evolution-Log с причиной и заменой.
Любое изменение контекста: Propose → Review (PR + drift) → Sync (library + Evolution-Log) → Verify (smoke). Удаление только через archive с записью причины и заменой.
SSOT и инженерная дисциплина для AI-артефактов; overlay правится в home. Исключение Shared/core: SSOT в library (projects/shared/<pack>/); в homes только pull/rollout.
Архивация вместо удаления, журналы и backup обеспечивают полную трассируемость.
Ручная сводка устаревает; генерируемая карта делает видимым суммарный контекст: project и packs из projects/shared/.
Overlap overlay↔shared: retire / adopt / hybrid. Автоматика не сливает и не удаляет сама.
Каждое подключение - явное решение со снимком. External ≠ shared: shared - свой общий стек library.
Статика выявляет структуру; смысл подтверждают smoke и evals.
Одна команда синка; карта и проверки - её побочные продукты.
Тонкий bootstrap объявляет SSOT и маршрутизирует. Overlay и shared-pack не делят один относительный путь; альтернативы - redirect, не дубль.
Решённая проблема фиксируется в библиотеке как переиспользуемый паттерн.
Без эллипсисов; изменение с оценкой влияния; общие слои с явной семантической версией.
Десять принципов: Контекст = код в месте работы; Ничего не теряется; Карта и индексы генерируются; Автоматика выявляет пересечения - решение принимает человек; Внешнее - зависимость по default-deny; Проверяется поведение, а не только форма; Минимум процедурных накладных расходов; Один вход, один канонический адрес; Контекст пополняется по итогам инцидентов; Инструкции исчерпывающи и версионированы. Это критерии завершённости, а не декларативные тезисы.
Подход масштабируется по ступеням. Внедрение всех компонентов одновременно не требуется; переход к следующему уровню без необходимого фундамента недопустим. Порог применимости (когда контур окупается) - во вступлении; таблица ниже - лестница наращивания после решения входить.
| Ступень | Размер | Минимум | Следующий шаг |
|---|---|---|---|
| L0 - Старт | 1-2 | AGENTS.md + 2-3 skills + 1 rule | pre-commit drift на индексы |
| L1 - Дисциплина | 3-5 | Library mirror + sync script + Evolution-Log | projects/shared/ для общего стека |
| L2 - Контроль | 5+ | Capability map + overlap-анализ + archive policy | smoke на top-3 skills |
| L3 - Платформа | 10+ или команда | CI gate, external registry, eval suite | поисковый индекс по library |
Выбор инструментов определяется командой. Канон описывает что должно быть измеримо и воспроизводимо, а не конкретного вендора.
Зрелость развивается по ступеням: L0 (1-2) → L1 library mirror (3-5) → L2 capability map и overlap (5+) → L3 CI, external registry, search (10+ или команда). Не следует переходить к следующему уровню без фундамента; выбор вендора инструментов имеет вторичное значение.
Внедрение идёт по этапам готовности, а не по календарю. Следующий этап начинается только когда выполнен Definition of Done предыдущего. Цель первого прохода: SSOT в home, зеркало в library, минимальный контроль качества.
AGENTS.md / аналог) с политикой языка, skills-first и done criteria.В home имеются ориентационный документ, remote, минимум два skill и один rule; по AGENTS.md агент определяет расположение канона и skills, подлежащие вызову.
projects/<slug>/, history/, archive/.history/, запись в Evolution-Log.Одна команда синка публикует проект в library; history и Evolution-Log пополняются; restore из зеркала проверен вручную. Правка library «за проект» запрещена.
Слои и приоритеты конфликтов описаны явно; отсутствуют незарегистрированные MCP; must-have закрыт или занесён в backlog с владельцем.
Карта генерируется при sync; drift выявляется автоматически; предусмотрен не менее чем один smoke для ключевого skill; внешний контекст проходит gate. Дальнейшее развитие ведётся по ступеням зрелости (раздел 9), без перехода через уровни.
Must-have описывает подключение; обратная операция обязательна, иначе остаются сироты в индексах и wiring.
projects/<slug>/ → archive/<slug>/<timestamp>/ с метафайлом; удаление = архивация.Архив и history/ сохраняются. Re-onboarding - как новое подключение из home (при необходимости читать архив, не edit-first в зеркале).
Внедрение начинается по этапам готовности, а не по календарю: фундамент в home → library + sync + restore → слои и must-have → карта, drift, smoke и external gate. Следующий этап начинается только после Definition of Done предыдущего.
Операционная политика контура: какие AIC-роли обязательны в проекте и какой parent model выбирать. Это не sync/wiring - копируемые интеграционные контракты остаются в приложениях.
Коды в таблице - портативные job-shaped идентификаторы ролей. Имена файлов в конкретном home (skill / command / agent) допускают расхождение; обязательны функция и must-have форма AIC, а не совпадение slug с диском. Примеры соответствия: dev-loop ↔ command restart/preview; safe-commit ↔ skill безопасного commit/push; ownership-check ↔ skill сверки home↔library. Продуктовые ярлыки в роли не включаются.
| AIC-роль | Зачем в проекте | Must-have AIC | Типовой триггер |
|---|---|---|---|
impact-check |
Impact check: impact перед правкой, минимальный diff | Rule (always-on) + Skill | «impact check», перед любой правкой кода/docs |
dev-loop |
Dev-loop: запустить/перезапустить dev-сервер, smoke маршрута | Command (+ Skill если workflow шире одной команды) | «dev-loop», локальный preview, smoke |
safe-commit |
Safe commit: status/diff/log, артефакты, без secrets, без force | Skill | «safe-commit», релизный commit |
code-reviewer |
Ревью diff, архитектуры, регрессий и контрактов до merge | Agent + Skill | «code review», PR, multi-file audit |
ci-repair |
CI repair: локализовать ошибку build/check/test, минимальный fix, повторный прогон | Agent + Command | «ci-repair», красный CI, failed check |
evals |
Пирамида проверки контекста: статика → smoke → evals на фикстурах и целевых моделях ИИ | Skill (+ Command / Agent для атомарного прогона) | «evals», smoke skill, eval suite, TDD / e2e |
orchestrator |
Разбиение сложной задачи, делегирование субагентам, сборка результата | Agent + Skill | «разбей задачу», multi-step plan, параллельные субагенты |
repo-audit |
Repo audit: docs, карта репо, маршруты, пайплайны, артефакты | Skill (baseline / apply / verify) | «repo-audit», полный audit репо |
aic-audit |
AIC audit: scored-проверка слоя skills/agents/commands/rules, битые ссылки, дубли | Command (+ Skill если scored-workflow вынесен отдельно) | «aic-audit», scored audit, архитектура контекста |
ownership-check |
Ownership check: сверка home-контекста с library-зеркалом - drift overlay, sync, история | Skill (+ ownership-профиль JSON; Command при ops-входе) | «ownership-check», overlay vs library drift |
update-docs |
Docs update: ориентация, навигация, индексы и changelog после смены примитивов | Skill (+ Command если требуется компактный вход) | «update-docs», guide/AGENTS drift, release notes |
code-cleaner |
Устранение дрейфа, сирот, неактивных ссылок, дублей skill+command, cruft | Agent + опционально Command / inventory-Skill | «очисти контекст», drift, orphan files |
best-practices |
Сверка с каноном и отраслевыми практиками; gap / adopt / hybrid | Skill (+ Agent при узкой экспертизе) | «best practices», сверка с каноном, gap-анализ, plan-review |
… |
Любая повторяемая AIC-роль домена - по тому же контракту | Agent и/или Skill; Command - только при отсутствии дубля workflow | Явный триггер в навигационном справочнике |
| AIC | Обязательность | Правило |
|---|---|---|
| Rule | ImpactCheck | Always-on; не дублировать длинный workflow внутри rule |
| Command | DevLoop и ops-входы (CiRepair, AicAudit, UpdateDocs, Evals) | Только атомарный вход; никогда не дублирует тот же workflow, что Skill |
| Skill | Да для большинства ролей (SafeCommit, OwnershipCheck, RepoAudit и далее) | Пошаговый workflow (когда вызывать, DoD, Must/Never) |
| Agent | CodeReviewer, Orchestrator, CiRepair, CodeCleaner | Узкая экспертиза; модель ИИ сессии наследуется, не пинится в frontmatter |
Отдельно от AIC-ролей: модели ИИ - семейства в picker (Grok, Opus и аналоги). Agents / skills / commands не фиксируют model: в frontmatter - наследуют session parent. Имена указываются только как (latest), без фиксации minor-версий.
ON (4): Composer (latest), Grok (latest) High, Sonnet (latest) High, Opus (latest) High. Opt (не ON) - budget fallback (2): Gemini Flash (latest), GPT Luna (latest).
| Пул | Модели | Когда |
|---|---|---|
| First-party (ON) | Composer, Grok | ~80% daily: edit, commit, explore, smoke, DevLoop, SafeCommit, UpdateDocs, CodeCleaner |
| API (ON) | Sonnet, Opus | Audit, deep review, hard policy, Orchestrator на сложных деревьях |
| Opt (budget) | Gemini Flash, GPT Luna | После исчерпания first-party / при жёстком API-бюджете |
| Задача или AIC-роль | Parent model (ИИ) | Пул |
|---|---|---|
| ImpactCheck (всегда в фоне) | наследует session | - |
| DevLoop, SafeCommit, UpdateDocs, CodeCleaner | Composer (latest) | first-party |
| Explore / bulk read / MAP | Grok (latest) High | first-party |
| CiRepair (простые поломки) | Composer (latest) | first-party |
| CodeReviewer, RepoAudit, AicAudit, OwnershipCheck, Evals, BestPractices | Sonnet (latest) High | API |
| Orchestrator (глубокое дерево / hard policy) | Opus (latest) High | API |
| CiRepair / redesign при жёсткой политике | Opus (latest) High | API |
| Budget explore fallback | Gemini Flash (latest) или GPT Luna (latest) | Opt |
High используется только для ресурсоёмких explore / audit / redesign. Routine выполняется Composer без High. Маршрутизация моделей задаётся таблицей выше; при необходимости она дублируется локальным файлом в home. Ориентационная навигация ссылается на эту таблицу (или локальный файл) и не дублирует цены и minor-версии. Коды AIC-ролей в таблице выше остаются портативными: соответствие skill/command/agent на диске определяет сам репозиторий.
AIC-роли - портативные job-shaped коды (имена файлов в home допускают расхождение); must-have определяет форму agent / skill / command / rule. Модели ИИ: ON (4) Composer / Grok / Sonnet / Opus; Opt (2) Gemini Flash / GPT Luna - session parent без pin в frontmatter. Два контура конкурентности - роли и picker - сверяются с фактической практикой, а не исключительно с внутренней практикой команды.
Краткие пояснения по разделам 1-11 собраны в одном месте для оперативного ознакомления. Полные сводки остаются в конце соответствующих разделов. Копируемые интеграционные контракты - в приложениях.
Без дисциплины AI-контекст на многих репозиториях деградирует по восьми направлениям: дубли, дрейф индексов, отсутствие истории, невидимые слои, двунаправленный хаос, чужой контекст, непроверяемое поведение, хрупкость. Механизм ответа - home-канон, library-зеркало, слои с default-deny и измеримый контроль (карта, инспекторы, тесты).
Концептуальный каркас: home = SSOT overlay; library = зеркало + журнал + archive; слои push/pull не смешиваются; внешнее - default-deny; карта и drift измеряют здоровье контекста.
Рабочий репозиторий - единственное место правки project overlay. Push-only в library; core/shared - pull из library. Каналы не пересекаются по путям. Un-retire - только через home.
Библиотека: зеркало + Evolution-Log + archive + индекс. Синк идемпотентен, создаёт manifest, поддерживает full_overlay / skills_only. Соответствие правилу 3-2-1 обеспечивается только фактическим backup-push и проверенным restore.
Слои + AIC-блоки + must-have из 10 пунктов. Приоритет: project > shared > core. Внешнее - default-deny через gate. Overlap: retire / adopt / hybrid. Интеграция репо = выполнение must-have и wiring в sync.
Карта генерируется при sync. Инспекторы: drift, ownership, mirror, external gate, AI-GUIDE. Тесты: статика → smoke → evals. CI библиотеки блокирует merge при дрейфе и падении scored-audit.
Любое изменение контекста: Propose → Review (PR + drift) → Sync (library + Evolution-Log) → Verify (smoke). Удаление только через archive с записью причины и заменой.
Десять принципов: Контекст = код в месте работы; Ничего не теряется; Карта и индексы генерируются; Автоматика выявляет пересечения - решение принимает человек; Внешнее - зависимость по default-deny; Проверяется поведение, а не только форма; Минимум процедурных накладных расходов; Один вход, один канонический адрес; Контекст пополняется по итогам инцидентов; Инструкции исчерпывающи и версионированы. Это критерии завершённости, а не декларативные тезисы.
Зрелость развивается по ступеням: L0 (1-2) → L1 library mirror (3-5) → L2 capability map и overlap (5+) → L3 CI, external registry, search (10+ или команда). Не следует переходить к следующему уровню без фундамента; выбор вендора инструментов имеет вторичное значение.
Внедрение начинается по этапам готовности, а не по календарю: фундамент в home → library + sync + restore → слои и must-have → карта, drift, smoke и external gate. Следующий этап начинается только после Definition of Done предыдущего.
AIC-роли - портативные job-shaped коды (имена файлов в home допускают расхождение); must-have определяет форму agent / skill / command / rule. Модели ИИ: ON (4) Composer / Grok / Sonnet / Opus; Opt (2) Gemini Flash / GPT Luna - session parent без pin в frontmatter. Два контура конкурентности - роли и picker - сверяются с фактической практикой, а не исключительно с внутренней практикой команды.
Playbook остаётся актуальным, пока слои, default-deny, карта и тесты сверяются с фактической практикой агентных сред - а не исключительно с внутренней практикой команды. Конкурентность представлена двумя контурами: (1) AIC-роли (§11.1) с must-have agent / skill / command / rule; (2) модели ИИ (§11.2) - ON (4) Composer / Grok / Sonnet / Opus и Opt (2) Gemini Flash / GPT Luna без pin в frontmatter. Дата сверки с отраслью (прил. I) - контрольная точка; при изменении picker или примитивов следует обновлять gate, шаблоны, таблицу маршрутизации моделей (§11.2) и матрицу репо × чек-лист, иначе контур устаревает быстрее кода.
Копируемые контракты для подключения репозитория к контуру. Пути и имена (.cursor/, AGENTS.md, CLAUDE.md) - примеры; следует адаптировать их к стеку используемого AI-инструмента. Концепция и операционная политика - в разделах 1-11; здесь - действия, выполняемые оператором вручную.
Этапы образуют последовательность готовности, а не календарный план.
# Home: SSOT + remote
cd project-a
git remote -v # remote обязателен
$EDITOR AGENTS.md # «контекст-SSOT здесь» + путь к зеркалу
# Library: отдельный репозиторий
mkdir context-library && cd context-library
git init
mkdir -p projects external scripts docs history archive
git remote add origin <private-remote-url>
git push -u origin HEAD
DoD A: у home имеются remote и ориентационный документ; library создана, запушена, каталоги на месте.
full_overlay или skills_only).projects/<slug>/, history, archive, Evolution-Log, manifest.json.pull --rebase).DoD B: одна команда зеркалит проект; history/archive/manifest пишутся; restore доказан.
репо × пункт.DoD C: любое изменение контекста проходит Propose → Review → Sync → Verify; деградация блокирует merge.
Repo: <slug> Дата: ____ Ответственный: ____
[ ] 1. Ориентационный документ (AGENTS.md / CLAUDE.md)
DoD: назначение, стек, строка «контекст-SSOT здесь», путь к зеркалу.
[ ] 2. Критический минимум rules (always-on)
DoD: язык, запреты, политика правок; десятки строк, не сотни.
[ ] 3. Workflow-skills
DoD: повторяемые процессы как skills; нет дубля skill+command.
[ ] 4. Операционные commands
DoD: компактные входы (restart, pre-deploy); smoke где применимо.
[ ] 5. Аудит-профиль (JSON)
DoD: ожидаемая архитектура; scored-audit его читает.
[ ] 6. Конфиг ownership
DoD: пути SSOT + каналы push/pull; ownership-check подхватывает.
[ ] 7. Wiring / индекс
DoD: slug в матрице библиотеки и в скрипте синка.
[ ] 8. Evolution-Log
DoD: создан первым sync; история ведётся с первого прогона.
[ ] 9. Git remote + backup-push
DoD: remote есть; off-site копия свежая после push.
[ ] 10. AI-GUIDE (навигация)
DoD: ситуация → примитив; ведётся (актуален) и валидатор = 0 errors.
Companion (не отдельный пункт): human-слой снимка меню «/» + порядок приоритетного вызова;
AI-GUIDE ссылается на него, не дублирует priority lists.
Companion к must-have №10 (AI-GUIDE), не отдельный пункт чек-листа. Меню / смешивает project, user, plugins, MCP и built-ins; требуется human-слой: полный снимок входов и явный порядок приоритетного вызова. AI-GUIDE остаётся situation → primitive и ссылается на приоритеты, не дублируя их.
Пояснение
Пояснение
Пояснение
Каталог slash-меню хранится в рабочем репозитории рядом с ориентационным справочником (типично под docs/: каталог рядом с AI-GUIDE). Имена файлов, генератор и CI-гейты адаптируются под стек команды.
context-library/
├── projects/<slug>/ # зеркало overlay (skills, agents, rules, commands, docs)
├── projects/shared/<pack>/ # pull-слой стека (namespace отделён от overlay)
├── external/ # снимки MCP / плагинов (версия + hash)
├── scripts/ # sync, map, inspectors
├── docs/ # индексы, AI-GUIDE library-роли
├── history/ # timestamp-снимки до overwrite
├── archive/ # retired с метаданными
├── Evolution-Log.md # или per-project log
└── manifest.json # каждый прогон sync
| Класс синка | Что зеркалится | Когда |
|---|---|---|
full_overlay | skills, agents, rules, commands, docs | Норма для продуктовых репо |
skills_only | skills (+ ориентация) | Переходное; ownership выявляет сироты |
# <Repo Name> - контекст для AI-агента
## Назначение
<Что за репозиторий и за что отвечает.>
## Стек
<Языки, фреймворки, ключевые сервисы.>
## Контекст-SSOT
Авторитетная версия располагается ЗДЕСЬ, в <.cursor/ | .claude/>.
Правки выполняются только здесь. Зеркало (read-only): context-library/projects/<slug>/.
НЕ редактировать зеркало и НЕ бэкпортить его в проект.
## Приоритет слоёв
project overlay > shared > core > user-level.
External / MCP / built-ins в разрешении конфликтов правил не участвуют.
## Каналы
- project overlay: push (home → library)
- core/shared: pull-материализация (локальные правки запрещены)
# Критические правила (always-on)
1. Язык общения: <lang>.
2. Запрещённые действия: <force-push main, delete без archive, …>.
3. Политика правок: SSOT - этот репо; core/shared исправляются в library.
4. Секреты в контекст-файлы НЕ попадают.
5. Списки без «и т.д.» / «...» - перечислять полностью.
6. Impact-before-change: объяснять влияние до правки.
7. Один тип артефакта - один адрес (без дублей в чужих каталогах).
---
name: <kebab-case>
description: <триггер: условия вызова; не реферат>
---
# <Название workflow>
## Когда применять
<Явные триггеры.>
## Шаги
1. …
2. …
## Definition of Done
- [ ] <проверяемый критерий>
## Must / Never
- MUST …
- NEVER …
## Ссылки (lazy)
- references/<details>.md
Текст skill следует поддерживать компактным; детали размещаются в references. Степень свободы: low для destructive/ops commands, medium/high для эвристических workflow. Проверка skill выполняется на целевых моделях.
{
"repo": "<slug>",
"repo_class": "product | library",
"stack_mode": "<node-web | python-svc | …>",
"required_categories": ["rules", "skills", "commands", "agents"],
"rules": { "min_count": 1 },
"skills": { "required_sections": ["Когда применять", "Шаги", "Definition of Done"] },
"commands": { "smoke_testable": true }
}
{
"repo": "<slug>",
"ssot_paths": [".cursor/", "AGENTS.md"],
"channels": {
"project_overlay": "push",
"core": "pull",
"shared": "pull"
},
"mirror_path": "context-library/projects/<slug>/"
}
Копируемый пример always-on rule + paired skill - полное тело как в приложении.
---
name: impact-check
description: Apply a strict pre-change critical checklist before editing code or docs. Use when user asks for "critical rule", "critical", "apply rules", or when starting implementation that needs impact, editing, and release-discipline safeguards.
disable-model-invocation: true
---
# Impact Check
Use this skill as a universal guardrail before making project changes.
## Goal
Enforce a consistent pre-change protocol:
- impact analysis before edits
- precise editing method
- documentation hygiene
- release/version discipline
## Mandatory Pre-Change Check
Before any edit, state:
1. current state
2. proposed change
3. impact:
- affected files and functions
- behavior change
- performance implications
- risks
Then ask for confirmation when the repository policy requires it.
## Universal Constraints
- Do not abbreviate configuration or checklist items with `etc.`, `...`, `and so on`.
- Avoid truncating user-facing copy unless explicitly requested.
## Editing Discipline
- Prefer targeted edits over full rewrites.
- Keep diffs minimal and local to the requested change.
- Do not create extra documents unless required.
- Reuse existing documentation and repository files as source of truth.
## Release Discipline
When the workflow includes versioning:
- follow the repository's version bump process
- keep changelog/release artefacts in sync with policy
- do not invent ad-hoc version steps
## Quick Response Template
Use this short template before implementation:
```markdown
Critical check:
- Current state: ...
- Proposed change: ...
- Impact:
- Files/functions: ...
- Behavior: ...
- Performance: ...
- Risks: ...
```
## When Not to Use
Skip this skill only when:
- the task is purely informational and no changes are requested
- the user explicitly asks to brainstorm without implementation
По умолчанию устанавливается deny. Подключение допускается только при явном adopt по всем пунктам:
Кандидат: <название, источник, версия/коммит/хеш>
[ ] Потребность реальна (есть задача, не «на всякий случай»).
[ ] Overlap-анализ: нет дубля, либо retire / adopt / hybrid записан.
[ ] Стоимость: always-on vs lazy; токены / латентность / внимание.
[ ] Безопасность: доверенный источник; tool poisoning / injection / эксфильтрация оценены.
[ ] Снимок в external/ (версия + hash + дата).
[ ] Update-чекер; при апдейте - ревизия overlap-решений.
[ ] MCP: pin hash tool manifest (name + description + input schema); алерт на drift.
[ ] MCP: tool returns = данные, не инструкции.
[ ] MCP: sandbox / least privilege; HITL на destructive / data-sharing.
[ ] MCP: multi-server = отдельные trust domains; нет shadowing tools.
Решение: [ ] adopt [ ] hybrid [ ] retire-свой [ ] deny
Кто / когда: ____
Подход, изложенный в разделах 1-11, согласуется с отраслевыми практиками на дату сверки 2026-08-10. Источники могли измениться после указанной даты.
| Практика | Как закрыто в playbook | Источники |
|---|---|---|
| Контекст как ресурс, а не несистематизированное накопление - минимальный высокосигнальный набор; «context rot» | Цена always-on / default-deny (§5, прил. F); карта и lazy skills (§6, прил. E.3) | Anthropic - Effective context engineering; Mem0 - Context engineering guide |
| Иерархия AGENTS.md / CLAUDE.md - компактный корень + углубление | Must-have №1; шаблон ориентации (прил. B, прил. E.1) | Packmind - Context engineering 2026 |
| Прогрессивное раскрытие skills - frontmatter → тело → assets; degrees of freedom; тест на целевых моделях | Skills-first (§5); шаблон SKILL.md (прил. E.3) | Anthropic - Agent Skills; Skill authoring best practices |
| MCP security = supply chain - allowlist, sandbox, HITL, pin hash, untrusted returns | Default-deny + gate (§5, прил. F): rug pull, tool poisoning, multi-server isolation | OWASP - MCP Security Cheat Sheet; CSA - Agentic MCP security |
| Evals и CI-гейты - прогон на изменение, regression-gate, трассировка | Пирамида статика → smoke → evals (§6); CI inspectors (§6.4, прил. A шаг C) | Anthropic - Demystifying evals; Braintrust - AI agent evaluation |
| Термин | Смысл |
|---|---|
| Wiring | Регистрация slug проекта в скрипте sync и в матрице library |
| Sync class | Класс зеркалирования: full_overlay или skills_only - фиксируется в wiring |
| Manifest | Машиночитаемый manifest.json каждого прогона sync |
| Tool manifest pin | Hash описаний MCP tools (name + description + input schema) на момент adopt |
| Scored audit | Детерминированная оценка здоровья контекста по аудит-профилю репозитория |
| External snapshot | Снимок MCP / плагина в external/ с версией, hash и датой |
AI Context (AIC) Engineering - from ad-hoc context to systematic governance
Rules, skills, agents and commands for an AI assistant constitute engineering artefacts analogous to code: they require a single source of truth, version control, explicit layers, automated checks and a change history.
This document is intended for engineers, team leads and platform teams responsible for managing AI context across multiple repositories.
The approach is tool-agnostic: file and directory names are mapped onto the reader's stack (for example, .cursor/, AGENTS.md and IDE slash commands).
Modern agent environments read context from files stored alongside the code. This arrangement is effective for a single repository. Across five, ten or fifteen repositories, however, duplication, inconsistency and undocumented ad-hoc instructions accumulate unless context is governed systematically.
This playbook defines a universal architecture independent of any particular IDE or cloud vendor. Cursor, Claude Code, Copilot and equivalent tools are illustrative context carriers.
The authoritative rules and skills reside alongside the code. Developers edit them within the working repository, without requiring central deployment for routine changes.
A separate Git repository provides a mirror of every project, an Evolution-Log, an archive in place of deletion, and a cross-project index.
The architecture defines explicit artefact types (skills, rules and agents) and ownership layers (project, shared stack and external), with a default-deny policy for external context.
A generated capability map, drift and ownership inspectors, and behavioural scenarios provide the equivalent of CI for context.
The return on this approach is sharply non-linear with the number of repositories. Three of the eight failures in section 1 (duplication, index drift, invisible layers) do not arise with one or two repositories.
| Scale (repos) | What is warranted | What is not warranted |
|---|---|---|
| 1-2 | Orientation document, critical minimum rules, skills-first | Library, mirrors, inspectors, snapshots, evals |
| 3-5 | The same + library with history and archiving | Full test pyramid, system metrics |
| 5+ | Full contour: sync, map, inspectors, default-deny | - |
| 10+ or team | The same + server overlay, regular runs | - |
Do not deploy the full contour in advance without demonstrated need. Introduce a library at the 3-5 repository scale and when the first real duplication emerges.
As the number of repositories increases, eight systemic failures become evident:
| Problem | Response | Section |
|---|---|---|
| Duplication | Common layers + overlap analysis (retire / adopt / hybrid) | → 5 |
| Index drift | Generated maps + drift checker | → 6 |
| No history | Evolution-Log, archive instead of deletion | → 4 |
| Invisible layers | Map of capabilities across all layers | → 6 |
| Bidirectional chaos | One source of truth, push-only sync | → 3 |
| External context | Default-deny + version snapshots + gate | → 5, → App. |
| Unverifiable behaviour | Test pyramid: static checks → smoke → evals | → 6 |
| Fragility | Git remote, 3-2-1 rule, test restore | → 4 |
Without systematic governance, AI context across multiple repositories degrades in eight ways: duplication, index drift, missing history, invisible layers, bidirectional chaos, uncontrolled external context, unverifiable behaviour and fragility. The required response comprises a home canon, a library mirror, default-deny layers and measurable controls: a capability map, inspectors and tests.
A shared vocabulary for this document: without it, the same words denote different concepts across sections. Narrow terms for connecting a repository to the system (sync registration, MCP snapshots and related terms) are collected separately in the integration glossary.
| Term | Definition |
|---|---|
| Home | The project's working repository: the authoritative AI-context layer alongside the code (for example .cursor/). The sole place where the project overlay may be edited. |
| Library | A separate git repository providing project mirrors, an Evolution-Log, an archive and a cross-project index. It does not replace home. |
| SSOT | The single authoritative version of an artefact: for the overlay, in home; for core/shared layers, in the library. |
| Overlay | The project context layer: skills, agents, rules, commands and orientation (AGENTS.md or equivalent). |
| Push-only | One-way publication of the overlay: home → library. Reverse edits from the library into a project are prohibited. |
| Core / shared | Shared stack layers that reside in the library and are materialised into projects as pull layers; local edits in home are prohibited. |
| Default-deny | External context (MCP servers, plugins, marketplace skills) must not enter a production workflow without an explicit adopt decision via the gate. |
| Capability map | A generated inventory of skills / rules / agents / commands by layer; it must not be maintained manually. |
| Drift | A discrepancy between declared indexes (README / AGENTS / the map) and the files on disk. |
| Evolution-Log | The change log for agent infrastructure: who changed the stack, when and why. |
| Archive | Storage for retired artefacts with date and metadata; deletion without a trace is prohibited. |
| Skill / Rule / Agent / Command | Artefact types: a multi-step workflow; a continuously active constraint; a narrowly scoped delegated role; an atomic operation without a skill wrapper. |
| 3-2-1 | Backup policy: at least three copies, on at least two media, with at least one off-site; satisfied only by an actual backup-push and a verified restore. |
Conceptual frame: home is the overlay SSOT; the library provides mirror, log and archive; push and pull layers must not share paths; external context is default-deny; the capability map and drift checks measure context health.
Each project manages its AI context locally, in the directory that the IDE reads by default (for example, .cursor/ or its equivalent). This is not a copy derived from the central library; it is the authoritative version for that repository.
AGENTS.md, CLAUDE.md or equivalent: the project's purpose, available skills and navigation paths.Changes are made only in the working repository and are then published unidirectionally to the central library. The reverse flow - editing a project's files in the library - is prohibited because it would establish two sources of truth.
Notes
| Artefact | Purpose |
|---|---|
AGENTS.md | Agent policy: MCP, skills-first, completion criteria |
skills/<name>/SKILL.md | One workflow per skill, with an explicit trigger |
rules/*.mdc | Non-negotiable rules (always in context) |
| Sync script | Copies home → library and records a timestamped snapshot in history/ |
Each context file belongs to exactly one channel; assignment to multiple channels would create competing sources of truth:
Namespace-invariant: pull layers are materialised under a separate prefix or directory and are not mixed with the project overlay. Relative path matching between channels constitutes a model error; specificity on disk does not determine precedence.
Un-retire: reinstate an artefact from archive/ by recreating the file in home (the SSOT) and then running the normal push sync - never by editing the mirror.
The working repository is the exclusive location for editing the project overlay. The overlay is pushed to the library; core/shared is pulled from it. Channel paths must not overlap, and retired artefacts may be restored only through home.
A separate Git repository does not replace home; it complements home in four ways:
projects/<slug>/skills/).archive/ with a date.ai-context-library/
├── projects/
│ ├── backend-api/
│ │ ├── skills/
│ │ ├── agents/
│ │ └── docs/AGENTS.md
│ ├── mobile-app/
│ │ └── ...
│ └── shared/
│ ├── register/ # pack: prose / workers (pull into homes)
│ └── svelte/ # pack: cross-Svelte stack (pull into homes)
├── Evolution-Log.md
├── history/ # timestamp snapshots after each sync
└── archive/ # retired skills with context
Apply the 3-2-1 rule: three copies of the data, on two types of media, with one copy off-site. At minimum, use a remote Git repository plus periodic export to object storage. Test recovery to a clean environment once per quarter.
Each sync execution must be idempotent and produce a predictable result:
projects/<slug>/ (Sync class: full_overlay or skills_only - record it in the wiring).history/<timestamp>/ and write the diff to Evolution-Log.archive/<slug>/<timestamp>/ with a metadata file (who, when, where) - do not delete permanently.manifest.json for each run.git pull --rebase and use either a single writer or standard Git reconciliation.Restore script (backup DoD): clone the library → clone home → restore the overlay from the mirror on a clean machine. A backup remains unverified until a test restore succeeds.
The library is a sensitive hub. Secrets (tokens, keys and internal URLs) must not be stored in context files. As teams expand, partition access through separate remotes or ACLs without relaxing the prohibition on secrets.
The library provides a mirror, Evolution-Log, archive and index. Sync is idempotent, writes a manifest and supports full_overlay / skills_only. The 3-2-1 requirement is satisfied only by an actual backup-push and a verified restore.
Context is not a flat list of files; it comprises a set of layers with distinct owners and inclusion policies.
| Type | When to use | Anti-pattern |
|---|---|---|
| Skill | Multi-step workflow with branches | Duplicate rule inside skill |
| Rule | Continuously active constraint | Overextended 100-line rule in place of a skill |
| Agent | Delegation of specialised expertise | General-purpose agent without bounded scope |
| Command | One operation without a skill wrapper | A command that duplicates a skill |
Skills-first. Workflows belong in skills; commands are reserved for atomic operations without a skill wrapper. Shared stack packs live in the library under projects/shared/… and reach homes by pull - not by copy-paste into every overlay.
Orthogonal to ownership layers. Formula: (skills + agents + commands + rules) + (contexts + hooks) + (memory + navigation + inventory).
| Group | Block | Role in integration |
|---|---|---|
| Primitives | skills / agents / commands / rules | Capabilities exercised by the agent; inventoried in the capability map |
| Modes | contexts / hooks | Operational modes of the agent; introduced after the must-have baseline |
| Control | memory (AGENTS.md), navigation (AI-GUIDE), inventory (map) | Entry point, router, drift control |
Notes
projects/shared/<pack>/ packs.When the project and projects/shared/ contain similar skills, select one of three options:
Each MCP server, plugin and marketplace skill must pass a gate that establishes its necessity, owner, pinned version and contribution to the prompt. Connection to a production workflow without a registry entry is prohibited.
This constitutes the minimum threshold for connecting a repository to the system. The full reusable checklist appears in → B. In summary:
Companion to item 10 (not a separate must-have). The / menu expands excessively (project, user, plugins, MCP, built-ins). Next to the guide, a human layer is required: a full inventory of those entries and an explicit priority-invocation order. AI-GUIDE stays situation → primitive and links to that layer; it does not duplicate priority lists. Diagrams and detail: → C.
Record the state of every repository in a repository × item matrix (Y/-); an approximate configuration state is not measurable.
The model combines ownership layers, AIC blocks and a ten-point must-have baseline. Priority is project > shared > core; external context is default-deny and must pass the gate. Resolve overlaps through retire / adopt / hybrid. A repository is integrated only when it meets the baseline and is wired into sync.
Context without measurement degrades as predictably as code without CI. Three instruments form an inspection loop.
A generated document or JSON inventory records all skills, rules, agents and commands by layer. A script updates it during every sync; it is never maintained manually. It provides:
| Inspector | Detection scope | Frequency |
|---|---|---|
| Drift checker | Indexes in README/AGENTS do not match files on disk | pre-commit / CI |
| Ownership check | A skill without an owner or a rule without a trigger | weekly |
| Mirror diff | Home has changed but sync has not been executed | after a merge to main |
| External gate | New MCP without registry entry | when adding |
Initial coverage should comprise static checks and one smoke test for each critical skill (for example, "safe-commit"). Evals should be added as the skills mature.
--fail-on-drift)[planned] - recommendations only; not a must-have item and not a CI gate.
File SSOT (sections 3-5) governs artefacts on disk. Runtime governs the context window during a long session:
NOTES.md / memory), retrieved on demand.Correspondence: the test pyramid (§6.3) verifies behaviour; this hygiene reduces context rot during a session.
The map is generated during sync. Inspectors address drift, ownership, the mirror, the external gate and AI-GUIDE. Tests progress from static checks → smoke → evals. Library CI blocks a merge when drift or a scored-audit failure is detected.
Every change to AI context must follow the same lifecycle as a code change:
Notes
Skills must never be deleted without a record: move them to archive/<date>-<name>/ and add an Evolution-Log entry stating the reason and replacement.
Every context change follows Propose → Review (PR + drift) → Sync (library + Evolution-Log) → Verify (smoke). Remove an artefact only through the archive, recording the reason and its replacement.
SSOT and engineering discipline for AI artefacts; edit the overlay in home. Shared/core exception: SSOT resides in the library (projects/shared/<pack>/); homes receive pull/rollout only.
Archive instead of delete, plus journals and backup, yields full traceability.
Manually maintained summaries become obsolete; a generated map renders total context visible: project overlays and packs under projects/shared/.
Overlay↔shared overlap: retire / adopt / hybrid. Automation never merges or deletes on its own.
Every connection is an explicit decision with a snapshot. External ≠ shared: shared is the library's own common stack.
Static checks detect structure; smoke and evals confirm meaning.
One sync command; the map and checks are its secondary outputs.
A thin bootstrap declares SSOT and routes onward. Overlay and shared-pack must not share one relative path; alternatives are redirects, not duplicates.
A solved problem is recorded in the library as a reusable pattern.
No ellipses; changes ship with impact analysis; shared layers carry an explicit semantic version.
Ten principles: Context = code where the work is; Nothing is lost; Maps and indexes are generated; Automation detects overlaps - humans decide; External is default-deny dependency; Behaviour is verified, not only form; Minimum procedural overhead; One entry, one canonical address; Context is enriched from incidents; Instructions are exhaustive and versioned. These constitute completion criteria, not declarative claims.
The approach scales in stages. Implementation may proceed incrementally, but each level requires a sound foundation before progression to the next. The applicability threshold (when the investment is warranted) appears in the introduction; the table below is the staged maturity ladder after the decision to adopt.
| Stage | Size | Minimum | Next step |
|---|---|---|---|
| L0 - Start | 1-2 | AGENTS.md + 2-3 skills + 1 rule | pre-commit drift on indexes |
| L1 - Discipline | 3-5 | Library mirror + sync script + Evolution-Log | projects/shared/ for shared stack |
| L2 - Control | 5+ | Capability map + overlap analysis + archive policy | smoke tests for the top 3 skills |
| L3 - Platform | 10+ or team | CI gate, external registry, eval suite | library search index |
The team selects the tools. The canon specifies what must be measurable and repeatable, rather than prescribing a vendor.
Maturity advances in stages: L0 (1-2) → L1 library mirror (3-5) → L2 capability map and overlap analysis (5+) → L3 CI, external registry and search (10+ or team). Each level's foundations must be established before progression; tool selection is secondary.
Deployment follows readiness stages, not a calendar. Each stage begins only after the previous stage's Definition of Done has been satisfied. The initial implementation should establish the SSOT in home, a library mirror and minimum quality controls.
AGENTS.md or equivalent) that defines the language policy, skills-first workflow and done criteria.Home has an orientation document, a remote, at least two skills and one rule; an agent reading AGENTS.md can identify the canon and the skills to invoke.
projects/<slug>/, history/ and archive/.history/ and adds an entry to Evolution-Log.A single sync execution publishes the project to the library; history and Evolution-Log are updated, and restoration from the mirror has been verified manually. Editing a project's files in the library is prohibited.
Layers and conflict priorities are explicit; no MCP server is connected without a registry entry; every must-have item is complete or placed in the backlog with an owner.
The map is generated during sync, drift is detected automatically, at least one key skill has a smoke test, and external context passes the gate. Subsequent development proceeds through the maturity stages in section 9 without omitting any level.
The must-have baseline describes onboarding; the reverse operation is mandatory, otherwise orphans remain in indexes and wiring.
projects/<slug>/ → archive/<slug>/<timestamp>/ with a meta file; deletion = archiving.The archive and history/ are retained. Re-onboarding follows the same path as a new connection from home (read the archive if needed; do not edit-first in the mirror).
Implementation proceeds through readiness stages, not a calendar: foundation in home → library + sync + restore → layers and must-have baseline → map, drift, smoke and external gate. Each stage begins only after the previous stage's Definition of Done has been satisfied.
Operating policy for the system: which AIC roles every project must carry, and which parent model to select. This is not sync or wiring - reusable integration contracts remain in the appendices.
Codes in the table are portable job-shaped role identifiers. File names in a given home (skill / command / agent) may differ; what is required is the function and the must-have AIC form, not a slug match on disk. Mapping examples: dev-loop ↔ a restart/preview command; safe-commit ↔ a safe commit/push skill; ownership-check ↔ a home↔library ownership skill. Product-tied labels are not used as role codes.
| AIC role | Why it belongs in the project | Must-have AIC | Typical trigger |
|---|---|---|---|
impact-check |
Impact check: impact analysis before edit, minimal diff | Rule (always-on) + Skill | "impact check", before any code/docs edit |
dev-loop |
Dev-loop: start/restart the dev server, route smoke | Command (+ Skill if the workflow is wider than one command) | "dev-loop", local preview, smoke |
safe-commit |
Safe commit: status/diff/log, artefacts, no secrets, no force | Skill | "safe-commit", release commit |
code-reviewer |
Review diffs, architecture, regressions, and contracts before merge | Agent + Skill | "code review", PR, multi-file audit |
ci-repair |
CI repair: isolate a failing build/check/test, minimal fix, re-run | Agent + Command | "ci-repair", red CI, failed check |
evals |
Context test pyramid: static → smoke → evals on fixtures and target AI models | Skill (+ Command / Agent for an atomic run) | "evals", skill smoke test, eval suite, TDD / e2e |
orchestrator |
Decompose a complex task, delegate to subagents and integrate the result | Agent + Skill | "break down the task", multi-step plan, parallel subagents |
repo-audit |
Repo audit: docs, repo map, routes, pipelines, artefacts | Skill (baseline / apply / verify) | "repo-audit", full repo audit |
aic-audit |
AIC audit: scored check of the skills/agents/commands/rules layer, dead links, duplicates | Command (+ Skill when the scored workflow is a separate skill) | "aic-audit", scored audit, context architecture |
ownership-check |
Ownership check: compare home context to the library mirror - overlay drift, sync, history | Skill (+ ownership-profile JSON; Command for an ops entry) | "ownership-check", overlay vs library drift |
update-docs |
Docs update: refresh orientation, navigation, indexes and changelogs after primitive changes | Skill (+ Command where a thin entry is required) | "update-docs", guide/AGENTS drift, release notes |
code-cleaner |
Resolve drift, orphaned files, dead links, skill+command duplicates and obsolete material | Agent + optional Command / inventory Skill | "clear the context", drift, orphan files |
best-practices |
Align with canon and industry practice; gap / adopt / hybrid | Skill (+ Agent for narrow expertise) | "best practices", canon check, gap analysis, plan-review |
… |
Any repeatable domain AIC role - subject to the same contract | Agent and/or Skill; Command only without workflow duplication | Explicit trigger in the navigation guide |
| AIC | Required | Rule |
|---|---|---|
| Rule | ImpactCheck | Always-on; do not duplicate a long workflow inside a rule |
| Command | DevLoop and ops entries (CiRepair, AicAudit, UpdateDocs, Evals) | Atomic entry only; never duplicates the same workflow as a Skill |
| Skill | Required for most roles (SafeCommit, OwnershipCheck, RepoAudit and onward) | Step-by-step workflow (when to use, DoD, Must/Never) |
| Agent | CodeReviewer, Orchestrator, CiRepair, CodeCleaner | Narrow expertise; session AI model is inherited, not pinned in frontmatter |
AI models are distinct from AIC roles: they are model families available in the picker (Grok, Opus and their peers). Agents / skills / commands do not pin model: in frontmatter; they inherit the parent session. Family names use (latest) exclusively - minor versions must not be pinned.
ON (4): Composer (latest), Grok (latest) High, Sonnet (latest) High, Opus (latest) High. Opt (not ON) - budget fallback (2): Gemini Flash (latest), GPT Luna (latest).
| Pool | Models | When |
|---|---|---|
| First-party (ON) | Composer, Grok | Approximately 80% of routine work: editing, commits, exploration, smoke tests, DevLoop, SafeCommit, UpdateDocs and CodeCleaner |
| API (ON) | Sonnet, Opus | Audits, rigorous reviews, complex policy work and Orchestrator on complex decision trees |
| Opt (budget) | Gemini Flash, GPT Luna | After first-party capacity is exhausted or under a tight API budget |
| Task or AIC role | Parent AI model | Pool |
|---|---|---|
| ImpactCheck (always in the background) | inherits session | - |
| DevLoop, SafeCommit, UpdateDocs, CodeCleaner | Composer (latest) | first-party |
| Explore / bulk read / MAP | Grok (latest) High | first-party |
| CiRepair (simple failures) | Composer (latest) | first-party |
| CodeReviewer, RepoAudit, AicAudit, OwnershipCheck, Evals, BestPractices | Sonnet (latest) High | API |
| Orchestrator (deep tree / hard policy) | Opus (latest) High | API |
| CiRepair / redesign under hard policy | Opus (latest) High | API |
| Budget explore fallback | Gemini Flash (latest) or GPT Luna (latest) | Opt |
High is reserved for intensive exploration, audits or redesign. Routine work uses Composer without High. Model routing is defined by the table above; optionally mirrored as a local file in home. Orientation navigation links to that table (or local file) and does not duplicate prices or minor versions. AIC role codes in the table above remain portable - each repository defines the mapping onto on-disk skills / commands / agents.
AIC roles are portable job-shaped codes (home file names may differ); the must-have column defines the agent / skill / command / rule form. AI models: ON (4) Composer / Grok / Sonnet / Opus; Opt (2) Gemini Flash / GPT Luna - chosen as the session parent without frontmatter pins. Competitiveness rests on both loops - roles and the picker - reviewed against current practice rather than internal convention alone.
Concise summaries of sections 1-11 are consolidated here for reference. Identical summaries remain at the end of their respective sections. Reusable integration contracts appear in the appendices.
Without systematic governance, AI context across multiple repositories degrades in eight ways: duplication, index drift, missing history, invisible layers, bidirectional chaos, uncontrolled external context, unverifiable behaviour and fragility. The required response comprises a home canon, a library mirror, default-deny layers and measurable controls: a capability map, inspectors and tests.
Conceptual frame: home is the overlay SSOT; the library provides mirror, log and archive; push and pull layers must not share paths; external context is default-deny; the capability map and drift checks measure context health.
The working repository is the exclusive location for editing the project overlay. The overlay is pushed to the library; core/shared is pulled from it. Channel paths must not overlap, and retired artefacts may be restored only through home.
The library provides a mirror, Evolution-Log, archive and index. Sync is idempotent, writes a manifest and supports full_overlay / skills_only. The 3-2-1 requirement is satisfied only by an actual backup-push and a verified restore.
The model combines ownership layers, AIC blocks and a ten-point must-have baseline. Priority is project > shared > core; external context is default-deny and must pass the gate. Resolve overlaps through retire / adopt / hybrid. A repository is integrated only when it meets the baseline and is wired into sync.
The map is generated during sync. Inspectors address drift, ownership, the mirror, the external gate and AI-GUIDE. Tests progress from static checks → smoke → evals. Library CI blocks a merge when drift or a scored-audit failure is detected.
Every context change follows Propose → Review (PR + drift) → Sync (library + Evolution-Log) → Verify (smoke). Remove an artefact only through the archive, recording the reason and its replacement.
Ten principles: Context = code where the work is; Nothing is lost; Maps and indexes are generated; Automation detects overlaps - humans decide; External is default-deny dependency; Behaviour is verified, not only form; Minimum procedural overhead; One entry, one canonical address; Context is enriched from incidents; Instructions are exhaustive and versioned. These constitute completion criteria, not declarative claims.
Maturity advances in stages: L0 (1-2) → L1 library mirror (3-5) → L2 capability map and overlap analysis (5+) → L3 CI, external registry and search (10+ or team). Each level's foundations must be established before progression; tool selection is secondary.
Implementation proceeds through readiness stages, not a calendar: foundation in home → library + sync + restore → layers and must-have baseline → map, drift, smoke and external gate. Each stage begins only after the previous stage's Definition of Done has been satisfied.
AIC roles are portable job-shaped codes (home file names may differ); the must-have column defines the agent / skill / command / rule form. AI models: ON (4) Composer / Grok / Sonnet / Opus; Opt (2) Gemini Flash / GPT Luna - chosen as the session parent without frontmatter pins. Competitiveness rests on both loops - roles and the picker - reviewed against current practice rather than internal convention alone.
The playbook remains current only while its layers, default-deny policy, capability map and tests are reviewed against current agent-platform practice, rather than solely against a team's internal conventions. Competitiveness depends on two concurrent loops: (1) AIC roles (§11.1), each with the required agent / skill / command / rule; and (2) AI models (§11.2) - ON (4) Composer / Grok / Sonnet / Opus and Opt (2) Gemini Flash / GPT Luna without frontmatter pins. The industry-alignment date (Appendix I) constitutes a checkpoint. When the picker or primitives change, the gate, templates, model-routing table (§11.2) and repo × checklist matrix must be updated; otherwise, the system will degrade more rapidly than the code.
Reusable contracts for connecting a repository to the system. Paths and filenames (.cursor/, AGENTS.md, CLAUDE.md) are illustrative; map the names onto the AI tooling stack in use. The conceptual model and operating policy appear in sections 1-11; these appendices cover operational procedures.
The stages constitute a readiness sequence rather than a calendar schedule.
# Home: SSOT + remote
cd project
git remote -v # remote is required
$EDITOR AGENTS.md # "context-SSOT here" + path to mirror
# Library: separate repository
mkdir context-library && cd context-library
git init
mkdir -p projects external scripts docs history archive
git remote add origin
git push -u origin HEAD
DoD A: home has a remote and an orientation document; the library repository is established and contains the required directories.
full_overlay or skills_only).projects/<slug>/, history, archive, Evolution-Log, manifest.json.pull --rebase).DoD B: a single sync execution mirrors the project, writes history/archive/manifest, and demonstrates successful restoration.
repo × item matrix.DoD C: every context change must follow Propose → Review → Sync → Verify; degradation blocks a merge.
Repo: Date: ____ Responsible: ____
[ ] 1. Orientation document (AGENTS.md / CLAUDE.md)
DoD: purpose, stack, explicit "context-SSOT here" statement, path to mirror.
[ ] 2. Critical minimum rules (always-on)
DoD: language, prohibitions, edit policy; concise enough to remain always-on.
[ ] 3. Workflow skills
DoD: repeatable processes as skills; no duplicate skill+command.
[ ] 4. Operational commands
DoD: thin entry points (restart, pre-deploy); smoke test where applicable.
[ ] 5. Audit profile (JSON)
DoD: expected architecture; scored-audit consumes the profile.
[ ] 6. Ownership config
DoD: SSOT paths + push/pull channels; ownership-check detects violations.
[ ] 7. Wiring / index
DoD: slug in the library matrix and in the sync script.
[ ] 8. Evolution-Log
DoD: created by first sync; history is written from day one.
[ ] 9. Git remote + backup-push
DoD: remote exists; off-site copy is current after push.
[ ] 10. AI-GUIDE (navigation)
DoD: situation → primitive; maintained (current) and validator = 0 errors.
Companion (not a separate item): human layer for «/» menu inventory + priority-invocation order;
AI-GUIDE links to it and does not duplicate priority lists.
Companion to must-have item 10 (AI-GUIDE), not a separate checklist item. The / menu mixes project, user, plugins, MCP and built-ins; a human layer is required: a full inventory of entries and an explicit priority-invocation order. AI-GUIDE stays situation → primitive and links to priorities without duplicating them.
Notes
Notes
Notes
The slash-menu catalog is stored in the working repository next to the orientation guide (typically under docs/: the catalog beside AI-GUIDE). File names, generators and CI gates are adapted to the team's tooling stack.
context-library/
├── projects// # mirror overlay (skills, agents, rules, commands, docs)
├── projects/shared// # pull stack layer (namespace separated from overlay)
├── external/ # snapshots of MCP / plugins (version + hash)
├── scripts/ # sync, map, inspectors
├── docs/ # indexes, AI-GUIDE library-roles
├── history/ # timestamp snapshots before overwrite
├── archive/ # retired with metadata
├── Evolution-Log.md # or per-project log
└── manifest.json # each sync run
| Sync class | What is mirrored | When |
|---|---|---|
full_overlay | skills, agents, rules, commands, docs | Standard for production repositories |
skills_only | skills (+ orientation) | Transitional; ownership checks identify orphaned artefacts |
# - context for the AI agent
## Purpose
## Stack
## Context-SSOT
The authoritative version resides HERE, at <.cursor/ | .cloud/>.
Edits only here. Mirror (read-only): context-library/projects//.
DO NOT edit the mirror and DO NOT backport it into the project.
## Layer priority
project overlay > shared > core > user-level.
External / MCP / built-ins are not involved in resolving rule conflicts.
## Channels
- project overlay: push (home → library)
- core/shared: pull materialization (local edits are prohibited)
# Critical rules (always-on)
1. Language of communication: .
2. Prohibited actions: .
3. Edit policy: SSOT - this repo; core/shared are edited in the library.
4. Secrets MUST NOT be stored in context files.
5. Lists without "etc." / "..." - list in full.
6. Impact-before-change: explain the impact before changes.
7. One type of artefact - one location (no duplicates in other directories).
---
name:
description:
---
#
## When to use
## Steps
1. ...
2. ...
## Definition of Done
- [ ]
## Must/Never
- MUST ...
- NEVER ...
## Links (lazy)
- references/.md
Keep the body concise and place detailed material in references. Assign a low degree of freedom to destructive or operational commands and medium/high to heuristic workflows. Test the skill on the target models.
{
"repo": "",
"repo_class": "product | library",
"stack_mode": "",
"required_categories": ["rules", "skills", "commands", "agents"],
"rules": { "min_count": 1 },
"skills": { "required_sections": ["When to apply", "Steps", "Definition of Done"] },
"commands": { "smoke_testable": true }
}
{
"repo": "<slug>",
"ssot_paths": [".cursor/", "AGENTS.md"],
"channels": {
"project_overlay": "push",
"core": "pull",
"shared": "pull"
},
"mirror_path": "context-library/projects/<slug>/"
}
A reusable example of an always-on rule and its paired skill, presented in full as it appears in the application.
---
name: impact-check
description: Apply a strict pre-change critical checklist before editing code or docs. Use when user asks for "critical rule", "critical", "apply rules", or when starting implementation that needs impact, editing, and release-discipline safeguards.
disable-model-invocation: true
---
# Impact Check
Use this skill as a universal guardrail before making project changes.
## Goal
Enforce a consistent pre-change protocol:
- impact analysis before edits
- precise editing method
- documentation hygiene
- release/version discipline
## Mandatory Pre-Change Check
Before any edit, state:
1. current state
2. proposed change
3. impact:
- affected files and functions
- behaviour change
- performance implications
- risks
Then ask for confirmation when the repository policy requires it.
## Universal Constraints
- Do not abbreviate configuration or checklist items with `etc.`, `...`, `and so on`.
- Avoid truncating user-facing copy unless explicitly requested.
## Editing Discipline
- Prefer targeted edits over full rewrites.
- Keep diffs minimal and local to the requested change.
- Do not create extra documents unless required.
- Reuse existing documentation and repository files as source of truth.
## Release Discipline
When the workflow includes versioning:
- follow the repository's version bump process
- keep changelog/release artefacts in sync with policy
- do not invent ad-hoc version steps
## Quick Response Template
Use this short template before implementation:
```markdown
Critical check:
- Current state: ...
- Proposed change: ...
- Impact:
- Files/functions: ...
- Behaviour: ...
- Performance: ...
- Risks: ...
```
## When Not to Use
Skip this skill only when:
- the task is purely informational and no changes are requested
- the user explicitly asks to brainstorm without implementation
The default is deny. External context may be adopted only after every criterion has been satisfied:
Candidate:
[ ] A documented task establishes the need; adoption is not precautionary.
[ ] Overlap analysis: no duplicate, or retire / adopt / hybrid is recorded.
[ ] Cost: always-on vs lazy; tokens / latency / attention.
[ ] Security: trusted source; tool poisoning / injection / exfiltration assessed.
[ ] Snapshot in external/ (version + hash + date).
[ ] Update checker; review the overlap decision during each update.
[ ] MCP: pin the tool-manifest hash (name + description + input schema); drift alert.
[ ] MCP: tool output = data, not instructions.
[ ] MCP: sandbox / least privilege; HITL on destructive / data-sharing.
[ ] MCP: multi-server = separate trust domains; no shadowing tools.
Decision: [ ] adopt [ ] hybrid [ ] retire-own [ ] deny
Who/When: ____
The approach in sections 1-11 was aligned with industry practice on the review date, 2026-08-10. Sources may have changed subsequently.
| Practice | How this playbook covers it | Sources |
|---|---|---|
| Context as a governed resource - minimal high-signal set; "context rot" | Cost of always-on context / default-deny (§5, Appendix F); capability map and lazy skills (§6, Appendix E.3) | Anthropic - Effective context engineering; Mem0 - Context engineering guide |
| Hierarchy AGENTS.md / CLAUDE.md - concise root + progressively detailed layers | Must-have item 1; orientation pattern (Appendix B, Appendix E.1) | Packmind - Context engineering 2026 |
| Progressive disclosure of skills - frontmatter → body → assets; degrees of freedom; test on target models | Skills-first (Section 5); template SKILL.md (Appendix E.3) | Anthropic - Agent Skills; Skill authoring best practices |
| MCP security as supply-chain security - allowlist, sandbox, HITL, pin hash, untrusted returns | Default-deny + gate (§5, Appendix F): rug pull, tool poisoning, multi-server isolation | OWASP - MCP Security Cheat Sheet; CSA - Agentic MCP security |
| Evals and CI gates - change-specific runs, regression gates and tracing | Pyramid of static checks → smoke → evals (§6); CI inspectors (§6.4, Appendix A step C) | Anthropic - Demystifying evals; Braintrust - AI agent evaluation |
| Term | Meaning |
|---|---|
| Wiring | Registration of a project slug in the sync script and the library matrix |
| Sync class | Mirroring class: full_overlay or skills_only - recorded in wiring |
| Manifest | Machine-readable manifest.json produced by each sync run |
| Tool manifest pin | A hash of MCP tool descriptions (name + description + input schema) at adoption time |
| Scored audit | A deterministic health assessment of context against the repository audit profile |
| External snapshot | A frozen MCP / plugin capture under external/ with version, hash and date |