# Серверный мини-атлас — план реализации

> **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:** сервер пакует все использованные кадры hello (карта, транспорт, облачка разговора) в один PNG и отдаёт его одним запросом `/atlas/<sha256>.png` с `Cache-Control: private, max-age=31536000, immutable` — вместо 24–27 запросов целых листов (демо: ~4,8 МБ → ~0,2 МБ, без водопада и ревалидаций).

**Architecture:** чистые функции сбора кадров, shelf-упаковки и переписывания hello — в новом `packages/server/src/atlas.ts`; `AtlasStore` — асинхронная паковка с кешем в памяти (промис на hash) и на диске (`<dataDir>/atlas/<hash>.png`, атомарная запись). `OfficeRuntime` запускает паковку в конструкторе без ожидания и держит атласные копии `map`/`vehicleKit`/`characterLayout`; `hello()` отдаёт их по готовности, до готовности и при ошибке — исходные URL листов. Старт (`main.ts`), `apply`/`rollback` (`OfficeHost`) и тестовый режим (`renderScenario`) ждут готовности через `OfficeRuntime.ready()`; маршрут `/atlas/:hash.png` в `http.ts` закрыт общим крюком токена зрителя. Вьюер и протокол не меняются: `Frame` тот же, меняется содержимое `sheet`.

**Tech Stack:** TypeScript без сборки (Node снимает типы; `erasableSyntaxOnly` — без enum/namespace/parameter properties; импорты с `.ts`), pngjs 7.0.0 (уже в зависимостях `packages/server`), `node:crypto` (sha256), Fastify 5, vitest.

Спека: [docs/superpowers/specs/2026-11-25-server-atlas-design.md](file:///Users/stas/Projects/My/PixelOffice/docs/superpowers/specs/2026-11-25-server-atlas-design.md). Пометки в комментариях кода — «спека атласа <пункт>».

## Общие ограничения

- Комментарии в коде — кириллицей; пометки «спека атласа <пункт>» ведут в спеку.
- `core` не трогаем: каталог только для чтения (проверяет `purity.test.ts`); протокол (`packages/protocol`) и вьюер — без правок: `Frame` тот же, меняется содержимое `sheet`.
- Новых зависимостей нет: pngjs 7.0.0 уже в `packages/server/package.json`.
- Коммиты — на русском, conventional commits без emoji и без строк атрибуции (правило пользователя). Реализация — в ветке `feat/server-atlas` от `master`, в ворктри по конвенции проекта; спека и план — в основном дереве.
- Тесты одной задачи: `pnpm vitest run --project server packages/server/tests/atlas.test.ts` (аналогично для других файлов); перед финалом — `pnpm gate`.
- Фикстуры — крошечные настоящие PNG во временном `assetsDir`: в CI ассетов нет, каталог demo грузится по тексту, листы тесты пишут сами.
- `dataDir` уже вне git (`.gitignore` `.data/`) — кеш атласа туда и ложится, новых правил gitignore не нужно.

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

- Создать `packages/server/src/atlas.ts` — весь мини-атлас: `frameKey`, `collectFrames`, `packAtlas`, `atlasHash`, `renderAtlasPng`, `rewriteMap`/`rewriteVehicleKit`/`rewriteLayout`, `AtlasStore`. Чистые функции отделены от дискового кеша; одна ответственность — «мини-атлас».
- Создать `packages/server/tests/atlas.test.ts` — юниты: сбор кадров, упаковка, переписывание, `AtlasStore` (hash, кеш, попиксельно), `OfficeRuntime`, `OfficeHost`.
- Создать `packages/server/tests/atlas-http.test.ts` — интеграционный: hello → `/atlas/…`, маршрут и заголовки, доступ, тестовый режим, без `assetsDir`.
- Править `packages/server/src/runtime.ts` — опция `atlas`, атласные копии, `ready()`, атласный `hello()`.
- Править `packages/server/src/host.ts` — опция `atlas` в `HostOptions` и `build`, `apply` ждёт готовности.
- Править `packages/server/src/test-mode.ts` — `renderScenario` асинхронный, ждёт атлас.
- Править `packages/server/src/http.ts` — асинхронный колбэк `testMode` (задача 7, вместе с `renderScenario`), маршрут `/atlas/:hash.png` (задача 8).
- Править `packages/server/src/main.ts` — создание `SheetCache`/`AtlasStore`, ожидание до `listen`.
- Править `packages/server/src/index.ts` — экспорт `atlas.ts`.
- Править `packages/server/tests/helpers.ts` — общие фикстуры `patternPng`/`miniAssets`.
- Править существующие тесты `renderScenario` (переход на async): `tests/test-mode.test.ts`, `tests/ui.test.ts`, `tests/portraits.test.ts`, `tests/avatars-http.test.ts`.
- Править `CLAUDE.md` — абзац об атласе в раздел «Архитектура».

---

### Task 1: `frameKey` и `collectFrames` — сбор кадров hello

**Files:**
- Create: `packages/server/src/atlas.ts`
- Modify: `packages/server/src/index.ts`
- Test: `packages/server/tests/atlas.test.ts`

**Interfaces:**
- Consumes: типы `Frame`, `RenderedMap`, `VehicleKit`, `CharacterLayout` из `@pixeloffice/protocol`; объекты hello офиса demo (`demoOffice()` из `tests/helpers.ts`).
- Produces: `frameKey(f: Frame): string` — ключ дедупа `(sheet, x, y, w, h)`; `collectFrames(map: RenderedMap, kit: VehicleKit | null, layout: CharacterLayout | null): Frame[]` — уникальные кадры одного hello. Используют задачи 2–5.

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

`packages/server/tests/atlas.test.ts`:

```ts
import { ManualClock, OfficeRuntime, collectFrames, frameKey } from '../src/index.ts';
import type { Frame } from '@pixeloffice/protocol';
import { demoOffice } from './helpers.ts';

describe('collectFrames (спека атласа 2.1)', () => {
  const office = demoOffice();
  const h = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(h.map, h.vehicleKit ?? null, h.characterLayout);
  const keys = new Set(frames.map(frameKey));
  const has = (f: Frame): boolean => keys.has(frameKey(f));

  it('карта: пол, спрайты с anim, двери, крыши, земля и полосы участка', () => {
    expect(h.map.floor.every((t) => has(t.frame))).toBe(true);
    expect(h.map.sprites.every((s) => has(s.frame) && (s.anim?.frames ?? [s.frame]).every(has))).toBe(true);
    expect(h.map.doors.every((d) => d.frames.every(has))).toBe(true);
    expect((h.map.roofs ?? []).every((r) => r.sprites.every((s) => has(s.frame)))).toBe(true);
    const site = h.map.site!;
    expect(site.ground.every((g) => g.frames.every(has))).toBe(true);
    expect(site.edges.every((e) => e.frames.every(has))).toBe(true);
  });

  it('транспорт: все направления всех моделей и автобус', () => {
    const kit = h.vehicleKit!;
    expect(kit.cars.every((c) => Object.values(c).every(has))).toBe(true);
    expect(has(kit.bus)).toBe(true);
  });

  it('облачка разговора: appear, tail, icons и sleep', () => {
    const e = h.characterLayout.talk!.emotes;
    const asFrame = (r: { x: number; y: number; w: number; h: number }): Frame => ({ sheet: e.sheet, x: r.x, y: r.y, w: r.w, h: r.h });
    expect(e.appear.every((r) => has(asFrame(r)))).toBe(true);
    expect(has(asFrame(e.tail))).toBe(true);
    expect(e.icons.every(([a, b]) => has(asFrame(a)) && has(asFrame(b)))).toBe(true);
    for (const r of e.sleep ?? []) expect(has(asFrame(r))).toBe(true);
  });

  it('дедуп по (sheet, x, y, w, h): повторяющийся тайл пола — один кадр', () => {
    expect(new Set(frames.map(frameKey)).size).toBe(frames.length);
    expect(frames.length).toBeLessThan(h.map.floor.length); // тайлы пола демо повторяются сотни раз
  });
});
```

- [ ] **Step 2: Запустить тест — убедиться, что падает**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: FAIL — `collectFrames` и `frameKey` не экспортируются (`collectFrames is not a function` / ошибка импорта из `../src/index.ts`).

- [ ] **Step 3: Написать минимальную реализацию**

`packages/server/src/atlas.ts`:

```ts
import type { CharacterLayout, Frame, RenderedMap, VehicleKit } from '@pixeloffice/protocol';

// Ключ кадра атласа (спека атласа 2.1.2): дедуп по (sheet, x, y, w, h).
export const frameKey = (f: Frame): string => `${f.sheet}|${f.x},${f.y},${f.w},${f.h}`;

const rectFrame = (sheet: string, r: { x: number; y: number; w: number; h: number }): Frame => ({ sheet, x: r.x, y: r.y, w: r.w, h: r.h });

// Все кадры одного hello (спека атласа 2.1.1): карта (пол, спрайты с anim, двери, крыши, земля и полосы
// участка), транспорт и облачка разговора. Дедуп по frameKey: тайл пола повторяется сотни раз — в атласе один.
export function collectFrames(map: RenderedMap, kit: VehicleKit | null, layout: CharacterLayout | null): Frame[] {
  const out = new Map<string, Frame>();
  const add = (f: Frame): void => void out.set(frameKey(f), f);
  const addSprite = (s: { frame: Frame; anim?: { frames: Frame[] } }): void => {
    add(s.frame);
    for (const f of s.anim?.frames ?? []) add(f);
  };
  for (const t of map.floor) add(t.frame);
  for (const s of map.sprites) addSprite(s);
  for (const d of map.doors) for (const f of d.frames) add(f);
  for (const r of map.roofs ?? []) for (const s of r.sprites) addSprite(s);
  if (map.site) {
    for (const g of map.site.ground) for (const f of g.frames) add(f);
    for (const e of map.site.edges) for (const f of e.frames) add(f);
  }
  if (kit) {
    for (const car of kit.cars) for (const f of Object.values(car)) add(f);
    add(kit.bus);
  }
  const e = layout?.talk?.emotes;
  if (e) {
    for (const r of e.appear) add(rectFrame(e.sheet, r));
    add(rectFrame(e.sheet, e.tail));
    for (const pair of e.icons) for (const r of pair) add(rectFrame(e.sheet, r));
    for (const r of e.sleep ?? []) add(rectFrame(e.sheet, r));
  }
  return [...out.values()];
}
```

- [ ] **Step 4: Экспортировать модуль**

`packages/server/src/index.ts` — добавить строку после `export * from './office.ts';`:

```ts
export * from './atlas.ts';
```

- [ ] **Step 5: Запустить тест — убедиться, что проходит**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: PASS (4 теста).

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

```bash
git add packages/server/src/atlas.ts packages/server/src/index.ts packages/server/tests/atlas.test.ts
git commit -m "feat(server): сбор кадров hello для мини-атласа"
```

---

### Task 2: `packAtlas` — shelf-упаковка с 1 px зазором

**Files:**
- Modify: `packages/server/src/atlas.ts`
- Test: `packages/server/tests/atlas.test.ts`

**Interfaces:**
- Consumes: `frameKey` из задачи 1.
- Produces: `ATLAS_WIDTH = 1024`; `type Placed = { x: number; y: number }`; `packAtlas(frames: Frame[]): { width: number; height: number; placed: Map<string, Placed> }` — чистая детерминированная раскладка. Используют задачи 3–5.

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

Добавить в `packages/server/tests/atlas.test.ts` (импорт `packAtlas` — в общий импорт из `'../src/index.ts'`):

```ts
describe('packAtlas (спека атласа 2.1.3)', () => {
  const f = (sheet: string, x: number, y: number, w: number, h: number): Frame => ({ sheet, x, y, w, h });

  it('кадры не пересекаются, между соседними 1 px, все в пределах страницы', () => {
    const frames = [f('a', 0, 0, 16, 16), f('a', 16, 0, 16, 16), f('b', 0, 0, 100, 8), f('b', 0, 8, 8, 40), f('c', 0, 0, 32, 32)];
    const { width, height, placed } = packAtlas(frames);
    const rects = frames.map((fr) => ({ ...placed.get(frameKey(fr))!, w: fr.w, h: fr.h }));
    for (const r of rects) {
      expect(r.x).toBeGreaterThanOrEqual(0);
      expect(r.y).toBeGreaterThanOrEqual(0);
      expect(r.x + r.w).toBeLessThanOrEqual(width);
      expect(r.y + r.h).toBeLessThanOrEqual(height);
    }
    // кадры, расширенные на 1 px, не пересекаются — это и есть зазор
    for (let i = 0; i < rects.length; i++)
      for (let j = i + 1; j < rects.length; j++) {
        const a = rects[i]!;
        const b = rects[j]!;
        const overlap = a.x < b.x + b.w + 1 && b.x < a.x + a.w + 1 && a.y < b.y + b.h + 1 && b.y < a.y + a.h + 1;
        expect(overlap, `кадры ${i} и ${j} ближе 1 px`).toBe(false);
      }
  });

  it('страница 1024; кадр шире расширяет её; пустой набор — пустая страница', () => {
    expect(packAtlas([f('a', 0, 0, 16, 16)]).width).toBe(1024);
    expect(packAtlas([f('a', 0, 0, 2000, 4)]).width).toBe(2000);
    expect([packAtlas([]).width, packAtlas([]).height]).toEqual([1024, 0]);
  });

  it('детерминирована: один набор — одна раскладка', () => {
    const frames = [f('a', 0, 0, 16, 16), f('a', 16, 0, 16, 8), f('b', 0, 0, 16, 16)];
    const p1 = packAtlas(frames);
    const p2 = packAtlas([...frames].reverse());
    const line = (p: typeof p1): string[] => [...p.placed.entries()].map(([k, v]) => `${k}:${v.x},${v.y}`).sort();
    expect(line(p1)).toEqual(line(p2));
  });
});
```

- [ ] **Step 2: Запустить тест — убедиться, что падает**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: FAIL — `packAtlas is not a function`.

- [ ] **Step 3: Написать реализацию**

Добавить в `packages/server/src/atlas.ts`:

```ts
// Ширина страницы атласа (спека атласа 2.1.3): 1024 px.
export const ATLAS_WIDTH = 1024;

// Куда лёг кадр в атласе.
export type Placed = { x: number; y: number };

// Shelf-упаковка (спека атласа 2.1.3): полки по убыванию высоты кадра, между соседними кадрами 1 px прозрачного
// зазора — при дробном масштабе (вписывание при открытии, ступени зума) nearest-фильтр без зазора тянет пиксель
// соседнего кадра. Вторая страница не заводится: лимита карты 150×100 клеток хватает с запасом; кадр шире
// страницы расширяет её. Чистая и детерминированная: один набор — одна раскладка (tie-break по frameKey).
export function packAtlas(frames: Frame[]): { width: number; height: number; placed: Map<string, Placed> } {
  const list = [...frames].sort((a, b) => b.h - a.h || b.w - a.w || frameKey(a).localeCompare(frameKey(b)));
  const width = Math.max(ATLAS_WIDTH, ...list.map((fr) => fr.w));
  const placed = new Map<string, Placed>();
  let x = 0;
  let y = 0;
  let shelfH = 0;
  for (const fr of list) {
    if (x + fr.w > width) {
      x = 0;
      y += shelfH + 1;
      shelfH = 0;
    }
    placed.set(frameKey(fr), { x, y });
    x += fr.w + 1;
    shelfH = Math.max(shelfH, fr.h);
  }
  return { width, height: list.length ? y + shelfH : 0, placed };
}
```

- [ ] **Step 4: Запустить тест — убедиться, что проходит**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: PASS.

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

```bash
git add packages/server/src/atlas.ts packages/server/tests/atlas.test.ts
git commit -m "feat(server): shelf-упаковка кадров атласа"
```

---

### Task 3: `rewriteMap` / `rewriteVehicleKit` / `rewriteLayout` — переписывание hello

**Files:**
- Modify: `packages/server/src/atlas.ts`
- Test: `packages/server/tests/atlas.test.ts`

**Interfaces:**
- Consumes: `frameKey`, `Placed` из задач 1–2.
- Produces: `rewriteMap(map: RenderedMap, url: string, placed: Map<string, Placed>): RenderedMap`; `rewriteVehicleKit(kit: VehicleKit, url: string, placed: Map<string, Placed>): VehicleKit`; `rewriteLayout(layout: CharacterLayout, url: string, placed: Map<string, Placed>): CharacterLayout` — копии с `sheet = url` и координатами упаковки, исходники не мутируются. Использует задача 5.

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

Добавить в `packages/server/tests/atlas.test.ts` (добавить `packAtlas`, `rewriteLayout`, `rewriteMap`, `rewriteVehicleKit` в импорт из `'../src/index.ts'`; `Rect` — в type-импорт из `'@pixeloffice/protocol'`):

```ts
describe('rewrite* (спека атласа 2.3)', () => {
  const office = demoOffice();
  const h = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(h.map, h.vehicleKit ?? null, h.characterLayout);
  const { placed } = packAtlas(frames);
  const url = '/atlas/test-hash.png';
  const moved = (fr: Frame): Frame => {
    const at = placed.get(frameKey(fr))!;
    return { sheet: url, x: at.x, y: at.y, w: fr.w, h: fr.h };
  };

  it('rewriteMap: пол, спрайты с anim, двери, крыши, участок — координаты упаковки; прочее — те же ссылки', () => {
    const m = rewriteMap(h.map, url, placed);
    h.map.floor.forEach((t, i) => expect(m.floor[i]!.frame).toEqual(moved(t.frame)));
    h.map.sprites.forEach((s, i) => {
      expect(m.sprites[i]!.frame).toEqual(moved(s.frame));
      (s.anim?.frames ?? []).forEach((a, k) => expect(m.sprites[i]!.anim!.frames[k]).toEqual(moved(a)));
      expect(m.sprites[i]!.px).toBe(s.px); // не-кадровые поля копируются как есть
    });
    h.map.doors.forEach((d, i) => d.frames.forEach((a, k) => expect(m.doors[i]!.frames[k]).toEqual(moved(a))));
    (h.map.roofs ?? []).forEach((r, i) => r.sprites.forEach((s, k) => expect(m.roofs![i]!.sprites[k]!.frame).toEqual(moved(s.frame))));
    const site = h.map.site!;
    site.ground.forEach((g, i) => g.frames.forEach((a, k) => expect(m.site!.ground[i]!.frames[k]).toEqual(moved(a))));
    site.edges.forEach((e, i) => e.frames.forEach((a, k) => expect(m.site!.edges[i]!.frames[k]).toEqual(moved(a))));
    expect(m.spots).toBe(h.map.spots);
    expect(m.screenArt).toBe(h.map.screenArt);
  });

  it('rewriteVehicleKit: кадры всех направлений и автобус; lift и engines — прежние', () => {
    const k = rewriteVehicleKit(h.vehicleKit!, url, placed);
    h.vehicleKit!.cars.forEach((c, i) => {
      for (const d of ['up', 'down', 'left', 'right'] as const) expect(k.cars[i]![d]).toEqual(moved(c[d]));
    });
    expect(k.bus).toEqual(moved(h.vehicleKit!.bus));
    expect(k.busLift).toBe(h.vehicleKit!.busLift);
    expect(k.carLift).toBe(h.vehicleKit!.carLift);
    expect(k.engines).toBe(h.vehicleKit!.engines);
  });

  it('rewriteLayout: emotes — URL атласа и координаты упаковки; animations — тот же объект', () => {
    const l = rewriteLayout(h.characterLayout, url, placed);
    const e = h.characterLayout.talk!.emotes;
    const ne = l.talk!.emotes;
    expect(ne.sheet).toBe(url);
    const mv = (r: Rect): Rect => {
      const at = placed.get(frameKey({ sheet: e.sheet, x: r.x, y: r.y, w: r.w, h: r.h }))!;
      return { x: at.x, y: at.y, w: r.w, h: r.h };
    };
    expect(ne.appear).toEqual(e.appear.map(mv));
    expect(ne.tail).toEqual(mv(e.tail));
    expect(ne.icons).toEqual(e.icons.map(([a, b]) => [mv(a), mv(b)]));
    expect(l.animations).toBe(h.characterLayout.animations); // не кадры — те же объекты
    expect(l.talk!.speakers).toBe(h.characterLayout.talk!.speakers);
  });
});
```

- [ ] **Step 2: Запустить тест — убедиться, что падает**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: FAIL — `rewriteMap is not a function`.

- [ ] **Step 3: Написать реализацию**

Добавить в `packages/server/src/atlas.ts` (дополнить type-импорт из `'@pixeloffice/protocol'`: `Facing`, `MapSprite`, `Rect`):

```ts
// Переписывание hello на атлас (спека атласа 2.3): копии с URL /atlas/<hash>.png и координатами упаковки;
// URL без хоста — как у /sprites/..., вьюер за прокси резолвит сам (спека 2.3.4). Исходные объекты не мутируются
// (предпросмотр и SheetCache живут по старым путям). Кадр вне placed — недостижимая по построению ветка
// (все источники кадров перечислены в collectFrames) — остался бы исходным.
const rewriteFrame = (f: Frame, url: string, placed: Map<string, Placed>): Frame => {
  const at = placed.get(frameKey(f));
  return at ? { sheet: url, x: at.x, y: at.y, w: f.w, h: f.h } : f;
};

export function rewriteMap(map: RenderedMap, url: string, placed: Map<string, Placed>): RenderedMap {
  const frame = (f: Frame): Frame => rewriteFrame(f, url, placed);
  const sprite = (s: MapSprite): MapSprite => ({ ...s, frame: frame(s.frame), ...(s.anim ? { anim: { ...s.anim, frames: s.anim.frames.map(frame) } } : {}) });
  return {
    ...map,
    floor: map.floor.map((t) => ({ ...t, frame: frame(t.frame) })),
    sprites: map.sprites.map(sprite),
    doors: map.doors.map((d) => ({ ...d, frames: d.frames.map(frame) })),
    ...(map.roofs ? { roofs: map.roofs.map((r) => ({ ...r, sprites: r.sprites.map(sprite) })) } : {}),
    ...(map.site
      ? {
          site: {
            ...map.site,
            ground: map.site.ground.map((g) => ({ ...g, frames: g.frames.map(frame) })),
            edges: map.site.edges.map((e) => ({ ...e, frames: e.frames.map(frame) })),
          },
        }
      : {}),
  };
}

export function rewriteVehicleKit(kit: VehicleKit, url: string, placed: Map<string, Placed>): VehicleKit {
  const frame = (f: Frame): Frame => rewriteFrame(f, url, placed);
  return {
    ...kit,
    cars: kit.cars.map((c) => Object.fromEntries(Object.entries(c).map(([d, f]) => [d, frame(f)])) as Record<Facing, Frame>),
    bus: frame(kit.bus),
  };
}

export function rewriteLayout(layout: CharacterLayout, url: string, placed: Map<string, Placed>): CharacterLayout {
  const t = layout.talk;
  if (!t) return layout;
  const move = (r: Rect): Rect => {
    const at = placed.get(frameKey({ sheet: t.emotes.sheet, x: r.x, y: r.y, w: r.w, h: r.h }));
    return at ? { ...r, x: at.x, y: at.y } : r;
  };
  return {
    ...layout,
    talk: {
      ...t,
      emotes: {
        ...t.emotes,
        sheet: url,
        appear: t.emotes.appear.map(move),
        tail: move(t.emotes.tail),
        icons: t.emotes.icons.map(([a, b]) => [move(a), move(b)]),
        ...(t.emotes.sleep ? { sleep: t.emotes.sleep.map(move) as [Rect, Rect] } : {}),
      },
    },
  };
}
```

- [ ] **Step 4: Запустить тест — убедиться, что проходит**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: PASS.

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

```bash
git add packages/server/src/atlas.ts packages/server/tests/atlas.test.ts
git commit -m "feat(server): переписывание hello на атлас"
```

---

### Task 4: `AtlasStore` — hash, PNG и кеш в памяти и на диске

**Files:**
- Modify: `packages/server/src/atlas.ts`
- Modify: `packages/server/tests/helpers.ts` (фикстуры мини-листов)
- Test: `packages/server/tests/atlas.test.ts`

**Interfaces:**
- Consumes: `frameKey`, `packAtlas` (задачи 1–2); `SheetSource` из `./preview.ts` (`{ get(name: string): Promise<PNG> }`, его реализует `SheetCache`); `Logger` из `./logger.ts`; `Catalog` из `@pixeloffice/core`.
- Produces: `atlasHash(frames: Frame[], sheetMeta: Map<string, { size: number; mtimeMs: number }>): string` — sha256; `renderAtlasPng(frames, placed, width, height, sheets: SheetSource): Promise<PNG>`; `sheetRel(sheet: string, catalog: Catalog): string | null`; `type AtlasPlan = { url: string; rects: Map<string, Placed> }`; `class AtlasStore { constructor(o: { dataDir: string; assetsDir: string; catalog: Catalog; sheets: SheetSource; log?: Logger }); get(frames: Frame[]): Promise<AtlasPlan | null>; read(hash: string): Promise<Buffer | null> }`. Используют задачи 5–8.

- [ ] **Step 1: Фикстуры мини-листов в helpers.ts**

Добавить в конец `packages/server/tests/helpers.ts` (импорты в начало файла: `mkdirSync, mkdtempSync, writeFileSync` из `node:fs`, `tmpdir` из `node:os`, `dirname, join` из `node:path`, `PNG` из `pngjs`, `type Catalog` из `@pixeloffice/core`, `type Frame` из `@pixeloffice/protocol`, `SheetCache` — в существующий импорт из `'../src/index.ts'`):

```ts
// Пиксельный паттерн мини-листа для тестов атласа: детерминированный и различимый — попиксельное сравнение
// атласа с исходником ловит перепутанные кадры.
export function patternPng(w: number, h: number, seed: number): PNG {
  const png = new PNG({ width: w, height: h });
  for (let y = 0; y < h; y++)
    for (let x = 0; x < w; x++) {
      const i = (y * w + x) * 4;
      png.data[i] = (x * 31 + seed * 5) % 256;
      png.data[i + 1] = (y * 17 + seed * 3) % 256;
      png.data[i + 2] = (x + y * 7 + seed * 11) % 256;
      png.data[i + 3] = 255;
    }
  return png;
}

// Крошечные настоящие PNG во временном assetsDir (спека атласа 4.4): лист — по самому правому-нижнему кадру
// набора. В CI ассетов нет — листы пишут сами тесты. Уборка не нужна: tmpdir прибирает ОС.
export function miniAssets(catalog: Catalog, frames: Frame[]): { assets: string; sheets: SheetCache } {
  const assets = mkdtempSync(join(tmpdir(), 'po-atlas-assets-'));
  const bounds = new Map<string, { w: number; h: number }>();
  for (const f of frames) {
    const b = bounds.get(f.sheet) ?? { w: 0, h: 0 };
    b.w = Math.max(b.w, f.x + f.w);
    b.h = Math.max(b.h, f.y + f.h);
    bounds.set(f.sheet, b);
  }
  let seed = 1;
  for (const [sheet, b] of bounds) {
    const rel = sheet.startsWith('/sprites/') ? sheet.slice('/sprites/'.length) : catalog.sheets[sheet]!;
    mkdirSync(dirname(join(assets, rel)), { recursive: true });
    writeFileSync(join(assets, rel), PNG.sync.write(patternPng(b.w, b.h, seed++)));
  }
  return { assets, sheets: new SheetCache(assets, catalog) };
}
```

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

Добавить в `packages/server/tests/atlas.test.ts` (импорты: `readFileSync, utimesSync, writeFileSync` и `mkdtempSync` из `node:fs`, `tmpdir` из `node:os`, `join` из `node:path`, `PNG` из `pngjs`, `AtlasStore, memoryLogger` и `type SheetSource` — из `'../src/index.ts'`, `miniAssets` — из `'./helpers.ts'`):

```ts
describe('AtlasStore (спека атласа 2.2)', () => {
  const office = demoOffice();
  const h = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(h.map, h.vehicleKit ?? null, h.characterLayout);

  const dataDir = (): string => mkdtempSync(join(tmpdir(), 'po-atlas-data-'));
  const store = (assets: string, sheets: SheetSource): { store: AtlasStore; dataDir: string } => {
    const dir = dataDir();
    return { store: new AtlasStore({ dataDir: dir, assetsDir: assets, catalog: office.bundle.catalog, sheets }), dataDir: dir };
  };

  it('get: план с URL /atlas/<hash>.png, PNG на диске повторяет исходники попиксельно', async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s } = store(assets, sheets);
    const plan = await s.get(frames);
    expect(plan).not.toBeNull();
    expect(plan!.url).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
    const body = await s.read(plan!.url.slice('/atlas/'.length, -'.png'.length));
    const png = PNG.sync.read(body!);
    for (const f of frames) {
      const at = plan!.rects.get(frameKey(f))!;
      const src = await sheets.get(f.sheet);
      let same = true;
      for (let y = 0; y < f.h && same; y++) {
        const from = ((f.y + y) * src.width + f.x) * 4;
        const to = ((at.y + y) * png.width + at.x) * 4;
        same = png.data.subarray(to, to + f.w * 4).equals(src.data.subarray(from, from + f.w * 4));
      }
      expect(same, frameKey(f)).toBe(true);
    }
  });

  it('файл есть — не перепаковываем: тот же store (кеш в памяти) и новый после рестарта', async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s, dataDir: dir } = store(assets, sheets);
    const plan = (await s.get(frames))!;
    const file = join(dir, 'atlas', plan.url.slice('/atlas/'.length));
    writeFileSync(file, 'маркер'); // если перепакует — маркер затрётся
    expect((await s.get(frames))!.url).toBe(plan.url); // промис из кеша в памяти
    const restarted = new AtlasStore({ dataDir: dir, assetsDir: assets, catalog: office.bundle.catalog, sheets });
    expect((await restarted.get(frames))!.url).toBe(plan.url); // файл на диске есть
    expect(readFileSync(file, 'utf8')).toBe('маркер');
  });

  it('правка листа меняет hash: и mtime, и байтовый размер (спека атласа 2.2.1)', async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s } = store(assets, sheets);
    const url1 = (await s.get(frames))!.url;
    const someSheet = join(assets, frames[0]!.sheet.slice('/sprites/'.length));
    utimesSync(someSheet, new Date(), new Date(Date.now() + 5000)); // правка пикселей без смены размеров ловится mtime
    const url2 = (await s.get(frames))!.url;
    expect(url2).not.toBe(url1);
    const old = PNG.sync.read(readFileSync(someSheet));
    writeFileSync(someSheet, PNG.sync.write(new PNG({ width: old.width + 1, height: old.height }))); // другой размер файла
    const url3 = (await s.get(frames))!.url;
    expect(url3).not.toBe(url2);
  });

  it('лист не читается — null и предупреждение в журнал (спека атласа 2.4.1)', async () => {
    const { assets } = miniAssets(office.bundle.catalog, frames);
    const log = memoryLogger();
    const s = new AtlasStore({ dataDir: dataDir(), assetsDir: assets, catalog: office.bundle.catalog, sheets: { get: async () => { throw new Error('битый лист'); } }, log });
    expect(await s.get(frames)).toBeNull();
    expect(log.lines.some((l) => l.level === 'warn' && l.msg.includes('атлас'))).toBe(true);
  });

  it('листа нет на диске — null: stat до паковки', async () => {
    const empty = mkdtempSync(join(tmpdir(), 'po-atlas-empty-'));
    const { sheets } = miniAssets(office.bundle.catalog, frames);
    const s = new AtlasStore({ dataDir: dataDir(), assetsDir: empty, catalog: office.bundle.catalog, sheets });
    expect(await s.get(frames)).toBeNull();
  });

  it('пустой набор — null; read чужого hash — null', async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s } = store(assets, sheets);
    expect(await s.get([])).toBeNull();
    expect(await s.read('0'.repeat(64))).toBeNull();
    expect(await s.read('../../etc/passwd')).toBeNull();
  });
});
```

- [ ] **Step 3: Запустить тесты — убедиться, что падают**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: FAIL — `AtlasStore is not a function` (ошибка создания).

- [ ] **Step 4: Написать реализацию**

Добавить в начало `packages/server/src/atlas.ts` импорты и в конец — хранилище:

```ts
import { createHash, randomBytes } from 'node:crypto';
import { existsSync } from 'node:fs';
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { PNG } from 'pngjs';
import type { Catalog } from '@pixeloffice/core';
import type { Logger } from './logger.ts';
import type { SheetSource } from './preview.ts';
```

```ts
// sha256 набора (спека атласа 2.2.1): по отсортированным кадрам и метаданным листов — байтовому размеру и mtime.
// 32-битного FNV-1a мало: коллизия подложила бы чужой атлас под неизменный immutable-URL; правка пикселей без
// смены размеров ни набор кадров, ни размеры листов не меняют — их ловят размер файла и mtime (pnpm art,
// обновление пака на месте).
export function atlasHash(frames: Frame[], sheetMeta: Map<string, { size: number; mtimeMs: number }>): string {
  const key = JSON.stringify([
    [...frames].map(frameKey).sort(),
    [...sheetMeta.entries()].map(([s, m]) => [s, m.size, m.mtimeMs]).sort(([a], [b]) => (a < b ? -1 : 1)),
  ]);
  return createHash('sha256').update(key).digest('hex');
}

// Сборка PNG атласа (спека атласа 2.1.4): кадры копируются с исходных листов через SheetCache (он уже кеширует
// декодированные листы в памяти процесса); пиксели за краем листа — прозрачные, как в предпросмотре.
export async function renderAtlasPng(
  frames: Frame[],
  placed: Map<string, Placed>,
  width: number,
  height: number,
  sheets: SheetSource,
): Promise<PNG> {
  const png = new PNG({ width, height });
  const bySheet = new Map<string, Frame[]>();
  for (const f of frames) bySheet.set(f.sheet, [...(bySheet.get(f.sheet) ?? []), f]);
  for (const [sheet, list] of bySheet) {
    const src = await sheets.get(sheet);
    for (const f of list) {
      const at = placed.get(frameKey(f))!;
      for (let y = 0; y < f.h; y++)
        for (let x = 0; x < f.w; x++) {
          const fx = f.x + x;
          const fy = f.y + y;
          if (fx >= src.width || fy >= src.height) continue;
          const from = (fy * src.width + fx) * 4;
          const to = ((at.y + y) * width + at.x + x) * 4;
          png.data.set(src.data.subarray(from, from + 4), to);
        }
    }
  }
  return png;
}

// Путь листа в assetsDir: кадры hello несут URL /sprites/...; имя листа каталога — как в SheetCache.
export function sheetRel(sheet: string, catalog: Catalog): string | null {
  if (sheet.startsWith('/sprites/')) return sheet.slice('/sprites/'.length);
  return catalog.sheets[sheet] ?? null;
}

export type AtlasPlan = { url: string; rects: Map<string, Placed> }; // поле rects — имя контракта из спеки атласа 2.5.1
export type AtlasOptions = { dataDir: string; assetsDir: string; catalog: Catalog; sheets: SheetSource; log?: Logger };

// Хранилище мини-атласов (спека атласа 2.2, 2.5.1): кеш в памяти — промис на hash (параллельные паковки одного
// набора не дублируются), на диске — <dataDir>/atlas/<hash>.png с атомарной записью (временный файл + rename —
// обрыв записи не оставит битый PNG под верным именем). Старые файлы не чистятся: их единицы, лежат в dataDir,
// чистка — гонки с concurrent-запросом; лишнее стирается вручную вместе с dataDir (спека 2.2.4).
export class AtlasStore {
  private readonly dir: string;
  private readonly cache = new Map<string, Promise<AtlasPlan | null>>();

  constructor(private readonly o: AtlasOptions) {
    this.dir = join(o.dataDir, 'atlas');
  }

  // Паковка набора кадров hello: null — не удалась (листа нет, pngjs упал) — hello остаётся на исходных листах.
  // Неудача кешируется до конца процесса: набор и метаданные листов не изменились бы, повтор в том же процессе
  // дал бы тот же результат; правка листа меняет hash — новым ключом кеша.
  get(frames: Frame[]): Promise<AtlasPlan | null> {
    if (frames.length === 0) return Promise.resolve(null);
    return this.hashOf(frames)
      .then((hash) => {
        let p = this.cache.get(hash);
        if (!p) {
          p = this.build(frames, hash).catch((e: unknown) => {
            this.o.log?.warn(`атлас не собран: ${(e as Error).message}`);
            return null;
          });
          this.cache.set(hash, p);
        }
        return p;
      })
      .catch((e: unknown) => {
        this.o.log?.warn(`атлас не собран: ${(e as Error).message}`);
        return null;
      });
  }

  // Тело атласа для маршрута /atlas/:hash.png (спека атласа 2.2.3): с диска при запросе, дальше решает
  // браузерный кеш. Имя файла — hex sha256, отдаём только существующие.
  async read(hash: string): Promise<Buffer | null> {
    if (!/^[0-9a-f]{64}$/.test(hash)) return null;
    try {
      return await readFile(join(this.dir, `${hash}.png`));
    } catch {
      return null;
    }
  }

  // sha256 набора с метаданными листов: stat каждого листа, без чтения содержимого.
  private async hashOf(frames: Frame[]): Promise<string> {
    const meta = new Map<string, { size: number; mtimeMs: number }>();
    for (const sheet of new Set(frames.map((f) => f.sheet))) {
      const rel = sheetRel(sheet, this.o.catalog);
      if (!rel) throw new Error(`лист «${sheet}» не найден в каталоге`);
      const st = await stat(join(this.o.assetsDir, rel));
      meta.set(sheet, { size: st.size, mtimeMs: st.mtimeMs });
    }
    return atlasHash(frames, meta);
  }

  private async build(frames: Frame[], hash: string): Promise<AtlasPlan> {
    const { width, height, placed } = packAtlas(frames); // раскладка детерминирована — файлу соответствует
    const file = join(this.dir, `${hash}.png`);
    if (!existsSync(file)) {
      const png = await renderAtlasPng(frames, placed, width, height, this.o.sheets);
      await mkdir(this.dir, { recursive: true });
      const tmp = join(this.dir, `.${hash}.${randomBytes(4).toString('hex')}.tmp`);
      await writeFile(tmp, PNG.sync.write(png));
      await rename(tmp, file);
    }
    return { url: `/atlas/${hash}.png`, rects: placed };
  }
}
```

- [ ] **Step 5: Запустить тесты — убедиться, что проходят**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: PASS (все describe).

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

```bash
git add packages/server/src/atlas.ts packages/server/tests/atlas.test.ts packages/server/tests/helpers.ts
git commit -m "feat(server): AtlasStore — hash, PNG и кеш на диске"
```

---

### Task 5: `OfficeRuntime` — атласные копии hello и `ready()`

**Files:**
- Modify: `packages/server/src/runtime.ts`
- Test: `packages/server/tests/atlas.test.ts`

**Interfaces:**
- Consumes: `AtlasStore`, `collectFrames`, `rewriteMap`, `rewriteVehicleKit`, `rewriteLayout` (задачи 1–4); `characterLayout` из `@pixeloffice/core` (уже импортирован в runtime.ts).
- Produces: `RuntimeOptions.atlas?: AtlasStore | null`; метод `OfficeRuntime.ready(): Promise<void>` — ждёт готовности, никогда не бросает. Используют задачи 6–8.

- [ ] **Step 1: Написать падающие тесты**

Добавить в `packages/server/tests/atlas.test.ts` (импорт `AtlasStore` уже есть; `memoryLogger` — из `'../src/index.ts'`):

```ts
describe('OfficeRuntime с атласом (спека атласа 2.3, 2.5.1)', () => {
  const office = demoOffice();
  const plain = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);
  const { assets, sheets } = miniAssets(office.bundle.catalog, frames);

  it('hello — атласные копии всех трёх частей; до готовности и без атласа — исходные листы', async () => {
    const store = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-rt-')), assetsDir: assets, catalog: office.bundle.catalog, sheets });
    const rt = new OfficeRuntime({ office, clock: new ManualClock(), atlas: store });
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//); // паковка ещё идёт — исходные URL (спека 2.3.3)
    await rt.ready();
    const h = rt.hello();
    const url = h.map.floor[0]!.frame.sheet;
    expect(url).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
    for (const t of h.map.floor) expect(t.frame.sheet).toBe(url);
    for (const s of h.map.sprites) expect(s.frame.sheet).toBe(url);
    expect(h.characterLayout.talk!.emotes.sheet).toBe(url);
    expect(h.vehicleKit!.bus.sheet).toBe(url);
    expect(h.vehicleKit!.cars.every((c) => Object.values(c).every((f) => f.sheet === url))).toBe(true);
    // исходный бандл не тронут (office и так заморожен deepFreeze — мутация бы упала)
    expect(office.bundle.rendered.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    // повторные hello дешёвые: копии не пересобираются (спека 2.3.1)
    expect(rt.hello().map).toBe(h.map);
    expect(rt.hello().characterLayout).toBe(h.characterLayout);
  });

  it('паковка не удалась — hello на исходных листах, ready() не бросает (спека атласа 2.4.1)', async () => {
    const log = memoryLogger();
    const bad = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-rt-')), assetsDir: assets, catalog: office.bundle.catalog, sheets: { get: async () => { throw new Error('упал'); } }, log });
    const rt = new OfficeRuntime({ office, clock: new ManualClock(), atlas: bad, log });
    await expect(rt.ready()).resolves.toBeUndefined();
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    expect(log.lines.some((l) => l.level === 'warn' && l.msg.includes('атлас'))).toBe(true);
  });

  it('без атласа (CI, нет assetsDir) — hello как раньше', () => {
    const rt = new OfficeRuntime({ office, clock: new ManualClock() });
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    expect(rt.hello().characterLayout.talk!.emotes.sheet).toMatch(/^\/sprites\//);
  });
});
```

- [ ] **Step 2: Запустить тесты — убедиться, что падают**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: FAIL — `rt.ready is not a function`, hello со старыми URL.

- [ ] **Step 3: Реализовать в runtime.ts**

1) Импорт (в существующий импорт из `'@pixeloffice/protocol'` добавить `RenderedMap, CharacterLayout` — оба нужны для `AtlasCopies` и поля `layout`, сейчас в runtime.ts их нет; новый импорт модуля атласа):

```ts
import { collectFrames, rewriteLayout, rewriteMap, rewriteVehicleKit, type AtlasStore } from './atlas.ts';
```

2) `RuntimeOptions` — поле (после `portraits`):

```ts
  atlas?: AtlasStore | null; // мини-атлас hello (спека атласа 2.5.1): null — нет assetsDir (CI) или тест без ассетов
```

3) Тип копий и поля класса (рядом с `private readonly vehicleKit`):

```ts
// Атласные копии (спека атласа 2.3.1): hello отдаёт их по готовности; исходные бандл и киты не мутируют.
type AtlasCopies = { map: RenderedMap; vehicleKit: VehicleKit | null; layout: CharacterLayout };
```

```ts
  private readonly layout: CharacterLayout;
  private atlas: AtlasCopies | null = null;
  private readonly atlasReady: Promise<void>;
```

4) Конструктор — в конец, после `this.lastRetentionCheck = this.clock.now();`:

```ts
    // Атлас (спека атласа 2.5.1): паковка запускается без ожидания — конструктор остаётся синхронным; копии
    // появятся по готовности, hello до тех пор — на исходных листах.
    this.layout = characterLayout(catalog.characters, defaultAssetUrl);
    this.atlasReady = o.atlas ? this.startAtlas(o.atlas) : Promise.resolve();
```

5) `hello()` — заменить три строки (`map`, `characterLayout`, ветку `vehicleKit`):

```ts
  hello(test = false): HelloMessage {
    const { bundle } = this.office;
    const kit = this.atlas?.vehicleKit ?? this.vehicleKit;
    return {
      type: 'hello',
      protocol: PROTOCOL_VERSION,
      t: this.world.now(),
      test,
      map: this.atlas?.map ?? bundle.rendered,
      characterLayout: this.atlas?.layout ?? this.layout,
      avatarKit: this.avatarKit(),
      ...(this.uiKit ? { ui: this.uiKit } : {}),
      ...(kit ? { vehicleKit: kit, vehicles: this.world.vehicles() } : {}),
      ...(this.owner() ? { owner: this.owner()! } : {}),
      entities: this.registry.all().map((e) => this.entityView(e)),
      characters: this.world.characters(),
    };
  }
```

6) Публичный метод (после `hello()`):

```ts
  // Готовность атласа (спека атласа 2.5.3): старт ждёт до app.listen, apply/rollback — до отключения зрителей,
  // тестовый режим — перед hello. Не бросает: сбой паковки уже записан в журнал предупреждением (спека 2.4.1).
  async ready(): Promise<void> {
    await this.atlasReady;
  }
```

7) Приватный метод (в раздел «---- внутреннее ----»):

```ts
  // Паковка атласа этого офиса (спека атласа 2.3.1, 2.4.1): копии появляются одним присвоением — зрители видят
  // либо исходные URL, либо готовый атлас целиком.
  private async startAtlas(store: AtlasStore): Promise<void> {
    const { rendered } = this.office.bundle;
    try {
      const frames = collectFrames(rendered, this.vehicleKit, this.layout);
      const plan = await store.get(frames);
      if (!plan) return; // предупреждение уже в журнале хранилища
      this.atlas = {
        map: rewriteMap(rendered, plan.url, plan.rects),
        vehicleKit: this.vehicleKit ? rewriteVehicleKit(this.vehicleKit, plan.url, plan.rects) : null,
        layout: rewriteLayout(this.layout, plan.url, plan.rects),
      };
    } catch (e) {
      this.log.warn(`атлас: ${(e as Error).message} — hello на исходных листах`);
    }
  }
```

- [ ] **Step 4: Запустить тесты — убедиться, что проходят**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: PASS. Затем прогон всех серверных тестов — регрессий нет:
Run: `pnpm vitest run --project server`
Expected: PASS.

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

```bash
git add packages/server/src/runtime.ts packages/server/tests/atlas.test.ts
git commit -m "feat(server): OfficeRuntime — атласные копии hello и ready()"
```

---

### Task 6: `OfficeHost` — опция `atlas`, apply ждёт готовности

**Files:**
- Modify: `packages/server/src/host.ts`
- Test: `packages/server/tests/atlas.test.ts`

**Interfaces:**
- Consumes: `AtlasStore` (задача 4), `OfficeRuntime.ready()` (задача 5), `officeCopy()` из `tests/admin-helpers.ts` (копия demo с временным dataDir).
- Produces: `HostOptions.atlas?: AtlasStore | null` — передаётся каждому `build()`; `applySet` асинхронный. Использует задача 8 (main.ts).

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

Добавить в `packages/server/tests/atlas.test.ts` (импорты: `loadOffice, OfficeHost, VersionStore` — из `'../src/index.ts'`, `officeCopy` — из `'./admin-helpers.ts'`, `parse, stringify` — из `'yaml'`):

```ts
describe('OfficeHost с атласом (спека атласа 2.4.3)', () => {
  it('apply: атлас нового runtime готов до отключения зрителей; тот же набор кадров — тот же hash', async () => {
    const { dir } = officeCopy();
    const office = loadOffice(dir);
    const clock = new ManualClock();
    const plain = new OfficeRuntime({ office, clock }).hello();
    const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const store = new AtlasStore({ dataDir: office.dataDir, assetsDir: assets, catalog: office.bundle.catalog, sheets });
    const host = new OfficeHost({ office, clock, log: memoryLogger(), versions: new VersionStore(office.dataDir, clock), atlas: store });
    // В момент отключения зрителей (onReset) hello уже атласный — это и есть «готовность до onReset» (спека 2.4.3).
    const resets: boolean[] = [];
    host.onReset = () => resets.push(host.runtime.hello().map.floor[0]!.frame.sheet.startsWith('/atlas/'));
    await host.runtime.ready();
    const url = host.runtime.hello().map.floor[0]!.frame.sheet;
    expect(url).toMatch(/^\/atlas\//);
    const people = host.current().files['people.yaml']!;
    const swapped = stringify({ people: (parse(people) as { people: { id: string; pod: string }[] }).people.map((p) => (p.id === 'p1' ? { ...p, pod: 'pod:p6' } : p.id === 'p6' ? { ...p, pod: 'pod:p1' } : p)) });
    const r = await host.apply({ 'people.yaml': swapped }, { comment: 'сменить кабинки' });
    expect(r.status).toBe('applied');
    expect(resets).toEqual([true]);
    // набор кадров не изменился — тот же hash, файл уже на диске, пересборка мгновенная (спека 2.4.3)
    expect(host.runtime.hello().map.floor[0]!.frame.sheet).toBe(url);
  });
});
```

- [ ] **Step 2: Запустить тест — убедиться, что падает**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: FAIL — по ассертам: `build` игнорирует незнакомую опцию, runtime без атласа — hello на исходных листах (`url` не матчит `/atlas/`, `resets` — `[false]`). Vitest типы не проверяет (esbuild без тайпчека) — ошибку «`atlas` нет в `HostOptions`» покажет только `tsc` в `pnpm gate` (задача 9).

- [ ] **Step 3: Реализовать в host.ts**

1) Импорт (после `import { checkFileSet, ... } from './office-files.ts';`):

```ts
import type { AtlasStore } from './atlas.ts';
```

2) `HostOptions` — поле (после `portraits?: boolean;`):

```ts
  atlas?: AtlasStore | null; // мини-атлас hello (спека атласа 2.5.3): один на процесс, передаётся каждому build
```

3) `build()` — добавить `atlas` в вызов `make`:

```ts
  protected build(office: LoadedOffice, avatars: EffectiveAvatars | undefined, sources?: SourceConfig[]): OfficeRuntime {
    const make = this.o.createRuntime ?? ((x: RuntimeOptions) => new OfficeRuntime(x));
    return make({ office, clock: this.o.clock, log: this.o.log, eventLog: this.o.persistence?.log, relay: this.o.relay, avatars, ui: this.o.ui, portraits: this.o.portraits, atlas: this.o.atlas, ...(sources ? { sources } : {}) });
  }
```

4) `applySet` — сделать асинхронным и ждать готовность нового runtime до блока `after` (отключение зрителей — шаг 9):

Сигнатура: `private async applySet(prev: ..., set: ..., kind: ..., comment?: string): Promise<ApplyOutcome> {`

После строки `this.rt = next;` (конец try-блока) и до `const problems: string[] = [];` вставить:

```ts
    // Атлас нового runtime готов до отключения зрителей (спека атласа 2.4.3): переподключение получает атласный
    // hello, а не исходные листы. ready() не бросает — очередь apply не рвётся.
    await next.ready();
```

- [ ] **Step 4: Запустить тесты — убедиться, что проходят**

Run: `pnpm vitest run --project server packages/server/tests/atlas.test.ts`
Expected: PASS. Затем — регресс host-тестов:
Run: `pnpm vitest run --project server packages/server/tests/host-apply.test.ts packages/server/tests/host.test.ts packages/server/tests/host-tokens.test.ts packages/server/tests/admin-apply.test.ts`
Expected: PASS (applySet теперь async — поведение то же, serial-очередь уже промизная).

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

```bash
git add packages/server/src/host.ts packages/server/tests/atlas.test.ts
git commit -m "feat(server): apply ждёт готовности атласа"
```

---

### Task 7: `renderScenario` — асинхронный, ждёт атлас

**Files:**
- Modify: `packages/server/src/test-mode.ts`
- Modify: `packages/server/src/http.ts` — асинхронная ветка `testMode` (в этой же задаче: renderScenario станет промисом, а синхронный обработчик сериализует его в `"{}"`)
- Modify: `packages/server/tests/test-mode.test.ts`
- Modify: `packages/server/tests/ui.test.ts:28-32`
- Modify: `packages/server/tests/portraits.test.ts:29-32`
- Modify: `packages/server/tests/avatars-http.test.ts:177-179`

**Interfaces:**
- Consumes: `OfficeRuntime` с опцией `atlas` и `ready()` (задача 5), `AtlasStore` (задача 4).
- Produces: `renderScenario(office: LoadedOffice, q: Record<string, string | undefined>, opts: { ui?: boolean; portraits?: boolean; atlas?: AtlasStore | null }): Promise<[HelloMessage, DebugMessage]>`; в http.ts — расширенный тип `ServerOptions.testMode` (допускает промис) и асинхронная ветка обработчика `/v1/ws`. Использует задача 8.

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

Добавить в `packages/server/tests/test-mode.test.ts` (импорты: `AtlasStore, OfficeRuntime, collectFrames` — в импорт из `'../src/index.ts'` (там уже есть `renderScenario`, `ManualClock` — нет: добавить); `mkdtempSync` из `node:fs`, `tmpdir` из `node:os`, `join` из `node:path`; `miniAssets` из `'./helpers.ts'`):

```ts
  it('атлас: renderScenario ждёт готовности — hello со ссылкой /atlas/ (спека атласа 2.4.2)', async () => {
    const plain = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
    const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const atlas = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-tm-')), assetsDir: assets, catalog: office.bundle.catalog, sheets });
    const h = await renderScenarioHello(office, { scenario: 'morning', t: '0', seed: '1' }, { atlas });
    expect(h.map.floor[0]!.frame.sheet).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
  });
```

- [ ] **Step 2: Запустить тест — убедиться, что падает**

Run: `pnpm vitest run --project server packages/server/tests/test-mode.test.ts`
Expected: FAIL — новый тест «атлас: renderScenario ждёт готовности»: `opts.atlas` ещё не принимается renderScenario, hello несёт `/sprites/…`. Остальные тесты файла проходят.

- [ ] **Step 3: Перевести renderScenario на async**

`packages/server/src/test-mode.ts` целиком (изменения: импорт типа `AtlasStore`, opts.atlas, async/await):

```ts
import type { AtlasStore } from './atlas.ts';
import type { DebugMessage, HelloMessage } from '@pixeloffice/protocol';
import { resolveScenarioSource, scenarios } from '@pixeloffice/replay';
import { ManualClock } from './clock.ts';
import { frameForViewer } from './frames.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).
// Вслед за hello — debug на тот же момент: дельт нет, а отладочному слою (клавиша D) нужны пути и брони.
// opts.ui — листы интерфейса есть (спека интерфейса §3.4): hello тестового режима несёт шкуру, как обычный.
// opts.portraits — файлы портретов есть: avatarKit несёт portraits, как обычный hello (спека диалоговых окон 2.4).
// opts.atlas — мини-атлас (спека атласа 2.4.2): ждём готовности перед hello; кеш пишется и в тестовом режиме —
// единственная запись тестового сервера в dataDir.
export async function renderScenario(
  office: LoadedOffice,
  q: Record<string, string | undefined>,
  opts: { ui?: boolean; portraits?: boolean; atlas?: AtlasStore | null } = {},
): Promise<[HelloMessage, DebugMessage]> {
  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, ui: opts.ui, portraits: opts.portraits, atlas: opts.atlas });
  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);
  }
  await rt.ready(); // атласный hello сразу (спека атласа 2.4.2); сбой — исходные листы, ошибки не будет
  // me (спека адресных сообщений 2.5.1): hello как кадр личного токена этого человека. Без me — без фильтрации
  // (видно всё — существующие скриншоты и сценарии не ломаются); адресаты срезаются и там, и там.
  const me = q.me === undefined || q.me === '' ? undefined : q.me;
  return [frameForViewer(rt.hello(true), me), rt.debug()];
}
```

- [ ] **Step 4: Поправить существующие вызовы renderScenario (async)**

1. `packages/server/tests/test-mode.test.ts` — хелпер (строка 6) и все вызовы:

```ts
const renderScenarioHello = async (...a: Parameters<typeof renderScenario>) => (await renderScenario(...a))[0];
```

В каждом `it` этого файла: декларацию `() => {` заменить на `async () => {`, а вызовы `renderScenarioHello(` и `renderScenario(` предварить `await` (пример: `const h = await renderScenarioHello(office, { scenario: 'morning', t: '60000', seed: '1' });`). Синхронные проверки без renderScenario не трогать.

Исключение — тест «неизвестный сценарий и t вне диапазона — ошибка» (~строки 101–104): вызов сидит внутри синхронной стрелки `expect(() => …)`, `await` туда не вставить, а после async-перехода исключение уходит в rejection и `toThrow` его не поймает — перевести на `rejects`:

```ts
  it('неизвестный сценарий и t вне диапазона — ошибка', async () => {
    await expect(renderScenarioHello(office, { scenario: 'nope', t: '0' })).rejects.toThrow();
    await expect(renderScenarioHello(office, { scenario: 'sit4', t: '-5' })).rejects.toThrow();
  });
```

2. `packages/server/tests/ui.test.ts` — тест «тестовый режим: флаг передаётся в renderScenario»:

```ts
  it('тестовый режим: флаг передаётся в renderScenario', async () => {
    const q = { scenario: 'morning', t: '0', seed: '1' };
    expect((await renderScenario(office, q, { ui: true }))[0].ui?.default).toBe('cold');
    expect((await renderScenario(office, q))[0].ui).toBeUndefined();
  });
```

3. `packages/server/tests/portraits.test.ts` — тест «тестовый режим: флаг передаётся в renderScenario» — аналогично: `it(..., async () => { ... })`, оба вызова с `await`:

```ts
    expect((await renderScenario(office, q, { portraits: true }))[0].avatarKit.portraits?.skins).toContain('PG_Skin_{body:0}');
    expect((await renderScenario(office, q))[0].avatarKit.portraits).toBeUndefined();
```

4. `packages/server/tests/avatars-http.test.ts` — строка ~179: `const [hello] = renderScenario(s.office, { scenario: 'morning', t: '0', seed: '1' });` → `const [hello] = await renderScenario(s.office, { scenario: 'morning', t: '0', seed: '1' });` (объявление `it` — `async`, если ещё не).

Колбэки `testMode: (q) => renderScenario(office, q)` в `messages.test.ts` и `avatars-http.test.ts` не менять: колбэк, возвращающий промис, допустим — тип `testMode` расширен и ветка переведена на async шагом 5 этой задачи.

- [ ] **Step 5: Асинхронная ветка `testMode` в http.ts**

`renderScenario` теперь возвращает промис, а обработчик `/v1/ws` синхронный: `JSON.stringify(промиса)` даёт `"{}"` вместо hello — упадут WS-тесты тестового режима из Step 6. Правка идёт в этой же задаче, до прогона тестов (не в задаче 8): каждая задача оставляет ветку зелёной.

1) `ServerOptions` — расширенный тип `testMode` (поле `atlas` добавит задача 8):

```ts
  testMode?: ((q: Record<string, string | undefined>) => ServerMessage | ServerMessage[] | Promise<ServerMessage | ServerMessage[]>) | null;
```

2) testMode-ветка обработчика `/v1/ws` — заменить на асинхронную (остальное без изменений):

```ts
    if (o.testMode && q.scenario) {
      // Тестовый режим: hello на момент t (и, если дали, debug), без дельт (спека 4.6). Колбэк асинхронный —
      // атлас ждётся внутри renderScenario (спека атласа 2.4.2).
      void (async () => {
        try {
          const out = await o.testMode(q);
          for (const m of Array.isArray(out) ? out : [out]) socket.send(JSON.stringify(m));
        } catch (e) {
          socket.close(1011, (e as Error).message.slice(0, 120));
        }
      })();
      return;
    }
```

- [ ] **Step 6: Запустить тесты — убедиться, что проходят**

Run: `pnpm vitest run --project server packages/server/tests/test-mode.test.ts packages/server/tests/ui.test.ts packages/server/tests/portraits.test.ts packages/server/tests/avatars-http.test.ts packages/server/tests/messages.test.ts`
Expected: PASS. Затем все серверные — затронут http.ts:
Run: `pnpm vitest run --project server`
Expected: PASS.

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

```bash
git add packages/server/src/test-mode.ts packages/server/src/http.ts packages/server/tests/test-mode.test.ts packages/server/tests/ui.test.ts packages/server/tests/portraits.test.ts packages/server/tests/avatars-http.test.ts
git commit -m "feat(server): тестовый режим ждёт атлас — renderScenario и testMode асинхронные"
```

---

### Task 8: Маршрут `/atlas/:hash.png` и старт с атласом (http.ts, main.ts)

**Files:**
- Modify: `packages/server/src/http.ts`
- Modify: `packages/server/src/main.ts`
- Test: `packages/server/tests/atlas-http.test.ts`

**Interfaces:**
- Consumes: `AtlasStore.read(hash)` (задача 4), асинхронный `renderScenario` и асинхронная ветка `testMode` (задача 7), `OfficeHost`/`OfficeRuntime` с атласом (задачи 5–6), `miniAssets` (задача 4).
- Produces: `ServerOptions.atlas?: AtlasStore | null`; маршрут `GET /atlas/:hash.png` (`private, max-age=31536000, immutable`); `main.ts` создаёт `SheetCache`/`AtlasStore` при наличии `assetsDir` и ждёт `ready()` до `listen`.

- [ ] **Step 1: Написать падающий интеграционный тест**

`packages/server/tests/atlas-http.test.ts`:

```ts
import { mkdtempSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PNG } from 'pngjs';
import { afterEach, describe, expect, it } from 'vitest';
import type { HelloMessage, ServerMessage } from '@pixeloffice/protocol';
import { AtlasStore, ManualClock, OfficeRuntime, buildServer, collectFrames, renderScenario } from '../src/index.ts';
import { demoOffice, miniAssets } from './helpers.ts';

const TOKEN = 'demo-viewer-token';
const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

const office = demoOffice();
const plain = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);

async function start() {
  const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
  const atlas = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-http-')), assetsDir: assets, catalog: office.bundle.catalog, sheets });
  const rt = new OfficeRuntime({ office, clock: new ManualClock(), atlas });
  await rt.ready();
  const srv = await buildServer({ runtime: rt, viewerTokens: [TOKEN], assetsDir: assets, viewerDist: null, atlas, testMode: (q) => renderScenario(office, q, { atlas }) });
  await srv.app.listen({ port: 0, host: '127.0.0.1' });
  closers.push(() => srv.app.close());
  return { rt, srv, base: `http://127.0.0.1:${(srv.app.server.address() as AddressInfo).port}` };
}

describe('мини-атлас: hello и отдача (спека атласа 2.2.3, 2.3)', () => {
  it('hello демо ссылается на /atlas/<hash>.png; маршрут отдаёт PNG с private immutable', async () => {
    const s = await start();
    const url = s.rt.hello().map.floor[0]!.frame.sheet;
    expect(url).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
    const res = await s.srv.app.inject({ method: 'GET', url: `${url}?token=${TOKEN}` });
    expect(res.statusCode).toBe(200);
    expect(res.headers['content-type']).toBe('image/png');
    expect(res.headers['cache-control']).toBe('private, max-age=31536000, immutable');
    expect(PNG.sync.read(res.rawPayload).width).toBeGreaterThan(0);
  });

  it('без токена — 401; чужой hash — 404', async () => {
    const s = await start();
    const url = s.rt.hello().map.floor[0]!.frame.sheet;
    expect((await s.srv.app.inject({ method: 'GET', url })).statusCode).toBe(401);
    expect((await s.srv.app.inject({ method: 'GET', url: `/atlas/${'0'.repeat(64)}.png?token=${TOKEN}` })).statusCode).toBe(404);
  });

  it('тестовый режим: hello сценария — атласный (testMode асинхронный, ждёт готовности)', async () => {
    const s = await start();
    const got: ServerMessage[] = [];
    const ws = new WebSocket(`${s.base.replace('http', 'ws')}/v1/ws?token=${TOKEN}&scenario=morning&t=0&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));
    const hello = got.find((m) => m.type === 'hello') as HelloMessage | undefined;
    expect(hello?.map.floor[0]!.frame.sheet).toMatch(/^\/atlas\//);
  });

  it('без assetsDir (CI) — hello на исходных листах, маршрута /atlas нет', async () => {
    const rt = new OfficeRuntime({ office, clock: new ManualClock() });
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    const srv = await buildServer({ runtime: rt, viewerTokens: [TOKEN], assetsDir: null, viewerDist: null, testMode: null });
    closers.push(() => srv.app.close());
    expect((await srv.app.inject({ method: 'GET', url: `/atlas/${'0'.repeat(64)}.png?token=${TOKEN}` })).statusCode).toBe(404);
  });
});
```

- [ ] **Step 2: Запустить тест — убедиться, что падает**

Run: `pnpm vitest run --project server packages/server/tests/atlas-http.test.ts`
Expected: FAIL — по ассертам: маршрут `/atlas/…` ещё не зарегистрирован — 404 на GET (hello при этом атласный: runtime собран с атласом напрямую). Vitest типы не проверяет (esbuild без тайпчека) — ошибку «`atlas` нет в `ServerOptions`» покажет только `tsc` в `pnpm gate` (задача 9).

- [ ] **Step 3: Реализовать маршрут в http.ts**

1) Импорт (рядом с `import type { OfficeRuntime } from './runtime.ts';`):

```ts
import type { AtlasStore } from './atlas.ts';
```

2) `ServerOptions` — поле `atlas` (тип `testMode` расширен в задаче 7):

```ts
  atlas?: AtlasStore | null; // мини-атлас: отдача /atlas/:hash.png (спека атласа 2.2.3); нет — маршрута нет
```

3) Маршрут — после `app.get('/v1/session', ...)` (до регистрации fastifyStatic; доступ закрывает общий крюк `onRequest` — `/atlas/...` не в `PUBLIC`):

```ts
  // Мини-атлас (спека атласа 2.2.3): один PNG на все использованные кадры офиса. Доступ закрывает общий крюк
  // токена зрителя выше — тот же лицензированный арт LimeZu, что у /sprites/. Имя файла — sha256 набора,
  // поэтому private + immutable на год без ETag: URL меняется вместе с содержимым, ревалидация бессмысленна.
  // Белый список assetsAllowed не нужен: hash валидируется, отдаём только существующие файлы хранилища.
  if (o.atlas) {
    const store = o.atlas;
    app.get('/atlas/:hash.png', async (req, reply) => {
      const { hash } = req.params as { hash: string };
      const png = await store.read(hash);
      if (!png) return reply.code(404).type('text/plain; charset=utf-8').send('нет такого атласа');
      return reply.type('image/png').header('cache-control', 'private, max-age=31536000, immutable').send(png);
    });
  }
```

- [ ] **Step 4: Провести опции в main.ts**

1) Импорт: `import { AtlasStore } from './atlas.ts';`

2) В ветке `serve`, после `const { config, catalog } = office.bundle;` (до создания `persistence`):

```ts
  // Листы и мини-атлас (спека атласа 2.5.2): SheetCache поднимается при наличии assetsDir — с атласом
  // декодированные листы резидентны в процессе (демо: ~64 МиБ RGBA, без выселения — цена одной паковки), их
  // читают паковка атласа и предпросмотр админки.
  const sheets = existsSync(office.assetsDir) ? new SheetCache(office.assetsDir, catalog) : null;
  const atlas = sheets ? new AtlasStore({ dataDir: office.dataDir, assetsDir: office.assetsDir, catalog, sheets, log: consoleLogger }) : null;
```

3) В создании `OfficeHost` добавить `atlas`:

```ts
    host = new OfficeHost({ office, clock: systemClock, log: consoleLogger, persistence, relay, ui, portraits, test: flags.test, versions, tokens, atlas });
```

4) Ожидание готовности до listen (спека атласа 2.5.3) — сразу после блока `try { host = ... } catch ...` (до `const guides = ...`; `onReset`/`onViewerRevoked` присваиваются позже, после `buildServer` — они про закрытие уже подключённых зрителей, к атласу отношения не имеют):

```ts
  // Атлас первого runtime готов до listen (спека атласа 2.5.3): первый зритель получает атласный hello сразу.
  await host.runtime.ready();
```

5) В объекте `admin` заменить строку `sheets: existsSync(office.assetsDir) ? new SheetCache(office.assetsDir, catalog) : null,` на общий кеш:

```ts
          sheets,
```

6) `testMode` — передать атлас:

```ts
    testMode: flags.test ? (q) => renderScenario(office, q, { ui, portraits, atlas }) : null,
```

- [ ] **Step 5: Запустить тесты — убедиться, что проходят**

Run: `pnpm vitest run --project server packages/server/tests/atlas-http.test.ts`
Expected: PASS (4 теста). Затем все серверные:
Run: `pnpm vitest run --project server`
Expected: PASS.

- [ ] **Step 6: Ручная проверка на машине с ассетами (если есть assets/)**

```bash
node packages/server/src/main.ts serve offices/demo --port 4899
# во втором терминале: заголовки атласа (hash взять из URL страницы в DevTools → Network)
curl -sI "http://127.0.0.1:4899/atlas/<hash>.png?token=demo-viewer-token" | grep -i 'cache-control\|content-type'
```

Открыть `http://127.0.0.1:4899/?token=demo-viewer-token`: в DevTools (Network) — один запрос `/atlas/<hash>.png` (~0,2 МБ; при повторном визите — из кеша, без ревалидации), запросов к `/sprites/...` нет; офис выглядит как раньше, сценарий `morning` — тоже. Перезапуск сервера — атлас берётся готовым из `offices/demo/.data/atlas/` (мгновенный старт). Остановить сервер.

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

```bash
git add packages/server/src/http.ts packages/server/src/main.ts packages/server/tests/atlas-http.test.ts
git commit -m "feat(server): маршрут /atlas/:hash.png и старт с атласом"
```

---

### Task 9: CLAUDE.md и полный gate

**Files:**
- Modify: `CLAUDE.md` (раздел «Архитектура», после буллета «**Сервер — источник правды и для вида**»)

- [ ] **Step 1: Абзац об атласе**

Вставить новый буллет:

```md
- **Мини-атлас** (спека атласа): `AtlasStore` (`packages/server/src/atlas.ts`) пакует все использованные кадры hello (карта с крышами и участком, транспорт, облачка разговора) в один PNG — дедуп по `(sheet, x, y, w, h)`, shelf-упаковка 1024 px с 1 px зазором между кадрами. `OfficeRuntime` запускает паковку при создании (конструктор синхронный), `hello()` отдаёт атласные копии `map`/`vehicleKit`/`characterLayout` с `/atlas/<sha256>.png`; пока паковка идёт или не удалась — исходные `/sprites/…` и предупреждение в журнал. Hash — sha256 по набору кадров плюс байтовый размер и mtime листов (правка арта меняет URL), кеш — промис в памяти и `<dataDir>/atlas/<hash>.png` (файл есть — не перепаковываем, запись атомарна, старые не чистятся). Отдача — маршрут `/atlas/:hash.png` с `private, max-age=31536000, immutable` за тем же токеном зрителя, что `/sprites/`. Старт ждёт готовности до `listen`, `apply`/`rollback` — до отключения зрителей, тестовый режим — перед hello (`OfficeRuntime.ready()`); без `assetsDir` атласа нет — hello на исходных листах. Вьюер и протокол не меняются.
```

- [ ] **Step 2: Полный gate**

Run: `pnpm gate`
Expected: все тесты, тайпчек всех пакетов и `validate:maps` — зелёные. Без паков ассетов скриншот-тесты и cli-тест скипаются по маркеру каталога — это норма.

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

```bash
git add CLAUDE.md
git commit -m "docs: мини-атлас в CLAUDE.md"
```

---

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

1. **Память `SheetCache`**: с атласом кеш листов резидентен в каждом процессе с ассетами (демо ≈ 64 МиБ RGBA, без выселения) — осознанная цена спеки 2.5.2. Альтернатива «выселять после паковки» ломает мгновенный `apply` с новым hash — отвергнута.
2. **Грубость mtime**: правка пикселей с тем же байтовым размером и в ту же миллисекунду mtime не меняет hash — практически недостижимо; hash страхуют сразу два сигнала (размер файла и mtime).
3. **`PNG.sync.read` pngjs 7 падает на больших листах** — чтение исходников только потоком через `SheetCache` (как в предпросмотре); `PNG.sync.write` для атласа (сотни КБ) безопасен. `renderAtlasPng` пропускает пиксели за краем листа — в реальных каталогах кадры в пределах (проверяет `checkAtlas`), ветка защитная.
4. **Кеш null при неудачной паковке живёт до конца процесса**: набор и метаданные листов не изменились бы — повтор дал бы то же; правка листа меняет hash и попадает новым ключом. Старт никогда не валится (спека 2.4.1).
5. **Визуальные тесты Playwright**: сервер `--test` ждёт атлас при первом сценарии (паковка ~десятки мс, дальше файл в `dataDir`), эталоны не меняются — пиксели те же, эталоны и так не в git.
6. **cli-тест занятого порта** (`serve --test` с реальными ассетами): старт ждёт `ready()` до `listen` — паковка доли секунды, таймауты теста не задеты.
7. **Отвергнутые альтернативы** (раздел 3 спеки): прогрев листов в вьюере (трафик 4,8 МБ остаётся), атлас на клиенте (дублирование знаний о составе и весь трафик старых листов), паковка без диска (нет мгновенного рестарта), `no-cache` + ETag (ревалидация на каждый визит).

Открытых вопросов нет — все решения зафиксированы спекой.

## Запуск плана

1. Subagent-Driven (рекомендуется): скилл `superpowers:subagent-driven-development` — свежий субагент на задачу, ревью между задачами.
2. Inline: скилл `superpowers:executing-plans` — исполнение в одной сессии с контрольными точками.


