feat(using-wiki): v2.0.0 — channel file → mappa wiki-сущности (#983)

Karpathy-дисциплина сохранена (ingest/query/lint, слаги, frontmatter,
index/log), канал — mappa: wiki_get/wiki_create/wiki_update/entity_search,
запись под лизом (task_claim_next → claim_token, решение 19).
setup-wiki умер (нечего настраивать). Per-type refs (#1037): ref/num
первыми, id internal — для wiki.update.
This commit is contained in:
2026-08-24 16:41:19 +03:00
parent 7d08c5beba
commit 92a15ecb50

View File

@@ -1,139 +1,202 @@
---
name: using-wiki
author: ours
version: 1.1.0
description: Policy skill for working with an existing `.wiki/` (Karpathy LLM Wiki pattern). Use when the user asks to ingest a document, answer from the wiki, lint/health-check it, or says "use project wiki", "обнови вики", "проверь вики", "запроси вики", "заингесть", "query the wiki". Also use when modifying any file under `.wiki/` — the workflow and formats below are mandatory, and project-specific conventions live in `.wiki/CLAUDE.md`. If `.wiki/` is missing or non-canonical, delegate to `setup-wiki` first (it has its own confirmation gate). Renamed from `wiki-maintainer` at v1.0.0.
version: 2.0.0
description: >
Policy skill for working with the project wiki in Mappa (Karpathy LLM Wiki
pattern, channel = mappa-сущности, решения 14/15 спеки mappa). Use when the
user asks to ingest a document, answer from the wiki, lint/health-check it, or
says «use project wiki», «обнови вики», «проверь вики», «запроси вики»,
«заингесть», «query the wiki». Also use when modifying any wiki page — the
workflow and formats below are mandatory, and project-specific conventions live
in the `CLAUDE` wiki-сущности проекта. Wiki = сущности `type=wiki` в сервисе
(чтение — карв-аут лиза; запись — под лизом проекта, решение 19). Файлового
`.wiki/` больше нет; `setup-wiki` умер (нечего настраивать).
---
# using-wiki
> Policy for maintaining an LLM Wiki (Karpathy pattern: https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). Knowledge is **compiled once and kept current** across three layers, via three named operations, with strict file formats that make the wiki parseable and grep-friendly. This skill governs *usage* of an existing wiki — initial creation and migration to canon are owned by `setup-wiki`.
> Policy for maintaining an LLM Wiki (Karpathy pattern:
> https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) whose pages
> live in **Mappa** as `type=wiki` сущности (решение 14/15), not in files.
> Knowledge is **compiled once and kept current**: three named operations
> (ingest / query / lint), strict page formats that keep the wiki parseable and
> grep-friendly, and a cross-linked graph ([[refs]] → рёбра, решение 4).
## Prerequisites
This skill assumes the project has a canonical `.wiki/` layout: `CLAUDE.md` (schema), `index.md` (catalog), `log.md` (op log), `overview.md`, `raw/README.md`, and the six content directories `entities/`, `concepts/`, `packages/`, `sources/`, `contradictions/`, `open-questions/`.
Wiki проекта = сущности в сервисе Mappa (HTTP-ядро, MCP-адаптер `mcp__mappa__*`).
Слаг страницы = путь от корня вики без расширения (`index`, `log`, `CLAUDE`,
`concepts/foo`, `entities/bar`, `packages/baz`, `sources/doc`, `overview`).
Body = frontmatter + markdown как есть (content-модель сохраняется, решение 2).
If `.wiki/` is **missing**, or the layout is **non-canonical** (e.g. `SUMMARY.md` instead of `index.md`, or `source/` instead of `concepts/`/`sources/`, or `contradictions/`/`open-questions/` directories are absent) — invoke the `setup-wiki` skill first. It detects the situation (greenfield vs migrate) and creates or migrates the structure with its own confirmation gate. Only after `setup-wiki` finishes should this skill proceed with the operations below.
Проектная вики (scope=project) читается/пишется с параметром проекта;
общая вики (scope=shared) — без проекта. Чей именно вики трогаем, определяет
контекст: `wiki.get(project, slug)` — проектная, `wiki.get(slug)` — shared.
## Three layers (do not blur)
Файловый `.wiki/` в репозиториях — легаси: источник истины — сервис.
Если вики проекта пуста (нет сущностей) — **ничего настраивать не надо**
(setup-wiki умер): первый ingest сам создаёт `CLAUDE`, `index`, `log` (см. Ingest).
1. **Raw sources**`.wiki/raw/` (or external paths registered in `raw/README.md`). **Immutable.** Read, never edit. The only exception is appending a `> Status` blockquote when the user explicitly asks for a status audit.
2. **Wiki** — everything else under `.wiki/`. Agent-owned. Entity / concept / package / source summary pages.
3. **Schema**`.wiki/CLAUDE.md`. Project-specific conventions (what entities, what packages, naming). Always read it first if present; it overrides this skill when it conflicts.
## MCP-поверхность
## First step on every operation
| Операция | Тул | Примечание |
|---|---|---|
| Чтение страницы | `mcp__mappa__wiki_get(project?, slug)` | чтение — карв-аут лиза (решение 19) |
| Поиск страниц | `mcp__mappa__entity_search(q, type='wiki', project?, scope?, limit)` | ILIKE по body/title |
| Захват лиза для записи | `mcp__mappa__task_claim_next(project, owner)` | → `token` (лиз проекта, решение 19); таска может отсутствовать |
| Продление лиза | `mcp__mappa__task_heartbeat(project, claim_token)` | долгие ingest-циклы |
| Создать страницу | `mcp__mappa__wiki_create(project, slug, body, claim_token)` | под лизом |
| Обновить страницу | `mcp__mappa__wiki_update(project, id, title?, body?, claim_token)` | под лизом; id — internal (см. ниже) |
1. Read `.wiki/CLAUDE.md` if it exists.
2. Read `.wiki/index.md` to locate relevant pages.
3. Only then act.
**Запись всегда под лизом.** Мутации wiki гейтятся лизом проекта: без
валидного `claim_token` — 422 busy. Лиз экспирится по TTL (дефолт 600s);
закрыть вручную нечем (кроме `admin_release_lease` для залипших) — пиши,
затем отпусти (не держи лиз на время чтения/размышлений).
If `.wiki/CLAUDE.md` is missing, the layout is incomplete — invoke `setup-wiki` rather than improvising.
**Рефы и id (#1037).** Публичная поверхность несёт per-type реф первым полем:
`ref: "w:3"` (тип+номер, решение 20), `num` следом, глобальный `id` — internal
(последним полем). Для `wiki.update` нужен internal `id` — бери его из ответа
`wiki_get`/`entity_search`. В тексте страниц ссылайся викилинками по слагу
(`[[concepts/foo]]`, решение 4) или per-type рефами (`[[i:N]]`/`[[t:N]]`).
## Three operations
## Три слоя (не смешивать)
1. **Raw-источники**`sources/<slug>` страницы. Иммутабельны: читай, не
редактируй (единственное исключение — блок-цитата `> Status` по явной
просьбе пользователя).
2. **Вики** — все остальные страницы (entities/concepts/packages/…).
3. **Схема** — сущность `CLAUDE` (slug `CLAUDE`). Конвенции проекта. Читай её
первой; она перекрывает этот скил при конфликте.
## Первый шаг любой операции
1. `mcp__mappa__wiki_get(project, 'CLAUDE')` — если есть, читай (схема).
2. `mcp__mappa__wiki_get(project, 'index')` — каталог, найди нужные страницы.
3. Только потом действуй.
Если `CLAUDE` нет — вики либо новая, либо неухоженная: не импровизируй
структуру, создай `CLAUDE`/`index`/`log` при первом ingest (см. ниже).
## Три операции
### Ingest — «заингесть X»
1. Read the raw source fully.
2. Extract: entities, concepts, packages, cross-cutting patterns.
3. Create `sources/<slug>.md` (one summary page per source, ~50150 lines).
4. For each affected entity/concept/package page:
- If it exists → update it. **Flag contradictions explicitly** with `> **Противоречие:** источник A говорит X, источник B — Y`. Don't silently overwrite.
- If not → create it.
5. Update `index.md` — add or move entries.
6. Append one line to `log.md` (format below).
7. Report to the user: what created, what updated, what contradictions found.
1. Прочитай источник полностью.
2. Извлеки: entities, concepts, packages, кросс-резы.
3. Создай `sources/<slug>` — одну страницу-резюме на источник (~50150 строк;
ссылку на raw клади в frontmatter `raw_path` + `ingested:`).
4. Для каждой затронутой страницы:
- есть → обнови (`wiki_update(project, id, body, claim_token)`). **Противоречия
помечай явно** блоком `> **Противоречие:** источник A говорит X, источник B — Y`.
Не затирай молча.
- нет → создай (`wiki_create`).
5. Обнови `index` (каталог: одна строка на страницу).
6. Допиши одну строку в `log` (формат ниже).
7. Отчитайся пользователю: что создано, что обновлено, какие противоречия.
**One ingest may touch 1015 pages. This is normal — that's why LLMs do it.**
**Один ingest может затронуть 1015 страниц. Это нормально — для того LLM и нужны.**
### Query — вопрос по wiki
Порядок записи: сначала лиз (`task_claim_next`), затем все wiki-мутации одним
циклом (не бери лиз на чтение), затем отпусти (лиз живёт TTL — просто закончи
писать; heartbeat только если цикл реально долгий).
1. Read `index.md` first, then drill into relevant pages.
2. Answer with citations as markdown links to wiki pages.
3. **Compound the wiki.** If the answer is a real synthesis (comparison, analysis, new connection) — ask the user: "Сохранить как страницу wiki?" Good queries become durable pages under `concepts/`, `analyses/`, or similar.
4. Append one line to `log.md`.
### Query — вопрос по вики
### Lint — «проверь wiki»
1. Читай `index` сначала, затем углубляйся в страницы (`wiki_get` по слагу).
2. Отвечай с цитатами-викилинками: `[[concepts/foo]]` (рёбра создаются при
записи, решение 4).
3. **Компаундируй вики.** Если ответ — реальный синтез (сравнение, анализ,
новая связь) — спроси пользователя: «Сохранить как страницу wiki?» Хорошие
вопросы становятся страницами в `concepts/`.
4. Допиши строку в `log`.
Scan for:
- **Contradictions** between pages.
- **Orphans** — pages with no inbound links.
- **Stale claims** — git `log -p` on the raw source shows it was updated after the summary's `ingested:` date.
- **Missing entities** — concepts mentioned in prose but without their own page.
- **Empty/TODO sections.**
### Lint — «проверь вики»
Report as a punch list. Don't delete anything automatically.
Append one line to `log.md` summarizing the findings.
Ищи:
- **Противоречия** между страницами.
- **Сирот** — страницы без входящих ссылок: `mcp__mappa__graph_backlinks(id)`
(id из `wiki_get`) → нет входящих рёбер = сирота (подробнее — using-wiki-graph).
- **Stale-claims** — `updated_at` страницы старше источника, который она резюмирует.
- **Потерянные сущности** — понятия из текста без своей страницы
(`entity_search` по имени → пусто).
- **Пустые/TODO-секции.**
## File formats (MANDATORY)
Отчёт — панч-лист. Ничего не удаляй автоматически.
Допиши строку в `log` с итогом.
### Page frontmatter
## Форматы страниц (ОБЯЗАТЕЛЬНО)
### Frontmatter
```yaml
---
title: Человекочитаемое имя
type: entity | concept | package | source | contradiction | open-question | overview
tags: [short, tokens]
sources: [../sources/foo.md, ../sources/bar.md]
updated: 2026-04-21
sources: [concepts/mappa.md]
updated: 2026-08-24
---
```
Source pages also carry `ingested: YYYY-MM-DD` and `raw_path: ../raw/...`.
Страницы `sources/` дополнительно несут `ingested: YYYY-MM-DD` и `raw_path: `.
`contradictions/``status: open | resolved | accepted-divergence` и `affects:`.
`open-questions/``status: open | answered | obsolete` и `touches:`.
Contradiction pages also carry `status: open | resolved | accepted-divergence` and `affects: [../entities/x.md, ../concepts/y.md]`.
### Слаги
Open-question pages also carry `status: open | answered | obsolete` and `touches: [../entities/x.md, ../sources/z.md]`.
- `kebab-case`, **только латиница**. Кириллицу/др. скрипты транслитерируй
(`план переписывания``ozon-client-rewrite`). Оригинальный title — в H1 и frontmatter.
- `entities/<name>`, `concepts/<name>`, `packages/<name>`, `sources/<slug>`,
`contradictions/<slug>`, `open-questions/<slug>`.
### File naming
### `log` — append-only, grep-parseable
- `kebab-case.md`, **Latin only**. Transliterate Cyrillic / other scripts in filenames (`план переписывания``ozon-client-rewrite.md`). Keep the original title in the H1 and frontmatter.
- `entities/<name>.md`, `concepts/<name>.md`, `packages/<name>.md` (no `@org/` prefix), `sources/<slug>.md`, `contradictions/<slug>.md`, `open-questions/<slug>.md`.
### `log.md` — append-only, grep-parseable
Every entry **must** start with:
Каждая запись **обязана** начинаться с:
```
## [YYYY-MM-DD] <operation> | <short description>
```
Operations: `ingest`, `query`, `lint`, `refactor`, `decision`, `init`.
Операции: `ingest`, `query`, `lint`, `refactor`, `decision`, `init`.
Парсится: `entity_search(q="## [", type="wiki", project=…)` по сущности `log`.
Parseable with: `grep "^## \[" .wiki/log.md | tail -20`.
### `index`
### `index.md`
Catalog, not narrative. One line per page: `- [Title](path) — hook.` Sections by type (entities / concepts / packages / sources / contradictions / open-questions). Update on every ingest.
### Cross-references
- Wiki → wiki: relative markdown links, `[Name](../entities/x.md)`.
- Wiki → code: relative path from repo root: `[foo.js](../../packages/api/foo.js)`.
- Wiki → raw: `../raw/<file>`.
- URL-encode spaces in paths (`%20`) and Cyrillic when needed.
Каталог, не нарратив. Одна строка на страницу: `- [Title](concepts/foo.md) — hook.`
Секции по типам. Обновляется на каждом ingest.
## Quick reference
| Situation | Files touched |
| Ситуация | Что трогаем |
|---|---|
| Ingest one doc | `sources/<slug>.md` (new) + 315 entity/concept/package pages + `index.md` + `log.md` |
| Query | (read only) + optionally new wiki page + `log.md` |
| Lint | (read only) + `log.md` |
| Bootstrap / migrate to canon | (delegated to `setup-wiki`) |
| Ingest одного документа | `sources/<slug>` (новая) + 315 entities/concepts/packages + `index` + `log` |
| Query | (чтение) + возможно новая страница + `log` |
| Lint | (чтение) + `log` |
| Новая вики проекта | первый ingest создаёт `CLAUDE`/`index`/`log` + контент |
## Common mistakes
## Частые ошибки
- **Editing `raw/`.** Don't. Only allowed: status blockquote when user explicitly asks.
- **Dumping raw content into `sources/`.** Summaries are summaries. Link to raw, don't copy it.
- **Silent overwrites.** When a new source contradicts an existing page, flag it with a `> **Противоречие:**` block; don't just overwrite.
- **Narrative `log.md`.** `Today I added…` is wrong. Use `## [YYYY-MM-DD] ingest | <what>`.
- **Non-ASCII file names.** Breaks greppability and cross-platform. Transliterate.
- **Forgetting `index.md`.** Pages not listed there are effectively invisible for future queries.
- **Skipping contradictions in lint.** The wiki's value grows from surfaced tensions, not from false consensus.
- **Improvising layout when canon files are missing.** If the wiki is missing or partial, hand off to `setup-wiki` instead of patching ad hoc.
- **Правка `sources/`.** Нельзя. Только статус-блок по явной просьбе.
- **Дамп сырья в `sources/`.** Резюме — это резюме. Ссылайся на raw, не копируй.
- **Молчаливые перезаписи.** Новый источник противоречит странице — пометь
блоком `> **Противоречие:**`; не затирай.
- **Нарративный `log`.** «Сегодня я добавил…» — неверно. Формат:
`## [YYYY-MM-DD] ingest | <что>`.
- **Не-ASCII слаги.** Ломают grep и кросс-платформенность. Транслитерируй.
- **Забытый `index`.** Страницы без записи в каталоге невидимы для будущих query.
- **Пропущенные противоречия в lint.** Ценность вики — в вскрытых напряжениях,
а не в ложном консенсусе.
- **Запись без лиза.** Wiki-мутации без `claim_token` → 422 busy; не пытайся
писать «напрямую».
- **Держать лиз на чтение/раздумья.** Лиз — на время записи. Чтение — карв-аут.
## When NOT to use this skill
## Когда НЕ использовать этот скил
- Project has CLAUDE.md / AGENTS.md docs but no `.wiki/`that's regular project documentation, not an LLM Wiki.
- User wants a single-file README or ADR — this skill is for persistent interlinked knowledge bases.
- One-off questions about code — use regular file reading, not wiki workflow.
- Проект без вики в mappa (нет сущностей `type=wiki`)обычная документация,
не LLM Wiki.
- Пользователь хочет однофайловый README/ADR — скил для персистентной
связной базы знаний.
- Разовые вопросы по коду — обычное чтение файлов, не вики-воркфлоу.
- Реляционные/структурные вопросы о вики (связи, сироты, пути) — это
**using-wiki-graph** (`mcp__mappa__graph_*`).