import { describe, expect, it } from 'vitest';
import { agentAvatar, agentPropKey, avatarLayerPaths, avatarPropPaths, defaultAssetUrl, defaultProjectAvatar } from '@pixeloffice/core';
import type { FrameCharacter } from '@pixeloffice/core';
import { MAX_LABEL, ManualClock, OfficeRuntime, buildServer, fitLabel, silentLogger, type LogEntry } from '../src/index.ts';
import { advance, demoOffice, iso, makeRuntime } from './helpers.ts';

const MANUAL = 'Bearer demo-manual-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('без токена — 401 до разбора тела; схема Bearer без учёта регистра', async () => {
    const { rt, clock } = makeRuntime();
    const { app } = await buildServer({ runtime: rt });
    const broken = await app.inject({ method: 'POST', url: '/v1/events', payload: '{нет', headers: { 'content-type': 'application/json' } });
    expect(broken.statusCode).toBe(401);
    const body = { events: [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }] };
    const lower = await app.inject({ method: 'POST', url: '/v1/events', payload: body, headers: { authorization: 'bearer demo-manual-token' } });
    expect(lower.statusCode).toBe(200);
  });

  it('битый JSON — 400, нет Content-Type — 415: ответ API по-русски, а не тело Fastify', async () => {
    const { rt } = makeRuntime();
    const { app } = await buildServer({ runtime: rt });
    const auth = 'Bearer demo-manual-token';
    const broken = await app.inject({ method: 'POST', url: '/v1/events', payload: '{нет', headers: { authorization: auth, 'content-type': 'application/json' } });
    expect([broken.statusCode, broken.json()]).toEqual([400, { error: 'invalid', message: 'тело запроса — не JSON' }]);
    const bare = await app.inject({ method: 'POST', url: '/v1/events', body: '{"events":[]}', headers: { authorization: auth, 'content-type': '' } });
    expect([bare.statusCode, bare.json()]).toEqual([415, { error: 'unsupported_media_type', message: 'нужен заголовок Content-Type: application/json' }]);
  });

  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('manual')!;
    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('manual')!, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }]);
    const other = { source: 'calendar', token: 'calendar-token', humans: false };
    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: MANUAL },
      // p6 — на метро: человек на машине появляется только после парковки (спека транспорта 4.5.1).
      payload: { events: [{ type: 'status', entityId: 'p6', 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(['p6']);
  });

  it('подпись агента с длинным проектом укорачивается, полное имя остаётся в name', () => {
    const { rt, clock } = makeRuntime();
    const long = 'p'.repeat(150);
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: { ...agentRef, project: long }, status: 'working', at: iso(clock) }]);
    const view = rt.drain().find((m) => m.type === 'entity');
    expect(view && view.type === 'entity' && view.entity.name).toBe(`Стас · ${long}`);
    expect(view && view.type === 'entity' && view.entity.label.length).toBeLessThanOrEqual(40);
    expect(view && view.type === 'entity' && view.entity.label.endsWith('…')).toBe(true);
  });

  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('manual')!;
    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('manual')!, [{ 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('manual')!;
    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('manual')!, [{ 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('idle и needs_input от человека — принимаются (спека 17.11.2026)', () => {
    const { rt, clock } = makeRuntime();
    const src = rt.sourceByName('manual')!;
    expect(rt.ingestFromSource(src, [{ type: 'status', entityId: 'p1', status: 'idle', at: iso(clock) }]).body).toEqual({ accepted: 1, ignored: 0 });
    expect(rt.ingestFromSource(src, [{ type: 'status', entityId: 'p1', status: 'needs_input', at: iso(clock) }]).body).toEqual({ accepted: 1, ignored: 0 });
    expect(rt.store.get('p1')?.status).toBe('needs_input');
    const snap = rt.ingestFromSource(src, [{ type: 'snapshot', at: iso(clock), entities: [{ entityId: 'p1', status: 'idle' }] }]);
    expect(snap.body).toEqual({ accepted: 1, ignored: 0 }); // снимок с новыми статусами тоже принимается
    expect(rt.store.get('p1')?.status).toBe('idle');
  });

  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('manual')!, [
      { 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' });
  });

  it('повторный снимок (heartbeat) без смены статуса не порождает дельт', () => {
    const { rt, clock } = makeRuntime();
    const nc = rt.sourceByName('manual')!;
    const snap = (d: number) => ({ type: 'snapshot' as const, at: iso(clock, d), entities: [{ entityId: 'p1', status: 'online' as const }] });
    rt.ingestFromSource(nc, [snap(0)]);
    advance(rt, clock, 60_000); // дошёл до места и успокоился
    rt.drain();
    rt.ingestFromSource(nc, [snap(1)]);
    advance(rt, clock, 5000);
    expect(rt.drain()).toEqual([]);
  });

  it('пакет проходит авторизацию целиком: валидное событие перед запрещённым не применяется (решение 20)', () => {
    const logged: unknown[] = [];
    const offered: unknown[] = [];
    const clock = new ManualClock();
    const rt = new OfficeRuntime({
      office: demoOffice(),
      clock,
      log: silentLogger,
      eventLog: { append: (e) => logged.push(e) },
      relay: { offer: (e) => offered.push(e) },
    });
    const res = rt.ingestFromSource(rt.sourceByName('manual')!, [
      { type: 'status', entityId: 'p1', status: 'online', at: iso(clock) },
      { type: 'status', agent: agentRef, status: 'working', at: iso(clock) },
    ]);
    expect(res).toMatchObject({ status: 403, body: { error: 'agent_event_requires_owner_token' } });
    expect(res.status === 403 && res.body.issues?.[0]?.path).toBe('events.1');
    expect(rt.store.get('p1')).toBeUndefined();
    expect(rt.store.ownerSource('p1')).toBeUndefined();
    advance(rt, clock, 2100);
    expect(rt.drain()).toEqual([]);
    expect(logged).toEqual([]);
    expect(offered).toEqual([]);
  });

  it('403 foreign_source для агента: сущность закреплена за другим источником того же хозяина', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: agentRef, status: 'working', at: iso(clock) }]);
    const otherHook = { source: 'hook-b', token: 'hook-b-token', owner: 'p1', humans: false };
    expect(rt.ingestFromSource(otherHook, [{ type: 'status', agent: agentRef, status: 'idle', at: iso(clock, 1000) }])).toMatchObject({
      status: 403,
      body: { error: 'foreign_source' },
    });
  });

  it('403 foreign_source для снимка с чужой сущностью; снимок целиком не применяется', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(rt.sourceByName('manual')!, [{ type: 'status', entityId: 'p1', status: 'online', at: iso(clock) }]);
    const other = { source: 'calendar', token: 'calendar-token', humans: false };
    const res = rt.ingestFromSource(other, [
      { type: 'snapshot', at: iso(clock, 1000), entities: [{ entityId: 'p2', status: 'online' }, { entityId: 'p1', status: 'offline' }] },
    ]);
    expect(res).toMatchObject({ status: 403, body: { error: 'foreign_source' } });
    expect(rt.store.get('p1')?.status).toBe('online');
    expect(rt.store.get('p2')).toBeUndefined();
  });
});

describe('номер одновременных агентов проекта (спека агентов §3.3)', () => {
  const hook = (rt: OfficeRuntime) => rt.sourceByName('claude-hook')!;
  const st = (slot: string, status: 'working' | 'idle' | 'offline', at: string, project = 'pixeloffice') => ({ type: 'status' as const, agent: { project, slot }, status, at });
  const entities = (rt: OfficeRuntime) => rt.drain().flatMap((m) => (m.type === 'entity' ? [m.entity] : []));

  it('два агента в разных слотах — 1 и 2: подписи, сдвиг цвета у второго, project и облик проекта в EntityView', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock)), st('%2', 'working', iso(clock))]);
    const [a, b] = entities(rt);
    expect([a!.label, b!.label]).toEqual(['Стас · pixeloffice', 'Стас · pixeloffice 2']);
    const chars = rt.office.bundle.catalog.characters;
    const project = defaultProjectAvatar('p1', 'pixeloffice', chars.pool);
    expect([a!.project, a!.avatar, b!.project, b!.avatar]).toEqual(['pixeloffice', project, 'pixeloffice', project]);
    expect(b!.layers).toEqual(avatarLayerPaths(chars, agentAvatar(project, 2, chars.pool)).map(defaultAssetUrl));
  });

  it('первый ушёл в offline — третий получает 1; первый вернулся — наименьший свободный и entity; активный → активный — без entity', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock)), st('%2', 'working', iso(clock))]);
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%1', 'offline', iso(clock))]);
    rt.drain();
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%3', 'working', iso(clock))]);
    expect(entities(rt).map((e) => [e.id, e.label])).toEqual([['agent:p1:pixeloffice:%3', 'Стас · pixeloffice']]);
    expect(rt.registry.agent('agent:p1:pixeloffice:%1')!.name).toBe('Стас · pixeloffice'); // идущий к выходу не переодевается
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%1', 'idle', iso(clock))]);
    expect(entities(rt).map((e) => [e.id, e.label])).toEqual([['agent:p1:pixeloffice:%1', 'Стас · pixeloffice 3']]);
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock))]);
    expect(entities(rt)).toEqual([]);
  });

  it('длинная подпись второго агента: « 2» остаётся на конце, длина — MAX_LABEL; полное имя — в name', () => {
    const { rt, clock } = makeRuntime();
    const long = 'очень-длинный-проект-'.repeat(5);
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), long), st('%2', 'working', iso(clock), long)]);
    const [, b] = entities(rt);
    expect(b!.label.endsWith('… 2')).toBe(true);
    expect(b!.label).toHaveLength(MAX_LABEL);
    expect(b!.name).toBe(`Стас · ${long} 2`);
  });

  it('усечение подписи с меткой: первой обрезается метка, номер сохраняется (спека метки §4.2.4)', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock)), st('%2', 'working', iso(clock))]);
    const [a, b] = rt.registry.agentList();
    const long = { text: 'Оценка объёма и сроков переезда офиса', private: true };
    rt.registry.setLabel(a!.id, long);
    rt.registry.relabel('p1', 'pixeloffice', (id) => rt.store.get(id)?.status !== 'offline');
    expect(rt.entityView(a!).label).toBe('Стас · pixeloffice · Оценка объёма и ср…');
    expect(rt.entityView(a!).name).toBe('Стас · pixeloffice · Оценка объёма и сроков переезда офиса');
    rt.registry.setLabel(b!.id, long);
    rt.registry.relabel('p1', 'pixeloffice', (id) => rt.store.get(id)?.status !== 'offline');
    // Граница — после пробела «и »: пробел перед «…» срезается, подпись на единицу короче предела.
    expect(rt.entityView(b!).label).toBe('Стас · pixeloffice · Оценка объёма и… 2');
  });

  it('fitLabel: короткая — как есть; номер 1 — хвост «…»; номер n — основа, «…», « n»', () => {
    expect(fitLabel('Стас · demo', 2)).toBe('Стас · demo 2');
    expect(fitLabel('x'.repeat(50))).toBe('x'.repeat(39) + '…');
    expect(fitLabel('x'.repeat(50), 12)).toBe('x'.repeat(36) + '… 12');
    expect(fitLabel('x'.repeat(38), 2)).toBe('x'.repeat(38) + ' 2');
  });

  it('fitLabel: пробелы и висящий « ·» перед «…» срезаются', () => {
    expect(fitLabel('Стас · pixeloffice · ab cd ef gh ij kl mn op')).toBe('Стас · pixeloffice · ab cd ef gh ij kl…');
    expect(fitLabel('Стас · ' + 'p'.repeat(30) + ' · метка')).toBe('Стас · ' + 'p'.repeat(30) + '…');
    expect(fitLabel('Стас · ' + 'p'.repeat(29) + ' · метка')).toBe('Стас · ' + 'p'.repeat(29) + '…');
  });

  it('fitLabel: граница усечения посреди эмодзи — суррогатная пара не разрезается', () => {
    const base = 'Стас · ' + 'x'.repeat(29) + '😀'.repeat(5);
    expect(fitLabel(base, 2)).toBe('Стас · ' + 'x'.repeat(29) + '… 2');
    expect(fitLabel(base)).toBe('Стас · ' + 'x'.repeat(29) + '😀…');
  });

  it('предметы в руках агента — по хозяину, проекту и номеру, не по слоту', () => {
    const a = makeRuntime();
    a.rt.ingestFromSource(hook(a.rt), [st('%1', 'working', iso(a.clock))]);
    const b = makeRuntime();
    b.rt.ingestFromSource(hook(b.rt), [st('%42', 'working', iso(b.clock))]);
    const [pa] = entities(a.rt);
    const [pb] = entities(b.rt);
    expect(pa!.props).toEqual(pb!.props);
    const chars = a.rt.office.bundle.catalog.characters;
    const expected = Object.fromEntries(Object.entries(avatarPropPaths(chars, agentPropKey('p1', 'pixeloffice', 1))).map(([k, v]) => [k, defaultAssetUrl(v)]));
    expect(pa!.props).toEqual(expected);
  });
});

describe('проект «.» и «..» (спека агентов §3.4)', () => {
  it('событие агента с проектом «..» — 400 на всю пачку, агент не появляется', () => {
    const { rt, clock } = makeRuntime();
    const r = rt.ingestHttp(HOOK, { events: [{ type: 'status', agent: { project: '..', slot: '%1' }, status: 'working', at: iso(clock) }] });
    expect(r.status).toBe(400);
    expect(rt.registry.agentList()).toEqual([]);
  });
});

describe('метка агента (спека метки §4.1–4.3)', () => {
  type Lbl = { text: string; private: boolean } | null;
  const hook = (rt: OfficeRuntime) => rt.sourceByName('claude-hook')!;
  const st = (slot: string, status: 'working' | 'idle' | 'offline', at: string, label?: Lbl, ttlSec?: number) => ({
    type: 'status' as const,
    agent: { project: 'pixeloffice', slot },
    status,
    at,
    ...(label !== undefined ? { label } : {}),
    ...(ttlSec !== undefined ? { ttlSec } : {}),
  });
  const L = (text: string, priv = false) => ({ text, private: priv });
  const sent = (rt: OfficeRuntime) => rt.drain().flatMap((m) => (m.type === 'entity' ? [[m.entity.id, m.entity.label]] : []));
  const A1 = 'agent:p1:pixeloffice:%1';
  const A2 = 'agent:p1:pixeloffice:%2';

  it('метка в подписи, номер не пишется; та же метка снова — без entity; одно entity на агента', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), null), st('%2', 'working', iso(clock), L('tmux names', true))]);
    expect(sent(rt)).toEqual([
      [A1, 'Стас · pixeloffice'],
      [A2, 'Стас · pixeloffice · tmux names'],
    ]);
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%2', 'working', iso(clock), L('tmux names', true))]);
    expect(sent(rt)).toEqual([]);
  });

  it('совпадение меток — у второго номер; второй переименовал вкладку — entity только ему', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), L('street')), st('%2', 'working', iso(clock), L('street'))]);
    expect(sent(rt)).toEqual([
      [A1, 'Стас · pixeloffice · street'],
      [A2, 'Стас · pixeloffice · street 2'],
    ]);
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%2', 'working', iso(clock), L('door'))]);
    expect(sent(rt)).toEqual([[A2, 'Стас · pixeloffice · door']]);
  });

  it('первый ушёл в offline — у второго пропадает номер, подпись первого не меняется', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), L('street')), st('%2', 'working', iso(clock), L('street'))]);
    rt.drain();
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%1', 'offline', iso(clock))]);
    expect(sent(rt)).toEqual([[A2, 'Стас · pixeloffice · street']]);
    expect(rt.registry.agent(A1)!.name).toBe('Стас · pixeloffice · street');
  });

  it('label: null сбрасывает метку, отсутствие поля — нет', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), L('street'))]);
    rt.drain();
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%1', 'idle', iso(clock))]);
    expect(sent(rt)).toEqual([]);
    expect(rt.registry.agent(A1)!.label).toEqual(L('street'));
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), null)]);
    expect(sent(rt)).toEqual([[A1, 'Стас · pixeloffice']]);
    expect('label' in rt.registry.agent(A1)!).toBe(false);
  });

  it('устаревшее событие с другой меткой метку не меняет', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), L('street'))]);
    rt.drain();
    const r = rt.ingestFromSource(hook(rt), [st('%1', 'idle', iso(clock, -1000), L('door'))]);
    expect(r.body).toEqual({ accepted: 0, ignored: 1 });
    expect(sent(rt)).toEqual([]);
    expect(rt.registry.agent(A1)!.label).toEqual(L('street'));
  });

  it('метка из события offline не применяется; подпись агента в offline не пересчитывается', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), L('street')), st('%2', 'working', iso(clock), L('street'))]);
    rt.drain();
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%2', 'offline', iso(clock), L('door'))]);
    expect(sent(rt)).toEqual([]); // у первого номер 1 и так не писался
    expect([rt.registry.agent(A2)!.label, rt.registry.agent(A2)!.name]).toEqual([L('street'), 'Стас · pixeloffice · street 2']);
    clock.advance(1000);
    rt.ingestFromSource(hook(rt), [st('%2', 'working', iso(clock))]); // вернулся с тем же номером и меткой
    expect(sent(rt)).toEqual([]);
  });

  it('совпадение пропало по TTL (step) — entity второму', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(hook(rt), [st('%1', 'working', iso(clock), L('street'), 60), st('%2', 'working', iso(clock), L('street'))]);
    rt.drain();
    clock.advance(61_000);
    rt.step(50);
    expect(sent(rt)).toEqual([[A2, 'Стас · pixeloffice · street']]);
  });
});

describe('источник с owner и humans: true (спека хостинга 10)', () => {
  // demo: claude-hook — источник с owner p1; включаем ему события людей.
  function humansRuntime() {
    const demo = demoOffice();
    const sources = demo.bundle.config.sources.map((s) => (s.source === 'claude-hook' ? { ...s, humans: true } : s));
    const office = { ...demo, bundle: { ...demo.bundle, config: { ...demo.bundle.config, sources } } };
    const clock = new ManualClock();
    return { rt: new OfficeRuntime({ office, clock, log: silentLogger }), clock };
  }

  // Регрессионный: проходит и до правки authorize — шаг 6 не должен ослабить запрет для источника без humans.
  it('без humans событие человека от источника с owner — 403, как раньше', () => {
    const { rt, clock } = makeRuntime();
    const r = rt.ingestHttp(HOOK, { events: [{ type: 'status', entityId: 'p2', status: 'online', at: iso(clock) }] });
    expect(r).toMatchObject({ status: 403, body: { error: 'agent_source_cannot_address_humans' } });
  });

  it('status, snapshot и bubble человека принимаются, агент того же источника садится к хозяину', () => {
    const { rt, clock } = humansRuntime();
    const r = rt.ingestHttp(HOOK, {
      events: [
        // Снапшот первым: снимок гасит остальных людей источника (store.applySnapshot) — p2 в нём ещё нет.
        { type: 'snapshot', entities: [{ entityId: 'p3', status: 'online' }], at: iso(clock) },
        { type: 'status', entityId: 'p2', status: 'online', at: iso(clock) },
        { type: 'bubble', entityId: 'p2', text: 'привет', ttlSec: 30, at: iso(clock) },
        { type: 'status', agent: agentRef, status: 'working', at: iso(clock) },
      ],
    });
    expect(r).toEqual({ status: 200, body: { accepted: 4, ignored: 0 } });
    expect(rt.store.get('p2')).toMatchObject({ status: 'online', source: 'claude-hook' });
    expect(rt.store.get('p3')?.status).toBe('online');
    // Облачко действительно выставлено, а не только посчитано в accepted (p2 на машине — ждём парковки).
    advance(rt, clock, 15_000);
    expect(rt.hello().characters.find((c) => c.id === 'p2')?.bubble).toEqual({ text: 'привет', kind: 'info' });
    const agent = rt.registry.agentList().find((a) => a.project === agentRef.project);
    expect(agent?.ownerId).toBe('p1');
  });

  it('снимок людей от источника с humans не гасит агентов того же источника (спека хостинга 10)', () => {
    const { rt, clock } = humansRuntime();
    rt.ingestHttp(HOOK, { events: [{ type: 'status', agent: agentRef, status: 'working', at: iso(clock) }] });
    const r = rt.ingestHttp(HOOK, { events: [{ type: 'snapshot', entities: [{ entityId: 'p3', status: 'online' }], at: iso(clock, 1000) }] });
    expect(r).toEqual({ status: 200, body: { accepted: 1, ignored: 0 } });
    expect(rt.store.get('agent:p1:PixelOffice:%17')?.status).toBe('working');
  });

  it('человек, закреплённый за другим источником, — foreign_source', () => {
    const { rt, clock } = humansRuntime();
    rt.ingestHttp(MANUAL, { events: [{ type: 'status', entityId: 'p5', status: 'online', at: iso(clock) }] });
    const r = rt.ingestHttp(HOOK, { events: [{ type: 'status', entityId: 'p5', status: 'offline', at: iso(clock, 1000) }] });
    expect(r).toMatchObject({ status: 403, body: { error: 'foreign_source' } });
  });

  it('адресат события bubble доезжает до облачка: человек — из события, агент — хозяину (спека адресных сообщений 2.1)', () => {
    const { rt, clock } = makeRuntime();
    rt.ingestFromSource(rt.sourceByName('manual')!, [
      { type: 'status', entityId: 'p2', status: 'online', at: iso(clock) },
      { type: 'bubble', entityId: 'p2', text: 'глянь PR', ttlSec: 60, to: ['p1'], at: iso(clock) },
    ]);
    advance(rt, clock, 15_000); // p2 на машине — ждём парковки, как соседний тест про p2
    const p2 = rt.hello().characters.find((c) => c.id === 'p2') as FrameCharacter;
    expect(p2.bubbleTo).toEqual(['p1']);
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [
      { type: 'status', agent: agentRef, status: 'working', at: iso(clock) },
      { type: 'bubble', agent: agentRef, text: 'готово', ttlSec: 60, at: iso(clock) },
    ]);
    advance(rt, clock, 15_000);
    const delta = rt.drain().find((m) => m.type === 'delta');
    const ag = delta && delta.type === 'delta' ? (delta.characters.find((c) => c.id === `agent:p1:${agentRef.project}:${agentRef.slot}`) as FrameCharacter) : undefined;
    expect([ag?.bubble?.text, ag?.bubbleTo]).toEqual(['готово', ['p1']]); // хозяин hook-а — p1
  });

  it('агентское bubble с to — 400 invalid (спека адресных сообщений 2.1.3)', 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: 'bubble', agent: agentRef, text: 'привет', ttlSec: 10, to: ['p1'], at: iso(clock) }] },
    });
    expect([res.statusCode, res.json().error]).toEqual([400, 'invalid']);
  });
});

describe('событие без at (спека хостинга 9)', () => {
  it('принимается: время — момент получения, в журнале событие уже с at', () => {
    const clock = new ManualClock();
    const entries: LogEntry[] = [];
    const rt = new OfficeRuntime({ office: demoOffice(), clock, log: silentLogger, eventLog: { append: (e) => entries.push(e) } });
    const r = rt.ingestHttp(MANUAL, { events: [{ type: 'status', entityId: 'p1', status: 'online' }] });
    expect(r).toEqual({ status: 200, body: { accepted: 1, ignored: 0 } });
    expect(rt.store.get('p1')).toMatchObject({ status: 'online', at: clock.now(), receivedAt: clock.now() });
    expect(entries[0]!.event).toMatchObject({ type: 'status', at: new Date(clock.now()).toISOString() });
  });
  it('snapshot и bubble без at принимаются', () => {
    const { rt } = makeRuntime();
    const r = rt.ingestHttp(MANUAL, {
      events: [
        { type: 'snapshot', entities: [{ entityId: 'p2', status: 'online' }] },
        { type: 'bubble', entityId: 'p2', text: 'тут', ttlSec: 30 },
      ],
    });
    expect(r).toEqual({ status: 200, body: { accepted: 2, ignored: 0 } });
    expect(rt.store.get('p2')?.status).toBe('online');
  });
  it('событие с at — время из события, как раньше', () => {
    const clock = new ManualClock();
    const entries: LogEntry[] = [];
    const rt = new OfficeRuntime({ office: demoOffice(), clock, log: silentLogger, eventLog: { append: (e) => entries.push(e) } });
    const at = iso(clock, -60_000);
    rt.ingestHttp(MANUAL, { events: [{ type: 'status', entityId: 'p1', status: 'online', at }] });
    expect(rt.store.get('p1')?.at).toBe(clock.now() - 60_000);
    expect(entries[0]!.event.at).toBe(at);
  });
});
