Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): align the agent send gate with what inbox pull delivers
Claudette#98731c2c73002b39
diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex e1ed692d5..c2c131d10 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -523,6 +523,67 @@ export async function listUnreadMessagesForAgent(return rows.map(({ lastReadSeq: _lastReadSeq, ...rest }) => rest);}+/**+ * Does `botUserId` have any message in `channelId`, beyond seq `seen`, that+ * `inboxPull` would actually DELIVER — i.e. at/after the bot's join baseline+ * and not its own? This is the send route's alignment gate, sharing+ * `listUnreadMessagesForAgent`'s DELIVERABILITY filters (`channelJoinBaselineGuard`+ * + `authorId != bot`) so the gate and the pull can never drift on which+ * messages "count". The `seen` threshold is the gate's own business: the caller+ * passes `seenUpToSeq ?? lastReadSeq ?? 0`, preserving the daemon's forward-seen+ * boundary (a bot may report it has seen past its acked `lastReadSeq`).+ *+ * Why not `getLatestSeqForScope > seen`: that counts the channel's raw `nextSeq`+ * — including pre-join backlog and the bot's own messages — which the pull's+ * baseline + author filters exclude. A bot @mentioned into a channel/thread with+ * history would then read as permanently "unaligned" (gate sees backlog) while+ * `inboxPull` delivers nothing to advance its `lastReadSeq` — a wedge that only+ * luck (a fresh post-join message) breaks. Gating on the deliverable predicate+ * makes the wedge impossible by construction and needs no read-state migration+ * for already-stuck bots: the gate stops counting messages the pull never hands+ * over.+ *+ * Visibility (channel roster / thread participation) is the caller's job — the+ * send route membership-gates the resolved channel before calling this.+ */+export async function hasDeliverableUnreadForAgentScope(+ db: Database,+ botUserId: string,+ channelId: string,+ seen: number+): Promise<boolean> {+ const rows = await db+ .select({ seq: communityMessage.seq })+ .from(communityMessage)+ .leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .leftJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityMessage.channelId),+ eq(communityChannelMember.userId, botUserId),+ eq(communityChannelMember.relation, "access")+ )+ )+ .leftJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.userId, botUserId)+ )+ )+ .where(+ and(+ eq(communityMessage.channelId, channelId),+ ne(communityMessage.authorId, botUserId),+ gt(communityMessage.seq, seen),+ channelJoinBaselineGuard+ )+ )+ .limit(1);++ return rows.length > 0;+}+export type InboxSnapshotRow = {channelId: string;pendingCount: number;diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex e3fc65f36..30f9a0946 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -811,3 +811,24 @@ describe("listMessagesBySeq", () => {expect(chainResult.limit).toHaveBeenCalledWith(201);});});++describe("hasDeliverableUnreadForAgentScope", () => {+ it("returns true when a deliverable message beyond `seen` exists", async () => {+ const db = createSequentialDb([[{ seq: 7 }]]);+ const result = await agentInbox.hasDeliverableUnreadForAgentScope(db, "bot_1", "c1", 3);+ expect(result).toBe(true);+ });++ it("returns false when nothing is deliverable beyond `seen` (pre-join backlog / own / already read)", async () => {+ const db = createSequentialDb([[]]);+ const result = await agentInbox.hasDeliverableUnreadForAgentScope(db, "bot_1", "c1", 0);+ expect(result).toBe(false);+ });++ it("probes with limit(1) — existence check, not a full scan", async () => {+ const db = createSequentialDb([[]]);+ await agentInbox.hasDeliverableUnreadForAgentScope(db, "bot_1", "c1", 0);+ const chainResult = db.select.mock.results[0]!.value;+ expect(chainResult.limit).toHaveBeenCalledWith(1);+ });+});diff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.tsindex 4c3e9b118..cd0c46ab0 100644--- a/src/web/src/app/api/community/agent/send/route.test.ts+++ b/src/web/src/app/api/community/agent/send/route.test.ts@@ -21,6 +21,7 @@ const mockCreateOrGetDM = vi.fn()const mockIsBlocked = vi.fn()const mockAreFriends = vi.fn()const mockGetLatestSeqForScope = vi.fn()+const mockHasDeliverableUnread = vi.fn()const mockGetReadState = vi.fn()const mockToAgentMessage = vi.fn()const mockGetMessageByChannelAndSeq = vi.fn()@@ -58,6 +59,7 @@ vi.mock("@alook/shared", async () => {},communityAgentInbox: {getLatestSeqForScope: (...a: unknown[]) => mockGetLatestSeqForScope(...a),+ hasDeliverableUnreadForAgentScope: (...a: unknown[]) => mockHasDeliverableUnread(...a),toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a),},communityReadState: { getReadState: (...a: unknown[]) => mockGetReadState(...a) },@@ -95,6 +97,11 @@ describe("POST /api/community/agent/send", () => {mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })mockGetLatestSeqForScope.mockResolvedValue(0)+ // Default aligned (no deliverable unread) — matches the beforeEach+ // latest=0. Tests asserting `blocked/unaligned` set this true explicitly;+ // the wedge test sets it false while latest>seen to prove the gate no+ // longer blocks on undeliverable backlog.+ mockHasDeliverableUnread.mockResolvedValue(false)mockGetReadState.mockResolvedValue(null)mockToAgentMessage.mockImplementation((_db: unknown, row: unknown) => Promise.resolve({ ...row as object, wireShaped: true }))mockGetMessageByChannelAndSeq.mockResolvedValue(null)@@ -124,6 +131,7 @@ describe("POST /api/community/agent/send", () => {it("returns { state: blocked, reason: unaligned } when the bot is behind the channel's latest seq and hasn't caught up", async () => {mockGetLatestSeqForScope.mockResolvedValue(10)mockGetReadState.mockResolvedValue({ lastReadSeq: 4 })+ mockHasDeliverableUnread.mockResolvedValue(true)const res = await POST(req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" }))@@ -132,6 +140,23 @@ describe("POST /api/community/agent/send", () => {expect(mockCreateCommunityMessage).not.toHaveBeenCalled()})+ it("late-joiner wedge: latestSeq is ahead of `seen` (pre-join backlog) but NO deliverable unread → send is NOT blocked", async () => {+ // The @-mentioned-into-a-thread-with-backlog case. Raw seq gate would+ // block forever (latestSeq 20 > seen 0) while inboxPull delivers nothing+ // to advance the waterline. Gating on deliverable-unread lets the send+ // through — the backlog is behind the join baseline, so it doesn't count.+ mockGetLatestSeqForScope.mockResolvedValue(20)+ mockGetReadState.mockResolvedValue(null) // fresh member, lastReadSeq → 0+ mockHasDeliverableUnread.mockResolvedValue(false)+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 21, content: "hi" } })+ const res = await POST(+ req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(res.status).toBe(200)+ expect((await res.json()).state).toBe("sent")+ expect(mockCreateCommunityMessage).toHaveBeenCalled()+ })+it("propagates a CAS 409 conflict from createCommunityMessage as blocked/unaligned with a freshly re-fetched latestSeq", async () => {// Alignment gate passes (latestSeq=9, seen=9), but another agent's send// wins the race between the gate and the CAS claim — by the time this@@ -307,9 +332,11 @@ describe("POST /api/community/agent/send", () => {})it("sequential scenario: blocked/unaligned → pull+ack (simulated by an advancing lastReadSeq) → send succeeds → a new message arrives → send blocks again", async () => {- // 1. Bot is behind: latestSeq=10, bot's own tracked lastReadSeq=4 → blocked.+ // 1. Bot is behind: latestSeq=10, bot's own tracked lastReadSeq=4 → blocked+ // (deliverable unread exists).mockGetLatestSeqForScope.mockResolvedValueOnce(10)mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 4 })+ mockHasDeliverableUnread.mockResolvedValueOnce(true)const blocked1 = await POST(req({ channel: "/studio/general", content: { text: "catching up" } }, { Authorization: "Bearer crk_abc" }))@@ -336,6 +363,7 @@ describe("POST /api/community/agent/send", () => {// again without a fresh pull+ack.mockGetLatestSeqForScope.mockResolvedValueOnce(12)mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 10 })+ mockHasDeliverableUnread.mockResolvedValueOnce(true)const blocked2 = await POST(req({ channel: "/studio/general", content: { text: "still going" } }, { Authorization: "Bearer crk_abc" }))diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.tsindex d928d8832..28265fc19 100644--- a/src/web/src/app/api/community/agent/send/route.ts+++ b/src/web/src/app/api/community/agent/send/route.ts@@ -48,16 +48,31 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {// server is the source of truth for the "seen" waterline: a client that// omits `seenUpToSeq` is checked against its OWN tracked `lastReadSeq`,// never allowed to skip the gate by simply not sending the field.+ //+ // "Unaligned" means the bot has an unread message it could actually PULL —+ // so the gate shares `inboxPull`'s deliverability predicate (join baseline ++ // not-own) via `hasDeliverableUnreadForAgentScope`, NOT the raw channel+ // `nextSeq`. A late joiner (@mentioned into a channel/thread with backlog)+ // has pre-join messages the pull will never deliver; gating on `nextSeq`+ // would block it forever while the pull hands over nothing to advance its+ // `lastReadSeq` — a permanent wedge. `latestSeq` is still fetched: it feeds+ // the optimistic `expectedSeq` claim below and the `blocked` response shape.const [latestSeq, readState] = await Promise.all([queries.communityAgentInbox.getLatestSeqForScope(db, resolved.channelId),queries.communityReadState.getReadState(db, { userId: ctx.botUserId, ...scopeTarget }),])const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0- if (latestSeq > seen) {+ const hasUnread = await queries.communityAgentInbox.hasDeliverableUnreadForAgentScope(+ db,+ ctx.botUserId,+ resolved.channelId,+ seen,+ )+ if (hasUnread) {return NextResponse.json({state: "blocked",reason: "unaligned",- unreadCount: latestSeq - seen,+ unreadCount: Math.max(0, latestSeq - seen),latestSeq,})}