# Карта-набросок в пикере — план реализации

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** пятая вкладка «Карта» в браузере спрайтов (`tools/sprite-index/browser.html`): человек набрасывает карту будущего офиса грубыми мазками (земли, здание, комнаты, точки, спрайты из пикера с подписями), страница рисует набросок спрайтами каталога и отдаёт машиночитаемый план-YAML для агента, который строит по нему настоящий офис.

**Architecture:** чистая модель документа — `map-model.mjs` (объекты-не-растр, сетка земель, автотайл по правилам каталога, YAML наружу/внутрь) без DOM, тестируется `node --test`; вкладка целиком в модуле `map-editor.js` (DOM, холст, инструменты), который страница грузит ES-модулем и зовёт через `window.mapEditor`. Кадры стен/дверей и словарь видов `sketchKinds` выводит `build-catalog.ts` из каталога готовыми — страница логику `renderMap` не повторяет. Хранение планов — `plans/<имя>.yaml` через три роута в `serve.py`.

**Tech Stack:** Node 24 (`node --test`, ESM `.mjs`), браузерный JS (canvas 2D), Python 3 (`http.server`). Новых зависимостей нет.

**Спека:** `docs/superpowers/specs/2026-11-21-map-sketch-design.md` (правки по ревью внесены, коммит 57ac369). Ссылки «спека N» ведут в неё; «спека улицы N» — в `docs/superpowers/specs/2026-10-21-street-design.md` (autotile земель).

## Global Constraints

- Работа в ворктри `.claude/worktrees/map-sketch`, ветка `feat/map-sketch`. Команды — от корня ворктри, тесты модели — из `tools/sprite-index`.
- `node --test test_map_model.mjs` — из `tools/sprite-index`, зелёный после каждой задачи модели; в `pnpm gate` не входит (как python-тесты пикера, запускаются вручную).
- Ворктри без ассетов LimeZu (`assets/` вне git): `node build-catalog.ts` работает (каталог в git), `python3 -I build-index.py` и живая страница — только в основном каталоге владельца, в ворктри не проверяются. Визуальная приёмка — раздел «Ручная приёмка» в конце плана, руками владельца.
- `pnpm gate` не затрагивается: пикер вне монорепо-пакетов, но финальный прогон (задача 13) — по привычке зелёным, вдруг задели общее.
- Комментарии — на русском, с пометками `спека N` в стиле соседнего кода. Кириллические комментарии в правимых файлах сохраняются.
- Коммиты — conventional на русском (`feat: …`, `docs: …`), без emoji и без какой-либо атрибуции ИИ (правило пользователя: никогда Co-Authored-By).
- Новых зависимостей нет; модель и модуль вкладки — самодостаточные ESM без импортов из `packages/` (страница не запускает TS).
- Верхний уровень `map-editor.js` — только объявления: `await import('./map-editor.js')` в Node без DOM не падает (это проверка задач 8–12), DOM-код срабатывает из `init`.
- Формат плана-YAML и правила кавычек — дословно из спеки 5: `note` в двойных кавычках, внутренние `"` удваиваются.
- Имя наброска — `[a-z0-9-]+`, размер до 150×100 (лимит валидатора хостинга), по умолчанию 48×35 (как участок local).

## Карта файлов

Новые:

- `tools/sprite-index/map-model.mjs` — чистая модель: документ, сетка земель, автотайл, YAML наружу/внутрь (задачи 1–4).
- `tools/sprite-index/test_map_model.mjs` — тесты модели, `node --test` (задачи 1–4).
- `tools/sprite-index/map-editor.js` — вкладка «Карта»: DOM, холст, отрисовка, инструменты, хранение (задачи 8–12).
- `tools/sprite-index/plans/` — каталог планов на диске, в `.gitignore` (задача 6).

Правимые:

- `tools/sprite-index/build-catalog.ts` — `terrains`/`floors`/`wallStyles`/`sketchKinds` в `catalog.json`, entry для дверей-предметов (задача 5).
- `tools/sprite-index/serve.py` — `GET /plans`, `POST /plan`, `POST /plan/delete`, Content-Type `.mjs` (задача 6).
- `tools/sprite-index/build-index.py` — лист `ext_vehicles` в `SHEETS` (задача 7).
- `tools/sprite-index/browser.html` — вкладка, кнопки «На карту →», вызов `mapEditor.init`, `<script type="module">` (задача 9).
- `tools/sprite-index/README.md` — вкладка «Карта», планы, пересборка (задача 13).
- `.gitignore` — `tools/sprite-index/plans/` (задача 6).

Не меняются: `packages/**` (модель карты — своя, без `@pixeloffice/core`), `catalog/limezu/catalog.yaml` (словарь видов живёт в `build-catalog.ts`, спека 3), `tools/office-grid.ts` (сетку рисует модуль так же, не импортирует).

---

## Задача 1: Модель — документ и сетка земель

**Files:**
- Create: `tools/sprite-index/map-model.mjs`
- Test: `tools/sprite-index/test_map_model.mjs`

**Interfaces:**
- Consumes: ничего (модуль без зависимостей).
- Produces (используют задачи 2–4, 8–12):
  - `createDoc(name: string, w: number, h: number): { name, size: [w, h], objects: [] }` — пустой документ;
  - типы объектов: `{ t: 'rect', kind, rect: [x, y, w, h], note? }`, `{ t: 'point', kind, at: [x, y], note? }`, `{ t: 'sprite', parts: { sheet, rect, at, sortY? }[], at: [x, y], note }`;
  - `terrainGrid(doc, kinds): { w, h, types: string[] }` — по клетке id типа земли или `'building'`; `kinds` — словарь видов `{ id: { name, group, tool, render } }` (формат `sketchKinds` из задачи 5, `render` — `{ terrain }` | `{ building }` | `{ wall }` | `{ floor }` | … ). Вне прямоугольников — `'grass'`.

- [ ] **Step 1: написать failing-тесты**

Создать `tools/sprite-index/test_map_model.mjs`:

```js
// Тесты чистой модели карты-наброска (спека 4): node --test test_map_model.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createDoc, terrainGrid } from './map-model.mjs';

// мини-словарь видов — как sketchKinds из catalog.json, только виды для тестов
export const KINDS = {
  grass: { name: 'Газон', group: 'Земля', tool: 'rect', render: { terrain: 'grass' } },
  sidewalk: { name: 'Тротуар', group: 'Земля', tool: 'rect', render: { terrain: 'sidewalk' } },
  road: { name: 'Дорога', group: 'Земля', tool: 'rect', render: { terrain: 'road' } },
  building: { name: 'Здание', group: 'Здание', tool: 'rect', render: { building: {} } },
  entrance: { name: 'Вход', group: 'Здание', tool: 'point', render: { entrance: {} } },
  meeting: { name: 'Переговорка', group: 'Комнаты', tool: 'rect', render: { floor: 'tiles_blue' } },
  wall: { name: 'Стена', group: 'Стены/двери', tool: 'rect', render: { wall: {} } },
  lamp: { name: 'Фонарь', group: 'Улица', tool: 'point', render: { item: 'lamp' } },
  other: { name: 'Другое…', group: 'Другое', tool: 'rect', render: { custom: true } },
};

test('createDoc — пустой документ', () => {
  assert.deepEqual(createDoc('my-office', 48, 35), { name: 'my-office', size: [48, 35], objects: [] });
});

test('terrainGrid — пустая карта залита газоном', () => {
  const g = terrainGrid(createDoc('x', 3, 2), KINDS);
  assert.equal(g.w, 3);
  assert.equal(g.types.length, 6);
  assert.ok(g.types.every(t => t === 'grass'));
});

test('terrainGrid — прямоугольник земли; поздний в списке ложится поверх', () => {
  const doc = createDoc('x', 6, 4);
  doc.objects.push({ t: 'rect', kind: 'sidewalk', rect: [1, 1, 3, 2] });
  doc.objects.push({ t: 'rect', kind: 'grass', rect: [2, 1, 1, 1] });   // позже — побеждает
  const g = terrainGrid(doc, KINDS);
  assert.equal(g.types[1 * 6 + 1], 'sidewalk');
  assert.equal(g.types[1 * 6 + 2], 'grass');        // поздний газон поверх тротуара
  assert.equal(g.types[0 * 6 + 0], 'grass');        // вне прямоугольников
});

test('terrainGrid — здание, комнаты и стены дают тип building, в сетку земель не пишутся', () => {
  const doc = createDoc('x', 8, 5);
  doc.objects.push({ t: 'rect', kind: 'sidewalk', rect: [0, 0, 8, 5] });  // вся карта тротуар
  doc.objects.push({ t: 'rect', kind: 'building', rect: [1, 1, 3, 2] });
  doc.objects.push({ t: 'rect', kind: 'meeting', rect: [5, 1, 2, 2] });
  doc.objects.push({ t: 'rect', kind: 'wall', rect: [1, 4, 2, 1] });
  const g = terrainGrid(doc, KINDS);
  assert.equal(g.types[1 * 8 + 1], 'building');
  assert.equal(g.types[1 * 8 + 5], 'building');     // комната — тоже building
  assert.equal(g.types[4 * 8 + 1], 'building');     // стена — тоже
  assert.equal(g.types[0 * 8 + 0], 'sidewalk');
});

test('terrainGrid — вид other и точки земель не меняют', () => {
  const doc = createDoc('x', 4, 3);
  doc.objects.push({ t: 'rect', kind: 'other', rect: [0, 0, 2, 2] });
  doc.objects.push({ t: 'point', kind: 'lamp', at: [3, 2] });
  const g = terrainGrid(doc, KINDS);
  assert.ok(g.types.every(t => t === 'grass'));
});

test('terrainGrid — прямоугольник за краем карты обрезается, не падает', () => {
  const doc = createDoc('x', 4, 4);
  doc.objects.push({ t: 'rect', kind: 'sidewalk', rect: [-2, -1, 5, 3] });  // вылезает за края
  const g = terrainGrid(doc, KINDS);
  assert.equal(g.types[0 * 4 + 0], 'sidewalk');
  assert.equal(g.types[2 * 4 + 3], 'grass');        // за пределами прямоугольника
});
```

- [ ] **Step 2: прогнать — упасть**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: FAIL — «Cannot find module …/map-model.mjs».

- [ ] **Step 3: написать модель (минимум для тестов)**

Создать `tools/sprite-index/map-model.mjs`:

```js
// Чистая модель карты-наброска (спека 4): документ — список объектов, не растр; без DOM и зависимостей.
// Порядок в списке — порядок наложения: итоговая земля клетки — земля последнего по списку
// прямоугольника с рендером-землёй; вне прямоугольников — газон. Прямоугольники здания, комнат
// и стен в сетку земель не пишутся — их клетки для автотайла имеют тип building (спека 6.1).

export function createDoc(name, w, h) {
  return { name, size: [w, h], objects: [] };
}

// Есть ли у вида рендер-земля / здание-комната-стена (по render из словаря видов, спека 7)
const isTerrain = r => r && r.terrain !== undefined;
const isBuilt = r => r && (r.building !== undefined || r.wall !== undefined || r.floor !== undefined);

// Сетка типов земель карты (спека 6.1): 'grass' | id земли | 'building'. kinds — словарь sketchKinds.
export function terrainGrid(doc, kinds) {
  const [w, h] = doc.size;
  const types = new Array(w * h).fill('grass');
  const busy = new Uint8Array(w * h);   // здание/комнаты/стены — тип building, поверх земель
  const each = (rect, fn) => {
    const x0 = Math.max(0, rect[0]), y0 = Math.max(0, rect[1]);
    const x1 = Math.min(w, rect[0] + rect[2]), y1 = Math.min(h, rect[1] + rect[3]);
    for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) fn(y * w + x);
  };
  for (const o of doc.objects) {
    if (o.t !== 'rect') continue;
    const r = kinds[o.kind]?.render;
    if (isBuilt(r)) each(o.rect, i => { busy[i] = 1; });
    else if (isTerrain(r)) each(o.rect, i => { types[i] = r.terrain; });
  }
  for (let i = 0; i < busy.length; i++) if (busy[i]) types[i] = 'building';
  return { w, h, types };
}
```

- [ ] **Step 4: прогнать тесты — пройти**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: PASS — 6 тестов, 0 fail.

- [ ] **Step 5: коммит**

```bash
git add tools/sprite-index/map-model.mjs tools/sprite-index/test_map_model.mjs
git commit -m "feat: модель карты-наброска — документ и сетка земель"
```

---

## Задача 2: Модель — автотайл земель

**Files:**
- Modify: `tools/sprite-index/map-model.mjs`
- Test: `tools/sprite-index/test_map_model.mjs` (новый `test`-блок)

**Interfaces:**
- Consumes: `terrainGrid` из задачи 1.
- Produces: `terrainFramesAt(grid, terrains, x, y): { sheet, rect }[]` — кадры клетки: части первого совпавшего правила автотайла (правило заменяет заливку целиком, спека 6.1) или вариант заливки по хешу клетки `(x*7 + y*13) % fill.length` (как в каталоге). `terrains` — `{ id: { fill: [{sheet, rect}], autotile?: { rules: [{ when, parts }] } } }` (формат из задачи 5). Сосед за краем карты — тип самой клетки, клетка `building` — `building` (как `terrainFrames` в `render-site.ts`).

- [ ] **Step 1: написать failing-тесты**

Добавить в `tools/sprite-index/test_map_model.mjs` (перед первым `test(`, рядом с `KINDS` — фикстура земель):

```js
// мини-каталог земель: fill-варианты и правила автотайла, как выгружает build-catalog.ts (задача 5)
export const TERRAINS = {
  grass: {
    fill: [{ sheet: 't', rect: [0, 0, 16, 16] }],
    autotile: { rules: [
      { when: { n: 'sidewalk' }, parts: [{ sheet: 't', rect: [16, 16, 16, 16] }, { sheet: 't', rect: [0, 176, 16, 16] }] },
      { when: { s: 1 }, parts: [{ sheet: 't', rect: [32, 176, 16, 16] }] },
    ] },
  },
  sidewalk: { fill: [{ sheet: 't', rect: [32, 32, 16, 16] }, { sheet: 't', rect: [48, 32, 16, 16] }] },
  road: {
    fill: [{ sheet: 't', rect: [64, 64, 16, 16] }],
    autotile: { rules: [
      { when: { n: 'sidewalk' }, parts: [{ sheet: 't', rect: [16, 32, 16, 16] }] },
      { when: { n: 'building' }, parts: [{ sheet: 't', rect: [80, 80, 16, 16] }] },
    ] },
  },
};
```

и в конец файла:

```js
import { terrainFramesAt } from './map-model.mjs';

test('terrainFramesAt — заливка без правил выбирается по хешу клетки', () => {
  const doc = createDoc('x', 4, 4);
  doc.objects.push({ t: 'rect', kind: 'sidewalk', rect: [0, 0, 4, 4] });   // тротуар — у него нет правил
  const g = terrainGrid(doc, KINDS);
  assert.deepEqual(terrainFramesAt(g, TERRAINS, 0, 0), [{ sheet: 't', rect: [32, 32, 16, 16] }]);  // (0*7+0*13)%2=0
  assert.deepEqual(terrainFramesAt(g, TERRAINS, 0, 1), [{ sheet: 't', rect: [48, 32, 16, 16] }]);  // (0+13)%2=1
});

test('terrainFramesAt — совпавшее правило заменяет заливку, все части правила', () => {
  const doc = createDoc('x', 4, 4);
  doc.objects.push({ t: 'rect', kind: 'sidewalk', rect: [0, 0, 4, 1] });   // тротуар сверху
  const g = terrainGrid(doc, KINDS);
  // газон (1,1): сосед n — тротуар → правило кромки, обе части
  assert.deepEqual(terrainFramesAt(g, TERRAINS, 1, 1), [{ sheet: 't', rect: [16, 16, 16, 16] }, { sheet: 't', rect: [0, 176, 16, 16] }]);
});

test('terrainFramesAt — значение 1 — тот же тип, 0 — другой', () => {
  const doc = createDoc('x', 4, 4);
  doc.objects.push({ t: 'rect', kind: 'grass', rect: [1, 2, 1, 1] });      // газон под газоном
  const g = terrainGrid(doc, KINDS);
  assert.deepEqual(terrainFramesAt(g, TERRAINS, 1, 1), [{ sheet: 't', rect: [32, 176, 16, 16] }]);  // s:1 — газон снизу
});

test('terrainFramesAt — сосед building матчится по имени, за краем — тип самой клетки', () => {
  const doc = createDoc('x', 4, 4);
  doc.objects.push({ t: 'rect', kind: 'building', rect: [1, 0, 2, 1] });   // здание над дорогой
  doc.objects.push({ t: 'rect', kind: 'road', rect: [0, 1, 4, 3] });       // дорога рядами 1–3
  const g = terrainGrid(doc, KINDS);
  assert.deepEqual(terrainFramesAt(g, TERRAINS, 1, 1), [{ sheet: 't', rect: [80, 80, 16, 16] }]);  // n:building
  // дорога у нижнего края: сосед s за краем — сама клетка (road), правило n:sidewalk не подходит → заливка
  assert.deepEqual(terrainFramesAt(g, TERRAINS, 0, 3), [{ sheet: 't', rect: [64, 64, 16, 16] }]);
});
```

- [ ] **Step 2: прогнать — упасть**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: FAIL — новый импорт `terrainFramesAt` не находится (SyntaxError: The requested module does not provide an export).

- [ ] **Step 3: реализовать**

Добавить в `tools/sprite-index/map-model.mjs` (после `terrainGrid`):

```js
// Восемь соседей клетки: направление when → сдвиг (как N8 в packages/core/src/grid.ts)
const N8 = { n: [0, -1], e: [1, 0], s: [0, 1], w: [-1, 0], ne: [1, -1], se: [1, 1], sw: [-1, 1], nw: [-1, -1] };

// Кадры земли клетки (спека 6.1, как terrainFrames в render-site.ts): первое подходящее правило
// автотайла заменяет заливку — части правила покрывают клетку целиком (в правиле кромки есть и кадр
// основы). Сосед за краем карты — тип самой клетки, клетка building — 'building'. Значение when:
// 1 — тот же тип, 0 — другой, строка — имя типа.
export function terrainFramesAt(grid, terrains, x, y) {
  const type = grid.types[y * grid.w + x];
  const def = terrains[type];
  if (!def) return [];
  const typeAt = (nx, ny) => (nx < 0 || ny < 0 || nx >= grid.w || ny >= grid.h ? type : grid.types[ny * grid.w + nx]);
  const rule = (def.autotile?.rules ?? []).find(r =>
    Object.entries(r.when).every(([dir, v]) => {
      const t = typeAt(x + N8[dir][0], y + N8[dir][1]);
      return v === 1 ? t === type : v === 0 ? t !== type : t === v;
    }),
  );
  return rule ? rule.parts : [def.fill[(x * 7 + y * 13) % def.fill.length]];
}
```

- [ ] **Step 4: прогнать тесты — пройти**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: PASS — 10 тестов.

- [ ] **Step 5: коммит**

```bash
git add tools/sprite-index/map-model.mjs tools/sprite-index/test_map_model.mjs
git commit -m "feat: автотайл земель в модели карты-наброска"
```

---

## Задача 3: Модель — план-YAML наружу

**Files:**
- Modify: `tools/sprite-index/map-model.mjs`
- Test: `tools/sprite-index/test_map_model.mjs` (новый `test`-блок)

**Interfaces:**
- Consumes: документ из задачи 1, `kinds` (имена видов для легенды).
- Produces: `docToYaml(doc, kinds)` → `{ ok: true, yaml: string }` | `{ ok: false, index: number, message: string }` (спека 5: спрайт без непустой `note` — ошибка, `index` — объект в `doc.objects` для подсветки). Формат — дословно из спеки 5: секции `name`/`size`/`rects`/`points`/`sprites`/`legend`, заголовок-комментарий в две строки, `note` в двойных кавычках (`"` внутри удваивается, `\` и перевод строки экранируются — файл остаётся валидным YAML и для настоящего парсера агента), `sortY` у части спрайта — `sortY.toFixed(2)` (целые — без точки, знак минус валиден). Легенда — имя вида из словаря `kinds` как есть (имена §3 спеки с заглавной; регистр в примере §5 не нормирован). Используют задачи 4 (круг туда-обратно), 12 (экспорт).

- [ ] **Step 1: написать failing-тесты**

Добавить в конец `tools/sprite-index/test_map_model.mjs`:

```js
import { docToYaml } from './map-model.mjs';

const DOC = {
  name: 'my-office', size: [48, 35],
  objects: [
    { t: 'rect', kind: 'road', rect: [24, 18, 24, 4], note: 'дорога вдоль восточной стороны' },
    { t: 'rect', kind: 'building', rect: [7, 1, 24, 18], note: 'главное здание' },
    { t: 'rect', kind: 'meeting', rect: [16, 8, 4, 3] },
    { t: 'point', kind: 'entrance', at: [12, 18], note: 'вход с юга' },
    { t: 'point', kind: 'lamp', at: [4, 10] },
    { t: 'sprite', note: 'фонтан, он же "главный" аттракцион', at: [3, 11],
      parts: [{ sheet: 'ext_city', rect: [32, 64, 32, 48], at: [0, 0], sortY: 3 }] },
  ],
};

test('docToYaml — формат спеки 5: секции, легенда использованных, note в кавычках', () => {
  const r = docToYaml(DOC, KINDS);
  assert.ok(r.ok);
  assert.equal(r.yaml, [
    '# Набросок карты PixelOffice для агента. Это не office.yaml: размеры в клетках 16 px,',
    '# [0, 0] — левый верхний угол; офис по каталогу и спекам строит агент (validate:maps).',
    'name: my-office',
    'size: [48, 35]',
    'rects:',
    '  - { kind: road, rect: [24, 18, 24, 4], note: "дорога вдоль восточной стороны" }',
    '  - { kind: building, rect: [7, 1, 24, 18], note: "главное здание" }',
    '  - { kind: meeting, rect: [16, 8, 4, 3] }',
    'points:',
    '  - { kind: entrance, at: [12, 18], note: "вход с юга" }',
    '  - { kind: lamp, at: [4, 10] }',
    'sprites:',
    '  - { note: "фонтан, он же ""главный"" аттракцион", at: [3, 11], parts: [ { sheet: ext_city, rect: [32, 64, 32, 48], at: [0, 0], sortY: 3 } ] }',
    'legend:                  # для агента: русские имена использованных видов',
    '  road: Дорога',
    '  building: Здание',
    '  meeting: Переговорка',
    '  entrance: Вход',
    '  lamp: Фонарь',
    '',
  ].join('\n'));
});
```

(в строке спрайта кавычки внутри `note` удвоены — так проверяется правило кавычек спеки 5; пустая `note` у переговорки не пишется; легенда — имя вида из словаря как есть, с заглавной, как в §3 спеки.)

Дальнейшие тесты:

```js
test('docToYaml — пустая note не пишется, легенда в порядке первого использования', () => {
  const r = docToYaml({ name: 'x', size: [10, 10], objects: [
    { t: 'rect', kind: 'meeting', rect: [1, 1, 2, 2], note: '' },
    { t: 'rect', kind: 'road', rect: [0, 5, 10, 2] },
  ] }, KINDS);
  assert.ok(r.ok);
  assert.ok(!r.yaml.includes('note: ""'));
  assert.ok(r.yaml.indexOf('meeting:') < r.yaml.indexOf('road:'));   // легенда по порядку появления
});

test('docToYaml — спрайт без note не проходит молча: объект для подсветки', () => {
  const doc = { name: 'x', size: [10, 10], objects: [
    { t: 'point', kind: 'lamp', at: [1, 1] },
    { t: 'sprite', note: '', at: [2, 2], parts: [{ sheet: 's', rect: [0, 0, 16, 16], at: [0, 0] }] },
    { t: 'sprite', note: '   ', at: [3, 3], parts: [{ sheet: 's', rect: [0, 0, 16, 16], at: [0, 0] }] },
  ] };
  const r = docToYaml(doc, KINDS);
  assert.ok(!r.ok);
  assert.equal(r.index, 1);   // первый без подписи
});

test('docToYaml — sortY дробный округляется до двух знаков', () => {
  const r = docToYaml({ name: 'x', size: [10, 10], objects: [
    { t: 'sprite', note: 'а', at: [0, 0], parts: [{ sheet: 's', rect: [0, 0, 16, 16], at: [0, 0], sortY: 2.34567 }] },
  ] }, KINDS);
  assert.ok(r.ok);
  assert.ok(r.yaml.includes('sortY: 2.35'));
});
```

- [ ] **Step 2: прогнать — упасть**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: FAIL — `docToYaml` не экспортируется.

- [ ] **Step 3: реализовать**

Добавить в `tools/sprite-index/map-model.mjs`:

```js
// Строка YAML в двойных кавычках: внутренние " удваиваются, \ и перевод строки экранируются — запятая или }
// в подписи не ломают flow-строку, а файл остаётся валидным YAML и для настоящего парсера агента (спека 5)
const quote = s => '"' + String(s).replaceAll('\\', '\\\\').replaceAll('"', '""').replaceAll('\n', '\\n') + '"';

// Число как в YAML: целые без точки, дробные — два знака, знак минус валиден
const num = n => Number.isInteger(n) ? String(n) : n.toFixed(2);

// План-YAML для агента (спека 5): самодостаточный, словарь использованных видов приложен легендой
// с русскими именами. Спрайт без непустой note — ошибка с индексом объекта (страница подсветит его).
export function docToYaml(doc, kinds) {
  const bad = doc.objects.findIndex(o => o.t === 'sprite' && !(o.note ?? '').trim());
  if (bad >= 0) return { ok: false, index: bad, message: 'спрайту нужна подпись (note) — без неё агент не поймёт, что это' };
  const line = (fields) => '  - { ' + fields.join(', ') + ' }';
  const rects = doc.objects.filter(o => o.t === 'rect').map(o =>
    line([`kind: ${o.kind}`, `rect: [${o.rect.join(', ')}]`, ...(o.note?.trim() ? [`note: ${quote(o.note)}`] : [])]));
  const points = doc.objects.filter(o => o.t === 'point').map(o =>
    line([`kind: ${o.kind}`, `at: [${o.at.join(', ')}]`, ...(o.note?.trim() ? [`note: ${quote(o.note)}`] : [])]));
  const sprites = doc.objects.filter(o => o.t === 'sprite').map(o => line([
    `note: ${quote(o.note)}`,
    `at: [${o.at.join(', ')}]`,
    'parts: [ ' + o.parts.map(p =>
      `{ sheet: ${p.sheet}, rect: [${p.rect.join(', ')}], at: [${p.at.join(', ')}]${p.sortY !== undefined ? `, sortY: ${num(p.sortY)}` : ''} }`,
    ).join(', ') + ' ]',
  ]));
  const legend = [...new Set(doc.objects.filter(o => o.t !== 'sprite').map(o => o.kind))];
  const yaml = [
    '# Набросок карты PixelOffice для агента. Это не office.yaml: размеры в клетках 16 px,',
    '# [0, 0] — левый верхний угол; офис по каталогу и спекам строит агент (validate:maps).',
    `name: ${doc.name}`,
    `size: [${doc.size.join(', ')}]`,
    ...(rects.length ? ['rects:', ...rects] : []),
    ...(points.length ? ['points:', ...points] : []),
    ...(sprites.length ? ['sprites:', ...sprites] : []),
    ...(legend.length ? ['legend:                  # для агента: русские имена использованных видов',
      ...legend.map(k => `  ${k}: ${kinds[k]?.name ?? k}`)] : []),
    '',
  ].join('\n');
  return { ok: true, yaml };
}
```

- [ ] **Step 4: прогнать тесты — пройти**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: PASS — 14 тестов. Если строка спрайта не сошлась знак в знак — сверить пробелы с образцом спеки 5 (после `parts: [ ` и перед ` ]`).

- [ ] **Step 5: коммит**

```bash
git add tools/sprite-index/map-model.mjs tools/sprite-index/test_map_model.mjs
git commit -m "feat: экспорт плана-YAML из модели карты-наброска"
```

---

## Задача 4: Модель — чтение плана-YAML внутрь

**Files:**
- Modify: `tools/sprite-index/map-model.mjs`
- Test: `tools/sprite-index/test_map_model.mjs` (новые `test`-блоки)

**Interfaces:**
- Consumes: `docToYaml` из задачи 3 (круг туда-обратно).
- Produces: `yamlToDoc(text)` → `{ ok: true, doc }` | `{ ok: false, line: number, error: string }` — свой мини-парсер только наших конструкций (спека 9): секции `name`/`size`/`rects`/`points`/`sprites`, flow-строки `{ k: v }`, значения в двойных кавычках читаются как есть, `legend` и комментарии пропускаются, общий YAML не парсится. Непонятная строка — честная ошибка с номером, без молчаливой потери. Использует задача 12 (открытие плана).

- [ ] **Step 1: написать failing-тесты**

Добавить в конец `tools/sprite-index/test_map_model.mjs`:

```js
import { yamlToDoc } from './map-model.mjs';

test('yamlToDoc — круг туда-обратно: вторая выгрузка байт в байт равна первой', () => {
  const first = docToYaml(DOC, KINDS);
  const back = yamlToDoc(first.yaml);
  assert.ok(back.ok);
  const second = docToYaml(back.doc, KINDS);
  assert.ok(second.ok);
  assert.equal(second.yaml, first.yaml);
});

test('yamlToDoc — комментарии и legend пропускаются, note без кавычек-внутри читается как есть', () => {
  const text = [
    '# шапка для агента',
    'name: my-office',
    'size: [20, 12]      # размер в клетках',
    'rects:',
    '  - { kind: road, rect: [1, 2, 3, 4], note: "запятая, скобка } и # решётка" }',
    'legend:                  # читателю не нужна',
    '  road: дорога',
    'points:',
    '  - { kind: lamp, at: [5, 6] }',
    '',
  ].join('\n');
  const r = yamlToDoc(text);
  assert.ok(r.ok);
  assert.equal(r.doc.name, 'my-office');
  assert.deepEqual(r.doc.size, [20, 12]);
  assert.deepEqual(r.doc.objects, [
    { t: 'rect', kind: 'road', rect: [1, 2, 3, 4], note: 'запятая, скобка } и # решётка' },
    { t: 'point', kind: 'lamp', at: [5, 6] },
  ]);
});

test('yamlToDoc — кавычки внутри note (удвоенные) читаются как одна', () => {
  const r = yamlToDoc('name: x\nsize: [2, 2]\nsprites:\n  - { note: "машинка ""жук""", at: [0, 0], parts: [ { sheet: s, rect: [0, 0, 16, 16], at: [0, 0] } ] }\n');
  assert.ok(r.ok);
  assert.equal(r.doc.objects[0].note, 'машинка "жук"');
  assert.equal(r.doc.objects[0].parts[0].sheet, 's');
});

test('yamlToDoc — чужой/правленный руками файл — честная ошибка с номером строки', () => {
  const bad = yamlToDoc('name: x\nsize: [2, 2]\nrects:\n  - { kind: road, rect: [1, 2, 3] }\n');   // rect из трёх чисел
  assert.ok(!bad.ok);
  assert.equal(bad.line, 4);
  const unknown = yamlToDoc('name: x\nsize: [2, 2]\nfoo: bar\n');
  assert.ok(!unknown.ok);
  assert.equal(unknown.line, 3);
});

test('yamlToDoc — name и size проверяются: имя [a-z0-9-]+, размер до 150×100', () => {
  assert.ok(!yamlToDoc('name: Мой Офис\nsize: [2, 2]\n').ok);
  assert.ok(!yamlToDoc('name: x\nsize: [200, 2]\n').ok);
  assert.ok(yamlToDoc('name: my-office-1\nsize: [150, 100]\n').ok);
});

test('yamlToDoc — круг с дробным и отрицательным sortY части спрайта', () => {
  const doc = { name: 'x', size: [10, 10], objects: [
    { t: 'sprite', note: 'а', at: [0, 0], parts: [
      { sheet: 's', rect: [0, 0, 16, 16], at: [0, 0], sortY: 2.35 },
      { sheet: 's', rect: [0, 32, 16, 16], at: [0, 2], sortY: -0.5 },
    ] },
  ] };
  const first = docToYaml(doc, KINDS);
  assert.ok(first.ok);
  assert.ok(first.yaml.includes('sortY: 2.35') && first.yaml.includes('sortY: -0.50'));
  const back = yamlToDoc(first.yaml);
  assert.ok(back.ok);
  assert.equal(back.doc.objects[0].parts[0].sortY, 2.35);
  assert.equal(back.doc.objects[0].parts[1].sortY, -0.5);
  const second = docToYaml(back.doc, KINDS);
  assert.ok(second.ok);
  assert.equal(second.yaml, first.yaml);
});

test('yamlToDoc — круг: бэкслеш и перевод строки в note экранируются', () => {
  const doc = { name: 'x', size: [10, 10], objects: [
    { t: 'point', kind: 'lamp', at: [1, 2], note: 'путь C:\\temp и\nещё строка' },
  ] };
  const first = docToYaml(doc, KINDS);
  assert.ok(first.ok);
  const back = yamlToDoc(first.yaml);
  assert.ok(back.ok);
  assert.equal(back.doc.objects[0].note, 'путь C:\\temp и\nещё строка');
  const second = docToYaml(back.doc, KINDS);
  assert.ok(second.ok);
  assert.equal(second.yaml, first.yaml);   // файл читается и пишется повторно байт в байт
});

test('yamlToDoc — неизвестное поле элемента — честная ошибка, без молчаливой потери', () => {
  const r = yamlToDoc('name: x\nsize: [2, 2]\nrects:\n  - { kind: road, rect: [1, 2, 3, 4], meta: 1 }\n');
  assert.ok(!r.ok);
  assert.equal(r.line, 4);
});
```

- [ ] **Step 2: прогнать — упасть**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: FAIL — `yamlToDoc` не экспортируется.

- [ ] **Step 3: реализовать**

Добавить в `tools/sprite-index/map-model.mjs`:

```js
// — чтение плана-YAML назад (спека 9): мини-парсер только наших конструкций. Файлы пишем сами,
// формат подконтролен; правленный руками файл, который не разобрался, — честная ошибка, без потерь.

// Отрезать комментарий: # вне двойных кавычек, в начале строки или после пробела
function stripComment(line) {
  let q = false;
  for (let i = 0; i < line.length; i++) {
    const c = line[i];
    if (c === '"') q = !q;
    else if (c === '#' && !q && (i === 0 || line[i - 1] === ' ' || line[i - 1] === '\t')) return line.slice(0, i);
  }
  return line;
}

// Разбить строку по разделителю верхнего уровня (запятая/двоеточие), не заходя в кавычки и вложенные [] {}
function splitTop(s, sep) {
  const out = [];
  let depth = 0, q = false, cur = '';
  for (const c of s) {
    if (c === '"') { q = !q; cur += c; }
    else if (!q && (c === '[' || c === '{')) { depth++; cur += c; }
    else if (!q && (c === ']' || c === '}')) { depth--; cur += c; }
    else if (!q && depth === 0 && c === sep) { out.push(cur); cur = ''; }
    else cur += c;
  }
  out.push(cur);
  return out.map(x => x.trim());
}

// Значение: "строка" (эскейпы экспорта: удвоенные " — одна, \\ — \, \n — перевод), число, [список], { ключ: значение }
function parseValue(s) {
  if (s.startsWith('"')) {
    // однопроходный разбор, чтобы \\n не превратился в перевод: пары \\ и \n — эскейпы, прочее — как есть (спека 9)
    let out = '';
    for (let i = 1; i < s.length - 1; i++) {
      if (s[i] === '\\' && s[i + 1] === '\\') { out += '\\'; i++; }
      else if (s[i] === '\\' && s[i + 1] === 'n') { out += '\n'; i++; }
      else if (s[i] === '"') { out += '"'; if (s[i + 1] === '"') i++; }
      else out += s[i];
    }
    return out;
  }
  if (s.startsWith('[')) return splitTop(s.slice(1, -1), ',').filter(x => x).map(parseValue);
  if (s.startsWith('{')) {
    const obj = {};
    for (const pair of splitTop(s.slice(1, -1), ',')) {
      if (!pair) continue;
      const i = pair.indexOf(':');
      if (i < 0) throw new Error('не поняла пару «' + pair + '»');
      obj[pair.slice(0, i).trim()] = parseValue(pair.slice(i + 1).trim());
    }
    return obj;
  }
  if (/^[+-]?\d+$/.test(s)) return parseInt(s, 10);
  if (/^[+-]?\d+\.\d+$/.test(s)) return parseFloat(s);   // дробный sortY (задача 9: bToMap пишет toFixed(2))
  return s;   // id вида, имя листа
}

const NAME_RE = /^[a-z0-9-]+$/;

// Прочитать план-YAML в документ. Секции name/size/rects/points/sprites; legend пропускается.
export function yamlToDoc(text) {
  const doc = { name: '', size: [0, 0], objects: [] };
  let section = null;   // 'rects' | 'points' | 'sprites' | 'legend' | null
  const lines = text.split('\n');
  for (let n = 0; n < lines.length; n++) {
    const raw = stripComment(lines[n]);
    // строки легенды (с отступом, «  road: дорога») — читателю не нужны, пропускаем до следующей секции
    if (section === 'legend' && /^\s+\S+\s*:/.test(raw)) continue;
    const line = raw.trim();
    if (!line) continue;
    const bad = msg => ({ ok: false, line: n + 1, error: msg });
    const item = line.match(/^- \{(.*)\}$/);
    if (item) {
      if (section !== 'rects' && section !== 'points' && section !== 'sprites') return bad('элемент списка вне секции rects/points/sprites');
      let v;
      try { v = parseValue('{' + item[1] + '}'); } catch { return bad('не разобралась flow-строка'); }
      const err = (m, f) => bad(`у элемента секции ${section} поле ${f}: ${m}`);
      // неизвестное поле элемента — честная ошибка, без молчаливой потери данных (спека 9)
      const keys = { rects: ['kind', 'rect', 'note'], points: ['kind', 'at', 'note'], sprites: ['note', 'at', 'parts'] }[section];
      for (const k of Object.keys(v)) if (!keys.includes(k)) return bad('неизвестное поле «' + k + '» у элемента секции ' + section);
      if (section === 'sprites') {
        if (typeof v.note !== 'string' || !Array.isArray(v.at) || !Array.isArray(v.parts)) return bad('у спрайта нужны note, at и parts');
        if (v.at.length !== 2 || v.at.some(x => !Number.isInteger(x))) return err('пара чисел', 'at');
        for (const p of v.parts)
          if (typeof p.sheet !== 'string' || !Array.isArray(p.rect) || p.rect.length !== 4 || p.rect.some(x => !Number.isInteger(x)) || !Array.isArray(p.at) || p.at.length !== 2)
            return err('нужны sheet, rect [4 числа], at [2 числа]', 'parts');
        doc.objects.push({ t: 'sprite', note: v.note, at: v.at, parts: v.parts });
      } else {
        if (typeof v.kind !== 'string') return err('строка', 'kind');
        if (section === 'rects' && (!Array.isArray(v.rect) || v.rect.length !== 4 || v.rect.some(x => !Number.isInteger(x)))) return err('4 числа', 'rect');
        if (section === 'points' && (!Array.isArray(v.at) || v.at.length !== 2 || v.at.some(x => !Number.isInteger(x)))) return err('пара чисел', 'at');
        const o = { t: section === 'rects' ? 'rect' : 'point', kind: v.kind };
        o[section === 'rects' ? 'rect' : 'at'] = v.rect ?? v.at;
        if (typeof v.note === 'string' && v.note) o.note = v.note;
        doc.objects.push(o);
      }
      continue;
    }
    const head = line.match(/^([a-z]+):\s*(.*)$/);
    if (!head) return bad('строка не по формату плана (секции name/size/rects/points/sprites)');
    const [, key, rest] = head;
    if (key === 'name') {
      if (!NAME_RE.test(rest)) return bad('имя — строчные латиница/цифры/дефис');
      doc.name = rest;
    } else if (key === 'size') {
      const v = parseValue(rest);
      if (!Array.isArray(v) || v.length !== 2 || v.some(x => !Number.isInteger(x)) || v[0] < 1 || v[1] < 1 || v[0] > 150 || v[1] > 100)
        return bad('размер — пара чисел до 150×100');
      doc.size = v;
    } else if (key === 'rects' || key === 'points' || key === 'sprites' || key === 'legend') section = key;
    else return bad('неизвестная секция «' + key + '»');
  }
  if (!doc.name) return { ok: false, line: 1, error: 'нет name' };
  return { ok: true, doc };
}
```

- [ ] **Step 4: прогнать тесты — пройти**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: PASS — 22 теста. Если круг не сошёлся — сравнить строку спрайта: парсер не должен терять `sortY` части и пустую `note` не создавать.

- [ ] **Step 5: коммит**

```bash
git add tools/sprite-index/map-model.mjs tools/sprite-index/test_map_model.mjs
git commit -m "feat: чтение плана-YAML в модель карты-наброска"
```

---

## Задача 5: build-catalog.ts — terrains, floors, wallStyles, sketchKinds

**Files:**
- Modify: `tools/sprite-index/build-catalog.ts`

**Interfaces:**
- Consumes: `loadCatalog` из `packages/core/src/catalog.ts` (уже импортирован), правила автотайла `wall` (грани здания, спека карты-наброска 6.3), `wallStyles` стиля `office` (лица от `base`), поле `door` каталога (кадр входной двери).
- Produces — новые поля `catalog.json` (существующие поля и записи не меняются: `entries` дополняется двумя новыми записями дверей — Step 2, они же становятся карточками вкладки «Каталог»; `catalog.json` в `.gitignore`):
  - `terrains: { id: { fill: [{sheet, rect}], autotile?: { rules: [{when, parts}] } } }` — как в каталоге, без `walk`/`drive` (спека 7);
  - `floors: { id: [{sheet, rect}] }`;
  - `wallStyles: { id: { sheet, base } }`;
  - `sketchKinds: { id: { id, name, group, tool: 'rect'|'point', render } }` — словарь видов §3; `render` конкретен: `{ terrain: <id> }`, `{ decal: 'crosswalk' }`, `{ building: FRAMES }` и `{ wall: FRAMES }` (один набор кадров, см. ниже), `{ entrance: { sheet, rect } }` — первый кадр входной двери, `{ floor: <id> }`, `{ item: <id> }`, `{ custom: true }` у `other`;
  - `FRAMES = { southLeft, southMid, southRight: {sheet, rect} (лица 16×32 от base стиля `office`), side, north: {sheet, rect, at, sortY} (грани из правил стен: `side` — правило «вертикальная стена» (`when` ровно `{s:1}`, at [0,−16]), `north` — «нижняя стена» (`when` ровно `{n:0, s:1}`, at [0,0])) }`;
  - в `entries` — новый entry для дверей-предметов без частей (`storage_door`, `elevator_door`): кадр закрытой `door.open[0]` размером `door.frame` с `at`/`sortY` предмета — для вида «Дверь» и вкладки «Каталог».
- Используют: задачи 8–12 (модуль карты берёт всё из `catalog.json` при `init`).

Таблица видов (спека 3, дословно — имена и группы):

| id | name | group | tool | render |
|---|---|---|---|---|
| grass | Газон | Земля | rect | `{ terrain: grass }` |
| sidewalk | Тротуар | Земля | rect | `{ terrain: sidewalk }` |
| road | Дорога | Земля | rect | `{ terrain: road }` |
| parking | Парковка | Земля | rect | `{ terrain: parking }` |
| crosswalk | Переход | Земля | rect | `{ decal: crosswalk }` |
| building | Здание | Здание | rect | `{ building: FRAMES }` |
| entrance | Вход | Здание | point | `{ entrance: кадр }` |
| meeting | Переговорка | Комнаты | rect | `{ floor: tiles_blue }` |
| lounge | Лаунж | Комнаты | rect | `{ floor: wood }` |
| coworking | Коворкинг | Комнаты | rect | `{ floor: carpet_grey }` |
| pod | Кабинки | Комнаты | rect | `{ floor: carpet_grey }` |
| techroom | Техкомната | Комнаты | rect | `{ floor: carpet_burgundy }` |
| storage | Склад | Комнаты | rect | `{ floor: concrete }` |
| dock | Док агентов | Комнаты | rect | `{ floor: steel_plate }` |
| wall | Стена | Стены/двери | rect | `{ wall: FRAMES }` |
| door | Дверь | Стены/двери | point | `{ item: storage_door }` |
| lamp | Фонарь | Улица | point | `{ item: lamp }` |
| bus_stop | Остановка | Улица | point | `{ item: bus_stop }` |
| metro | Метро | Улица | point | `{ item: metro_entrance }` |
| tree | Дерево | Улица | point | `{ item: tree }` |
| bench | Скамейка | Улица | point | `{ item: bench }` |
| fountain | Фонтан | Улица | point | `{ item: fountain }` |
| other | Другое… | Другое | rect | `{ custom: true }` |

- [ ] **Step 1: добавить выгрузку в build-catalog.ts**

В `tools/sprite-index/build-catalog.ts` после цикла по предметам (перед `const out = {`) вставить:

```ts
// — вкладка «Карта» (спека карты-наброска 7): земли, полы, стили стен и словарь видов наброска —
// страница рисует набросок спрайтами каталога, не повторяя логику renderMap.

// Земли: как в каталоге, без walk/drive — странице не нужны
const terrains = Object.fromEntries(Object.entries(cat.terrains).map(([id, t]) => [id, {
  fill: t.fill.map(f => ({ sheet: f.sheet, rect: f.rect })),
  ...(t.rules.length ? { autotile: { rules: t.rules.map(r => ({ when: r.when, parts: r.parts.map(p => ({ sheet: p.sheet, rect: p.rect })) })) } } : {}),
}]));
const floors = Object.fromEntries(Object.entries(cat.floors).map(([id, fr]) => [id, fr.map(f => ({ sheet: f.sheet, rect: f.rect }))]));
const wallStyles = Object.fromEntries(Object.entries(cat.wallStyles).map(([id, s]) => [id, { sheet: s.sheet, base: s.base }]));

// Кадры граней здания: из правил автотайла wall. «Вертикальная стена» — when ровно {s:1},
// «нижняя стена» — when ровно {n:0, s:1}; части правил — обычные (не face), по одной.
const ts = cat.tileSize;
const auto = cat.items['wall']!.autotile!;
const plain = (when: Record<string, unknown>) => {
  const rule = auto.rules.find(r => Object.keys(r.when).length === Object.keys(when).length && Object.entries(when).every(([k, v]) => r.when[k as keyof typeof r.when] === v));
  if (!rule) throw new Error('в каталоге нет правила стен ' + JSON.stringify(when));
  const p = rule.parts.find(p => 'sheet' in p);
  if (!p) throw new Error('у правила ' + JSON.stringify(when) + ' нет обычной части');
  return { sheet: p.sheet, rect: p.rect, at: p.at, sortY: p.sortY };
};
// Здание снаружи (спека 6.3): южный ряд — лица 16×32 стиля office с углами, боковые ряды — вертикальная
// грань со сдвигом вверх на клетку, северный — грань нижнего ряда без сдвига. Отличие от renderMap, где
// лицо получает и северный ряд, сознательное: набросок показывает здание снаружи.
const style = cat.wallStyles['office']!;
const face = (fx: number) => ({ sheet: style.sheet, rect: [style.base[0] + fx, style.base[1], ts, 2 * ts] as [number, number, number, number] });
const frames = { southLeft: face(0), southMid: face(16), southRight: face(32), side: plain({ s: 1 }), north: plain({ n: 0, s: 1 }) };
// Первый кадр входной двери (поле door каталога, спека 6.3): полоса листа слева направо
const d = cat.door!;
const entrance = { sheet: d.sheet, rect: [d.open[0]! * d.frame[0], 0, d.frame[0], d.frame[1]] as [number, number, number, number] };
const K = (id: string, name: string, group: string, tool: 'rect' | 'point', render: object) => ({ id, name, group, tool, render });
const sketchKinds = Object.fromEntries([
  K('grass', 'Газон', 'Земля', 'rect', { terrain: 'grass' }),
  K('sidewalk', 'Тротуар', 'Земля', 'rect', { terrain: 'sidewalk' }),
  K('road', 'Дорога', 'Земля', 'rect', { terrain: 'road' }),
  K('parking', 'Парковка', 'Земля', 'rect', { terrain: 'parking' }),
  K('crosswalk', 'Переход', 'Земля', 'rect', { decal: 'crosswalk' }),
  K('building', 'Здание', 'Здание', 'rect', { building: frames }),
  K('entrance', 'Вход', 'Здание', 'point', { entrance }),
  K('meeting', 'Переговорка', 'Комнаты', 'rect', { floor: 'tiles_blue' }),
  K('lounge', 'Лаунж', 'Комнаты', 'rect', { floor: 'wood' }),
  K('coworking', 'Коворкинг', 'Комнаты', 'rect', { floor: 'carpet_grey' }),
  K('pod', 'Кабинки', 'Комнаты', 'rect', { floor: 'carpet_grey' }),
  K('techroom', 'Техкомната', 'Комнаты', 'rect', { floor: 'carpet_burgundy' }),
  K('storage', 'Склад', 'Комнаты', 'rect', { floor: 'concrete' }),
  K('dock', 'Док агентов', 'Комнаты', 'rect', { floor: 'steel_plate' }),
  K('wall', 'Стена', 'Стены/двери', 'rect', { wall: frames }),
  K('door', 'Дверь', 'Стены/двери', 'point', { item: 'storage_door' }),
  K('lamp', 'Фонарь', 'Улица', 'point', { item: 'lamp' }),
  K('bus_stop', 'Остановка', 'Улица', 'point', { item: 'bus_stop' }),
  K('metro', 'Метро', 'Улица', 'point', { item: 'metro_entrance' }),
  K('tree', 'Дерево', 'Улица', 'point', { item: 'tree' }),
  K('bench', 'Скамейка', 'Улица', 'point', { item: 'bench' }),
  K('fountain', 'Фонтан', 'Улица', 'point', { item: 'fountain' }),
  K('other', 'Другое…', 'Другое', 'rect', { custom: true }),
]);
```

и расширить `out`:

```ts
const out = {
  // путь — от корня репозитория, как в index.json (в каталоге пути относительны assetsDir, т.е. assets/)
  sheets: Object.fromEntries(Object.entries(cat.sheets).map(([n, p]) => [n, { path: 'assets/' + p }])),
  entries,
  terrains, floors, wallStyles, sketchKinds,
};
```

- [ ] **Step 2: entry для дверей-предметов без частей**

Сразу после цикла `for (const [item, def] of Object.entries(cat.items))` (основной сборщик entries) добавить:

```ts
// Двери-предметы без частей (storage_door, elevator_door): кадр закрытой как единственная часть —
// для вида «Дверь» наброска и карточки в «Каталоге» (спека 3: предмет storage_door, кадр закрытой)
for (const [item, def] of Object.entries(cat.items)) {
  if (!def.door || def.variants.some(v => Object.values(v).some(view => view?.parts.length))) continue;
  const dd = def.door;
  entries.push({
    id: item, item, view: 'default', variant: 0, size: def.size, about: def.about,
    parts: [{ sheet: dd.sheet, rect: [dd.open[0]! * dd.frame[0], 0, dd.frame[0], dd.frame[1]], at: dd.at, sortY: dd.sortY }],
    spots: [],
  });
}
```

- [ ] **Step 3: пересобрать и проверить ассертами**

Run:

```bash
cd tools/sprite-index && node build-catalog.ts && node -e "
const c = require('./catalog.json'); const a = require('node:assert');
a.ok(c.sketchKinds && c.terrains && c.floors && c.wallStyles);
const k = c.sketchKinds;
a.deepEqual(k.building.render.building.southMid, { sheet: 'room', rect: [16, 176, 16, 32] });
a.deepEqual(k.building.render.building.southLeft.rect, [0, 176, 16, 32]);
a.deepEqual(k.building.render.building.side, { sheet: 'room', rect: [176, 16, 16, 16], at: [0, -16], sortY: 1 });
a.deepEqual(k.wall.render.wall.north.rect, [176, 32, 16, 16]);
a.deepEqual(k.entrance.render.entrance, { sheet: 'ext_door', rect: [0, 0, 48, 32] });
a.equal(k.door.render.item, 'storage_door');
a.equal(k.crosswalk.render.decal, 'crosswalk');
a.equal(k.other.render.custom, true);
a.equal(Object.keys(k).length, 23);
a.equal(c.terrains.grass.autotile.rules.length, 12);
a.ok(!('walk' in c.terrains.grass));
a.deepEqual(c.floors.wood, [{ sheet: 'floors', rect: [16, 208, 16, 16] }]);
a.ok(c.entries.some(e => e.item === 'storage_door'));
const sd = c.entries.find(e => e.item === 'storage_door');
a.deepEqual(sd.parts[0], { sheet: 'door_wood', rect: [0, 0, 16, 32], at: [0, -16], sortY: 0.97 });
console.log('catalog.json: sketchKinds', Object.keys(k).length, 'видов; всё сошлось');
"
```

Expected: `предметов: 69, вариантов-видов: 88` (86 было + 2 двери) и `catalog.json: sketchKinds 23 видов; всё сошлось`.
Если ассерты упали на кадрах граней — сверить правило автотайла `wall` в `catalog/limezu/catalog.yaml` (строки 213–216): «нижняя стена» `{n: 0, s: 1}` → rect [176, 32, 16, 16]; «вертикальная стена» `{s: 1}` → rect [176, 16, 16, 16].

- [ ] **Step 4: тесты модели не сломались**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: PASS — 22 теста (модель от catalog.json не зависит).

- [ ] **Step 5: коммит**

```bash
git add tools/sprite-index/build-catalog.ts
git commit -m "feat: выгрузка sketchKinds и земель каталога для вкладки «Карта»"
```

(`catalog.json` в `.gitignore`, в коммит не попадает.)

---

## Задача 6: serve.py — планы и Content-Type модулей

**Files:**
- Modify: `tools/sprite-index/serve.py`
- Modify: `.gitignore:33-35` (блок браузера спрайтов)

**Interfaces:**
- Consumes: стиль существующих `/save` и `/pending` (спека 8).
- Produces (использует задача 12):
  - `GET /plans` → JSON `[{ name, mtime }]` по алфавиту имени (`mtime` — unix-время изменения файла);
  - `POST /plan` `{ name, yaml }` → пишет `tools/sprite-index/plans/<name>.yaml` (имя строго `^[a-z0-9-]+$`, иначе 400; перезапись разрешена; каталог создаётся);
  - `POST /plan/delete` `{ name }` → удаляет файл (нет файла — тоже `ok`, как несуществующая запись);
  - `Content-Type: text/javascript` для `.mjs` (на старых Python < 3.12 встроенный сервер отдаёт `.mjs` октет-стримом — ES-модуль карты не грузится);
  - каталог `tools/sprite-index/plans/` в `.gitignore`.

- [ ] **Step 1: написать код**

В `tools/sprite-index/serve.py`:

после строк с путями (10–12) добавить:

```python
import re

PLANS = os.path.join(os.path.dirname(__file__), 'plans')
NAME_RE = re.compile(r'^[a-z0-9-]+$')   # имя файла плана карты-наброска (спека карты-наброска 8)
```

в классе `Handler` — класс-атрибут рядом с `__init__` (после `directory=ROOT`): расширение `.mjs` — модуль карты; на старых Python его нет в карте типов:

```python
    # .mjs — ES-модуль вкладки «Карта»: без явного типа старый SimpleHTTPRequestHandler отдаёт
    # его октет-стримом и браузер модуль не грузит (спека карты-наброска 8)
    extensions_map = {**SimpleHTTPRequestHandler.extensions_map, '.mjs': 'text/javascript; charset=utf-8'}
```

новый метод `do_GET` перед `do_POST`:

```python
    def do_GET(self):
        if self.path == '/plans':   # список набросков карты: имя + время изменения
            items = []
            if os.path.isdir(PLANS):
                for f in sorted(os.listdir(PLANS)):
                    if f.endswith('.yaml'):
                        items.append({'name': f[:-5], 'mtime': int(os.path.getmtime(os.path.join(PLANS, f)))})
            self._json(200, {'ok': True, 'plans': items})
        else:
            super().do_GET()
```

в `do_POST` после ветки `/pending`:

```python
        elif self.path == '/plan':   # сохранить набросок карты: plans/<name>.yaml, перезапись разрешена
            name, yaml = body.get('name', ''), body.get('yaml', '')
            if not NAME_RE.match(name):
                self._json(400, {'ok': False, 'error': 'имя плана — строчные латиница, цифры и дефис'})
            elif not isinstance(yaml, str):
                self._json(400, {'ok': False, 'error': 'yaml — строка'})
            else:
                os.makedirs(PLANS, exist_ok=True)
                with open(os.path.join(PLANS, name + '.yaml'), 'w') as f:
                    f.write(yaml)
                self._json(200, {'ok': True})
        elif self.path == '/plan/delete':   # удалить набросок; нет файла — тоже ок
            name = body.get('name', '')
            if not NAME_RE.match(name):
                self._json(400, {'ok': False, 'error': 'имя плана — строчные латиница, цифры и дефис'})
            else:
                try:
                    os.remove(os.path.join(PLANS, name + '.yaml'))
                except FileNotFoundError:
                    pass
                self._json(200, {'ok': True})
```

и обновить комментарий в шапке файла (строки 1–4): добавить «и планы карты-наброска (`GET /plans`, `POST /plan`, `POST /plan/delete` → `plans/`)».

- [ ] **Step 2: .gitignore**

В `.gitignore` в блоке браузера спрайтов (строки 33–35) добавить строку:

```
tools/sprite-index/plans/
```

- [ ] **Step 3: проверить curl-ом**

```bash
python3 -m py_compile tools/sprite-index/serve.py && echo ок
cd tools/sprite-index && python3 -I serve.py 4899 >/tmp/serve.log 2>&1 &
sleep 1
curl -s -X POST localhost:4899/plan -d '{"name":"test-plan","yaml":"name: test-plan\nsize: [4, 4]\n"}'; echo
curl -s -X POST localhost:4899/plan -d '{"name":"ПЛОХО","yaml":"x"}'; echo          # 400: имя не по маске
curl -s localhost:4899/plans; echo
curl -s -X POST localhost:4899/plan/delete -d '{"name":"test-plan"}'; echo
curl -s localhost:4899/plans; echo
printf 'export const x = 1;\n' > /tmp/probe.mjs && cp /tmp/probe.mjs ./probe.mjs
curl -sI localhost:4899/tools/sprite-index/probe.mjs | grep -i content-type; rm ./probe.mjs
kill %1
```

Expected: первый POST — `{"ok": true}`; второй — `{"ok": false, "error": "имя плана..."}`; `/plans` — список с `test-plan`, после удаления — `{"ok": true, "plans": []}`; Content-Type — `text/javascript; charset=utf-8`. Файл `tools/sprite-index/plans/` после проверки пуст (или отсутствует) и не виден в `git status`.

- [ ] **Step 4: коммит**

```bash
git add tools/sprite-index/serve.py .gitignore
git commit -m "feat: хранение планов карты-наброска в serve.py"
```

---

## Задача 7: build-index.py — лист ext_vehicles

**Files:**
- Modify: `tools/sprite-index/build-index.py:12-20` (`SHEETS`)

**Interfaces:**
- Consumes: ничего нового.
- Produces: машины в индексе спрайтов — лист `ext_vehicles` (машины ставят спрайтом из пикера с подписью, спека 3). Пересборка `index.json` требует `assets/` — в ворктри их нет, запуск переносится в ручную приёмку.

- [ ] **Step 1: добавить лист**

В `SHEETS` после записи `ext_office` добавить:

```python
    # Машины для наброска карты (спека карты-наброска 3): ставят спрайтом из пикера с подписью
    dict(name='ext_vehicles',
         path='assets/modern-exteriors/Modern_Exteriors_16x16/ME_Theme_Sorter_16x16/10_Vehicles_16x16.png'),
```

- [ ] **Step 2: проверить синтаксис**

Run: `python3 -m py_compile tools/sprite-index/build-index.py && echo ок`
Expected: `ок`.

- [ ] **Step 3: коммит**

```bash
git add tools/sprite-index/build-index.py
git commit -m "feat: лист ext_vehicles в индексе спрайтов"
```

Пересборка `index.json` — в основном каталоге владельца (там ассеты), в ручной приёмке.

---

## Задача 8: map-editor.js — каркас вкладки: холст, зум, панорама, земли

**Files:**
- Create: `tools/sprite-index/map-editor.js`

**Interfaces:**
- Consumes: `map-model.mjs` (задачи 1–2): `createDoc`, `terrainGrid`, `terrainFramesAt`; данные `catalog.json` (задача 5): `sheets`, `terrains`, `sketchKinds`, `entries`.
- Produces (используют задачи 9–12):
  - `window.mapEditor = { init({ catalog }), placeSprite(parts), onShow() }` — страница зовёт `init` после загрузки `catalog.json`, `placeSprite` кладёт спрайт в руки и включает вкладку (спека 2);
  - внутреннее состояние `st` и функции `render()`, `ensureImg(sheet)`, `cellAt(event)`, `snap()`, `toast(msg)` — их доопределяют/используют задачи 10–12;
  - события `window.map-editor-ready` — после установки `window.mapEditor`.
- Каркас рисует уже земли (газон дефолтной карты) — слои 2–6 добавит задача 10, инструменты — задача 11.

- [ ] **Step 1: написать модуль**

Создать `tools/sprite-index/map-editor.js`:

```js
// Вкладка «Карта» (спека карты-наброска 2): набросок карты будущего офиса грубыми мазками.
// Модуль грузится страницей ES-модулем, общение через window.mapEditor: init строит вкладку и DOM,
// placeSprite кладёт спрайт из пикера в руки. Верхний уровень — только объявления, чтобы
// `await import('./map-editor.js')` проходил в Node без DOM (проверка задач).
import * as M from './map-model.mjs';

const TS = 16;
const ROOT = '../../';   // страница в tools/sprite-index/, паки в assets/ корня репозитория
const ZOOM_MAX = 8;

let st = null;   // состояние вкладки: doc, виды, ленты листов, вид (зум), инструменты, undo/redo

// — листы: грузим лениво, по onload перерисовываемся —
function ensureImg(name) {
  if (!st.images[name]) {
    const im = new Image();
    im.onload = () => st && render();
    im.src = ROOT + st.sheets[name].path;
    st.images[name] = im;
  }
  return st.images[name];
}
function drawFrame(ctx, f, px, py, s) {
  const im = ensureImg(f.sheet);
  if (!im.complete || !im.naturalWidth) return;   // лист ещё не готов — перерисуемся по onload
  ctx.imageSmoothingEnabled = false;
  ctx.drawImage(im, f.rect[0], f.rect[1], f.rect[2], f.rect[3], px, py, f.rect[2] * s, f.rect[3] * s);
}

function toast(msg) {
  let el = document.getElementById('mapToast');
  if (!el) {
    el = document.createElement('div');
    el.id = 'mapToast';
    el.style.cssText = 'position:fixed;left:50%;bottom:18px;transform:translateX(-50%);background:#4a6fa5;color:#fff;padding:7px 14px;border-radius:8px;opacity:0;transition:opacity .25s;pointer-events:none;z-index:9';
    document.body.appendChild(el);
  }
  el.textContent = msg;
  el.style.opacity = 1;
  clearTimeout(el._t);
  el._t = setTimeout(() => { el.style.opacity = 0; }, 1800);
}

// Снимок документа в undo перед изменением (спека 2: стек до 100); redo сбрасывается
function snap() {
  st.undo.push(JSON.stringify(st.doc));
  if (st.undo.length > 100) st.undo.shift();
  st.redo.length = 0;
}

// — DOM вкладки: слева холст с прокруткой, справа панель. Панель наполняют задачи 11–12 —
function buildDom() {
  const sec = document.getElementById('mapView');
  sec.innerHTML = '';
  sec.style.cssText += 'gap:0';
  const wrap = document.createElement('div');
  wrap.id = 'mapWrap';
  wrap.style.cssText = 'flex:1;overflow:auto;background:#14161a;cursor:default';
  const cv = document.createElement('canvas');
  cv.id = 'mapCanvas';
  wrap.appendChild(cv);
  const side = document.createElement('aside');
  side.id = 'mapSide';
  side.style.cssText = 'width:340px;border-left:1px solid #33363c;background:#202227;padding:10px;overflow-y:auto';
  sec.append(wrap, side);
  // Стили страницы здесь же: панель карты повторяет вид соседних вкладок
  const css = document.createElement('style');
  css.textContent = `
    #mapSide h3 { margin: 8px 0; font-size: 13px; }
    #mapSide button, #mapSide input, #mapSide select { width: 100%; margin: 4px 0; padding: 8px; background: #2d3138; color: #d8d4cc; border: 1px solid #3c4046; border-radius: 6px; font-size: 14px; box-sizing: border-box; }
    #mapSide button { cursor: pointer; }
    #mapSide button.primary { background: #4a6fa5; border-color: #4a6fa5; color: #fff; }
    #mapSide textarea { width: 100%; background: #14161a; color: #d8d4cc; border: 1px solid #3c4046; border-radius: 6px; font: 13px/1.4 system-ui, sans-serif; padding: 7px; box-sizing: border-box; }
    #mapTools { display: flex; gap: 4px; }
    #mapTools button { flex: 1; }
    #mapTools button[data-on="1"] { background: #4a6fa5; border-color: #4a6fa5; color: #fff; }
    #mapCanvas { display: block; }
    #mapSide details { margin: 4px 0; }
    #mapSide summary { cursor: pointer; color: #a9c7ea; font-size: 13px; margin: 6px 0 2px; }
    .mapKind { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; }
    .mapKind canvas { image-rendering: pixelated; background: repeating-conic-gradient(#2a2d33 0 25%, #22252a 0 50%) 0 0 / 16px 16px; border-radius: 3px; flex: none; }
    .mapKind[data-on="1"] { background: #4a6fa5; border-color: #4a6fa5; color: #fff; }
    #mapHint { font-size: 12.5px; color: #7d8188; margin-top: 8px; }
  `;
  document.head.appendChild(css);
  st.wrap = wrap;
  st.cv = cv;
  buildSide();
}

// Правая панель: имя/размер, инструменты, палитра, свойства, хранение — разделы дописывают задачи 11–12
function buildSide() {
  const side = document.getElementById('mapSide');
  side.innerHTML = '';
  const h = (text) => { const el = document.createElement('h3'); el.textContent = text; side.appendChild(el); return el; };
  h('Карта');
  const name = document.createElement('input');
  name.id = 'mapName';
  name.value = st.doc.name;
  name.placeholder = 'имя файла: латиница, цифры, дефис';
  name.title = '[a-z0-9-]+ — имя плана-файла';
  side.appendChild(name);
  const sizeLbl = document.createElement('div');
  sizeLbl.id = 'mapSizeLbl';
  sizeLbl.style.cssText = 'font-size:12.5px;color:#7d8188;margin:2px 0 8px';
  side.appendChild(sizeLbl);
  st.side = { h, name, sizeLbl };
  updSizeLabel();
}

function updSizeLabel() {
  document.getElementById('mapSizeLbl').textContent =
    `${st.doc.size[0]}×${st.doc.size[1]} клеток · ×${st.view.zoom} · клетка 16 px`;
}

// — отрисовка: слои снизу вверх (спека 6); в этой задаче — сетка и земли, остальное добавит задача 10.
// Буфер канваса — всегда в пикселях карты (16 px на клетку), зум растягивает CSS-ом: буфер 150×100
// клеток — 2400×1600 при любом зуме, лимитов канваса нет; image-rendering: pixelated — пиксели честные.
function render() {
  if (!st) return;
  const s = 1;   // масштаб буфера; зум — только в style.width/height
  const [w, h] = st.doc.size;
  const cv = st.cv, ctx = cv.getContext('2d');
  cv.width = w * TS;
  cv.height = h * TS;
  cv.style.width = w * TS * st.view.zoom + 'px';
  cv.style.height = h * TS * st.view.zoom + 'px';
  cv.style.imageRendering = 'pixelated';
  ctx.imageSmoothingEnabled = false;
  ctx.clearRect(0, 0, cv.width, cv.height);
  // 1. Земли: сетка типов + автотайл по правилам каталога (спека 6.1)
  const grid = M.terrainGrid(st.doc, st.kinds);
  for (let y = 0; y < h; y++)
    for (let x = 0; x < w; x++)
      for (const f of M.terrainFramesAt(grid, st.terrains, x, y)) drawFrame(ctx, f, x * TS * s, y * TS * s, s);
  drawGrid(ctx, w, h, s);
  updSizeLabel();
}

// Сетка как в office-grid.ts: каждая 5-я линия темнее
function drawGrid(ctx, w, h, s) {
  const W = w * TS * s, H = h * TS * s;
  ctx.strokeStyle = 'rgba(120,130,150,.25)';
  ctx.beginPath();
  for (let x = 0; x <= w; x++) { ctx.moveTo(x * TS * s + .5, 0); ctx.lineTo(x * TS * s + .5, H); }
  for (let y = 0; y <= h; y++) { ctx.moveTo(0, y * TS * s + .5); ctx.lineTo(W, y * TS * s + .5); }
  ctx.stroke();
  ctx.strokeStyle = 'rgba(150,160,185,.45)';
  ctx.beginPath();
  for (let x = 0; x <= w; x += 5) { ctx.moveTo(x * TS * s + .5, 0); ctx.lineTo(x * TS * s + .5, H); }
  for (let y = 0; y <= h; y += 5) { ctx.moveTo(0, y * TS * s + .5); ctx.lineTo(W, y * TS * s + .5); }
  ctx.stroke();
}

// — мышь и клавиатура: зум колесом (×1…×8), панорама пробелом или средней кнопкой (спека 2) —
let panning = null, spaceDown = false;

function cellAt(e) {
  const r = st.cv.getBoundingClientRect();
  // kx/ky — уже зум (CSS-ширина = w*TS*zoom, буфер = w*TS): клетка в CSS-пикселях — kx*TS, без второго деления
  const kx = r.width / st.cv.width || 1, ky = r.height / st.cv.height || 1;
  return [Math.floor((e.clientX - r.left) / (kx * TS)), Math.floor((e.clientY - r.top) / (ky * TS))];
}

function bindCanvas() {
  const cv = st.cv;
  cv.addEventListener('wheel', e => {
    e.preventDefault();
    const wrap = st.wrap;
    const cx = (wrap.scrollLeft + wrap.clientWidth / 2) / wrap.scrollWidth;   // центр вьюпорта в долях
    const cy = (wrap.scrollTop + wrap.clientHeight / 2) / wrap.scrollHeight;
    st.view.zoom = Math.max(1, Math.min(ZOOM_MAX, st.view.zoom + (e.deltaY < 0 ? 1 : -1)));
    render();
    wrap.scrollLeft = cx * wrap.scrollWidth - wrap.clientWidth / 2;
    wrap.scrollTop = cy * wrap.scrollHeight - wrap.clientHeight / 2;
  }, { passive: false });
  cv.addEventListener('mousedown', e => {
    if (e.button === 1 || spaceDown) {
      panning = { x: e.clientX, y: e.clientY, sl: st.wrap.scrollLeft, st_: st.wrap.scrollTop };
      e.preventDefault();
    }
  });
  window.addEventListener('mousemove', e => {
    if (!panning) return;
    st.wrap.scrollLeft = panning.sl - (e.clientX - panning.x);
    st.wrap.scrollTop = panning.st_ - (e.clientY - panning.y);
  });
  window.addEventListener('mouseup', () => { panning = null; });
  document.addEventListener('keydown', e => {
    if (document.getElementById('mapView').style.display === 'none') return;
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') return;
    if (e.code === 'Space') { spaceDown = true; st.cv.style.cursor = 'grab'; e.preventDefault(); }
  });
  document.addEventListener('keyup', e => {
    if (e.code === 'Space') { spaceDown = false; st.cv.style.cursor = 'default'; }
  });
}

// — точка входа страницы (спека 2): после загрузки catalog.json —
export function init({ catalog }) {
  if (st) return;   // уже построена
  st = {
    doc: M.createDoc('my-office', 48, 35),
    kinds: catalog.sketchKinds,
    terrains: catalog.terrains,
    floors: catalog.floors,
    entries: new Map(catalog.entries.map(e => [e.item, e])),
    sheets: catalog.sheets,
    images: {},
    view: { zoom: 2 },
    tool: 'select', kind: null, hand: null,   // инструмент, выбранный вид, спрайт в руках
    sel: -1, undo: [], redo: [],
    savedList: [],
  };
  buildDom();
  bindCanvas();
  render();
}

// Спрайт из пикера в руки (спека 2): включает вкладку; клик по клетке поставит, Esc — отпустить
export function placeSprite(parts) {
  if (!st) return;
  st.hand = parts.map(p => ({ ...p }));
  st.tool = 'sprite';
  st.sel = -1;
  document.getElementById('tabMap')?.click();
  render();
}

// Вкладку показали — перерисоваться (листы могли догрузиться)
export function onShow() {
  if (st) render();
}

// Node-проверка задач: импорт без DOM не выполняет этот блок
if (typeof window !== 'undefined') {
  window.mapEditor = { init, placeSprite, onShow };
  window.dispatchEvent(new Event('map-editor-ready'));
}
```

- [ ] **Step 2: проверить импорт без DOM**

Run: `cd tools/sprite-index && node -e "await import('./map-editor.js'); console.log('модуль грузится, DOM не тронут')"`
Expected: `модуль грузится, DOM не тронут`. Любая ошибка — в модуле DOM-код вне функций.

- [ ] **Step 3: тесты модели живы**

Run: `cd tools/sprite-index && node --test test_map_model.mjs`
Expected: PASS — 22 теста.

- [ ] **Step 4: коммит**

```bash
git add tools/sprite-index/map-editor.js
git commit -m "feat: каркас вкладки «Карта» — холст, зум, панорама, земли"
```

---

## Задача 9: browser.html — вкладка, кнопки «На карту →», вызов init

**Files:**
- Modify: `tools/sprite-index/browser.html:78-165` (header, main), `:535-550` (`switchTab`), `:766-767` (hash), `:790-809` (цепочка fetch)

**Interfaces:**
- Consumes: `window.mapEditor` из задачи 8 (`init`, `placeSprite`), событие `map-editor-ready`.
- Produces: пятая вкладка «Карта» (`#map`, спека 2), кнопки «На карту →» в панели детали спрайта, в панели предмета каталога и на верстаке (спека 2). `mapView` — пустой каркас, содержимое строит `init`.

- [ ] **Step 1: кнопка вкладки и каркас секции**

В `tools/sprite-index/browser.html`:

в header после кнопки `tabIndex` (строка 83):

```html
    <button id="tabMap" data-on="0">Карта</button>
```

в `main` после `</section>` вкладки «Индексация» (перед закрывающим `</main>`, строка 165):

```html
  <section id="mapView" style="display:none; flex:1; overflow:hidden"></section>
```

- [ ] **Step 2: switchTab и прямая ссылка**

В `switchTab` (строки 536–546) добавить в ряд переключателей:

```js
  $('tabMap').dataset.on = which === 'map' ? '1' : '0';
  $('mapView').style.display = which === 'map' ? 'flex' : 'none';
  if (which === 'map') window.mapEditor?.onShow();
```

после `$('tabIndex').onclick` (строка 550):

```js
$('tabMap').onclick = () => switchTab('map');
```

строки прямой ссылки (766–767, комментарий и `if`) заменить:

```js
// прямая ссылка на вкладку: browser.html#catalog / #bench / #describe / #map
if (['#catalog', '#bench', '#describe', '#map'].includes(location.hash)) switchTab(location.hash.slice(1));
```

- [ ] **Step 3: кнопки «На карту →»**

В панель детали спрайта после `<button class="primary" id="dToBench">На верстак →</button>` (строка 111):

```html
      <button id="dToMap">На карту →</button>
```

В панель каталога после `<button class="primary" id="cdToBench">На верстак →</button>` (строка 142):

```html
        <button id="cdToMap">На карту →</button>
```

На верстаке после `<button id="bCopy">Копировать YAML</button>` (строка 128):

```html
        <button id="bToMap">На карту →</button>
```

- [ ] **Step 4: модуль и обработчики**

Перед основным `<script>` (строка 167) добавить:

```html
<script type="module" src="map-editor.js"></script>
```

В конце основного скрипта (после `applyZoom();`, строка 829) добавить:

```js
// — вкладка «Карта»: ES-модуль map-editor.js; пока модуль не догрузился — зовём по событию —
const mapReady = cb => window.mapEditor ? cb(window.mapEditor) : window.addEventListener('map-editor-ready', () => cb(window.mapEditor), { once: true });
const mapPlace = parts => mapReady(me => me.placeSprite(parts));
// спрайт пикера (с вырезкой): одна часть в левом верхнем углу клетки
$('dToMap').onclick = () => { const sp = effSprite(); sp && mapPlace([{ sheet: sp.sheet, rect: sp.rect, at: [0, 0] }]); };
// предмет каталога: собранная композиция идёт на карту предметом целиком (спека 2)
$('cdToMap').onclick = () => catSel && mapPlace(catSel.parts.map(p => ({ sheet: p.sheet, rect: p.rect, at: p.at, sortY: p.sortY })));
// верстак: слои — части от общего левого верха, sortY как в экспорте (минус origin, как bExport)
$('bToMap').onclick = () => {
  if (!layers.length) { toast('Верстак пуст'); return; }
  const [ox, oy] = benchOrigin();
  mapPlace(sortedLayers().map(l => ({ sheet: l.sp.sheet, rect: l.sp.rect, at: [l.x - ox, l.y - oy], sortY: +(l.sy - oy / TS).toFixed(2) })));
};
```

и в цепочке fetch после `renderCatalog();` (строка 806) — перед `return fetch('descriptions.json')`:

```js
  mapReady(me => me.init({ catalog: d }));   // вкладка «Карта» строится по catalog.json (sketchKinds, terrains)
```

- [ ] **Step 5: проверить**

```bash
cd tools/sprite-index && node -e "await import('./map-editor.js'); console.log('ок')"
grep -c 'tabMap\|map-editor.js\|dToMap\|cdToMap\|bToMap\|mapReady' browser.html   # ≥ 8 вхождений
python3 -I serve.py 4899 >/tmp/serve.log 2>&1 &
sleep 1
curl -s localhost:4899/tools/sprite-index/browser.html | grep -c 'tabMap'
curl -s localhost:4899/tools/sprite-index/map-editor.js | head -1
kill %1
```

Expected: `ок`; grep ≥ 8; curl tabMap = 3; первая строка map-editor.js отдаётся (200, `Content-Type: text/javascript`). Ассетов в ворктри нет — газон в браузере не видно, живая проверка вкладки в ручной приёмке.

- [ ] **Step 6: коммит**

```bash
git add tools/sprite-index/browser.html
git commit -m "feat: вкладка «Карта» в браузере спрайтов и кнопки «На карту →»"
```

---

## Задача 10: map-editor.js — отрисовка наброска по слоям

**Files:**
- Modify: `tools/sprite-index/map-editor.js`

**Interfaces:**
- Consumes: `sketchKinds` (кадры `building`/`wall`/`entrance`, `floor`, `item`, `decal`), `entries` (кадры декалей зебры и точечных предметов), `floors` — из задачи 5; `terrainGrid`/`terrainFramesAt` — задачи 1–2.
- Produces: полный `render()` — слои 1–6 спеки 6; функции `drawWallRing`, `objBox` (использует задача 11 для hit-теста и контура выделения).

- [ ] **Step 1: заменить render() и добавить слои**

В `tools/sprite-index/map-editor.js` заменить функцию `render` из задачи 8 на:

```js
// — отрисовка: слои снизу вверх (спека 6); буфер 1:1, зум — CSS (см. задачу 8) —
function render() {
  if (!st) return;
  const s = 1;
  const [w, h] = st.doc.size;
  const cv = st.cv, ctx = cv.getContext('2d');
  cv.width = w * TS;
  cv.height = h * TS;
  cv.style.width = w * TS * st.view.zoom + 'px';
  cv.style.height = h * TS * st.view.zoom + 'px';
  cv.style.imageRendering = 'pixelated';
  ctx.imageSmoothingEnabled = false;
  ctx.clearRect(0, 0, cv.width, cv.height);
  // 1. Земли: сетка типов + автотайл по правилам каталога (спека 6.1)
  const grid = M.terrainGrid(st.doc, st.kinds);
  for (let y = 0; y < h; y++)
    for (let x = 0; x < w; x++)
      for (const f of M.terrainFramesAt(grid, st.terrains, x, y)) drawFrame(ctx, f, x * TS * s, y * TS * s, s);
  drawCrosswalks(ctx, s);   // 2. переход поверх земли
  drawBuildings(ctx, s);    // 3. здание
  drawRooms(ctx, s);        // 4. комнаты + рамка вида
  drawWalls(ctx, s);        // 4. кольцо-контур стен
  drawSorted(ctx, s);       // 5. вход, дверь, предметы и спрайты по sortY
  drawOthers(ctx, s);       // 6. «Другое» и подписи
  drawGrid(ctx, w, h, s);   // сетка поверх слоёв, каждая 5-я линия темнее
  updSizeLabel();
}
```

и добавить после `drawGrid` (перед блоком мыши):

```js
// Зебра (спека 6.2): два левых столбца прямоугольника по всей высоте; арт каталога другой ширины
// не имеет. Верхняя строка прямоугольника — top_l/top_r, ниже — l/r. Вертикальной зебры в арте нет —
// при вертикальной дороге рисуются те же кадры, ориентацию агент поймёт по раскладке.
const CROSS = { topL: 'crosswalk_top_l', topR: 'crosswalk_top_r', l: 'crosswalk_l', r: 'crosswalk_r' };

function drawCrosswalks(ctx, s) {
  for (const o of st.doc.objects) {
    if (o.t !== 'rect' || st.kinds[o.kind]?.render.decal !== 'crosswalk') continue;
    const [x, y, rw, rh] = o.rect;
    for (let r = 0; r < rh; r++)
      for (let c = 0; c < 2 && c < rw; c++) {
        const id = r === 0 ? (c === 0 ? CROSS.topL : CROSS.topR) : c === 0 ? CROSS.l : CROSS.r;
        for (const p of st.entries.get(id)?.parts ?? [])
          drawFrame(ctx, p, (x + c) * TS * s + p.at[0] * s, (y + r) * TS * s + p.at[1] * s, s);
      }
  }
}

// Периметр прямоугольника кадрами здания (спека 6.3): южный ряд — лица 16×32 с углами (левый угол,
// середина, правый от base стиля), боковые ряды — вертикальная грань со сдвигом вверх на клетку,
// северный — грань нижнего ряда без сдвига. Используют вид building (спека 6.3) и вид wall —
// кольцо-контур без пола (спека 6.4): сплошной блок скрыл бы пол и комнаты.
function drawWallRing(ctx, s, rect, fr) {
  const [x, y, rw, rh] = rect;
  const south = y + rh - 1;
  for (let cx = 0; cx < rw; cx++) {
    const f = rw === 1 ? fr.southMid : cx === 0 ? fr.southLeft : cx === rw - 1 ? fr.southRight : fr.southMid;
    drawFrame(ctx, f, (x + cx) * TS * s, south * TS * s, s);   // лицо 16×32: верх — ряд стены, низ — перед зданием
  }
  if (rh < 2) return;
  for (let cy = 1; cy < rh - 1; cy++)
    for (const cx of rw === 1 ? [] : [0, rw - 1])
      drawFrame(ctx, fr.side, (x + cx) * TS * s + fr.side.at[0] * s, (y + cy) * TS * s + fr.side.at[1] * s, s);
  for (let cx = 0; cx < rw; cx++)
    drawFrame(ctx, fr.north, (x + cx) * TS * s + fr.north.at[0] * s, y * TS * s + fr.north.at[1] * s, s);
}

function drawBuildings(ctx, s) {
  for (const o of st.doc.objects) {
    if (o.t !== 'rect' || !st.kinds[o.kind]?.render.building) continue;
    const [x, y, rw, rh] = o.rect;
    const fl = st.floors.carpet_grey ?? [];   // интерьер — ковролин (спека 6.3)
    for (let cy = 0; cy < rh; cy++)
      for (let cx = 0; cx < rw; cx++) {
        const f = fl[(cx * 7 + cy * 13) % fl.length];
        if (f) drawFrame(ctx, f, (x + cx) * TS * s, (y + cy) * TS * s, s);
      }
    drawWallRing(ctx, s, o.rect, st.kinds[o.kind].render.building);
  }
}

function drawWalls(ctx, s) {
  for (const o of st.doc.objects) {
    if (o.t !== 'rect' || !st.kinds[o.kind]?.render.wall) continue;
    drawWallRing(ctx, s, o.rect, st.kinds[o.kind].render.wall);
  }
}

// Цвет рамки вида комнаты (спека 6.4: пол вида + цветная рамка; внутренние стены строит агент)
const ROOM_COLOR = { meeting: '#4a90d9', lounge: '#d9904a', coworking: '#7a9d54', pod: '#9a6fd0', techroom: '#b05050', storage: '#8a8a97', dock: '#50b0a8' };

function drawRooms(ctx, s) {
  for (const o of st.doc.objects) {
    if (o.t !== 'rect') continue;
    const r = st.kinds[o.kind]?.render;
    if (!r?.floor) continue;
    const fl = st.floors[r.floor] ?? [];
    const [x, y, rw, rh] = o.rect;
    for (let cy = 0; cy < rh; cy++)
      for (let cx = 0; cx < rw; cx++) {
        const f = fl[(cx * 7 + cy * 13) % fl.length];
        if (f) drawFrame(ctx, f, (x + cx) * TS * s, (y + cy) * TS * s, s);
      }
    ctx.strokeStyle = ROOM_COLOR[o.kind] ?? '#cccccc';
    ctx.lineWidth = 2;
    ctx.setLineDash([6, 4]);
    ctx.strokeRect(x * TS * s + 1, y * TS * s + 1, rw * TS * s - 2, rh * TS * s - 2);
    ctx.setLineDash([]);
    ctx.lineWidth = 1;
  }
}

// Предметы и спрайты (спека 6.5): предметы каталога — по sortY части (он не всегда нижний край: у
// bus_stop — середина ряда), сырые спрайты пикера — по нижней кромке кадра (как partLine страницы).
// Вход — кадр входной двери поверх южного лица (спека 6.3), якорь — клетка клика, как у предметов.
function drawSorted(ctx, s) {
  const list = [];
  const push = (sy, draw) => list.push({ sy, draw });
  for (const o of st.doc.objects) {
    if (o.t === 'point') {
      const r = st.kinds[o.kind]?.render;
      if (r?.entrance) push(o.at[1] + 1.5, () => drawFrame(ctx, r.entrance, o.at[0] * TS * s, o.at[1] * TS * s, s));
      else if (r?.item)
        for (const p of st.entries.get(r.item)?.parts ?? [])
          push(o.at[1] + p.sortY, () => drawFrame(ctx, p, o.at[0] * TS * s + p.at[0] * s, o.at[1] * TS * s + p.at[1] * s, s));
    } else if (o.t === 'sprite') {
      for (const p of o.parts) {
        const sy = p.sortY !== undefined ? o.at[1] + p.sortY : o.at[1] + (p.at[1] + p.rect[3]) / TS;
        push(sy, () => drawFrame(ctx, p, o.at[0] * TS * s + p.at[0] * s, o.at[1] * TS * s + p.at[1] * s, s));
      }
    }
  }
  list.sort((a, b) => a.sy - b.sy);
  for (const it of list) it.draw();
}

// «Другое» (спека 6.6): полупрозрачная плашка с рамкой и текстом note
function drawOthers(ctx, s) {
  ctx.font = `${Math.round(11 * Math.max(1, Math.min(2, s / 2)))}px ui-monospace, monospace`;
  for (const o of st.doc.objects) {
    if (!st.kinds[o.kind]?.render.custom) continue;
    const [x, y, rw, rh] = o.t === 'rect' ? o.rect : [o.at[0], o.at[1], 1, 1];
    ctx.fillStyle = 'rgba(226,178,80,.15)';
    ctx.fillRect(x * TS * s, y * TS * s, rw * TS * s, rh * TS * s);
    ctx.strokeStyle = '#e0b050';
    ctx.setLineDash([4, 3]);
    ctx.strokeRect(x * TS * s + .5, y * TS * s + .5, rw * TS * s - 1, rh * TS * s - 1);
    ctx.setLineDash([]);
    if (o.note) {
      const tw = ctx.measureText(o.note).width;
      ctx.fillStyle = 'rgba(20,22,26,.75)';
      ctx.fillRect(x * TS * s + 2, y * TS * s + 2, tw + 8, 15);
      ctx.fillStyle = '#f0e6c8';
      ctx.fillText(o.note, x * TS * s + 6, y * TS * s + 13);
    }
  }
}

// Контур объекта в клетках: rect — сам, точка/спрайт — по частям (предметы с якорем больше клетки,
// спека 3: контур виден при выделении); без частей — клетка
function objBox(o) {
  if (o.t === 'rect') return [...o.rect];
  const parts = o.t === 'sprite' ? o.parts : st.entries.get(st.kinds[o.kind]?.render.item)?.parts ?? [];
  if (!parts.length) return [o.at[0], o.at[1], 1, 1];
  const x0 = Math.min(...parts.map(p => o.at[0] + p.at[0]));
  const y0 = Math.min(...parts.map(p => o.at[1] + p.at[1]));
  const x1 = Math.max(...parts.map(p => o.at[0] + p.at[0] + p.rect[2]));
  const y1 = Math.max(...parts.map(p => o.at[1] + p.at[1] + p.rect[3]));
  return [x0, y0, x1 - x0, y1 - y0];
}
```

- [ ] **Step 2: проверить импорт и тесты**

```bash
cd tools/sprite-index && node -e "await import('./map-editor.js'); console.log('ок')"
node --test test_map_model.mjs
```

Expected: `ок`; PASS — 22 теста.

- [ ] **Step 3: коммит**

```bash
git add tools/sprite-index/map-editor.js
git commit -m "feat: отрисовка наброска спрайтами каталога"
```

---

## Задача 11: map-editor.js — инструменты, палитра, свойства, отмена/повтор

**Files:**
- Modify: `tools/sprite-index/map-editor.js`

**Interfaces:**
- Consumes: `render`/`objBox`/`snap`/`cellAt` (задачи 8, 10), `createDoc` модели.
- Produces: инструменты «Прямоугольник»/«Точка»/«Спрайт в руках»/«Выбор» (спека 2): палитра видов с превью (выбранный вид задаёт инструмент сам), выделение с перетаскиванием и Delete, панель свойств (смена вида, `note`), Ctrl+Z/Ctrl+Shift+Z (стек до 100), диалог новой карты (48×35 по умолчанию, пределы 150×100, имя `[a-z0-9-]+`).

- [ ] **Step 1: панель — заменить buildSide целиком**

В `tools/sprite-index/map-editor.js` заменить `buildSide` из задачи 8 на:

```js
// Правая панель: имя, новая карта, инструменты, палитра видов, свойства выбранного (спека 2–3)
function buildSide() {
  const side = document.getElementById('mapSide');
  side.innerHTML = '';
  const h = (text) => { const el = document.createElement('h3'); el.textContent = text; side.appendChild(el); };
  h('Карта');
  const name = document.createElement('input');
  name.id = 'mapName';
  name.value = st.doc.name;
  name.placeholder = 'имя файла: латиница, цифры, дефис';
  name.title = '[a-z0-9-]+ — имя плана-файла и YAML name';
  name.oninput = () => { st.doc.name = name.value.trim(); };
  side.appendChild(name);
  const sizeLbl = document.createElement('div');
  sizeLbl.id = 'mapSizeLbl';
  sizeLbl.style.cssText = 'font-size:12.5px;color:#7d8188;margin:2px 0 8px';
  side.appendChild(sizeLbl);
  const newBtn = document.createElement('button');
  newBtn.textContent = 'Новая карта…';
  newBtn.onclick = () => document.getElementById('mapNewDlg')?.showModal();
  side.appendChild(newBtn);
  buildNewDialog(side);
  h('Инструменты');
  const tools = document.createElement('div');
  tools.id = 'mapTools';
  for (const [id, label, title] of [
    ['select', 'Выбор', 'выделить, таскать, Delete — удалить'],
    ['rect', 'Прямоугольник', 'выделить область — объект выбранного вида'],
    ['point', 'Точка', 'клик — точечный объект выбранного вида'],
    ['sprite', 'Спрайт', 'спрайт в руках: клик — поставить, Esc — отпустить'],
    ['undo', '↶', 'отмена (Ctrl+Z)'],
    ['redo', '↷', 'повтор (Ctrl+Shift+Z)'],
  ]) {
    const b = document.createElement('button');
    b.id = 'mapTool_' + id;
    b.textContent = label;
    b.title = title;
    b.onclick = () => {
      if (id === 'undo') return undo();
      if (id === 'redo') return redo();
      if (id === 'sprite' && !st.hand) { toast('возьми спрайт кнопкой «На карту →» в пикере'); return; }
      st.tool = id;
      renderTools();
    };
    tools.appendChild(b);
  }
  side.appendChild(tools);
  h('Виды');
  buildPalette(side);
  h('Свойства');
  const props = document.createElement('div');
  props.id = 'mapProps';
  side.appendChild(props);
  renderTools();
  renderProps();
  updSizeLabel();
}

// Диалог новой карты (спека 2): имя и размер; пустая карта залита газоном (модель даёт grass вне прям.)
function buildNewDialog(side) {
  const dlg = document.createElement('dialog');
  dlg.id = 'mapNewDlg';
  dlg.style.cssText = 'background:#24272c;color:#d8d4cc;border:1px solid #3c4046;border-radius:8px;padding:14px';   // дефолтный dialog белый
  const form = document.createElement('form');
  form.style.cssText = 'display:grid;gap:8px;min-width:300px';
  form.innerHTML = `
    <h3 style="margin:0;font-size:14px">Новая карта</h3>
    <input name="name" placeholder="имя файла: my-office" value="my-office">
    <div style="display:flex;gap:8px">
      <input name="w" type="number" min="1" max="150" value="48">
      <input name="h" type="number" min="1" max="100" value="35">
    </div>
    <span style="font-size:12.5px;color:#7d8188">клеток; по умолчанию 48×35 (как участок local), пределы 150×100 —
лимит валидатора хостинга. Пустая карта залита газоном.</span>
    <div style="display:flex;gap:8px">
      <button value="cancel" type="submit" style="flex:1">Отмена</button>
      <button class="primary" value="ok" type="submit" style="flex:1">Создать</button>
    </div>`;
  dlg.appendChild(form);
  side.appendChild(dlg);
  form.onsubmit = ev => {
    ev.preventDefault();
    if ((ev.submitter?.value ?? '') !== 'ok') { dlg.close(); return; }   // отмена — закрыть без сабмита страницы
    const nm = form.elements.name.value.trim();
    const w = parseInt(form.elements.w.value, 10), hh = parseInt(form.elements.h.value, 10);
    if (!/^[a-z0-9-]+$/.test(nm)) { toast('имя — строчные латиница, цифры и дефис'); return; }
    if (!(w >= 1 && hh >= 1 && w <= 150 && hh <= 100)) { toast('размер — пара чисел до 150×100'); return; }
    snap();
    st.doc = M.createDoc(nm, w, hh);
    st.sel = -1;
    document.getElementById('mapName').value = nm;
    dlg.close();
    render();
    renderProps();
  };
}

// Палитра видов (спека 3): выпадающие группы, у вида — значок-превью спрайтом. Новый вид — строка
// в словаре build-catalog.ts и пересборка, HTML не трогаем.
function buildPalette(side) {
  const groups = new Map();
  for (const k of Object.values(st.kinds)) {
    if (!groups.has(k.group)) groups.set(k.group, []);
    groups.get(k.group).push(k);
  }
  for (const [group, kinds] of groups) {
    const det = document.createElement('details');
    det.open = group === 'Земля';
    const sum = document.createElement('summary');
    sum.textContent = group;
    det.appendChild(sum);
    for (const k of kinds) {
      const b = document.createElement('button');
      b.className = 'mapKind';
      b.dataset.kind = k.id;
      b.title = k.tool === 'rect' ? 'рисуется прямоугольником' : 'рисуется точкой';
      const cv = document.createElement('canvas');
      cv.width = 22;
      cv.height = 22;
      const f = kindPreviewFrame(k);
      if (f) {
        const scale = Math.max(1, Math.floor(22 / Math.max(f.rect[2], f.rect[3])) || 1);
        const paint = () => { const c2 = cv.getContext('2d'); c2.clearRect(0, 0, 22, 22); drawFrame(c2, f, 0, 0, scale); };
        st.previews.push(paint);   // лист не готов — дорисуется по onload (ensureImg зовёт render и превью)
        paint();
      }
      b.appendChild(cv);
      const nm = document.createElement('span');
      nm.textContent = k.name;
      b.appendChild(nm);
      b.onclick = () => {
        st.kind = k.id;
        st.tool = k.tool;   // выбранный вид задаёт инструмент сам (спека 2)
        renderTools();
        renderPalette();
      };
      det.appendChild(b);
    }
    side.appendChild(det);
  }
}

// Кадр-превью вида: земля — fill, комната — пол, предмет — первая часть, здание/стена — середина лица
function kindPreviewFrame(k) {
  const r = k.render;
  if (r.terrain) return st.terrains[r.terrain]?.fill[0];
  if (r.floor) return st.floors[r.floor]?.[0];
  if (r.item) return st.entries.get(r.item)?.parts[0];
  if (r.entrance) return r.entrance;
  if (r.building) return r.building.southMid;
  if (r.wall) return r.wall.southMid;
  if (r.decal) return st.entries.get(CROSS.topL)?.parts[0];
  return null;   // other — без превью
}

function renderTools() {
  for (const id of ['select', 'rect', 'point', 'sprite']) {
    const b = document.getElementById('mapTool_' + id);
    if (b) b.dataset.on = st.tool === id ? '1' : '0';
  }
}

function renderPalette() {
  for (const b of document.querySelectorAll('#mapSide .mapKind'))
    b.dataset.on = b.dataset.kind === st.kind ? '1' : '0';
}

// Панель свойств выбранного (спека 2): сменить вид и подпись; у спрайта подпись обязательна
function renderProps() {
  const box = document.getElementById('mapProps');
  if (!box) return;
  const o = st.doc.objects[st.sel];
  if (!o) {
    box.innerHTML = '<div id="mapHint">Выбери объект («Выбор») или рисуй: выбранный вид в палитре задаёт инструмент сам. Зум — колесо, панорама — пробел или средняя кнопка.</div>';
    return;
  }
  box.innerHTML = '';
  const title = document.createElement('div');
  title.style.cssText = 'font-size:13px;color:#a9c7ea;margin-bottom:4px';
  title.textContent = o.t === 'sprite'
    ? 'спрайт из пикера · ' + o.at.join(', ')
    : (st.kinds[o.kind]?.name ?? o.kind) + ' · ' + (o.t === 'rect' ? o.rect.join(', ') : o.at.join(', '));
  box.appendChild(title);
  if (o.t !== 'sprite') {
    const sel = document.createElement('select');
    for (const k of Object.values(st.kinds)) {
      if (k.tool !== (o.t === 'rect' ? 'rect' : 'point')) continue;   // rect-виды — прямоугольнику, point — точке
      const op = document.createElement('option');
      op.value = k.id;
      op.textContent = k.group + ' · ' + k.name;
      if (k.id === o.kind) op.selected = true;
      sel.appendChild(op);
    }
    sel.onchange = () => { snap(); o.kind = sel.value; render(); renderProps(); };
    box.appendChild(sel);
  }
  const note = document.createElement('textarea');
  note.placeholder = 'подпись для агента (note); у спрайта обязательна';
  note.value = o.note ?? '';
  note.onfocus = () => snap();              // снимок до правки текста — Ctrl+Z вернёт прежний
  note.oninput = () => { o.note = note.value; };
  box.appendChild(note);
  const del = document.createElement('button');
  del.textContent = 'Удалить (Delete)';
  del.onclick = () => delSel();
  box.appendChild(del);
}

function delSel() {
  if (st.sel < 0) return;
  snap();
  st.doc.objects.splice(st.sel, 1);
  st.sel = -1;
  render();
  renderProps();
}

// Отмена/повтор (спека 2): снимки документа, стек до 100 (snap ограничивает)
function undo() {
  if (!st.undo.length) return;
  st.redo.push(JSON.stringify(st.doc));
  st.doc = JSON.parse(st.undo.pop()!);
  st.sel = Math.min(st.sel, st.doc.objects.length - 1);
  render();
  renderProps();
}

function redo() {
  if (!st.redo.length) return;
  st.undo.push(JSON.stringify(st.doc));
  st.doc = JSON.parse(st.redo.pop()!);
  st.sel = Math.min(st.sel, st.doc.objects.length - 1);
  render();
  renderProps();
}
```

- [ ] **Step 2: инструменты мышью и клавишами — дописать bindCanvas**

В `bindCanvas` (задача 8) после обработчика `wheel` добавить инструменты, а существующий `mousedown` дополнить. Итоговый блок обработчиков (вставить после `wheel`-обработника, а прежний `mousedown` из задачи 8 заменить целиком):

```js
  // — инструменты (спека 2) —
  let drag = null;   // rect: {mode:'rect', from, to}; move: {mode:'move', i, last}
  const hitTest = (x, y) => {
    for (let i = st.doc.objects.length - 1; i >= 0; i--) {   // верхние — раньше на попадание
      const [bx, by, bw, bh] = objBox(st.doc.objects[i]!);
      if (x >= bx && x < bx + bw && y >= by && y < by + bh) return i;
    }
    return -1;
  };
  cv.addEventListener('mousedown', e => {
    if (e.button === 1 || spaceDown) {   // панорама — средняя кнопка или пробел (задача 8)
      panning = { x: e.clientX, y: e.clientY, sl: st.wrap.scrollLeft, st_: st.wrap.scrollTop };
      e.preventDefault();
      return;
    }
    if (e.button !== 0) return;
    const [x, y] = cellAt(e);
    if (st.tool === 'select') {
      st.sel = hitTest(x, y);
      if (st.sel >= 0) drag = { mode: 'move', i: st.sel, last: [x, y], moved: false };
      render();
      renderProps();
    } else if (st.tool === 'rect' && st.kind) {
      drag = { mode: 'rect', from: [x, y], to: [x, y] };
    } else if (st.tool === 'point' && st.kind) {
      snap();
      st.doc.objects.push({ t: 'point', kind: st.kind, at: [x, y] });
      st.sel = st.doc.objects.length - 1;
      render();
      renderProps();
    } else if (st.tool === 'sprite' && st.hand) {
      snap();
      st.doc.objects.push({ t: 'sprite', parts: st.hand.map(p => ({ ...p })), at: [x, y], note: '' });
      st.hand = null;                 // поставили — руки пусты; спрайт остаётся выделенным (спека 2)
      st.tool = 'select';
      st.sel = st.doc.objects.length - 1;
      renderTools();
      render();
      renderProps();
    }
  });
  cv.addEventListener('mousemove', e => {
    if (!drag) return;
    const [x, y] = cellAt(e);
    if (drag.mode === 'rect') {
      drag.to = [x, y];
      render();
    } else if (drag.mode === 'move') {
      const o = st.doc.objects[drag.i]!;
      if (!o) { drag = null; return; }
      const dx = x - drag.last[0], dy = y - drag.last[1];
      if (dx || dy) {
        if (!drag.moved) { snap(); drag.moved = true; }   // снимок один на всё перетаскивание
        if (o.t === 'rect') { o.rect[0] += dx; o.rect[1] += dy; }
        else { o.at[0] += dx; o.at[1] += dy; }
        drag.last = [x, y];
        render();
      }
    }
  });
  window.addEventListener('mouseup', () => {
    if (drag?.mode === 'rect') {
      const [x0, y0] = drag.from, [x1, y1] = drag.to;
      const rect = [Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0) + 1, Math.abs(y1 - y0) + 1];
      snap();
      st.doc.objects.push({ t: 'rect', kind: st.kind, rect });
      st.sel = st.doc.objects.length - 1;
      render();
      renderProps();
    }
    drag = null;
  });
```

и удалить из задачи-8 обработчик `mousedown` (панорама теперь в новом обработчике первой веткой), оставив `mousemove`/`mouseup` панорамы как были. Движение объектов за край карты не ограничиваем: модель `terrainGrid` клипит по границам, а утащенный объект виден (контур выделения) и возвращается перетаскиванием.

- [ ] **Step 3: клавиши — дополнить обработчик из задачи 8**

В `document.addEventListener('keydown', …)` (задача 8) после ветки `Space` добавить:

```js
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') {
      e.preventDefault();
      e.shiftKey ? redo() : undo();
    }
    if (e.key === 'Escape' && st.hand) { st.hand = null; st.tool = 'select'; renderTools(); toast('спрайт отпущен'); }
    else if (e.key === 'Escape') { st.sel = -1; render(); renderProps(); }
    if ((e.key === 'Delete' || e.key === 'Backspace') && st.sel >= 0) { e.preventDefault(); delSel(); }
```

- [ ] **Step 4: превью прямоугольника и контур выделения — дополнить render**

В `render` (задача 10) перед `drawGrid(ctx, w, h, s);` вставить:

```js
  drawSelection(ctx, s);
```

и добавить функцию:

```js
// Превью прямоугольника при рисовании и контур выбранного объекта (спека 3: контур виден при выделении)
function drawSelection(ctx, s) {
  if (st.dragRect) {
    const [x, y, w, h] = st.dragRect;
    ctx.fillStyle = 'rgba(110,163,232,.2)';
    ctx.fillRect(x * TS * s, y * TS * s, w * TS * s, h * TS * s);
    ctx.strokeStyle = '#6ea3e8';
    ctx.strokeRect(x * TS * s + .5, y * TS * s + .5, w * TS * s - 1, h * TS * s - 1);
  }
  const o = st.doc.objects[st.sel];
  if (o) {
    const [x, y, w, h] = objBox(o);
    ctx.strokeStyle = '#e0b050';
    ctx.setLineDash([5, 4]);
    ctx.strokeRect(x * TS * s + .5, y * TS * s + .5, w * TS * s - 1, h * TS * s - 1);
    ctx.setLineDash([]);
  }
}
```

Превью держать в `st.dragRect`: в `mousemove` ветки `rect` после `drag.to = [x, y]` ставить `st.dragRect = [Math.min(drag.from[0], x), Math.min(drag.from[1], y), Math.abs(x - drag.from[0]) + 1, Math.abs(y - drag.from[1]) + 1]`, в `mouseup` — `st.dragRect = null`.

- [ ] **Step 5: превью палитры перерисовываются по onload листов**

В `ensureImg` (задача 8) строку `im.onload = () => st && render();` заменить:

```js
    im.onload = () => { if (!st) return; render(); for (const p of st.previews ?? []) p(); };
```

и в `init` (задача 8) добавить `previews: []` в объект `st` — до `buildDom()` (массив накапливают `buildPalette`/`buildSide`, они его только наполняют, присваивания в них нет; живёт со состоянием и не стирается при догрузке листов):

```js
    images: {},
    previews: [],   // перерисовки превью палитры по onload листов (задача 11)
```

- [ ] **Step 6: проверить**

```bash
cd tools/sprite-index && node -e "await import('./map-editor.js'); console.log('ок')"
node --test test_map_model.mjs
```

Expected: `ок`; PASS. Живое поведение (инструменты, undo, диалог) — ручная приёмка.

- [ ] **Step 7: коммит**

```bash
git add tools/sprite-index/map-editor.js
git commit -m "feat: инструменты карты-наброска — прямоугольник, точка, спрайт, выбор"
```

---

## Задача 12: map-editor.js — сохранение, открытие, экспорт

**Files:**
- Modify: `tools/sprite-index/map-editor.js`

**Interfaces:**
- Consumes: `docToYaml`/`yamlToDoc` модели (задачи 3–4), роуты `serve.py` (задача 6), файл плана по статике `plans/<имя>.yaml`.
- Produces: раздел «План» в панели — список сохранённых (`GET /plans`), «Открыть»/«Удалить», «Сохранить на сервер» (`POST /plan`), «Скопировать YAML» и «Скачать PNG» (буфер/`toBlob`, спека 5). Экспорт со спрайтом без подписи не проходит молча: ошибка с подсветкой объекта (спека 2).

- [ ] **Step 1: добавить раздел плана и функции**

В `tools/sprite-index/map-editor.js` после `redo()` добавить:

```js
// — план для агента (спека 5, 8): сохранить/открыть/удалить, YAML в буфер, PNG снимком холста —
async function post(url, body) {
  const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
  const d = await r.json().catch(() => ({}));
  if (!r.ok || !d.ok) throw new Error(d.error || r.status);
  return d;
}

// Экспорт не проходит молча (спека 2): спрайт без подписи — ошибка и подсветка объекта
function checkExport() {
  const r = M.docToYaml(st.doc, st.kinds);
  if (!r.ok) {
    st.sel = r.index;
    render();
    renderProps();
    toast(r.message);
    return null;
  }
  return r.yaml;
}

async function refreshPlans() {
  const sel = document.getElementById('mapPlanList');
  if (!sel) return;
  try {
    const d = await (await fetch('/plans')).json();
    sel.innerHTML = '';
    for (const p of d.plans ?? []) {
      const op = document.createElement('option');
      op.value = p.name;
      op.textContent = p.name + ' · ' + new Date(p.mtime * 1000).toLocaleString('ru-RU');
      sel.appendChild(op);
    }
  } catch { /* сервер не запущен — список пуст, страница работает */ }
}

async function savePlan() {
  if (!/^[a-z0-9-]+$/.test(st.doc.name)) { toast('имя — строчные латиница, цифры и дефис'); return; }
  const yaml = checkExport();
  if (yaml === null) return;
  try {
    await post('/plan', { name: st.doc.name, yaml });
    toast('Сохранён: plans/' + st.doc.name + '.yaml');
    await refreshPlans();
  } catch (e) { toast('Не сохранилось: сервер — python3 -I serve.py (' + e.message + ')'); }
}

async function openPlan(name) {
  if (!name) return;
  try {
    const r = await fetch('plans/' + name + '.yaml', { cache: 'no-store' });   // статика serve.py
    if (!r.ok) throw new Error('файл не читается');
    const back = M.yamlToDoc(await r.text());
    if (!back.ok) throw new Error('строка ' + back.line + ': ' + back.error);   // правлен руками — честная ошибка
    snap();
    st.doc = back.doc;
    st.sel = -1;
    document.getElementById('mapName').value = st.doc.name;
    render();
    renderProps();
    toast('Открыт ' + name);
  } catch (e) { toast('Не открылся: ' + e.message); }
}

function buildPlanSection(side) {
  const h = document.createElement('h3');
  h.textContent = 'План для агента';
  side.appendChild(h);
  const list = document.createElement('select');
  list.id = 'mapPlanList';
  side.appendChild(list);
  const row = document.createElement('div');
  row.style.cssText = 'display:flex;gap:6px';
  const open = document.createElement('button');
  open.textContent = 'Открыть';
  open.style.flex = '1';
  open.onclick = () => openPlan(list.value);
  const del = document.createElement('button');
  del.textContent = 'Удалить';
  del.style.flex = '1';
  del.onclick = async () => {
    if (!list.value) return;
    try { await post('/plan/delete', { name: list.value }); toast('Удалён'); await refreshPlans(); }
    catch (e) { toast('Не удалилось: ' + e.message); }
  };
  row.append(open, del);
  side.appendChild(row);
  const save = document.createElement('button');
  save.className = 'primary';
  save.textContent = 'Сохранить на сервер';
  save.onclick = savePlan;
  side.appendChild(save);
  const copyY = document.createElement('button');
  copyY.textContent = 'Скопировать YAML';
  copyY.onclick = () => {
    const yaml = checkExport();
    if (yaml !== null) navigator.clipboard.writeText(yaml).then(() => toast('YAML скопирован'), () => toast('Не вышло'));
  };
  side.appendChild(copyY);
  const png = document.createElement('button');
  png.textContent = 'Скачать PNG';
  png.onclick = () => {
    if (checkExport() === null) return;
    st.cv.toBlob(b => {   // снимок холста — агенту глазами (спека 5); на сервер не пишется
      const a = document.createElement('a');
      a.href = URL.createObjectURL(b);
      a.download = st.doc.name + '.png';
      a.click();
      URL.revokeObjectURL(a.href);
    });
  };
  side.appendChild(png);
  const hint = document.createElement('div');
  hint.style.cssText = 'font-size:12.5px;color:#7d8188;margin-top:8px';
  hint.textContent = 'Файл для агента: tools/sprite-index/plans/<имя>.yaml — набросок, не office.yaml; офис по каталогу и спекам строит агент.';
  side.appendChild(hint);
  refreshPlans();
}
```

и в `buildSide` (задача 11) после `renderProps();` перед `updSizeLabel();` добавить:

```js
  buildPlanSection(side);
```

- [ ] **Step 2: проверить**

```bash
cd tools/sprite-index && node -e "await import('./map-editor.js'); console.log('ок')"
node --test test_map_model.mjs
python3 -m py_compile serve.py && echo serve-ок
```

Expected: `ок`, PASS, `serve-ок`. Живое сохранение/открытие — ручная приёмка.

- [ ] **Step 3: коммит**

```bash
git add tools/sprite-index/map-editor.js
git commit -m "feat: сохранение и экспорт наброска — YAML, PNG, список планов"
```

---

## Задача 13: README и финальная проверка

**Files:**
- Modify: `tools/sprite-index/README.md`

**Interfaces:**
- Consumes: всё сделанное.
- Produces: документация пикера в согласии с кодом.

- [ ] **Step 1: README**

В `tools/sprite-index/README.md`:

в списке «Вкладки» после пункта «Индексация» добавить:

```markdown
- **Карта** (`#map`) — набросок карты будущего офиса (спека карты-наброска): земли, здание, комнаты и
  точки — прямоугольниками и кликами по палитре видов, предметы и машины — спрайтами из пикера
  (кнопка «На карту →»). Рисуется спрайтами каталога (автотайл земель — правила каталога), выход —
  план-YAML для агента: «Скопировать YAML», «Скачать PNG», «Сохранить на сервер» (`plans/<имя>.yaml`,
  расходный материал, в git не входят). Путь файла для агента: `tools/sprite-index/plans/<имя>.yaml`.
```

в «Запуск» после строки про serve.py дописать: «планы карты-наброска — `plans/` рядом, отдаётся и статикой, и `GET /plans`».

строку «Прямая ссылка на вкладку: `#bench`, `#catalog`, `#describe`» дополнить: «Прямая ссылка на вкладку: `#bench`, `#catalog`, `#describe`, `#map`».

в «Пересборка индексов» дополнить: `build-index.py` индексирует и `ext_vehicles` (машины для наброска);
`node build-catalog.ts` выгружает ещё `terrains`/`floors`/`wallStyles`/`sketchKinds` для вкладки «Карта» —
новый вид наброска — строка в словаре `sketchKinds` `build-catalog.ts` и пересборка, HTML не трогаем.

добавить раздел «Тесты» после «Пересборка индексов»:

```markdown
## Тесты

`node --test test_map_model.mjs` — чистая модель карты-наброска (сетка земель, автотайл, YAML
туда-обратно); в `pnpm gate` не входит, запускать руками после правок модели.
```

- [ ] **Step 2: финальный прогон**

```bash
cd tools/sprite-index && node --test test_map_model.mjs && node build-catalog.ts && node -e "await import('./map-editor.js'); console.log('модуль ок')"
python3 -m py_compile serve.py build-index.py && cd ../.. && pnpm gate
git status --short   # только ожидаемые файлы, plans/ не виден
```

Expected: тесты зелёные, сборка без ошибок, `pnpm gate` зелёный (пикер его не касается — на всякий случай), `git status` пуст.

- [ ] **Step 3: коммит**

```bash
git add tools/sprite-index/README.md
git commit -m "docs: README вкладки «Карта» браузера спрайтов"
```

---

## Ручная приёмка (владелец, основной каталог с assets)

Спека 10. Выполняется после мержа ветки в основной каталог (или в нём самом поверх):

1. Пересборка индексов: `python3 -I build-index.py` (лист `ext_vehicles` появился) и `node tools/sprite-index/build-catalog.ts` из `tools/sprite-index` — затем `python3 -I serve.py` из `tools/sprite-index`.
2. `browser.html#map` → «Новая карта…» 48×35 → газон. Нарисовать по памяти улицу demo (спека 10): дорога справа полосой, тротуар вдоль, здание 24×18 с входом на южном ряду, переход через дорогу двумя столбцами, метро за дорогой, фонари, деревья.
3. Сравнить видом с `node tools/office-grid.ts offices/demo` — сходство вида, не точность: кромка газона, бордюр дороги, фасад снаружи, зебра.
4. Спрайт из пикера: «Поиск» → машина с листа `ext_vehicles` → «На карту →» → клик по клетке → подпись в панели свойств → «Скопировать YAML»: заголовок-комментарий, `legend` с русскими именами, спрайт со своей `note`. Без подписи — ошибка и подсветка спрайта.
5. «Сохранить на сервер» → имя файла `plans/<имя>.yaml`; обновить страницу → «Открыть» восстанавливает; «Удалить» убирает.
6. Ctrl+Z/Ctrl+Shift+Z, Delete, Esc для спрайта в руках, зум колесом ×1…×8, панорама пробелом и средней кнопкой.
7. Фонтан и остановка (якорь больше клетки): клик ставит левый верхний угол в клетку, контур виден при выделении.
8. «Скачать PNG» — снимок холста открывается.

## Риски и альтернативы

1. **Мини-парсер YAML.** Свой разбор только наших конструкций (спека 9) вместо общего YAML-парсера: файлы пишем сами, формат подконтролен; файл, правленный руками и не разобравшийся, — честная ошибка с номером строки. Альтернатива — тащить js-yaml в пикер, отвергнута спекой (и пикер живёт без зависимостей). Риск закрыт тестами круга и крайних случаев (задача 4).
2. **Кадры граней здания ищутся по правилам автотайла.** `build-catalog.ts` находит правила `when {s:1}` и `{n:0,s:1}` — при перестройке каталога они могут измениться; сборка падает с понятной ошибкой (`plain` бросает), ассерты задачи 5 фиксируют координаты. Альтернатива — хардкод rect в `build-catalog.ts`, отвергнута: дублировали бы каталог.
3. **Буфер канваса при 150×100.** Рисуем в буфер 1:1 (2400×1600 px), зум — CSS-растяжение с `image-rendering: pixelated`: буфер не растёт с зумом (19200×12800 при ×8 упёрлись бы в лимиты Safari). Текст плашек «Другое» растягивается вместе с холстом — для наброска приемлемо.
4. **События мыши и вкладка.** `map-editor.js` слушает `window`-события (mousemove/mouseup панорамы и перетаскивания) — активны только при видимой вкладке (`mapView` скрыт — рано выходить по display; обработчики стартуют только из событий канваса, поэтому утечки поведения на другие вкладки нет: drag сбрасывается на mouseup). Если в живой приёмке заметны ложные срабатывания — добавить guard `if (document.getElementById('mapView').style.display === 'none') return;` в window-обработчики.
5. **Порядок наложения земель vs здание.** Земли позднего прямоугольника побеждают, но клетки здания/комнат/стен всегда дают тип `building` для автотайла (спека 6.1) — решено в модели двумя проходами (земли, затем занятость) и покрыто тестами задачи 1.
6. **Проверяемость без assets.** В ворктри нет `assets/`: модель и сборка каталога проверяются (`node --test`, `node build-catalog.ts`, `py_compile`, curl-роуты), всё визуальное — ручная приёмка в основном каталоге. Импорт `map-editor.js` в Node (`await import`) страхует от синтаксических ошибок DOM-задач.

