# PixelOffice v2 MVP (M0–M5): план реализации

> **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:** браузерный пиксель-арт офис, где персонажи людей (Nextcloud) и ИИ-агентов (hooks Claude Code) двигаются по статусам. Мир живёт на сервере и общий для всех зрителей.

**Architecture:** pnpm-монорепо на TypeScript 7. Чистое ядро `packages/core` (схема офиса, каталог, валидация, A\*, правила, симуляция) без I/O. `packages/server` (Fastify 5) владеет миром: принимает события `POST /v1/events`, хранит статусы с JSONL-логом, крутит симуляцию с шагом 50 мс и шлёт зрителям `hello`/`delta` по WebSocket. `packages/viewer` (Vite + PixiJS 8) только рисует. Адаптеры и реплей — отдельные процессы, которые говорят с тем же HTTP API.

**Tech Stack:** Node 24 LTS (type stripping, без сборки серверного кода), TypeScript 7 (`tsc` только как CLI-тайпчекер), pnpm 12 workspaces, Vitest 5, Fastify 5 + @fastify/websocket + @fastify/static, zod 4, yaml 2, PixiJS 8 + pixi-viewport 6, Playwright, picomatch.

**Источник правды:** спека `docs/superpowers/specs/2026-10-20-pixeloffice-v2-design.md` (далее «спека», ссылки вида «спека 4.3»). Архитектурные решения спеки план не пересматривает.

## Global Constraints

Каждая задача неявно включает все пункты этого раздела.

1. **Окружение.** Node `24.22 LTS (Krypton)` из `brew install node@24`. Формула keg-only, глобальный node 23 не трогаем. **Каждый** блок shell-команд выполнять из корня репозитория и начинать строкой ENV:
   ```bash
   cd /Users/stas/Projects/My/PixelOffice && export PATH="/opt/homebrew/opt/node@24/bin:$PATH" COREPACK_ENABLE_DOWNLOAD_PROMPT=0
   ```
   Ниже в блоках команд эта строка подразумевается. Проверка: `node --version` печатает `v24.*`.
2. **pnpm** `12.14` через corepack и поле `packageManager` корневого `package.json`.
3. **Версии зависимостей** — новейшие стабильные на момент исполнения: ставить через `pnpm add <pkg>@latest`, `.npmrc` с `save-exact=true` пинит точную версию. Таблица спеки 2 — ориентир: TypeScript 7.0.2, Vite 8.3.4, Vitest 5.0.5, pixi.js 8.22.0, pixi-viewport 6.0.3, Fastify 5.12.7, @fastify/websocket 11.3.4, @fastify/static 10.1.6, zod 4.6.7, yaml 2.9.1, Playwright 1.64.1. Исключение: `@types/node` — последняя `24.x`, под рантайм.
4. **TypeScript 7:** `strict`, `noUnusedLocals`, `noUnusedParameters`. Тайпчек только CLI `tsc` 7. Инструменты, которым нужен TS API (typescript-eslint с type-aware правилами, vite-plugin-checker, генераторы `.d.ts`), не используем (спека 2).
5. **Node type stripping:** серверный и инструментальный код запускается как `node file.ts` без сборки. Отсюда: нет `enum`, `namespace`, parameter properties (`constructor(private x)`), в tsconfig `erasableSyntaxOnly: true`. Относительные импорты пишем с расширением `.ts`. Импорты типов — через `import type` (`verbatimModuleSyntax: true`).
6. **Правила зависимостей (спека 3, дословно):** «`core` зависит только от `protocol`, `zod` и `yaml` (чистые библиотеки без Node-API; разбор YAML живёт в `core`); `core` и `protocol` не импортируют Node-API, DOM и PixiJS; `viewer` импортирует из `protocol` (и чистые хелперы `core` при необходимости), но не `server`». Тесты `core` могут читать файлы через `node:fs`, исходники `core/src` не могут: это проверяет тест `packages/core/tests/purity.test.ts`.
7. **Библиотеку `pathfinding` не используем**, A\* своя (спека 2).
8. **PNG не коммитятся** (лицензия LimeZu, спека 8), эталонные скриншоты тоже: `.gitignore` уже содержит `*.png` и `assets/`. Тесты, которым нужны ассеты, без `assetsDir` помечаются skipped.
9. **Гейт каждой задачи:** `pnpm test`, `pnpm typecheck` и, начиная с задачи 9, `pnpm validate:maps` (структурная валидация всех карт `offices/`). Все три вместе запускает `pnpm gate`. При наличии `~/tmp` (assetsDir) `validate:maps` ещё проверяет атлас. Скриншот-тесты (`pnpm test:visual`) — с задачи 28.
10. **Визуальные задачи** (3, 25, 26, 27, 28) не считаются готовыми без скриншота headless-браузером, который исполнитель открыл (Read tool) и проверил глазами по критериям задачи.
11. **Git:** работа идёт в ветке `feat/v2-mvp` от `master`. Merge и push не делаем. Коммиты — Conventional Commits с русской темой (`feat(core): …`), **без эмодзи, без `Co-Authored-By` и без упоминаний Claude/ИИ**. Коммит в конце каждой задачи.
12. **Внешние системы не меняем:** `~/.claude/settings.json` не трогаем (hook — только README-фрагмент), реального деплоя нет, в Nextcloud не пишем. Живые проверки Nextcloud и hook-а проектируются как ручные шаги человека с местом для результата в `docs/spikes/`. Уведомления и гейты — дело исполняющего скилла (контроллера SDD): после каждой завершённой задачи он шлёт короткий прогресс `tg-me -t 191 -m "…"` (без `-w`, правило проекта — прогресс в Telegram-топик 191). Субагенты-имплементеры отдельных задач tg-me и другие внешние записи не используют.
13. **Язык:** комментарии в коде, сообщения ошибок и логов — по-русски. Идентификаторы — по-английски.
14. **Кредит LimeZu** (`limezu.itch.io`) — в подвале viewer и в README (спека 8).
15. **`docs/` в `.gitignore`:** заметки спайков и результаты ручных проверок лежат в `docs/spikes/` только на диске и не коммитятся.

## Решения, принятые при планировании

Пользователь AFK; решения ниже приняты автономно. Если исполнение их опровергнет, правится план, а не спека.

1. **Node 24:** `brew install node@24` (keg-only) + префикс `PATH` в каждой команде. pnpm ставит `corepack enable pnpm` из node@24: шимы ложатся в bin кега и глобальный node 23 не задевают. Запасной путь, если corepack сломан (подписи, сеть): `npm i -g pnpm@12.14.0` тем же npm из node@24.
2. **Без сборки серверного кода:** workspace-пакеты экспортируют `./src/index.ts`, Node 24 исполняет TS через type stripping. Запасной путь, если Node откажется стрипать типы в symlink-пакетах (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`): devDependency `tsx`, запуск `tsx file.ts`. Код не меняется.
3. **Тайпчек по пакетам:** у каждого пакета `tsconfig.json` (только `src`) и `tsconfig.test.json` (`src` + `tests`, с `@types/node`). У `core` и `protocol` в `src` `lib: ["ES2024"]`, `types: []`, поэтому случайный `process`/`document` в исходниках ядра падает на тайпчеке. Корневой `pnpm typecheck` = `pnpm -r run typecheck`.
4. **Офис для тестов `offices/demo`** (9 человек, две переговорки, комната отдыха, коворкинг, кресла в 4 направлениях). Его используют тестовый режим сервера, сценарии реплея и скриншот-тесты. `offices/local` — личный офис пользователя, `offices/team` — командный (M5).
5. **Секреты не коммитим:** у `local` и `team` в git лежит только `config.example.yaml`, рабочий `config.yaml` игнорируется (`offices/*/config.yaml`) и создаётся командой `node packages/server/src/main.ts init offices/local`, которая подставляет случайные токены. У `demo` `config.yaml` коммитится, токены в нём тестовые.
6. **Поле `catalog` в `config.yaml`** (по умолчанию `../../catalog/limezu/catalog.yaml` относительно каталога офиса). В примере спеки 9 его нет, без него сервер не знает, где каталог. Относительные `dataDir`/`assetsDir` считаются от каталога конфига, `~` раскрывается при загрузке.
7. **Чтение файлов офиса с диска и проверка атласа** живут в `tools/validate-maps` (Node-код: `readOfficeTexts`, `expandHome`, `checkAtlas`). Его используют CLI `pnpm validate:maps` и сервер. Размер PNG читается из заголовка IHDR без библиотек.
8. **Схема каталога** (задача 3) — YAML: `sheets`, `floors`, `items` с `variants` → `{default|up|down|left|right: {parts, spots}}`, у стены `autotile.rules` (первое совпадение маски соседей), раздел `characters`. M0 подтверждает или правит схему. Если правит, исполнитель M0 вносит изменения в задачи 6, 11 и 12 этого плана до их старта.
9. **Стены рисуются «вверх от клетки»**, как высокий предмет: grid остаётся с однорядными стенами `#`, лицевая сторона (в Room Builder Office она 2 тайла высотой) уходит вверх за край клетки. Спайк M0(а) может выбрать другой вариант (спека 5.1 оставляет это ему), тогда он правит задачу 11.
10. **Аркада** — предмет 1×2: верхняя клетка блокирует (автомат), нижняя — место `play` лицом вверх. Кандидат спрайта — `1_Interiors/16x16/Theme_Sorter/14_Basement_16x16.png` (внизу слева ряд игровых автоматов). Там же диваны, пинг-понг и бильярд.
11. **Доска (`whiteboard`)** 1×2 со стоячим местом `stand` — источник мест `meeting_room_standing`.
12. **Облачко `needs_input` гаснет**, когда принятый статус уходит из `needs_input`: иначе запрос разрешения висел бы после ответа. Остальные облачка живут свои `ttlSec`.
13. **`setRules` при горячей перезагрузке** сразу переназначает цели всем персонажам. Занятое место предпочитается, поэтому без нужды никто не встаёт.
14. **Доступ зрителя:** токен из `?token=` на `/` или через `GET /v1/session?token=` (нужен dev-режиму Vite с прокси) ставит HttpOnly-cookie `po_viewer`. WebSocket принимает и cookie, и `?token=`. Cookie разбирается вручную, без `@fastify/cookie`.
15. **Vite собирает бандл в `dist/app/`** (`build.assetsDir: 'app'`), чтобы не конфликтовать с префиксом ассетов LimeZu `/assets/`.
16. **Пиксельный шрифт** — Press Start 2P из npm-пакета `@fontsource/press-start-2p` (OFL, есть кириллица), Pixi `BitmapFont` 8 px. Подписи и облачка держат постоянный экранный размер: масштаб `1/zoom`. Альтернатива — Pixelify Sans.
17. **Сообщение `debug`** (пути и брони) сервер шлёт всем зрителям раз в секунду. Viewer показывает его по клавише `D`.
18. **`delta`** — конверт `{ type: 'delta', t, characters: [...] }`. У персонажа есть поле `offset` (сдвиг спрайта из места, спека 5.2), которого нет в перечне спеки 4.6: без него viewer не знает сдвиг.
19. **Источники и сущности (403):** источник без `owner` — «человеческий», адресует только людей по `entityId`. Источник с `owner` — агентский, адресует только агентов через `agent`. Сущность закрепляется за первым приславшим её источником. Другой источник → 403. Событие с неизвестным человеком игнорируется с warn и отвечается 200.
20. **Ответ `POST /v1/events`** — `200 { accepted, ignored }`. Пакет проходит проверку 401/400/403 целиком («всё или ничего»), потом применяется.
21. **Тестовый режим** доступен только с флагом `--test`: слушает `127.0.0.1`, маршрута `POST /v1/events` нет. Токен зрителя — из конфига офиса (`demo-viewer-token` у `offices/demo`).
22. **Реплей пишет `at` в момент отправки.** Для сценариев время события — смещение `atMs`, в тестовом режиме время считается от управляемых часов.
23. **Hook Claude Code** запускается как `/opt/homebrew/opt/node@24/bin/node <repo>/adapters/claude-hook/src/main.ts`: абсолютный путь к node 24, без `#!/usr/bin/env node`, потому что в сессии первым в PATH стоит node 23. `ttlSec` hook не шлёт: умолчания по статусам берутся из `config.yaml` (спека 9).

## Структура файлов

```
package.json, pnpm-workspace.yaml, tsconfig.base.json, vitest.config.ts, .npmrc, .node-version, README.md
packages/
  protocol/src/{common,avatar,events,ws,index}.ts            — zod-схемы API, типы WS (без I/O)
  core/src/
    errors.ts, yaml.ts, duration.ts, random.ts              — Result/MapError, разбор YAML через zod, длительности, хеш/ГПСЧ
    catalog.ts                                              — схема и загрузка catalog.yaml
    office.ts                                               — разбор office.yaml (grid, legend, placements, zones)
    config.ts, rules.ts                                     — config.yaml, rules.yaml
    world-map.ts, validate.ts, bundle.ts                    — WorldMap, структурная валидация, загрузка офиса целиком
    path/heap.ts, path/astar.ts                             — A*
    render-map.ts, characters.ts                            — RenderedMap для hello, слои/кадры персонажей
    sim/types.ts, sim/meetings.ts, sim/targets.ts, sim/world.ts — типы симуляции, переговорки, разрешение целей, симуляция
    index.ts
  server/src/
    clock.ts, logger.ts, office.ts                          — часы, логгер, загрузка офиса с диска
    store.ts, registry.ts, runtime.ts                       — Status Store, сущности, связка store↔world↔ingest
    persistence.ts                                          — JSONL-лог, state.json
    http.ts, loop.ts, rules-watch.ts, test-mode.ts, relay.ts, main.ts, index.ts
  viewer/
    index.html, vite.config.ts, playwright.config.ts
    src/{main,connection,state,params}.ts, src/global.d.ts, src/render/{scene,office,characters,labels,bubbles,debug,font,view}.ts
    scripts/shot.ts                                          — headless-скриншот для визуальных проверок
    tests/unit/*.test.ts, tests/visual/*.spec.ts, tests/__screenshots__/ (вне git)
adapters/
  claude-hook/src/{map,config,main}.ts, README.md
  nextcloud/src/{ocs,map,bubbles,poller,main}.ts, scripts/spike.ts, tests/fixtures/*.json
tools/
  replay/src/{scenarios,play,cli,index}.ts                  — сценарии и реплей
  validate-maps/src/{read,validate,atlas,cli,index}.ts      — файлы офиса с диска, валидация offices/, проверка атласа, CLI
  spike/                                                    — одноразовый спайк M0(а), удаляется в задаче 28
catalog/limezu/catalog.yaml
offices/{local,demo,team}/{office.yaml,rules.yaml,config.example.yaml|config.yaml}, offices/team/README.md
```

## Ключевые контракты (сводка)

Полные определения — в задачах, где они создаются. Здесь сводка имён, чтобы соседние задачи не разошлись.

| Модуль | Экспорт |
|---|---|
| `@pixeloffice/protocol` | `Facing`, `Pose`, `Status`, `HumanStatus`, `AgentStatus`, `AvatarParts`, `Entity`, `AgentRef`, `Event`, `EventsBodySchema`, `formatIssues`, `Frame`, `RenderedMap`, `CharacterLayout`, `AnimName`, `EntityView`, `Bubble`, `CharacterState`, `HelloMessage`, `DeltaMessage`, `DebugMessage`, `ServerMessage`, `PROTOCOL_VERSION` |
| `core/errors` | `MapError`, `Result<T>`, `ok`, `fail`, `formatErrors` |
| `core/catalog` | `Catalog`, `ItemDef`, `Part`, `SpotDef`, `ItemView`, `CharactersDef`, `loadCatalog(text, file?)`, `itemView(def, facing, variant)` |
| `core/office` | `OfficeLayout`, `PlacedItem`, `Zone`, `CellKind`, `parseOffice(text, catalog, file?)`, `zoneContains`, `zoneAt` |
| `core/config` | `OfficeConfig`, `SourceConfig`, `Person`, `parseConfig(text, file?)` |
| `core/rules` | `Rules`, `RuleTarget`, `parseRules(text, file?, zoneIds?)`, `parseTarget` |
| `core/world-map` | `WorldMap`, `Spot`, `buildWorldMap(layout, catalog, file?)` |
| `core/validate` | `validateWorld(map, config, file?)`, `reachableFrom(map, start)` |
| `core/bundle` | `OfficeTexts`, `OfficeBundle`, `loadOfficeBundle(texts)` |
| `core/path/astar` | `Cell`, `findPath(map, from, to)` |
| `core/render-map` | `renderMap(layout, map, catalog, assetUrl?)`, `defaultAssetUrl` |
| `core/characters` | `fillTemplate`, `avatarLayerPaths`, `avatarFromKey`, `animFor`, `frameRect`, `characterLayout` |
| `core/random` | `fnv1a`, `mulberry32` |
| `core/sim` | `MeetingRooms`, `resolveTargets`, `World`, `SimEntity` |
| `validate-maps` | `readOfficeTexts(dir)`, `expandHome(p)`, `resolveFrom(base, p)`, `checkAtlas(catalog, people, assetsDir)`, `readPngSize(path)`, `validateOfficesDir(root)` |
| `server` | `Clock`, `ManualClock`, `systemClock`, `Logger`, `loadOffice(dir)`, `StatusStore`, `EntityRegistry`, `agentKey`, `OfficeRuntime`, `Persistence`, `buildServer`, `startLoop`, `watchRules`, `renderScenarioHello`, `Relay` |
| `@pixeloffice/replay` | `Scenario`, `ScenarioEvent`, `ScenarioContext`, `scenarios`, `resolveScenarioSource`, `playTimed` |
| `adapter-claude-hook` | `HookInput`, `mapHook(input, env, now)`, `NEEDS_INPUT_BUBBLE_TTL`, `HookConfig`, `loadHookConfig(env, home?)` |
| `adapter-nextcloud` | `OcsAuth`, `OcsError`, `ocsGet`, `buildSnapshot`, `TalkBubbles`, `renderText`, `pollOnce` |

---

## Этап 0. Bootstrap

### Задача 1: ветка, тулчейн и каркас монорепо

**Files:**
- Create: `package.json`, `pnpm-workspace.yaml`, `.npmrc`, `.node-version`, `tsconfig.base.json`, `vitest.config.ts`, `README.md`
- Create: `packages/protocol/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts,src/index.ts,tests/smoke.test.ts}`
- Create: `packages/core/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts,src/index.ts,tests/smoke.test.ts,tests/purity.test.ts}`
- Modify: `.gitignore`

**Interfaces:**
- Consumes: ничего.
- Produces: workspace-пакеты `@pixeloffice/protocol` и `@pixeloffice/core` (exports `./src/index.ts`), корневые скрипты `test`, `typecheck`, `gate`, шаблон tsconfig/vitest для следующих пакетов.

- [ ] **Step 1: ветка**

```bash
git status --short          # ожидается пусто
git checkout -b feat/v2-mvp master
```

- [ ] **Step 2: Node 24 и pnpm**

```bash
brew list node@24 >/dev/null 2>&1 || brew install node@24
export PATH="/opt/homebrew/opt/node@24/bin:$PATH" COREPACK_ENABLE_DOWNLOAD_PROMPT=0
node --version                       # v24.22.x или новее 24.x
corepack enable pnpm                 # шимы в bin кега node@24
```

Если `corepack enable` падает: `npm i -g pnpm@12.14.0` (npm из node@24 ставит в префикс кега). Глобальный `/opt/homebrew/bin/node` (23.x) не трогать.

- [ ] **Step 3: корневые файлы**

`package.json`:
```json
{
  "name": "pixeloffice",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@12.14.0",
  "engines": { "node": ">=24.22 <25" },
  "scripts": {
    "test": "vitest run",
    "typecheck": "pnpm -r --sort run typecheck",
    "gate": "pnpm test && pnpm typecheck"
  }
}
```

`pnpm-workspace.yaml`:
```yaml
packages:
  - packages/*
  - adapters/*
  - tools/*
```

`.npmrc`:
```
save-exact=true
engine-strict=true
```

`.node-version`: `24.22.0`

`tsconfig.base.json`:
```json
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "allowImportingTsExtensions": true,
    "isolatedModules": true,
    "noEmit": true,
    "skipLibCheck": true,
    "resolveJsonModule": true
  }
}
```

`vitest.config.ts`:
```ts
import { defineConfig } from 'vitest/config';

// Каждый пакет — отдельный проект со своим vitest.config.ts.
export default defineConfig({
  test: {
    projects: ['packages/*/vitest.config.ts', 'adapters/*/vitest.config.ts', 'tools/*/vitest.config.ts'],
  },
});
```

В `.gitignore` дописать:
```
.data/
offices/*/config.yaml
!offices/demo/config.yaml
```

`README.md`:
```markdown
# PixelOffice

Пиксель-арт офис в браузере: персонажи отражают статусы людей и ИИ-агентов.

Требуется Node 24 (`brew install node@24`, затем `export PATH="/opt/homebrew/opt/node@24/bin:$PATH"`) и pnpm через corepack.

Арт: платные паки LimeZu — Modern Office Revamped и Modern Interiors (limezu.itch.io). Ассеты в репозиторий не входят.
```

- [ ] **Step 4: пакет protocol — сначала падающий тест**

`packages/protocol/package.json`:
```json
{
  "name": "@pixeloffice/protocol",
  "private": true,
  "type": "module",
  "exports": { ".": "./src/index.ts" },
  "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json" }
}
```

`packages/protocol/tsconfig.json` (исходники без Node-типов и DOM):
```json
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024"], "types": [] }, "include": ["src"] }
```

`packages/protocol/tsconfig.test.json`:
```json
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024"], "types": ["node"] }, "include": ["src", "tests"] }
```

`packages/protocol/vitest.config.ts`:
```ts
import { defineProject } from 'vitest/config';

export default defineProject({ test: { name: 'protocol', include: ['tests/**/*.test.ts'] } });
```

`packages/protocol/tests/smoke.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { PROTOCOL_VERSION } from '../src/index.ts';

describe('protocol', () => {
  it('версия протокола 1', () => {
    expect(PROTOCOL_VERSION).toBe(1);
  });
});
```

- [ ] **Step 5: зависимости и проверка падения**

```bash
pnpm add -w -D typescript@latest vitest@latest @types/node@24
pnpm --filter @pixeloffice/protocol add zod@latest
pnpm test
```
Expected: FAIL — `Cannot find module '../src/index.ts'` (или «Failed to load»).

Если pnpm сообщает о заблокированных build-скриптах зависимостей — выполнить `pnpm approve-builds` и разрешить только нужные (esbuild/rolldown-бинарники, если спросит).

- [ ] **Step 6: минимальный код protocol**

`packages/protocol/src/index.ts`:
```ts
// Публичный API протокола PixelOffice. Наполняется в задаче 5.
export const PROTOCOL_VERSION = 1;
```

- [ ] **Step 7: пакет core с тестом чистоты**

`packages/core/package.json`:
```json
{
  "name": "@pixeloffice/core",
  "private": true,
  "type": "module",
  "exports": { ".": "./src/index.ts" },
  "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json" },
  "dependencies": { "@pixeloffice/protocol": "workspace:*" }
}
```

`packages/core/tsconfig.json`, `tsconfig.test.json`, `vitest.config.ts` — как у protocol (в vitest `name: 'core'`).

`packages/core/tests/smoke.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { PROTOCOL_VERSION } from '../src/index.ts';

describe('core', () => {
  it('видит workspace-пакет protocol', () => {
    expect(PROTOCOL_VERSION).toBe(1);
  });
});
```

`packages/core/tests/purity.test.ts`:
```ts
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

// Спека 3: core и protocol не импортируют Node-API, DOM и PixiJS.
const ROOTS = ['../src/', '../../protocol/src/'].map((p) => fileURLToPath(new URL(p, import.meta.url)));
const FORBIDDEN_IMPORT =
  /from\s+['"](node:[^'"]+|fs|path|os|child_process|http|https|url|pixi\.js|pixi-viewport|fastify|@fastify\/[^'"]+|@pixeloffice\/(server|viewer)[^'"]*)['"]/;
const FORBIDDEN_GLOBAL = /\b(process\.|document\.|window\.|require\()/;

function tsFiles(dir: string): string[] {
  return readdirSync(dir).flatMap((name) => {
    const p = join(dir, name);
    if (statSync(p).isDirectory()) return tsFiles(p);
    return p.endsWith('.ts') ? [p] : [];
  });
}

describe('чистота core и protocol', () => {
  for (const root of ROOTS) {
    it(`нет Node-API, DOM и PixiJS в ${root}`, () => {
      const bad: string[] = [];
      for (const file of tsFiles(root)) {
        readFileSync(file, 'utf8')
          .split('\n')
          .forEach((line, i) => {
            if (FORBIDDEN_IMPORT.test(line) || FORBIDDEN_GLOBAL.test(line)) bad.push(`${file}:${i + 1}: ${line.trim()}`);
          });
      }
      expect(bad).toEqual([]);
    });
  }
});
```

`packages/core/src/index.ts`:
```ts
// Публичный API ядра. Наполняется задачами 6–15.
export { PROTOCOL_VERSION } from '@pixeloffice/protocol';
```

```bash
pnpm --filter @pixeloffice/core add zod@latest yaml@latest
pnpm install
```

- [ ] **Step 8: гейт**

```bash
pnpm gate
```
Expected: 4 теста PASS в 3 файлах (protocol smoke, core smoke, purity ×2), typecheck без ошибок.

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

```bash
git add -A
git status --short     # убедиться: нет *.png, нет node_modules
git commit -m "chore: каркас монорепо на pnpm, TypeScript 7 и Vitest"
```

**Критерий готовности:** ветка `feat/v2-mvp`, `node --version` = v24, `pnpm --version` = 12.x, `pnpm gate` зелёный.

---

## Этап M0. Спайки

### Задача 2: M0(а) — разведка ассетов LimeZu

Цель: перед каталогом зафиксировать по факту раскладку кадров персонажей и координаты нужных предметов. Урок v1: координаты атласа угадывали (манифест `PixelOffice_bak/src/tileset/manifests/limezuOffice.ts` весь из `col: 0..6, row: 0..1` наугад).

**Files:**
- Create (вне git): `docs/spikes/2026-10-20-m0-art.md`, `docs/spikes/m0-art/*.png`
- Временные скрипты — в scratchpad-каталоге сессии исполнителя (или `mktemp -d`), не в репозитории.

**Interfaces:**
- Consumes: ассеты в `~/tmp`.
- Produces: заметка с координатами (x, y, w, h в пикселях листа) для: пол ×3 (`carpet_grey`, `wood`, `tiles_blue`), стена (куски автотайлинга и проём входа), `desk`, `chair` ×4 направления (сиденье и спинка отдельно), `monitor` (перед/зад), `ficus`, `arcade`, `sofa`, `meeting_table`, `whiteboard`; подтверждённая раскладка генератора персонажей.

Уже известно (проверено при планировании, перепроверить):

1. Листы офиса: `~/tmp/Modern_Office_Revamped_v1.2/Modern_Office_16x16.png` (256×848), стены и полы — `~/tmp/Modern_Office_Revamped_v1.2/1_Room_Builder_Office/Room_Builder_Office_16x16.png` (256×224). В Room Builder ряды 0–3 (y 0–63) — верхние кромки стен (углы, Т, торцы); ряды 5–12 — лицевые стороны стен по 2 тайла высотой (4 стиля, колонки 0–9); колонки 10–15 рядов 5–12 — полы. Поштучные предметы без имён: `4_Modern_Office_singles/16x16/Modern_Office_Singles_N.png` (339 файлов).
2. Аркада, диваны, пинг-понг, бильярд: `~/tmp/modern-interiors/moderninteriors-win/1_Interiors/16x16/Theme_Sorter/14_Basement_16x16.png` (256×800), игровые автоматы — внизу слева (y ≈ 660–700).
3. Генератор персонажей: `~/tmp/modern-interiors/moderninteriors-win/2_Characters/Character_Generator/`. Порядок слоёв (`CHARACTER_GENERATOR.txt`): Body → Eyes → Outfit → Hairstyle → Accessory. Файлы 16×16: `Bodies/16x16/Body_01..09.png`, `Eyes/16x16/Eyes_01..07.png`, `Outfits/16x16/Outfit_MM_CC.png` (33 модели, у модели 01 10 цветов, у 02 4…), `Hairstyles/16x16/Hairstyle_MM_CC.png` (29 моделей), `Accessories/16x16/Accessory_MM_<Имя>_CC.png` (имя в файле, напр. `Accessory_01_Ladybug_03.png`).
4. Лист персонажа 896×656: кадры 16×32, 56 колонок, ряды по 32 px. Ряд 0 — 4 превью-кадра; ряд 1 (y=32) — idle, 24 кадра = 4 направления × 6; ряд 2 (y=64) — walk, так же; порядок направлений в idle/walk: **right (кол. 0–5), up (6–11), left (12–17), down (18–23)**. Ряд 3 — sleep; ряды 4 и 5 (y=128, y=160) — два варианта sit по 12 кадров = right (0–5) + left (6–11); ряд 6 — phone (лицом вниз); ряд 7 — чтение книги. Сидячих кадров лицом вверх и вниз нет (спека 5.2).
5. Все `Bodies/16x16/Body_01..09.png` шириной 927 px (927×656), непустой хвост за x=896 только у `Body_01`: пиксели в x 898–924, y 368–416, вне рядов 0–7. Слои накладываются в (0,0).

- [ ] **Step 1: хелпер контакт-листа (Python/PIL уже есть: `python3 -c "import PIL"`)**

Сохранить в scratchpad как `grid.py`:
```python
import sys
from PIL import Image, ImageDraw
# grid.py <png> <out.png> <масштаб> [cell=16] — лист с сеткой и подписями «col,row»
src, out, k = sys.argv[1], sys.argv[2], int(sys.argv[3])
cell = int(sys.argv[4]) if len(sys.argv) > 4 else 16
im = Image.open(src).convert('RGBA')
bg = Image.new('RGBA', im.size, (255, 0, 255, 255)); bg.alpha_composite(im)
bg = bg.resize((im.width * k, im.height * k), Image.NEAREST)
d = ImageDraw.Draw(bg)
for x in range(0, bg.width, cell * k): d.line([(x, 0), (x, bg.height)], fill=(0, 0, 0, 255))
for y in range(0, bg.height, cell * k): d.line([(0, y), (bg.width, y)], fill=(0, 0, 0, 255))
for cx in range(im.width // cell):
    for cy in range(im.height // cell):
        d.text((cx * cell * k + 1, cy * cell * k + 1), f"{cx},{cy}", fill=(255, 255, 255, 255))
bg.save(out)
```
Длинные листы резать по высоте (`im.crop((0, y0, 256, y0 + 256))`) — изображение больше ~2000 px по стороне не читается.

- [ ] **Step 2: контакт-листы и просмотр**

```bash
S=<scratchpad>
python3 -I $S/grid.py ~/tmp/Modern_Office_Revamped_v1.2/1_Room_Builder_Office/Room_Builder_Office_16x16.png $S/room.png 3
python3 -I $S/grid.py ~/tmp/Modern_Office_Revamped_v1.2/Modern_Office_16x16.png $S/office.png 2
python3 -I $S/grid.py ~/tmp/modern-interiors/moderninteriors-win/1_Interiors/16x16/Theme_Sorter/14_Basement_16x16.png $S/basement.png 2
```
Открыть каждый PNG (Read tool) кусками, выписать координаты в заметку. Для кресла найти 4 направления и разделить на сиденье и спинку: спинка сортируется отдельно (спека 5.2 `parts`).

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

Сложить слои в scratchpad и посмотреть ряды 0–7 с сеткой 16×32:
```python
import sys
from PIL import Image
G = '/Users/stas/tmp/modern-interiors/moderninteriors-win/2_Characters/Character_Generator/'
layers = [G + 'Bodies/16x16/Body_03.png', G + 'Eyes/16x16/Eyes_02.png', G + 'Outfits/16x16/Outfit_01_01.png', G + 'Hairstyles/16x16/Hairstyle_01_01.png']
base = Image.new('RGBA', (927, 656))
for p in layers: base.alpha_composite(Image.open(p).convert('RGBA'), (0, 0))
base.crop((0, 0, 24 * 16, 8 * 32)).resize((24 * 64, 8 * 128), Image.NEAREST).save(sys.argv[1])
```
Подтвердить факты 4–5 выше. Решить, какой ряд sit (4 или 5) годится для офисного кресла, и записать выбор с обоснованием.

- [ ] **Step 4: заметка `docs/spikes/2026-10-20-m0-art.md`**

Разделы: «Листы» (пути, размеры), «Персонажи» (таблица рядов и направлений, выбранный ряд sit, наблюдения по сдвигам при сидении), «Предметы» (таблица `item | лист | rect | размер в клетках | блокирует | части/sortY | места`), «Стены» (какие куски Room Builder — верх, лицо, углы, торцы, проём; высота лица), «Вопросы к схеме каталога».

- [ ] **Step 5: гейт**

`pnpm gate` — без изменений в репозитории, зелёный. Коммита нет: заметка в `docs/` вне git.

**Критерий готовности:** в заметке есть координаты всех предметов списка Produces и подтверждённая раскладка персонажа; каждое значение снято с контакт-листа, а не угадано.

---

### Задача 3: M0(а) — черновой каталог и спайк-рендер со скриншотом

**Files:**
- Create: `catalog/limezu/catalog.yaml`
- Create: `tools/spike/{package.json,tsconfig.json,index.html,vite.config.ts,src/main.ts,gen-pool.ts,shot.ts}`
- Create (вне git): `docs/spikes/m0-art/scene.png`; дополнить `docs/spikes/2026-10-20-m0-art.md`

**Interfaces:**
- Consumes: координаты из задачи 2.
- Produces: `catalog/limezu/catalog.yaml` по схеме ниже. Схему читают задачи 6, 11, 12 и 16. Если спайк её меняет — сразу поправить в этом плане задачи 6, 11, 12, 16 и записать изменение в заметку.

**Схема каталога (решение 8):**
```yaml
version: 1
tileSize: 16
sheets:                      # имя → путь PNG относительно assetsDir (~/tmp)
  office: Modern_Office_Revamped_v1.2/Modern_Office_16x16.png
  room: Modern_Office_Revamped_v1.2/1_Room_Builder_Office/Room_Builder_Office_16x16.png
  basement: modern-interiors/moderninteriors-win/1_Interiors/16x16/Theme_Sorter/14_Basement_16x16.png
floors:                      # тип пола → варианты тайла 16×16 (выбор по хешу клетки)
  carpet_grey: [ { sheet: room, rect: [176, 112, 16, 16] } ]   # стартовое значение (кол. 11, ряд 7) — сверить
  wood:        [ { sheet: room, rect: [208, 80, 16, 16] } ]    # стартовое значение (кол. 13, ряд 5) — сверить
  tiles_blue:  [ { sheet: room, rect: [160, 176, 16, 16] } ]   # стартовое значение — сверить
items:
  wall:
    size: [1, 1]
    blocks: all
    autotile:
      outside: 1             # клетка за краем карты считается стеной: у нижнего ряда стен «под ним стена» → только кромка,
                             # иначе лицо 2 тайла легло бы на последний ряд пола и перекрыло стоящих там персонажей
      rules:                 # первое совпадение; n,e,s,w,ne,se,sw,nw: 1 — стена, 0 — нет (вход E = 0); пропуск — любое
        - when: { s: 0 }     # под стеной пол → видна лицевая сторона
          parts:
            - { sheet: room, rect: [16, 80, 16, 32], at: [0, -16], sortY: 1 }   # лицо 2 тайла, вверх от клетки
            - { sheet: room, rect: [16, 16, 16, 16], at: [0, -32], sortY: 1 }   # верхняя кромка
        - when: {}           # иначе — только кромка
          parts:
            - { sheet: room, rect: [16, 16, 16, 16], at: [0, 0], sortY: 1 }
      door:                  # клетка E
        - { sheet: room, rect: [128, 0, 16, 16], at: [0, 0], sortY: 0 }
  desk:
    size: [2, 1]
    blocks: all
    variants:
      - default:
          parts: [ { sheet: office, rect: [0, 0, 32, 32], at: [0, -16], sortY: 1 } ]
  chair:
    size: [1, 1]
    blocks: none
    facings: [up, down, left, right]   # куда смотрит сидящий
    variants:
      - up:
          parts:
            - { sheet: office, rect: [0, 0, 16, 16], at: [0, 0], sortY: 0.5, name: seat }
            - { sheet: office, rect: [0, 0, 16, 16], at: [0, 0], sortY: 1.05, name: back }   # спинка перед сидящим
          spots: [ { cell: [0, 0], pose: sit, offset: [0, -4] } ]
        down:  { parts: [], spots: [ { cell: [0, 0], pose: sit, offset: [0, -4] } ] }
        left:  { parts: [], spots: [ { cell: [0, 0], pose: sit, offset: [0, 0] } ] }
        right: { parts: [], spots: [ { cell: [0, 0], pose: sit, offset: [0, 0] } ] }
  monitor: { size: [1, 1], blocks: none, variants: [ { default: { parts: [] } }, { default: { parts: [] } } ] }  # 1 — экран к зрителю, 2 — спиной
  ficus:   { size: [1, 1], blocks: all,  variants: [ { default: { parts: [] } } ] }
  arcade:
    size: [1, 2]
    blocks: [[0, 0]]
    variants:
      - default:
          parts: []
          spots: [ { cell: [0, 1], facing: up, pose: play } ]
  sofa:
    size: [2, 1]
    blocks: none
    variants:
      - default:
          parts: []
          spots: [ { cell: [0, 0], facing: down, pose: sit }, { cell: [1, 0], facing: down, pose: sit } ]
characters:
  frame: [16, 32]
  layers:                    # шаблоны путей относительно assetsDir; {x} — число с ведущим нулём до 2 знаков
    body: modern-interiors/moderninteriors-win/2_Characters/Character_Generator/Bodies/16x16/Body_{body}.png
    eyes: modern-interiors/moderninteriors-win/2_Characters/Character_Generator/Eyes/16x16/Eyes_{eyes}.png
    outfit: modern-interiors/moderninteriors-win/2_Characters/Character_Generator/Outfits/16x16/Outfit_{model}_{color}.png
    hair: modern-interiors/moderninteriors-win/2_Characters/Character_Generator/Hairstyles/16x16/Hairstyle_{model}_{color}.png
    accessory: modern-interiors/moderninteriors-win/2_Characters/Character_Generator/Accessories/16x16/Accessory_{model}_{name}_{color}.png
  animations:                # row — ряд листа (в кадрах высотой frame[1]); dirs — колонка начала по направлению
    idle: { row: 1, frames: 6, dirs: { right: 0, up: 6, left: 12, down: 18 } }
    walk: { row: 2, frames: 6, dirs: { right: 0, up: 6, left: 12, down: 18 } }
    sit:  { row: 4, frames: 6, dirs: { right: 0, left: 6 } }
  poses:                     # поза + направление → анимация; сидение лицом вверх/вниз — кадр walk (спека 5.2)
    sit:   { up: walk, down: walk, left: sit, right: sit }
    stand: { up: idle, down: idle, left: idle, right: idle }
    play:  { up: idle, down: idle, left: idle, right: idle }
  accessoryNames: {}         # заполняет gen-pool.ts
  pool: { bodies: [], eyes: [], outfits: {}, hairs: {} }   # заполняет gen-pool.ts
```

Все `rect` с пометкой «сверить» и пустые `parts: []` спайк заменяет координатами из заметки задачи 2. Единицы: `rect` и `at` — пиксели; `at` — смещение левого верхнего угла части от левого верхнего угла предмета; `sortY` — в клетках от верха предмета (абсолютная линия = `(y + sortY) * tileSize`); `offset` места — пиксели.

- [ ] **Step 1: пакет спайка**

`tools/spike/package.json`:
```json
{
  "name": "@pixeloffice/spike",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "typecheck": "tsc -p tsconfig.json"
  }
}
```

```bash
pnpm --filter @pixeloffice/spike add pixi.js@latest yaml@latest
pnpm --filter @pixeloffice/spike add -D vite@latest @playwright/test@latest
pnpm --filter @pixeloffice/spike exec playwright install chromium
```

`tools/spike/tsconfig.json`:
```json
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024", "DOM", "DOM.Iterable"], "types": ["node", "vite/client"] }, "include": ["src", "*.ts"] }
```

`tools/spike/vite.config.ts`:
```ts
import { createReadStream, existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { defineConfig, type Plugin } from 'vite';

const ASSETS = join(homedir(), 'tmp');
const CATALOG = resolve(import.meta.dirname, '../../catalog/limezu/catalog.yaml');

// Раздаёт /catalog.yaml и /assets/* из ~/tmp — только для локального спайка.
function spikeFiles(): Plugin {
  return {
    name: 'spike-files',
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        const url = decodeURIComponent((req.url ?? '').split('?')[0] ?? '');
        const file = url === '/catalog.yaml' ? CATALOG : url.startsWith('/assets/') ? join(ASSETS, url.slice(8)) : null;
        // Из ~/tmp — только PNG: там лежат и личные файлы.
        if (!file || (file !== CATALOG && (!file.startsWith(ASSETS + '/') || !file.endsWith('.png'))) || !existsSync(file)) return next();
        res.setHeader('content-type', file.endsWith('.png') ? 'image/png' : 'text/yaml; charset=utf-8');
        createReadStream(file).pipe(res);
      });
    },
  };
}

export default defineConfig({ plugins: [spikeFiles()], server: { port: 5199, strictPort: true } });
```

`tools/spike/index.html`:
```html
<!doctype html>
<html lang="ru">
  <head><meta charset="utf-8" /><title>PixelOffice — спайк M0</title><style>body{margin:0;background:#222}</style></head>
  <body><script type="module" src="/src/main.ts"></script></body>
</html>
```

- [ ] **Step 2: генератор пула аватаров**

`tools/spike/gen-pool.ts`:
```ts
import { readdirSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { stringify } from 'yaml';

// Печатает accessoryNames и pool для раздела characters каталога.
const ROOT = join(homedir(), 'tmp/modern-interiors/moderninteriors-win/2_Characters/Character_Generator');
const matches = (dir: string, re: RegExp) =>
  readdirSync(join(ROOT, dir))
    .map((f) => re.exec(f))
    .filter((m): m is RegExpExecArray => m !== null);
const numbers = (dir: string, re: RegExp) => matches(dir, re).map((m) => Number(m[1])).sort((a, b) => a - b);

function models(dir: string, re: RegExp): Record<string, number> {
  const colors = new Map<number, number[]>();
  for (const m of matches(dir, re)) {
    const model = Number(m[1]);
    colors.set(model, [...(colors.get(model) ?? []), Number(m[2])]);
  }
  const out: Record<string, number> = {};
  for (const [model, list] of [...colors].sort((a, b) => a[0] - b[0])) {
    const max = Math.max(...list);
    if (list.length !== max) console.error(`ВНИМАНИЕ: ${dir} модель ${model}: цвета не подряд (${list.sort((a, b) => a - b).join(',')})`);
    out[String(model)] = max;
  }
  return out;
}

const accessoryNames: Record<string, string> = {};
for (const m of matches('Accessories/16x16', /^Accessory_(\d+)_(.+)_(\d+)\.png$/)) accessoryNames[String(Number(m[1]))] = m[2] ?? '';

console.log(
  stringify({
    accessoryNames,
    pool: {
      bodies: numbers('Bodies/16x16', /^Body_(\d+)\.png$/),
      eyes: numbers('Eyes/16x16', /^Eyes_(\d+)\.png$/),
      outfits: models('Outfits/16x16', /^Outfit_(\d+)_(\d+)\.png$/),
      hairs: models('Hairstyles/16x16', /^Hairstyle_(\d+)_(\d+)\.png$/),
    },
  }),
);
```

```bash
node tools/spike/gen-pool.ts
```
Вывод вставить в `characters` каталога. Если есть «цвета не подряд» — записать в заметку и перечислять такие модели списком цветов (тогда в задаче 6 `pool.outfits` становится `record<string, number[]>`; поправить задачи 6 и 12).

- [ ] **Step 3: спайк-рендер**

`tools/spike/src/main.ts`:
```ts
import { Application, Assets, Container, Rectangle, Sprite, Texture, TextureSource } from 'pixi.js';
import { parse } from 'yaml';

// Одноразовый спайк M0(а): читает каталог и рисует тестовую сцену. Удаляется в задаче 28.
type Rect = [number, number, number, number];
type Part = { sheet: string; rect: Rect; at?: [number, number]; sortY: number };
type Spot = { cell: [number, number]; facing?: string; pose: string; offset?: [number, number] };
type View = { parts?: Part[]; spots?: Spot[] };
type Item = {
  size?: [number, number];
  variants?: Record<string, View>[];
  autotile?: { outside?: 0 | 1; rules: { when: Record<string, 0 | 1>; parts: Part[] }[]; door?: Part[] };
};
type Anim = { row: number; frames: number; dirs: Record<string, number> };
type Catalog = {
  tileSize: number;
  sheets: Record<string, string>;
  floors: Record<string, { sheet: string; rect: Rect }[]>;
  items: Record<string, Item>;
  characters: {
    frame: [number, number];
    layers: Record<string, string>;
    animations: Record<string, Anim>;
    poses: Record<string, Record<string, string>>;
  };
};

const GRID = [
  '############',
  '#....#.....#',
  '#.DD.#.f.p.#',
  '#.^^.#...p.#',
  '#..........#',
  '#.vv..>..<.#',
  '#.DD.......#',
  '#.....ss...#',
  '#####E######',
];
const LEGEND: Record<string, { item: string; facing?: string }> = {
  D: { item: 'desk' },
  '^': { item: 'chair', facing: 'up' },
  v: { item: 'chair', facing: 'down' },
  '>': { item: 'chair', facing: 'right' },
  '<': { item: 'chair', facing: 'left' },
  f: { item: 'ficus' },
  p: { item: 'arcade' },
  s: { item: 'sofa' },
};
const MONITORS: { at: [number, number]; variant: number }[] = [
  { at: [2, 2], variant: 1 },
  { at: [2, 6], variant: 2 },
];
// Персонажи на местах: кресла 4 направлений, аркада, диван, плюс один идущий.
const PEOPLE: { at: [number, number]; pose: string; facing: string; frame?: number }[] = [
  { at: [2, 3], pose: 'sit', facing: 'up' },
  { at: [2, 5], pose: 'sit', facing: 'down' },
  { at: [6, 5], pose: 'sit', facing: 'right' },
  { at: [9, 5], pose: 'sit', facing: 'left' },
  { at: [9, 3], pose: 'play', facing: 'up' },
  { at: [6, 7], pose: 'sit', facing: 'down' },
  { at: [8, 4], pose: 'walk', facing: 'right', frame: 2 },
];
const AVATAR: Record<string, number> = { body: 3, eyes: 2, outfitModel: 1, outfitColor: 1, hairModel: 1, hairColor: 1 };
const SCALE = 4;

const asset = (p: string) => '/assets/' + p.split('/').map(encodeURIComponent).join('/');
const pad = (n: number) => String(n).padStart(2, '0');

async function main() {
  TextureSource.defaultOptions.scaleMode = 'nearest';
  const cat = parse(await (await fetch('/catalog.yaml')).text()) as Catalog;
  const ts = cat.tileSize;
  const app = new Application();
  await app.init({ width: GRID[0]!.length * ts * SCALE, height: (GRID.length + 3) * ts * SCALE, background: '#2b2b33', antialias: false });
  document.body.appendChild(app.canvas);
  const world = new Container();
  world.scale.set(SCALE);
  world.y = 3 * ts * SCALE; // место для стен, уходящих вверх
  app.stage.addChild(world);
  const floorLayer = new Container();
  const sorted = new Container();
  sorted.sortableChildren = true;
  world.addChild(floorLayer, sorted);

  const tex = new Map<string, Texture>();
  for (const p of Object.values(cat.sheets)) tex.set(p, await Assets.load<Texture>(asset(p)));
  const sub = (sheet: string, r: Rect) =>
    new Texture({ source: tex.get(cat.sheets[sheet]!)!.source, frame: new Rectangle(r[0], r[1], r[2], r[3]) });
  const put = (part: Part, cx: number, cy: number) => {
    const s = new Sprite(sub(part.sheet, part.rect));
    s.x = cx * ts + (part.at?.[0] ?? 0);
    s.y = cy * ts + (part.at?.[1] ?? 0);
    s.zIndex = (cy + part.sortY) * ts;
    sorted.addChild(s);
  };

  const at = (x: number, y: number) => GRID[y]?.[x];
  const floor = cat.floors['carpet_grey']![0]!;
  // Пол под всем, кроме стен.
  for (let y = 0; y < GRID.length; y++)
    for (let x = 0; x < GRID[0]!.length; x++)
      if (at(x, y) !== '#') {
        const s = new Sprite(sub(floor.sheet, floor.rect));
        s.x = x * ts;
        s.y = y * ts;
        floorLayer.addChild(s);
      }

  // Стены: маска 8 соседей, первое совпавшее правило.
  const wall = cat.items['wall']!.autotile!;
  const isWall = (x: number, y: number) => {
    const c = at(x, y);
    return c === undefined ? (wall.outside ?? 0) : c === '#' ? 1 : 0;
  };
  const N: Record<string, [number, number]> = { n: [0, -1], e: [1, 0], s: [0, 1], w: [-1, 0], ne: [1, -1], se: [1, 1], sw: [-1, 1], nw: [-1, -1] };
  for (let y = 0; y < GRID.length; y++)
    for (let x = 0; x < GRID[0]!.length; x++) {
      if (at(x, y) === 'E') for (const p of wall.door ?? []) put(p, x, y);
      if (at(x, y) !== '#') continue;
      const rule = wall.rules.find((r) => Object.entries(r.when).every(([k, v]) => isWall(x + N[k]![0], y + N[k]![1]) === v));
      if (!rule) {
        console.error(`нет правила стены для (${x},${y})`);
        continue;
      }
      for (const p of rule.parts) put(p, x, y);
    }

  // Предметы: жадный разбор прямоугольников.
  const claimed = new Set<string>();
  for (let y = 0; y < GRID.length; y++)
    for (let x = 0; x < GRID[0]!.length; x++) {
      const l = LEGEND[at(x, y) ?? ''];
      if (!l || claimed.has(`${x},${y}`)) continue;
      const def = cat.items[l.item]!;
      const [w, h] = def.size ?? [1, 1];
      for (let dy = 0; dy < h; dy++) for (let dx = 0; dx < w; dx++) claimed.add(`${x + dx},${y + dy}`);
      const view = def.variants?.[0]?.[l.facing ?? 'default'];
      for (const p of view?.parts ?? []) put(p, x, y);
    }
  for (const m of MONITORS) for (const p of cat.items['monitor']!.variants?.[m.variant - 1]?.['default']?.parts ?? []) put(p, m.at[0], m.at[1]);

  // Персонаж: слои генератора в одну текстуру.
  const L = cat.characters.layers;
  const files = [
    L['body']!.replace('{body}', pad(AVATAR['body']!)),
    L['eyes']!.replace('{eyes}', pad(AVATAR['eyes']!)),
    L['outfit']!.replace('{model}', pad(AVATAR['outfitModel']!)).replace('{color}', pad(AVATAR['outfitColor']!)),
    L['hair']!.replace('{model}', pad(AVATAR['hairModel']!)).replace('{color}', pad(AVATAR['hairColor']!)),
  ];
  const imgs = await Promise.all(
    files.map(async (f) => {
      const img = new Image();
      img.src = asset(f);
      await img.decode();
      return img;
    }),
  );
  const canvas = document.createElement('canvas');
  canvas.width = Math.max(...imgs.map((i) => i.naturalWidth));
  canvas.height = Math.max(...imgs.map((i) => i.naturalHeight));
  const ctx = canvas.getContext('2d')!;
  for (const img of imgs) ctx.drawImage(img, 0, 0);
  const charTex = Texture.from(canvas);
  const [fw, fh] = cat.characters.frame;
  const chairSpot = (facing: string) => cat.items['chair']!.variants?.[0]?.[facing]?.spots?.[0];
  for (const p of PEOPLE) {
    const animName = p.pose === 'walk' ? 'walk' : cat.characters.poses[p.pose]![p.facing]!;
    const anim = cat.characters.animations[animName]!;
    const col = (anim.dirs[p.facing] ?? anim.dirs['right']!) + (p.frame ?? 0);
    const s = new Sprite(new Texture({ source: charTex.source, frame: new Rectangle(col * fw, anim.row * fh, fw, fh) }));
    const isChair = LEGEND[at(p.at[0], p.at[1]) ?? '']?.item === 'chair';
    const off = (isChair ? chairSpot(p.facing)?.offset : undefined) ?? [0, 0];
    s.x = p.at[0] * ts + off[0];
    s.y = (p.at[1] + 1) * ts - fh + off[1];
    s.zIndex = (p.at[1] + 1) * ts;
    sorted.addChild(s);
  }
  (window as unknown as { __spikeReady: boolean }).__spikeReady = true;
}

main().catch((e) => {
  console.error(e);
  document.body.textContent = String(e);
});
```

- [ ] **Step 4: скрипт скриншота**

`tools/spike/shot.ts`:
```ts
import { chromium } from '@playwright/test';

// node tools/spike/shot.ts [out.png] — при запущенном `pnpm --filter @pixeloffice/spike dev`
const out = process.argv[2] ?? 'docs/spikes/m0-art/scene.png';
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 900, height: 800 }, deviceScaleFactor: 1 });
page.on('console', (m) => console.log(`[browser] ${m.type()}: ${m.text()}`));
await page.goto('http://localhost:5199/');
await page.waitForFunction(() => (window as unknown as { __spikeReady?: boolean }).__spikeReady === true, null, { timeout: 30_000 });
await page.screenshot({ path: out, fullPage: true });
await browser.close();
console.log(`скриншот: ${out}`);
```

- [ ] **Step 5: цикл «заполнить каталог → скриншот → посмотреть»**

```bash
mkdir -p docs/spikes/m0-art
pnpm --filter @pixeloffice/spike dev &      # фоновой процесс (run_in_background): живёт весь цикл правок
curl -sf -o /dev/null --noproxy '*' --retry 30 --retry-delay 1 --retry-connrefused http://localhost:5199/   # ждать, пока Vite слушает порт
node tools/spike/shot.ts docs/spikes/m0-art/scene.png
```
Открыть `docs/spikes/m0-art/scene.png` (Read tool) и проверить по критериям ниже. Не так — поправить `catalog.yaml` (rect, at, sortY, offset, правила стен), повторить. Остановить dev-сервер в конце: `lsof -ti tcp:5199 | xargs kill` (`kill %1` из другого шелла задание не найдёт).

`--noproxy '*'`: если в окружении сессии задан `http_proxy`, curl иначе пойдёт к 127.0.0.1 через прокси. Node `fetch` и Playwright переменную не читают.

Критерии скриншота:
1. Стены: внешний контур с углами; вертикальная внутренняя стена x=5 с Т-примыканием к верхней стене и торцом снизу; проём входа E внизу; соседи проёма — торцы.
2. Четыре кресла с сидящими персонажами: вверх (спиной к зрителю, спинка кресла перед ним), вниз (лицом, стол перед ним перекрывает ноги), вправо и влево (боковые sit-кадры).
3. Персонаж у аркады — `idle` вверх; на диване — лицом вниз; идущий — кадр `walk` вправо.
4. Нет «дыр» в полу и обрезанных спрайтов; пиксели чёткие (nearest).

- [ ] **Step 6: зафиксировать итог в заметке**

Дописать в `docs/spikes/2026-10-20-m0-art.md` раздел «Итог M0(а)»: правило автотайлинга (таблица `when → куски`), высота лица стены и как она ложится на grid (решение 9 подтверждено или изменено), выбранный ряд sit, значения `offset` сидения по направлениям, изменения схемы каталога (если были — какие задачи плана поправлены).

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

```bash
pnpm gate
git add catalog tools/spike pnpm-lock.yaml package.json
git status --short      # PNG не должно быть
git commit -m "feat(catalog): черновой каталог LimeZu и спайк рендера M0"
```

**Критерий готовности:** скриншот `docs/spikes/m0-art/scene.png` просмотрен и выполняет критерии 1–4. В каталоге нет `parts: []` и значений «сверить» у предметов сцены. Заметка содержит итог.

---

### Задача 4: M0(б) — спайк Nextcloud (скрипт; живой прогон — человек)

Цель: проверить на реальном сервере, что видно через User Status и Talk. URL сервера и app password сейчас нет, поэтому задача готовит инструмент и шаблон заметки, а прогон делает человек. Остальной план от прогона не зависит: адаптер (задача 30) пишется по фикстурам из документации OCS.

**Files:**
- Create: `adapters/nextcloud/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts}`
- Create: `adapters/nextcloud/src/ocs.ts`, `adapters/nextcloud/tests/ocs.test.ts`, `adapters/nextcloud/scripts/spike.ts`
- Create (вне git): `docs/spikes/2026-10-20-m0-nextcloud.md`

**Interfaces:**
- Produces: `type OcsAuth = { baseUrl: string; user: string; appPassword: string }`, `class OcsError extends Error { status: number }`, `ocsGet<T>(auth: OcsAuth, path: string, fetchImpl?: typeof fetch, timeoutMs?: number): Promise<T>`. `path` — без ведущего `/` (`ocs/v2.php/...`), чтобы работал Nextcloud в подкаталоге.

- [ ] **Step 1: пакет**

`adapters/nextcloud/package.json`:
```json
{
  "name": "@pixeloffice/adapter-nextcloud",
  "private": true,
  "type": "module",
  "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json" },
  "dependencies": {}
}
```
`tsconfig.json`: `{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024"], "types": ["node"] }, "include": ["src", "scripts"] }`; `tsconfig.test.json` — то же плюс `"tests"`; `vitest.config.ts` с `name: 'adapter-nextcloud'`.

- [ ] **Step 2: падающий тест**

`adapters/nextcloud/tests/ocs.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { OcsError, ocsGet } from '../src/ocs.ts';

const auth = { baseUrl: 'https://cloud.example/nc', user: 'bot', appPassword: 'p@ss' };

function fakeFetch(status: number, body: unknown, seen: { url?: string; headers?: Record<string, string> }): typeof fetch {
  return (async (url: URL | string, init?: RequestInit) => {
    seen.url = String(url);
    seen.headers = init?.headers as Record<string, string>;
    return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
  }) as typeof fetch;
}

describe('ocsGet', () => {
  it('шлёт OCS-заголовки и basic auth, возвращает ocs.data', async () => {
    const seen: { url?: string; headers?: Record<string, string> } = {};
    const data = await ocsGet<{ x: number }>(auth, 'ocs/v2.php/apps/user_status/api/v1/statuses', fakeFetch(200, { ocs: { meta: { status: 'ok', statuscode: 200 }, data: { x: 1 } } }, seen));
    expect(data).toEqual({ x: 1 });
    expect(seen.url).toBe('https://cloud.example/nc/ocs/v2.php/apps/user_status/api/v1/statuses?format=json');
    expect(seen.headers?.['OCS-APIRequest']).toBe('true');
    expect(seen.headers?.['Authorization']).toBe('Basic ' + Buffer.from('bot:p@ss').toString('base64'));
  });

  it('HTTP-ошибка → OcsError со статусом', async () => {
    await expect(ocsGet(auth, 'ocs/v2.php/x', fakeFetch(401, {}, {}))).rejects.toMatchObject({ status: 401 });
  });

  it('meta.status != ok → OcsError', async () => {
    const p = ocsGet(auth, 'ocs/v2.php/x', fakeFetch(200, { ocs: { meta: { status: 'failure', statuscode: 404, message: 'нет' } } }, {}));
    await expect(p).rejects.toBeInstanceOf(OcsError);
  });
});
```

Run: `pnpm vitest run adapters/nextcloud` → FAIL (нет модуля).

- [ ] **Step 3: реализация `adapters/nextcloud/src/ocs.ts`**

```ts
// Минимальный клиент OCS API Nextcloud (JSON, basic auth app password).
export type OcsAuth = { baseUrl: string; user: string; appPassword: string };

export class OcsError extends Error {
  status: number;
  constructor(message: string, status: number) {
    super(message);
    this.status = status;
  }
}

type OcsEnvelope<T> = { ocs?: { meta?: { status?: string; statuscode?: number; message?: string }; data?: T } };

export async function ocsGet<T>(auth: OcsAuth, path: string, fetchImpl: typeof fetch = fetch, timeoutMs = 10_000): Promise<T> {
  const base = auth.baseUrl.endsWith('/') ? auth.baseUrl : auth.baseUrl + '/';
  const url = new URL(path, base);
  if (!url.searchParams.has('format')) url.searchParams.set('format', 'json');
  const res = await fetchImpl(url, {
    headers: {
      'OCS-APIRequest': 'true',
      Accept: 'application/json',
      Authorization: 'Basic ' + Buffer.from(`${auth.user}:${auth.appPassword}`).toString('base64'),
    },
    signal: AbortSignal.timeout(timeoutMs),
  });
  if (!res.ok) throw new OcsError(`OCS ${url.pathname}: HTTP ${res.status}`, res.status);
  const body = (await res.json()) as OcsEnvelope<T>;
  if (!body.ocs || body.ocs.meta?.status !== 'ok') {
    throw new OcsError(`OCS ${url.pathname}: ${body.ocs?.meta?.message ?? 'нет ocs.meta'}`, body.ocs?.meta?.statuscode ?? res.status);
  }
  return body.ocs.data as T;
}
```

Run: `pnpm vitest run adapters/nextcloud` → PASS.

- [ ] **Step 4: скрипт спайка `adapters/nextcloud/scripts/spike.ts`**

```ts
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ocsGet, type OcsAuth } from '../src/ocs.ts';

// Спайк M0(б). Запуск человеком:
//   NC_URL=https://cloud.example NC_USER=pixeloffice-bot NC_APP_PASSWORD=xxxx node adapters/nextcloud/scripts/spike.ts
// Сырые ответы (тексты сообщений вырезаны) → docs/spikes/nextcloud-raw/, сводка → stdout.
const env = (k: string) => {
  const v = process.env[k];
  if (!v) throw new Error(`нужна переменная окружения ${k}`);
  return v;
};
const auth: OcsAuth = { baseUrl: env('NC_URL'), user: env('NC_USER'), appPassword: env('NC_APP_PASSWORD') };
const OUT = 'docs/spikes/nextcloud-raw';
mkdirSync(OUT, { recursive: true });

// Тексты сообщений и статусов — персональные данные: оставляем только длину.
function redact(v: unknown): unknown {
  if (Array.isArray(v)) return v.map(redact);
  if (v && typeof v === 'object') {
    return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, k === 'message' && typeof x === 'string' ? `<${x.length} симв.>` : redact(x)]));
  }
  return v;
}

async function grab<T>(name: string, path: string): Promise<T | null> {
  try {
    const data = await ocsGet<T>(auth, path);
    writeFileSync(join(OUT, `${name}.json`), JSON.stringify(redact(data), null, 2));
    console.log(`OK   ${name}`);
    return data;
  } catch (e) {
    console.log(`FAIL ${name}: ${(e as Error).message}`);
    return null;
  }
}

type Room = { token: string; displayName: string; hasCall?: boolean; callFlag?: number; type: number };
await grab('capabilities', 'ocs/v2.php/cloud/capabilities');
await grab('own-status', 'ocs/v2.php/apps/user_status/api/v1/user_status');
const statuses = await grab<{ userId: string; status: string }[]>('statuses', 'ocs/v2.php/apps/user_status/api/v1/statuses?limit=200');
const rooms = (await grab<Room[]>('rooms', 'ocs/v2.php/apps/spreed/api/v4/room')) ?? [];
for (const r of rooms) {
  await grab(`participants-${r.token}`, `ocs/v2.php/apps/spreed/api/v4/room/${r.token}/participants`);
  if (r.hasCall) await grab(`call-${r.token}`, `ocs/v2.php/apps/spreed/api/v4/call/${r.token}`);
  await grab(`chat-${r.token}`, `ocs/v2.php/apps/spreed/api/v1/chat/${r.token}?lookIntoFuture=0&limit=5`);
}

const byStatus = new Map<string, number>();
for (const s of statuses ?? []) byStatus.set(s.status, (byStatus.get(s.status) ?? 0) + 1);
console.log('\nСводка:');
console.log(`  статусов пользователей: ${statuses?.length ?? 'нет доступа'}`, Object.fromEntries(byStatus));
console.log(`  комнат бота: ${rooms.length}, со звонком сейчас: ${rooms.filter((r) => r.hasCall).length}`);
```

`tsc -p adapters/nextcloud/tsconfig.json` должен проходить (входит в `pnpm typecheck`).

- [ ] **Step 5: шаблон заметки `docs/spikes/2026-10-20-m0-nextcloud.md`**

```markdown
# M0(б) — спайк Nextcloud

Статус: **ожидает человека** (нужны URL сервера и app password сервисного пользователя).

## Как запустить
1. В Nextcloud создать сервисного пользователя (напр. `pixeloffice-bot`), добавить его в комнаты Talk, звонки в которых должны быть видны.
2. Personal settings → Security → Devices & sessions → Create new app password.
3. `NC_URL=https://… NC_USER=pixeloffice-bot NC_APP_PASSWORD=… node adapters/nextcloud/scripts/spike.ts`
4. Сырые ответы — `docs/spikes/nextcloud-raw/` (тексты вырезаны).

## Что выяснить (заполнить)
1. Версия Nextcloud и Talk (capabilities): …
2. `GET …/user_status/api/v1/statuses` доступен боту? Какие значения `status` встречаются: …
3. Есть ли автоматический статус «In a call» (`status`/`icon`/`messageId` у звонящего), как он выглядит: …
4. `hasCall` у комнаты и список участников звонка (`…/call/{token}`): видно ли `actorId` каждого участника: …
5. Как Talk помечает участника в звонке в `…/participants` (`inCall` > 0?): …
6. Чат: поля сообщения (`id`, `actorId`, `message`, `systemMessage`), работает ли `lookIntoFuture=1&timeout=0&lastKnownMessageId=`: …
7. Итоговая таблица `statusMap` по умолчанию (спека 6.2) — подтверждена / изменена: …

## Итог для адаптера (задача 30)
- Что поменять в `adapters/nextcloud/src/map.ts` и фикстурах: …
```

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

```bash
pnpm install
pnpm gate
git add adapters/nextcloud pnpm-lock.yaml
git commit -m "feat(nextcloud): OCS-клиент и скрипт спайка M0(б)"
```

**Критерий готовности:** тесты `ocsGet` зелёные. Скрипт тайпчекается. Шаблон заметки лежит в `docs/spikes/` со статусом «ожидает человека». Живой прогон в эту задачу не входит.

---

## Этап M1. Ядро `core` (и `protocol`)

### Задача 5: protocol — схемы событий, сущности, сообщения WebSocket

**Files:**
- Create: `packages/protocol/src/{common.ts,avatar.ts,events.ts,ws.ts}`
- Modify: `packages/protocol/src/index.ts`
- Test: `packages/protocol/tests/events.test.ts`

**Interfaces:**
- Produces (всё реэкспортирует `@pixeloffice/protocol`):
  - `common.ts`: `PROTOCOL_VERSION = 1`, `FacingSchema`, `type Facing = 'up'|'down'|'left'|'right'`, `PoseSchema`, `type Pose = 'sit'|'stand'|'play'`, `StatusSchema`, `type Status`, `type HumanStatus`, `type AgentStatus`, `HUMAN_STATUSES`, `AGENT_STATUSES`, `isHumanStatus(s)`, `isAgentStatus(s)`.
  - `avatar.ts`: `AvatarPartsSchema`, `type AvatarParts = { body: number; eyes: number; outfit: [number, number]; hair: [number, number]; accessory?: [number, number] }`, `type Entity = { id; kind: 'human'|'agent'; name; ownerId?; avatar: AvatarParts }`.
  - `events.ts`: `AgentRefSchema`, `type AgentRef = { project; projectDir?; slot }`, `StatusEventSchema`, `SnapshotEventSchema`, `BubbleEventSchema`, `EventSchema`, `EventsBodySchema`, типы `StatusEvent`, `SnapshotEvent`, `BubbleEvent`, `Event`, `type Issue = { path: string; message: string }`, `formatIssues(error): Issue[]`.
  - `ws.ts`: `Frame`, `FloorTile`, `MapSprite`, `SpotView`, `RenderedMap`, `AnimName`, `AnimDef`, `CharacterLayout`, `EntityView`, `Bubble`, `CharacterState`, `HelloMessage`, `DeltaMessage`, `DespawnMessage`, `EntityMessage`, `EntityRemovedMessage`, `DebugMessage`, `ServerMessage`.

- [ ] **Step 1: падающие тесты `packages/protocol/tests/events.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { EventsBodySchema, formatIssues } from '../src/index.ts';

const at = '2026-10-20T10:00:00.000Z';
const issuesOf = (body: unknown) => {
  const r = EventsBodySchema.safeParse(body);
  return r.success ? [] : formatIssues(r.error);
};

describe('EventsBodySchema', () => {
  it('статус человека по entityId', () => {
    expect(EventsBodySchema.safeParse({ events: [{ type: 'status', entityId: 'stas', status: 'online', at }] }).success).toBe(true);
  });

  it('статус агента через agent', () => {
    const body = { events: [{ type: 'status', agent: { project: 'PixelOffice', projectDir: '/p/PixelOffice', slot: '%17' }, status: 'working', at, ttlSec: 900 }] };
    expect(EventsBodySchema.safeParse(body).success).toBe(true);
  });

  it('entityId вида agent:… → ошибка с путём поля', () => {
    const issues = issuesOf({ events: [{ type: 'status', entityId: 'agent:stas:x:%1', status: 'working', at }] });
    expect(issues.map((i) => i.path)).toContain('events.0.entityId');
  });

  it('нужно ровно одно из entityId и agent', () => {
    expect(issuesOf({ events: [{ type: 'status', status: 'online', at }] }).map((i) => i.path)).toContain('events.0.entityId');
    const both = { type: 'bubble', entityId: 'stas', agent: { project: 'p', slot: 's' }, text: 'hi', ttlSec: 10, at };
    expect(issuesOf({ events: [both] }).map((i) => i.path)).toContain('events.0.entityId');
  });

  it('source и owner в теле запрещены', () => {
    expect(issuesOf({ events: [{ type: 'status', entityId: 'stas', status: 'online', at, source: 'x' }] }).length).toBeGreaterThan(0);
  });

  it('невалидное время → путь events.0.at', () => {
    expect(issuesOf({ events: [{ type: 'status', entityId: 'stas', status: 'online', at: 'вчера' }] }).map((i) => i.path)).toContain('events.0.at');
  });

  it('snapshot со списком сущностей', () => {
    const body = { events: [{ type: 'snapshot', at, ttlSec: 120, entities: [{ entityId: 'stas', status: 'meeting', meetingId: 'room1' }] }] };
    expect(EventsBodySchema.safeParse(body).success).toBe(true);
  });

  it('пустой список событий → ошибка', () => {
    expect(issuesOf({ events: [] }).map((i) => i.path)).toContain('events');
  });
});
```

Run: `pnpm vitest run packages/protocol` → FAIL (нет экспорта).

- [ ] **Step 2: `packages/protocol/src/common.ts`**

```ts
import { z } from 'zod';

export const PROTOCOL_VERSION = 1;

export const FacingSchema = z.enum(['up', 'down', 'left', 'right']);
export type Facing = z.infer<typeof FacingSchema>;

export const PoseSchema = z.enum(['sit', 'stand', 'play']);
export type Pose = z.infer<typeof PoseSchema>;

export const HUMAN_STATUSES = ['online', 'offline', 'meeting'] as const;
export const AGENT_STATUSES = ['working', 'idle', 'needs_input', 'offline'] as const;
export type HumanStatus = (typeof HUMAN_STATUSES)[number];
export type AgentStatus = (typeof AGENT_STATUSES)[number];

export const StatusSchema = z.enum(['online', 'offline', 'meeting', 'working', 'idle', 'needs_input']);
export type Status = z.infer<typeof StatusSchema>;

export const isHumanStatus = (s: Status): s is HumanStatus => (HUMAN_STATUSES as readonly string[]).includes(s);
export const isAgentStatus = (s: Status): s is AgentStatus => (AGENT_STATUSES as readonly string[]).includes(s);
```

- [ ] **Step 3: `packages/protocol/src/avatar.ts`**

```ts
import { z } from 'zod';

const Pair = z.tuple([z.number().int().min(1), z.number().int().min(1)]);

// body, eyes — номера файлов Body_NN, Eyes_NN; у одежды, причёски и аксессуара — [модель, цвет] (спека 4.1).
export const AvatarPartsSchema = z.strictObject({
  body: z.number().int().min(1),
  eyes: z.number().int().min(1),
  outfit: Pair,
  hair: Pair,
  accessory: Pair.optional(),
});
export type AvatarParts = z.infer<typeof AvatarPartsSchema>;

export type Entity = {
  id: string;
  kind: 'human' | 'agent';
  name: string;
  ownerId?: string;
  avatar: AvatarParts;
};
```

- [ ] **Step 4: `packages/protocol/src/events.ts`**

```ts
import { z } from 'zod';
import { StatusSchema } from './common.ts';

const Id = z.string().min(1).max(200);
const At = z.iso.datetime({ offset: true });
const TtlSec = z.number().int().positive().max(30 * 86_400);

export const AgentRefSchema = z.strictObject({
  project: Id,
  projectDir: z.string().min(1).max(4096).optional(),
  slot: Id,
});
export type AgentRef = z.infer<typeof AgentRefSchema>;

// Агента адресуют только через agent: ключ строит сервер (спека 4.1, 4.3).
const EntityId = Id.refine((id) => !id.startsWith('agent:'), { message: 'агента адресуют только через поле agent' });
const target = { entityId: EntityId.optional(), agent: AgentRefSchema.optional() };
const oneTarget = (v: { entityId?: string; agent?: AgentRef }) => (v.entityId === undefined) !== (v.agent === undefined);
const oneTargetMsg = { message: 'нужно ровно одно из полей entityId или agent', path: ['entityId'] };

export const StatusEventSchema = z
  .strictObject({ type: z.literal('status'), status: StatusSchema, meetingId: Id.optional(), at: At, ttlSec: TtlSec.optional(), ...target })
  .refine(oneTarget, oneTargetMsg);

export const SnapshotEventSchema = z.strictObject({
  type: z.literal('snapshot'),
  entities: z.array(z.strictObject({ entityId: EntityId, status: StatusSchema, meetingId: Id.optional() })).max(1000),
  at: At,
  ttlSec: TtlSec.optional(),
});

export const BubbleEventSchema = z
  .strictObject({ type: z.literal('bubble'), text: z.string().min(1).max(500), ttlSec: TtlSec, at: At, ...target })
  .refine(oneTarget, oneTargetMsg);

export const EventSchema = z.discriminatedUnion('type', [StatusEventSchema, SnapshotEventSchema, BubbleEventSchema]);
export const EventsBodySchema = z.strictObject({ events: z.array(EventSchema).min(1).max(500) });

export type StatusEvent = z.infer<typeof StatusEventSchema>;
export type SnapshotEvent = z.infer<typeof SnapshotEventSchema>;
export type BubbleEvent = z.infer<typeof BubbleEventSchema>;
export type Event = z.infer<typeof EventSchema>;

export type Issue = { path: string; message: string };
export const formatIssues = (error: z.ZodError): Issue[] => error.issues.map((i) => ({ path: i.path.join('.'), message: i.message }));
```

Если zod откажется принимать объекты с `.refine` внутри `discriminatedUnion`, заменить `z.discriminatedUnion('type', …)` на `z.union([...])`. Тесты не меняются.

- [ ] **Step 5: `packages/protocol/src/ws.ts`**

```ts
import type { Facing, Pose } from './common.ts';

// Кадр атласа: sheet — URL листа (/assets/...), прямоугольник в пикселях.
export type Frame = { sheet: string; x: number; y: number; w: number; h: number };
export type FloorTile = { x: number; y: number; frame: Frame }; // x, y — клетки
export type MapSprite = { frame: Frame; px: number; py: number; sortY: number }; // px, py, sortY — пиксели мира
export type SpotView = { id: string; x: number; y: number; facing: Facing; pose: Pose; zoneId: string | null; tags: string[] };
export type RenderedMap = {
  tileSize: number;
  width: number;
  height: number;
  floor: FloorTile[];
  sprites: MapSprite[];
  spots: SpotView[];
  blocked: [number, number][];
  entrance: [number, number];
};

export type AnimName = 'idle' | 'walk' | 'sit';
export type AnimDef = { row: number; frames: number; dirs: Partial<Record<Facing, number>> };
export type CharacterLayout = { frameW: number; frameH: number; animations: Record<AnimName, AnimDef> };

// Сущность для зрителя: без projectDir (спека 4.1); layers — URL слоёв аватара в порядке наложения.
export type EntityView = { id: string; kind: 'human' | 'agent'; name: string; ownerId?: string; label: string; layers: string[] };

export type Bubble = { text: string; kind: 'info' | 'needs_input' };
// bubble: поля нет — без изменений; null — убрать; объект — показать (спека 4.6).
export type CharacterState = {
  id: string;
  x: number;
  y: number;
  facing: Facing;
  pose: Pose | 'walk';
  anim: AnimName;
  offset: [number, number];
  bubble?: Bubble | null;
};

export type HelloMessage = {
  type: 'hello';
  protocol: number;
  t: number;
  test: boolean;
  map: RenderedMap;
  characterLayout: CharacterLayout;
  entities: EntityView[];
  characters: CharacterState[];
};
export type DeltaMessage = { type: 'delta'; t: number; characters: CharacterState[] };
export type DespawnMessage = { type: 'despawn'; id: string };
export type EntityMessage = { type: 'entity'; entity: EntityView };
export type EntityRemovedMessage = { type: 'entity_removed'; id: string };
export type DebugMessage = {
  type: 'debug';
  paths: Record<string, [number, number][]>;
  reservations: Record<string, string>;
  meetings: Record<string, string[]>;
};
export type ServerMessage = HelloMessage | DeltaMessage | DespawnMessage | EntityMessage | EntityRemovedMessage | DebugMessage;
```

- [ ] **Step 6: `packages/protocol/src/index.ts`**

```ts
export * from './common.ts';
export * from './avatar.ts';
export * from './events.ts';
export * from './ws.ts';
```

Run: `pnpm vitest run packages/protocol` → PASS (9 тестов).

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

```bash
pnpm gate
git add packages/protocol
git commit -m "feat(protocol): zod-схемы событий API и типы сообщений WebSocket"
```

**Критерий готовности:** тесты событий зелёные, тест чистоты зелёный, `pnpm typecheck` чистый.

---

### Задача 6: core — ошибки, YAML через zod, каталог

**Files:**
- Create: `packages/core/src/{errors.ts,yaml.ts,catalog.ts}`
- Create: `packages/core/tests/fixtures.ts`, `packages/core/tests/catalog.test.ts`
- Modify: `packages/core/src/index.ts`

**Interfaces:**
- Produces:
  - `errors.ts`: `type MapError = { file: string; code: string; message: string; at?: [number, number] }`, `type Result<T> = { ok: true; value: T } | { ok: false; errors: MapError[] }`, `ok(value)`, `fail(errors)`, `formatErrors(errors): string`.
  - `yaml.ts`: `parseYamlWith<S extends z.ZodType>(file, text, schema): Result<z.output<S>>`.
  - `catalog.ts`: `type Part = { sheet; rect: [x,y,w,h]; at: [dx,dy]; sortY; name? }`, `type SpotDef = { cell; facing?; pose; offset; tags }`, `type ItemView = { parts: Part[]; spots: SpotDef[] }`, `type ViewKey = 'default'|Facing`, `type WallAutotile = { outside: 0|1; rules: { when: Partial<Record<'n'|'e'|'s'|'w'|'ne'|'se'|'sw'|'nw', 0|1>>; parts: Part[] }[]; door: Part[] }`, `type ItemDef = { id; size: [w,h]; blocks: [dx,dy][]; facings: Facing[] | null; tags; variants: Partial<Record<ViewKey, ItemView>>[]; autotile: WallAutotile | null }`, `type CharactersDef` (раздел `characters`, поля как в схеме задачи 3), `type FloorFrame = { sheet; rect }`, `type Catalog = { tileSize; sheets; floors: Record<string, FloorFrame[]>; items: Record<string, ItemDef>; characters: CharactersDef }`, `loadCatalog(text, file = 'catalog.yaml'): Result<Catalog>`, `itemView(def, facing, variant): ItemView`.
  - `tests/fixtures.ts`: `MINI_CATALOG` (строка YAML), `miniCatalog(): Catalog`, `mutateYaml(text, fn): string`.

- [ ] **Step 1: фикстуры `packages/core/tests/fixtures.ts`**

```ts
import { parse, stringify } from 'yaml';
import { loadCatalog, type Catalog } from '../src/index.ts';

// Мини-каталог для тестов ядра: координаты условные, PNG не нужны.
export const MINI_CATALOG = `
version: 1
tileSize: 16
sheets: { s: test/sheet.png }
floors:
  carpet: [ { sheet: s, rect: [0, 0, 16, 16] } ]
  wood: [ { sheet: s, rect: [16, 0, 16, 16] }, { sheet: s, rect: [32, 0, 16, 16] } ]
items:
  wall:
    autotile:
      rules:
        - when: { s: 0 }
          parts: [ { sheet: s, rect: [0, 16, 16, 32], at: [0, -16], sortY: 1 } ]
        - when: {}
          parts: [ { sheet: s, rect: [16, 16, 16, 16], sortY: 1 } ]
      door: [ { sheet: s, rect: [32, 16, 16, 16], sortY: 0 } ]
  desk:
    size: [2, 1]
    variants: [ { default: { parts: [ { sheet: s, rect: [0, 48, 32, 32], at: [0, -16], sortY: 1 } ] } } ]
  table:
    size: [2, 1]
    variants: [ { default: { parts: [ { sheet: s, rect: [0, 48, 32, 32], at: [0, -16], sortY: 1 } ] } } ]
  chair:
    blocks: none
    facings: [up, down, left, right]
    variants:
      - up:    { parts: [ { sheet: s, rect: [0, 80, 16, 16], sortY: 0.5 }, { sheet: s, rect: [16, 80, 16, 16], sortY: 1.05 } ], spots: [ { cell: [0, 0], pose: sit, offset: [0, -4] } ] }
        down:  { parts: [ { sheet: s, rect: [32, 80, 16, 16], sortY: 0.5 } ], spots: [ { cell: [0, 0], pose: sit } ] }
        left:  { parts: [ { sheet: s, rect: [48, 80, 16, 16], sortY: 0.5 } ], spots: [ { cell: [0, 0], pose: sit } ] }
        right: { parts: [ { sheet: s, rect: [64, 80, 16, 16], sortY: 0.5 } ], spots: [ { cell: [0, 0], pose: sit } ] }
  monitor:
    blocks: none
    variants: [ { default: { parts: [ { sheet: s, rect: [0, 96, 16, 16], at: [0, -8], sortY: 0.9 } ] } } ]
  arcade:
    size: [1, 2]
    blocks: [[0, 0]]
    variants: [ { default: { parts: [ { sheet: s, rect: [0, 112, 16, 32], sortY: 1 } ], spots: [ { cell: [0, 1], facing: up, pose: play } ] } } ]
  board:
    size: [1, 2]
    blocks: [[0, 0]]
    variants: [ { default: { parts: [ { sheet: s, rect: [16, 112, 16, 32], sortY: 1 } ], spots: [ { cell: [0, 1], facing: up, pose: stand } ] } } ]
  plant:
    variants:
      - { default: { parts: [ { sheet: s, rect: [32, 112, 16, 32], at: [0, -16], sortY: 1 } ] } }
      - { default: { parts: [ { sheet: s, rect: [48, 112, 16, 32], at: [0, -16], sortY: 1 } ] } }
characters:
  frame: [16, 32]
  layers:
    body: gen/Body_{body}.png
    eyes: gen/Eyes_{eyes}.png
    outfit: gen/Outfit_{model}_{color}.png
    hair: gen/Hairstyle_{model}_{color}.png
    accessory: gen/Accessory_{model}_{name}_{color}.png
  accessoryNames: { "1": Ladybug }
  animations:
    idle: { row: 1, frames: 6, dirs: { right: 0, up: 6, left: 12, down: 18 } }
    walk: { row: 2, frames: 6, dirs: { right: 0, up: 6, left: 12, down: 18 } }
    sit:  { row: 4, frames: 6, dirs: { right: 0, left: 6 } }
  poses:
    sit:   { up: walk, down: walk, left: sit, right: sit }
    stand: { up: idle, down: idle, left: idle, right: idle }
    play:  { up: idle, down: idle, left: idle, right: idle }
  pool: { bodies: [1, 2, 3], eyes: [1, 2], outfits: { "1": 3, "2": 2 }, hairs: { "1": 4 } }
`;

export function miniCatalog(): Catalog {
  const r = loadCatalog(MINI_CATALOG);
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
}

// Правка YAML-фикстуры как объекта (для негативных тестов).
export function mutateYaml(text: string, fn: (doc: any) => void): string {
  const doc = parse(text);
  fn(doc);
  return stringify(doc);
}
```

`any` в `mutateYaml` допустим только в тестовом хелпере. Если тайпчек тестов его не пропускает, заменить на `Record<string, any>`.

- [ ] **Step 2: падающие тесты `packages/core/tests/catalog.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { itemView, loadCatalog } from '../src/index.ts';
import { MINI_CATALOG, miniCatalog, mutateYaml } from './fixtures.ts';

const codes = (text: string) => {
  const r = loadCatalog(text);
  return r.ok ? [] : r.errors.map((e) => e.code);
};

describe('loadCatalog', () => {
  it('загружает мини-каталог и нормализует blocks', () => {
    const c = miniCatalog();
    expect(c.items['desk']!.blocks).toEqual([[0, 0], [1, 0]]);
    expect(c.items['chair']!.blocks).toEqual([]);
    expect(c.items['arcade']!.blocks).toEqual([[0, 0]]);
    expect(c.items['chair']!.facings).toEqual(['up', 'down', 'left', 'right']);
    expect(c.items['wall']!.autotile!.rules).toHaveLength(2);
    expect(c.items['wall']!.autotile!.outside).toBe(0);
    expect(c.characters.animations.walk.dirs.down).toBe(18);
  });

  it('itemView выбирает вариант и направление', () => {
    const c = miniCatalog();
    expect(itemView(c.items['chair']!, 'up', 1).parts).toHaveLength(2);
    expect(itemView(c.items['plant']!, null, 2).parts[0]!.rect).toEqual([48, 112, 16, 32]);
    expect(itemView(c.items['plant']!, null, 9).parts[0]!.rect).toEqual([32, 112, 16, 32]); // нет варианта → первый
  });

  it('синтаксическая ошибка YAML', () => {
    expect(codes('version: [1')).toEqual(['yaml_syntax']);
  });

  it('неизвестный лист', () => {
    expect(codes(mutateYaml(MINI_CATALOG, (d) => (d.items.desk.variants[0].default.parts[0].sheet = 'nope')))).toContain('unknown_sheet');
  });

  it('у предмета с направлениями нет вида', () => {
    const r = loadCatalog(mutateYaml(MINI_CATALOG, (d) => delete d.items.chair.variants[0].left));
    expect(r.ok).toBe(false);
    if (!r.ok) expect(r.errors[0]!.message).toContain('нет вида «left»');
  });

  it('место вне размера предмета', () => {
    expect(codes(mutateYaml(MINI_CATALOG, (d) => (d.items.arcade.variants[0].default.spots[0].cell = [0, 2])))).toContain('spot_outside');
  });

  it('нет стены с autotile', () => {
    expect(codes(mutateYaml(MINI_CATALOG, (d) => delete d.items.wall))).toContain('wall_missing');
  });

  it('лишний ключ предмета — ошибка схемы с путём', () => {
    const r = loadCatalog(mutateYaml(MINI_CATALOG, (d) => (d.items.desk.colour = 'red')));
    expect(r.ok).toBe(false);
    if (!r.ok) expect(r.errors[0]!.message).toContain('items.desk');
  });
});
```

Run: `pnpm vitest run packages/core/tests/catalog.test.ts` → FAIL.

- [ ] **Step 3: `packages/core/src/errors.ts`**

```ts
// Ошибка карты/каталога/правил: громкая, с файлом и координатами (урок v1 №2).
export type MapError = { file: string; code: string; message: string; at?: [number, number] };
export type Result<T> = { ok: true; value: T } | { ok: false; errors: MapError[] };

export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
export const fail = <T = never>(errors: MapError[]): Result<T> => ({ ok: false, errors });

export function formatErrors(errors: MapError[]): string {
  return errors.map((e) => `${e.file}${e.at ? ` (${e.at[0]},${e.at[1]})` : ''}: [${e.code}] ${e.message}`).join('\n');
}
```

- [ ] **Step 4: `packages/core/src/yaml.ts`**

```ts
import { parse } from 'yaml';
import type { z } from 'zod';
import { fail, ok, type Result } from './errors.ts';

export function parseYamlWith<S extends z.ZodType>(file: string, text: string, schema: S): Result<z.output<S>> {
  let raw: unknown;
  try {
    raw = parse(text);
  } catch (e) {
    return fail([{ file, code: 'yaml_syntax', message: (e as Error).message }]);
  }
  const r = schema.safeParse(raw);
  if (!r.success) {
    return fail(r.error.issues.map((i) => ({ file, code: 'schema', message: `${i.path.join('.') || '<корень>'}: ${i.message}` })));
  }
  return ok(r.data);
}
```

- [ ] **Step 5: `packages/core/src/catalog.ts`**

```ts
import { z } from 'zod';
import { FacingSchema, PoseSchema, type Facing } from '@pixeloffice/protocol';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { parseYamlWith } from './yaml.ts';

const Int = z.number().int();
const RectSchema = z.tuple([Int.min(0), Int.min(0), Int.positive(), Int.positive()]);
const PartSchema = z.strictObject({
  sheet: z.string(),
  rect: RectSchema,
  at: z.tuple([Int, Int]).default([0, 0]),
  sortY: z.number(),
  name: z.string().optional(),
});
const SpotSchema = z.strictObject({
  cell: z.tuple([Int.min(0), Int.min(0)]),
  facing: FacingSchema.optional(),
  pose: PoseSchema,
  offset: z.tuple([Int, Int]).default([0, 0]),
  tags: z.array(z.string()).default([]),
});
const ViewSchema = z.strictObject({ parts: z.array(PartSchema).default([]), spots: z.array(SpotSchema).default([]) });
const ViewKeySchema = z.enum(['default', 'up', 'down', 'left', 'right']);
const Bit = z.union([z.literal(0), z.literal(1)]);
const WhenSchema = z.strictObject({
  n: Bit.optional(), e: Bit.optional(), s: Bit.optional(), w: Bit.optional(),
  ne: Bit.optional(), se: Bit.optional(), sw: Bit.optional(), nw: Bit.optional(),
});
const AutotileSchema = z.strictObject({
  outside: Bit.default(0),
  rules: z.array(z.strictObject({ when: WhenSchema, parts: z.array(PartSchema).min(1) })).min(1),
  door: z.array(PartSchema).default([]),
});
const ItemSchema = z.strictObject({
  size: z.tuple([Int.positive(), Int.positive()]).default([1, 1]),
  blocks: z.union([z.literal('all'), z.literal('none'), z.array(z.tuple([Int.min(0), Int.min(0)]))]).default('all'),
  facings: z.array(FacingSchema).min(1).optional(),
  tags: z.array(z.string()).default([]),
  variants: z.array(z.partialRecord(ViewKeySchema, ViewSchema)).default([]),
  autotile: AutotileSchema.optional(),
});
const AnimNameSchema = z.enum(['idle', 'walk', 'sit']);
const AnimSchema = z.strictObject({ row: Int.min(0), frames: Int.positive(), dirs: z.partialRecord(FacingSchema, Int.min(0)) });
const PoseAnims = z.record(FacingSchema, AnimNameSchema);
const CharactersSchema = z.strictObject({
  frame: z.tuple([Int.positive(), Int.positive()]),
  layers: z.strictObject({ body: z.string(), eyes: z.string(), outfit: z.string(), hair: z.string(), accessory: z.string() }),
  accessoryNames: z.record(z.string(), z.string()).default({}),
  animations: z.strictObject({ idle: AnimSchema, walk: AnimSchema, sit: AnimSchema }),
  poses: z.strictObject({ sit: PoseAnims, stand: PoseAnims, play: PoseAnims }),
  pool: z.strictObject({
    bodies: z.array(Int.positive()).min(1),
    eyes: z.array(Int.positive()).min(1),
    outfits: z.record(z.string(), Int.positive()),
    hairs: z.record(z.string(), Int.positive()),
  }),
});
const CatalogFileSchema = z.strictObject({
  version: z.literal(1),
  tileSize: Int.positive(),
  sheets: z.record(z.string(), z.string().min(1)),
  floors: z.record(z.string(), z.array(z.strictObject({ sheet: z.string(), rect: RectSchema })).min(1)),
  items: z.record(z.string(), ItemSchema),
  characters: CharactersSchema,
});

export type Part = z.output<typeof PartSchema>;
export type SpotDef = z.output<typeof SpotSchema>;
export type ItemView = z.output<typeof ViewSchema>;
export type ViewKey = z.output<typeof ViewKeySchema>;
export type WallAutotile = z.output<typeof AutotileSchema>;
export type CharactersDef = z.output<typeof CharactersSchema>;
export type FloorFrame = { sheet: string; rect: [number, number, number, number] };
export type ItemDef = {
  id: string;
  size: [number, number];
  blocks: [number, number][];
  facings: Facing[] | null;
  tags: string[];
  variants: Partial<Record<ViewKey, ItemView>>[];
  autotile: WallAutotile | null;
};
export type Catalog = {
  tileSize: number;
  sheets: Record<string, string>;
  floors: Record<string, FloorFrame[]>;
  items: Record<string, ItemDef>;
  characters: CharactersDef;
};

// floor и entrance — ключевые слова legend, не предметы каталога.
export const RESERVED_NAMES: readonly string[] = ['floor', 'entrance'];

const allCells = (w: number, h: number): [number, number][] =>
  Array.from({ length: w * h }, (_, i) => [i % w, Math.floor(i / w)] as [number, number]);

export function loadCatalog(text: string, file = 'catalog.yaml'): Result<Catalog> {
  const parsed = parseYamlWith(file, text, CatalogFileSchema);
  if (!parsed.ok) return parsed;
  const f = parsed.value;
  const errors: MapError[] = [];
  const err = (code: string, message: string) => errors.push({ file, code, message });
  const checkParts = (where: string, parts: Part[]) => {
    for (const p of parts) if (!(p.sheet in f.sheets)) err('unknown_sheet', `${where}: лист «${p.sheet}» не описан в sheets`);
  };
  for (const [name, frames] of Object.entries(f.floors)) {
    for (const fr of frames) if (!(fr.sheet in f.sheets)) err('unknown_sheet', `floors.${name}: лист «${fr.sheet}» не описан в sheets`);
  }
  const items: Record<string, ItemDef> = {};
  for (const [id, it] of Object.entries(f.items)) {
    if (RESERVED_NAMES.includes(id)) {
      err('reserved_name', `items.${id}: имя зарезервировано для legend`);
      continue;
    }
    const [w, h] = it.size;
    const blocks = it.blocks === 'all' ? allCells(w, h) : it.blocks === 'none' ? [] : it.blocks;
    for (const [dx, dy] of blocks) if (dx >= w || dy >= h) err('block_outside', `items.${id}: блок [${dx},${dy}] вне размера ${w}×${h}`);
    if (it.autotile) {
      it.autotile.rules.forEach((rule, i) => checkParts(`items.${id}.autotile.rules[${i}]`, rule.parts));
      checkParts(`items.${id}.autotile.door`, it.autotile.door);
    } else if (it.variants.length === 0) {
      err('no_variants', `items.${id}: нет ни variants, ни autotile`);
    }
    const keys: ViewKey[] = it.facings ?? ['default'];
    it.variants.forEach((v, vi) => {
      for (const k of keys) if (!v[k]) err('missing_view', `items.${id}.variants[${vi}]: нет вида «${k}»`);
      for (const [k, view] of Object.entries(v)) {
        if (!view) continue;
        checkParts(`items.${id}.variants[${vi}].${k}`, view.parts);
        for (const s of view.spots) {
          if (s.cell[0] >= w || s.cell[1] >= h) err('spot_outside', `items.${id}.variants[${vi}].${k}: место [${s.cell.join(',')}] вне размера ${w}×${h}`);
        }
      }
    });
    items[id] = { id, size: [w, h], blocks, facings: it.facings ?? null, tags: it.tags, variants: it.variants, autotile: it.autotile ?? null };
  }
  if (!items['wall']?.autotile) err('wall_missing', 'нужен предмет wall с autotile');
  if (errors.length) return fail(errors);
  return ok({ tileSize: f.tileSize, sheets: f.sheets, floors: f.floors, items, characters: f.characters });
}

export function itemView(def: ItemDef, facing: Facing | null, variant: number): ItemView {
  const v = def.variants[variant - 1] ?? def.variants[0];
  return v?.[facing ?? 'default'] ?? { parts: [], spots: [] };
}
```

- [ ] **Step 6: экспорт и прогон**

`packages/core/src/index.ts`:
```ts
export { PROTOCOL_VERSION } from '@pixeloffice/protocol';
export * from './errors.ts';
export * from './yaml.ts';
export * from './catalog.ts';
```

Run: `pnpm vitest run packages/core` → PASS.

- [ ] **Step 7: настоящий каталог проходит загрузку**

Добавить в `catalog.test.ts`:
```ts
import { readFileSync } from 'node:fs';

it('catalog/limezu/catalog.yaml валиден', () => {
  const text = readFileSync(new URL('../../../catalog/limezu/catalog.yaml', import.meta.url), 'utf8');
  const r = loadCatalog(text);
  expect(r.ok ? [] : r.errors).toEqual([]);
});
```
Если падает — чинить `catalog.yaml` (а не схему), если только спайк не зафиксировал изменение схемы.

- [ ] **Step 8: гейт и коммит**

```bash
pnpm gate
git add packages/core
git commit -m "feat(core): загрузка каталога арт-пака с громкими ошибками"
```

**Критерий готовности:** 9 тестов каталога зелёные, включая реальный `catalog.yaml`.

---

### Задача 7: core — разбор `office.yaml`

**Files:**
- Create: `packages/core/src/office.ts`
- Modify: `packages/core/src/index.ts`, `packages/core/tests/fixtures.ts`
- Test: `packages/core/tests/office.test.ts`

**Interfaces:**
- Consumes: `Catalog`, `itemView`, `parseYamlWith`, `Result`, `MapError` (задача 6).
- Produces: `type CellKind = 'floor' | 'wall' | 'entrance'`, `type PlacedItem = { uid: string; item: string; x: number; y: number; facing: Facing | null; variant: number; tags: string[]; on: string | null; origin: 'grid' | 'placement' }` (`uid = "<item>@<x>,<y>"`, у предмета с `on` — `"<item>@<x>,<y>^<on>"`), `type Zone = { id: string; kind: 'pod' | 'meeting' | 'common'; rect: [x, y, w, h] }`, `type OfficeLayout = { width; height; base: CellKind[] /* y*width+x */; items: PlacedItem[]; zones: Zone[]; floor: { default: string; zones: Record<string, string> } }`, `parseOffice(text, catalog, file = 'office.yaml'): Result<OfficeLayout>`, `zoneContains(zone, x, y): boolean`, `zoneAt(zones, x, y): Zone | null` (первая по порядку). В `fixtures.ts`: `WORLD_OFFICE` (YAML) и `office(text?): OfficeLayout`.

- [ ] **Step 1: дописать фикстуру в `packages/core/tests/fixtures.ts`**

```ts
import { parseOffice, type OfficeLayout } from '../src/index.ts';

// Офис 14×7 для тестов: угол pod:a (хозяин + 3 агентских места), переговорка на 2, коворкинг на 2, лаунж с двумя аркадами.
export const WORLD_OFFICE = `
size: [14, 7]
floor:
  default: carpet
  zones: { lounge: wood }
legend:
  "#": wall
  ".": floor
  "E": entrance
  "D": desk
  "T": table
  "^": { item: chair, facing: up }
  "p": arcade
grid: |
  ##############
  #DDDD.TT..DD.#
  #^^^^.^^..^^.#
  #............#
  #p.p.........#
  #p.p.........#
  ######E#######
placements:
  - { item: chair, at: [1, 2], tags: [owner_seat] }
  - { item: monitor, at: [1, 1], on: desk }
zones:
  - { id: "pod:a", kind: pod, rect: [1, 1, 4, 2] }
  - { id: "meeting:m1", kind: meeting, rect: [6, 1, 2, 2] }
  - { id: coworking, kind: common, rect: [10, 1, 2, 2] }
  - { id: lounge, kind: common, rect: [1, 4, 3, 2] }
`;

export function office(text = WORLD_OFFICE): OfficeLayout {
  const r = parseOffice(text, miniCatalog());
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
}

// Минимальный офис из grid и legend (для негативных тестов разбора).
export const tinyOffice = (grid: string[], legend: Record<string, unknown>, extra: Record<string, unknown> = {}) =>
  mutateYaml('floor: { default: carpet }', (d) => {
    d.legend = { '#': 'wall', '.': 'floor', E: 'entrance', ...legend };
    d.grid = grid.join('\n') + '\n';
    Object.assign(d, extra);
  });
```

Импорт `parseOffice` добавить к существующему импорту из `../src/index.ts`.

- [ ] **Step 2: падающие тесты `packages/core/tests/office.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { parseOffice, zoneAt } from '../src/index.ts';
import { WORLD_OFFICE, miniCatalog, mutateYaml, office, tinyOffice } from './fixtures.ts';

const errs = (text: string) => {
  const r = parseOffice(text, miniCatalog());
  return r.ok ? [] : r.errors;
};
const codes = (text: string) => errs(text).map((e) => e.code);

describe('parseOffice', () => {
  it('разбирает офис: размеры, стены, вход, предметы', () => {
    const o = office();
    expect([o.width, o.height]).toEqual([14, 7]);
    expect(o.base[0]).toBe('wall');
    expect(o.base[6 * 14 + 6]).toBe('entrance');
    const desks = o.items.filter((i) => i.item === 'desk').map((i) => [i.x, i.y]);
    expect(desks).toEqual([[1, 1], [3, 1], [10, 1]]); // DDDD → два стола 2×1
    const owner = o.items.find((i) => i.item === 'chair' && i.x === 1 && i.y === 2)!;
    expect(owner.tags).toEqual(['owner_seat']); // аннотация, второго кресла нет
    expect(o.items.filter((i) => i.item === 'chair' && i.x === 1 && i.y === 2)).toHaveLength(1);
    const monitor = o.items.find((i) => i.item === 'monitor')!;
    expect(monitor).toMatchObject({ x: 1, y: 1, on: 'desk', origin: 'placement', uid: 'monitor@1,1^desk' });
    expect(o.items.filter((i) => i.item === 'arcade').map((i) => [i.x, i.y])).toEqual([[1, 4], [3, 4]]);
  });

  it('zoneAt находит зону клетки', () => {
    const o = office();
    expect(zoneAt(o.zones, 2, 2)?.id).toBe('pod:a');
    expect(zoneAt(o.zones, 8, 3)).toBeNull();
  });

  it('неполный footprint — ошибка с координатами', () => {
    const e = errs(tinyOffice(['####', '#D.#', '#E##'], { D: 'desk' }));
    expect(e.map((x) => x.code)).toContain('incomplete_footprint');
    expect(e.find((x) => x.code === 'incomplete_footprint')!.at).toEqual([1, 1]);
  });

  it('неполный вертикальный footprint (аркада 1×2 в одну строку)', () => {
    expect(codes(tinyOffice(['#####', '#.p.#', '#...#', '#E###'], { p: 'arcade' }))).toContain('incomplete_footprint');
  });

  it('строки grid разной длины', () => {
    expect(codes(tinyOffice(['####', '#..', '#E##'], {}))).toContain('grid_ragged');
  });

  it('size не совпадает с grid', () => {
    expect(codes(mutateYaml(WORLD_OFFICE, (d) => (d.size = [15, 7])))).toEqual(['size_mismatch']);
  });

  it('символа нет в legend — ошибка с координатами', () => {
    const e = errs(tinyOffice(['####', '#.x#', '#E##'], {}));
    expect(e).toEqual([expect.objectContaining({ code: 'unknown_symbol', at: [2, 1] })]);
  });

  it('предмет с направлениями без facing', () => {
    expect(codes(tinyOffice(['####', '#c.#', '#E##'], { c: 'chair' }))).toContain('facing_required');
  });

  it('неизвестный предмет', () => {
    expect(codes(tinyOffice(['####', '#z.#', '#E##'], { z: 'piano' }))).toContain('unknown_item');
  });

  it('placement «на» несуществующем предмете', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.placements.push({ item: 'monitor', at: [8, 3], on: 'desk' }));
    expect(codes(text)).toContain('on_target_missing');
  });

  it('новый предмет без on пересекает блокирующую клетку', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.placements.push({ item: 'plant', at: [2, 1] }));
    expect(codes(text)).toContain('overlap');
  });

  it('зона за пределами карты', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.zones.push({ id: 'far', kind: 'common', rect: [12, 5, 4, 4] }));
    expect(codes(text)).toContain('zone_out_of_bounds');
  });

  it('пол: неизвестная зона и неизвестный тип пола', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.floor.zones = { nowhere: 'wood', lounge: 'marble' }));
    expect(codes(text).sort()).toEqual(['unknown_floor', 'unknown_zone']);
  });

  it('собирает все ошибки сразу', () => {
    expect(errs(tinyOffice(['#####', '#x.y#', '#E###'], {})).length).toBe(2);
  });
});
```

Run: `pnpm vitest run packages/core/tests/office.test.ts` → FAIL.

- [ ] **Step 3: `packages/core/src/office.ts`**

```ts
import { z } from 'zod';
import { FacingSchema, type Facing } from '@pixeloffice/protocol';
import type { Catalog, ItemDef } from './catalog.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { parseYamlWith } from './yaml.ts';

const Int = z.number().int();
const LegendValue = z.union([
  z.string(),
  z.strictObject({ item: z.string(), facing: FacingSchema.optional(), variant: Int.min(1).optional(), tags: z.array(z.string()).optional() }),
]);
const OfficeFileSchema = z.strictObject({
  size: z.tuple([Int.positive(), Int.positive()]).optional(),
  floor: z.strictObject({ default: z.string(), zones: z.record(z.string(), z.string()).default({}) }),
  legend: z.record(z.string().length(1), LegendValue),
  grid: z.string().min(1),
  placements: z
    .array(
      z.strictObject({
        item: z.string(),
        at: z.tuple([Int.min(0), Int.min(0)]),
        on: z.string().optional(),
        facing: FacingSchema.optional(),
        variant: Int.min(1).optional(),
        tags: z.array(z.string()).optional(),
      }),
    )
    .default([]),
  zones: z
    .array(z.strictObject({ id: z.string().min(1), kind: z.enum(['pod', 'meeting', 'common']), rect: z.tuple([Int.min(0), Int.min(0), Int.positive(), Int.positive()]) }))
    .default([]),
});

export type CellKind = 'floor' | 'wall' | 'entrance';
export type PlacedItem = {
  uid: string;
  item: string;
  x: number;
  y: number;
  facing: Facing | null;
  variant: number;
  tags: string[];
  on: string | null;
  origin: 'grid' | 'placement';
};
export type Zone = { id: string; kind: 'pod' | 'meeting' | 'common'; rect: [number, number, number, number] };
export type OfficeLayout = {
  width: number;
  height: number;
  base: CellKind[];
  items: PlacedItem[];
  zones: Zone[];
  floor: { default: string; zones: Record<string, string> };
};

type LegendEntry =
  | { kind: CellKind }
  | { kind: 'item'; item: string; facing: Facing | null; variant: number; tags: string[] };

const KEYWORDS: Record<string, CellKind> = { wall: 'wall', floor: 'floor', entrance: 'entrance' };

export const zoneContains = (z: Zone, x: number, y: number) =>
  x >= z.rect[0] && y >= z.rect[1] && x < z.rect[0] + z.rect[2] && y < z.rect[1] + z.rect[3];
export const zoneAt = (zones: Zone[], x: number, y: number): Zone | null => zones.find((z) => zoneContains(z, x, y)) ?? null;

export function parseOffice(text: string, catalog: Catalog, file = 'office.yaml'): Result<OfficeLayout> {
  const parsed = parseYamlWith(file, text, OfficeFileSchema);
  if (!parsed.ok) return parsed;
  const f = parsed.value;
  const errors: MapError[] = [];
  const err = (code: string, message: string, at?: [number, number]) => errors.push(at ? { file, code, message, at } : { file, code, message });

  // 1. Геометрия grid.
  const rows = f.grid.replace(/\r/g, '').replace(/\n+$/, '').split('\n');
  const width = rows[0]?.length ?? 0;
  const height = rows.length;
  rows.forEach((r, y) => {
    if (r.length !== width) err('grid_ragged', `строка ${y} длиной ${r.length}, ожидалось ${width}`, [0, y]);
  });
  if (f.size && (f.size[0] !== width || f.size[1] !== height)) err('size_mismatch', `size [${f.size.join(', ')}] не совпадает с grid ${width}×${height}`);
  if (errors.length) return fail(errors);
  const inBounds = (x: number, y: number) => x >= 0 && y >= 0 && x < width && y < height;

  // 2. Legend.
  const checkFacing = (def: ItemDef, facing: Facing | undefined, where: string): Facing | null => {
    if (def.facings && !facing) err('facing_required', `${where}: у «${def.id}» есть направления (${def.facings.join(', ')}), нужен facing`);
    if (facing && (!def.facings || !def.facings.includes(facing))) err('facing_unsupported', `${where}: у «${def.id}» нет направления «${facing}»`);
    return facing ?? null;
  };
  const checkVariant = (def: ItemDef, variant: number, where: string) => {
    if (def.variants.length > 0 && variant > def.variants.length) err('unknown_variant', `${where}: у «${def.id}» нет варианта ${variant}`);
  };
  const legend = new Map<string, LegendEntry>();
  for (const [ch, v] of Object.entries(f.legend)) {
    const spec = typeof v === 'string' ? { item: v } : v;
    const kw = KEYWORDS[spec.item];
    if (kw) {
      legend.set(ch, { kind: kw });
      continue;
    }
    const def = catalog.items[spec.item];
    if (!def) {
      err('unknown_item', `символ '${ch}': предмета «${spec.item}» нет в каталоге`);
      continue;
    }
    const facing = checkFacing(def, spec.facing, `символ '${ch}'`);
    const variant = 'variant' in spec && spec.variant ? spec.variant : 1;
    checkVariant(def, variant, `символ '${ch}'`);
    legend.set(ch, { kind: 'item', item: spec.item, facing, variant, tags: 'tags' in spec && spec.tags ? spec.tags : [] });
  }

  // 3. Жадный разбор footprint: слева направо, сверху вниз (спека 5.1).
  const base: CellKind[] = new Array<CellKind>(width * height).fill('floor');
  const claimed = new Uint8Array(width * height);
  const items: PlacedItem[] = [];
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const ch = rows[y]![x]!;
      const e = legend.get(ch);
      if (!e) {
        if (!(ch in f.legend)) err('unknown_symbol', `символа '${ch}' нет в legend`, [x, y]);
        continue;
      }
      if (e.kind !== 'item') {
        base[y * width + x] = e.kind;
        continue;
      }
      if (claimed[y * width + x]) continue;
      const [w, h] = catalog.items[e.item]!.size;
      let complete = true;
      for (let dy = 0; dy < h; dy++)
        for (let dx = 0; dx < w; dx++) {
          const xx = x + dx;
          const yy = y + dy;
          if (!inBounds(xx, yy) || rows[yy]![xx] !== ch || claimed[yy * width + xx]) complete = false;
        }
      if (!complete) {
        err('incomplete_footprint', `«${e.item}» ${w}×${h} с символа '${ch}': неполный прямоугольник`, [x, y]);
        claimed[y * width + x] = 1;
        continue;
      }
      for (let dy = 0; dy < h; dy++) for (let dx = 0; dx < w; dx++) claimed[(y + dy) * width + x + dx] = 1;
      items.push({ uid: `${e.item}@${x},${y}`, item: e.item, x, y, facing: e.facing, variant: e.variant, tags: [...e.tags], on: null, origin: 'grid' });
    }
  }

  // 4. Placements: аннотация или новый предмет.
  const covers = (it: PlacedItem, x: number, y: number) => {
    const [w, h] = catalog.items[it.item]!.size;
    return x >= it.x && y >= it.y && x < it.x + w && y < it.y + h;
  };
  f.placements.forEach((p, i) => {
    const where = `placements[${i}]`;
    const [x, y] = p.at;
    if (!inBounds(x, y)) return err('placement_out_of_bounds', `${where}: клетка вне карты`, [x, y]);
    const def = catalog.items[p.item];
    if (!def) return err('unknown_item', `${where}: предмета «${p.item}» нет в каталоге`, [x, y]);
    const existing = items.find((it) => it.origin === 'grid' && it.item === p.item && it.x === x && it.y === y);
    if (existing) {
      if (p.facing && p.facing !== existing.facing) err('annotation_facing', `${where}: аннотация меняет facing предмета из grid`, [x, y]);
      if (p.variant) {
        checkVariant(def, p.variant, where);
        existing.variant = p.variant;
      }
      if (p.tags) existing.tags.push(...p.tags);
      return;
    }
    const [w, h] = def.size;
    if (!inBounds(x + w - 1, y + h - 1)) return err('placement_out_of_bounds', `${where}: «${p.item}» ${w}×${h} не помещается в карту`, [x, y]);
    const facing = checkFacing(def, p.facing, where);
    const variant = p.variant ?? 1;
    checkVariant(def, variant, where);
    if (p.on && !items.some((it) => it.item === p.on && covers(it, x, y))) {
      err('on_target_missing', `${where}: под (${x},${y}) нет предмета «${p.on}»`, [x, y]);
    }
    items.push({ uid: `${p.item}@${x},${y}${p.on ? `^${p.on}` : ''}`, item: p.item, x, y, facing, variant, tags: p.tags ?? [], on: p.on ?? null, origin: 'placement' });
  });

  // 5. Пересечения блокирующих клеток (кроме предметов «на» других).
  const blockedBy = new Map<number, string>();
  for (const it of items) {
    if (it.on) continue;
    for (const [dx, dy] of catalog.items[it.item]!.blocks) {
      const cx = it.x + dx;
      const cy = it.y + dy;
      const idx = cy * width + cx;
      if (base[idx] !== 'floor') {
        err('overlap', `«${it.uid}» блокирует клетку стены или входа`, [cx, cy]);
        continue;
      }
      const other = blockedBy.get(idx);
      if (other) err('overlap', `«${it.uid}» и «${other}» блокируют одну клетку`, [cx, cy]);
      else blockedBy.set(idx, it.uid);
    }
  }

  // 6. Зоны и пол.
  const zoneIds = new Set<string>();
  for (const z of f.zones) {
    if (zoneIds.has(z.id)) err('zone_duplicate', `зона «${z.id}» описана дважды`);
    zoneIds.add(z.id);
    const [x, y, w, h] = z.rect;
    if (!inBounds(x, y) || !inBounds(x + w - 1, y + h - 1)) err('zone_out_of_bounds', `зона «${z.id}» выходит за карту`, [x, y]);
  }
  if (!catalog.floors[f.floor.default]) err('unknown_floor', `floor.default: типа пола «${f.floor.default}» нет в каталоге`);
  for (const [zid, type] of Object.entries(f.floor.zones)) {
    if (!zoneIds.has(zid)) err('unknown_zone', `floor.zones: зоны «${zid}» нет в zones`);
    if (!catalog.floors[type]) err('unknown_floor', `floor.zones.${zid}: типа пола «${type}» нет в каталоге`);
  }

  if (errors.length) return fail(errors);
  return ok({ width, height, base, items, zones: f.zones, floor: f.floor });
}
```

- [ ] **Step 4: экспорт и прогон**

В `packages/core/src/index.ts` добавить `export * from './office.ts';`.

Run: `pnpm vitest run packages/core` → PASS.

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

```bash
pnpm gate
git add packages/core
git commit -m "feat(core): разбор схемы офиса office.yaml"
```

**Критерий готовности:** все тесты `office.test.ts` зелёные. Каждая ошибка разбора grid несёт координаты.

---

### Задача 8: core — `config.yaml`, `rules.yaml`, длительности

**Files:**
- Create: `packages/core/src/{duration.ts,config.ts,rules.ts}`
- Modify: `packages/core/src/index.ts`, `packages/core/tests/fixtures.ts`
- Test: `packages/core/tests/config.test.ts`, `packages/core/tests/rules.test.ts`

**Interfaces:**
- Produces:
  - `duration.ts`: `parseDuration(s: string): number` (мс; `500ms`, `20s`, `2m`, `1h`; иначе бросает `Error`).
  - `config.ts`: `type SourceConfig = { source: string; token: string; owner?: string; ttlSec?: number | Partial<Record<Status, number>> }`, `type Person = { id; name; nextcloudUid?; pod: string; avatar: AvatarParts }`, `type OfficeConfig = { officeId; catalog: string; listen: { host; port }; assetsDir; dataDir; log: { keepDays }; agentRetentionDays; viewerTokens: string[]; sources: SourceConfig[]; people: Person[]; nextcloud: { statusMap: Record<string, 'online'|'offline'> }; bubbles: { talk: 'full'|'truncated'|'typing_only' }; relay?: { target; token; include: string[] } }`, `DEFAULT_STATUS_MAP`, `parseConfig(text, file = 'config.yaml'): Result<OfficeConfig>`.
  - `rules.ts`: `type RuleTarget = { kind: 'own_seat'|'owner_pod_seat'|'meeting_room'|'meeting_room_standing'|'current_work_seat'|'stay'|'exit' } | { kind: 'zone'; zoneId: string; pose?: Pose; tag?: string }`, `type Rules = { dwellMs: { agent: number; human: number }; human: Record<HumanStatus, RuleTarget[]>; agent: Record<AgentStatus, RuleTarget[]> }`, `parseTarget(s): RuleTarget | null`, `parseRules(text, file = 'rules.yaml', zoneIds?: ReadonlySet<string>): Result<Rules>`.
  - `fixtures.ts`: `MINI_CONFIG`, `MINI_RULES` (YAML).

- [ ] **Step 1: фикстуры (дописать в `packages/core/tests/fixtures.ts`)**

```ts
export const MINI_CONFIG = `
officeId: test
assetsDir: ./assets-missing
dataDir: ./.data/test
viewerTokens: [viewer-token-1]
sources:
  - { source: claude-hook, token: hook-token-1, owner: a, ttlSec: { working: 900, idle: 43200, needs_input: 43200 } }
  - { source: nextcloud, token: nc-token-1, ttlSec: 120 }
people:
  - { id: a, name: Анна, nextcloudUid: anna, pod: "pod:a", avatar: { body: 1, eyes: 1, outfit: [1, 1], hair: [1, 1] } }
`;

export const MINI_RULES = `
dwell: { agent: 20s, human: 60s }
human:
  online: [own_seat]
  meeting: [meeting_room, meeting_room_standing]
  offline: [exit]
agent:
  working: [owner_pod_seat, "zone:coworking:pose=sit"]
  idle: ["zone:lounge:pose=play", "zone:lounge"]
  needs_input: [current_work_seat, owner_pod_seat, "zone:coworking:pose=sit"]
  offline: [exit]
`;
```

- [ ] **Step 2: падающие тесты `packages/core/tests/config.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { parseConfig, parseDuration } from '../src/index.ts';
import { MINI_CONFIG, mutateYaml } from './fixtures.ts';

describe('parseDuration', () => {
  it('единицы ms, s, m, h', () => {
    expect([parseDuration('500ms'), parseDuration('20s'), parseDuration('2m'), parseDuration('1h')]).toEqual([500, 20_000, 120_000, 3_600_000]);
  });
  it('мусор → ошибка', () => {
    expect(() => parseDuration('20 секунд')).toThrow();
  });
});

describe('parseConfig', () => {
  it('мини-конфиг с умолчаниями', () => {
    const r = parseConfig(MINI_CONFIG);
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    expect(r.value.listen).toEqual({ host: '127.0.0.1', port: 4870 });
    expect(r.value.log.keepDays).toBe(30);
    expect(r.value.agentRetentionDays).toBe(7);
    expect(r.value.catalog).toBe('../../catalog/limezu/catalog.yaml');
    expect(r.value.nextcloud.statusMap['away']).toBe('online');
    expect(r.value.nextcloud.statusMap['invisible']).toBe('offline');
    expect(r.value.bubbles.talk).toBe('truncated');
    expect(r.value.sources[0]!.owner).toBe('a');
  });

  it('повтор токена → ошибка', () => {
    const r = parseConfig(mutateYaml(MINI_CONFIG, (d) => (d.sources[1].token = 'hook-token-1')));
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toContain('token_duplicate');
  });

  it('повтор id человека → ошибка', () => {
    const r = parseConfig(mutateYaml(MINI_CONFIG, (d) => d.people.push({ ...d.people[0] })));
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toContain('person_duplicate');
  });

  it('лишний ключ → ошибка схемы', () => {
    expect(parseConfig(mutateYaml(MINI_CONFIG, (d) => (d.colour = 1))).ok).toBe(false);
  });
});
```

- [ ] **Step 3: падающие тесты `packages/core/tests/rules.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { parseRules, parseTarget } from '../src/index.ts';
import { MINI_RULES, mutateYaml } from './fixtures.ts';

describe('parseTarget', () => {
  it('словарь целей (спека 5.3)', () => {
    expect(parseTarget('own_seat')).toEqual({ kind: 'own_seat' });
    expect(parseTarget('exit')).toEqual({ kind: 'exit' });
    expect(parseTarget('zone:lounge')).toEqual({ kind: 'zone', zoneId: 'lounge' });
    expect(parseTarget('zone:lounge:pose=play')).toEqual({ kind: 'zone', zoneId: 'lounge', pose: 'play' });
    expect(parseTarget('zone:coworking:tag=quiet')).toEqual({ kind: 'zone', zoneId: 'coworking', tag: 'quiet' });
    expect(parseTarget('zone:pod:a')).toEqual({ kind: 'zone', zoneId: 'pod:a' });
    expect(parseTarget('zone:meeting:m1:pose=sit')).toEqual({ kind: 'zone', zoneId: 'meeting:m1', pose: 'sit' });
    expect(parseTarget('zone:x:pose=fly')).toBeNull();
    expect(parseTarget('sofa_seat')).toBeNull();
  });
});

describe('parseRules', () => {
  it('мини-правила', () => {
    const r = parseRules(MINI_RULES);
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    expect(r.value.dwellMs).toEqual({ agent: 20_000, human: 60_000 });
    expect(r.value.agent.working[1]).toEqual({ kind: 'zone', zoneId: 'coworking', pose: 'sit' });
    expect(r.value.human.meeting.map((t) => t.kind)).toEqual(['meeting_room', 'meeting_room_standing']);
  });

  it('неизвестная цель — ошибка с путём', () => {
    const r = parseRules(mutateYaml(MINI_RULES, (d) => (d.agent.idle[0] = 'sofa_seat')));
    expect(r.ok).toBe(false);
    if (!r.ok) expect(r.errors[0]).toMatchObject({ code: 'unknown_target', message: expect.stringContaining('agent.idle[0]') });
  });

  it('ссылка на несуществующую зону при известном списке зон', () => {
    const r = parseRules(MINI_RULES, 'rules.yaml', new Set(['lounge']));
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toContain('unknown_zone');
  });

  it('нет статуса в правилах → ошибка схемы', () => {
    expect(parseRules(mutateYaml(MINI_RULES, (d) => delete d.agent.needs_input)).ok).toBe(false);
  });

  it('dwell по умолчанию 20 с / 60 с', () => {
    const r = parseRules(mutateYaml(MINI_RULES, (d) => delete d.dwell));
    expect(r.ok && r.value.dwellMs).toEqual({ agent: 20_000, human: 60_000 });
  });
});
```

Run: `pnpm vitest run packages/core` → FAIL.

- [ ] **Step 4: `packages/core/src/duration.ts`**

```ts
const UNITS: Record<string, number> = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 };

export function parseDuration(s: string): number {
  const m = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(s.trim());
  if (!m) throw new Error(`длительность «${s}»: ожидается число с единицей ms, s, m или h`);
  return Math.round(Number(m[1]) * UNITS[m[2]!]!);
}
```

- [ ] **Step 5: `packages/core/src/config.ts`**

```ts
import { z } from 'zod';
import { AvatarPartsSchema, StatusSchema } from '@pixeloffice/protocol';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { parseYamlWith } from './yaml.ts';

export const DEFAULT_STATUS_MAP: Record<string, 'online' | 'offline'> = {
  online: 'online',
  away: 'online',
  dnd: 'online',
  busy: 'online',
  invisible: 'offline',
  offline: 'offline',
};

const Token = z.string().min(8);
const SourceSchema = z.strictObject({
  source: z.string().min(1),
  token: Token,
  owner: z.string().min(1).optional(),
  ttlSec: z.union([z.number().int().positive(), z.partialRecord(StatusSchema, z.number().int().positive())]).optional(),
});
const PersonSchema = z.strictObject({
  id: z.string().regex(/^[A-Za-z0-9_-]+$/, 'id человека: латиница, цифры, _ и -'),
  name: z.string().min(1),
  nextcloudUid: z.string().min(1).optional(),
  pod: z.string().min(1),
  avatar: AvatarPartsSchema,
});
const ConfigSchema = z.strictObject({
  officeId: z.string().min(1),
  catalog: z.string().default('../../catalog/limezu/catalog.yaml'),
  listen: z
    .strictObject({ host: z.string().default('127.0.0.1'), port: z.number().int().min(0).max(65_535).default(4870) })
    .default({ host: '127.0.0.1', port: 4870 }),
  assetsDir: z.string().min(1),
  dataDir: z.string().min(1),
  log: z.strictObject({ keepDays: z.number().int().positive().default(30) }).default({ keepDays: 30 }),
  agentRetentionDays: z.number().positive().default(7),
  viewerTokens: z.array(Token).min(1),
  sources: z.array(SourceSchema).default([]),
  people: z.array(PersonSchema).default([]),
  nextcloud: z
    .strictObject({ statusMap: z.record(z.string(), z.enum(['online', 'offline'])).default(DEFAULT_STATUS_MAP) })
    .default({ statusMap: DEFAULT_STATUS_MAP }),
  bubbles: z.strictObject({ talk: z.enum(['full', 'truncated', 'typing_only']).default('truncated') }).default({ talk: 'truncated' }),
  relay: z.strictObject({ target: z.url(), token: Token, include: z.array(z.string().min(1)).min(1) }).optional(),
});

export type OfficeConfig = z.output<typeof ConfigSchema>;
export type SourceConfig = z.output<typeof SourceSchema>;
export type Person = z.output<typeof PersonSchema>;

export function parseConfig(text: string, file = 'config.yaml'): Result<OfficeConfig> {
  const r = parseYamlWith(file, text, ConfigSchema);
  if (!r.ok) return r;
  const c = r.value;
  const errors: MapError[] = [];
  const seen = (list: string[], code: string, what: string) => {
    const s = new Set<string>();
    for (const v of list) {
      if (s.has(v)) errors.push({ file, code, message: `${what} «${v.length > 12 ? v.slice(0, 4) + '…' : v}» встречается дважды` });
      s.add(v);
    }
  };
  seen([...c.viewerTokens, ...c.sources.map((s) => s.token), ...(c.relay ? [c.relay.token] : [])], 'token_duplicate', 'токен');
  seen(c.sources.map((s) => s.source), 'source_duplicate', 'источник');
  seen(c.people.map((p) => p.id), 'person_duplicate', 'человек');
  return errors.length ? fail(errors) : ok(c);
}
```

- [ ] **Step 6: `packages/core/src/rules.ts`**

```ts
import { z } from 'zod';
import type { AgentStatus, HumanStatus, Pose } from '@pixeloffice/protocol';
import { parseDuration } from './duration.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { parseYamlWith } from './yaml.ts';

export type RuleTarget =
  | { kind: 'own_seat' | 'owner_pod_seat' | 'meeting_room' | 'meeting_room_standing' | 'current_work_seat' | 'stay' | 'exit' }
  | { kind: 'zone'; zoneId: string; pose?: Pose; tag?: string };
export type Rules = {
  dwellMs: { agent: number; human: number };
  human: Record<HumanStatus, RuleTarget[]>;
  agent: Record<AgentStatus, RuleTarget[]>;
};

const SIMPLE = new Set(['own_seat', 'owner_pod_seat', 'meeting_room', 'meeting_room_standing', 'current_work_seat', 'stay', 'exit']);
const POSES = new Set(['sit', 'stand', 'play']);
// id зоны может содержать «:» (`pod:stas`, `meeting:m1`, спека 5.1), поэтому id разбирается лениво до необязательного суффикса.
const ZONE_RE = /^zone:([^=]+?)(?::(pose|tag)=([^:=]+))?$/;

export function parseTarget(s: string): RuleTarget | null {
  if (SIMPLE.has(s)) return { kind: s } as RuleTarget;
  const m = ZONE_RE.exec(s);
  if (!m) return null;
  const zoneId = m[1]!;
  if (!m[2]) return { kind: 'zone', zoneId };
  if (m[2] === 'pose') return POSES.has(m[3]!) ? { kind: 'zone', zoneId, pose: m[3] as Pose } : null;
  return { kind: 'zone', zoneId, tag: m[3]! };
}

const Duration = z.string().regex(/^\d+(\.\d+)?(ms|s|m|h)$/, 'длительность вида 20s').transform(parseDuration);
const List = z.array(z.string()).min(1);
const RulesFileSchema = z.strictObject({
  dwell: z.strictObject({ agent: Duration, human: Duration }).default({ agent: 20_000, human: 60_000 }),
  human: z.strictObject({ online: List, meeting: List, offline: List }),
  agent: z.strictObject({ working: List, idle: List, needs_input: List, offline: List }),
});

export function parseRules(text: string, file = 'rules.yaml', zoneIds?: ReadonlySet<string>): Result<Rules> {
  const r = parseYamlWith(file, text, RulesFileSchema);
  if (!r.ok) return r;
  const errors: MapError[] = [];
  const convert = <K extends string>(group: 'human' | 'agent', src: Record<K, string[]>): Record<K, RuleTarget[]> => {
    const out = {} as Record<K, RuleTarget[]>;
    for (const key of Object.keys(src) as K[]) {
      out[key] = src[key].flatMap((s, i) => {
        const t = parseTarget(s);
        if (!t) {
          errors.push({ file, code: 'unknown_target', message: `${group}.${key}[${i}]: неизвестная цель «${s}»` });
          return [];
        }
        if (t.kind === 'zone' && zoneIds && !zoneIds.has(t.zoneId)) {
          errors.push({ file, code: 'unknown_zone', message: `${group}.${key}[${i}]: зоны «${t.zoneId}» нет в office.yaml` });
        }
        return [t];
      });
    }
    return out;
  };
  const human = convert('human', r.value.human);
  const agent = convert('agent', r.value.agent);
  if (errors.length) return fail(errors);
  return ok({ dwellMs: r.value.dwell, human, agent });
}
```

- [ ] **Step 7: экспорт, прогон, гейт, коммит**

В `packages/core/src/index.ts` добавить:
```ts
export * from './duration.ts';
export * from './config.ts';
export * from './rules.ts';
```

```bash
pnpm vitest run packages/core     # PASS
pnpm gate
git add packages/core
git commit -m "feat(core): разбор config.yaml и rules.yaml"
```

**Критерий готовности:** тесты конфига и правил зелёные. Ошибки правил содержат путь вида `agent.idle[0]`.

---

### Задача 9: core — WorldMap, структурная валидация, загрузка офиса; CLI `validate:maps`

**Files:**
- Create: `packages/core/src/{world-map.ts,validate.ts,bundle.ts}`
- Create: `tools/validate-maps/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts}`, `tools/validate-maps/src/{read.ts,validate.ts,index.ts,cli.ts}`
- Modify: `packages/core/src/index.ts`, `packages/core/tests/fixtures.ts`, корневой `package.json`
- Test: `packages/core/tests/{world-map.test.ts,validate.test.ts,bundle.test.ts}`, `tools/validate-maps/tests/validate.test.ts`

**Interfaces:**
- Consumes: `parseOffice`, `OfficeLayout`, `Zone`, `zoneAt`, `Catalog`, `itemView`, `parseConfig`, `OfficeConfig`, `parseRules`, `Rules`, `loadCatalog`, `Result`.
- Produces:
  - `type Spot = { id: string; x: number; y: number; facing: Facing; pose: Pose; offset: [number, number]; tags: string[]; itemUid: string; zoneId: string | null }` (`id = "<itemUid>#<индекс места>"`).
  - `class WorldMap { width; height; spots: Spot[] /* по (y, x, id) */; zones: Zone[]; entrances: [number, number][]; constructor(init: { width; height; blocked: Uint8Array; spots; zones; entrances }); inBounds(x, y); isBlocked(x, y) /* вне карты → true */; spotAt(x, y): Spot | undefined; spot(id): Spot | undefined; spotsInZone(zoneId): Spot[]; isTransit(x, y) /* в карте, не блок, не место */; entrance(): [number, number] }`.
  - `buildWorldMap(layout, catalog, file = 'office.yaml'): Result<WorldMap>`.
  - `reachableFrom(map, start: [number, number]): Uint8Array`; `validateWorld(map, config, file = 'office.yaml'): MapError[]`.
  - `type OfficeTexts = { office: string; rules: string; config: string; catalog: string; files?: Partial<Record<'office'|'rules'|'config'|'catalog', string>> }`, `type OfficeBundle = { catalog; config; layout; map; rules }`, `loadOfficeBundle(t): Result<OfficeBundle>`.
  - `@pixeloffice/validate-maps`: `expandHome(p)`, `resolveFrom(baseDir, p)`, `type OfficeFiles = { dir; configPath; officePath; rulesPath; catalogPath }`, `officeFiles(dir)`, `readOfficeTexts(dir): { files: OfficeFiles; texts: OfficeTexts }`, `type DirReport = { dir: string; errors: string[]; notes: string[] }`, `validateOfficesDir(root): Promise<DirReport[]>`.
  - В `fixtures.ts`: `asciiMap(rows: string[]): WorldMap`, `bundle(overrides?): OfficeBundle`.

- [ ] **Step 1: падающие тесты `packages/core/tests/world-map.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { buildWorldMap } from '../src/index.ts';
import { WORLD_OFFICE, miniCatalog, mutateYaml, office } from './fixtures.ts';

const build = (text = WORLD_OFFICE) => buildWorldMap(office(text), miniCatalog());

describe('buildWorldMap', () => {
  it('места, блоки, транзит, вход', () => {
    const r = build();
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    const m = r.value;
    expect(m.spots).toHaveLength(10);
    const owner = m.spotAt(1, 2)!;
    expect(owner).toMatchObject({ pose: 'sit', facing: 'up', zoneId: 'pod:a', offset: [0, -4] });
    expect(owner.tags).toContain('owner_seat');
    expect(m.spotAt(1, 5)).toMatchObject({ pose: 'play', facing: 'up', zoneId: 'lounge' });
    expect(m.isBlocked(1, 1)).toBe(true); // стол
    expect(m.isBlocked(1, 4)).toBe(true); // верх аркады
    expect(m.isBlocked(-1, 0)).toBe(true); // вне карты
    expect(m.isTransit(1, 3)).toBe(true);
    expect(m.isTransit(1, 2)).toBe(false); // место — цель, но не транзит
    expect(m.entrance()).toEqual([6, 6]);
    expect(m.spotsInZone('meeting:m1').map((s) => [s.x, s.y])).toEqual([[6, 2], [7, 2]]);
  });

  it('место на блокирующей клетке → spot_blocked', () => {
    const r = build(mutateYaml(WORLD_OFFICE, (d) => d.placements.push({ item: 'plant', at: [1, 5] })));
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toContain('spot_blocked');
  });

  it('два места в одной клетке → spot_duplicate', () => {
    const r = build(
      mutateYaml(WORLD_OFFICE, (d) =>
        d.placements.push({ item: 'chair', at: [8, 3], facing: 'up' }, { item: 'chair', at: [8, 3], facing: 'down' }),
      ),
    );
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toContain('spot_duplicate');
  });
});
```

- [ ] **Step 2: падающие тесты `packages/core/tests/validate.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { buildWorldMap, parseConfig, validateWorld } from '../src/index.ts';
import { MINI_CONFIG, WORLD_OFFICE, miniCatalog, mutateYaml, office, tinyOffice } from './fixtures.ts';

const config = (fn?: (d: any) => void) => {
  const r = parseConfig(fn ? mutateYaml(MINI_CONFIG, fn) : MINI_CONFIG);
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
};
const noPeople = (d: any) => (d.people = []);
const errorsOf = (officeText: string, cfg = config()) => {
  const m = buildWorldMap(office(officeText), miniCatalog());
  if (!m.ok) throw new Error(JSON.stringify(m.errors));
  return validateWorld(m.value, cfg);
};

describe('validateWorld', () => {
  it('тестовый офис валиден', () => {
    expect(errorsOf(WORLD_OFFICE)).toEqual([]);
  });

  it('регрессия v1: вход в стене (за входом стол)', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.grid = d.grid.replace('#p.p.........#\n######E', '#p.p..DD.....#\n######E')));
    expect(errorsOf(text).map((e) => e.code)).toContain('entrance_enclosed');
  });

  it('регрессия v1 (d9): карман — кресло окружено фикусами', () => {
    const text = tinyOffice(['#######', '#^f...#', '#f....#', '#.....#', '###E###'], { '^': { item: 'chair', facing: 'up' }, f: 'plant' });
    const e = errorsOf(text, config(noPeople));
    expect(e).toEqual([expect.objectContaining({ code: 'spot_unreachable', at: [1, 1] })]);
  });

  it('регрессия v1 (d4): места не транзит — среднее кресло в ряду у стены недостижимо', () => {
    const text = tinyOffice(['######', '#vvv.#', '#DD..#', '#....#', '##E###'], { v: { item: 'chair', facing: 'down' }, D: 'desk' });
    const at = errorsOf(text, config(noPeople)).filter((e) => e.code === 'spot_unreachable').map((e) => e.at);
    expect(at).toEqual([[1, 1], [2, 1]]);
  });

  it('нет входа', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.grid = d.grid.replace('E', '#')));
    expect(errorsOf(text).map((e) => e.code)).toContain('entrance_missing');
  });

  it('угол человека: нет зоны, не pod, общий угол, углов меньше людей', () => {
    expect(errorsOf(WORLD_OFFICE, config((d) => (d.people[0].pod = 'pod:zzz'))).map((e) => e.code)).toContain('person_pod_missing');
    expect(errorsOf(WORLD_OFFICE, config((d) => (d.people[0].pod = 'lounge'))).map((e) => e.code)).toContain('person_pod_kind');
    const two = config((d) => d.people.push({ ...d.people[0], id: 'b' }));
    expect(errorsOf(WORLD_OFFICE, two).map((e) => e.code).sort()).toEqual(['pod_shared', 'pods_too_few']);
  });

  it('в углу ровно один owner_seat', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.placements = d.placements.filter((p: any) => !p.tags)));
    expect(errorsOf(text).map((e) => e.code)).toContain('owner_seat_count');
  });
});
```

- [ ] **Step 3: падающий тест `packages/core/tests/bundle.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { loadOfficeBundle } from '../src/index.ts';
import { MINI_CATALOG, MINI_CONFIG, MINI_RULES, WORLD_OFFICE, mutateYaml } from './fixtures.ts';

const texts = { office: WORLD_OFFICE, rules: MINI_RULES, config: MINI_CONFIG, catalog: MINI_CATALOG };

describe('loadOfficeBundle', () => {
  it('собирает офис целиком', () => {
    const r = loadOfficeBundle(texts);
    expect(r.ok ? [] : r.errors).toEqual([]);
    if (r.ok) expect(r.value.map.spots).toHaveLength(10);
  });

  it('правила ссылаются на несуществующую зону', () => {
    const r = loadOfficeBundle({ ...texts, rules: mutateYaml(MINI_RULES, (d) => (d.agent.idle = ['zone:arcade'])) });
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toContain('unknown_zone');
  });

  it('ошибки каталога и конфига приходят вместе, у каждой — имя файла', () => {
    const r = loadOfficeBundle({ ...texts, catalog: 'version: 2', config: 'officeId: 1', files: { catalog: 'cat.yaml' } });
    expect(r.ok).toBe(false);
    if (!r.ok) expect(new Set(r.errors.map((e) => e.file))).toEqual(new Set(['cat.yaml', 'config.yaml']));
  });
});
```

Run: `pnpm vitest run packages/core` → FAIL.

- [ ] **Step 4: `packages/core/src/world-map.ts`**

```ts
import type { Facing, Pose } from '@pixeloffice/protocol';
import { itemView, type Catalog } from './catalog.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { zoneAt, type OfficeLayout, type Zone } from './office.ts';

export type Spot = {
  id: string;
  x: number;
  y: number;
  facing: Facing;
  pose: Pose;
  offset: [number, number];
  tags: string[];
  itemUid: string;
  zoneId: string | null;
};

export class WorldMap {
  readonly width: number;
  readonly height: number;
  readonly spots: Spot[];
  readonly zones: Zone[];
  readonly entrances: [number, number][];
  private readonly blocked: Uint8Array;
  private readonly byCell = new Map<number, Spot>();
  private readonly byId = new Map<string, Spot>();
  private readonly byZone = new Map<string, Spot[]>();

  constructor(init: { width: number; height: number; blocked: Uint8Array; spots: Spot[]; zones: Zone[]; entrances: [number, number][] }) {
    this.width = init.width;
    this.height = init.height;
    this.blocked = init.blocked;
    this.spots = [...init.spots].sort((a, b) => a.y - b.y || a.x - b.x || a.id.localeCompare(b.id));
    this.zones = init.zones;
    this.entrances = init.entrances;
    for (const s of this.spots) {
      this.byCell.set(s.y * this.width + s.x, s);
      this.byId.set(s.id, s);
      if (s.zoneId) this.byZone.set(s.zoneId, [...(this.byZone.get(s.zoneId) ?? []), s]);
    }
  }

  inBounds(x: number, y: number): boolean {
    return x >= 0 && y >= 0 && x < this.width && y < this.height;
  }
  isBlocked(x: number, y: number): boolean {
    return !this.inBounds(x, y) || this.blocked[y * this.width + x] === 1;
  }
  spotAt(x: number, y: number): Spot | undefined {
    return this.inBounds(x, y) ? this.byCell.get(y * this.width + x) : undefined;
  }
  spot(id: string): Spot | undefined {
    return this.byId.get(id);
  }
  spotsInZone(zoneId: string): Spot[] {
    return this.byZone.get(zoneId) ?? [];
  }
  // Транзит — пол без блокирующих предметов и без мест (спека 5.4).
  isTransit(x: number, y: number): boolean {
    return !this.isBlocked(x, y) && this.spotAt(x, y) === undefined;
  }
  entrance(): [number, number] {
    const e = this.entrances[0];
    if (!e) throw new Error('у карты нет входа');
    return e;
  }
}

export function buildWorldMap(layout: OfficeLayout, catalog: Catalog, file = 'office.yaml'): Result<WorldMap> {
  const { width, height } = layout;
  const errors: MapError[] = [];
  const blocked = new Uint8Array(width * height);
  layout.base.forEach((k, i) => {
    if (k === 'wall') blocked[i] = 1;
  });
  for (const it of layout.items) {
    for (const [dx, dy] of catalog.items[it.item]!.blocks) blocked[(it.y + dy) * width + it.x + dx] = 1;
  }
  const spots: Spot[] = [];
  const taken = new Map<number, string>();
  for (const it of layout.items) {
    const view = itemView(catalog.items[it.item]!, it.facing, it.variant);
    view.spots.forEach((s, i) => {
      const x = it.x + s.cell[0];
      const y = it.y + s.cell[1];
      const idx = y * width + x;
      const id = `${it.uid}#${i}`;
      if (blocked[idx]) return errors.push({ file, code: 'spot_blocked', message: `место ${id} на блокирующей клетке`, at: [x, y] });
      const other = taken.get(idx);
      if (other) return errors.push({ file, code: 'spot_duplicate', message: `места ${other} и ${id} в одной клетке`, at: [x, y] });
      taken.set(idx, id);
      spots.push({
        id,
        x,
        y,
        facing: s.facing ?? it.facing ?? 'down',
        pose: s.pose,
        offset: s.offset,
        tags: [...s.tags, ...it.tags],
        itemUid: it.uid,
        zoneId: zoneAt(layout.zones, x, y)?.id ?? null,
      });
    });
  }
  const entrances: [number, number][] = [];
  layout.base.forEach((k, i) => {
    if (k === 'entrance') entrances.push([i % width, Math.floor(i / width)]);
  });
  if (errors.length) return fail(errors);
  return ok(new WorldMap({ width, height, blocked, spots, zones: layout.zones, entrances }));
}
```

- [ ] **Step 5: `packages/core/src/validate.ts`**

```ts
import type { OfficeConfig } from './config.ts';
import type { MapError } from './errors.ts';
import type { WorldMap } from './world-map.ts';

const DIRS: [number, number][] = [[0, -1], [1, 0], [0, 1], [-1, 0]];

// BFS по транзитным клеткам от start (start — сам транзитный).
export function reachableFrom(map: WorldMap, start: [number, number]): Uint8Array {
  const w = map.width;
  const seen = new Uint8Array(w * map.height);
  const [sx, sy] = start;
  if (!map.isTransit(sx, sy)) return seen;
  const queue = [sy * w + sx];
  seen[sy * w + sx] = 1;
  for (let head = 0; head < queue.length; head++) {
    const i = queue[head]!;
    const x = i % w;
    const y = Math.floor(i / w);
    for (const [dx, dy] of DIRS) {
      const nx = x + dx;
      const ny = y + dy;
      const ni = ny * w + nx;
      if (map.isTransit(nx, ny) && !seen[ni]) {
        seen[ni] = 1;
        queue.push(ni);
      }
    }
  }
  return seen;
}

// Структурная валидация (спека 5.5): то, что не проверил разбор office.yaml.
export function validateWorld(map: WorldMap, config: OfficeConfig, file = 'office.yaml'): MapError[] {
  const errors: MapError[] = [];
  const err = (code: string, message: string, at?: [number, number]) => errors.push(at ? { file, code, message, at } : { file, code, message });

  if (map.entrances.length === 0) err('entrance_missing', 'нет клетки входа E');
  if (map.entrances.length > 1) err('entrance_multiple', `входов ${map.entrances.length}, в MVP поддерживается один`, map.entrances[1]);

  const pods = map.zones.filter((z) => z.kind === 'pod');
  if (pods.length < config.people.length) err('pods_too_few', `углов (zone kind: pod) ${pods.length}, людей в конфиге ${config.people.length}`);
  const podOwner = new Map<string, string>();
  for (const p of config.people) {
    const z = map.zones.find((zone) => zone.id === p.pod);
    if (!z) err('person_pod_missing', `people.${p.id}.pod: зоны «${p.pod}» нет в office.yaml`);
    else if (z.kind !== 'pod') err('person_pod_kind', `people.${p.id}.pod: зона «${p.pod}» имеет kind ${z.kind}, нужен pod`);
    const other = podOwner.get(p.pod);
    if (other) err('pod_shared', `угол «${p.pod}» назначен и ${other}, и ${p.id}`);
    podOwner.set(p.pod, p.id);
  }
  for (const z of pods) {
    const n = map.spotsInZone(z.id).filter((s) => s.tags.includes('owner_seat')).length;
    if (n !== 1) err('owner_seat_count', `в углу «${z.id}» мест owner_seat: ${n}, нужно ровно 1`, [z.rect[0], z.rect[1]]);
  }

  const entrance = map.entrances[0];
  if (entrance) {
    const [ex, ey] = entrance;
    if (!DIRS.some(([dx, dy]) => map.isTransit(ex + dx, ey + dy))) err('entrance_enclosed', 'у входа нет проходимой соседней клетки (вход в стене?)', [ex, ey]);
    const seen = reachableFrom(map, entrance);
    for (const s of map.spots) {
      const reachable = DIRS.some(([dx, dy]) => {
        const nx = s.x + dx;
        const ny = s.y + dy;
        return map.inBounds(nx, ny) && seen[ny * map.width + nx] === 1;
      });
      if (!reachable) err('spot_unreachable', `место ${s.id} (${s.pose}) недостижимо от входа`, [s.x, s.y]);
    }
  }
  return errors;
}
```

- [ ] **Step 6: `packages/core/src/bundle.ts`**

```ts
import { loadCatalog, type Catalog } from './catalog.ts';
import { parseConfig, type OfficeConfig } from './config.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { parseOffice, type OfficeLayout } from './office.ts';
import { parseRules, type Rules } from './rules.ts';
import { validateWorld } from './validate.ts';
import { buildWorldMap, type WorldMap } from './world-map.ts';

export type OfficeTexts = {
  office: string;
  rules: string;
  config: string;
  catalog: string;
  files?: Partial<Record<'office' | 'rules' | 'config' | 'catalog', string>>;
};
export type OfficeBundle = { catalog: Catalog; config: OfficeConfig; layout: OfficeLayout; map: WorldMap; rules: Rules };

// Полная загрузка офиса: все ошибки всех файлов одним списком (спека 5.5).
export function loadOfficeBundle(t: OfficeTexts): Result<OfficeBundle> {
  const f = { office: 'office.yaml', rules: 'rules.yaml', config: 'config.yaml', catalog: 'catalog.yaml', ...t.files };
  const errors: MapError[] = [];
  const catalog = loadCatalog(t.catalog, f.catalog);
  const config = parseConfig(t.config, f.config);
  if (!catalog.ok) errors.push(...catalog.errors);
  if (!config.ok) errors.push(...config.errors);
  if (!catalog.ok) return fail(errors);
  const layout = parseOffice(t.office, catalog.value, f.office);
  if (!layout.ok) return fail([...errors, ...layout.errors]);
  const map = buildWorldMap(layout.value, catalog.value, f.office);
  if (!map.ok) return fail([...errors, ...map.errors]);
  const rules = parseRules(t.rules, f.rules, new Set(map.value.zones.map((z) => z.id)));
  if (!rules.ok) errors.push(...rules.errors);
  if (config.ok) errors.push(...validateWorld(map.value, config.value, f.office));
  if (errors.length || !config.ok || !rules.ok) return fail(errors);
  return ok({ catalog: catalog.value, config: config.value, layout: layout.value, map: map.value, rules: rules.value });
}
```

- [ ] **Step 7: фикстуры-хелперы (дописать в `fixtures.ts`)**

```ts
import { WorldMap, loadOfficeBundle, type OfficeBundle, type OfficeTexts, type Spot } from '../src/index.ts';

// Карта из ASCII: '#' — блок, '.' — транзит, 'S' — место sit лицом вниз, 'E' — вход.
export function asciiMap(rows: string[]): WorldMap {
  const width = rows[0]!.length;
  const height = rows.length;
  const blocked = new Uint8Array(width * height);
  const spots: Spot[] = [];
  const entrances: [number, number][] = [];
  rows.forEach((r, y) =>
    [...r].forEach((ch, x) => {
      if (ch === '#') blocked[y * width + x] = 1;
      if (ch === 'S') spots.push({ id: `s@${x},${y}`, x, y, facing: 'down', pose: 'sit', offset: [0, 0], tags: [], itemUid: `s@${x},${y}`, zoneId: null });
      if (ch === 'E') entrances.push([x, y]);
    }),
  );
  return new WorldMap({ width, height, blocked, spots, zones: [], entrances });
}

export function bundle(overrides: Partial<OfficeTexts> = {}): OfficeBundle {
  const r = loadOfficeBundle({ office: WORLD_OFFICE, rules: MINI_RULES, config: MINI_CONFIG, catalog: MINI_CATALOG, ...overrides });
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
}
```

- [ ] **Step 8: экспорт и прогон core**

В `packages/core/src/index.ts` добавить:
```ts
export * from './world-map.ts';
export * from './validate.ts';
export * from './bundle.ts';
```
Run: `pnpm vitest run packages/core` → PASS.

- [ ] **Step 9: пакет `tools/validate-maps` — тест**

`tools/validate-maps/package.json`:
```json
{
  "name": "@pixeloffice/validate-maps",
  "private": true,
  "type": "module",
  "exports": { ".": "./src/index.ts" },
  "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json" },
  "dependencies": { "@pixeloffice/core": "workspace:*" }
}
```
`tsconfig.json`: `{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024"], "types": ["node"] }, "include": ["src"] }`; `tsconfig.test.json` — плюс `"tests"`; `vitest.config.ts` с `name: 'validate-maps'`.

```bash
pnpm --filter @pixeloffice/validate-maps add yaml@latest
pnpm install
```

`tools/validate-maps/tests/validate.test.ts`:
```ts
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { expandHome, validateOfficesDir } from '../src/index.ts';
import { MINI_CATALOG, MINI_CONFIG, MINI_RULES, WORLD_OFFICE, mutateYaml } from '../../../packages/core/tests/fixtures.ts';

function makeRoot(officeText: string) {
  const root = mkdtempSync(join(tmpdir(), 'po-maps-'));
  writeFileSync(join(root, 'catalog.yaml'), MINI_CATALOG);
  const dir = join(root, 'offices', 'test');
  mkdirSync(dir, { recursive: true });
  writeFileSync(join(dir, 'office.yaml'), officeText);
  writeFileSync(join(dir, 'rules.yaml'), MINI_RULES);
  writeFileSync(join(dir, 'config.example.yaml'), mutateYaml(MINI_CONFIG, (d) => (d.catalog = '../../catalog.yaml')));
  return join(root, 'offices');
}

describe('validateOfficesDir', () => {
  it('валидный офис — без ошибок (config.example.yaml как запасной)', async () => {
    const [rep] = await validateOfficesDir(makeRoot(WORLD_OFFICE));
    expect(rep!.errors).toEqual([]);
  });

  it('ошибки карты попадают в отчёт с кодом и координатами', async () => {
    const [rep] = await validateOfficesDir(makeRoot(WORLD_OFFICE.replace('#^^^^.^^..^^.#', '#^^^^.^^..^^#')));
    expect(rep!.errors.join('\n')).toContain('grid_ragged');
  });

  it('нет каталога offices — пустой отчёт', async () => {
    expect(await validateOfficesDir('/nonexistent/offices')).toEqual([]);
  });

  it('expandHome раскрывает ~', () => {
    expect(expandHome('~/tmp')).not.toContain('~');
    expect(expandHome('/abs')).toBe('/abs');
  });
});
```

Run: `pnpm vitest run tools/validate-maps` → FAIL.

- [ ] **Step 10: реализация validate-maps**

`tools/validate-maps/src/read.ts`:
```ts
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { isAbsolute, join, relative, resolve } from 'node:path';
import { parse } from 'yaml';
import type { OfficeTexts } from '@pixeloffice/core';

export const expandHome = (p: string): string => (p === '~' ? homedir() : p.startsWith('~/') ? join(homedir(), p.slice(2)) : p);

// Путь из конфига: ~ раскрывается, относительный — от каталога конфига (решение 6).
export const resolveFrom = (baseDir: string, p: string): string => {
  const e = expandHome(p);
  return isAbsolute(e) ? e : resolve(baseDir, e);
};

export type OfficeFiles = { dir: string; configPath: string; officePath: string; rulesPath: string; catalogPath: string };

export function officeFiles(dir: string): OfficeFiles {
  const abs = resolve(dir);
  const configPath = existsSync(join(abs, 'config.yaml')) ? join(abs, 'config.yaml') : join(abs, 'config.example.yaml');
  let catalogRel = '../../catalog/limezu/catalog.yaml';
  try {
    const raw = parse(readFileSync(configPath, 'utf8')) as { catalog?: unknown } | null;
    if (typeof raw?.catalog === 'string') catalogRel = raw.catalog;
  } catch {
    // Ошибку чтения/синтаксиса конфига покажет loadOfficeBundle.
  }
  return { dir: abs, configPath, officePath: join(abs, 'office.yaml'), rulesPath: join(abs, 'rules.yaml'), catalogPath: resolveFrom(abs, catalogRel) };
}

export function readOfficeTexts(dir: string): { files: OfficeFiles; texts: OfficeTexts } {
  const files = officeFiles(dir);
  const read = (p: string) => {
    if (!existsSync(p)) throw new Error(`нет файла ${p}`);
    return readFileSync(p, 'utf8');
  };
  const rel = (p: string) => relative(process.cwd(), p);
  return {
    files,
    texts: {
      office: read(files.officePath),
      rules: read(files.rulesPath),
      config: read(files.configPath),
      catalog: read(files.catalogPath),
      files: { office: rel(files.officePath), rules: rel(files.rulesPath), config: rel(files.configPath), catalog: rel(files.catalogPath) },
    },
  };
}
```

`tools/validate-maps/src/validate.ts`:
```ts
import { existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { formatErrors, loadOfficeBundle } from '@pixeloffice/core';
import { readOfficeTexts } from './read.ts';

export type DirReport = { dir: string; errors: string[]; notes: string[] };

export async function validateOfficesDir(root: string): Promise<DirReport[]> {
  if (!existsSync(root)) return [];
  const dirs = readdirSync(root, { withFileTypes: true })
    .filter((d) => d.isDirectory() && existsSync(join(root, d.name, 'office.yaml')))
    .map((d) => join(root, d.name))
    .sort();
  const reports: DirReport[] = [];
  for (const dir of dirs) {
    try {
      const { texts } = readOfficeTexts(dir);
      const r = loadOfficeBundle(texts);
      reports.push(r.ok ? { dir, errors: [], notes: ['структура: ok'] } : { dir, errors: [formatErrors(r.errors)], notes: [] });
    } catch (e) {
      reports.push({ dir, errors: [(e as Error).message], notes: [] });
    }
  }
  return reports;
}
```

`tools/validate-maps/src/index.ts`:
```ts
export * from './read.ts';
export * from './validate.ts';
```

`tools/validate-maps/src/cli.ts`:
```ts
import { validateOfficesDir } from './validate.ts';

// node tools/validate-maps/src/cli.ts offices — валидация всех офисов; код выхода 1 при ошибках.
const root = process.argv[2] ?? 'offices';
const reports = await validateOfficesDir(root);
if (reports.length === 0) console.log(`validate:maps: в ${root} нет офисов — пропуск`);
let failed = false;
for (const r of reports) {
  if (r.errors.length) {
    failed = true;
    console.error(`✗ ${r.dir}\n${r.errors.join('\n')}`);
  } else {
    console.log(`✓ ${r.dir} — ${r.notes.join('; ')}`);
  }
}
process.exit(failed ? 1 : 0);
```

Корневой `package.json` — скрипты:
```json
"validate:maps": "node tools/validate-maps/src/cli.ts offices",
"gate": "pnpm test && pnpm typecheck && pnpm validate:maps"
```

```bash
pnpm vitest run tools/validate-maps    # PASS
pnpm validate:maps                     # «в offices нет офисов — пропуск», код 0
```

- [ ] **Step 11: гейт и коммит**

```bash
pnpm gate
git add packages/core tools/validate-maps package.json pnpm-lock.yaml
git commit -m "feat(core): структурная валидация карты и CLI validate:maps"
```

**Критерий готовности:** регрессии v1 (вход в стене, карман d9, среднее кресло d4) ловятся с координатами. `pnpm gate` включает `validate:maps`.

---

### Задача 10: core — A\*

**Files:**
- Create: `packages/core/src/path/heap.ts`, `packages/core/src/path/astar.ts`
- Modify: `packages/core/src/index.ts`
- Test: `packages/core/tests/astar.test.ts`

**Interfaces:**
- Consumes: `WorldMap` (`inBounds`, `isBlocked`, `isTransit`), `asciiMap` из фикстур.
- Produces: `type Cell = [number, number]`, `findPath(map: WorldMap, from: Cell, to: Cell): Cell[] | null`. Путь 4-направленный, включает обе концевые клетки. Транзит — только `isTransit`. Цель может быть местом, старт может быть местом (персонаж встаёт с кресла). Цель-блок или недостижимая цель → `null`. Порядок соседей и тай-брейк фиксированы, результат детерминирован.

- [ ] **Step 1: падающие тесты `packages/core/tests/astar.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { findPath, type Cell } from '../src/index.ts';
import { asciiMap } from './fixtures.ts';

const isAdjacentChain = (p: Cell[]) => p.every((c, i) => i === 0 || Math.abs(c[0] - p[i - 1]![0]) + Math.abs(c[1] - p[i - 1]![1]) === 1);

describe('findPath', () => {
  it('прямая в открытом поле, концы включены', () => {
    const m = asciiMap(['......', '......']);
    expect(findPath(m, [0, 0], [3, 0])).toEqual([[0, 0], [1, 0], [2, 0], [3, 0]]);
  });

  it('обходит стену', () => {
    const m = asciiMap(['.#..', '.#..', '....']);
    const p = findPath(m, [0, 0], [2, 0])!;
    expect(p[0]).toEqual([0, 0]);
    expect(p.at(-1)).toEqual([2, 0]);
    expect(p).toHaveLength(7);
    expect(isAdjacentChain(p)).toBe(true);
  });

  it('места не транзит: путь не проходит через чужие кресла', () => {
    const m = asciiMap(['.SSS.', '.....']);
    const p = findPath(m, [0, 0], [4, 0])!;
    expect(p.some(([x, y]) => y === 0 && x >= 1 && x <= 3)).toBe(false);
  });

  it('цель — место: доходит до него', () => {
    const m = asciiMap(['.S.', '...']);
    expect(findPath(m, [0, 1], [1, 0])).toEqual([[0, 1], [1, 1], [1, 0]]);
  });

  it('старт — место: встаёт и уходит', () => {
    const m = asciiMap(['S..', '...']);
    expect(findPath(m, [0, 0], [2, 0])).toEqual([[0, 0], [1, 0], [2, 0]]);
  });

  it('недостижимо → null; цель-блок → null; та же клетка → [клетка]', () => {
    const m = asciiMap(['.#.', '.#.', '.#.']);
    expect(findPath(m, [0, 0], [2, 0])).toBeNull();
    expect(findPath(m, [0, 0], [1, 0])).toBeNull();
    expect(findPath(m, [0, 2], [0, 2])).toEqual([[0, 2]]);
  });

  it('детерминирован', () => {
    const m = asciiMap(['......', '..##..', '......']);
    expect(findPath(m, [0, 0], [5, 2])).toEqual(findPath(m, [0, 0], [5, 2]));
  });
});
```

Run: `pnpm vitest run packages/core/tests/astar.test.ts` → FAIL.

- [ ] **Step 2: `packages/core/src/path/heap.ts`**

```ts
// Двоичная куча по ключу (f, h, seq): меньший f, затем меньший h, затем раньше добавленный.
type Entry<T> = { v: T; f: number; h: number; seq: number };

const less = <T>(a: Entry<T>, b: Entry<T>) => a.f < b.f || (a.f === b.f && (a.h < b.h || (a.h === b.h && a.seq < b.seq)));

export class MinHeap<T> {
  private items: Entry<T>[] = [];

  get size(): number {
    return this.items.length;
  }

  push(v: T, f: number, h: number, seq: number): void {
    const a = this.items;
    a.push({ v, f, h, seq });
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }

  pop(): T | undefined {
    const a = this.items;
    if (a.length === 0) return undefined;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let m = i;
        if (l < a.length && less(a[l]!, a[m]!)) m = l;
        if (r < a.length && less(a[r]!, a[m]!)) m = r;
        if (m === i) break;
        [a[i], a[m]] = [a[m]!, a[i]!];
        i = m;
      }
    }
    return top.v;
  }
}
```

- [ ] **Step 3: `packages/core/src/path/astar.ts`**

```ts
import type { WorldMap } from '../world-map.ts';
import { MinHeap } from './heap.ts';

export type Cell = [number, number];

// Фиксированный порядок соседей: вверх, вправо, вниз, влево.
const DIRS: Cell[] = [[0, -1], [1, 0], [0, 1], [-1, 0]];

export function findPath(map: WorldMap, from: Cell, to: Cell): Cell[] | null {
  const [fx, fy] = from;
  const [tx, ty] = to;
  if (!map.inBounds(fx, fy) || map.isBlocked(tx, ty)) return null;
  if (fx === tx && fy === ty) return [[fx, fy]];
  const w = map.width;
  const size = w * map.height;
  const start = fy * w + fx;
  const goal = ty * w + tx;
  const g = new Float64Array(size).fill(Infinity);
  const came = new Int32Array(size).fill(-1);
  const closed = new Uint8Array(size);
  const h = (i: number) => Math.abs((i % w) - tx) + Math.abs(Math.floor(i / w) - ty);
  const open = new MinHeap<number>();
  let seq = 0;
  g[start] = 0;
  open.push(start, h(start), h(start), seq++);
  while (open.size > 0) {
    const cur = open.pop()!;
    if (cur === goal) break;
    if (closed[cur]) continue;
    closed[cur] = 1;
    const cx = cur % w;
    const cy = Math.floor(cur / w);
    for (const [dx, dy] of DIRS) {
      const nx = cx + dx;
      const ny = cy + dy;
      if (!map.inBounds(nx, ny)) continue;
      const ni = ny * w + nx;
      if (closed[ni]) continue;
      if (ni !== goal && !map.isTransit(nx, ny)) continue; // места — только как цель
      const ng = g[cur]! + 1;
      if (ng < g[ni]!) {
        g[ni] = ng;
        came[ni] = cur;
        open.push(ni, ng + h(ni), h(ni), seq++);
      }
    }
  }
  if (came[goal] === -1) return null;
  const path: Cell[] = [];
  for (let i = goal; i !== start; i = came[i]!) path.push([i % w, Math.floor(i / w)]);
  path.push([fx, fy]);
  return path.reverse();
}
```

- [ ] **Step 4: экспорт, прогон, гейт, коммит**

В `index.ts`: `export * from './path/astar.ts';`

```bash
pnpm vitest run packages/core/tests/astar.test.ts   # PASS
pnpm gate
git add packages/core
git commit -m "feat(core): A* по клеткам с местами-целями"
```

**Критерий готовности:** 7 тестов A\* зелёные. Библиотеки `pathfinding` в зависимостях нет.

---

### Задача 11: core — `renderMap`: пол, автотайлинг стен, предметы, `sortY`

**Files:**
- Create: `packages/core/src/render-map.ts`
- Modify: `packages/core/src/bundle.ts` (поле `rendered`), `packages/core/src/index.ts`
- Test: `packages/core/tests/render-map.test.ts`

**Interfaces:**
- Consumes: `OfficeLayout`, `zoneContains`, `WorldMap`, `Catalog`, `itemView`, `Part`, типы `Frame`, `FloorTile`, `MapSprite`, `RenderedMap` из protocol.
- Produces: `defaultAssetUrl(path: string): string` (`'/assets/' + сегменты через encodeURIComponent`), `renderMap(layout, map, catalog, assetUrl = defaultAssetUrl, file = 'office.yaml'): Result<RenderedMap>`. В `OfficeBundle` появляется `rendered: RenderedMap`, ошибки `wall_no_rule` становятся частью структурной валидации.

Правила рендера (спека 5.1, 5.6):
1. Пол — под каждой клеткой, кроме стен. Тип — по первой зоне (в порядке `zones`), у которой есть запись в `floor.zones`, иначе `floor.default`. Вариант тайла — `frames[(x*7 + y*13) % n]`.
2. Стена `#` — первое правило `autotile.rules`, у которого все заданные биты `when` совпали с маской соседей. Бит соседа: стена → 1; вход, пол, предмет → 0; за краем карты → `autotile.outside`. Не совпало ни одно → ошибка `wall_no_rule` с координатами.
3. Вход `E` — части `autotile.door`.
4. Часть `p` предмета или стены в клетке (x, y): `px = x*ts + p.at[0]`, `py = y*ts + p.at[1]`, `sortY = (y + p.sortY) * ts`. Для предмета (x, y) — его левая верхняя клетка.

- [ ] **Step 1: падающие тесты `packages/core/tests/render-map.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { buildWorldMap, defaultAssetUrl, renderMap } from '../src/index.ts';
import { MINI_CATALOG, bundle, miniCatalog, mutateYaml, office } from './fixtures.ts';
import { loadCatalog } from '../src/index.ts';

const render = (catalogText = MINI_CATALOG) => {
  const cat = loadCatalog(catalogText);
  if (!cat.ok) throw new Error('каталог');
  const layout = office();
  const map = buildWorldMap(layout, miniCatalog());
  if (!map.ok) throw new Error('карта');
  return renderMap(layout, map.value, cat.value);
};
const SHEET = '/assets/test/sheet.png';

describe('renderMap', () => {
  it('пол под всеми клетками, кроме стен; зона lounge — wood', () => {
    const r = render();
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    const nonWall = office().base.filter((k) => k !== 'wall').length;
    expect(r.value.floor).toHaveLength(nonWall);
    const lounge = r.value.floor.find((t) => t.x === 2 && t.y === 5)!;
    expect([16, 32]).toContain(lounge.frame.x); // wood: два варианта
    const plain = r.value.floor.find((t) => t.x === 8 && t.y === 3)!;
    expect(plain.frame).toEqual({ sheet: SHEET, x: 0, y: 0, w: 16, h: 16 });
  });

  it('стены: лицо над полом, кромка в углу; проём входа', () => {
    const r = render();
    if (!r.ok) throw new Error();
    const at = (px: number, py: number) => r.value.sprites.filter((s) => s.px === px && s.py === py);
    // (0,0): снизу стена (0,1) → правило-заглушка, кромка 16×16
    expect(at(0, 0).map((s) => s.frame.x)).toContain(16);
    // (5,0): снизу пол (5,1) → лицо 2 тайла, вверх от клетки
    expect(at(80, -16)[0]).toMatchObject({ frame: { x: 0, y: 16, w: 16, h: 32 }, sortY: 16 });
    // вход (6,6) → дверь
    expect(at(96, 96)[0]).toMatchObject({ frame: { x: 32, y: 16 }, sortY: 96 });
  });

  it('outside: 1 — нижний ряд стен только с кромкой, лицо не ложится на пол', () => {
    const r = render(mutateYaml(MINI_CATALOG, (d) => (d.items.wall.autotile.outside = 1)));
    if (!r.ok) throw new Error();
    const at = (px: number, py: number) => r.value.sprites.filter((s) => s.px === px && s.py === py);
    // (5,6): снизу край карты → бит 1 → правило-заглушка, кромка 16×16 в своей клетке
    expect(at(80, 96).map((s) => s.frame)).toEqual([{ sheet: SHEET, x: 16, y: 16, w: 16, h: 16 }]);
    expect(at(80, 80)).toEqual([]); // над последним рядом пола (5,5) лица нет
    // верхний ряд по-прежнему с лицом: под (5,0) пол
    expect(at(80, -16)[0]).toMatchObject({ frame: { h: 32 } });
  });

  it('предметы: стол, кресло с двумя частями, монитор на столе', () => {
    const r = render();
    if (!r.ok) throw new Error();
    const desk = r.value.sprites.find((s) => s.px === 16 && s.py === 0 && s.frame.y === 48)!;
    expect(desk.sortY).toBe(32);
    const chairBack = r.value.sprites.find((s) => s.px === 32 && s.py === 32 && s.frame.x === 16 && s.frame.y === 80)!;
    expect(chairBack.sortY).toBeCloseTo(48.8);
    const monitor = r.value.sprites.find((s) => s.frame.y === 96)!;
    expect(monitor).toMatchObject({ px: 16, py: 8 });
    expect(monitor.sortY).toBeCloseTo(30.4);
  });

  it('места, блоки и вход для зрителя', () => {
    const r = render();
    if (!r.ok) throw new Error();
    expect(r.value.spots).toHaveLength(10);
    expect(r.value.spots[0]).toMatchObject({ x: 1, y: 2, pose: 'sit', zoneId: 'pod:a' });
    expect(r.value.blocked).toContainEqual([1, 1]);
    expect(r.value.entrance).toEqual([6, 6]);
    expect([r.value.width, r.value.height, r.value.tileSize]).toEqual([14, 7, 16]);
  });

  it('стена без подходящего правила → wall_no_rule с координатами', () => {
    const r = render(mutateYaml(MINI_CATALOG, (d) => d.items.wall.autotile.rules.pop()));
    expect(r.ok).toBe(false);
    if (!r.ok) expect(r.errors[0]).toMatchObject({ code: 'wall_no_rule', at: [0, 0] });
  });

  it('URL ассетов: сегменты кодируются', () => {
    expect(defaultAssetUrl('Modern Office/a b.png')).toBe('/assets/Modern%20Office/a%20b.png');
  });

  it('bundle содержит rendered', () => {
    expect(bundle().rendered.sprites.length).toBeGreaterThan(0);
  });
});
```

Run: `pnpm vitest run packages/core/tests/render-map.test.ts` → FAIL.

- [ ] **Step 2: `packages/core/src/render-map.ts`**

```ts
import type { FloorTile, Frame, MapSprite, RenderedMap } from '@pixeloffice/protocol';
import { itemView, type Catalog, type Part } from './catalog.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { zoneContains, type OfficeLayout } from './office.ts';
import type { WorldMap } from './world-map.ts';

const N8: Record<string, [number, number]> = {
  n: [0, -1], e: [1, 0], s: [0, 1], w: [-1, 0], ne: [1, -1], se: [1, 1], sw: [-1, 1], nw: [-1, -1],
};

export const defaultAssetUrl = (path: string): string => '/assets/' + path.split('/').map(encodeURIComponent).join('/');

// Отрендеренная карта для hello: сервер — источник правды для того, что рисовать (спека 4.6).
export function renderMap(
  layout: OfficeLayout,
  map: WorldMap,
  catalog: Catalog,
  assetUrl: (path: string) => string = defaultAssetUrl,
  file = 'office.yaml',
): Result<RenderedMap> {
  const ts = catalog.tileSize;
  const { width, height } = layout;
  const errors: MapError[] = [];
  const frame = (sheet: string, r: [number, number, number, number]): Frame => ({
    sheet: assetUrl(catalog.sheets[sheet]!),
    x: r[0],
    y: r[1],
    w: r[2],
    h: r[3],
  });
  const sprites: MapSprite[] = [];
  const put = (p: Part, x: number, y: number) =>
    sprites.push({ frame: frame(p.sheet, p.rect), px: x * ts + p.at[0], py: y * ts + p.at[1], sortY: (y + p.sortY) * ts });
  const kindAt = (x: number, y: number) => layout.base[y * width + x];
  const auto = catalog.items['wall']!.autotile!;
  const wallBit = (x: number, y: number): 0 | 1 =>
    x < 0 || y < 0 || x >= width || y >= height ? auto.outside : kindAt(x, y) === 'wall' ? 1 : 0;
  const floorType = (x: number, y: number) => {
    for (const z of layout.zones) {
      const t = layout.floor.zones[z.id];
      if (t && zoneContains(z, x, y)) return t;
    }
    return layout.floor.default;
  };

  const floor: FloorTile[] = [];
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const k = kindAt(x, y);
      if (k !== 'wall') {
        const frames = catalog.floors[floorType(x, y)]!;
        const fr = frames[(x * 7 + y * 13) % frames.length]!;
        floor.push({ x, y, frame: frame(fr.sheet, fr.rect) });
      }
      if (k === 'entrance') for (const p of auto.door) put(p, x, y);
      if (k === 'wall') {
        const rule = auto.rules.find((r) =>
          Object.entries(r.when).every(([dir, bit]) => {
            if (bit === undefined) return true;
            const [dx, dy] = N8[dir]!;
            return wallBit(x + dx, y + dy) === bit;
          }),
        );
        if (!rule) errors.push({ file, code: 'wall_no_rule', message: 'ни одно правило autotile стены не подходит', at: [x, y] });
        else for (const p of rule.parts) put(p, x, y);
      }
    }
  }
  for (const it of layout.items) {
    for (const p of itemView(catalog.items[it.item]!, it.facing, it.variant).parts) put(p, it.x, it.y);
  }
  const blocked: [number, number][] = [];
  for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) if (map.isBlocked(x, y)) blocked.push([x, y]);
  if (errors.length) return fail(errors);
  return ok({
    tileSize: ts,
    width,
    height,
    floor,
    sprites,
    spots: map.spots.map((s) => ({ id: s.id, x: s.x, y: s.y, facing: s.facing, pose: s.pose, zoneId: s.zoneId, tags: s.tags })),
    blocked,
    entrance: map.entrance(),
  });
}
```

- [ ] **Step 3: `rendered` в bundle**

В `packages/core/src/bundle.ts`:
- импорт: `import { defaultAssetUrl, renderMap } from './render-map.ts';` и `import type { RenderedMap } from '@pixeloffice/protocol';`;
- тип: `export type OfficeBundle = { catalog: Catalog; config: OfficeConfig; layout: OfficeLayout; map: WorldMap; rules: Rules; rendered: RenderedMap };`;
- после строки `if (!map.ok) return fail([...errors, ...map.errors]);` вставить:
```ts
  const rendered = map.value.entrances.length ? renderMap(layout.value, map.value, catalog.value, defaultAssetUrl, f.office) : null;
  if (rendered && !rendered.ok) errors.push(...rendered.errors);
```
- последнюю проверку и возврат заменить на:
```ts
  if (errors.length || !config.ok || !rules.ok || !rendered || !rendered.ok) return fail(errors);
  return ok({ catalog: catalog.value, config: config.value, layout: layout.value, map: map.value, rules: rules.value, rendered: rendered.value });
```
(без входа `renderMap` не вызывается: `validateWorld` уже вернул `entrance_missing`).

В `index.ts`: `export * from './render-map.ts';`

- [ ] **Step 4: прогон, гейт, коммит**

```bash
pnpm vitest run packages/core    # PASS
pnpm gate
git add packages/core
git commit -m "feat(core): отрендеренная карта с автотайлингом стен и линиями сортировки"
```

**Критерий готовности:** тесты рендера зелёные. Стена без подходящего правила валит загрузку офиса с координатами.

---

### Задача 12: core — персонажи: слои аватара, кадры, аватар по хешу

**Files:**
- Create: `packages/core/src/random.ts`, `packages/core/src/characters.ts`
- Modify: `packages/core/src/index.ts`
- Test: `packages/core/tests/characters.test.ts`

**Interfaces:**
- Consumes: `CharactersDef` (задача 6), `AvatarParts`, `Facing`, `Pose`, `AnimName`, `CharacterLayout` (protocol).
- Produces: `fnv1a(s): number` (uint32), `mulberry32(seed): () => number` ([0, 1)), `fillTemplate(t, vars): string` (`{key}`; числа — с ведущим нулём до 2 знаков; нет ключа → `Error`), `avatarLayerPaths(c: CharactersDef, a: AvatarParts): string[]` (порядок body, eyes, outfit, hair, accessory), `avatarFromKey(key, pool): AvatarParts` (детерминированно, без аксессуара), `animFor(poses, pose: Pose | 'walk', facing): AnimName`, `characterLayout(c): CharacterLayout`, `frameRect(layout, anim, facing, frame): { x; y; w; h }` (нет колонки для направления → `down`, затем `right`).

- [ ] **Step 1: падающие тесты `packages/core/tests/characters.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { animFor, avatarFromKey, avatarLayerPaths, characterLayout, fillTemplate, fnv1a, frameRect, mulberry32 } from '../src/index.ts';
import { miniCatalog } from './fixtures.ts';

const chars = () => miniCatalog().characters;

describe('персонажи', () => {
  it('fillTemplate: ведущий ноль, строки как есть, нет ключа — ошибка', () => {
    expect(fillTemplate('Outfit_{model}_{color}.png', { model: 3, color: 12 })).toBe('Outfit_03_12.png');
    expect(fillTemplate('A_{name}.png', { name: 'Bee' })).toBe('A_Bee.png');
    expect(() => fillTemplate('{body}', {})).toThrow();
  });

  it('слои аватара в порядке наложения, с аксессуаром', () => {
    expect(avatarLayerPaths(chars(), { body: 3, eyes: 2, outfit: [41, 2], hair: [17, 5], accessory: [1, 3] })).toEqual([
      'gen/Body_03.png',
      'gen/Eyes_02.png',
      'gen/Outfit_41_02.png',
      'gen/Hairstyle_17_05.png',
      'gen/Accessory_01_Ladybug_03.png',
    ]);
  });

  it('аватар по ключу: детерминирован и в пределах пула', () => {
    const pool = chars().pool;
    const a = avatarFromKey('agent:stas:PixelOffice:%17', pool);
    expect(avatarFromKey('agent:stas:PixelOffice:%17', pool)).toEqual(a);
    expect(pool.bodies).toContain(a.body);
    expect(pool.eyes).toContain(a.eyes);
    expect(a.outfit[1]).toBeLessThanOrEqual(pool.outfits[String(a.outfit[0])]!);
    const distinct = new Set(Array.from({ length: 20 }, (_, i) => JSON.stringify(avatarFromKey(`k${i}`, pool))));
    expect(distinct.size).toBeGreaterThan(1);
  });

  it('fnv1a и mulberry32 стабильны', () => {
    expect(fnv1a('a')).toBe(0xe40c292c);
    const r1 = mulberry32(42);
    const r2 = mulberry32(42);
    expect([r1(), r1()]).toEqual([r2(), r2()]);
  });

  it('поза → анимация: сидение вверх/вниз — walk (спека 5.2)', () => {
    const poses = chars().poses;
    expect(animFor(poses, 'sit', 'up')).toBe('walk');
    expect(animFor(poses, 'sit', 'left')).toBe('sit');
    expect(animFor(poses, 'play', 'up')).toBe('idle');
    expect(animFor(poses, 'walk', 'right')).toBe('walk');
  });

  it('кадр по анимации и направлению', () => {
    const l = characterLayout(chars());
    expect(frameRect(l, 'walk', 'down', 0)).toEqual({ x: 288, y: 64, w: 16, h: 32 });
    expect(frameRect(l, 'walk', 'down', 7)).toEqual({ x: 304, y: 64, w: 16, h: 32 }); // 7 % 6 = 1
    expect(frameRect(l, 'sit', 'left', 0)).toEqual({ x: 96, y: 128, w: 16, h: 32 });
    expect(frameRect(l, 'sit', 'up', 0).x).toBe(0); // нет колонки up/down у sit → right
  });
});
```

Run: `pnpm vitest run packages/core/tests/characters.test.ts` → FAIL.

- [ ] **Step 2: `packages/core/src/random.ts`**

```ts
// FNV-1a 32 бита: стабильный хеш строки.
export function fnv1a(s: string): number {
  let h = 0x811c9dc5;
  for (let i = 0; i < s.length; i++) {
    h ^= s.charCodeAt(i);
    h = Math.imul(h, 0x01000193);
  }
  return h >>> 0;
}

// Детерминированный ГПСЧ для сценариев и выбора аватара.
export function mulberry32(seed: number): () => number {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
```

- [ ] **Step 3: `packages/core/src/characters.ts`**

```ts
import type { AnimName, AvatarParts, CharacterLayout, Facing, Pose } from '@pixeloffice/protocol';
import type { CharactersDef } from './catalog.ts';
import { fnv1a, mulberry32 } from './random.ts';

export function fillTemplate(t: string, vars: Record<string, string | number>): string {
  return t.replace(/\{(\w+)\}/g, (_m, key: string) => {
    const v = vars[key];
    if (v === undefined) throw new Error(`шаблон «${t}»: нет значения {${key}}`);
    return typeof v === 'number' ? String(v).padStart(2, '0') : v;
  });
}

// Пути слоёв относительно assetsDir в порядке генератора: тело → глаза → одежда → причёска → аксессуар.
export function avatarLayerPaths(c: CharactersDef, a: AvatarParts): string[] {
  const out = [
    fillTemplate(c.layers.body, { body: a.body }),
    fillTemplate(c.layers.eyes, { eyes: a.eyes }),
    fillTemplate(c.layers.outfit, { model: a.outfit[0], color: a.outfit[1] }),
    fillTemplate(c.layers.hair, { model: a.hair[0], color: a.hair[1] }),
  ];
  if (a.accessory) {
    const name = c.accessoryNames[String(a.accessory[0])];
    if (name === undefined) throw new Error(`аксессуар ${a.accessory[0]}: нет имени в characters.accessoryNames`);
    out.push(fillTemplate(c.layers.accessory, { model: a.accessory[0], color: a.accessory[1], name }));
  }
  return out;
}

// Аватар агента — детерминированно по хешу стабильного ключа (спека 4.1).
export function avatarFromKey(key: string, pool: CharactersDef['pool']): AvatarParts {
  const rnd = mulberry32(fnv1a(key));
  const pick = <T>(xs: readonly T[]): T => xs[Math.floor(rnd() * xs.length)]!;
  const pair = (rec: Record<string, number>): [number, number] => {
    const model = Number(pick(Object.keys(rec).sort((a, b) => Number(a) - Number(b))));
    return [model, 1 + Math.floor(rnd() * rec[String(model)]!)];
  };
  return { body: pick(pool.bodies), eyes: pick(pool.eyes), outfit: pair(pool.outfits), hair: pair(pool.hairs) };
}

export function animFor(poses: CharactersDef['poses'], pose: Pose | 'walk', facing: Facing): AnimName {
  return pose === 'walk' ? 'walk' : poses[pose][facing];
}

export function characterLayout(c: CharactersDef): CharacterLayout {
  return { frameW: c.frame[0], frameH: c.frame[1], animations: c.animations };
}

export function frameRect(layout: CharacterLayout, anim: AnimName, facing: Facing, frame: number): { x: number; y: number; w: number; h: number } {
  const a = layout.animations[anim];
  const col0 = a.dirs[facing] ?? a.dirs.down ?? a.dirs.right ?? 0;
  const i = ((frame % a.frames) + a.frames) % a.frames;
  return { x: (col0 + i) * layout.frameW, y: a.row * layout.frameH, w: layout.frameW, h: layout.frameH };
}
```

- [ ] **Step 4: экспорт, прогон, гейт, коммит**

В `index.ts`:
```ts
export * from './random.ts';
export * from './characters.ts';
```
Значение `fnv1a('a')` в тесте — эталон FNV-1a 32 (`0xe40c292c`). Если тест не сходится, проверить реализацию, а не эталон.

```bash
pnpm vitest run packages/core   # PASS
pnpm gate
git add packages/core
git commit -m "feat(core): слои и кадры персонажей, аватар по хешу ключа"
```

**Критерий готовности:** тесты персонажей зелёные. Хелперы чистые, viewer может их импортировать.

---

### Задача 13: core — переговорки и разрешение целей правил

**Files:**
- Create: `packages/core/src/sim/types.ts`, `packages/core/src/sim/meetings.ts`, `packages/core/src/sim/targets.ts`
- Modify: `packages/core/src/index.ts`
- Test: `packages/core/tests/meetings.test.ts`, `packages/core/tests/targets.test.ts`

**Interfaces:**
- Consumes: `WorldMap`, `Spot`, `Zone`, `RuleTarget`, `parseTarget`, фикстура `bundle()`.
- Produces:
  - `type SimEntity = { id: string; kind: 'human' | 'agent'; ownerId?: string; podZoneId?: string }`.
  - `class MeetingRooms { constructor(map); capacity(zoneId): number /* мест sit */; roomsOf(meetingId): string[]; ensure(meetingId, need): string[]; addRoom(meetingId): string | null; release(active: ReadonlySet<string>): void; allocations(): Record<string, string[]> }`. `ensure` закрепляет самую маленькую свободную переговорку с `capacity >= need`, иначе самую большую свободную; при равенстве — по id. Нет свободных → `[]`.
  - `type Resolved = { kind: 'spot'; spotId: string } | { kind: 'exit' } | { kind: 'stay' }`, `type ResolveContext = { map; reservations: ReadonlyMap<string, string> /* spotId → entityId */; entity: SimEntity; podOf(entityId): string | undefined; lastSeat: string | null; currentSpot: string | null; currentIsWorkSeat: boolean; meetingId: string | undefined; meetings: MeetingRooms; meetingNeed(meetingId): number }`, `resolveTargets(targets, ctx): { resolved: Resolved | null; lastZoneId: string | null }`.

Семантика (спека 5.3): место свободно, если не забронировано или забронировано этой же сущностью. Места `owner_seat` выдаёт только `own_seat`. При выборе сначала предпочитается текущее место (`currentSpot`), для `owner_pod_seat` затем прошлое (`lastSeat`), затем первое по порядку (y, x).

- [ ] **Step 1: падающие тесты `packages/core/tests/meetings.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { MeetingRooms, WorldMap, type Spot, type Zone } from '../src/index.ts';

// small: 2 sit; mid: 3 sit; big: 4 sit + 1 stand.
function meetingMap(): WorldMap {
  const spots: Spot[] = [];
  const add = (zoneId: string, x: number, y: number, pose: 'sit' | 'stand') =>
    spots.push({ id: `${zoneId}#${x},${y}`, x, y, facing: 'up', pose, offset: [0, 0], tags: [], itemUid: 'x', zoneId });
  [1, 2].forEach((x) => add('meeting:small', x, 1, 'sit'));
  [1, 2, 3].forEach((x) => add('meeting:mid', x, 5, 'sit'));
  [1, 2, 3, 4].forEach((x) => add('meeting:big', x, 3, 'sit'));
  add('meeting:big', 6, 3, 'stand');
  const zones: Zone[] = [
    { id: 'meeting:small', kind: 'meeting', rect: [0, 0, 10, 2] },
    { id: 'meeting:big', kind: 'meeting', rect: [0, 2, 10, 2] },
    { id: 'meeting:mid', kind: 'meeting', rect: [0, 4, 10, 2] },
  ];
  return new WorldMap({ width: 10, height: 6, blocked: new Uint8Array(60), spots, zones, entrances: [[0, 0]] });
}

describe('MeetingRooms', () => {
  it('вместимость — только места sit', () => {
    expect(new MeetingRooms(meetingMap()).capacity('meeting:big')).toBe(4);
  });

  it('самая маленькая подходящая, иначе самая большая свободная', () => {
    const m = meetingMap();
    expect(new MeetingRooms(m).ensure('a', 2)).toEqual(['meeting:small']);
    expect(new MeetingRooms(m).ensure('a', 3)).toEqual(['meeting:mid']);
    expect(new MeetingRooms(m).ensure('a', 4)).toEqual(['meeting:big']);
    expect(new MeetingRooms(m).ensure('a', 9)).toEqual(['meeting:big']);
  });

  it('повторный ensure возвращает закреплённую', () => {
    const r = new MeetingRooms(meetingMap());
    r.ensure('a', 2);
    expect(r.ensure('a', 4)).toEqual(['meeting:small']);
  });

  it('несколько встреч: свободных нет — пусто', () => {
    const r = new MeetingRooms(meetingMap());
    expect(r.ensure('a', 4)).toEqual(['meeting:big']);
    expect(r.ensure('b', 2)).toEqual(['meeting:small']);
    expect(r.ensure('c', 9)).toEqual(['meeting:mid']);
    expect(r.ensure('d', 1)).toEqual([]);
  });

  it('addRoom добавляет самую большую свободную; release освобождает', () => {
    const r = new MeetingRooms(meetingMap());
    r.ensure('a', 2);
    expect(r.addRoom('a')).toBe('meeting:big');
    expect(r.roomsOf('a')).toEqual(['meeting:small', 'meeting:big']);
    r.release(new Set());
    expect(r.allocations()).toEqual({});
    expect(r.ensure('b', 1)).toEqual(['meeting:small']);
  });
});
```

- [ ] **Step 2: падающие тесты `packages/core/tests/targets.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { MeetingRooms, parseTarget, resolveTargets, type ResolveContext } from '../src/index.ts';
import { bundle } from './fixtures.ts';

const map = bundle().map;
const id = (x: number, y: number) => map.spotAt(x, y)!.id;
const T = (...s: string[]) => s.map((x) => parseTarget(x)!);
const AGENT = { id: 'agent:a:p:%1', kind: 'agent' as const, ownerId: 'a' };
const HUMAN = { id: 'a', kind: 'human' as const, podZoneId: 'pod:a' };

function ctx(over: Partial<ResolveContext> = {}): ResolveContext {
  return {
    map,
    reservations: new Map(),
    entity: AGENT,
    podOf: (eid) => (eid === 'a' ? 'pod:a' : undefined),
    lastSeat: null,
    currentSpot: null,
    currentIsWorkSeat: false,
    meetingId: undefined,
    meetings: new MeetingRooms(map),
    meetingNeed: () => 1,
    ...over,
  };
}
const spotOf = (r: ReturnType<typeof resolveTargets>) => (r.resolved?.kind === 'spot' ? r.resolved.spotId : r.resolved?.kind ?? null);

describe('resolveTargets', () => {
  it('own_seat — место owner_seat в углу человека', () => {
    expect(spotOf(resolveTargets(T('own_seat'), ctx({ entity: HUMAN })))).toBe(id(1, 2));
    expect(resolveTargets(T('own_seat'), ctx()).resolved).toBeNull(); // у агента своего угла нет
  });

  it('owner_pod_seat: первое свободное агентское место, бронь соседа пропускается', () => {
    expect(spotOf(resolveTargets(T('owner_pod_seat'), ctx()))).toBe(id(2, 2));
    const res = new Map([[id(2, 2), 'agent:a:p:%9']]);
    expect(spotOf(resolveTargets(T('owner_pod_seat'), ctx({ reservations: res })))).toBe(id(3, 2));
  });

  it('owner_pod_seat предпочитает текущее, затем прошлое место', () => {
    expect(spotOf(resolveTargets(T('owner_pod_seat'), ctx({ lastSeat: id(4, 2) })))).toBe(id(4, 2));
    expect(spotOf(resolveTargets(T('owner_pod_seat'), ctx({ lastSeat: id(4, 2), currentSpot: id(3, 2) })))).toBe(id(3, 2));
  });

  it('зоны с фильтрами; owner_seat зоной не выдаётся', () => {
    expect(spotOf(resolveTargets(T('zone:coworking:pose=sit'), ctx()))).toBe(id(10, 2));
    expect(spotOf(resolveTargets(T('zone:lounge:pose=play'), ctx()))).toBe(id(1, 5));
    expect(spotOf(resolveTargets(T('zone:pod:a'), ctx()))).toBe(id(2, 2));
    expect(resolveTargets(T('zone:lounge:pose=sit'), ctx()).resolved).toBeNull();
  });

  it('список по приоритету и lastZoneId для запасной клетки', () => {
    const full = new Map([id(2, 2), id(3, 2), id(4, 2)].map((s) => [s, 'other']));
    const r = resolveTargets(T('owner_pod_seat', 'zone:coworking:pose=sit'), ctx({ reservations: full }));
    expect(spotOf(r)).toBe(id(10, 2));
    const none = resolveTargets(T('owner_pod_seat', 'zone:lounge:pose=sit'), ctx({ reservations: full }));
    expect(none).toEqual({ resolved: null, lastZoneId: 'lounge' });
  });

  it('current_work_seat — только если текущее место назначено работой', () => {
    expect(resolveTargets(T('current_work_seat'), ctx({ currentSpot: id(3, 2) })).resolved).toBeNull();
    expect(spotOf(resolveTargets(T('current_work_seat'), ctx({ currentSpot: id(3, 2), currentIsWorkSeat: true })))).toBe(id(3, 2));
  });

  it('stay и exit', () => {
    expect(spotOf(resolveTargets(T('stay'), ctx()))).toBe('stay');
    expect(spotOf(resolveTargets(T('exit'), ctx()))).toBe('exit');
  });

  it('meeting_room закрепляет переговорку; при заполнении — стоячие, затем другая комната', () => {
    const meetings = new MeetingRooms(map);
    const c = ctx({ entity: HUMAN, meetingId: 'm', meetings, meetingNeed: () => 2 });
    expect(spotOf(resolveTargets(T('meeting_room'), c))).toBe(id(6, 2));
    expect(meetings.roomsOf('m')).toEqual(['meeting:m1']);
    const full = new Map([[id(6, 2), 'x'], [id(7, 2), 'y']]);
    expect(resolveTargets(T('meeting_room', 'meeting_room_standing'), { ...c, reservations: full }).resolved).toBeNull(); // других комнат нет
    expect(resolveTargets(T('meeting_room'), ctx({ entity: HUMAN })).resolved).toBeNull(); // без meetingId
  });
});
```

Run: `pnpm vitest run packages/core` → FAIL.

- [ ] **Step 3: `packages/core/src/sim/types.ts`**

```ts
// Сущность с точки зрения симуляции: агенту нужен хозяин, человеку — его угол.
export type SimEntity = { id: string; kind: 'human' | 'agent'; ownerId?: string; podZoneId?: string };
```

- [ ] **Step 4: `packages/core/src/sim/meetings.ts`**

```ts
import type { Zone } from '../office.ts';
import type { WorldMap } from '../world-map.ts';

// Закрепление переговорок за встречами (спека 5.3).
export class MeetingRooms {
  private readonly map: WorldMap;
  private readonly alloc = new Map<string, string[]>();

  constructor(map: WorldMap) {
    this.map = map;
  }

  capacity(zoneId: string): number {
    return this.map.spotsInZone(zoneId).filter((s) => s.pose === 'sit').length;
  }

  roomsOf(meetingId: string): string[] {
    return this.alloc.get(meetingId) ?? [];
  }

  private free(): Zone[] {
    const taken = new Set([...this.alloc.values()].flat());
    return this.map.zones.filter((z) => z.kind === 'meeting' && !taken.has(z.id));
  }

  private largestFree(): Zone | undefined {
    return [...this.free()].sort((a, b) => this.capacity(b.id) - this.capacity(a.id) || a.id.localeCompare(b.id))[0];
  }

  ensure(meetingId: string, need: number): string[] {
    const cur = this.alloc.get(meetingId);
    if (cur) return cur;
    const fit = [...this.free()]
      .sort((a, b) => this.capacity(a.id) - this.capacity(b.id) || a.id.localeCompare(b.id))
      .find((z) => this.capacity(z.id) >= need);
    const room = fit ?? this.largestFree();
    if (!room) return [];
    this.alloc.set(meetingId, [room.id]);
    return [room.id];
  }

  addRoom(meetingId: string): string | null {
    const room = this.largestFree();
    if (!room) return null;
    this.alloc.set(meetingId, [...this.roomsOf(meetingId), room.id]);
    return room.id;
  }

  release(active: ReadonlySet<string>): void {
    for (const id of [...this.alloc.keys()]) if (!active.has(id)) this.alloc.delete(id);
  }

  allocations(): Record<string, string[]> {
    return Object.fromEntries(this.alloc);
  }
}
```

- [ ] **Step 5: `packages/core/src/sim/targets.ts`**

```ts
import type { RuleTarget } from '../rules.ts';
import type { Spot, WorldMap } from '../world-map.ts';
import type { MeetingRooms } from './meetings.ts';
import type { SimEntity } from './types.ts';

export type Resolved = { kind: 'spot'; spotId: string } | { kind: 'exit' } | { kind: 'stay' };
export type ResolveContext = {
  map: WorldMap;
  reservations: ReadonlyMap<string, string>;
  entity: SimEntity;
  podOf(entityId: string): string | undefined;
  lastSeat: string | null;
  currentSpot: string | null;
  currentIsWorkSeat: boolean;
  meetingId: string | undefined;
  meetings: MeetingRooms;
  meetingNeed(meetingId: string): number;
};
type One = { resolved: Resolved | null; zoneId?: string | null };

const spot = (s: Spot): Resolved => ({ kind: 'spot', spotId: s.id });
const isFree = (ctx: ResolveContext, s: Spot) => {
  const who = ctx.reservations.get(s.id);
  return who === undefined || who === ctx.entity.id;
};
const pick = (candidates: Spot[], prefer: (string | null)[]): Spot | undefined => {
  for (const p of prefer) {
    const s = p ? candidates.find((c) => c.id === p) : undefined;
    if (s) return s;
  }
  return candidates[0];
};

function resolveMeeting(kind: 'meeting_room' | 'meeting_room_standing', ctx: ResolveContext): One {
  const mid = ctx.meetingId;
  if (!mid) return { resolved: null, zoneId: null };
  let rooms = ctx.meetings.roomsOf(mid);
  if (rooms.length === 0) rooms = ctx.meetings.ensure(mid, ctx.meetingNeed(mid));
  if (rooms.length === 0) return { resolved: null, zoneId: null };
  const pose = kind === 'meeting_room' ? 'sit' : 'stand';
  for (const z of rooms) {
    const s = pick(ctx.map.spotsInZone(z).filter((sp) => sp.pose === pose && isFree(ctx, sp)), [ctx.currentSpot]);
    if (s) return { resolved: spot(s), zoneId: rooms[0]! };
  }
  if (kind === 'meeting_room_standing') {
    // Стоячих мест нет — за встречей закрепляется ещё одна свободная переговорка.
    const extra = ctx.meetings.addRoom(mid);
    if (extra) {
      const c = ctx.map.spotsInZone(extra).filter((sp) => (sp.pose === 'sit' || sp.pose === 'stand') && isFree(ctx, sp));
      const s = c.find((sp) => sp.pose === 'sit') ?? c[0];
      if (s) return { resolved: spot(s), zoneId: extra };
    }
  }
  return { resolved: null, zoneId: rooms[0]! };
}

function resolveOne(t: RuleTarget, ctx: ResolveContext): One {
  switch (t.kind) {
    case 'own_seat': {
      const pod = ctx.podOf(ctx.entity.id);
      if (!pod) return { resolved: null, zoneId: null };
      const s = ctx.map.spotsInZone(pod).find((sp) => sp.tags.includes('owner_seat') && isFree(ctx, sp));
      return { resolved: s ? spot(s) : null, zoneId: pod };
    }
    case 'owner_pod_seat': {
      const pod = ctx.entity.ownerId ? ctx.podOf(ctx.entity.ownerId) : undefined;
      if (!pod) return { resolved: null, zoneId: null };
      const c = ctx.map.spotsInZone(pod).filter((sp) => sp.pose === 'sit' && !sp.tags.includes('owner_seat') && isFree(ctx, sp));
      const s = pick(c, [ctx.currentSpot, ctx.lastSeat]);
      return { resolved: s ? spot(s) : null, zoneId: pod };
    }
    case 'zone': {
      const c = ctx.map
        .spotsInZone(t.zoneId)
        .filter((sp) => !sp.tags.includes('owner_seat') && (!t.pose || sp.pose === t.pose) && (!t.tag || sp.tags.includes(t.tag)) && isFree(ctx, sp));
      const s = pick(c, [ctx.currentSpot]);
      return { resolved: s ? spot(s) : null, zoneId: t.zoneId };
    }
    case 'current_work_seat':
      return { resolved: ctx.currentIsWorkSeat && ctx.currentSpot ? { kind: 'spot', spotId: ctx.currentSpot } : null };
    case 'meeting_room':
    case 'meeting_room_standing':
      return resolveMeeting(t.kind, ctx);
    case 'stay':
      return { resolved: { kind: 'stay' } };
    case 'exit':
      return { resolved: { kind: 'exit' } };
  }
}

export function resolveTargets(targets: readonly RuleTarget[], ctx: ResolveContext): { resolved: Resolved | null; lastZoneId: string | null } {
  let lastZoneId: string | null = null;
  for (const t of targets) {
    const r = resolveOne(t, ctx);
    if (r.zoneId !== undefined) lastZoneId = r.zoneId;
    if (r.resolved) return { resolved: r.resolved, lastZoneId };
  }
  return { resolved: null, lastZoneId };
}
```

- [ ] **Step 6: экспорт, прогон, гейт, коммит**

В `index.ts`:
```ts
export * from './sim/types.ts';
export * from './sim/meetings.ts';
export * from './sim/targets.ts';
```

```bash
pnpm vitest run packages/core   # PASS
pnpm gate
git add packages/core
git commit -m "feat(core): разрешение целей правил и закрепление переговорок"
```

**Критерий готовности:** тесты переговорок и целей зелёные, включая выбор переговорки по вместимости, `current_work_seat` и предпочтение прошлого места.

---

### Задача 14: core — World: статусы с dwell, брони, появление, движение, выход

**Files:**
- Create: `packages/core/src/sim/world.ts`
- Modify: `packages/core/src/index.ts`
- Test: `packages/core/tests/world.test.ts`

**Interfaces:**
- Consumes: `WorldMap`, `Rules`, `RuleTarget`, `CharactersDef['poses']`, `animFor`, `findPath`, `Cell`, `MeetingRooms`, `resolveTargets`, `ResolveContext`, `SimEntity`, `zoneContains`, типы `CharacterState`, `Bubble`, `Status` из protocol.
- Produces: `type WorldOptions = { map; rules; poses; speedCellsPerSec?: number /* 3 */; spawnIntervalMs?: number /* 400 */; onWarn?: (msg: string) => void }`, `class World` с методами:
  - `now(): number` — время симуляции, мс.
  - `upsertEntity(e: SimEntity): void`, `removeEntity(id): void` (видимый → попадёт в `despawned`).
  - `setStatus(id, status, meetingId?)` — сырой статус. `needs_input` принимается сразу, остальные — через `rules.dwellMs` (спека 4.4).
  - `status(id): { status; meetingId? } | undefined` — принятый статус.
  - `tick(dtMs)` — принять созревшие статусы (порядок: время появления, `meetingId`, id), освободить переговорки, выпустить одного из очереди у входа (не чаще `spawnIntervalMs`), сдвинуть персонажей.
  - `characters(): CharacterState[]` — видимые персонажи. Поле `bubble` есть, только если облачко активно.
  - `drainEvents(): { changed: CharacterState[]; despawned: string[] }` — изменения с прошлого вызова. `bubble` в `changed` присутствует, только если облачко изменилось.
  
  Задача 15 добавит `setBubble`, `bootstrap`, `setRules`, `lastSeats`, `restoreLastSeats`, `debugInfo`.

Поведение (спека 5.3–5.4):
1. Место бронируется в момент назначения. Смена цели снимает старую бронь.
2. Цель, назначенная при статусе `working`, — «рабочее место» (`workSeat`), его видит `current_work_seat`.
3. Невидимый персонаж с целью-местом встаёт в очередь у входа. Видимый идёт по A\* от округлённой текущей клетки.
4. Скорость 3 клетки/с, 4 направления. В пути `pose: 'walk'`, `anim: 'walk'`, `facing` — по направлению шага.
5. Дошёл до места → координаты места, `pose`, `facing`, `offset` места, `anim = animFor(poses, pose, facing)`. Агент, севший на `sit` в углу хозяина, запоминает место как `lastSeat`.
6. Дошёл до выхода → невидим, id в `despawned`.
7. Ни одна цель недоступна → warn и ближайшая свободная транзитная клетка зоны последней цели. Если в зоне таких нет — в рамке зоны, расширенной на 1. Нет и там → `stay`.

- [ ] **Step 1: падающие тесты `packages/core/tests/world.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { World, type Rules } from '../src/index.ts';
import { bundle } from './fixtures.ts';

const b = bundle();
const FAST: Partial<Rules> = { dwellMs: { agent: 0, human: 0 } };

function world(over: Partial<Rules> = {}, warns: string[] = []) {
  const w = new World({ map: b.map, rules: { ...b.rules, ...over }, poses: b.catalog.characters.poses, onWarn: (m) => warns.push(m) });
  w.upsertEntity({ id: 'a', kind: 'human', podZoneId: 'pod:a' });
  return w;
}
const agent = (n: number) => ({ id: `agent:a:p:%${n}`, kind: 'agent' as const, ownerId: 'a' });
function run(w: World, ms: number, each?: () => void) {
  for (let t = 0; t < ms; t += 50) {
    w.tick(50);
    each?.();
  }
}
const ch = (w: World, id: string) => w.characters().find((c) => c.id === id);
const at = (w: World, id: string) => {
  const c = ch(w, id);
  return c ? [c.x, c.y] : null;
};

describe('World', () => {
  it('человек online: после dwell появляется у входа и садится на своё место', () => {
    const w = world();
    w.setStatus('a', 'online');
    run(w, 59_950);
    expect(ch(w, 'a')).toBeUndefined();
    run(w, 100);
    const c = ch(w, 'a')!;
    expect(c.x).toBe(6);
    expect(c.y).toBeLessThan(6);
    expect(c.pose).toBe('walk');
    run(w, 5000);
    expect(ch(w, 'a')).toMatchObject({ x: 1, y: 2, pose: 'sit', facing: 'up', anim: 'walk', offset: [0, -4] });
  });

  it('дребезг: статус, не продержавшийся dwell, не меняет цель', () => {
    const w = world();
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'working');
    run(w, 10_000);
    w.setStatus(A.id, 'idle');
    run(w, 15_000);
    expect(ch(w, A.id)).toBeUndefined(); // working не созрел, idle ещё не созрел
    run(w, 10_000);
    expect(w.status(A.id)?.status).toBe('idle');
    run(w, 10_000);
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5, pose: 'play' });
  });

  it('needs_input без dwell: из лаунжа сразу идёт в угол хозяина', () => {
    const w = world();
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'idle');
    run(w, 30_000);
    expect(at(w, A.id)).toEqual([1, 5]);
    w.setStatus(A.id, 'needs_input');
    expect(w.status(A.id)?.status).toBe('needs_input');
    run(w, 6000);
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit' });
  });

  it('needs_input за рабочим столом — остаётся на месте (current_work_seat)', () => {
    const w = world();
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'working');
    run(w, 30_000);
    expect(at(w, A.id)).toEqual([2, 2]);
    w.setStatus(A.id, 'needs_input');
    run(w, 1000);
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit' });
  });

  it('offline: идёт к выходу и исчезает', () => {
    const w = world(FAST);
    w.setStatus('a', 'online');
    run(w, 6000);
    w.drainEvents();
    w.setStatus('a', 'offline');
    run(w, 6000);
    expect(ch(w, 'a')).toBeUndefined();
    expect(w.drainEvents().despawned).toEqual(['a']);
  });

  it('очередь появления: по одному каждые 0,4 с', () => {
    const w = world(FAST);
    const [A, B] = [agent(1), agent(2)];
    w.upsertEntity(A);
    w.upsertEntity(B);
    w.setStatus(A.id, 'working');
    w.setStatus(B.id, 'working');
    w.tick(50);
    expect([!!ch(w, A.id), !!ch(w, B.id)]).toEqual([true, false]);
    run(w, 350);
    expect(ch(w, B.id)).toBeUndefined();
    run(w, 50);
    expect(ch(w, B.id)).toBeDefined();
  });

  it('смена цели посреди пути — перепланирование, блокирующие клетки не посещаются', () => {
    const w = world(FAST);
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'working');
    run(w, 1000);
    w.setStatus(A.id, 'idle');
    const visited: string[] = [];
    run(w, 8000, () => {
      const c = ch(w, A.id);
      if (c) visited.push(`${Math.round(c.x)},${Math.round(c.y)}`);
    });
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5, pose: 'play' });
    expect(visited.filter((k) => { const [x, y] = k.split(',').map(Number); return b.map.isBlocked(x!, y!); })).toEqual([]);
  });

  it('брони: места не дублируются; нехватка — коворкинг, затем запасная клетка с warn', () => {
    const warns: string[] = [];
    const w = world(FAST, warns);
    const agents = [1, 2, 3, 4, 5, 6].map(agent);
    for (const A of agents) {
      w.upsertEntity(A);
      w.setStatus(A.id, 'working');
    }
    run(w, 15_000);
    const pos = agents.map((A) => at(w, A.id)!.join(','));
    expect(new Set(pos).size).toBe(6);
    expect(pos.slice(0, 5).sort()).toEqual(['10,2', '11,2', '2,2', '3,2', '4,2']);
    const [fx, fy] = at(w, agents[5]!.id)!;
    expect(fx).toBeGreaterThanOrEqual(9);
    expect(fx).toBeLessThanOrEqual(12);
    expect(fy).toBeLessThanOrEqual(3);
    expect(warns.some((m) => m.includes('недоступна'))).toBe(true);
  });

  it('owner_pod_seat предпочитает место, где агент сидел в прошлый раз', () => {
    const w = world(FAST);
    const [X, W] = [agent(1), agent(2)];
    w.upsertEntity(W);
    w.upsertEntity(X);
    w.setStatus(W.id, 'working');
    run(w, 500);
    w.setStatus(X.id, 'working');
    run(w, 10_000);
    expect(at(w, X.id)).toEqual([3, 2]);
    w.setStatus(W.id, 'offline');
    w.setStatus(X.id, 'idle');
    run(w, 10_000);
    w.setStatus(X.id, 'working');
    run(w, 10_000);
    expect(at(w, X.id)).toEqual([3, 2]); // без предпочтения сел бы на свободное (2,2)
  });

  it('stay — остаётся где есть', () => {
    const w = world({ ...FAST, agent: { ...b.rules.agent, needs_input: [{ kind: 'stay' }] } });
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'idle');
    run(w, 10_000);
    w.setStatus(A.id, 'needs_input');
    run(w, 3000);
    expect(at(w, A.id)).toEqual([1, 5]);
  });

  it('drainEvents отдаёт изменения один раз', () => {
    const w = world(FAST);
    w.setStatus('a', 'online');
    w.tick(50);
    expect(w.drainEvents().changed.map((c) => c.id)).toEqual(['a']);
    expect(w.drainEvents().changed).toEqual([]);
  });
});
```

Run: `pnpm vitest run packages/core/tests/world.test.ts` → FAIL.

- [ ] **Step 2: `packages/core/src/sim/world.ts`**

```ts
import type { AnimName, Bubble, CharacterState, Facing, Pose, Status } from '@pixeloffice/protocol';
import type { CharactersDef } from '../catalog.ts';
import { animFor } from '../characters.ts';
import { zoneContains, type Zone } from '../office.ts';
import { findPath, type Cell } from '../path/astar.ts';
import type { RuleTarget, Rules } from '../rules.ts';
import type { WorldMap } from '../world-map.ts';
import { MeetingRooms } from './meetings.ts';
import { resolveTargets, type ResolveContext } from './targets.ts';
import type { SimEntity } from './types.ts';

export type WorldOptions = {
  map: WorldMap;
  rules: Rules;
  poses: CharactersDef['poses'];
  speedCellsPerSec?: number;
  spawnIntervalMs?: number;
  onWarn?: (msg: string) => void;
};

type StatusRec = { status: Status; meetingId?: string };
type Goal = { kind: 'spot'; spotId: string } | { kind: 'cell'; x: number; y: number } | { kind: 'exit' } | { kind: 'stay' };
type Char = {
  e: SimEntity;
  latest: StatusRec & { since: number }; // последний сырой статус
  committed: StatusRec; // принятый (прошёл dwell)
  visible: boolean;
  queued: boolean;
  x: number;
  y: number;
  facing: Facing;
  pose: Pose | 'walk';
  anim: AnimName;
  offset: [number, number];
  path: Cell[];
  goal: Goal | null;
  reserved: string | null;
  workSeat: string | null;
  lastSeat: string | null;
  bubble: { text: string; kind: Bubble['kind']; expiresAt: number } | null;
  bubbleDirty: boolean;
};

const DIRS: Cell[] = [[0, -1], [1, 0], [0, 1], [-1, 0]];
const sameStatus = (a: StatusRec, b: StatusRec) => a.status === b.status && (a.meetingId ?? null) === (b.meetingId ?? null);
const round3 = (v: number) => Math.round(v * 1000) / 1000;
const facingOf = (dx: number, dy: number): Facing => (Math.abs(dx) >= Math.abs(dy) ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'down' : 'up');

export class World {
  private readonly map: WorldMap;
  private rules: Rules;
  private readonly poses: CharactersDef['poses'];
  private readonly speed: number;
  private readonly spawnInterval: number;
  private readonly warn: (msg: string) => void;
  private readonly chars = new Map<string, Char>();
  private readonly reservations = new Map<string, string>();
  private readonly meetings: MeetingRooms;
  private spawnQueue: string[] = [];
  private nextSpawnAt = 0;
  private despawned: string[] = [];
  private readonly lastSent = new Map<string, string>();
  private t = 0;

  constructor(o: WorldOptions) {
    this.map = o.map;
    this.rules = o.rules;
    this.poses = o.poses;
    this.speed = o.speedCellsPerSec ?? 3;
    this.spawnInterval = o.spawnIntervalMs ?? 400;
    this.warn = o.onWarn ?? (() => {});
    this.meetings = new MeetingRooms(o.map);
  }

  now(): number {
    return this.t;
  }

  upsertEntity(e: SimEntity): void {
    const existing = this.chars.get(e.id);
    if (existing) {
      existing.e = e;
      return;
    }
    const [ex, ey] = this.map.entrance();
    this.chars.set(e.id, {
      e,
      latest: { status: 'offline', since: this.t },
      committed: { status: 'offline' },
      visible: false,
      queued: false,
      x: ex,
      y: ey,
      facing: 'up',
      pose: 'stand',
      anim: 'idle',
      offset: [0, 0],
      path: [],
      goal: null,
      reserved: null,
      workSeat: null,
      lastSeat: null,
      bubble: null,
      bubbleDirty: false,
    });
  }

  removeEntity(id: string): void {
    const c = this.chars.get(id);
    if (!c) return;
    if (c.reserved) this.reservations.delete(c.reserved);
    if (c.visible) this.despawned.push(id);
    this.spawnQueue = this.spawnQueue.filter((x) => x !== id);
    this.lastSent.delete(id);
    this.chars.delete(id);
  }

  status(id: string): StatusRec | undefined {
    return this.chars.get(id)?.committed;
  }

  setStatus(id: string, status: Status, meetingId?: string): void {
    const c = this.chars.get(id);
    if (!c) return;
    const next: StatusRec = { status, meetingId };
    if (sameStatus(c.latest, next)) return;
    c.latest = { ...next, since: this.t };
    if (sameStatus(c.latest, c.committed)) return; // вернулся к принятому — ждать нечего
    if (status === 'needs_input') this.commit(c); // без dwell (спека 4.4)
  }

  tick(dtMs: number): void {
    this.t += dtMs;
    const due = [...this.chars.values()].filter((c) => !sameStatus(c.latest, c.committed) && this.t - c.latest.since >= this.dwell(c));
    due.sort(
      (a, b) =>
        a.latest.since - b.latest.since ||
        (a.latest.meetingId ?? '').localeCompare(b.latest.meetingId ?? '') ||
        a.e.id.localeCompare(b.e.id),
    );
    for (const c of due) this.commit(c);
    this.releaseMeetings();
    this.processSpawns();
    for (const c of this.chars.values()) this.move(c, dtMs);
  }

  characters(): CharacterState[] {
    return [...this.chars.values()]
      .filter((c) => c.visible)
      .map((c) => (c.bubble ? { ...this.stateOf(c), bubble: this.bubbleOf(c) } : this.stateOf(c)));
  }

  drainEvents(): { changed: CharacterState[]; despawned: string[] } {
    const changed: CharacterState[] = [];
    for (const c of this.chars.values()) {
      if (!c.visible) continue;
      const s = this.stateOf(c);
      const key = JSON.stringify(s);
      if (this.lastSent.get(c.e.id) === key && !c.bubbleDirty) continue;
      this.lastSent.set(c.e.id, key);
      changed.push(c.bubbleDirty ? { ...s, bubble: this.bubbleOf(c) } : s);
      c.bubbleDirty = false;
    }
    const despawned = this.despawned.filter((id) => !this.chars.get(id)?.visible);
    this.despawned = [];
    return { changed, despawned };
  }

  // ---- внутреннее ----

  private dwell(c: Char): number {
    return c.e.kind === 'agent' ? this.rules.dwellMs.agent : this.rules.dwellMs.human;
  }

  private commit(c: Char): void {
    c.committed = { status: c.latest.status, meetingId: c.latest.meetingId };
    this.retarget(c);
  }

  private targetsFor(c: Char): RuleTarget[] | undefined {
    const table = (c.e.kind === 'human' ? this.rules.human : this.rules.agent) as Record<string, RuleTarget[] | undefined>;
    return table[c.committed.status];
  }

  private ctx(c: Char): ResolveContext {
    return {
      map: this.map,
      reservations: this.reservations,
      entity: c.e,
      podOf: (id) => this.chars.get(id)?.e.podZoneId,
      lastSeat: c.lastSeat,
      currentSpot: c.reserved,
      currentIsWorkSeat: c.reserved !== null && c.reserved === c.workSeat,
      meetingId: c.committed.meetingId,
      meetings: this.meetings,
      meetingNeed: (mid) => [...this.chars.values()].filter((x) => x.latest.status === 'meeting' && x.latest.meetingId === mid).length,
    };
  }

  private retarget(c: Char): void {
    const list = this.targetsFor(c);
    if (!list) {
      this.warn(`${c.e.id}: нет правил для ${c.e.kind}:${c.committed.status}`);
      return;
    }
    const { resolved, lastZoneId } = resolveTargets(list, this.ctx(c));
    if (resolved) return this.setGoal(c, resolved);
    this.warn(`${c.e.id}: ни одна цель для «${c.committed.status}» недоступна`);
    const cell = this.fallbackCell(c, lastZoneId);
    this.setGoal(c, cell ? { kind: 'cell', x: cell[0], y: cell[1] } : { kind: 'stay' });
  }

  private setGoal(c: Char, goal: Goal): void {
    if (goal.kind === 'stay') {
      c.goal = goal;
      return;
    }
    const spotId = goal.kind === 'spot' ? goal.spotId : null;
    if (c.reserved && c.reserved !== spotId) this.reservations.delete(c.reserved);
    c.reserved = spotId;
    if (spotId) this.reservations.set(spotId, c.e.id);
    if (spotId && c.committed.status === 'working') c.workSeat = spotId;
    else if (spotId !== c.workSeat) c.workSeat = null;
    c.goal = goal;
    if (goal.kind === 'exit') {
      if (!c.visible) {
        this.dequeue(c);
        c.path = [];
        return;
      }
      this.plan(c, this.map.entrance());
      return;
    }
    if (!c.visible) return this.enqueue(c);
    this.plan(c, this.goalCell(goal));
  }

  private goalCell(g: Goal): Cell {
    if (g.kind === 'spot') {
      const s = this.map.spot(g.spotId)!;
      return [s.x, s.y];
    }
    if (g.kind === 'cell') return [g.x, g.y];
    return this.map.entrance();
  }

  private enqueue(c: Char): void {
    if (c.queued) return;
    c.queued = true;
    this.spawnQueue.push(c.e.id);
  }

  private dequeue(c: Char): void {
    if (!c.queued) return;
    c.queued = false;
    this.spawnQueue = this.spawnQueue.filter((id) => id !== c.e.id);
  }

  private plan(c: Char, target: Cell): void {
    const from: Cell = [Math.round(c.x), Math.round(c.y)];
    const path = findPath(this.map, from, target);
    if (!path) {
      this.warn(`${c.e.id}: нет пути из (${from.join(',')}) в (${target.join(',')})`);
      c.path = [];
      return;
    }
    if (path.length === 1 && c.x === from[0] && c.y === from[1]) {
      c.path = [];
      this.arrive(c);
      return;
    }
    c.path = path;
    c.pose = 'walk';
    c.anim = 'walk';
    c.offset = [0, 0];
  }

  private processSpawns(): void {
    while (this.spawnQueue.length > 0 && this.t >= this.nextSpawnAt) {
      const c = this.chars.get(this.spawnQueue.shift()!);
      if (!c) continue;
      c.queued = false;
      if (c.visible || !c.goal || c.goal.kind === 'exit' || c.goal.kind === 'stay') continue;
      const [ex, ey] = this.map.entrance();
      c.x = ex;
      c.y = ey;
      c.facing = 'up';
      c.visible = true;
      c.bubbleDirty = c.bubble !== null;
      this.nextSpawnAt = this.t + this.spawnInterval;
      this.plan(c, this.goalCell(c.goal));
      break; // по одному (спека 5.4)
    }
  }

  private move(c: Char, dtMs: number): void {
    if (!c.visible || c.path.length === 0) return;
    let budget = (this.speed * dtMs) / 1000;
    while (budget > 1e-9 && c.path.length > 0) {
      const [nx, ny] = c.path[0]!;
      const dx = nx - c.x;
      const dy = ny - c.y;
      const dist = Math.abs(dx) + Math.abs(dy);
      if (dist <= budget + 1e-9) {
        c.x = nx;
        c.y = ny;
        budget -= dist;
        c.path.shift();
        if (dist > 0) c.facing = facingOf(dx, dy);
      } else {
        c.x += (dx / dist) * budget;
        c.y += (dy / dist) * budget;
        c.facing = facingOf(dx, dy);
        budget = 0;
      }
    }
    if (c.path.length === 0) this.arrive(c);
  }

  private arrive(c: Char): void {
    const g = c.goal;
    if (!g) return;
    if (g.kind === 'exit') {
      c.visible = false;
      c.path = [];
      c.goal = null;
      c.pose = 'stand';
      c.anim = 'idle';
      this.despawned.push(c.e.id);
      this.lastSent.delete(c.e.id);
      return;
    }
    if (g.kind === 'spot') {
      const s = this.map.spot(g.spotId)!;
      c.x = s.x;
      c.y = s.y;
      c.facing = s.facing;
      c.pose = s.pose;
      c.anim = animFor(this.poses, s.pose, s.facing);
      c.offset = s.offset;
      const ownerPod = c.e.ownerId ? this.chars.get(c.e.ownerId)?.e.podZoneId : undefined;
      if (c.e.kind === 'agent' && s.pose === 'sit' && ownerPod && s.zoneId === ownerPod) c.lastSeat = s.id;
      return;
    }
    if (g.kind === 'cell') {
      c.pose = 'stand';
      c.anim = animFor(this.poses, 'stand', c.facing);
      c.offset = [0, 0];
    }
  }

  private releaseMeetings(): void {
    const active = new Set<string>();
    for (const c of this.chars.values()) {
      for (const s of [c.latest, c.committed]) if (s.status === 'meeting' && s.meetingId) active.add(s.meetingId);
    }
    this.meetings.release(active);
  }

  // Ближайшая свободная транзитная клетка зоны (BFS от персонажа); нет — в рамке зоны +1.
  private fallbackCell(c: Char, zoneId: string | null): Cell | null {
    const zone = zoneId ? this.map.zones.find((z) => z.id === zoneId) : undefined;
    if (!zone) return null;
    const taken = new Set<string>();
    for (const o of this.chars.values()) if (o !== c && o.goal?.kind === 'cell') taken.add(`${o.goal.x},${o.goal.y}`);
    const start: Cell = c.visible ? [Math.round(c.x), Math.round(c.y)] : this.map.entrance();
    const grown: Zone = { ...zone, rect: [zone.rect[0] - 1, zone.rect[1] - 1, zone.rect[2] + 2, zone.rect[3] + 2] };
    for (const z of [zone, grown]) {
      const w = this.map.width;
      const seen = new Uint8Array(w * this.map.height);
      const queue: Cell[] = [start];
      seen[start[1] * w + start[0]] = 1;
      for (let i = 0; i < queue.length; i++) {
        const [x, y] = queue[i]!;
        if (zoneContains(z, x, y) && this.map.isTransit(x, y) && !taken.has(`${x},${y}`)) return [x, y];
        for (const [dx, dy] of DIRS) {
          const nx = x + dx;
          const ny = y + dy;
          if (this.map.isTransit(nx, ny) && !seen[ny * w + nx]) {
            seen[ny * w + nx] = 1;
            queue.push([nx, ny]);
          }
        }
      }
    }
    return null;
  }

  private stateOf(c: Char): CharacterState {
    return { id: c.e.id, x: round3(c.x), y: round3(c.y), facing: c.facing, pose: c.pose, anim: c.anim, offset: c.offset };
  }

  private bubbleOf(c: Char): Bubble | null {
    return c.bubble ? { text: c.bubble.text, kind: c.bubble.kind } : null;
  }
}
```

- [ ] **Step 3: экспорт, прогон**

В `index.ts`: `export * from './sim/world.ts';`

Run: `pnpm vitest run packages/core/tests/world.test.ts` → PASS. Если падают тесты с таймингом (например, «очередь появления»), проверить порядок операций в `tick` (принять → переговорки → появление → движение), а не подгонять числа в тесте.

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

```bash
pnpm gate
git add packages/core
git commit -m "feat(core): симуляция мира — dwell, брони, очередь у входа, движение"
```

**Критерий готовности:** 11 тестов World зелёные. Все тайминги детерминированы шагом 50 мс.

---

### Задача 15: core — World: облачка, мгновенная расстановка, горячая смена правил, отладка

**Files:**
- Modify: `packages/core/src/sim/world.ts`
- Test: `packages/core/tests/world-extra.test.ts`

**Interfaces:**
- Consumes: класс `World` из задачи 14.
- Produces (новые методы `World`):
  - `setBubble(id, text, ttlSec): void` — облачко сразу (спека 4.4). `kind = 'needs_input'`, если статус `needs_input`, иначе `'info'`. По истечении сервер убирает облачко: в дельте `bubble: null`.
  - `bootstrap(list: { id: string; status: Status; meetingId?: string }[]): void` — принять статусы без dwell и сразу поставить персонажей на места, без шествия от входа (спека 4.7, 5.4).
  - `setRules(rules: Rules): void` — заменить правила и сразу переназначить цели (решение 13).
  - `lastSeats(): Record<string, string>`, `restoreLastSeats(rec: Record<string, string>): void` — брони «прошлых мест» для `state.json`.
  - `debugInfo(): { paths: Record<string, [number, number][]>; reservations: Record<string, string>; meetings: Record<string, string[]> }`.
  - Правило решения 12: уход принятого статуса из `needs_input` гасит облачко вида `needs_input`.

- [ ] **Step 1: падающие тесты `packages/core/tests/world-extra.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { World, type Rules } from '../src/index.ts';
import { bundle } from './fixtures.ts';

const b = bundle();
const FAST: Partial<Rules> = { dwellMs: { agent: 0, human: 0 } };
const A = { id: 'agent:a:p:%1', kind: 'agent' as const, ownerId: 'a' };
const A2 = { id: 'agent:a:p:%2', kind: 'agent' as const, ownerId: 'a' };

function world(over: Partial<Rules> = FAST) {
  const w = new World({ map: b.map, rules: { ...b.rules, ...over }, poses: b.catalog.characters.poses });
  w.upsertEntity({ id: 'a', kind: 'human', podZoneId: 'pod:a' });
  w.upsertEntity(A);
  w.upsertEntity(A2);
  return w;
}
const run = (w: World, ms: number) => {
  for (let t = 0; t < ms; t += 50) w.tick(50);
};
const ch = (w: World, id: string) => w.characters().find((c) => c.id === id);
const bubbleIn = (w: World, id: string) => w.drainEvents().changed.find((c) => c.id === id)?.bubble;

describe('World: облачка', () => {
  it('появляется, не дублируется, убирается по ttl', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    w.drainEvents();
    w.setBubble(A.id, 'Привет', 5);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Привет', kind: 'info' });
    expect(w.drainEvents().changed).toEqual([]);
    run(w, 5000);
    expect(bubbleIn(w, A.id)).toBeNull();
  });

  it('needs_input: облачко с ?-видом и гаснет, когда статус уходит', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    w.setStatus(A.id, 'needs_input');
    w.setBubble(A.id, 'Разрешить pnpm test?', 3600);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Разрешить pnpm test?', kind: 'needs_input' });
    w.setStatus(A.id, 'working');
    run(w, 100);
    expect(bubbleIn(w, A.id)).toBeNull();
  });

  it('облачко невидимого персонажа приходит с его появлением', () => {
    const w = world();
    w.setBubble(A.id, 'Готов', 60);
    w.setStatus(A.id, 'working');
    w.tick(50);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Готов', kind: 'info' });
  });
});

describe('World: bootstrap, правила, прошлые места, отладка', () => {
  it('bootstrap ставит онлайн-сущности сразу на места, офлайн — невидимы', () => {
    const w = world({}); // реальный dwell: bootstrap его не ждёт
    w.bootstrap([
      { id: 'a', status: 'online' },
      { id: A.id, status: 'working' },
      { id: A2.id, status: 'offline' },
    ]);
    expect(ch(w, 'a')).toMatchObject({ x: 1, y: 2, pose: 'sit' });
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit' });
    expect(ch(w, A2.id)).toBeUndefined();
    expect(w.status(A.id)?.status).toBe('working');
  });

  it('setRules сразу переназначает цели', () => {
    const w = world();
    w.setStatus(A.id, 'idle');
    run(w, 8000);
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5 });
    w.setRules({ ...b.rules, ...FAST, agent: { ...b.rules.agent, idle: [{ kind: 'zone', zoneId: 'coworking', pose: 'sit' }] } });
    run(w, 8000);
    expect(ch(w, A.id)).toMatchObject({ x: 10, y: 2 });
  });

  it('прошлые места сохраняются и восстанавливаются', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 8000);
    expect(w.lastSeats()).toEqual({ [A.id]: b.map.spotAt(2, 2)!.id });
    const w2 = world();
    w2.restoreLastSeats({ [A.id]: b.map.spotAt(4, 2)!.id, 'agent:ghost': 'нет-такого' });
    w2.setStatus(A.id, 'working');
    run(w2, 8000);
    expect(ch(w2, A.id)).toMatchObject({ x: 4, y: 2 });
  });

  it('debugInfo: путь идущего, брони, переговорки', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    w.tick(50);
    const d = w.debugInfo();
    expect(d.paths[A.id]!.length).toBeGreaterThan(1);
    expect(d.reservations[b.map.spotAt(2, 2)!.id]).toBe(A.id);
    expect(d.meetings).toEqual({});
  });
});
```

Run: `pnpm vitest run packages/core/tests/world-extra.test.ts` → FAIL (нет методов).

- [ ] **Step 2: изменения в `packages/core/src/sim/world.ts`**

2.1. Метод `commit` заменить целиком:
```ts
  private commit(c: Char): void {
    const was = c.committed.status;
    c.committed = { status: c.latest.status, meetingId: c.latest.meetingId };
    // Решение 12: ответ на запрос — облачко запроса гаснет.
    if (was === 'needs_input' && c.committed.status !== 'needs_input' && c.bubble?.kind === 'needs_input') {
      c.bubble = null;
      c.bubbleDirty = true;
    }
    if (c.committed.status === 'needs_input' && c.bubble && c.bubble.kind !== 'needs_input') {
      c.bubble.kind = 'needs_input';
      c.bubbleDirty = true;
    }
    this.retarget(c);
  }
```

2.2. В `tick` сразу после `this.t += dtMs;` вставить:
```ts
    for (const c of this.chars.values()) {
      if (c.bubble && c.bubble.expiresAt <= this.t) {
        c.bubble = null;
        c.bubbleDirty = true;
      }
    }
```

2.3. Публичные методы — вставить после метода `status`:
```ts
  setBubble(id: string, text: string, ttlSec: number): void {
    const c = this.chars.get(id);
    if (!c) return;
    const kind = c.committed.status === 'needs_input' || c.latest.status === 'needs_input' ? 'needs_input' : 'info';
    c.bubble = { text, kind, expiresAt: this.t + ttlSec * 1000 };
    c.bubbleDirty = true;
  }

  // Старт сервера: статусы без dwell, онлайн-сущности сразу на местах (спека 4.7, 5.4).
  bootstrap(list: { id: string; status: Status; meetingId?: string }[]): void {
    for (const s of list) {
      const c = this.chars.get(s.id);
      if (!c) continue;
      c.latest = { status: s.status, meetingId: s.meetingId, since: this.t };
      c.committed = { status: s.status, meetingId: s.meetingId };
      c.visible = false;
      c.path = [];
      this.dequeue(c);
      if (s.status === 'offline') {
        if (c.reserved) this.reservations.delete(c.reserved);
        c.reserved = null;
        c.goal = null;
        continue;
      }
      this.retarget(c); // невидимый: цель назначена и поставлен в очередь
      this.dequeue(c);
      if (c.goal && (c.goal.kind === 'spot' || c.goal.kind === 'cell')) {
        const [x, y] = this.goalCell(c.goal);
        c.x = x;
        c.y = y;
        c.visible = true;
        this.arrive(c);
        c.bubbleDirty = c.bubble !== null;
      }
    }
  }

  setRules(rules: Rules): void {
    this.rules = rules;
    for (const c of this.chars.values()) if (c.committed.status !== 'offline') this.retarget(c);
  }

  lastSeats(): Record<string, string> {
    const out: Record<string, string> = {};
    for (const c of this.chars.values()) if (c.lastSeat) out[c.e.id] = c.lastSeat;
    return out;
  }

  restoreLastSeats(rec: Record<string, string>): void {
    for (const [id, spotId] of Object.entries(rec)) {
      const c = this.chars.get(id);
      if (c && this.map.spot(spotId)) c.lastSeat = spotId;
    }
  }

  debugInfo(): { paths: Record<string, [number, number][]>; reservations: Record<string, string>; meetings: Record<string, string[]> } {
    const paths: Record<string, [number, number][]> = {};
    for (const c of this.chars.values()) if (c.visible && c.path.length > 0) paths[c.e.id] = c.path.map(([x, y]) => [x, y]);
    return { paths, reservations: Object.fromEntries(this.reservations), meetings: this.meetings.allocations() };
  }
```

- [ ] **Step 3: прогон, гейт, коммит**

```bash
pnpm vitest run packages/core   # PASS, включая тесты задачи 14
pnpm gate
git add packages/core
git commit -m "feat(core): облачка, мгновенная расстановка и горячая смена правил в симуляции"
```

**Критерий готовности:** тесты `world-extra` и `world` зелёные. Облачко `needs_input` гаснет после ответа.

---

### Задача 16: офисы `local` и `demo`, расширение каталога, проверка атласа

**Files:**
- Modify: `catalog/limezu/catalog.yaml` (добавить `meeting_table`, `whiteboard`, проверить `monitor` с 2 вариантами, полы `wood`, `tiles_blue`)
- Create: `offices/local/{office.yaml,rules.yaml,config.example.yaml}`, `offices/demo/{office.yaml,rules.yaml,config.yaml}`
- Create: `tools/validate-maps/src/atlas.ts`, `tools/validate-maps/tests/atlas.test.ts`
- Modify: `tools/validate-maps/src/validate.ts`, `tools/validate-maps/src/index.ts`

**Interfaces:**
- Consumes: каталог (задача 3), `loadOfficeBundle`, `avatarLayerPaths`, `Catalog`, `Person`, `resolveFrom`.
- Produces: `readPngSize(path): { width; height }` (из IHDR, не PNG → `Error`), `checkAtlas(catalog, people, assetsDir): string[]` (пусто — ok). Офисы `offices/local` и `offices/demo` проходят `pnpm validate:maps`. `demo` — основа тестового режима и скриншотов (решение 4). Его токены: зритель `demo-viewer-token`, `nextcloud` → `demo-nextcloud-token`, `claude-hook` (owner `p1`) → `demo-hook-token`.

- [ ] **Step 1: каталог — переговорный стол и доска**

По координатам из заметки задачи 2 добавить в `catalog/limezu/catalog.yaml`:
```yaml
  meeting_table:
    size: [2, 1]
    blocks: all
    variants:
      - default:
          parts: [ { sheet: office, rect: [<x>, <y>, 32, 32], at: [0, -16], sortY: 1 } ]   # из заметки M0
  whiteboard:
    size: [1, 2]
    blocks: [[0, 0]]
    variants:
      - default:
          parts: [ { sheet: office, rect: [<x>, <y>, 16, 32], at: [0, 0], sortY: 1 } ]     # из заметки M0
          spots: [ { cell: [0, 1], facing: up, pose: stand } ]
```
Вместо `<x>, <y>` подставить значения из таблицы предметов `docs/spikes/2026-10-20-m0-art.md`. Если подходящего спрайта нет, взять из `14_Basement` или Modern Office похожий (стол переговорной — любой стол 2×1) и записать выбор в заметку. Тест каталога из задачи 6 (Step 7) должен остаться зелёным.

- [ ] **Step 2: `offices/local/office.yaml`**

```yaml
# Личный офис: угол Стаса (его место + 3 агентских), переговорка на 2, лаунж, коворкинг.
size: [16, 8]
floor:
  default: carpet_grey
  zones: { lounge: wood, "meeting:m1": tiles_blue }
legend:
  "#": wall
  ".": floor
  "E": entrance
  "D": desk
  "T": meeting_table
  "^": { item: chair, facing: up }
  "f": ficus
  "p": arcade
  "s": sofa
grid: |
  ################
  #DD.DD...TT..f.#
  #^^.^^...^^....#
  #..............#
  #p.p.ss..DD.DD.#
  #p.p.....^^.^^.#
  #..............#
  #######E########
placements:
  - { item: chair, at: [1, 2], tags: [owner_seat] }
  - { item: monitor, at: [1, 1], on: desk }
  - { item: monitor, at: [4, 1], on: desk }
  - { item: monitor, at: [9, 4], on: desk }
  - { item: monitor, at: [12, 4], on: desk }
zones:
  - { id: "pod:stas", kind: pod, rect: [1, 1, 5, 2] }
  - { id: "meeting:m1", kind: meeting, rect: [8, 1, 4, 2] }
  - { id: lounge, kind: common, rect: [1, 4, 6, 2] }
  - { id: coworking, kind: common, rect: [9, 4, 5, 2] }
```

Если у монитора в каталоге два варианта (к зрителю / спиной), здесь нужен вариант «к зрителю»: сидящий за этими столами смотрит вверх, на экран.

- [ ] **Step 3: `offices/local/rules.yaml` (как в спеке 5.3)**

```yaml
dwell: { agent: 20s, human: 60s }
human:
  online:  [own_seat]
  meeting: [meeting_room, meeting_room_standing]
  offline: [exit]
agent:
  working:     [owner_pod_seat, "zone:coworking:pose=sit"]
  idle:        ["zone:lounge:pose=play", "zone:lounge"]
  needs_input: [current_work_seat, owner_pod_seat, "zone:coworking:pose=sit"]
  offline:     [exit]
```

- [ ] **Step 4: `offices/local/config.example.yaml`**

```yaml
# Скопируйте в config.yaml командой `node packages/server/src/main.ts init offices/local` — токены подставятся случайные.
officeId: local
catalog: ../../catalog/limezu/catalog.yaml
listen: { host: 127.0.0.1, port: 4870 }
assetsDir: ~/tmp
dataDir: ~/.local/share/pixeloffice/local
log: { keepDays: 30 }
agentRetentionDays: 7
viewerTokens: [ "CHANGE_ME_viewer" ]
sources:
  - { source: claude-hook, token: "CHANGE_ME_hook", owner: stas,
      ttlSec: { working: 900, idle: 43200, needs_input: 43200 } }
  - { source: mock, token: "CHANGE_ME_mock", ttlSec: 3600 }   # люди для mock-сценариев (без owner); агенты сценариев идут через claude-hook
people:
  - { id: stas, name: Стас, nextcloudUid: stas, pod: "pod:stas",
      avatar: { body: 3, eyes: 2, outfit: [1, 1], hair: [1, 1] } }
bubbles: { talk: truncated }
# relay:                                  # включить в M5
#   target: https://office.example/v1/events
#   token: "CHANGE_ME_relay"
#   include: [ "~/Projects/Work/**" ]
```

Аватар взять из пула каталога: значения `outfit`/`hair` должны существовать среди файлов. Проверка атласа (Step 7) это поймает.

- [ ] **Step 5: `offices/demo/office.yaml`**

Сетка проверена при планировании: 45 мест, все достижимы от входа.

```yaml
# Демо- и тестовый офис: 9 человек, две переговорки (4 и 10 мест), лаунж, коворкинг,
# кресла во всех 4 направлениях. Используется тестовым режимом и скриншот-тестами.
size: [32, 14]
floor:
  default: carpet_grey
  zones: { lounge: wood, "meeting:m1": tiles_blue, "meeting:m2": tiles_blue }
legend:
  "#": wall
  ".": floor
  "E": entrance
  "D": desk
  "T": meeting_table
  "^": { item: chair, facing: up }
  "v": { item: chair, facing: down }
  "<": { item: chair, facing: left }
  ">": { item: chair, facing: right }
  "f": ficus
  "p": arcade
  "s": sofa
  "w": whiteboard
grid: |
  ################################
  #..............................#
  #.vv...vv...vv...vv.w..vvvvv..w#
  #.DD...DD...DD...TT.w..TTTTTT.w#
  #................^^....^^^^^...#
  #.DD...DD...DD.................#
  #.^^...^^...^^.................#
  #..............................#
  #>DD<.>DD<.>DD<..p.p.p......f..#
  #................p.p.p..ss.....#
  #.DD.DD.DD.....................#
  #.^^.^^.^^.....................#
  #..............................#
  ###############E################
placements:
  - { item: chair, at: [2, 2], tags: [owner_seat] }
  - { item: chair, at: [7, 2], tags: [owner_seat] }
  - { item: chair, at: [12, 2], tags: [owner_seat] }
  - { item: chair, at: [2, 6], tags: [owner_seat] }
  - { item: chair, at: [7, 6], tags: [owner_seat] }
  - { item: chair, at: [12, 6], tags: [owner_seat] }
  - { item: chair, at: [1, 8], tags: [owner_seat] }
  - { item: chair, at: [9, 8], tags: [owner_seat] }
  - { item: chair, at: [11, 8], tags: [owner_seat] }
  - { item: monitor, at: [2, 5], on: desk }
  - { item: monitor, at: [7, 5], on: desk }
  - { item: monitor, at: [12, 5], on: desk }
zones:
  - { id: "pod:p1", kind: pod, rect: [2, 2, 2, 2] }
  - { id: "pod:p2", kind: pod, rect: [7, 2, 2, 2] }
  - { id: "pod:p3", kind: pod, rect: [12, 2, 2, 2] }
  - { id: "pod:p4", kind: pod, rect: [2, 5, 2, 2] }
  - { id: "pod:p5", kind: pod, rect: [7, 5, 2, 2] }
  - { id: "pod:p6", kind: pod, rect: [12, 5, 2, 2] }
  - { id: "pod:p7", kind: pod, rect: [1, 8, 4, 1] }
  - { id: "pod:p8", kind: pod, rect: [6, 8, 4, 1] }
  - { id: "pod:p9", kind: pod, rect: [11, 8, 4, 1] }
  - { id: "meeting:m1", kind: meeting, rect: [16, 1, 5, 5] }
  - { id: "meeting:m2", kind: meeting, rect: [22, 1, 9, 5] }
  - { id: lounge, kind: common, rect: [16, 8, 10, 2] }
  - { id: coworking, kind: common, rect: [1, 10, 9, 2] }
```

Направления сидения у хозяев: p1–p3 — вниз, p4–p6 — вверх, p7 — вправо, p8 — влево (кресло `<` в (9,8)), p9 — вправо. Сценарий `sit4` (задача 22) использует p1, p4, p7, p8.

- [ ] **Step 6: `offices/demo/rules.yaml` и `offices/demo/config.yaml`**

`rules.yaml` — как у local, но с короткой защитой от дребезга (сценарии короче):
```yaml
dwell: { agent: 2s, human: 2s }
human:
  online:  [own_seat]
  meeting: [meeting_room, meeting_room_standing]
  offline: [exit]
agent:
  working:     [owner_pod_seat, "zone:coworking:pose=sit"]
  idle:        ["zone:lounge:pose=play", "zone:lounge"]
  needs_input: [current_work_seat, owner_pod_seat, "zone:coworking:pose=sit"]
  offline:     [exit]
```

`config.yaml` (коммитится, решение 5):
```yaml
officeId: demo
catalog: ../../catalog/limezu/catalog.yaml
listen: { host: 127.0.0.1, port: 4871 }
assetsDir: ~/tmp
dataDir: ../../.data/demo
viewerTokens: [ "demo-viewer-token" ]
sources:
  - { source: nextcloud, token: "demo-nextcloud-token", ttlSec: 120 }
  - { source: claude-hook, token: "demo-hook-token", owner: p1,
      ttlSec: { working: 900, idle: 43200, needs_input: 43200 } }
people:
  - { id: p1, name: Анна,    pod: "pod:p1", avatar: { body: 1, eyes: 1, outfit: [1, 1], hair: [1, 1] } }
  - { id: p2, name: Борис,   pod: "pod:p2", avatar: { body: 2, eyes: 2, outfit: [2, 1], hair: [2, 1] } }
  - { id: p3, name: Вера,    pod: "pod:p3", avatar: { body: 3, eyes: 3, outfit: [3, 1], hair: [3, 1] } }
  - { id: p4, name: Глеб,    pod: "pod:p4", avatar: { body: 4, eyes: 4, outfit: [4, 1], hair: [4, 1] } }
  - { id: p5, name: Дина,    pod: "pod:p5", avatar: { body: 5, eyes: 5, outfit: [5, 1], hair: [5, 1] } }
  - { id: p6, name: Егор,    pod: "pod:p6", avatar: { body: 6, eyes: 6, outfit: [6, 1], hair: [6, 1] } }
  - { id: p7, name: Жанна,   pod: "pod:p7", avatar: { body: 7, eyes: 7, outfit: [7, 1], hair: [7, 1] } }
  - { id: p8, name: Захар,   pod: "pod:p8", avatar: { body: 8, eyes: 1, outfit: [8, 1], hair: [8, 1] } }
  - { id: p9, name: Ирина,   pod: "pod:p9", avatar: { body: 9, eyes: 2, outfit: [9, 1], hair: [9, 1] } }
```
Номера моделей и цветов сверить с `pool` каталога: проверка атласа (Step 7) ловит отсутствующие файлы.

```bash
pnpm validate:maps
```
Expected: `✓ offices/demo — структура: ok`, `✓ offices/local — структура: ok`. Ошибки чинить в YAML офиса или каталога.

- [ ] **Step 7: проверка атласа — падающий тест `tools/validate-maps/tests/atlas.test.ts`**

```ts
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { checkAtlas, expandHome, readPngSize, validateOfficesDir } from '../src/index.ts';
import { miniCatalog } from '../../../packages/core/tests/fixtures.ts';

// Минимальный «PNG»: сигнатура + заголовок IHDR (размер читается только из него).
function fakePng(path: string, width: number, height: number) {
  mkdirSync(dirname(path), { recursive: true });
  const b = Buffer.alloc(33);
  Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0);
  b.writeUInt32BE(13, 8);
  b.write('IHDR', 12, 'ascii');
  b.writeUInt32BE(width, 16);
  b.writeUInt32BE(height, 20);
  writeFileSync(path, b);
}
const person = { id: 'a', name: 'A', pod: 'pod:a', avatar: { body: 1, eyes: 1, outfit: [1, 1] as [number, number], hair: [1, 1] as [number, number] } };

function assets(sheetW: number, sheetH: number, withEyes = true) {
  const dir = mkdtempSync(join(tmpdir(), 'po-atlas-'));
  fakePng(join(dir, 'test/sheet.png'), sheetW, sheetH);
  for (const f of ['gen/Body_01.png', 'gen/Outfit_01_01.png', 'gen/Hairstyle_01_01.png', ...(withEyes ? ['gen/Eyes_01.png'] : [])]) fakePng(join(dir, f), 896, 656);
  return dir;
}

describe('проверка атласа', () => {
  it('readPngSize читает IHDR', () => {
    const dir = assets(256, 848);
    expect(readPngSize(join(dir, 'test/sheet.png'))).toEqual({ width: 256, height: 848 });
  });

  it('все кадры в границах — пусто', () => {
    expect(checkAtlas(miniCatalog(), [person], assets(128, 160))).toEqual([]);
  });

  it('кадр за границей листа', () => {
    expect(checkAtlas(miniCatalog(), [person], assets(128, 100)).join('\n')).toContain('вне листа');
  });

  it('нет файла слоя аватара', () => {
    expect(checkAtlas(miniCatalog(), [person], assets(128, 160, false)).join('\n')).toContain('Eyes_01.png');
  });
});

// Спека 5.5: атлас по настоящим PNG — в тестах при наличии assetsDir, без ассетов тест skipped.
const OFFICES = fileURLToPath(new URL('../../../offices/', import.meta.url));
const REAL_ASSETS = expandHome('~/tmp'); // assetsDir офисов demo и local

describe('атлас настоящих офисов', () => {
  it.skipIf(!existsSync(REAL_ASSETS))('offices/*: кадры каталога и слои аватаров в границах PNG', async () => {
    const reports = await validateOfficesDir(OFFICES);
    expect(reports.flatMap((r) => r.errors)).toEqual([]);
    const checked = reports.filter((r) => r.notes.includes('атлас: ok')).map((r) => basename(r.dir));
    expect(checked).toEqual(expect.arrayContaining(['demo', 'local']));
  });
});
```

Run: `pnpm vitest run tools/validate-maps` → FAIL.

- [ ] **Step 8: `tools/validate-maps/src/atlas.ts`**

```ts
import { closeSync, existsSync, openSync, readSync } from 'node:fs';
import { join } from 'node:path';
import { avatarLayerPaths, itemView, type Catalog, type Part, type Person } from '@pixeloffice/core';

export function readPngSize(path: string): { width: number; height: number } {
  const fd = openSync(path, 'r');
  try {
    const buf = Buffer.alloc(24);
    readSync(fd, buf, 0, 24, 0);
    if (buf.readUInt32BE(0) !== 0x89504e47 || buf.toString('ascii', 12, 16) !== 'IHDR') throw new Error(`${path}: не PNG`);
    return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
  } finally {
    closeSync(fd);
  }
}

// Кадры каталога попадают в границы PNG, слои аватаров существуют (спека 5.5).
export function checkAtlas(catalog: Catalog, people: Person[], assetsDir: string): string[] {
  const errors: string[] = [];
  const sizes = new Map<string, { width: number; height: number } | null>();
  const size = (rel: string) => {
    if (!sizes.has(rel)) {
      const p = join(assetsDir, rel);
      sizes.set(rel, existsSync(p) ? readPngSize(p) : null);
    }
    return sizes.get(rel)!;
  };
  const checkRect = (where: string, rel: string, [x, y, w, h]: [number, number, number, number]) => {
    const s = size(rel);
    if (!s) return errors.push(`${where}: нет файла ${rel}`);
    if (x + w > s.width || y + h > s.height) errors.push(`${where}: кадр [${x},${y},${w},${h}] вне листа ${rel} ${s.width}×${s.height}`);
  };
  const checkParts = (where: string, parts: Part[]) => parts.forEach((p, i) => checkRect(`${where}[${i}]`, catalog.sheets[p.sheet]!, p.rect));
  for (const [name, frames] of Object.entries(catalog.floors)) frames.forEach((f, i) => checkRect(`floors.${name}[${i}]`, catalog.sheets[f.sheet]!, f.rect));
  for (const def of Object.values(catalog.items)) {
    if (def.autotile) {
      def.autotile.rules.forEach((r, i) => checkParts(`items.${def.id}.autotile.rules[${i}]`, r.parts));
      checkParts(`items.${def.id}.autotile.door`, def.autotile.door);
    }
    def.variants.forEach((_v, vi) => {
      for (const key of def.facings ?? [null]) checkParts(`items.${def.id}.variants[${vi}].${key ?? 'default'}`, itemView(def, key, vi + 1).parts);
    });
  }
  const { frame, animations } = catalog.characters;
  for (const p of people) {
    for (const rel of avatarLayerPaths(catalog.characters, p.avatar)) {
      const s = size(rel);
      if (!s) {
        errors.push(`people.${p.id}.avatar: нет файла ${rel}`);
        continue;
      }
      for (const [name, a] of Object.entries(animations)) {
        const maxCol = Math.max(...Object.values(a.dirs).map((d) => d ?? 0)) + a.frames;
        if (maxCol * frame[0] > s.width || (a.row + 1) * frame[1] > s.height) errors.push(`characters.animations.${name}: не помещается в ${rel} ${s.width}×${s.height}`);
      }
    }
  }
  return errors;
}
```

- [ ] **Step 9: атлас в `validateOfficesDir`**

В `tools/validate-maps/src/validate.ts`:
- импорт: `import { checkAtlas } from './atlas.ts';` и добавить `resolveFrom` к импорту из `./read.ts`;
- строку `reports.push(r.ok ? … )` заменить на:
```ts
      if (!r.ok) {
        reports.push({ dir, errors: [formatErrors(r.errors)], notes: [] });
        continue;
      }
      const assetsDir = resolveFrom(dir, r.value.config.assetsDir);
      if (!existsSync(assetsDir)) {
        reports.push({ dir, errors: [], notes: ['структура: ok', `атлас: пропущен (нет ${assetsDir})`] });
        continue;
      }
      const atlas = checkAtlas(r.value.catalog, r.value.config.people, assetsDir);
      reports.push({ dir, errors: atlas, notes: ['структура: ok', atlas.length ? 'атлас: ошибки' : 'атлас: ok'] });
```
В `index.ts`: `export * from './atlas.ts';`

```bash
pnpm vitest run tools/validate-maps   # PASS
pnpm validate:maps                    # demo и local: структура ok, атлас ok (ассеты в ~/tmp есть)
```

- [ ] **Step 10: гейт и коммит**

```bash
pnpm gate
git add catalog offices tools/validate-maps .gitignore
git status --short    # offices/local/config.yaml отсутствует или игнорируется; PNG нет
git commit -m "feat(offices): офисы local и demo, проверка атласа каталога"
```

**Критерий готовности:** `pnpm validate:maps` печатает «структура: ok» и «атлас: ok» для `demo` и `local`. Тесты атласа зелёные.

---

## Этап M2. Сервер

### Задача 17: server — каркас, загрузка офиса, часы, логгер, Status Store

**Files:**
- Create: `packages/server/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts}`
- Create: `packages/server/src/{clock.ts,logger.ts,office.ts,store.ts,index.ts}`
- Create: `packages/server/tests/helpers.ts`, `packages/server/tests/store.test.ts`, `packages/server/tests/office.test.ts`

**Interfaces:**
- Consumes: `loadOfficeBundle`, `formatErrors`, `OfficeBundle` (core); `readOfficeTexts`, `resolveFrom`, `OfficeFiles` (validate-maps); `Status` (protocol).
- Produces:
  - `clock.ts`: `type Clock = { now(): number }`, `systemClock`, `class ManualClock { constructor(start = Date.parse('2026-01-05T09:00:00Z')); now(); advance(ms); set(ms) }`.
  - `logger.ts`: `type Logger = { info(m: string): void; warn(m: string): void; error(m: string): void }`, `consoleLogger`, `silentLogger`, `memoryLogger(): Logger & { lines: { level: 'info' | 'warn' | 'error'; msg: string }[] }`.
  - `office.ts`: `type LoadedOffice = { dir: string; bundle: OfficeBundle; files: OfficeFiles; assetsDir: string; dataDir: string }`, `class OfficeLoadError extends Error { details: string }`, `loadOffice(dir): LoadedOffice` (без `config.yaml` → `OfficeLoadError` «выполните init»: запасной `config.example.yaml` только для `validate:maps`).
  - `store.ts`: `type StoredStatus = { status; meetingId?; at: number; receivedAt: number; ttlSec?: number; source: string }`, `type StoreChange = { entityId; status; meetingId? }`, `type StoreJSON = { statuses: Record<string, StoredStatus>; owners: Record<string, string> }`, `class StatusStore { get(id); entries(): [string, StoredStatus][]; ownerSource(id); claim(id, source): boolean; applyStatus(id, source, s: { status; meetingId?; at; ttlSec? }, receivedAt): 'accepted' | 'stale'; applySnapshot(source, entries, at, ttlFor: (s: Status) => number | undefined, receivedAt): StoreChange[]; expire(now): StoreChange[]; remove(id); toJSON(): StoreJSON; restore(j: StoreJSON) }`.
  - `tests/helpers.ts`: `DEMO_DIR`, `demoOffice()`, `makeRuntime()` (появится в задаче 18), `iso(clock, deltaMs?)`.

Семантика Status Store (спека 4.3):
1. `at` раньше сохранённого → `stale`. Равный `at` → побеждает последний.
2. ttl отсчитывается от `receivedAt`. Повтор того же статуса продлевает его (heartbeat). У `offline` ttl нет.
3. `snapshot` — полный список источника. Всё, что источник присылал раньше и чего нет в снимке, становится `offline`.
4. Сущность закрепляется за первым источником (`claim`).

- [ ] **Step 1: пакет**

`packages/server/package.json`:
```json
{
  "name": "@pixeloffice/server",
  "private": true,
  "type": "module",
  "exports": { ".": "./src/index.ts" },
  "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json" },
  "dependencies": {
    "@pixeloffice/core": "workspace:*",
    "@pixeloffice/protocol": "workspace:*",
    "@pixeloffice/validate-maps": "workspace:*"
  }
}
```
`tsconfig.json`: `{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024"], "types": ["node"] }, "include": ["src"] }`; `tsconfig.test.json` — плюс `"tests"`; `vitest.config.ts`: `defineProject({ test: { name: 'server', include: ['tests/**/*.test.ts'] } })`.

```bash
pnpm --filter @pixeloffice/server add fastify@latest @fastify/websocket@latest @fastify/static@latest yaml@latest
pnpm install
```

- [ ] **Step 2: падающие тесты `packages/server/tests/store.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { StatusStore } from '../src/index.ts';

const T0 = Date.parse('2026-01-05T09:00:00Z');

describe('StatusStore', () => {
  it('порядок по at: старое отбрасывается, равное — побеждает последнее', () => {
    const s = new StatusStore();
    expect(s.applyStatus('p1', 'nc', { status: 'online', at: T0 + 10 }, T0)).toBe('accepted');
    expect(s.applyStatus('p1', 'nc', { status: 'offline', at: T0 + 5 }, T0)).toBe('stale');
    expect(s.get('p1')?.status).toBe('online');
    expect(s.applyStatus('p1', 'nc', { status: 'meeting', meetingId: 'r', at: T0 + 10 }, T0)).toBe('accepted');
    expect(s.get('p1')).toMatchObject({ status: 'meeting', meetingId: 'r' });
  });

  it('ttl от времени приёма, а не от at', () => {
    const s = new StatusStore();
    s.applyStatus('p1', 'nc', { status: 'online', at: T0 - 3_600_000, ttlSec: 60 }, T0);
    expect(s.expire(T0 + 59_999)).toEqual([]);
    expect(s.expire(T0 + 60_000)).toEqual([{ entityId: 'p1', status: 'offline' }]);
    expect(s.get('p1')?.ttlSec).toBeUndefined();
  });

  it('повтор того же статуса продлевает ttl (heartbeat)', () => {
    const s = new StatusStore();
    s.applyStatus('a', 'hook', { status: 'working', at: T0, ttlSec: 60 }, T0);
    s.applyStatus('a', 'hook', { status: 'working', at: T0 + 50_000, ttlSec: 60 }, T0 + 50_000);
    expect(s.expire(T0 + 61_000)).toEqual([]);
    expect(s.expire(T0 + 110_000)).toHaveLength(1);
  });

  it('у offline нет ttl', () => {
    const s = new StatusStore();
    s.applyStatus('p1', 'nc', { status: 'offline', at: T0, ttlSec: 60 }, T0);
    expect(s.get('p1')?.ttlSec).toBeUndefined();
  });

  it('snapshot: пропавшие из снимка сущности источника → offline', () => {
    const s = new StatusStore();
    const ttl = () => 120;
    expect(s.applySnapshot('nc', [{ entityId: 'p1', status: 'online' }, { entityId: 'p2', status: 'online' }], T0, ttl, T0)).toHaveLength(2);
    const ch = s.applySnapshot('nc', [{ entityId: 'p1', status: 'meeting', meetingId: 'm' }], T0 + 30_000, ttl, T0 + 30_000);
    expect(ch).toEqual([
      { entityId: 'p1', status: 'meeting', meetingId: 'm' },
      { entityId: 'p2', status: 'offline' },
    ]);
  });

  it('snapshot не перетирает более новый статус', () => {
    const s = new StatusStore();
    s.applyStatus('p1', 'nc', { status: 'meeting', meetingId: 'm', at: T0 + 100 }, T0);
    expect(s.applySnapshot('nc', [{ entityId: 'p1', status: 'online' }], T0, () => undefined, T0)).toEqual([]);
  });

  it('claim: сущность закрепляется за первым источником', () => {
    const s = new StatusStore();
    expect(s.claim('p1', 'nc')).toBe(true);
    expect(s.claim('p1', 'nc')).toBe(true);
    expect(s.claim('p1', 'other')).toBe(false);
    expect(s.ownerSource('p1')).toBe('nc');
  });

  it('toJSON/restore и remove', () => {
    const s = new StatusStore();
    s.claim('p1', 'nc');
    s.applyStatus('p1', 'nc', { status: 'online', at: T0, ttlSec: 60 }, T0);
    const s2 = new StatusStore();
    s2.restore(JSON.parse(JSON.stringify(s.toJSON())));
    expect(s2.get('p1')).toEqual(s.get('p1'));
    expect(s2.ownerSource('p1')).toBe('nc');
    s2.remove('p1');
    expect([s2.get('p1'), s2.ownerSource('p1')]).toEqual([undefined, undefined]);
  });
});
```

- [ ] **Step 3: падающие тесты загрузки офиса `packages/server/tests/office.test.ts` и хелперы**

`packages/server/tests/helpers.ts`:
```ts
import { fileURLToPath } from 'node:url';
import { loadOffice, type ManualClock } from '../src/index.ts';

export const DEMO_DIR = fileURLToPath(new URL('../../../offices/demo/', import.meta.url));
export const demoOffice = () => loadOffice(DEMO_DIR);
export const iso = (clock: ManualClock, deltaMs = 0) => new Date(clock.now() + deltaMs).toISOString();
```

`packages/server/tests/office.test.ts`:
```ts
import { cpSync, mkdtempSync, renameSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { OfficeLoadError, loadOffice } from '../src/index.ts';
import { DEMO_DIR, demoOffice } from './helpers.ts';

describe('loadOffice', () => {
  it('загружает demo и раскрывает пути', () => {
    const o = demoOffice();
    expect(o.bundle.config.officeId).toBe('demo');
    expect(o.assetsDir.startsWith('/')).toBe(true);
    expect(o.assetsDir).not.toContain('~');
    expect(o.dataDir.endsWith('/.data/demo')).toBe(true);
  });

  it('невалидная карта → OfficeLoadError со списком ошибок и координатами', () => {
    const root = mkdtempSync(join(tmpdir(), 'po-office-'));
    const dir = join(root, 'offices', 'bad');
    cpSync(DEMO_DIR, dir, { recursive: true });
    cpSync(join(DEMO_DIR, '../../catalog'), join(root, 'catalog'), { recursive: true });
    writeFileSync(join(dir, 'office.yaml'), 'floor: { default: carpet_grey }\nlegend: { "#": wall, E: entrance }\ngrid: "###\\n#E##\\n"\n');
    try {
      loadOffice(dir);
      expect.unreachable();
    } catch (e) {
      expect(e).toBeInstanceOf(OfficeLoadError);
      expect((e as OfficeLoadError).details).toContain('grid_ragged');
    }
  });

  it('без config.yaml (только config.example.yaml) → OfficeLoadError «выполните init»', () => {
    const root = mkdtempSync(join(tmpdir(), 'po-office-'));
    const dir = join(root, 'offices', 'noinit');
    cpSync(DEMO_DIR, dir, { recursive: true });
    cpSync(join(DEMO_DIR, '../../catalog'), join(root, 'catalog'), { recursive: true });
    renameSync(join(dir, 'config.yaml'), join(dir, 'config.example.yaml'));
    expect(() => loadOffice(dir)).toThrow(OfficeLoadError);
    expect(() => loadOffice(dir)).toThrow(/init/);
  });
});
```

Run: `pnpm vitest run packages/server` → FAIL.

- [ ] **Step 4: `clock.ts`, `logger.ts`**

`packages/server/src/clock.ts`:
```ts
export type Clock = { now(): number };

export const systemClock: Clock = { now: () => Date.now() };

// Управляемые часы для тестов и тестового режима (спека 4.6).
export class ManualClock implements Clock {
  private t: number;
  constructor(start = Date.parse('2026-01-05T09:00:00Z')) {
    this.t = start;
  }
  now(): number {
    return this.t;
  }
  advance(ms: number): void {
    this.t += ms;
  }
  set(ms: number): void {
    this.t = ms;
  }
}
```

`packages/server/src/logger.ts`:
```ts
export type Logger = { info(msg: string): void; warn(msg: string): void; error(msg: string): void };

export const consoleLogger: Logger = {
  info: (m) => console.log(m),
  warn: (m) => console.warn(`warn: ${m}`),
  error: (m) => console.error(`error: ${m}`),
};

export const silentLogger: Logger = { info() {}, warn() {}, error() {} };

export function memoryLogger(): Logger & { lines: { level: 'info' | 'warn' | 'error'; msg: string }[] } {
  const lines: { level: 'info' | 'warn' | 'error'; msg: string }[] = [];
  return {
    lines,
    info: (msg) => lines.push({ level: 'info', msg }),
    warn: (msg) => lines.push({ level: 'warn', msg }),
    error: (msg) => lines.push({ level: 'error', msg }),
  };
}
```

- [ ] **Step 5: `office.ts`**

```ts
import { basename } from 'node:path';
import { formatErrors, loadOfficeBundle, type OfficeBundle } from '@pixeloffice/core';
import { readOfficeTexts, resolveFrom, type OfficeFiles } from '@pixeloffice/validate-maps';

export type LoadedOffice = { dir: string; bundle: OfficeBundle; files: OfficeFiles; assetsDir: string; dataDir: string };

export class OfficeLoadError extends Error {
  details: string;
  constructor(dir: string, details: string) {
    super(`офис ${dir} не загружен:\n${details}`);
    this.details = details;
  }
}

// Невалидная карта/каталог → сервер не стартует, все ошибки с координатами (спека 5.5, 10).
export function loadOffice(dir: string): LoadedOffice {
  const { files, texts } = readOfficeTexts(dir);
  // config.example.yaml — запасной только для validate:maps: его токены CHANGE_ME_* лежат в git, сервер с ними не стартует.
  if (basename(files.configPath) !== 'config.yaml') {
    throw new OfficeLoadError(files.dir, `нет config.yaml — выполните: node packages/server/src/main.ts init ${dir}`);
  }
  const r = loadOfficeBundle(texts);
  if (!r.ok) throw new OfficeLoadError(files.dir, formatErrors(r.errors));
  return {
    dir: files.dir,
    bundle: r.value,
    files,
    assetsDir: resolveFrom(files.dir, r.value.config.assetsDir),
    dataDir: resolveFrom(files.dir, r.value.config.dataDir),
  };
}
```

- [ ] **Step 6: `store.ts`**

```ts
import type { Status } from '@pixeloffice/protocol';

export type StoredStatus = { status: Status; meetingId?: string; at: number; receivedAt: number; ttlSec?: number; source: string };
export type StoreChange = { entityId: string; status: Status; meetingId?: string };
export type StoreJSON = { statuses: Record<string, StoredStatus>; owners: Record<string, string> };
type Incoming = { status: Status; meetingId?: string; at: number; ttlSec?: number };

// Статусы сущностей: порядок по at, ttl от приёма, снимки источников (спека 4.3).
export class StatusStore {
  private readonly statuses = new Map<string, StoredStatus>();
  private readonly owners = new Map<string, string>();

  get(id: string): StoredStatus | undefined {
    return this.statuses.get(id);
  }

  entries(): [string, StoredStatus][] {
    return [...this.statuses];
  }

  ownerSource(id: string): string | undefined {
    return this.owners.get(id);
  }

  claim(id: string, source: string): boolean {
    const owner = this.owners.get(id);
    if (owner !== undefined && owner !== source) return false;
    this.owners.set(id, source);
    return true;
  }

  applyStatus(id: string, source: string, s: Incoming, receivedAt: number): 'accepted' | 'stale' {
    const cur = this.statuses.get(id);
    if (cur && s.at < cur.at) return 'stale';
    const next: StoredStatus = { status: s.status, at: s.at, receivedAt, source };
    if (s.meetingId !== undefined) next.meetingId = s.meetingId;
    if (s.status !== 'offline' && s.ttlSec !== undefined) next.ttlSec = s.ttlSec;
    this.statuses.set(id, next);
    return 'accepted';
  }

  applySnapshot(
    source: string,
    entries: { entityId: string; status: Status; meetingId?: string }[],
    at: number,
    ttlFor: (s: Status) => number | undefined,
    receivedAt: number,
  ): StoreChange[] {
    const changes: StoreChange[] = [];
    const seen = new Set<string>();
    for (const e of entries) {
      seen.add(e.entityId);
      const r = this.applyStatus(e.entityId, source, { status: e.status, meetingId: e.meetingId, at, ttlSec: ttlFor(e.status) }, receivedAt);
      if (r === 'accepted') changes.push(e.meetingId !== undefined ? { entityId: e.entityId, status: e.status, meetingId: e.meetingId } : { entityId: e.entityId, status: e.status });
    }
    for (const [id, s] of [...this.statuses]) {
      if (s.source !== source || seen.has(id) || s.status === 'offline') continue;
      if (this.applyStatus(id, source, { status: 'offline', at }, receivedAt) === 'accepted') changes.push({ entityId: id, status: 'offline' });
    }
    return changes;
  }

  expire(now: number): StoreChange[] {
    const changes: StoreChange[] = [];
    for (const [id, s] of this.statuses) {
      if (s.ttlSec === undefined || s.status === 'offline') continue;
      if (s.receivedAt + s.ttlSec * 1000 <= now) {
        this.statuses.set(id, { status: 'offline', at: s.at, receivedAt: s.receivedAt, source: s.source });
        changes.push({ entityId: id, status: 'offline' });
      }
    }
    return changes;
  }

  remove(id: string): void {
    this.statuses.delete(id);
    this.owners.delete(id);
  }

  toJSON(): StoreJSON {
    return { statuses: Object.fromEntries(this.statuses), owners: Object.fromEntries(this.owners) };
  }

  restore(j: StoreJSON): void {
    this.statuses.clear();
    this.owners.clear();
    for (const [id, s] of Object.entries(j.statuses)) this.statuses.set(id, s);
    for (const [id, o] of Object.entries(j.owners)) this.owners.set(id, o);
  }
}
```

`packages/server/src/index.ts`:
```ts
export * from './clock.ts';
export * from './logger.ts';
export * from './office.ts';
export * from './store.ts';
```

- [ ] **Step 7: прогон, гейт, коммит**

```bash
pnpm vitest run packages/server   # PASS
pnpm gate
git add packages/server pnpm-lock.yaml
git commit -m "feat(server): загрузка офиса и хранилище статусов с ttl и порядком по at"
```

**Критерий готовности:** тесты Status Store и загрузки офиса зелёные. Невалидный офис даёт ошибку со списком кодов. Офис без `config.yaml` сервер не загружает (токены `CHANGE_ME_*` из примера публичны).

---

### Задача 18: server — сущности, OfficeRuntime, `POST /v1/events`

**Files:**
- Create: `packages/server/src/{registry.ts,runtime.ts,http.ts}`
- Modify: `packages/server/src/index.ts`, `packages/server/tests/helpers.ts`
- Test: `packages/server/tests/registry.test.ts`, `packages/server/tests/ingest.test.ts`

**Interfaces:**
- Consumes: `StatusStore`, `Clock`, `Logger`, `LoadedOffice` (задача 17); `World`, `SimEntity`, `avatarFromKey`, `avatarLayerPaths`, `characterLayout`, `defaultAssetUrl`, `SourceConfig`, `Person`, `Rules`, `CharactersDef` (core); `EventsBodySchema`, `formatIssues`, `Event`, `AgentRef`, `Entity`, `EntityView`, `HelloMessage`, `DebugMessage`, `ServerMessage`, `Issue`, `isHumanStatus`, `isAgentStatus`, `PROTOCOL_VERSION` (protocol).
- Produces:
  - `registry.ts`: `type AgentEntity = Entity & { kind: 'agent'; ownerId: string; project: string; slot: string; projectDir?: string; lastEventAt: number }`, `agentKey(owner, ref): string` = `agent:<owner>:<project>:<slot>`, `class EntityRegistry { constructor(people: Person[], characters: CharactersDef); get(id): Entity | undefined; isHuman(id): boolean; podOf(id): string | undefined; all(): Entity[]; agentList(): AgentEntity[]; ensureAgent(owner, ref, now): { entity: AgentEntity; created: boolean }; removeExpiredAgents(isOffline: (id) => boolean, now, retentionDays): string[]; toJSON(): AgentEntity[]; restore(list: AgentEntity[]): void }`.
  - `runtime.ts`: `type LogEntry = { receivedAt: number; source: string; event: Event }`, `type IngestResult = { status: 200; body: { accepted: number; ignored: number } } | { status: 400 | 401 | 403; body: { error: string; issues?: Issue[] } }`, `type RuntimeOptions = { office: LoadedOffice; clock: Clock; log?: Logger; eventLog?: { append(e: LogEntry): void }; relay?: { offer(ev: Event): void } }`, `class OfficeRuntime { readonly world; readonly store; readonly registry; readonly office; sourceByName(name): SourceConfig | undefined; ingestHttp(auth, body): IngestResult; ingestFromSource(source, events, opts?: { log?: boolean; relay?: boolean; receivedAt?: number }): IngestResult; step(dtMs = 50): void; drain(): ServerMessage[]; hello(test = false): HelloMessage; debug(): DebugMessage; setRules(r: Rules): void; entityView(e): EntityView }`.
  - `http.ts`: `type ServerOptions = { runtime: OfficeRuntime; viewerTokens?: string[]; assetsDir?: string | null; viewerDist?: string | null; testMode?: ((q: Record<string, string | undefined>) => HelloMessage) | null; ingest?: boolean; logger?: boolean }`, `buildServer(o): Promise<{ app: FastifyInstance; broadcast(msgs: ServerMessage[]): void }>`. Здесь — только `/healthz` и `POST /v1/events`. Задача 20 дописывает остальное, сигнатура не меняется.
  - `tests/helpers.ts`: `makeRuntime(): { rt; clock: ManualClock; log; office }`, `advance(rt, clock, ms)`.

Авторизация (спека 4.3, решение 19): нет/неверный токен → 401. Агентское событие под токеном без `owner` → 403 `agent_event_requires_owner_token`. Событие человека (`entityId`, `snapshot`) под агентским токеном → 403 `agent_source_cannot_address_humans`. Сущность закреплена за другим источником → 403 `foreign_source`. Неизвестный человек → игнор + warn. Агент с человеческим статусом (и наоборот) → игнор + warn.

- [ ] **Step 1: хелперы (дописать в `packages/server/tests/helpers.ts`)**

```ts
import { ManualClock, OfficeRuntime, memoryLogger } from '../src/index.ts';

export function makeRuntime() {
  const clock = new ManualClock();
  const log = memoryLogger();
  const office = demoOffice();
  const rt = new OfficeRuntime({ office, clock, log });
  return { rt, clock, log, office };
}

// Шаги симуляции по 50 мс вместе с часами (как в настоящем цикле).
export function advance(rt: OfficeRuntime, clock: ManualClock, ms: number) {
  for (let t = 0; t < ms; t += 50) {
    clock.advance(50);
    rt.step(50);
  }
}
```
(`ManualClock` убрать из `import type` в начале файла: теперь он нужен как значение.)

- [ ] **Step 2: падающие тесты `packages/server/tests/registry.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { EntityRegistry, agentKey } from '../src/index.ts';
import { demoOffice } from './helpers.ts';

const office = demoOffice();
const reg = () => new EntityRegistry(office.bundle.config.people, office.bundle.catalog.characters);
const T0 = Date.parse('2026-01-05T09:00:00Z');

describe('EntityRegistry', () => {
  it('люди из конфига с углами', () => {
    const r = reg();
    expect(r.all()).toHaveLength(9);
    expect(r.isHuman('p1')).toBe(true);
    expect(r.podOf('p8')).toBe('pod:p8');
  });

  it('агент: ключ из хозяина, проекта и панели; имя «хозяин · проект»; аватар по хешу', () => {
    const r = reg();
    const { entity, created } = r.ensureAgent('p1', { project: 'PixelOffice', projectDir: '/x/PixelOffice', slot: '%17' }, T0);
    expect(created).toBe(true);
    expect(entity.id).toBe(agentKey('p1', { project: 'PixelOffice', slot: '%17' }));
    expect(entity.id).toBe('agent:p1:PixelOffice:%17');
    expect(entity.name).toBe('Анна · PixelOffice');
    expect(r.ensureAgent('p1', { project: 'PixelOffice', slot: '%17' }, T0 + 1).created).toBe(false);
    expect(reg().ensureAgent('p1', { project: 'PixelOffice', slot: '%17' }, T0).entity.avatar).toEqual(entity.avatar);
  });

  it('удаление по сроку хранения: только офлайн и старше срока', () => {
    const r = reg();
    r.ensureAgent('p1', { project: 'a', slot: '%1' }, T0);
    r.ensureAgent('p1', { project: 'b', slot: '%2' }, T0 + 6 * 86_400_000);
    const removed = r.removeExpiredAgents(() => true, T0 + 7 * 86_400_000 + 1, 7);
    expect(removed).toEqual(['agent:p1:a:%1']);
    expect(r.removeExpiredAgents(() => false, T0 + 100 * 86_400_000, 7)).toEqual([]);
  });
});
```

- [ ] **Step 3: падающие тесты `packages/server/tests/ingest.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { ManualClock, OfficeRuntime, buildServer, silentLogger } from '../src/index.ts';
import { advance, demoOffice, iso, makeRuntime } from './helpers.ts';

const NC = 'Bearer demo-nextcloud-token';
const HOOK = 'Bearer demo-hook-token';
const agentRef = { project: 'PixelOffice', projectDir: '/Users/x/PixelOffice', slot: '%17' };

describe('POST /v1/events', () => {
  it('401 без токена и с чужим токеном', async () => {
    const { rt, clock } = makeRuntime();
    const { app } = await buildServer({ runtime: rt });
    const body = { events: [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }] };
    expect((await app.inject({ method: 'POST', url: '/v1/events', payload: body })).statusCode).toBe(401);
    expect((await app.inject({ method: 'POST', url: '/v1/events', payload: body, headers: { authorization: 'Bearer nope' } })).statusCode).toBe(401);
  });

  it('400 с путём поля для entityId агента', async () => {
    const { rt, clock } = makeRuntime();
    const { app } = await buildServer({ runtime: rt });
    const res = await app.inject({
      method: 'POST',
      url: '/v1/events',
      headers: { authorization: HOOK },
      payload: { events: [{ type: 'status', entityId: 'agent:p1:x:%1', status: 'working', at: iso(clock) }] },
    });
    expect(res.statusCode).toBe(400);
    expect(res.json().issues.map((i: { path: string }) => i.path)).toContain('events.0.entityId');
  });

  it('403: агентское событие под токеном без хозяина и человек под агентским токеном', () => {
    const { rt, clock } = makeRuntime();
    const nc = rt.sourceByName('nextcloud')!;
    const hook = rt.sourceByName('claude-hook')!;
    expect(rt.ingestFromSource(nc, [{ type: 'status', agent: agentRef, status: 'working', at: iso(clock) }])).toMatchObject({
      status: 403,
      body: { error: 'agent_event_requires_owner_token' },
    });
    expect(rt.ingestFromSource(hook, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }])).toMatchObject({
      status: 403,
      body: { error: 'agent_source_cannot_address_humans' },
    });
  });

  it('403: сущность закреплена за другим источником', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(rt.sourceByName('nextcloud')!, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }]);
    const other = { source: 'calendar', token: 'calendar-token' };
    expect(rt.ingestFromSource(other, [{ type: 'status', entityId: 'p1', status: 'meeting', meetingId: 'm', at: iso(clock) }]).status).toBe(403);
  });

  it('200: статус человека → после dwell дельта с персонажем', async () => {
    const { rt, clock } = makeRuntime();
    const { app } = await buildServer({ runtime: rt });
    const res = await app.inject({
      method: 'POST',
      url: '/v1/events',
      headers: { authorization: NC },
      payload: { events: [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }] },
    });
    expect(res.json()).toEqual({ accepted: 1, ignored: 0 });
    advance(rt, clock, 2100);
    const delta = rt.drain().find((m) => m.type === 'delta');
    expect(delta && delta.type === 'delta' && delta.characters.map((c) => c.id)).toEqual(['p1']);
  });

  it('агент регистрируется первым событием: сообщение entity раньше дельты, без projectDir', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: agentRef, status: 'working', at: iso(clock) }]);
    advance(rt, clock, 2100);
    const msgs = rt.drain();
    expect(msgs[0]).toMatchObject({ type: 'entity', entity: { id: 'agent:p1:PixelOffice:%17', name: 'Анна · PixelOffice', kind: 'agent', ownerId: 'p1' } });
    expect(JSON.stringify(msgs)).not.toContain('/Users/x');
    expect(msgs.findIndex((m) => m.type === 'delta')).toBeGreaterThan(0);
  });

  it('порядок по at: старое событие — ignored', () => {
    const { rt, clock } = makeRuntime();
    const nc = rt.sourceByName('nextcloud')!;
    rt.ingestFromSource(nc, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock, 1000) }]);
    expect(rt.ingestFromSource(nc, [{ type: 'status', entityId: 'p1', status: 'offline', at: iso(clock) }]).body).toEqual({ accepted: 0, ignored: 1 });
    expect(rt.store.get('p1')?.status).toBe('online');
  });

  it('ttl от приёма: статус с at в прошлом живёт ttlSec от приёма', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(rt.sourceByName('nextcloud')!, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock, -3_600_000), ttlSec: 60 }]);
    advance(rt, clock, 59_000);
    expect(rt.store.get('p1')?.status).toBe('online');
    advance(rt, clock, 1500);
    expect(rt.store.get('p1')?.status).toBe('offline');
  });

  it('snapshot: пропавший из снимка — offline', () => {
    const { rt, clock } = makeRuntime();
    const nc = rt.sourceByName('nextcloud')!;
    rt.ingestFromSource(nc, [{ type: 'snapshot', at: iso(clock), entities: [{ entityId: 'p1', status: 'online' }, { entityId: 'p2', status: 'online' }] }]);
    rt.ingestFromSource(nc, [{ type: 'snapshot', at: iso(clock, 30_000), entities: [{ entityId: 'p1', status: 'online' }] }]);
    expect(rt.store.get('p2')?.status).toBe('offline');
  });

  it('неизвестный человек и агент с человеческим статусом — ignored с warn', () => {
    const { rt, clock, log } = makeRuntime();
    expect(rt.ingestFromSource(rt.sourceByName('nextcloud')!, [{ type: 'status', entityId: 'ghost', status: 'online', at: iso(clock) }]).body).toEqual({ accepted: 0, ignored: 1 });
    expect(rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: agentRef, status: 'online', at: iso(clock) }]).body).toEqual({ accepted: 0, ignored: 1 });
    expect(log.lines.filter((l) => l.level === 'warn').length).toBeGreaterThanOrEqual(2);
    expect(rt.drain().filter((m) => m.type === 'entity')).toEqual([]); // фантомного агента нет
  });

  it('в журнал событий пишутся только принятые события (спека 4.7)', () => {
    const logged: unknown[] = [];
    const clock = new ManualClock();
    const rt = new OfficeRuntime({ office: demoOffice(), clock, log: silentLogger, eventLog: { append: (e) => logged.push(e) } });
    rt.ingestFromSource(rt.sourceByName('nextcloud')!, [
      { type: 'status', entityId: 'p1', status: 'online', at: iso(clock) },
      { type: 'status', entityId: 'ghost', status: 'online', at: iso(clock) },
    ]);
    expect(logged).toHaveLength(1);
  });

  it('облачко агента доходит до симуляции', () => {
    const { rt, clock } = makeRuntime();
    const hook = rt.sourceByName('claude-hook')!;
    rt.ingestFromSource(hook, [
      { type: 'status', agent: agentRef, status: 'needs_input', at: iso(clock) },
      { type: 'bubble', agent: agentRef, text: 'Разрешить?', ttlSec: 600, at: iso(clock) },
    ]);
    advance(rt, clock, 100);
    const delta = rt.drain().find((m) => m.type === 'delta');
    expect(delta && delta.type === 'delta' && delta.characters[0]!.bubble).toEqual({ text: 'Разрешить?', kind: 'needs_input' });
  });
});
```

Run: `pnpm vitest run packages/server` → FAIL.

- [ ] **Step 4: `packages/server/src/registry.ts`**

```ts
import { avatarFromKey, type CharactersDef, type Person } from '@pixeloffice/core';
import type { AgentRef, Entity } from '@pixeloffice/protocol';

export type AgentEntity = Entity & { kind: 'agent'; ownerId: string; project: string; slot: string; projectDir?: string; lastEventAt: number };

// Стабильный ключ агента строит сервер (спека 4.1).
export const agentKey = (owner: string, ref: { project: string; slot: string }) => `agent:${owner}:${ref.project}:${ref.slot}`;

const DAY = 86_400_000;

export class EntityRegistry {
  private readonly characters: CharactersDef;
  private readonly humans = new Map<string, Entity & { pod: string }>();
  private readonly agents = new Map<string, AgentEntity>();

  constructor(people: Person[], characters: CharactersDef) {
    this.characters = characters;
    for (const p of people) this.humans.set(p.id, { id: p.id, kind: 'human', name: p.name, avatar: p.avatar, pod: p.pod });
  }

  get(id: string): Entity | undefined {
    return this.humans.get(id) ?? this.agents.get(id);
  }
  isHuman(id: string): boolean {
    return this.humans.has(id);
  }
  podOf(id: string): string | undefined {
    return this.humans.get(id)?.pod;
  }
  all(): Entity[] {
    return [...this.humans.values(), ...this.agents.values()];
  }
  agentList(): AgentEntity[] {
    return [...this.agents.values()];
  }

  ensureAgent(owner: string, ref: AgentRef, now: number): { entity: AgentEntity; created: boolean } {
    const id = agentKey(owner, ref);
    const cur = this.agents.get(id);
    if (cur) {
      cur.lastEventAt = now;
      if (ref.projectDir) cur.projectDir = ref.projectDir;
      return { entity: cur, created: false };
    }
    const entity: AgentEntity = {
      id,
      kind: 'agent',
      name: `${this.humans.get(owner)?.name ?? owner} · ${ref.project}`,
      ownerId: owner,
      project: ref.project,
      slot: ref.slot,
      avatar: avatarFromKey(id, this.characters.pool),
      lastEventAt: now,
    };
    if (ref.projectDir) entity.projectDir = ref.projectDir;
    this.agents.set(id, entity);
    return { entity, created: true };
  }

  // Агент в offline без событий дольше срока удаляется (спека 4.1).
  removeExpiredAgents(isOffline: (id: string) => boolean, now: number, retentionDays: number): string[] {
    const removed: string[] = [];
    for (const [id, a] of this.agents) {
      if (isOffline(id) && now - a.lastEventAt > retentionDays * DAY) {
        this.agents.delete(id);
        removed.push(id);
      }
    }
    return removed;
  }

  toJSON(): AgentEntity[] {
    return this.agentList();
  }

  restore(list: AgentEntity[]): void {
    this.agents.clear();
    for (const a of list) this.agents.set(a.id, a);
  }
}
```

- [ ] **Step 5: `packages/server/src/runtime.ts`**

```ts
import {
  World,
  avatarLayerPaths,
  characterLayout,
  defaultAssetUrl,
  type Rules,
  type SimEntity,
  type SourceConfig,
} from '@pixeloffice/core';
import {
  EventsBodySchema,
  PROTOCOL_VERSION,
  formatIssues,
  isAgentStatus,
  isHumanStatus,
  type DebugMessage,
  type Entity,
  type EntityView,
  type Event,
  type HelloMessage,
  type Issue,
  type ServerMessage,
  type Status,
} from '@pixeloffice/protocol';
import type { Clock } from './clock.ts';
import { consoleLogger, type Logger } from './logger.ts';
import type { LoadedOffice } from './office.ts';
import { EntityRegistry, agentKey } from './registry.ts';
import { StatusStore } from './store.ts';

export type LogEntry = { receivedAt: number; source: string; event: Event };
export type IngestResult =
  | { status: 200; body: { accepted: number; ignored: number } }
  | { status: 400 | 401 | 403; body: { error: string; issues?: Issue[] } };
export type RuntimeOptions = {
  office: LoadedOffice;
  clock: Clock;
  log?: Logger;
  eventLog?: { append(e: LogEntry): void };
  relay?: { offer(ev: Event): void };
};
type IngestOpts = { log?: boolean; relay?: boolean; receivedAt?: number };

const ttlFor = (source: SourceConfig, status: Status, evTtl?: number): number | undefined => {
  if (status === 'offline') return undefined;
  if (evTtl !== undefined) return evTtl;
  return typeof source.ttlSec === 'number' ? source.ttlSec : source.ttlSec?.[status];
};

// Связка Ingest → Status Store → World Sim одного офиса.
export class OfficeRuntime {
  readonly office: LoadedOffice;
  readonly store = new StatusStore();
  readonly registry: EntityRegistry;
  readonly world: World;
  private readonly clock: Clock;
  private readonly log: Logger;
  private readonly eventLog: RuntimeOptions['eventLog'];
  private readonly relay: RuntimeOptions['relay'];
  private readonly byToken = new Map<string, SourceConfig>();
  private readonly byName = new Map<string, SourceConfig>();
  private pending: ServerMessage[] = [];
  private lastRetentionCheck: number;

  constructor(o: RuntimeOptions) {
    this.office = o.office;
    this.clock = o.clock;
    this.log = o.log ?? consoleLogger;
    this.eventLog = o.eventLog;
    this.relay = o.relay;
    const { config, catalog, map, rules } = o.office.bundle;
    for (const s of config.sources) {
      this.byToken.set(s.token, s);
      this.byName.set(s.source, s);
    }
    this.registry = new EntityRegistry(config.people, catalog.characters);
    this.world = new World({ map, rules, poses: catalog.characters.poses, onWarn: (m) => this.log.warn(m) });
    for (const e of this.registry.all()) this.world.upsertEntity(this.simEntity(e));
    this.lastRetentionCheck = this.clock.now();
  }

  sourceByName(name: string): SourceConfig | undefined {
    return this.byName.get(name);
  }

  ingestHttp(auth: string | undefined, body: unknown): IngestResult {
    const token = /^Bearer (.+)$/.exec(auth ?? '')?.[1];
    const source = token ? this.byToken.get(token) : undefined;
    if (!source) return { status: 401, body: { error: 'unauthorized' } };
    const parsed = EventsBodySchema.safeParse(body);
    if (!parsed.success) return { status: 400, body: { error: 'invalid', issues: formatIssues(parsed.error) } };
    return this.ingestFromSource(source, parsed.data.events);
  }

  // Пакет проходит авторизацию целиком, затем применяется (решение 20).
  ingestFromSource(source: SourceConfig, events: Event[], opts: IngestOpts = {}): IngestResult {
    const receivedAt = opts.receivedAt ?? this.clock.now();
    for (const [i, ev] of events.entries()) {
      const denied = this.authorize(source, ev);
      if (denied) return { status: 403, body: { error: denied, issues: [{ path: `events.${i}`, message: denied }] } };
    }
    let accepted = 0;
    let ignored = 0;
    for (const ev of events) {
      if (!this.apply(source, ev, receivedAt)) {
        ignored++;
        continue;
      }
      accepted++;
      // В JSONL-лог и ретрансляцию — только принятые события (спека 4.7).
      if (opts.log !== false) this.eventLog?.append({ receivedAt, source: source.source, event: ev });
      if (opts.relay !== false) this.relay?.offer(ev);
    }
    return { status: 200, body: { accepted, ignored } };
  }

  step(dtMs = 50): void {
    this.world.tick(dtMs);
    const now = this.clock.now();
    for (const ch of this.store.expire(now)) this.world.setStatus(ch.entityId, ch.status, ch.meetingId);
    if (now - this.lastRetentionCheck >= 60_000) {
      this.lastRetentionCheck = now;
      this.removeExpiredAgents(now);
    }
  }

  drain(): ServerMessage[] {
    const { changed, despawned } = this.world.drainEvents();
    const out = this.pending;
    this.pending = [];
    if (changed.length) out.push({ type: 'delta', t: this.world.now(), characters: changed });
    for (const id of despawned) out.push({ type: 'despawn', id });
    return out;
  }

  hello(test = false): HelloMessage {
    const { bundle } = this.office;
    return {
      type: 'hello',
      protocol: PROTOCOL_VERSION,
      t: this.world.now(),
      test,
      map: bundle.rendered,
      characterLayout: characterLayout(bundle.catalog.characters),
      entities: this.registry.all().map((e) => this.entityView(e)),
      characters: this.world.characters(),
    };
  }

  debug(): DebugMessage {
    return { type: 'debug', ...this.world.debugInfo() };
  }

  setRules(r: Rules): void {
    this.world.setRules(r);
  }

  // Для зрителя: без projectDir (спека 4.1).
  entityView(e: Entity): EntityView {
    const view: EntityView = {
      id: e.id,
      kind: e.kind,
      name: e.name,
      label: e.name,
      layers: avatarLayerPaths(this.office.bundle.catalog.characters, e.avatar).map(defaultAssetUrl),
    };
    if (e.ownerId) view.ownerId = e.ownerId;
    return view;
  }

  // ---- внутреннее ----

  private simEntity(e: Entity): SimEntity {
    if (e.kind === 'human') {
      const pod = this.registry.podOf(e.id);
      return pod ? { id: e.id, kind: 'human', podZoneId: pod } : { id: e.id, kind: 'human' };
    }
    return e.ownerId ? { id: e.id, kind: 'agent', ownerId: e.ownerId } : { id: e.id, kind: 'agent' };
  }

  private foreign(id: string, source: SourceConfig): boolean {
    const owner = this.store.ownerSource(id);
    return owner !== undefined && owner !== source.source;
  }

  private authorize(source: SourceConfig, ev: Event): string | null {
    if (ev.type !== 'snapshot' && ev.agent) {
      if (!source.owner) return 'agent_event_requires_owner_token';
      return this.foreign(agentKey(source.owner, ev.agent), source) ? 'foreign_source' : null;
    }
    if (source.owner) return 'agent_source_cannot_address_humans';
    const ids = ev.type === 'snapshot' ? ev.entities.map((e) => e.entityId) : [ev.entityId!];
    return ids.some((id) => this.foreign(id, source)) ? 'foreign_source' : null;
  }

  private resolveTarget(source: SourceConfig, ev: Exclude<Event, { type: 'snapshot' }>, receivedAt: number): string | null {
    if (ev.agent) {
      const { entity, created } = this.registry.ensureAgent(source.owner!, ev.agent, receivedAt);
      if (created) {
        this.world.upsertEntity(this.simEntity(entity));
        this.pending.push({ type: 'entity', entity: this.entityView(entity) });
      }
      return entity.id;
    }
    if (!this.registry.isHuman(ev.entityId!)) {
      this.log.warn(`неизвестный человек «${ev.entityId}» от ${source.source} — событие пропущено`);
      return null;
    }
    return ev.entityId!;
  }

  private apply(source: SourceConfig, ev: Event, receivedAt: number): boolean {
    if (ev.type === 'snapshot') {
      const known = ev.entities.filter((e) => {
        if (this.registry.isHuman(e.entityId) && isHumanStatus(e.status)) return true;
        this.log.warn(`снимок ${source.source}: «${e.entityId}» (${e.status}) пропущен`);
        return false;
      });
      for (const e of known) this.store.claim(e.entityId, source.source);
      const changes = this.store.applySnapshot(source.source, known, Date.parse(ev.at), (s) => ttlFor(source, s, ev.ttlSec), receivedAt);
      for (const ch of changes) this.world.setStatus(ch.entityId, ch.status, ch.meetingId);
      return true;
    }
    // Вид статуса проверяется до resolveTarget: иначе агентское событие с человеческим статусом
    // заводит через ensureAgent фантомного агента (entity зрителям, хранение 7 дней).
    if (ev.type === 'status' && (ev.agent ? !isAgentStatus(ev.status) : !isHumanStatus(ev.status))) {
      const who = ev.agent ? agentKey(source.owner!, ev.agent) : ev.entityId;
      this.log.warn(`${who}: статус «${ev.status}» не для ${ev.agent ? 'агента' : 'человека'} — пропущен`);
      return false;
    }
    const id = this.resolveTarget(source, ev, receivedAt);
    if (!id) return false;
    this.store.claim(id, source.source);
    if (ev.type === 'bubble') {
      this.world.setBubble(id, ev.text, ev.ttlSec);
      return true;
    }
    const r = this.store.applyStatus(id, source.source, { status: ev.status, meetingId: ev.meetingId, at: Date.parse(ev.at), ttlSec: ttlFor(source, ev.status, ev.ttlSec) }, receivedAt);
    if (r === 'stale') return false;
    this.world.setStatus(id, ev.status, ev.meetingId);
    return true;
  }

  private removeExpiredAgents(now: number): void {
    const isOffline = (id: string) => (this.store.get(id)?.status ?? 'offline') === 'offline';
    for (const id of this.registry.removeExpiredAgents(isOffline, now, this.office.bundle.config.agentRetentionDays)) {
      this.store.remove(id);
      this.world.removeEntity(id);
      this.pending.push({ type: 'entity_removed', id });
    }
  }
}
```

- [ ] **Step 6: `packages/server/src/http.ts` (первая версия)**

```ts
import Fastify, { type FastifyInstance } from 'fastify';
import type { HelloMessage, ServerMessage } from '@pixeloffice/protocol';
import type { OfficeRuntime } from './runtime.ts';

export type ServerOptions = {
  runtime: OfficeRuntime;
  viewerTokens?: string[];
  assetsDir?: string | null;
  viewerDist?: string | null;
  testMode?: ((q: Record<string, string | undefined>) => HelloMessage) | null;
  ingest?: boolean; // false — без POST /v1/events (тестовый режим)
  logger?: boolean;
};

// Первая версия: здоровье и приём событий. WebSocket, доступ зрителя и статика — задача 20.
export async function buildServer(o: ServerOptions): Promise<{ app: FastifyInstance; broadcast(msgs: ServerMessage[]): void }> {
  const app = Fastify({ logger: o.logger ?? false, bodyLimit: 1_000_000 });
  app.get('/healthz', async () => 'ok');
  if (o.ingest !== false) {
    app.post('/v1/events', async (req, reply) => {
      const r = o.runtime.ingestHttp(req.headers.authorization, req.body);
      return reply.code(r.status).send(r.body);
    });
  }
  return { app, broadcast: () => {} };
}
```

В `index.ts` добавить:
```ts
export * from './registry.ts';
export * from './runtime.ts';
export * from './http.ts';
```

- [ ] **Step 7: прогон, гейт, коммит**

```bash
pnpm vitest run packages/server   # PASS
pnpm gate
git add packages/server
git commit -m "feat(server): приём событий /v1/events с проверкой токенов и источников"
```

**Критерий готовности:** все тесты ingest и registry зелёные: 401/400/403, порядок по `at`, ttl от приёма, snapshot, регистрация агента без утечки `projectDir`.

---

### Задача 19: server — JSONL-лог, `state.json`, восстановление, срок хранения

**Files:**
- Create: `packages/server/src/persistence.ts`
- Modify: `packages/server/src/runtime.ts` (методы `persistedState`, `restore`), `packages/server/src/index.ts`
- Test: `packages/server/tests/persistence.test.ts`

**Interfaces:**
- Consumes: `LogEntry`, `OfficeRuntime`, `StoreJSON`, `AgentEntity`.
- Produces: `class EventLog { constructor(dir, keepDays); append(e: LogEntry): void; files(): string[]; readSince(ts): LogEntry[]; prune(now): string[] }`, `type PersistedState = { savedAt: number; store: StoreJSON; agents: AgentEntity[]; lastSeats: Record<string, string> }`, `class Persistence { readonly log: EventLog; constructor(dataDir, keepDays); loadState(): PersistedState | null; saveState(s): void }`. Новые методы `OfficeRuntime`: `persistedState(): PersistedState`, `restore(p: Persistence): void`.

Спека 4.7:
1. Каждое принятое событие пишется в `<dataDir>/events-YYYY-MM-DD.jsonl` (день по UTC времени приёма).
2. `state.json` пишется атомарно (tmp + rename).
3. Старт = снимок + хвост лога после `savedAt`. Истёкшие по ttl → `offline` без шествия к выходу, остальные сразу на местах.
4. `keepDays` — удаление старых файлов лога.

- [ ] **Step 1: падающие тесты `packages/server/tests/persistence.test.ts`**

```ts
import { mkdtempSync, appendFileSync, readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { EventLog, ManualClock, OfficeRuntime, Persistence, memoryLogger } from '../src/index.ts';
import { advance, demoOffice, iso } from './helpers.ts';

const DAY = 86_400_000;
const T0 = Date.parse('2026-01-05T09:00:00Z');
const tmp = () => mkdtempSync(join(tmpdir(), 'po-data-'));
const ev = (entityId: string) => ({ type: 'status' as const, entityId, status: 'online' as const, at: new Date(T0).toISOString() });

describe('EventLog', () => {
  it('ротация по суткам, чтение хвоста после метки, битая строка пропускается', () => {
    const dir = tmp();
    const log = new EventLog(dir, 30);
    log.append({ receivedAt: T0, source: 'nc', event: ev('p1') });
    log.append({ receivedAt: T0 + DAY, source: 'nc', event: ev('p2') });
    appendFileSync(join(dir, 'events-2026-01-06.jsonl'), '{"обрыв');
    expect(log.files()).toEqual(['events-2026-01-05.jsonl', 'events-2026-01-06.jsonl']);
    expect(log.readSince(T0).map((e) => (e.event.type === 'status' ? e.event.entityId : ''))).toEqual(['p2']);
    expect(log.readSince(0)).toHaveLength(2);
  });

  it('prune удаляет файлы старше keepDays', () => {
    const dir = tmp();
    const log = new EventLog(dir, 2);
    for (let d = 0; d < 5; d++) log.append({ receivedAt: T0 + d * DAY, source: 'nc', event: ev('p1') });
    expect(log.prune(T0 + 4 * DAY)).toEqual(['events-2026-01-05.jsonl', 'events-2026-01-06.jsonl']);
    expect(readdirSync(dir).filter((f) => f.endsWith('.jsonl'))).toHaveLength(3);
  });
});

describe('Persistence + OfficeRuntime.restore', () => {
  function runtimeOn(dir: string, clock: ManualClock) {
    const p = new Persistence(dir, 30);
    const rt = new OfficeRuntime({ office: demoOffice(), clock, log: memoryLogger(), eventLog: p.log });
    return { p, rt };
  }
  const hook = { project: 'PixelOffice', projectDir: '/x/PixelOffice', slot: '%3' };

  it('снимок + хвост лога: все онлайн сразу на местах, без дельт шествия', () => {
    const dir = tmp();
    const clock = new ManualClock(T0);
    const a = runtimeOn(dir, clock);
    a.rt.ingestFromSource(a.rt.sourceByName('nextcloud')!, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }]);
    a.rt.ingestFromSource(a.rt.sourceByName('claude-hook')!, [{ type: 'status', agent: hook, status: 'working', at: iso(clock) }]);
    advance(a.rt, clock, 20_000);
    a.p.saveState(a.rt.persistedState());
    clock.advance(1000);
    a.rt.ingestFromSource(a.rt.sourceByName('nextcloud')!, [{ type: 'status', entityId: 'p4', status: 'online', at: iso(clock) }]);

    const b = runtimeOn(dir, clock);
    b.rt.restore(b.p);
    const chars = b.rt.hello().characters;
    expect(chars.map((c) => c.id).sort()).toEqual(['agent:p1:PixelOffice:%3', 'p1', 'p4']);
    expect(chars.find((c) => c.id === 'p4')).toMatchObject({ x: 2, y: 6, pose: 'sit' });
    expect(b.rt.drain()).toEqual([]);
    expect(b.rt.registry.get('agent:p1:PixelOffice:%3')).toBeDefined();
  });

  it('истёкший ttl при старте → offline без шествия', () => {
    const dir = tmp();
    const clock = new ManualClock(T0);
    const a = runtimeOn(dir, clock);
    a.rt.ingestFromSource(a.rt.sourceByName('nextcloud')!, [{ type: 'status', entityId: 'p3', status: 'online', at: iso(clock), ttlSec: 60 }]);
    a.p.saveState(a.rt.persistedState());
    clock.advance(120_000);
    const b = runtimeOn(dir, clock);
    b.rt.restore(b.p);
    expect(b.rt.hello().characters).toEqual([]);
    expect(b.rt.store.get('p3')?.status).toBe('offline');
  });

  it('удаление агента по сроку хранения → entity_removed', () => {
    const clock = new ManualClock(T0);
    const { rt } = runtimeOn(tmp(), clock);
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: hook, status: 'offline', at: iso(clock) }]);
    rt.drain();
    clock.advance(8 * DAY);
    rt.step(50);
    expect(rt.drain()).toContainEqual({ type: 'entity_removed', id: 'agent:p1:PixelOffice:%3' });
    expect(rt.registry.get('agent:p1:PixelOffice:%3')).toBeUndefined();
  });

  it('state.json пишется атомарно и читается', () => {
    const dir = tmp();
    const p = new Persistence(dir, 30);
    expect(p.loadState()).toBeNull();
    p.saveState({ savedAt: T0, store: { statuses: {}, owners: {} }, agents: [], lastSeats: {} });
    expect(p.loadState()?.savedAt).toBe(T0);
    expect(readdirSync(dir)).not.toContain('state.json.tmp');
  });
});
```

Run: `pnpm vitest run packages/server/tests/persistence.test.ts` → FAIL.

- [ ] **Step 2: `packages/server/src/persistence.ts`**

```ts
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { AgentEntity } from './registry.ts';
import type { LogEntry } from './runtime.ts';
import type { StoreJSON } from './store.ts';

export type PersistedState = { savedAt: number; store: StoreJSON; agents: AgentEntity[]; lastSeats: Record<string, string> };

const DAY = 86_400_000;
const dayOf = (ms: number) => new Date(ms).toISOString().slice(0, 10);
const FILE_RE = /^events-\d{4}-\d{2}-\d{2}\.jsonl$/;

// JSONL-лог принятых событий с ротацией по суткам (спека 4.7).
export class EventLog {
  private readonly dir: string;
  private readonly keepDays: number;

  constructor(dir: string, keepDays: number) {
    this.dir = dir;
    this.keepDays = keepDays;
    mkdirSync(dir, { recursive: true });
  }

  append(e: LogEntry): void {
    appendFileSync(join(this.dir, `events-${dayOf(e.receivedAt)}.jsonl`), JSON.stringify(e) + '\n');
  }

  files(): string[] {
    return readdirSync(this.dir).filter((f) => FILE_RE.test(f)).sort();
  }

  readSince(ts: number): LogEntry[] {
    const from = `events-${dayOf(ts)}.jsonl`;
    const out: LogEntry[] = [];
    for (const f of this.files()) {
      if (f < from) continue;
      for (const line of readFileSync(join(this.dir, f), 'utf8').split('\n')) {
        if (!line.trim()) continue;
        try {
          const e = JSON.parse(line) as LogEntry;
          if (e.receivedAt > ts) out.push(e);
        } catch {
          // Строка оборвана при аварийной остановке — пропускаем.
        }
      }
    }
    return out.sort((a, b) => a.receivedAt - b.receivedAt);
  }

  prune(now: number): string[] {
    const cutoff = `events-${dayOf(now - this.keepDays * DAY)}.jsonl`;
    const removed = this.files().filter((f) => f < cutoff);
    for (const f of removed) rmSync(join(this.dir, f));
    return removed;
  }
}

export class Persistence {
  readonly log: EventLog;
  private readonly dir: string;

  constructor(dataDir: string, keepDays: number) {
    this.dir = dataDir;
    mkdirSync(dataDir, { recursive: true });
    this.log = new EventLog(dataDir, keepDays);
  }

  loadState(): PersistedState | null {
    const p = join(this.dir, 'state.json');
    return existsSync(p) ? (JSON.parse(readFileSync(p, 'utf8')) as PersistedState) : null;
  }

  saveState(s: PersistedState): void {
    const p = join(this.dir, 'state.json');
    writeFileSync(p + '.tmp', JSON.stringify(s));
    renameSync(p + '.tmp', p);
  }
}
```

- [ ] **Step 3: методы `OfficeRuntime`**

В `runtime.ts`: импорт `import type { PersistedState, Persistence } from './persistence.ts';`, в класс после `setRules` добавить:
```ts
  persistedState(): PersistedState {
    return {
      savedAt: this.clock.now(),
      store: this.store.toJSON(),
      agents: this.registry.toJSON(),
      lastSeats: this.world.lastSeats(),
    };
  }

  // Старт: снимок + хвост лога; истёкшие — offline без шествия; онлайн — сразу на местах (спека 4.7).
  restore(p: Persistence): void {
    const st = p.loadState();
    if (st) {
      this.store.restore(st.store);
      this.registry.restore(st.agents);
      for (const a of this.registry.agentList()) this.world.upsertEntity(this.simEntity(a));
      this.world.restoreLastSeats(st.lastSeats);
    }
    for (const e of p.log.readSince(st?.savedAt ?? 0)) {
      const src = this.byName.get(e.source);
      if (!src) {
        this.log.warn(`восстановление: источника «${e.source}» нет в конфиге — событие пропущено`);
        continue;
      }
      this.ingestFromSource(src, [e.event], { log: false, relay: false, receivedAt: e.receivedAt });
    }
    this.store.expire(this.clock.now());
    this.world.bootstrap(this.store.entries().map(([id, s]) => ({ id, status: s.status, meetingId: s.meetingId })));
    this.pending = [];
    this.world.drainEvents(); // начальное состояние уходит в hello, не в дельты
  }
```

В `index.ts`: `export * from './persistence.ts';`

- [ ] **Step 4: прогон, гейт, коммит**

```bash
pnpm vitest run packages/server   # PASS
pnpm gate
git add packages/server
git commit -m "feat(server): журнал событий, снимок состояния и восстановление при старте"
```

**Критерий готовности:** восстановление из снимка и хвоста лога ставит онлайн-сущности сразу на места. Истёкшие по ttl остаются невидимыми. Удаление по сроку хранения шлёт `entity_removed`.

---

### Задача 20: server — WebSocket, цикл симуляции, доступ зрителя, статика, CLI

**Files:**
- Modify: `packages/server/src/http.ts` (полная версия `buildServer`)
- Create: `packages/server/src/loop.ts`, `packages/server/src/main.ts`
- Modify: `packages/server/src/index.ts`
- Test: `packages/server/tests/ws.test.ts`, `packages/server/tests/loop.test.ts`

**Interfaces:**
- Consumes: `OfficeRuntime`, `Persistence`, `loadOffice`, `OfficeLoadError`, `checkAtlas` (validate-maps), `ServerMessage`, `HelloMessage`.
- Produces:
  - `buildServer(o: ServerOptions)` — сигнатура задачи 18. Маршруты: `GET /healthz` (публичный); `GET /v1/session?token=` (сам проверяет токен, ставит cookie, 204/401); `POST /v1/events` (если `ingest !== false`, авторизация — Bearer-токен источника); `GET /v1/ws` (WebSocket: `hello` при подключении, далее `broadcast`); статика viewer из `viewerDist` на `/`; ассеты из `assetsDir` на `/assets/*` — только PNG листов `catalog.sheets` и файлы из каталогов слоёв `characters.layers`, остальное 404 (`assetsDir` local/demo — весь `~/tmp`). Всё, кроме `/healthz`, `/v1/events`, `/v1/session`, требует токен зрителя (`?token=` или cookie `po_viewer`), иначе 401. Валидный `?token=` ставит HttpOnly-cookie.
  - `loop.ts`: `type LoopTarget = { step(dtMs: number): void; drain(): ServerMessage[]; debug(): ServerMessage }`, `startLoop(target, broadcast, opts?: { now?: () => number; onSecond?: () => void }): { stop(): void }` — фиксированный шаг 50 мс по накопителю, дельты каждые 2 шага (10 раз/с), `debug` и `onSecond` — каждые 20 шагов (1 раз/с). Накопитель режется до 1000 мс: после сна не нагоняем часы.
  - `main.ts`: CLI `node packages/server/src/main.ts <serve|check|init> <officeDir> [--test] [--port N]`.

- [ ] **Step 1: падающие тесты `packages/server/tests/ws.test.ts`**

```ts
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import type { ServerMessage } from '@pixeloffice/protocol';
import { buildServer } from '../src/index.ts';
import { advance, iso, makeRuntime } from './helpers.ts';

const TOKEN = 'demo-viewer-token';
const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

async function start() {
  const { rt, clock } = makeRuntime();
  const assets = mkdtempSync(join(tmpdir(), 'po-assets-'));
  // Лист из каталога demo раздаётся, посторонние файлы assetsDir — нет (у local и demo assetsDir — весь ~/tmp).
  const sheet = Object.values(rt.office.bundle.catalog.sheets)[0]!;
  mkdirSync(dirname(join(assets, sheet)), { recursive: true });
  writeFileSync(join(assets, sheet), 'png');
  writeFileSync(join(assets, 'x.txt'), 'secret');
  writeFileSync(join(assets, 'private.png'), 'secret');
  const srv = await buildServer({ runtime: rt, viewerTokens: [TOKEN], assetsDir: assets, viewerDist: null, testMode: null });
  await srv.app.listen({ port: 0, host: '127.0.0.1' });
  closers.push(() => srv.app.close());
  const port = (srv.app.server.address() as AddressInfo).port;
  const sheetUrl = '/assets/' + sheet.split('/').map(encodeURIComponent).join('/');
  return { rt, clock, ...srv, sheetUrl, base: `http://127.0.0.1:${port}`, wsBase: `ws://127.0.0.1:${port}/v1/ws` };
}

function connect(url: string) {
  const ws = new WebSocket(url);
  const inbox: ServerMessage[] = [];
  const waiters: { pred: (m: ServerMessage) => boolean; resolve: (m: ServerMessage) => void }[] = [];
  ws.addEventListener('message', (e) => {
    const m = JSON.parse(String(e.data)) as ServerMessage;
    inbox.push(m);
    for (const w of [...waiters]) if (w.pred(m)) {
      waiters.splice(waiters.indexOf(w), 1);
      w.resolve(m);
    }
  });
  closers.push(async () => ws.close());
  const next = (pred: (m: ServerMessage) => boolean, ms = 2000) =>
    new Promise<ServerMessage>((resolve, reject) => {
      const found = inbox.find(pred);
      if (found) return resolve(found);
      waiters.push({ pred, resolve });
      setTimeout(() => reject(new Error('нет сообщения')), ms);
    });
  return { ws, inbox, next };
}

describe('доступ зрителя', () => {
  it('без токена: 401 на viewer, ассеты и WebSocket', async () => {
    const s = await start();
    expect((await fetch(`${s.base}/`)).status).toBe(401);
    expect((await fetch(`${s.base}${s.sheetUrl}`)).status).toBe(401);
    const ws = new WebSocket(s.wsBase);
    const outcome = await new Promise<string>((r) => {
      ws.addEventListener('open', () => r('open'));
      ws.addEventListener('error', () => r('error'));
    });
    expect(outcome).toBe('error');
  });

  it('/?token= ставит HttpOnly-cookie, с cookie отдаются листы каталога, прочие файлы assetsDir — 404', async () => {
    const s = await start();
    const res = await fetch(`${s.base}/?token=${TOKEN}`);
    const cookie = res.headers.get('set-cookie')!;
    expect(cookie).toContain('po_viewer=');
    expect(cookie).toContain('HttpOnly');
    const headers = { cookie: cookie.split(';')[0]! };
    const asset = await fetch(`${s.base}${s.sheetUrl}`, { headers });
    expect(asset.status).toBe(200);
    expect(await asset.text()).toBe('png');
    expect((await fetch(`${s.base}/assets/x.txt`, { headers })).status).toBe(404);
    expect((await fetch(`${s.base}/assets/private.png`, { headers })).status).toBe(404);
  });

  it('/v1/session: 401 с плохим токеном, 204 с хорошим', async () => {
    const s = await start();
    expect((await fetch(`${s.base}/v1/session?token=bad-token`)).status).toBe(401);
    const ok = await fetch(`${s.base}/v1/session?token=${TOKEN}`);
    expect(ok.status).toBe(204);
    expect(ok.headers.get('set-cookie')).toContain('po_viewer=');
  });

  it('/healthz публичный', async () => {
    const s = await start();
    expect(await (await fetch(`${s.base}/healthz`)).text()).toBe('ok');
  });
});

describe('WebSocket', () => {
  it('hello при подключении: карта, сущности, пустой офис', async () => {
    const s = await start();
    const c = connect(`${s.wsBase}?token=${TOKEN}`);
    const hello = await c.next((m) => m.type === 'hello');
    expect(hello.type === 'hello' && [hello.map.width, hello.entities.length, hello.characters.length]).toEqual([32, 9, 0]);
  });

  it('событие → дельта у зрителя; новый агент — entity раньше delta; offline → despawn', async () => {
    const s = await start();
    const c = connect(`${s.wsBase}?token=${TOKEN}`);
    await c.next((m) => m.type === 'hello');
    await fetch(`${s.base}/v1/events`, {
      method: 'POST',
      headers: { 'content-type': 'application/json', authorization: 'Bearer demo-hook-token' },
      body: JSON.stringify({ events: [{ type: 'status', agent: { project: 'P', slot: '%1' }, status: 'working', at: iso(s.clock) }] }),
    });
    advance(s.rt, s.clock, 2100);
    s.broadcast(s.rt.drain());
    await c.next((m) => m.type === 'delta');
    const types = c.inbox.map((m) => m.type);
    expect(types.indexOf('entity')).toBeLessThan(types.indexOf('delta'));

    await fetch(`${s.base}/v1/events`, {
      method: 'POST',
      headers: { 'content-type': 'application/json', authorization: 'Bearer demo-hook-token' },
      body: JSON.stringify({ events: [{ type: 'status', agent: { project: 'P', slot: '%1' }, status: 'offline', at: iso(s.clock, 1) }] }),
    });
    advance(s.rt, s.clock, 15_000);
    s.broadcast(s.rt.drain());
    expect(await c.next((m) => m.type === 'despawn')).toEqual({ type: 'despawn', id: 'agent:p1:P:%1' });
  });
});
```

- [ ] **Step 2: падающий тест `packages/server/tests/loop.test.ts`**

```ts
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ServerMessage } from '@pixeloffice/protocol';
import { startLoop } from '../src/index.ts';

afterEach(() => vi.useRealTimers());

describe('startLoop', () => {
  it('шаг 50 мс, дельты 10 раз/с, debug раз в секунду, без нагона после сна', () => {
    vi.useFakeTimers();
    let now = 0;
    const steps: number[] = [];
    const sent: ServerMessage[][] = [];
    const target = {
      step: (dt: number) => steps.push(dt),
      drain: (): ServerMessage[] => [{ type: 'despawn', id: 'x' }],
      debug: (): ServerMessage => ({ type: 'debug', paths: {}, reservations: {}, meetings: {} }),
    };
    const loop = startLoop(target, (m) => sent.push(m), { now: () => now });
    for (let i = 0; i < 20; i++) {
      now += 50;
      vi.advanceTimersByTime(50);
    }
    expect(steps).toHaveLength(20);
    expect(sent.filter((m) => m[0]?.type === 'despawn')).toHaveLength(10);
    expect(sent.filter((m) => m[0]?.type === 'debug')).toHaveLength(1);
    now += 3_600_000; // сон ноутбука
    vi.advanceTimersByTime(50);
    expect(steps.length).toBeLessThanOrEqual(20 + 20);
    loop.stop();
  });
});
```

Run: `pnpm vitest run packages/server` → FAIL.

- [ ] **Step 3: `packages/server/src/http.ts` — полная версия (заменить файл)**

```ts
import { existsSync } from 'node:fs';
import fastifyStatic from '@fastify/static';
import websocket from '@fastify/websocket';
import Fastify, { type FastifyInstance, type FastifyRequest } from 'fastify';
import type { Catalog } from '@pixeloffice/core';
import type { HelloMessage, ServerMessage } from '@pixeloffice/protocol';
import type { OfficeRuntime } from './runtime.ts';

export type ServerOptions = {
  runtime: OfficeRuntime;
  viewerTokens?: string[];
  assetsDir?: string | null;
  viewerDist?: string | null;
  testMode?: ((q: Record<string, string | undefined>) => HelloMessage) | null;
  ingest?: boolean;
  logger?: boolean;
};

const COOKIE = 'po_viewer';
const PUBLIC = new Set(['/healthz', '/v1/events', '/v1/session']);

function cookies(header: string | undefined): Record<string, string> {
  const out: Record<string, string> = {};
  for (const part of (header ?? '').split(';')) {
    const i = part.indexOf('=');
    if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
  }
  return out;
}
const setCookie = (token: string) => `${COOKIE}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000`;

// assetsDir у local и demo — весь ~/tmp, а там лежат и личные файлы. Раздаём только PNG, которые знает каталог:
// листы sheets и файлы из каталогов слоёв персонажей. Остальное — 404 даже с токеном зрителя.
// pathName от @fastify/static уже декодирован и нормализован («/Pack/a b.png», без «..»).
function assetAllowed(catalog: Catalog): (pathName: string) => boolean {
  const dirOf = (t: string) => t.slice(0, t.lastIndexOf('/', t.includes('{') ? t.indexOf('{') : t.length) + 1);
  const sheets = new Set(Object.values(catalog.sheets));
  const layerDirs = Object.values(catalog.characters.layers).map(dirOf).filter((d) => d !== '');
  return (pathName) => {
    const rel = pathName.replace(/^\/+/, '');
    if (!rel.toLowerCase().endsWith('.png')) return false;
    return sheets.has(rel) || layerDirs.some((d) => rel.startsWith(d) && !rel.slice(d.length).includes('/'));
  };
}

export async function buildServer(o: ServerOptions): Promise<{ app: FastifyInstance; broadcast(msgs: ServerMessage[]): void }> {
  const app = Fastify({ logger: o.logger ?? false, bodyLimit: 1_000_000 });
  const tokens = new Set(o.viewerTokens ?? []);
  const query = (req: FastifyRequest) => (req.query ?? {}) as Record<string, string | undefined>;
  const queryToken = (req: FastifyRequest) => {
    const t = query(req).token;
    return t && tokens.has(t) ? t : null;
  };
  const viewerOk = (req: FastifyRequest) => queryToken(req) !== null || tokens.has(cookies(req.headers.cookie)[COOKIE] ?? '');

  // Viewer, ассеты и WebSocket — только по токену зрителя: PNG LimeZu не раздаются посторонним (спека 4.6, 8).
  app.addHook('onRequest', async (req, reply) => {
    const path = req.url.split('?')[0]!;
    if (PUBLIC.has(path)) return;
    if (!viewerOk(req)) return reply.code(401).type('text/plain').send('нужен токен зрителя');
    const t = queryToken(req);
    if (t) reply.header('set-cookie', setCookie(t));
  });

  await app.register(websocket);
  const clients = new Set<{ send(data: string): void; readyState: number }>();

  app.get('/healthz', async () => 'ok');

  app.get('/v1/session', async (req, reply) => {
    const t = queryToken(req);
    if (!t) return reply.code(401).send({ error: 'unauthorized' });
    return reply.header('set-cookie', setCookie(t)).code(204).send();
  });

  if (o.ingest !== false) {
    app.post('/v1/events', async (req, reply) => {
      const r = o.runtime.ingestHttp(req.headers.authorization, req.body);
      return reply.code(r.status).send(r.body);
    });
  }

  app.get('/v1/ws', { websocket: true }, (socket, req) => {
    const q = query(req);
    if (o.testMode && q.scenario) {
      // Тестовый режим: один hello на момент t, без дельт (спека 4.6).
      try {
        socket.send(JSON.stringify(o.testMode(q)));
      } catch (e) {
        socket.close(1011, (e as Error).message.slice(0, 120));
      }
      return;
    }
    socket.send(JSON.stringify(o.runtime.hello(false)));
    clients.add(socket);
    socket.on('close', () => clients.delete(socket));
  });

  if (o.assetsDir && existsSync(o.assetsDir)) {
    await app.register(fastifyStatic, {
      root: o.assetsDir,
      prefix: '/assets/',
      decorateReply: false,
      index: false,
      allowedPath: assetAllowed(o.runtime.office.bundle.catalog),
    });
  }
  if (o.viewerDist && existsSync(o.viewerDist)) {
    await app.register(fastifyStatic, { root: o.viewerDist, prefix: '/', decorateReply: false });
  } else {
    app.get('/', async (_req, reply) => reply.code(503).type('text/plain').send('viewer не собран: pnpm --filter @pixeloffice/viewer build'));
  }

  const broadcast = (msgs: ServerMessage[]) => {
    for (const m of msgs) {
      const data = JSON.stringify(m);
      for (const c of clients) if (c.readyState === 1) c.send(data);
    }
  };
  return { app, broadcast };
}
```

- [ ] **Step 4: `packages/server/src/loop.ts`**

```ts
import type { ServerMessage } from '@pixeloffice/protocol';

export type LoopTarget = { step(dtMs: number): void; drain(): ServerMessage[]; debug(): ServerMessage };

const STEP = 50;

// Фиксированный шаг 50 мс (спека 4.6); дельты 10 раз/с; debug раз в секунду.
export function startLoop(
  target: LoopTarget,
  broadcast: (msgs: ServerMessage[]) => void,
  opts: { now?: () => number; onSecond?: () => void } = {},
): { stop(): void } {
  const now = opts.now ?? (() => performance.now());
  let last = now();
  let acc = 0;
  let steps = 0;
  const timer = setInterval(() => {
    const t = now();
    acc += Math.min(t - last, 1000); // после сна не нагоняем часы
    last = t;
    while (acc >= STEP) {
      target.step(STEP);
      acc -= STEP;
      steps++;
      if (steps % 2 === 0) {
        const msgs = target.drain();
        if (msgs.length) broadcast(msgs);
      }
      if (steps % 20 === 0) {
        broadcast([target.debug()]);
        opts.onSecond?.();
      }
    }
  }, STEP);
  return { stop: () => clearInterval(timer) };
}
```

- [ ] **Step 5: `packages/server/src/main.ts`**

```ts
import { randomBytes } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { checkAtlas } from '@pixeloffice/validate-maps';
import { systemClock } from './clock.ts';
import { buildServer } from './http.ts';
import { consoleLogger } from './logger.ts';
import { startLoop } from './loop.ts';
import { OfficeLoadError, loadOffice, type LoadedOffice } from './office.ts';
import { Persistence } from './persistence.ts';
import { OfficeRuntime } from './runtime.ts';

const USAGE = 'использование: node packages/server/src/main.ts <serve|check|init> <каталог офиса> [--test] [--port N]';
const [cmd, dirArg, ...rest] = process.argv.slice(2);
const flags = { test: rest.includes('--test'), port: rest.includes('--port') ? Number(rest[rest.indexOf('--port') + 1]) : undefined };
if (!cmd || !dirArg) {
  console.error(USAGE);
  process.exit(2);
}
const dir = resolve(dirArg);

function loadOrExit(): LoadedOffice {
  try {
    const office = loadOffice(dir);
    if (existsSync(office.assetsDir)) {
      const atlas = checkAtlas(office.bundle.catalog, office.bundle.config.people, office.assetsDir);
      if (atlas.length) throw new OfficeLoadError(office.dir, atlas.join('\n'));
    } else {
      consoleLogger.warn(`assetsDir ${office.assetsDir} не найден — проверка атласа пропущена, ассеты не раздаются`);
    }
    return office;
  } catch (e) {
    console.error(e instanceof OfficeLoadError ? e.message : String(e));
    process.exit(1);
  }
}

if (cmd === 'init') {
  const target = join(dir, 'config.yaml');
  if (existsSync(target)) {
    console.error(`${target} уже есть — не трогаю`);
    process.exit(1);
  }
  const text = readFileSync(join(dir, 'config.example.yaml'), 'utf8').replace(/CHANGE_ME_[A-Za-z0-9_]+/g, () => randomBytes(24).toString('base64url'));
  writeFileSync(target, text, { mode: 0o600 });
  console.log(`создан ${target} со случайными токенами`);
} else if (cmd === 'check') {
  const office = loadOrExit();
  console.log(`офис ${office.bundle.config.officeId}: ok`);
} else if (cmd === 'serve') {
  const office = loadOrExit();
  const { config } = office.bundle;
  const persistence = flags.test ? null : new Persistence(office.dataDir, config.log.keepDays);
  const runtime = new OfficeRuntime({ office, clock: systemClock, log: consoleLogger, eventLog: persistence?.log });
  if (persistence) runtime.restore(persistence);
  const { app, broadcast } = await buildServer({
    runtime,
    viewerTokens: config.viewerTokens,
    assetsDir: office.assetsDir,
    viewerDist: fileURLToPath(new URL('../../viewer/dist/', import.meta.url)),
    testMode: null,
    ingest: !flags.test,
    logger: true,
  });
  const host = flags.test ? '127.0.0.1' : config.listen.host;
  const port = flags.port ?? config.listen.port;
  await app.listen({ host, port });
  let seconds = 0;
  const loop = startLoop(runtime, broadcast, {
    onSecond: () => {
      seconds++;
      if (persistence && seconds % 60 === 0) persistence.saveState(runtime.persistedState());
      if (persistence && seconds % 3600 === 0) persistence.log.prune(Date.now());
    },
  });
  const shutdown = async () => {
    loop.stop();
    if (persistence) persistence.saveState(runtime.persistedState());
    await app.close();
    process.exit(0);
  };
  process.on('SIGINT', shutdown);
  process.on('SIGTERM', shutdown);
  consoleLogger.info(`офис ${config.officeId}: http://${host}:${port}/?token=<viewerToken>${flags.test ? ' (тестовый режим)' : ''}`);
} else {
  console.error(USAGE);
  process.exit(2);
}
```

В `index.ts` добавить `export * from './loop.ts';` (`main.ts` не экспортируется).

- [ ] **Step 6: прогон и ручная проверка CLI**

```bash
pnpm vitest run packages/server                       # PASS
node packages/server/src/main.ts check offices/demo   # «офис demo: ok»
node packages/server/src/main.ts serve offices/demo --port 4899 &   # фоном
SRV=$!
curl -sf -o /dev/null --noproxy '*' --retry 30 --retry-delay 1 --retry-connrefused http://127.0.0.1:4899/healthz   # ждать готовности
curl -s --noproxy '*' http://127.0.0.1:4899/healthz                 # ok
curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' http://127.0.0.1:4899/   # 401
kill $SRV
```
Если Node отказывается исполнять TS из workspace-пакета (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`) — применить запасной путь решения 2 (`tsx`) и отметить это в README.

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

```bash
pnpm gate
git add packages/server
git commit -m "feat(server): WebSocket hello и дельты, доступ зрителя по токену, цикл симуляции, CLI"
```

**Критерий готовности:** тесты доступа (401 на `/`, `/assets/*`, `/v1/ws`; 404 на файлы `assetsDir` вне каталога), cookie, `hello`, дельт, `entity` раньше `delta`, `despawn` и цикла зелёные. `serve` поднимает сервер.

---

### Задача 21: server — горячая перезагрузка `rules.yaml`

**Files:**
- Create: `packages/server/src/rules-watch.ts`
- Modify: `packages/server/src/main.ts`, `packages/server/src/index.ts`
- Test: `packages/server/tests/rules-watch.test.ts`

**Interfaces:**
- Consumes: `parseRules`, `formatErrors`, `Rules` (core); `Logger`.
- Produces: `watchRules(path, zoneIds: ReadonlySet<string>, onRules: (r: Rules) => void, log: Logger, debounceMs = 150): { close(): void }`. Следит за каталогом файла: редакторы заменяют файл целиком, наблюдение за самим файлом теряется. Невалидный файл → `log.error` с ошибками, прежние правила остаются (спека 5.3, 10).

- [ ] **Step 1: падающий тест `packages/server/tests/rules-watch.test.ts`**

```ts
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import type { Rules } from '@pixeloffice/core';
import { memoryLogger, watchRules } from '../src/index.ts';

const RULES = (agentDwell: string) => `
dwell: { agent: ${agentDwell}, human: 60s }
human: { online: [own_seat], meeting: [meeting_room], offline: [exit] }
agent: { working: ["zone:coworking"], idle: ["zone:lounge"], needs_input: [current_work_seat], offline: [exit] }
`;

describe('watchRules', () => {
  it('валидная правка применяется, невалидная — лог ошибки и прежние правила', async () => {
    const dir = mkdtempSync(join(tmpdir(), 'po-rules-'));
    const path = join(dir, 'rules.yaml');
    writeFileSync(path, RULES('20s'));
    const applied: Rules[] = [];
    const log = memoryLogger();
    const w = watchRules(path, new Set(['coworking', 'lounge']), (r) => applied.push(r), log, 50);
    try {
      await new Promise((r) => setTimeout(r, 100)); // FSEvents успевает подписаться
      writeFileSync(path, 'human: [сломано');
      await vi.waitFor(() => expect(log.lines.some((l) => l.level === 'error')).toBe(true), { timeout: 3000 });
      expect(applied).toEqual([]);
      writeFileSync(path, RULES('5s'));
      await vi.waitFor(() => expect(applied.at(-1)?.dwellMs.agent).toBe(5000), { timeout: 3000 });
    } finally {
      w.close();
    }
  });
});
```

Run: `pnpm vitest run packages/server/tests/rules-watch.test.ts` → FAIL.

- [ ] **Step 2: `packages/server/src/rules-watch.ts`**

```ts
import { readFileSync, watch } from 'node:fs';
import { basename, dirname } from 'node:path';
import { formatErrors, parseRules, type Rules } from '@pixeloffice/core';
import type { Logger } from './logger.ts';

export function watchRules(
  path: string,
  zoneIds: ReadonlySet<string>,
  onRules: (r: Rules) => void,
  log: Logger,
  debounceMs = 150,
): { close(): void } {
  let timer: ReturnType<typeof setTimeout> | null = null;
  const reload = () => {
    let text: string;
    try {
      text = readFileSync(path, 'utf8');
    } catch (e) {
      log.error(`rules.yaml не читается: ${(e as Error).message}`);
      return;
    }
    const r = parseRules(text, basename(path), zoneIds);
    if (!r.ok) {
      log.error(`rules.yaml невалиден, остаются прежние правила:\n${formatErrors(r.errors)}`);
      return;
    }
    onRules(r.value);
    log.info('rules.yaml перезагружен');
  };
  const watcher = watch(dirname(path), (_event, name) => {
    if (name !== basename(path)) return;
    if (timer) clearTimeout(timer);
    timer = setTimeout(reload, debounceMs);
  });
  return {
    close() {
      watcher.close();
      if (timer) clearTimeout(timer);
    },
  };
}
```

В `index.ts`: `export * from './rules-watch.ts';`

- [ ] **Step 3: подключение в `main.ts`**

В ветке `serve` после `await app.listen(...)` вставить:
```ts
  const zoneIds = new Set(office.bundle.layout.zones.map((z) => z.id));
  const rulesWatcher = watchRules(office.files.rulesPath, zoneIds, (r) => runtime.setRules(r), consoleLogger);
```
В `shutdown` перед `await app.close();` добавить `rulesWatcher.close();`. Импорт: `import { watchRules } from './rules-watch.ts';`.

- [ ] **Step 4: прогон, гейт, коммит**

```bash
pnpm vitest run packages/server   # PASS
pnpm gate
git add packages/server
git commit -m "feat(server): горячая перезагрузка rules.yaml"
```

**Критерий готовности:** тест горячей перезагрузки зелёный. Невалидный файл не ломает работающие правила.

---

### Задача 22: tools/replay — сценарии и реплей лога

**Files:**
- Create: `tools/replay/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts}`, `tools/replay/src/{scenarios.ts,play.ts,cli.ts,index.ts}`
- Test: `tools/replay/tests/scenarios.test.ts`, `tools/replay/tests/play.test.ts`
- Modify: корневой `package.json` (скрипт `mock:local`)

**Interfaces:**
- Consumes: `Event`, `EventsBodySchema` (protocol), `mulberry32`, `parseConfig`, `SourceConfig` (core), `readOfficeTexts` (validate-maps).
- Produces:
  - `type ScenarioEvent = { atMs: number; source: 'human' | 'agent'; event: Event }` — логический источник; реальный подставляет `resolveScenarioSource`.
  - `type ScenarioContext = { people: string[]; owner: string; seed: number; baseTime: number }`.
  - `type Scenario = { name: string; description: string; build(ctx): ScenarioEvent[] }` (события по возрастанию `atMs`).
  - `scenarios: Record<string, Scenario>` — `morning`, `meeting9`, `agents20`, `needs-input`, `lounge`, `sit4`.
  - `resolveScenarioSource(sources: SourceConfig[], kind): SourceConfig | undefined` — `agent` → первый источник с `owner`, `human` → первый без.
  - `play.ts`: `playTimed<T>(items: { atMs: number; item: T }[], send: (batch: T[]) => Promise<void>, speed: number, sleep?: (ms) => Promise<void>): Promise<void>` — пачки с одинаковым `atMs` уходят одним запросом.
  - CLI: `node tools/replay/src/cli.ts scenario <name> --office <dir> --url <base> [--speed 1] [--seed 1]` и `node tools/replay/src/cli.ts log <file.jsonl> --office <dir> --url <base> [--speed 10]`. Поле `at` переписывается на время отправки (решение 22).

Сценарии (спека 6.3 + нужды скриншотов):
1. `morning` — «утро, все приходят»: человек i — `online` в `1500·i` мс. У хозяина два агента `working` (%1, %2) в 3000 и 4000 мс.
2. `meeting9` — «встреча на 9 человек»: все `online` в 0…, в 20 000 мс снимок: первые 9 — `meeting` с `meetingId: standup`. Людей меньше 9 → `Error`.
3. `agents20` — «20 агентов дёргаются working↔idle»: слоты %1…%20, переключения через случайные 3–15 с на интервале 120 с (ГПСЧ по `seed`).
4. `needs-input` — хозяин `online`, агент %1 `working` в 0, в 10 000 мс `needs_input` + облачко «Разрешить запуск pnpm test?» (ttl 3600).
5. `lounge` — хозяин `online`, агенты %1…%5 `idle` в 0…2000 мс (аркады и диван).
6. `sit4` — люди с индексами 0, 3, 6, 7 `online` в 0 (в demo — p1 вниз, p4 вверх, p7 вправо, p8 влево).

- [ ] **Step 1: пакет**

`tools/replay/package.json`:
```json
{
  "name": "@pixeloffice/replay",
  "private": true,
  "type": "module",
  "exports": { ".": "./src/index.ts" },
  "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json" },
  "dependencies": {
    "@pixeloffice/core": "workspace:*",
    "@pixeloffice/protocol": "workspace:*",
    "@pixeloffice/validate-maps": "workspace:*"
  }
}
```
`tsconfig.json`/`tsconfig.test.json`/`vitest.config.ts` — по образцу `tools/validate-maps` (`name: 'replay'`).

```bash
pnpm install
```

- [ ] **Step 2: падающие тесты `tools/replay/tests/scenarios.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { EventsBodySchema } from '@pixeloffice/protocol';
import { resolveScenarioSource, scenarios, type ScenarioContext } from '../src/index.ts';

const people = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9'];
const ctx: ScenarioContext = { people, owner: 'p1', seed: 1, baseTime: Date.parse('2026-01-05T09:00:00Z') };

describe('сценарии', () => {
  for (const [name, s] of Object.entries(scenarios)) {
    it(`${name}: события валидны и упорядочены`, () => {
      const evs = s.build(ctx);
      expect(evs.length).toBeGreaterThan(0);
      expect(evs.map((e) => e.atMs)).toEqual([...evs.map((e) => e.atMs)].sort((a, b) => a - b));
      expect(EventsBodySchema.safeParse({ events: evs.map((e) => e.event).slice(0, 500) }).success).toBe(true);
    });
  }

  it('детерминированы по seed', () => {
    expect(scenarios['agents20']!.build(ctx)).toEqual(scenarios['agents20']!.build(ctx));
    expect(scenarios['agents20']!.build({ ...ctx, seed: 2 })).not.toEqual(scenarios['agents20']!.build(ctx));
  });

  it('agents20 — 20 разных панелей', () => {
    const slots = new Set(scenarios['agents20']!.build(ctx).flatMap((e) => (e.event.type !== 'snapshot' && e.event.agent ? [e.event.agent.slot] : [])));
    expect(slots.size).toBe(20);
  });

  it('meeting9: снимок с 9 участниками; меньше 9 людей — ошибка', () => {
    const snap = scenarios['meeting9']!.build(ctx).find((e) => e.event.type === 'snapshot')!;
    expect(snap.event.type === 'snapshot' && snap.event.entities.filter((x) => x.status === 'meeting')).toHaveLength(9);
    expect(() => scenarios['meeting9']!.build({ ...ctx, people: ['p1'] })).toThrow();
  });

  it('resolveScenarioSource: агентский — с owner, человеческий — без', () => {
    const sources = [{ source: 'nextcloud', token: 'x'.repeat(8) }, { source: 'claude-hook', token: 'y'.repeat(8), owner: 'p1' }];
    expect(resolveScenarioSource(sources, 'agent')?.source).toBe('claude-hook');
    expect(resolveScenarioSource(sources, 'human')?.source).toBe('nextcloud');
  });
});
```

`tools/replay/tests/play.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { playTimed } from '../src/index.ts';

describe('playTimed', () => {
  it('ждёт разницу atMs / speed и шлёт пачки с равным atMs вместе', async () => {
    const sleeps: number[] = [];
    const sent: string[][] = [];
    await playTimed(
      [{ atMs: 0, item: 'a' }, { atMs: 0, item: 'b' }, { atMs: 1000, item: 'c' }, { atMs: 3000, item: 'd' }],
      async (batch) => void sent.push(batch),
      2,
      async (ms) => void sleeps.push(ms),
    );
    expect(sent).toEqual([['a', 'b'], ['c'], ['d']]);
    expect(sleeps).toEqual([500, 1000]);
  });
});
```

Run: `pnpm vitest run tools/replay` → FAIL.

- [ ] **Step 3: `tools/replay/src/scenarios.ts`**

```ts
import { mulberry32, type SourceConfig } from '@pixeloffice/core';
import type { Event, Status } from '@pixeloffice/protocol';

export type ScenarioEvent = { atMs: number; source: 'human' | 'agent'; event: Event };
export type ScenarioContext = { people: string[]; owner: string; seed: number; baseTime: number };
export type Scenario = { name: string; description: string; build(ctx: ScenarioContext): ScenarioEvent[] };

const PROJECT = 'demo';
const at = (ctx: ScenarioContext, ms: number) => new Date(ctx.baseTime + ms).toISOString();
const human = (ctx: ScenarioContext, atMs: number, entityId: string, status: Status): ScenarioEvent => ({
  atMs,
  source: 'human',
  event: { type: 'status', entityId, status, at: at(ctx, atMs) },
});
const agent = (ctx: ScenarioContext, atMs: number, slot: string, status: Status): ScenarioEvent => ({
  atMs,
  source: 'agent',
  event: { type: 'status', agent: { project: PROJECT, slot }, status, at: at(ctx, atMs) },
});
const bubble = (ctx: ScenarioContext, atMs: number, slot: string, text: string, ttlSec: number): ScenarioEvent => ({
  atMs,
  source: 'agent',
  event: { type: 'bubble', agent: { project: PROJECT, slot }, text, ttlSec, at: at(ctx, atMs) },
});
const sorted = (xs: ScenarioEvent[]) => xs.sort((a, b) => a.atMs - b.atMs);

export const scenarios: Record<string, Scenario> = {
  morning: {
    name: 'morning',
    description: 'утро — все приходят по одному, у хозяина просыпаются два агента',
    build: (ctx) =>
      sorted([...ctx.people.map((p, i) => human(ctx, 1500 * i, p, 'online')), agent(ctx, 3000, '%1', 'working'), agent(ctx, 4000, '%2', 'working')]),
  },
  meeting9: {
    name: 'meeting9',
    description: 'встреча на 9 человек в самой подходящей переговорке',
    build: (ctx) => {
      if (ctx.people.length < 9) throw new Error(`meeting9: нужно минимум 9 людей, в офисе ${ctx.people.length}`);
      const online = ctx.people.map((p, i) => human(ctx, 500 * i, p, 'online'));
      const snapshot: ScenarioEvent = {
        atMs: 20_000,
        source: 'human',
        event: {
          type: 'snapshot',
          at: at(ctx, 20_000),
          entities: ctx.people.map((p, i) => (i < 9 ? { entityId: p, status: 'meeting' as const, meetingId: 'standup' } : { entityId: p, status: 'online' as const })),
        },
      };
      return sorted([...online, snapshot]);
    },
  },
  agents20: {
    name: 'agents20',
    description: '20 агентов дёргаются working↔idle',
    build: (ctx) => {
      const rnd = mulberry32(ctx.seed);
      const out: ScenarioEvent[] = [human(ctx, 0, ctx.people[0] ?? ctx.owner, 'online')];
      for (let i = 1; i <= 20; i++) {
        let t = Math.floor(rnd() * 3000);
        let working = true;
        while (t < 120_000) {
          out.push(agent(ctx, t, `%${i}`, working ? 'working' : 'idle'));
          working = !working;
          t += 3000 + Math.floor(rnd() * 12_000);
        }
      }
      return sorted(out);
    },
  },
  'needs-input': {
    name: 'needs-input',
    description: 'агент работает, затем ждёт разрешения с облачком',
    build: (ctx) =>
      sorted([
        human(ctx, 0, ctx.owner, 'online'),
        agent(ctx, 0, '%1', 'working'),
        agent(ctx, 10_000, '%1', 'needs_input'),
        bubble(ctx, 10_000, '%1', 'Разрешить запуск pnpm test?', 3600),
      ]),
  },
  lounge: {
    name: 'lounge',
    description: 'агенты закончили и отдыхают в лаунже',
    build: (ctx) => sorted([human(ctx, 0, ctx.owner, 'online'), ...[1, 2, 3, 4, 5].map((i) => agent(ctx, (i - 1) * 500, `%${i}`, 'idle'))]),
  },
  sit4: {
    name: 'sit4',
    description: 'четыре направления сидения',
    build: (ctx) => sorted([0, 3, 6, 7].flatMap((i) => (ctx.people[i] ? [human(ctx, 0, ctx.people[i]!, 'online')] : []))),
  },
};

export function resolveScenarioSource(sources: SourceConfig[], kind: 'human' | 'agent'): SourceConfig | undefined {
  return sources.find((s) => (kind === 'agent' ? s.owner !== undefined : s.owner === undefined));
}
```

- [ ] **Step 4: `tools/replay/src/play.ts`**

```ts
const realSleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

export async function playTimed<T>(
  items: { atMs: number; item: T }[],
  send: (batch: T[]) => Promise<void>,
  speed: number,
  sleep: (ms: number) => Promise<void> = realSleep,
): Promise<void> {
  let prev: number | null = null;
  for (let i = 0; i < items.length; ) {
    const t = items[i]!.atMs;
    const batch: T[] = [];
    while (i < items.length && items[i]!.atMs === t) batch.push(items[i++]!.item);
    if (prev !== null && t > prev) await sleep((t - prev) / speed);
    prev = t;
    await send(batch);
  }
}
```

- [ ] **Step 5: `tools/replay/src/cli.ts` и `index.ts`**

`tools/replay/src/index.ts`:
```ts
export * from './scenarios.ts';
export * from './play.ts';
```

`tools/replay/src/cli.ts`:
```ts
import { readFileSync } from 'node:fs';
import { parseConfig, type SourceConfig } from '@pixeloffice/core';
import type { Event } from '@pixeloffice/protocol';
import { readOfficeTexts } from '@pixeloffice/validate-maps';
import { playTimed } from './play.ts';
import { resolveScenarioSource, scenarios } from './scenarios.ts';

// Реплей в /v1/events. Время события (at) — момент отправки (решение 22).
const USAGE = `использование:
  node tools/replay/src/cli.ts scenario <имя> --office <каталог> --url <http://host:port> [--speed 1] [--seed 1]
  node tools/replay/src/cli.ts log <events.jsonl> --office <каталог> --url <http://host:port> [--speed 10]
сценарии: ${Object.keys(scenarios).join(', ')}`;
const [mode, arg, ...rest] = process.argv.slice(2);
const opt = (name: string, def?: string) => (rest.includes(`--${name}`) ? rest[rest.indexOf(`--${name}`) + 1] : def);
const officeDir = opt('office');
const url = opt('url');
if (!mode || !arg || !officeDir || !url) {
  console.error(USAGE);
  process.exit(2);
}
const cfg = parseConfig(readOfficeTexts(officeDir).texts.config);
if (!cfg.ok) {
  console.error(cfg.errors.map((e) => e.message).join('\n'));
  process.exit(1);
}
const config = cfg.value;
const speed = Number(opt('speed', mode === 'log' ? '10' : '1'));

async function post(source: SourceConfig, events: Event[]) {
  const now = new Date().toISOString();
  const res = await fetch(new URL('/v1/events', url), {
    method: 'POST',
    headers: { 'content-type': 'application/json', authorization: `Bearer ${source.token}` },
    body: JSON.stringify({ events: events.map((e) => ({ ...e, at: now })) }),
  });
  const text = await res.text();
  console.log(`${new Date().toLocaleTimeString()} ${source.source} ×${events.length} → ${res.status} ${text}`);
}

if (mode === 'scenario') {
  const s = scenarios[arg];
  if (!s) {
    console.error(`нет сценария «${arg}»\n${USAGE}`);
    process.exit(2);
  }
  const agentSrc = resolveScenarioSource(config.sources, 'agent');
  const humanSrc = resolveScenarioSource(config.sources, 'human');
  const evs = s.build({ people: config.people.map((p) => p.id), owner: agentSrc?.owner ?? '', seed: Number(opt('seed', '1')), baseTime: Date.now() });
  await playTimed(
    evs.map((e) => ({ atMs: e.atMs, item: e })),
    async (batch) => {
      for (const kind of ['human', 'agent'] as const) {
        const src = kind === 'agent' ? agentSrc : humanSrc;
        const part = batch.filter((e) => e.source === kind).map((e) => e.event);
        if (part.length && src) await post(src, part);
        else if (part.length) console.warn(`нет источника для событий «${kind}» в конфиге — пропущено ${part.length}`);
      }
    },
    speed,
  );
} else if (mode === 'log') {
  const entries = readFileSync(arg, 'utf8')
    .split('\n')
    .filter((l) => l.trim())
    .map((l) => JSON.parse(l) as { receivedAt: number; source: string; event: Event });
  const t0 = entries[0]?.receivedAt ?? 0;
  const byName = new Map(config.sources.map((s) => [s.source, s]));
  await playTimed(
    entries.map((e) => ({ atMs: e.receivedAt - t0, item: e })),
    async (batch) => {
      for (const name of new Set(batch.map((e) => e.source))) {
        const src = byName.get(name);
        if (!src) {
          console.warn(`источника «${name}» нет в конфиге — пропуск`);
          continue;
        }
        await post(src, batch.filter((e) => e.source === name).map((e) => e.event));
      }
    },
    speed,
  );
} else {
  console.error(USAGE);
  process.exit(2);
}
```

Корневой `package.json` — скрипт:
```json
"mock:local": "node tools/replay/src/cli.ts scenario lounge --office offices/local --url http://127.0.0.1:4870"
```

- [ ] **Step 6: прогон, гейт, коммит**

```bash
pnpm vitest run tools/replay   # PASS
pnpm gate
git add tools/replay package.json pnpm-lock.yaml
git commit -m "feat(replay): сценарии-генераторы и реплей журнала событий"
```

**Критерий готовности:** 11 тестов зелёные: 6 сценариев в цикле, 4 отдельных теста сценариев и `playTimed`. CLI тайпчекается.

---

### Задача 23: server — тестовый режим `--test`

**Files:**
- Create: `packages/server/src/test-mode.ts`
- Modify: `packages/server/package.json` (зависимость `@pixeloffice/replay`), `packages/server/src/main.ts`, `packages/server/src/index.ts`
- Test: `packages/server/tests/test-mode.test.ts`

**Interfaces:**
- Consumes: `scenarios`, `resolveScenarioSource` (replay); `ManualClock`, `OfficeRuntime`, `silentLogger`, `LoadedOffice`, `buildServer`.
- Produces: `renderScenarioHello(office: LoadedOffice, q: Record<string, string | undefined>): HelloMessage` — новый мир на управляемых часах, события сценария, шаги по 50 мс до `t`, `hello` с `test: true` (спека 4.6). Неизвестный сценарий или `t` вне 0…3 600 000 → `Error`.

- [ ] **Step 1: зависимость**

В `packages/server/package.json` → `dependencies` добавить `"@pixeloffice/replay": "workspace:*"`, затем `pnpm install`.

- [ ] **Step 2: падающий тест `packages/server/tests/test-mode.test.ts`**

```ts
import type { AddressInfo } from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
import type { ServerMessage } from '@pixeloffice/protocol';
import { buildServer, renderScenarioHello } from '../src/index.ts';
import { demoOffice, makeRuntime } from './helpers.ts';

const office = demoOffice();
const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

describe('тестовый режим', () => {
  it('sit4: четыре человека сидят в четырёх направлениях; результат детерминирован', () => {
    const q = { scenario: 'sit4', t: '30000', seed: '1' };
    const h = renderScenarioHello(office, q);
    expect(h.test).toBe(true);
    const facings = Object.fromEntries(h.characters.map((c) => [c.id, [c.facing, c.pose]]));
    expect(facings).toEqual({ p1: ['down', 'sit'], p4: ['up', 'sit'], p7: ['right', 'sit'], p8: ['left', 'sit'] });
    expect(renderScenarioHello(office, q)).toEqual(h);
  });

  it('meeting9: девять человек в большой переговорке', () => {
    const h = renderScenarioHello(office, { scenario: 'meeting9', t: '60000', seed: '1' });
    const m2 = h.map.spots.filter((s) => s.zoneId === 'meeting:m2').map((s) => `${s.x},${s.y}`);
    const seated = h.characters.filter((c) => m2.includes(`${c.x},${c.y}`));
    expect(seated).toHaveLength(9);
  });

  it('неизвестный сценарий и t вне диапазона — ошибка', () => {
    expect(() => renderScenarioHello(office, { scenario: 'nope', t: '0' })).toThrow();
    expect(() => renderScenarioHello(office, { scenario: 'sit4', t: '-5' })).toThrow();
  });

  it('по WebSocket: один hello без дельт; POST /v1/events отсутствует', async () => {
    const { rt } = makeRuntime();
    const srv = await buildServer({
      runtime: rt,
      viewerTokens: ['demo-viewer-token'],
      viewerDist: null,
      assetsDir: null,
      ingest: false,
      testMode: (q) => renderScenarioHello(office, q),
    });
    await srv.app.listen({ port: 0, host: '127.0.0.1' });
    closers.push(() => srv.app.close());
    const port = (srv.app.server.address() as AddressInfo).port;
    const got: ServerMessage[] = [];
    const ws = new WebSocket(`ws://127.0.0.1:${port}/v1/ws?token=demo-viewer-token&scenario=sit4&t=30000&seed=1`);
    closers.push(async () => ws.close());
    ws.addEventListener('message', (e) => got.push(JSON.parse(String(e.data))));
    await new Promise((r) => setTimeout(r, 500));
    expect(got.map((m) => m.type)).toEqual(['hello']);
    const post = await fetch(`http://127.0.0.1:${port}/v1/events`, { method: 'POST', body: '{}', headers: { 'content-type': 'application/json' } });
    expect(post.status).toBe(404);
  });
});
```

Run: `pnpm vitest run packages/server/tests/test-mode.test.ts` → FAIL.

- [ ] **Step 3: `packages/server/src/test-mode.ts`**

```ts
import type { HelloMessage } from '@pixeloffice/protocol';
import { resolveScenarioSource, scenarios } from '@pixeloffice/replay';
import { ManualClock } from './clock.ts';
import { silentLogger } from './logger.ts';
import type { LoadedOffice } from './office.ts';
import { OfficeRuntime } from './runtime.ts';

const MAX_T = 3_600_000;

// Детерминированный кадр: сценарий на управляемых часах до момента t (спека 4.6).
export function renderScenarioHello(office: LoadedOffice, q: Record<string, string | undefined>): HelloMessage {
  const scenario = scenarios[q.scenario ?? ''];
  if (!scenario) throw new Error(`нет сценария «${q.scenario}»`);
  const tMs = Number(q.t ?? 0);
  const seed = Number(q.seed ?? 1);
  if (!Number.isFinite(tMs) || tMs < 0 || tMs > MAX_T) throw new Error(`t: от 0 до ${MAX_T} мс`);
  const clock = new ManualClock();
  const rt = new OfficeRuntime({ office, clock, log: silentLogger });
  const { sources, people } = office.bundle.config;
  const agentSrc = resolveScenarioSource(sources, 'agent');
  const humanSrc = resolveScenarioSource(sources, 'human');
  const events = scenario.build({ people: people.map((p) => p.id), owner: agentSrc?.owner ?? '', seed, baseTime: clock.now() });
  let i = 0;
  for (let t = 0; ; t += 50) {
    while (i < events.length && events[i]!.atMs <= t) {
      const e = events[i++]!;
      const src = e.source === 'agent' ? agentSrc : humanSrc;
      if (src) rt.ingestFromSource(src, [e.event], { log: false, relay: false });
    }
    if (t >= tMs) break;
    clock.advance(50);
    rt.step(50);
  }
  return rt.hello(true);
}
```

В `index.ts`: `export * from './test-mode.ts';`

- [ ] **Step 4: подключение в `main.ts`**

В вызове `buildServer` ветки `serve` заменить `testMode: null,` на:
```ts
    testMode: flags.test ? (q) => renderScenarioHello(office, q) : null,
```
Импорт: `import { renderScenarioHello } from './test-mode.ts';`.

- [ ] **Step 5: прогон, гейт, коммит**

```bash
pnpm vitest run packages/server   # PASS
pnpm gate
git add packages/server pnpm-lock.yaml
git commit -m "feat(server): тестовый режим с детерминированным hello по сценарию"
```

**Критерий готовности:** `sit4` даёт 4 направления сидения. `meeting9` сажает 9 человек в `meeting:m2`. По WebSocket приходит ровно один `hello`. В `--test` нет приёма событий.

---

## Этап M3. Зритель

### Задача 24: viewer — каркас, подключение, состояние и интерполяция

**Files:**
- Create: `packages/viewer/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts,vite.config.ts,index.html}`
- Create: `packages/viewer/src/{params.ts,state.ts,connection.ts,main.ts,global.d.ts}`
- Create: `packages/viewer/scripts/shot.ts`
- Test: `packages/viewer/tests/unit/{params.test.ts,state.test.ts,connection.test.ts}`
- Modify: `packages/core/package.json` (subpath `./characters`)

**Interfaces:**
- Consumes: типы `ServerMessage`, `HelloMessage`, `CharacterState`, `Bubble`, `EntityView`, `DebugMessage` (protocol).
- Produces:
  - `params.ts`: `type ViewerParams = { token: string | null; scenario: string | null; t: number | null; seed: number | null; test: boolean; debug: boolean }`, `readParams(search): ViewerParams`, `wsUrl(loc: { protocol: string; host: string }, p): string`, `backoffDelay(attempt): number` (500·2^n, не больше 15 000).
  - `state.ts`: `type CharView = { cur: CharacterState; prev: CharacterState | null; recvAt: number; bubble: Bubble | null }`, `type ViewerState = { hello: HelloMessage | null; entities: Map<string, EntityView>; chars: Map<string, CharView>; debug: DebugMessage | null; test: boolean; version: number }`, `createState()`, `applyMessage(s, m, now): { reset: boolean }`, `interpolated(s, now): (CharacterState & { bubble: Bubble | null })[]`, `PERIOD_MS = 100`.
  - `connection.ts`: `class Connection { constructor(o: ConnectionOptions); start(); stop() }` — переподключение с экспоненциальной задержкой. При `visibilitychange` → `visible` — новое соединение и новый `hello` (спека 4.6). В тестовом режиме переподключений нет.
  - `scripts/shot.ts`: `node packages/viewer/scripts/shot.ts <url> <out.png>` — headless-скриншот. Для URL со `scenario=` ждёт `window.__pixelofficeReady`, иначе 3 с.
  - `@pixeloffice/core/characters` — лёгкий импорт `frameRect` без zod и yaml.

- [ ] **Step 1: пакет**

`packages/viewer/package.json`:
```json
{
  "name": "@pixeloffice/viewer",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json",
    "test:visual": "playwright test"
  },
  "dependencies": {
    "@pixeloffice/core": "workspace:*",
    "@pixeloffice/protocol": "workspace:*"
  }
}
```

```bash
pnpm --filter @pixeloffice/viewer add pixi.js@latest pixi-viewport@latest @fontsource/press-start-2p@latest
pnpm --filter @pixeloffice/viewer add -D vite@latest @playwright/test@latest yaml@latest
pnpm --filter @pixeloffice/viewer exec playwright install chromium
```

`packages/viewer/tsconfig.json`:
```json
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024", "DOM", "DOM.Iterable"], "types": ["vite/client"] }, "include": ["src"] }
```
`packages/viewer/tsconfig.test.json`:
```json
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024", "DOM", "DOM.Iterable"], "types": ["node", "vite/client"] }, "include": ["src", "tests", "scripts", "playwright.config.ts"] }
```
`packages/viewer/vitest.config.ts`:
```ts
import { defineProject } from 'vitest/config';

// Только юнит-тесты чистой логики; Playwright-спеки в tests/visual запускает `pnpm test:visual`.
export default defineProject({ test: { name: 'viewer', include: ['tests/unit/**/*.test.ts'] } });
```
`packages/viewer/vite.config.ts`:
```ts
import { defineConfig } from 'vite';

export default defineConfig({
  build: { outDir: 'dist', assetsDir: 'app', emptyOutDir: true }, // /assets/ занят ассетами LimeZu (решение 15)
  server: {
    port: 5173,
    proxy: {
      '/v1': { target: 'http://127.0.0.1:4870', ws: true },
      '/assets': 'http://127.0.0.1:4870',
    },
  },
});
```
`packages/viewer/index.html`:
```html
<!doctype html>
<html lang="ru">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>PixelOffice</title>
    <style>
      html, body { margin: 0; height: 100%; overflow: hidden; background: #1b1b24; }
      #app { position: fixed; inset: 0; }
      #credit { position: fixed; right: 8px; bottom: 6px; font: 11px sans-serif; color: #9aa; }
      #credit a { color: #bcd; }
      #status { position: fixed; left: 8px; bottom: 6px; font: 11px sans-serif; color: #9aa; }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <div id="status"></div>
    <div id="credit">Art: LimeZu — <a href="https://limezu.itch.io" target="_blank" rel="noopener">limezu.itch.io</a></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
```

В `packages/core/package.json` поле `exports` заменить на:
```json
"exports": { ".": "./src/index.ts", "./characters": "./src/characters.ts" }
```

`packages/viewer/src/global.d.ts`:
```ts
// Флаг готовности кадра для скриншот-тестов (тестовый режим).
interface Window {
  __pixelofficeReady?: boolean;
}
```

- [ ] **Step 2: падающие тесты**

`packages/viewer/tests/unit/params.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { backoffDelay, readParams, wsUrl } from '../../src/params.ts';

describe('params', () => {
  it('тестовый режим из URL', () => {
    const p = readParams('?token=abc&scenario=sit4&t=30000&seed=2&debug=1');
    expect(p).toEqual({ token: 'abc', scenario: 'sit4', t: 30000, seed: 2, test: true, debug: true });
    expect(wsUrl({ protocol: 'https:', host: 'office.example' }, p)).toBe('wss://office.example/v1/ws?token=abc&scenario=sit4&t=30000&seed=2');
  });

  it('обычный режим', () => {
    const p = readParams('');
    expect(p.test).toBe(false);
    expect(wsUrl({ protocol: 'http:', host: 'localhost:5173' }, p)).toBe('ws://localhost:5173/v1/ws');
  });

  it('экспоненциальная задержка с потолком', () => {
    expect([0, 1, 2, 10].map(backoffDelay)).toEqual([500, 1000, 2000, 15_000]);
  });
});
```

`packages/viewer/tests/unit/state.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import type { CharacterState, HelloMessage } from '@pixeloffice/protocol';
import { applyMessage, createState, interpolated } from '../../src/state.ts';

const c = (id: string, x: number, y: number, extra: Partial<CharacterState> = {}): CharacterState => ({
  id, x, y, facing: 'down', pose: 'walk', anim: 'walk', offset: [0, 0], ...extra,
});
const hello = (chars: CharacterState[], test = false): HelloMessage => ({
  type: 'hello', protocol: 1, t: 0, test,
  map: { tileSize: 16, width: 2, height: 2, floor: [], sprites: [], spots: [], blocked: [], entrance: [0, 0] },
  characterLayout: { frameW: 16, frameH: 32, animations: { idle: { row: 1, frames: 6, dirs: {} }, walk: { row: 2, frames: 6, dirs: {} }, sit: { row: 4, frames: 6, dirs: {} } } },
  entities: [{ id: 'a', kind: 'human', name: 'A', label: 'A', layers: [] }],
  characters: chars,
});

describe('состояние зрителя', () => {
  it('hello сбрасывает состояние, облачко из hello', () => {
    const s = createState();
    expect(applyMessage(s, hello([c('a', 1, 1, { bubble: { text: 'hi', kind: 'info' } })]), 0).reset).toBe(true);
    expect(s.chars.get('a')!.bubble).toEqual({ text: 'hi', kind: 'info' });
    expect(s.entities.size).toBe(1);
  });

  it('облачко: нет поля — без изменений, null — убрать, объект — показать', () => {
    const s = createState();
    applyMessage(s, hello([c('a', 1, 1, { bubble: { text: 'hi', kind: 'info' } })]), 0);
    applyMessage(s, { type: 'delta', t: 100, characters: [c('a', 1, 1)] }, 100);
    expect(s.chars.get('a')!.bubble).toEqual({ text: 'hi', kind: 'info' });
    applyMessage(s, { type: 'delta', t: 200, characters: [c('a', 1, 1, { bubble: null })] }, 200);
    expect(s.chars.get('a')!.bubble).toBeNull();
  });

  it('интерполяция между дельтами; прыжок больше 2 клеток — без интерполяции', () => {
    const s = createState();
    applyMessage(s, hello([c('a', 0, 0)]), 0);
    applyMessage(s, { type: 'delta', t: 100, characters: [c('a', 1, 0)] }, 1000);
    expect(interpolated(s, 1050)[0]!.x).toBeCloseTo(0.5);
    expect(interpolated(s, 1200)[0]!.x).toBe(1);
    applyMessage(s, { type: 'delta', t: 200, characters: [c('a', 9, 9)] }, 2000);
    expect(interpolated(s, 2010)[0]!.x).toBe(9);
  });

  it('тестовый режим — без интерполяции', () => {
    const s = createState();
    applyMessage(s, hello([c('a', 3, 3)], true), 0);
    expect(interpolated(s, 0)[0]).toMatchObject({ x: 3, y: 3 });
    expect(s.test).toBe(true);
  });

  it('despawn, entity, entity_removed', () => {
    const s = createState();
    applyMessage(s, hello([c('a', 0, 0)]), 0);
    applyMessage(s, { type: 'entity', entity: { id: 'b', kind: 'agent', name: 'B', label: 'B', layers: [] } }, 0);
    expect(s.entities.has('b')).toBe(true);
    applyMessage(s, { type: 'despawn', id: 'a' }, 0);
    expect(s.chars.has('a')).toBe(false);
    applyMessage(s, { type: 'entity_removed', id: 'b' }, 0);
    expect(s.entities.has('b')).toBe(false);
  });
});
```

`packages/viewer/tests/unit/connection.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import type { ServerMessage } from '@pixeloffice/protocol';
import { Connection } from '../../src/connection.ts';

class FakeSocket {
  onopen: ((e: unknown) => void) | null = null;
  onmessage: ((e: { data: unknown }) => void) | null = null;
  onclose: ((e: unknown) => void) | null = null;
  closed = false;
  close() {
    this.closed = true;
    this.onclose?.({});
  }
}

function setup(test = false) {
  const sockets: FakeSocket[] = [];
  const timers: { fn: () => void; ms: number }[] = [];
  const listeners: (() => void)[] = [];
  const doc = { visibilityState: 'visible', addEventListener: (_t: 'visibilitychange', f: () => void) => void listeners.push(f) };
  const got: ServerMessage[] = [];
  const conn = new Connection({
    url: 'ws://x/v1/ws',
    test,
    onMessage: (m) => got.push(m),
    createSocket: () => {
      const s = new FakeSocket();
      sockets.push(s);
      return s;
    },
    schedule: (fn, ms) => timers.push({ fn, ms }),
    doc,
  });
  conn.start();
  return { conn, sockets, timers, listeners, got };
}

describe('Connection', () => {
  it('обрыв → переподключение 500, 1000 мс; hello сбрасывает счётчик', () => {
    const { sockets, timers } = setup();
    sockets[0]!.onclose?.({});
    expect(timers.at(-1)!.ms).toBe(500);
    timers.at(-1)!.fn();
    sockets[1]!.onclose?.({});
    expect(timers.at(-1)!.ms).toBe(1000);
    timers.at(-1)!.fn();
    sockets[2]!.onmessage?.({ data: JSON.stringify({ type: 'despawn', id: 'x' }) });
    sockets[2]!.onmessage?.({ data: JSON.stringify({ type: 'hello' }) });
    sockets[2]!.onclose?.({});
    expect(timers.at(-1)!.ms).toBe(500);
  });

  it('возврат вкладки — новое соединение', () => {
    const { sockets, listeners } = setup();
    listeners[0]!();
    expect(sockets).toHaveLength(2);
    expect(sockets[0]!.closed).toBe(true);
  });

  it('тестовый режим — без переподключений', () => {
    const { sockets, timers } = setup(true);
    sockets[0]!.onclose?.({});
    expect(timers).toHaveLength(0);
  });
});
```

Run: `pnpm vitest run packages/viewer` → FAIL.

- [ ] **Step 3: `packages/viewer/src/params.ts`**

```ts
export type ViewerParams = { token: string | null; scenario: string | null; t: number | null; seed: number | null; test: boolean; debug: boolean };

export function readParams(search: string): ViewerParams {
  const q = new URLSearchParams(search);
  const scenario = q.get('scenario');
  const num = (k: string) => (q.has(k) ? Number(q.get(k)) : null);
  return { token: q.get('token'), scenario, t: num('t'), seed: num('seed'), test: scenario !== null, debug: q.get('debug') === '1' };
}

export function wsUrl(loc: { protocol: string; host: string }, p: ViewerParams): string {
  const u = new URL('/v1/ws', `${loc.protocol === 'https:' ? 'wss' : 'ws'}://${loc.host}`);
  if (p.token) u.searchParams.set('token', p.token);
  if (p.scenario) {
    u.searchParams.set('scenario', p.scenario);
    u.searchParams.set('t', String(p.t ?? 0));
    u.searchParams.set('seed', String(p.seed ?? 1));
  }
  return u.toString();
}

export const backoffDelay = (attempt: number): number => Math.min(15_000, 500 * 2 ** attempt);
```

- [ ] **Step 4: `packages/viewer/src/state.ts`**

```ts
import type { Bubble, CharacterState, DebugMessage, EntityView, HelloMessage, ServerMessage } from '@pixeloffice/protocol';

export type CharView = { cur: CharacterState; prev: CharacterState | null; recvAt: number; bubble: Bubble | null };
export type ViewerState = {
  hello: HelloMessage | null;
  entities: Map<string, EntityView>;
  chars: Map<string, CharView>;
  debug: DebugMessage | null;
  test: boolean;
  version: number;
};

export const PERIOD_MS = 100; // дельты 10 раз в секунду

export const createState = (): ViewerState => ({ hello: null, entities: new Map(), chars: new Map(), debug: null, test: false, version: 0 });

const strip = (c: CharacterState): CharacterState => {
  const { bubble: _bubble, ...rest } = c;
  return rest;
};

function at(v: CharView, now: number): CharacterState {
  if (!v.prev) return v.cur;
  if (Math.abs(v.cur.x - v.prev.x) + Math.abs(v.cur.y - v.prev.y) > 2) return v.cur;
  const k = Math.min(1, Math.max(0, (now - v.recvAt) / PERIOD_MS));
  return { ...v.cur, x: v.prev.x + (v.cur.x - v.prev.x) * k, y: v.prev.y + (v.cur.y - v.prev.y) * k };
}

export function applyMessage(s: ViewerState, m: ServerMessage, now: number): { reset: boolean } {
  switch (m.type) {
    case 'hello':
      s.hello = m;
      s.test = m.test;
      s.version++;
      s.entities = new Map(m.entities.map((e) => [e.id, e]));
      s.chars = new Map(m.characters.map((c) => [c.id, { cur: strip(c), prev: null, recvAt: now, bubble: c.bubble ?? null }]));
      s.debug = null;
      return { reset: true };
    case 'delta':
      for (const c of m.characters) {
        const old = s.chars.get(c.id);
        const bubble = 'bubble' in c ? (c.bubble ?? null) : (old?.bubble ?? null);
        s.chars.set(c.id, { cur: strip(c), prev: old ? at(old, now) : null, recvAt: now, bubble });
      }
      return { reset: false };
    case 'despawn':
      s.chars.delete(m.id);
      return { reset: false };
    case 'entity':
      s.entities.set(m.entity.id, m.entity);
      return { reset: false };
    case 'entity_removed':
      s.entities.delete(m.id);
      s.chars.delete(m.id);
      return { reset: false };
    case 'debug':
      s.debug = m;
      return { reset: false };
  }
}

export function interpolated(s: ViewerState, now: number): (CharacterState & { bubble: Bubble | null })[] {
  return [...s.chars.values()].map((v) => ({ ...(s.test ? v.cur : at(v, now)), bubble: v.bubble }));
}
```

- [ ] **Step 5: `packages/viewer/src/connection.ts`**

```ts
import type { ServerMessage } from '@pixeloffice/protocol';
import { backoffDelay } from './params.ts';

type WsLike = {
  onopen: ((e: unknown) => void) | null;
  onmessage: ((e: { data: unknown }) => void) | null;
  onclose: ((e: unknown) => void) | null;
  close(): void;
};
export type ConnectionOptions = {
  url: string;
  test: boolean;
  onMessage(m: ServerMessage): void;
  onStatus?(s: 'connecting' | 'open' | 'closed'): void;
  createSocket?: (url: string) => WsLike;
  schedule?: (fn: () => void, ms: number) => unknown;
  doc?: { visibilityState: string; addEventListener(type: 'visibilitychange', fn: () => void): void };
};

// Переподключение с экспоненциальной задержкой; возврат вкладки — новый hello (спека 4.6).
export class Connection {
  private readonly o: ConnectionOptions;
  private ws: WsLike | null = null;
  private attempt = 0;
  private stopped = false;

  constructor(o: ConnectionOptions) {
    this.o = o;
  }

  start(): void {
    this.open();
    this.o.doc?.addEventListener('visibilitychange', () => {
      if (this.o.doc?.visibilityState === 'visible' && !this.o.test && !this.stopped) this.reconnectNow();
    });
  }

  stop(): void {
    this.stopped = true;
    this.ws?.close();
  }

  private open(): void {
    const create = this.o.createSocket ?? ((u: string) => new WebSocket(u) as unknown as WsLike);
    const ws = create(this.o.url);
    this.ws = ws;
    this.o.onStatus?.('connecting');
    ws.onopen = () => this.o.onStatus?.('open');
    ws.onmessage = (e) => {
      const m = JSON.parse(String(e.data)) as ServerMessage;
      if (m.type === 'hello') this.attempt = 0;
      this.o.onMessage(m);
    };
    ws.onclose = () => {
      if (this.ws !== ws) return; // закрыто намеренно при переподключении
      this.ws = null;
      this.o.onStatus?.('closed');
      if (this.stopped || this.o.test) return;
      const delay = backoffDelay(this.attempt++);
      (this.o.schedule ?? setTimeout)(() => {
        if (!this.stopped && !this.ws) this.open();
      }, delay);
    };
  }

  private reconnectNow(): void {
    const old = this.ws;
    this.ws = null;
    old?.close();
    this.attempt = 0;
    this.open();
  }
}
```

- [ ] **Step 6: `packages/viewer/src/main.ts` (первая версия) и `scripts/shot.ts`**

```ts
import { Connection } from './connection.ts';
import { readParams, wsUrl } from './params.ts';
import { applyMessage, createState } from './state.ts';

// Первая версия: подключение и статус. Рендер — задачи 25–27.
const params = readParams(location.search);
const state = createState();
const status = document.getElementById('status')!;

async function main() {
  if (params.token) {
    await fetch(`/v1/session?token=${encodeURIComponent(params.token)}`); // cookie для /assets в dev через прокси
    if (!params.test) history.replaceState(null, '', location.pathname);
  }
  new Connection({
    url: wsUrl(location, params),
    test: params.test,
    doc: document,
    onStatus: (s) => (status.textContent = s === 'open' ? '' : s === 'connecting' ? 'подключение…' : 'нет связи'),
    onMessage: (m) => {
      applyMessage(state, m, performance.now());
      if (m.type === 'hello') status.textContent = `офис ${m.map.width}×${m.map.height}, персонажей: ${m.characters.length}`;
    },
  }).start();
}

main().catch((e) => (status.textContent = String(e)));
```

`packages/viewer/scripts/shot.ts`:
```ts
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { chromium } from '@playwright/test';

// node packages/viewer/scripts/shot.ts <url> <out.png> — скриншот headless-браузером для визуальной проверки.
const [url, out] = process.argv.slice(2);
if (!url || !out) {
  console.error('использование: node packages/viewer/scripts/shot.ts <url> <out.png>');
  process.exit(2);
}
mkdirSync(dirname(out), { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 });
page.on('console', (m) => console.log(`[browser] ${m.type()}: ${m.text()}`));
await page.goto(url);
if (url.includes('scenario=')) {
  await page.waitForFunction(() => window.__pixelofficeReady === true, null, { timeout: 30_000 });
} else {
  await page.waitForTimeout(3000);
}
await page.screenshot({ path: out });
await browser.close();
console.log(`скриншот: ${out}`);
```

- [ ] **Step 7: прогон, сборка, гейт, коммит**

```bash
pnpm install
pnpm vitest run packages/viewer        # PASS
pnpm --filter @pixeloffice/viewer build # dist/index.html, dist/app/*.js
pnpm gate
git add packages/viewer packages/core/package.json pnpm-lock.yaml
git commit -m "feat(viewer): каркас зрителя — подключение, состояние и интерполяция"
```

**Критерий готовности:** юнит-тесты params/state/connection зелёные. Viewer собирается в `dist/` (бандл в `dist/app/`).

---

### Задача 25: viewer — рендер офиса (пол, предметы, сортировка, pan/zoom)

**Files:**
- Create: `packages/viewer/src/render/scene.ts`, `packages/viewer/src/render/office.ts`
- Modify: `packages/viewer/src/main.ts`
- Create (вне git): `docs/spikes/m3/office.png`

**Interfaces:**
- Consumes: `RenderedMap`, `Frame` (protocol); `ViewerState`, `applyMessage`, `Connection`, `readParams`, `wsUrl`.
- Produces:
  - `scene.ts`: `type Bounds = { minX; minY; maxX; maxY }`, `type Scene = { app: Application; viewport: Viewport; floor: Container; sorted: Container; debug: Container; overlay: Container; fit(b: Bounds): void; zoom(): number; onZoom(cb: (scale: number) => void): void }`, `createScene(host: HTMLElement): Promise<Scene>`. Масштаб только целочисленный, `nearest`, pan/zoom мышью и пальцами, при открытии карта вписывается в окно (спека 7).
  - `office.ts`: `frameTexture(f: Frame): Promise<Texture>` (кэш листов), `buildOffice(map, scene): Promise<Bounds>` — пол в `floor`, части предметов и стен в `sorted` (`zIndex = sortY`, `label = 'office'`).

- [ ] **Step 1: `packages/viewer/src/render/scene.ts`**

```ts
import { Application, Container, TextureSource } from 'pixi.js';
import { Viewport } from 'pixi-viewport';

export type Bounds = { minX: number; minY: number; maxX: number; maxY: number };
export type Scene = {
  app: Application;
  viewport: Viewport;
  floor: Container;
  sorted: Container;
  debug: Container;
  overlay: Container;
  fit(b: Bounds): void;
  zoom(): number;
  onZoom(cb: (scale: number) => void): void;
};

export async function createScene(host: HTMLElement): Promise<Scene> {
  TextureSource.defaultOptions.scaleMode = 'nearest'; // пиксель-арт без размытия
  const app = new Application();
  await app.init({ background: '#1b1b24', resizeTo: window, antialias: false, roundPixels: true, resolution: 1 });
  host.appendChild(app.canvas);

  const viewport = new Viewport({
    screenWidth: window.innerWidth,
    screenHeight: window.innerHeight,
    worldWidth: 256,
    worldHeight: 256,
    events: app.renderer.events,
  });
  app.stage.addChild(viewport);
  viewport.drag().pinch().wheel().clampZoom({ minScale: 1, maxScale: 8 });

  const floor = new Container();
  const sorted = new Container();
  sorted.sortableChildren = true; // спека 5.6: всё выше пола — по sortY
  const debug = new Container();
  debug.visible = false;
  const overlay = new Container(); // подписи и облачка
  viewport.addChild(floor, sorted, debug, overlay);

  const zoomCbs: ((s: number) => void)[] = [];
  const emit = () => zoomCbs.forEach((cb) => cb(viewport.scale.x));
  // Только целочисленный масштаб (спека 7).
  viewport.on('zoomed-end', () => {
    const s = Math.max(1, Math.round(viewport.scale.x));
    if (s !== viewport.scale.x) viewport.setZoom(s, true);
    emit();
  });

  let bounds: Bounds = { minX: 0, minY: 0, maxX: 256, maxY: 256 };
  const fit = (b: Bounds) => {
    bounds = b;
    const w = b.maxX - b.minX;
    const h = b.maxY - b.minY;
    viewport.resize(window.innerWidth, window.innerHeight, w, h);
    const s = Math.max(1, Math.floor(Math.min(window.innerWidth / w, (window.innerHeight - 24) / h)));
    viewport.setZoom(s, true);
    viewport.moveCenter((b.minX + b.maxX) / 2, (b.minY + b.maxY) / 2);
    emit();
  };
  window.addEventListener('resize', () => fit(bounds));

  return { app, viewport, floor, sorted, debug, overlay, fit, zoom: () => viewport.scale.x, onZoom: (cb) => zoomCbs.push(cb) };
}
```

- [ ] **Step 2: `packages/viewer/src/render/office.ts`**

```ts
import { Assets, Rectangle, Sprite, Texture } from 'pixi.js';
import type { Frame, RenderedMap } from '@pixeloffice/protocol';
import type { Bounds, Scene } from './scene.ts';

const sheets = new Map<string, Promise<Texture>>();

function sheet(url: string): Promise<Texture> {
  let p = sheets.get(url);
  if (!p) {
    p = Assets.load<Texture>(url);
    sheets.set(url, p);
  }
  return p;
}

export async function frameTexture(f: Frame): Promise<Texture> {
  const base = await sheet(f.sheet);
  return new Texture({ source: base.source, frame: new Rectangle(f.x, f.y, f.w, f.h) });
}

// Пол — отдельный слой; части предметов и стен — в общем сортируемом слое (спека 5.6).
export async function buildOffice(map: RenderedMap, scene: Scene): Promise<Bounds> {
  scene.floor.removeChildren().forEach((c) => c.destroy());
  for (const c of [...scene.sorted.children]) if (c.label === 'office') c.destroy();
  const ts = map.tileSize;
  const b: Bounds = { minX: 0, minY: 0, maxX: map.width * ts, maxY: map.height * ts };
  for (const t of map.floor) {
    const s = new Sprite(await frameTexture(t.frame));
    s.position.set(t.x * ts, t.y * ts);
    scene.floor.addChild(s);
  }
  for (const sp of map.sprites) {
    const s = new Sprite(await frameTexture(sp.frame));
    s.position.set(sp.px, sp.py);
    s.zIndex = sp.sortY;
    s.label = 'office';
    scene.sorted.addChild(s);
    b.minX = Math.min(b.minX, sp.px);
    b.minY = Math.min(b.minY, sp.py);
    b.maxX = Math.max(b.maxX, sp.px + sp.frame.w);
    b.maxY = Math.max(b.maxY, sp.py + sp.frame.h);
  }
  return b;
}
```

- [ ] **Step 3: `packages/viewer/src/main.ts` (версия с офисом — заменить файл)**

```ts
import { Connection } from './connection.ts';
import { readParams, wsUrl } from './params.ts';
import { buildOffice } from './render/office.ts';
import { createScene } from './render/scene.ts';
import { applyMessage, createState } from './state.ts';

const params = readParams(location.search);
const state = createState();
const status = document.getElementById('status')!;

async function main() {
  if (params.token) {
    await fetch(`/v1/session?token=${encodeURIComponent(params.token)}`);
    if (!params.test) history.replaceState(null, '', location.pathname);
  }
  const scene = await createScene(document.getElementById('app')!);
  new Connection({
    url: wsUrl(location, params),
    test: params.test,
    doc: document,
    onStatus: (s) => (status.textContent = s === 'open' ? '' : s === 'connecting' ? 'подключение…' : 'нет связи'),
    onMessage: (m) => {
      const { reset } = applyMessage(state, m, performance.now());
      if (reset && state.hello) {
        void buildOffice(state.hello.map, scene).then((b) => {
          scene.fit(b);
          if (params.test) requestAnimationFrame(() => requestAnimationFrame(() => (window.__pixelofficeReady = true)));
        });
      }
    },
  }).start();
}

main().catch((e) => (status.textContent = String(e)));
```

- [ ] **Step 4: скриншот и просмотр**

```bash
pnpm --filter @pixeloffice/viewer build
node packages/server/src/main.ts serve offices/demo --test --port 4871 &     # фоном
SRV=$!
curl -sf -o /dev/null --noproxy '*' --retry 30 --retry-delay 1 --retry-connrefused http://127.0.0.1:4871/healthz   # ждать готовности
node packages/viewer/scripts/shot.ts "http://127.0.0.1:4871/?token=demo-viewer-token&scenario=sit4&t=0&seed=1" docs/spikes/m3/office.png
kill $SRV
```
Открыть `docs/spikes/m3/office.png` (Read tool). Критерии:
1. Офис demo целиком вписан в окно, масштаб целый (пиксели квадратные и чёткие).
2. Стены с углами и проёмом входа внизу, лицевая сторона стен над верхним рядом не обрезана.
3. Столы, кресла 4 направлений, переговорные столы, доски, аркады, диван, фикус — на своих клетках. Спинки кресел `^` перекрывают сиденье, кресла `v` стоят за столами.
4. Полы зон (лаунж, переговорки) отличаются от ковра.
5. В консоли браузера нет ошибок загрузки PNG.

Не так — чинить каталог (`rect`, `at`, `sortY`) или `buildOffice`, повторить скриншот.

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

```bash
pnpm gate
git add packages/viewer
git commit -m "feat(viewer): рендер офиса с сортировкой по sortY и целочисленным масштабом"
```

**Критерий готовности:** скриншот `docs/spikes/m3/office.png` просмотрен и выполняет критерии 1–5.

---

### Задача 26: viewer — персонажи, подписи, кредит

**Files:**
- Create: `packages/viewer/src/render/{font.ts,characters.ts,labels.ts,view.ts}`
- Modify: `packages/viewer/src/main.ts`
- Create (вне git): `docs/spikes/m3/sit4.png`, `docs/spikes/m3/morning.png`

**Interfaces:**
- Consumes: `frameRect` из `@pixeloffice/core/characters`; `CharacterLayout`, `CharacterState`, `EntityView` (protocol); `Scene`, `buildOffice`; `ViewerState`, `interpolated`.
- Produces:
  - `font.ts`: `FONT = 'pixel'`, `installPixelFont(): Promise<void>` (Press Start 2P 8 px в `BitmapFont`, кириллица включена).
  - `characters.ts`: `avatarTexture(layers: string[]): Promise<Texture>` — слои в одну текстуру, кэш по набору (спека 7); `class CharacterSprite { readonly sprite: Sprite; constructor(entity: EntityView, layout: CharacterLayout); ready: Promise<void>; update(c: CharacterState, ts: number, frame: number): void }`; `animFrame(c, nowMs, test): number` — в тестовом режиме 0, при ходьбе — смена кадра каждые 100 мс, в позах — 0.
  - `labels.ts`: `makeLabel(text): Container` — подпись мелким пиксельным шрифтом на полупрозрачной подложке, якорь по центру сверху.
  - `view.ts`: `class OfficeView { constructor(scene); rebuild(state): Promise<void>; update(state, now): void; ready(): Promise<void> }` — персонажи и подписи. Задача 27 заменит файл целиком на версию с облачками и отладкой.

Подпись: имя человека; у агента `хозяин · проект` (спека 7, уже лежит в `EntityView.label`). Подписи живут в `overlay`, их масштаб `1/zoom`: на экране постоянно 8 px (решение 16).

- [ ] **Step 1: `packages/viewer/src/render/font.ts`**

```ts
import '@fontsource/press-start-2p/400.css';
import { BitmapFont } from 'pixi.js';

export const FONT = 'pixel';

// Пиксельный шрифт с кириллицей (решение 16). textureStyle nearest — чёткие глифы.
export async function installPixelFont(): Promise<void> {
  await document.fonts.load('8px "Press Start 2P"', 'AzАяЁё·?');
  BitmapFont.install({
    name: FONT,
    style: { fontFamily: 'Press Start 2P', fontSize: 8, fill: 0xffffff },
    chars: [['a', 'z'], ['A', 'Z'], ['0', '9'], ['а', 'я'], ['А', 'Я'], ' ёЁ.,:;!?·-–—_()[]{}/\\\'"%+=*&#@<>«»…|~'],
    resolution: 1,
    textureStyle: { scaleMode: 'nearest' },
  });
}
```
Если `textureStyle` нет в типах установленной версии Pixi — убрать опцию: глобальный `TextureSource.defaultOptions.scaleMode = 'nearest'` из `createScene` уже действует (сцену создавать до установки шрифта).

- [ ] **Step 2: `packages/viewer/src/render/characters.ts`**

```ts
import { Rectangle, Sprite, Texture } from 'pixi.js';
import { frameRect } from '@pixeloffice/core/characters';
import type { CharacterLayout, CharacterState, EntityView } from '@pixeloffice/protocol';

const composites = new Map<string, Promise<Texture>>();

async function loadImage(url: string): Promise<HTMLImageElement | null> {
  const img = new Image();
  img.src = url;
  try {
    await img.decode();
    return img;
  } catch {
    console.warn(`слой персонажа не загрузился: ${url}`);
    return null;
  }
}

// Слои генератора (тело → глаза → одежда → причёска → аксессуар) в одну текстуру, кэш по набору (спека 7).
export function avatarTexture(layers: string[]): Promise<Texture> {
  const key = layers.join('|');
  let p = composites.get(key);
  if (!p) {
    p = (async () => {
      const imgs = (await Promise.all(layers.map(loadImage))).filter((i): i is HTMLImageElement => i !== null);
      const canvas = document.createElement('canvas');
      canvas.width = Math.max(1, ...imgs.map((i) => i.naturalWidth));
      canvas.height = Math.max(1, ...imgs.map((i) => i.naturalHeight));
      const ctx = canvas.getContext('2d')!;
      ctx.imageSmoothingEnabled = false;
      for (const img of imgs) ctx.drawImage(img, 0, 0);
      return Texture.from(canvas);
    })();
    composites.set(key, p);
  }
  return p;
}

export const animFrame = (c: CharacterState, nowMs: number, test: boolean): number => (test || c.pose !== 'walk' ? 0 : Math.floor(nowMs / 100));

export class CharacterSprite {
  readonly sprite = new Sprite();
  readonly ready: Promise<void>;
  private readonly layout: CharacterLayout;
  private base: Texture | null = null;
  private readonly frames = new Map<string, Texture>();

  constructor(entity: EntityView, layout: CharacterLayout) {
    this.layout = layout;
    this.sprite.label = 'char';
    this.ready = avatarTexture(entity.layers).then((t) => {
      this.base = t;
    });
  }

  // Ноги на нижней кромке клетки, сдвиг места (offset) поверх; сортировка по линии ног (спека 5.6).
  update(c: CharacterState, ts: number, frame: number): void {
    if (this.base) {
      const key = `${c.anim}:${c.facing}:${frame % this.layout.animations[c.anim].frames}`;
      let tex = this.frames.get(key);
      if (!tex) {
        const r = frameRect(this.layout, c.anim, c.facing, frame);
        tex = new Texture({ source: this.base.source, frame: new Rectangle(r.x, r.y, r.w, r.h) });
        this.frames.set(key, tex);
      }
      this.sprite.texture = tex;
    }
    this.sprite.position.set(Math.round(c.x * ts + c.offset[0]), Math.round((c.y + 1) * ts - this.layout.frameH + c.offset[1]));
    this.sprite.zIndex = (c.y + 1) * ts;
  }
}
```

- [ ] **Step 3: `packages/viewer/src/render/labels.ts`**

```ts
import { BitmapText, Container, Graphics } from 'pixi.js';
import { FONT } from './font.ts';

export function makeLabel(text: string): Container {
  const c = new Container();
  const t = new BitmapText({ text, style: { fontFamily: FONT, fontSize: 8, fill: 0xffffff } });
  const bg = new Graphics().rect(-2, -1, Math.ceil(t.width) + 4, Math.ceil(t.height) + 2).fill({ color: 0x000000, alpha: 0.55 });
  c.addChild(bg, t);
  c.pivot.set(Math.round(t.width / 2), 0);
  return c;
}
```

- [ ] **Step 4: `packages/viewer/src/render/view.ts`**

```ts
import type { Container } from 'pixi.js';
import { CharacterSprite, animFrame } from './characters.ts';
import { makeLabel } from './labels.ts';
import { buildOffice } from './office.ts';
import type { Scene } from './scene.ts';
import { interpolated, type ViewerState } from '../state.ts';

type Item = { char: CharacterSprite; label: Container };

// Персонажи и подписи поверх офиса. Логики мира нет — только отрисовка состояния (спека 3).
export class OfficeView {
  private readonly scene: Scene;
  private readonly items = new Map<string, Item>();

  constructor(scene: Scene) {
    this.scene = scene;
  }

  async rebuild(state: ViewerState): Promise<void> {
    for (const id of [...this.items.keys()]) this.drop(id);
    if (!state.hello) return;
    this.scene.fit(await buildOffice(state.hello.map, this.scene));
    this.update(state, performance.now());
  }

  ready(): Promise<void> {
    return Promise.all([...this.items.values()].map((i) => i.char.ready)).then(() => undefined);
  }

  update(state: ViewerState, now: number): void {
    const hello = state.hello;
    if (!hello) return;
    const ts = hello.map.tileSize;
    const inv = 1 / this.scene.zoom();
    const seen = new Set<string>();
    for (const c of interpolated(state, now)) {
      const entity = state.entities.get(c.id);
      if (!entity) continue;
      seen.add(c.id);
      let item = this.items.get(c.id);
      if (!item) {
        item = { char: new CharacterSprite(entity, hello.characterLayout), label: makeLabel(entity.label) };
        this.scene.sorted.addChild(item.char.sprite);
        this.scene.overlay.addChild(item.label);
        this.items.set(c.id, item);
      }
      item.char.update(c, ts, animFrame(c, now, state.test));
      item.label.position.set((c.x + 0.5) * ts + c.offset[0], (c.y + 1) * ts + 1);
      item.label.scale.set(inv);
    }
    for (const id of [...this.items.keys()]) if (!seen.has(id)) this.drop(id);
  }

  private drop(id: string): void {
    const item = this.items.get(id);
    if (!item) return;
    item.char.sprite.destroy();
    item.label.destroy({ children: true });
    this.items.delete(id);
  }
}
```

- [ ] **Step 5: `packages/viewer/src/main.ts` (заменить файл)**

```ts
import { Connection } from './connection.ts';
import { readParams, wsUrl } from './params.ts';
import { installPixelFont } from './render/font.ts';
import { createScene } from './render/scene.ts';
import { OfficeView } from './render/view.ts';
import { applyMessage, createState } from './state.ts';

const params = readParams(location.search);
const state = createState();
const status = document.getElementById('status')!;

async function main() {
  if (params.token) {
    await fetch(`/v1/session?token=${encodeURIComponent(params.token)}`);
    if (!params.test) history.replaceState(null, '', location.pathname);
  }
  const scene = await createScene(document.getElementById('app')!);
  await installPixelFont();
  const view = new OfficeView(scene);
  new Connection({
    url: wsUrl(location, params),
    test: params.test,
    doc: document,
    onStatus: (s) => (status.textContent = s === 'open' ? '' : s === 'connecting' ? 'подключение…' : 'нет связи'),
    onMessage: (m) => {
      const { reset } = applyMessage(state, m, performance.now());
      if (!reset) return;
      void view.rebuild(state).then(async () => {
        if (!params.test) return;
        await view.ready();
        view.update(state, 0);
        requestAnimationFrame(() => requestAnimationFrame(() => (window.__pixelofficeReady = true)));
      });
    },
  }).start();
  scene.app.ticker.add(() => view.update(state, performance.now()));
}

main().catch((e) => (status.textContent = String(e)));
```

- [ ] **Step 6: скриншоты и просмотр**

```bash
pnpm --filter @pixeloffice/viewer build
node packages/server/src/main.ts serve offices/demo --test --port 4871 &
SRV=$!
curl -sf -o /dev/null --noproxy '*' --retry 30 --retry-delay 1 --retry-connrefused http://127.0.0.1:4871/healthz   # ждать готовности
node packages/viewer/scripts/shot.ts "http://127.0.0.1:4871/?token=demo-viewer-token&scenario=sit4&t=30000&seed=1" docs/spikes/m3/sit4.png
node packages/viewer/scripts/shot.ts "http://127.0.0.1:4871/?token=demo-viewer-token&scenario=morning&t=60000&seed=1" docs/spikes/m3/morning.png
kill $SRV
```
Открыть оба PNG. Критерии:
1. `sit4`: четыре человека сидят — p1 лицом вниз (стол перекрывает ноги), p4 спиной (спинка кресла поверх), p7 боком вправо, p8 боком влево. Сдвиги `offset` выглядят естественно: человек «в кресле», а не над ним.
2. `morning`: девять человек на своих местах, два агента Анны в её углу или коворкинге.
3. Подписи под ногами читаемы, кириллица не битая; у агентов — «Анна · demo».
4. В правом нижнем углу кредит «Art: LimeZu — limezu.itch.io».

Не так — править `offset` в каталоге, позиционирование в `CharacterSprite.update` или подписи, повторить.

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

```bash
pnpm gate
git add packages/viewer
git commit -m "feat(viewer): персонажи из слоёв генератора, подписи пиксельным шрифтом, кредит LimeZu"
```

**Критерий готовности:** скриншоты `sit4.png` и `morning.png` просмотрены и выполняют критерии 1–4.

---

### Задача 27: viewer — облачка и отладочный слой

**Files:**
- Create: `packages/viewer/src/render/bubbles.ts`, `packages/viewer/src/render/debug.ts`
- Modify: `packages/viewer/src/render/view.ts` (заменить целиком), `packages/viewer/src/main.ts`
- Create (вне git): `docs/spikes/m3/bubble.png`, `docs/spikes/m3/debug.png`

**Interfaces:**
- Consumes: `Bubble`, `DebugMessage`, `RenderedMap`, `CharacterState` (protocol); `FONT`; `OfficeView` (задача 26).
- Produces:
  - `bubbles.ts`: `makeBubble(b: Bubble): Container` — облачко-комикс: пиксельный шрифт, перенос строк, ширина не больше 128 px, текст не длиннее 140 символов. У `needs_input` — «?» в начале и жёлтый фон. Якорь — кончик хвоста.
  - `debug.ts`: `drawDebug(g: Graphics, map: RenderedMap, dbg: DebugMessage | null, chars: CharacterState[]): void` — сетка, блоки, места по позам, вход, брони (заливка места), пути.
  - `OfficeView` (новая версия): облачки поверх персонажей (`overlay`, масштаб `1/zoom`), `toggleDebug()`, `setDebug(on)`. Облачко исчезает, когда в состоянии `bubble: null` (спека 7).

- [ ] **Step 1: `packages/viewer/src/render/bubbles.ts`**

```ts
import { BitmapText, Container, Graphics } from 'pixi.js';
import type { Bubble } from '@pixeloffice/protocol';
import { FONT } from './font.ts';

const MAX_W = 128;
const MAX_CHARS = 140;

// Облачко как в комиксе (спека 7): у needs_input — «?» и текст запроса.
export function makeBubble(b: Bubble): Container {
  const body = b.text.length > MAX_CHARS ? b.text.slice(0, MAX_CHARS - 1) + '…' : b.text;
  const text = b.kind === 'needs_input' ? `? ${body}` : body;
  const t = new BitmapText({ text, style: { fontFamily: FONT, fontSize: 8, fill: 0x1b1b24, wordWrap: true, wordWrapWidth: MAX_W, breakWords: true } });
  const pad = 4;
  const w = Math.ceil(t.width) + pad * 2;
  const h = Math.ceil(t.height) + pad * 2;
  const fill = b.kind === 'needs_input' ? 0xfff1b8 : 0xffffff;
  const g = new Graphics()
    .roundRect(-w / 2, -h - 5, w, h, 3)
    .fill(fill)
    .stroke({ color: 0x1b1b24, width: 1 })
    .poly([-3, -6, 3, -6, 0, 0])
    .fill(fill)
    .stroke({ color: 0x1b1b24, width: 1 });
  t.position.set(Math.round(-w / 2 + pad), Math.round(-h - 5 + pad));
  const c = new Container();
  c.addChild(g, t);
  return c;
}
```

- [ ] **Step 2: `packages/viewer/src/render/debug.ts`**

```ts
import type { Graphics } from 'pixi.js';
import type { CharacterState, DebugMessage, RenderedMap } from '@pixeloffice/protocol';

const POSE_COLOR = { sit: 0x3fa7ff, stand: 0xffd23f, play: 0x6fdc6f } as const;

// Отладочный слой по клавише D (спека 7): сетка, места, пути, брони.
export function drawDebug(g: Graphics, map: RenderedMap, dbg: DebugMessage | null, chars: CharacterState[]): void {
  const ts = map.tileSize;
  g.clear();
  for (let x = 0; x <= map.width; x++) g.moveTo(x * ts, 0).lineTo(x * ts, map.height * ts);
  for (let y = 0; y <= map.height; y++) g.moveTo(0, y * ts).lineTo(map.width * ts, y * ts);
  g.stroke({ color: 0xffffff, alpha: 0.15, width: 0.5 });
  for (const [x, y] of map.blocked) g.rect(x * ts, y * ts, ts, ts);
  g.fill({ color: 0xff3b3b, alpha: 0.18 });
  g.rect(map.entrance[0] * ts, map.entrance[1] * ts, ts, ts).fill({ color: 0xff00ff, alpha: 0.4 });
  const reserved = new Set(Object.keys(dbg?.reservations ?? {}));
  for (const s of map.spots) {
    g.rect(s.x * ts + 1, s.y * ts + 1, ts - 2, ts - 2);
    if (reserved.has(s.id)) g.fill({ color: POSE_COLOR[s.pose], alpha: 0.35 });
    g.stroke({ color: POSE_COLOR[s.pose], width: 1 });
  }
  for (const [id, path] of Object.entries(dbg?.paths ?? {})) {
    const c = chars.find((ch) => ch.id === id);
    if (!c || path.length === 0) continue;
    g.moveTo((c.x + 0.5) * ts, (c.y + 0.5) * ts);
    for (const [x, y] of path) g.lineTo((x + 0.5) * ts, (y + 0.5) * ts);
    g.stroke({ color: 0xff66cc, width: 1 });
  }
}
```

- [ ] **Step 3: `packages/viewer/src/render/view.ts` — новая версия (заменить файл)**

```ts
import { Graphics, type Container } from 'pixi.js';
import type { Bubble } from '@pixeloffice/protocol';
import { makeBubble } from './bubbles.ts';
import { CharacterSprite, animFrame } from './characters.ts';
import { drawDebug } from './debug.ts';
import { makeLabel } from './labels.ts';
import { buildOffice } from './office.ts';
import type { Scene } from './scene.ts';
import { interpolated, type ViewerState } from '../state.ts';

type Item = { char: CharacterSprite; label: Container; bubble: Container | null; bubbleKey: string | null };
const bubbleKey = (b: Bubble | null) => (b ? `${b.kind}|${b.text}` : null);

// Персонажи, подписи, облачка и отладочный слой. Логики мира нет (спека 3).
export class OfficeView {
  private readonly scene: Scene;
  private readonly items = new Map<string, Item>();
  private readonly debugGfx = new Graphics();
  private debugOn = false;

  constructor(scene: Scene) {
    this.scene = scene;
    scene.debug.addChild(this.debugGfx);
  }

  async rebuild(state: ViewerState): Promise<void> {
    for (const id of [...this.items.keys()]) this.drop(id);
    if (!state.hello) return;
    this.scene.fit(await buildOffice(state.hello.map, this.scene));
    this.update(state, performance.now());
  }

  ready(): Promise<void> {
    return Promise.all([...this.items.values()].map((i) => i.char.ready)).then(() => undefined);
  }

  setDebug(on: boolean): void {
    this.debugOn = on;
    this.scene.debug.visible = on;
  }

  toggleDebug(): void {
    this.setDebug(!this.debugOn);
  }

  update(state: ViewerState, now: number): void {
    const hello = state.hello;
    if (!hello) return;
    const ts = hello.map.tileSize;
    const fh = hello.characterLayout.frameH;
    const inv = 1 / this.scene.zoom();
    const seen = new Set<string>();
    const chars = interpolated(state, now);
    for (const c of chars) {
      const entity = state.entities.get(c.id);
      if (!entity) continue;
      seen.add(c.id);
      let item = this.items.get(c.id);
      if (!item) {
        item = { char: new CharacterSprite(entity, hello.characterLayout), label: makeLabel(entity.label), bubble: null, bubbleKey: null };
        this.scene.sorted.addChild(item.char.sprite);
        this.scene.overlay.addChild(item.label);
        this.items.set(c.id, item);
      }
      item.char.update(c, ts, animFrame(c, now, state.test));
      const cx = (c.x + 0.5) * ts + c.offset[0];
      item.label.position.set(cx, (c.y + 1) * ts + 1);
      item.label.scale.set(inv);
      const key = bubbleKey(c.bubble);
      if (key !== item.bubbleKey) {
        item.bubble?.destroy({ children: true });
        item.bubble = c.bubble ? makeBubble(c.bubble) : null;
        if (item.bubble) this.scene.overlay.addChild(item.bubble);
        item.bubbleKey = key;
      }
      if (item.bubble) {
        item.bubble.position.set(cx, (c.y + 1) * ts - fh + c.offset[1] + 2);
        item.bubble.scale.set(inv);
      }
    }
    for (const id of [...this.items.keys()]) if (!seen.has(id)) this.drop(id);
    if (this.debugOn) drawDebug(this.debugGfx, hello.map, state.debug, chars);
  }

  private drop(id: string): void {
    const item = this.items.get(id);
    if (!item) return;
    item.char.sprite.destroy();
    item.label.destroy({ children: true });
    item.bubble?.destroy({ children: true });
    this.items.delete(id);
  }
}
```

- [ ] **Step 4: клавиша `D` и `?debug=1` в `main.ts`**

После строки `const view = new OfficeView(scene);` вставить:
```ts
  view.setDebug(params.debug);
  window.addEventListener('keydown', (e) => {
    if (e.key === 'd' || e.key === 'D' || e.key === 'в' || e.key === 'В') view.toggleDebug(); // В — та же клавиша в русской раскладке
  });
```

- [ ] **Step 5: скриншоты и просмотр**

```bash
pnpm --filter @pixeloffice/viewer build
node packages/server/src/main.ts serve offices/demo --test --port 4871 &
SRV=$!
curl -sf -o /dev/null --noproxy '*' --retry 30 --retry-delay 1 --retry-connrefused http://127.0.0.1:4871/healthz   # ждать готовности
node packages/viewer/scripts/shot.ts "http://127.0.0.1:4871/?token=demo-viewer-token&scenario=needs-input&t=15000&seed=1" docs/spikes/m3/bubble.png
node packages/viewer/scripts/shot.ts "http://127.0.0.1:4871/?token=demo-viewer-token&scenario=lounge&t=40000&seed=1&debug=1" docs/spikes/m3/debug.png
kill $SRV
```
Открыть оба PNG. Критерии:
1. `bubble`: над агентом Анны за столом жёлтое облачко «? Разрешить запуск pnpm test?» с хвостом к голове. Текст переносится, не выходит за рамку, кириллица читается.
2. `debug`: сетка, красные блоки, рамки мест (синие sit, жёлтые stand, зелёные play), брони мест агентов в лаунже залиты, вход отмечен.
3. Агенты в лаунже — у аркад (`idle` вверх) и на диване.

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

```bash
pnpm gate
git add packages/viewer
git commit -m "feat(viewer): облачка-комиксы и отладочный слой по клавише D"
```

**Критерий готовности:** скриншоты `bubble.png` и `debug.png` просмотрены и выполняют критерии 1–3.

---

### Задача 28: viewer — скриншот-тесты Playwright, локальный офис на mock, удаление спайка

**Files:**
- Create: `packages/viewer/playwright.config.ts`, `packages/viewer/tests/visual/scenes.spec.ts`
- Modify: корневой `package.json` (скрипты `test:visual`, `dev:server`, `dev:viewer`), `README.md`
- Delete: `tools/spike/`
- Create (вне git): `packages/viewer/tests/__screenshots__/*.png`, `docs/spikes/m3/local-mock.png`

**Interfaces:**
- Consumes: тестовый режим (задача 23), сценарии (задача 22), `scripts/shot.ts`.
- Produces: `pnpm test:visual` — пять ключевых сцен (спека 11): рабочий офис (`morning`), встреча (`meeting9`), комната отдыха (`lounge`), облачко (`needs-input`), 4 направления сидения (`sit4`). Без `assetsDir` тесты skipped. Эталоны — в `packages/viewer/tests/__screenshots__/`, в git не попадают (`*.png`).

- [ ] **Step 1: `packages/viewer/playwright.config.ts`**

```ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: 'tests/visual',
  snapshotPathTemplate: '{testDir}/../__screenshots__/{arg}{ext}',
  fullyParallel: false,
  workers: 1,
  use: { baseURL: 'http://127.0.0.1:4871', viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 },
  expect: { toHaveScreenshot: { maxDiffPixels: 0, animations: 'disabled' } },
  webServer: {
    command: 'pnpm build && node ../server/src/main.ts serve ../../offices/demo --test --port 4871',
    url: 'http://127.0.0.1:4871/healthz',
    reuseExistingServer: false,
    timeout: 120_000,
  },
  projects: [{ name: 'chromium', use: { browserName: 'chromium' } }],
});
```

- [ ] **Step 2: `packages/viewer/tests/visual/scenes.spec.ts`**

```ts
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { expect, test } from '@playwright/test';
import { parse } from 'yaml';

// Ассеты LimeZu только локально: без assetsDir скриншот-тесты пропускаются (спека 11).
const cfg = parse(readFileSync(new URL('../../../../offices/demo/config.yaml', import.meta.url), 'utf8')) as { assetsDir: string };
const assetsDir = cfg.assetsDir.replace(/^~(?=\/|$)/, homedir());
test.skip(!existsSync(assetsDir), `нет assetsDir (${assetsDir}) — скриншот-тесты пропущены`);

const SCENES = [
  { name: 'office', scenario: 'morning', t: 60_000 },
  { name: 'meeting', scenario: 'meeting9', t: 60_000 },
  { name: 'lounge', scenario: 'lounge', t: 40_000 },
  { name: 'bubble', scenario: 'needs-input', t: 15_000 },
  { name: 'sit4', scenario: 'sit4', t: 30_000 },
];

for (const s of SCENES) {
  test(`сцена ${s.name}`, async ({ page }) => {
    await page.goto(`/?token=demo-viewer-token&scenario=${s.scenario}&t=${s.t}&seed=1`);
    await page.waitForFunction(() => (window as unknown as { __pixelofficeReady?: boolean }).__pixelofficeReady === true, null, { timeout: 30_000 });
    await expect(page).toHaveScreenshot(`${s.name}.png`);
  });
}
```

Корневой `package.json` — скрипты:
```json
"test:visual": "pnpm --filter @pixeloffice/viewer test:visual",
"dev:server": "node packages/server/src/main.ts serve offices/local",
"dev:viewer": "pnpm --filter @pixeloffice/viewer dev"
```

- [ ] **Step 3: эталоны и просмотр**

```bash
pnpm test:visual -- --update-snapshots
ls packages/viewer/tests/__screenshots__/      # office.png meeting.png lounge.png bubble.png sit4.png
```
Открыть все пять PNG (Read tool). Кроме критериев задач 25–27 проверить:
1. `meeting`: девять человек в большой переговорке `m2` (часть сидит, места заполнены по порядку), малая `m1` пуста.
2. `office`: все девять людей на своих местах, нет персонажей в стенах и на столах.

Затем повторный прогон без обновления — проверка детерминизма:
```bash
pnpm test:visual          # 5 passed
pnpm test:visual          # снова 5 passed
```
Если второй прогон даёт расхождения — искать источник недетерминизма (шрифт не загружен до готовности, анимационный кадр не 0, `fit` зависит от таймингов). Порог `maxDiffPixels` не поднимать.

Проверить, что эталоны не попали в git:
```bash
git status --short packages/viewer/tests   # PNG не видны (игнорируются)
```

- [ ] **Step 4: локальный офис на mock — итог M3**

```bash
node packages/server/src/main.ts init offices/local        # config.yaml со случайными токенами (не коммитится)
pnpm --filter @pixeloffice/viewer build
node packages/server/src/main.ts serve offices/local &      # то же, что pnpm dev:server (127.0.0.1:4870); напрямую, чтобы $! был PID сервера, а не pnpm
SRV=$!
curl -sf -o /dev/null --noproxy '*' --retry 30 --retry-delay 1 --retry-connrefused http://127.0.0.1:4870/healthz   # ждать готовности
pnpm mock:local                                             # сценарий lounge через /v1/events
TOKEN=$(sed -n 's/^viewerTokens: *\[ *"\([^"]*\)".*/\1/p' offices/local/config.yaml)   # первый токен зрителя из config.yaml
sleep 75                                                    # dwell офиса local: человек 60 с, агент 20 с, плюс дорога от входа
node packages/viewer/scripts/shot.ts "http://127.0.0.1:4870/?token=$TOKEN" docs/spikes/m3/local-mock.png
kill $SRV
```

Открыть `docs/spikes/m3/local-mock.png`: офис local, Стас за своим столом. Агенты «Стас · demo» (статус `idle`) в лаунже: четыре на местах (две аркады и диван на двоих — в лаунже local 4 места), пятый стоит в свободной клетке лаунжа рядом, в логе сервера warn про запасную клетку. В коворкинг агенты `idle` не идут. Мир живой: сервер с настоящими часами, без тестового режима.

- [ ] **Step 5: удаление спайка и README**

```bash
git rm -r tools/spike
pnpm install
```
В `README.md` добавить раздел «Запуск»:
```markdown
## Запуск

1. `node packages/server/src/main.ts init offices/local` — создаст `offices/local/config.yaml` со случайными токенами.
2. `pnpm --filter @pixeloffice/viewer build` — собрать зрителя.
3. `pnpm dev:server` — сервер офиса на http://127.0.0.1:4870. Открыть `/?token=<viewerTokens[0] из config.yaml>`.
4. `pnpm mock:local` — оживить офис сценарием (`node tools/replay/src/cli.ts scenario <имя> …`, сценарии: morning, meeting9, agents20, needs-input, lounge, sit4).
5. Разработка зрителя с горячей перезагрузкой: `pnpm dev:viewer` (Vite проксирует /v1 и /assets на сервер).

Клавиша `D` — отладочный слой (сетка, места, пути, брони).

## Проверки

- `pnpm gate` — тесты, тайпчек, валидация карт `offices/`.
- `pnpm test:visual` — скриншот-тесты (только при наличии ассетов LimeZu в `~/tmp`; эталоны не коммитятся, на новой машине: `pnpm test:visual -- --update-snapshots` и просмотр глазами).
```

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

```bash
pnpm gate
pnpm test:visual
git add -A
git status --short     # нет *.png, нет offices/local/config.yaml
git commit -m "test(viewer): скриншот-тесты ключевых сцен; локальный офис на mock"
```

**Критерий готовности:** `pnpm test:visual` — 5 passed дважды подряд. Пять эталонов просмотрены. Локальный офис на mock виден на скриншоте. `tools/spike` удалён.

---

## Этап M4. Адаптеры

### Задача 29: adapters/claude-hook — hook Claude Code

**Files:**
- Create: `adapters/claude-hook/{package.json,tsconfig.json,tsconfig.test.json,vitest.config.ts,README.md}`
- Create: `adapters/claude-hook/src/{map.ts,config.ts,main.ts}`
- Test: `adapters/claude-hook/tests/{map.test.ts,config.test.ts,e2e.test.ts}`
- Create (вне git): `docs/spikes/m4-claude-hook-live.md`

**Interfaces:**
- Consumes: `Event`, `AgentStatus`, `EventsBodySchema` (protocol); в e2e-тесте — `buildServer`, `OfficeRuntime`, `ManualClock`, `loadOffice`, `silentLogger` (server, devDependency).
- Produces:
  - `type HookInput = { session_id?: string; hook_event_name?: string; source?: string; notification_type?: string; message?: string; agent_id?: string; cwd?: string }`.
  - `mapHook(input: HookInput, env: Record<string, string | undefined>, now: Date): Event[]` — таблица спеки 6.1. `project` = basename `CLAUDE_PROJECT_DIR`, запасной путь — `input.cwd`. `slot` = `TMUX_PANE`, вне tmux — `session_id`. Без проекта или слота — `[]`.
  - `NEEDS_INPUT_BUBBLE_TTL = 3600`: облачко запроса разрешения живёт час, но гаснет раньше, когда статус уходит из `needs_input` (решение 12).
  - `type HookConfig = { url: string; token: string }`, `loadHookConfig(env, home = homedir()): HookConfig | null` — env `PIXELOFFICE_URL` + `PIXELOFFICE_TOKEN`, иначе `~/.config/pixeloffice/hook.json` (`{ "url": "http://127.0.0.1:4870", "token": "…" }`), иначе `null` и hook молча выходит.
  - `main.ts` — исполняемый скрипт: stdin → `mapHook` → `POST <url>/v1/events`, таймаут HTTP 1 с, страховочный выход через 1,5 с, ошибки проглатываются, код выхода всегда 0. С `PIXELOFFICE_HOOK_DEBUG=1` ошибки печатаются в stderr (для ручной проверки).

Субагенты (`agent_id` в событии) засчитываются родителю: панель и проект те же, поле `agent_id` не используется (спека 6.1). `ttlSec` hook не шлёт: умолчания по статусам — в `config.yaml` (решение 23).

- [ ] **Step 1: пакет**

`adapters/claude-hook/package.json`:
```json
{
  "name": "@pixeloffice/adapter-claude-hook",
  "private": true,
  "type": "module",
  "bin": { "pixeloffice-hook": "./src/main.ts" },
  "scripts": { "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json" },
  "dependencies": { "@pixeloffice/protocol": "workspace:*" },
  "devDependencies": { "@pixeloffice/server": "workspace:*" }
}
```
`tsconfig.json`: `{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2024"], "types": ["node"] }, "include": ["src"] }`. `tsconfig.test.json` — то же с `"include": ["src", "tests"]`. `vitest.config.ts`: `defineProject({ test: { name: 'adapter-claude-hook', include: ['tests/**/*.test.ts'] } })`.

```bash
pnpm install
```

- [ ] **Step 2: падающие тесты маппинга `adapters/claude-hook/tests/map.test.ts`**

```ts
import { describe, expect, it } from 'vitest';
import { EventsBodySchema } from '@pixeloffice/protocol';
import { mapHook, NEEDS_INPUT_BUBBLE_TTL, type HookInput } from '../src/map.ts';

const NOW = new Date('2026-10-20T10:00:00.000Z');
const ENV = { CLAUDE_PROJECT_DIR: '/Users/x/Projects/PixelOffice', TMUX_PANE: '%17' };
const AGENT = { project: 'PixelOffice', projectDir: '/Users/x/Projects/PixelOffice', slot: '%17' };
const statusOf = (input: HookInput, env: Record<string, string | undefined> = ENV) =>
  mapHook(input, env, NOW).map((e) => (e.type === 'status' ? e.status : e.type));

describe('mapHook — таблица спеки 6.1', () => {
  it.each(['startup', 'resume', 'clear', 'fork'])('SessionStart source=%s → idle', (source) => {
    expect(statusOf({ hook_event_name: 'SessionStart', source })).toEqual(['idle']);
  });

  it('SessionStart source=compact → без изменений', () => {
    expect(statusOf({ hook_event_name: 'SessionStart', source: 'compact' })).toEqual([]);
  });

  it.each(['UserPromptSubmit', 'PostToolUse', 'PostToolUseFailure'])('%s → working', (name) => {
    expect(statusOf({ hook_event_name: name })).toEqual(['working']);
  });

  it('Stop → idle, SessionEnd → offline', () => {
    expect(statusOf({ hook_event_name: 'Stop' })).toEqual(['idle']);
    expect(statusOf({ hook_event_name: 'SessionEnd' })).toEqual(['offline']);
  });

  it.each(['permission_prompt', 'elicitation_dialog', 'elicitation_url_dialog', 'agent_needs_input'])('Notification %s → needs_input + облачко', (t) => {
    const evs = mapHook({ hook_event_name: 'Notification', notification_type: t, message: 'Claude needs your permission to use Bash' }, ENV, NOW);
    expect(evs).toEqual([
      { type: 'status', agent: AGENT, status: 'needs_input', at: NOW.toISOString() },
      { type: 'bubble', agent: AGENT, text: 'Claude needs your permission to use Bash', ttlSec: NEEDS_INPUT_BUBBLE_TTL, at: NOW.toISOString() },
    ]);
  });

  it.each(['elicitation_response', 'elicitation_complete'])('Notification %s → working', (t) => {
    expect(statusOf({ hook_event_name: 'Notification', notification_type: t })).toEqual(['working']);
  });

  it.each(['idle_prompt', 'agent_completed', 'auth_success', 'quota_auto_resume_started', 'что-то-новое'])('Notification %s → игнор', (t) => {
    expect(statusOf({ hook_event_name: 'Notification', notification_type: t })).toEqual([]);
  });

  it('облачко без текста — запасной текст; длинный текст обрезается до 500', () => {
    const empty = mapHook({ hook_event_name: 'Notification', notification_type: 'permission_prompt' }, ENV, NOW);
    expect(empty[1]).toMatchObject({ type: 'bubble', text: 'Нужен ответ' });
    const long = mapHook({ hook_event_name: 'Notification', notification_type: 'permission_prompt', message: 'я'.repeat(900) }, ENV, NOW);
    expect(long[1]?.type === 'bubble' && long[1].text.length).toBe(500);
  });

  it('события субагента (agent_id) засчитываются родителю', () => {
    const evs = mapHook({ hook_event_name: 'PostToolUse', agent_id: 'sub-1', session_id: 's1' }, ENV, NOW);
    expect(evs).toEqual([{ type: 'status', agent: AGENT, status: 'working', at: NOW.toISOString() }]);
  });

  it('вне tmux слот — session_id; без CLAUDE_PROJECT_DIR проект из cwd; без проекта и слота — ничего', () => {
    const evs = mapHook({ hook_event_name: 'Stop', session_id: 'abc-123', cwd: '/w/Repo/' }, {}, NOW);
    expect(evs[0]).toMatchObject({ agent: { project: 'Repo', projectDir: '/w/Repo/', slot: 'abc-123' } });
    expect(mapHook({ hook_event_name: 'Stop' }, {}, NOW)).toEqual([]);
  });

  it('неизвестный hook → игнор; результат проходит схему /v1/events', () => {
    expect(statusOf({ hook_event_name: 'SubagentStop' })).toEqual([]);
    const evs = mapHook({ hook_event_name: 'Notification', notification_type: 'permission_prompt', message: 'x' }, ENV, NOW);
    expect(EventsBodySchema.safeParse({ events: evs }).success).toBe(true);
  });
});
```

`adapters/claude-hook/tests/config.test.ts`:
```ts
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { loadHookConfig } from '../src/config.ts';

describe('loadHookConfig', () => {
  const home = mkdtempSync(join(tmpdir(), 'po-hook-'));

  it('env важнее файла; без env и файла — null', () => {
    expect(loadHookConfig({}, home)).toBeNull();
    mkdirSync(join(home, '.config/pixeloffice'), { recursive: true });
    writeFileSync(join(home, '.config/pixeloffice/hook.json'), JSON.stringify({ url: 'http://file', token: 'tok-file-1' }));
    expect(loadHookConfig({}, home)).toEqual({ url: 'http://file', token: 'tok-file-1' });
    expect(loadHookConfig({ PIXELOFFICE_URL: 'http://env', PIXELOFFICE_TOKEN: 'tok-env-1' }, home)).toEqual({ url: 'http://env', token: 'tok-env-1' });
  });

  it('битый файл — null, без исключения', () => {
    const h = mkdtempSync(join(tmpdir(), 'po-hook-'));
    mkdirSync(join(h, '.config/pixeloffice'), { recursive: true });
    writeFileSync(join(h, '.config/pixeloffice/hook.json'), '{ не json');
    expect(loadHookConfig({}, h)).toBeNull();
  });
});
```

Run: `pnpm vitest run adapters/claude-hook` → FAIL.

- [ ] **Step 3: `adapters/claude-hook/src/map.ts`**

```ts
import { basename } from 'node:path';
import type { AgentStatus, Event } from '@pixeloffice/protocol';

// JSON, который Claude Code передаёт hook-у в stdin (используемые поля).
export type HookInput = {
  session_id?: string;
  hook_event_name?: string;
  source?: string;
  notification_type?: string;
  message?: string;
  agent_id?: string;
  cwd?: string;
};

export const NEEDS_INPUT_BUBBLE_TTL = 3600;
const NEEDS_INPUT = new Set(['permission_prompt', 'elicitation_dialog', 'elicitation_url_dialog', 'agent_needs_input']);
const BACK_TO_WORK = new Set(['elicitation_response', 'elicitation_complete']);

// Маппинг hook → события (спека 6.1). Субагенты (agent_id) засчитываются родителю: панель и проект те же.
export function mapHook(input: HookInput, env: Record<string, string | undefined>, now: Date): Event[] {
  const projectDir = env['CLAUDE_PROJECT_DIR'] || input.cwd;
  const slot = env['TMUX_PANE'] || input.session_id;
  if (!projectDir || !slot) return [];
  const project = basename(projectDir.replace(/\/+$/, '')) || projectDir;
  const agent = { project, projectDir, slot };
  const at = now.toISOString();
  const status = (s: AgentStatus): Event => ({ type: 'status', agent, status: s, at });
  switch (input.hook_event_name) {
    case 'SessionStart':
      return input.source === 'compact' ? [] : [status('idle')]; // автокомпакт случается посреди работы
    case 'UserPromptSubmit':
    case 'PostToolUse':
    case 'PostToolUseFailure':
      return [status('working')];
    case 'Stop':
      return [status('idle')];
    case 'SessionEnd':
      return [status('offline')];
    case 'Notification': {
      const t = input.notification_type ?? '';
      if (NEEDS_INPUT.has(t)) {
        const text = (input.message ?? '').trim().slice(0, 500) || 'Нужен ответ';
        return [status('needs_input'), { type: 'bubble', agent, text, ttlSec: NEEDS_INPUT_BUBBLE_TTL, at }];
      }
      if (BACK_TO_WORK.has(t)) return [status('working')];
      return []; // idle_prompt, agent_completed, auth_success, quota_auto_resume_*, неизвестные
    }
    default:
      return [];
  }
}
```

- [ ] **Step 4: `adapters/claude-hook/src/config.ts`**

```ts
import { readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';

export type HookConfig = { url: string; token: string };

// URL сервера и токен: env, иначе ~/.config/pixeloffice/hook.json (спека 6.1).
export function loadHookConfig(env: Record<string, string | undefined>, home: string = homedir()): HookConfig | null {
  const url = env['PIXELOFFICE_URL'];
  const token = env['PIXELOFFICE_TOKEN'];
  if (url && token) return { url, token };
  try {
    const raw = JSON.parse(readFileSync(join(home, '.config/pixeloffice/hook.json'), 'utf8')) as Partial<HookConfig>;
    if (typeof raw.url === 'string' && typeof raw.token === 'string') return { url: raw.url, token: raw.token };
  } catch {
    // нет файла или битый JSON — hook молча ничего не шлёт
  }
  return null;
}
```

Run: `pnpm vitest run adapters/claude-hook/tests/map.test.ts adapters/claude-hook/tests/config.test.ts` → PASS.

- [ ] **Step 5: падающий e2e-тест `adapters/claude-hook/tests/e2e.test.ts`**

```ts
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it } from 'vitest';
import { ManualClock, OfficeRuntime, buildServer, loadOffice, silentLogger } from '@pixeloffice/server';

const MAIN = fileURLToPath(new URL('../src/main.ts', import.meta.url));
const DEMO = fileURLToPath(new URL('../../../offices/demo/', import.meta.url));
const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

function runHook(input: unknown, env: Record<string, string>): Promise<{ code: number | null; ms: number }> {
  const t0 = Date.now();
  return new Promise((resolve) => {
    const p = spawn(process.execPath, [MAIN], { env: { PATH: process.env['PATH'] ?? '', HOME: '/nonexistent', ...env }, stdio: ['pipe', 'ignore', 'ignore'] });
    p.on('exit', (code) => resolve({ code, ms: Date.now() - t0 }));
    p.stdin.end(typeof input === 'string' ? input : JSON.stringify(input));
  });
}

describe('pixeloffice-hook против сервера', () => {
  it('PostToolUse регистрирует агента хозяина токена', async () => {
    const rt = new OfficeRuntime({ office: loadOffice(DEMO), clock: new ManualClock(), log: silentLogger });
    const srv = await buildServer({ runtime: rt, viewerTokens: ['demo-viewer-token'], viewerDist: null, assetsDir: null, testMode: null });
    await srv.app.listen({ port: 0, host: '127.0.0.1' });
    closers.push(() => srv.app.close());
    const url = `http://127.0.0.1:${(srv.app.server.address() as AddressInfo).port}`;
    const r = await runHook(
      { session_id: 's1', hook_event_name: 'PostToolUse' },
      { PIXELOFFICE_URL: url, PIXELOFFICE_TOKEN: 'demo-hook-token', CLAUDE_PROJECT_DIR: '/x/Proj', TMUX_PANE: '%5' },
    );
    expect(r.code).toBe(0);
    expect(rt.registry.get('agent:p1:Proj:%5')).toMatchObject({ kind: 'agent', ownerId: 'p1', project: 'Proj', slot: '%5' });
  });

  it('сервер молчит — выход 0 не дольше ~1,5 с', async () => {
    const hang = createServer(() => {}); // принимает соединение и не отвечает
    await new Promise<void>((r) => hang.listen(0, '127.0.0.1', r));
    closers.push(() => new Promise((r) => hang.close(r)));
    hang.unref();
    const url = `http://127.0.0.1:${(hang.address() as AddressInfo).port}`;
    const r = await runHook({ hook_event_name: 'Stop', session_id: 's' }, { PIXELOFFICE_URL: url, PIXELOFFICE_TOKEN: 'x'.repeat(8), TMUX_PANE: '%1', CLAUDE_PROJECT_DIR: '/x/P' });
    expect(r.code).toBe(0);
    expect(r.ms).toBeLessThan(2500);
  });

  it('мусор в stdin и нет конфига — выход 0', async () => {
    expect((await runHook('не json', {})).code).toBe(0);
    expect((await runHook({ hook_event_name: 'Stop' }, { PIXELOFFICE_URL: 'http://127.0.0.1:1', PIXELOFFICE_TOKEN: 'x'.repeat(8) })).code).toBe(0);
  });
});
```

Run: `pnpm vitest run adapters/claude-hook/tests/e2e.test.ts` → FAIL (нет `main.ts`).

Если `hang.close` ждёт незакрытых соединений и тест виснет на `afterEach` — вызвать `hang.closeAllConnections()` перед `close` в `closers`.

- [ ] **Step 6: `adapters/claude-hook/src/main.ts`**

```ts
import { loadHookConfig } from './config.ts';
import { mapHook, type HookInput } from './map.ts';

// pixeloffice-hook: никогда не ломает и не тормозит сессию Claude Code —
// таймаут HTTP 1 с, любые ошибки проглатываются, код выхода всегда 0 (спека 6.1).
const debug = process.env['PIXELOFFICE_HOOK_DEBUG'] === '1';
const guard = setTimeout(() => process.exit(0), 1500);
guard.unref();

async function readStdin(): Promise<string> {
  const chunks: Buffer[] = [];
  for await (const c of process.stdin) chunks.push(c as Buffer);
  return Buffer.concat(chunks).toString('utf8');
}

async function run(): Promise<void> {
  const cfg = loadHookConfig(process.env);
  if (!cfg) return;
  const input = JSON.parse(await readStdin()) as HookInput;
  const events = mapHook(input, process.env, new Date());
  if (events.length === 0) return;
  const res = await fetch(new URL('/v1/events', cfg.url), {
    method: 'POST',
    headers: { 'content-type': 'application/json', authorization: `Bearer ${cfg.token}` },
    body: JSON.stringify({ events }),
    signal: AbortSignal.timeout(1000),
  });
  if (debug) console.error(`pixeloffice-hook: ${input.hook_event_name} → ${res.status} ${await res.text()}`);
}

try {
  await run();
} catch (e) {
  if (debug) console.error(`pixeloffice-hook: ${(e as Error).message}`);
}
process.exit(0);
```

Run: `pnpm vitest run adapters/claude-hook` → PASS.

- [ ] **Step 7: `adapters/claude-hook/README.md`** (фрагмент settings.json — пользователь вставляет сам, план `~/.claude/settings.json` не трогает)

````markdown
# pixeloffice-hook

Hook Claude Code: статус сессии → персонаж-агент в PixelOffice (спека 6.1).

## Установка (вручную)

1. Конфиг: `~/.config/pixeloffice/hook.json`
   ```json
   { "url": "http://127.0.0.1:4870", "token": "<token источника claude-hook из offices/local/config.yaml>" }
   ```
   Или env `PIXELOFFICE_URL` и `PIXELOFFICE_TOKEN`.
2. В `~/.claude/settings.json` добавить в `hooks` (путь к репозиторию поправить). Node — абсолютный путь к 24-й версии: первым в PATH может стоять более старый node без type stripping.
   ```json
   {
     "hooks": {
       "SessionStart":       [{ "hooks": [{ "type": "command", "async": true, "command": "/opt/homebrew/opt/node@24/bin/node /Users/stas/Projects/My/PixelOffice/adapters/claude-hook/src/main.ts" }] }],
       "UserPromptSubmit":   [{ "hooks": [{ "type": "command", "async": true, "command": "/opt/homebrew/opt/node@24/bin/node /Users/stas/Projects/My/PixelOffice/adapters/claude-hook/src/main.ts" }] }],
       "PostToolUse":        [{ "hooks": [{ "type": "command", "async": true, "command": "/opt/homebrew/opt/node@24/bin/node /Users/stas/Projects/My/PixelOffice/adapters/claude-hook/src/main.ts" }] }],
       "PostToolUseFailure": [{ "hooks": [{ "type": "command", "async": true, "command": "/opt/homebrew/opt/node@24/bin/node /Users/stas/Projects/My/PixelOffice/adapters/claude-hook/src/main.ts" }] }],
       "Stop":               [{ "hooks": [{ "type": "command", "async": true, "command": "/opt/homebrew/opt/node@24/bin/node /Users/stas/Projects/My/PixelOffice/adapters/claude-hook/src/main.ts" }] }],
       "Notification":       [{ "hooks": [{ "type": "command", "async": true, "command": "/opt/homebrew/opt/node@24/bin/node /Users/stas/Projects/My/PixelOffice/adapters/claude-hook/src/main.ts" }] }],
       "SessionEnd":         [{ "hooks": [{ "type": "command", "async": true, "command": "/opt/homebrew/opt/node@24/bin/node /Users/stas/Projects/My/PixelOffice/adapters/claude-hook/src/main.ts" }] }]
     }
   }
   ```
   Если в `hooks` уже есть эти события — добавить объект в существующий массив, а не заменять его.
3. Проверка без Claude Code:
   ```bash
   echo '{"hook_event_name":"UserPromptSubmit","session_id":"t"}' | PIXELOFFICE_HOOK_DEBUG=1 TMUX_PANE=%99 CLAUDE_PROJECT_DIR=$PWD /opt/homebrew/opt/node@24/bin/node adapters/claude-hook/src/main.ts
   ```
   Ожидается `pixeloffice-hook: UserPromptSubmit → 200 {"accepted":1,"ignored":0}`.

Hook всегда завершается с кодом 0 за ≤1,5 с, даже если сервер недоступен. `SubagentStop` не подписываем: субагенты засчитываются родителю.
````

- [ ] **Step 8: шаблон ручной проверки `docs/spikes/m4-claude-hook-live.md`** (вне git)

```markdown
# M4 — hook Claude Code на живой сессии

Статус: **ожидает человека** (нужно вставить фрагмент в ~/.claude/settings.json, см. adapters/claude-hook/README.md).

## Шаги
1. `pnpm dev:server` (offices/local), открыть офис в браузере.
2. Установить hook по README, открыть новую сессию Claude Code в tmux.
3. Отметить, что видно в офисе.

## Результат (заполнить)
1. SessionStart → агент «Стас · <проект>» появился у входа и ушёл в лаунж (idle): …
2. Промпт → агент идёт в угол Стаса или коворкинг (working, через dwell 20 с): …
3. Запрос разрешения → облачко «?» с текстом сразу, без dwell: …
4. Ответ на запрос → облачко гаснет, агент снова working: …
5. Реальные значения `notification_type` (из `PIXELOFFICE_HOOK_DEBUG=1` или лога сервера): …
6. Смысл `elicitation_*` и `agent_*` (спека 6.1 просит сверить): …
7. /exit → SessionEnd → агент уходит к выходу: …
8. Задержка hook-а заметна в сессии? …
```

- [ ] **Step 9: гейт и коммит**

```bash
pnpm gate
git add adapters/claude-hook pnpm-lock.yaml
git commit -m "feat(claude-hook): hook Claude Code — маппинг событий сессии в статусы агента"
```

**Критерий готовности:** тесты маппинга покрывают все `source` у `SessionStart`, все `notification_type` спеки и события с `agent_id`. e2e подтверждает регистрацию агента и выход 0 при молчащем сервере. README-фрагмент готов, `~/.claude/settings.json` не тронут.

---

### Задача 30: adapters/nextcloud — опросчик User Status и Talk

**Files:**
- Create: `adapters/nextcloud/src/{map.ts,bubbles.ts,poller.ts,main.ts}`
- Create: `adapters/nextcloud/tests/fixtures/{statuses.json,rooms.json,call-abc123.json,chat-def456-1.json,chat-def456-2.json}`
- Test: `adapters/nextcloud/tests/{map.test.ts,bubbles.test.ts,poller.test.ts}`
- Modify: `adapters/nextcloud/package.json` (зависимости)
- Create (вне git): `docs/spikes/m4-nextcloud-live.md`

**Interfaces:**
- Consumes: `ocsGet`, `OcsError`, `OcsAuth` (задача 4); `Person`, `parseConfig` (core); `readOfficeTexts` (validate-maps); `Event`, `SnapshotEvent`, `BubbleEvent`, `Status` (protocol).
- Produces:
  - `map.ts`: `type NcUserStatus = { userId: string; status: string; messageId?: string | null; icon?: string | null; message?: string | null }`, `type NcRoom = { token: string; type: number; displayName?: string; hasCall?: boolean }`, `type NcCallPeer = { actorType: string; actorId: string }`, `IN_A_CALL_MESSAGE_IDS`, `buildSnapshot(people, statuses, calls: ReadonlyMap<string, string[]>, statusMap, at, warn?): SnapshotEvent`.
  - `bubbles.ts`: `type NcMessage = { id: number; actorType: string; actorId: string; message: string; systemMessage?: string; messageType?: string; messageParameters?: Record<string, { name?: string }> | unknown[] }`, `type TalkMode = 'full' | 'truncated' | 'typing_only'`, `TALK_BUBBLE_TTL = 10`, `renderText(m, mode): string | null`, `class TalkBubbles { constructor(mode, uidToEntity: ReadonlyMap<string, string>); process(room, messages, at): BubbleEvent[] }`.
  - `poller.ts`: `type PollDeps = { get<T>(path: string): Promise<T>; people: Person[]; statusMap: Record<string, 'online' | 'offline'>; bubbles: TalkBubbles; now(): Date; warn(m: string): void }`, `pollOnce(d): Promise<Event[]>` — `[snapshot, ...bubbles]`.
  - `main.ts`: `NC_URL=… NC_USER=… NC_APP_PASSWORD=… PIXELOFFICE_URL=… PIXELOFFICE_TOKEN=… node adapters/nextcloud/src/main.ts --office offices/team` — опрос раз в 30 с (`NC_POLL_SEC` переопределяет).

Решения задачи (спека 6.2; уточняются по итогам M0(б), до этого — по документации OCS):
1. Один `snapshot` на опрос по всем людям с `nextcloudUid`. Люди без uid в снимок не входят.
2. Приоритет: `meeting` (участник активного звонка в комнате бота, `meetingId` = token комнаты; при нескольких звонках — первый по token) > User Status через `statusMap`.
3. Пользователь, которого нет в ответе `/statuses`, — `offline`: API отдаёт только пользователей с выставленным статусом.
4. Автоматический «In a call» (`messageId` из `IN_A_CALL_MESSAGE_IDS` = `call`, `meeting`) без видимого звонка → `online` независимо от `statusMap`.
5. Неизвестное значение `status` → `offline` и warn.
6. Облачка Talk: первый опрос комнаты запоминает последний `id` и истории не показывает. Системные сообщения и не-`users` авторы пропускаются. Плейсхолдеры `{mention-user1}` заменяются на `messageParameters[*].name`. Режимы: `full` — до 500 символов, `truncated` — 60, `typing_only` — «…». Облачко живёт 10 с.
7. Ошибка `/statuses` или `/room` → опрос пропускается (сущности уйдут в `offline` по ttl источника, спека 10). Ошибка звонка или чата одной комнаты → warn, остальное продолжается. Ответ чата 304 = новых сообщений нет.

- [ ] **Step 1: зависимости**

В `adapters/nextcloud/package.json` → `dependencies`:
```json
"@pixeloffice/core": "workspace:*",
"@pixeloffice/protocol": "workspace:*",
"@pixeloffice/validate-maps": "workspace:*"
```
```bash
pnpm install
```

- [ ] **Step 2: фикстуры (содержимое `ocs.data`, как его возвращает `ocsGet`)**

`adapters/nextcloud/tests/fixtures/statuses.json`:
```json
[
  { "userId": "anna", "status": "online", "icon": null, "message": null, "messageId": null },
  { "userId": "boris", "status": "away", "icon": null, "message": null, "messageId": null },
  { "userId": "vera", "status": "dnd", "icon": null, "message": "Не беспокоить", "messageId": null },
  { "userId": "gleb", "status": "busy", "icon": null, "message": null, "messageId": "call" },
  { "userId": "dina", "status": "invisible", "icon": null, "message": null, "messageId": null },
  { "userId": "egor", "status": "online", "icon": null, "message": null, "messageId": null }
]
```
`rooms.json`:
```json
[
  { "token": "abc123", "type": 2, "displayName": "Планёрка", "hasCall": true },
  { "token": "def456", "type": 3, "displayName": "Общий", "hasCall": false }
]
```
`call-abc123.json`:
```json
[
  { "actorType": "users", "actorId": "egor", "displayName": "Егор" },
  { "actorType": "users", "actorId": "anna", "displayName": "Анна" },
  { "actorType": "guests", "actorId": "g-1", "displayName": "Гость" }
]
```
`chat-def456-1.json`:
```json
[
  { "id": 100, "actorType": "users", "actorId": "boris", "message": "старое сообщение", "systemMessage": "", "messageType": "comment", "messageParameters": [] }
]
```
`chat-def456-2.json`:
```json
[
  { "id": 102, "actorType": "users", "actorId": "vera", "message": "Привет, {mention-user1}! Созвон в 15:00?", "systemMessage": "", "messageType": "comment", "messageParameters": { "mention-user1": { "type": "user", "id": "anna", "name": "Анна" } } },
  { "id": 101, "actorType": "users", "actorId": "boris", "message": "Вы начали звонок", "systemMessage": "call_started", "messageType": "system", "messageParameters": [] },
  { "id": 100, "actorType": "users", "actorId": "boris", "message": "старое сообщение", "systemMessage": "", "messageType": "comment", "messageParameters": [] }
]
```

- [ ] **Step 3: падающие тесты**

`adapters/nextcloud/tests/people.ts` (общая фикстура людей):
```ts
import type { Person } from '@pixeloffice/core';

const avatar = { body: 1, eyes: 1, outfit: [1, 1] as [number, number], hair: [1, 1] as [number, number] };
const p = (id: string, nextcloudUid?: string): Person => ({ id, name: id, pod: `pod:${id}`, avatar, ...(nextcloudUid ? { nextcloudUid } : {}) });
export const PEOPLE: Person[] = [p('p1', 'anna'), p('p2', 'boris'), p('p3', 'vera'), p('p4', 'gleb'), p('p5', 'dina'), p('p6', 'egor'), p('p7', 'zhanna'), p('p8')];
export const UID_TO_ENTITY = new Map(PEOPLE.flatMap((x) => (x.nextcloudUid ? [[x.nextcloudUid, x.id] as const] : [])));
```
Если тип `Person` требует других полей (по задаче 8) — дополнить литерал, тесты не меняются.

`adapters/nextcloud/tests/map.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { DEFAULT_STATUS_MAP } from '@pixeloffice/core';
import { buildSnapshot, type NcUserStatus } from '../src/map.ts';
import statuses from './fixtures/statuses.json' with { type: 'json' };
import { PEOPLE } from './people.ts';

const AT = '2026-10-20T10:00:00.000Z';
const byId = (s: ReturnType<typeof buildSnapshot>) => Object.fromEntries(s.entities.map((e) => [e.entityId, e.meetingId ? `${e.status}:${e.meetingId}` : e.status]));

describe('buildSnapshot', () => {
  it('приоритет meeting, statusMap по умолчанию, In a call → online, отсутствующий → offline', () => {
    const calls = new Map([['abc123', ['egor', 'anna']]]);
    const snap = buildSnapshot(PEOPLE, statuses as NcUserStatus[], calls, DEFAULT_STATUS_MAP, AT);
    expect(snap.type).toBe('snapshot');
    expect(snap.at).toBe(AT);
    expect(byId(snap)).toEqual({
      p1: 'meeting:abc123',
      p2: 'online',
      p3: 'online',
      p4: 'online',
      p5: 'offline',
      p6: 'meeting:abc123',
      p7: 'offline',
    });
  });

  it('statusMap из конфига переопределяет умолчание; In a call всё равно online', () => {
    const map = { ...DEFAULT_STATUS_MAP, dnd: 'offline' as const, busy: 'offline' as const };
    const snap = buildSnapshot(PEOPLE, statuses as NcUserStatus[], new Map(), map, AT);
    expect(byId(snap)['p3']).toBe('offline');
    expect(byId(snap)['p4']).toBe('online');
  });

  it('неизвестный статус → offline и warn', () => {
    const warns: string[] = [];
    const snap = buildSnapshot(PEOPLE, [{ userId: 'anna', status: 'on-vacation' }], new Map(), DEFAULT_STATUS_MAP, AT, (m) => warns.push(m));
    expect(byId(snap)['p1']).toBe('offline');
    expect(warns).toHaveLength(1);
  });

  it('человек в двух звонках — первая комната по token', () => {
    const calls = new Map([['zzz', ['anna']], ['aaa', ['anna']]]);
    expect(byId(buildSnapshot(PEOPLE, [], calls, DEFAULT_STATUS_MAP, AT))['p1']).toBe('meeting:aaa');
  });
});
```

`adapters/nextcloud/tests/bubbles.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { TALK_BUBBLE_TTL, TalkBubbles, renderText, type NcMessage } from '../src/bubbles.ts';
import chat1 from './fixtures/chat-def456-1.json' with { type: 'json' };
import chat2 from './fixtures/chat-def456-2.json' with { type: 'json' };
import { UID_TO_ENTITY } from './people.ts';

const AT = '2026-10-20T10:00:00.000Z';
const msg = (message: string): NcMessage => ({ id: 1, actorType: 'users', actorId: 'anna', message, systemMessage: '', messageType: 'comment', messageParameters: [] });

describe('облачка Talk', () => {
  it('первый опрос — без истории; дальше только новые сообщения людей', () => {
    const b = new TalkBubbles('truncated', UID_TO_ENTITY);
    expect(b.process('def456', chat1 as NcMessage[], AT)).toEqual([]);
    expect(b.process('def456', chat2 as NcMessage[], AT)).toEqual([
      { type: 'bubble', entityId: 'p3', text: 'Привет, Анна! Созвон в 15:00?', ttlSec: TALK_BUBBLE_TTL, at: AT },
    ]);
    expect(b.process('def456', chat2 as NcMessage[], AT)).toEqual([]); // повтор не дублирует
  });

  it('пустая комната при первом опросе — следующее сообщение показывается', () => {
    const b = new TalkBubbles('full', UID_TO_ENTITY);
    expect(b.process('r', [], AT)).toEqual([]);
    expect(b.process('r', [{ ...msg('эй'), id: 5 }], AT)).toHaveLength(1);
  });

  it('неизвестный автор и гости пропускаются', () => {
    const b = new TalkBubbles('full', UID_TO_ENTITY);
    b.process('r', [], AT);
    expect(b.process('r', [{ ...msg('x'), id: 2, actorId: 'stranger' }, { ...msg('y'), id: 3, actorType: 'guests' }], AT)).toEqual([]);
  });

  it('режимы full / truncated / typing_only', () => {
    const long = 'а'.repeat(80);
    expect(renderText(msg(long), 'full')).toBe(long);
    expect(renderText(msg(long), 'truncated')).toBe('а'.repeat(59) + '…');
    expect(renderText(msg(long), 'typing_only')).toBe('…');
    expect(renderText(msg('   '), 'full')).toBeNull();
    expect(renderText(msg('я'.repeat(900)), 'full')!.length).toBe(500);
  });
});
```

`adapters/nextcloud/tests/poller.test.ts`:
```ts
import { describe, expect, it } from 'vitest';
import { DEFAULT_STATUS_MAP } from '@pixeloffice/core';
import { TalkBubbles } from '../src/bubbles.ts';
import { OcsError } from '../src/ocs.ts';
import { pollOnce } from '../src/poller.ts';
import call from './fixtures/call-abc123.json' with { type: 'json' };
import chat1 from './fixtures/chat-def456-1.json' with { type: 'json' };
import chat2 from './fixtures/chat-def456-2.json' with { type: 'json' };
import rooms from './fixtures/rooms.json' with { type: 'json' };
import statuses from './fixtures/statuses.json' with { type: 'json' };
import { PEOPLE, UID_TO_ENTITY } from './people.ts';

function fakeGet(round: () => number, failCall = false) {
  return async <T>(path: string): Promise<T> => {
    const p = path.split('?')[0]!;
    if (p.endsWith('/user_status/api/v1/statuses')) return statuses as T;
    if (p.endsWith('/spreed/api/v4/room')) return rooms as T;
    if (p.endsWith('/call/abc123')) {
      if (failCall) throw new OcsError('boom', 500);
      return call as T;
    }
    if (p.endsWith('/chat/abc123')) throw new OcsError('нет новых', 304);
    if (p.endsWith('/chat/def456')) return (round() === 1 ? chat1 : chat2) as T;
    throw new Error(`неожиданный путь ${path}`);
  };
}

describe('pollOnce', () => {
  it('снимок + облачка со второго опроса', async () => {
    let n = 1;
    const warns: string[] = [];
    const deps = {
      get: fakeGet(() => n),
      people: PEOPLE,
      statusMap: DEFAULT_STATUS_MAP,
      bubbles: new TalkBubbles('truncated', UID_TO_ENTITY),
      now: () => new Date('2026-10-20T10:00:00Z'),
      warn: (m: string) => warns.push(m),
    };
    const first = await pollOnce(deps);
    expect(first).toHaveLength(1);
    expect(first[0]).toMatchObject({ type: 'snapshot' });
    expect(first[0]!.type === 'snapshot' && first[0]!.entities.find((e) => e.entityId === 'p6')).toEqual({ entityId: 'p6', status: 'meeting', meetingId: 'abc123' });
    n = 2;
    const second = await pollOnce(deps);
    expect(second.map((e) => e.type)).toEqual(['snapshot', 'bubble']);
    expect(warns).toEqual([]);
  });

  it('ошибка звонка одной комнаты — warn, снимок без meeting', async () => {
    const warns: string[] = [];
    const evs = await pollOnce({
      get: fakeGet(() => 1, true),
      people: PEOPLE,
      statusMap: DEFAULT_STATUS_MAP,
      bubbles: new TalkBubbles('full', UID_TO_ENTITY),
      now: () => new Date(),
      warn: (m) => warns.push(m),
    });
    expect(evs[0]!.type === 'snapshot' && evs[0]!.entities.find((e) => e.entityId === 'p6')?.status).toBe('online');
    expect(warns).toHaveLength(1);
  });

  it('ошибка /statuses — исключение (опрос пропускается)', async () => {
    const get = async <T>(): Promise<T> => {
      throw new OcsError('401', 401);
    };
    await expect(
      pollOnce({ get, people: PEOPLE, statusMap: DEFAULT_STATUS_MAP, bubbles: new TalkBubbles('full', UID_TO_ENTITY), now: () => new Date(), warn: () => {} }),
    ).rejects.toBeInstanceOf(OcsError);
  });
});
```

`DEFAULT_STATUS_MAP` экспортирует core (задача 8). Импорт JSON с `with { type: 'json' }` работает в Vitest и Node 24, `resolveJsonModule` уже включён.

Run: `pnpm vitest run adapters/nextcloud` → FAIL.

- [ ] **Step 4: `adapters/nextcloud/src/map.ts`**

```ts
import type { Person } from '@pixeloffice/core';
import type { SnapshotEvent, Status } from '@pixeloffice/protocol';

export type NcUserStatus = { userId: string; status: string; messageId?: string | null; icon?: string | null; message?: string | null };
export type NcRoom = { token: string; type: number; displayName?: string; hasCall?: boolean };
export type NcCallPeer = { actorType: string; actorId: string };

// messageId автоматического статуса «In a call» — сверить в M0(б).
export const IN_A_CALL_MESSAGE_IDS: ReadonlySet<string> = new Set(['call', 'meeting']);

// Один снимок на опрос: meeting (звонок в комнате бота) > User Status через statusMap (спека 6.2).
export function buildSnapshot(
  people: Person[],
  statuses: NcUserStatus[],
  calls: ReadonlyMap<string, string[]>,
  statusMap: Record<string, 'online' | 'offline'>,
  at: string,
  warn: (m: string) => void = () => {},
): SnapshotEvent {
  const byUid = new Map(statuses.map((s) => [s.userId, s]));
  const meetingOf = new Map<string, string>();
  for (const [token, uids] of [...calls.entries()].sort(([a], [b]) => a.localeCompare(b))) {
    for (const uid of uids) if (!meetingOf.has(uid)) meetingOf.set(uid, token);
  }
  const entities: SnapshotEvent['entities'] = [];
  for (const p of people) {
    const uid = p.nextcloudUid;
    if (!uid) continue;
    const meetingId = meetingOf.get(uid);
    if (meetingId) {
      entities.push({ entityId: p.id, status: 'meeting', meetingId });
      continue;
    }
    const s = byUid.get(uid);
    let status: Status = 'offline'; // нет в /statuses — статус не выставлен
    if (s) {
      const mapped = statusMap[s.status];
      if (s.messageId && IN_A_CALL_MESSAGE_IDS.has(s.messageId)) status = 'online'; // звонок не виден боту — переговорку не закрепить
      else if (mapped) status = mapped;
      else warn(`неизвестный статус Nextcloud «${s.status}» у ${uid} — считаю offline`);
    }
    entities.push({ entityId: p.id, status });
  }
  return { type: 'snapshot', entities, at };
}
```

- [ ] **Step 5: `adapters/nextcloud/src/bubbles.ts`**

```ts
import type { BubbleEvent } from '@pixeloffice/protocol';

export type NcMessage = {
  id: number;
  actorType: string;
  actorId: string;
  message: string;
  systemMessage?: string;
  messageType?: string;
  messageParameters?: Record<string, { name?: string }> | unknown[];
};
export type TalkMode = 'full' | 'truncated' | 'typing_only';
export const TALK_BUBBLE_TTL = 10;
const TRUNCATE = 60;
const MAX = 500;

export function renderText(m: NcMessage, mode: TalkMode): string | null {
  const params = Array.isArray(m.messageParameters) ? {} : (m.messageParameters ?? {});
  const text = m.message.replace(/\{([\w-]+)\}/g, (all, key: string) => params[key]?.name ?? all).trim();
  if (!text) return null;
  if (mode === 'typing_only') return '…';
  const max = mode === 'truncated' ? TRUNCATE : MAX;
  return text.length > max ? text.slice(0, max - 1) + '…' : text;
}

// Новые сообщения в комнатах бота → облачка над авторами. Первый опрос комнаты истории не показывает.
export class TalkBubbles {
  private readonly lastSeen = new Map<string, number>();
  private readonly mode: TalkMode;
  private readonly uidToEntity: ReadonlyMap<string, string>;

  constructor(mode: TalkMode, uidToEntity: ReadonlyMap<string, string>) {
    this.mode = mode;
    this.uidToEntity = uidToEntity;
  }

  process(room: string, messages: NcMessage[], at: string): BubbleEvent[] {
    const sorted = [...messages].sort((a, b) => a.id - b.id);
    const prev = this.lastSeen.get(room);
    const maxId = sorted.at(-1)?.id ?? 0;
    this.lastSeen.set(room, Math.max(prev ?? 0, maxId));
    if (prev === undefined) return [];
    const out: BubbleEvent[] = [];
    for (const m of sorted) {
      if (m.id <= prev || m.actorType !== 'users' || m.systemMessage || (m.messageType ?? 'comment') !== 'comment') continue;
      const entityId = this.uidToEntity.get(m.actorId);
      const text = renderText(m, this.mode);
      if (entityId && text) out.push({ type: 'bubble', entityId, text, ttlSec: TALK_BUBBLE_TTL, at });
    }
    return out;
  }
}
```

- [ ] **Step 6: `adapters/nextcloud/src/poller.ts`**

```ts
import type { Person } from '@pixeloffice/core';
import type { BubbleEvent, Event } from '@pixeloffice/protocol';
import type { NcMessage, TalkBubbles } from './bubbles.ts';
import { buildSnapshot, type NcCallPeer, type NcRoom, type NcUserStatus } from './map.ts';
import { OcsError } from './ocs.ts';

export type PollDeps = {
  get<T>(path: string): Promise<T>;
  people: Person[];
  statusMap: Record<string, 'online' | 'offline'>;
  bubbles: TalkBubbles;
  now(): Date;
  warn(m: string): void;
};

const STATUSES = 'ocs/v2.php/apps/user_status/api/v1/statuses?limit=1000';
const ROOMS = 'ocs/v2.php/apps/spreed/api/v4/room';

// Один опрос: снимок по всем людям + облачка новых сообщений (спека 6.2).
export async function pollOnce(d: PollDeps): Promise<Event[]> {
  const at = d.now().toISOString();
  const statuses = await d.get<NcUserStatus[]>(STATUSES);
  const rooms = await d.get<NcRoom[]>(ROOMS);
  const calls = new Map<string, string[]>();
  const bubbles: BubbleEvent[] = [];
  for (const r of rooms) {
    if (r.hasCall) {
      try {
        const peers = await d.get<NcCallPeer[]>(`ocs/v2.php/apps/spreed/api/v4/call/${r.token}`);
        calls.set(r.token, peers.filter((p) => p.actorType === 'users').map((p) => p.actorId));
      } catch (e) {
        d.warn(`звонок в комнате ${r.token}: ${(e as Error).message}`);
      }
    }
    try {
      const msgs = await d.get<NcMessage[]>(`ocs/v2.php/apps/spreed/api/v1/chat/${r.token}?lookIntoFuture=0&limit=20&setReadMarker=0`);
      bubbles.push(...d.bubbles.process(r.token, msgs, at));
    } catch (e) {
      if (!(e instanceof OcsError && e.status === 304)) d.warn(`чат комнаты ${r.token}: ${(e as Error).message}`);
    }
  }
  return [buildSnapshot(d.people, statuses, calls, d.statusMap, at, d.warn), ...bubbles];
}
```

- [ ] **Step 7: `adapters/nextcloud/src/main.ts`**

```ts
import { parseConfig } from '@pixeloffice/core';
import type { Event } from '@pixeloffice/protocol';
import { readOfficeTexts } from '@pixeloffice/validate-maps';
import { TalkBubbles } from './bubbles.ts';
import { ocsGet, type OcsAuth } from './ocs.ts';
import { pollOnce } from './poller.ts';

// Опросчик Nextcloud: раз в 30 с снимок статусов и облачка Talk → POST /v1/events (спека 6.2).
const USAGE = `использование:
  NC_URL=… NC_USER=… NC_APP_PASSWORD=… PIXELOFFICE_URL=http://127.0.0.1:4870 PIXELOFFICE_TOKEN=… \\
  node adapters/nextcloud/src/main.ts --office <каталог офиса>   [NC_POLL_SEC=30]`;
const args = process.argv.slice(2);
const officeDir = args.includes('--office') ? args[args.indexOf('--office') + 1] : undefined;
const need = ['NC_URL', 'NC_USER', 'NC_APP_PASSWORD', 'PIXELOFFICE_URL', 'PIXELOFFICE_TOKEN'] as const;
const missing = need.filter((k) => !process.env[k]);
if (!officeDir || missing.length) {
  console.error(`${missing.length ? `нет переменных: ${missing.join(', ')}\n` : ''}${USAGE}`);
  process.exit(2);
}
const cfg = parseConfig(readOfficeTexts(officeDir).texts.config);
if (!cfg.ok) {
  console.error(cfg.errors.map((e) => e.message).join('\n'));
  process.exit(1);
}
const config = cfg.value;
const auth: OcsAuth = { baseUrl: process.env['NC_URL']!, user: process.env['NC_USER']!, appPassword: process.env['NC_APP_PASSWORD']! };
const target = new URL('/v1/events', process.env['PIXELOFFICE_URL']!);
const token = process.env['PIXELOFFICE_TOKEN']!;
const uidToEntity = new Map(config.people.flatMap((p) => (p.nextcloudUid ? [[p.nextcloudUid, p.id] as const] : [])));
const bubbles = new TalkBubbles(config.bubbles.talk, uidToEntity);
const intervalMs = Number(process.env['NC_POLL_SEC'] ?? 30) * 1000;

async function send(events: Event[]) {
  for (let i = 0; i < events.length; i += 500) {
    const res = await fetch(target, {
      method: 'POST',
      headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
      body: JSON.stringify({ events: events.slice(i, i + 500) }),
      signal: AbortSignal.timeout(10_000),
    });
    if (!res.ok) console.warn(`сервер офиса: ${res.status} ${await res.text()}`);
  }
}

let busy = false;
async function tick() {
  if (busy) return; // предыдущий опрос ещё идёт
  busy = true;
  try {
    const events = await pollOnce({
      get: (path) => ocsGet(auth, path),
      people: config.people,
      statusMap: config.nextcloud.statusMap,
      bubbles,
      now: () => new Date(),
      warn: (m) => console.warn(m),
    });
    await send(events);
    console.log(`${new Date().toLocaleTimeString()} снимок отправлен, облачков: ${events.length - 1}`);
  } catch (e) {
    console.warn(`опрос пропущен: ${(e as Error).message}`);
  } finally {
    busy = false;
  }
}

await tick();
setInterval(() => void tick(), intervalMs);
```

Run: `pnpm vitest run adapters/nextcloud` → PASS.

- [ ] **Step 8: шаблон ручной проверки `docs/spikes/m4-nextcloud-live.md`** (вне git)

```markdown
# M4 — опросчик Nextcloud на живом сервере

Статус: **ожидает человека** (нужны NC_URL, сервисный пользователь и app password; сначала — M0(б), см. 2026-10-20-m0-nextcloud.md).

## Шаги
1. Если M0(б) изменил таблицу статусов или поля API — поправить `adapters/nextcloud/src/map.ts`, фикстуры и тесты.
2. `node packages/server/src/main.ts init offices/team`, вписать людей с `nextcloudUid` в `offices/team/config.yaml`.
3. `node packages/server/src/main.ts serve offices/team --port 4880`.
4. `NC_URL=… NC_USER=pixeloffice-bot NC_APP_PASSWORD=… PIXELOFFICE_URL=http://127.0.0.1:4880 PIXELOFFICE_TOKEN=<token источника nextcloud> node adapters/nextcloud/src/main.ts --office offices/team`

## Результат (заполнить)
1. Люди online в Nextcloud сидят на своих местах (через dwell 60 с): …
2. Звонок в комнате бота → участники идут в переговорку: …
3. «In a call» без видимого звонка → online: …
4. Сообщение в Talk → облачко над автором, режим truncated: …
5. Ошибки/предупреждения опросчика: …
```

- [ ] **Step 9: гейт и коммит**

```bash
pnpm gate
git add adapters/nextcloud pnpm-lock.yaml
git commit -m "feat(nextcloud): опросчик User Status и Talk — снимок с приоритетом встречи и облачка"
```

**Критерий готовности:** тесты маппинга (приоритет `meeting`, `statusMap`, In a call, неизвестный статус), облачков (без истории, режимы, пропуски) и опроса по фикстурам зелёные. Живая проверка вынесена в ручной шаблон.

---

## Этап M5. Командный офис и ретрансляция

### Задача 31: `offices/team` и инструкция развёртывания

**Files:**
- Create: `offices/team/{office.yaml,rules.yaml,config.example.yaml,README.md}`
- Test: `pnpm validate:maps` (структура `offices/team`)

**Interfaces:**
- Consumes: схема офиса, каталог, `validate:maps`, `init` (задача 20).
- Produces: командный офис для сервера за reverse proxy. Источники: `nextcloud` (люди), `relay-<owner>` (агенты, ретранслированные с ноутбука хозяина). Реального деплоя в плане нет — только конфиг и инструкция.

- [ ] **Step 1: `offices/team/office.yaml`**

Сетка — как у demo: 9 мест-углов, две переговорки, лаунж, коворкинг. Это стартовая раскладка, которую команда потом правит под себя.
```bash
cp offices/demo/office.yaml offices/team/office.yaml
```
Первые две строки-комментария файла заменить на:
```yaml
# Командный офис: 9 углов (pod:p1…p9), переговорки на 4 и 10 мест, лаунж, коворкинг.
# Люди и их углы — в config.yaml (people[].pod); раскладку меняйте здесь, проверка: pnpm validate:maps.
```

- [ ] **Step 2: `offices/team/rules.yaml`** — как у local (спека 5.3)

```yaml
dwell: { agent: 20s, human: 60s }
human:
  online:  [own_seat]
  meeting: [meeting_room, meeting_room_standing]
  offline: [exit]
agent:
  working:     [owner_pod_seat, "zone:coworking:pose=sit"]
  idle:        ["zone:lounge:pose=play", "zone:lounge"]
  needs_input: [current_work_seat, owner_pod_seat, "zone:coworking:pose=sit"]
  offline:     [exit]
```

- [ ] **Step 3: `offices/team/config.example.yaml`**

```yaml
# Командный офис. Рабочий config.yaml: `node packages/server/src/main.ts init offices/team` (токены случайные).
# Реальные имена, uid Nextcloud и аватары вписать в config.yaml — он не коммитится.
officeId: team
catalog: ../../catalog/limezu/catalog.yaml
listen: { host: 127.0.0.1, port: 4880 }   # наружу — только через reverse proxy (README)
assetsDir: /srv/pixeloffice/assets         # PNG LimeZu копируются на сервер вручную, в git их нет
dataDir: /var/lib/pixeloffice/team
log: { keepDays: 30 }
agentRetentionDays: 7
viewerTokens: [ "CHANGE_ME_viewer" ]
sources:
  - { source: nextcloud, token: "CHANGE_ME_nextcloud", ttlSec: 120 }
  # Ретрансляция агентов с ноутбука: по источнику на хозяина (спека 4.5). Токен отдать хозяину для relay.token.
  - { source: relay-p1, token: "CHANGE_ME_relay_p1", owner: p1,
      ttlSec: { working: 900, idle: 43200, needs_input: 43200 } }
people:
  - { id: p1, name: Человек 1, nextcloudUid: user1, pod: "pod:p1", avatar: { body: 1, eyes: 1, outfit: [1, 1], hair: [1, 1] } }
  - { id: p2, name: Человек 2, nextcloudUid: user2, pod: "pod:p2", avatar: { body: 2, eyes: 2, outfit: [2, 1], hair: [2, 1] } }
  - { id: p3, name: Человек 3, nextcloudUid: user3, pod: "pod:p3", avatar: { body: 3, eyes: 3, outfit: [3, 1], hair: [3, 1] } }
nextcloud:
  statusMap: { online: online, away: online, dnd: online, busy: online, invisible: offline, offline: offline }
bubbles: { talk: truncated }
```
Аватары — те же номера, что у demo (они проходят проверку атласа).

```bash
pnpm validate:maps
```
Expected: `✓ offices/team — структура: ok` (вместе с demo и local). Если `assetsDir` на этой машине не существует, проверка атласа для team пропускается с заметкой — это ожидаемо.

- [ ] **Step 4: `offices/team/README.md` — развёртывание (реального деплоя нет)**

````markdown
# Командный офис — развёртывание

Сервер — тот же `packages/server`, другой каталог офиса. Ниже — инструкция для Linux-хоста с systemd и Caddy. Ничего из этого план реализации не выполняет.

## 1. Хост
1. Node 24 LTS, pnpm 12 (`corepack enable pnpm`).
2. `git clone … /opt/pixeloffice && cd /opt/pixeloffice && pnpm install --frozen-lockfile && pnpm --filter @pixeloffice/viewer build`.
3. Ассеты LimeZu (лицензия запрещает их распространять — только на свой сервер): скопировать `Modern_Office_Revamped_v1.2` и `modern-interiors` в `/srv/pixeloffice/assets` той же структурой, что `~/tmp` на ноутбуке. Права — только пользователю сервиса.
4. `node packages/server/src/main.ts init offices/team`, затем в `offices/team/config.yaml`: люди, uid Nextcloud, углы, аватары, источники `relay-<id>` на каждого, кто ретранслирует агентов.
5. `node packages/server/src/main.ts check offices/team` — офис и атлас валидны.

## 2. systemd: `/etc/systemd/system/pixeloffice-team.service`
```ini
[Unit]
Description=PixelOffice team
After=network-online.target

[Service]
User=pixeloffice
WorkingDirectory=/opt/pixeloffice
ExecStart=/usr/bin/node packages/server/src/main.ts serve offices/team
Restart=on-failure

[Install]
WantedBy=multi-user.target
```

Опросчик Nextcloud — второй юнит `pixeloffice-nextcloud.service` с `EnvironmentFile=/etc/pixeloffice/nextcloud.env` (`NC_URL`, `NC_USER`, `NC_APP_PASSWORD`, `PIXELOFFICE_URL=http://127.0.0.1:4880`, `PIXELOFFICE_TOKEN=<nextcloud token>`) и `ExecStart=/usr/bin/node adapters/nextcloud/src/main.ts --office offices/team`.

## 3. Caddy (TLS и WebSocket)
```
office.example.com {
  reverse_proxy 127.0.0.1:4880
}
```
Caddy проксирует WebSocket без доп. настроек. Сервер слушает только 127.0.0.1.

## 4. Доступ
1. Зрителям — ссылка `https://office.example.com/?token=<viewerTokens[0]>`; после первого входа токен живёт в HttpOnly-cookie, URL очищается.
2. Хозяину агентов — его `relay-<id>` токен; на ноутбуке в `offices/local/config.yaml`:
   ```yaml
   relay:
     target: https://office.example.com/v1/events
     token: "<relay-<id> токен>"
     include: [ "~/Projects/Work/**" ]
   ```
3. Смена токена — правка `config.yaml` и `systemctl restart pixeloffice-team`.

## 5. Обновление
`git pull && pnpm install --frozen-lockfile && pnpm --filter @pixeloffice/viewer build && systemctl restart pixeloffice-team pixeloffice-nextcloud`.
````

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

```bash
pnpm gate
git add offices/team
git status --short offices/team      # нет config.yaml
git commit -m "feat(offices): командный офис team и инструкция развёртывания"
```

**Критерий готовности:** `offices/team` проходит `validate:maps`. В git только `config.example.yaml`. README описывает systemd, Caddy, токены и ассеты.

---

### Задача 32: server — ретрансляция агентов на командный сервер

**Files:**
- Create: `packages/server/src/relay.ts`
- Modify: `packages/server/package.json` (зависимость `picomatch`), `packages/server/src/main.ts`, `packages/server/src/index.ts`
- Test: `packages/server/tests/relay.test.ts`

**Interfaces:**
- Consumes: `Event` (protocol); `expandHome` (validate-maps); `Logger`; `OfficeRuntime` с `RuntimeOptions.relay: { offer(ev: Event): void }` (задача 18 уже вызывает `relay.offer` для принятых событий, кроме восстановления и тестового режима); `buildServer` (интеграционный тест).
- Produces: `type RelayOptions = { target: string; token: string; include: string[]; log: Logger; fetchImpl?: typeof fetch; now?: () => number; maxQueue?: number }`, `class Relay { constructor(o); offer(ev: Event): void; flush(): Promise<void>; size(): number }`.

Поведение (спека 4.5):
1. Пересылаются только события с `agent`, у которых `projectDir` подходит под один из glob-ов `include` (`~` раскрывается). Без `projectDir` или с `entityId` (люди) и `snapshot` — не пересылаются.
2. `projectDir` вырезается: командный сервер строит ключ из `project`, `slot` и хозяина relay-токена.
3. Очередь не длиннее 1000 событий (при переполнении выбрасываются самые старые, warn один раз на эпизод).
4. `flush()` вызывается раз в секунду: до 500 событий одним POST. 2xx — убрать из очереди. Прочие 4xx (400/401/403…) — пачка выбрасывается с `log.error` (повтор не поможет). Сеть, 5xx, 408 и 429 (временные ответы прокси и лимитов) — пачка остаётся, задержка 1 с, 2 с, 4 с … до 60 с.
5. `at` событий сохраняется: порядок на командном сервере по нему, ttl считается от приёма (спека 4.3).

- [ ] **Step 1: зависимость**

```bash
pnpm --filter @pixeloffice/server add picomatch@latest
pnpm --filter @pixeloffice/server add -D @types/picomatch@latest
```

- [ ] **Step 2: падающие тесты `packages/server/tests/relay.test.ts`**

```ts
import { homedir } from 'node:os';
import type { AddressInfo } from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
import type { Event } from '@pixeloffice/protocol';
import { ManualClock, OfficeRuntime, Relay, buildServer, memoryLogger, silentLogger } from '../src/index.ts';
import { demoOffice, iso } from './helpers.ts';

const AT = '2026-10-20T10:00:00.000Z';
const agentEv = (projectDir: string | undefined, slot = '%1'): Event => ({
  type: 'status',
  agent: { project: 'Proj', slot, ...(projectDir ? { projectDir } : {}) },
  status: 'working',
  at: AT,
});

type Call = { url: string; auth: string | null; body: { events: Event[] } };
function fakeFetch(statuses: number[], calls: Call[]): typeof fetch {
  return (async (url: URL | string, init?: RequestInit) => {
    calls.push({ url: String(url), auth: new Headers(init?.headers).get('authorization'), body: JSON.parse(String(init?.body)) });
    const status = statuses.shift() ?? 200;
    if (status === 0) throw new TypeError('fetch failed');
    return new Response('{}', { status });
  }) as typeof fetch;
}

const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

describe('Relay', () => {
  it('фильтр по glob с ~, projectDir вырезается, люди и snapshot не идут', async () => {
    const calls: Call[] = [];
    const r = new Relay({ target: 'https://team/v1/events', token: 'relay-token', include: ['~/Projects/Work/**'], log: silentLogger, fetchImpl: fakeFetch([], calls) });
    r.offer(agentEv(`${homedir()}/Projects/Work/acme`));
    r.offer(agentEv(`${homedir()}/Projects/My/secret`));
    r.offer(agentEv(undefined));
    r.offer({ type: 'status', entityId: 'p1', status: 'online', at: AT });
    r.offer({ type: 'snapshot', entities: [], at: AT });
    expect(r.size()).toBe(1);
    await r.flush();
    expect(calls).toHaveLength(1);
    expect(calls[0]!.auth).toBe('Bearer relay-token');
    expect(calls[0]!.body.events).toEqual([{ type: 'status', agent: { project: 'Proj', slot: '%1' }, status: 'working', at: AT }]);
    expect(r.size()).toBe(0);
  });

  it('сетевая ошибка и 5xx — повтор с растущей задержкой; 4xx — пачка выброшена', async () => {
    const calls: Call[] = [];
    let now = 0;
    const log = memoryLogger();
    const r = new Relay({ target: 'https://team/v1/events', token: 't'.repeat(8), include: ['/w/**'], log, fetchImpl: fakeFetch([0, 503, 200, 403], calls), now: () => now });
    r.offer(agentEv('/w/a'));
    await r.flush(); // сеть упала → ждать 1 с
    await r.flush(); // рано — запроса нет
    expect(calls).toHaveLength(1);
    now = 1000;
    await r.flush(); // 503 → ждать 2 с
    now = 2500;
    await r.flush(); // рано
    expect(calls).toHaveLength(2);
    now = 3000;
    await r.flush(); // 200
    expect(r.size()).toBe(0);
    r.offer(agentEv('/w/b'));
    await r.flush(); // 403 → выброшено
    expect(r.size()).toBe(0);
    expect(log.lines.some((l) => l.level === 'error')).toBe(true);
  });

  it('408 и 429 — временные ответы: пачка остаётся и уходит повтором', async () => {
    const calls: Call[] = [];
    let now = 0;
    const r = new Relay({ target: 'https://team/v1/events', token: 't'.repeat(8), include: ['/w/**'], log: silentLogger, fetchImpl: fakeFetch([429, 408, 200], calls), now: () => now });
    r.offer(agentEv('/w/a'));
    await r.flush(); // 429 → ждать 1 с
    expect(r.size()).toBe(1);
    now = 1000;
    await r.flush(); // 408 → ждать 2 с
    expect(r.size()).toBe(1);
    now = 3000;
    await r.flush(); // 200
    expect([r.size(), calls.length]).toEqual([0, 3]);
  });

  it('очередь ограничена: старые вытесняются', () => {
    const r = new Relay({ target: 'https://team/v1/events', token: 't'.repeat(8), include: ['/w/**'], log: silentLogger, fetchImpl: fakeFetch([], []), maxQueue: 3 });
    for (let i = 0; i < 5; i++) r.offer(agentEv('/w/a', `%${i}`));
    expect(r.size()).toBe(3);
  });

  it('два сервера: локальный runtime → relay → командный /v1/events, агент с хозяином relay-токена, без projectDir', async () => {
    const team = new OfficeRuntime({ office: demoOffice(), clock: new ManualClock(), log: silentLogger });
    const srv = await buildServer({ runtime: team, viewerTokens: ['demo-viewer-token'], viewerDist: null, assetsDir: null, testMode: null });
    await srv.app.listen({ port: 0, host: '127.0.0.1' });
    closers.push(() => srv.app.close());
    const target = `http://127.0.0.1:${(srv.app.server.address() as AddressInfo).port}/v1/events`;
    // В demo источник claude-hook с owner p1 играет роль relay-p1 командного офиса.
    const relay = new Relay({ target, token: 'demo-hook-token', include: ['/work/**'], log: silentLogger });
    const clock = new ManualClock();
    const local = new OfficeRuntime({ office: demoOffice(), clock, log: silentLogger, relay });
    local.ingestFromSource(local.sourceByName('claude-hook')!, [
      { type: 'status', agent: { project: 'acme', projectDir: '/work/acme', slot: '%3' }, status: 'working', at: iso(clock) },
      { type: 'status', agent: { project: 'diary', projectDir: '/home/me/diary', slot: '%4' }, status: 'working', at: iso(clock) },
    ]);
    await relay.flush();
    const relayed = team.registry.agentList();
    expect(relayed.map((a) => a.id)).toEqual(['agent:p1:acme:%3']);
    expect(relayed[0]!.projectDir).toBeUndefined();
    expect(team.entityView(relayed[0]!)).not.toHaveProperty('projectDir');
  });
});
```

Run: `pnpm vitest run packages/server/tests/relay.test.ts` → FAIL.

- [ ] **Step 3: `packages/server/src/relay.ts`**

```ts
import picomatch from 'picomatch';
import type { Event } from '@pixeloffice/protocol';
import { expandHome } from '@pixeloffice/validate-maps';
import type { Logger } from './logger.ts';

export type RelayOptions = {
  target: string;
  token: string;
  include: string[];
  log: Logger;
  fetchImpl?: typeof fetch;
  now?: () => number;
  maxQueue?: number;
};

const BATCH = 500;
const MAX_BACKOFF_MS = 60_000;

// Ретрансляция агентов на командный сервер по glob-фильтру projectDir (спека 4.5).
export class Relay {
  private readonly o: RelayOptions;
  private readonly match: (path: string) => boolean;
  private readonly queue: Event[] = [];
  private readonly maxQueue: number;
  private failures = 0;
  private nextTryAt = 0;
  private overflowWarned = false;
  private inFlight = false;

  constructor(o: RelayOptions) {
    this.o = o;
    this.maxQueue = o.maxQueue ?? 1000;
    this.match = picomatch(o.include.map(expandHome), { dot: true });
  }

  size(): number {
    return this.queue.length;
  }

  offer(ev: Event): void {
    if (ev.type === 'snapshot' || !ev.agent?.projectDir || !this.match(ev.agent.projectDir)) return;
    const { projectDir: _private, ...agent } = ev.agent; // приватный путь на командный сервер не уходит
    this.queue.push({ ...ev, agent });
    if (this.queue.length > this.maxQueue) {
      this.queue.splice(0, this.queue.length - this.maxQueue);
      if (!this.overflowWarned) this.o.log.warn(`relay: очередь переполнена (${this.maxQueue}), старые события выброшены`);
      this.overflowWarned = true;
    }
  }

  async flush(): Promise<void> {
    const now = (this.o.now ?? Date.now)();
    if (this.inFlight || this.queue.length === 0 || now < this.nextTryAt) return;
    this.inFlight = true;
    const batch = this.queue.slice(0, BATCH);
    try {
      const res = await (this.o.fetchImpl ?? fetch)(this.o.target, {
        method: 'POST',
        headers: { 'content-type': 'application/json', authorization: `Bearer ${this.o.token}` },
        body: JSON.stringify({ events: batch }),
        signal: AbortSignal.timeout(10_000),
      });
      const transient = res.status === 408 || res.status === 429; // таймаут прокси, лимит — повторяемы, как 5xx
      if (res.ok || (res.status >= 400 && res.status < 500 && !transient)) {
        this.queue.splice(0, batch.length);
        this.failures = 0;
        this.nextTryAt = 0;
        this.overflowWarned = false;
        if (!res.ok) this.o.log.error(`relay: командный сервер отверг ${batch.length} событий: ${res.status} ${await res.text()}`);
        return;
      }
      this.retryLater(now, `HTTP ${res.status}`);
    } catch (e) {
      this.retryLater(now, (e as Error).message);
    } finally {
      this.inFlight = false;
    }
  }

  private retryLater(now: number, why: string): void {
    const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** this.failures++);
    this.nextTryAt = now + delay;
    this.o.log.warn(`relay: ${why}, повтор через ${delay / 1000} с (в очереди ${this.queue.length})`);
  }
}
```

В `index.ts`: `export * from './relay.ts';`

Если в тесте `entityView(...)` не принимает `AgentEntity` напрямую — передать `team.registry.get(id)!`. Суть проверки — в `EntityView` нет `projectDir`.

- [ ] **Step 4: подключение в `main.ts`**

В ветке `serve` перед `const runtime = …` вставить:
```ts
  const relay = !flags.test && config.relay ? new Relay({ ...config.relay, log: consoleLogger }) : undefined;
```
Конструктор runtime дополнить: `new OfficeRuntime({ office, clock: systemClock, log: consoleLogger, eventLog: persistence?.log, relay })`. В `onSecond` первой строкой добавить `void relay?.flush();`. Импорт: `import { Relay } from './relay.ts';`. В лог старта, если `relay` есть: `consoleLogger.info(\`ретрансляция агентов → ${config.relay!.target} (${config.relay!.include.join(', ')})\`)`.

- [ ] **Step 5: прогон, гейт, коммит**

```bash
pnpm vitest run packages/server   # PASS
pnpm gate
git add packages/server pnpm-lock.yaml
git commit -m "feat(server): ретрансляция агентов на командный сервер по фильтру projectDir"
```

**Критерий готовности:** тесты фильтра, вырезания `projectDir`, очереди, повторов с задержкой и связки двух серверов зелёные. Ретрансляция включается только при `relay` в конфиге и не работает в `--test`.

---

### Задача 33: финал MVP — README, полный гейт, визуальный прогон, сводка ручных шагов

**Files:**
- Modify: `README.md`
- Create (вне git): `docs/spikes/2026-10-20-mvp-manual-steps.md`, `docs/spikes/m5/*.png`

**Interfaces:**
- Consumes: всё предыдущее.
- Produces: README, по которому новый человек поднимает локальный и командный офис. Финальный зелёный гейт и визуальный прогон. Список того, что осталось сделать руками.

- [ ] **Step 1: README — полный текст разделов**

Привести `README.md` к структуре (существующие разделы «Запуск» и «Проверки» из задачи 28 сохранить, добавить остальное):
```markdown
# PixelOffice

Пиксельный офис, где люди (Nextcloud) и агенты Claude Code живут как персонажи: сидят за столами, ходят на встречи, отдыхают в лаунже.

Арт: LimeZu — https://limezu.itch.io (Modern Office Revamped, Modern Interiors). PNG арт-паков в репозитории нет и не будет: лицензия запрещает распространение. Положите паки в `~/tmp` (см. `assetsDir` в `config.yaml`).

## Требования
- Node 24 LTS: `brew install node@24`, в каждой сессии `export PATH="/opt/homebrew/opt/node@24/bin:$PATH"`.
- pnpm 12: `corepack enable pnpm` (версия из `packageManager`).

## Структура
- `packages/protocol` — схемы событий и сообщений WebSocket.
- `packages/core` — чистое ядро: офис, каталог, правила, валидация, A*, симуляция.
- `packages/server` — сервер офиса: `/v1/events`, WebSocket, лог событий, ретрансляция.
- `packages/viewer` — зритель на PixiJS.
- `adapters/claude-hook` — hook Claude Code (установка: `adapters/claude-hook/README.md`).
- `adapters/nextcloud` — опросчик Nextcloud.
- `tools/replay` — сценарии и реплей лога; `tools/validate-maps` — проверка карт.
- `catalog/limezu` — каталог арт-пака; `offices/{local,demo,team}` — офисы.

## Запуск
(раздел из задачи 28)

## Агенты Claude Code в офисе
См. `adapters/claude-hook/README.md`: фрагмент для `~/.claude/settings.json` и `~/.config/pixeloffice/hook.json`.

## Командный офис
См. `offices/team/README.md`: развёртывание, Nextcloud, ретрансляция агентов с ноутбука (`relay` в `offices/local/config.yaml`).

## Свой офис
Офис — каталог с `office.yaml` (сетка и зоны), `rules.yaml` (куда идти при каком статусе), `config.yaml` (люди, токены). После правки — `pnpm validate:maps`; ошибки указывают файл и клетку.

## Проверки
(раздел из задачи 28)
```

- [ ] **Step 2: полный гейт**

```bash
pnpm install --frozen-lockfile
pnpm gate                 # test + typecheck + validate:maps — всё зелёное
pnpm test:visual          # 5 passed (ассеты есть)
git status --short        # чисто, нет *.png, нет offices/local|team/config.yaml
```

- [ ] **Step 3: визуальный прогон итогов M4–M5**

Хук «вживую» не ставится (решение 23, Global Constraints 12), поэтому имитация на тех же интерфейсах: события hook-а через `main.ts` и ретрансляция на второй сервер.
```bash
node packages/server/src/main.ts serve offices/demo --port 4871 &        # «командный» — demo без --test
DEMO=$!
curl -sf -o /dev/null --noproxy '*' --retry 30 --retry-delay 1 --retry-connrefused http://127.0.0.1:4871/healthz   # ждать готовности: hook шлёт события сразу
for ev in SessionStart UserPromptSubmit; do
  echo "{\"hook_event_name\":\"$ev\",\"session_id\":\"s1\",\"source\":\"startup\"}" | \
    PIXELOFFICE_URL=http://127.0.0.1:4871 PIXELOFFICE_TOKEN=demo-hook-token TMUX_PANE=%7 CLAUDE_PROJECT_DIR=$PWD PIXELOFFICE_HOOK_DEBUG=1 \
    node adapters/claude-hook/src/main.ts
done
echo '{"hook_event_name":"Notification","notification_type":"permission_prompt","message":"Разрешить запуск pnpm test?","session_id":"s1"}' | \
  PIXELOFFICE_URL=http://127.0.0.1:4871 PIXELOFFICE_TOKEN=demo-hook-token TMUX_PANE=%7 CLAUDE_PROJECT_DIR=$PWD node adapters/claude-hook/src/main.ts
sleep 25
node packages/viewer/scripts/shot.ts "http://127.0.0.1:4871/?token=demo-viewer-token" docs/spikes/m5/hook.png
kill $DEMO
```
Открыть `docs/spikes/m5/hook.png`: агент «Анна · PixelOffice» в углу Анны или коворкинге, над ним жёлтое облачко «? Разрешить запуск pnpm test?».

- [ ] **Step 4: сводка ручных шагов `docs/spikes/2026-10-20-mvp-manual-steps.md`** (вне git)

Содержимое — раздел «Ручные шаги для человека» этого плана, со ссылками на шаблоны:
`docs/spikes/2026-10-20-m0-nextcloud.md`, `docs/spikes/m4-claude-hook-live.md`, `docs/spikes/m4-nextcloud-live.md`, `offices/team/README.md`. Отметить, какие визуальные скриншоты лежат в `docs/spikes/m3/` и `docs/spikes/m5/`.

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

```bash
git add README.md
git commit -m "docs: README MVP — запуск, адаптеры, командный офис"
git log --oneline master..HEAD    # история ветки feat/v2-mvp; merge и push не делаем
```

**Критерий готовности:** `pnpm gate` и `pnpm test:visual` зелёные. Скриншот `hook.png` просмотрен. Ветка `feat/v2-mvp` содержит все коммиты MVP без merge и push. Сводка ручных шагов лежит в `docs/spikes/`.

---

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

1. **M0 меняет схему каталога** (раскладка листов, автотайлинг стен, кадры персонажей). Задачи 6, 11, 12 и 16 написаны под схему решения 8. Смягчение: исполнитель M0 правит эти задачи плана до их старта (решения 8 и 9). Альтернатива автотайлингу по маске — явные части стены в `office.yaml`, если правило по маске не ложится на Room Builder.
2. **Type stripping Node 24 в workspace-пакетах** (`node_modules` через symlink) и новые опции TS 7 (`erasableSyntaxOnly`, `allowImportingTsExtensions`). Если Node откажется исполнять `.ts` из пакета — запасной путь решения 2: `tsx` как devDependency, команды `tsx file.ts`, код не меняется. Если `tsc` 7 не принимает опцию — убрать её из `tsconfig.base.json`, правило (без enum и parameter properties) проверять ревью.
3. **API Nextcloud не проверен на реальном сервере** (видимость звонков, «In a call», `/statuses`, 304 у чата). Адаптер пишется по документации и фикстурам. Смягчение: ручной M0(б) и `m4-nextcloud-live.md`; изменения ограничены `map.ts`, фикстурами и тестами. Альтернатива `/statuses` (если боту закрыт) — `GET …/user_status/api/v1/statuses/{userId}` по каждому человеку.
4. **Недетерминизм скриншот-тестов** (загрузка шрифта, тайминги `fit`, анимационные кадры, асинхронная загрузка слоёв). Смягчение: тестовый режим без интерполяции и дельт, кадр анимации 0, флаг `__pixelofficeReady` после загрузки слоёв и двух кадров, `maxDiffPixels: 0` и двойной прогон в задаче 28. Альтернатива при стойком дребезге — сравнивать `canvas.toDataURL()` вместо скриншота страницы.
5. **Corepack и pnpm 12** (подписи, `minimumReleaseAge` и одобрение build-скриптов в pnpm 11+). Запасной путь: `npm i -g pnpm@12.14.0` из node@24. Если pnpm блокирует свежие версии из-за `minimumReleaseAge` — ставить последнюю допустимую. Esbuild (Vite) добавить в `onlyBuiltDependencies`, если pnpm спросит одобрение.
6. **В паках нет подходящего спрайта** аркады, переговорного стола или доски нужного размера. Смягчение: решения 10–11 указывают кандидатов (`14_Basement`), предмет можно составить из нескольких частей (`parts`). Если спрайта нет совсем — заменить предмет в каталоге (например, аркаду на настольный футбол) без изменения схемы офиса.
7. **Поведение hook-ов Claude Code** (точные `notification_type`, порядок async-событий, `PostToolUseFailure`). Маппинг покрыт тестами по спеке. Расхождения правятся в `map.ts` по итогам `m4-claude-hook-live.md`; правило порядка по `at` на сервере закрывает переупорядочивание.
8. **Нагрузка на `World` при 20+ агентах** (A\* на каждую смену цели). Сетки офисов малы (≤ 32×14), A\* с бинарной кучей укладывается в доли миллисекунды. При проблемах — кэш путей по паре клеток с инвалидацией на смене броней.

## Ручные шаги для человека

План их не выполняет, автономная реализация от них не зависит.

1. **M0(б) — живой прогон спайка Nextcloud.** Создать сервисного пользователя и app password, запустить `adapters/nextcloud/scripts/spike.ts`, заполнить `docs/spikes/2026-10-20-m0-nextcloud.md`. По итогам — правки `adapters/nextcloud/src/map.ts` и фикстур.
2. **Установка hook-а Claude Code.** `node packages/server/src/main.ts init offices/local`, `~/.config/pixeloffice/hook.json` и фрагмент `~/.claude/settings.json` из `adapters/claude-hook/README.md`.
3. **Живая проверка hook-а.** Заполнить `docs/spikes/m4-claude-hook-live.md`, в том числе реальные `notification_type` и смысл `elicitation_*`/`agent_*`.
4. **Живая проверка опросчика Nextcloud.** Заполнить `docs/spikes/m4-nextcloud-live.md`.
5. **Развёртывание командного офиса.** По `offices/team/README.md`: хост, ассеты, systemd, Caddy, токены.
6. **Ретрансляция.** Выдать себе `relay-<id>` токен на командном сервере, включить `relay` в `offices/local/config.yaml`, убедиться, что агенты рабочих проектов появились в командном офисе, а личные — нет.
7. **Merge ветки `feat/v2-mvp` в `master` и push** — по решению человека после просмотра.
