Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(db): normalize conversation membership (#168)
OKNOTOKbb961a36f97e
diff --git a/docs/decisions/0004-normalized-conversation-membership.md b/docs/decisions/0004-normalized-conversation-membership.mdnew file mode 100644index 0000000..07fdde4--- /dev/null+++ b/docs/decisions/0004-normalized-conversation-membership.md@@ -0,0 +1,73 @@+# ADR 0004: Normalized conversation membership as authorization truth++- Status: Accepted+- Date: 2026-09-03++## Context++`conversations.members` was a JSONB array used simultaneously as an API+projection, an authorization boundary, and a routing index. It could not carry+tenant-scoped foreign keys. Invite, leave, and kick paths also rewrote the+whole array, so overlapping requests could lose a change, resurrect a removed+member, or commit a system notice that disagreed with the effective access+state. Correctness depended on every caller remembering the same predicates+and Redis publishing happened outside the membership transaction.++Email threads additionally used synthetic `external:<addr>` author markers in+the array. Those markers identify message authors, but they are not tenant+participants and must never become authorization principals.++## Decision++- `conversation_members` is the sole authorization and routing source. Its+ composite foreign keys bind each row to both the conversation tenant and an+ actual participant in that tenant.+- Membership changes insert or delete one normalized row while holding active+ participant locks followed by the conversation lock. Authorization is+ re-read in a separate statement after the conversation lock is acquired so+ a lock wait cannot retain an obsolete statement snapshot.+- The membership row, derived JSONB projection, system audit message, sequence+ counter, and realtime outbox record commit in one PostgreSQL transaction.+- `conversations.members` remains only as a response-shape compatibility+ projection for the new application. A database function rebuilds it from+ normalized rows. During the expand release, a trigger translates writes from+ the previous application revision into tenant-validated normalized rows and+ canonicalizes the projection under the same row lock.+- A conversation insert trigger converts the initial JSONB input into+ normalized rows. Synthetic external email author markers are discarded;+ any other missing or cross-tenant participant fails closed.+- Production authorization, recipient fan-out, member counts, and direct-pair+ lookup use the normalized indexes. The former JSONB GIN path and its+ session-level query-planner override are no longer runtime dependencies.++## Consequences++- PostgreSQL enforces tenant integrity and prevents orphan or foreign member+ identifiers rather than relying on route-level convention.+- Concurrent invites, leaves, and kicks serialize without whole-array lost+ updates; a failed audit or outbox write rolls the membership change back.+- Participant tenant reassignment must first detach the participant from old+ conversations. This explicit cleanup replaces stale cross-tenant member ids.+- Legacy and API consumers may continue reading `conversations.members`, but+ new code must not use that projection for authorization or routing.+- The expand release retains the legacy JSONB index and synchronization ingress+ so the previous revision can serve safely during rollout or rollback. A later+ contract release may reject projection writes and drop that index only after+ the pre-0002 revision is outside the rollback window.+- Migration 0002 backfills and canonicalizes existing rows. It rejects unknown+ internal member ids while intentionally removing external email markers.++## Alternatives considered++- **Keep JSONB and centralize array helpers:** rejected because application+ helpers cannot provide foreign keys, prevent ad hoc writes, or give the+ planner a relational tenant/member index.+- **Add only a JSONB projection trigger:** rejected because the array would+ remain the writable truth and every authorization query would still depend+ on denormalized containment semantics.+- **Use Redis sets as membership truth:** rejected because message, audit, and+ access changes need one durable transaction; Redis cannot share PostgreSQL's+ commit boundary.+- **Store external email addresses as participants:** rejected because an+ inbound address is an author identity, not an authenticated workspace+ principal, and would expand the authorization domain unnecessarily.diff --git a/server/src/__integration__/_helpers.ts b/server/src/__integration__/_helpers.tsindex 8c6c60d..3ea48cf 100644--- a/server/src/__integration__/_helpers.ts+++ b/server/src/__integration__/_helpers.ts@@ -58,6 +58,7 @@ const TABLES_TO_WIPE: readonly string[] = ['conversation_reads','conversation_counters','messages',+ 'conversation_members','conversations','agent_climate','agent_workspace',diff --git a/server/src/__integration__/conversation-members-normalization.test.ts b/server/src/__integration__/conversation-members-normalization.test.tsnew file mode 100644index 0000000..58651ca--- /dev/null+++ b/server/src/__integration__/conversation-members-normalization.test.ts@@ -0,0 +1,157 @@+import assert from 'node:assert/strict'+import { randomUUID } from 'node:crypto'+import { after, before, beforeEach, test } from 'node:test'+import { addConversationMember } from '../agents/membership.js'+import { pool } from '../db/pool.js'+import {+ ensureSchemaOnce,+ resetAllTables,+ seedCompanyWithAgent,+ teardownAll,+} from './_helpers.js'++before(async () => { await ensureSchemaOnce() })+beforeEach(async () => { await resetAllTables() })+after(async () => { await teardownAll() })++async function seedGroup(companyId: string, members: string[]): Promise<string> {+ const conversationId = `conv-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO conversations (id, company_id, kind, title, members)+ VALUES ($1, $2, 'group', 'normalized membership', $3::jsonb)`,+ [conversationId, companyId, JSON.stringify(members)],+ )+ return conversationId+}++test('[integration] tenant FKs reject a foreign participant membership', async () => {+ const tenantA = await seedCompanyWithAgent({ agentId: 'normalized-a' })+ const tenantB = await seedCompanyWithAgent({ agentId: 'normalized-b' })+ const conversationId = await seedGroup(tenantA.companyId, [tenantA.agentId])++ await assert.rejects(+ () => pool.query(+ `INSERT INTO conversation_members+ (conversation_id, company_id, participant_id, ordinal)+ VALUES ($1, $2, $3, 1)`,+ [conversationId, tenantA.companyId, tenantB.agentId],+ ),+ (error) => (error as { code?: string }).code === '23503',+ )++ const { rows } = await pool.query<{ participant_id: string }>(+ `SELECT participant_id FROM conversation_members+ WHERE conversation_id = $1 ORDER BY ordinal`,+ [conversationId],+ )+ assert.deepEqual(rows.map((row) => row.participant_id), [tenantA.agentId])+})++test('[integration] legacy JSONB writes synchronize into the normalized truth during expand', async () => {+ const tenant = await seedCompanyWithAgent({ agentId: 'projection-owner' })+ const peer = await seedCompanyWithAgent({+ companyId: tenant.companyId,+ agentId: 'projection-peer',+ })+ const conversationId = await seedGroup(tenant.companyId, [+ tenant.agentId,+ 'external:[email protected]',+ ])++ const { rows: initial } = await pool.query<{ members: string[] }>(+ `SELECT members FROM conversations WHERE id = $1`,+ [conversationId],+ )+ assert.deepEqual(initial[0].members, [tenant.agentId])++ await pool.query(+ `UPDATE conversations SET members = $2::jsonb WHERE id = $1`,+ [conversationId, JSON.stringify([+ tenant.agentId,+ peer.agentId,+ 'external:[email protected]',+ ])],+ )++ const { rows: synchronized } = await pool.query<{ members: string[]; normalized: string[] }>(+ `SELECT c.members,+ ARRAY(+ SELECT member.participant_id FROM conversation_members member+ WHERE member.conversation_id = c.id ORDER BY member.ordinal+ ) AS normalized+ FROM conversations c WHERE c.id = $1`,+ [conversationId],+ )+ assert.deepEqual(synchronized[0], {+ members: [tenant.agentId, peer.agentId],+ normalized: [tenant.agentId, peer.agentId],+ })++ await assert.rejects(+ () => pool.query(+ `UPDATE conversations SET members = '["missing-participant"]'::jsonb WHERE id = $1`,+ [conversationId],+ ),+ (error) => (error as { code?: string }).code === '23503',+ )++ const { rows: unchanged } = await pool.query<{ members: string[] }>(+ `SELECT members FROM conversations WHERE id = $1`,+ [conversationId],+ )+ assert.deepEqual(unchanged[0].members, [tenant.agentId, peer.agentId])+})++test('[integration] membership, audit message, and realtime outbox roll back together', async () => {+ const tenant = await seedCompanyWithAgent({ agentId: 'atomic-owner' })+ const target = await seedCompanyWithAgent({+ companyId: tenant.companyId,+ agentId: 'atomic-target',+ })+ const conversationId = await seedGroup(tenant.companyId, [tenant.agentId])++ await pool.query(`+ CREATE FUNCTION ar_h3_reject_realtime_outbox()+ RETURNS TRIGGER LANGUAGE plpgsql AS $test$+ BEGIN+ RAISE EXCEPTION 'forced realtime outbox failure';+ END+ $test$;+ CREATE TRIGGER ar_h3_reject_realtime_outbox+ BEFORE INSERT ON realtime_outbox+ FOR EACH ROW EXECUTE FUNCTION ar_h3_reject_realtime_outbox();+ `)+ try {+ await assert.rejects(+ () => addConversationMember({+ conversationId,+ companyId: tenant.companyId,+ actorId: tenant.agentId,+ memberId: target.agentId,+ }),+ /forced realtime outbox failure/,+ )+ } finally {+ await pool.query(`DROP TRIGGER IF EXISTS ar_h3_reject_realtime_outbox ON realtime_outbox`)+ await pool.query(`DROP FUNCTION IF EXISTS ar_h3_reject_realtime_outbox()`)+ }++ const { rows } = await pool.query<{+ members: string[]; membership_count: number; message_count: number; outbox_count: number+ }>(+ `SELECT c.members,+ (SELECT COUNT(*)::int FROM conversation_members member+ WHERE member.conversation_id = c.id) AS membership_count,+ (SELECT COUNT(*)::int FROM messages message+ WHERE message.conversation_id = c.id) AS message_count,+ (SELECT COUNT(*)::int FROM realtime_outbox) AS outbox_count+ FROM conversations c WHERE c.id = $1`,+ [conversationId],+ )+ assert.deepEqual(rows[0], {+ members: [tenant.agentId],+ membership_count: 1,+ message_count: 0,+ outbox_count: 0,+ })+})diff --git a/server/src/__integration__/html.test.ts b/server/src/__integration__/html.test.tsindex 28755b6..37504cb 100644--- a/server/src/__integration__/html.test.ts+++ b/server/src/__integration__/html.test.ts@@ -108,11 +108,27 @@ test('[integration] returns 403 when the requester is not a thread member', asyn// members list so the membership check fails even though the auth// header is valid.const { messageId, companyId } = await seedEmailWithHtml('<p>secret</p>')- await pool.query(- `UPDATE conversations SET members = to_jsonb(ARRAY[$2]::text[])- WHERE id = (SELECT conversation_id FROM email_messages WHERE message_id = $1)`,- [messageId, 'someone-else'],- )+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const { rows } = await client.query<{ conversation_id: string }>(+ `DELETE FROM conversation_members+ WHERE participant_id = $2+ AND conversation_id = (+ SELECT conversation_id FROM email_messages WHERE message_id = $1+ )+ RETURNING conversation_id`,+ [messageId, ME_USER_ID],+ )+ assert.ok(rows[0])+ await client.query(`SELECT refresh_conversation_members_projection($1)`, [rows[0].conversation_id])+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }const res = await fetchHtml(messageId, companyId)assert.equal(res.status, 403)})diff --git a/server/src/__integration__/human-cli-collaboration.test.ts b/server/src/__integration__/human-cli-collaboration.test.tsindex 5bbcefa..4d1dd81 100644--- a/server/src/__integration__/human-cli-collaboration.test.ts+++ b/server/src/__integration__/human-cli-collaboration.test.ts@@ -33,12 +33,16 @@ test('[integration] a human participant can open a CLI DM with an agent', asyncassert.equal(result.ok, true, `human-authored DM should succeed: ${result.text}`)const { rows: conversations } = await pool.query<{ id: string; members: string[] }>(- `SELECT id, members FROM conversations- WHERE kind = 'direct'- AND members @> $1::jsonb- AND members @> $2::jsonb- AND jsonb_array_length(members) = 2`,- [JSON.stringify([humanId]), JSON.stringify([agentId])],+ `SELECT c.id,+ ARRAY_AGG(member.participant_id ORDER BY member.ordinal) AS members+ FROM conversations c+ JOIN conversation_members member ON member.conversation_id = c.id+ WHERE c.kind = 'direct'+ GROUP BY c.id+ HAVING COUNT(*) = 2+ AND BOOL_OR(member.participant_id = $1)+ AND BOOL_OR(member.participant_id = $2)`,+ [humanId, agentId],)assert.equal(conversations.length, 1)assert.deepEqual(new Set(conversations[0].members), new Set([humanId, agentId]))diff --git a/server/src/__integration__/membership-concurrency.test.ts b/server/src/__integration__/membership-concurrency.test.tsindex 04517a8..1121223 100644--- a/server/src/__integration__/membership-concurrency.test.ts+++ b/server/src/__integration__/membership-concurrency.test.ts@@ -1,19 +1,18 @@/*** Concurrent membership changes must not lose each other.*- * `conversations.members` is a jsonb array, and every mutation of it read the- * array, edited it in JavaScript, and wrote the whole thing back. Two of those- * overlapping means the second write is computed from a snapshot taken before- * the first, so the first change is silently erased.+ * Membership is normalized into tenant-constrained rows. Every mutation locks+ * the active participant rows and conversation in one order, changes one+ * membership row, rebuilds the JSON compatibility projection, and commits its+ * system message plus realtime outbox row in the same transaction.** This is a hot path here rather than a theoretical one: the scheduler wakes* several agents for the same message, and `cumora invite` / `leave` / `kick`* are things those agents do in response. Concurrency is the normal case.*- * The dropped invite is worse than it first looks. The `joined` system row is- * posted regardless, so the transcript records a join that did not happen —- * and because the mailbox query filters on `members @> [agentId]`, the agent- * who "joined" is never woken for that conversation again. Nothing errors.+ * These tests keep two real PostgreSQL clients on opposing lock queues. They+ * therefore cover lost updates, stale authorization, duplicate invites, and+ * the transcript/routing divergence that the old JSONB source allowed.** Only a real Postgres can show this: it is about what two overlapping* statements do to one row.@@ -23,6 +22,7 @@ import assert from 'node:assert/strict'import { randomUUID } from 'node:crypto'import { createServer, type Server } from 'node:http'import { setTimeout as delay } from 'node:timers/promises'+import type { PoolClient } from 'pg'import { pool } from '../db/pool.js'import { runCli } from '../agents/cli.js'import { inprocClient } from '../agents/runtime/inproc-client.js'@@ -78,11 +78,67 @@ async function seedGroup(companyId: string, members: string[]): Promise<string>async function membersOf(convoId: string): Promise<string[]> {const { rows } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1`, [convoId],+ `SELECT COALESCE(+ ARRAY_AGG(participant_id ORDER BY ordinal),+ ARRAY[]::text[]+ ) AS members+ FROM conversation_members+ WHERE conversation_id = $1`,+ [convoId],)return rows[0]?.members ?? []}+async function removeMemberWithClient(+ client: PoolClient,+ conversationId: string,+ participantId: string,+ companyId?: string,+): Promise<void> {+ await client.query(+ `DELETE FROM conversation_members+ WHERE conversation_id = $1+ AND participant_id = $2+ AND ($3::text IS NULL OR company_id = $3)`,+ [conversationId, participantId, companyId ?? null],+ )+ await client.query(`SELECT refresh_conversation_members_projection($1)`, [conversationId])+}++async function removeMember(+ conversationId: string,+ participantId: string,+ companyId?: string,+): Promise<void> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await removeMemberWithClient(client, conversationId, participantId, companyId)+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}++async function detachParticipantWithClient(+ client: PoolClient,+ participantId: string,+ companyId: string,+): Promise<void> {+ const { rows } = await client.query<{ conversation_id: string }>(+ `DELETE FROM conversation_members+ WHERE participant_id = $1 AND company_id = $2+ RETURNING conversation_id`,+ [participantId, companyId],+ )+ for (const conversationId of new Set(rows.map((row) => row.conversation_id))) {+ await client.query(`SELECT refresh_conversation_members_projection($1)`, [conversationId])+ }+}+async function noticesOf(convoId: string): Promise<Array<{ kind?: string; participantId?: string }>> {const { rows } = await pool.query<{ body: string }>(`SELECT body FROM messages WHERE conversation_id = $1 AND kind = 'system'`, [convoId],@@ -107,8 +163,8 @@ async function waitForBlockedQuery(pattern: string, minimum: number = 1): Promisthrow new Error(`query never reached the expected row lock: ${pattern}`)}-async function waitForBlockedMembershipUpdate(fragment: 'members ||' | 'members -'): Promise<void> {- await waitForBlockedQuery(`%UPDATE conversations c%SET members = ${fragment}%`)+async function waitForBlockedMembershipUpdate(_fragment: 'members ||' | 'members -'): Promise<void> {+ await waitForBlockedQuery('%SELECT c.id%FROM conversations c%FOR UPDATE OF c%')}async function waitForBlockedMembershipGuards(minimum: number): Promise<void> {@@ -120,7 +176,7 @@ async function waitForBlockedMembershipGuards(minimum: number): Promise<void> {AND pid <> pg_backend_pid()AND wait_event_type = 'Lock'AND (- query ILIKE '%UPDATE conversations c%SET members =%'+ query ILIKE '%SELECT c.id%FROM conversations c%FOR UPDATE OF c%'OR query ILIKE '%FROM participants%FOR UPDATE%')`,)@@ -151,7 +207,7 @@ test('[integration] simultaneous invites do not lose an invitee', async () => {// Every invite reported success, so every invitee must actually be a member.// Before the fix several were missing while their `joined` rows still stood,- // and their mailbox query (members @> [id]) never matched again.+ // and their normalized mailbox membership never matched again.const members = await membersOf(convo)const missing = invitees.filter((who) => !members.includes(who))assert.deepEqual(missing, [], `dropped despite reporting success: ${JSON.stringify(missing)}`)@@ -270,10 +326,7 @@ test('[integration] a revoked HTTP actor cannot finish a stale invite or emit alet pending: Promise<Response> | undefinedtry {await revoker.query('BEGIN')- await revoker.query(- `UPDATE conversations SET members = members - $2::text WHERE id = $1`,- [convo, HTTP_A],- )+ await removeMemberWithClient(revoker, convo, HTTP_A)pending = fetch(`${httpBaseUrls[0]}/api/conversations/${convo}/members`, {method: 'POST',headers: { 'content-type': 'application/json', 'x-company-id': companyId },@@ -311,16 +364,13 @@ test('[integration] a revoked HTTP actor cannot finish a stale text message writlet pending: Promise<Response> | undefinedtry {await revoker.query('BEGIN')- await revoker.query(- `UPDATE conversations SET members = members - $2::text WHERE id = $1`,- [convo, HTTP_A],- )+ await removeMemberWithClient(revoker, convo, HTTP_A)pending = fetch(`${httpBaseUrls[0]}/api/conversations/${convo}/messages`, {method: 'POST',headers: { 'content-type': 'application/json', 'x-company-id': companyId },body: JSON.stringify({ body: 'must-not-land-after-kick' }),})- await waitForBlockedQuery('%SELECT kind FROM conversations%FOR UPDATE%')+ await waitForBlockedQuery('%SELECT c.kind FROM conversations c%FOR UPDATE OF c%')await revoker.query('COMMIT')committed = true} finally {@@ -388,10 +438,7 @@ test('[integration] a revoked HTTP email reply is rejected before the provider clet response: Response | undefinedtry {await revoker.query('BEGIN')- await revoker.query(- `UPDATE conversations SET members = members - $2::text WHERE id = $1`,- [convo, HTTP_A],- )+ await removeMemberWithClient(revoker, convo, HTTP_A)pending = fetch(`${httpBaseUrls[0]}/api/email/reply/${inboundId}`, {method: 'POST',headers: { 'content-type': 'application/json', 'x-company-id': companyId },@@ -464,8 +511,16 @@ test('[integration] HTTP group and direct creation reject targets moved while pa})assert.equal(directResponse.status, 404, await directResponse.text())const created = await pool.query(- `SELECT 1 FROM conversations- WHERE company_id = $1 AND (title = 'must-not-create-stale-group' OR members @> to_jsonb(ARRAY[$2::text]))`,+ `SELECT 1 FROM conversations c+ WHERE c.company_id = $1+ AND (+ c.title = 'must-not-create-stale-group'+ OR EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )+ )`,[companyA, directTarget],)assert.equal(created.rowCount, 0)@@ -483,10 +538,7 @@ test('[integration] a revoked CLI actor cannot finish a stale kick or emit a kiclet pending: ReturnType<typeof runCli> | undefinedtry {await revoker.query('BEGIN')- await revoker.query(- `UPDATE conversations SET members = members - $2::text WHERE id = $1`,- [convo, actor],- )+ await removeMemberWithClient(revoker, convo, actor)pending = runCli(['--as', actor, 'kick', convo, target])await waitForBlockedMembershipUpdate('members -')await revoker.query('COMMIT')@@ -517,6 +569,7 @@ test('[integration] an actor tenant move that wins the participant lock cancelslet pending: ReturnType<typeof runCli> | undefinedtry {await mover.query('BEGIN')+ await detachParticipantWithClient(mover, actor, companyA)await mover.query(`UPDATE participants SET company_id = $2 WHERE id = $1 AND company_id = $3`,[actor, companyB, companyA],@@ -534,7 +587,7 @@ test('[integration] an actor tenant move that wins the participant lock cancelsconst result = await pending!assert.equal(result.ok, false, result.text)- assert.deepEqual(await membersOf(convo), [actor])+ assert.deepEqual(await membersOf(convo), [])assert.equal((await noticesOf(convo)).length, 0)})@@ -643,10 +696,21 @@ test('[integration] a moved agent cannot read a stale old-tenant membership', asVALUES ($1,$2,$3,'text','old tenant secret',1,$4)`,[`m-${randomUUID()}`, convo, actor, companyA],)- await pool.query(- `UPDATE participants SET company_id = $2 WHERE id = $1 AND company_id = $3`,- [moved, companyB, companyA],- )+ const mover = await pool.connect()+ try {+ await mover.query('BEGIN')+ await detachParticipantWithClient(mover, moved, companyA)+ await mover.query(+ `UPDATE participants SET company_id = $2 WHERE id = $1 AND company_id = $3`,+ [moved, companyB, companyA],+ )+ await mover.query('COMMIT')+ } catch (error) {+ await mover.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ mover.release()+ }const inbox = await inprocClient.loadInbox(moved)assert.deepEqual(inbox, [])@@ -671,10 +735,7 @@ test('[integration] a kicked poll author is not woken with later room tally detaVALUES ($1,$2,$3,'poll',$4,1,$5::jsonb,$6)`,[messageId, convo, author, poll.question, JSON.stringify(poll), companyId],)- await pool.query(- `UPDATE conversations SET members = members - $2::text WHERE id = $1 AND company_id = $3`,- [convo, author, companyId],- )+ await removeMember(convo, author, companyId)const woke = await handlePollUpdated({type: 'poll.updated',@@ -713,10 +774,7 @@ test('[integration] WebSocket routing uses current room membership with one duraassert.deepEqual([...before].sort(), [HTTP_A, HTTP_B].sort())assert.ok(!before.has(outsider), 'same-tenant non-member received a private conversation frame')- await pool.query(- `UPDATE conversations SET members = members - $2::text WHERE id = $1`,- [convo, HTTP_A],- )+ await removeMember(convo, HTTP_A)const afterKick = await resolveWsEventRecipientUserIds({type: 'message.new', companyId, conversationId: convo, message: { id: ordinaryId },})diff --git a/server/src/__integration__/runtime-aux-authorization.test.ts b/server/src/__integration__/runtime-aux-authorization.test.tsindex bbfd6a9..f0a4310 100644--- a/server/src/__integration__/runtime-aux-authorization.test.ts+++ b/server/src/__integration__/runtime-aux-authorization.test.ts@@ -197,7 +197,7 @@ test('[integration] runtime notices: a queued kick wins before notice authorizat// Queue the real membership mutation first. It holds both participant rows// while waiting for our conversation lock.kickPromise = runCli(['--as', actor.agentId, 'kick', conversationId, target.agentId])- await waitForBlockedQuery('%UPDATE conversations c%SET members = members -%')+ await waitForBlockedQuery('%SELECT c.id%FROM conversations c%FOR UPDATE OF c%')// The notice request passes JWT validation, then blocks on the target's// participant row behind the already-queued kick transaction.diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.tsindex 06c3724..30a2726 100644--- a/server/src/__integration__/runtime-server.test.ts+++ b/server/src/__integration__/runtime-server.test.ts@@ -385,8 +385,10 @@ test('[integration] runtime: /context enforces tenant and conversation membershiconst otherTenant = await seedAgent()const crossTenantId = await seedContextConversation({companyId: otherTenant.companyId,- // Even a forged members array cannot override the JWT tenant boundary.- members: [agentId, otherTenant.agentId],+ // The composite membership FK now prevents forging agentId into this+ // tenant at fixture time; the runtime tenant boundary must still exclude+ // a valid foreign conversation id supplied by the caller.+ members: [otherTenant.agentId],authorId: otherTenant.agentId,body: 'cross-tenant-private',})@@ -535,11 +537,29 @@ test('[integration] runtime: a current token cannot use a stale member id to rea],)- const moved = await pool.query(- `UPDATE participants SET company_id = $1 WHERE id = $2 AND company_id = $3`,- [currentTenant.companyId, originalTenant.agentId, originalTenant.companyId],- )- assert.equal(moved.rowCount, 1)+ const mover = await pool.connect()+ try {+ await mover.query('BEGIN')+ await mover.query(+ `DELETE FROM conversation_members+ WHERE conversation_id = $1+ AND participant_id = $2+ AND company_id = $3`,+ [oldConversationId, originalTenant.agentId, originalTenant.companyId],+ )+ await mover.query(`SELECT refresh_conversation_members_projection($1)`, [oldConversationId])+ const moved = await mover.query(+ `UPDATE participants SET company_id = $1 WHERE id = $2 AND company_id = $3`,+ [currentTenant.companyId, originalTenant.agentId, originalTenant.companyId],+ )+ assert.equal(moved.rowCount, 1)+ await mover.query('COMMIT')+ } catch (error) {+ await mover.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ mover.release()+ }const currentToken = signAgentToken({agentId: originalTenant.agentId,companyId: currentTenant.companyId,@@ -605,8 +625,16 @@ test('[integration] runtime: a current token cannot use a stale member id to reapulled_by ->> 'agentId' = $2OR (kind = 'direct'- AND members @> to_jsonb(ARRAY[$2::text])- AND members @> to_jsonb(ARRAY[$3::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members first_member+ WHERE first_member.conversation_id = conversations.id+ AND first_member.participant_id = $2+ )+ AND EXISTS (+ SELECT 1 FROM conversation_members second_member+ WHERE second_member.conversation_id = conversations.id+ AND second_member.participant_id = $3+ )))`,[currentTenant.companyId, originalTenant.agentId, oldPeerId],diff --git a/server/src/__tests__/conversation-membership-source.test.ts b/server/src/__tests__/conversation-membership-source.test.tsnew file mode 100644index 0000000..5f94bee--- /dev/null+++ b/server/src/__tests__/conversation-membership-source.test.ts@@ -0,0 +1,41 @@+import assert from 'node:assert/strict'+import { readdir, readFile } from 'node:fs/promises'+import { dirname, extname, join, relative, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import { test } from 'node:test'++const serverSource = resolve(dirname(fileURLToPath(import.meta.url)), '..')++async function productionTypeScriptFiles(root: string): Promise<string[]> {+ const entries = await readdir(root, { withFileTypes: true })+ const files: string[] = []+ for (const entry of entries) {+ const path = join(root, entry.name)+ if (entry.isDirectory()) {+ if (entry.name === '__tests__' || entry.name === '__integration__' || entry.name === 'migrations') continue+ files.push(...await productionTypeScriptFiles(path))+ } else if (extname(entry.name) === '.ts') {+ files.push(path)+ }+ }+ return files+}++test('production authorization and routing never use the JSONB membership projection', async () => {+ const violations: string[] = []+ for (const path of await productionTypeScriptFiles(serverSource)) {+ // Migration 0001 is frozen historical SQL and deliberately retains its+ // old containment index and compatibility helpers.+ if (relative(serverSource, path) === 'db/migrate.ts') continue+ const source = await readFile(path, 'utf8')+ for (const pattern of [+ /members\s*@>/g,+ /jsonb_array_length\([^\n]*members/g,+ /jsonb_array_elements_text\([^\n]*members/g,+ /\.members\.includes\(/g,+ ]) {+ if (pattern.test(source)) violations.push(`${relative(serverSource, path)}: ${pattern.source}`)+ }+ }+ assert.deepEqual(violations, [])+})diff --git a/server/src/__tests__/schema-migrations.test.ts b/server/src/__tests__/schema-migrations.test.tsindex 1dc7ad0..ea4f1c2 100644--- a/server/src/__tests__/schema-migrations.test.ts+++ b/server/src/__tests__/schema-migrations.test.ts@@ -13,6 +13,7 @@ process.env.CUMORA_RUNTIME_CLIENT = 'http'process.env.OPENAI_API_KEY ??= 'test-key'const { computedBaselineMigrationChecksum } = await import('../db/migrate.js')+const { normalizedConversationMembersChecksum } = await import('../db/migrations/0002-normalized-conversation-members.js')const { verifySchemaCompatibility } = await import('../db/schema-version.js')type SchemaVersionQueryable = import('../db/schema-version.js').SchemaVersionQueryable@@ -22,6 +23,10 @@ test('the frozen baseline SQL matches its immutable manifest checksum', () => {assert.equal(computedBaselineMigrationChecksum(), SCHEMA_MIGRATIONS[0].checksum)})+test('the normalized membership migration matches its immutable manifest checksum', () => {+ assert.equal(normalizedConversationMembersChecksum(), SCHEMA_MIGRATIONS[1].checksum)+})+test('the migration owner accepts an exact prefix and reports its pending suffix', () => {const empty = validateMigrationHistory([], { allowPending: true })assert.equal(empty.currentVersion, 0)diff --git a/server/src/agents/agenda.ts b/server/src/agents/agenda.tsindex c608ab6..ec30202 100644--- a/server/src/agents/agenda.ts+++ b/server/src/agents/agenda.ts@@ -231,31 +231,25 @@ async function loadDueEvents(agentId: string, companyId: string, now: Date): Pro}/** Conversations the agent is a member of whose LATEST text message sits in the- * stall window [STALL_MIN_MS, STALL_MAX_MS] of silence. Cheap: members GIN +- * idx_messages_convo_created via a LATERAL "latest message" per conversation.- *- * enable_seqscan=off (session-level, NO transaction — a single autocommit SELECT- * only takes ACCESS SHARE, can't deadlock) forces the members GIN; the planner- * otherwise seq-scans all conversations (~2s). Same approach as loadInbox. On- * error the connection is destroyed so the GUC never leaks back into the pool. */+ * stall window [STALL_MIN_MS, STALL_MAX_MS] of silence. The participant-led+ * normalized membership index narrows the conversations first, then+ * idx_messages_convo_created serves the LATERAL latest-message lookup. */async function loadStalledConversations(agentId: string, companyId: string): Promise<StalledConvo[]> {- const client = await pool.connect()- let rows: Array<{+ const { rows } = await pool.query<{conversation_id: string; kind: string; title: string | nulllast_message_id: string; last_author_id: string; last_author_name: stringlast_author_is_self: boolean; last_body: string; minutes_silent: string; recent_tail: string | null- }>- try {- await client.query('SET enable_seqscan = off')- const res = await client.query<{- conversation_id: string; kind: string; title: string | null- last_message_id: string; last_author_id: string; last_author_name: string- last_author_is_self: boolean; last_body: string; minutes_silent: string; recent_tail: string | null- }>(- `WITH convos AS (+ }>(+ `WITH convos AS (SELECT c.id, c.kind, c.titleFROM conversations c- WHERE c.company_id = $2 AND c.members @> to_jsonb(ARRAY[$1::text])+ WHERE c.company_id = $2+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $1+ ))SELECT co.id AS conversation_id, co.kind, co.title,m.id AS last_message_id, m.author_id AS last_author_id,@@ -286,15 +280,8 @@ async function loadStalledConversations(agentId: string, companyId: string): ProAND m.created_at >= NOW() - ($4::double precision * INTERVAL '1 millisecond')ORDER BY m.created_at DESCLIMIT 10`,- [agentId, companyId, STALL_MIN_MS, STALL_MAX_MS],- )- await client.query('RESET enable_seqscan')- rows = res.rows- } catch (err) {- client.release(true) // destroy — never return a connection in unknown GUC state- throw err- }- client.release()+ [agentId, companyId, STALL_MIN_MS, STALL_MAX_MS],+ )return rows.map((r) => ({conversationId: r.conversation_id,kind: r.kind,diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.tsindex dc4af9a..e3a5fff 100644--- a/server/src/agents/cli.ts+++ b/server/src/agents/cli.ts@@ -122,20 +122,27 @@ async function withConversationActorLock<T>(args: {companyId: args.companyId,kind: args.kind,run: async (client) => {- const params: unknown[] = [args.conversationId, args.companyId, args.participantId]+ const params: unknown[] = [args.conversationId, args.companyId]let kindPredicate = ''if (args.conversationKind) {params.push(args.conversationKind)- kindPredicate = `AND kind = $4`+ kindPredicate = `AND c.kind = $3`}- const authorized = await client.query(- `SELECT id FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])+ const locked = await client.query(+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2${kindPredicate}FOR UPDATE`,params,)+ if (!locked.rowCount) return null+ const authorized = await client.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1+ AND company_id = $2+ AND participant_id = $3`,+ [args.conversationId, args.companyId, args.participantId],+ )if (!authorized.rowCount) return nullreturn args.run(client)},@@ -517,7 +524,11 @@ async function cmdWhoami(parsed: ParsedArgs): Promise<CliResult> {const { rows: convos } = await pool.query<{ id: string; title: string; kind: string }>(`SELECT id, title, kind FROM conversationsWHERE company_id = $2- AND members @> to_jsonb(ARRAY[$1::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = conversations.id+ AND member.participant_id = $1+ )AND EXISTS (SELECT 1 FROM participants requesterWHERE requester.id = $1@@ -597,7 +608,11 @@ async function cmdConversations(parsed: ParsedArgs, kindFilter?: 'group' | 'direAND requester.kind = 'agent'AND requester.departed_at IS NULLWHERE c.company_id = $2- AND c.members @> to_jsonb(ARRAY[$1::text]) ${kindWhere}+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $1+ ) ${kindWhere}ORDER BY c.updated_at DESC`,params,)@@ -625,8 +640,9 @@ async function cmdMembers(parsed: ParsedArgs): Promise<CliResult> {const id = parsed.positional[0]if (!id) return err('usage: members <conversation_id>')const { rows } = await pool.query<{ members: string[] }>(- `SELECT c.members+ `SELECT ARRAY_AGG(member.participant_id ORDER BY member.ordinal) AS membersFROM conversations c+ JOIN conversation_members member ON member.conversation_id = c.idJOIN participants requesterON requester.id = $2AND requester.company_id = c.company_id@@ -634,7 +650,12 @@ async function cmdMembers(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE c.id = $1AND c.company_id = $3- AND c.members @> to_jsonb(ARRAY[$2::text])`,+ AND EXISTS (+ SELECT 1 FROM conversation_members actor+ WHERE actor.conversation_id = c.id+ AND actor.participant_id = $2+ )+ GROUP BY c.id`,[id, me, companyId],)if (!rows[0]) return err(`unknown conversation: ${id}`)@@ -697,7 +718,11 @@ async function cmdMessages(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE c.id = $1AND c.company_id = $3- AND c.members @> to_jsonb(ARRAY[$2::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ ))SELECTm.id, m.author_id, m.kind, m.body, m.sequence, m.created_at, m.attachment, m.poll,@@ -800,7 +825,11 @@ async function cmdConvening(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE ci.conversation_id = $1AND c.company_id = $3- AND c.members @> to_jsonb(ARRAY[$2::text])`,+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )`,[id, me, companyId],)const c = rows[0]@@ -854,7 +883,11 @@ async function cmdSearch(parsed: ParsedArgs): Promise<CliResult> {AND requester.kind = 'agent'AND requester.departed_at IS NULLWHERE c.company_id = $2- AND c.members @> to_jsonb(ARRAY[$1::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $1+ )AND m.body ILIKE $3 ${whereExtra}ORDER BY m.created_at DESC LIMIT ${limitParam}`,params,@@ -1031,7 +1064,11 @@ async function loadInbox(agentId: string): Promise<InboxItem[]> {AND requesting_agent.kind = 'agent'AND requesting_agent.departed_at IS NULLLEFT JOIN participants p ON p.id = m.author_id AND p.company_id = c.company_id- WHERE (c.members @> to_jsonb(ARRAY[$1::text]) OR m.delivery_recipient_id = $1)+ WHERE (EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $1+ ) OR m.delivery_recipient_id = $1)AND (m.author_id <> $1 OR m.delivery_recipient_id = $1)AND m.created_at > COALESCE((SELECT last_read_at FROM conversation_reads@@ -1153,7 +1190,11 @@ async function cmdGlance(parsed: ParsedArgs): Promise<CliResult> {LEFT JOIN participants p ON p.id = m.author_id AND p.company_id = c.company_idWHERE m.conversation_id = $1AND c.company_id = $3- AND c.members @> to_jsonb(ARRAY[$2::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )ORDER BY m.created_at DESCLIMIT 12`,[convoId, me, companyId],@@ -1236,7 +1277,11 @@ async function cmdAck(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE c.id = $2AND ($3::text IS NULL OR c.company_id = $3)- AND c.members @> to_jsonb(ARRAY[$1::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $1+ )ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,[me, convoId, activeAgentCompanyId],)@@ -1287,13 +1332,20 @@ async function cmdMute(parsed: ParsedArgs): Promise<CliResult> {if (!conversationId) return err('usage: mute <conversation_id> [--for 30m|2h|1d|1w] [--until <iso>] OR mute list')let until: Date | nulltry { until = parseMuteUntil(parsed) } catch (error) { return err(error instanceof Error ? error.message : String(error)) }- const { rows } = await pool.query<{ kind: string; title: string; members: string[] }>(- `SELECT kind, title, members FROM conversations WHERE id = $1 AND company_id = $2`,- [conversationId, companyId],+ const { rows } = await pool.query<{ kind: string; title: string; actor_is_member: boolean }>(+ `SELECT c.kind, c.title,+ EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $3+ ) AS actor_is_member+ FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2`,+ [conversationId, companyId, me],)const conversation = rows[0]if (!conversation) return err(`conversation not found: ${conversationId}`)- if (!conversation.members.includes(me)) return err(`you are not a member of ${conversationId}`)+ if (!conversation.actor_is_member) return err(`you are not a member of ${conversationId}`)if (conversation.kind === 'direct') return err('direct conversations always deliver; mute a group instead')const muted = await withConversationActorLock({participantId: me,@@ -1548,10 +1600,16 @@ async function cmdLeave(parsed: ParsedArgs): Promise<CliResult> {if (!convoId) return err('usage: leave <conversation_id>')const { rows } = await pool.query<{- kind: string; title: string; members: string[]; company_id: string | null+ kind: string; title: string; company_id: string | null; actor_is_member: boolean}>(- `SELECT kind, title, members, company_id FROM conversations WHERE id = $1`,- [convoId],+ `SELECT c.kind, c.title, c.company_id,+ EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ ) AS actor_is_member+ FROM conversations c WHERE c.id = $1`,+ [convoId, me],)const c = rows[0]if (!c) return err(`unknown conversation ${convoId}`)@@ -1559,7 +1617,7 @@ async function cmdLeave(parsed: ParsedArgs): Promise<CliResult> {if (c.kind === 'direct') {return err('cannot leave a direct conversation — use `cumora ack` to mute it from your inbox instead')}- if (!c.members.includes(me)) return err(`${me} is not a member of ${convoId}`)+ if (!c.actor_is_member) return err(`${me} is not a member of ${convoId}`)// Bind authorization to the write itself. If another member revoked us// after the SELECT above, this must fail closed and must not emit a false@@ -1597,10 +1655,22 @@ async function cmdInvite(parsed: ParsedArgs): Promise<CliResult> {if (target === me) return err(`${me} is already the one inviting`)const { rows } = await pool.query<{- kind: string; title: string; members: string[]; company_id: string | null+ kind: string; title: string; company_id: string | null;+ actor_is_member: boolean; target_is_member: boolean}>(- `SELECT kind, title, members, company_id FROM conversations WHERE id = $1`,- [convoId],+ `SELECT c.kind, c.title, c.company_id,+ EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ ) AS actor_is_member,+ EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $3+ ) AS target_is_member+ FROM conversations c WHERE c.id = $1`,+ [convoId, me, target],)const c = rows[0]if (!c) return err(`unknown conversation ${convoId}`)@@ -1608,8 +1678,8 @@ async function cmdInvite(parsed: ParsedArgs): Promise<CliResult> {if (c.kind === 'direct') {return err('cannot invite into a direct conversation — use `cumora pull-group` to start a fresh thread')}- if (!c.members.includes(me)) return err(`${me} is not a member of ${convoId} — can't invite into a group you're not in`)- if (c.members.includes(target)) return ok(`${target} is already a member of ${convoId}`)+ if (!c.actor_is_member) return err(`${me} is not a member of ${convoId} — can't invite into a group you're not in`)+ if (c.target_is_member) return ok(`${target} is already a member of ${convoId}`)// Verify the invitee exists in this tenant.const tenant = c.company_id@@ -1652,25 +1722,39 @@ async function cmdKick(parsed: ParsedArgs): Promise<CliResult> {if (target === me) return err('use `cumora leave <convo_id>` to leave a group yourself')const { rows } = await pool.query<{- kind: string; title: string; members: string[]; company_id: string | null+ kind: string; title: string; company_id: string | null; member_count: number;+ actor_is_member: boolean; target_is_member: boolean}>(- `SELECT kind, title, members, company_id FROM conversations WHERE id = $1`,- [convoId],+ `SELECT c.kind, c.title, c.company_id,+ (SELECT COUNT(*)::int FROM conversation_members member+ WHERE member.conversation_id = c.id) AS member_count,+ EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ ) AS actor_is_member,+ EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $3+ ) AS target_is_member+ FROM conversations c WHERE c.id = $1`,+ [convoId, me, target],)const c = rows[0]if (!c) return err(`unknown conversation ${convoId}`)if (!c.company_id) return err(`conversation ${convoId} is not attached to a workspace`)if (c.kind === 'direct') return err('cannot kick from a direct conversation')- if (!c.members.includes(me)) return err(`${me} is not a member of ${convoId} — can't kick from a group you're not in`)- if (!c.members.includes(target)) return err(`${target} is not a member of ${convoId}`)+ if (!c.actor_is_member) return err(`${me} is not a member of ${convoId} — can't kick from a group you're not in`)+ if (!c.target_is_member) return err(`${target} is not a member of ${convoId}`)- const next = c.members.filter((m) => m !== target)+ const nextCount = c.member_count - 1// Refuse to leave a group with just one member as a side-effect of kick —// if there'd only be the actor left, that's "everyone else gone", which// is fine, but require explicit confirmation via --confirm-empty for the// case where the kick removes the LAST other member. Cheap guard against// accidental group-clearing.- if (next.length === 1 && !parsed.flags['confirm-empty']) {+ if (nextCount === 1 && !parsed.flags['confirm-empty']) {return err(`kicking ${target} would leave only ${me} in this group; pass --confirm-empty if that's intended`)}@@ -1740,9 +1824,11 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {// conversation row, so a concurrent kick, offboarding, or tenant move// cannot leave this snapshot authorized at the write boundary.const { rows: cv } = await pool.query<{- members: string[]; company_id: string; kind: string; actor_is_agent: boolean+ member_count: number; company_id: string; kind: string; actor_is_agent: boolean}>(- `SELECT c.members, c.company_id, c.kind,+ `SELECT (SELECT COUNT(*)::int FROM conversation_members member+ WHERE member.conversation_id = c.id) AS member_count,+ c.company_id, c.kind,(requester.kind = 'agent') AS actor_is_agentFROM conversations cJOIN participants requester@@ -1752,7 +1838,11 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE c.id = $1AND ($3::text IS NULL OR c.company_id = $3)- AND c.members @> to_jsonb(ARRAY[$2::text])`,+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )`,[convoId, me, activeAgentCompanyId],)if (!cv[0]) return err(`conversation ${convoId} not found or no longer authorized`)@@ -1781,7 +1871,7 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {// forces the agent to commit deliberately rather than absent-// mindedly continuing to monologue.const monologueBypass = Boolean(parsed.flags.continue || parsed.flags.also)- if (!monologueBypass && cv[0].actor_is_agent && cv[0].members.length > 2) {+ if (!monologueBypass && cv[0].actor_is_agent && cv[0].member_count > 2) {const { rows: lastMsg } = await pool.query<{ author_id: string; created_at: string }>(`SELECT author_id, created_at FROM messagesWHERE conversation_id = $1@@ -1885,7 +1975,7 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {// the agent a HELD envelope for this conversation.const sendAnywayFlag = Boolean(parsed.flags['send-anyway'])const replyHoldScope = `reply:${convoId}`- const preflightApplies = !monologueBypass && cv[0].members.length > 2+ const preflightApplies = !monologueBypass && cv[0].member_count > 2const heldAck = sendAnywayFlag? await consumeHold(me, replyHoldScope): { armed: false, heldUpToSeq: null }@@ -2167,20 +2257,30 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {const txClient = await pool.connect()try {await txClient.query('BEGIN')- const { rows: authorizedRows } = await txClient.query<{ member_count: number }>(- `SELECT jsonb_array_length(c.members)::int AS member_count- FROM participants requester- JOIN conversations c- ON c.company_id = requester.company_id- AND c.id = $2- AND c.members @> to_jsonb(ARRAY[$1::text])- WHERE requester.id = $1- AND requester.company_id = $3- AND requester.kind IN ('agent', 'human')- AND requester.departed_at IS NULL- FOR SHARE OF requester, c`,- [me, convoId, companyId],+ const activeActor = await txClient.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ FOR SHARE`,+ [me, companyId],)+ const lockedConversation = activeActor.rowCount+ ? await txClient.query(+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ FOR SHARE OF c`,+ [convoId, companyId],+ )+ : null+ const { rows: authorizedRows } = lockedConversation?.rowCount+ ? await txClient.query<{ member_count: number }>(+ `SELECT COUNT(*)::int AS member_count+ FROM conversation_members+ WHERE conversation_id = $1 AND company_id = $2+ HAVING BOOL_OR(participant_id = $3)`,+ [convoId, companyId, me],+ )+ : { rows: [] as Array<{ member_count: number }> }if (!authorizedRows[0]) {await txClient.query('ROLLBACK')return err(`conversation ${convoId} no longer authorized; reply cancelled`)@@ -2877,7 +2977,11 @@ async function listAgentEmailThreads(args: {FROM conversations cWHERE c.kind = 'email'AND c.company_id = $1- AND c.members @> to_jsonb(ARRAY[$2::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )),last_msg AS (SELECT DISTINCT ON (em.conversation_id)@@ -3042,7 +3146,11 @@ async function cmdPollShow(parsed: ParsedArgs, me: string, companyId: string): PFROM participants requesterJOIN conversations cON c.company_id = requester.company_id- AND c.members @> to_jsonb(ARRAY[$3::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $3+ )JOIN messages m ON m.conversation_id = c.id AND m.company_id = c.company_idWHERE m.id = $1 AND m.company_id = $2 AND m.kind = 'poll'AND requester.id = $3@@ -3733,7 +3841,11 @@ async function cmdTopicRead(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE c.id = $1AND ($3::text IS NULL OR c.company_id = $3)- AND c.members @> to_jsonb(ARRAY[$2::text])`,+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )`,[convoId, me, activeAgentCompanyId],)if (!rows[0]) return err(`conversation ${convoId} not found or no longer authorized`)@@ -3760,7 +3872,11 @@ async function cmdTopicSet(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE c.id = $1AND ($3::text IS NULL OR c.company_id = $3)- AND c.members @> to_jsonb(ARRAY[$2::text])`,+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )`,[convoId, me, activeAgentCompanyId],)if (!preflight[0]) return err(`conversation ${convoId} not found or no longer authorized`)@@ -3819,7 +3935,11 @@ async function cmdRename(parsed: ParsedArgs): Promise<CliResult> {AND requester.departed_at IS NULLWHERE c.id = $1AND ($3::text IS NULL OR c.company_id = $3)- AND c.members @> to_jsonb(ARRAY[$2::text])`,+ AND EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.participant_id = $2+ )`,[convoId, me, activeAgentCompanyId],)if (!rows[0]) return err(`conversation ${convoId} not found or no longer authorized`)diff --git a/server/src/agents/convene.ts b/server/src/agents/convene.tsindex 300b895..2b089b9 100644--- a/server/src/agents/convene.ts+++ b/server/src/agents/convene.ts@@ -52,10 +52,14 @@ async function appendTranscript(args: {}}const conversation = await client.query(- `SELECT id FROM conversations- WHERE id = $1 AND company_id = $2- AND ($3::text = 'system' OR members @> to_jsonb(ARRAY[$3::text]))- FOR SHARE`,+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ AND ($3::text = 'system' OR EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ ))+ FOR SHARE OF c`,[initial.conversation_id, initial.company_id, args.authorId],)if (!conversation.rowCount) {@@ -137,10 +141,14 @@ export async function startConvene(args: {)if (!actor.rowCount) throw new Error('convene starter is no longer an active tenant participant')const { rows } = await client.query<{ title: string }>(- `SELECT title FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])- FOR UPDATE`,+ `SELECT c.title FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )+ FOR UPDATE OF c`,[args.conversationId, args.companyId, args.startedBy],)if (!rows[0]) throw new Error(`conversation ${args.conversationId} not found or not authorized`)@@ -210,9 +218,10 @@ async function orchestrate(args: {const { rows: agentMembers } = await pool.query<{ id: string }>(`SELECT p.idFROM conversations c- CROSS JOIN LATERAL jsonb_array_elements_text(c.members) member(id)+ JOIN conversation_members cm+ ON cm.conversation_id = c.id AND cm.company_id = c.company_idJOIN participants p- ON p.id = member.id AND p.company_id = c.company_id+ ON p.id = cm.participant_id AND p.company_id = cm.company_idAND p.kind = 'agent' AND p.departed_at IS NULLWHERE c.id = $1 AND c.company_id = $2ORDER BY p.id`,@@ -319,10 +328,14 @@ async function loadAuthorizedTurnSnapshot(args: {return null}const conversation = await client.query(- `SELECT id FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])- FOR SHARE`,+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )+ FOR SHARE OF c`,[args.session.conversation_id, args.companyId, args.agentId],)if (!conversation.rowCount) {diff --git a/server/src/agents/membership.ts b/server/src/agents/membership.tsindex 7d8c418..5535f07 100644--- a/server/src/agents/membership.ts+++ b/server/src/agents/membership.ts@@ -9,9 +9,7 @@* 1. Post a `kind='system'` message into the conversation describing* what happened (joined / left / kicked), so the audit trail is* visible to remaining members.- * 2. Publish CH_MESSAGE_NEW after a real membership change. The database- * mutation must happen first: otherwise a concurrently revoked actor can- * emit a false audit row and then fail the protected write. Departure+ * 2. Enqueue CH_MESSAGE_NEW in the same PostgreSQL transaction. Departure* notices carry a durable delivery recipient so the removed agent still* sees the one row that explains why the conversation disappeared.*@@ -20,7 +18,8 @@import { randomUUID } from 'node:crypto'import type { PoolClient } from 'pg'import { pool } from '../db/pool.js'-import { CH_MESSAGE_NEW, publish, type MessageNewEvent } from '../redis.js'+import { CH_MESSAGE_NEW, type MessageNewEvent } from '../redis.js'+import { enqueueBroadcast, nudgeRealtimeOutbox } from '../realtime-outbox.js'export type MembershipKind = 'joined' | 'left' | 'kicked'@@ -31,17 +30,10 @@ export interface MembershipMutationResult {systemMessageId: string}-interface CommittedMembershipChange {- result: MembershipMutationResult- event: MessageNewEvent-}-/** Serialize membership authorization against offboarding / tenant moves.- * The UPDATE below still repeats every predicate; these row locks close the- * narrower race where a participant row changes after a statement snapshot is- * taken while the conversation UPDATE is waiting on another writer. IDs are- * sorted so cross-kicks cannot deadlock by locking actor/target in opposite- * orders. */+ * Normalized membership writes then lock the conversation row, giving every+ * invite/leave/kick one participant -> conversation lock order. IDs are sorted+ * so cross-kicks cannot deadlock by locking actor/target in opposite orders. */async function withActiveParticipantLocks<T>(args: {participantIds: string[]companyId: string@@ -67,6 +59,7 @@ async function withActiveParticipantLocks<T>(args: {}const result = await args.run(client)await client.query('COMMIT')+ if (result !== null) nudgeRealtimeOutbox()return result} catch (err) {await client.query('ROLLBACK').catch(() => { /* preserve original error */ })@@ -84,7 +77,7 @@ async function insertMembershipSystemMessage(args: {kind: MembershipKindparticipantId: stringmembers: string[]-}): Promise<CommittedMembershipChange> {+}): Promise<MembershipMutationResult> {const messageId = `m-${randomUUID()}`const sequence = await nextConversationSequenceWithClient(args.client, args.conversationId)const body = JSON.stringify({@@ -103,64 +96,69 @@ async function insertMembershipSystemMessage(args: {args.companyId, deliveryRecipientId,],)- return {- result: { members: args.members, systemMessageId: messageId },- event: {- type: 'message.new',+ const event: MessageNewEvent = {+ type: 'message.new',+ conversationId: args.conversationId,+ companyId: args.companyId,+ message: {+ id: messageId,conversationId: args.conversationId,- companyId: args.companyId,- message: {- id: messageId,- conversationId: args.conversationId,- authorId: args.actorId,- kind: 'system',- body,- sequence,- at: new Date().toISOString(),- ...(deliveryRecipientId ? { deliveryRecipientId } : {}),- },+ authorId: args.actorId,+ kind: 'system',+ body,+ sequence,+ at: new Date().toISOString(),+ ...(deliveryRecipientId ? { deliveryRecipientId } : {}),},}+ await enqueueBroadcast(args.client, CH_MESSAGE_NEW, event)+ return { members: args.members, systemMessageId: messageId }}-/** Redis is the wake accelerator; the committed message is the source of- * truth. Do not turn a transient publish failure into an apparent mutation- * failure that callers retry after the database already changed. */-async function publishCommittedMembershipChange(- committed: CommittedMembershipChange | null,-): Promise<MembershipMutationResult | null> {- if (!committed) return null- await publish(CH_MESSAGE_NEW, committed.event).catch((err) => {- console.warn(- `[membership] publish ${committed.result.systemMessageId} failed; row remains durable`,- err instanceof Error ? err.message : err,- )- })- return committed.result+async function lockConversationForMembership(args: {+ client: PoolClient+ conversationId: string+ companyId: string+ actorId: string+}): Promise<boolean> {+ const locked = await args.client.query(+ `SELECT c.id+ FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ FOR UPDATE OF c`,+ [args.conversationId, args.companyId],+ )+ if (locked.rowCount !== 1) return false++ // This must be a separate statement after the row lock is acquired. If the+ // membership predicate is part of the blocking SELECT, its statement+ // snapshot can still see a membership deleted by the transaction we waited+ // behind even though EvalPlanQual refreshed the conversation tuple.+ const authorized = await args.client.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1+ AND company_id = $2+ AND participant_id = $3`,+ [args.conversationId, args.companyId, args.actorId],+ )+ return authorized.rowCount === 1+}++async function refreshMembersProjection(+ client: PoolClient,+ conversationId: string,+): Promise<string[]> {+ const { rows } = await client.query<{ members: string[] }>(+ `SELECT refresh_conversation_members_projection($1) AS members`,+ [conversationId],+ )+ return rows[0]?.members ?? []}/**- * Add `memberId` to a conversation's member list and return the list as it- * stands AFTER the write.- *- * The array is edited by Postgres, not by us. Every caller used to SELECT- * `members`, splice it in JavaScript and write the whole array back, which- * makes two overlapping membership changes a last-write-wins race: the second- * write is computed from a snapshot taken before the first, so the first one- * is erased with no error anywhere.- *- * That is not a rare interleaving here. The scheduler wakes several agents for- * the same message, and `invite` / `leave` / `kick` are what those agents do- * next. And the damage is silent in the worst way: the `joined` system row is- * posted regardless, so the transcript records a join that did not happen,- * while the agent's mailbox query (`members @> [agentId]`) never matches, so- * they are simply never woken for that conversation again.- *- * Authorization is deliberately repeated in this single UPDATE. Route-level- * SELECTs are only for friendly error messages; they are stale the moment a- * concurrent kick, offboarding, or tenant move commits. Both the actor and the- * target therefore have to be active participants in the conversation's- * current tenant at the exact write boundary.+ * Add one normalized membership row and return the derived JSON projection as+ * it stands after the write. Route-level SELECTs remain friendly preflights;+ * actor authorization is repeated while the conversation row is locked.** Returns null when the write was not authorized or no longer necessary. The* helper intentionally performs no fallback SELECT: a second statement would@@ -179,27 +177,31 @@ export async function addConversationMember(args: {participantIds: [args.actorId, args.memberId],companyId: args.companyId,run: async (client) => {- const { rows } = await client.query<{ members: string[] }>(- `UPDATE conversations c- SET members = members || to_jsonb(ARRAY[$2::text]), updated_at = NOW()- WHERE c.id = $1- AND c.company_id = $4- AND c.members @> to_jsonb(ARRAY[$3::text])- AND NOT (c.members @> to_jsonb(ARRAY[$2::text]))- AND EXISTS (- SELECT 1 FROM participants actor- WHERE actor.id = $3 AND actor.company_id = c.company_id- AND actor.departed_at IS NULL- )- AND EXISTS (- SELECT 1 FROM participants target- WHERE target.id = $2 AND target.company_id = c.company_id- AND target.departed_at IS NULL- )- RETURNING members`,- [args.conversationId, args.memberId, args.actorId, args.companyId],+ if (!(await lockConversationForMembership({+ client,+ conversationId: args.conversationId,+ companyId: args.companyId,+ actorId: args.actorId,+ }))) return null++ const inserted = await client.query(+ `INSERT INTO conversation_members (+ conversation_id, company_id, participant_id, ordinal+ )+ SELECT c.id, c.company_id, $2,+ COALESCE(MAX(existing.ordinal) + 1, 0)::integer+ FROM conversations c+ LEFT JOIN conversation_members existing+ ON existing.conversation_id = c.id+ AND existing.company_id = c.company_id+ WHERE c.id = $1 AND c.company_id = $3+ GROUP BY c.id, c.company_id+ ON CONFLICT (conversation_id, participant_id) DO NOTHING+ RETURNING participant_id`,+ [args.conversationId, args.memberId, args.companyId],)- if (!rows[0]) return null+ if (!inserted.rowCount) return null+ const members = await refreshMembersProjection(client, args.conversationId)return insertMembershipSystemMessage({client,conversationId: args.conversationId,@@ -207,19 +209,15 @@ export async function addConversationMember(args: {actorId: args.actorId,kind: 'joined',participantId: args.memberId,- members: rows[0].members,+ members,})},})- return publishCommittedMembershipChange(committed)+ return committed}/**- * Remove `memberId` from a conversation's member list, returning the list as- * it stands after the write. Same reasoning as addConversationMember.- *- * `jsonb - text` deletes every matching element, so this is idempotent and- * also cleans up a duplicate left behind by the old racy path.+ * Delete one normalized membership row and return the rebuilt projection.*/export async function removeConversationMember(args: {conversationId: string@@ -239,28 +237,33 @@ export async function removeConversationMember(args: {participantIds: [args.actorId, args.memberId],companyId: args.companyId,run: async (client) => {- const { rows } = await client.query<{ members: string[] }>(- `UPDATE conversations c- SET members = members - $2::text, updated_at = NOW()- WHERE c.id = $1- AND c.company_id = $4- AND c.members @> to_jsonb(ARRAY[$2::text])- AND c.members @> to_jsonb(ARRAY[$3::text])- AND ($5::boolean OR jsonb_array_length(c.members - $2::text) <> 1)- AND EXISTS (- SELECT 1 FROM participants actor- WHERE actor.id = $3 AND actor.company_id = c.company_id- AND actor.departed_at IS NULL- )- AND EXISTS (- SELECT 1 FROM participants target- WHERE target.id = $2 AND target.company_id = c.company_id- AND target.departed_at IS NULL- )- RETURNING members`,- [args.conversationId, args.memberId, args.actorId, args.companyId, Boolean(args.allowSoleMember)],+ if (!(await lockConversationForMembership({+ client,+ conversationId: args.conversationId,+ companyId: args.companyId,+ actorId: args.actorId,+ }))) return null++ const removed = await client.query(+ `DELETE FROM conversation_members target+ WHERE target.conversation_id = $1+ AND target.company_id = $3+ AND target.participant_id = $2+ AND (+ $4::boolean+ OR (+ SELECT COUNT(*)::integer+ FROM conversation_members remaining+ WHERE remaining.conversation_id = target.conversation_id+ AND remaining.company_id = target.company_id+ AND remaining.participant_id <> target.participant_id+ ) <> 1+ )+ RETURNING participant_id`,+ [args.conversationId, args.memberId, args.companyId, Boolean(args.allowSoleMember)],)- if (!rows[0]) return null+ if (!removed.rowCount) return null+ const members = await refreshMembersProjection(client, args.conversationId)return insertMembershipSystemMessage({client,conversationId: args.conversationId,@@ -268,11 +271,11 @@ export async function removeConversationMember(args: {actorId: args.actorId,kind: args.kind,participantId: args.memberId,- members: rows[0].members,+ members,})},})- return publishCommittedMembershipChange(committed)+ return committed}/** Atomically claim the next sequence number for a conversation.diff --git a/server/src/agents/observability.ts b/server/src/agents/observability.tsindex f494ea0..089dd24 100644--- a/server/src/agents/observability.ts+++ b/server/src/agents/observability.ts@@ -877,9 +877,13 @@ export async function getTurnsPerMessage(args: {AND a.departed_at IS NULLAND EXISTS (SELECT 1- FROM jsonb_array_elements_text(c.members) AS j(mid)- JOIN participants ap ON ap.id = j.mid AND ap.company_id = c.company_id- WHERE ap.kind = 'agent' AND ap.departed_at IS NULL+ FROM conversation_members cm+ JOIN participants ap+ ON ap.id = cm.participant_id+ AND ap.company_id = cm.company_id+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND ap.kind = 'agent' AND ap.departed_at IS NULL)),turns AS (diff --git a/server/src/agents/private_chat.ts b/server/src/agents/private_chat.tsindex fc39934..575475f 100644--- a/server/src/agents/private_chat.ts+++ b/server/src/agents/private_chat.ts@@ -27,15 +27,24 @@ async function findOrCreateDirect(bName: string,): Promise<string> {const { rows } = await client.query<{ id: string }>(- `SELECT id FROM conversations- WHERE kind = 'direct'- AND members @> $1::jsonb- AND members @> $2::jsonb- AND jsonb_array_length(members) = 2- AND company_id = $3- ORDER BY created_at DESC LIMIT 1- FOR UPDATE`,- [JSON.stringify([aId]), JSON.stringify([bId]), companyId],+ `SELECT c.id FROM conversations c+ WHERE c.kind = 'direct'+ AND c.company_id = $3+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $1+ )+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )+ AND (SELECT COUNT(*) FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id) = 2+ ORDER BY c.created_at DESC LIMIT 1+ FOR UPDATE OF c`,+ [aId, bId, companyId],)if (rows[0]) {if (topic) {diff --git a/server/src/agents/runtime/authorization.ts b/server/src/agents/runtime/authorization.tsindex c4be592..bb9f9cc 100644--- a/server/src/agents/runtime/authorization.ts+++ b/server/src/agents/runtime/authorization.ts@@ -97,10 +97,15 @@ export async function withRuntimeConversationAuthorization<T>(args: {}if (conversationIds.length > 0) {const conversations = await client.query<{ id: string }>(- `SELECT id FROM conversations- WHERE company_id = $1 AND id = ANY($2::text[])- AND members @> to_jsonb(ARRAY[$3::text])- ORDER BY id FOR SHARE`,+ `SELECT c.id FROM conversations c+ WHERE c.company_id = $1 AND c.id = ANY($2::text[])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )+ ORDER BY c.id FOR SHARE OF c`,[args.companyId, conversationIds, args.agentId],)if (conversations.rows.length !== conversationIds.length) {@@ -150,7 +155,12 @@ export async function withRuntimeMessageReadAuthorization<T>(args: {ON m.id = $4 AND m.conversation_id = c.id AND m.company_id = c.company_idWHERE c.id = $1 AND c.company_id = $2AND (- c.members @> to_jsonb(ARRAY[$3::text])+ EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )OR (m.kind = 'system' AND m.delivery_recipient_id = $3))FOR SHARE OF c, m`,diff --git a/server/src/agents/runtime/inproc-client.ts b/server/src/agents/runtime/inproc-client.tsindex f2b3d4a..b53cfe7 100644--- a/server/src/agents/runtime/inproc-client.ts+++ b/server/src/agents/runtime/inproc-client.ts@@ -136,24 +136,10 @@ export class InProcRuntimeClient implements AgentRuntimeClient {}async loadInbox(agentId: string): Promise<InboxRow[]> {- // Resolve the agent's conversations via the members GIN, then pull each one's- // unread tail with a LATERAL over idx_messages_convo_created — instead of the- // old form that joined ALL messages of every member conversation with a PER-ROW- // cursor subquery (an 8s query that, with loadContext, starved the pool).- //- // Force the members GIN: the planner mis-costs `members @>` and SEQ-SCANS all- // conversations (~2s), which starves the pool under load. enable_seqscan=off- // makes it use the GIN (~100ms). It is set at SESSION level on a dedicated- // client with NO transaction — a single autocommit SELECT only takes ACCESS- // SHARE, so (unlike the earlier BEGIN…COMMIT version) it can't deadlock with- // DML or a rolling-deploy ALTER TABLE. RESET on the success path; on any error- // the connection is DESTROYED (release(true)) so a stray GUC never leaks back- // into the pool. Every access in the query is index-backed.- const client = await pool.connect()- let rows: InboxRow[] = []- try {- await client.query('SET enable_seqscan = off')- const res = await client.query<InboxRow>(+ // Resolve membership through the normalized participant-led index, then+ // pull each conversation's unread tail with the message index. This avoids+ // both the old JSONB seq-scan and its dedicated enable_seqscan=off session.+ const { rows } = await pool.query<InboxRow>(`WITH requesting_agent AS MATERIALIZED (SELECT company_idFROM participants@@ -165,7 +151,7 @@ export class InProcRuntimeClient implements AgentRuntimeClient {c.project_id, pr.name AS project_name,COALESCE(cr.last_read_at, '1970-01-01T00:00:00Z'::timestamptz) AS lr_at,COALESCE(cr.last_read_message_id, '') AS lr_id,- c.members @> to_jsonb(ARRAY[$1::text]) AS current_member,+ (current_membership.participant_id IS NOT NULL) AS current_member,EXISTS (SELECT 1 FROM conversation_mutes muWHERE mu.user_id = $1 AND mu.conversation_id = c.id@@ -173,9 +159,13 @@ export class InProcRuntimeClient implements AgentRuntimeClient {) AS mutedFROM requesting_agent raJOIN conversations c ON c.company_id = ra.company_id+ LEFT JOIN conversation_members current_membership+ ON current_membership.conversation_id = c.id+ AND current_membership.company_id = c.company_id+ AND current_membership.participant_id = $1LEFT JOIN conversation_reads cr ON cr.user_id = $1 AND cr.conversation_id = c.idLEFT JOIN projects pr ON pr.id = c.project_id- WHERE c.members @> to_jsonb(ARRAY[$1::text])+ WHERE current_membership.participant_id IS NOT NULLOR EXISTS (SELECT 1FROM messages delivered@@ -233,15 +223,8 @@ export class InProcRuntimeClient implements AgentRuntimeClient {LEFT JOIN participants p ON p.id = m.author_id AND p.company_id = co.company_idORDER BY m.created_at ASC, m.id ASCLIMIT 200`,- [agentId],- )- await client.query('RESET enable_seqscan')- rows = res.rows- } catch (err) {- client.release(true) // destroy — never return a connection in unknown GUC state- throw err- }- client.release()+ [agentId],+ )await refreshAttachmentUrls(rows)// NOTE: This used to call recordSeen() here to advance the freshness-// preflight boundary, but that fired for EVERY caller of loadInbox —@@ -429,7 +412,12 @@ export class InProcRuntimeClient implements AgentRuntimeClient {LEFT JOIN participants p ON p.id = m.author_id AND p.company_id = c.company_idWHERE c.id = ANY($3::text[])AND c.company_id = $2- AND c.members @> to_jsonb(ARRAY[$1::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $1+ ))SELECT id, conversation_id, company_id, conversation_title, conversation_kind, conversation_topic,project_name,@@ -668,10 +656,15 @@ export class InProcRuntimeClient implements AgentRuntimeClient {return { posted: false, authorized: false }}const conversation = await client.query(- `SELECT id FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])- FOR UPDATE`,+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )+ FOR UPDATE OF c`,[args.conversationId, companyId, args.agentId],)if (!conversation.rowCount) {@@ -1076,7 +1069,12 @@ export class InProcRuntimeClient implements AgentRuntimeClient {WHERE m.id = $1 AND m.conversation_id = $3AND ($4::text IS NULL OR c.company_id = $4)AND (- c.members @> to_jsonb(ARRAY[$2::text])+ EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )OR (m.kind = 'system' AND m.delivery_recipient_id = $2)))diff --git a/server/src/agents/scanner.ts b/server/src/agents/scanner.tsindex 6fdcb91..bab490c 100644--- a/server/src/agents/scanner.ts+++ b/server/src/agents/scanner.ts@@ -58,7 +58,12 @@ async function agentHasUnreadInbox(agentId: string): Promise<boolean> {SELECT 1FROM messages mJOIN conversations c ON c.id = m.conversation_id- WHERE c.members @> to_jsonb(ARRAY[$1::text])+ WHERE EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $1+ )AND m.author_id <> $1AND ROW(m.created_at, m.id) > (SELECTdiff --git a/server/src/agents/scanner_helper.ts b/server/src/agents/scanner_helper.tsindex 9d72e0f..3f656bf 100644--- a/server/src/agents/scanner_helper.ts+++ b/server/src/agents/scanner_helper.ts@@ -56,9 +56,13 @@ export async function startPulledGroup(args: {AND c.pulled_by ->> 'agentId' = $1AND c.created_at > NOW() - ($2 || ' hours')::intervalAND EXISTS (- SELECT 1 FROM jsonb_array_elements_text(c.members) m- LEFT JOIN participants p ON p.id = m AND p.company_id = c.company_id- WHERE p.kind <> 'agent'+ SELECT 1 FROM conversation_members cm+ JOIN participants p+ ON p.id = cm.participant_id+ AND p.company_id = cm.company_id+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND p.kind <> 'agent')ORDER BY c.created_at DESCLIMIT 1`,diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.tsindex 2e3be57..f179700 100644--- a/server/src/agents/scheduler.ts+++ b/server/src/agents/scheduler.ts@@ -676,13 +676,20 @@ async function wake(payload: MessageNewEvent): Promise<void> {company_id: stringmuted_agent_ids: string[]}>(- `SELECT c.members, c.kind, c.company_id,- COALESCE(array_agg(mu.user_id) FILTER (WHERE mu.user_id IS NOT NULL), ARRAY[]::text[]) AS muted_agent_ids+ `SELECT COALESCE((+ SELECT array_agg(cm.participant_id ORDER BY cm.ordinal, cm.participant_id)+ FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ ), ARRAY[]::text[]) AS members,+ c.kind, c.company_id,+ COALESCE((+ SELECT array_agg(mu.user_id)+ FROM conversation_mutes mu+ WHERE mu.conversation_id = c.id+ AND (mu.muted_until IS NULL OR mu.muted_until > NOW())+ ), ARRAY[]::text[]) AS muted_agent_idsFROM conversations c- LEFT JOIN conversation_mutes mu ON mu.conversation_id = c.id- AND (mu.muted_until IS NULL OR mu.muted_until > NOW())- WHERE c.id = $1- GROUP BY c.id`,+ WHERE c.id = $1`,[conversationId],)const conversation = convoRows[0]@@ -708,8 +715,8 @@ async function wake(payload: MessageNewEvent): Promise<void> {const agentRecipients: string[] = []for (const m of members) {if (m === authorId) continue- // Treat conversations.members as untrusted denormalized data. A malformed- // cross-tenant id must never become a wake/steer recipient for this tenant.+ // The normalized membership FK is tenant-constrained; the active+ // participant filter additionally excludes offboarded agents.if (!currentAgents.has(m)) continueif (mutedAgentIds.has(m) && !shouldDeliverToMutedAgent({agentId: m,@@ -1030,7 +1037,12 @@ const POLL_CLOSE_WAKE_CLAIM_SECONDS = 600export async function handlePollUpdated(event: PollUpdatedEvent): Promise<boolean> {if (!event.companyId) return falseconst { rows } = await pool.query<{ author_id: string; members: string[] }>(- `SELECT m.author_id, c.members+ `SELECT m.author_id,+ COALESCE((+ SELECT array_agg(cm.participant_id ORDER BY cm.ordinal, cm.participant_id)+ FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ ), ARRAY[]::text[]) AS membersFROM messages mJOIN conversations c ON c.id = m.conversation_idJOIN participants author@@ -1041,7 +1053,12 @@ export async function handlePollUpdated(event: PollUpdatedEvent): Promise<booleaWHERE m.id = $1 AND m.company_id = $2AND m.conversation_id = $3AND c.company_id = $2- AND c.members @> to_jsonb(ARRAY[m.author_id])`,+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = m.author_id+ )`,[event.messageId, event.companyId, event.conversationId],)const row = rows[0]diff --git a/server/src/agents/tools.ts b/server/src/agents/tools.tsindex 273a9b6..9b23f0f 100644--- a/server/src/agents/tools.ts+++ b/server/src/agents/tools.ts@@ -204,7 +204,12 @@ async function tReact(args: Record<string, unknown>, agentId: string): Promise<TFROM participants requesterJOIN conversations cON c.company_id = requester.company_id- AND c.members @> to_jsonb(ARRAY[$2::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )JOIN messages mON m.conversation_id = c.idAND m.company_id = c.company_iddiff --git a/server/src/api/router.ts b/server/src/api/router.tsindex c38b834..72de8c9 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -368,8 +368,8 @@ async function requireCompanyRole(* Tenant + conversation membership gate in one round-trip.** Verifies (a) the caller belongs to the active tenant and (b) the- * conversation lives in that tenant AND (c) the caller is in the- * conversation's `members` array. This is the missing check that used to+ * conversation lives in that tenant AND (c) the caller has a normalized+ * conversation-membership row. This is the missing check that used to* allow any tenant member to read or react in conversations they weren't* part of (private DMs etc.).*@@ -386,15 +386,19 @@ async function requireConversationMember(): Promise<{ userId: string; companyId: string; members: string[]; kind: string }> {const { userId, companyId } = await requireCompany(req)const { rows } = await pool.query<{ members: string[]; kind: string }>(- `SELECT members, kind FROM conversations WHERE id = $1 AND company_id = $2 LIMIT 1`,- [conversationId, companyId],+ `SELECT c.members, c.kind+ FROM conversations c+ JOIN conversation_members cm+ ON cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ WHERE c.id = $1 AND c.company_id = $2+ LIMIT 1`,+ [conversationId, companyId, userId],)+ // Stay opaque: same 404 a non-existent / cross-tenant convo returns,+ // so a probing client can't tell "doesn't exist" from "I'm not in it".if (!rows[0]) throw new HttpError(404, 'not found')- if (!rows[0].members.includes(userId)) {- // Stay opaque: same 404 a non-existent / cross-tenant convo returns,- // so a probing client can't tell "doesn't exist" from "I'm not in it".- throw new HttpError(404, 'not found')- }return { userId, companyId, members: rows[0].members, kind: rows[0].kind }}@@ -423,13 +427,20 @@ async function withLockedConversationMember<T>(args: {)if (!actor.rowCount) throw new HttpError(404, 'not found')const { rows } = await client.query<{ members: string[]; kind: string; pinned: boolean }>(- `SELECT members, kind, pinned FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])- FOR UPDATE`,- [args.conversationId, args.companyId, args.userId],+ `SELECT c.members, c.kind, c.pinned FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ FOR UPDATE OF c`,+ [args.conversationId, args.companyId],)if (!rows[0]) throw new HttpError(404, 'not found')+ const membership = await client.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1+ AND company_id = $2+ AND participant_id = $3`,+ [args.conversationId, args.companyId, args.userId],+ )+ if (!membership.rowCount) throw new HttpError(404, 'not found')const result = await args.work(client, rows[0])await client.query('COMMIT')return result@@ -2908,12 +2919,14 @@ api.get('/conversations', async (req, res) => {LEFT JOIN conversation_mutes mu ON mu.conversation_id = c.id AND mu.user_id = $1LEFT JOIN LATERAL (SELECT p_other.name- FROM jsonb_array_elements_text(c.members) WITH ORDINALITY AS member(id, ord)+ FROM conversation_members memberJOIN participants p_other- ON p_other.id = member.id- AND p_other.company_id = c.company_id- WHERE member.id <> $1- ORDER BY member.ord+ ON p_other.id = member.participant_id+ AND p_other.company_id = member.company_id+ WHERE member.conversation_id = c.id+ AND member.company_id = c.company_id+ AND member.participant_id <> $1+ ORDER BY member.ordinalLIMIT 1) other_participant ON c.kind = 'direct'WHERE c.company_id = $2@@ -2922,7 +2935,12 @@ api.get('/conversations', async (req, res) => {-- into the user's list even though they're not a participant-- — those are private to the agents and surfaced only via the-- "Whispers" peek tab.- AND c.members @> to_jsonb(ARRAY[$1::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $1+ )ORDER BY c.pinned DESC, c.updated_at DESC`,[me, tenant],)@@ -3072,12 +3090,22 @@ api.post('/conversations/direct', async (req, res) => {[tenant, pairKey],)const { rows: existing } = await client.query<{ id: string }>(- `SELECT id FROM conversations- WHERE kind = 'direct' AND company_id = $3- AND members @> to_jsonb(ARRAY[$1::text]) AND members @> to_jsonb(ARRAY[$2::text])- AND jsonb_array_length(members) = 2- ORDER BY updated_at DESC LIMIT 1- FOR UPDATE`,+ `SELECT c.id FROM conversations c+ WHERE c.kind = 'direct' AND c.company_id = $3+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $1+ )+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )+ AND (SELECT COUNT(*) FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id) = 2+ ORDER BY c.updated_at DESC LIMIT 1+ FOR UPDATE OF c`,[me, otherId, tenant],)if (existing[0]) {@@ -3204,14 +3232,29 @@ api.post('/conversations/:id/members', async (req, res) => {const { id } = req.paramsconst newMember = String(req.body?.id ?? '').trim()if (!newMember) { res.status(400).json({ error: 'id required' }); return }- const { rows } = await pool.query<{ kind: string; members: string[] }>(- `SELECT kind, members FROM conversations WHERE id = $1 AND company_id = $2`, [id, tenant],+ const { rows } = await pool.query<{+ kind: string; members: string[]; actor_is_member: boolean; target_is_member: boolean+ }>(+ `SELECT c.kind, c.members,+ EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ ) AS actor_is_member,+ EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $4+ ) AS target_is_member+ FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2`,+ [id, tenant, me, newMember],)const c = rows[0]if (!c) { res.status(404).json({ error: 'not found' }); return }if (c.kind !== 'group') { res.status(400).json({ error: `cannot add to a ${c.kind} conversation` }); return }- if (!c.members.includes(me)) { res.status(403).json({ error: 'only members can add others' }); return }- if (c.members.includes(newMember)) { res.json({ ok: true, members: c.members, alreadyIn: true }); return }+ if (!c.actor_is_member) { res.status(403).json({ error: 'only members can add others' }); return }+ if (c.target_is_member) { res.json({ ok: true, members: c.members, alreadyIn: true }); return }// Validate participant exists in this tenant.const { rows: existing } = await pool.query<{ id: string }>(`SELECT id FROM participants WHERE id = $1 AND company_id = $2`, [newMember, tenant],@@ -3235,15 +3278,23 @@ api.post('/conversations/:id/members', async (req, res) => {api.post('/conversations/:id/leave', async (req, res) => {const { userId: me, companyId: tenant } = await requireCompany(req)const { id } = req.params- const { rows } = await pool.query<{ kind: string; members: string[] }>(- `SELECT kind, members FROM conversations WHERE id = $1 AND company_id = $2`, [id, tenant],+ const { rows } = await pool.query<{ kind: string; members: string[]; actor_is_member: boolean }>(+ `SELECT c.kind, c.members,+ EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ ) AS actor_is_member+ FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2`,+ [id, tenant, me],)const c = rows[0]if (!c) { res.status(404).json({ error: 'not found' }); return }if (c.kind === 'direct') {res.status(400).json({ error: 'cannot leave a direct conversation' }); return}- if (!c.members.includes(me)) { res.status(409).json({ error: 'not a member' }); return }+ if (!c.actor_is_member) { res.status(409).json({ error: 'not a member' }); return }const { removeConversationMember } = await import('../agents/membership.js')const mutation = await removeConversationMember({conversationId: id, memberId: me, actorId: me, companyId: tenant,@@ -3572,16 +3623,23 @@ api.post('/conversations/:id/messages', async (req, res) => {}})- const { rows: convoRows } = await pool.query<{ members: string[]; kind: string }>(- `SELECT members, kind FROM conversations WHERE id = $1 AND company_id = $2`,- [id, tenant],+ const { rows: convoRows } = await pool.query<{ kind: string; actor_is_member: boolean }>(+ `SELECT c.kind,+ EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ ) AS actor_is_member+ FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2`,+ [id, tenant, me],)const convo = convoRows[0]if (!convo) {res.status(404).json({ error: 'conversation not found' })return}- if (!convo.members.includes(me)) {+ if (!convo.actor_is_member) {res.status(403).json({ error: 'not a member of this conversation' })return}@@ -3641,13 +3699,18 @@ api.post('/conversations/:id/messages', async (req, res) => {)if (!actor.rowCount) throw new HttpError(403, 'participant is no longer active in this workspace')const currentConversation = await client.query<{ kind: string }>(- `SELECT kind FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])- FOR UPDATE`,- [id, tenant, me],+ `SELECT c.kind FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ FOR UPDATE OF c`,+ [id, tenant],)if (!currentConversation.rowCount) throw new HttpError(403, 'not a member of this conversation')+ const currentMembership = await client.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1 AND company_id = $2 AND participant_id = $3`,+ [id, tenant, me],+ )+ if (!currentMembership.rowCount) throw new HttpError(403, 'not a member of this conversation')if (currentConversation.rows[0].kind === 'email') {throw new HttpError(409, 'conversation changed; retry the email reply')}@@ -4131,10 +4194,12 @@ api.get('/email/:messageId/html', async (req, res) => {const row = rows[0]if (!row) { res.status(404).json({ error: 'unknown email message' }); return }if (!row.html) { res.status(204).end(); return }- const { rows: cv } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1`, [row.conversation_id],+ const { rows: cv } = await pool.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1 AND company_id = $2 AND participant_id = $3`,+ [row.conversation_id, tenant, me],)- if (!cv[0] || !cv[0].members.includes(me)) {+ if (!cv[0]) {res.status(403).json({ error: 'not a member of this thread' }); return}const { sanitizeEmailHtml } = await import('../email.js')@@ -4181,10 +4246,12 @@ api.post('/email/reply/:messageId', async (req, res) => {)const o = orig[0]if (!o) { res.status(404).json({ error: 'unknown email message' }); return }- const { rows: cv } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1`, [o.conversation_id],+ const { rows: cv } = await pool.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1 AND company_id = $2 AND participant_id = $3`,+ [o.conversation_id, tenant, me],)- if (!cv[0] || !cv[0].members.includes(me)) {+ if (!cv[0]) {res.status(403).json({ error: 'not a member of this thread' }); return}@@ -4515,7 +4582,7 @@ api.post('/messages/:id/reactions', async (req, res) => {* if you don't see what you want.** Scoping: requireCompany() pins to the active company. Conversation/message- * results additionally filter on `members @> [userId]` so we never leak+ * results additionally join the normalized membership truth so we never leak* rooms the caller isn't actually in (same guard `/conversations` uses).*/api.get('/search', async (req, res) => {@@ -4577,17 +4644,23 @@ api.get('/search', async (req, res) => {LEFT JOIN projects p ON p.id = c.project_idLEFT JOIN LATERAL (SELECT p_other.name- FROM jsonb_array_elements_text(c.members) WITH ORDINALITY AS member(id, ord)+ FROM conversation_members memberJOIN participants p_other- ON p_other.id = member.id- AND p_other.company_id = c.company_id- WHERE member.id <> $2- ORDER BY member.ord+ ON p_other.id = member.participant_id+ AND p_other.company_id = member.company_id+ WHERE member.conversation_id = c.id+ AND member.company_id = c.company_id+ AND member.participant_id <> $2+ ORDER BY member.ordinalLIMIT 1) other_participant ON c.kind = 'direct'WHERE c.company_id = $1AND c.kind IN ('direct', 'whisper')- AND c.members @> to_jsonb(ARRAY[$2::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ ))SELECT r.id, r.kind, r.title, r.members, r."projectName"FROM my_rooms r@@ -4597,7 +4670,12 @@ api.get('/search', async (req, res) => {WHERE p.company_id = $1AND p.name ILIKE $3 ESCAPE '\\'AND p.id <> $2- AND r.members @> to_jsonb(ARRAY[p.id::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = r.id+ AND cm.company_id = $1+ AND cm.participant_id = p.id+ ))ORDER BYCASE WHEN lower(r.title) = lower($4) THEN 0@@ -4614,7 +4692,11 @@ api.get('/search', async (req, res) => {LEFT JOIN projects p ON p.id = c.project_idWHERE c.company_id = $1AND c.kind = 'group'- AND c.members @> to_jsonb(ARRAY[$2::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )AND (c.title ILIKE $3 ESCAPE '\\' OR (c.topic IS NOT NULL AND c.topic ILIKE $3 ESCAPE '\\'))ORDER BYCASE WHEN lower(c.title) = lower($4) THEN 0@@ -4645,16 +4727,22 @@ api.get('/search', async (req, res) => {ON p.id = m.author_id AND p.company_id = c.company_idLEFT JOIN LATERAL (SELECT p_other.name- FROM jsonb_array_elements_text(c.members) WITH ORDINALITY AS member(id, ord)+ FROM conversation_members memberJOIN participants p_other- ON p_other.id = member.id- AND p_other.company_id = c.company_id- WHERE member.id <> $2- ORDER BY member.ord+ ON p_other.id = member.participant_id+ AND p_other.company_id = member.company_id+ WHERE member.conversation_id = c.id+ AND member.company_id = c.company_id+ AND member.participant_id <> $2+ ORDER BY member.ordinalLIMIT 1) other_participant ON c.kind = 'direct'WHERE c.company_id = $1- AND c.members @> to_jsonb(ARRAY[$2::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )AND m.kind = 'text'AND m.body ILIKE $3 ESCAPE '\\'ORDER BY m.created_at DESC@@ -4701,19 +4789,32 @@ api.get('/peek/agent-chats', async (req, res) => {c.kind,c.title,c.members,- (c.members->>0) AS "agentA",- (c.members->>1) AS "agentB",+ (SELECT member.participant_id+ FROM conversation_members member+ WHERE member.conversation_id = c.id+ ORDER BY member.ordinal+ LIMIT 1) AS "agentA",+ (SELECT member.participant_id+ FROM conversation_members member+ WHERE member.conversation_id = c.id+ ORDER BY member.ordinal+ OFFSET 1 LIMIT 1) AS "agentB",c.topic AS about,c.created_at AS "createdAt",c.updated_at AS "updatedAt",(SELECT COUNT(*)::int FROM messages WHERE conversation_id = c.id) AS "msgCount"FROM conversations cWHERE c.company_id = $1- AND jsonb_array_length(c.members) >= 2+ AND (SELECT COUNT(*) FROM conversation_members member+ WHERE member.conversation_id = c.id) >= 2AND NOT EXISTS (- SELECT 1 FROM jsonb_array_elements_text(c.members) m- LEFT JOIN participants p ON p.id = m AND p.company_id = c.company_id- WHERE p.kind IS DISTINCT FROM 'agent'+ SELECT 1+ FROM conversation_members member+ LEFT JOIN participants p+ ON p.id = member.participant_id+ AND p.company_id = member.company_id+ WHERE member.conversation_id = c.id+ AND p.kind IS DISTINCT FROM 'agent')ORDER BY c.updated_at DESCLIMIT 50`,@@ -4734,11 +4835,16 @@ api.get('/peek/agent-chats/:id/messages', async (req, res) => {// of kind='agent' in this company.const { rows: w } = await pool.query<{ ok: boolean }>(`SELECT (- jsonb_array_length(c.members) >= 1+ (SELECT COUNT(*) FROM conversation_members member+ WHERE member.conversation_id = c.id) >= 1AND NOT EXISTS (- SELECT 1 FROM jsonb_array_elements_text(c.members) m- LEFT JOIN participants p ON p.id = m AND p.company_id = c.company_id- WHERE p.kind IS DISTINCT FROM 'agent'+ SELECT 1+ FROM conversation_members member+ LEFT JOIN participants p+ ON p.id = member.participant_id+ AND p.company_id = member.company_id+ WHERE member.conversation_id = c.id+ AND p.kind IS DISTINCT FROM 'agent')) AS okFROM conversations cdiff --git a/server/src/calendar.ts b/server/src/calendar.tsindex 7fa8bb0..de323bd 100644--- a/server/src/calendar.ts+++ b/server/src/calendar.ts@@ -91,15 +91,23 @@ function renderDispatchBody(event: CalendarEventRow, scheduledFor: Date): string* missing, target conversation deleted, etc.). */async function resolveTargetConversation(event: CalendarEventRow): Promise<string | null> {if (event.target_conversation_id) {- const { rows } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1 AND company_id = $2 LIMIT 1`,- [event.target_conversation_id, event.company_id],+ const { rows } = await pool.query<{ assignee_is_member: boolean }>(+ `SELECT ($3::text IS NULL OR EXISTS (+ SELECT 1 FROM conversation_members member+ WHERE member.conversation_id = c.id+ AND member.company_id = c.company_id+ AND member.participant_id = $3+ )) AS assignee_is_member+ FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ LIMIT 1`,+ [event.target_conversation_id, event.company_id, event.assignee_id],)if (!rows[0]) return null// Best-effort: skip dispatch if the assignee isn't a member of the// target conversation. Avoids the @mention dangling in a room the// agent can't see.- if (event.assignee_id && !rows[0].members.includes(event.assignee_id)) return null+ if (!rows[0].assignee_is_member) return nullreturn event.target_conversation_id}if (!event.assignee_id) return null@@ -107,11 +115,22 @@ async function resolveTargetConversation(event: CalendarEventRow): Promise<strin// creator and the assignee. We don't auto-create one — if it doesn't// exist the dispatch records 'skipped'.const { rows } = await pool.query<{ id: string }>(- `SELECT id FROM conversations- WHERE company_id = $1 AND kind = 'direct'- AND members @> $2::jsonb AND members @> $3::jsonb+ `SELECT c.id FROM conversations c+ WHERE c.company_id = $1 AND c.kind = 'direct'+ AND EXISTS (+ SELECT 1 FROM conversation_members creator+ WHERE creator.conversation_id = c.id+ AND creator.participant_id = $2+ )+ AND EXISTS (+ SELECT 1 FROM conversation_members assignee+ WHERE assignee.conversation_id = c.id+ AND assignee.participant_id = $3+ )+ AND (SELECT COUNT(*) FROM conversation_members member+ WHERE member.conversation_id = c.id) = 2LIMIT 1`,- [event.company_id, JSON.stringify([event.created_by]), JSON.stringify([event.assignee_id])],+ [event.company_id, event.created_by, event.assignee_id],)return rows[0]?.id ?? null}@@ -123,6 +142,21 @@ async function postDispatchMessage(args: {}): Promise<string> {const { event, conversationId, body } = argsreturn withOutboxTransaction(async (client) => {+ const target = await client.query(+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ FOR UPDATE OF c`,+ [conversationId, event.company_id],+ )+ if (!target.rowCount) throw new Error('calendar target conversation disappeared')+ const membership = await client.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1+ AND company_id = $2+ AND participant_id = $3`,+ [conversationId, event.company_id, event.assignee_id],+ )+ if (!membership.rowCount) throw new Error('calendar assignee is no longer a target member')const seqResult = await client.query<{ seq: number }>(`INSERT INTO conversation_counters (conversation_id, next_sequence)VALUES ($1, 2)diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex 0d3e4f7..c0f30bf 100644--- a/server/src/db/migrate.ts+++ b/server/src/db/migrate.ts@@ -13,6 +13,10 @@ import {SCHEMA_MIGRATIONS,validateMigrationHistory,} from './migrations/manifest.js'+import {+ NORMALIZED_CONVERSATION_MEMBERS_SQL,+ normalizedConversationMembersChecksum,+} from './migrations/0002-normalized-conversation-members.js'/** Frozen data backfill embedded in migration 0001. Exported so its behavior* can be exercised against PostgreSQL without replaying the whole migration. */@@ -2083,7 +2087,11 @@ async function applyLegacyBaseline(client: import('pg').PoolClient): Promise<voi`)await ensureMessageClientIdIndex(client)await buildConcurrentIndexes(client)- await verifyRequiredIndexes(client)+ await verifyRequiredIndexes(client, BASELINE_REQUIRED_SCHEMA_INDEXES)+}++async function applyNormalizedConversationMembers(client: import('pg').PoolClient): Promise<void> {+ await client.query(NORMALIZED_CONVERSATION_MEMBERS_SQL)}const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [@@ -2092,6 +2100,11 @@ const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [sourceChecksum: computedBaselineMigrationChecksum(),up: applyLegacyBaseline,},+ {+ ...SCHEMA_MIGRATIONS[1],+ sourceChecksum: normalizedConversationMembersChecksum(),+ up: applyNormalizedConversationMembers,+ },]function validateMigrationDefinitions(): void {@@ -2299,7 +2312,7 @@ async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<}}-export const REQUIRED_SCHEMA_INDEXES = [+const BASELINE_REQUIRED_SCHEMA_INDEXES = ['participants_agent_id_unique','uniq_participants_agent_creation_request','uniq_messages_client_id',@@ -2312,9 +2325,18 @@ export const REQUIRED_SCHEMA_INDEXES = ['idx_llm_calls_created_brin',] as const+export const REQUIRED_SCHEMA_INDEXES = [+ ...BASELINE_REQUIRED_SCHEMA_INDEXES,+ 'conversation_members_conversation_ordinal_key',+ 'idx_conversation_members_participant',+] as const+/** Promotion gate: every required index must exist and be valid, ready, and* live. An interrupted CREATE INDEX CONCURRENTLY must never look healthy. */-async function verifyRequiredIndexes(client: import('pg').PoolClient): Promise<void> {+async function verifyRequiredIndexes(+ client: import('pg').PoolClient,+ requiredIndexes: readonly string[] = REQUIRED_SCHEMA_INDEXES,+): Promise<void> {const { rows } = await client.query<{name: stringindisvalid: boolean@@ -2327,10 +2349,10 @@ async function verifyRequiredIndexes(client: import('pg').PoolClient): Promise<vJOIN pg_namespace n ON n.oid = c.relnamespaceWHERE n.nspname = current_schema()AND c.relname = ANY($1::text[])`,- [[...REQUIRED_SCHEMA_INDEXES]],+ [[...requiredIndexes]],)const byName = new Map(rows.map((row) => [row.name, row]))- const invalid = REQUIRED_SCHEMA_INDEXES.filter((name) => {+ const invalid = requiredIndexes.filter((name) => {const row = byName.get(name)return !row || !row.indisvalid || !row.indisready || !row.indislive})diff --git a/server/src/db/migrations/0002-normalized-conversation-members.ts b/server/src/db/migrations/0002-normalized-conversation-members.tsnew file mode 100644index 0000000..d98e7c2--- /dev/null+++ b/server/src/db/migrations/0002-normalized-conversation-members.ts@@ -0,0 +1,224 @@+import { createHash } from 'node:crypto'++/**+ * Migration 0002: make normalized rows the conversation-membership truth.+ *+ * Keep this string immutable after release. The manifest stores its SHA-256,+ * and both the migration owner and application startup verify that identity.+ */+export const NORMALIZED_CONVERSATION_MEMBERS_SQL = `+ALTER TABLE conversations ALTER COLUMN company_id SET NOT NULL;++DO $migration$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conname = 'conversations_id_company_key'+ AND conrelid = 'conversations'::regclass+ ) THEN+ ALTER TABLE conversations+ ADD CONSTRAINT conversations_id_company_key UNIQUE (id, company_id);+ END IF;+END+$migration$;++CREATE TABLE conversation_members (+ conversation_id TEXT NOT NULL,+ company_id TEXT NOT NULL,+ participant_id TEXT NOT NULL,+ ordinal INTEGER NOT NULL CHECK (ordinal >= 0),+ joined_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ PRIMARY KEY (conversation_id, participant_id),+ CONSTRAINT conversation_members_conversation_fk+ FOREIGN KEY (conversation_id, company_id)+ REFERENCES conversations(id, company_id)+ ON UPDATE CASCADE ON DELETE CASCADE,+ CONSTRAINT conversation_members_participant_fk+ FOREIGN KEY (participant_id, company_id)+ REFERENCES participants(id, company_id)+ ON UPDATE RESTRICT ON DELETE RESTRICT+);++CREATE UNIQUE INDEX conversation_members_conversation_ordinal_key+ ON conversation_members(conversation_id, ordinal);+CREATE INDEX idx_conversation_members_participant+ ON conversation_members(company_id, participant_id, conversation_id);++-- Fail closed instead of silently dropping a legacy member that does not+-- resolve to a participant in the conversation's tenant. Synthetic external+-- email author markers were never authorization principals and are removed+-- from the compatibility projection during normalization.+DO $migration$+BEGIN+ IF EXISTS (+ SELECT 1+ FROM conversations c+ CROSS JOIN LATERAL jsonb_array_elements_text(c.members) member(id)+ LEFT JOIN participants p+ ON p.id = member.id AND p.company_id = c.company_id+ WHERE p.id IS NULL+ AND member.id NOT LIKE 'external:%'+ ) THEN+ RAISE EXCEPTION 'cannot normalize conversation membership: foreign or missing participant'+ USING ERRCODE = '23503';+ END IF;+END+$migration$;++INSERT INTO conversation_members (+ conversation_id, company_id, participant_id, ordinal, joined_at+)+SELECT seeded.conversation_id,+ seeded.company_id,+ seeded.participant_id,+ seeded.ordinal,+ seeded.joined_at+ FROM (+ SELECT DISTINCT ON (c.id, member.id)+ c.id AS conversation_id,+ c.company_id,+ member.id AS participant_id,+ (member.ord - 1)::integer AS ordinal,+ c.created_at AS joined_at+ FROM conversations c+ CROSS JOIN LATERAL jsonb_array_elements_text(c.members)+ WITH ORDINALITY AS member(id, ord)+ WHERE member.id NOT LIKE 'external:%'+ ORDER BY c.id, member.id, member.ord+ ) seeded;++-- Canonicalize the retained JSONB projection once. Authorization and routing+-- never read this column after this migration; it exists for response-shape+-- compatibility and can always be rebuilt from conversation_members.+UPDATE conversations c+ SET members = COALESCE(+ (+ SELECT jsonb_agg(cm.participant_id ORDER BY cm.ordinal, cm.participant_id)+ FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ ),+ '[]'::jsonb+ );++CREATE FUNCTION refresh_conversation_members_projection(p_conversation_id TEXT)+RETURNS JSONB+LANGUAGE plpgsql+AS $function$+DECLARE+ projected JSONB;+BEGIN+ SELECT COALESCE(+ jsonb_agg(cm.participant_id ORDER BY cm.ordinal, cm.participant_id),+ '[]'::jsonb+ )+ INTO projected+ FROM conversation_members cm+ WHERE cm.conversation_id = p_conversation_id;++ UPDATE conversations+ SET members = projected,+ updated_at = NOW()+ WHERE id = p_conversation_id;++ RETURN projected;+END+$function$;++CREATE FUNCTION seed_conversation_members_from_projection()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $function$+BEGIN+ INSERT INTO conversation_members (+ conversation_id, company_id, participant_id, ordinal, joined_at+ )+ SELECT NEW.id,+ NEW.company_id,+ seeded.participant_id,+ seeded.ordinal,+ NEW.created_at+ FROM (+ SELECT DISTINCT ON (member.id)+ member.id AS participant_id,+ (member.ord - 1)::integer AS ordinal+ FROM jsonb_array_elements_text(NEW.members)+ WITH ORDINALITY AS member(id, ord)+ WHERE member.id NOT LIKE 'external:%'+ ORDER BY member.id, member.ord+ ) seeded;++ PERFORM refresh_conversation_members_projection(NEW.id);+ RETURN NEW;+END+$function$;++-- Expand-phase compatibility for the revision that may still be serving while+-- migration 0002 runs. A legacy JSONB write is translated into normalized rows+-- under the same conversation row lock; new code never uses this ingress. A+-- later contract migration can replace this function with a hard rejection+-- after the pre-0002 application can no longer be rolled back.+CREATE FUNCTION synchronize_conversation_members_projection()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $function$+DECLARE+ expected JSONB;+BEGIN+ SELECT COALESCE(+ jsonb_agg(cm.participant_id ORDER BY cm.ordinal, cm.participant_id),+ '[]'::jsonb+ )+ INTO expected+ FROM conversation_members cm+ WHERE cm.conversation_id = NEW.id+ AND cm.company_id = NEW.company_id;++ -- refresh_conversation_members_projection already supplied the canonical+ -- normalized value; do not feed that value back through the compatibility+ -- ingress.+ IF NEW.members IS NOT DISTINCT FROM expected THEN RETURN NEW; END IF;++ DELETE FROM conversation_members WHERE conversation_id = OLD.id;+ INSERT INTO conversation_members (+ conversation_id, company_id, participant_id, ordinal, joined_at+ )+ SELECT NEW.id,+ NEW.company_id,+ seeded.participant_id,+ seeded.ordinal,+ NOW()+ FROM (+ SELECT DISTINCT ON (member.id)+ member.id AS participant_id,+ (member.ord - 1)::integer AS ordinal+ FROM jsonb_array_elements_text(NEW.members)+ WITH ORDINALITY AS member(id, ord)+ WHERE member.id NOT LIKE 'external:%'+ ORDER BY member.id, member.ord+ ) seeded;++ SELECT COALESCE(+ jsonb_agg(cm.participant_id ORDER BY cm.ordinal, cm.participant_id),+ '[]'::jsonb+ )+ INTO NEW.members+ FROM conversation_members cm+ WHERE cm.conversation_id = NEW.id+ AND cm.company_id = NEW.company_id;+ RETURN NEW;+END+$function$;++CREATE TRIGGER conversations_seed_members_after_insert+AFTER INSERT ON conversations+FOR EACH ROW EXECUTE FUNCTION seed_conversation_members_from_projection();++CREATE TRIGGER conversations_sync_legacy_members_projection+BEFORE UPDATE OF members ON conversations+FOR EACH ROW EXECUTE FUNCTION synchronize_conversation_members_projection();+`++export function normalizedConversationMembersChecksum(): string {+ return createHash('sha256').update(NORMALIZED_CONVERSATION_MEMBERS_SQL).digest('hex')+}diff --git a/server/src/db/migrations/manifest.ts b/server/src/db/migrations/manifest.tsindex 424911b..9c24a28 100644--- a/server/src/db/migrations/manifest.ts+++ b/server/src/db/migrations/manifest.ts@@ -22,12 +22,17 @@ export const SCHEMA_MIGRATIONS = [name: '0001_legacy_baseline',checksum: '5250b63e17bb5a028483b72a799b868418b875e7c0802be4168175b9930aa7d0',},+ {+ version: 2,+ name: '0002_normalized_conversation_members',+ checksum: '489abe15a28b6c1ee11e7a3e03f79c2949574687333de1d97e7b7eff33c6d2b3',+ },] as const satisfies readonly MigrationMetadata[]/** This build intentionally supports one exact schema range. Expand/contract* releases may widen the range, but both bounds must remain explicit. */-export const MIN_SUPPORTED_SCHEMA_VERSION = 1-export const MAX_SUPPORTED_SCHEMA_VERSION = 1+export const MIN_SUPPORTED_SCHEMA_VERSION = 2+export const MAX_SUPPORTED_SCHEMA_VERSION = 2function assertManifestShape(): void {for (let i = 0; i < SCHEMA_MIGRATIONS.length; i++) {diff --git a/server/src/email.ts b/server/src/email.tsindex 2b485ec..3189781 100644--- a/server/src/email.ts+++ b/server/src/email.ts@@ -657,11 +657,20 @@ export async function persistEmailMessage(args: {const conversation = await client.query(`SELECT id FROM conversationsWHERE id = $1 AND company_id = $2- AND ($3::boolean = FALSE OR members @> to_jsonb(ARRAY[$4::text]))FOR UPDATE`,- [args.conversationId, args.companyId, args.direction === 'out', args.authorId],+ [args.conversationId, args.companyId],)if (!conversation.rowCount) throw new Error('email conversation not found or no longer authorized')+ if (args.direction === 'out') {+ const membership = await client.query(+ `SELECT 1 FROM conversation_members+ WHERE conversation_id = $1+ AND company_id = $2+ AND participant_id = $3`,+ [args.conversationId, args.companyId, args.authorId],+ )+ if (!membership.rowCount) throw new Error('email conversation not found or no longer authorized')+ }const seqResult = await client.query<{ seq: number }>(`INSERT INTO conversation_counters (conversation_id, next_sequence)@@ -811,9 +820,10 @@ export async function persistEmailMessage(args: {* direct/group conversations use. Title = the subject line* (collapses Re:/Fwd: prefixes for display sanity).*- * members is what powers the inbox / RLS / wake fan-out. Including- * the sender means their own outbox messages show up in their inbox- * view (matches Gmail's behavior). */+ * Normalized participant memberships power inbox authorization and wake+ * fan-out. Synthetic `external:<addr>` author markers are deliberately not+ * memberships; including the internal sender still makes their own outbox+ * messages appear in their inbox (matching Gmail's behavior). */export async function findOrCreateEmailConversation(args: {companyId: stringinReplyTo: string | null@@ -823,8 +833,9 @@ export async function findOrCreateEmailConversation(args: {* sender. Order is preserved for the title fallback ("A ↔ B"). */memberIds: string[]}): Promise<{ conversationId: string; created: boolean }> {- const uniqueMembers = Array.from(new Set(args.memberIds))- const concreteMembers = uniqueMembers.filter((id) => !id.startsWith('external:')).sort()+ const concreteMembers = Array.from(new Set(args.memberIds))+ .filter((id) => !id.startsWith('external:'))+ .sort()const client = await pool.connect()try {await client.query('BEGIN')@@ -846,22 +857,32 @@ export async function findOrCreateEmailConversation(args: {.filter((x): x is string => Boolean(x))const existing = await findEmailConversationByMessageIds(candidates, args.companyId, client)if (existing) {- // Membership repair is serialized with participant moves and validates- // every concrete member before extending the JSON array.+ // Serialize thread repair before checking/inserting normalized rows.+ // The next statement gets a fresh snapshot after any lock wait.+ const locked = await client.query(+ `SELECT id FROM conversations+ WHERE id = $1 AND company_id = $2+ FOR UPDATE`,+ [existing, args.companyId],+ )+ if (!locked.rowCount) throw new Error('email conversation moved or disappeared')await client.query(- `UPDATE conversations- SET members = (- SELECT to_jsonb(ARRAY(- SELECT DISTINCT m FROM (- SELECT jsonb_array_elements_text(members) AS m- UNION- SELECT unnest($2::text[]) AS m- ) u- ))- )- WHERE id = $1 AND company_id = $3`,- [existing, uniqueMembers, args.companyId],+ `INSERT INTO conversation_members (+ conversation_id, company_id, participant_id, ordinal+ )+ SELECT $1, $3, incoming.participant_id,+ base.next_ordinal + incoming.input_ordinal - 1+ FROM UNNEST($2::text[]) WITH ORDINALITY+ AS incoming(participant_id, input_ordinal)+ CROSS JOIN LATERAL (+ SELECT COALESCE(MAX(ordinal) + 1, 0)::integer AS next_ordinal+ FROM conversation_members+ WHERE conversation_id = $1 AND company_id = $3+ ) base+ ON CONFLICT (conversation_id, participant_id) DO NOTHING`,+ [existing, concreteMembers, args.companyId],)+ await client.query(`SELECT refresh_conversation_members_projection($1)`, [existing])await client.query('COMMIT')return { conversationId: existing, created: false }}@@ -871,7 +892,7 @@ export async function findOrCreateEmailConversation(args: {await client.query(`INSERT INTO conversations (id, kind, title, members, company_id, topic)VALUES ($1, 'email', $2, $3::jsonb, $4, $5)`,- [id, cleanSubject.slice(0, 200), JSON.stringify(uniqueMembers), args.companyId, cleanSubject.slice(0, 200)],+ [id, cleanSubject.slice(0, 200), JSON.stringify(concreteMembers), args.companyId, cleanSubject.slice(0, 200)],)await client.query('COMMIT')return { conversationId: id, created: true }diff --git a/server/src/onboardCompany.ts b/server/src/onboardCompany.tsindex dc5600d..b65f9be 100644--- a/server/src/onboardCompany.ts+++ b/server/src/onboardCompany.ts@@ -15,6 +15,8 @@ import { invalidatePersonaCache } from './agents/personas.js'import { randomUUID } from 'node:crypto'import { gravatarUrlForEmail } from './auth.js'import { ensureDirectConversation } from './agents/private_chat.js'+import { CH_MESSAGE_NEW } from './redis.js'+import { enqueueBroadcast, nudgeRealtimeOutbox } from './realtime-outbox.js'interface StarterAgent {/** Preferred id; we'll suffix on collision. */@@ -168,10 +170,21 @@ export async function onboardStarterAgents(// Skip if a DM already exists for this pair — saves needless rows on// partial reruns.const { rows: ex } = await pool.query(- `SELECT 1 FROM conversations- WHERE company_id = $1 AND kind = 'direct'- AND members @> to_jsonb(ARRAY[$2::text, $3::text])- AND jsonb_array_length(members) = 2 LIMIT 1`,+ `SELECT 1 FROM conversations c+ WHERE c.company_id = $1 AND c.kind = 'direct'+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )+ AND (SELECT COUNT(*) FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id) = 2+ LIMIT 1`,[companyId, ownerId, a.id],)if (ex[0]) continue@@ -251,8 +264,8 @@ export async function onboardStarterAgents(* group and broadcast a "X joined" system message. Called from POST /agents,* /auth/signup, and POST /companies after a new participant is persisted.*- * Idempotent — if the participant is already in the members array, only the- * system message is skipped too. If the company has no all-hands group yet+ * Idempotent — if the participant already has a normalized membership row,+ * the system message is skipped too. If the company has no all-hands group yet* (legacy or seeding race), this is a no-op rather than an error.*/export async function joinAllHands(args: {@@ -294,26 +307,37 @@ export async function joinAllHands(args: {return}- const { rows: updated } = await client.query<{ added: boolean }>(- `UPDATE conversations c- SET members = members || to_jsonb(ARRAY[$2::text]),- updated_at = NOW()- WHERE c.id = $1- AND c.company_id = $3- AND NOT (c.members @> to_jsonb(ARRAY[$2::text]))- AND EXISTS (- SELECT 1 FROM participants target- WHERE target.id = $2 AND target.company_id = c.company_id- AND target.kind IN ('agent', 'human')- AND target.departed_at IS NULL- )- RETURNING TRUE AS added`,+ const lockedConversation = await client.query(+ `SELECT id FROM conversations+ WHERE id = $1 AND company_id = $2+ FOR UPDATE`,+ [convId, companyId],+ )+ if (!lockedConversation.rowCount) {+ await client.query('COMMIT')+ return+ }+ const inserted = await client.query(+ `INSERT INTO conversation_members (+ conversation_id, company_id, participant_id, ordinal+ )+ SELECT c.id, c.company_id, $2,+ COALESCE(MAX(existing.ordinal) + 1, 0)::integer+ FROM conversations c+ LEFT JOIN conversation_members existing+ ON existing.conversation_id = c.id+ AND existing.company_id = c.company_id+ WHERE c.id = $1 AND c.company_id = $3+ GROUP BY c.id, c.company_id+ ON CONFLICT (conversation_id, participant_id) DO NOTHING+ RETURNING participant_id`,[convId, participantId, companyId],)- if (updated.length === 0) {+ if (!inserted.rowCount) {await client.query('COMMIT')return}+ await client.query(`SELECT refresh_conversation_members_projection($1)`, [convId])const seqResult = await client.query<{ seq: number }>(`INSERT INTO conversation_counters (conversation_id, next_sequence)@@ -328,7 +352,17 @@ export async function joinAllHands(args: {VALUES ($1, $2, $3, 'system', $4, $5, $6)`,[messageId, convId, participantId, body, sequence, companyId],)+ await enqueueBroadcast(client, CH_MESSAGE_NEW, {+ type: 'message.new',+ conversationId: convId,+ companyId,+ message: {+ id: messageId, conversationId: convId, authorId: participantId,+ kind: 'system', body, sequence, at: new Date().toISOString(),+ },+ })await client.query('COMMIT')+ nudgeRealtimeOutbox()} catch (error) {await client.query('ROLLBACK').catch(() => {})throw error@@ -337,20 +371,6 @@ export async function joinAllHands(args: {}if (!convId || sequence === 0) return- // Broadcast so already-open clients see the join in real time.- const { CH_MESSAGE_NEW, CH_STATUS, publish } = await import('./redis.js')- await publish(CH_MESSAGE_NEW, {- type: 'message.new',- conversationId: convId,- companyId,- message: {- id: messageId, conversationId: convId, authorId: participantId,- kind: 'system', body, sequence, at: new Date().toISOString(),- },- }).catch((error) => {- console.warn('[onboard] all-hands message publish failed; row remains durable', error instanceof Error ? error.message : error)- })-// Fire-and-forget: also publish the full participant payload so existing// members upsert it into their local byId store. Without this, the system// row above references a participantId nobody in the workspace knows@@ -359,6 +379,7 @@ export async function joinAllHands(args: {// update — broadcast misses are tolerable (the 60s refresher backfills),// a DB hiccup here should not roll back the actual membership change.try {+ const { CH_STATUS, publish } = await import('./redis.js')const { rows: pRow } = await pool.query<{id: string; kind: string; name: string; role: string | null;initial: string; avatar_bg: string; avatar_url: string | null;diff --git a/server/src/polls.ts b/server/src/polls.tsindex 9028b05..6a62c74 100644--- a/server/src/polls.ts+++ b/server/src/polls.ts@@ -120,10 +120,15 @@ export async function createPoll(input: CreatePollInput): Promise<CreatedPoll> {)if (!actor.rowCount) throw new PollError('author is not an active tenant participant', 403)const authorized = await client.query(- `SELECT id FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])- FOR UPDATE`,+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )+ FOR UPDATE OF c`,[input.conversationId, input.companyId, input.authorId],)if (!authorized.rowCount) throw new PollError('conversation not found or not authorized', 403)@@ -203,10 +208,15 @@ export async function castVote(input: CastVoteInput): Promise<PollUpdatedEvent>company_id: string}>(`SELECT m.poll, m.conversation_id, m.company_id- FROM conversations c+ FROM conversations cJOIN messages m ON m.conversation_id = c.id AND m.company_id = c.company_idWHERE m.id = $1 AND m.company_id = $2 AND m.kind = 'poll'- AND c.members @> to_jsonb(ARRAY[$3::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )FOR SHARE OF cFOR UPDATE OF m`,[input.messageId, input.companyId, input.voterParticipantId],@@ -281,7 +291,12 @@ export async function closePoll(input: CloseInput): Promise<PollUpdatedEvent | nFROM conversations cJOIN messages m ON m.conversation_id = c.id AND m.company_id = c.company_idWHERE m.id = $1 AND m.company_id = $2 AND m.kind = 'poll'- AND c.members @> to_jsonb(ARRAY[$3::text])+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id+ AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )FOR SHARE OF cFOR UPDATE OF m`: `SELECT poll, author_id FROM messagesdiff --git a/server/src/push.ts b/server/src/push.tsindex b16bc9f..7b4fd4e 100644--- a/server/src/push.ts+++ b/server/src/push.ts@@ -314,13 +314,11 @@ export async function computeMessageRecipients(args: {authorId: string}): Promise<string[]> {const { rows } = await pool.query<{ user_id: string }>(- `WITH convo AS (- SELECT members FROM conversations WHERE id = $1- )- SELECT u.id AS user_id- FROM users u- JOIN convo c ON u.id = ANY(SELECT jsonb_array_elements_text(c.members))- WHERE u.id <> $2+ `SELECT u.id AS user_id+ FROM conversation_members cm+ JOIN users u ON u.id = cm.participant_id+ WHERE cm.conversation_id = $1+ AND u.id <> $2AND NOT EXISTS (SELECT 1 FROM conversation_mutes mWHERE m.conversation_id = $1diff --git a/server/src/ws.ts b/server/src/ws.tsindex 62f7c82..073d053 100644--- a/server/src/ws.ts+++ b/server/src/ws.ts@@ -205,21 +205,23 @@ export async function resolveWsEventRecipientUserIds(: nullconst { rows } = await pool.query<{ user_id: string }>(`WITH scoped_conversation AS (- SELECT id, company_id, members+ SELECT id, company_idFROM conversationsWHERE id = $1 AND company_id = $2), current_members AS (- SELECT cm.user_id+ SELECT company_member.user_idFROM scoped_conversation c- CROSS JOIN LATERAL jsonb_array_elements_text(c.members) member(id)+ JOIN conversation_members room_member+ ON room_member.conversation_id = c.id+ AND room_member.company_id = c.company_idJOIN participants p- ON p.id = member.id+ ON p.id = room_member.participant_idAND p.company_id = c.company_idAND p.kind = 'human'AND p.departed_at IS NULL- JOIN company_members cm- ON cm.user_id = p.id- AND cm.company_id = c.company_id+ JOIN company_members company_member+ ON company_member.user_id = p.id+ AND company_member.company_id = c.company_id), durable_recipient AS (SELECT cm.user_idFROM scoped_conversation c@@ -701,24 +703,41 @@ async function postDocMentionWake(args: {// participants still belong to it. 2) Otherwise reuse/create one DM.if (document[0].conversation_id) {const { rows } = await client.query<{ id: string }>(- `SELECT id FROM conversations- WHERE id = $1 AND company_id = $2- AND members @> to_jsonb(ARRAY[$3::text])- AND members @> to_jsonb(ARRAY[$4::text])- FOR UPDATE`,+ `SELECT c.id FROM conversations c+ WHERE c.id = $1 AND c.company_id = $2+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $3+ )+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $4+ )+ FOR UPDATE OF c`,[document[0].conversation_id, companyId, mentionerId, agentId],)conversationId = rows[0]?.id ?? ''}if (!conversationId) {const { rows } = await client.query<{ id: string }>(- `SELECT id FROM conversations- WHERE kind = 'direct' AND company_id = $3- AND members @> to_jsonb(ARRAY[$1::text])- AND members @> to_jsonb(ARRAY[$2::text])- AND jsonb_array_length(members) = 2- ORDER BY updated_at DESC LIMIT 1- FOR UPDATE`,+ `SELECT c.id FROM conversations c+ WHERE c.kind = 'direct' AND c.company_id = $3+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $1+ )+ AND EXISTS (+ SELECT 1 FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id+ AND cm.participant_id = $2+ )+ AND (SELECT COUNT(*) FROM conversation_members cm+ WHERE cm.conversation_id = c.id AND cm.company_id = c.company_id) = 2+ ORDER BY c.updated_at DESC LIMIT 1+ FOR UPDATE OF c`,[mentionerId, agentId, companyId],)conversationId = rows[0]?.id ?? ''