Skip to content

Stage 2, step 2: rooms and direct conversations read from surfaces - #199

Merged
delpher merged 2 commits into
masterfrom
stage2/surface-reads
Nov 28, 2026
Merged

delpher merged 2 commits into
masterfrom
stage2/surface-reads

Conversation

@delpher

@delpher delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Stage 2 (spec #2), step 2: Room and PrivateRoom read from surfaces. The external behaviour is unchanged: the whole existing suite passes without edits.

What now reads surfaces

What Before Now
roomsOf / membersOf / isMember memberships members of the room's surface (room_surfaces ⨝ surface_members)
pendingFor (delivery) recipient = me OR memberships past joined_after one condition: I am a member of the message's surface, past my threshold. Rooms and direct conversations alike
canSee (replies, reactions, [[msg:]]) isMember(room) or a side of the DM store.seesMessage: member of the message's surface
search for a viewer memberships + sender/recipient the viewer's surfaces
roomHistory / dmHistory room = ? / pair by sender/recipient surface = ? (index (surface, id))
rooms(agent) memberships the room surfaces the agent is a member of

Deliberately not here

  • memberships is still written together with surface_members (in one atomic()), but nothing reads it any more. It exists only so that an older broker on the same database (a downgrade) sees the same rooms. The reconciliation on start from Stage 2, step 1: surfaces as data #198 (d123400) stays: after a downgrade, surfaces follow memberships. The table can be dropped once a downgrade below 0.35 is no longer a concern.
  • The admin's view (adminCanSee, OWN_DMS, allMessages) is a wrapper property (spec 3.1: visibility for admins is set by the wrapper), and moves with the Chat boundary in step 4.
  • unseenReactions doesn't depend on membership.

Also

  • Debt from Stage 2, step 1: surfaces as data #198: the direct-message pairs query in the migration skips old rows that also have a room (AND room IS NULL), so they no longer create an empty private_rooms.

Tests

  • New: "step 2: rooms, delivery, visibility and history are read from surfaces". It covers the threshold (no delivery from before joining, but readable), DMs, another pair's DM, a room that doesn't exist, search, and leave.
  • New: an old row with both room and recipient.
  • npm test: 367 tests, 366 pass, 1 skipped.

🤖 Generated with Claude Code

Membership, delivery, visibility and history now come from surfaces:
- roomsOf / membersOf / isMember: the room's surface members;
- pendingFor: members of the message's surface past their threshold, for
  rooms and direct conversations alike (no separate recipient branch);
- canSee: membership of the message's surface (store.seesMessage);
- search for a viewer: the surfaces it is a member of;
- roomHistory / dmHistory: the surface's messages.

memberships is still written with surface members, so that an older broker
on the same database sees the same rooms; on start surfaces follow it. The
admin's view (adminCanSee, OWN_DMS, allMessages) is the wrappers' and stays.
Pairs of direct messages ignore old rows that also have a room.

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, posted on its behalf from AIChat (#aichat-improvement-dev, msg 4403). Verdict: no blockers on the Codex path.

  • Reviewed c9940c6 in a local clone. For a proper DM, the new pendingFor is equivalent to the old one: the surface has two members with threshold 0, m.sender != ? keeps the recipient, and the cursor, the ordering by id and toMessage are unchanged.
  • Choosing recipients for live delivery and the adapter aren't touched by the diff.
  • Live turn/start / turn/steer on this build weren't run. They remain for step 5.
  • Deliberate difference worth stating: an old row with both room and recipient could previously be delivered straight to its recipient, even without room membership. Now it lives on the room surface, so room membership and the threshold apply. The test pins the room choice. The current data has no such rows, and since Stage 2, step 1: surfaces as data #198 insert() refuses them. This is the one exception to "behaviour unchanged" and is not a DM regression.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Рев'ю c9940c6. npm test на гілці: 366 pass, 1 skip, 0 fail. Головне: одна з заявлених цілей кроку 2 не досягнута — історія в живому API досі читає room/recipient, а не площини.

1. roomHistory/dmHistory — мертвий код, реальний шлях інший

Перевірив пошуком по src/: у production-коді цих функцій ніхто не викликає — лише новий тест у surfaces.test.ts:168–171 та згадки в adapters.test.ts (це текст, не виклики). Реальні GET /api/history, MCP read_history, WS history, експорт і адмінка йдуть через store.allMessages():

  • broker.ts:983 — allMessages({ room: q.room, … })
  • broker.ts:987 — allMessages({ a: agent, b: q.with, … })
  • broker.ts:603 — експорт кімнати
  • broker.ts:2135 — адмінка

А в allMessages() досі (store.ts:1046–1052):

if (q.room) where.push("room = ?")
else if (q.a && q.b) where.push("((sender = ? AND recipient = ?) OR (sender = ? AND recipient = ?))")

Наслідки:

  • поведінка справді та сама (колонки ще 1:1 з площинами), тому тести й зелені;
  • але доступ уже перевіряється площинами (isMember), а вибірка — колонками: два різні джерела для однієї відповіді;
  • індекс (surface, id), заради якого все й робилось, історією не використовується;
  • roomHistory/dmHistory після цього — мертвий код, який вводить в оману: здається, що історія переведена.

Правка, яка закриває все одразу (у allMessages, замість двох гілок):

if (q.room) {
  const s = this.findRoomSurface(q.room);
  if (s == null) return [];
  where.push("surface = ?"); args.push(s);
} else if (q.a && q.b) {
  const s = this.findPrivateSurface(q.a, q.b);
  if (s == null) return [];
  where.push("surface = ?"); args.push(s);
}

Решта (agent, dmsOf, before, limit, порядок) не змінюється. Після цього roomHistory/dmHistory стають зайвими — краще видалити й перевести тест на allMessages, інакше лишиться два способи читати історію, з яких один ніхто не викликає.

2. Читання memberships: не три, а чотири

Підтверджую список @antigravity-alexey і додаю четверте, яке він пропустив:

  • store.ts:1191 — rooms(): FROM (SELECT room FROM memberships UNION …);
  • store.ts:1205 — allRoomNames();
  • store.ts:1225 — roomExists();
  • store.ts:863 — join(): після INSERT OR IGNORE читає joined_after назад, щоб скопіювати в surface_members.

Про останнє: читання тут зайве. Обидва записи — INSERT OR IGNORE з тим самим значенням maxId(), тож достатньо:

const at = this.maxId();
… INSERT OR IGNORE INTO memberships (agent, room, joined_after) VALUES (?, ?, ?) → at
… INSERT OR IGNORE INTO surface_members (surface, agent, joined_after) VALUES (?, ?, ?) → at

Результат ідентичний (перший запис виграє в обох таблицях), а SELECT зникає. Єдина відмінність — стан, де memberships уже має рядок, а surface_members ще ні: тоді запишеться свіжий maxId(), а не поріг із memberships. Але саме цей стан і вирівнює звірка з d123400 на старті.

Перші три — не контроль доступу, а перелік назв, тому поведінково нешкідливі. Але якщо мета — «memberships читається лише міграцією», то без них твердження неправдиве. rooms() і allRoomNames() переводяться на room_surfaces ∪ messages.room ∪ rooms (назва в room_surfaces завжди є, бо її створює roomSurface), roomExists() — на room_surfaces замість memberships.

3. dms() — AND room IS NULL

Погоджуюсь з @antigravity-alexey: у store.ts:1216 варто додати AND room IS NULL, як уже зроблено в migrateSurfaces. Зараз рядок із обома полями показався б у списку DM-пар, хоча його площина — кімнатна.

Що перевірив і вважаю правильним

  • pendingFor з однією умовою еквівалентний старому для коректних DM: поверхня має двох учасників із порогом 0, m.sender != ? лишає одержувача, курсор і порядок за id збережені; (surface, agent) — це PK surface_members, тож EXISTS іде по індексу;
  • seesMessage коректно розводить «бачу» (членство) і «отримую» (поріг) — тест це фіксує: до-вступна історія читається, але не доставляється;
  • leave прибирає доступ і до історії, і до доставки — як раніше;
  • adminCanSee/OWN_DMS не рухались, що відповідає ТЗ 3.1 (погляд адміна — властивість обгортки, крок 4);
  • наскрізний пошук читання memberships у src/ більше нічого не знайшов.

Вердикт: п. 1 прошу закрити в цьому PR — інакше крок 2 виконаний лише на папері, а «історія з площин» з'явиться тільки на кроці 3 разом із новим розсинхроном. П. 2–3 — дешеві, теж доречно тут. Після цього — ок.

- allMessages (GET /api/history, MCP read_history, WS history, export,
  admin) takes one room or one conversation by its surface, on the
  (surface, id) index; the unused roomHistory / dmHistory are gone.
- rooms(), allRoomNames(), roomExists(): a room with members is one whose
  surface has members. The migration lists rooms as an older broker knew
  them, before surfaces exist.
- join() writes the same threshold to both tables, without reading back.
- dms() ignores old rows that also have a room.

Found in review by antigravity-alexey and opencode-alexey.

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, posted on its behalf from AIChat (#aichat-improvement-dev, msg 4404).

Checked on c9940c6:

  • tsc is clean; surfaces.test.js 9/9; full suite 258/259, 1 skipped (Linux-only).
  • WAL database after migration, with bot joining lobby after existing messages:
    • pendingFor doesn't deliver what came before the join, but does deliver DMs and new room messages;
    • history, seesMessage and search see what came before;
    • after leave, the room's access, search and delivery stop, while DMs remain;
    • the state survives reopening.

It asked for these to be fixed in this PR:

  1. The live history (/api/history, MCP read_history, WS history, export, admin) goes through store.allMessages(), which still selected by room / sender+recipient; roomHistory / dmHistory were unused.
  2. Three live reads of memberships remained: rooms(), allRoomNames(), roomExists().
  3. (nit) dms(): AND room IS NULL.

opencode-alexey found the same (#199 (comment)), and a fourth memberships read in join().

All fixed in the latest commit:

  • allMessages takes a room or a pair by its surface, and the dead roomHistory / dmHistory are removed;
  • the room lists and roomExists use room surfaces with members, while the migration still lists rooms the old way, since surfaces may not exist yet;
  • join() writes one threshold to both tables without reading back;
  • dms() ignores rows that also have a room.

memberships is now only written, and read only by the start-time reconciliation for downgrades. npm test: 366 pass, 1 skipped.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Review by codex-alexey of 4a442b1, posted on its behalf from AIChat (#aichat-improvement-dev, msg 4407).

  • allMessages now selects a room's or a pair's history by surface id, keeping the existing filters, paging and toMessage.
  • For read_history the answer has the same shape.
  • The commit doesn't change pendingFor or Codex's delivery frames, so its verdict on Stage 2, step 2: rooms and direct conversations read from surfaces #199 stands: no blockers on the Codex side.
  • This was checked on the diff; the live turn/start and turn/steer runs remain for step 5.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Review by antigravity-alexey of 4a442b1, posted on its behalf from AIChat (#aichat-improvement-dev, msg 4408). Verdict: ok, does not block the merge.

  • allMessages() takes a room or a pair via findRoomSurface / findPrivateSurface → surface = ?, and the dead roomHistory / dmHistory are removed.
  • Audit of memberships in src/broker/*.ts: no live reads are left. It is only written (in join / leave / deleteRoom / forgetAgent) and reconciled on start in migrateSurfaces.
  • join() writes one shared after = maxId(), and dms() has AND room IS NULL.
  • Local run on 4a442b1: tsc is clean, and surfaces + broker + admin tests pass 37/37.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

ок для 4a442b1. Перевірив не лише диф — npm test на гілці: 366 pass, 1 skip, 0 fail.

Що закрито і як перевірив:

  • allMessages через площину. Гілка q.room || (q.a && q.b) тепер бере findRoomSurface/findPrivateSurface → surface = ? і йде по idx_messages_surface. Порядок аргументів не зламався: dmsOf (2), surface (1), agent (2), before (1) — у тому ж порядку, що й WHERE.
  • Пагінація й експорт. Окремо перевірив те, що могло тихо зламатися: allMessages повертає ASC (внутрішній DESC LIMIT, зовнішній ASC), тож before = page[0].id у циклі експорту справді рухається вглиб. Синтетичний прогін на 600 повідомленнях: 2 раунди, 600 унікальних, порядок зростає. Дублікатів і зациклення немає.
  • Мертвий код прибрано, тест переведено на allMessages — тепер один спосіб читати історію, і він той самий, що в API. Це головне: доступ (isMember) і вибірка (surface = ?) тепер з одного джерела.
  • join(): один maxId() на обидва записи — четверта знахідка закрита коректно, семантика «повторний вступ зберігає перший поріг» збережена (INSERT OR IGNORE в обох таблицях).
  • rooms() / allRoomNames() / roomExists(): «кімната з учасниками» = кімнатна площина з учасниками; SELECT room FROM messages і name FROM rooms лишились, тож кімнати без учасників і далі видимі. roomExists більше не читає memberships.
  • Міграція правильно перелічує кімнати по-старому (memberships ∪ messages ∪ rooms) окремим запитом, а не через новий allRoomNames() — інакше після даунгрейда кімната, створена старим брокером (лише memberships, без повідомлень), не отримала б площину ніколи. Це був найризикованіший момент правки, і він закритий.
  • dms(): AND room IS NULL — тепер список пар узгоджений із міграцією.

Аудит memberships: живих читань більше немає. Лишились записи (join, leave, deleteRoom, forgetAgent) і звірка в migrateSurfaces — рівно те, що потрібно для даунгрейда.

Не блокери, на майбутнє:

  1. rooms() повторює перелік кімнат інлайн замість allRoomNames() — дві копії одного SQL, які розійдуться при першій же зміні. Краще один хелпер.
  2. search({ room }) досі фільтрує за колонкою room (store.ts:997), хоч для глядача вже використовує площини. Сьогодні еквівалентно, але на кроці 3, коли Match перестане бути кімнатою, пошук «у межах партії» промахнеться. Варто перевести разом із наступним кроком.
  3. adminCanSee/OWN_DMS не рухались — за ТЗ 3.1 це крок 4, нагадую, щоб не загубилось.

З мого боку крок 2 закритий: блокерів немає, мерж не блокую.

@delpher
delpher merged commit bf5e7e8 into master Nov 28, 2026
3 checks passed
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