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(security): bind writes to live membership (#133)
OKNOTOK7697bbf39578
diff --git a/server/src/__integration__/convene-concurrency.test.ts b/server/src/__integration__/convene-concurrency.test.tsnew file mode 100644index 0000000..449bd4b--- /dev/null+++ b/server/src/__integration__/convene-concurrency.test.ts@@ -0,0 +1,298 @@+/**+ * Deterministic authorization races for Convene orchestration.+ *+ * The production LLM override is used only as a controllable Promise barrier:+ * the first speech request can be paused while a real membership kick commits.+ * Persisted transcript rows and Redis events still travel through production+ * code, so these tests cover both pre-generation and post-generation checks.+ */++import assert from 'node:assert/strict'+import { randomUUID } from 'node:crypto'+import { after, before, beforeEach, test } from 'node:test'+import { setTimeout as delay } from 'node:timers/promises'+import IORedis from 'ioredis'+import { runCli } from '../agents/cli.js'+import { startConvene } from '../agents/convene.js'+import { pool } from '../db/pool.js'+import { env } from '../env.js'+import { __setLlmClientOverrideForTesting } from '../llm.js'+import { CH_CONVENE } from '../redis.js'+import {+ ensureSchemaOnce, resetAllTables, seedCompanyWithAgent,+ seedUserMembership, teardownAll,+} from './_helpers.js'++interface FakeLlmRequest {+ input?: unknown+ text?: unknown+}++interface ConveneEvent {+ type?: string+ sessionId?: string+ conversationId?: string+ companyId?: string+ kind?: string+ data?: {+ id?: string+ authorId?: string+ body?: string+ kind?: string+ }+}++before(async () => {+ await ensureSchemaOnce()+})++beforeEach(async () => {+ __setLlmClientOverrideForTesting(null)+ await resetAllTables()+})++after(async () => {+ __setLlmClientOverrideForTesting(null)+ await teardownAll()+})++function signal(): { promise: Promise<void>; resolve: () => void } {+ let resolve!: () => void+ const promise = new Promise<void>((done) => { resolve = done })+ return { promise, resolve }+}++async function withTimeout<T>(promise: Promise<T>, label: string, timeoutMs = 8_000): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ promise,+ new Promise<T>((_resolve, reject) => {+ timer = setTimeout(() => reject(new Error(`timed out waiting for ${label}`)), timeoutMs)+ }),+ ])+ } finally {+ if (timer) clearTimeout(timer)+ }+}++async function waitForSessionEnded(sessionId: string): Promise<void> {+ for (let attempt = 0; attempt < 800; attempt++) {+ const { rows } = await pool.query<{ state: string }>(+ `SELECT state FROM convene_sessions WHERE id = $1`,+ [sessionId],+ )+ if (rows[0]?.state === 'ended') return+ await delay(10)+ }+ throw new Error(`convene session ${sessionId} did not end`)+}++async function waitForEvent(+ events: ConveneEvent[],+ predicate: (event: ConveneEvent) => boolean,+ label: string,+): Promise<ConveneEvent> {+ for (let attempt = 0; attempt < 800; attempt++) {+ const match = events.find(predicate)+ if (match) return match+ await delay(10)+ }+ throw new Error(`did not receive ${label}`)+}++function installFakeLlm(+ create: (request: FakeLlmRequest) => Promise<{ output_text: string; usage?: unknown }>,+): void {+ __setLlmClientOverrideForTesting((async () => ({+ responses: { create },+ })) as unknown as Parameters<typeof __setLlmClientOverrideForTesting>[0])+}++async function seedConvene(agentIds: string[]): Promise<{+ companyId: string+ starterId: string+ conversationId: string+}> {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ for (const agentId of agentIds) {+ await seedCompanyWithAgent({ companyId, agentId })+ }+ const starterId = `human-${randomUUID().slice(0, 8)}`+ await seedUserMembership(starterId, companyId, {+ email: `${starterId}@test.local`,+ displayName: `Starter ${starterId}`,+ })+ const conversationId = `conv-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO conversations (id, company_id, kind, title, members)+ VALUES ($1, $2, 'group', $3, $4::jsonb)`,+ [+ conversationId,+ companyId,+ `Convene ${conversationId}`,+ JSON.stringify([starterId, ...agentIds]),+ ],+ )+ return { companyId, starterId, conversationId }+}++function isSpeechRequest(request: FakeLlmRequest): boolean {+ return Array.isArray(request.input)+}++function moderatorLine(request: FakeLlmRequest): string {+ if (!Array.isArray(request.input)) return ''+ const last = request.input[request.input.length - 1] as { content?: unknown } | undefined+ return String(last?.content ?? '')+}++test('[integration] convene skips a queued second agent kicked while the first speech is paused', async () => {+ const firstAgentId = `agent-a-first-${randomUUID().slice(0, 6)}`+ const secondAgentId = `agent-z-second-${randomUUID().slice(0, 6)}`+ const seeded = await seedConvene([firstAgentId, secondAgentId])+ const firstEntered = signal()+ const releaseFirst = signal()+ const speechPrompts: string[] = []++ installFakeLlm(async (request) => {+ if (isSpeechRequest(request)) {+ const moderator = moderatorLine(request)+ speechPrompts.push(moderator)+ if (moderator.includes(firstAgentId)) {+ firstEntered.resolve()+ await releaseFirst.promise+ return { output_text: 'first agent contribution' }+ }+ return { output_text: 'second agent must never be called' }+ }+ return { output_text: JSON.stringify({ reached: false, headline: '', body: '' }) }+ })++ const session = await startConvene({+ conversationId: seeded.conversationId,+ companyId: seeded.companyId,+ startedBy: seeded.starterId,+ topic: 'membership revalidation before each turn',+ })+ let kick: Awaited<ReturnType<typeof runCli>>+ try {+ await withTimeout(firstEntered.promise, 'the first convene speech request')+ kick = await runCli([+ '--as', seeded.starterId, 'kick', seeded.conversationId, secondAgentId,+ ])+ } finally {+ releaseFirst.resolve()+ }+ assert.equal(kick!.ok, true, kick!.text)+ await withTimeout(waitForSessionEnded(session.id), 'the convene session to end')++ assert.equal(speechPrompts.length, 1, JSON.stringify(speechPrompts))+ assert.match(speechPrompts[0] ?? '', new RegExp(firstAgentId))+ assert.ok(!speechPrompts.some((prompt) => prompt.includes(secondAgentId)), 'kicked second agent reached the LLM')+ const { rows } = await pool.query<{ author_id: string; body: string }>(+ `SELECT author_id, body FROM convene_transcript+ WHERE session_id = $1 AND kind = 'text'+ ORDER BY sequence`,+ [session.id],+ )+ assert.deepEqual(rows, [{ author_id: firstAgentId, body: 'first agent contribution' }])+})++test('[integration] convene drops an agent result when the agent is kicked during generation', async () => {+ const agentId = `agent-generating-${randomUUID().slice(0, 6)}`+ const seeded = await seedConvene([agentId])+ const generationEntered = signal()+ const releaseGeneration = signal()+ let speechCalls = 0++ installFakeLlm(async (request) => {+ if (isSpeechRequest(request)) {+ speechCalls+++ generationEntered.resolve()+ await releaseGeneration.promise+ return { output_text: 'revoked result must not land' }+ }+ return { output_text: JSON.stringify({ reached: false, headline: '', body: '' }) }+ })++ const session = await startConvene({+ conversationId: seeded.conversationId,+ companyId: seeded.companyId,+ startedBy: seeded.starterId,+ topic: 'post-generation authorization',+ })+ let kick: Awaited<ReturnType<typeof runCli>>+ try {+ await withTimeout(generationEntered.promise, 'the in-flight convene generation')+ kick = await runCli([+ '--as', seeded.starterId, 'kick', seeded.conversationId, agentId, '--confirm-empty',+ ])+ } finally {+ releaseGeneration.resolve()+ }+ assert.equal(kick!.ok, true, kick!.text)+ await withTimeout(waitForSessionEnded(session.id), 'the convene session to end')++ assert.equal(speechCalls, 1)+ const { rows } = await pool.query<{ author_id: string; body: string }>(+ `SELECT author_id, body FROM convene_transcript WHERE session_id = $1`,+ [session.id],+ )+ assert.deepEqual(rows, [], 'a response generated after revocation reached the transcript')+})++test('[integration] convene transcript events carry the persisted conversation id', async () => {+ const agentId = `agent-event-${randomUUID().slice(0, 6)}`+ const seeded = await seedConvene([agentId])+ const subscriber = new IORedis(env.REDIS_URL, {+ maxRetriesPerRequest: 1,+ enableReadyCheck: true,+ })+ const events: ConveneEvent[] = []+ subscriber.on('message', (channel, raw) => {+ if (channel !== CH_CONVENE) return+ try { events.push(JSON.parse(raw) as ConveneEvent) } catch { /* ignore unrelated malformed traffic */ }+ })+ await subscriber.subscribe(CH_CONVENE)++ installFakeLlm(async (request) => {+ if (isSpeechRequest(request)) return { output_text: 'event-backed contribution' }+ return { output_text: JSON.stringify({ reached: false, headline: '', body: '' }) }+ })++ try {+ const session = await startConvene({+ conversationId: seeded.conversationId,+ companyId: seeded.companyId,+ startedBy: seeded.starterId,+ topic: 'publish the true conversation scope',+ })+ const event = await withTimeout(+ waitForEvent(+ events,+ (candidate) => candidate.sessionId === session.id+ && candidate.kind === 'transcript'+ && candidate.data?.authorId === agentId,+ 'the transcript Redis event',+ ),+ 'the transcript Redis event',+ )+ await withTimeout(waitForSessionEnded(session.id), 'the convene session to end')++ assert.equal(event.type, 'convene')+ assert.equal(event.companyId, seeded.companyId)+ assert.equal(event.conversationId, seeded.conversationId)+ assert.notEqual(event.conversationId, '')+ const { rows } = await pool.query<{ id: string; author_id: string; body: string }>(+ `SELECT id, author_id, body FROM convene_transcript+ WHERE session_id = $1 AND author_id = $2`,+ [session.id, agentId],+ )+ assert.equal(rows.length, 1)+ assert.equal(event.data?.id, rows[0].id)+ assert.equal(event.data?.body, rows[0].body)+ } finally {+ subscriber.disconnect()+ }+})diff --git a/server/src/__integration__/membership-concurrency.test.ts b/server/src/__integration__/membership-concurrency.test.tsindex d853a58..04517a8 100644--- a/server/src/__integration__/membership-concurrency.test.ts+++ b/server/src/__integration__/membership-concurrency.test.ts@@ -21,13 +21,45 @@import { test, before, beforeEach, after } from 'node:test'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 { pool } from '../db/pool.js'import { runCli } from '../agents/cli.js'-import { ensureSchemaOnce, resetAllTables, seedCompanyWithAgent, teardownAll } from './_helpers.js'+import { inprocClient } from '../agents/runtime/inproc-client.js'+import {+ handlePollUpdated, resolveDurableDeliveryAgent, triageWakeRecipient,+} from '../agents/scheduler.js'+import { joinAllHands } from '../onboardCompany.js'+import { resolveWsEventRecipientUserIds } from '../ws.js'+import {+ buildApiTestApp, ensureSchemaOnce, resetAllTables,+ seedCompanyWithAgent, seedUserMembership, teardownAll,+} from './_helpers.js'-before(async () => { await ensureSchemaOnce() })+const HTTP_A = 'human-http-a'+const HTTP_B = 'human-http-b'+const httpServers: Server[] = []+const httpBaseUrls: string[] = []++before(async () => {+ await ensureSchemaOnce()+ for (const userId of [HTTP_A, HTTP_B]) {+ const app = await buildApiTestApp(userId)+ await new Promise<void>((resolve) => {+ const server = createServer(app).listen(0, () => {+ const addr = server.address()+ if (addr && typeof addr === 'object') httpBaseUrls.push(`http://127.0.0.1:${addr.port}`)+ httpServers.push(server)+ resolve()+ })+ })+ }+})beforeEach(async () => { await resetAllTables() })-after(async () => { await teardownAll() })+after(async () => {+ await Promise.all(httpServers.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))+ await teardownAll()+})async function seedAgent(companyId: string, id: string): Promise<string> {await seedCompanyWithAgent({ companyId, agentId: id })@@ -51,6 +83,53 @@ async function membersOf(convoId: string): Promise<string[]> {return rows[0]?.members ?? []}+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],+ )+ return rows.map(({ body }) => JSON.parse(body) as { kind?: string; participantId?: string })+}++async function waitForBlockedQuery(pattern: string, minimum: number = 1): Promise<void> {+ for (let attempt = 0; attempt < 200; attempt++) {+ const { rows } = await pool.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count+ FROM pg_stat_activity+ WHERE datname = current_database()+ AND pid <> pg_backend_pid()+ AND wait_event_type = 'Lock'+ AND query ILIKE $1`,+ [pattern],+ )+ if ((rows[0]?.count ?? 0) >= minimum) return+ await delay(10)+ }+ throw 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 waitForBlockedMembershipGuards(minimum: number): Promise<void> {+ for (let attempt = 0; attempt < 200; attempt++) {+ const { rows } = await pool.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count+ FROM pg_stat_activity+ WHERE datname = current_database()+ AND pid <> pg_backend_pid()+ AND wait_event_type = 'Lock'+ AND (+ query ILIKE '%UPDATE conversations c%SET members =%'+ OR query ILIKE '%FROM participants%FOR UPDATE%'+ )`,+ )+ if ((rows[0]?.count ?? 0) >= minimum) return+ await delay(10)+ }+ throw new Error(`membership requests never reached ${minimum} blocked guards`)+}+test('[integration] simultaneous invites do not lose an invitee', async () => {// Eight at once rather than two: a single overlapping pair only sometimes// interleaves inside the read→write window on a local socket, and a test@@ -102,6 +181,634 @@ test('[integration] a leave that overlaps an invite keeps both effects', async (assert.ok(members.includes(b))})+test('[integration] a kick that overlaps an invite cannot resurrect the revoked member', async () => {+ // This is the exact authorization failure mode: a stale whole-array invite+ // write used to put a concurrently kicked participant back into `members`,+ // immediately restoring access to the private conversation.+ for (let round = 0; round < 8; round++) {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const a = await seedAgent(companyId, `agent-a-${round}`)+ const b = await seedAgent(companyId, `agent-b-${round}`)+ const revoked = await seedAgent(companyId, `agent-revoked-${round}`)+ const invited = await seedAgent(companyId, `agent-invited-${round}`)+ const convo = await seedGroup(companyId, [a, b, revoked])++ const [kick, invite] = await Promise.all([+ runCli(['--as', a, 'kick', convo, revoked]),+ runCli(['--as', b, 'invite', convo, invited]),+ ])+ assert.equal(kick.ok, true, `round ${round} kick failed: ${kick.text}`)+ assert.equal(invite.ok, true, `round ${round} invite failed: ${invite.text}`)++ const members = await membersOf(convo)+ assert.ok(!members.includes(revoked), `round ${round}: revoked member resurrected: ${JSON.stringify(members)}`)+ assert.ok(members.includes(invited), `round ${round}: concurrent invite was lost: ${JSON.stringify(members)}`)+ }+})++test('[integration] real HTTP leave and members routes preserve both concurrent effects', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'HTTP membership race', $2, $3)`,+ [companyId, companyId, HTTP_A],+ )+ const invited = 'human-http-invited'+ await seedUserMembership(HTTP_A, companyId)+ await seedUserMembership(HTTP_B, companyId)+ await seedUserMembership(invited, companyId)++ // Several independent rows make the old read/modify/write implementation+ // fail reliably without test-only hooks in production SQL.+ for (let round = 0; round < 8; round++) {+ const convo = await seedGroup(companyId, [HTTP_A, HTTP_B])+ const [leaveResponse, inviteResponse] = await Promise.all([+ fetch(`${httpBaseUrls[0]}/api/conversations/${convo}/leave`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-company-id': companyId },+ body: '{}',+ }),+ fetch(`${httpBaseUrls[1]}/api/conversations/${convo}/members`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-company-id': companyId },+ body: JSON.stringify({ id: invited }),+ }),+ ])+ assert.equal(leaveResponse.status, 200, `round ${round} leave: ${await leaveResponse.text()}`)+ assert.equal(inviteResponse.status, 200, `round ${round} invite: ${await inviteResponse.text()}`)++ const members = await membersOf(convo)+ assert.ok(!members.includes(HTTP_A), `round ${round}: HTTP leave was reverted: ${JSON.stringify(members)}`)+ assert.ok(members.includes(invited), `round ${round}: HTTP invite was lost: ${JSON.stringify(members)}`)+ assert.ok(members.includes(HTTP_B))++ const notices = await noticesOf(convo)+ assert.ok(notices.some((body) => body.kind === 'left' && body.participantId === HTTP_A))+ assert.ok(notices.some((body) => body.kind === 'joined' && body.participantId === invited))+ }+})++test('[integration] a revoked HTTP actor cannot finish a stale invite or emit a joined notice', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'HTTP actor revocation', $2, $3)`,+ [companyId, companyId, HTTP_A],+ )+ const invited = 'human-http-late-invite'+ await seedUserMembership(HTTP_A, companyId)+ await seedUserMembership(HTTP_B, companyId)+ await seedUserMembership(invited, companyId)+ const convo = await seedGroup(companyId, [HTTP_A, HTTP_B])++ // Hold an uncommitted revocation on the row. The route's initial SELECT sees+ // the old committed membership and passes; its UPDATE then blocks behind us.+ // Once the kick commits, Postgres must re-check actor membership in the+ // UPDATE predicate and reject the stale request.+ const revoker = await pool.connect()+ let committed = false+ let pending: Promise<Response> | undefined+ try {+ await revoker.query('BEGIN')+ await revoker.query(+ `UPDATE conversations SET members = members - $2::text WHERE id = $1`,+ [convo, HTTP_A],+ )+ pending = fetch(`${httpBaseUrls[0]}/api/conversations/${convo}/members`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-company-id': companyId },+ body: JSON.stringify({ id: invited }),+ })+ await waitForBlockedMembershipUpdate('members ||')+ await revoker.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await revoker.query('ROLLBACK').catch(() => {})+ revoker.release()+ }++ const response = await pending!+ assert.equal(response.status, 403, await response.text())+ const members = await membersOf(convo)+ assert.ok(!members.includes(HTTP_A))+ assert.ok(!members.includes(invited), `revoked actor added ${invited}: ${JSON.stringify(members)}`)+ assert.ok(!(await noticesOf(convo)).some((body) => body.kind === 'joined' && body.participantId === invited))+})++test('[integration] a revoked HTTP actor cannot finish a stale text message write', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'HTTP message revocation', $2, $3)`,+ [companyId, companyId, HTTP_A],+ )+ await seedUserMembership(HTTP_A, companyId)+ await seedUserMembership(HTTP_B, companyId)+ const convo = await seedGroup(companyId, [HTTP_A, HTTP_B])++ const revoker = await pool.connect()+ let committed = false+ let pending: Promise<Response> | undefined+ try {+ await revoker.query('BEGIN')+ await revoker.query(+ `UPDATE conversations SET members = members - $2::text WHERE id = $1`,+ [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 revoker.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await revoker.query('ROLLBACK').catch(() => {})+ revoker.release()+ }++ const response = await pending!+ assert.equal(response.status, 403, await response.text())+ const leaked = await pool.query(+ `SELECT 1 FROM messages WHERE conversation_id = $1 AND body = $2`,+ [convo, 'must-not-land-after-kick'],+ )+ assert.equal(leaked.rowCount, 0)+})++test('[integration] a revoked HTTP email reply is rejected before the provider call', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'HTTP email revocation', $2, $3)`,+ [companyId, companyId, HTTP_A],+ )+ await seedUserMembership(HTTP_A, companyId)+ await seedUserMembership(HTTP_B, companyId)+ const senderAddress = `${HTTP_A}.${companyId}@cumora.local`+ await pool.query(+ `UPDATE participants SET email = $1 WHERE id = $2 AND company_id = $3`,+ [senderAddress, HTTP_A, companyId],+ )+ const convo = `email-${randomUUID().slice(0, 8)}`+ const inboundId = `m-${randomUUID()}`+ await pool.query(+ `INSERT INTO conversations (id, company_id, kind, title, members)+ VALUES ($1,$2,'email','revocation thread',$3::jsonb)`,+ [convo, companyId, JSON.stringify([HTTP_A, HTTP_B])],+ )+ await pool.query(+ `INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1,2)`,+ [convo],+ )+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1,$2,'external:alice','email','old mail',1,$3)`,+ [inboundId, convo, companyId],+ )+ await pool.query(+ `INSERT INTO email_messages+ (message_id, conversation_id, company_id, direction, transport_status,+ smtp_message_id, subject, from_addr, to_addrs)+ VALUES ($1,$2,$3,'in','received','[email protected]','secret thread',+ 'Alice <[email protected]>',$4::jsonb)`,+ [inboundId, convo, companyId, JSON.stringify([senderAddress])],+ )++ const providerLogs: string[] = []+ const originalLog = console.log+ console.log = (...values: unknown[]) => {+ providerLogs.push(values.map(String).join(' '))+ originalLog(...values)+ }+ const revoker = await pool.connect()+ let committed = false+ let pending: Promise<Response> | undefined+ let response: Response | undefined+ try {+ await revoker.query('BEGIN')+ await revoker.query(+ `UPDATE conversations SET members = members - $2::text WHERE id = $1`,+ [convo, HTTP_A],+ )+ pending = fetch(`${httpBaseUrls[0]}/api/email/reply/${inboundId}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-company-id': companyId },+ body: JSON.stringify({ body: 'must-not-be-sent-after-kick' }),+ })+ await waitForBlockedQuery('%SELECT id FROM conversations%FOR UPDATE%')+ await revoker.query('COMMIT')+ committed = true+ response = await pending+ } finally {+ if (!committed) await revoker.query('ROLLBACK').catch(() => {})+ revoker.release()+ console.log = originalLog+ }++ assert.equal(response!.status, 500, await response!.text())+ assert.ok(!providerLogs.some((line) => line.includes('[email/mock]')), providerLogs.join('\n'))+ const outbound = await pool.query(+ `SELECT 1 FROM email_messages WHERE conversation_id = $1 AND direction = 'out'`,+ [convo],+ )+ assert.equal(outbound.rowCount, 0)+})++test('[integration] HTTP group and direct creation reject targets moved while participant locks wait', async () => {+ const companyA = `c-${randomUUID().slice(0, 8)}`+ const companyB = `c-${randomUUID().slice(0, 8)}`+ const directTarget = 'human-http-direct-moving'+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'HTTP room tenant A', $1, $3), ($2, 'HTTP room tenant B', $2, $3)`,+ [companyA, companyB, HTTP_A],+ )+ await seedUserMembership(HTTP_A, companyA)+ await seedUserMembership(HTTP_B, companyA)+ await seedUserMembership(directTarget, companyA)++ const moveAndRequest = async (targetId: string, url: string, body: Record<string, unknown>) => {+ const mover = await pool.connect()+ let committed = false+ let pending: Promise<Response> | undefined+ try {+ await mover.query('BEGIN')+ await mover.query(+ `UPDATE participants SET company_id = $2 WHERE id = $1 AND company_id = $3`,+ [targetId, companyB, companyA],+ )+ pending = fetch(`${httpBaseUrls[0]}${url}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-company-id': companyA },+ body: JSON.stringify(body),+ })+ await waitForBlockedQuery('%ORDER BY id FOR SHARE%')+ await mover.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await mover.query('ROLLBACK').catch(() => {})+ mover.release()+ }+ return pending!+ }++ const groupResponse = await moveAndRequest(HTTP_B, '/api/conversations', {+ title: 'must-not-create-stale-group', members: [HTTP_B],+ })+ assert.equal(groupResponse.status, 400, await groupResponse.text())++ const directResponse = await moveAndRequest(directTarget, '/api/conversations/direct', {+ otherId: directTarget,+ })+ 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]))`,+ [companyA, directTarget],+ )+ assert.equal(created.rowCount, 0)+})++test('[integration] a revoked CLI actor cannot finish a stale kick or emit a kicked notice', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyId, 'agent-stale-actor')+ const peer = await seedAgent(companyId, 'agent-stale-peer')+ const target = await seedAgent(companyId, 'agent-stale-target')+ const convo = await seedGroup(companyId, [actor, peer, target])++ const revoker = await pool.connect()+ let committed = false+ let pending: ReturnType<typeof runCli> | undefined+ try {+ await revoker.query('BEGIN')+ await revoker.query(+ `UPDATE conversations SET members = members - $2::text WHERE id = $1`,+ [convo, actor],+ )+ pending = runCli(['--as', actor, 'kick', convo, target])+ await waitForBlockedMembershipUpdate('members -')+ await revoker.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await revoker.query('ROLLBACK').catch(() => {})+ revoker.release()+ }++ const result = await pending!+ assert.equal(result.ok, false, result.text)+ const members = await membersOf(convo)+ assert.ok(!members.includes(actor))+ assert.ok(members.includes(target), `revoked actor kicked ${target}: ${JSON.stringify(members)}`)+ assert.ok(!(await noticesOf(convo)).some((body) => body.kind === 'kicked' && body.participantId === target))+})++test('[integration] an actor tenant move that wins the participant lock cancels a stale invite', async () => {+ const companyA = `c-${randomUUID().slice(0, 8)}`+ const companyB = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyA, 'agent-moving-actor')+ const target = await seedAgent(companyA, 'agent-stays-a')+ await seedAgent(companyB, 'agent-company-b-anchor')+ const convo = await seedGroup(companyA, [actor])++ const mover = await pool.connect()+ let committed = false+ let pending: ReturnType<typeof runCli> | undefined+ try {+ await mover.query('BEGIN')+ await mover.query(+ `UPDATE participants SET company_id = $2 WHERE id = $1 AND company_id = $3`,+ [actor, companyB, companyA],+ )+ // The friendly route SELECT still sees the old committed row. The helper's+ // participant FOR UPDATE must wait and then reject the moved actor.+ pending = runCli(['--as', actor, 'invite', convo, target])+ await waitForBlockedQuery('%FROM participants%FOR UPDATE%')+ await mover.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await mover.query('ROLLBACK').catch(() => {})+ mover.release()+ }++ const result = await pending!+ assert.equal(result.ok, false, result.text)+ assert.deepEqual(await membersOf(convo), [actor])+ assert.equal((await noticesOf(convo)).length, 0)+})++test('[integration] a target tenant move that wins the participant lock cancels a stale invite', async () => {+ const companyA = `c-${randomUUID().slice(0, 8)}`+ const companyB = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyA, 'agent-stays-a')+ const target = await seedAgent(companyA, 'agent-moving-target')+ await seedAgent(companyB, 'agent-company-b-anchor')+ const convo = await seedGroup(companyA, [actor])++ const mover = await pool.connect()+ let committed = false+ let pending: ReturnType<typeof runCli> | undefined+ try {+ await mover.query('BEGIN')+ await mover.query(+ `UPDATE participants SET company_id = $2 WHERE id = $1 AND company_id = $3`,+ [target, companyB, companyA],+ )+ pending = runCli(['--as', actor, 'invite', convo, target])+ await waitForBlockedQuery('%FROM participants%FOR UPDATE%')+ await mover.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await mover.query('ROLLBACK').catch(() => {})+ mover.release()+ }++ const result = await pending!+ assert.equal(result.ok, false, result.text)+ assert.deepEqual(await membersOf(convo), [actor])+ assert.equal((await noticesOf(convo)).length, 0)+})++test('[integration] target offboarding that wins the participant lock cancels a stale invite', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyId, 'agent-offboard-target-actor')+ const target = await seedAgent(companyId, 'agent-offboard-invite-target')+ const convo = await seedGroup(companyId, [actor])++ const offboarder = await pool.connect()+ let committed = false+ let pending: ReturnType<typeof runCli> | undefined+ try {+ await offboarder.query('BEGIN')+ await offboarder.query(+ `UPDATE participants SET departed_at = NOW() WHERE id = $1 AND company_id = $2`,+ [target, companyId],+ )+ pending = runCli(['--as', actor, 'invite', convo, target])+ await waitForBlockedQuery('%FROM participants%FOR UPDATE%')+ await offboarder.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await offboarder.query('ROLLBACK').catch(() => {})+ offboarder.release()+ }++ const result = await pending!+ assert.equal(result.ok, false, result.text)+ assert.deepEqual(await membersOf(convo), [actor])+ assert.equal((await noticesOf(convo)).length, 0)+})++test('[integration] actor offboarding that wins the participant lock cancels a stale kick', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyId, 'agent-offboard-kick-actor')+ const peer = await seedAgent(companyId, 'agent-offboard-kick-peer')+ const target = await seedAgent(companyId, 'agent-offboard-kick-target')+ const convo = await seedGroup(companyId, [actor, peer, target])++ const offboarder = await pool.connect()+ let committed = false+ let pending: ReturnType<typeof runCli> | undefined+ try {+ await offboarder.query('BEGIN')+ await offboarder.query(+ `UPDATE participants SET departed_at = NOW() WHERE id = $1 AND company_id = $2`,+ [actor, companyId],+ )+ pending = runCli(['--as', actor, 'kick', convo, target])+ await waitForBlockedQuery('%FROM participants%FOR UPDATE%')+ await offboarder.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await offboarder.query('ROLLBACK').catch(() => {})+ offboarder.release()+ }++ const result = await pending!+ assert.equal(result.ok, false, result.text)+ assert.ok((await membersOf(convo)).includes(target))+ assert.equal((await noticesOf(convo)).length, 0)+})++test('[integration] a moved agent cannot read a stale old-tenant membership', async () => {+ const companyA = `c-${randomUUID().slice(0, 8)}`+ const companyB = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyA, 'agent-old-tenant-peer')+ const moved = await seedAgent(companyA, 'agent-moved-with-stale-member-id')+ await seedAgent(companyB, 'agent-company-b-anchor')+ const convo = await seedGroup(companyA, [actor, moved])+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($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 inbox = await inprocClient.loadInbox(moved)+ assert.deepEqual(inbox, [])+})++test('[integration] a kicked poll author is not woken with later room tally details', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const author = await seedAgent(companyId, 'agent-kicked-poll-author')+ const peer = await seedAgent(companyId, 'agent-poll-peer')+ const convo = await seedGroup(companyId, [author, peer])+ const messageId = `m-${randomUUID()}`+ const poll = {+ question: 'old room secret?',+ mode: 'single' as const,+ options: [{ id: 'yes', text: 'classified option' }, { id: 'no', text: 'other' }],+ expiresAt: null,+ closedAt: null,+ closedReason: null,+ }+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, poll, company_id)+ VALUES ($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],+ )++ const woke = await handlePollUpdated({+ type: 'poll.updated',+ conversationId: convo,+ companyId,+ messageId,+ poll,+ tallies: [{ optionId: 'yes', count: 1, voterIds: [peer] }],+ actorId: peer,+ })+ assert.equal(woke, false)+})++test('[integration] WebSocket routing uses current room membership with one durable departure exception', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const outsider = 'human-ws-outsider'+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'WS authorization', $2, $3)`,+ [companyId, companyId, HTTP_A],+ )+ await seedUserMembership(HTTP_A, companyId)+ await seedUserMembership(HTTP_B, companyId)+ await seedUserMembership(outsider, companyId)+ const convo = await seedGroup(companyId, [HTTP_A, HTTP_B])+ const ordinaryId = `m-${randomUUID()}`+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1,$2,$3,'text','private body',1,$4)`,+ [ordinaryId, convo, HTTP_B, companyId],+ )++ const before = await resolveWsEventRecipientUserIds({+ type: 'message.new', companyId, conversationId: convo, message: { id: ordinaryId },+ })+ assert.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],+ )+ const afterKick = await resolveWsEventRecipientUserIds({+ type: 'message.new', companyId, conversationId: convo, message: { id: ordinaryId },+ })+ assert.deepEqual([...afterKick], [HTTP_B])++ const departureId = `m-${randomUUID()}`+ await pool.query(+ `INSERT INTO messages+ (id, conversation_id, author_id, kind, body, sequence, company_id, delivery_recipient_id)+ VALUES ($1,$2,$3,'system',$4,2,$5,$6)`,+ [+ departureId,+ convo,+ HTTP_B,+ JSON.stringify({ kind: 'kicked', participantId: HTTP_A, actorId: HTTP_B }),+ companyId,+ HTTP_A,+ ],+ )+ const departure = await resolveWsEventRecipientUserIds({+ type: 'message.new', companyId, conversationId: convo, message: { id: departureId },+ })+ assert.deepEqual([...departure].sort(), [HTTP_A, HTTP_B].sort())++ const forged = await resolveWsEventRecipientUserIds({+ type: 'message.new', companyId, conversationId: convo, message: { id: ordinaryId },+ })+ assert.deepEqual([...forged], [HTTP_B], 'ordinary row inherited a forged departure exception')++ await pool.query(+ `UPDATE participants SET departed_at = NOW() WHERE id = $1 AND company_id = $2`,+ [HTTP_A, companyId],+ )+ const workspaceRecipients = await resolveWsEventRecipientUserIds({+ type: 'participants.status', companyId,+ })+ assert.ok(!workspaceRecipients.has(HTTP_A), 'departed account retained workspace-wide WS delivery')+ assert.deepEqual([...workspaceRecipients].sort(), [HTTP_B, outsider].sort())+})++test('[integration] a corrupt all-hands pointer cannot add a member across tenants', async () => {+ const companyA = `c-${randomUUID().slice(0, 8)}`+ const companyB = `c-${randomUUID().slice(0, 8)}`+ const memberA = await seedAgent(companyA, 'agent-company-a')+ const memberB = await seedAgent(companyB, 'agent-company-b')+ const foreignConversation = await seedGroup(companyB, [memberB])+ await pool.query(+ `UPDATE companies SET all_hands_conversation_id = $2 WHERE id = $1`,+ [companyA, foreignConversation],+ )++ await joinAllHands({ companyId: companyA, participantId: memberA })++ assert.deepEqual(await membersOf(foreignConversation), [memberB])+ assert.equal((await noticesOf(foreignConversation)).length, 0)+})++test('[integration] joinAllHands rejects a participant moved while onboarding is waiting', async () => {+ const companyA = `c-${randomUUID().slice(0, 8)}`+ const companyB = `c-${randomUUID().slice(0, 8)}`+ const anchor = await seedAgent(companyA, 'agent-all-hands-anchor')+ const moving = await seedAgent(companyA, 'agent-all-hands-moving')+ await seedAgent(companyB, 'agent-all-hands-company-b')+ const allHands = await seedGroup(companyA, [anchor])+ await pool.query(+ `UPDATE companies SET all_hands_conversation_id = $2 WHERE id = $1`,+ [companyA, allHands],+ )++ const mover = await pool.connect()+ let committed = false+ let pending: ReturnType<typeof joinAllHands> | undefined+ try {+ await mover.query('BEGIN')+ await mover.query(+ `UPDATE participants SET company_id = $2 WHERE id = $1 AND company_id = $3`,+ [moving, companyB, companyA],+ )+ pending = joinAllHands({ companyId: companyA, participantId: moving })+ await waitForBlockedQuery('%FROM participants%FOR UPDATE%')+ await mover.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await mover.query('ROLLBACK').catch(() => {})+ mover.release()+ }++ await pending!+ assert.deepEqual(await membersOf(allHands), [anchor])+ assert.equal((await noticesOf(allHands)).length, 0)+})+test('[integration] concurrent kicks of different agents both take effect', async () => {const companyId = `c-${randomUUID().slice(0, 8)}`const a = await seedAgent(companyId, 'agent-a')@@ -123,22 +830,176 @@ test('[integration] concurrent kicks of different agents both take effect', asynassert.deepEqual([...members].sort(), [a, b].sort())})+test('[integration] concurrent kicks cannot bypass --confirm-empty', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyId, 'agent-confirm-actor')+ const x = await seedAgent(companyId, 'agent-confirm-x')+ const y = await seedAgent(companyId, 'agent-confirm-y')+ const convo = await seedGroup(companyId, [actor, x, y])++ // Hold the shared actor row so both commands finish their friendly snapshot+ // checks before either protected UPDATE can commit. Once released, Postgres+ // serializes the writes and the second UPDATE must re-evaluate cardinality.+ const blocker = await pool.connect()+ let committed = false+ let kickX: ReturnType<typeof runCli> | undefined+ let kickY: ReturnType<typeof runCli> | undefined+ try {+ await blocker.query('BEGIN')+ await blocker.query(+ `SELECT id FROM participants WHERE id = $1 AND company_id = $2 FOR UPDATE`,+ [actor, companyId],+ )+ kickX = runCli(['--as', actor, 'kick', convo, x])+ kickY = runCli(['--as', actor, 'kick', convo, y])+ await waitForBlockedQuery('%FROM participants%FOR UPDATE%', 2)+ await blocker.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await blocker.query('ROLLBACK').catch(() => {})+ blocker.release()+ }++ const results = await Promise.all([kickX!, kickY!])+ assert.equal(results.filter((result) => result.ok).length, 1, JSON.stringify(results))+ assert.equal(results.filter((result) => !result.ok).length, 1, JSON.stringify(results))+ const members = await membersOf(convo)+ assert.equal(members.length, 2, JSON.stringify(members))+ assert.ok(members.includes(actor))+ const kicked = (await noticesOf(convo)).filter((body) => body.kind === 'kicked')+ assert.equal(kicked.length, 1, JSON.stringify(kicked))+})+test('[integration] inviting the same agent twice at once adds them once', async () => {- // The "already a member" guard reads a snapshot, so both callers can pass it.- // The write itself has to be what refuses the duplicate.+ // Force both callers past their initial snapshot before the first UPDATE is+ // allowed to commit. This makes the duplicate-event regression deterministic+ // instead of hoping two local-socket requests happen to overlap.const companyId = `c-${randomUUID().slice(0, 8)}`const a = await seedAgent(companyId, 'agent-a')const b = await seedAgent(companyId, 'agent-b')const x = await seedAgent(companyId, 'agent-x')const convo = await seedGroup(companyId, [a, b])- await Promise.all([- runCli(['--as', a, 'invite', convo, x]),- runCli(['--as', b, 'invite', convo, x]),- ])+ const blocker = await pool.connect()+ let committed = false+ let inviteA: ReturnType<typeof runCli> | undefined+ let inviteB: ReturnType<typeof runCli> | undefined+ try {+ await blocker.query('BEGIN')+ await blocker.query(`UPDATE conversations SET updated_at = updated_at WHERE id = $1`, [convo])+ inviteA = runCli(['--as', a, 'invite', convo, x])+ inviteB = runCli(['--as', b, 'invite', convo, x])+ await waitForBlockedMembershipGuards(2)+ await blocker.query('COMMIT')+ committed = true+ } finally {+ if (!committed) await blocker.query('ROLLBACK').catch(() => {})+ blocker.release()+ }++ const results = await Promise.all([inviteA!, inviteB!])+ assert.equal(results.filter((result) => result.ok).length, 1, JSON.stringify(results))const members = await membersOf(convo)assert.equal(members.filter((m) => m === x).length, 1, `${x} added twice: ${JSON.stringify(members)}`)+ const joins = (await noticesOf(convo)).filter((body) => body.kind === 'joined' && body.participantId === x)+ assert.equal(joins.length, 1, `duplicate joined notices: ${JSON.stringify(joins)}`)+})++test('[integration] kicked agent receives only its durable departure notice', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const actor = await seedAgent(companyId, 'agent-kick-notice-actor')+ const target = await seedAgent(companyId, 'agent-kick-notice-target')+ const peer = await seedAgent(companyId, 'agent-kick-notice-peer')+ const convo = await seedGroup(companyId, [actor, target, peer])+ const secretId = `m-${randomUUID()}`+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1,$2,$3,'text','not visible after removal',1,$4)`,+ [secretId, convo, peer, companyId],+ )+ const muted = await runCli(['--as', target, 'mute', convo, '--for', '1h'])+ assert.equal(muted.ok, true, muted.text)++ const result = await runCli(['--as', actor, 'kick', convo, target])+ assert.equal(result.ok, true, result.text)+ assert.ok(!(await membersOf(convo)).includes(target))++ const inbox = await inprocClient.loadInbox(target)+ assert.equal(inbox.length, 1, JSON.stringify(inbox))+ assert.equal(inbox[0].kind, 'system')+ assert.equal(inbox[0].conversation_id, convo)+ assert.ok(!inbox.some((row) => row.id === secretId), 'removed agent received ordinary conversation history')+ const body = JSON.parse(inbox[0].body) as { kind?: string; participantId?: string }+ assert.deepEqual(body, { kind: 'kicked', participantId: target, actorId: actor })++ const { rows } = await pool.query<{ delivery_recipient_id: string | null }>(+ `SELECT delivery_recipient_id FROM messages WHERE id = $1`, [inbox[0].id],+ )+ assert.equal(rows[0]?.delivery_recipient_id, target)++ assert.equal(await resolveDurableDeliveryAgent({+ conversationId: convo,+ messageId: inbox[0].id,+ companyId,+ claimedRecipientId: target,+ }), target)+ assert.equal(await resolveDurableDeliveryAgent({+ conversationId: convo,+ messageId: secretId,+ companyId,+ claimedRecipientId: target,+ }), null, 'forged pubsub recipient turned an ordinary message into a wake')+ assert.equal(await resolveDurableDeliveryAgent({+ conversationId: convo,+ messageId: inbox[0].id,+ companyId,+ claimedRecipientId: peer,+ }), null, 'pubsub recipient did not match the persisted departure recipient')++ const cloudWake = await triageWakeRecipient(target, {+ conversationId: convo,+ messageId: inbox[0].id,+ })+ assert.equal(cloudWake, null, 'informational departure unexpectedly woke the cloud main brain')+ assert.deepEqual(await inprocClient.loadInbox(target), [])++ await pool.query(+ `UPDATE participants SET departed_at = NOW() WHERE id = $1 AND company_id = $2`,+ [target, companyId],+ )+ assert.equal(await resolveDurableDeliveryAgent({+ conversationId: convo,+ messageId: inbox[0].id,+ companyId,+ claimedRecipientId: target,+ }), null, 'departed agent remained eligible for scheduler fan-out')+})++test('[integration] leaving agent receives and can acknowledge its own departure notice', async () => {+ const companyId = `c-${randomUUID().slice(0, 8)}`+ const leaver = await seedAgent(companyId, 'agent-leave-notice-self')+ const peer = await seedAgent(companyId, 'agent-leave-notice-peer')+ const convo = await seedGroup(companyId, [leaver, peer])+ const muted = await runCli(['--as', leaver, 'mute', convo, '--for', '1h'])+ assert.equal(muted.ok, true, muted.text)++ const result = await runCli(['--as', leaver, 'leave', convo])+ assert.equal(result.ok, true, result.text)+ assert.ok(!(await membersOf(convo)).includes(leaver))++ const inbox = await inprocClient.loadInbox(leaver)+ assert.equal(inbox.length, 1, JSON.stringify(inbox))+ assert.equal(inbox[0].author_id, leaver, 'self-authored departure notice was filtered out')+ const body = JSON.parse(inbox[0].body) as { kind?: string; participantId?: string; actorId?: string }+ assert.deepEqual(body, { kind: 'left', participantId: leaver, actorId: leaver })++ await inprocClient.markConversationRead({+ agentId: leaver,+ conversationId: convo,+ upToMessageId: inbox[0].id,+ })+ assert.deepEqual(await inprocClient.loadInbox(leaver), [])})test('[integration] a lone sequential invite still behaves exactly as before', async () => {diff --git a/server/src/__integration__/retry.test.ts b/server/src/__integration__/retry.test.tsindex 6a91488..b037675 100644--- a/server/src/__integration__/retry.test.ts+++ b/server/src/__integration__/retry.test.ts@@ -63,6 +63,22 @@ async function seedFailedOutbound(): Promise<{return { messageId, conversationId: conv.conversationId, companyId, agentId }}+async function seedSendingOutbound(): Promise<{ messageId: string }> {+ const { companyId, agentId, agentEmail } = await seedCompanyWithAgent()+ const conv = await findOrCreateEmailConversation({+ companyId, inReplyTo: null, references: [], subject: 'outbox pending',+ memberIds: [agentId],+ })+ const { messageId } = await persistEmailMessage({+ conversationId: conv.conversationId, companyId, authorId: agentId,+ direction: 'out', transportStatus: 'sending', transportError: null,+ smtpMessageId: `outbox-${Date.now()}@host`, inReplyTo: null, references: [],+ subject: 'outbox pending', fromAddr: agentEmail,+ toAddrs: ['[email protected]'], body: 'recover me', autoSubmitted: true,+ })+ return { messageId }+}+test('[integration] retry worker promotes a failed row to sent when the provider succeeds', async (t) => {const { messageId } = await seedFailedOutbound()// Swap sendViaProvider via env-mock: empty RESEND_API_KEY → mock mode@@ -88,6 +104,36 @@ test('[integration] retry worker promotes a failed row to sent when the providerassert.equal(rows[0].next_retry_at, null, 'sent rows must clear next_retry_at to stay out of the retry set')})+test('[integration] retry worker recovers a crash-stale sending outbox row', async () => {+ const { messageId } = await seedSendingOutbound()+ const scheduled = await pool.query<{ next_retry_at: string | null }>(+ `SELECT next_retry_at FROM email_messages WHERE message_id = $1`,+ [messageId],+ )+ assert.ok(scheduled.rows[0].next_retry_at, 'sending row must have a recovery deadline')+ assert.ok(new Date(scheduled.rows[0].next_retry_at!).getTime() > Date.now())+ await pool.query(+ `UPDATE email_messages SET next_retry_at = NOW() - INTERVAL '1 second' WHERE message_id = $1`,+ [messageId],+ )++ delete process.env.RESEND_API_KEY+ delete process.env.EMAIL_MOCK_FAIL_RATE+ const { runRetryTick } = await import('../email-retry.js')+ const result = await runRetryTick(8)+ assert.equal(result.attempted, 1)+ const recovered = await pool.query<{+ transport_status: string; retry_attempts: number; next_retry_at: string | null;+ }>(+ `SELECT transport_status, retry_attempts, next_retry_at+ FROM email_messages WHERE message_id = $1`,+ [messageId],+ )+ assert.deepEqual(recovered.rows[0], {+ transport_status: 'sent', retry_attempts: 1, next_retry_at: null,+ })+})+test('[integration] retry worker advances backoff on a still-failing send', async () => {const { messageId } = await seedFailedOutbound()// Force mock mode to always fail.diff --git a/server/src/__integration__/runtime-aux-authorization.test.ts b/server/src/__integration__/runtime-aux-authorization.test.tsnew file mode 100644index 0000000..91a13ff--- /dev/null+++ b/server/src/__integration__/runtime-aux-authorization.test.ts@@ -0,0 +1,709 @@+/**+ * Security regressions for the auxiliary `/runtime/*` write surfaces.+ *+ * These tests deliberately use the real Express router, PostgreSQL locks, and+ * Redis. In particular, the kick/notices race is ordered with a row-lock+ * holder: the real CLI kick queues first, the notice request queues behind the+ * kick's participant lock, and only then is the holder released. A passing+ * test therefore proves the authorization check and notice insert share one+ * serialization boundary; timing luck cannot make the race disappear.+ */++import assert from 'node:assert/strict'+import { randomUUID } from 'node:crypto'+import { createServer, type Server } from 'node:http'+import { after, before, beforeEach, test } from 'node:test'+import { setTimeout as delay } from 'node:timers/promises'+import { Client } from 'pg'+import { runCli } from '../agents/cli.js'+import {+ thinkingKey, worklogField, worklogKey,+} from '../agents/runtime/inproc-client.js'+import { signAgentToken } from '../agents/runtime/jwt.js'+import { pool } from '../db/pool.js'+import { readDocumentText, subscribe } from '../documents/rooms.js'+import { env } from '../env.js'+import { CH_DOCS, redis } from '../redis.js'+import {+ ensureSchemaOnce, resetAllTables, seedCompanyWithAgent, teardownAll,+} from './_helpers.js'++let server: Server+let baseUrl = ''++before(async () => {+ await ensureSchemaOnce()+ const expressMod = await import('express')+ const express = expressMod.default+ const { runtimeRouter } = await import('../agents/runtime/server.js')+ const app = express()+ app.use(express.json({ limit: '4mb' }))+ app.use('/runtime', runtimeRouter)+ await new Promise<void>((resolve) => {+ server = createServer(app).listen(0, () => {+ const address = server.address()+ if (address && typeof address === 'object') {+ baseUrl = `http://127.0.0.1:${address.port}`+ }+ resolve()+ })+ })+})++beforeEach(async () => {+ await resetAllTables()+})++after(async () => {+ await teardownAll(server)+})++async function call(+ path: string,+ opts: { method?: string; token: string; body?: unknown },+): Promise<{ status: number; body: any }> {+ const response = await fetch(`${baseUrl}${path}`, {+ method: opts.method ?? 'POST',+ headers: {+ authorization: `Bearer ${opts.token}`,+ 'content-type': 'application/json',+ },+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),+ })+ const text = await response.text()+ let body: any = null+ try { body = text ? JSON.parse(text) : null } catch { body = text }+ return { status: response.status, body }+}++async function seedAgent(companyId?: string, agentId?: string): Promise<{+ companyId: string+ agentId: string+ token: string+}> {+ const seeded = await seedCompanyWithAgent({ companyId, agentId })+ return {+ companyId: seeded.companyId,+ agentId: seeded.agentId,+ token: signAgentToken({ agentId: seeded.agentId, companyId: seeded.companyId }),+ }+}++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', $3, $4::jsonb)`,+ [conversationId, companyId, `Runtime auth ${conversationId}`, JSON.stringify(members)],+ )+ return conversationId+}++async function seedMessage(args: {+ conversationId: string+ companyId: string+ authorId: string+ body: string+ kind?: 'text' | 'system'+ deliveryRecipientId?: string | null+}): Promise<string> {+ const id = `m-${randomUUID()}`+ await pool.query(+ `INSERT INTO messages+ (id, conversation_id, author_id, kind, body, sequence, company_id, delivery_recipient_id)+ VALUES ($1,$2,$3,$4,$5,1,$6,$7)`,+ [+ id, args.conversationId, args.authorId, args.kind ?? 'text', args.body,+ args.companyId, args.deliveryRecipientId ?? null,+ ],+ )+ await pool.query(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE+ SET next_sequence = GREATEST(conversation_counters.next_sequence, 2)`,+ [args.conversationId],+ )+ return id+}++async function waitForBlockedQuery(pattern: string, minimum = 1): Promise<void> {+ for (let attempt = 0; attempt < 300; attempt++) {+ const { rows } = await pool.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count+ FROM pg_stat_activity+ WHERE datname = current_database()+ AND pid <> pg_backend_pid()+ AND wait_event_type = 'Lock'+ AND query ILIKE $1`,+ [pattern],+ )+ if ((rows[0]?.count ?? 0) >= minimum) return+ await delay(10)+ }+ throw new Error(`query never reached the expected row lock: ${pattern}`)+}++async function waitForExternalBlockedQuery(+ observer: Client,+ pattern: string,+ minimum = 1,+): Promise<void> {+ for (let attempt = 0; attempt < 500; attempt++) {+ const { rows } = await observer.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count+ FROM pg_stat_activity+ WHERE datname = current_database()+ AND pid <> pg_backend_pid()+ AND wait_event_type = 'Lock'+ AND query ILIKE $1`,+ [pattern],+ )+ if ((rows[0]?.count ?? 0) >= minimum) return+ await delay(10)+ }+ throw new Error(`query never reached ${minimum} blocked sessions: ${pattern}`)+}++async function withTimeout<T>(promise: Promise<T>, label: string, timeoutMs = 10_000): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ promise,+ new Promise<T>((_resolve, reject) => {+ timer = setTimeout(() => reject(new Error(`timed out waiting for ${label}`)), timeoutMs)+ }),+ ])+ } finally {+ if (timer) clearTimeout(timer)+ }+}++test('[integration] runtime notices: a queued kick wins before notice authorization and leaves no notice row', async () => {+ const actor = await seedAgent(undefined, `agent-actor-${randomUUID().slice(0, 6)}`)+ const target = await seedAgent(actor.companyId, `agent-target-${randomUUID().slice(0, 6)}`)+ const peer = await seedAgent(actor.companyId, `agent-peer-${randomUUID().slice(0, 6)}`)+ const conversationId = await seedGroup(actor.companyId, [actor.agentId, target.agentId, peer.agentId])+ const noticeText = `must-not-land-${randomUUID()}`+ const holder = await pool.connect()+ let holderFinished = false+ let kickPromise: ReturnType<typeof runCli> | undefined+ let noticePromise: ReturnType<typeof call> | undefined++ try {+ await holder.query('BEGIN')+ await holder.query(`SELECT id FROM conversations WHERE id = $1 FOR UPDATE`, [conversationId])++ // 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 -%')++ // The notice request passes JWT validation, then blocks on the target's+ // participant row behind the already-queued kick transaction.+ noticePromise = call('/runtime/notices', {+ token: target.token,+ body: {+ conversationId,+ noticeKind: 'race-probe',+ text: noticeText,+ dedupeKey: `race-${randomUUID()}`,+ dedupeTtlSec: 60,+ },+ })+ await waitForBlockedQuery('%SELECT id FROM participants%FOR SHARE%')++ await holder.query('COMMIT')+ holderFinished = true+ const [kick, notice] = await Promise.all([kickPromise, noticePromise])+ assert.equal(kick.ok, true, kick.text)+ assert.equal(notice.status, 403, JSON.stringify(notice.body))+ assert.match(String(notice.body?.error ?? ''), /not a member/i)++ const { rows } = await pool.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count+ FROM messages+ WHERE conversation_id = $1+ AND kind = 'system'+ AND body::jsonb ->> 'noticeKind' = 'race-probe'`,+ [conversationId],+ )+ assert.equal(rows[0]?.count, 0, 'the rejected request inserted a runtime notice')+ } finally {+ if (!holderFinished) await holder.query('ROLLBACK').catch(() => {})+ holder.release()+ await Promise.allSettled([kickPromise, noticePromise].filter(Boolean) as Promise<unknown>[])+ }+})++test('[integration] runtime CLI: 20 cold document reads do not self-exhaust the pool and offboarding advances', async () => {+ const agent = await seedAgent()+ const documentId = `doc_${randomUUID().replace(/-/g, '').slice(0, 16)}`+ await pool.query(+ `INSERT INTO documents (id, company_id, title, created_by)+ VALUES ($1, $2, 'Cold pool probe', $3)`,+ [documentId, agent.companyId, agent.agentId],+ )++ // These clients intentionally sit outside the application's max=20 pool.+ // ACCESS EXCLUSIVE pauses each command only after cmdDoc has taken its+ // participant lock and checked out a pool slot, making the exhaustion+ // schedule deterministic instead of depending on local query timing.+ const locker = new Client({ connectionString: env.DATABASE_URL })+ const observer = new Client({ connectionString: env.DATABASE_URL })+ const offboarder = new Client({ connectionString: env.DATABASE_URL })+ const commandPromises: Array<ReturnType<typeof call>> = []+ let offboardPromise: Promise<{ rowCount: number | null }> | undefined+ let lockerFinished = false++ await Promise.all([locker.connect(), observer.connect(), offboarder.connect()])+ try {+ await locker.query('BEGIN')+ await locker.query('LOCK TABLE documents IN ACCESS EXCLUSIVE MODE')++ for (let i = 0; i < 20; i++) {+ commandPromises.push(call('/runtime/cli', {+ token: agent.token,+ body: { argv: ['doc', 'read', documentId, '--json'] },+ }))+ }+ await waitForExternalBlockedQuery(observer, '%FROM documents WHERE id = $1 LIMIT 1%', 20)++ offboardPromise = offboarder.query(+ `UPDATE participants SET departed_at = NOW()+ WHERE id = $1 AND company_id = $2 AND departed_at IS NULL`,+ [agent.agentId, agent.companyId],+ )+ await waitForExternalBlockedQuery(observer, '%UPDATE participants SET departed_at = NOW()%')++ await locker.query('COMMIT')+ lockerFinished = true+ const responses = await withTimeout(+ Promise.all(commandPromises),+ '20 runtime document reads',+ )+ const offboard = await withTimeout(offboardPromise, 'offboarding after document reads')++ assert.equal(offboard.rowCount, 1)+ assert.equal(responses.length, 20)+ for (const [index, response] of responses.entries()) {+ assert.equal(response.status, 200, `request ${index}: ${JSON.stringify(response.body)}`)+ assert.equal(response.body?.ok, true, `request ${index}: ${JSON.stringify(response.body)}`)+ assert.match(String(response.body?.text ?? ''), /Cold pool probe/)+ }++ const stale = await call('/runtime/cli', {+ token: agent.token,+ body: { argv: ['doc', 'read', documentId] },+ })+ assert.equal(stale.status, 403, 'offboarded runtime token remained usable')+ } finally {+ if (!lockerFinished) await locker.query('ROLLBACK').catch(() => {})+ await Promise.allSettled(commandPromises)+ if (offboardPromise) await Promise.allSettled([offboardPromise])+ await Promise.all([+ locker.end().catch(() => {}),+ observer.end().catch(() => {}),+ offboarder.end().catch(() => {}),+ ])+ }+})++test('[integration] document rooms reserve one connection across snapshot and tail hydration', async () => {+ const agent = await seedAgent()+ const documentIds = Array.from({ length: 20 }, () => `doc_${randomUUID().replace(/-/g, '').slice(0, 16)}`)+ for (const [index, documentId] of documentIds.entries()) {+ await pool.query(+ `INSERT INTO documents (id, company_id, title, created_by)+ VALUES ($1, $2, $3, $4)`,+ [documentId, agent.companyId, `Hydration lease ${index}`, agent.agentId],+ )+ }++ const snapshotLocker = new Client({ connectionString: env.DATABASE_URL })+ const participantLocker = new Client({ connectionString: env.DATABASE_URL })+ const observer = new Client({ connectionString: env.DATABASE_URL })+ const hydrationPromises: Array<ReturnType<typeof subscribe>> = []+ const cliPromises: Array<ReturnType<typeof call>> = []+ let snapshotReleased = false+ let participantsReleased = false++ await Promise.all([snapshotLocker.connect(), participantLocker.connect(), observer.connect()])+ try {+ await snapshotLocker.query('BEGIN')+ await snapshotLocker.query('LOCK TABLE document_snapshots IN ACCESS EXCLUSIVE MODE')+ await participantLocker.query('BEGIN')+ await participantLocker.query('LOCK TABLE participants IN ACCESS EXCLUSIVE MODE')++ for (const [index, documentId] of documentIds.entries()) {+ hydrationPromises.push(subscribe(documentId, agent.companyId, {+ originId: `lease-probe-${index}`,+ onUpdate: () => {},+ onAwareness: () => {},+ }))+ }+ await waitForExternalBlockedQuery(observer, '%FROM document_snapshots%', 20)++ // These requests queue behind the 20 hydration leases. Once they receive+ // a slot they intentionally block on `participants`; a buggy hydration+ // that releases its client after the snapshot would let these requests+ // consume every slot before the tail queries can run.+ for (const documentId of documentIds) {+ cliPromises.push(call('/runtime/cli', {+ token: agent.token,+ body: { argv: ['doc', 'read', documentId, '--json'] },+ }))+ }+ for (let attempt = 0; attempt < 500 && pool.waitingCount < 20; attempt++) await delay(10)+ assert.ok(pool.waitingCount >= 20, `expected queued CLI requests, got ${pool.waitingCount}`)++ await snapshotLocker.query('COMMIT')+ snapshotReleased = true+ const hydrated = await withTimeout(+ Promise.all(hydrationPromises),+ '20 snapshot+tail hydrations while CLI requests are queued',+ 5_000,+ )+ assert.equal(hydrated.length, 20)+ await waitForExternalBlockedQuery(observer, '%FROM participants%', 20)++ await participantLocker.query('COMMIT')+ participantsReleased = true+ const responses = await withTimeout(Promise.all(cliPromises), 'queued document reads')+ for (const [index, response] of responses.entries()) {+ assert.equal(response.status, 200, `request ${index}: ${JSON.stringify(response.body)}`)+ assert.equal(response.body?.ok, true, `request ${index}: ${JSON.stringify(response.body)}`)+ }+ } finally {+ if (!snapshotReleased) await snapshotLocker.query('ROLLBACK').catch(() => {})+ if (!participantsReleased) await participantLocker.query('ROLLBACK').catch(() => {})+ await Promise.allSettled([...hydrationPromises, ...cliPromises])+ await Promise.all([+ snapshotLocker.end().catch(() => {}),+ participantLocker.end().catch(() => {}),+ observer.end().catch(() => {}),+ ])+ }+})++test('[integration] a failed document hydration is evicted so a corrected row can retry', async () => {+ const agent = await seedAgent()+ const documentId = `doc_${randomUUID().replace(/-/g, '').slice(0, 16)}`+ await pool.query(+ `INSERT INTO documents (id, company_id, title, created_by)+ VALUES ($1, $2, 'Retry hydration', $3)`,+ [documentId, agent.companyId, agent.agentId],+ )+ await pool.query(+ `INSERT INTO document_snapshots+ (document_id, state_bytes, snapshot_at_update_id, updated_at)+ VALUES ($1, $2, 0, NOW())`,+ [documentId, Buffer.from([0xff, 0xff, 0xff])],+ )++ await assert.rejects(readDocumentText(documentId, agent.companyId))+ await pool.query(`DELETE FROM document_snapshots WHERE document_id = $1`, [documentId])+ assert.equal(await readDocumentText(documentId, agent.companyId), '')+})++test('[integration] CLI document change events are published only after commit', async () => {+ const agent = await seedAgent()+ const observer = new Client({ connectionString: env.DATABASE_URL })+ const subscriber = redis.duplicate({ enableOfflineQueue: true, maxRetriesPerRequest: null })+ await observer.connect()+ await subscriber.subscribe(CH_DOCS)++ type ChangedEvent = {+ type: 'doc.changed'+ kind: 'document.created' | 'document.updated' | 'document.deleted'+ companyId: string+ documentId: string+ actorId: string+ }+ const observeNext = (+ kind: ChangedEvent['kind'],+ inspect: (event: ChangedEvent) => Promise<void>,+ ): Promise<ChangedEvent> => new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ subscriber.off('message', onMessage)+ reject(new Error(`timed out waiting for ${kind}`))+ }, 5_000)+ const onMessage = (channel: string, payload: string) => {+ if (channel !== CH_DOCS) return+ let event: ChangedEvent+ try { event = JSON.parse(payload) as ChangedEvent } catch { return }+ if (+ event.type !== 'doc.changed'+ || event.kind !== kind+ || event.companyId !== agent.companyId+ || event.actorId !== agent.agentId+ ) return+ clearTimeout(timer)+ subscriber.off('message', onMessage)+ void inspect(event).then(() => resolve(event), reject)+ }+ subscriber.on('message', onMessage)+ })++ try {+ const createObserved = observeNext('document.created', async (event) => {+ const { rows } = await observer.query<{ title: string }>(+ `SELECT title FROM documents WHERE id = $1`,+ [event.documentId],+ )+ assert.deepEqual(rows, [{ title: 'Committed document' }])+ })+ const created = await runCli(['--as', agent.agentId, 'doc', 'create', 'Committed document'])+ assert.equal(created.ok, true, created.text)+ const createEvent = await createObserved++ const renameObserved = observeNext('document.updated', async (event) => {+ assert.equal(event.documentId, createEvent.documentId)+ const { rows } = await observer.query<{ title: string }>(+ `SELECT title FROM documents WHERE id = $1`,+ [event.documentId],+ )+ assert.deepEqual(rows, [{ title: 'Committed rename' }])+ })+ const renamed = await runCli([+ '--as', agent.agentId, 'doc', 'rename', createEvent.documentId, 'Committed rename',+ ])+ assert.equal(renamed.ok, true, renamed.text)+ await renameObserved++ const deleteObserved = observeNext('document.deleted', async (event) => {+ assert.equal(event.documentId, createEvent.documentId)+ const { rows } = await observer.query(`SELECT 1 FROM documents WHERE id = $1`, [event.documentId])+ assert.equal(rows.length, 0)+ })+ const deleted = await runCli(['--as', agent.agentId, 'doc', 'delete', createEvent.documentId])+ assert.equal(deleted.ok, true, deleted.text)+ await deleteObserved+ } finally {+ await subscriber.unsubscribe(CH_DOCS).catch(() => {})+ await subscriber.quit().catch(() => {})+ await observer.end().catch(() => {})+ }+})++test('[integration] runtime notices: concurrent same-key requests commit exactly one durable notice', async () => {+ const agent = await seedAgent()+ const conversationId = await seedGroup(agent.companyId, [agent.agentId])+ const dedupeKey = `same-${randomUUID()}`+ const body = {+ conversationId,+ noticeKind: 'same-key',+ text: 'post once',+ dedupeKey,+ dedupeTtlSec: 60,+ }++ const responses = await Promise.all([+ call('/runtime/notices', { token: agent.token, body }),+ call('/runtime/notices', { token: agent.token, body }),+ ])+ assert.deepEqual(responses.map((response) => response.status), [200, 200])+ assert.deepEqual(+ responses.map((response) => response.body?.posted).sort(),+ [false, true],+ )++ const { rows } = await pool.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count+ FROM messages+ WHERE conversation_id = $1+ AND kind = 'system'+ AND body::jsonb ->> 'noticeKind' = 'same-key'`,+ [conversationId],+ )+ assert.equal(rows[0]?.count, 1)+})++test('[integration] runtime notices: the same dedupe key is independent across tenants', async () => {+ const tenantA = await seedAgent()+ const tenantB = await seedAgent()+ const conversationA = await seedGroup(tenantA.companyId, [tenantA.agentId])+ const conversationB = await seedGroup(tenantB.companyId, [tenantB.agentId])+ const dedupeKey = `shared-${randomUUID()}`++ const [responseA, responseB] = await Promise.all([+ call('/runtime/notices', {+ token: tenantA.token,+ body: {+ conversationId: conversationA,+ noticeKind: 'cross-tenant-key',+ text: 'tenant A',+ dedupeKey,+ dedupeTtlSec: 60,+ },+ }),+ call('/runtime/notices', {+ token: tenantB.token,+ body: {+ conversationId: conversationB,+ noticeKind: 'cross-tenant-key',+ text: 'tenant B',+ dedupeKey,+ dedupeTtlSec: 60,+ },+ }),+ ])+ assert.equal(responseA.status, 200, JSON.stringify(responseA.body))+ assert.equal(responseB.status, 200, JSON.stringify(responseB.body))+ assert.equal(responseA.body?.posted, true)+ assert.equal(responseB.body?.posted, true)++ const { rows } = await pool.query<{ company_id: string; count: number }>(+ `SELECT company_id, COUNT(*)::int AS count+ FROM messages+ WHERE conversation_id = ANY($1::text[])+ AND body::jsonb ->> 'noticeKind' = 'cross-tenant-key'+ GROUP BY company_id+ ORDER BY company_id`,+ [[conversationA, conversationB]],+ )+ const expected: Array<[string, number]> = [+ [tenantA.companyId, 1],+ [tenantB.companyId, 1],+ ]+ expected.sort(([a], [b]) => a.localeCompare(b))+ assert.deepEqual(rows.map((row): [string, number] => [row.company_id, row.count]), expected)+})++test('[integration] runtime auxiliary routes reject a same-tenant conversation non-member before side effects', async () => {+ const outsider = await seedAgent()+ const member = await seedAgent(outsider.companyId)+ const conversationId = await seedGroup(outsider.companyId, [member.agentId])+ const messageId = await seedMessage({+ conversationId,+ companyId: outsider.companyId,+ authorId: member.agentId,+ body: 'private',+ })+ const typingThrottleKey = `cumora:typ:${outsider.agentId}:${conversationId}`+ const reverseThinkingKey = `cumora:agent-thinking-convos:${outsider.agentId}`+ const claimKey = worklogKey(conversationId)+ const claimField = worklogField('web-search', 'private subject')+ const existingClaim = JSON.stringify({+ agentId: outsider.agentId,+ taskType: 'web-search',+ subject: 'private subject',+ startedAt: Date.now(),+ })+ await redis.zadd(thinkingKey(conversationId), 123, outsider.agentId)+ await redis.expire(thinkingKey(conversationId), 60)+ await redis.hset(claimKey, claimField, existingClaim)+ await redis.expire(claimKey, 60)++ try {+ const probes = [+ ['typing', '/runtime/typing', 'POST', { conversationId, done: false }],+ ['thinking mark', '/runtime/thinking/mark', 'POST', { conversationIds: [conversationId], ttlSec: 60 }],+ ['thinking unmark', '/runtime/thinking/unmark', 'POST', { conversationIds: [conversationId] }],+ ['thinking peek', `/runtime/thinking/peek?conversationId=${encodeURIComponent(conversationId)}`, 'GET', undefined],+ ['worklog claim', '/runtime/worklog/claim', 'POST', {+ scopeKey: conversationId, taskType: 'web-search', subject: 'private subject', ttlSec: 60,+ }],+ ['worklog release', '/runtime/worklog/release', 'POST', {+ scopeKey: conversationId, taskType: 'web-search', subject: 'private subject',+ }],+ ['worklog peek', `/runtime/worklog/peek?scopeKey=${encodeURIComponent(conversationId)}`, 'GET', undefined],+ ['mark read', '/runtime/conversation/mark-read', 'POST', {+ conversationId, upToMessageId: messageId,+ }],+ ] as const++ for (const [label, path, method, body] of probes) {+ const response = await call(path, { token: outsider.token, method, body })+ assert.equal(response.status, 403, `${label}: ${JSON.stringify(response.body)}`)+ }++ assert.equal(await redis.get(typingThrottleKey), null, 'rejected typing request wrote its throttle key')+ assert.equal(await redis.get(reverseThinkingKey), null, 'rejected thinking request wrote its reverse index')+ assert.equal(await redis.zscore(thinkingKey(conversationId), outsider.agentId), '123', 'rejected unmark changed the claim')+ assert.equal(await redis.hget(claimKey, claimField), existingClaim, 'rejected release changed the worklog')+ const { rows } = await pool.query(+ `SELECT 1 FROM conversation_reads WHERE user_id = $1 AND conversation_id = $2`,+ [outsider.agentId, conversationId],+ )+ assert.equal(rows.length, 0, 'rejected mark-read advanced a cursor')+ } finally {+ await redis.del(typingThrottleKey, reverseThinkingKey, thinkingKey(conversationId), claimKey)+ }+})++test('[integration] runtime mark-read binds the message to the requested conversation', async () => {+ const agent = await seedAgent()+ const peer = await seedAgent(agent.companyId)+ const readableConversation = await seedGroup(agent.companyId, [agent.agentId, peer.agentId])+ const otherConversation = await seedGroup(agent.companyId, [peer.agentId])+ const otherMessage = await seedMessage({+ conversationId: otherConversation,+ companyId: agent.companyId,+ authorId: peer.agentId,+ body: 'belongs elsewhere',+ })++ const response = await call('/runtime/conversation/mark-read', {+ token: agent.token,+ body: { conversationId: readableConversation, upToMessageId: otherMessage },+ })+ assert.equal(response.status, 403, JSON.stringify(response.body))+ const { rows } = await pool.query(+ `SELECT 1 FROM conversation_reads WHERE user_id = $1`,+ [agent.agentId],+ )+ assert.equal(rows.length, 0)+})++test('[integration] runtime mark-read accepts only the kicked agent\'s durable departure row', async () => {+ const actor = await seedAgent()+ const target = await seedAgent(actor.companyId)+ const peer = await seedAgent(actor.companyId)+ const conversationId = await seedGroup(actor.companyId, [actor.agentId, target.agentId, peer.agentId])+ const ordinaryMessage = await seedMessage({+ conversationId,+ companyId: actor.companyId,+ authorId: peer.agentId,+ body: 'ordinary history',+ })++ const kick = await runCli(['--as', actor.agentId, 'kick', conversationId, target.agentId])+ assert.equal(kick.ok, true, kick.text)+ const { rows: departures } = await pool.query<{ id: string }>(+ `SELECT id FROM messages+ WHERE conversation_id = $1+ AND kind = 'system'+ AND delivery_recipient_id = $2+ ORDER BY created_at DESC, id DESC+ LIMIT 1`,+ [conversationId, target.agentId],+ )+ const departureMessage = departures[0]?.id+ assert.ok(departureMessage, 'kick did not persist a durable departure recipient')++ const ordinary = await call('/runtime/conversation/mark-read', {+ token: target.token,+ body: { conversationId, upToMessageId: ordinaryMessage },+ })+ assert.equal(ordinary.status, 403, 'departure exception leaked to an ordinary message')++ const departure = await call('/runtime/conversation/mark-read', {+ token: target.token,+ body: { conversationId, upToMessageId: departureMessage },+ })+ assert.equal(departure.status, 200, JSON.stringify(departure.body))++ // A retry is harmless and does not create a second cursor row.+ const retry = await call('/runtime/conversation/mark-read', {+ token: target.token,+ body: { conversationId, upToMessageId: departureMessage },+ })+ assert.equal(retry.status, 200, JSON.stringify(retry.body))+ const { rows } = await pool.query<{ last_read_message_id: string }>(+ `SELECT last_read_message_id FROM conversation_reads+ WHERE user_id = $1 AND conversation_id = $2`,+ [target.agentId, conversationId],+ )+ assert.deepEqual(rows, [{ last_read_message_id: departureMessage }])+})diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.tsindex d36d4e5..9cb91d4 100644--- a/server/src/__integration__/runtime-server.test.ts+++ b/server/src/__integration__/runtime-server.test.ts@@ -318,6 +318,126 @@ test('[integration] runtime: /inbox-triage/payload rejects a stale token beforeassert.match(String(r.body?.error ?? ''), /token tenant/i)})+test('[integration] runtime: a current token cannot use a stale member id to read or write the old tenant through /cli', async () => {+ const originalTenant = await seedAgent()+ const currentTenant = await seedAgent()+ const oldPeerId = `a-old-peer-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO participants (id, company_id, kind, name, role, initial, avatar_bg, status)+ VALUES ($1,$2,'agent',$1,'peer','P','#abcdef','avail')`,+ [oldPeerId, originalTenant.companyId],+ )+ const oldConversationId = await seedContextConversation({+ companyId: originalTenant.companyId,+ members: [originalTenant.agentId],+ authorId: originalTenant.agentId,+ body: 'old-runtime-tenant-secret',+ })+ await pool.query(+ `UPDATE conversations SET topic = 'old-runtime-topic-secret' WHERE id = $1`,+ [oldConversationId],+ )+ const { rows: oldMessageRows } = await pool.query<{ id: string }>(+ `SELECT id FROM messages WHERE conversation_id = $1 AND kind = 'text' LIMIT 1`,+ [oldConversationId],+ )+ const oldMessageId = oldMessageRows[0].id+ const oldPollId = `m-${randomUUID()}`+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, poll, company_id)+ VALUES ($1,$2,$3,'poll','old-runtime-poll-secret',2,$4::jsonb,$5)`,+ [+ oldPollId,+ oldConversationId,+ originalTenant.agentId,+ JSON.stringify({+ question: 'old-runtime-poll-secret', mode: 'single',+ options: [{ id: 'opt-one', text: 'one' }, { id: 'opt-two', text: 'two' }],+ expiresAt: null, closedAt: null, closedReason: null,+ }),+ originalTenant.companyId,+ ],+ )++ 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 currentToken = signAgentToken({+ agentId: originalTenant.agentId,+ companyId: currentTenant.companyId,+ })++ for (const argv of [+ ['conversations', '--json'],+ ['messages', oldConversationId, '--json'],+ ['members', oldConversationId, '--json'],+ ['glance', oldConversationId, '--json'],+ ['topic', oldConversationId],+ ['search', 'old-runtime', '--json'],+ ['react', oldMessageId, '👀'],+ ['poll', 'show', oldPollId],+ ['poll', 'vote', oldPollId, 'opt-one'],+ ['poll', 'close', oldPollId],+ ['poll', 'create', oldConversationId, 'must-not-land', 'one', 'two'],+ ['dm', oldPeerId, 'forbidden', 'must-not-land'],+ ['pull-group', 'forbidden', '--members', oldPeerId, '--reason', 'must-not-land', '--say', 'must-not-land'],+ ['reply', oldConversationId, 'must-not-land'],+ ['topic-set', oldConversationId, 'must-not-land'],+ ['rename', oldConversationId, 'must-not-land'],+ ]) {+ const r = await call('/runtime/cli', { token: currentToken, body: { argv } })+ assert.equal(r.status, 200, argv.join(' '))+ assert.doesNotMatch(+ String(r.body?.text ?? ''),+ /old-runtime-(tenant|topic|poll)-secret/,+ argv.join(' '),+ )+ }++ const { rows } = await pool.query<{ body: string; topic: string | null; title: string }>(+ `SELECT m.body, c.topic, c.title+ FROM conversations c+ JOIN messages m ON m.conversation_id = c.id AND m.kind = 'text'+ WHERE c.id = $1+ ORDER BY m.sequence ASC`,+ [oldConversationId],+ )+ assert.deepEqual(rows, [{+ body: 'old-runtime-tenant-secret',+ topic: 'old-runtime-topic-secret',+ title: `Context ${oldConversationId}`,+ }])+ const { rows: sideEffects } = await pool.query<{+ reactions: number; votes: number; message_count: number; closed_at: string | null+ }>(+ `SELECT+ (SELECT COUNT(*)::int FROM message_reactions WHERE message_id = $1) AS reactions,+ (SELECT COUNT(*)::int FROM poll_votes WHERE message_id = $2) AS votes,+ (SELECT COUNT(*)::int FROM messages WHERE conversation_id = $3) AS message_count,+ (SELECT poll->>'closedAt' FROM messages WHERE id = $2) AS closed_at`,+ [oldMessageId, oldPollId, oldConversationId],+ )+ assert.deepEqual(sideEffects[0], {+ reactions: 0, votes: 0, message_count: 2, closed_at: null,+ })+ const forbiddenConversations = await pool.query(+ `SELECT 1 FROM conversations+ WHERE company_id = $1+ AND (+ pulled_by ->> 'agentId' = $2+ OR (+ kind = 'direct'+ AND members @> to_jsonb(ARRAY[$2::text])+ AND members @> to_jsonb(ARRAY[$3::text])+ )+ )`,+ [currentTenant.companyId, originalTenant.agentId, oldPeerId],+ )+ assert.equal(forbiddenConversations.rowCount, 0)+})+test('[integration] runtime: /cli rejects email server-path attachments before storage or mail side effects', async () => {const { token } = await seedAgent()const root = await mkdtemp(join(tmpdir(), 'cumora-email-attachment-'))diff --git a/server/src/__tests__/email.test.ts b/server/src/__tests__/email.test.tsindex cf9fb1d..150db8c 100644--- a/server/src/__tests__/email.test.ts+++ b/server/src/__tests__/email.test.ts@@ -19,6 +19,7 @@ import {formatAddress,normalizeMessageId,computeAgentAddress,+ sendViaProvider,} from '../email.js'/* ============================== sanitizeSubject ============================ */@@ -207,3 +208,35 @@ test('computeAgentAddress strips dots from id portion', () => {// The slug separator remains the LAST dot only.assert.equal(addr.split('@')[0].split('.').length, 2, `expected exactly one dot separator, got: ${addr}`)})++test('sendViaProvider derives a stable Resend idempotency key from Message-ID', async () => {+ const savedFetch = globalThis.fetch+ const savedKey = process.env.RESEND_API_KEY+ const requestHeaders: Headers[] = []+ process.env.RESEND_API_KEY = 're_test_only'+ globalThis.fetch = (async (_input: string | URL | Request, init?: RequestInit) => {+ requestHeaders.push(new Headers(init?.headers))+ return new Response(JSON.stringify({ id: 'provider-test-id' }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ }) as typeof fetch+ try {+ const result = await sendViaProvider({+ from: '[email protected]',+ to: ['[email protected]'],+ subject: 'idempotent',+ text: 'body',+ messageId: '[email protected]',+ })+ assert.equal(result.ok, true)+ assert.equal(+ requestHeaders[0]?.get('idempotency-key'),+ 'cumora-email/[email protected]',+ )+ } finally {+ globalThis.fetch = savedFetch+ if (savedKey === undefined) delete process.env.RESEND_API_KEY+ else process.env.RESEND_API_KEY = savedKey+ }+})diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.tsindex 29c1f08..4ab7867 100644--- a/server/src/agents/cli.ts+++ b/server/src/agents/cli.ts@@ -10,6 +10,7 @@*/import { pool } from '../db/pool.js'+import type { PoolClient } from 'pg'import { storage, freshenAttachmentUrl, type StoredAttachment } from '../storage.js'import { env } from '../env.js'import type { CliResult, CliSideEffect } from './cli-result.js'@@ -48,11 +49,86 @@ function err(text: string, code = 1): CliResult {* /agents POST), so id-only lookup returns the single correct row. */async function agentCompany(agentId: string): Promise<string | null> {const { rows } = await pool.query<{ company_id: string | null }>(- `SELECT company_id FROM participants WHERE id = $1 LIMIT 1`, [agentId],+ `SELECT company_id FROM participants+ WHERE id = $1 AND kind = 'agent' AND departed_at IS NULL+ LIMIT 1`,+ [agentId],)return rows[0]?.company_id ?? null}+/** Keep an active participant's tenant assignment stable for a command whose+ * work spans multiple SQL statements (or a provider network call). Membership+ * mutations, offboarding, and tenant moves all take a conflicting participant+ * row lock, so they serialize before or after this command instead of changing+ * authorization midway through it. */+async function withActiveParticipantLock<T>(args: {+ participantId: string+ companyId: string+ kind?: 'agent' | 'human'+ run: (client: PoolClient) => Promise<T>+}): Promise<T | null> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const params: unknown[] = [args.participantId, args.companyId]+ const kindPredicate = args.kind ? `AND kind = $3` : `AND kind IN ('agent', 'human')`+ if (args.kind) params.push(args.kind)+ const active = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ ${kindPredicate} AND departed_at IS NULL+ FOR SHARE`,+ params,+ )+ if (!active.rowCount) {+ await client.query('ROLLBACK')+ return null+ }+ const result = await args.run(client)+ await client.query('COMMIT')+ return result+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}++async function withConversationActorLock<T>(args: {+ participantId: string+ companyId: string+ conversationId: string+ kind?: 'agent' | 'human'+ conversationKind?: string+ run: (client: PoolClient) => Promise<T>+}): Promise<T | null> {+ return withActiveParticipantLock({+ participantId: args.participantId,+ companyId: args.companyId,+ kind: args.kind,+ run: async (client) => {+ const params: unknown[] = [args.conversationId, args.companyId, args.participantId]+ let kindPredicate = ''+ if (args.conversationKind) {+ params.push(args.conversationKind)+ kindPredicate = `AND kind = $4`+ }+ const authorized = await client.query(+ `SELECT id FROM conversations+ WHERE id = $1 AND company_id = $2+ AND members @> to_jsonb(ARRAY[$3::text])+ ${kindPredicate}+ FOR UPDATE`,+ params,+ )+ if (!authorized.rowCount) return null+ return args.run(client)+ },+ })+}+/* ============== argv parsing ============== */import { parseArgs, unescapeChat, joinBodyArgs, tokenize, type ParsedArgs } from './cli-parse.js'@@ -409,12 +485,17 @@ EXAMPLES:async function cmdWhoami(parsed: ParsedArgs): Promise<CliResult> {const id = resolveAs(parsed)+ const companyId = await agentCompany(id)+ if (!companyId) return err(`cannot resolve active company for ${id}`)const { rows } = await pool.query<{id: string; kind: string; name: string; role: string | null;status: string; bio: string | null; tools: string[] | null}>(- `SELECT id, kind, name, role, status, bio, tools FROM participants WHERE id = $1`,- [id],+ `SELECT id, kind, name, role, status, bio, tools+ FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL`,+ [id, companyId],)const p = rows[0]if (!p) return err(`unknown participant: ${id}`)@@ -422,9 +503,17 @@ async function cmdWhoami(parsed: ParsedArgs): Promise<CliResult> {const { rows: convos } = await pool.query<{ id: string; title: string; kind: string }>(`SELECT id, title, kind FROM conversations- WHERE members @> to_jsonb(ARRAY[$1::text])+ WHERE company_id = $2+ AND members @> to_jsonb(ARRAY[$1::text])+ AND EXISTS (+ SELECT 1 FROM participants requester+ WHERE requester.id = $1+ AND requester.company_id = conversations.company_id+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ )ORDER BY updated_at DESC`,- [id],+ [id, companyId],)const lines = [`id: ${p.id}`,@@ -474,21 +563,29 @@ async function cmdParticipants(parsed: ParsedArgs): Promise<CliResult> {async function cmdConversations(parsed: ParsedArgs, kindFilter?: 'group' | 'direct'): Promise<CliResult> {const me = resolveAs(parsed)- const params: unknown[] = [me]+ const companyId = await agentCompany(me)+ if (!companyId) return err(`cannot resolve active company for ${me}`)+ const params: unknown[] = [me, companyId]let kindWhere = ''if (kindFilter) {params.push(kindFilter)- kindWhere = `AND kind = $2`+ kindWhere = `AND c.kind = $3`}const { rows } = await pool.query<{id: string; kind: string; title: string; subtitle: string | null;members: string[]; tag: string | null;updated_at: string; pulled_by: { agentId?: string } | null}>(- `SELECT id, kind, title, subtitle, members, tag, updated_at, pulled_by- FROM conversations- WHERE members @> to_jsonb(ARRAY[$1::text]) ${kindWhere}- ORDER BY updated_at DESC`,+ `SELECT c.id, c.kind, c.title, c.subtitle, c.members, c.tag, c.updated_at, c.pulled_by+ FROM conversations c+ JOIN participants requester+ ON requester.id = $1+ AND requester.company_id = c.company_id+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ WHERE c.company_id = $2+ AND c.members @> to_jsonb(ARRAY[$1::text]) ${kindWhere}+ ORDER BY c.updated_at DESC`,params,)if (parsed.flags.json) return ok(JSON.stringify(rows, null, 2))@@ -509,19 +606,33 @@ async function cmdConversations(parsed: ParsedArgs, kindFilter?: 'group' | 'dire}async function cmdMembers(parsed: ParsedArgs): Promise<CliResult> {+ const me = resolveAs(parsed)+ const companyId = await agentCompany(me)+ if (!companyId) return err(`cannot resolve active company for ${me}`)const id = parsed.positional[0]if (!id) return err('usage: members <conversation_id>')const { rows } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1`,- [id],+ `SELECT c.members+ FROM conversations c+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ WHERE c.id = $1+ AND c.company_id = $3+ AND c.members @> to_jsonb(ARRAY[$2::text])`,+ [id, me, companyId],)if (!rows[0]) return err(`unknown conversation: ${id}`)const memberIds = rows[0].membersconst { rows: peeps } = await pool.query<{id: string; name: string; kind: string; role: string | null; status: string; avatar_url: string | null}>(- `SELECT id, name, kind, role, status, avatar_url FROM participants WHERE id = ANY($1::text[])`,- [memberIds],+ `SELECT id, name, kind, role, status, avatar_url+ FROM participants+ WHERE id = ANY($1::text[]) AND company_id = $2`,+ [memberIds, companyId],)if (parsed.flags.json) return ok(JSON.stringify(peeps, null, 2))const memberLines: string[] = []@@ -538,6 +649,9 @@ async function cmdMembers(parsed: ParsedArgs): Promise<CliResult> {}async function cmdMessages(parsed: ParsedArgs): Promise<CliResult> {+ const me = resolveAs(parsed)+ const companyId = await agentCompany(me)+ if (!companyId) return err(`cannot resolve active company for ${me}`)const id = parsed.positional[0]if (!id) return err('usage: messages <conversation_id> [--tail N] [--thread <root_id>]')const tail = Math.min(200, Math.max(1, Number(parsed.flags.tail ?? 20)))@@ -545,11 +659,11 @@ async function cmdMessages(parsed: ParsedArgs): Promise<CliResult> {// when an agent wants to focus on what's happening in one sub-discussion// before deciding how to respond.const threadRootId = parsed.flags.thread ? String(parsed.flags.thread) : null- const params: unknown[] = [id]+ const params: unknown[] = [id, me, companyId]let whereExtra = ''if (threadRootId) {params.push(threadRootId)- whereExtra = `AND quoted_message_id = $2`+ whereExtra = `AND m.quoted_message_id = $4`}params.push(tail)const limitParam = `$${params.length}`@@ -560,9 +674,21 @@ async function cmdMessages(parsed: ParsedArgs): Promise<CliResult> {quoted_message_id: string | null;quoted: { id: string; authorId: string; authorName: string; body: string } | null;}>(- `SELECT- id, author_id, kind, body, sequence, created_at, attachment, poll,- quoted_message_id,+ `WITH authorized_conversation AS MATERIALIZED (+ SELECT c.id+ FROM conversations c+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ WHERE c.id = $1+ AND c.company_id = $3+ AND c.members @> to_jsonb(ARRAY[$2::text])+ )+ SELECT+ m.id, m.author_id, m.kind, m.body, m.sequence, m.created_at, m.attachment, m.poll,+ m.quoted_message_id,(SELECT jsonb_build_object('id', qm.id,@@ -571,12 +697,14 @@ async function cmdMessages(parsed: ParsedArgs): Promise<CliResult> {'body', LEFT(qm.body, 240))FROM messages qm- WHERE qm.id = messages.quoted_message_id- AND qm.conversation_id = messages.conversation_id+ WHERE qm.id = m.quoted_message_id+ AND qm.conversation_id = m.conversation_id) AS quoted- FROM messages WHERE conversation_id = $1+ FROM messages m+ JOIN authorized_conversation authorized ON authorized.id = m.conversation_id+ WHERE TRUE${whereExtra}- ORDER BY sequence DESC LIMIT ${limitParam}`,+ ORDER BY m.sequence DESC LIMIT ${limitParam}`,params,)for (const row of rows) await freshenRowAttachment(row)@@ -587,7 +715,7 @@ async function cmdMessages(parsed: ParsedArgs): Promise<CliResult> {// this, the agent's typical flow `messages → reply` would HOLD on the// very tail it just fetched. Redis-only, fail-open, monotonic.if (inOrder.length > 0) {- await recordSeen(resolveAs(parsed), id, inOrder[inOrder.length - 1].sequence)+ await recordSeen(me, id, inOrder[inOrder.length - 1].sequence)}if (parsed.flags.json) return ok(JSON.stringify(inOrder, null, 2))if (inOrder.length === 0) {@@ -639,16 +767,28 @@ async function cmdThread(parsed: ParsedArgs): Promise<CliResult> {}async function cmdConvening(parsed: ParsedArgs): Promise<CliResult> {+ const me = resolveAs(parsed)+ const companyId = await agentCompany(me)+ if (!companyId) return err(`cannot resolve active company for ${me}`)const id = parsed.positional[0]if (!id) return err('usage: convening <conversation_id>')const { rows } = await pool.query<{pulled_by_id: string; pulled_at: string; headline_lead: string; headline_tail: string;subhead: string; who_and_why: unknown; reasoning: unknown; status: string}>(- `SELECT pulled_by_id, pulled_at, headline_lead, headline_tail, subhead,- who_and_why, reasoning, status- FROM convening_info WHERE conversation_id = $1`,- [id],+ `SELECT ci.pulled_by_id, ci.pulled_at, ci.headline_lead, ci.headline_tail, ci.subhead,+ ci.who_and_why, ci.reasoning, ci.status+ FROM convening_info ci+ JOIN conversations c ON c.id = ci.conversation_id+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ WHERE ci.conversation_id = $1+ AND c.company_id = $3+ AND c.members @> to_jsonb(ARRAY[$2::text])`,+ [id, me, companyId],)const c = rows[0]if (!c) return err(`no convening info for ${id}`)@@ -673,15 +813,18 @@ async function cmdConvening(parsed: ParsedArgs): Promise<CliResult> {}async function cmdSearch(parsed: ParsedArgs): Promise<CliResult> {+ const me = resolveAs(parsed)+ const companyId = await agentCompany(me)+ if (!companyId) return err(`cannot resolve active company for ${me}`)const query = parsed.positional[0]if (!query) return err('usage: search <query> [--in <convo_id>] [--limit N]')const inConvo = parsed.flags.in ? String(parsed.flags.in) : nullconst limit = Math.min(50, Math.max(1, Number(parsed.flags.limit ?? 10)))- const params: unknown[] = [`%${query}%`]+ const params: unknown[] = [me, companyId, `%${query}%`]let whereExtra = ''if (inConvo) {params.push(inConvo)- whereExtra = `AND m.conversation_id = $2`+ whereExtra = `AND m.conversation_id = $4`}params.push(limit)const limitParam = `$${params.length}`@@ -691,7 +834,15 @@ async function cmdSearch(parsed: ParsedArgs): Promise<CliResult> {}>(`SELECT m.id, m.conversation_id, m.author_id, m.body, m.created_at, m.attachmentFROM messages m- WHERE m.body ILIKE $1 ${whereExtra}+ JOIN conversations c ON c.id = m.conversation_id+ JOIN participants requester+ ON requester.id = $1+ AND requester.company_id = c.company_id+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ WHERE c.company_id = $2+ AND c.members @> to_jsonb(ARRAY[$1::text])+ AND m.body ILIKE $3 ${whereExtra}ORDER BY m.created_at DESC LIMIT ${limitParam}`,params,)@@ -711,11 +862,14 @@ async function cmdSearch(parsed: ParsedArgs): Promise<CliResult> {}async function cmdToolsLog(parsed: ParsedArgs): Promise<CliResult> {+ const me = resolveAs(parsed)+ const companyId = await agentCompany(me)+ if (!companyId) return err(`cannot resolve active company for ${me}`)const agent = parsed.flags.agent ? String(parsed.flags.agent) : nullconst limit = Math.min(50, Math.max(1, Number(parsed.flags.limit ?? 15)))- const params: unknown[] = []- let where = ''- if (agent) { params.push(agent); where = `WHERE agent_id = $1` }+ const params: unknown[] = [companyId]+ let where = 'WHERE company_id = $1'+ if (agent) { params.push(agent); where += ` AND agent_id = $2` }params.push(limit)const limitParam = `$${params.length}`const { rows } = await pool.query<{@@ -858,15 +1012,21 @@ async function loadInbox(agentId: string): Promise<InboxItem[]> {) AS quotedFROM messages mJOIN conversations c ON c.id = m.conversation_id+ JOIN participants requesting_agent+ ON requesting_agent.id = $1+ AND requesting_agent.company_id = c.company_id+ 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])- AND m.author_id <> $1+ WHERE (c.members @> to_jsonb(ARRAY[$1::text]) 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_readsWHERE user_id = $1 AND conversation_id = c.id),'1970-01-01T00:00:00Z'::timestamptz)AND (- c.kind = 'direct'+ m.delivery_recipient_id = $1+ OR c.kind = 'direct'OR NOT EXISTS (SELECT 1 FROM conversation_mutes muWHERE mu.user_id = $1 AND mu.conversation_id = c.id@@ -952,6 +1112,8 @@ async function cmdInbox(parsed: ParsedArgs): Promise<CliResult> {* on it, pick a different angle) instead of blurting the same thing. */async function cmdGlance(parsed: ParsedArgs): Promise<CliResult> {const me = resolveAs(parsed)+ const companyId = await agentCompany(me)+ if (!companyId) return err(`cannot resolve active company for ${me}`)const convoId = (typeof parsed.flags['conversation'] === 'string' ? parsed.flags['conversation'] : null)?? parsed.positional[0]if (!convoId) return err('usage: glance --conversation <id> (or: glance <id>)')@@ -970,11 +1132,18 @@ async function cmdGlance(parsed: ParsedArgs): Promise<CliResult> {m.kind, m.body, m.created_at, m.sequenceFROM messages mJOIN conversations c ON c.id = m.conversation_id+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULLLEFT JOIN participants p ON p.id = m.author_id AND p.company_id = c.company_idWHERE m.conversation_id = $1+ AND c.company_id = $3+ AND c.members @> to_jsonb(ARRAY[$2::text])ORDER BY m.created_at DESCLIMIT 12`,- [convoId],+ [convoId, me, companyId],)const recent = rows.reverse()@@ -1042,12 +1211,23 @@ async function cmdAck(parsed: ParsedArgs): Promise<CliResult> {}const convoId = parsed.positional[0]if (!convoId) return err('usage: ack <conversation_id> OR ack --all')- await pool.query(+ const activeAgentCompanyId = await agentCompany(me)+ const { rowCount } = await pool.query(`INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)- VALUES ($1, $2, NOW())+ SELECT $1, c.id, NOW()+ FROM conversations c+ JOIN participants requester+ ON requester.id = $1+ AND requester.company_id = c.company_id+ AND requester.kind IN ('agent', 'human')+ AND requester.departed_at IS NULL+ WHERE c.id = $2+ AND ($3::text IS NULL OR c.company_id = $3)+ AND c.members @> to_jsonb(ARRAY[$1::text])ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,- [me, convoId],+ [me, convoId, activeAgentCompanyId],)+ if (!rowCount) return err(`conversation ${convoId} not found or no longer authorized`)// Standing down — see the --all branch above.void clearHold(me, `reply:${convoId}`)return ok(`acked ${convoId}`)@@ -1102,31 +1282,31 @@ async function cmdMute(parsed: ParsedArgs): Promise<CliResult> {if (!conversation) return err(`conversation not found: ${conversationId}`)if (!conversation.members.includes(me)) return err(`you are not a member of ${conversationId}`)if (conversation.kind === 'direct') return err('direct conversations always deliver; mute a group instead')- const client = await pool.connect()- try {- await client.query('BEGIN')- await client.query(+ const muted = await withConversationActorLock({+ participantId: me,+ companyId,+ conversationId,+ kind: 'agent',+ run: async (client) => {+ await client.query(`INSERT INTO conversation_mutes (user_id, conversation_id, muted_at, muted_until)VALUES ($1, $2, NOW(), $3)ON CONFLICT (user_id, conversation_id)DO UPDATE SET muted_at = NOW(), muted_until = EXCLUDED.muted_until`,- [me, conversationId, until],- )- // Muting is a deliberate stand-down. Seal the current unread tail so- // following later resumes from that point instead of replaying a backlog.- await client.query(- `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)- VALUES ($1, $2, NOW())- ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,- [me, conversationId],- )- await client.query('COMMIT')- } catch (error) {- await client.query('ROLLBACK').catch(() => {})- throw error- } finally {- client.release()- }+ [me, conversationId, until],+ )+ // Muting is a deliberate stand-down. Seal the current unread tail so+ // following later resumes from that point instead of replaying a backlog.+ await client.query(+ `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)+ VALUES ($1, $2, NOW())+ ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,+ [me, conversationId],+ )+ return true+ },+ })+ if (!muted) return err(`conversation ${conversationId} is no longer authorized`)void clearHold(me, `reply:${conversationId}`)const expiry = until ? ` until ${until.toISOString()}` : ' until you follow it again'return ok(@@ -1142,12 +1322,19 @@ async function cmdFollow(parsed: ParsedArgs): Promise<CliResult> {if (!conversationId) return err('usage: follow <conversation_id>')const companyId = await agentCompany(me)if (!companyId) return err(`unknown agent ${me} (no company)`)- const { rowCount } = await pool.query(- `DELETE FROM conversation_mutes mu USING conversations c- WHERE mu.user_id = $1 AND mu.conversation_id = $2- AND c.id = mu.conversation_id AND c.company_id = $3`,- [me, conversationId, companyId],- )+ const followed = await withConversationActorLock({+ participantId: me,+ companyId,+ conversationId,+ kind: 'agent',+ run: (client) => client.query(+ `DELETE FROM conversation_mutes+ WHERE user_id = $1 AND conversation_id = $2`,+ [me, conversationId],+ ),+ })+ if (!followed) return err(`conversation ${conversationId} is no longer authorized`)+ const rowCount = followed.rowCountreturn ok(rowCount? `Following ${conversationId} again. New messages will resume normal inbox delivery.`: `${conversationId} was not muted; normal delivery is already active.`)@@ -1340,7 +1527,7 @@ async function cmdShip(parsed: ParsedArgs): Promise<CliResult> {// `agents/membership.ts` so the HTTP endpoints (POST /members,// POST /leave) and the agent CLI share one implementation. Importing// here re-exposes the names this file already used.-import { addConversationMember, postMembershipSystemMessage, removeConversationMember } from './membership.js'+import { addConversationMember, removeConversationMember } from './membership.js'async function cmdLeave(parsed: ParsedArgs): Promise<CliResult> {const me = resolveAs(parsed)@@ -1355,24 +1542,25 @@ async function cmdLeave(parsed: ParsedArgs): Promise<CliResult> {)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 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}`)- // Post the system message BEFORE updating members so the leaving- // agent's inbox (filtered by c.members @> [me]) still surfaces this- // final row in their next wake — that's how they "perceive" their own- // departure cleanly.- const systemMessage = await postMembershipSystemMessage({+ // 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+ // departure event.+ const mutation = await removeConversationMember({conversationId: convoId,- companyId: c.company_id,+ memberId: me,actorId: me,+ companyId: c.company_id,+ allowSoleMember: true,kind: 'left',- participantId: me,})-- const next = await removeConversationMember({ conversationId: convoId, memberId: me }) ?? []+ if (!mutation) return err(`${me} is no longer a member of ${convoId}`)+ const next = mutation.membersreturn ok(`left "${c.title}" (${convoId}); ${next.length} member(s) remain`, [{event: 'conversation.membership_changed',@@ -1382,7 +1570,7 @@ async function cmdLeave(parsed: ParsedArgs): Promise<CliResult> {actorId: me,participantId: me,companyId: c.company_id ?? undefined,- systemMessageId: systemMessage.messageId,+ systemMessageId: mutation.systemMessageId,memberCount: next.length,visibleToUser: true,}])@@ -1403,6 +1591,7 @@ async function cmdInvite(parsed: ParsedArgs): Promise<CliResult> {)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 invite into a direct conversation — use `cumora pull-group` to start a fresh thread')}@@ -1419,15 +1608,14 @@ async function cmdInvite(parsed: ParsedArgs): Promise<CliResult> {if (!pp[0]) return err(`${target} is not a participant in this workspace`)}- const next = await addConversationMember({ conversationId: convoId, memberId: target }) ?? []-- const systemMessage = await postMembershipSystemMessage({+ const mutation = await addConversationMember({conversationId: convoId,- companyId: c.company_id,+ memberId: target,actorId: me,- kind: 'joined',- participantId: target,+ companyId: c.company_id,})+ if (!mutation) return err(`${me} is no longer a member of ${convoId} — invite cancelled`)+ const next = mutation.membersreturn ok(`invited ${target} into "${c.title}" (${convoId}); ${next.length} member(s) total`, [{event: 'conversation.membership_changed',@@ -1437,7 +1625,7 @@ async function cmdInvite(parsed: ParsedArgs): Promise<CliResult> {actorId: me,participantId: target,companyId: c.company_id ?? undefined,- systemMessageId: systemMessage.messageId,+ systemMessageId: mutation.systemMessageId,memberCount: next.length,visibleToUser: true,}])@@ -1458,6 +1646,7 @@ async function cmdKick(parsed: ParsedArgs): Promise<CliResult> {)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}`)@@ -1472,23 +1661,24 @@ async function cmdKick(parsed: ParsedArgs): Promise<CliResult> {return err(`kicking ${target} would leave only ${me} in this group; pass --confirm-empty if that's intended`)}- // Post BEFORE removing the target from members. The mailbox query- // filters by current `c.members @> [agentId]`, so if we updated first- // the kicked agent would never see the row that explains why their- // inbox went quiet on this conversation. Posting first means the- // target gets one last wake with this exact message.- const systemMessage = await postMembershipSystemMessage({+ // Report what the row actually holds now, not the array we predicted from a+ // read taken before the guards above. The actor predicate is part of this+ // UPDATE, so a concurrent revocation cannot leave this stale kick authorized.+ const confirmedEmpty = Boolean(parsed.flags['confirm-empty'])+ const mutation = await removeConversationMember({conversationId: convoId,- companyId: c.company_id,+ memberId: target,actorId: me,+ companyId: c.company_id,+ allowSoleMember: confirmedEmpty,kind: 'kicked',- participantId: target,})-- // Report what the row actually holds now, not the array we predicted from a- // read taken before the guards above — a concurrent join or leave lands in- // between, and the count is user-visible.- const remaining = await removeConversationMember({ conversationId: convoId, memberId: target }) ?? []+ if (!mutation) {+ return err(confirmedEmpty+ ? `membership changed or ${me} is no longer authorized in ${convoId} — kick cancelled`+ : `membership changed, the kick is no longer authorized, or it would leave only ${me}; retry with --confirm-empty if intended`)+ }+ const remaining = mutation.membersreturn ok(`kicked ${target} from "${c.title}" (${convoId}); ${remaining.length} member(s) remain`, [{event: 'conversation.membership_changed',@@ -1498,7 +1688,7 @@ async function cmdKick(parsed: ParsedArgs): Promise<CliResult> {actorId: me,participantId: target,companyId: c.company_id ?? undefined,- systemMessageId: systemMessage.messageId,+ systemMessageId: mutation.systemMessageId,memberCount: remaining.length,visibleToUser: true,}])@@ -1527,21 +1717,32 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {return err('usage: reply <convo_id> "<body>" [--quote <msg_id>] [--attach <url> | --generate-image "<prompt>" [--size square|wide|tall] | --attach-text "<filename>" "<content>" | --attach-bytes "<filename>" --bytes-b64 "<base64>" [--bytes-mime "<mime>"]]')}- // Verify the participant is a member of the conversation.+ // Agent ids are globally unique, so pin their current tenant here. Human+ // callers can belong to several companies; for them the conversation id ++ // active participant membership below selects the tenant instead.+ const activeAgentCompanyId = await agentCompany(me)++ // Friendly preflight only. The final INSERT transaction repeats this+ // authorization while holding both the active participant row and the+ // 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}>(`SELECT c.members, c.company_id, c.kind,- EXISTS (- SELECT 1 FROM participants p- WHERE p.id = $2 AND p.company_id = c.company_id- AND p.kind = 'agent' AND p.departed_at IS NULL- ) AS actor_is_agent- FROM conversations c WHERE c.id = $1`,- [convoId, me],+ (requester.kind = 'agent') AS actor_is_agent+ FROM conversations c+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind IN ('agent', 'human')+ AND requester.departed_at IS NULL+ WHERE c.id = $1+ AND ($3::text IS NULL OR c.company_id = $3)+ AND c.members @> to_jsonb(ARRAY[$2::text])`,+ [convoId, me, activeAgentCompanyId],)- if (!cv[0]) return err(`unknown conversation ${convoId}`)- if (!cv[0].members.includes(me)) return err(`${me} is not a member of ${convoId}`)+ if (!cv[0]) return err(`conversation ${convoId} not found or no longer authorized`)const companyId = cv[0].company_id// ─── Anti-monologue gate ──────────────────────────────────────────@@ -1953,6 +2154,24 @@ 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],+ )+ if (!authorizedRows[0]) {+ await txClient.query('ROLLBACK')+ return err(`conversation ${convoId} no longer authorized; reply cancelled`)+ }const { rows: seqRow } = await txClient.query<{ seq: number }>(`INSERT INTO conversation_counters (conversation_id, next_sequence)VALUES ($1, 2)@@ -1984,7 +2203,7 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {// contradicting this check's own "verbatim-dup is a hard no, the server enforces"// contract.) The peer-only query below already exempts genuine self-monologue: a// real follow-up isn't verbatim-identical to a recent PEER post, so it still passes.- if (cv[0].members.length > 2) {+ if (authorizedRows[0].member_count > 2) {const draftBodyTrimmed = body.trim()if (draftBodyTrimmed.length > 0) {const { rows: lastPeer } = await txClient.query<{ sequence: number; author_id: string; body: string }>(@@ -2011,6 +2230,13 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {VALUES ($1,$2,$3,'text',$4,$5,$6::jsonb,$7,$8)`,[messageId, convoId, me, finalBody, sequence, attachment ? JSON.stringify(attachment) : null, resolvedQuotedId, companyId],)+ await txClient.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [convoId])+ await txClient.query(+ `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)+ VALUES ($1, $2, NOW())+ ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,+ [me, convoId],+ )await txClient.query('COMMIT')} catch (e) {await txClient.query('ROLLBACK').catch(() => { /* already failed */ })@@ -2018,22 +2244,15 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {} finally {txClient.release()}- await pool.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [convoId])-- // Posting auto-acks me on this conversation (I clearly saw the messages I'm replying to)- await pool.query(- `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)- VALUES ($1, $2, NOW())- ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,- [me, convoId],- )// Advance the Redis "seen" boundary to my own just-inserted seq, so the// freshness preflight on my NEXT cumora reply compares against the post-// insertion state (peer messages with seq <= mine are "things I obviously// saw"; only seq > mine would trip a HOLD). Pure Redis side-effect — does// NOT touch conversation_reads.last_read_at or anything else loadInbox// depends on.- await recordSeen(me, convoId, sequence)+ await recordSeen(me, convoId, sequence).catch((error) => {+ console.warn(`[reply] message ${messageId} committed but seen-boundary update failed`, error)+ })// Drop any lingering hold token: this send committed WITHOUT the// override, so a hold acknowledged-but-unused must not arm a later// preemptive --send-anyway in this conversation.@@ -2065,6 +2284,8 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {sequence: quotedSummary.sequence,} : undefined,},+ }).catch((error) => {+ console.warn(`[reply] durable message ${messageId} committed but publish failed`, error)})const attachmentNote = attachment? ` · attached ${attachment.kind} "${attachment.name}"`@@ -2490,8 +2711,10 @@ async function listEmailContacts(companyId: string,viewerId: string,query?: string,+ client?: PoolClient,): Promise<EmailContact[]> {const out: EmailContact[] = []+ const db = client ?? poolconst { computeAgentAddress } = await import('../email.js')// Optional fuzzy filter. Applied uniformly across name / id / email so a// single query like "wey" matches an agent's id, a human's display@@ -2510,7 +2733,7 @@ async function listEmailContacts(// exposes a deterministic address for un-minted agents, so the CLI// contact list should match (otherwise a fresh agent is invisible until// someone has emailed them, which is the bootstrap chicken-and-egg).- const { rows: agents } = await pool.query<{ id: string; name: string; email: string | null; slug: string; role: string | null }>(+ const { rows: agents } = await db.query<{ id: string; name: string; email: string | null; slug: string; role: string | null }>(`SELECT p.id, p.name, p.email, p.role, c.slugFROM participants pJOIN companies c ON c.id = p.company_id@@ -2527,7 +2750,7 @@ async function listEmailContacts(if (matches(c)) out.push(c)}// 2. Workspace humans (auth email).- const { rows: humans } = await pool.query<{ id: string; display_name: string; email: string }>(+ const { rows: humans } = await db.query<{ id: string; display_name: string; email: string }>(`SELECT u.id, u.display_name, u.emailFROM users uJOIN company_members cm ON cm.user_id = u.id@@ -2543,7 +2766,7 @@ async function listEmailContacts(// at the 30 most recent; with a filter we widen the net so a search// can find older correspondents too (still capped to keep memory bounded).const limit = q ? 200 : 30- const { rows: ext } = await pool.query<{ address: string; display_name: string | null; message_count: number }>(+ const { rows: ext } = await db.query<{ address: string; display_name: string | null; message_count: number }>(`SELECT address, display_name, message_count FROM email_contactsWHERE company_id = $1ORDER BY last_seen_at DESC LIMIT $2`,@@ -2624,13 +2847,14 @@ async function listAgentEmailThreads(args: {companyId: stringunreadOnly: booleanlimit: number+ client?: PoolClient}): Promise<EmailThreadRow[]> {// Threads = email conversations the agent is in. We surface the latest// email_messages row per thread for the snippet, and an unread count// computed against conversation_reads.last_read_at (same source of// truth as the chat inbox uses). Keeps the agent's mental model// consistent: "unread" means "you haven't acked this thread since".- const { rows } = await pool.query<EmailThreadRow>(+ const { rows } = await (args.client ?? pool).query<EmailThreadRow>(`WITH my_threads AS (SELECT c.id, c.title, c.updated_atFROM conversations c@@ -2797,9 +3021,18 @@ async function cmdPollShow(parsed: ParsedArgs, me: string, companyId: string): Pconst messageId = parsed.positional[1]if (!messageId) return err('usage: poll show <message_id>')const { rows } = await pool.query<{ poll: { question: string; mode: string; options: Array<{ id: string; text: string }>; expiresAt: string | null; closedAt: string | null } | null; author_id: string }>(- `SELECT poll, author_id FROM messages- WHERE id = $1 AND company_id = $2 AND kind = 'poll' LIMIT 1`,- [messageId, companyId],+ `SELECT m.poll, m.author_id+ FROM participants requester+ JOIN conversations c+ ON c.company_id = requester.company_id+ AND c.members @> to_jsonb(ARRAY[$3::text])+ JOIN messages m ON m.conversation_id = c.id AND m.company_id = c.company_id+ WHERE m.id = $1 AND m.company_id = $2 AND m.kind = 'poll'+ AND requester.id = $3+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ LIMIT 1`,+ [messageId, companyId, me],)const row = rows[0]if (!row || !row.poll) return err(`poll ${messageId} not found`)@@ -2890,7 +3123,14 @@ async function cmdEmailContacts(// — the agent's LLM uses this signal to ask the user for the address// instead of silently doing nothing.const query = parsed.positional[1]?.trim() ?? ''- const list = await listEmailContacts(companyId, me, query)+ const lockedList = await withActiveParticipantLock({+ participantId: me,+ companyId,+ kind: 'agent',+ run: (client) => listEmailContacts(companyId, me, query, client),+ })+ if (!lockedList) return err(`cannot resolve active company for ${me}`)+ const list = lockedListif (json) return ok(JSON.stringify(list, null, 2))if (list.length === 0) {const { env } = await import('../env.js')@@ -2923,7 +3163,14 @@ async function cmdEmailContacts(async function cmdEmailInbox(parsed: ParsedArgs, me: string, companyId: string): Promise<CliResult> {const unread = Boolean(parsed.flags.unread)const limit = Math.min(50, Math.max(1, Number(parsed.flags.limit ?? 20)))- const threads = await listAgentEmailThreads({ agentId: me, companyId, unreadOnly: unread, limit })+ const lockedThreads = await withActiveParticipantLock({+ participantId: me,+ companyId,+ kind: 'agent',+ run: (client) => listAgentEmailThreads({ agentId: me, companyId, unreadOnly: unread, limit, client }),+ })+ if (!lockedThreads) return err(`cannot resolve active company for ${me}`)+ const threads = lockedThreadsif (parsed.flags.json) return ok(JSON.stringify(threads, null, 2))if (threads.length === 0) {// Distinguish "feature not wired" from "feature wired, just empty" so@@ -2958,49 +3205,55 @@ async function cmdEmailShow(parsed: ParsedArgs, me: string, companyId: string):const convoId = parsed.positional[1]if (!convoId) return err('usage: email show <conversation_id> [--tail N]')const tail = Math.min(50, Math.max(1, Number(parsed.flags.tail ?? 10)))- // Confirm membership — agents can only read threads they're on.- const { rows: cv } = await pool.query<{ members: string[]; title: string }>(- `SELECT members, title FROM conversations- WHERE id = $1 AND company_id = $2 AND kind = 'email' LIMIT 1`,- [convoId, companyId],- )- if (!cv[0]) return err(`unknown email thread ${convoId}`)- if (!cv[0].members.includes(me)) return err(`${me} is not a member of ${convoId}`)- const { rows: msgs } = await pool.query<{- id: string; created_at: string; body: string; from_addr: string;- to_addrs: string[]; cc_addrs: string[]; subject: string;- smtp_message_id: string | null; in_reply_to: string | null;- direction: 'in' | 'out'; transport_status: string;- }>(- `SELECT m.id, m.created_at::text, m.body,- em.from_addr, em.to_addrs, em.cc_addrs, em.subject,- em.smtp_message_id, em.in_reply_to, em.direction, em.transport_status- FROM messages m- JOIN email_messages em ON em.message_id = m.id- WHERE m.conversation_id = $1- ORDER BY m.sequence DESC- LIMIT $2`,- [convoId, tail],- )- msgs.reverse()- if (parsed.flags.json) return ok(JSON.stringify({ thread: convoId, title: cv[0].title, messages: msgs }, null, 2))- if (msgs.length === 0) return ok(`(thread ${convoId} has no email messages)`)- const lines: string[] = [`thread ${convoId} "${cv[0].title}"`, '']- for (const m of msgs) {- const at = new Date(m.created_at).toISOString().replace('T', ' ').slice(0, 16)- const arrow = m.direction === 'in' ? '↓ in' : '↑ out'- lines.push(`──── [${m.id}] ${arrow} ${m.transport_status} ${at}`)- lines.push(`from: ${m.from_addr}`)- if (m.to_addrs?.length) lines.push(`to: ${m.to_addrs.join(', ')}`)- if (m.cc_addrs?.length) lines.push(`cc: ${m.cc_addrs.join(', ')}`)- lines.push(`subject: ${m.subject}`)- if (m.in_reply_to) lines.push(`in-reply-to: <${m.in_reply_to}>`)- lines.push('')- lines.push(m.body)- lines.push('')- }- lines.push(`reply with \`cumora email reply ${msgs[msgs.length - 1].id} --body "..."\`.`)- return ok(lines.join('\n'))+ const result = await withConversationActorLock({+ participantId: me,+ companyId,+ conversationId: convoId,+ kind: 'agent',+ conversationKind: 'email',+ run: async (client) => {+ const { rows: cv } = await client.query<{ title: string }>(+ `SELECT title FROM conversations WHERE id = $1 AND company_id = $2`,+ [convoId, companyId],+ )+ const { rows: msgs } = await client.query<{+ id: string; created_at: string; body: string; from_addr: string;+ to_addrs: string[]; cc_addrs: string[]; subject: string;+ smtp_message_id: string | null; in_reply_to: string | null;+ direction: 'in' | 'out'; transport_status: string;+ }>(+ `SELECT m.id, m.created_at::text, m.body,+ em.from_addr, em.to_addrs, em.cc_addrs, em.subject,+ em.smtp_message_id, em.in_reply_to, em.direction, em.transport_status+ FROM messages m+ JOIN email_messages em ON em.message_id = m.id AND em.company_id = $3+ WHERE m.conversation_id = $1 AND m.company_id = $3+ ORDER BY m.sequence DESC+ LIMIT $2`,+ [convoId, tail, companyId],+ )+ msgs.reverse()+ if (parsed.flags.json) return ok(JSON.stringify({ thread: convoId, title: cv[0].title, messages: msgs }, null, 2))+ if (msgs.length === 0) return ok(`(thread ${convoId} has no email messages)`)+ const lines: string[] = [`thread ${convoId} "${cv[0].title}"`, '']+ for (const m of msgs) {+ const at = new Date(m.created_at).toISOString().replace('T', ' ').slice(0, 16)+ const arrow = m.direction === 'in' ? '↓ in' : '↑ out'+ lines.push(`──── [${m.id}] ${arrow} ${m.transport_status} ${at}`)+ lines.push(`from: ${m.from_addr}`)+ if (m.to_addrs?.length) lines.push(`to: ${m.to_addrs.join(', ')}`)+ if (m.cc_addrs?.length) lines.push(`cc: ${m.cc_addrs.join(', ')}`)+ lines.push(`subject: ${m.subject}`)+ if (m.in_reply_to) lines.push(`in-reply-to: <${m.in_reply_to}>`)+ lines.push('')+ lines.push(m.body)+ lines.push('')+ }+ lines.push(`reply with \`cumora email reply ${msgs[msgs.length - 1].id} --body "..."\`.`)+ return ok(lines.join('\n'))+ },+ })+ return result ?? err(`email thread ${convoId} not found or no longer authorized`)}async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string): Promise<CliResult> {@@ -3061,27 +3314,17 @@ async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string):memberIds: [...memberIds],})- // Call the provider FIRST so we record sent/failed accurately. If- // anything throws we still write a queued/failed row — the agent- // shouldn't lose the draft just because Resend hiccuped.- const sendRes = await sendViaProvider({- from: formatAddress(sender.email, sender.displayName),- to: toResolved.map((r) => formatAddress(r.addr, r.name)),- cc: ccResolved.length ? ccResolved.map((r) => formatAddress(r.addr, r.name)) : undefined,- subject,- text: body,- messageId,- autoSubmitted: 'auto-generated',- })-+ // WRITE-FIRST: persist an authorized durable row before the network hop.+ // persistEmailMessage locks the active author and current conversation+ // membership in its transaction, so a revoked actor never reaches Resend.const persisted = await persistEmailMessage({conversationId: conv.conversationId,companyId,authorId: me,direction: 'out',- transportStatus: sendRes.ok ? 'sent' : 'failed',- transportError: sendRes.error,- smtpMessageId: sendRes.smtpMessageId ?? messageId,+ transportStatus: 'sending',+ transportError: null,+ smtpMessageId: messageId,inReplyTo: null,references: [],subject,@@ -3092,6 +3335,30 @@ async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string):autoSubmitted: true,})+ const sendRes = await sendViaProvider({+ from: formatAddress(sender.email, sender.displayName),+ to: toResolved.map((r) => formatAddress(r.addr, r.name)),+ cc: ccResolved.length ? ccResolved.map((r) => formatAddress(r.addr, r.name)) : undefined,+ subject,+ text: body,+ messageId,+ autoSubmitted: 'auto-generated',+ })+ const finalStatus = sendRes.ok ? 'sent' : 'failed'+ await pool.query(+ `UPDATE email_messages+ SET transport_status = $1, transport_error = $2,+ smtp_message_id = $3, next_retry_at = $4+ WHERE message_id = $5 AND company_id = $6`,+ [+ finalStatus, sendRes.error, sendRes.smtpMessageId ?? messageId,+ finalStatus === 'failed' ? new Date(Date.now() + 60_000) : null,+ persisted.messageId, companyId,+ ],+ ).catch((error) => {+ console.warn(`[email] post-send UPDATE failed for ${persisted.messageId}; retry worker will reconcile`, error)+ })+if (!sendRes.ok) {return err(`email persisted as failed: ${sendRes.error} · message_id=${persisted.messageId}`, 1)}@@ -3119,7 +3386,14 @@ async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string):if (!replyTo || !body) return err('usage: email reply <message_id> --body "..." [--cc <addr|id>...]')const attachmentError = rejectsEmailAttachmentFlags(parsed)if (attachmentError) return attachmentError- // Pull the original email row and its conversation context.+ const {+ ensureAgentAddress, formatAddress,+ sendViaProvider, persistEmailMessage, mintMessageId, normalizeMessageId,+ sanitizeSubject, splitReplyAddresses,+ } = await import('../email.js')+ const sender = await ensureAgentAddress(me)+ if (!sender) return err('agent has no email address (EMAIL_DOMAIN unset or company missing)')+const { rows: orig } = await pool.query<{conversation_id: stringsmtp_message_id: string | null@@ -3136,21 +3410,6 @@ async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string):)if (!orig[0]) return err(`unknown email message ${replyTo}`)const o = orig[0]- // Confirm membership — same gate as `email show`.- const { rows: cv } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1`, [o.conversation_id],- )- if (!cv[0] || !cv[0].members.includes(me)) {- return err(`${me} is not a member of thread ${o.conversation_id}`)- }-- const {- ensureAgentAddress, formatAddress,- sendViaProvider, persistEmailMessage, mintMessageId, normalizeMessageId,- sanitizeSubject, splitReplyAddresses,- } = await import('../email.js')- const sender = await ensureAgentAddress(me)- if (!sender) return err('agent has no email address (EMAIL_DOMAIN unset or company missing)')// Reply-all split: TO = original From, CC = original To+Cc minus self.// Earlier iterations collapsed everyone into TO; that read fine but@@ -3197,26 +3456,17 @@ async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string):const inReplyTo = o.smtp_message_id ? normalizeMessageId(o.smtp_message_id) : nullconst messageId = mintMessageId()- const sendRes = await sendViaProvider({- from: formatAddress(sender.email, sender.displayName),- to: toAddrs,- cc: ccCombined.length ? ccCombined : undefined,- subject,- text: body,- inReplyTo: inReplyTo ?? undefined,- references: newReferences,- messageId,- autoSubmitted: 'auto-replied',- })-+ // WRITE-FIRST. This is the authorization boundary: persistEmailMessage+ // locks the current participant and verifies current conversation+ // membership before committing the durable outbound row.const persisted = await persistEmailMessage({conversationId: o.conversation_id,companyId,authorId: me,direction: 'out',- transportStatus: sendRes.ok ? 'sent' : 'failed',- transportError: sendRes.error,- smtpMessageId: sendRes.smtpMessageId ?? messageId,+ transportStatus: 'sending',+ transportError: null,+ smtpMessageId: messageId,inReplyTo,references: newReferences,subject,@@ -3227,6 +3477,32 @@ async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string):autoSubmitted: true,})+ const sendRes = await sendViaProvider({+ from: formatAddress(sender.email, sender.displayName),+ to: toAddrs,+ cc: ccCombined.length ? ccCombined : undefined,+ subject,+ text: body,+ inReplyTo: inReplyTo ?? undefined,+ references: newReferences,+ messageId,+ autoSubmitted: 'auto-replied',+ })+ const finalStatus = sendRes.ok ? 'sent' : 'failed'+ await pool.query(+ `UPDATE email_messages+ SET transport_status = $1, transport_error = $2,+ smtp_message_id = $3, next_retry_at = $4+ WHERE message_id = $5 AND company_id = $6`,+ [+ finalStatus, sendRes.error, sendRes.smtpMessageId ?? messageId,+ finalStatus === 'failed' ? new Date(Date.now() + 60_000) : null,+ persisted.messageId, companyId,+ ],+ ).catch((error) => {+ console.warn(`[email] post-send UPDATE failed for ${persisted.messageId}; retry worker will reconcile`, error)+ })+// Auto-ack — replying definitionally means I read the original.await pool.query(`INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)@@ -3425,12 +3701,24 @@ async function saveTextAttachment(}async function cmdTopicRead(parsed: ParsedArgs): Promise<CliResult> {+ const me = resolveAs(parsed)const convoId = parsed.positional[0]if (!convoId) return err('usage: topic <conversation_id>')+ const activeAgentCompanyId = await agentCompany(me)const { rows } = await pool.query<{ topic: string | null; title: string }>(- `SELECT topic, title FROM conversations WHERE id = $1`, [convoId],+ `SELECT c.topic, c.title+ FROM conversations c+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind IN ('agent', 'human')+ AND requester.departed_at IS NULL+ WHERE c.id = $1+ AND ($3::text IS NULL OR c.company_id = $3)+ AND c.members @> to_jsonb(ARRAY[$2::text])`,+ [convoId, me, activeAgentCompanyId],)- if (!rows[0]) return err(`unknown conversation ${convoId}`)+ if (!rows[0]) return err(`conversation ${convoId} not found or no longer authorized`)const t = rows[0].topicif (!t) return ok(`(no topic set on "${rows[0].title}")`)return ok(t)@@ -3442,22 +3730,40 @@ async function cmdTopicSet(parsed: ParsedArgs): Promise<CliResult> {if (!convoId) return err('usage: topic-set <conversation_id> "<text>" (empty body clears the topic)')const raw = unescapeChat(parsed.positional.slice(1).join(' ')).trim()const topic = raw.length > 0 ? raw.slice(0, 200) : null-- const { rows } = await pool.query<{ members: string[]; company_id: string }>(- `SELECT members, company_id FROM conversations WHERE id = $1`, [convoId],- )- if (!rows[0]) return err(`unknown conversation ${convoId}`)- if (!rows[0].members.includes(me)) return err(`${me} is not a member of ${convoId}`)-- await pool.query(- `UPDATE conversations SET topic = $2, updated_at = NOW() WHERE id = $1`,- [convoId, topic],+ const activeAgentCompanyId = await agentCompany(me)++ const { rows: preflight } = await pool.query<{ company_id: string }>(+ `SELECT c.company_id+ FROM conversations c+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind IN ('agent', 'human')+ AND requester.departed_at IS NULL+ WHERE c.id = $1+ AND ($3::text IS NULL OR c.company_id = $3)+ AND c.members @> to_jsonb(ARRAY[$2::text])`,+ [convoId, me, activeAgentCompanyId],)+ if (!preflight[0]) return err(`conversation ${convoId} not found or no longer authorized`)+ const updated = await withConversationActorLock({+ participantId: me,+ companyId: preflight[0].company_id,+ conversationId: convoId,+ run: async (client) => client.query<{ company_id: string }>(+ `UPDATE conversations SET topic = $2, updated_at = NOW()+ WHERE id = $1 AND company_id = $3+ RETURNING company_id`,+ [convoId, topic, preflight[0].company_id],+ ),+ })+ const companyId = updated?.rows[0]?.company_id+ if (!companyId) return err(`conversation ${convoId} not found or no longer authorized`)const { CH_CONVO_UPDATED, publish } = await import('../redis.js')await publish(CH_CONVO_UPDATED, {type: 'conversation.updated',conversationId: convoId,- companyId: rows[0].company_id,+ companyId,patch: { topic },})return ok(topic ? `topic set: "${topic}"` : '(topic cleared)', [{@@ -3465,7 +3771,7 @@ async function cmdTopicSet(parsed: ParsedArgs): Promise<CliResult> {command: 'topic-set',conversationId: convoId,actorId: me,- companyId: rows[0].company_id,+ companyId,topic,visibleToUser: true,}])@@ -3479,13 +3785,23 @@ async function cmdRename(parsed: ParsedArgs): Promise<CliResult> {if (!convoId) return err('usage: rename <conversation_id> "<new title>"')const title = unescapeChat(parsed.positional.slice(1).join(' ')).trim().slice(0, 80)if (!title) return err('rename requires a non-empty title')+ const activeAgentCompanyId = await agentCompany(me)const { rows } = await pool.query<{ members: string[]; kind: string; company_id: string; title: string }>(- `SELECT members, kind, company_id, title FROM conversations WHERE id = $1`, [convoId],+ `SELECT c.members, c.kind, c.company_id, c.title+ FROM conversations c+ JOIN participants requester+ ON requester.id = $2+ AND requester.company_id = c.company_id+ AND requester.kind IN ('agent', 'human')+ AND requester.departed_at IS NULL+ WHERE c.id = $1+ AND ($3::text IS NULL OR c.company_id = $3)+ AND c.members @> to_jsonb(ARRAY[$2::text])`,+ [convoId, me, activeAgentCompanyId],)- if (!rows[0]) return err(`unknown conversation ${convoId}`)+ if (!rows[0]) return err(`conversation ${convoId} not found or no longer authorized`)if (rows[0].kind !== 'group') return err(`only group chats can be renamed (${convoId} is a ${rows[0].kind})`)- if (!rows[0].members.includes(me)) return err(`${me} is not a member of ${convoId}`)const currentTitle = rows[0].title// Optimistic-concurrency: --if-equals "<expected current title>" lets a caller@@ -3510,10 +3826,19 @@ async function cmdRename(parsed: ParsedArgs): Promise<CliResult> {return ok(`(no-op — title was already "${title}")`)}- await pool.query(- `UPDATE conversations SET title = $2, updated_at = NOW() WHERE id = $1`,- [convoId, title],- )+ const updated = await withConversationActorLock({+ participantId: me,+ companyId: rows[0].company_id,+ conversationId: convoId,+ run: async (client) => client.query(+ `UPDATE conversations+ SET title = $2, updated_at = NOW()+ WHERE id = $1 AND company_id = $3+ AND kind = 'group' AND title = $4`,+ [convoId, title, rows[0].company_id, currentTitle],+ ),+ })+ if (!updated?.rowCount) return err(`conversation ${convoId} changed or is no longer authorized; rename cancelled`)const { CH_CONVO_UPDATED, publish } = await import('../redis.js')await publish(CH_CONVO_UPDATED, {type: 'conversation.updated',@@ -5471,6 +5796,8 @@ async function publishDocChanged(companyId,documentId,actorId,+ }).catch((error) => {+ console.warn(`[doc] durable ${kind} for ${documentId} committed but publish failed`, error)})}@@ -5479,9 +5806,59 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const me = resolveAs(parsed)const companyId = await agentCompany(me)if (!companyId) return err(`unknown agent ${me} (no company)`)+ const pendingChanges: Array<{+ kind: 'document.created' | 'document.updated' | 'document.deleted'+ documentId: string+ }> = []+ const finalizers: Array<() => Promise<void>> = []+ let locked: CliResult | null+ try {+ locked = await withActiveParticipantLock({+ participantId: me,+ companyId,+ kind: 'agent',+ run: async (client) => cmdDocAsActiveAgent(+ parsed,+ op,+ me,+ companyId,+ client,+ (kind, documentId) => pendingChanges.push({ kind, documentId }),+ (finalizer) => finalizers.push(finalizer),+ ),+ })+ } finally {+ for (const finalize of finalizers) {+ await finalize().catch((error) => {+ console.warn('[doc] post-transaction cleanup failed', error)+ })+ }+ }+ if (!locked) return err(`agent ${me} is no longer active in ${companyId}`)+ // `withActiveParticipantLock` commits before returning. Publish only now so+ // subscribers that immediately reload never observe pre-commit state, and a+ // failed transaction cannot emit a ghost document event.+ for (const change of pendingChanges) {+ await publishDocChanged(companyId, change.documentId, change.kind, me)+ }+ return locked+}++async function cmdDocAsActiveAgent(+ parsed: ParsedArgs,+ op: string,+ me: string,+ companyId: string,+ dbClient: PoolClient,+ onChanged: (+ kind: 'document.created' | 'document.updated' | 'document.deleted',+ documentId: string,+ ) => void,+ onFinally: (finalizer: () => Promise<void>) => void,+): Promise<CliResult> {if (op === 'ls' || op === 'list') {- const { rows } = await pool.query<{+ const { rows } = await dbClient.query<{id: string; title: string; created_by: string; updated_at: Date}>(`SELECT id, title, created_by, updated_at FROM documents@@ -5508,8 +5885,9 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {// still collide thanks to subject normalization.const blocked = await tryClaimTenantWork(companyId, me, 'doc-create', title)if (blocked) return blocked+ onFinally(() => releaseTenantWork(companyId, me, 'doc-create', title))- try {+ {// The claim above only guards work IN FLIGHT — it's released the// moment the first creator finishes, so it cannot stop a SEQUENTIAL// duplicate (2026-06-12: nova created+released 《第七天的猫》 at@@ -5524,7 +5902,7 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const docHoldScope = `doc-create:${normTitle}`const forceArmed = Boolean(parsed.flags.force) && (await consumeHold(me, docHoldScope)).armedif (!forceArmed) {- const { rows: recentDups } = await pool.query<{+ const { rows: recentDups } = await dbClient.query<{id: string; title: string; created_by: string; created_at: Date}>(`SELECT id, title, created_by, created_at FROM documents@@ -5548,7 +5926,7 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {}}const id = `doc_${randomUUID().replace(/-/g, '').slice(0, 16)}`- await pool.query(+ await dbClient.query(`INSERT INTO documents (id, company_id, title, created_by) VALUES ($1, $2, $3, $4)`,[id, companyId, title.slice(0, 200), me],)@@ -5558,9 +5936,9 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const body = typeof parsed.flags.body === 'string' ? unescapeChat(parsed.flags.body) : ''if (body) {const { applyAgentEdit } = await import('../documents/rooms.js')- await applyAgentEdit(id, companyId, me, [{ kind: 'append', text: body }])+ await applyAgentEdit(id, companyId, me, [{ kind: 'append', text: body }], dbClient)}- await publishDocChanged(companyId, id, 'document.created', me)+ onChanged('document.created', id)return ok(`created document ${id}: ${title}`, [{event: 'document.created',command: 'doc create',@@ -5571,20 +5949,18 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {bodyLength: body.length,visibleToUser: true,}])- } finally {- await releaseTenantWork(companyId, me, 'doc-create', title)}}if (op === 'read' || op === 'show') {const docId = parsed.positional[1]if (!docId) return err('usage: doc read <document_id>')- const { rows } = await pool.query<{ company_id: string; title: string }>(+ const { rows } = await dbClient.query<{ company_id: string; title: string }>(`SELECT company_id, title FROM documents WHERE id = $1 LIMIT 1`, [docId],)if (rows.length === 0 || rows[0].company_id !== companyId) return err(`document ${docId} not found`)const { readDocumentText } = await import('../documents/rooms.js')- const body = await readDocumentText(docId, companyId)+ const body = await readDocumentText(docId, companyId, dbClient)if (parsed.flags.json) return ok(JSON.stringify({ id: docId, title: rows[0].title, body }, null, 2))return ok([`# ${rows[0].title} (${docId})`,@@ -5598,13 +5974,13 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const text = parsed.positional.slice(2).join(' ').trim()|| (typeof parsed.flags.text === 'string' ? unescapeChat(parsed.flags.text) : '')if (!docId || !text) return err('usage: doc append <document_id> "<text>"')- const { rows } = await pool.query<{ company_id: string }>(+ const { rows } = await dbClient.query<{ company_id: string }>(`SELECT company_id FROM documents WHERE id = $1 LIMIT 1`, [docId],)if (rows.length === 0 || rows[0].company_id !== companyId) return err(`document ${docId} not found`)const { applyAgentEdit } = await import('../documents/rooms.js')- await applyAgentEdit(docId, companyId, me, [{ kind: 'append', text }])- await publishDocChanged(companyId, docId, 'document.updated', me)+ await applyAgentEdit(docId, companyId, me, [{ kind: 'append', text }], dbClient)+ onChanged('document.updated', docId)return ok(`appended ${text.length} chars to ${docId}`, [{event: 'document.updated',command: 'doc append',@@ -5622,13 +5998,13 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const text = parsed.positional.slice(2).join(' ').trim()|| (typeof parsed.flags.text === 'string' ? unescapeChat(parsed.flags.text) : '')if (!docId || !text) return err('usage: doc prepend <document_id> "<text>"')- const { rows } = await pool.query<{ company_id: string }>(+ const { rows } = await dbClient.query<{ company_id: string }>(`SELECT company_id FROM documents WHERE id = $1 LIMIT 1`, [docId],)if (rows.length === 0 || rows[0].company_id !== companyId) return err(`document ${docId} not found`)const { applyAgentEdit } = await import('../documents/rooms.js')- await applyAgentEdit(docId, companyId, me, [{ kind: 'insertParagraph', at: 'start', text }])- await publishDocChanged(companyId, docId, 'document.updated', me)+ await applyAgentEdit(docId, companyId, me, [{ kind: 'insertParagraph', at: 'start', text }], dbClient)+ onChanged('document.updated', docId)return ok(`prepended ${text.length} chars to ${docId}`, [{event: 'document.updated',command: 'doc prepend',@@ -5685,12 +6061,12 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {placement = { mode: atRaw === 'start' ? 'start' : 'end' }}- const { rows } = await pool.query<{ company_id: string }>(+ const { rows } = await dbClient.query<{ company_id: string }>(`SELECT company_id FROM documents WHERE id = $1 LIMIT 1`, [docId],)if (rows.length === 0 || rows[0].company_id !== companyId) return err(`document ${docId} not found`)const { applyAgentEdit, isAnchoredImagePlacement } = await import('../documents/rooms.js')- const result = await applyAgentEdit(docId, companyId, me, [{ kind: 'image', src, alt: alt || null, placement }])+ const result = await applyAgentEdit(docId, companyId, me, [{ kind: 'image', src, alt: alt || null, placement }], dbClient)// Anchor miss is a HARD error now — falling back to end-of-doc on a// missed snippet is how the doc collected duplicate inert images@@ -5701,7 +6077,7 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const snippet = placement.anchorText.slice(0, 60)return err(`anchor not found in ${docId}: "${snippet}". Re-read the doc and pick a snippet that uniquely identifies the target block — no image was inserted.`)}- await publishDocChanged(companyId, docId, 'document.updated', me)+ onChanged('document.updated', docId)let where: stringif (isAnchoredImagePlacement(placement)) {@@ -5736,7 +6112,7 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {if (provided.length > 1) {return err('pass only one of --src / --src-contains / --alt')}- const { rows } = await pool.query<{ company_id: string }>(+ const { rows } = await dbClient.query<{ company_id: string }>(`SELECT company_id FROM documents WHERE id = $1 LIMIT 1`, [docId],)if (rows.length === 0 || rows[0].company_id !== companyId) return err(`document ${docId} not found`)@@ -5745,11 +6121,11 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {: srcContains ? { by: 'src-contains', substring: srcContains }: { by: 'alt', alt: altMatch }const { applyAgentEdit } = await import('../documents/rooms.js')- const result = await applyAgentEdit(docId, companyId, me, [{ kind: 'imageDelete', match }])+ const result = await applyAgentEdit(docId, companyId, me, [{ kind: 'imageDelete', match }], dbClient)if (result.imagesDeleted === 0) {return err(`no images in ${docId} matched the criterion`)}- await publishDocChanged(companyId, docId, 'document.updated', me)+ onChanged('document.updated', docId)return ok(`deleted ${result.imagesDeleted} image${result.imagesDeleted === 1 ? '' : 's'} from ${docId}`, [{event: 'document.updated',command: 'doc image-delete',@@ -5767,14 +6143,14 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const find = typeof parsed.flags.find === 'string' ? unescapeChat(parsed.flags.find) : ''const replace = typeof parsed.flags.replace === 'string' ? unescapeChat(parsed.flags.replace) : ''if (!docId || !find) return err('usage: doc replace <document_id> --find "..." --replace "..."')- const { rows } = await pool.query<{ company_id: string }>(+ const { rows } = await dbClient.query<{ company_id: string }>(`SELECT company_id FROM documents WHERE id = $1 LIMIT 1`, [docId],)if (rows.length === 0 || rows[0].company_id !== companyId) return err(`document ${docId} not found`)const { applyAgentEdit } = await import('../documents/rooms.js')- const r = await applyAgentEdit(docId, companyId, me, [{ kind: 'replace', find, replace }])+ const r = await applyAgentEdit(docId, companyId, me, [{ kind: 'replace', find, replace }], dbClient)if (r.replaced === 0) return err(`text not found in ${docId}: ${JSON.stringify(find).slice(0, 80)}`)- await publishDocChanged(companyId, docId, 'document.updated', me)+ onChanged('document.updated', docId)return ok(`replaced ${r.replaced} occurrence in ${docId}`, [{event: 'document.updated',command: 'doc replace',@@ -5793,14 +6169,14 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const text = parsed.positional.slice(2).join(' ').trim()|| (typeof parsed.flags.text === 'string' ? unescapeChat(parsed.flags.text) : '')if (!docId || !anchor || !text) return err('usage: doc replace-block <document_id> --anchor "<snippet in the block>" "<replacement markdown>"')- const { rows } = await pool.query<{ company_id: string }>(+ const { rows } = await dbClient.query<{ company_id: string }>(`SELECT company_id FROM documents WHERE id = $1 LIMIT 1`, [docId],)if (rows.length === 0 || rows[0].company_id !== companyId) return err(`document ${docId} not found`)const { applyAgentEdit } = await import('../documents/rooms.js')- const r = await applyAgentEdit(docId, companyId, me, [{ kind: 'replaceBlock', anchorText: anchor, text }])+ const r = await applyAgentEdit(docId, companyId, me, [{ kind: 'replaceBlock', anchorText: anchor, text }], dbClient)if (r.blocksReplaced === 0) return err(`no block containing ${JSON.stringify(anchor).slice(0, 80)} in ${docId}`)- await publishDocChanged(companyId, docId, 'document.updated', me)+ onChanged('document.updated', docId)return ok(`replaced 1 block in ${docId}`, [{event: 'document.updated',command: 'doc replace-block',@@ -5817,13 +6193,13 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {const title = parsed.positional.slice(2).join(' ').trim()|| (typeof parsed.flags.title === 'string' ? parsed.flags.title : '')if (!docId || !title) return err('usage: doc rename <document_id> "<title>"')- const r = await pool.query(+ const r = await dbClient.query(`UPDATE documents SET title = $1, updated_at = NOW()WHERE id = $2 AND company_id = $3`,[title.slice(0, 200), docId, companyId],)if (!r.rowCount) return err(`document ${docId} not found`)- await publishDocChanged(companyId, docId, 'document.updated', me)+ onChanged('document.updated', docId)return ok(`renamed ${docId} to "${title}"`, [{event: 'document.updated',command: 'doc rename',@@ -5839,14 +6215,14 @@ async function cmdDoc(parsed: ParsedArgs): Promise<CliResult> {if (op === 'delete' || op === 'rm') {const docId = parsed.positional[1]if (!docId) return err('usage: doc delete <document_id>')- const { rows } = await pool.query<{ created_by: string }>(+ const { rows } = await dbClient.query<{ created_by: string }>(`SELECT created_by FROM documents WHERE id = $1 AND company_id = $2 LIMIT 1`,[docId, companyId],)if (rows.length === 0) return err(`document ${docId} not found`)if (rows[0].created_by !== me) return err(`only the creator can delete document ${docId}`)- await pool.query(`DELETE FROM documents WHERE id = $1`, [docId])- await publishDocChanged(companyId, docId, 'document.deleted', me)+ await dbClient.query(`DELETE FROM documents WHERE id = $1`, [docId])+ onChanged('document.deleted', docId)return ok(`deleted document ${docId}`, [{event: 'document.deleted',command: 'doc delete',diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex 6c27627..809d1d5 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -33,7 +33,12 @@ export const COMPUTER_STALE_MS = 90_000async function broadcastComputerStatus(computerId: string, companyId: string, status: ComputerStatus,): Promise<void> {- await publish(CH_STATUS, { type: 'computers.status', computerId, status, companyId })+ await publish(CH_STATUS, { type: 'computers.status', computerId, status, companyId }).catch((error) => {+ console.warn(+ `[computer] durable ${computerId}=${status} update committed but publish failed`,+ error,+ )+ })}/** Announce a just-paired computer as online. Split out from {@link pairComputer}diff --git a/server/src/agents/convene.ts b/server/src/agents/convene.tsindex 6340af3..300b895 100644--- a/server/src/agents/convene.ts+++ b/server/src/agents/convene.ts@@ -5,9 +5,9 @@ import { pool } from '../db/pool.js'import { env } from '../env.js'import { enforceModelPolicy, realTaskModel } from './model-policy.js'import { CH_CONVENE, publish } from '../redis.js'-import { getAllAgentPersonas, getPersona, buildSystemPrompt } from './personas.js'+import { getPersona, buildSystemPrompt } from './personas.js'import { setStatus } from '../status.js'-import { companyIdForConveneSession, companyIdForConversation } from '../tenant.js'+import { companyIdForConveneSession } from '../tenant.js'interface SessionRow {id: string@@ -20,37 +20,87 @@ interface SessionRow {state: string}-async function nextTranscriptSequence(sessionId: string): Promise<number> {- const { rows } = await pool.query<{ c: number }>(- `SELECT COUNT(*)::int AS c FROM convene_transcript WHERE session_id = $1`,- [sessionId],- )- return (rows[0]?.c ?? 0) + 1-}-async function appendTranscript(args: {sessionId: stringauthorId: stringkind: 'text' | 'thought' | 'tool' | 'decision'body: stringdecision?: { headline: string; body: string } | null-}): Promise<{ id: string; sequence: number }> {+}): Promise<{ id: string; sequence: number } | null> {const id = `ct-${randomUUID()}`- const sequence = await nextTranscriptSequence(args.sessionId)- await pool.query(- `INSERT INTO convene_transcript (id, session_id, author_id, kind, body, sequence, decision)- VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb)`,- [id, args.sessionId, args.authorId, args.kind, args.body, sequence,- args.decision ? JSON.stringify(args.decision) : null],+ const scope = await pool.query<{ conversation_id: string; company_id: string }>(+ `SELECT conversation_id, company_id FROM convene_sessions WHERE id = $1`,+ [args.sessionId],)- const companyId = (await companyIdForConveneSession(args.sessionId)) ?? undefined+ const initial = scope.rows[0]+ if (!initial) return null+ let sequence = 0+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ if (args.authorId !== 'system') {+ const participant = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL+ FOR SHARE`,+ [args.authorId, initial.company_id],+ )+ if (!participant.rowCount) {+ await client.query('ROLLBACK')+ return null+ }+ }+ 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`,+ [initial.conversation_id, initial.company_id, args.authorId],+ )+ if (!conversation.rowCount) {+ await client.query('ROLLBACK')+ return null+ }+ const session = await client.query(+ `SELECT id FROM convene_sessions+ WHERE id = $1 AND conversation_id = $2 AND company_id = $3 AND state = 'live'+ FOR UPDATE`,+ [args.sessionId, initial.conversation_id, initial.company_id],+ )+ if (!session.rowCount) {+ await client.query('ROLLBACK')+ return null+ }+ const seq = await client.query<{ sequence: number }>(+ `SELECT COALESCE(MAX(sequence), 0)::int + 1 AS sequence+ FROM convene_transcript WHERE session_id = $1`,+ [args.sessionId],+ )+ sequence = seq.rows[0]?.sequence ?? 1+ await client.query(+ `INSERT INTO convene_transcript+ (id, session_id, author_id, kind, body, sequence, decision, company_id)+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8)`,+ [id, args.sessionId, args.authorId, args.kind, args.body, sequence,+ args.decision ? JSON.stringify(args.decision) : null, initial.company_id],+ )+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }await publish(CH_CONVENE, {type: 'convene',sessionId: args.sessionId,- conversationId: '',- companyId,+ conversationId: initial.conversation_id,+ companyId: initial.company_id,kind: 'transcript',data: { id, sessionId: args.sessionId, authorId: args.authorId, kind: args.kind, body: args.body, sequence, decision: args.decision ?? null, createdAt: new Date().toISOString() },+ }).catch((error) => {+ console.warn(`[convene] durable transcript ${id} committed but publish failed`, error)})return { id, sequence }}@@ -68,45 +118,82 @@ export async function getActiveConvene(conversationId: string): Promise<SessionRexport async function startConvene(args: {conversationId: string+ companyId: stringstartedBy: stringtopic: string}): Promise<SessionRow> {const id = `cs-${randomUUID()}`- const { rows: cv } = await pool.query<{ members: string[]; title: string }>(- `SELECT members, title FROM conversations WHERE id = $1`,- [args.conversationId],- )- const convo = cv[0]- if (!convo) throw new Error(`conversation ${args.conversationId} not found`)-- const session: SessionRow = {- id,- conversation_id: args.conversationId,- title: `${convo.title} · live`,- flair: args.topic.slice(0, 80),- started_by: args.startedBy,- started_at: new Date().toISOString(),- ended_at: null,- state: 'live',+ let session: SessionRow+ let created = false+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const actor = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ FOR SHARE`,+ [args.startedBy, args.companyId],+ )+ 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`,+ [args.conversationId, args.companyId, args.startedBy],+ )+ if (!rows[0]) throw new Error(`conversation ${args.conversationId} not found or not authorized`)+ const existing = await client.query<SessionRow>(+ `SELECT id, conversation_id, title, flair, started_by, started_at, ended_at, state+ FROM convene_sessions+ WHERE conversation_id = $1 AND company_id = $2 AND state = 'live'+ ORDER BY started_at DESC LIMIT 1+ FOR UPDATE`,+ [args.conversationId, args.companyId],+ )+ if (existing.rows[0]) {+ await client.query('COMMIT')+ return existing.rows[0]+ }+ session = {+ id,+ conversation_id: args.conversationId,+ title: `${rows[0].title} · live`,+ flair: args.topic.slice(0, 80),+ started_by: args.startedBy,+ started_at: new Date().toISOString(),+ ended_at: null,+ state: 'live',+ }+ await client.query(+ `INSERT INTO convene_sessions+ (id, conversation_id, title, flair, started_by, started_at, state, company_id)+ VALUES ($1,$2,$3,$4,$5,NOW(),'live',$6)`,+ [id, session.conversation_id, session.title, session.flair, session.started_by, args.companyId],+ )+ created = true+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()}- await pool.query(- `INSERT INTO convene_sessions (id, conversation_id, title, flair, started_by, started_at, state)- VALUES ($1,$2,$3,$4,$5,NOW(),'live')`,- [id, session.conversation_id, session.title, session.flair, session.started_by],- )-- const companyId = (await companyIdForConversation(args.conversationId)) ?? undefined+ if (!created) return sessionawait publish(CH_CONVENE, {type: 'convene',sessionId: id,conversationId: args.conversationId,- companyId,+ companyId: args.companyId,kind: 'started',data: session,+ }).catch((error) => {+ console.warn(`[convene] durable session ${id} committed but started publish failed`, error)})- orchestrate({ session, members: convo.members, topic: args.topic }).catch((e) => {+ orchestrate({ session, companyId: args.companyId, topic: args.topic }).catch((e) => {console.error('[convene] orchestration error', e)})@@ -115,85 +202,66 @@ export async function startConvene(args: {async function orchestrate(args: {session: SessionRow- members: string[]+ companyId: stringtopic: string}): Promise<void> {- const { session, members, topic } = args- // Snapshot the agent roster once for this orchestrate run, scoped to the- // tenant the convene's conversation belongs to.- const tenant = (await companyIdForConversation(session.conversation_id)) ?? 'personal'- const allAgents = await getAllAgentPersonas(tenant)- const nameById = new Map(allAgents.map((p) => [p.id, p.name]))- const isAgentId = new Set(allAgents.map((p) => p.id))- const agentMembers = members.filter((m) => isAgentId.has(m))-- const { rows: ctxMsgs } = await pool.query<{ author_id: string; body: string; kind: string }>(- `SELECT author_id, body, kind FROM messages- WHERE conversation_id = $1 AND kind IN ('text','thought')- ORDER BY sequence DESC LIMIT 12`,- [session.conversation_id],- )- const groundingHistory: ResponseInputItem[] = ctxMsgs.reverse().map((m) => ({- role: 'user',- content: `[${nameById.get(m.author_id) ?? m.author_id}]: ${m.body}`,- }))-- for (const agentId of agentMembers) {- await runAgentTurn({ session, agentId, groundingHistory, topic })- }+ const { session, companyId, topic } = args+ try {+ const { rows: agentMembers } = await pool.query<{ id: string }>(+ `SELECT p.id+ FROM conversations c+ CROSS JOIN LATERAL jsonb_array_elements_text(c.members) member(id)+ JOIN participants p+ ON p.id = member.id AND p.company_id = c.company_id+ AND p.kind = 'agent' AND p.departed_at IS NULL+ WHERE c.id = $1 AND c.company_id = $2+ ORDER BY p.id`,+ [session.conversation_id, companyId],+ )+ for (const { id: agentId } of agentMembers) {+ await runAgentTurn({ session, companyId, agentId, topic })+ }- const summary = await classifyDecision({ sessionId: session.id, topic })- if (summary) {- await appendTranscript({+ const summary = await classifyDecision({ sessionId: session.id, topic })+ if (summary) {+ await appendTranscript({+ sessionId: session.id,+ authorId: 'system',+ kind: 'decision',+ body: summary.body,+ decision: { headline: summary.headline, body: summary.body },+ })+ }+ } finally {+ await pool.query(+ `UPDATE convene_sessions SET state = 'ended', ended_at = NOW()+ WHERE id = $1 AND company_id = $2 AND state = 'live'`,+ [session.id, companyId],+ )+ await publish(CH_CONVENE, {+ type: 'convene',sessionId: session.id,- authorId: 'system',- kind: 'decision',- body: summary.body,- decision: { headline: summary.headline, body: summary.body },+ conversationId: session.conversation_id,+ companyId,+ kind: 'ended',+ }).catch((error) => {+ console.warn(`[convene] session ${session.id} ended but publish failed`, error)})}-- await pool.query(- `UPDATE convene_sessions SET state = 'ended', ended_at = NOW() WHERE id = $1`,- [session.id],- )- const companyId = (await companyIdForConversation(session.conversation_id)) ?? undefined- await publish(CH_CONVENE, {- type: 'convene',- sessionId: session.id,- conversationId: session.conversation_id,- companyId,- kind: 'ended',- })}async function runAgentTurn(args: {session: SessionRow+ companyId: stringagentId: string- groundingHistory: ResponseInputItem[]topic: string}): Promise<void> {+ const snapshot = await loadAuthorizedTurnSnapshot(args)+ if (!snapshot) returnconst persona = await getPersona(args.agentId)if (!persona) returnawait setStatus(args.agentId, 'thinking')- const { rows: transcript } = await pool.query<{ author_id: string; kind: string; body: string }>(- `SELECT author_id, kind, body FROM convene_transcript- WHERE session_id = $1 ORDER BY sequence ASC`,- [args.session.id],- )- // Pre-fetch every distinct author's name in one round-trip.- const distinctAuthors = [...new Set(transcript.map((t) => t.author_id))]- const nameByAuthor = new Map<string, string>()- for (const a of distinctAuthors) {- const p = await getPersona(a)- if (p) nameByAuthor.set(a, p.name)- }- const transcriptHistory: ResponseInputItem[] = transcript.map((t) => ({- role: t.author_id === args.agentId ? 'assistant' : 'user',- content: `[${nameByAuthor.get(t.author_id) ?? t.author_id}]: ${t.body}`,- }))-const baseSystem = await buildSystemPrompt(args.agentId)const sys = `${baseSystem ?? persona.style}@@ -201,10 +269,9 @@ You're in a LIVE CONVENE — a real-time work session. Other team members will sTopic of this convene: ${args.topic}`- const tenant = (await companyIdForConversation(args.session.conversation_id)) ?? nullconst client = await getTrackedLlmClient({purpose: 'convene-speech',- companyId: tenant,+ companyId: args.companyId,agentId: args.agentId,conversationId: args.session.conversation_id,extras: { sessionId: args.session.id, topic: args.topic.slice(0, 120) },@@ -215,8 +282,8 @@ Topic of this convene: ${args.topic}`model: enforceModelPolicy(realTaskModel(persona.model), 'convene-speech'),instructions: sys,input: [- ...args.groundingHistory,- ...transcriptHistory,+ ...snapshot.groundingHistory,+ ...snapshot.transcriptHistory,{ role: 'user', content: `[Convene moderator]: ${persona.name}, your turn.` },],max_output_tokens: 3000,@@ -229,6 +296,89 @@ Topic of this convene: ${args.topic}`await setStatus(args.agentId, 'avail')}+async function loadAuthorizedTurnSnapshot(args: {+ session: SessionRow+ companyId: string+ agentId: string+}): Promise<{+ groundingHistory: ResponseInputItem[]+ transcriptHistory: ResponseInputItem[]+} | null> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const participant = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL+ FOR SHARE`,+ [args.agentId, args.companyId],+ )+ if (!participant.rowCount) {+ await client.query('ROLLBACK')+ 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`,+ [args.session.conversation_id, args.companyId, args.agentId],+ )+ if (!conversation.rowCount) {+ await client.query('ROLLBACK')+ return null+ }+ const liveSession = await client.query(+ `SELECT id FROM convene_sessions+ WHERE id = $1 AND conversation_id = $2 AND company_id = $3 AND state = 'live'+ FOR SHARE`,+ [args.session.id, args.session.conversation_id, args.companyId],+ )+ if (!liveSession.rowCount) {+ await client.query('ROLLBACK')+ return null+ }+ const { rows: contextRows } = await client.query<{+ author_id: string; author_name: string; body: string+ }>(+ `SELECT m.author_id, COALESCE(p.name, m.author_id) AS author_name, m.body+ FROM messages m+ LEFT JOIN participants p ON p.id = m.author_id AND p.company_id = m.company_id+ WHERE m.conversation_id = $1 AND m.company_id = $2+ AND m.kind IN ('text','thought')+ ORDER BY m.sequence DESC LIMIT 12`,+ [args.session.conversation_id, args.companyId],+ )+ const { rows: transcriptRows } = await client.query<{+ author_id: string; author_name: string; body: string+ }>(+ `SELECT t.author_id, COALESCE(p.name, t.author_id) AS author_name, t.body+ FROM convene_transcript t+ LEFT JOIN participants p ON p.id = t.author_id AND p.company_id = $2+ WHERE t.session_id = $1+ ORDER BY t.sequence ASC`,+ [args.session.id, args.companyId],+ )+ await client.query('COMMIT')+ return {+ groundingHistory: contextRows.reverse().map((row): ResponseInputItem => ({+ role: 'user',+ content: `[${row.author_name}]: ${row.body}`,+ })),+ transcriptHistory: transcriptRows.map((row): ResponseInputItem => ({+ role: row.author_id === args.agentId ? 'assistant' : 'user',+ content: `[${row.author_name}]: ${row.body}`,+ })),+ }+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}+/** Strip hallucinated tool-call XML when the LLM has no real tools. */function sanitizeToolCallMarkup(s: string): string {return sdiff --git a/server/src/agents/membership.ts b/server/src/agents/membership.tsindex 01a8596..7d8c418 100644--- a/server/src/agents/membership.ts+++ b/server/src/agents/membership.ts@@ -9,17 +9,135 @@* 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 so the mailbox scheduler wakes everyone- * who's a member at message-creation time — including the newly- * added member (for joins) or the departing one (for leaves /- * kicks, when the system message is posted BEFORE the members- * array update).+ * 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+ * notices carry a durable delivery recipient so the removed agent still+ * sees the one row that explains why the conversation disappeared.** Putting both in one file keeps the CLI and HTTP paths from drifting.*/import { randomUUID } from 'node:crypto'+import type { PoolClient } from 'pg'import { pool } from '../db/pool.js'-import { CH_MESSAGE_NEW, publish } from '../redis.js'+import { CH_MESSAGE_NEW, publish, type MessageNewEvent } from '../redis.js'++export type MembershipKind = 'joined' | 'left' | 'kicked'++export interface MembershipMutationResult {+ /** The current database value after this operation serialized on the row. */+ members: string[]+ /** Audit row committed atomically with the membership change. */+ 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. */+async function withActiveParticipantLocks<T>(args: {+ participantIds: string[]+ companyId: string+ run: (client: PoolClient) => Promise<T>+}): Promise<T | null> {+ const client = await pool.connect()+ const participantIds = [...new Set(args.participantIds)].sort()+ try {+ await client.query('BEGIN')+ const { rows } = await client.query<{ id: string }>(+ `SELECT id+ FROM participants+ WHERE company_id = $1+ AND id = ANY($2::text[])+ AND departed_at IS NULL+ ORDER BY id+ FOR UPDATE`,+ [args.companyId, participantIds],+ )+ if (rows.length !== participantIds.length) {+ await client.query('ROLLBACK')+ return null+ }+ const result = await args.run(client)+ await client.query('COMMIT')+ return result+ } catch (err) {+ await client.query('ROLLBACK').catch(() => { /* preserve original error */ })+ throw err+ } finally {+ client.release()+ }+}++async function insertMembershipSystemMessage(args: {+ client: PoolClient+ conversationId: string+ companyId: string+ actorId: string+ kind: MembershipKind+ participantId: string+ members: string[]+}): Promise<CommittedMembershipChange> {+ const messageId = `m-${randomUUID()}`+ const sequence = await nextConversationSequenceWithClient(args.client, args.conversationId)+ const body = JSON.stringify({+ kind: args.kind,+ participantId: args.participantId,+ actorId: args.actorId,+ })+ const deliveryRecipientId = args.kind === 'joined' ? null : args.participantId+ await args.client.query(+ `INSERT INTO messages (+ id, conversation_id, author_id, kind, body, sequence, company_id,+ delivery_recipient_id+ ) VALUES ($1,$2,$3,'system',$4,$5,$6,$7)`,+ [+ messageId, args.conversationId, args.actorId, body, sequence,+ args.companyId, deliveryRecipientId,+ ],+ )+ return {+ result: { members: args.members, systemMessageId: messageId },+ event: {+ type: 'message.new',+ 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 } : {}),+ },+ },+ }+}++/** 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+}/*** Add `memberId` to a conversation's member list and return the list as it@@ -38,37 +156,62 @@ import { CH_MESSAGE_NEW, publish } from '../redis.js'* while the agent's mailbox query (`members @> [agentId]`) never matches, so* they are simply never woken for that conversation again.*- * `companyId` is the tenant guard the HTTP paths already applied; omit it on- * the agent CLI paths, which resolve the conversation by id.+ * 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.*- * Returns null when the conversation does not exist (or is not in that tenant).+ * Returns null when the write was not authorized or no longer necessary. The+ * helper intentionally performs no fallback SELECT: a second statement would+ * create an ABA window in which a removed-and-reinvited actor could turn a+ * rejected mutation into an apparent idempotent success.*/export async function addConversationMember(args: {conversationId: stringmemberId: string- companyId?: string | null-}): Promise<string[] | null> {- const tenant = args.companyId ? ' AND company_id = $3' : ''- const params = args.companyId- ? [args.conversationId, args.memberId, args.companyId]- : [args.conversationId, args.memberId]- const { rows } = await pool.query<{ members: string[] }>(- `UPDATE conversations+ /** The member authorizing this mutation. Checked in the UPDATE itself so a+ * concurrent kick/revocation cannot leave a stale request authorized. */+ actorId: string+ companyId: string+}): Promise<MembershipMutationResult | null> {+ const committed = await withActiveParticipantLocks({+ participantIds: [args.actorId, args.memberId],+ companyId: args.companyId,+ run: async (client) => {+ const { rows } = await client.query<{ members: string[] }>(+ `UPDATE conversations cSET members = members || to_jsonb(ARRAY[$2::text]), updated_at = NOW()- WHERE id = $1 AND NOT (members @> to_jsonb(ARRAY[$2::text]))${tenant}+ 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`,- params,- )- if (rows[0]) return rows[0].members- // No row updated: either they were already a member — which is the outcome- // the caller wanted, and the reason the guard is in the WHERE rather than- // only in JavaScript — or the conversation is gone. Read back to tell those- // apart, and to answer with a current list rather than a stale one.- const { rows: current } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1${args.companyId ? ' AND company_id = $2' : ''}`,- args.companyId ? [args.conversationId, args.companyId] : [args.conversationId],- )- return current[0]?.members ?? null+ [args.conversationId, args.memberId, args.actorId, args.companyId],+ )+ if (!rows[0]) return null+ return insertMembershipSystemMessage({+ client,+ conversationId: args.conversationId,+ companyId: args.companyId,+ actorId: args.actorId,+ kind: 'joined',+ participantId: args.memberId,+ members: rows[0].members,+ })+ },+ })+ return publishCommittedMembershipChange(committed)}/**@@ -81,26 +224,64 @@ export async function addConversationMember(args: {export async function removeConversationMember(args: {conversationId: stringmemberId: string- companyId?: string | null-}): Promise<string[] | null> {- const tenant = args.companyId ? ' AND company_id = $3' : ''- const params = args.companyId- ? [args.conversationId, args.memberId, args.companyId]- : [args.conversationId, args.memberId]- const { rows } = await pool.query<{ members: string[] }>(- `UPDATE conversations+ actorId: string+ companyId: string+ /** Leave is allowed to remove the final member. Kick passes this only after+ * explicit --confirm-empty; keeping the cardinality predicate in the UPDATE+ * makes two concurrent kicks re-check it after the row lock is acquired. */+ allowSoleMember?: boolean+ kind: 'left' | 'kicked'+}): Promise<MembershipMutationResult | null> {+ if ((args.kind === 'left') !== (args.actorId === args.memberId)) {+ throw new Error('membership removal kind does not match actor/participant')+ }+ const committed = await withActiveParticipantLocks({+ participantIds: [args.actorId, args.memberId],+ companyId: args.companyId,+ run: async (client) => {+ const { rows } = await client.query<{ members: string[] }>(+ `UPDATE conversations cSET members = members - $2::text, updated_at = NOW()- WHERE id = $1${tenant}+ 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`,- params,- )- return rows[0]?.members ?? null+ [args.conversationId, args.memberId, args.actorId, args.companyId, Boolean(args.allowSoleMember)],+ )+ if (!rows[0]) return null+ return insertMembershipSystemMessage({+ client,+ conversationId: args.conversationId,+ companyId: args.companyId,+ actorId: args.actorId,+ kind: args.kind,+ participantId: args.memberId,+ members: rows[0].members,+ })+ },+ })+ return publishCommittedMembershipChange(committed)}/** Atomically claim the next sequence number for a conversation.* Same UPSERT pattern as the human reply path and `cumora reply`. */-export async function nextConversationSequence(conversationId: string): Promise<number> {- const { rows } = await pool.query<{ seq: number }>(+async function nextConversationSequenceWithClient(+ client: PoolClient,+ conversationId: string,+): Promise<number> {+ const { rows } = await client.query<{ seq: number }>(`INSERT INTO conversation_counters (conversation_id, next_sequence)VALUES ($1, 2)ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1@@ -110,45 +291,13 @@ export async function nextConversationSequence(conversationId: string): Promise<return rows[0]?.seq ?? 1}-export type MembershipKind = 'joined' | 'left' | 'kicked'--/** Insert a membership system row + broadcast it. Order of operations- * vs the actual `conversations.members` mutation matters:- * - For 'joined': call AFTER members has been updated. The new- * member is now in the array, so the scheduler wakes them on the- * CH_MESSAGE_NEW event and they perceive the join.- * - For 'left' / 'kicked': call BEFORE removing the departing- * member. The mailbox query filters by current members, so if we- * removed them first they'd never see the system row that explains- * why their inbox went quiet. */-export async function postMembershipSystemMessage(args: {- conversationId: string- companyId: string | null- actorId: string- kind: MembershipKind- participantId: string-}): Promise<{ messageId: string; sequence: number }> {- const messageId = `m-${randomUUID()}`- const sequence = await nextConversationSequence(args.conversationId)- const body = JSON.stringify({- kind: args.kind,- participantId: args.participantId,- actorId: args.actorId,- })- await pool.query(- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)- VALUES ($1,$2,$3,'system',$4,$5,$6)`,- [messageId, args.conversationId, args.actorId, body, sequence, args.companyId],+export async function nextConversationSequence(conversationId: string): Promise<number> {+ const { rows } = await pool.query<{ seq: number }>(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1+ RETURNING next_sequence - 1 AS seq`,+ [conversationId],)- await publish(CH_MESSAGE_NEW, {- type: 'message.new',- conversationId: args.conversationId,- companyId: args.companyId ?? undefined,- message: {- id: messageId, conversationId: args.conversationId, authorId: args.actorId,- kind: 'system', body, sequence,- at: new Date().toISOString(),- },- })- return { messageId, sequence }+ return rows[0]?.seq ?? 1}diff --git a/server/src/agents/private_chat.ts b/server/src/agents/private_chat.tsindex 273b9f0..daddb41 100644--- a/server/src/agents/private_chat.ts+++ b/server/src/agents/private_chat.ts@@ -10,45 +10,35 @@* doesn't change the data model.)*/import { randomUUID } from 'node:crypto'+import type { PoolClient } from 'pg'import { pool } from '../db/pool.js'import { CH_MESSAGE_NEW, publish } from '../redis.js'-import { companyIdForParticipant } from '../tenant.js'--/** A participant's display name + kind, for ANY participant — human OR agent.- * Unlike getPersona (which is agent-only: `kind='agent'`), this resolves humans- * too, so an agent can open a DM with a person and we can title the thread with- * the person's real name. */-async function participantBrief(id: string): Promise<{ name: string; kind: string } | null> {- const { rows } = await pool.query<{ name: string; kind: string }>(- `SELECT name, kind FROM participants WHERE id = $1 AND departed_at IS NULL`,- [id],- )- return rows[0] ?? null-}/** Find an existing direct conversation between two participants, or* create one and return its id. Order-independent on members. */async function findOrCreateDirect(+ client: PoolClient,aId: string,bId: string,- companyId: string | null,+ companyId: string,topic: string | null,+ aName: string,+ bName: string,): Promise<string> {- const { rows } = await pool.query<{ id: string }>(+ const { rows } = await client.query<{ id: string }>(`SELECT id FROM conversationsWHERE kind = 'direct'AND members @> $1::jsonbAND members @> $2::jsonbAND jsonb_array_length(members) = 2- ${companyId ? 'AND company_id = $3' : ''}- ORDER BY created_at DESC LIMIT 1`,- companyId- ? [JSON.stringify([aId]), JSON.stringify([bId]), companyId]- : [JSON.stringify([aId]), JSON.stringify([bId])],+ AND company_id = $3+ ORDER BY created_at DESC LIMIT 1+ FOR UPDATE`,+ [JSON.stringify([aId]), JSON.stringify([bId]), companyId],)if (rows[0]) {if (topic) {- await pool.query(+ await client.query(`UPDATE conversations SET topic = $2, updated_at = NOW() WHERE id = $1`,[rows[0].id, topic],)@@ -56,11 +46,8 @@ async function findOrCreateDirect(return rows[0].id}- const [aBrief, bBrief] = await Promise.all([participantBrief(aId), participantBrief(bId)])- const aName = aBrief?.name ?? aId- const bName = bBrief?.name ?? bIdconst id = `direct-${randomUUID().slice(0, 12)}`- await pool.query(+ await client.query(`INSERT INTO conversations(id, kind, title, members, company_id, topic)VALUES ($1, 'direct', $2, $3::jsonb, $4, $5)`,@@ -71,8 +58,8 @@ async function findOrCreateDirect(/** Atomic per-conversation sequence claim — same mechanism as cmdReply* and the HTTP POST messages handler. */-async function nextConversationSequence(conversationId: string): Promise<number> {- const { rows } = await pool.query<{ seq: number }>(+async function nextConversationSequence(client: PoolClient, conversationId: string): Promise<number> {+ const { rows } = await client.query<{ seq: number }>(`INSERT INTO conversation_counters (conversation_id, next_sequence)VALUES ($1, 2)ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1@@ -82,6 +69,65 @@ async function nextConversationSequence(conversationId: string): Promise<number>return rows[0]?.seq ?? 1}+/** Ensure one direct conversation exists for an active same-tenant pair.+ * All DM creation entry points share the same participant lock order and+ * advisory pair key, preventing stale/departed members and duplicate rooms. */+export async function ensureDirectConversation(args: {+ companyId: string+ firstId: string+ secondId: string+ topic?: string | null+}): Promise<string> {+ if (args.firstId === args.secondId) throw new Error('cannot open a DM with yourself')+ const participantIds = [args.firstId, args.secondId].sort()+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const { rows: participants } = await client.query<{ id: string; name: string }>(+ `SELECT p.id, p.name FROM participants p+ WHERE p.company_id = $1 AND p.id = ANY($2::text[])+ AND p.kind IN ('agent', 'human') AND p.departed_at IS NULL+ AND (+ p.kind = 'agent'+ OR EXISTS (+ SELECT 1 FROM users u+ JOIN company_members cm ON cm.user_id = u.id AND cm.company_id = p.company_id+ WHERE u.id = p.id AND u.deleted_at IS NULL+ )+ )+ ORDER BY p.id FOR SHARE`,+ [args.companyId, participantIds],+ )+ if (participants.length !== 2) throw new Error('direct-chat participant is foreign, departed, or missing')+ await client.query(+ `SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))`,+ [args.companyId, JSON.stringify(participantIds)],+ )+ const names = new Map(participants.map((participant) => [participant.id, participant.name]))+ const conversationId = await findOrCreateDirect(+ client,+ args.firstId,+ args.secondId,+ args.companyId,+ args.topic ?? null,+ names.get(args.firstId) ?? args.firstId,+ names.get(args.secondId) ?? args.secondId,+ )+ await client.query(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 1) ON CONFLICT (conversation_id) DO NOTHING`,+ [conversationId],+ )+ await client.query('COMMIT')+ return conversationId+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}+/** Open (or post into) a private 1-on-1 chat between two participants.* Idempotent on the conversation creation — repeated calls between the* same pair reuse the existing direct conversation. */@@ -95,45 +141,89 @@ export async function startPrivateChat(args: {// Humans and agents use the same direct-conversation model. Validate both// endpoints by active participant existence rather than agent persona presence.if (instigatorId === partnerId) throw new Error('cannot open a DM with yourself')- const [instigator, partner] = await Promise.all([- participantBrief(instigatorId),- participantBrief(partnerId),- ])- if (!instigator) throw new Error(`private-chat instigator not found: ${instigatorId}`)- if (!partner) throw new Error(`private-chat partner not found: ${partnerId}`)-- const companyId = (await companyIdForParticipant(instigatorId)) ?? null- const conversationId = await findOrCreateDirect(instigatorId, partnerId, companyId, topic || null)-- const messageId = `m-${randomUUID()}`- const sequence = await nextConversationSequence(conversationId)- await pool.query(- `INSERT INTO messages- (id, conversation_id, author_id, kind, body, sequence, company_id)- VALUES ($1, $2, $3, 'text', $4, $5, $6)`,- [messageId, conversationId, instigatorId, opening, sequence, companyId],+ const { rows: tenantRows } = await pool.query<{ company_id: string }>(+ `SELECT company_id FROM participants+ WHERE id = $1 AND kind IN ('agent', 'human') AND departed_at IS NULL+ LIMIT 1`,+ [instigatorId],)- await pool.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [conversationId])+ const companyId = tenantRows[0]?.company_id+ if (!companyId) throw new Error(`private-chat instigator not found: ${instigatorId}`)- // Posting auto-acks the instigator on this conversation.- await pool.query(- `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)- VALUES ($1, $2, NOW())- ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,- [instigatorId, conversationId],- )+ let conversationId = ''+ const messageId = `m-${randomUUID()}`+ let sequence = 0+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const participantIds = [instigatorId, partnerId].sort()+ const { rows: participants } = await client.query<{ id: string; name: string }>(+ `SELECT p.id, p.name FROM participants p+ WHERE p.company_id = $1 AND p.id = ANY($2::text[])+ AND p.kind IN ('agent', 'human') AND p.departed_at IS NULL+ AND (+ p.kind = 'agent'+ OR EXISTS (+ SELECT 1 FROM users u+ JOIN company_members cm ON cm.user_id = u.id AND cm.company_id = p.company_id+ WHERE u.id = p.id AND u.deleted_at IS NULL+ )+ )+ ORDER BY p.id FOR SHARE`,+ [companyId, participantIds],+ )+ if (participants.length !== 2) {+ throw new Error(`private-chat partner is foreign, departed, or missing: ${partnerId}`)+ }+ await client.query(+ `SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))`,+ [companyId, JSON.stringify(participantIds)],+ )+ const names = new Map(participants.map((participant) => [participant.id, participant.name]))+ conversationId = await findOrCreateDirect(+ client,+ instigatorId,+ partnerId,+ companyId,+ topic || null,+ names.get(instigatorId) ?? instigatorId,+ names.get(partnerId) ?? partnerId,+ )+ sequence = await nextConversationSequence(client, conversationId)+ await client.query(+ `INSERT INTO messages+ (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'text', $4, $5, $6)`,+ [messageId, conversationId, instigatorId, opening, sequence, companyId],+ )+ await client.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [conversationId])+ await client.query(+ `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)+ VALUES ($1, $2, NOW())+ ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW()`,+ [instigatorId, conversationId],+ )+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }// Same channel as every other message. Agent recipients wake through the// mailbox scheduler; human recipients see the direct conversation normally.await publish(CH_MESSAGE_NEW, {type: 'message.new',conversationId,- companyId: companyId ?? undefined,+ companyId,message: {id: messageId, conversationId, authorId: instigatorId,kind: 'text', body: opening, sequence,at: new Date().toISOString(),},+ }).catch((error) => {+ console.warn(`[private_chat] durable message ${messageId} committed but publish failed`, error)})return { conversationId, messageId }diff --git a/server/src/agents/runtime/authorization.ts b/server/src/agents/runtime/authorization.tsindex dfa8d97..ec2ec7b 100644--- a/server/src/agents/runtime/authorization.ts+++ b/server/src/agents/runtime/authorization.ts@@ -1,4 +1,5 @@import { pool } from '../../db/pool.js'+import type { PoolClient } from 'pg'/*** A signed runtime token captures the agent's tenant at mint time. Resolve the@@ -19,3 +20,104 @@ export async function isRuntimeAgentAuthorized()return rowCount === 1}++/** Hold the current agent and every requested conversation membership stable+ * while an ephemeral Redis/pubsub side effect runs. Membership mutation uses+ * the same participant -> conversation lock order, so a revoke is linearized+ * either wholly before or wholly after the side effect. */+export async function withRuntimeConversationAuthorization<T>(args: {+ agentId: string+ companyId: string+ conversationIds: readonly string[]+ task: () => Promise<T>+}): Promise<{ authorized: boolean; result?: T }> {+ const conversationIds = [...new Set(args.conversationIds)].sort()+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const participant = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL+ FOR SHARE`,+ [args.agentId, args.companyId],+ )+ if (!participant.rowCount) {+ await client.query('ROLLBACK')+ return { authorized: false }+ }+ 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`,+ [args.companyId, conversationIds, args.agentId],+ )+ if (conversations.rows.length !== conversationIds.length) {+ await client.query('ROLLBACK')+ return { authorized: false }+ }+ }+ const result = await args.task()+ await client.query('COMMIT')+ return { authorized: true, result }+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}++/** Authorize a read-cursor advance against the exact persisted message. The+ * durable departure-recipient exception lets a just-kicked agent acknowledge+ * its one terminal system row without restoring conversation access. */+export async function withRuntimeMessageReadAuthorization<T>(args: {+ agentId: string+ companyId: string+ conversationId: string+ messageId: string+ task: (client: PoolClient) => Promise<T>+}): Promise<{ authorized: boolean; result?: T }> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const participant = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL+ FOR SHARE`,+ [args.agentId, args.companyId],+ )+ if (!participant.rowCount) {+ await client.query('ROLLBACK')+ return { authorized: false }+ }+ const allowed = await client.query(+ `SELECT m.id+ FROM conversations c+ JOIN messages m+ ON m.id = $4 AND m.conversation_id = c.id AND m.company_id = c.company_id+ WHERE c.id = $1 AND c.company_id = $2+ AND (+ c.members @> to_jsonb(ARRAY[$3::text])+ OR (m.kind = 'system' AND m.delivery_recipient_id = $3)+ )+ FOR SHARE OF c, m`,+ [args.conversationId, args.companyId, args.agentId, args.messageId],+ )+ if (!allowed.rowCount) {+ await client.query('ROLLBACK')+ return { authorized: false }+ }+ const result = await args.task(client)+ await client.query('COMMIT')+ return { authorized: true, result }+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}diff --git a/server/src/agents/runtime/client.ts b/server/src/agents/runtime/client.tsindex 64d43e4..ecc1406 100644--- a/server/src/agents/runtime/client.ts+++ b/server/src/agents/runtime/client.ts@@ -344,9 +344,10 @@ export interface AgentRuntimeClient {* Body shape: `{ kind: 'notice', noticeKind, text }` — SystemRow renders* the text as a centered italic line.*- * `dedupeKey` + `dedupeTtlSec` deduplicate via Redis NX/EX so multiple- * agents 429-ing in the same room don't all post the same notice. Returns- * `{ posted }` — false when the dedupe window swallowed it. */+ * `dedupeKey` + `dedupeTtlSec` use a durable PostgreSQL idempotency marker+ * so multiple agents failing in the same room do not post duplicates, even+ * across Redis/process failures. Returns `{ posted }` — false when the+ * dedupe window swallowed it. */postSystemNotice(args: {conversationId: stringcompanyId?: string | null@@ -383,6 +384,7 @@ export interface AgentRuntimeClient {* cursor is already past, this is a no-op. */markConversationRead(args: {agentId: string+ companyId?: string | nullconversationId: stringupToMessageId: string}): Promise<void>diff --git a/server/src/agents/runtime/inproc-client.ts b/server/src/agents/runtime/inproc-client.tsindex 41969b9..3c9086a 100644--- a/server/src/agents/runtime/inproc-client.ts+++ b/server/src/agents/runtime/inproc-client.ts@@ -14,7 +14,8 @@* The pod-side HttpRuntimeClient (Phase 3) will speak the same shapes* over HTTP.*/-import { randomUUID } from 'node:crypto'+import { createHash, randomUUID } from 'node:crypto'+import type { PoolClient } from 'pg'import { pool } from '../../db/pool.js'import { CH_MESSAGE_NEW, CH_TYPING, publish, redis } from '../../redis.js'import { notifyAlert } from '../../alerting.js'@@ -45,7 +46,6 @@ async function refreshAttachmentUrls(rows: ReadonlyArray<{ attachment?: unknownconst inprocBusyHeartbeatFailures = new Map<string, number>()const INPROC_BUSY_HEARTBEAT_ALERT_THRESHOLD = 5import { companyIdForConversation } from '../../tenant.js'-import { nextConversationSequence } from '../membership.js'import { getPersona } from '../personas.js'import {setStatus as setStatusImpl,@@ -153,21 +153,38 @@ export class InProcRuntimeClient implements AgentRuntimeClient {try {await client.query('SET enable_seqscan = off')const res = await client.query<InboxRow>(- `WITH convos AS (+ `WITH requesting_agent AS MATERIALIZED (+ SELECT company_id+ FROM participants+ WHERE id = $1 AND kind = 'agent' AND departed_at IS NULL+ ),+ convos AS (SELECT c.id, c.company_id,c.title AS conversation_title, c.kind AS conversation_kind, c.topic AS conversation_topic,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,EXISTS (SELECT 1 FROM conversation_mutes muWHERE mu.user_id = $1 AND mu.conversation_id = c.idAND (mu.muted_until IS NULL OR mu.muted_until > NOW())) AS muted- FROM conversations c+ FROM requesting_agent ra+ JOIN conversations c ON c.company_id = ra.company_idLEFT JOIN conversation_reads cr ON cr.user_id = $1 AND cr.conversation_id = c.idLEFT JOIN projects pr ON pr.id = c.project_idWHERE c.members @> to_jsonb(ARRAY[$1::text])+ OR EXISTS (+ SELECT 1+ FROM messages delivered+ WHERE delivered.conversation_id = c.id+ AND delivered.delivery_recipient_id = $1+ AND ROW(delivered.created_at, delivered.id) > ROW(+ COALESCE(cr.last_read_at, '1970-01-01T00:00:00Z'::timestamptz),+ COALESCE(cr.last_read_message_id, '')+ )+ ))SELECTm.id, m.conversation_id, co.company_id,@@ -191,10 +208,12 @@ export class InProcRuntimeClient implements AgentRuntimeClient {-- last_read_message_id as a tiebreaker for same-instant messages.SELECT * FROM messages mmWHERE mm.conversation_id = co.id- AND mm.author_id <> $1+ AND (co.current_member OR mm.delivery_recipient_id = $1)+ AND (mm.author_id <> $1 OR mm.delivery_recipient_id = $1)AND ROW(mm.created_at, mm.id) > ROW(co.lr_at, co.lr_id)AND (- NOT co.muted+ mm.delivery_recipient_id = $1+ OR NOT co.mutedOR co.conversation_kind = 'direct'OR EXISTS (SELECT 1 FROM regexp_matches(mm.body, '@([[:alnum:]_-]+)', 'g') mention@@ -608,25 +627,6 @@ export class InProcRuntimeClient implements AgentRuntimeClient {}}- /** Is `agentId` a member of `conversationId`, scoped to `companyId` when- * given? Used to keep JWT-pinned writes (e.g. postSystemNotice) from- * touching conversations the caller isn't in. */- async isConversationMember(- conversationId: string,- agentId: string,- companyId?: string | null,- ): Promise<boolean> {- const { rows } = await pool.query<{ ok: boolean }>(- `SELECT 1 AS ok FROM conversations- WHERE id = $1- AND ($3::text IS NULL OR company_id = $3)- AND members @> to_jsonb(ARRAY[$2::text])- LIMIT 1`,- [conversationId, agentId, companyId ?? null],- )- return rows.length > 0- }-async postSystemNotice(args: {conversationId: stringcompanyId?: string | null@@ -635,41 +635,113 @@ export class InProcRuntimeClient implements AgentRuntimeClient {text: stringdedupeKey: stringdedupeTtlSec: number- }): Promise<{ posted: boolean }> {- // NX/EX deduplication: first caller to set the key wins and posts the- // notice; everyone else gets `posted: false`. The key namespace lives- // entirely in Redis so it auto-expires and survives across pods.- const lockKey = `notice:${args.dedupeKey}`- const acquired = await redis.set(- lockKey, args.agentId,- 'EX', args.dedupeTtlSec,- 'NX',- )- if (acquired !== 'OK') return { posted: false }-+ }): Promise<{ posted: boolean; authorized: boolean }> {+ const companyId = args.companyId+ ?? await companyIdForConversation(args.conversationId)+ if (!companyId) return { posted: false, authorized: false }+ const ttlSec = Math.max(1, Math.min(Math.floor(args.dedupeTtlSec), 7 * 24 * 3600))+ const dedupeFingerprint = createHash('sha256')+ .update(`${companyId}\0${args.conversationId}\0${args.dedupeKey}`)+ .digest('hex')+ const clientId = `runtime-notice:${dedupeFingerprint}`const messageId = `m-${randomUUID()}`- const sequence = await nextConversationSequence(args.conversationId)const body = JSON.stringify({kind: 'notice',noticeKind: args.noticeKind,text: args.text,})- await pool.query(- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)- VALUES ($1,$2,$3,'system',$4,$5,$6)`,- [messageId, args.conversationId, args.agentId, body, sequence, args.companyId ?? null],- )+ let sequence = 0+ let posted = false+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const participant = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL+ FOR SHARE`,+ [args.agentId, companyId],+ )+ if (!participant.rowCount) {+ await client.query('ROLLBACK')+ 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`,+ [args.conversationId, companyId, args.agentId],+ )+ if (!conversation.rowCount) {+ await client.query('ROLLBACK')+ return { posted: false, authorized: false }+ }++ // PostgreSQL is the durable idempotency boundary. The advisory lock+ // serializes all agents using the same room/key, while client_id lets a+ // committed notice survive Redis/process failures. Clear only expired+ // markers so the original rolling TTL semantics remain intact.+ await client.query(+ `SELECT pg_advisory_xact_lock(hashtext('runtime-notice'), hashtext($1))`,+ [dedupeFingerprint],+ )+ await client.query(+ `UPDATE messages SET client_id = NULL+ WHERE conversation_id = $1 AND client_id = $2+ AND created_at <= NOW() - make_interval(secs => $3::int)`,+ [args.conversationId, clientId, ttlSec],+ )+ const recent = await client.query(+ `SELECT 1 FROM messages+ WHERE conversation_id = $1 AND client_id = $2+ AND created_at > NOW() - make_interval(secs => $3::int)+ LIMIT 1`,+ [args.conversationId, clientId, ttlSec],+ )+ if (recent.rowCount) {+ await client.query('COMMIT')+ return { posted: false, authorized: true }+ }++ const seqRes = await client.query<{ seq: number }>(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE+ SET next_sequence = conversation_counters.next_sequence + 1+ RETURNING next_sequence - 1 AS seq`,+ [args.conversationId],+ )+ sequence = seqRes.rows[0]?.seq ?? 1+ await client.query(+ `INSERT INTO messages+ (id, conversation_id, author_id, kind, body, sequence, company_id, client_id)+ VALUES ($1,$2,$3,'system',$4,$5,$6,$7)`,+ [messageId, args.conversationId, args.agentId, body, sequence, companyId, clientId],+ )+ await client.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [args.conversationId])+ await client.query('COMMIT')+ posted = true+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+await publish(CH_MESSAGE_NEW, {type: 'message.new',conversationId: args.conversationId,- companyId: args.companyId ?? undefined,+ companyId,message: {id: messageId, conversationId: args.conversationId, authorId: args.agentId,kind: 'system', body, sequence,at: new Date().toISOString(),},+ }).catch((error) => {+ console.warn(`[runtime] durable notice ${messageId} committed but publish failed`, error)})- return { posted: true }+ return { posted, authorized: true }}// ─── Steering busy heartbeat ──────────────────────────────────────@@ -978,18 +1050,31 @@ export class InProcRuntimeClient implements AgentRuntimeClient {async markConversationRead(args: {agentId: string+ companyId?: string | nullconversationId: stringupToMessageId: string- }): Promise<void> {+ }, dbClient?: PoolClient): Promise<void> {// Monotonic advance via ROW comparison: only update the cursor// when the incoming (created_at, message_id) pair lexicographically// exceeds the existing pair. This makes the operation idempotent,// out-of-order safe, AND collision-safe — two messages with the// same created_at are distinguishable by id.try {- await pool.query(+ await (dbClient ?? pool).query(`WITH msg AS (- SELECT created_at, id AS message_id FROM messages WHERE id = $1+ SELECT m.created_at, m.id AS message_id+ FROM messages m+ JOIN conversations c+ ON c.id = m.conversation_id AND c.company_id = m.company_id+ JOIN participants p+ ON p.id = $2 AND p.company_id = c.company_id+ AND p.kind = 'agent' AND p.departed_at IS NULL+ WHERE m.id = $1 AND m.conversation_id = $3+ AND ($4::text IS NULL OR c.company_id = $4)+ AND (+ c.members @> to_jsonb(ARRAY[$2::text])+ OR (m.kind = 'system' AND m.delivery_recipient_id = $2)+ ))INSERT INTO conversation_reads (user_id, conversation_id, last_read_at, last_read_message_id)SELECT $2, $3, msg.created_at, msg.message_id FROM msg@@ -1003,9 +1088,10 @@ export class InProcRuntimeClient implements AgentRuntimeClient {WHEN ROW(EXCLUDED.last_read_at, EXCLUDED.last_read_message_id)> ROW(conversation_reads.last_read_at, conversation_reads.last_read_message_id)THEN EXCLUDED.last_read_message_id ELSE conversation_reads.last_read_message_id END`,- [args.upToMessageId, args.agentId, args.conversationId],+ [args.upToMessageId, args.agentId, args.conversationId, args.companyId ?? null],)} catch (err) {+ if (dbClient) throw errconsole.warn(`[runtime] markConversationRead(${args.agentId}, ${args.conversationId}, ${args.upToMessageId}) failed — dropping`,err instanceof Error ? err.message : err)}diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.tsindex b01339a..454a138 100644--- a/server/src/agents/runtime/server.ts+++ b/server/src/agents/runtime/server.ts@@ -23,7 +23,11 @@ import { gatherAgentAgenda, classifyAgendaActionable, renderAgendaBrief, claimStimport { consumeAgentTurnToken } from '../scheduler.js'import { touchAgentRun, recordTriage } from '../observability.js'import { normalizeByoaSource } from './byoa-source.js'-import { isRuntimeAgentAuthorized } from './authorization.js'+import {+ isRuntimeAgentAuthorized,+ withRuntimeConversationAuthorization,+ withRuntimeMessageReadAuthorization,+} from './authorization.js'import { buildRuntimeArgv } from './cli-argv.js'import { attachFsEndpoints } from './fs-endpoints.js'import { inprocClient } from './inproc-client.js'@@ -36,6 +40,8 @@ interface RuntimeRequest extends Request {agent?: AgentRuntimeClaims}+type AuthorizedAgentRuntimeClaims = AgentRuntimeClaims & { companyId: string }+async function authMiddleware(req: RuntimeRequest, res: Response, next: NextFunction): Promise<void> {const header = req.headers['authorization']if (!header || typeof header !== 'string' || !header.startsWith('Bearer ')) {@@ -76,13 +82,14 @@ async function authMiddleware(req: RuntimeRequest, res: Response, next: NextFunc}function withAgent(- handler: (claims: AgentRuntimeClaims, req: RuntimeRequest, res: Response) => Promise<void>,+ handler: (claims: AuthorizedAgentRuntimeClaims, req: RuntimeRequest, res: Response) => Promise<void>,) {return async (req: RuntimeRequest, res: Response): Promise<void> => {const claims = req.agentif (!claims) { res.status(401).json({ error: 'unauthenticated' }); return }+ if (!claims.companyId) { res.status(403).json({ error: 'companyId claim required' }); return }try {- await handler(claims, req, res)+ await handler(claims as AuthorizedAgentRuntimeClaims, req, res)} catch (err) {const msg = err instanceof Error ? err.message : String(err)console.error(`[runtime] ${req.method} ${req.path} failed`, msg)@@ -353,12 +360,18 @@ runtimeRouter.post('/status/heartbeat', withAgent(async (c, req, res) => {runtimeRouter.post('/typing', withAgent(async (c, req, res) => {const body = req.body as { conversationId?: string; done?: boolean } | undefinedif (!body?.conversationId) { res.status(400).json({ error: 'conversationId required' }); return }- await inprocClient.publishTyping({- conversationId: body.conversationId,+ const gate = await withRuntimeConversationAuthorization({agentId: c.sub,- done: Boolean(body.done),companyId: c.companyId,+ conversationIds: [body.conversationId],+ task: () => inprocClient.publishTyping({+ conversationId: body.conversationId as string,+ agentId: c.sub,+ done: Boolean(body.done),+ companyId: c.companyId,+ }),})+ if (!gate.authorized) { res.status(403).json({ error: 'not a member of that conversation' }); return }res.json({ ok: true })}))@@ -579,42 +592,65 @@ runtimeRouter.post('/busy/clear', withAgent(async (c, _req, res) => {// ─── thinking-claim — peer-visible "I'm composing" signal ─────────runtimeRouter.post('/thinking/mark', withAgent(async (c, req, res) => {const body = req.body as { conversationIds?: string[]; ttlSec?: number } | undefined- const ids = Array.isArray(body?.conversationIds) ? body!.conversationIds.filter((s) => typeof s === 'string') : []+ const ids = Array.isArray(body?.conversationIds)+ ? [...new Set(body.conversationIds.filter((s) => typeof s === 'string'))].sort()+ : []+ if (ids.length > 100) { res.status(400).json({ error: 'at most 100 conversationIds' }); return }const ttlSec = typeof body?.ttlSec === 'number' && body.ttlSec > 0 && body.ttlSec <= 600 ? body.ttlSec : 60- await inprocClient.markThinking(c.sub, ids, ttlSec)- // Stamp the freshness-preflight compose-anchor for these convos at THE- // SAME moment (NX-preserved, so heartbeats don't keep bumping it later- // and defeating the point — the anchor must reflect TURN START, not- // "most recent heartbeat"). The cli.cmdReply preflight uses this anchor- // to detect peer posts that landed mid-compose even when the agent's- // own glance has since advanced the seen-baseline past them.- if (ids.length > 0) {- const { recordComposeAnchor, getComposeAnchor } = await import('../seen-boundary.js')- const now = Date.now()- await Promise.all(ids.map(async (cid) => {- const existing = await getComposeAnchor(c.sub, cid)- if (existing > 0 && now - existing < 30 * 60_000) return // already stamped this turn — keep the first- await recordComposeAnchor(c.sub, cid, now)- }))- }+ const gate = await withRuntimeConversationAuthorization({+ agentId: c.sub,+ companyId: c.companyId,+ conversationIds: ids,+ task: async () => {+ await inprocClient.markThinking(c.sub, ids, ttlSec)+ // Stamp the freshness-preflight compose-anchor at turn start. NX-style+ // preservation keeps heartbeats from moving the anchor later.+ if (ids.length > 0) {+ const { recordComposeAnchor, getComposeAnchor } = await import('../seen-boundary.js')+ const now = Date.now()+ await Promise.all(ids.map(async (cid) => {+ const existing = await getComposeAnchor(c.sub, cid)+ if (existing > 0 && now - existing < 30 * 60_000) return+ await recordComposeAnchor(c.sub, cid, now)+ }))+ }+ },+ })+ if (!gate.authorized) { res.status(403).json({ error: 'not a member of every conversation' }); return }res.json({ ok: true })}))runtimeRouter.post('/thinking/unmark', withAgent(async (c, req, res) => {const body = req.body as { conversationIds?: string[] } | undefined- const ids = Array.isArray(body?.conversationIds) ? body!.conversationIds.filter((s) => typeof s === 'string') : []- await inprocClient.unmarkThinking(c.sub, ids)- // Clear the compose-anchor too — turn ended, next turn gets a fresh anchor.- if (ids.length > 0) {- const { clearComposeAnchor } = await import('../seen-boundary.js')- await Promise.all(ids.map((cid) => clearComposeAnchor(c.sub, cid)))- }+ const ids = Array.isArray(body?.conversationIds)+ ? [...new Set(body.conversationIds.filter((s) => typeof s === 'string'))].sort()+ : []+ if (ids.length > 100) { res.status(400).json({ error: 'at most 100 conversationIds' }); return }+ const gate = await withRuntimeConversationAuthorization({+ agentId: c.sub,+ companyId: c.companyId,+ conversationIds: ids,+ task: async () => {+ await inprocClient.unmarkThinking(c.sub, ids)+ if (ids.length > 0) {+ const { clearComposeAnchor } = await import('../seen-boundary.js')+ await Promise.all(ids.map((cid) => clearComposeAnchor(c.sub, cid)))+ }+ },+ })+ if (!gate.authorized) { res.status(403).json({ error: 'not a member of every conversation' }); return }res.json({ ok: true })}))-runtimeRouter.get('/thinking/peek', withAgent(async (_c, req, res) => {+runtimeRouter.get('/thinking/peek', withAgent(async (c, req, res) => {const cid = typeof req.query.conversationId === 'string' ? req.query.conversationId : ''if (!cid) { res.status(400).json({ error: 'conversationId required' }); return }- const agents = await inprocClient.peekThinking(cid)- res.json({ agents })+ const gate = await withRuntimeConversationAuthorization({+ agentId: c.sub,+ companyId: c.companyId,+ conversationIds: [cid],+ task: () => inprocClient.peekThinking(cid),+ })+ if (!gate.authorized) { res.status(403).json({ error: 'not a member of that conversation' }); return }+ res.json({ agents: gate.result ?? [] })}))// ─── worklog — anti-duplicate-work claims ───────────────────────────@@ -630,14 +666,21 @@ runtimeRouter.post('/worklog/claim', withAgent(async (c, req, res) => {if (!body?.scopeKey || !body.taskType || !body.subject) {res.status(400).json({ error: 'scopeKey, taskType, subject required' }); return}- const result = await inprocClient.claimWork({- scopeKey: body.scopeKey,+ const scopeConversationIds = body.scopeKey === `tenant:${c.companyId}` ? [] : [body.scopeKey]+ const gate = await withRuntimeConversationAuthorization({agentId: c.sub,- taskType: body.taskType as Parameters<typeof inprocClient.claimWork>[0]['taskType'],- subject: body.subject,- ttlSec: typeof body.ttlSec === 'number' && body.ttlSec > 0 && body.ttlSec <= 3600 ? body.ttlSec : undefined,+ companyId: c.companyId,+ conversationIds: scopeConversationIds,+ task: () => inprocClient.claimWork({+ scopeKey: body.scopeKey as string,+ agentId: c.sub,+ taskType: body.taskType as Parameters<typeof inprocClient.claimWork>[0]['taskType'],+ subject: body.subject as string,+ ttlSec: typeof body.ttlSec === 'number' && body.ttlSec > 0 && body.ttlSec <= 3600 ? body.ttlSec : undefined,+ }),})- res.json(result)+ if (!gate.authorized) { res.status(403).json({ error: 'worklog scope is not authorized' }); return }+ res.json(gate.result)}))runtimeRouter.post('/worklog/release', withAgent(async (c, req, res) => {const body = req.body as {@@ -648,19 +691,33 @@ runtimeRouter.post('/worklog/release', withAgent(async (c, req, res) => {if (!body?.scopeKey || !body.taskType || !body.subject) {res.status(400).json({ error: 'scopeKey, taskType, subject required' }); return}- await inprocClient.releaseWork({- scopeKey: body.scopeKey,+ const scopeConversationIds = body.scopeKey === `tenant:${c.companyId}` ? [] : [body.scopeKey]+ const gate = await withRuntimeConversationAuthorization({agentId: c.sub,- taskType: body.taskType as Parameters<typeof inprocClient.releaseWork>[0]['taskType'],- subject: body.subject,+ companyId: c.companyId,+ conversationIds: scopeConversationIds,+ task: () => inprocClient.releaseWork({+ scopeKey: body.scopeKey as string,+ agentId: c.sub,+ taskType: body.taskType as Parameters<typeof inprocClient.releaseWork>[0]['taskType'],+ subject: body.subject as string,+ }),})+ if (!gate.authorized) { res.status(403).json({ error: 'worklog scope is not authorized' }); return }res.json({ ok: true })}))-runtimeRouter.get('/worklog/peek', withAgent(async (_c, req, res) => {+runtimeRouter.get('/worklog/peek', withAgent(async (c, req, res) => {const sk = typeof req.query.scopeKey === 'string' ? req.query.scopeKey : ''if (!sk) { res.status(400).json({ error: 'scopeKey required' }); return }- const entries = await inprocClient.peekWorklog(sk)- res.json({ entries })+ const scopeConversationIds = sk === `tenant:${c.companyId}` ? [] : [sk]+ const gate = await withRuntimeConversationAuthorization({+ agentId: c.sub,+ companyId: c.companyId,+ conversationIds: scopeConversationIds,+ task: () => inprocClient.peekWorklog(sk),+ })+ if (!gate.authorized) { res.status(403).json({ error: 'worklog scope is not authorized' }); return }+ res.json({ entries: gate.result ?? [] })}))// ─── steering dedup: advance per-agent conversation_reads cursor ─────@@ -673,11 +730,19 @@ runtimeRouter.post('/conversation/mark-read', withAgent(async (c, req, res) => {if (!body?.conversationId || !body.upToMessageId) {res.status(400).json({ error: 'conversationId and upToMessageId required' }); return}- await inprocClient.markConversationRead({+ const gate = await withRuntimeMessageReadAuthorization({agentId: c.sub,+ companyId: c.companyId,conversationId: body.conversationId,- upToMessageId: body.upToMessageId,+ messageId: body.upToMessageId,+ task: (client) => inprocClient.markConversationRead({+ agentId: c.sub,+ companyId: c.companyId,+ conversationId: body.conversationId as string,+ upToMessageId: body.upToMessageId as string,+ }, client),})+ if (!gate.authorized) { res.status(403).json({ error: 'message is not readable in that conversation' }); return }res.json({ ok: true })}))@@ -693,16 +758,9 @@ runtimeRouter.post('/notices', withAgent(async (c, req, res) => {res.status(400).json({ error: 'conversationId, noticeKind, text, dedupeKey required' })return}- // Identity comes from the JWT, NEVER the body — a notice is always about- // THIS agent (e.g. its own engine failure). Trusting a body-supplied- // agentId/companyId would let any valid token spoof another agent as the- // author, cross-tenant. Scope the target conversation to the token's- // company and require this agent to be a member of it.- const member = await inprocClient.isConversationMember(body.conversationId, c.sub, c.companyId)- if (!member) {- res.status(403).json({ error: 'not a member of that conversation' })- return- }+ // Identity comes from the JWT, NEVER the body. postSystemNotice performs+ // participant + conversation membership validation and the write under one+ // transaction, closing the check-then-write revocation window.const out = await inprocClient.postSystemNotice({conversationId: body.conversationId,companyId: c.companyId,@@ -712,5 +770,9 @@ runtimeRouter.post('/notices', withAgent(async (c, req, res) => {dedupeKey: body.dedupeKey,dedupeTtlSec: body.dedupeTtlSec ?? 3600,})- res.json(out)+ if (!out.authorized) {+ res.status(403).json({ error: 'not a member of that conversation' })+ return+ }+ res.json({ posted: out.posted })}))diff --git a/server/src/agents/scanner_helper.ts b/server/src/agents/scanner_helper.tsindex 1fc1735..9d72e0f 100644--- a/server/src/agents/scanner_helper.ts+++ b/server/src/agents/scanner_helper.ts@@ -2,13 +2,8 @@import { randomUUID } from 'node:crypto'import { pool } from '../db/pool.js'import { CH_GROUP_PULLED, CH_MESSAGE_NEW, publish } from '../redis.js'-import { getPersona } from './personas.js'-import { companyIdForParticipant } from '../tenant.js'-/** Hours an agent must wait between pulling two groups that INCLUDE a- * human. Throttles spam that would interrupt people. Agent-only pulls- * bypass this cooldown — those land in the peek tab and don't interrupt- * anyone. */+/** Hours an agent must wait between human-interrupting group pulls. */const PULL_COOLDOWN_HOURS = 6export async function startPulledGroup(args: {@@ -18,130 +13,130 @@ export async function startPulledGroup(args: {reason: stringopening: string}): Promise<{ conversationId: string }> {- const { instigatorId, title, members, reason, opening } = args-- // Determine whether this pull would interrupt any humans. If all- // members are agents, the resulting group is peek-only — no human- // sees it appear in their list — so we skip the cooldown gate.- const humanCheck = await pool.query<{ has_human: boolean }>(- `SELECT EXISTS (- SELECT 1 FROM participants p- WHERE p.id = ANY ($1::text[])- AND p.kind <> 'agent'- ) AS has_human`,- [members],+ const { instigatorId, title, reason, opening } = args+ const members = [...new Set([...args.members, instigatorId])]+ const { rows: tenantRows } = await pool.query<{ company_id: string }>(+ `SELECT company_id FROM participants+ WHERE id = $1 AND kind = 'agent' AND departed_at IS NULL+ LIMIT 1`,+ [instigatorId],)- const includesHuman = humanCheck.rows[0]?.has_human ?? true // default conservative+ const companyId = tenantRows[0]?.company_id+ if (!companyId) throw new Error(`pull-group instigator not found: ${instigatorId}`)- // ---- Restraint #1: per-agent cooldown ----- // Only applies when the new group includes a human — those pulls- // interrupt people. Agent-only pulls don't.- if (includesHuman) {- const { rows: cooldown } = await pool.query<{ id: string; title: string; at: string }>(- `SELECT c.id, c.title, c.created_at AS at- FROM conversations c- WHERE c.kind = 'group'- AND c.pulled_by ->> 'agentId' = $1- AND c.created_at > NOW() - ($2 || ' hours')::interval- -- Only count past pulls that included a human, matching the- -- new policy — agent-only pulls don't burn the cooldown either.- AND 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'- )- ORDER BY c.created_at DESC- LIMIT 1`,- [instigatorId, String(PULL_COOLDOWN_HOURS)],+ const conversationId = `pulled-${randomUUID().slice(0, 8)}`+ const messageId = `m-${randomUUID()}`+ const pulledAt = new Date().toISOString()+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ // Lock every endpoint in deterministic order. A foreign/departed target,+ // or a tenant move that commits while this command waits, makes the count+ // mismatch and prevents creation of a cross-tenant members array.+ const participantIds = [...members].sort()+ const { rows: participants } = await client.query<{+ id: string; name: string; kind: 'agent' | 'human'+ }>(+ `SELECT id, name, kind FROM participants+ WHERE company_id = $1 AND id = ANY($2::text[])+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ ORDER BY id FOR SHARE`,+ [companyId, participantIds],)- if (cooldown[0]) {- const at = new Date(cooldown[0].at)- const minsAgo = Math.round((Date.now() - at.getTime()) / 60_000)- throw new Error(- `pull-group rate-limited: you (${instigatorId}) already pulled "${cooldown[0].title}" ${minsAgo} minutes ago (id: ${cooldown[0].id}). ` +- `Cooldown is ${PULL_COOLDOWN_HOURS}h for pulls that include a human. Send a message in that group, or @mention people in an existing conversation, instead of pulling a fresh one. ` +- `(If you'd like a peer-only thread, pull a group with agent members only — those bypass the cooldown.)`,- )+ if (participants.length !== participantIds.length) {+ throw new Error('pull-group members must all be active participants in the instigator tenant')}- }-- // Member-set dedup used to live here but was removed: real teams have- // multiple groups with the same people scoped by TOPIC (hiring / bug- // triage / planning) — refusing identical-member pulls treated channel- // semantics as group-chat semantics. Restraint #1 already throttles- // human-interrupting spam; agent-on-agent pulls land peek-only so- // they can multiply freely. Same-instant parallel pulls from two- // agents are race-prevented by the broadcast coordination layer- // (announce-before-action + glance + thinking claim).-- const conversationId = `pulled-${randomUUID().slice(0, 8)}`- const companyId = (await companyIdForParticipant(instigatorId)) ?? null-- await pool.query(- `INSERT INTO conversations (id, kind, title, subtitle, members, pinned, tag, pulled_by, company_id)- VALUES ($1, 'group', $2, $3, $4::jsonb, FALSE, 'fresh-pulled', $5::jsonb, $6)`,- [- conversationId,- title,- `cross-project · ${members.length}`,- JSON.stringify(members),- JSON.stringify({ agentId: instigatorId, at: new Date().toISOString(), reason }),- companyId,- ],- )- await pool.query(- `INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 2)`,- [conversationId],- )+ const includesHuman = participants.some((participant) => participant.kind === 'human')- // Persist a minimal convening_info row so the right-pane Why-this-group panel renders.- // Use the title as a single headline; don't fabricate a fake italic tail.- await pool.query(- `INSERT INTO convening_info- (conversation_id, pulled_by_id, headline_lead, headline_tail, subhead,- who_and_why, evidence, asks, trigger, reasoning)- VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb)`,- [- conversationId,- instigatorId,- title,- '',- reason,- JSON.stringify(members.map((p) => ({ pid: p, reason: '' }))),- JSON.stringify({ tail: { tag: 'context', copy: reason } }),- JSON.stringify([]),- JSON.stringify({ when: new Date().toLocaleString(), what: `${(await getPersona(instigatorId))?.name ?? instigatorId} pulled this together via tool call.` }),- JSON.stringify([reason]),- ],- )+ if (includesHuman) {+ const { rows: cooldown } = await client.query<{ id: string; title: string; at: string }>(+ `SELECT c.id, c.title, c.created_at AS at+ FROM conversations c+ WHERE c.kind = 'group'+ AND c.pulled_by ->> 'agentId' = $1+ AND c.created_at > NOW() - ($2 || ' hours')::interval+ AND 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'+ )+ ORDER BY c.created_at DESC+ LIMIT 1`,+ [instigatorId, String(PULL_COOLDOWN_HOURS)],+ )+ if (cooldown[0]) {+ const minsAgo = Math.round((Date.now() - new Date(cooldown[0].at).getTime()) / 60_000)+ throw new Error(+ `pull-group rate-limited: you (${instigatorId}) already pulled "${cooldown[0].title}" ${minsAgo} minutes ago ` ++ `(id: ${cooldown[0].id}). Cooldown is ${PULL_COOLDOWN_HOURS}h for pulls that include a human. ` ++ `Send a message in that group, or @mention people in an existing conversation, instead.`,+ )+ }+ }- // Post the opening message as the instigator's first message in the new group.- const messageId = `m-${randomUUID()}`- await pool.query(- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)- VALUES ($1, $2, $3, 'text', $4, 1, $5)`,- [messageId, conversationId, instigatorId, opening, companyId],- )+ await client.query(+ `INSERT INTO conversations (id, kind, title, subtitle, members, pinned, tag, pulled_by, company_id)+ VALUES ($1, 'group', $2, $3, $4::jsonb, FALSE, 'fresh-pulled', $5::jsonb, $6)`,+ [+ conversationId,+ title,+ `cross-project · ${members.length}`,+ JSON.stringify(members),+ JSON.stringify({ agentId: instigatorId, at: pulledAt, reason }),+ companyId,+ ],+ )+ await client.query(+ `INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 2)`,+ [conversationId],+ )+ const instigatorName = participants.find((participant) => participant.id === instigatorId)?.name ?? instigatorId+ await client.query(+ `INSERT INTO convening_info+ (conversation_id, pulled_by_id, headline_lead, headline_tail, subhead,+ who_and_why, evidence, asks, trigger, reasoning)+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb)`,+ [+ conversationId,+ instigatorId,+ title,+ '',+ reason,+ JSON.stringify(members.map((participantId) => ({ pid: participantId, reason: '' }))),+ JSON.stringify({ tail: { tag: 'context', copy: reason } }),+ JSON.stringify([]),+ JSON.stringify({ when: new Date().toLocaleString(), what: `${instigatorName} pulled this together via tool call.` }),+ JSON.stringify([reason]),+ ],+ )+ await client.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'text', $4, 1, $5)`,+ [messageId, conversationId, instigatorId, opening, companyId],+ )+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }await publish(CH_GROUP_PULLED, {- type: 'group.pulled',- conversationId,- companyId: companyId ?? undefined,- pulledById: instigatorId,+ type: 'group.pulled', conversationId, companyId, pulledById: instigatorId,+ }).catch((error) => {+ console.warn(`[pull_group] durable conversation ${conversationId} committed but group publish failed`, error)})await publish(CH_MESSAGE_NEW, {type: 'message.new',conversationId,- companyId: companyId ?? undefined,+ companyId,message: {- id: messageId,- conversationId,- authorId: instigatorId,- kind: 'text',- body: opening,- sequence: 1,- at: new Date().toISOString(),+ id: messageId, conversationId, authorId: instigatorId,+ kind: 'text', body: opening, sequence: 1, at: pulledAt,},+ }).catch((error) => {+ console.warn(`[pull_group] durable message ${messageId} committed but publish failed`, error)})console.log(`[pull_group] ${instigatorId} pulled ${conversationId}: ${title}`)diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.tsindex 4666210..6a5b637 100644--- a/server/src/agents/scheduler.ts+++ b/server/src/agents/scheduler.ts@@ -24,7 +24,6 @@ import { pool } from '../db/pool.js'import { env } from '../env.js'import { CH_MESSAGE_NEW, CH_POLLS, CH_TYPING, publish, redis, sub, type MessageNewEvent, type PollUpdatedEvent } from '../redis.js'import { notifyAlert } from '../alerting.js'-import { isAgent } from './personas.js'import { ensurePod } from './runtime/orchestrator.js'import { resolveAgentHost, isByoaKind } from './computer/registry.js'import { companyTier } from '../tier.js'@@ -273,6 +272,39 @@ export function _resetLowPriorityWakeBudgetForTests(): void {lowPriDroppedInWindow = 0}+/** Resolve the exceptional recipient on a departure notice. The pubsub payload+ * is only a hint: an attacker or buggy publisher cannot add an arbitrary wake+ * target because the exact message, conversation, tenant, persisted recipient,+ * and active-agent row must all agree in Postgres. Exported for the delivery+ * contract regression test. */+export async function resolveDurableDeliveryAgent(args: {+ conversationId: string+ messageId: string+ companyId: string | undefined+ claimedRecipientId: string | undefined+}): Promise<string | null> {+ if (!args.companyId || !args.claimedRecipientId) return null+ const { rows } = await pool.query<{ delivery_recipient_id: string }>(+ `SELECT dm.delivery_recipient_id+ FROM messages dm+ JOIN conversations c+ ON c.id = dm.conversation_id+ AND c.company_id = $3+ JOIN participants p+ ON p.id = dm.delivery_recipient_id+ AND p.company_id = c.company_id+ AND p.kind = 'agent'+ AND p.departed_at IS NULL+ WHERE dm.id = $1+ AND dm.conversation_id = $2+ AND dm.kind = 'system'+ AND dm.delivery_recipient_id = $4+ LIMIT 1`,+ [args.messageId, args.conversationId, args.companyId, args.claimedRecipientId],+ )+ return rows[0]?.delivery_recipient_id ?? null+}+async function wakeOne(agentId: string,reason: WakeReason,@@ -550,8 +582,13 @@ async function wake(payload: MessageNewEvent): Promise<void> {steerPayload = { messageId, conversationId, authorName, body: messageBody, companyId: payload.companyId ?? '' }}- const { rows: convoRows } = await pool.query<{ members: string[]; kind: string; muted_agent_ids: string[] }>(- `SELECT c.members, c.kind,+ const { rows: convoRows } = await pool.query<{+ members: string[]+ kind: string+ company_id: string+ muted_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_idsFROM conversations cLEFT JOIN conversation_mutes mu ON mu.conversation_id = c.id@@ -561,7 +598,9 @@ async function wake(payload: MessageNewEvent): Promise<void> {[conversationId],)const conversation = convoRows[0]+ if (!conversation) returnconst members = conversation?.members ?? []+ if (steerPayload) steerPayload.companyId = conversation.company_idconst mutedAgentIds = new Set(conversation?.muted_agent_ids ?? [])let quotedAuthorId = payload.message.quoted?.authorId ?? nullif (!quotedAuthorId && payload.message.quotedMessageId && mutedAgentIds.size > 0) {@@ -571,10 +610,19 @@ async function wake(payload: MessageNewEvent): Promise<void> {)quotedAuthorId = rows[0]?.author_id ?? null}+ const { rows: currentAgentRows } = await pool.query<{ id: string }>(+ `SELECT id FROM participants+ WHERE company_id = $1 AND kind = 'agent' AND departed_at IS NULL+ AND id = ANY($2::text[])`,+ [conversation.company_id, members],+ )+ const currentAgents = new Set(currentAgentRows.map((row) => row.id))const agentRecipients: string[] = []for (const m of members) {if (m === authorId) continue- if (!(await isAgent(m))) continue+ // Treat conversations.members as untrusted denormalized data. A malformed+ // cross-tenant id must never become a wake/steer recipient for this tenant.+ if (!currentAgents.has(m)) continueif (mutedAgentIds.has(m) && !shouldDeliverToMutedAgent({agentId: m,conversationKind: conversation?.kind ?? 'group',@@ -590,7 +638,12 @@ async function wake(payload: MessageNewEvent): Promise<void> {// floor: when an AGENT's message would wake peers, drop the wake for any// recipient that is over its activation budget, so a runaway can't burn// unbounded cost. Human-driven wakes are NEVER throttled.- const authorIsAgent = await isAgent(authorId)+ const authorIsAgent = currentAgents.has(authorId) || Boolean((await pool.query(+ `SELECT 1 FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = 'agent' AND departed_at IS NULL`,+ [authorId, conversation.company_id],+ )).rowCount)let recipients = agentRecipientsif (authorIsAgent) {const allowed = await Promise.all(@@ -603,6 +656,23 @@ async function wake(payload: MessageNewEvent): Promise<void> {}}+ // A leave/kick commits the membership removal before this event is+ // published, so the departing agent no longer appears in `members`. The+ // persisted message may name one durable delivery recipient; the query+ // above validates that it is an active agent in this conversation's tenant+ // before we restore it to fan-out. Departure explanations bypass mute and+ // the agent-authored cost floor because this is the final access-revocation+ // notice, not ordinary conversation chatter.+ const deliveryAgentId = await resolveDurableDeliveryAgent({+ conversationId,+ messageId,+ companyId: conversation.company_id,+ claimedRecipientId: payload.message.deliveryRecipientId,+ })+ if (deliveryAgentId && !recipients.includes(deliveryAgentId)) {+ recipients = [...recipients, deliveryAgentId]+ }+// ROUTING (#70). A human message that explicitly NAMES agents is usually for// them, and waking the rest of the room costs a full big-brain turn each to// reach "not mine" — production measures ~26% of group wakes replying with@@ -647,7 +717,12 @@ async function wake(payload: MessageNewEvent): Promise<void> {// scheduler wakes every subscribed, non-muted agent at the same time,// like a Slack room. A muted agent only passes through for an exact// mention or quoted reply.- await fanOutWake(recipients, conversationId, steerPayload)+ await fanOutWake(+ recipients,+ conversationId,+ steerPayload,+ deliveryAgentId ? { recipientId: deliveryAgentId, messageId } : null,+ )}function escapeRegex(value: string): string {@@ -699,12 +774,35 @@ function renderTriageNote(verdict: InboxTriageVerdict): string {return `Small-brain inbox triage (${state}, ${verdict.source}): ${verdict.promptNote.trim()}${reason}`}-async function triageWakeRecipient(agentId: string): Promise<WakeOptions | null> {+export async function triageWakeRecipient(+ agentId: string,+ durableDelivery: { conversationId: string; messageId: string } | null = null,+): Promise<WakeOptions | null> {try {const persona = await inprocClient.loadPersona(agentId)if (!persona) return null- const inbox = await inprocClient.loadInbox(agentId)+ let inbox = await inprocClient.loadInbox(agentId)if (inbox.length === 0) return null+ if (durableDelivery) {+ const terminal = inbox.find((row) =>+ row.id === durableDelivery.messageId &&+ row.conversation_id === durableDelivery.conversationId)+ if (terminal) {+ // Managed/cloud agents do not need an expensive main-brain turn for an+ // informational departure. Consume the exact persisted row here, which+ // mirrors the BYOA daemon's system-only snapshot+ack path and prevents+ // the terminal notice from replaying forever or resurfacing after a+ // later re-invite. Other unread work remains eligible for normal triage.+ await inprocClient.markConversationRead({+ agentId,+ conversationId: terminal.conversation_id,+ upToMessageId: terminal.id,+ })+ console.log(`[scheduler] ${agentId} acknowledged durable departure notice ${terminal.id}`)+ inbox = inbox.filter((row) => row.id !== terminal.id)+ if (inbox.length === 0) return null+ }+ }const convoIds = [...new Set(inbox.map((m) => m.conversation_id))]const context = await inprocClient.loadContext(agentId, persona.companyId, convoIds)const verdict = await classifyInboxTriage({@@ -734,6 +832,7 @@ export async function fanOutWake(recipients: string[],conversationId: string,steerPayload: SteerWakePayload | null,+ durableDelivery: { recipientId: string; messageId: string } | null = null,): Promise<void> {// Bounded fan-out (env.WAKE_FANOUT_CONCURRENCY). Each recipient's work// — host resolve, the support-model triage (3 DB reads + a model call)@@ -758,7 +857,12 @@ export async function fanOutWake(const host = await resolveAgentHost(m).catch(() => ({ kind: null, companyId: null }))let triageOptions: WakeOptions | undefinedif (!isByoaKind(host.kind)) {- const verdict = await triageWakeRecipient(m)+ const verdict = await triageWakeRecipient(+ m,+ durableDelivery?.recipientId === m+ ? { conversationId, messageId: durableDelivery.messageId }+ : null,+ )if (!verdict) return // cloud triage said "not relevant" → no waketriageOptions = verdict}@@ -844,24 +948,32 @@ export function startScheduler(): void {const POLL_VOTE_WAKE_DEBOUNCE_SECONDS = 8const POLL_CLOSE_WAKE_CLAIM_SECONDS = 600-async function handlePollUpdated(event: PollUpdatedEvent): Promise<void> {- if (!event.companyId) return+export 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.membersFROM messages mJOIN conversations c ON c.id = m.conversation_id- WHERE m.id = $1 AND m.company_id = $2`,- [event.messageId, event.companyId],+ JOIN participants author+ ON author.id = m.author_id+ AND author.company_id = c.company_id+ AND author.kind = 'agent'+ AND author.departed_at IS NULL+ WHERE m.id = $1 AND m.company_id = $2+ AND m.conversation_id = $3+ AND c.company_id = $2+ AND c.members @> to_jsonb(ARRAY[m.author_id])`,+ [event.messageId, event.companyId, event.conversationId],)const row = rows[0]- if (!row) return+ if (!row) return falseconst authorId = row.author_id- // Skip if author isn't an active agent — humans see the tally- // update through the WS bridge already.- if (!(await isAgent(authorId))) return+ // The join above is the disclosure boundary: a departed, moved, or kicked+ // poll author must not receive a later tally containing room membership,+ // voter identities, or option text.// Skip self-wake: if the agent voted on (or closed) their own poll,// they already know.- if (event.actorId && event.actorId === authorId) return+ if (event.actorId && event.actorId === authorId) return falseconst isClose = Boolean(event.poll.closedAt)const claimKey = isClose@@ -869,7 +981,7 @@ async function handlePollUpdated(event: PollUpdatedEvent): Promise<void> {: `cumora:poll-vote-wake-claim:${event.messageId}`const claimTtl = isClose ? POLL_CLOSE_WAKE_CLAIM_SECONDS : POLL_VOTE_WAKE_DEBOUNCE_SECONDSconst claimed = await redis.set(claimKey, '1', 'EX', claimTtl, 'NX').catch(() => null)- if (claimed === null) return // another replica owned this wake, or debounce window still open+ if (claimed === null) return false // another replica owned this wake, or debounce window still open// Resolve display names for everyone we plan to surface in the// brief — author already excluded, voters from the tallies, and@@ -878,10 +990,13 @@ async function handlePollUpdated(event: PollUpdatedEvent): Promise<void> {for (const t of event.tallies) {for (const v of t.voterIds) voterSet.add(v)}- const pendingIds = row.members.filter((m) => m !== authorId && !voterSet.has(m))- const idsToResolve = new Set<string>([...voterSet, ...pendingIds])+ const idsToResolve = new Set<string>([...row.members, ...voterSet])if (event.actorId) idsToResolve.add(event.actorId)- const names = await resolveParticipantNames([...idsToResolve])+ const names = await resolveCurrentParticipantNames([...idsToResolve], event.companyId)+ const currentIds = new Set(names.keys())+ const currentVoters = new Set([...voterSet].filter((id) => currentIds.has(id)))+ const pendingIds = row.members.filter((id) =>+ id !== authorId && currentIds.has(id) && !currentVoters.has(id))const brief: PollWakeBrief = {messageId: event.messageId,@@ -891,58 +1006,50 @@ async function handlePollUpdated(event: PollUpdatedEvent): Promise<void> {status: isClose ? 'closed' : 'open',closedReason: event.poll.closedReason,expiresAt: event.poll.expiresAt,- totalVotes: event.tallies.reduce((s, t) => s + t.count, 0),+ totalVotes: event.tallies.reduce(+ (sum, tally) => sum + tally.voterIds.filter((id) => currentIds.has(id)).length,+ 0,+ ),tallies: event.poll.options.map((opt) => {const tally = event.tallies.find((t) => t.optionId === opt.id)- const count = tally?.count ?? 0- const voters = (tally?.voterIds ?? []).map((id) => ({+ const voters = (tally?.voterIds ?? []).filter((id) => currentIds.has(id)).map((id) => ({id, name: names.get(id) ?? id,}))- return { optionId: opt.id, text: opt.text, count, voters }+ return { optionId: opt.id, text: opt.text, count: voters.length, voters }}),pending: pendingIds.map((id) => ({ id, name: names.get(id) ?? id })),actor: {- id: event.actorId,- name: event.actorId ? (names.get(event.actorId) ?? event.actorId) : null,+ id: event.actorId && currentIds.has(event.actorId) ? event.actorId : null,+ name: event.actorId && currentIds.has(event.actorId) ? (names.get(event.actorId) ?? event.actorId) : null,},phase: isClose ? 'close' : 'vote',}await wakeAgent(authorId, 'poll.updated', event.conversationId, null, { pollBrief: brief })+ return true}-/** Batch-lookup participant display names. Falls back to the id on- * miss/error so the brief is always renderable. Uses the same cache- * as resolveAuthorName for any ids already there. */-async function resolveParticipantNames(ids: string[]): Promise<Map<string, string>> {+/** Resolve only current participants in the poll conversation's tenant.+ * Conversation member arrays and historical vote rows are denormalized and+ * may contain legacy foreign/departed ids; never disclose those through a+ * poll wake. */+async function resolveCurrentParticipantNames(+ ids: string[],+ companyId: string,+): Promise<Map<string, string>> {const out = new Map<string, string>()if (ids.length === 0) return out- const now = Date.now()- const missing: string[] = []- for (const id of ids) {- const hit = authorNameCache.get(id)- if (hit && hit.expiresAt > now) {- out.set(id, hit.name)- } else {- missing.push(id)- }- }- if (missing.length === 0) return outtry {const { rows } = await pool.query<{ id: string; name: string | null }>(- `SELECT id, name FROM participants WHERE id = ANY($1::text[])`,- [missing],+ `SELECT id, name FROM participants+ WHERE company_id = $1 AND id = ANY($2::text[])+ AND kind IN ('agent', 'human') AND departed_at IS NULL`,+ [companyId, ids],)for (const r of rows) {const name = r.name || r.id- authorNameCache.set(r.id, { name, expiresAt: now + AUTHOR_NAME_CACHE_TTL_MS })out.set(r.id, name)}- for (const id of missing) {- if (!out.has(id)) out.set(id, id) // unresolved → fall back to id- }- } catch {- for (const id of missing) out.set(id, id)- }+ } catch { /* fail closed: an empty map yields no identity disclosure */ }return out}diff --git a/server/src/agents/tools.ts b/server/src/agents/tools.tsindex 67adb7a..2c7f8d6 100644--- a/server/src/agents/tools.ts+++ b/server/src/agents/tools.ts@@ -186,47 +186,86 @@ async function tReact(args: Record<string, unknown>, agentId: string): Promise<Tdisplay: { name: 'react', arg: '', status: 'error', detail: 'missing args' } }}- // Toggle: if already reacted with this emoji, remove; else add- const existing = await pool.query<{ count: string }>(- `SELECT COUNT(*)::text AS count FROM message_reactions- WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,- [messageId, agentId, emoji],- )- const action = Number(existing.rows[0]?.count ?? '0') > 0 ? 'removed' : 'added'- if (action === 'removed') {- await pool.query(- `DELETE FROM message_reactions WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,- [messageId, agentId, emoji],+ // Authorize and toggle in one transaction. Lock order matches membership+ // mutations (participant first, conversation second), so a concurrent kick,+ // offboarding, or tenant move either commits first and rejects this reaction,+ // or waits until this already-authorized write commits.+ const client = await pool.connect()+ let action: 'removed' | 'added'+ let agg: Array<{ emoji: string; count: number; users: string[] }>+ let conversationId: string+ let companyId: string+ try {+ await client.query('BEGIN')+ const { rows: authorized } = await client.query<{ conversation_id: string; company_id: string }>(+ `SELECT m.conversation_id, c.company_id+ FROM participants requester+ JOIN conversations c+ ON c.company_id = requester.company_id+ AND c.members @> to_jsonb(ARRAY[$2::text])+ JOIN messages m+ ON m.conversation_id = c.id+ AND m.company_id = c.company_id+ WHERE m.id = $1+ AND requester.id = $2+ AND requester.kind = 'agent'+ AND requester.departed_at IS NULL+ FOR SHARE OF requester, c, m`,+ [messageId, agentId],)- } else {- await pool.query(- `INSERT INTO message_reactions (message_id, user_id, emoji) VALUES ($1, $2, $3)- ON CONFLICT DO NOTHING`,+ if (!authorized[0]) {+ await client.query('ROLLBACK')+ return {+ ok: false,+ output: null,+ error: 'message not found or no longer authorized',+ durationMs: Date.now() - t0,+ display: {+ name: 'react', arg: `${emoji} ${messageId.slice(0, 12)}`,+ status: 'forbidden', detail: 'message not found or no longer authorized', icon: 'web',+ },+ }+ }+ conversationId = authorized[0].conversation_id+ companyId = authorized[0].company_id++ const existing = await client.query<{ count: string }>(+ `SELECT COUNT(*)::text AS count FROM message_reactions+ WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,[messageId, agentId, emoji],)- }+ action = Number(existing.rows[0]?.count ?? '0') > 0 ? 'removed' : 'added'+ if (action === 'removed') {+ await client.query(+ `DELETE FROM message_reactions WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,+ [messageId, agentId, emoji],+ )+ } else {+ await client.query(+ `INSERT INTO message_reactions (message_id, user_id, emoji) VALUES ($1, $2, $3)+ ON CONFLICT DO NOTHING`,+ [messageId, agentId, emoji],+ )+ }- // Aggregate + broadcast. We DON'T compute a `mine` flag server-side:- // this row is broadcast to every WS client in the tenant, and "is this- // mine" is recipient-specific. The renderer derives it from `users` +- // the local user id. (Pre-fix, this query hardcoded user_id = 'yetone'- // — dev-seed leakage that made the badge wrong for every real user.)- const { rows: agg } = await pool.query<{ emoji: string; count: number; users: string[] }>(- `SELECT emoji,- COUNT(*)::int AS count,- array_agg(user_id ORDER BY user_id) AS users- FROM message_reactions WHERE message_id = $1- GROUP BY emoji ORDER BY count DESC, emoji ASC`,- [messageId],- )- const { rows: cv } = await pool.query<{ conversation_id: string; company_id: string }>(- `SELECT m.conversation_id, c.company_id- FROM messages m- JOIN conversations c ON c.id = m.conversation_id- WHERE m.id = $1`, [messageId],- )- const conversationId = cv[0]?.conversation_id ?? ''- const companyId = cv[0]?.company_id+ // Aggregate while the authorization locks are still held. We DON'T+ // compute a `mine` flag server-side: that is recipient-specific.+ const aggregate = await client.query<{ emoji: string; count: number; users: string[] }>(+ `SELECT emoji,+ COUNT(*)::int AS count,+ array_agg(user_id ORDER BY user_id) AS users+ FROM message_reactions WHERE message_id = $1+ GROUP BY emoji ORDER BY count DESC, emoji ASC`,+ [messageId],+ )+ agg = aggregate.rows+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }// Do NOT advance conversation_reads here. A reaction can be a lightweight// acknowledgement for long work, and marking the request read before the@@ -239,6 +278,8 @@ async function tReact(args: Record<string, unknown>, agentId: string): Promise<TcompanyId,messageId,reactions: agg,+ }).catch((error) => {+ console.warn(`[react] durable reaction on ${messageId} committed but publish failed`, error)})return {diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex fa38ce5..f3de301 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -1,4 +1,5 @@import { Router, type Request, type Response, type NextFunction } from 'express'+import type { PoolClient } from 'pg'import {storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey,storageKeyFromPublicUrl, messageAttachmentStorageKey,@@ -7,7 +8,8 @@ import { pool } from '../db/pool.js'import { CH_MESSAGE_NEW, CH_REACTIONS, CH_CONVO_UPDATED, CH_DOCS, CH_TYPING, CH_CALENDAR_EVENTS, publish } from '../redis.js'import { createPoll, castVote, closePoll, PollError } from '../polls.js'import { env } from '../env.js'-import { startConvene, getActiveConvene } from '../agents/convene.js'+import { startConvene } from '../agents/convene.js'+import { ensureDirectConversation } from '../agents/private_chat.js'import { fetchImageBytes } from '../agents/image-fetcher.js'import { getTriageEconomics, getWakeEconomics } from '../agents/observability.js'import { resolveKanbanAssigneeChange, wakeKanbanAgents } from '../agents/kanban-wake.js'@@ -335,6 +337,49 @@ async function requireConversationMember(return { userId, companyId, members: rows[0].members, kind: rows[0].kind }}+/** Execute a conversation mutation at a linearizable authorization point.+ * Lock order is always participant -> conversation, matching membership+ * helpers. The conversation row is exclusive because every current caller+ * mutates either it or state whose authorization derives from its members. */+async function withLockedConversationMember<T>(args: {+ userId: string+ companyId: string+ conversationId: string+ work: (+ client: PoolClient,+ conversation: { members: string[]; kind: string; pinned: boolean },+ ) => Promise<T>+}): Promise<T> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const actor = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ FOR SHARE`,+ [args.userId, args.companyId],+ )+ 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],+ )+ if (!rows[0]) throw new HttpError(404, 'not found')+ const result = await args.work(client, rows[0])+ await client.query('COMMIT')+ return result+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}+async function getDevtoolsState(req: Request & AuthedRequest): Promise<{userId: stringcompanyId: string@@ -1815,25 +1860,25 @@ api.post('/conversations/:id/project', async (req, res) => {const projectId = req.body?.projectId === null ? null: (typeof req.body?.projectId === 'string' ? req.body.projectId.trim() : undefined)if (projectId === undefined) { res.status(400).json({ error: 'projectId required (string or null to detach)' }); return }- const { rows } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1 AND company_id = $2`,- [id, tenant],- )- if (!rows[0]) { res.status(404).json({ error: 'not found' }); return }- if (!rows[0].members.includes(me)) {- res.status(403).json({ error: 'only members can change the project' }); return- }- if (projectId !== null) {- const { rows: pj } = await pool.query(- `SELECT 1 FROM projects WHERE id = $1 AND company_id = $2 LIMIT 1`,- [projectId, tenant],- )- if (!pj[0]) { res.status(400).json({ error: 'unknown project' }); return }- }- await pool.query(- `UPDATE conversations SET project_id = $2, updated_at = NOW() WHERE id = $1 AND company_id = $3`,- [id, projectId, tenant],- )+ await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId: id,+ work: async (client) => {+ if (projectId !== null) {+ const { rows: project } = await client.query(+ `SELECT 1 FROM projects WHERE id = $1 AND company_id = $2 LIMIT 1`,+ [projectId, tenant],+ )+ if (!project[0]) throw new HttpError(400, 'unknown project')+ }+ await client.query(+ `UPDATE conversations SET project_id = $2, updated_at = NOW()+ WHERE id = $1 AND company_id = $3`,+ [id, projectId, tenant],+ )+ },+ })res.json({ ok: true, projectId })})@@ -2474,22 +2519,11 @@ api.post('/agents', async (req, res) => {// button on the agent card stays disabled because no direct exists.// Same idempotent shape as `POST /conversations/direct`.try {- await pool.query(- `INSERT INTO conversations (id, kind, title, subtitle, members, pinned, tag, company_id)- VALUES ($1, 'direct', $2, NULL, $3::jsonb, FALSE, NULL, $4)- ON CONFLICT (id) DO NOTHING`,- [`direct-${data.id}-${randomUUID().slice(0, 6)}`, data.name, JSON.stringify([me, data.id]), tenant],- )- // Counter row is required for sequence allocation on the first message.- await pool.query(- `INSERT INTO conversation_counters (conversation_id, next_sequence)- SELECT id, 1 FROM conversations- WHERE kind = 'direct' AND company_id = $2- AND members @> to_jsonb(ARRAY[$1::text]) AND members @> to_jsonb(ARRAY[$3::text])- AND jsonb_array_length(members) = 2- ON CONFLICT (conversation_id) DO NOTHING`,- [me, tenant, data.id],- )+ await ensureDirectConversation({+ companyId: tenant,+ firstId: me,+ secondId: data.id,+ })} catch (e) {console.warn('[agents] auto-create direct convo failed', e)}@@ -2854,33 +2888,44 @@ api.post('/conversations', async (req, res) => {if (!title) { res.status(400).json({ error: 'title required' }); return }if (members.length < 2) { res.status(400).json({ error: 'pick at least one teammate' }); return }- // Validate every member exists in this tenant.- const { rows: existing } = await pool.query<{ id: string }>(- `SELECT id FROM participants WHERE id = ANY($1::text[]) AND company_id = $2`,- [members, tenant],- )- const validIds = new Set(existing.map((r) => r.id))- const missing = members.filter((m) => !validIds.has(m))- if (missing.length > 0) {- res.status(400).json({ error: `unknown participant(s): ${missing.join(', ')}` }); return- }-- // If a project was specified, validate it exists in this tenant.- if (projectId) {- const { rows: pj } = await pool.query(- `SELECT 1 FROM projects WHERE id = $1 AND company_id = $2 LIMIT 1`,- [projectId, tenant],+ const id = `g-${randomUUID().slice(0, 8)}`+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const participantIds = [...members].sort()+ const { rows: active } = await client.query<{ id: string }>(+ `SELECT id FROM participants+ WHERE company_id = $1 AND id = ANY($2::text[])+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ ORDER BY id FOR SHARE`,+ [tenant, participantIds],+ )+ if (active.length !== participantIds.length) {+ throw new HttpError(400, 'every member must be an active participant in this workspace')+ }+ if (projectId) {+ const { rows: project } = await client.query(+ `SELECT 1 FROM projects WHERE id = $1 AND company_id = $2 LIMIT 1`,+ [projectId, tenant],+ )+ if (!project[0]) throw new HttpError(400, 'unknown project')+ }+ await client.query(+ `INSERT INTO conversations (id, kind, title, topic, members, pinned, tag, pulled_by, company_id, project_id)+ VALUES ($1, 'group', $2, $3, $4::jsonb, FALSE, NULL, NULL, $5, $6)`,+ [id, title, topic, JSON.stringify(members), tenant, projectId],+ )+ await client.query(+ `INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 1)`,+ [id],)- if (!pj[0]) { res.status(400).json({ error: 'unknown project' }); return }+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()}-- const id = `g-${randomUUID().slice(0, 8)}`- await pool.query(- `INSERT INTO conversations (id, kind, title, topic, members, pinned, tag, pulled_by, company_id, project_id)- VALUES ($1, 'group', $2, $3, $4::jsonb, FALSE, NULL, NULL, $5, $6)`,- [id, title, topic, JSON.stringify(members), tenant, projectId],- )- await pool.query(`INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 1)`, [id])res.status(201).json({ id, members, projectId })})@@ -2890,17 +2935,18 @@ api.post('/conversations/:id/topic', async (req, res) => {const { id } = req.paramsconst raw = req.body?.topicconst topic = raw === null || raw === '' ? null : (typeof raw === 'string' ? raw.trim().slice(0, 200) : null)- const { rows } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1 AND company_id = $2`, [id, tenant],- )- if (!rows[0]) { res.status(404).json({ error: 'not found' }); return }- if (!rows[0].members.includes(me)) {- res.status(403).json({ error: 'only members can change the topic' }); return- }- await pool.query(- `UPDATE conversations SET topic = $2, updated_at = NOW() WHERE id = $1 AND company_id = $3`,- [id, topic, tenant],- )+ await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId: id,+ work: async (client) => {+ await client.query(+ `UPDATE conversations SET topic = $2, updated_at = NOW()+ WHERE id = $1 AND company_id = $3`,+ [id, topic, tenant],+ )+ },+ })await publish(CH_CONVO_UPDATED, {type: 'conversation.updated',conversationId: id,@@ -2917,18 +2963,19 @@ api.post('/conversations/:id/title', async (req, res) => {const { id } = req.paramsconst title = String(req.body?.title ?? '').trim().slice(0, 80)if (!title) { res.status(400).json({ error: 'title required' }); return }- const { rows } = await pool.query<{ members: string[]; kind: string }>(- `SELECT members, kind FROM conversations WHERE id = $1 AND company_id = $2`, [id, tenant],- )- if (!rows[0]) { res.status(404).json({ error: 'not found' }); return }- if (rows[0].kind !== 'group') { res.status(400).json({ error: 'only group chats can be renamed' }); return }- if (!rows[0].members.includes(me)) {- res.status(403).json({ error: 'only members can rename the group' }); return- }- await pool.query(- `UPDATE conversations SET title = $2, updated_at = NOW() WHERE id = $1 AND company_id = $3`,- [id, title, tenant],- )+ await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId: id,+ work: async (client, conversation) => {+ if (conversation.kind !== 'group') throw new HttpError(400, 'only group chats can be renamed')+ await client.query(+ `UPDATE conversations SET title = $2, updated_at = NOW()+ WHERE id = $1 AND company_id = $3`,+ [id, title, tenant],+ )+ },+ })await publish(CH_CONVO_UPDATED, {type: 'conversation.updated',conversationId: id,@@ -2946,33 +2993,60 @@ api.post('/conversations/direct', async (req, res) => {const otherId = String(req.body?.otherId ?? '').trim()if (!otherId) { res.status(400).json({ error: 'otherId required' }); return }if (otherId === me) { res.status(400).json({ error: 'cannot DM yourself' }); return }- const { rows: pp } = await pool.query<{ id: string; kind: string }>(- `SELECT id, kind FROM participants WHERE id = $1 AND company_id = $2`, [otherId, tenant],- )- if (!pp[0]) { res.status(404).json({ error: 'unknown participant' }); return }-- // Look for an existing direct chat with exactly these two members.- const { rows: existing } = await pool.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`,- [me, otherId, tenant],- )- if (existing[0]) { res.json({ id: existing[0].id, created: false }); return }+ const participantIds = [me, otherId].sort()+ const pairKey = JSON.stringify(participantIds)+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const { rows: participants } = await client.query<{ id: string; kind: string; name: string }>(+ `SELECT id, kind, name FROM participants+ WHERE company_id = $1 AND id = ANY($2::text[])+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ ORDER BY id FOR SHARE`,+ [tenant, participantIds],+ )+ if (participants.length !== 2) throw new HttpError(404, 'unknown or inactive participant')+ // JSON member pairs have no native unique constraint. A transaction-level+ // advisory lock makes HTTP and agent direct-chat creation idempotent under+ // concurrent first messages.+ await client.query(+ `SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))`,+ [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`,+ [me, otherId, tenant],+ )+ if (existing[0]) {+ await client.query('COMMIT')+ res.json({ id: existing[0].id, created: false })+ return+ }- const id = `direct-${otherId}-${randomUUID().slice(0, 6)}`- const { rows: title } = await pool.query<{ name: string }>(- `SELECT name FROM participants WHERE id = $1 AND company_id = $2`, [otherId, tenant],- )- await pool.query(- `INSERT INTO conversations (id, kind, title, subtitle, members, pinned, tag, company_id)- VALUES ($1, 'direct', $2, NULL, $3::jsonb, FALSE, $4, $5)`,- [id, title[0]?.name ?? otherId, JSON.stringify([me, otherId]), pp[0].kind === 'human' ? 'human' : null, tenant],- )- await pool.query(`INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 1)`, [id])- res.status(201).json({ id, created: true })+ const id = `direct-${otherId}-${randomUUID().slice(0, 6)}`+ const other = participants.find((participant) => participant.id === otherId)!+ await client.query(+ `INSERT INTO conversations (id, kind, title, subtitle, members, pinned, tag, company_id)+ VALUES ($1, 'direct', $2, NULL, $3::jsonb, FALSE, $4, $5)`,+ [id, other.name, JSON.stringify([me, otherId]), other.kind === 'human' ? 'human' : null, tenant],+ )+ await client.query(+ `INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 1)`,+ [id],+ )+ await client.query('COMMIT')+ res.status(201).json({ id, created: true })+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }})/** Toggle (or set) the pinned state of a conversation. */@@ -2981,17 +3055,22 @@ api.post('/conversations/:id/pin', async (req, res) => {// Pin state is column-level on conversations (shared across all viewers).// Without a membership gate, any tenant member could pin/unpin a private// DM they're not part of, mutating UI state for the real members.- const { companyId: tenant } = await requireConversationMember(req, id)- const { rows } = await pool.query<{ pinned: boolean }>(- `SELECT pinned FROM conversations WHERE id = $1 AND company_id = $2`, [id, tenant],- )- if (!rows[0]) { res.status(404).json({ error: 'not found' }); return }+ const { userId: me, companyId: tenant } = await requireCompany(req)const requested = req.body?.pinned- const next = typeof requested === 'boolean' ? requested : !rows[0].pinned- await pool.query(- `UPDATE conversations SET pinned = $2, updated_at = NOW() WHERE id = $1 AND company_id = $3`,- [id, next, tenant],- )+ const next = await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId: id,+ work: async (client, conversation) => {+ const value = typeof requested === 'boolean' ? requested : !conversation.pinned+ await client.query(+ `UPDATE conversations SET pinned = $2, updated_at = NOW()+ WHERE id = $1 AND company_id = $3`,+ [id, value, tenant],+ )+ return value+ },+ })res.json({ ok: true, pinned: next })})@@ -3012,19 +3091,19 @@ api.post('/conversations/:id/pin', async (req, res) => {api.post('/conversations/:id/mute', async (req, res) => {const { userId: me, companyId: tenant } = await requireCompany(req)const { id } = req.params- // Validate the conversation belongs to this tenant + the caller is a- // member — same rule as every other per-convo mutation.- const { rows: convo } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1 AND company_id = $2`, [id, tenant],- )- if (!convo[0]) { res.status(404).json({ error: 'not found' }); return }- if (!convo[0].members.includes(me)) { res.status(403).json({ error: 'not a member' }); return }const mute = req.body?.mute !== false // default to mute=true if omittedif (!mute) {- await pool.query(- `DELETE FROM conversation_mutes WHERE user_id = $1 AND conversation_id = $2`,- [me, id],- )+ await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId: id,+ work: async (client) => {+ await client.query(+ `DELETE FROM conversation_mutes WHERE user_id = $1 AND conversation_id = $2`,+ [me, id],+ )+ },+ })res.json({ ok: true, muted: false, mutedUntil: null })return}@@ -3041,13 +3120,20 @@ api.post('/conversations/:id/mute', async (req, res) => {}until = parsed}- await pool.query(- `INSERT INTO conversation_mutes (user_id, conversation_id, muted_at, muted_until)- VALUES ($1, $2, NOW(), $3)- ON CONFLICT (user_id, conversation_id)- DO UPDATE SET muted_at = NOW(), muted_until = EXCLUDED.muted_until`,- [me, id, until],- )+ await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId: id,+ work: async (client) => {+ await client.query(+ `INSERT INTO conversation_mutes (user_id, conversation_id, muted_at, muted_until)+ VALUES ($1, $2, NOW(), $3)+ ON CONFLICT (user_id, conversation_id)+ DO UPDATE SET muted_at = NOW(), muted_until = EXCLUDED.muted_until`,+ [me, id, until],+ )+ },+ })res.json({ ok: true, muted: true, mutedUntil: until ? until.toISOString() : null })})@@ -3073,23 +3159,21 @@ api.post('/conversations/:id/members', async (req, res) => {`SELECT id FROM participants WHERE id = $1 AND company_id = $2`, [newMember, tenant],)if (!existing[0]) { res.status(400).json({ error: `unknown participant: ${newMember}` }); return }- const { addConversationMember, postMembershipSystemMessage } = await import('../agents/membership.js')+ const { addConversationMember } = await import('../agents/membership.js')// Postgres edits the array. Splicing it here and writing the whole thing// back loses a concurrent membership change, and the `joined` row below is// posted either way — so the transcript would record a join that the// members column does not agree with.- const next = await addConversationMember({ conversationId: id, memberId: newMember, companyId: tenant }) ?? []- await postMembershipSystemMessage({- conversationId: id, companyId: tenant, actorId: me,- kind: 'joined', participantId: newMember,+ const mutation = await addConversationMember({+ conversationId: id, memberId: newMember, actorId: me, companyId: tenant,})- res.json({ ok: true, members: next })+ if (!mutation) { res.status(403).json({ error: 'membership changed; add cancelled' }); return }+ res.json({ ok: true, members: mutation.members })})/** Leave a group conversation — removes the caller from members.- * Posts the `left` system row BEFORE the members mutation so the- * caller's mailbox surfaces this final row in their next wake (the- * inbox query filters by current `c.members @> [me]`). */+ * The authorization predicate is repeated in the mutation itself so a+ * concurrent revocation cannot leave this stale request authorized. */api.post('/conversations/:id/leave', async (req, res) => {const { userId: me, companyId: tenant } = await requireCompany(req)const { id } = req.params@@ -3102,13 +3186,14 @@ api.post('/conversations/:id/leave', async (req, res) => {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 }- const { postMembershipSystemMessage, removeConversationMember } = await import('../agents/membership.js')- await postMembershipSystemMessage({- conversationId: id, companyId: tenant, actorId: me,- kind: 'left', participantId: me,+ const { removeConversationMember } = await import('../agents/membership.js')+ const mutation = await removeConversationMember({+ conversationId: id, memberId: me, actorId: me, companyId: tenant,+ allowSoleMember: true,+ kind: 'left',})- const next = await removeConversationMember({ conversationId: id, memberId: me, companyId: tenant }) ?? []- res.json({ ok: true, members: next })+ if (!mutation) { res.status(409).json({ error: 'membership changed; leave cancelled' }); return }+ res.json({ ok: true, members: mutation.members })})/** Human typing indicator. The client throttles emission to roughly one@@ -3474,84 +3559,121 @@ api.post('/conversations/:id/messages', async (req, res) => {}}- // If the client asked to quote, prove that target message exists in THIS- // same conversation. Cross-convo quotes would leak content across rooms- // (the renderer inlines a summary regardless of who's in the target room),- // so we reject those at the boundary. Silently drop instead of 400 if the- // quoted id is unknown — most likely it was deleted between the user- // hitting reply and us receiving the request; better to send the body- // than fail the whole send.let quotedSummary: {id: string; authorId: string; authorName: string; kind: string;body: string; sequence: number} | null = nulllet resolvedQuotedId: string | null = null- if (quotedMessageId) {- const { rows: qr } = await pool.query<{- id: string; author_id: string; author_name: string; kind: string;- body: string; sequence: number- }>(- `SELECT m.id, m.author_id,- COALESCE(p.name, u.display_name, m.author_id) AS author_name,- m.kind, m.body, m.sequence- FROM messages m- LEFT JOIN participants p ON p.id = m.author_id AND p.company_id = $3- LEFT JOIN users u ON u.id = m.author_id- WHERE m.id = $1 AND m.conversation_id = $2`,- [quotedMessageId, id, tenant],+ const proposedMessageId = `m-${randomUUID()}`+ let persisted: { id: string; sequence: number } | undefined+ let insertedNew = false+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ // Final write authorization is transactional. Locking the actor before+ // the conversation matches membership mutation lock order, so a kick,+ // offboard, or tenant move either happens before this write (and rejects+ // it) or after the committed message — never between check and INSERT.+ const actor = await client.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, tenant],)- if (qr[0]) {- resolvedQuotedId = qr[0].id- quotedSummary = {- id: qr[0].id,- authorId: qr[0].author_id,- authorName: qr[0].author_name,- kind: qr[0].kind,- body: qr[0].body.slice(0, 240),- sequence: qr[0].sequence,- }+ 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],+ )+ if (!currentConversation.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')}- }- // Retrying a message, or sending it twice at the same time, can leave a gap- // in sequence numbers. They only sort messages, so gaps are safe.- const seqResult = await pool.query<{ seq: number }>(- `INSERT INTO conversation_counters (conversation_id, next_sequence)- VALUES ($1, 2)- ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1- RETURNING next_sequence - 1 AS seq`,- [id],- )- const sequence = seqResult.rows[0]?.seq ?? 1+ // Prove a quoted target belongs to this same authorized conversation.+ // Unknown/deleted ids are dropped so the body can still be delivered.+ if (quotedMessageId) {+ const { rows: qr } = await client.query<{+ id: string; author_id: string; author_name: string; kind: string;+ body: string; sequence: number+ }>(+ `SELECT m.id, m.author_id,+ COALESCE(p.name, u.display_name, m.author_id) AS author_name,+ m.kind, m.body, m.sequence+ FROM messages m+ LEFT JOIN participants p ON p.id = m.author_id AND p.company_id = $3+ LEFT JOIN users u ON u.id = m.author_id+ WHERE m.id = $1 AND m.conversation_id = $2`,+ [quotedMessageId, id, tenant],+ )+ if (qr[0]) {+ resolvedQuotedId = qr[0].id+ quotedSummary = {+ id: qr[0].id,+ authorId: qr[0].author_id,+ authorName: qr[0].author_name,+ kind: qr[0].kind,+ body: qr[0].body.slice(0, 240),+ sequence: qr[0].sequence,+ }+ }+ }- const proposedMessageId = `m-${randomUUID()}`- const inserted = await pool.query<{ id: string; sequence: number }>(- `INSERT INTO messages- (id, conversation_id, author_id, kind, body, sequence, attachment, quoted_message_id, company_id, client_id)- VALUES ($1,$2,$3,'text',$4,$5,$6::jsonb,$7,$8,$9)- ON CONFLICT (conversation_id, author_id, client_id) WHERE client_id IS NOT NULL- DO NOTHING- RETURNING id, sequence`,- [proposedMessageId, id, me, body, sequence, attachment ? JSON.stringify(attachment) : null, resolvedQuotedId, tenant, clientId],- )- const persisted = inserted.rows[0] ?? (clientId- ? (await pool.query<{ id: string; sequence: number }>(- `SELECT id, sequence FROM messages- WHERE conversation_id = $1 AND author_id = $2 AND client_id = $3`,- [id, me, clientId],- )).rows[0]- : undefined)+ // Retrying a message, or sending it twice at the same time, can leave a+ // sequence gap. Gaps are safe because sequence is ordering-only.+ const seqResult = await client.query<{ seq: number }>(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1+ RETURNING next_sequence - 1 AS seq`,+ [id],+ )+ const sequence = seqResult.rows[0]?.seq ?? 1+ const inserted = await client.query<{ id: string; sequence: number }>(+ `INSERT INTO messages+ (id, conversation_id, author_id, kind, body, sequence, attachment, quoted_message_id, company_id, client_id)+ VALUES ($1,$2,$3,'text',$4,$5,$6::jsonb,$7,$8,$9)+ ON CONFLICT (conversation_id, author_id, client_id) WHERE client_id IS NOT NULL+ DO NOTHING+ RETURNING id, sequence`,+ [proposedMessageId, id, me, body, sequence, attachment ? JSON.stringify(attachment) : null, resolvedQuotedId, tenant, clientId],+ )+ persisted = inserted.rows[0] ?? (clientId+ ? (await client.query<{ id: string; sequence: number }>(+ `SELECT id, sequence FROM messages+ WHERE conversation_id = $1 AND author_id = $2 AND client_id = $3`,+ [id, me, clientId],+ )).rows[0]+ : undefined)+ if (!persisted) throw new Error('message insert returned no row')+ insertedNew = Boolean(inserted.rows[0])+ if (insertedNew) {+ await client.query(+ `UPDATE conversations SET updated_at = NOW() WHERE id = $1 AND company_id = $2`,+ [id, tenant],+ )+ }+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }if (!persisted) throw new Error('message insert returned no row')const messageId = persisted.idconst persistedSequence = persisted.sequencedeliveryMessageId = messageId- if (!inserted.rows[0]) {+ if (!insertedNew) {logDelivery('message.reused', { sequence: persistedSequence })res.status(202).json({ id: messageId, sequence: persistedSequence })return}logDelivery('message.committed', { sequence: persistedSequence })- await pool.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [id])// Test-only fault injection: reproduce a connection disappearing after// persistence but before either HTTP or WebSocket acknowledgement.@@ -3867,23 +3989,17 @@ api.post('/email/send', async (req, res) => {subject, memberIds: [...memberIds],})const fromLine = formatAddress(sender.email, sender.displayName)- const sendRes = await sendViaProvider({- from: fromLine,- to: toResolved.map((r) => formatAddress(r.addr, r.name)),- cc: ccResolved.length ? ccResolved.map((r) => formatAddress(r.addr, r.name)) : undefined,- subject, text: body, messageId,- attachments: resolvedAttachments.map((a) => ({- filename: a.filename, mimeType: a.mimeType, path: a.publicUrl,- })),- })+ // Authorize and commit the durable outbound row before the network hop.+ // persistEmailMessage pins the active participant and conversation+ // membership, so a concurrent removal wins before any provider call.const persisted = await persistEmailMessage({conversationId: conv.conversationId,companyId: tenant,authorId: me,direction: 'out',- transportStatus: sendRes.ok ? 'sent' : 'failed',- transportError: sendRes.error,- smtpMessageId: sendRes.smtpMessageId ?? messageId,+ transportStatus: 'sending',+ transportError: null,+ smtpMessageId: messageId,inReplyTo: null, references: [],subject,fromAddr: fromLine,@@ -3895,6 +4011,32 @@ api.post('/email/send', async (req, res) => {storageKey: a.storageKey,})),})+ const sendRes = await sendViaProvider({+ from: fromLine,+ to: toResolved.map((r) => formatAddress(r.addr, r.name)),+ cc: ccResolved.length ? ccResolved.map((r) => formatAddress(r.addr, r.name)) : undefined,+ subject, text: body, messageId,+ attachments: resolvedAttachments.map((a) => ({+ filename: a.filename, mimeType: a.mimeType, path: a.publicUrl,+ })),+ })+ const finalStatus = sendRes.ok ? 'sent' : 'failed'+ await pool.query(+ `UPDATE email_messages+ SET transport_status = $1, transport_error = $2,+ smtp_message_id = $3, next_retry_at = $4+ WHERE message_id = $5 AND company_id = $6`,+ [+ finalStatus, sendRes.error, sendRes.smtpMessageId ?? messageId,+ finalStatus === 'failed' ? new Date(Date.now() + 60_000) : null,+ persisted.messageId, tenant,+ ],+ ).catch((error) => {+ // The provider result is already irreversible. Preserve that response+ // so a client does not retry and send a duplicate merely because the+ // local status update had a transient failure.+ console.warn(`[email/send] post-send status update failed for ${persisted.messageId}`, error)+ })res.status(sendRes.ok ? 200 : 502).json({messageId: persisted.messageId,conversationId: conv.conversationId,@@ -4044,25 +4186,17 @@ api.post('/email/reply/:messageId', async (req, res) => {const inReplyTo = o.smtp_message_id ? normalizeMessageId(o.smtp_message_id) : nullconst messageId = mintMessageId()const fromLine = formatAddress(sender.email, sender.displayName)- const sendRes = await sendViaProvider({- from: fromLine, to: replyTo,- cc: ccCombined.length ? ccCombined : undefined,- subject, text: body,- inReplyTo: inReplyTo ?? undefined,- references: newReferences,- messageId,- attachments: resolvedAttachments.map((a) => ({- filename: a.filename, mimeType: a.mimeType, path: a.publicUrl,- })),- })+ // WRITE-FIRST: this transaction is the final authorization boundary.+ // A participant removed while this request is in flight cannot reach the+ // external mail provider with stale conversation access.const persisted = await persistEmailMessage({conversationId: o.conversation_id,companyId: tenant,authorId: me,direction: 'out',- transportStatus: sendRes.ok ? 'sent' : 'failed',- transportError: sendRes.error,- smtpMessageId: sendRes.smtpMessageId ?? messageId,+ transportStatus: 'sending',+ transportError: null,+ smtpMessageId: messageId,inReplyTo, references: newReferences,subject, fromAddr: fromLine,toAddrs: replyTo, ccAddrs: ccCombined,@@ -4072,6 +4206,31 @@ api.post('/email/reply/:messageId', async (req, res) => {storageKey: a.storageKey,})),})+ const sendRes = await sendViaProvider({+ from: fromLine, to: replyTo,+ cc: ccCombined.length ? ccCombined : undefined,+ subject, text: body,+ inReplyTo: inReplyTo ?? undefined,+ references: newReferences,+ messageId,+ attachments: resolvedAttachments.map((a) => ({+ filename: a.filename, mimeType: a.mimeType, path: a.publicUrl,+ })),+ })+ const finalStatus = sendRes.ok ? 'sent' : 'failed'+ await pool.query(+ `UPDATE email_messages+ SET transport_status = $1, transport_error = $2,+ smtp_message_id = $3, next_retry_at = $4+ WHERE message_id = $5 AND company_id = $6`,+ [+ finalStatus, sendRes.error, sendRes.smtpMessageId ?? messageId,+ finalStatus === 'failed' ? new Date(Date.now() + 60_000) : null,+ persisted.messageId, tenant,+ ],+ ).catch((error) => {+ console.warn(`[email/reply] post-send status update failed for ${persisted.messageId}`, error)+ })// Auto-ack — replying definitionally means I read the original.await pool.query(`INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)@@ -4199,56 +4358,63 @@ api.post('/messages/:id/reactions', async (req, res) => {const emoji = String(req.body?.emoji ?? '').trim()if (!emoji) { res.status(400).json({ error: 'emoji required' }); return }- // Resolve conversation + author *and* enforce that the caller is in the- // conversation's members array. The previous query was tenant-only, which- // let any peer add reactions to private DMs they had no business reading.- // We pull `members` in the same round-trip so we don't need a follow-up- // SELECT just to gate.- const { rows: cv } = await pool.query<{- conversation_id: string; author_id: string; members: string[]- }>(- `SELECT m.conversation_id, m.author_id, c.members+ const { rows: cv } = await pool.query<{ conversation_id: string }>(+ `SELECT m.conversation_idFROM messages mJOIN conversations c ON c.id = m.conversation_idWHERE m.id = $1 AND c.company_id = $2 LIMIT 1`,[id, tenant],)if (!cv[0]) { res.status(404).json({ error: 'message not found' }); return }- if (!cv[0].members.includes(me)) {- // Stay opaque on permission denied (same 404 a cross-tenant message- // returns) so the response doesn't disclose existence.- res.status(404).json({ error: 'message not found' }); return- }const conversationId = cv[0].conversation_id- const messageAuthorId = cv[0].author_id-- // Toggle- const existing = await pool.query<{ count: string }>(- `SELECT COUNT(*)::text AS count FROM message_reactions- WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,- [id, me, emoji],- )- const wasRemoval = Number(existing.rows[0]?.count ?? '0') > 0- if (wasRemoval) {- await pool.query(- `DELETE FROM message_reactions WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,- [id, me, emoji],- )- } else {- await pool.query(- `INSERT INTO message_reactions (message_id, user_id, emoji) VALUES ($1, $2, $3)- ON CONFLICT DO NOTHING`,- [id, me, emoji],- )- }+ const mutation = await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId,+ work: async (client) => {+ const { rows: message } = await client.query<{ author_id: string }>(+ `SELECT author_id FROM messages+ WHERE id = $1 AND conversation_id = $2 AND company_id = $3`,+ [id, conversationId, tenant],+ )+ if (!message[0]) throw new HttpError(404, 'message not found')+ const existing = await client.query<{ count: string }>(+ `SELECT COUNT(*)::text AS count FROM message_reactions+ WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,+ [id, me, emoji],+ )+ const wasRemoval = Number(existing.rows[0]?.count ?? '0') > 0+ if (wasRemoval) {+ await client.query(+ `DELETE FROM message_reactions WHERE message_id = $1 AND user_id = $2 AND emoji = $3`,+ [id, me, emoji],+ )+ } else {+ await client.query(+ `INSERT INTO message_reactions (message_id, user_id, emoji) VALUES ($1, $2, $3)+ ON CONFLICT DO NOTHING`,+ [id, me, emoji],+ )+ }+ const { rows: reactions } = await client.query<{ emoji: string; count: number; users: string[] }>(+ `SELECT emoji,+ COUNT(*)::int AS count,+ array_agg(user_id ORDER BY user_id) AS users+ FROM message_reactions WHERE message_id = $1+ GROUP BY emoji ORDER BY count DESC, emoji ASC`,+ [id],+ )+ return { wasRemoval, messageAuthorId: message[0].author_id, reactions }+ },+ })// Climate signal: a new reaction TO an agent's message bumps that// agent's affinity toward the reactor (they feel valued). Un-reacting// doesn't dock — the "I didn't mean it" path shouldn't be punitive.- if (!wasRemoval) {+ if (!mutation.wasRemoval) {const { bumpClimate } = await import('../agents/climate.js')void bumpClimate({- agentId: messageAuthorId, aboutId: me,+ agentId: mutation.messageAuthorId, aboutId: me,affinity: 0.05, trust: 0.02,note: `received ${emoji} from ${me}`,})@@ -4258,24 +4424,17 @@ api.post('/messages/:id/reactions', async (req, res) => {// WS to every client in the tenant, and "is this mine" is per-recipient.// Renderer derives mine = users.includes(meId) — see fromApi /// applyEvent in src/stores/messages.ts.- const { rows: agg } = await pool.query<{ emoji: string; count: number; users: string[] }>(- `SELECT emoji,- COUNT(*)::int AS count,- array_agg(user_id ORDER BY user_id) AS users- FROM message_reactions WHERE message_id = $1- GROUP BY emoji ORDER BY count DESC, emoji ASC`,- [id],- )-await publish(CH_REACTIONS, {type: 'message.reactions',conversationId,companyId: tenant,messageId: id,- reactions: agg,+ reactions: mutation.reactions,+ }).catch((error) => {+ console.warn(`[reactions] durable reaction on ${id} committed but publish failed`, error)})- res.json({ reactions: agg })+ res.json({ reactions: mutation.reactions })})/* ============== Peek (agent-only conversations) ==============@@ -4556,45 +4715,64 @@ api.post('/conversations/:id/convene', async (req, res) => {// initiate. Without membership-gating, a peer could spin up convene// sessions on private DMs, both leaking the topic and triggering agent// activity in rooms they don't belong to.- const { userId: me } = await requireConversationMember(req, id)+ const { userId: me, companyId: tenant } = await requireCompany(req)const topic = String(req.body?.topic ?? 'live work session')- const session = await startConvene({ conversationId: id, startedBy: me, topic })+ const session = await startConvene({ conversationId: id, companyId: tenant, startedBy: me, topic })res.json(session)})api.get('/conversations/:id/convene', async (req, res) => {- // Reading the active session leaks its existence + topic — same membership- // bar as starting it.- await requireConversationMember(req, req.params.id)- const session = await getActiveConvene(req.params.id)+ const { userId, companyId } = await requireCompany(req)+ const session = await withLockedConversationMember({+ userId,+ companyId,+ conversationId: req.params.id,+ work: async (client) => {+ const { rows } = await client.query(+ `SELECT id, conversation_id, title, flair, started_by, started_at, ended_at, state+ FROM convene_sessions+ WHERE conversation_id = $1 AND company_id = $2 AND state = 'live'+ ORDER BY started_at DESC LIMIT 1`,+ [req.params.id, companyId],+ )+ return rows[0] ?? null+ },+ })res.json(session)})api.get('/convene/:sessionId/transcript', async (req, res) => {const { userId: me, companyId: tenant } = await requireCompany(req)- // Resolve the parent conversation + its members in a single round-trip so- // we can enforce membership without an extra SELECT. Tenant gate stays in- // the JOIN; the members check is the new bar.- const { rows: gate } = await pool.query<{ members: string[] }>(- `SELECT c.members+ const { rows: scope } = await pool.query<{ conversation_id: string }>(+ `SELECT s.conversation_idFROM convene_sessions sJOIN conversations c ON c.id = s.conversation_idWHERE s.id = $1 AND c.company_id = $2 LIMIT 1`,[req.params.sessionId, tenant],)- if (!gate[0]) { res.status(404).json({ error: 'not found' }); return }- if (!gate[0].members.includes(me)) {- // Opaque 404 — don't disclose that the session exists in a room the- // caller can't read.- res.status(404).json({ error: 'not found' }); return- }- const { rows } = await pool.query(- `SELECT id, session_id AS "sessionId", author_id AS "authorId", kind, body, sequence,- decision, created_at AS "createdAt"- FROM convene_transcript WHERE session_id = $1- ORDER BY sequence ASC`,- [req.params.sessionId],- )+ if (!scope[0]) throw new HttpError(404, 'not found')+ const rows = await withLockedConversationMember({+ userId: me,+ companyId: tenant,+ conversationId: scope[0].conversation_id,+ work: async (client) => {+ const currentSession = await client.query(+ `SELECT 1 FROM convene_sessions+ WHERE id = $1 AND conversation_id = $2 AND company_id = $3`,+ [req.params.sessionId, scope[0].conversation_id, tenant],+ )+ if (!currentSession.rowCount) throw new HttpError(404, 'not found')+ const transcript = await client.query(+ `SELECT id, session_id AS "sessionId", author_id AS "authorId", kind, body, sequence,+ decision, created_at AS "createdAt"+ FROM convene_transcript+ WHERE session_id = $1 AND company_id = $2+ ORDER BY sequence ASC`,+ [req.params.sessionId, tenant],+ )+ return transcript.rows+ },+ })res.json(rows)})diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex 310c0ec..6f93600 100644--- a/server/src/db/migrate.ts+++ b/server/src/db/migrate.ts@@ -30,12 +30,20 @@ CREATE TABLE IF NOT EXISTS messages (tool JSONB,attachment JSONB,client_id TEXT,+ -- A membership departure message remains in the removed participant's+ -- runtime inbox even though the conversation membership update has already+ -- committed. Null for ordinary messages.+ delivery_recipient_id TEXT,created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW());CREATE INDEX IF NOT EXISTS idx_messages_convo_seq ON messages(conversation_id, sequence);CREATE INDEX IF NOT EXISTS idx_messages_convo_created ON messages(conversation_id, created_at);ALTER TABLE messages ADD COLUMN IF NOT EXISTS client_id TEXT;+ALTER TABLE messages ADD COLUMN IF NOT EXISTS delivery_recipient_id TEXT;+CREATE INDEX IF NOT EXISTS idx_messages_delivery_recipient+ ON messages(delivery_recipient_id, created_at, id)+ WHERE delivery_recipient_id IS NOT NULL;-- Reply-to / quote target. Soft self-FK (no ON DELETE CASCADE) so deleting-- the original leaves replies as orphans rendered as "[deleted]" stubsdiff --git a/server/src/db/schema.ts b/server/src/db/schema.tsindex 687b4ea..ba35fbb 100644--- a/server/src/db/schema.ts+++ b/server/src/db/schema.ts@@ -27,6 +27,9 @@ export const messages = pgTable(tool: jsonb('tool').$type<Record<string, unknown> | null>(),attachment: jsonb('attachment').$type<Record<string, unknown> | null>(),clientId: text('client_id'),+ // Durable one-shot delivery for departure notices after membership is+ // removed. Ordinary messages leave this null.+ deliveryRecipientId: text('delivery_recipient_id'),poll: jsonb('poll').$type<PollPayload | null>(),// Reply-to / quote target: id of another message in THIS conversation that// this message is quoting. Soft FK to messages.id with ON DELETE SET NULL@@ -42,6 +45,9 @@ export const messages = pgTable(clientIdIdx: uniqueIndex('uniq_messages_client_id').on(table.conversationId, table.authorId, table.clientId).where(sql`${table.clientId} IS NOT NULL`),+ deliveryRecipientIdx: index('idx_messages_delivery_recipient')+ .on(table.deliveryRecipientId, table.createdAt, table.id)+ .where(sql`${table.deliveryRecipientId} IS NOT NULL`),}),)diff --git a/server/src/documents/rooms.ts b/server/src/documents/rooms.tsindex af694b5..c033742 100644--- a/server/src/documents/rooms.ts+++ b/server/src/documents/rooms.ts@@ -15,6 +15,7 @@* twice is a no-op.*/import * as Y from 'yjs'+import type { PoolClient } from 'pg'import { pool } from '../db/pool.js'import {redis, sub, publish,@@ -67,8 +68,11 @@ const evictions = new Map<string, NodeJS.Timeout>()* echo-suppressed when they originated here. */const INSTANCE_ORIGIN = `instance:${env.INSTANCE_ID}`-async function loadSnapshot(documentId: string): Promise<{ state: Uint8Array | null; lastIncluded: bigint }> {- const { rows } = await pool.query<{ state_bytes: Buffer; snapshot_at_update_id: string }>(+async function loadSnapshot(+ documentId: string,+ dbClient?: PoolClient,+): Promise<{ state: Uint8Array | null; lastIncluded: bigint }> {+ const { rows } = await (dbClient ?? pool).query<{ state_bytes: Buffer; snapshot_at_update_id: string }>(`SELECT state_bytes, snapshot_at_update_idFROM document_snapshotsWHERE document_id = $1`,@@ -82,8 +86,9 @@ async function loadSnapshot(documentId: string): Promise<{ state: Uint8Array | nasync function loadUpdatesAfter(documentId: string,afterId: bigint,+ dbClient?: PoolClient,): Promise<Array<{ id: bigint; bytes: Uint8Array }>> {- const { rows } = await pool.query<{ id: string; update_bytes: Buffer }>(+ const { rows } = await (dbClient ?? pool).query<{ id: string; update_bytes: Buffer }>(`SELECT id, update_bytesFROM document_updatesWHERE document_id = $1 AND id > $2@@ -133,12 +138,23 @@ async function maybeCompact(room: Room): Promise<void> {room.updatesSinceSnapshot = 0}-async function hydrateDoc(documentId: string, doc: Y.Doc): Promise<void> {- const snap = await loadSnapshot(documentId)- if (snap.state) Y.applyUpdate(doc, snap.state, 'hydrate')- const tail = await loadUpdatesAfter(documentId, snap.lastIncluded)- for (const u of tail) {- Y.applyUpdate(doc, u.bytes, 'hydrate')+async function hydrateDoc(documentId: string, doc: Y.Doc, dbClient?: PoolClient): Promise<void> {+ // A cold load is a two-query logical read. When the caller does not already+ // own a transaction connection, reserve one for the whole hydration rather+ // than returning it between snapshot and tail. Otherwise a pool-full wave+ // of locked CLI callers can occupy every released slot while waiting on the+ // shared `room.loaded`, leaving each hydration's tail query queued behind+ // the callers that depend on it.+ const client = dbClient ?? await pool.connect()+ try {+ const snap = await loadSnapshot(documentId, client)+ if (snap.state) Y.applyUpdate(doc, snap.state, 'hydrate')+ const tail = await loadUpdatesAfter(documentId, snap.lastIncluded, client)+ for (const u of tail) {+ Y.applyUpdate(doc, u.bytes, 'hydrate')+ }+ } finally {+ if (!dbClient) client.release()}}@@ -146,7 +162,11 @@ function roomKey(documentId: string): string {return documentId}-async function getOrCreateRoom(documentId: string, companyId: string): Promise<Room> {+async function getOrCreateRoom(+ documentId: string,+ companyId: string,+ dbClient?: PoolClient,+): Promise<Room> {// Clear any pending eviction — we're reusing the warm room.const pending = evictions.get(documentId)if (pending) { clearTimeout(pending); evictions.delete(documentId) }@@ -167,10 +187,11 @@ async function getOrCreateRoom(documentId: string, companyId: string): Promise<Rhydrated: false,loaded: Promise.resolve(),}- rooms.set(roomKey(documentId), room)+ const key = roomKey(documentId)+ rooms.set(key, room)room.loaded = (async () => {- await hydrateDoc(documentId, doc)+ await hydrateDoc(documentId, doc, dbClient)room.hydrated = truedoc.on('update', (update: Uint8Array, origin: unknown) => {// Hydration replays are tagged 'hydrate' to skip persistence + fan-out.@@ -214,7 +235,14 @@ async function getOrCreateRoom(documentId: string, companyId: string): Promise<R})normalizeMarkdownImageParagraphs(doc, pmFragment(doc), { originId: 'system:doc-image-normalize', authorId: 'system' })await refreshDocumentImageUrls(doc, pmFragment(doc), { originId: 'system:doc-image-refresh', authorId: 'system' })- })()+ })().catch((error) => {+ // Never cache a rejected hydration promise. A transient DB timeout or a+ // corrupt row must fail the current waiters, but a later request should be+ // able to build a fresh room after the underlying problem is corrected.+ if (rooms.get(key) === room) rooms.delete(key)+ room.doc.destroy()+ throw error+ })await room.loadedreturn room@@ -258,8 +286,9 @@ export async function applyLocalUpdate(originId: string,authorId: string,update: Uint8Array,+ dbClient?: PoolClient,): Promise<void> {- const room = await getOrCreateRoom(documentId, companyId)+ const room = await getOrCreateRoom(documentId, companyId, dbClient)// origin carries everything the persistence hook needs to route the// event correctly. Plain object so the `remote` discriminator is absent// (i.e. it's a LOCAL update — must persist + fan-out).@@ -596,8 +625,12 @@ function fragmentToPlainText(fragment: Y.XmlFragment): string {/** Read-only access to the doc's current plain-text body. Used by REST* bootstrap responses + agent tools that don't want to hold a WS* session. Extracted by walking the ProseMirror fragment. */-export async function readDocumentText(documentId: string, companyId: string): Promise<string> {- const room = await getOrCreateRoom(documentId, companyId)+export async function readDocumentText(+ documentId: string,+ companyId: string,+ dbClient?: PoolClient,+): Promise<string> {+ const room = await getOrCreateRoom(documentId, companyId, dbClient)await refreshDocumentImageUrls(room.doc, pmFragment(room.doc), { originId: 'system:doc-image-refresh', authorId: 'system' })return fragmentToPlainText(pmFragment(room.doc))}@@ -701,8 +734,9 @@ export async function applyAgentEdit(| { kind: 'image'; src: string; alt: string | null; placement: AgentImagePlacement }| { kind: 'imageDelete'; match: AgentImageDeleteMatch }>,+ dbClient?: PoolClient,): Promise<{ replaced: number; imagePlaced: 'absolute' | 'anchor' | 'anchor-missed' | null; imagesDeleted: number; blocksReplaced: number }> {- const room = await getOrCreateRoom(documentId, companyId)+ const room = await getOrCreateRoom(documentId, companyId, dbClient)const fragment = pmFragment(room.doc)let replaced = 0let imagePlaced: 'absolute' | 'anchor' | 'anchor-missed' | null = nulldiff --git a/server/src/email-retry.ts b/server/src/email-retry.tsindex 87f1313..118185d 100644--- a/server/src/email-retry.ts+++ b/server/src/email-retry.ts@@ -3,7 +3,8 @@** A `transport_status='failed'` row used to sit forever — Resend hiccups,* DNS flap, a Cloudflare 502 during deploy, and the message would never- * leave the database. This loop reclaims those rows: every+ * leave the database. A process crash could likewise strand a write-first+ * row in `sending`. This loop reclaims both due states: every* EMAIL_RETRY_INTERVAL_MS it picks the next batch whose `next_retry_at`* has passed, re-issues the send (preserving threading + recipients +* attachments), updates retry_attempts + status, and schedules the next@@ -56,7 +57,7 @@ interface RetryRow {retry_attempts: number}-/** Claim a batch of due retries with SKIP LOCKED so concurrent replicas+/** Claim a batch of due failed or crash-stale sending rows with SKIP LOCKED so concurrent replicas* don't fight for the same row. We hold the transaction for the entire* send loop so a slow Resend call doesn't cause the next tick on this* replica to grab the same row. */@@ -72,7 +73,7 @@ async function claimDueRetries(limit: number): Promise<RetryRow[]> {FROM email_messages emJOIN messages m ON m.id = em.message_idWHERE em.direction = 'out'- AND em.transport_status = 'failed'+ AND em.transport_status IN ('failed', 'sending')AND em.next_retry_at IS NOT NULLAND em.next_retry_at <= NOW()ORDER BY em.next_retry_at ASC@@ -173,7 +174,8 @@ async function retryOne(row: RetryRow): Promise<void> {const next = nextRetryAt(attemptNumber)await pool.query(`UPDATE email_messages- SET transport_error = $2,+ SET transport_status = 'failed',+ transport_error = $2,retry_attempts = $3,next_retry_at = $4WHERE message_id = $1`,diff --git a/server/src/email.ts b/server/src/email.tsindex 2f58b26..2b485ec 100644--- a/server/src/email.ts+++ b/server/src/email.ts@@ -15,6 +15,7 @@* want to burn Resend quota.*/import { randomUUID } from 'node:crypto'+import type { PoolClient } from 'pg'import { pool } from './db/pool.js'import { env } from './env.js'@@ -330,9 +331,8 @@ interface SendArgs {inReplyTo?: string | nullreferences?: string[]/** When set, the provider should accept this id as the Message-ID rather- * than minting its own. Resend doesn't support this directly — it- * always mints — so we track our minted id alongside whatever the- * provider returns and use whichever is non-null. */+ * than minting its own. The same stable value also derives Resend's+ * Idempotency-Key, making crash recovery safe within its 24-hour window. */messageId?: string | null/** True when this send is automation (heartbeat decision or agent CLI* shelling out). Adds an RFC 3834 Auto-Submitted header so receiving@@ -452,6 +452,9 @@ export async function sendViaProvider(args: SendArgs): Promise<ProviderSendResulheaders: {'authorization': `Bearer ${apiKey}`,'content-type': 'application/json',+ ...(args.messageId+ ? { 'idempotency-key': `cumora-email/${normalizeMessageId(args.messageId) ?? args.messageId}` }+ : {}),},body: JSON.stringify(body),})@@ -513,11 +516,12 @@ export async function sendViaProvider(args: SendArgs): Promise<ProviderSendResulexport async function findEmailConversationByMessageIds(messageIds: string[],companyId: string,+ client?: PoolClient,): Promise<string | null> {if (messageIds.length === 0) return nullconst norm = messageIds.map(normalizeMessageId).filter((x): x is string => Boolean(x))if (norm.length === 0) return null- const { rows } = await pool.query<{ conversation_id: string }>(+ const { rows } = await (client ?? pool).query<{ conversation_id: string }>(`SELECT conversation_id FROM email_messagesWHERE company_id = $1AND LOWER(smtp_message_id) = ANY($2::text[])@@ -628,32 +632,59 @@ export async function persistEmailMessage(args: {// Need this lazily to avoid a circular import (redis pulls in env, etc).const { CH_MESSAGE_NEW, publish } = await import('./redis.js')const messageId = `m-${randomUUID()}`- // Atomic sequence claim — same pattern as cmdReply / api/router.ts.- const seqResult = await pool.query<{ seq: number }>(- `INSERT INTO conversation_counters (conversation_id, next_sequence)- VALUES ($1, 2)- ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1- RETURNING next_sequence - 1 AS seq`,- [args.conversationId],- )- const sequence = seqResult.rows[0]?.seq ?? 1- // No need to stash headers on the messages row — the API joins on- // email_messages and emits a typed `email` field per row when kind='email'.- await pool.query(- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)- VALUES ($1, $2, $3, 'email', $4, $5, $6)`,- [messageId, args.conversationId, args.authorId, args.body, sequence, args.companyId],- )- // Schedule the first retry attempt for outbound failures. The retry- // worker only ever looks at direction='out' + status='failed' rows whose- // next_retry_at is in the past, so inbound + sent rows trivially get- // ignored. We use a fresh 60-second backoff for the first try; the- // worker compounds it on each subsequent miss.- const initialRetryAt = (args.direction === 'out' && args.transportStatus === 'failed')- ? new Date(Date.now() + 60_000)- : null- await pool.query(- `INSERT INTO email_messages (+ interface PersistedAttachment {+ id: string; filename: string; mimeType: string; sizeBytes: number;+ storageKey: string | null; truncated: boolean;+ }+ const persistedAttachments: PersistedAttachment[] = []+ let sequence = 0+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ if (args.direction === 'out') {+ // Outbound mail is a privileged conversation write. Pin the current+ // participant row before checking membership so a concurrent kick,+ // offboarding, or tenant reassignment serializes at this boundary.+ const actor = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ FOR SHARE`,+ [args.authorId, args.companyId],+ )+ if (!actor.rowCount) throw new Error('email author is no longer an active tenant participant')+ }+ const conversation = await client.query(+ `SELECT id FROM conversations+ WHERE 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],+ )+ if (!conversation.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)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1+ RETURNING next_sequence - 1 AS seq`,+ [args.conversationId],+ )+ sequence = seqResult.rows[0]?.seq ?? 1+ await client.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'email', $4, $5, $6)`,+ [messageId, args.conversationId, args.authorId, args.body, sequence, args.companyId],+ )+ const initialRetryAt = args.direction === 'out'+ ? (args.transportStatus === 'failed'+ ? new Date(Date.now() + 60_000)+ : args.transportStatus === 'sending'+ ? new Date(Date.now() + 5 * 60_000)+ : null)+ : null+ await client.query(+ `INSERT INTO email_messages (message_id, conversation_id, company_id, direction, transport_status,transport_error, smtp_message_id, in_reply_to, references_chain,subject, from_addr, to_addrs, cc_addrs, bcc_addrs, html, raw_size_bytes,@@ -679,40 +710,41 @@ export async function persistEmailMessage(args: {args.rawSizeBytes ?? null,Boolean(args.autoSubmitted),initialRetryAt,- ],- )- // Outbound attachments: same email_attachments shape inbound writes from- // the webhook, so the /messages JOIN doesn't need to know which direction- // produced the row. We also capture the inserted ids so the wake event- // can echo them — the renderer's freshly-arrived bubble shouldn't have- // to wait for a /messages refetch to see attachments.- interface PersistedAttachment {- id: string; filename: string; mimeType: string; sizeBytes: number;- storageKey: string | null; truncated: boolean;- }- const persistedAttachments: PersistedAttachment[] = []- if (args.attachments?.length) {- for (const a of args.attachments) {- const attId = `eatt-${randomUUID().slice(0, 12)}`- const filename = a.filename.slice(0, 200)- const mimeType = (a.mimeType || 'application/octet-stream').slice(0, 120)- const truncated = Boolean(a.truncated)- await pool.query(- `INSERT INTO email_attachments+ ],+ )+ if (args.attachments?.length) {+ for (const a of args.attachments) {+ const attId = `eatt-${randomUUID().slice(0, 12)}`+ const filename = a.filename.slice(0, 200)+ const mimeType = (a.mimeType || 'application/octet-stream').slice(0, 120)+ const truncated = Boolean(a.truncated)+ await client.query(+ `INSERT INTO email_attachments(id, message_id, conversation_id, company_id, filename, mime_type, size_bytes, storage_key, truncated)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,- [- attId,- messageId, args.conversationId, args.companyId,- filename, mimeType, a.sizeBytes,- a.storageKey, truncated,- ],- )- persistedAttachments.push({- id: attId, filename, mimeType, sizeBytes: a.sizeBytes,- storageKey: a.storageKey, truncated,- })+ [+ attId,+ messageId, args.conversationId, args.companyId,+ filename, mimeType, a.sizeBytes,+ a.storageKey, truncated,+ ],+ )+ persistedAttachments.push({+ id: attId, filename, mimeType, sizeBytes: a.sizeBytes,+ storageKey: a.storageKey, truncated,+ })+ }}+ await client.query(+ `UPDATE conversations SET updated_at = NOW() WHERE id = $1 AND company_id = $2`,+ [args.conversationId, args.companyId],+ )+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()}// Resolve a fresh public URL per attachment for the wake event, mirroring// what /conversations/:id/messages does on read. Truncated rows stay@@ -729,7 +761,6 @@ export async function persistEmailMessage(args: {url, truncated: a.truncated,}}))- await pool.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [args.conversationId])// Wake every member-agent of the conversation. The scheduler dedups// across replicas via the wake-claim Redis key.await publish(CH_MESSAGE_NEW, {@@ -762,6 +793,12 @@ export async function persistEmailMessage(args: {attachments: wakeAttachments,},},+ }).catch((error) => {+ // Persistence is the outbox boundary. A transient Redis outage must not+ // prevent the caller from reaching the provider; clients will refetch the+ // committed row, and a stale `sending` deadline lets the retry worker+ // recover if the process dies before finalizing transport state.+ console.warn(`[email] message publish failed for ${messageId}`, error)})return { messageId, sequence }}@@ -786,40 +823,64 @@ export async function findOrCreateEmailConversation(args: {* sender. Order is preserved for the title fallback ("A ↔ B"). */memberIds: string[]}): Promise<{ conversationId: string; created: boolean }> {- const candidates = [args.inReplyTo, ...args.references]- .map((x) => normalizeMessageId(x))- .filter((x): x is string => Boolean(x))- const existing = await findEmailConversationByMessageIds(candidates, args.companyId)- if (existing) {- // Membership repair: a thread can pick up new participants over time- // (someone CC'd later). Add anyone who isn't already a member.- await pool.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`,- [existing, args.memberIds],+ const uniqueMembers = Array.from(new Set(args.memberIds))+ const concreteMembers = uniqueMembers.filter((id) => !id.startsWith('external:')).sort()+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ if (concreteMembers.length > 0) {+ const active = await client.query<{ id: string }>(+ `SELECT id FROM participants+ WHERE company_id = $1 AND id = ANY($2::text[])+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ ORDER BY id FOR SHARE`,+ [args.companyId, concreteMembers],+ )+ if (active.rows.length !== concreteMembers.length) {+ throw new Error('email conversation contains a foreign or departed participant')+ }+ }++ const candidates = [args.inReplyTo, ...args.references]+ .map((x) => normalizeMessageId(x))+ .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.+ 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],+ )+ await client.query('COMMIT')+ return { conversationId: existing, created: false }+ }++ const cleanSubject = args.subject.replace(/^\s*((re|fwd|fw)\s*:\s*)+/i, '').trim() || '(no subject)'+ const id = `email-${randomUUID().slice(0, 12)}`+ 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)],)- return { conversationId: existing, created: false }+ await client.query('COMMIT')+ return { conversationId: id, created: true }+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()}- // Strip leading Re:/Fwd: for the title — easier to scan in the- // conversation list. The full subject is preserved on each message.- const cleanSubject = args.subject.replace(/^\s*((re|fwd|fw)\s*:\s*)+/i, '').trim() || '(no subject)'- const id = `email-${randomUUID().slice(0, 12)}`- const uniqueMembers = Array.from(new Set(args.memberIds))- await pool.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)],- )- return { conversationId: id, created: true }}/** Bump (or create) the email_contacts row for an external sender. Wediff --git a/server/src/onboardCompany.ts b/server/src/onboardCompany.tsindex 8f4baff..dc5600d 100644--- a/server/src/onboardCompany.ts+++ b/server/src/onboardCompany.ts@@ -14,6 +14,7 @@ import { pool } from './db/pool.js'import { invalidatePersonaCache } from './agents/personas.js'import { randomUUID } from 'node:crypto'import { gravatarUrlForEmail } from './auth.js'+import { ensureDirectConversation } from './agents/private_chat.js'interface StarterAgent {/** Preferred id; we'll suffix on collision. */@@ -259,46 +260,82 @@ export async function joinAllHands(args: {participantId: string}): Promise<void> {const { companyId, participantId } = args- const { rows: companyRow } = await pool.query<{- all_hands_conversation_id: string | null- }>(- `SELECT all_hands_conversation_id FROM companies WHERE id = $1`,- [companyId],- )- const convId = companyRow[0]?.all_hands_conversation_id- if (!convId) return // no group yet → nothing to join-- // Append the new member to the conversation's members JSON array if not- // already present, atomically.- const { rows: updated } = await pool.query<{ added: boolean }>(- `UPDATE conversations- SET members = members || to_jsonb(ARRAY[$2::text]),- updated_at = NOW()- WHERE id = $1- AND NOT (members @> to_jsonb(ARRAY[$2::text]))- RETURNING TRUE AS added`,- [convId, participantId],- )- if (updated.length === 0) return // already a member → don't double-post-- // Drop a `kind='system'` message so the join is visible in the thread.- // body is a JSON-encoded payload — the frontend parses it and renders a- // clickable participant chip.- const seqResult = await pool.query<{ seq: number }>(- `INSERT INTO conversation_counters (conversation_id, next_sequence)- VALUES ($1, 2)- ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1- RETURNING next_sequence - 1 AS seq`,- [convId],- )- const sequence = seqResult.rows[0]?.seq ?? 1+ let convId: string | null = null+ let sequence = 0const messageId = `m-${randomUUID()}`const body = JSON.stringify({ kind: 'joined', participantId })- await pool.query(- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)- VALUES ($1, $2, $3, 'system', $4, $5, $6)`,- [messageId, convId, participantId, body, sequence, companyId],- )+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ // Serialize onboarding against offboarding / tenant reassignment. A stale+ // caller must not add a departed or foreign participant to the tenant's+ // all-hands conversation.+ const participant = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ FOR UPDATE`,+ [participantId, companyId],+ )+ if (!participant.rowCount) {+ await client.query('ROLLBACK')+ return+ }++ const { rows: companyRow } = await client.query<{+ all_hands_conversation_id: string | null+ }>(+ `SELECT all_hands_conversation_id FROM companies WHERE id = $1 FOR SHARE`,+ [companyId],+ )+ convId = companyRow[0]?.all_hands_conversation_id ?? null+ if (!convId) {+ await client.query('COMMIT')+ 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`,+ [convId, participantId, companyId],+ )+ if (updated.length === 0) {+ await client.query('COMMIT')+ return+ }++ const seqResult = await client.query<{ seq: number }>(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1+ RETURNING next_sequence - 1 AS seq`,+ [convId],+ )+ sequence = seqResult.rows[0]?.seq ?? 1+ await client.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'system', $4, $5, $6)`,+ [messageId, convId, participantId, body, sequence, companyId],+ )+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+ 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')@@ -310,6 +347,8 @@ export async function joinAllHands(args: {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@@ -382,30 +421,13 @@ export async function seedMemberDms(args: {[companyId, memberId],)for (const other of others) {- // Skip if a direct chat between this pair already exists in this- // company — saves redundant rows on partial reruns or when the same- // member is somehow re-onboarded.- 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`,- [companyId, memberId, other.id],- )- if (ex[0]) continue- const dmId = `direct-${other.id}-${randomUUID().slice(0, 6)}`- await pool.query(- `INSERT INTO conversations (id, kind, title, subtitle, members, pinned, tag, company_id)- VALUES ($1, 'direct', $2, NULL, $3::jsonb, FALSE, $4, $5)- ON CONFLICT (id) DO NOTHING`,- [dmId, other.name, JSON.stringify([memberId, other.id]),- other.kind === 'human' ? 'human' : null, companyId],- )- await pool.query(- `INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 1)- ON CONFLICT (conversation_id) DO NOTHING`,- [dmId],- )+ await ensureDirectConversation({+ companyId,+ firstId: memberId,+ secondId: other.id,+ }).catch((error) => {+ console.warn(`[onboard] skipped stale DM pair ${memberId}/${other.id}`, error)+ })}}diff --git a/server/src/polls.ts b/server/src/polls.tsindex 9f9f63c..cbb8dd3 100644--- a/server/src/polls.ts+++ b/server/src/polls.ts@@ -93,39 +93,60 @@ export async function createPoll(input: CreatePollInput): Promise<CreatedPoll> {closedReason: null,}- // Validate conversation membership at the boundary — the HTTP layer- // already does this, but agent paths reach in here directly so we- // double-check rather than trust the caller.- const { rows: convoRows } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1 AND company_id = $2`,- [input.conversationId, input.companyId],- )- const convo = convoRows[0]- if (!convo) throw new PollError('conversation not found', 404)- if (!convo.members.includes(input.authorId)) {- throw new PollError('not a member of this conversation', 403)- }-- const seqResult = await pool.query<{ seq: number }>(- `INSERT INTO conversation_counters (conversation_id, next_sequence)- VALUES ($1, 2)- ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1- RETURNING next_sequence - 1 AS seq`,- [input.conversationId],- )- const sequence = seqResult.rows[0]?.seq ?? 1const messageId = `m-${randomUUID()}`// Body shadows the question so any code that lists messages without// unpacking the poll payload (notifications, search index, plain-text// logs) still surfaces something meaningful.const body = `📊 ${question}`- await pool.query(- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, poll, company_id)- VALUES ($1,$2,$3,'poll',$4,$5,$6::jsonb,$7)`,- [messageId, input.conversationId, input.authorId, body, sequence, JSON.stringify(payload), input.companyId],- )- await pool.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [input.conversationId])+ let sequence: number+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ // Pin current participant + membership at the write boundary. Lock order+ // matches membership mutations, preventing a stale author from creating a+ // poll after a concurrent kick, offboarding, or tenant move.+ const actor = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ FOR SHARE`,+ [input.authorId, input.companyId],+ )+ 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`,+ [input.conversationId, input.companyId, input.authorId],+ )+ if (!authorized.rowCount) throw new PollError('conversation not found or not authorized', 403)++ const seqResult = await client.query<{ seq: number }>(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1+ RETURNING next_sequence - 1 AS seq`,+ [input.conversationId],+ )+ sequence = seqResult.rows[0]?.seq ?? 1+ await client.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, poll, company_id)+ VALUES ($1,$2,$3,'poll',$4,$5,$6::jsonb,$7)`,+ [messageId, input.conversationId, input.authorId, body, sequence, JSON.stringify(payload), input.companyId],+ )+ await client.query(+ `UPDATE conversations SET updated_at = NOW() WHERE id = $1 AND company_id = $2`,+ [input.conversationId, input.companyId],+ )+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }// Drop the poll into the message bus exactly like a text message — the// mailbox scheduler wakes member agents, each gets to decide for itself@@ -152,6 +173,8 @@ export async function createPoll(input: CreatePollInput): Promise<CreatedPoll> {poll: payload,pollTallies: [],},+ }).catch((error) => {+ console.warn(`[poll] durable message ${messageId} committed but publish failed`, error)})return { messageId, sequence, poll: payload }@@ -173,32 +196,33 @@ export async function castVote(input: CastVoteInput): Promise<PollUpdatedEvent>const client = await pool.connect()try {await client.query('BEGIN')+ const voter = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind = $3 AND departed_at IS NULL+ FOR SHARE`,+ [input.voterParticipantId, input.companyId, input.voterKind],+ )+ if (!voter.rowCount) throw new PollError('voter is not an active tenant participant', 403)const { rows } = await client.query<{poll: PollPayload | nullconversation_id: stringcompany_id: string}>(- `SELECT poll, conversation_id, company_id- FROM messages- WHERE id = $1 AND company_id = $2 AND kind = 'poll'- FOR UPDATE`,- [input.messageId, input.companyId],+ `SELECT m.poll, m.conversation_id, m.company_id+ FROM conversations c+ JOIN messages m ON m.conversation_id = c.id AND m.company_id = c.company_id+ WHERE m.id = $1 AND m.company_id = $2 AND m.kind = 'poll'+ AND c.members @> to_jsonb(ARRAY[$3::text])+ FOR SHARE OF c+ FOR UPDATE OF m`,+ [input.messageId, input.companyId, input.voterParticipantId],)const row = rows[0]if (!row || !row.poll) throw new PollError('poll not found', 404)const poll = row.pollif (poll.closedAt) throw new PollError('poll is closed', 409)- // Membership gate: only conversation members can vote.- const { rows: convoRows } = await client.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1`,- [row.conversation_id],- )- const members = convoRows[0]?.members ?? []- if (!members.includes(input.voterParticipantId)) {- throw new PollError('not a member of this conversation', 403)- }-if (poll.mode === 'single' && requested.length > 1) {throw new PollError('single-choice poll accepts at most one option')}@@ -244,14 +268,35 @@ export async function closePoll(input: CloseInput): Promise<PollUpdatedEvent | nconst client = await pool.connect()try {await client.query('BEGIN')+ if (input.reason === 'manual') {+ if (!input.actorId) throw new PollError('actor required for manual close', 403)+ const actor = await client.query(+ `SELECT id FROM participants+ WHERE id = $1 AND company_id = $2+ AND kind IN ('agent', 'human') AND departed_at IS NULL+ FOR SHARE`,+ [input.actorId, input.companyId],+ )+ if (!actor.rowCount) throw new PollError('actor is not an active tenant participant', 403)+ }const { rows } = await client.query<{poll: PollPayload | nullauthor_id: string}>(- `SELECT poll, author_id FROM messages- WHERE id = $1 AND company_id = $2 AND kind = 'poll'- FOR UPDATE`,- [input.messageId, input.companyId],+ input.reason === 'manual'+ ? `SELECT m.poll, m.author_id+ FROM conversations c+ JOIN messages m ON m.conversation_id = c.id AND m.company_id = c.company_id+ WHERE m.id = $1 AND m.company_id = $2 AND m.kind = 'poll'+ AND c.members @> to_jsonb(ARRAY[$3::text])+ FOR SHARE OF c+ FOR UPDATE OF m`+ : `SELECT poll, author_id FROM messages+ WHERE id = $1 AND company_id = $2 AND kind = 'poll'+ FOR UPDATE`,+ input.reason === 'manual'+ ? [input.messageId, input.companyId, input.actorId]+ : [input.messageId, input.companyId],)const row = rows[0]if (!row || !row.poll) throw new PollError('poll not found', 404)diff --git a/server/src/redis.ts b/server/src/redis.tsindex 8a154e8..2a1ad4c 100644--- a/server/src/redis.ts+++ b/server/src/redis.ts@@ -11,7 +11,12 @@ const lazyConnect = process.env.CUMORA_RUNTIME_CLIENT === 'http'/** Single shared client for normal commands. */export const redis = new IORedis(env.REDIS_URL, {- maxRetriesPerRequest: null,+ // Durable writes must never hang forever after PostgreSQL COMMIT while a+ // disconnected Redis client quietly accumulates an offline queue. Callers+ // can now fail-open or retry explicitly within a bounded deadline.+ maxRetriesPerRequest: 1,+ enableOfflineQueue: false,+ commandTimeout: 2_000,enableReadyCheck: true,lazyConnect,})@@ -85,6 +90,10 @@ export interface MessageNewEvent extends TenantTagged {* optimistic bubble when the WS event races the POST response — id* alone can't match because the optimistic is keyed by tempId. */clientId?: string+ /** Durable one-shot recipient for membership departure notices. The+ * scheduler verifies this value against the persisted message before+ * adding it to wake fan-out. */+ deliveryRecipientId?: string/** When this message is a reply, the id of the quoted-original. */quotedMessageId?: string/** Inlined summary so the renderer can draw the quote card on receipt@@ -328,11 +337,9 @@ export interface DocMentionEvent extends TenantTagged {}/** "Heads-up — this calendar event fires in N minutes." Broadcast on- * CH_CALENDAR_REMINDER and bridged to every WS client in the company;- * the renderer filters on `recipientUserIds.includes(meId)` so only the- * intended humans actually pop a toast. Note: recipients can be empty- * on agent-only events — the WS bridge still delivers it but no- * renderer will match. */+ * CH_CALENDAR_REMINDER; the WS bridge resolves recipientUserIds against live+ * workspace membership before routing. The renderer repeats the filter as+ * defense in depth. Recipients may be empty for agent-only events. */export interface CalendarReminderEvent extends TenantTagged {type: 'calendar.reminder'eventId: stringdiff --git a/server/src/status.ts b/server/src/status.tsindex c04f94a..3cae73a 100644--- a/server/src/status.ts+++ b/server/src/status.ts@@ -37,6 +37,8 @@ export async function setStatus(participantId: string, status: ParticipantStatusstatus,statusUpdatedAt: toIso(r.status_updated_at),companyId: r.company_id,+ }).catch((error) => {+ console.warn(`[status] durable ${participantId}=${status} update committed but publish failed`, error)})}}@@ -57,5 +59,7 @@ export async function heartbeatStatus(participantId: string, status: Extract<Parstatus,statusUpdatedAt: toIso(rows[0].status_updated_at),companyId: rows[0].company_id,+ }).catch((error) => {+ console.warn(`[status] durable ${participantId} heartbeat committed but publish failed`, error)})}diff --git a/server/src/ws.ts b/server/src/ws.tsindex be983b5..62f7c82 100644--- a/server/src/ws.ts+++ b/server/src/ws.ts@@ -45,6 +45,7 @@ interface AuthedSocket {}const clients = new Set<AuthedSocket>()+const redisFanoutQueues = new Map<string, Promise<void>>()// Per-client WebSocket send backpressure caps (OOM fix). A socket that can't// drain makes `ws` buffer unsent frames in process memory; without a cap, a high@@ -54,6 +55,7 @@ const clients = new Set<AuthedSocket>()// reconnects + re-syncs via REST).const WS_MAX_BUFFERED_BYTES = 2 * 1024 * 1024 // 2 MBconst WS_TERMINATE_BUFFERED_BYTES = 8 * 1024 * 1024 // 8 MB+const DOC_SYNC_MAX_BYTES = 32 * 1024 * 1024 // bounded one-shot snapshot/** Open WS connections per user. Drives real human presence:* - 0 → 1 : user is now online, flip participant status to 'avail'.@@ -140,6 +142,110 @@ async function loadMemberships(userId: string): Promise<Set<string>> {return new Set(rows.map((r) => r.company_id))}+interface RoutedRedisEvent {+ type?: string+ companyId?: string+ conversationId?: string+ message?: { id?: string }+ mentionedIds?: string[]+ recipientUserIds?: string[]+}++/** Resolve every broadcast against live authorization, not the membership+ * snapshot captured when a socket connected. Conversation events are routed+ * only to current active human members. The sole exception is a persisted+ * system message with delivery_recipient_id, which lets a just-removed human+ * receive that one terminal leave/kick notice without reopening room access. */+export async function resolveWsEventRecipientUserIds(+ event: RoutedRedisEvent,+): Promise<Set<string>> {+ const companyId = typeof event.companyId === 'string' ? event.companyId : ''+ if (!companyId) return new Set()+ const targetedUserIds = event.type === 'doc.mention'+ ? event.mentionedIds+ : event.type === 'calendar.reminder'+ ? event.recipientUserIds+ : null+ if (targetedUserIds) {+ const requested = [...new Set(targetedUserIds.filter((id) => typeof id === 'string'))]+ if (requested.length === 0) return new Set()+ const { rows } = await pool.query<{ user_id: string }>(+ `SELECT cm.user_id+ FROM company_members cm+ JOIN users u ON u.id = cm.user_id AND u.deleted_at IS NULL+ JOIN participants p+ ON p.id = cm.user_id+ AND p.company_id = cm.company_id+ AND p.kind = 'human'+ AND p.departed_at IS NULL+ WHERE cm.company_id = $1 AND cm.user_id = ANY($2::text[])`,+ [companyId, requested],+ )+ return new Set(rows.map((row) => row.user_id))+ }+ const conversationId = typeof event.conversationId === 'string' ? event.conversationId : ''+ if (!conversationId) {+ const { rows } = await pool.query<{ user_id: string }>(+ `SELECT cm.user_id+ FROM company_members cm+ JOIN users u ON u.id = cm.user_id AND u.deleted_at IS NULL+ JOIN participants p+ ON p.id = cm.user_id+ AND p.company_id = cm.company_id+ AND p.kind = 'human'+ AND p.departed_at IS NULL+ WHERE cm.company_id = $1`,+ [companyId],+ )+ return new Set(rows.map((row) => row.user_id))+ }++ const durableMessageId = event.type === 'message.new' && typeof event.message?.id === 'string'+ ? event.message.id+ : null+ const { rows } = await pool.query<{ user_id: string }>(+ `WITH scoped_conversation AS (+ SELECT id, company_id, members+ FROM conversations+ WHERE id = $1 AND company_id = $2+ ), current_members AS (+ SELECT cm.user_id+ FROM scoped_conversation c+ CROSS JOIN LATERAL jsonb_array_elements_text(c.members) member(id)+ JOIN participants p+ ON p.id = member.id+ AND p.company_id = c.company_id+ AND 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+ ), durable_recipient AS (+ SELECT cm.user_id+ FROM scoped_conversation c+ JOIN messages m+ ON m.id = $3+ AND m.conversation_id = c.id+ AND m.company_id = c.company_id+ AND m.kind = 'system'+ AND m.delivery_recipient_id IS NOT NULL+ JOIN participants p+ ON p.id = m.delivery_recipient_id+ AND p.company_id = c.company_id+ AND 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+ )+ SELECT user_id FROM current_members+ UNION+ SELECT user_id FROM durable_recipient`,+ [conversationId, companyId, durableMessageId],+ )+ return new Set(rows.map((row) => row.user_id))+}+/** Look up a doc + verify the caller's tenant membership in one shot.* Returns null when the doc doesn't exist OR the caller can't see it —* same opaque posture the chat handlers use to avoid leaking existence. */@@ -148,6 +254,12 @@ async function docCompanyFor(documentId: string, userId: string): Promise<string`SELECT d.company_idFROM documents dJOIN company_members m ON m.company_id = d.company_id AND m.user_id = $2+ JOIN users u ON u.id = m.user_id AND u.deleted_at IS NULL+ JOIN participants p+ ON p.id = m.user_id+ AND p.company_id = d.company_id+ AND p.kind = 'human'+ AND p.departed_at IS NULLWHERE d.id = $1LIMIT 1`,[documentId, userId],@@ -155,11 +267,109 @@ async function docCompanyFor(documentId: string, userId: string): Promise<stringreturn rows[0]?.company_id ?? null}+/** Deliver one document frame while holding share locks on every row whose+ * mutation can revoke access. A concurrent delete/offboard waits until the+ * synchronous ws.send has happened; once revocation commits, the next lookup+ * fails closed and detaches the stale room subscription. */+async function sendAuthorizedDocFrame(+ c: AuthedSocket,+ documentId: string,+ subRec: DocSubscriber,+ payload: unknown,+): Promise<boolean> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const authorized = await client.query(+ `SELECT d.id+ FROM documents d+ JOIN company_members cm ON cm.company_id = d.company_id AND cm.user_id = $2+ JOIN users u ON u.id = cm.user_id AND u.deleted_at IS NULL+ JOIN participants p+ ON p.id = cm.user_id+ AND p.company_id = d.company_id+ AND p.kind = 'human'+ AND p.departed_at IS NULL+ WHERE d.id = $1+ FOR SHARE OF d, cm, u, p`,+ [documentId, c.userId],+ )+ if (!authorized.rowCount || c.docSubs.get(documentId) !== subRec) {+ await client.query('ROLLBACK')+ detachDocSubscription(c, documentId, subRec)+ return false+ }+ if (c.ws.readyState !== c.ws.OPEN || c.ws.bufferedAmount > WS_MAX_BUFFERED_BYTES) {+ await client.query('ROLLBACK')+ detachDocSubscription(c, documentId, subRec)+ try { c.ws.terminate() } catch { /* ignore */ }+ return false+ }+ sendJson(c.ws, payload)+ await client.query('COMMIT')+ return true+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}++async function withAuthorizedDocOperation(+ c: AuthedSocket,+ documentId: string,+ subRec: DocSubscriber,+ task: (companyId: string, client: import('pg').PoolClient) => Promise<void>,+): Promise<boolean> {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const { rows } = await client.query<{ company_id: string }>(+ `SELECT d.company_id+ FROM documents d+ JOIN company_members cm ON cm.company_id = d.company_id AND cm.user_id = $2+ JOIN users u ON u.id = cm.user_id AND u.deleted_at IS NULL+ JOIN participants p+ ON p.id = cm.user_id+ AND p.company_id = d.company_id+ AND p.kind = 'human'+ AND p.departed_at IS NULL+ WHERE d.id = $1+ FOR SHARE OF d, cm, u, p`,+ [documentId, c.userId],+ )+ if (!rows[0] || c.docSubs.get(documentId) !== subRec) {+ await client.query('ROLLBACK')+ detachDocSubscription(c, documentId, subRec)+ return false+ }+ await task(rows[0].company_id, client)+ await client.query('COMMIT')+ return true+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+}+function sendJson(ws: WebSocket, payload: unknown): void {if (ws.readyState !== ws.OPEN) returntry { ws.send(JSON.stringify(payload)) } catch { /* ignore */ }}+function detachDocSubscription(+ c: AuthedSocket,+ documentId: string,+ subRec: DocSubscriber,+): void {+ if (c.docSubs.get(documentId) !== subRec) return+ docUnsubscribe(documentId, subRec)+ c.docSubs.delete(documentId)+}+async function handleDocFrame(c: AuthedSocket, msg: Record<string, unknown>): Promise<void> {const type = msg.type as string | undefinedconst documentId = typeof msg.documentId === 'string' ? msg.documentId : null@@ -172,33 +382,75 @@ async function handleDocFrame(c: AuthedSocket, msg: Record<string, unknown>): PrsendJson(c.ws, { type: 'doc.error', documentId, error: 'not found' })return}- const subRec: DocSubscriber = {+ let outboundQueue = Promise.resolve()+ let pendingOutboundBytes = 0+ let pendingOutboundFrames = 0+ let subRec: DocSubscriber+ const enqueueAuthorizedFrame = (+ payload: unknown,+ byteLength: number,+ pendingByteLimit: number = WS_TERMINATE_BUFFERED_BYTES,+ ): void => {+ const estimatedBytes = Math.max(1, Math.ceil(byteLength * 4 / 3) + 256)+ if (+ pendingOutboundFrames >= 64+ || pendingOutboundBytes + estimatedBytes > pendingByteLimit+ ) {+ detachDocSubscription(c, documentId, subRec)+ try { c.ws.terminate() } catch { /* ignore */ }+ return+ }+ pendingOutboundBytes += estimatedBytes+ pendingOutboundFrames += 1+ const current = outboundQueue.catch(() => {}).then(async () => {+ if (c.docSubs.get(documentId) !== subRec) return+ await sendAuthorizedDocFrame(c, documentId, subRec, payload)+ }).finally(() => {+ pendingOutboundBytes = Math.max(0, pendingOutboundBytes - estimatedBytes)+ pendingOutboundFrames = Math.max(0, pendingOutboundFrames - 1)+ })+ outboundQueue = current+ void current.catch((error) => {+ console.warn(`[ws] document authorization lookup failed for ${documentId}`, error)+ detachDocSubscription(c, documentId, subRec)+ })+ }+ subRec = {originId: c.originId,onUpdate: (update, originId) => {- sendJson(c.ws, {+ enqueueAuthorizedFrame({type: 'doc.update',documentId,updateB64: Buffer.from(update).toString('base64'),originId,- })+ }, update.byteLength)},onAwareness: (update, originId) => {- sendJson(c.ws, {+ enqueueAuthorizedFrame({type: 'doc.awareness',documentId,updateB64: Buffer.from(update).toString('base64'),originId,- })+ }, update.byteLength)},}const { initialState } = await docSubscribe(documentId, companyId, subRec)c.docSubs.set(documentId, subRec)- sendJson(c.ws, {+ if (initialState.byteLength > DOC_SYNC_MAX_BYTES) {+ detachDocSubscription(c, documentId, subRec)+ sendJson(c.ws, {+ type: 'doc.error',+ documentId,+ error: 'document snapshot exceeds the 32 MiB realtime sync limit',+ })+ return+ }+ enqueueAuthorizedFrame({type: 'doc.sync',documentId,stateB64: Buffer.from(initialState).toString('base64'),originId: c.originId,- })+ }, initialState.byteLength, Math.ceil(DOC_SYNC_MAX_BYTES * 4 / 3) + 256)return}@@ -215,11 +467,10 @@ async function handleDocFrame(c: AuthedSocket, msg: Record<string, unknown>): Prif (!subRec) return // must subscribe firstconst updateB64 = typeof msg.updateB64 === 'string' ? msg.updateB64 : ''if (!updateB64) return- const companyId = await docCompanyFor(documentId, c.userId)- if (!companyId) returnconst buf = Buffer.from(updateB64, 'base64')const update = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)- await docApplyLocalUpdate(documentId, companyId, c.originId, c.userId, update)+ await withAuthorizedDocOperation(c, documentId, subRec, (companyId, client) =>+ docApplyLocalUpdate(documentId, companyId, c.originId, c.userId, update, client))return}@@ -228,11 +479,10 @@ async function handleDocFrame(c: AuthedSocket, msg: Record<string, unknown>): Prif (!subRec) returnconst updateB64 = typeof msg.updateB64 === 'string' ? msg.updateB64 : ''if (!updateB64) return- const companyId = await docCompanyFor(documentId, c.userId)- if (!companyId) returnconst buf = Buffer.from(updateB64, 'base64')const update = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)- await docBroadcastAwareness(documentId, companyId, c.originId, update)+ await withAuthorizedDocOperation(c, documentId, subRec, (companyId) =>+ docBroadcastAwareness(documentId, companyId, c.originId, update))return}@@ -264,91 +514,107 @@ async function processDocMention(args: {requestedIds: string[]}): Promise<void> {const { documentId, companyId, mentionerId, requestedIds } = args-- // Resolve the mentioned ids that actually belong to this tenant.- // Match against `participants` (covers both humans + agents).- const { rows: validRows } = await pool.query<{ id: string; kind: string; name: string }>(- `SELECT id, kind, name FROM participants- WHERE company_id = $1 AND id = ANY($2::text[])`,- [companyId, requestedIds],- )- if (validRows.length === 0) return-- // Doc metadata for the broadcast payload — title + the conversation- // (if any) the doc is pinned to. The pinned convo is the preferred- // surface for the agent-wake chat ping; falling back to a 1:1 DM- // when the doc isn't pinned avoids dragging unrelated members into- // a chat noise loop.- const { rows: docRows } = await pool.query<{ title: string; conversation_id: string | null }>(- `SELECT title, conversation_id FROM documents WHERE id = $1 AND company_id = $2`,- [documentId, companyId],- )- const documentTitle = docRows[0]?.title ?? 'Untitled'- const pinnedConversationId = docRows[0]?.conversation_id ?? null-- // Mentioner display name (humans live in `users`, agents in- // `participants`). Fall back to the id if neither has a name.- const mentionerName = await resolveDisplayName(mentionerId, companyId)-- // Dedup against the last 60 seconds. We don't try for global- // uniqueness — that would falsely block legitimate re-mentions hours- // later — just enough to absorb the editor's per-keystroke chatter.- const freshIds: string[] = []- for (const row of validRows) {- const { rows: recent } = await pool.query<{ id: string }>(- `SELECT id FROM document_mentions- WHERE document_id = $1 AND mentioner_id = $2 AND mentioned_id = $3- AND created_at > NOW() - INTERVAL '60 seconds'- LIMIT 1`,- [documentId, mentionerId, row.id],+ const participantIds = [...new Set([mentionerId, ...requestedIds])].sort()+ let mentionerName = mentionerId+ let documentTitle = 'Untitled'+ const freshRows: Array<{ id: string; kind: string; name: string }> = []+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const { rows: participants } = await client.query<{ id: string; kind: string; name: string }>(+ `SELECT p.id, p.kind, p.name FROM participants p+ WHERE p.company_id = $1 AND p.id = ANY($2::text[])+ AND p.kind IN ('agent', 'human') AND p.departed_at IS NULL+ AND (+ p.kind = 'agent'+ OR EXISTS (+ SELECT 1 FROM users u+ JOIN company_members cm ON cm.user_id = u.id AND cm.company_id = p.company_id+ WHERE u.id = p.id AND u.deleted_at IS NULL+ )+ )+ ORDER BY p.id FOR SHARE`,+ [companyId, participantIds],)- if (recent[0]) continue- freshIds.push(row.id)- await pool.query(- `INSERT INTO document_mentions- (id, document_id, company_id, mentioner_id, mentioned_id)- VALUES ($1, $2, $3, $4, $5)`,- [`dm_${randomUUID().replace(/-/g, '').slice(0, 16)}`,- documentId, companyId, mentionerId, row.id],+ const byId = new Map(participants.map((row) => [row.id, row]))+ const mentioner = byId.get(mentionerId)+ if (!mentioner || mentioner.kind !== 'human') {+ throw new Error('document mentioner is no longer an active workspace user')+ }+ mentionerName = mentioner.name || mentionerId+ const validRows = [...new Set(requestedIds)]+ .map((id) => byId.get(id))+ .filter((row): row is { id: string; kind: string; name: string } => Boolean(row))+ if (validRows.length === 0) {+ await client.query('COMMIT')+ return+ }+ const { rows: document } = await client.query<{ title: string }>(+ `SELECT title FROM documents+ WHERE id = $1 AND company_id = $2+ FOR SHARE`,+ [documentId, companyId],)- // Agents: drop an agent_log breadcrumb so the mention surfaces in- // `cumora log`. Humans don't have this surface; the toast is- // their notification.- if (row.kind === 'agent') {- await pool.query(- `INSERT INTO agent_log (id, agent_id, company_id, kind, body, ref)- VALUES ($1, $2, $3, 'doc_mention', $4, $5::jsonb)`,- [- `log_${randomUUID().replace(/-/g, '').slice(0, 16)}`,- row.id, companyId,- `${mentionerName} @-mentioned you in doc "${documentTitle}"`,- JSON.stringify({ documentId, mentionerId }),- ],- ).catch((e) => console.warn('[doc.mention] agent_log insert failed', e))-- // Also post a real `text` message authored by the mentioner so- // the agent actually WAKES + has context to act on. The mailbox- // scheduler watches CH_MESSAGE_NEW and runs an agent turn for- // every recipient. Without this step the agent only sees the- // doc-mention via `cumora log` on its NEXT natural wake — which- // might never come if no one else messages it.- try {- await postDocMentionWake({- companyId,- mentionerId,- mentionerName,- agentId: row.id,- agentName: row.name,- documentId,- documentTitle,- pinnedConversationId,- })- } catch (e) {- console.warn(`[doc.mention] wake post for ${row.id} failed`, e)+ if (!document[0]) throw new Error('document is no longer available in this workspace')+ documentTitle = document[0].title || 'Untitled'+ await client.query(+ `SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))`,+ [documentId, mentionerId],+ )++ for (const row of validRows) {+ const { rows: recent } = await client.query<{ id: string }>(+ `SELECT id FROM document_mentions+ WHERE document_id = $1 AND mentioner_id = $2 AND mentioned_id = $3+ AND created_at > NOW() - INTERVAL '60 seconds'+ LIMIT 1`,+ [documentId, mentionerId, row.id],+ )+ if (recent[0]) continue+ await client.query(+ `INSERT INTO document_mentions+ (id, document_id, company_id, mentioner_id, mentioned_id)+ VALUES ($1, $2, $3, $4, $5)`,+ [`dm_${randomUUID().replace(/-/g, '').slice(0, 16)}`,+ documentId, companyId, mentionerId, row.id],+ )+ if (row.kind === 'agent') {+ await client.query(+ `INSERT INTO agent_log (id, agent_id, company_id, kind, body, ref)+ VALUES ($1, $2, $3, 'doc_mention', $4, $5::jsonb)`,+ [+ `log_${randomUUID().replace(/-/g, '').slice(0, 16)}`,+ row.id, companyId,+ `${mentionerName} @-mentioned you in doc "${documentTitle}"`,+ JSON.stringify({ documentId, mentionerId }),+ ],+ )}+ freshRows.push(row)+ }+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()+ }+ if (freshRows.length === 0) return++ for (const row of freshRows) {+ if (row.kind !== 'agent') continue+ try {+ await postDocMentionWake({+ companyId,+ mentionerId,+ agentId: row.id,+ documentId,+ })+ } catch (e) {+ console.warn(`[doc.mention] wake post for ${row.id} failed`, e)}}- if (freshIds.length === 0) return+ const freshIds = freshRows.map((row) => row.id)const event: DocMentionEvent = {type: 'doc.mention',@@ -381,79 +647,116 @@ async function processDocMention(args: {async function postDocMentionWake(args: {companyId: stringmentionerId: string- mentionerName: stringagentId: string- agentName: stringdocumentId: string- documentTitle: string- pinnedConversationId: string | null}): Promise<void> {- const {- companyId, mentionerId, agentId, agentName,- documentId, documentTitle, pinnedConversationId,- } = args-- // 1) Try the pinned convo if both mentioner + agent are members.- let conversationId: string | null = null- if (pinnedConversationId) {- const { rows } = await pool.query<{ members: string[] }>(- `SELECT members FROM conversations WHERE id = $1 AND company_id = $2`,- [pinnedConversationId, companyId],+ const { companyId, mentionerId, agentId, documentId } = args+ const participantIds = [mentionerId, agentId].sort()+ let conversationId = ''+ let documentTitle = 'Untitled'+ let sequence = 0+ const messageId = `m-${randomUUID()}`+ let body = ''+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ const { rows: participants } = await client.query<{ id: string; kind: string; name: string }>(+ `SELECT p.id, p.kind, p.name FROM participants p+ WHERE p.company_id = $1 AND p.id = ANY($2::text[])+ AND p.kind IN ('agent', 'human') AND p.departed_at IS NULL+ AND (+ p.kind = 'agent'+ OR EXISTS (+ SELECT 1 FROM users u+ JOIN company_members cm ON cm.user_id = u.id AND cm.company_id = p.company_id+ WHERE u.id = p.id AND u.deleted_at IS NULL+ )+ )+ ORDER BY p.id FOR SHARE`,+ [companyId, participantIds],)- const members = rows[0]?.members ?? []- if (members.includes(mentionerId) && members.includes(agentId)) {- conversationId = pinnedConversationId+ const byId = new Map(participants.map((row) => [row.id, row]))+ const mentioner = byId.get(mentionerId)+ const agent = byId.get(agentId)+ if (mentioner?.kind !== 'human' || agent?.kind !== 'agent') {+ throw new Error('document mention participants are no longer active in this workspace')}- }- // 2) Existing DM (same 2-member query the /conversations/direct- // handler uses — single source of truth for the dedup shape).- if (!conversationId) {- const { rows } = await pool.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`,- [mentionerId, agentId, companyId],+ const { rows: document } = await client.query<{ title: string; conversation_id: string | null }>(+ `SELECT title, conversation_id FROM documents+ WHERE id = $1 AND company_id = $2+ FOR SHARE`,+ [documentId, companyId],)- if (rows[0]) conversationId = rows[0].id- }+ if (!document[0]) throw new Error('document is no longer available in this workspace')+ documentTitle = document[0].title || 'Untitled'- // 3) Create one.- if (!conversationId) {- const fresh = `direct-${agentId}-${randomUUID().slice(0, 6)}`- await pool.query(- `INSERT INTO conversations (id, kind, title, subtitle, members, pinned, tag, company_id)- VALUES ($1, 'direct', $2, NULL, $3::jsonb, FALSE, NULL, $4)`,- [fresh, agentName, JSON.stringify([mentionerId, agentId]), companyId],+ // Serialize direct-conversation creation with every other DM entry point.+ await client.query(+ `SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))`,+ [companyId, JSON.stringify(participantIds)],+ )++ // 1) Use the document's current pinned conversation only while both+ // 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`,+ [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`,+ [mentionerId, agentId, companyId],+ )+ conversationId = rows[0]?.id ?? ''+ }+ if (!conversationId) {+ conversationId = `direct-${agentId}-${randomUUID().slice(0, 6)}`+ await client.query(+ `INSERT INTO conversations+ (id, kind, title, subtitle, members, pinned, tag, company_id)+ VALUES ($1, 'direct', $2, NULL, $3::jsonb, FALSE, NULL, $4)`,+ [conversationId, agent.name || agentId, JSON.stringify([mentionerId, agentId]), companyId],+ )+ }++ const seqRes = await client.query<{ seq: number }>(+ `INSERT INTO conversation_counters (conversation_id, next_sequence)+ VALUES ($1, 2)+ ON CONFLICT (conversation_id) DO UPDATE+ SET next_sequence = conversation_counters.next_sequence + 1+ RETURNING next_sequence - 1 AS seq`,+ [conversationId],)- await pool.query(- `INSERT INTO conversation_counters (conversation_id, next_sequence) VALUES ($1, 1)- ON CONFLICT (conversation_id) DO NOTHING`,- [fresh],+ sequence = seqRes.rows[0]?.seq ?? 1+ body = `@${agentId} heads-up — I @-mentioned you in the doc "${documentTitle}". Take a look with \`cumora doc read ${documentId}\`, then either reply here or edit the doc directly (\`cumora doc append/replace ${documentId} …\`).`+ await client.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'text', $4, $5, $6)`,+ [messageId, conversationId, mentionerId, body, sequence, companyId],)- conversationId = fresh+ await client.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [conversationId])+ await client.query('COMMIT')+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {})+ throw error+ } finally {+ client.release()}- // Allocate a sequence + insert the message. Same shape sendMessage uses.- const seqRes = await pool.query<{ seq: number }>(- `INSERT INTO conversation_counters (conversation_id, next_sequence)- VALUES ($1, 2)- ON CONFLICT (conversation_id) DO UPDATE SET next_sequence = conversation_counters.next_sequence + 1- RETURNING next_sequence - 1 AS seq`,- [conversationId],- )- const sequence = seqRes.rows[0]?.seq ?? 1- const messageId = `m-${randomUUID()}`- const body = `@${agentId} heads-up — I @-mentioned you in the doc "${documentTitle}". Take a look with \`cumora doc read ${documentId}\`, then either reply here or edit the doc directly (\`cumora doc append/replace ${documentId} …\`).`- await pool.query(- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)- VALUES ($1, $2, $3, 'text', $4, $5, $6)`,- [messageId, conversationId, mentionerId, body, sequence, companyId],- )- await pool.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [conversationId])-// Publish on the same bus chat messages use → scheduler wakes the// agent's pod, the turn loop drains the inbox, the agent sees this// message with the doc id verbatim.@@ -471,26 +774,9 @@ async function postDocMentionWake(args: {at: new Date().toISOString(),},}- await publish(CH_MESSAGE_NEW, event)-}--/** Display-name lookup for the mention payload. Tries users first- * (humans live there), falls back to participants (covers agents and- * is also a backstop for humans that haven't logged in yet), finally- * defaults to the raw id. Best-effort — the renderer will fall back- * to its own participant store if the name comes back blank. */-async function resolveDisplayName(id: string, companyId: string): Promise<string> {- try {- const { rows } = await pool.query<{ name: string }>(- `SELECT name FROM users WHERE id = $1 LIMIT 1`, [id],- )- if (rows[0]?.name) return rows[0].name- } catch { /* table may not exist in legacy schemas — fall through */ }- const { rows } = await pool.query<{ name: string }>(- `SELECT name FROM participants WHERE id = $1 AND company_id = $2 LIMIT 1`,- [id, companyId],- )- return rows[0]?.name ?? id+ await publish(CH_MESSAGE_NEW, event).catch((error) => {+ console.warn(`[doc.mention] durable wake ${messageId} committed but publish failed`, error)+ })}export function attachWebSocket(httpServer: Server) {@@ -597,12 +883,12 @@ export function attachWebSocket(httpServer: Server) {// Tenant-aware fan-out: only deliver an event to a socket if the event's// companyId is in the socket's set of memberships. Untagged events are// dropped (no leakage), since every publisher is expected to tag.- let companyId: string | undefined+ let event: RoutedRedisEventtry {- const parsed = JSON.parse(payload) as { companyId?: string }- if (typeof parsed.companyId === 'string') companyId = parsed.companyId+ event = JSON.parse(payload) as RoutedRedisEvent} catch { /* malformed — drop */ return }+ const companyId = typeof event.companyId === 'string' ? event.companyId : undefinedif (!companyId) {// Conservative: untagged events have no tenant — refuse to route.// (If an untagged event ever reaches here it's a publisher bug; logging@@ -611,24 +897,42 @@ export function attachWebSocket(httpServer: Server) {return}- for (const c of clients) {- if (!c.companies.has(companyId)) continue- if (c.ws.readyState !== c.ws.OPEN) continue- // Backpressure guard (OOM fix): `ws.send()` buffers unsent frames in- // process memory when a socket can't drain (slow/stuck client). Under a- // high broadcast rate that buffer grows UNBOUNDED across clients → the pod- // OOMs. If a socket is backed up past the cap it isn't keeping up — drop- // this frame for it; if it's wildly backed up, terminate it to reclaim the- // memory (it reconnects and re-syncs via REST). Bounds WS memory to- // ~WS_MAX_BUFFERED_BYTES per client.- const buffered = c.ws.bufferedAmount- if (buffered > WS_TERMINATE_BUFFERED_BYTES) {- try { c.ws.terminate() } catch { /* ignore */ }- continue+ // Membership resolution is asynchronous. Serialize per conversation (or+ // company for workspace-wide frames) so a message and its delta/reaction+ // cannot be reordered while independent rooms still route in parallel.+ const routeKey = event.conversationId+ ? `${companyId}:conversation:${event.conversationId}`+ : `${companyId}:workspace`+ const previous = redisFanoutQueues.get(routeKey) ?? Promise.resolve()+ const current = previous.catch(() => {}).then(async () => {+ const recipients = await resolveWsEventRecipientUserIds(event)+ for (const c of clients) {+ if (!recipients.has(c.userId)) continue+ if (c.ws.readyState !== c.ws.OPEN) continue+ // Backpressure guard (OOM fix): `ws.send()` buffers unsent frames in+ // process memory when a socket can't drain (slow/stuck client). Under a+ // high broadcast rate that buffer grows UNBOUNDED across clients → the pod+ // OOMs. If a socket is backed up past the cap it isn't keeping up — drop+ // this frame for it; if it's wildly backed up, terminate it to reclaim the+ // memory (it reconnects and re-syncs via REST). Bounds WS memory to+ // ~WS_MAX_BUFFERED_BYTES per client.+ const buffered = c.ws.bufferedAmount+ if (buffered > WS_TERMINATE_BUFFERED_BYTES) {+ try { c.ws.terminate() } catch { /* ignore */ }+ continue+ }+ if (buffered > WS_MAX_BUFFERED_BYTES) continue // skip frame; let it drain+ try { c.ws.send(payload) } catch { /* ignore */ }}- if (buffered > WS_MAX_BUFFERED_BYTES) continue // skip frame; let it drain- try { c.ws.send(payload) } catch { /* ignore */ }- }+ })+ redisFanoutQueues.set(routeKey, current)+ void current.catch((error) => {+ // Fail closed: a routing lookup failure drops the frame instead of+ // falling back to the stale socket membership snapshot.+ console.warn(`[ws] live authorization lookup failed for ${routeKey}`, error)+ }).finally(() => {+ if (redisFanoutQueues.get(routeKey) === current) redisFanoutQueues.delete(routeKey)+ })})// Heartbeat sweeper. Real-deal human presence used to drift because TCP