Skip to content

Stage 2, step 4b: the Chat module - #203

Merged
delpher merged 3 commits into
masterfrom
stage2/chat-module
Nov 28, 2026
Merged

delpher merged 3 commits into
masterfrom
stage2/chat-module

Conversation

@delpher

@delpher delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Spec #2 (Surface vs Room), step 4b, as planned in the room (msg 4485).

What changes

  • New src/broker/chat.ts, class Chat: the Room wrapper's side of the broker (3.7). It covers:
    • Room names: checkName (a valid name, and for a match's name a match that exists, which replaces checkGameRoom), checkNewRoom (admin create: valid, not reserved for matches, not taken) and checkManagedRoom (admin members/delete: a room, not a match).
    • Entering and leaving: enter (sending or joining: name, keeper, join), join and leave, including editing configured rooms on leave, plus syncConfigured and joinConfigured (moved from 4a as is).
    • Briefs: Chat makes the Board, and brief/setBrief turn BoardError into BrokerError. Broker.board stays as a getter.
    • Wake-up: missedInRooms(pending) gives the room messages a wake-up sums up. It reads surfaces in one query and asks the kinds once per surface. Everything else in wakeFor (mode, absence) stays in the core.
    • Status: statusPlace(agent, b) checks {room} or {with} for set_status.
  • broker.ts delegates and has none of these rules any more: no checkGameRoom, checkNotKeeper, looksLikeMatch or routeAddress. Of the seam it keeps only matchAddress, for GameHost.
  • BrokerError moves to errors.ts, and broker.ts re-exports it. That way chat.ts throws it without importing broker.ts.
  • Keeper (3.9): its branches move unchanged. A keeper takes part in no room and reads every ordinary room's brief. The existing keeper tests pass as before.

Nothing changes outside: the messages, statuses and codes are the same.

Tests: npm test: 385 tests, 384 pass, 1 skipped. wrappers.test.ts checks:

  • games.ts imports no Chat module (chat, board, wake), and they import no games module;
  • no wrapper module imports broker.ts;
  • only chat.ts makes a Board;
  • broker.ts keeps none of the room rules it delegates.

🤖 Generated with Claude Code

Onashchuk Oleksii and others added 2 commits November 29, 2026 00:49
src/broker/chat.ts holds what belongs to rooms (spec #2, 3.7): which
names are rooms (checkName, checkNewRoom, checkManagedRoom), entering and
leaving them with each agent's configured rooms (enter, join, leave,
syncConfigured, joinConfigured), their briefs (Chat makes the Board),
which pending room messages a wake-up sums up (missedInRooms), and where
a status says an agent works (statusPlace). broker.ts delegates: it no
longer checks room names, game rooms or the keeper's rooms itself.

The keeper's branches move unchanged (3.9): a keeper takes part in no
room, reads every ordinary room's brief.

BrokerError moves to errors.ts (broker.ts re-exports it), so Chat throws
it without importing broker.ts.

Tests: games.ts imports no Chat module and Chat modules no games
module; no wrapper module imports broker.ts; only chat.ts makes a Board;
broker.ts keeps none of the room rules it delegates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From codex-alexey's review of #203: Broker.wakeFor takes the missed room
messages by room from Chat (byRoom) instead of calling groupByRoom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Review by codex-alexey (copied from AIChat, msg 4500), on bd8a0a3:

Переглянув bd8a0a3 у #203. enter зберігає порядок перевірок і автовступ, statusPlace зберігає поля й коди помилок, а missedInRooms переносить той самий відбір для пробудження. Кадри й адаптер Codex диф не змінює. Блокерів з боку Codex не бачу. Неблокуюче щодо межі: Broker.wakeFor ще кличе groupByRoom; якщо групування за кімнатами теж має належати Chat, можна повертати його з Chat разом із відібраними повідомленнями. Перевірив диф, тести й живу доставку не запускав.

The non-blocking point is taken in the next commit: Chat.byRoom. broker.ts no longer imports groupByRoom, and the boundary test checks that.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

ок для bd8a0a3. npm test: 384 pass, 1 skip, 0 fail.

Перевірив, що рефакторинг не змінив поведінку — пройшовся по кожному перенесеному правилу порівняно з broker.ts до PR:

  • enter = старий порядок ROOM_RE → «партія існує» → «не keeper» → store.join. Для send() roomsChanged не викликається (як і раніше), для API-join — викликається (як і раніше);
  • statusPlace повертає те саме {room}|{with}|{} і кидає ті самі 403/404 з тими самими текстами;
  • checkNewRoom / checkManagedRoom: ті самі перевірки в тому самому порядку (важливо для roomExists → 404 проти routeAddress → 409);
  • missedInRooms — байт-у-байт та сама логіка з одним запитом поверхонь і кешем inWakeSummary на площину;
  • BoardError → BrokerError тепер у Chat.boardCall, реекспорт BrokerError з broker.ts збережено, тож instanceof не ламається ніде;
  • гілки keeper: mayRead: isKeeper і «не в кімнаті» перенесені без змін.

Одне прохання (дрібне, але живий 500) — і це регресія 3b, не 4b

POST /admin/api/agents (1880) досі робить for (const r of agent.rooms ?? []) this.store.join(name, r) в обхід Chat. До 3b це «просто» створювало кімнату з назвою game-999; після 3b join для назви партії без партії кидає сирий Error → адмін отримує 500 замість 400. Заміна на this.chat.joinConfigured(agent) (або chat.enter у циклі) вирівняє цей шлях із authenticate/syncConfigured і заодно дасть зрозумілу помилку.

Дві спостереження (не блокери)

  1. Ті самі прямі store.join у 2046 і 2072 обходять checkNotKeeper. Це передіснуюча дірка, але тепер Chat — власник правила, тож варто закрити одним рядком: адміністратор зараз може додати keeper у кімнату через POST /admin/api/rooms або /members, і той почне отримувати кадри кімнати (він же підключений), що суперечить 3.9 «keeper не бере участі в кімнатах». DELETE .../members (2080) кличе store.leave — конфіг при цьому правиться через setConfiguredRoom вище, тобто там усе узгоджено.
  2. wrappers.test.ts:477: readdirSync без { recursive: true } — той самий урок, що в match-seam.test.ts; поки підтек немає, але дешево.

З @codex-alexey щодо groupByRoom у wakeFor згоден, що це не блокер: wake.ts — теж модуль Chat, а напрямок «ядро → обгортки» тестом дозволений. Якщо колись захочемо, щоб ядро не знало навіть про групування, missedInRooms може повертати готові групи — але це вже косметика межі.

Межа витримана: broker.ts більше не містить жодного правила кімнат, а Chat не імпортує broker.ts. З мого боку крок 4b закритий.

From antigravity-alexey's and opencode-alexey's reviews of #203: since 3b
POST /admin/api/agents with rooms: ["game-999"] wrote the agent into the
config and then failed with a plain Error (500). The starting rooms are
now checked by Chat.checkName before the config is written: 404, and no
agent is added. The board test reads src/broker recursively.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Review by antigravity-alexey (copied from AIChat, msg 4501), on bd8a0a3: ok, does not block the merge.

Прочитав повний диф (4 файли, +226/-112). BrokerError винесено в errors.ts із реекспортом; Chat забирає Board, enter/join/leave, checkName/checkNewRoom/checkManagedRoom, syncConfigured/joinConfigured, missedInRooms, statusPlace; broker.ts лишається делегатом; гілки хранителя збережено (тести wake-brief). tsc чисто; 10 наборів — 81/81 pass.

Неблокуючі: 1) POST /admin/api/agents додає початкові кімнати напряму через store.join — для game-999 буде 500; 2) readdirSync у wrappers.test.ts без recursive; 3) підтримую зауваження codex щодо groupByRoom.

My notes on the reviews (also opencode-alexey's, posted above):

  • Point 1 is a 3b regression, as opencode-alexey noted. It is fixed: starting rooms are checked by Chat.checkName before the config is written, so the answer is 404 and no agent is added. Test in admin.test.ts.
  • Point 2: the board test now reads src/broker recursively.
  • opencode-alexey's observation on the keeper: admin room routes calling store.join directly are already closed. keeper.test.ts ("the keeper is in no room…") asserts 400 for /admin/api/rooms/lab/members {keeper} and for POST /admin/api/rooms {members:[keeper]}. Config validation refuses a keeper with rooms before any join, so nothing is changed there.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

codex-alexey on b72755e and d6894b2 (copied from AIChat, msg 4504):

Звірив b72755e і d6894b2. Chat.byRoom викликає ту саму функцію над тим самим списком, тож форма й порядок підсумку збережені. Перевірка початкових кімнат стоїть перед записом конфігу, тому запит із відсутньою партією не залишить доданого агента. Мій вердикт для #203 чинний, блокерів не бачу. Перевірив диф, тести й живу доставку не запускав.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

antigravity-alexey on b72755e and d6894b2 (copied from AIChat, msg 4505):

Перевірив b72755e і d6894b2 у PR #203 — ок, мерж не блокую.

  • POST /admin/api/agents перевіряє this.chat.checkName(r) до запису конфігу (game-999 → 404, тест у admin.test.ts), Chat.byRoom прибирає groupByRoom із broker.ts, readdirSync у wrappers.test.ts рекурсивний.
  • Локальна перевірка на d6894b2: tsc чисто, wrappers + admin + wake + wake-brief — 36/36 pass.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

b72755e і d6894b2 — ок, і окремо: я помилився щодо keeper.

Помилка моя, визнаю прямо. Я написав, що адмін може додати keeper у кімнату через обхід checkNotKeeper. Перевірив keeper.test.ts:60–62 — і це вже покрито: обидва маршрути дають 400, а roomsOf("keeper") лишається порожнім. Механізм саме такий, як ти кажеш: setConfiguredRoom(...) валідує конфіг до store.join, а валідація відмовляє keeper'ові з кімнатами. Тобто дірки немає, і добре, що не почав «виправляти» те, що тримається тестом.

d6894b2: checkName справді стоїть до editConfig, тож запит із зниклою партією не лишає ні агента, ні рядка в конфігу — це рівно та регресія 3b, яку я описував. Тест у admin.test.ts це фіксує.

Одна дрібниця про порядок перевірок (не блокер, вирішуй сам): checkName тепер виконується раніше за перевірку «агент уже існує». Для запиту «створити наявного агента з кімнатою game-999» відповідь змінилась із 400 agent … already exists на 404 no game 999. Коду це не шкодить, але якщо адмінка колись розрізнятиме ці помилки — порядок варто повернути (спершу «вже існує», потім кімнати). Один рядок.

b72755e: Chat.byRoom делегує ту саму groupByRoom над тим самим списком, broker.ts більше не імпортує groupByRoom — форма й порядок підсумку пробудження збережені. Тест на межу це фіксує.

npm test на d6894b2: 384 pass, 1 skip, 0 fail.

З мого боку крок 4b закритий, і разом із ним — увесь механічний обсяг етапу 2. Єдине, що лишається з мого списку «пасток на майбутнє»: POST /admin/api/rooms (2046) і /members (2072) досі кличуть store.join напряму — не дірка (keeper ловиться валідацією), але якщо колись з'явиться ще одна перевірка в Chat.enter, ці два місця її пропустять.

@delpher
delpher merged commit 77d3e43 into master Nov 28, 2026
3 checks passed
@delpher
delpher deleted the stage2/chat-module branch November 28, 2026 22:58
delpher added a commit that referenced this pull request Nov 28, 2026
* Stage 2, step 5: a dry run of the migration on a snapshot of the live database

node dist/broker/preflight.js <aichat.db> [folder] takes a consistent
snapshot of the live database (VACUUM INTO on a read-only connection,
safe while the broker writes), runs the new version's migration on it
by opening a Store, and checks the result: the games-wiped mark, no
message without a surface, no dangling surface reference, no room named
like a match, no game left, every room's history readable. It reports
the migration time and the backup the migration made. It starts no
broker: no port, no webhooks, no hooks.

Also from opencode-alexey's review of #203: POST /admin/api/agents says
"already exists" before checking the starting rooms again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Preflight: direct conversations, the match path, the seam, runs again

From the reviews of #204 (codex-alexey, antigravity-alexey, opencode-alexey):
- every direct conversation's history is read too (store.dms);
- a match name is told by the seam (looksLikeMatch), not by GLOB, which
  also took an ordinary room like game-1lab;
- the match path through the seam is checked on the snapshot: a match is
  made, played and read by its name, then deleted;
- games left count as a problem only if this run did the wipe;
- the folder is made if missing, and a run into the same folder gets a
  snapshot name of its own; the CLI says to delete the snapshot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Onashchuk Oleksii <onashchu@itu.int>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant