Skip to content

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

feat(agent-routing): elect one agent for unaddressed human group messages (#123)

cicada6d674d805144
diff --git a/server/src/__integration__/_helpers.ts b/server/src/__integration__/_helpers.ts
index 784124e..6959adf 100644
--- a/server/src/__integration__/_helpers.ts
+++ b/server/src/__integration__/_helpers.ts
@@ -78,6 +78,7 @@ const TABLES_TO_WIPE: readonly string[] = [
'agent_runs',
'agent_events',
'agent_tasks',
+ 'agent_routing_claims',
'agent_log',
'user_preferences',
'company_invitations',
diff --git a/server/src/__integration__/agents-routing-claims.test.ts b/server/src/__integration__/agents-routing-claims.test.ts
new file mode 100644
index 0000000..8d9c3e8
--- /dev/null
+++ b/server/src/__integration__/agents-routing-claims.test.ts
@@ -0,0 +1,256 @@
+import assert from 'node:assert/strict'
+import { after, before, beforeEach, test } from 'node:test'
+import { pool } from '../db/pool.js'
+import {
+ claimPrimary,
+ getClaim,
+ sweepRoutingClaimsOnce,
+} from '../agents/routing-claims.js'
+import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'
+
+before(async () => {
+ await ensureSchemaOnce()
+})
+
+beforeEach(async () => {
+ await resetAllTables()
+})
+
+after(async () => {
+ await teardownAll()
+})
+
+const COMPANY_ID = 'co-routing-test'
+const USER_ID = 'u-routing-test'
+const CONVERSATION_ID = 'conv-routing-test'
+const AGENT_A = 'agent-routing-a'
+const AGENT_B = 'agent-routing-b'
+
+async function seedFixture() {
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, 'Routing Co', $1, $2)`,
+ [COMPANY_ID, USER_ID],
+ )
+ await pool.query(
+ `INSERT INTO participants (id, company_id, kind, name, initial, avatar_bg, status)
+ VALUES ($1, $2, 'agent', 'Agent A', 'A', '#112233', 'avail'),
+ ($3, $2, 'agent', 'Agent B', 'B', '#445566', 'avail')`,
+ [AGENT_A, COMPANY_ID, AGENT_B],
+ )
+ await pool.query(
+ `INSERT INTO conversations (id, company_id, kind, title, members)
+ VALUES ($1, $2, 'group', 'Routing Channel', $3::jsonb)`,
+ [CONVERSATION_ID, COMPANY_ID, JSON.stringify([AGENT_A, AGENT_B])],
+ )
+}
+
+test('[integration] routing-claims: claimPrimary persists claim with cursor_advanced_at and handles re-delivery', async () => {
+ await seedFixture()
+ const messageId = 'msg-claim-1'
+
+ const claim = await claimPrimary({
+ messageId,
+ companyId: COMPANY_ID,
+ conversationId: CONVERSATION_ID,
+ orderedCandidates: [AGENT_A, AGENT_B],
+ })
+
+ assert.ok(claim)
+ assert.equal(claim.messageId, messageId)
+ assert.equal(claim.status, 'pending')
+ assert.equal(claim.cursor, 0)
+ assert.deepEqual(claim.candidates, [AGENT_A, AGENT_B])
+
+ const fetched = await getClaim(messageId)
+ assert.ok(fetched)
+ assert.equal(fetched.messageId, messageId)
+ assert.ok(fetched.cursorAdvancedAt instanceof Date)
+
+ // Re-delivery returns existing row without inserting a new one
+ const reDelivery = await claimPrimary({
+ messageId,
+ companyId: COMPANY_ID,
+ conversationId: CONVERSATION_ID,
+ orderedCandidates: [AGENT_B, AGENT_A],
+ })
+ assert.ok(reDelivery)
+ assert.deepEqual(reDelivery.candidates, [AGENT_A, AGENT_B])
+})
+
+test('[integration] routing-claims: sweep executes CTE without syntax errors and advances quiet candidate', async () => {
+ await seedFixture()
+ const messageId = 'msg-sweep-1'
+
+ await claimPrimary({
+ messageId,
+ companyId: COMPANY_ID,
+ conversationId: CONVERSATION_ID,
+ orderedCandidates: [AGENT_A, AGENT_B],
+ })
+
+ // Expire the lease in the past
+ await pool.query(
+ `UPDATE agent_routing_claims
+ SET lease_expires_at = NOW() - INTERVAL '10 seconds'
+ WHERE message_id = $1`,
+ [messageId],
+ )
+
+ // Sweep runs on real Postgres — CTE with FOR UPDATE SKIP LOCKED must execute cleanly
+ const decisions = await sweepRoutingClaimsOnce({
+ hasRunSince: async () => false, // Primary started no run
+ })
+
+ assert.equal(decisions.length, 1)
+ assert.deepEqual(decisions[0], {
+ kind: 'advance',
+ agentId: AGENT_B,
+ conversationId: CONVERSATION_ID,
+ })
+
+ const updated = await getClaim(messageId)
+ assert.equal(updated?.cursor, 1)
+ assert.equal(updated?.status, 'pending')
+})
+
+test('[integration] routing-claims: sweep marks claim served when candidate has run since advance timestamp', async () => {
+ await seedFixture()
+ const messageId = 'msg-sweep-served'
+
+ await claimPrimary({
+ messageId,
+ companyId: COMPANY_ID,
+ conversationId: CONVERSATION_ID,
+ orderedCandidates: [AGENT_A, AGENT_B],
+ })
+
+ await pool.query(
+ `UPDATE agent_routing_claims
+ SET lease_expires_at = NOW() - INTERVAL '10 seconds'
+ WHERE message_id = $1`,
+ [messageId],
+ )
+
+ let evaluatedSince: any = null
+ const decisions = await sweepRoutingClaimsOnce({
+ hasRunSince: async (_agentId, since) => {
+ evaluatedSince = since
+ return true
+ },
+ })
+
+ assert.equal(decisions.length, 0)
+ assert.ok(evaluatedSince)
+ assert.ok(evaluatedSince instanceof Date)
+
+ const updated = await getClaim(messageId)
+ assert.equal(updated?.status, 'served')
+})
+
+test('[integration] routing-claims: sweep exhausts and falls back to full-room fanout when all candidates go quiet', async () => {
+ await seedFixture()
+ const messageId = 'msg-sweep-exhaust'
+
+ await claimPrimary({
+ messageId,
+ companyId: COMPANY_ID,
+ conversationId: CONVERSATION_ID,
+ orderedCandidates: [AGENT_A, AGENT_B],
+ })
+
+ // Set cursor to 1 (last candidate) and expire lease
+ await pool.query(
+ `UPDATE agent_routing_claims
+ SET cursor = 1, lease_expires_at = NOW() - INTERVAL '10 seconds'
+ WHERE message_id = $1`,
+ [messageId],
+ )
+
+ const decisions = await sweepRoutingClaimsOnce({
+ hasRunSince: async () => false,
+ })
+
+ assert.equal(decisions.length, 1)
+ assert.deepEqual(decisions[0], {
+ kind: 'exhaust',
+ conversationId: CONVERSATION_ID,
+ room: [AGENT_A, AGENT_B],
+ })
+
+ const updated = await getClaim(messageId)
+ assert.equal(updated?.status, 'exhausted')
+})
+
+test('[integration] routing-claims: sweep served wakes cursor-lagging room members on PostgreSQL', async () => {
+ await seedFixture()
+ const messageId = 'msg-sweep-catchup'
+
+ // Seed the unaddressed group message
+ await pool.query(
+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id, created_at)
+ VALUES ($1, $2, 'human-1', 'text', 'who can look into this?', 1, $3, NOW() - INTERVAL '60 seconds')`,
+ [messageId, CONVERSATION_ID, COMPANY_ID],
+ )
+
+ await claimPrimary({
+ messageId,
+ companyId: COMPANY_ID,
+ conversationId: CONVERSATION_ID,
+ orderedCandidates: [AGENT_A, AGENT_B],
+ })
+
+ // Expire the lease in the past
+ await pool.query(
+ `UPDATE agent_routing_claims
+ SET lease_expires_at = NOW() - INTERVAL '10 seconds'
+ WHERE message_id = $1`,
+ [messageId],
+ )
+
+ // Primary AGENT_A has run since anchor, but AGENT_B was not woken at T=0 and its cursor lags behind
+ const decisions = await sweepRoutingClaimsOnce({
+ hasRunSince: async (_agentId) => true,
+ })
+
+ assert.equal(decisions.length, 1)
+ assert.deepEqual(decisions[0], {
+ kind: 'catchup',
+ conversationId: CONVERSATION_ID,
+ room: [AGENT_B],
+ })
+
+ const claim = await getClaim(messageId)
+ assert.equal(claim?.status, 'served')
+
+ // When AGENT_B's cursor catches up, a subsequent claim served emits no catchup wake
+ await pool.query(
+ `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at, last_read_message_id)
+ VALUES ($1, $2, NOW(), $3)
+ ON CONFLICT (user_id, conversation_id) DO UPDATE SET last_read_at = NOW(), last_read_message_id = $3`,
+ [AGENT_B, CONVERSATION_ID, messageId],
+ )
+
+ const messageId2 = 'msg-sweep-caught-up'
+ await pool.query(
+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id, created_at)
+ VALUES ($1, $2, 'human-1', 'text', 'another question', 2, $3, NOW() - INTERVAL '30 seconds')`,
+ [messageId2, CONVERSATION_ID, COMPANY_ID],
+ )
+ await claimPrimary({
+ messageId: messageId2,
+ companyId: COMPANY_ID,
+ conversationId: CONVERSATION_ID,
+ orderedCandidates: [AGENT_A, AGENT_B],
+ })
+ await pool.query(
+ `UPDATE agent_routing_claims
+ SET lease_expires_at = NOW() - INTERVAL '10 seconds'
+ WHERE message_id = $1`,
+ [messageId2],
+ )
+
+ const decisions2 = await sweepRoutingClaimsOnce({
+ hasRunSince: async (_agentId) => true,
+ })
+ assert.equal(decisions2.length, 0)
+})
diff --git a/server/src/__tests__/agents-routing-election.test.ts b/server/src/__tests__/agents-routing-election.test.ts
new file mode 100644
index 0000000..2d44df7
--- /dev/null
+++ b/server/src/__tests__/agents-routing-election.test.ts
@@ -0,0 +1,283 @@
+/**
+ * The one-of-us election (#70): the router's unaddressed decision, the
+ * deterministic lineup, and the lease-sweep state machine.
+ *
+ * Run: node --import tsx --test server/src/__tests__/agents-routing-election.test.ts
+ */
+import { afterEach, test } from 'node:test'
+import assert from 'node:assert/strict'
+
+// Same pattern as computer-engine-redetect.test.ts: pin the HTTP runtime
+// client and mock the pool, so the routing-claims tests run without Redis or
+// Postgres.
+process.env.CUMORA_RUNTIME_CLIENT = 'http'
+process.env.OPENAI_API_KEY ??= 'test-key'
+
+const { parseRoute, buildUnaddressedRouteRequest, parseUnaddressedRoute } = await import('../agents/routing.js')
+const { electLineup, orderCandidates } = await import('../agents/routing-election.js')
+const { claimPrimary, sweepRoutingClaimsOnce, ELECTION_LEASE_MS } = await import('../agents/routing-claims.js')
+const { pool } = await import('../db/pool.js')
+
+type ElectionCandidate = import('../agents/routing-election.js').ElectionCandidate
+
+const realQuery = pool.query.bind(pool)
+
+afterEach(() => {
+ ;(pool as unknown as { query: typeof realQuery }).query = realQuery
+})
+
+// ── router plumbing ────────────────────────────────────────────────────────
+
+test('parseRoute recognizes one-of-us instead of lossily mapping it to each', () => {
+ assert.equal(parseRoute('{"responseMode": "one-of-us"}'), 'one-of-us')
+ assert.equal(parseRoute('garbage {"responseMode":"ME"} trailing'), 'me')
+ assert.equal(parseRoute('{"responseMode": "each"}'), 'each')
+ assert.equal(parseRoute('no json at all'), 'each')
+ assert.equal(parseRoute('{"responseMode": "spray"}'), 'each')
+})
+
+const ROOM = [
+ { id: 'atlas', role: 'engineer', status: 'avail', statusUpdatedAt: new Date() },
+ { id: 'iris', role: 'designer', status: 'avail', statusUpdatedAt: new Date() },
+ { id: 'nova', role: null, status: 'avail', statusUpdatedAt: new Date() },
+]
+
+test('the unaddressed router is only asked when there is a room to elect from', () => {
+ const body = 'we need a launch email drafted today'
+ // A broadcast must never narrow — even when it names nobody with an exact @id.
+ assert.equal(buildUnaddressedRouteRequest({ body: 'what does everyone think @all', conversationKind: 'group', candidates: ROOM }).mode, 'each')
+ // A DM has one recipient; the human-DM triage note already covers it.
+ assert.equal(buildUnaddressedRouteRequest({ body, conversationKind: 'direct', candidates: ROOM }).mode, 'each')
+ // A room of one has nothing to elect among.
+ assert.equal(buildUnaddressedRouteRequest({ body, conversationKind: 'group', candidates: [ROOM[0]] }).mode, 'each')
+ const req = buildUnaddressedRouteRequest({ body, conversationKind: 'group', candidates: ROOM })
+ assert.ok(!req.mode, 'a real room asks the router')
+ assert.match(req.instructions ?? '', /one-of-us/)
+ assert.match(req.input ?? '', /iris \(designer\)/, 'roles ride along for the fit signal')
+ assert.match(req.input ?? '', /nova/, 'roleless candidates still appear')
+})
+
+test('parseUnaddressedRoute narrows only on an explicit, well-formed one-of-us', () => {
+ assert.deepEqual(parseUnaddressedRoute('{"responseMode":"one-of-us","primary":"iris"}'), { mode: 'one-of-us', primary: 'iris' })
+ assert.deepEqual(parseUnaddressedRoute('{"responseMode":"one-of-us"}'), { mode: 'one-of-us', primary: null })
+ assert.deepEqual(parseUnaddressedRoute('{"responseMode":"each","primary":"iris"}'), { mode: 'each', primary: null })
+ // Everything else reads as `each` — narrowing is the silent mistake.
+ assert.deepEqual(parseUnaddressedRoute(''), { mode: 'each', primary: null })
+ assert.deepEqual(parseUnaddressedRoute('{"responseMode":"each"}'), { mode: 'each', primary: null })
+})
+
+// ── deterministic election ─────────────────────────────────────────────────
+
+const NOW = 1_000_000
+const LEASE = 60_000
+
+function cand(id: string, status: string | null, ageMs: number, role: string | null = null): ElectionCandidate {
+ return { id, role, status, statusUpdatedAt: new Date(NOW - ageMs) }
+}
+
+test('ordering puts available agents first and never trusts membership order', () => {
+ const candidates = [
+ cand('zoe', 'thinking', 1_000), // busy, fresh
+ cand('atlas', 'avail', 1_000),
+ cand('iris', null, 1_000),
+ cand('milu', 'working', 5 * 60_000), // stale busy — the lease expired it
+ ]
+ assert.deepEqual(
+ orderCandidates(candidates, { now: NOW, leaseMs: LEASE }),
+ ['atlas', 'iris', 'milu', 'zoe'],
+ )
+})
+
+test('the lineup honors an available proposal, then available, then anyone', () => {
+ const candidates = [
+ cand('atlas', 'thinking', 1_000),
+ cand('iris', 'avail', 1_000),
+ cand('nova', 'avail', 1_000),
+ ]
+ // Role fit wins when the proposed agent can actually take the turn.
+ const proposed = electLineup('nova', candidates, { now: NOW, leaseMs: LEASE })
+ assert.equal(proposed?.primary, 'nova')
+ assert.equal(proposed?.lineup[0], 'nova')
+ // A proposal for a mid-turn agent is ignored in favour of an available one.
+ assert.equal(electLineup('atlas', candidates, { now: NOW, leaseMs: LEASE })?.primary, 'iris')
+ // No proposal → the head of the deterministic order.
+ assert.equal(electLineup(null, candidates, { now: NOW, leaseMs: LEASE })?.primary, 'iris')
+ // A proposal for an agent that is not in the room changes nothing.
+ assert.equal(electLineup('ghost', candidates, { now: NOW, leaseMs: LEASE })?.primary, 'iris')
+})
+
+test('with the whole room mid-turn, the election still picks someone', () => {
+ const candidates = [cand('atlas', 'working', 1_000), cand('iris', 'thinking', 1_000)]
+ // A proposal that is a real candidate is kept — waking a busy agent queues
+ // the message behind its turn, which still beats no one being woken.
+ assert.equal(electLineup('iris', candidates, { now: NOW, leaseMs: LEASE })?.primary, 'iris')
+ assert.equal(electLineup(null, candidates, { now: NOW, leaseMs: LEASE })?.primary, 'atlas')
+ assert.equal(electLineup(null, [], { now: NOW, leaseMs: LEASE }), null)
+})
+
+// ── the lease row + sweep ──────────────────────────────────────────────────
+
+type QueryHandler = (sql: string, params?: unknown[]) => { rows: unknown[] }
+
+function mockPool(handler: QueryHandler): void {
+ ;(pool as unknown as { query: QueryHandler }).query = (sql: string, params?: unknown[]) => handler(sql, params)
+}
+
+const INSERT = 'INSERT INTO agent_routing_claims'
+const TAKE = 'WITH due AS'
+const SERVE_OR_EXHAUST = 'UPDATE agent_routing_claims SET status'
+const ADVANCE = 'UPDATE agent_routing_claims\n SET cursor'
+const REAP = 'DELETE FROM agent_routing_claims'
+const GET = 'SELECT message_id'
+const LAGGING = 'SELECT cm.participant_id'
+
+test('claimPrimary returns the fresh row to the winner and the existing row to a re-delivery', async () => {
+ mockPool((sql) => {
+ if (sql.startsWith(INSERT)) {
+ return { rows: [{ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', candidates: ['iris', 'atlas'], cursor: 0, status: 'pending' }] }
+ }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ const won = await claimPrimary({ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', orderedCandidates: ['iris', 'atlas'] })
+ assert.equal(won?.candidates[0], 'iris')
+ assert.equal(won?.status, 'pending')
+
+ // The message re-delivered after the wake-claim TTL: INSERT conflicts, the
+ // existing row comes back so the caller honors the recorded primary.
+ mockPool((sql) => {
+ if (sql.startsWith(INSERT)) return { rows: [] }
+ if (sql.startsWith(GET)) {
+ return { rows: [{ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', candidates: ['atlas', 'iris'], cursor: 1, status: 'pending' }] }
+ }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ const existing = await claimPrimary({ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', orderedCandidates: ['iris', 'atlas'] })
+ assert.deepEqual(existing?.candidates, ['atlas', 'iris'])
+ assert.equal(existing?.cursor, 1)
+})
+
+test('the sweep serves a claim whose primary started any turn since the claim', async () => {
+ const updates: string[] = []
+ mockPool((sql) => {
+ if (sql.startsWith(TAKE)) return { rows: [{ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', candidates: ['iris', 'atlas'], cursor: 0, status: 'pending', createdAt: new Date(NOW - 120_000) }] }
+ if (sql.startsWith('SELECT id FROM agent_runs')) return { rows: [{ id: 'r1' }] }
+ if (sql.startsWith(SERVE_OR_EXHAUST)) {
+ updates.push(sql)
+ return { rows: [] }
+ }
+ if (sql.startsWith(LAGGING)) return { rows: [] }
+ if (sql.startsWith(REAP)) return { rows: [] }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ const wakes = await sweepRoutingClaimsOnce()
+ assert.deepEqual(wakes, [])
+ assert.equal(updates.length, 1)
+ assert.match(updates[0], /status = 'served'/)
+})
+
+test('the sweep wakes cursor-lagging room members when a claim resolves as served', async () => {
+ // Resolves the cursor-exposure window finding from yetone's review (#123):
+ // When primary serves the claim, unwoken members whose read cursor still
+ // lags behind the message are woken to close the correctness hole.
+ mockPool((sql) => {
+ if (sql.startsWith(TAKE)) return { rows: [{ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', candidates: ['iris', 'atlas'], cursor: 0, status: 'pending', createdAt: new Date(NOW - 120_000) }] }
+ if (sql.startsWith('SELECT id FROM agent_runs')) return { rows: [{ id: 'r1' }] }
+ if (sql.startsWith(SERVE_OR_EXHAUST)) return { rows: [] }
+ if (sql.startsWith(LAGGING)) return { rows: [{ participant_id: 'atlas' }] }
+ if (sql.startsWith(REAP)) return { rows: [] }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ const decisions = await sweepRoutingClaimsOnce()
+ assert.deepEqual(decisions, [{ kind: 'catchup', conversationId: 'conv1', room: ['atlas'] }])
+})
+
+test('the sweep advances to the next candidate when the primary went quiet', async () => {
+ let advanced = false
+ mockPool((sql) => {
+ if (sql.startsWith(TAKE)) return { rows: [{ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', candidates: ['iris', 'atlas'], cursor: 0, status: 'pending', createdAt: new Date(NOW - 120_000) }] }
+ if (sql.startsWith('SELECT id FROM agent_runs')) return { rows: [] }
+ if (sql.startsWith(ADVANCE)) {
+ advanced = true
+ return { rows: [] }
+ }
+ if (sql.startsWith(REAP)) return { rows: [] }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ const decisions = await sweepRoutingClaimsOnce()
+ assert.equal(advanced, true)
+ assert.deepEqual(decisions, [{ kind: 'advance', agentId: 'atlas', conversationId: 'conv1' }])
+})
+
+test('an exhausted lineup is marked and falls back to the full-room fan-out', async () => {
+ // Exhaust means every candidate held the wake and started no turn. Leaving
+ // the message to each member's next natural wake would let a later
+ // read-cursor ack skip it permanently (the #70 cursor semantics), so the
+ // sweep hands the room back to the pre-election behaviour: one full fan-out.
+ const statuses: string[] = []
+ mockPool((sql) => {
+ if (sql.startsWith(TAKE)) return { rows: [{ messageId: 'm1', companyId: 'c1', conversationId: 'conv1', candidates: ['iris', 'atlas'], cursor: 1, status: 'pending', createdAt: new Date(NOW - 300_000) }] }
+ if (sql.startsWith('SELECT id FROM agent_runs')) return { rows: [] }
+ if (sql.startsWith(SERVE_OR_EXHAUST)) {
+ statuses.push(/'exhausted'/.test(sql) ? 'exhausted' : 'other')
+ return { rows: [] }
+ }
+ if (sql.startsWith(REAP)) return { rows: [] }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ const decisions = await sweepRoutingClaimsOnce()
+ assert.deepEqual(statuses, ['exhausted'])
+ assert.deepEqual(decisions, [{ kind: 'exhaust', conversationId: 'conv1', room: ['iris', 'atlas'] }])
+})
+
+test('the sweep leaves healthy claims alone and reaps terminal rows', async () => {
+ const calls: string[] = []
+ mockPool((sql) => {
+ calls.push(sql)
+ if (sql.startsWith(TAKE)) return { rows: [] }
+ if (sql.startsWith(REAP)) return { rows: [] }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ const wakes = await sweepRoutingClaimsOnce()
+ assert.deepEqual(wakes, [])
+ assert.equal(calls.filter((c) => c.startsWith(REAP)).length, 1, 'terminal rows are reaped so the table stays operator-sized')
+})
+
+test('the election lease is generous enough for a cold pod or a reconnecting daemon', () => {
+ assert.equal(ELECTION_LEASE_MS, 90_000)
+})
+
+test('the sweep anchors hasRunSince to cursorAdvancedAt rather than claim createdAt', async () => {
+ let passedSince: any = null
+ const claimCreated = new Date(NOW - 300_000)
+ const candidateAdvanced = new Date(NOW - 90_000)
+ mockPool((sql) => {
+ if (sql.startsWith(TAKE)) {
+ return {
+ rows: [{
+ messageId: 'm1',
+ companyId: 'c1',
+ conversationId: 'conv1',
+ candidates: ['iris', 'atlas'],
+ cursor: 1,
+ status: 'pending',
+ createdAt: claimCreated,
+ cursorAdvancedAt: candidateAdvanced,
+ }],
+ }
+ }
+ if (sql.startsWith('SELECT id FROM agent_runs')) return { rows: [] }
+ if (sql.startsWith(SERVE_OR_EXHAUST)) return { rows: [] }
+ if (sql.startsWith(ADVANCE)) return { rows: [] }
+ if (sql.startsWith(REAP)) return { rows: [] }
+ throw new Error('unexpected: ' + sql.slice(0, 60))
+ })
+ await sweepRoutingClaimsOnce({
+ hasRunSince: async (_agentId, since) => {
+ passedSince = since
+ return false
+ },
+ })
+ assert.ok(passedSince)
+ assert.equal(passedSince.getTime(), candidateAdvanced.getTime())
+})
+
diff --git a/server/src/__tests__/agents-routing.test.ts b/server/src/__tests__/agents-routing.test.ts
index a248dcf..e13f2e8 100644
--- a/server/src/__tests__/agents-routing.test.ts
+++ b/server/src/__tests__/agents-routing.test.ts
@@ -57,7 +57,6 @@ test('an explicit me is honoured', () => {
test('each, unknown modes, junk and empty all read as each', () => {
for (const raw of [
'{"responseMode": "each"}',
- '{"responseMode": "one-of-us"}', // step two, not wired — must not narrow yet
'{"responseMode": "nonsense"}',
'the model wrote prose instead',
'',
@@ -66,6 +65,15 @@ test('each, unknown modes, junk and empty all read as each', () => {
}
})
+test('one-of-us parses as itself but never narrows the ADDRESSED route', () => {
+ // Step two is wired now (#70): parseRoute recognizes it. The addressed
+ // router is still instructed to answer me|each only, and even if a rogue
+ // model answers one-of-us, recipientsForRoute treats it like each — full
+ // fan-out. The unaddressed election parses through parseUnaddressedRoute.
+ assert.equal(parseRoute('{"responseMode": "one-of-us"}'), 'one-of-us')
+ assert.deepEqual(recipientsForRoute('one-of-us', ['a', 'b'], ['a']), ['a', 'b'])
+})
+
test('me is found inside a fenced or chatty completion', () => {
assert.equal(parseRoute('```json\n{"responseMode": "me", "why": "direct request"}\n```'), 'me')
})
diff --git a/server/src/__tests__/schema-migrations.test.ts b/server/src/__tests__/schema-migrations.test.ts
index 53977d8..30319d2 100644
--- a/server/src/__tests__/schema-migrations.test.ts
+++ b/server/src/__tests__/schema-migrations.test.ts
@@ -19,6 +19,8 @@ const { agentRuntimeAssignmentChecksum } = await import('../db/migrations/0004-a
const { searchTrigramIndexChecksum } = await import('../db/migrations/0005-search-trigram-index.js')
const { emailMessagesCompanySmtpIdChecksum } = await import('../db/migrations/0006-email-messages-company-smtp-id.js')
const { engineDefaultsChecksum } = await import('../db/migrations/0007-engine-defaults.js')
+const { agentProviderProfileChecksum } = await import('../db/migrations/0008-agent-provider-profile.js')
+const { agentRoutingClaimsChecksum } = await import('../db/migrations/0009-agent-routing-claims.js')
const { verifySchemaCompatibility } = await import('../db/schema-version.js')
type SchemaVersionQueryable = import('../db/schema-version.js').SchemaVersionQueryable
@@ -52,6 +54,14 @@ test('the engine defaults migration matches its immutable manifest checksum', ()
assert.equal(engineDefaultsChecksum(), SCHEMA_MIGRATIONS[6].checksum)
})
+test('the agent provider profile migration matches its immutable manifest checksum', () => {
+ assert.equal(agentProviderProfileChecksum(), SCHEMA_MIGRATIONS[7].checksum)
+})
+
+test('the agent routing claims migration matches its immutable manifest checksum', () => {
+ assert.equal(agentRoutingClaimsChecksum(), SCHEMA_MIGRATIONS[8].checksum)
+})
+
test('the migration owner accepts an exact prefix and reports its pending suffix', () => {
const empty = validateMigrationHistory([], { allowPending: true })
assert.equal(empty.currentVersion, 0)
diff --git a/server/src/agents/routing-claims.ts b/server/src/agents/routing-claims.ts
new file mode 100644
index 0000000..f2f7463
--- /dev/null
+++ b/server/src/agents/routing-claims.ts
@@ -0,0 +1,314 @@
+/**
+ * The claim row behind a `one-of-us` election (#70).
+ *
+ * Wake delivery is already single-owner per message (`claimAndWake` SETNXes
+ * `cumora:wake-claim:<messageId>` before `wake()` runs), so this row is NOT a
+ * mutual-exclusion primitive. It is the durable memory of the election:
+ *
+ * - observable — an operator can see which agent was elected for which
+ * message and how many candidates were burnt before one turned;
+ * - leaseable — the elected primary has LEASE_MS to start a turn; a sweeper
+ * advances to the next ordered candidate when the lease lapses with no
+ * `agent_runs` row from the primary, so a no-show degrades to the next
+ * agent instead of a silent room;
+ * - recoverable — if the wake-claim TTL lapses and the message re-delivers,
+ * the existing row is honored (same primary, same cursor) instead of
+ * re-electing.
+ *
+ * Cursor semantics: `candidates[cursor]` is the agent currently holding the
+ * wake. `candidates` is stored in the deterministic order produced by
+ * `orderCandidates` — the sweep walks it, it never re-orders.
+ *
+ * Multi-replica safety of the sweep: a due row is taken with
+ * `UPDATE … WHERE lease_expires_at < NOW() RETURNING`, so exactly one replica
+ * advances each round; the renewed lease keeps the others out until then.
+ */
+import { pool } from '../db/pool.js'
+import { env } from '../env.js'
+import type { ElectionCandidate } from './routing-election.js'
+
+/** How long the elected primary has to START a turn before the sweep moves on.
+ * Generous on purpose: a cloud pod may be cold-booting, a BYOA daemon may be
+ * mid-reconnect; both deliver the turn from the durable inbox once alive. */
+export const ELECTION_LEASE_MS = 90_000
+const SWEEP_INTERVAL_MS = 15_000
+const SWEEP_BATCH = 20
+/** Terminal rows are operator-facing history, not state — reap after a day. */
+const TERMINAL_ROW_TTL_MS = 24 * 60 * 60_000
+
+export type ClaimStatus = 'pending' | 'served' | 'exhausted'
+
+export interface RoutingClaim {
+ messageId: string
+ companyId: string | null
+ conversationId: string
+ candidates: string[]
+ cursor: number
+ status: ClaimStatus
+ cursorAdvancedAt?: Date | null
+}
+
+/** Read the wake candidates' roster rows (role + busy-status lease) for the
+ * election. Candidates that departed mid-flight are dropped — they must not
+ * be electable even if membership still lists them. */
+export async function loadElectionCandidates(agentIds: readonly string[]): Promise<ElectionCandidate[]> {
+ if (agentIds.length === 0) return []
+ const { rows } = await pool.query<{
+ id: string; role: string | null; status: string | null; statusUpdatedAt: Date | null
+ }>(
+ `SELECT id, role, status, status_updated_at AS "statusUpdatedAt"
+ FROM participants
+ WHERE id = ANY($1::text[])
+ AND kind = 'agent'
+ AND departed_at IS NULL`,
+ [[...agentIds]],
+ )
+ return rows
+}
+
+/** Write the election's winner. Returns the row when THIS caller won the
+ * insert; when a row already exists (the message re-delivered after the wake
+ * claim TTL), returns the existing row so the caller honors it instead of
+ * re-electing. */
+export async function claimPrimary(args: {
+ messageId: string
+ companyId: string | null
+ conversationId: string
+ orderedCandidates: readonly string[]
+ leaseMs?: number
+}): Promise<RoutingClaim | null> {
+ const leaseMs = args.leaseMs ?? ELECTION_LEASE_MS
+ const { rows } = await pool.query<RoutingClaimRow>(
+ `INSERT INTO agent_routing_claims
+ (message_id, company_id, conversation_id, candidates, cursor, cursor_advanced_at, status, lease_expires_at)
+ VALUES ($1, $2, $3, $4::text[], 0, NOW(), 'pending', NOW() + ($5::int * INTERVAL '1 millisecond'))
+ ON CONFLICT (message_id) DO NOTHING
+ RETURNING message_id AS "messageId", company_id AS "companyId", conversation_id AS "conversationId",
+ candidates, cursor, status, cursor_advanced_at AS "cursorAdvancedAt"`,
+ [args.messageId, args.companyId, args.conversationId, [...args.orderedCandidates], leaseMs],
+ )
+ if (rows[0]) return toClaim(rows[0])
+ return await getClaim(args.messageId)
+}
+
+export async function getClaim(messageId: string): Promise<RoutingClaim | null> {
+ const { rows } = await pool.query<RoutingClaimRow>(
+ `SELECT message_id AS "messageId", company_id AS "companyId", conversation_id AS "conversationId",
+ candidates, cursor, status, cursor_advanced_at AS "cursorAdvancedAt"
+ FROM agent_routing_claims
+ WHERE message_id = $1`,
+ [messageId],
+ )
+ return rows[0] ? toClaim(rows[0]) : null
+}
+
+interface RoutingClaimRow {
+ messageId: string
+ companyId: string | null
+ conversationId: string
+ candidates: string[]
+ cursor: number
+ status: ClaimStatus
+ cursorAdvancedAt?: Date | null
+}
+
+function toClaim(r: RoutingClaimRow): RoutingClaim {
+ return {
+ messageId: r.messageId,
+ companyId: r.companyId,
+ conversationId: r.conversationId,
+ candidates: [...r.candidates],
+ cursor: r.cursor,
+ status: r.status,
+ cursorAdvancedAt: r.cursorAdvancedAt,
+ }
+}
+
+/** One sweep pass. Returns the wakes the sweep decided on, if any — the caller
+ * (the interval worker) performs them, so this module stays free of the
+ * scheduler's import cycle.
+ *
+ * `advance` moves the wake to the next candidate. `exhaust` is the terminal
+ * state: every candidate held the wake and started no turn, so the room is
+ * handed back to the pre-election behaviour — a full fan-out of the original
+ * lineup — rather than being left to each member's next natural wake. Wakes
+ * are durable in the inbox, so for members already back online this is
+ * redundant; for the ones whose laptop was shut during their window it is
+ * the difference between the message being processed and being skipped past
+ * by a later read-cursor ack (see the #70 discussion on cursor semantics). */
+export type SweepDecision =
+ | { kind: 'advance'; agentId: string; conversationId: string }
+ | { kind: 'exhaust'; conversationId: string; room: string[] }
+ | { kind: 'catchup'; conversationId: string; room: string[] }
+
+export async function sweepRoutingClaimsOnce(opts: {
+ leaseMs?: number
+ hasRunSince?: (agentId: string, since: Date, companyId: string | null) => Promise<boolean>
+ findLaggingMembers?: (conversationId: string, messageId: string, companyId: string | null, excludeAgentId: string) => Promise<string[]>
+} = {}): Promise<SweepDecision[]> {
+ const leaseMs = opts.leaseMs ?? ELECTION_LEASE_MS
+ const hasRunSince = opts.hasRunSince ?? defaultHasRunSince
+ const findLaggingMembers = opts.findLaggingMembers ?? defaultFindCursorLaggingMembers
+ const decisions: SweepDecision[] = []
+
+ const due = await pool.query<TakenRow>(
+ `WITH due AS (
+ SELECT message_id
+ FROM agent_routing_claims
+ WHERE status = 'pending'
+ AND lease_expires_at < NOW()
+ ORDER BY lease_expires_at ASC
+ LIMIT $2
+ FOR UPDATE SKIP LOCKED
+ )
+ UPDATE agent_routing_claims c
+ SET lease_expires_at = NOW() + ($1::int * INTERVAL '1 millisecond'),
+ updated_at = NOW()
+ FROM due
+ WHERE c.message_id = due.message_id
+ RETURNING c.message_id AS "messageId", c.company_id AS "companyId", c.conversation_id AS "conversationId",
+ c.candidates, c.cursor, c.status, c.created_at AS "createdAt",
+ c.cursor_advanced_at AS "cursorAdvancedAt"`,
+ [leaseMs, SWEEP_BATCH],
+ )
+
+ for (const row of due.rows) {
+ const primary = row.candidates[row.cursor]
+ if (!primary) {
+ // Defensive: an out-of-range cursor can only come from manual edits.
+ await pool.query(`UPDATE agent_routing_claims SET status = 'exhausted', updated_at = NOW() WHERE message_id = $1`, [row.messageId])
+ continue
+ }
+ const anchor = row.cursorAdvancedAt ?? row.createdAt
+ if (await hasRunSince(primary, anchor, row.companyId)) {
+ await pool.query(`UPDATE agent_routing_claims SET status = 'served', updated_at = NOW() WHERE message_id = $1`, [row.messageId])
+ const lagging = await findLaggingMembers(row.conversationId, row.messageId, row.companyId, primary).catch((err) => {
+ console.error(`[routing] findCursorLaggingMembers failed for message ${row.messageId}:`, err instanceof Error ? err.message : err)
+ return []
+ })
+ if (lagging.length > 0) {
+ console.log(`[routing] claim for message ${row.messageId} served by ${primary} — waking ${lagging.length} cursor-lagging room member(s) to close exposure window`)
+ decisions.push({ kind: 'catchup', conversationId: row.conversationId, room: lagging })
+ }
+ continue
+ }
+ const nextCursor = row.cursor + 1
+ if (nextCursor >= row.candidates.length) {
+ await pool.query(`UPDATE agent_routing_claims SET status = 'exhausted', updated_at = NOW() WHERE message_id = $1`, [row.messageId])
+ console.warn(`[routing] election for message ${row.messageId}: every candidate went quiet — falling back to the full-room fan-out`)
+ decisions.push({ kind: 'exhaust', conversationId: row.conversationId, room: [...row.candidates] })
+ continue
+ }
+ await pool.query(
+ `UPDATE agent_routing_claims
+ SET cursor = $2,
+ cursor_advanced_at = NOW(),
+ lease_expires_at = NOW() + ($3::int * INTERVAL '1 millisecond'),
+ updated_at = NOW()
+ WHERE message_id = $1 AND cursor = $4`,
+ [row.messageId, nextCursor, leaseMs, row.cursor],
+ )
+ console.warn(`[routing] elected primary ${primary} for message ${row.messageId} produced no turn within its lease — advancing to ${row.candidates[nextCursor]}`)
+ decisions.push({ kind: 'advance', agentId: row.candidates[nextCursor], conversationId: row.conversationId })
+ }
+
+ // Reap terminal rows so the table stays operator-sized.
+ await pool.query(
+ `DELETE FROM agent_routing_claims
+ WHERE status <> 'pending'
+ AND updated_at < NOW() - ($1::int * INTERVAL '1 millisecond')`,
+ [TERMINAL_ROW_TTL_MS],
+ )
+ return decisions
+}
+
+interface TakenRow extends RoutingClaimRow {
+ createdAt: Date
+}
+
+/** Did the agent start ANY turn since the claim? Coarse on purpose: a run in
+ * another room proves the agent is alive and turning, and wrongly "serving"
+ * a claim costs one silent room — the same silence the pre-election world
+ * lived in. Wrongly advancing on a live agent would double-wake. */
+async function defaultHasRunSince(agentId: string, since: Date, companyId: string | null): Promise<boolean> {
+ const { rows } = await pool.query<{ id: string }>(
+ `SELECT id FROM agent_runs
+ WHERE agent_id = $1
+ AND started_at > $2
+ AND ($3::text IS NULL OR company_id = $3)
+ LIMIT 1`,
+ [agentId, since, companyId],
+ )
+ return rows.length > 0
+}
+
+/** Find any active agent member in the conversation whose read cursor
+ * is still behind this message. Used on claim resolution ('served') to
+ * close the cursor-exposure window: room members that were not woken
+ * for the election are woken once the claim resolves, catching their
+ * cursor up and preventing silent message skipping on a subsequent post. */
+export async function defaultFindCursorLaggingMembers(
+ conversationId: string,
+ messageId: string,
+ companyId: string | null,
+ excludeAgentId: string,
+): Promise<string[]> {
+ const { rows } = await pool.query<{ participant_id: string }>(
+ `SELECT cm.participant_id
+ FROM conversation_members cm
+ JOIN participants p
+ ON p.id = cm.participant_id
+ AND p.company_id = cm.company_id
+ AND p.kind = 'agent'
+ AND p.departed_at IS NULL
+ JOIN messages m
+ ON m.id = $1
+ LEFT JOIN conversation_reads cr
+ ON cr.user_id = cm.participant_id
+ AND cr.conversation_id = cm.conversation_id
+ WHERE cm.conversation_id = $2
+ AND ($3::text IS NULL OR cm.company_id = $3)
+ AND cm.participant_id <> $4
+ AND ROW(COALESCE(cr.last_read_at, '1970-01-01T00:00:00Z'::timestamptz), COALESCE(cr.last_read_message_id, ''))
+ < ROW(m.created_at, m.id)
+ ORDER BY cm.ordinal ASC`,
+ [messageId, conversationId, companyId, excludeAgentId],
+ )
+ return rows.map((r) => r.participant_id)
+}
+
+function startRoutingClaimSweeper(intervalMs: number = SWEEP_INTERVAL_MS): NodeJS.Timeout {
+ const tick = (): void => {
+ sweepRoutingClaimsOnce()
+ .then((decisions) => {
+ for (const d of decisions) {
+ void (async () => {
+ const scheduler = await import('./scheduler.js')
+ if (d.kind === 'advance') {
+ await scheduler.wakeAgent(d.agentId, 'message.new', d.conversationId)
+ } else {
+ // Both 'exhaust' and 'catchup' fan out to the candidate list:
+ // - exhaust: election expired without a run; fall back to pre-election full fan-out
+ // - catchup: claim resolved (served); wake cursor-lagging members so their read cursor
+ // catches up, eliminating the cursor-exposure window.
+ await scheduler.fanOutWake(d.room, d.conversationId, null)
+ }
+ })().catch((err) => {
+ console.error(`[routing] lease-advance wake failed (${d.kind}):`, err instanceof Error ? err.message : err)
+ })
+ }
+ })
+ .catch((err) => console.error('[routing] election sweep failed:', err instanceof Error ? err.message : err))
+ }
+ setImmediate(tick)
+ const t = setInterval(tick, intervalMs)
+ t.unref?.()
+ return t
+}
+
+/** Started by the scheduler module once the server is up. No-op when the
+ * one-of-us route is disabled — no elections are written, so nothing to sweep. */
+export function startRoutingClaimSweeperIfEnabled(): NodeJS.Timeout | null {
+ if (!env.ROUTING_ONE_OF_US) return null
+ return startRoutingClaimSweeper()
+}
diff --git a/server/src/agents/routing-election.ts b/server/src/agents/routing-election.ts
new file mode 100644
index 0000000..fe77a09
--- /dev/null
+++ b/server/src/agents/routing-election.ts
@@ -0,0 +1,100 @@
+/**
+ * Primary election for the `one-of-us` route (#70).
+ *
+ * The router (`routing.ts`) only answers whether an unaddressed human group
+ * message needs the whole room (`each`) or ONE agent to take the turn
+ * (`one-of-us`), and may propose that one agent by role fit. Everything that
+ * must be deterministic across replicas happens HERE, in code, with no I/O:
+ *
+ * - ordering: available agents first, stable id tie-break inside each class;
+ * - validation: a router proposal that is not a real candidate is ignored;
+ * - fallback: no valid proposal → the first ordered candidate.
+ *
+ * "Available" mirrors the busy-status lease the rest of the system uses
+ * (`BUSY_STATUS_LEASE_MS`): an agent whose `status` is thinking/working/waiting
+ * with a fresh `status_updated_at` is mid-turn elsewhere, and electing it would
+ * queue a new room behind a turn it is already running. Stale busy states read
+ * as available, same contract as the status pill.
+ *
+ * Deterministic tie-breaking matters because two replicas can evaluate the
+ * same message (the per-message wake-claim makes it rare, not impossible) and
+ * they must agree without coordinating. Membership order is a SQL artifact, so
+ * it is never trusted: ids sort lexicographically inside each availability
+ * class.
+ */
+
+/** One wake candidate as read from `participants` for this conversation. */
+export interface ElectionCandidate {
+ id: string
+ role: string | null
+ status: string | null
+ /** Fresh `status_updated_at` makes a busy status real; a stale one is expired. */
+ statusUpdatedAt: Date | null
+}
+
+const BUSY_STATUSES = new Set(['thinking', 'working', 'waiting'])
+
+export function isBusyCandidate(c: ElectionCandidate, now: number, leaseMs: number): boolean {
+ if (!c.status || !BUSY_STATUSES.has(c.status)) return false
+ if (!c.statusUpdatedAt) return true
+ return now - c.statusUpdatedAt.getTime() < leaseMs
+}
+
+/** Ordered candidate ids: available first, each class sorted by id. */
+export function orderCandidates(
+ candidates: readonly ElectionCandidate[],
+ opts: { now?: number; leaseMs?: number } = {},
+): string[] {
+ const now = opts.now ?? Date.now()
+ const leaseMs = opts.leaseMs ?? Number.POSITIVE_INFINITY
+ const available: string[] = []
+ const busy: string[] = []
+ for (const c of candidates) {
+ (isBusyCandidate(c, now, leaseMs) ? busy : available).push(c.id)
+ }
+ return [...available.sort(compareIds), ...busy.sort(compareIds)]
+}
+
+function compareIds(a: string, b: string): number {
+ return a < b ? -1 : a > b ? 1 : 0
+}
+
+/** The election result: `lineup[0]` is the elected primary, the rest is the
+ * deterministic fallback order the lease sweep walks when a primary goes
+ * quiet. */
+export interface Election {
+ lineup: string[]
+ primary: string
+}
+
+/** Combine the router's role-fit proposal with the deterministic order:
+ *
+ * - a proposal for an AVAILABLE candidate wins — role fit is the one signal
+ * the router has that code does not;
+ * - no proposal (or a proposal for a non-candidate / mid-turn agent) → the
+ * first available candidate in stable order;
+ * - the whole room busy → the proposal if it is a candidate, else the head of
+ * the order — waking a mid-turn agent queues the message behind its current
+ * turn (and steers it), which still beats no one being woken.
+ *
+ * `null` only when the room is empty — the caller must fan out. */
+export function electLineup(
+ proposal: string | null | undefined,
+ candidates: readonly ElectionCandidate[],
+ opts: { now?: number; leaseMs?: number } = {},
+): Election | null {
+ const ordered = orderCandidates(candidates, opts)
+ if (ordered.length === 0) return null
+ const now = opts.now ?? Date.now()
+ const leaseMs = opts.leaseMs ?? Number.POSITIVE_INFINITY
+ const busy = new Set(
+ candidates.filter((c) => isBusyCandidate(c, now, leaseMs)).map((c) => c.id),
+ )
+ const available = ordered.filter((id) => !busy.has(id))
+ const primary =
+ (proposal && available.includes(proposal) ? proposal : null) ??
+ available[0] ??
+ (proposal && busy.has(proposal) ? proposal : null) ??
+ ordered[0]
+ return { lineup: [primary, ...ordered.filter((id) => id !== primary)], primary }
+}
diff --git a/server/src/agents/routing.ts b/server/src/agents/routing.ts
index 218ef57..e1efb6d 100644
--- a/server/src/agents/routing.ts
+++ b/server/src/agents/routing.ts
@@ -72,11 +72,14 @@ export function buildRouteRequest(args: {
}
/** Parse the router's answer. Anything unexpected — malformed JSON, a mode we
- * don't know, an empty completion — reads as `each`, i.e. change nothing. */
+ * don't know, an empty completion — reads as `each`, i.e. change nothing.
+ * `one-of-us` is recognized but only ever produced for an UNADDRESSED group
+ * message (see buildUnaddressedRouteRequest); the addressed router is still
+ * told to answer `me`|`each` only. */
export function parseRoute(raw: string): ResponseMode {
const match = raw.match(/"responseMode"\s*:\s*"(me|each|one-of-us)"/i)
const mode = match?.[1]?.toLowerCase()
- return mode === 'me' ? 'me' : 'each'
+ return mode === 'me' ? 'me' : mode === 'one-of-us' ? 'one-of-us' : 'each'
}
/** The recipients to actually wake. Separated from the model call so the
@@ -124,3 +127,91 @@ export async function routeMessage(args: {
return 'each'
}
}
+
+/** The unaddressed half of #70: a human group message that names NOBODY. Today
+ * that always fans out to every agent, and production measures ~26% of those
+ * wakes producing nothing — an open question makes everyone reason over the
+ * same room. The router decides between:
+ *
+ * - `each` — the room engages (discussion, opinions, votes, small talk);
+ * - `one-of-us` — one agent should take the turn (a task, a question with a
+ * deliverable), and it may propose WHICH agent by role fit.
+ *
+ * The proposal is only a hint: `pickPrimary` (routing-election.ts) validates it
+ * against real candidates and falls back to a deterministic order, so two
+ * replicas agree without coordinating. */
+export interface UnaddressedRoute {
+ mode: 'each' | 'one-of-us'
+ /** Router's role-fit proposal, when mode is `one-of-us`. Unvalidated. */
+ primary: string | null
+}
+
+export function buildUnaddressedRouteRequest(args: {
+ body: string
+ conversationKind: string
+ /** Wake candidates with their roster role, for the fit signal. */
+ candidates: ReadonlyArray<{ id: string; role: string | null }>
+}): RouteRequest {
+ // A broadcast is for everyone, by definition.
+ if (ALL_MENTION_RE.test(args.body)) return { mode: 'each' }
+ // DMs are handled before the router ever runs (one recipient, human-DM
+ // triage note). Anything odd about the room reads as `each`.
+ if (args.conversationKind === 'direct') return { mode: 'each' }
+ // A room of one agent has nothing to elect among.
+ if (args.candidates.length < 2) return { mode: 'each' }
+
+ return {
+ instructions: [
+ 'You route ONE message in a team chat where some teammates are AI agents.',
+ 'The message does not name anyone. Decide whether the whole room should engage, or whether ONE agent should take it.',
+ 'Answer "one-of-us" when the message is a task, an assignment, or a question with a concrete answer one person can own — and set "primary" to the candidate id whose role fits best.',
+ 'Answer "each" when the room is expected to engage together — discussion, opinions, votes, roll calls, small talk, or anything where several independent replies are wanted.',
+ 'When unsure, answer "each". Waking an extra agent costs tokens; waking no one loses the message.',
+ 'Respond ONLY with a single JSON object: {"responseMode": "each"|"one-of-us", "primary": "<candidate id or null>"}.',
+ ].join('\n'),
+ input: [
+ `Agents in the room: ${args.candidates.map((c) => (c.role ? `${c.id} (${c.role})` : c.id)).join(', ')}`,
+ '',
+ 'Message:',
+ args.body.slice(0, 2000),
+ ].join('\n'),
+ }
+}
+
+/** Parse the unaddressed router's answer. Everything unexpected reads as
+ * `each` — narrowing is the one mistake that is silent, so the bar for it is
+ * an explicit, well-formed `one-of-us`. */
+export function parseUnaddressedRoute(raw: string): UnaddressedRoute {
+ if (!/"responseMode"\s*:\s*"one-of-us"/i.test(raw)) return { mode: 'each', primary: null }
+ const primary = raw.match(/"primary"\s*:\s*"([^"]*)"/i)?.[1]?.trim() || null
+ return { mode: 'one-of-us', primary }
+}
+
+/** Run the unaddressed router on the cloud SMALL model. Fails OPEN to `each`
+ * — today's full fan-out — on any error, exactly like routeMessage. Tracked
+ * under the same `message-routing` purpose so its cost lands next to the
+ * turns it is meant to save. */
+export async function routeUnaddressedMessage(args: {
+ companyId: string | null
+ body: string
+ conversationKind: string
+ candidates: ReadonlyArray<{ id: string; role: string | null }>
+}): Promise<UnaddressedRoute> {
+ const req = buildUnaddressedRouteRequest(args)
+ if (req.mode) return { mode: req.mode as 'each' | 'one-of-us', primary: null }
+ try {
+ const { getTrackedLlmClient } = await import('./llm-ledger.js')
+ const { supportModel } = await import('./model-policy.js')
+ const client = await getTrackedLlmClient({ purpose: 'message-routing', companyId: args.companyId })
+ const r = await client.responses.create({
+ model: supportModel(),
+ instructions: req.instructions,
+ input: req.input ?? '',
+ max_output_tokens: 200,
+ })
+ return parseUnaddressedRoute(r.output_text ?? '')
+ } catch (err) {
+ console.warn(`[routing] router unavailable; waking everyone: ${err instanceof Error ? err.message : String(err)}`)
+ return { mode: 'each', primary: null }
+ }
+}
diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.ts
index 530bcb8..e57e90f 100644
--- a/server/src/agents/scheduler.ts
+++ b/server/src/agents/scheduler.ts
@@ -34,7 +34,10 @@ import { deliver as deliverWake, deliverSteer, type PollWakeBrief } from './runt
import { inprocClient, isAgentBusy } from './runtime/inproc-client.js'
import { classifyInboxTriage, type InboxTriageVerdict } from './inbox-triage.js'
import type { AgentTurnOptions } from './turn.js'
-import { recipientsForRoute, routeMessage } from './routing.js'
+import { recipientsForRoute, routeMessage, routeUnaddressedMessage } from './routing.js'
+import { electLineup, type ElectionCandidate } from './routing-election.js'
+import { claimPrimary, loadElectionCandidates, startRoutingClaimSweeperIfEnabled } from './routing-claims.js'
+import { BUSY_STATUS_LEASE_MS } from '../status.js'
import { Semaphore } from '../concurrency.js'
/** Bounds how many recipients the wake fan-out triages + wakes at once
@@ -799,7 +802,16 @@ async function wake(payload: MessageNewEvent): Promise<void> {
// human-authored group message with a real named subset, and every uncertainty
// (@all, no targets, a model error, an unparseable answer) keeps today's full
// fan-out. See routing.ts.
- if (!authorIsAgent && (conversation?.kind ?? 'group') !== 'direct' && recipients.length > 1) {
+ //
+ // The UNADDRESSED case (names nobody) gets the same treatment when
+ // env.ROUTING_ONE_OF_US is on: the router may elect ONE agent to take the
+ // turn instead of waking the room. The election is bounded by a lease row
+ // (routing-claims.ts) — a primary that never starts a turn is replaced by
+ // the next candidate — and every uncertainty fails open to the fan-out
+ // below. It deliberately does NOT resurrect the daemon-side `claimReply`
+ // that was removed for breaking chains: this happens once per message,
+ // before waking, and the woken agent still runs its own glance/yield.
+ if (!authorIsAgent && (conversation?.kind ?? 'group') !== 'direct' && recipients.length > 1 && messageKind !== 'system' && !deliveryAgentId) {
const targets = [
...mentionedAgentIds(messageBody, recipients),
...(quotedAuthorId && recipients.includes(quotedAuthorId) ? [quotedAuthorId] : []),
@@ -807,7 +819,7 @@ async function wake(payload: MessageNewEvent): Promise<void> {
const uniqueTargets = [...new Set(targets)]
if (uniqueTargets.length > 0) {
const mode = await routeMessage({
- companyId: payload.companyId ?? null,
+ companyId: conversation.company_id,
body: messageBody,
conversationKind: conversation?.kind ?? 'group',
candidates: recipients,
@@ -818,6 +830,41 @@ async function wake(payload: MessageNewEvent): Promise<void> {
console.log(`[scheduler] routed ${conversationId} to ${routed.join(', ')} (mode=${mode}, ${recipients.length - routed.length} wake(s) avoided)`)
}
recipients = routed
+ } else if (env.ROUTING_ONE_OF_US) {
+ const roster = await loadElectionCandidates(recipients).catch(() => [] as ElectionCandidate[])
+ const route = await routeUnaddressedMessage({
+ companyId: conversation.company_id,
+ body: messageBody,
+ conversationKind: conversation?.kind ?? 'group',
+ candidates: roster.map((c) => ({ id: c.id, role: c.role })),
+ })
+ if (route.mode === 'one-of-us') {
+ const election = electLineup(route.primary, roster, { leaseMs: BUSY_STATUS_LEASE_MS })
+ if (election) {
+ // Fail open: if the lease row cannot be written, the no-show sweep
+ // has nothing to advance, so narrowing would be silent-room with no
+ // safety net — keep the full fan-out instead.
+ // An existing row means the message re-delivered after the wake
+ // claim TTL lapsed: honor the recorded primary instead of
+ // re-electing, and skip entirely when the lease already resolved.
+ const claim = await claimPrimary({
+ messageId: payload.message.id,
+ companyId: conversation.company_id,
+ conversationId,
+ orderedCandidates: election.lineup,
+ }).catch(() => null)
+ if (claim?.status === 'served' || claim?.status === 'exhausted') {
+ console.log(`[scheduler] claim for message ${payload.message.id} is already ${claim.status} — skipping wake on re-delivery`)
+ recipients = []
+ } else if (claim?.status === 'pending') {
+ const primary = claim.candidates[claim.cursor]
+ if (primary && recipients.includes(primary)) {
+ console.log(`[scheduler] routed ${conversationId} to ${primary} (mode=one-of-us, ${recipients.length - 1} wake(s) avoided)`)
+ recipients = [primary]
+ }
+ }
+ }
+ }
}
}
@@ -1024,6 +1071,7 @@ export function startScheduler(): void {
}
})
startWakeRetryWorker()
+ startRoutingClaimSweeperIfEnabled()
console.log(`[scheduler] mailbox scheduler listening on ${CH_MESSAGE_NEW}, ${CH_POLLS} · runtime=pod-only`)
}
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index b465316..6134ab4 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -42,6 +42,10 @@ import {
ENGINE_DEFAULTS_SQL,
engineDefaultsChecksum,
} from './migrations/0007-engine-defaults.js'
+import {
+ AGENT_ROUTING_CLAIMS_SQL,
+ agentRoutingClaimsChecksum,
+} from './migrations/0009-agent-routing-claims.js'
/** Frozen data backfill embedded in migration 0001. Exported so its behavior
* can be exercised against PostgreSQL without replaying the whole migration. */
@@ -2551,6 +2555,10 @@ async function applyEngineDefaults(client: import('pg').PoolClient): Promise<voi
await client.query(ENGINE_DEFAULTS_SQL)
}
+async function applyAgentRoutingClaims(client: import('pg').PoolClient): Promise<void> {
+ await client.query(AGENT_ROUTING_CLAIMS_SQL)
+}
+
const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
{
...SCHEMA_MIGRATIONS[0],
@@ -2602,6 +2610,12 @@ const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
transactional: true,
up: async (client) => { await client.query(AGENT_PROVIDER_PROFILE_SQL) },
},
+ {
+ ...SCHEMA_MIGRATIONS[8],
+ sourceChecksum: agentRoutingClaimsChecksum(),
+ transactional: true,
+ up: applyAgentRoutingClaims,
+ },
]
export async function applyPendingMigration(
diff --git a/server/src/db/migrations/0009-agent-routing-claims.ts b/server/src/db/migrations/0009-agent-routing-claims.ts
new file mode 100644
index 0000000..75f1f51
--- /dev/null
+++ b/server/src/db/migrations/0009-agent-routing-claims.ts
@@ -0,0 +1,33 @@
+import { createHash } from 'node:crypto'
+
+/**
+ * Migration 0009: elect one agent for unaddressed human group messages (#123).
+ *
+ * One row per one-of-us ROUTING ELECTION (#70). When a human group message
+ * names nobody and the small-model router elects ONE agent to take the turn
+ * instead of waking the room, this row records who was elected (candidates[0]
+ * is the primary; the rest is the deterministic fallback order) and holds the
+ * lease the sweeper uses to advance to the next candidate when the primary
+ * produces no turn.
+ */
+export const AGENT_ROUTING_CLAIMS_SQL = `
+CREATE TABLE IF NOT EXISTS agent_routing_claims (
+ message_id TEXT PRIMARY KEY,
+ company_id TEXT,
+ conversation_id TEXT NOT NULL,
+ candidates TEXT[] NOT NULL,
+ cursor INTEGER NOT NULL DEFAULT 0,
+ cursor_advanced_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ status TEXT NOT NULL DEFAULT 'pending',
+ lease_expires_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX IF NOT EXISTS idx_agent_routing_claims_sweep
+ ON agent_routing_claims(status, lease_expires_at);
+`
+
+export function agentRoutingClaimsChecksum(): string {
+ return createHash('sha256').update(AGENT_ROUTING_CLAIMS_SQL).digest('hex')
+}
diff --git a/server/src/db/migrations/manifest.ts b/server/src/db/migrations/manifest.ts
index 73e276c..f5e2e0e 100644
--- a/server/src/db/migrations/manifest.ts
+++ b/server/src/db/migrations/manifest.ts
@@ -57,12 +57,17 @@ export const SCHEMA_MIGRATIONS = [
name: '0008_agent_provider_profile',
checksum: '8816423a0ad867d4781c6a9e323e6e34ecadca0ecaf82bd0b9541f164a199fa0',
},
+ {
+ version: 9,
+ name: '0009_agent_routing_claims',
+ checksum: '2bf97e295fef3fa7e42cdc476867e89b4d9c976362dfad7e7256bf74308c30fc',
+ },
] as const satisfies readonly MigrationMetadata[]
/** This build intentionally supports one exact schema range. Expand/contract
* releases may widen the range, but both bounds must remain explicit. */
-export const MIN_SUPPORTED_SCHEMA_VERSION = 8
-export const MAX_SUPPORTED_SCHEMA_VERSION = 8
+export const MIN_SUPPORTED_SCHEMA_VERSION = 9
+export const MAX_SUPPORTED_SCHEMA_VERSION = 9
function assertManifestShape(): void {
for (let i = 0; i < SCHEMA_MIGRATIONS.length; i++) {
diff --git a/server/src/env.ts b/server/src/env.ts
index 393ada7..fa35a51 100644
--- a/server/src/env.ts
+++ b/server/src/env.ts
@@ -96,6 +96,14 @@ export const env = {
* and you need to disable it without a redeploy.
*/
STEER_ENABLED: !/^(false|0|no|off)$/i.test(process.env.STEER_ENABLED ?? ''),
+ /**
+ * The `one-of-us` half of agent routing (#70): when a human group message
+ * names NO agent, the small-model router may elect ONE candidate to take the
+ * turn instead of waking the whole room. Election + lease + fallback live in
+ * agents/routing-election.ts / agents/routing-claims.ts.
+ * Default 'off' (opt-in) — set ROUTING_ONE_OF_US=true to enable.
+ */
+ ROUTING_ONE_OF_US: /^(true|1|yes|on)$/i.test(process.env.ROUTING_ONE_OF_US ?? ''),
/**
* Minimum interval (ms) between alerts that share the same
* (label, error-fingerprint). Defaults to 60s — protects the webhook