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
feat(community): agent unread visibility unify + wake audit hardening
Gusf8b0e107724b
diff --git a/src/daemon/package.json b/src/daemon/package.jsonindex 6ff74afd8..f23f8e570 100644--- a/src/daemon/package.json+++ b/src/daemon/package.json@@ -37,6 +37,7 @@},"scripts": {"build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external ws && bun build src/cli/index.ts --outdir dist/cli --target node --format esm --external commander --external ws && node scripts/prepare-dist.mjs",+ "prepack": "pnpm run build","typecheck": "tsc --noEmit","test": "vitest run","test:watch": "vitest",diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex 75ec38c83..29cc2da75 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -143,6 +143,54 @@ describe("inbox pull", () => {expect(ackSpy).not.toHaveBeenCalled();expect(env.success.acked).toBe(0);});++ it("surfaces ackError instead of poisoning the whole pull when ack throws", async () => {+ // Regression guard for Mellicent's dead-loop: ack failing on ONE cursor+ // used to collapse the whole envelope to `{"error":"forbidden"}`, wiping+ // the messages the agent needed to see. The pull envelope must retain+ // its messages AND report `ackError` distinctly.+ const ackSpy = vi.fn(async () => {+ throw new Error("forbidden");+ });+ setApiForTesting(+ stubApi({+ inboxPull: async () => ({+ messages: [+ { seq: "#2", channel: "/s/general", sender: "@x", content: { text: "hi" }, time: "" },+ { seq: "#3", channel: "/s/general", sender: "@x", content: { text: "bye" }, time: "" },+ ],+ hasMore: false,+ }),+ ack: ackSpy,+ }),+ );+ await main(["inbox", "pull"]);+ const env = parseEnvelope(cap.lines()) as {+ success: { acked: number; messages: unknown[]; ackError?: string };+ };+ expect(ackSpy).toHaveBeenCalledOnce();+ expect(env.success.messages).toHaveLength(2);+ expect(env.success.acked).toBe(0);+ expect(env.success.ackError).toBe("forbidden");+ });++ it("does NOT include ackError when the ack succeeds", async () => {+ setApiForTesting(+ stubApi({+ inboxPull: async () => ({+ messages: [{ seq: "#2", channel: "/s/general", sender: "@x", content: { text: "yo" }, time: "" }],+ hasMore: false,+ }),+ ack: async () => undefined,+ }),+ );+ await main(["inbox", "pull"]);+ const env = parseEnvelope(cap.lines()) as {+ success: { acked: number; ackError?: string };+ };+ expect(env.success.acked).toBe(1);+ expect(env.success.ackError).toBeUndefined();+ });});describe("server list", () => {@@ -616,3 +664,17 @@ describe("channel subscribe removed", () => {expect(env.error).toContain("unknown command");});});++describe("import side effects", () => {+ it("importing ./index does not invoke main() — guard evaluates false under vitest", async () => {+ const commander = await import("commander");+ const parseSpy = vi.spyOn(commander.Command.prototype, "parseAsync");+ vi.resetModules();+ try {+ await import("./index");+ expect(parseSpy).not.toHaveBeenCalled();+ } finally {+ parseSpy.mockRestore();+ }+ });+});diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 063f43b0c..e0b8754ac 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -15,6 +15,8 @@* the sole result channel.*/import { Command, CommanderError } from "commander";+import { realpathSync } from "node:fs";+import { pathToFileURL } from "node:url";import type { ServerApi, Cursor, Message } from "../server/contract.js";import { parseRef } from "../server/contract.js";import { proxyServerApiFromEnv } from "./proxyServerApi.js";@@ -267,6 +269,7 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {const pulledAt = nowLocalISO();let acked = 0;+ let ackError: string | undefined;if (opts.ack !== false && messages.length > 0) {const latest = new Map<string, Cursor>();for (const m of messages) {@@ -274,11 +277,27 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {const cur = latest.get(m.channel);if (!cur || seqN > cur.seq) latest.set(m.channel, { channel: m.channel, seq: seqN });}- await api.ack({ agentId: agent, cursors: [...latest.values()] });- acked = latest.size;+ try {+ await api.ack({ agentId: agent, cursors: [...latest.values()] });+ acked = latest.size;+ } catch (err) {+ // Do NOT rethrow: the pull already succeeded, and if ack fails on a+ // single scope (e.g. a stale visibility mismatch) the whole envelope+ // would otherwise collapse to a bare error, wiping the messages the+ // agent needs. Surface the ack failure separately so the agent (or a+ // human debugging) sees BOTH the delivered messages AND that the+ // waterline didn't move.+ ackError = err instanceof Error ? err.message : String(err);+ }}- return { messages: messagesInLocalTime(messages), hasMore, acked, pulledAt };+ return {+ messages: messagesInLocalTime(messages),+ hasMore,+ acked,+ pulledAt,+ ...(ackError ? { ackError } : {}),+ };}async function cmdServerList(opts: Record<string, unknown>): Promise<unknown> {@@ -620,13 +639,17 @@ function getHelpText(program: Command, argv: string[]): string {return cmd.helpInformation();}-// Run when invoked directly (not when imported via test/vitest).-const invokedDirectly =- typeof process !== "undefined" &&- process.argv[1] &&- /(?:^|[\\/])(?:cli[\\/]index\.[jt]s|alook)$/.test(process.argv[1]) &&- !process.argv[1].includes("vitest") &&- !process.argv[1].includes("node_modules");-if (invokedDirectly) {+let isMainModule = false;+try {+ if (typeof process !== "undefined" && process.argv[1]) {+ isMainModule =+ import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;+ }+} catch {+ // Any realpath failure (argv[1] not a real file — worker threads, `node --eval`,+ // exotic sandboxes; or EACCES/EIO/ELOOP on a real path) falls through to not-main.+}++if (isMainModule) {main().then((code) => process.exit(code));}diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 15033758d..6b38b5ff6 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -611,7 +611,18 @@ export type AgentActivityState = "idle" | "starting" | "running" | "stopping";export type BotAuditEventPayload =| { kind: "cli_invocation"; payload: { subcommand: string } }| { kind: "tool_call"; payload: { name: string; target?: string } }- | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } };+ | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }+ | {+ kind: "wake_trigger";+ payload: {+ messageId: string;+ channel: ChannelRef;+ seq: Seq;+ senderId: string;+ senderHandle: string;+ reason: "unread" | "mention";+ };+ };export interface HostBotAuditEventFrame {type: "bot_audit_event";diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 2b3a57a45..d330e89be 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -7,6 +7,9 @@ import * as bot from "../db/queries/community/bot";import * as member from "../db/queries/community/member";import * as readState from "../db/queries/community/read-state";import * as agentInbox from "../db/queries/community/agent-inbox";+import * as mention from "../db/queries/community/mention";+import * as botAuditLog from "../db/queries/community/bot-audit-log";+import { getUsersByIds } from "../db/queries/user";import type { Database } from "../db/index";/**@@ -21,6 +24,10 @@ interface FetcherLike {fetch(input: string, init?: RequestInit): Promise<Response>;}+interface WakeDispatchEnv {+ WS_DO_WORKER: FetcherLike;+}+/*** One `WAKE_QUEUE` message — deliberately minimal (plan* minimal-wake-queue-unread-notice §1): just enough to rebuild the wake@@ -110,10 +117,17 @@ export type BuildUnreadWakeResult =* Every `skip` reason here is a PERMANENT current-state miss — the caller* `ack()`s the queue message. D1 exceptions propagate (thrown, not* returned) so the caller can `retry()` instead.+ *+ * When `env` is provided, also writes a `wake_trigger` audit row and asks+ * ws-do to fan the resulting `community:bot.audit_event` frame to the+ * owner's WS — both best-effort (wrapped in try/catch, MUST NOT block or+ * fail the wake). Callers that don't run in a Workers env (unit tests+ * exercising just the command-building) may omit `env`.*/export async function buildUnreadWakeCommand(db: Database,- input: { messageId: string; botUserId: string }+ input: { messageId: string; botUserId: string },+ env?: WakeDispatchEnv): Promise<BuildUnreadWakeResult> {const msg = await message.getWakeMessageScopeById(db, input.messageId);if (!msg) return { state: "skip", reason: "message_missing" };@@ -160,9 +174,104 @@ export async function buildUnreadWakeCommand(launchId: nanoid(),unreadNotice,};++ // Audit trail (best-effort) — commit that this wake fired for a specific+ // trigger message. MUST NOT block or fail the wake: on retry (D1 blip) a+ // second row is preferable to a silently-lost wake. See "Audit write+ // failure policy" in plans/agent-unread-visibility-unify.md.+ try {+ await writeWakeTriggerAudit(db, env, {+ botUserId: input.botUserId,+ ownerUserId: botCtx.ownerUserId,+ launchId: command.launchId,+ messageId: msg.id,+ channel,+ seq: msg.seq,+ authorId: msg.authorId,+ });+ } catch (err) {+ // eslint-disable-next-line no-console+ console.warn("wake_trigger_audit_failed", {+ botUserId: input.botUserId,+ messageId: msg.id,+ err: String(err),+ });+ }+return { state: "ready", machineId: botCtx.machineId, command };}+async function writeWakeTriggerAudit(+ db: Database,+ env: WakeDispatchEnv | undefined,+ input: {+ botUserId: string;+ ownerUserId: string | null;+ launchId: string;+ messageId: string;+ channel: string;+ seq: number;+ authorId: string;+ }+): Promise<void> {+ // Owner is already known from `getBotWakeContext` — no second D1 hit.+ // Resolve sender handle in parallel with the mention check. Every lookup is+ // best-effort — a missing sender / D1 exception short-circuits the audit+ // write and MUST NOT surface as a wake failure. `allSettled` (not `all`) so+ // one rejected leg can't unhandled-reject the parallel legs before the+ // outer catch reaches them.+ if (!input.ownerUserId) return;+ const [senderRes, mentionRes] = await Promise.allSettled([+ getUsersByIds(db, [input.authorId]),+ mention.hasMentionForMessage(db, input.messageId, input.botUserId),+ ]);+ if (senderRes.status !== "fulfilled") return;+ const sender = senderRes.value[0];+ const isMention = mentionRes.status === "fulfilled" ? mentionRes.value : false;+ if (!sender) return;++ const payload = {+ messageId: input.messageId,+ channel: input.channel,+ seq: input.seq,+ senderId: input.authorId,+ senderHandle: `@${formatHandle(sender.name, sender.discriminator)}`,+ reason: (isMention ? "mention" : "unread") as "unread" | "mention",+ };+ const inserted = await botAuditLog.insertBotAuditWakeTrigger(db, {+ botId: input.botUserId,+ launchId: input.launchId,+ payload,+ });+ if (!inserted || !env) return;++ // ws-do live broadcast — best-effort, must not block the wake. `catch`+ // swallows any transport failure; owner still sees the row on next UI+ // refresh via the D1 row that already landed above.+ try {+ await env.WS_DO_WORKER.fetch("http://internal/internal/broadcast-bot-audit-event", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ botId: input.botUserId,+ ownerUserId: input.ownerUserId,+ id: inserted.id,+ kind: "wake_trigger",+ payload,+ createdAt: inserted.createdAt,+ launchId: input.launchId,+ }),+ });+ } catch (err) {+ // eslint-disable-next-line no-console+ console.warn("wake_trigger_broadcast_failed", {+ botUserId: input.botUserId,+ messageId: input.messageId,+ err: String(err),+ });+ }+}+/** Outcome of resolving ONE wake candidate — what every caller (the real queue consumer, and the dev-only inline stand-in) needs to decide what to log. */export type DispatchOneWakeResult =| { outcome: "skip"; reason: SkipReason }@@ -186,7 +295,7 @@ export async function dispatchOneUnreadWake(env: { WS_DO_WORKER: FetcherLike },input: { messageId: string; botUserId: string }): Promise<DispatchOneWakeResult> {- const result = await buildUnreadWakeCommand(db, input);+ const result = await buildUnreadWakeCommand(db, input, env);if (result.state === "skip") return { outcome: "skip", reason: result.reason };const { sent } = await sendWakeToMachine(env, result.machineId, result.command);return sent ? { outcome: "sent" } : { outcome: "delivered_nowhere", machineId: result.machineId };diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex 6ece6b760..d59588a69 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -17,7 +17,6 @@ import {communityServer,communityReadState,communityMessageSeq,- communityServerMember,} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -31,6 +30,9 @@ import {type ChannelRef,} from "../../../community-cli-contract";import { formatHandle } from "../../../lib/discriminator";+import { listVisibleChannelIdsForUser } from "./channel";+import { listParticipatingThreadIds } from "./thread";+import { isThread, isForumPost } from "../../../utils/community-roles";type RawAgentMessage = {id: string;@@ -329,31 +331,64 @@ export async function getLatestSeqForScope(db: Database, scopeKey: string): Promreturn rows[0]?.nextSeq ?? 0;}+/**+ * Effective allowed channel-id set for a bot: visible channels MINUS+ * thread/forum_post channels the bot isn't a participant of. Pushes the+ * thread-participation narrowing into a pre-computed set so it can join the+ * message SQL as a single `inArray` predicate — the old shape did the+ * narrowing as a JS post-filter AFTER `.limit(max)`, which silently+ * collapsed a page of non-participating rows to `[]` (breaking `hasMore` in+ * `inboxPull`) and could return `null` from `getLatestUnreadMessageForAgent`+ * when older participating unread existed outside the top-N-by-createdAt+ * candidate window.+ */+async function listAgentAllowedChannelIds(db: Database, botUserId: string): Promise<string[]> {+ const visibleChannelIds = await listVisibleChannelIdsForUser(db, botUserId);+ if (visibleChannelIds.length === 0) return [];+ const typeRows = await db+ .select({ id: communityChannel.id, type: communityChannel.type })+ .from(communityChannel)+ .where(inArray(communityChannel.id, visibleChannelIds));+ const narrowIds = typeRows+ .filter((r) => isThread(r.type) || isForumPost(r.type))+ .map((r) => r.id);+ const participating =+ narrowIds.length > 0+ ? new Set(await listParticipatingThreadIds(db, narrowIds, botUserId))+ : new Set<string>();+ const narrowSet = new Set(narrowIds);+ return visibleChannelIds.filter((id) => !narrowSet.has(id) || participating.has(id));+}+/*** Cross-channel unread fill for `inboxPull`, grouped by channel/DM (not* global seq order — `seq` is a per-scope counter, comparing raw values* across scopes is meaningless, see plan §7 v4). Always drains one channel's* unread completely (in seq order) before starting the next. Excludes the- * bot's own authored messages. Never mutates- * read state. Scope checks happen in SQL before returning rows: channel- * messages require server membership, and DM messages require participation.+ * bot's own authored messages. Never mutates read state.+ *+ * Visibility rule: same as the human unread path (`listUnreadChannels`) —+ * (1) channel messages restricted to `listVisibleChannelIdsForUser(botUserId)`+ * (respects private-category rosters and private-forum-post narrowness), and+ * (2) thread / forum_post channels additionally require a+ * `community_thread_participant` row for the bot. Both dimensions are folded+ * into ONE `inArray` predicate up front so `.limit(max)` operates on+ * already-visible rows — post-filtering after `limit` (the earlier shape)+ * could silently collapse a page to `[]` and break `hasMore`.*/export async function listUnreadMessagesForAgent(db: Database,botUserId: string,opts: { max: number }): Promise<RawAgentMessage[]> {+ const allowedChannelIds = await listAgentAllowedChannelIds(db, botUserId);+const rows = await db.select({...AGENT_MESSAGE_COLUMNS,lastReadSeq: sql<number>`COALESCE(${communityReadState.lastReadSeq}, 0)`,}).from(communityMessage)- .leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))- .leftJoin(- communityServerMember,- and(eq(communityServerMember.serverId, communityChannel.serverId), eq(communityServerMember.userId, botUserId))- ).leftJoin(communityDmConversation, eq(communityDmConversation.id, communityMessage.dmConversationId)).leftJoin(communityReadState,@@ -370,7 +405,12 @@ export async function listUnreadMessagesForAgent(ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,or(- and(isNotNull(communityMessage.channelId), eq(communityServerMember.userId, botUserId)),+ and(+ isNotNull(communityMessage.channelId),+ allowedChannelIds.length > 0+ ? inArray(communityMessage.channelId, allowedChannelIds)+ : sql`1 = 0`+ ),and(isNotNull(communityMessage.dmConversationId),or(eq(communityDmConversation.user1Id, botUserId), eq(communityDmConversation.user2Id, botUserId))@@ -396,12 +436,21 @@ export type InboxSnapshotRow = {/*** Per-channel/DM unread summary for `inboxSnapshot` — non-consuming, no read-- * state mutation. One row per scope with pending unread. Scope checks happen- * in SQL before aggregation. `hasMention` powers- * the `InboxRow.flags` "mention" flag: true iff any of the scope's PENDING- * (still-unread) messages carries a `kind: "mention"` row for this bot.+ * state mutation. One row per scope with pending unread.+ *+ * Visibility rule mirrors `listUnreadMessagesForAgent`: (1) channel scopes+ * restricted to `listVisibleChannelIdsForUser(botUserId)`, and (2) scopes of+ * type `thread` or `forum_post` additionally require a+ * `community_thread_participant` row for the bot (post-filter). Because the+ * outer `WHERE` is `inArray(channelId, visibleChannelIds)` and non-participated+ * thread rows are dropped in the post-filter, `hasMention` (a correlated+ * sub-select keyed on the surviving row's `channel_id`) can never inherit a+ * mention from an invisible or non-participated thread — do NOT try to+ * sub-select mentions independently or the leak reopens on this axis.*/export async function getInboxSnapshotForAgent(db: Database, botUserId: string): Promise<InboxSnapshotRow[]> {+ const allowedChannelIds = await listAgentAllowedChannelIds(db, botUserId);+const rows = await db.select({channelId: communityMessage.channelId,@@ -419,11 +468,6 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):AND m3.seq > COALESCE(${communityReadState.lastReadSeq}, 0))`,}).from(communityMessage)- .leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))- .leftJoin(- communityServerMember,- and(eq(communityServerMember.serverId, communityChannel.serverId), eq(communityServerMember.userId, botUserId))- ).leftJoin(communityDmConversation, eq(communityDmConversation.id, communityMessage.dmConversationId)).leftJoin(communityReadState,@@ -440,7 +484,12 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,or(- and(isNotNull(communityMessage.channelId), eq(communityServerMember.userId, botUserId)),+ and(+ isNotNull(communityMessage.channelId),+ allowedChannelIds.length > 0+ ? inArray(communityMessage.channelId, allowedChannelIds)+ : sql`1 = 0`+ ),and(isNotNull(communityMessage.dmConversationId),or(eq(communityDmConversation.user1Id, botUserId), eq(communityDmConversation.user2Id, botUserId))@@ -452,7 +501,9 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):if (rows.length === 0) return [];- const senderIds = [...new Set(rows.map((r) => r.latestSenderId).filter(Boolean))];+ const filtered = rows;++ const senderIds = [...new Set(filtered.map((r) => r.latestSenderId).filter(Boolean))];const users = senderIds.length? await db.select({ id: user.id, name: user.name, discriminator: user.discriminator })@@ -461,7 +512,7 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):: [];const userById = new Map(users.map((u) => [u.id, u]));- return rows.map((r) => {+ return filtered.map((r) => {const sender = userById.get(r.latestSenderId);return {channelId: r.channelId,@@ -520,22 +571,27 @@ export async function toInboxRows(* `getInboxSnapshotForAgent`'s per-scope aggregation, which has no single* message id to hand back). "Most recent" is by `createdAt`, since `seq` is a* per-scope counter and isn't comparable across scopes (see- * `listUnreadMessagesForAgent`'s doc comment). Same scope/membership/- * exclude-self-authored predicates as `listUnreadMessagesForAgent`. Returns- * `null` when the bot has no unread anywhere.+ * `listUnreadMessagesForAgent`'s doc comment).+ *+ * Visibility rule identical to `listUnreadMessagesForAgent`: the bot must be+ * able to see the channel (`listVisibleChannelIdsForUser`) AND, for thread /+ * forum_post scopes, hold a `community_thread_participant` row. Both+ * dimensions are folded into the SQL WHERE via `listAgentAllowedChannelIds`+ * so `LIMIT 1` returns the newest allowed row directly — an earlier shape+ * used a bounded post-filter window that could return `null` when older+ * allowed unread existed outside the top-N-by-createdAt slice.*/export async function getLatestUnreadMessageForAgent(db: Database,botUserId: string): Promise<{ messageId: string } | null> {+ const allowedChannelIds = await listAgentAllowedChannelIds(db, botUserId);+const rows = await db- .select({ id: communityMessage.id })+ .select({+ id: communityMessage.id,+ }).from(communityMessage)- .leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))- .leftJoin(- communityServerMember,- and(eq(communityServerMember.serverId, communityChannel.serverId), eq(communityServerMember.userId, botUserId))- ).leftJoin(communityDmConversation, eq(communityDmConversation.id, communityMessage.dmConversationId)).leftJoin(communityReadState,@@ -552,7 +608,12 @@ export async function getLatestUnreadMessageForAgent(ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,or(- and(isNotNull(communityMessage.channelId), eq(communityServerMember.userId, botUserId)),+ and(+ isNotNull(communityMessage.channelId),+ allowedChannelIds.length > 0+ ? inArray(communityMessage.channelId, allowedChannelIds)+ : sql`1 = 0`+ ),and(isNotNull(communityMessage.dmConversationId),or(eq(communityDmConversation.user1Id, botUserId), eq(communityDmConversation.user2Id, botUserId))@@ -563,7 +624,8 @@ export async function getLatestUnreadMessageForAgent(.orderBy(desc(communityMessage.createdAt)).limit(1);- return rows[0] ? { messageId: rows[0].id } : null;+ const r = rows[0];+ return r ? { messageId: r.id } : null;}/**diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.tsindex ee861a286..8d32b57c5 100644--- a/src/shared/src/db/queries/community/bot-audit-log.ts+++ b/src/shared/src/db/queries/community/bot-audit-log.ts@@ -30,10 +30,24 @@ export type BotActivityEventInput = {botId: string;sessionId?: string | null;launchId?: string | null;- kind: "cli_invocation" | "tool_call" | "thinking";+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger";payload: string;};+/**+ * Typed payload for a `wake_trigger` audit row (matches+ * `AuditLogWakeTriggerPayloadSchema` in schemas.ts). Frozen at wake time —+ * a subsequent rename does NOT rewrite past rows.+ */+export type WakeTriggerPayload = {+ messageId: string;+ channel: string;+ seq: number;+ senderId: string;+ senderHandle: string;+ reason: "unread" | "mention";+};+/*** Insert + retention prune in a single D1 batch. This is the writer ws-do* calls on every inbound `bot_audit_event` frame. Returns the inserted row@@ -157,3 +171,30 @@ export async function listBotActivityEvents(return rows;}++/**+ * Wake-trigger audit write — thin wrapper around+ * `insertBotActivityEventAndPrune` for the wake-worker's write path+ * (`buildUnreadWakeCommand`). Serializes the typed `WakeTriggerPayload` into+ * the existing opaque `payload` text column and runs the same rolling-500+ * prune atomically. Distinct entry point so wake-worker callers can't+ * accidentally construct a shape that fails `BotAuditEventSchema` at read+ * time.+ */+export async function insertBotAuditWakeTrigger(+ db: Database,+ data: {+ botId: string;+ sessionId?: string | null;+ launchId?: string | null;+ payload: WakeTriggerPayload;+ }+): Promise<{ id: string; createdAt: string } | null> {+ return insertBotActivityEventAndPrune(db, {+ botId: data.botId,+ sessionId: data.sessionId ?? null,+ launchId: data.launchId ?? null,+ kind: "wake_trigger",+ payload: JSON.stringify(data.payload),+ });+}diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex ed4af8828..a9ecc5757 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -292,7 +292,15 @@ export type BotWakeContext =| { state: "bot_missing" }| { state: "bot_deleted" }| { state: "bot_unbound" }- | { state: "ready"; botUserId: string; name: string; discriminator: string; machineId: string; runtime: string };+ | {+ state: "ready";+ botUserId: string;+ name: string;+ discriminator: string;+ machineId: string;+ runtime: string;+ ownerUserId: string | null;+ };export async function getBotWakeContext(db: Database, botUserId: string): Promise<BotWakeContext> {const rows = await db@@ -302,6 +310,7 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promisdiscriminator: user.discriminator,isBot: user.isBot,deletedAt: user.deletedAt,+ ownerUserId: user.ownerUserId,machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,})@@ -320,6 +329,7 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promisdiscriminator: r.discriminator,machineId: r.machineId,runtime: r.runtime,+ ownerUserId: r.ownerUserId,};}diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 9b21aae94..62d79a997 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -7,8 +7,9 @@ import {MAX_MEMBERS_PAGE_SIZE,} from "../../../constants/community";import { escapeLikePattern } from "../../../utils/sql-like";-import { canSeePrivateChannel } from "../../../utils/community-roles";+import { canSeePrivateChannel, isThread, isForumPost } from "../../../utils/community-roles";import { resolveChannelAccessContext } from "./channel";+import { isThreadParticipant } from "./thread";export async function addMember(db: Database,@@ -429,12 +430,17 @@ export async function removeOwnerBotsFromServer(* revoked, DM peer changed); this must return false rather than let the* caller wake a bot that lost access to the scope.*+ * The gate applies BOTH visibility AND notification-set semantics: a public+ * forum_post is technically READABLE by any server member, but wakes only+ * fire for its `community_thread_participant` set — same rule the human+ * inbox uses (`listUnreadChannels`, `inbox.ts:123-143`). Without the+ * participation gate a bogus source query could still leak a wake for a+ * public-forum message the bot never touched (Mellicent's exact bug).+ ** A channel in a PRIVATE category is only readable by the bot if it's the* channel creator or has a `community_channel_member` row (server admins too);- * public/uncategorized channels need only server membership. Thread scopes are- * ordinary `communityChannel` rows that inherit their parent's audience — the- * shared `resolveChannelAccessContext` predicate climbs `parentChannelId`, so- * this delegates to it rather than re-deriving the rule.+ * public/uncategorized channels need only server membership. Thread/forum_post+ * scopes must additionally hold a participant row on top of the access check.*/export async function canBotReadWakeScope(db: Database,@@ -444,13 +450,21 @@ export async function canBotReadWakeScope(if (scope.channelId) {const ctx = await resolveChannelAccessContext(db, scope.channelId, botUserId);if (!ctx) return false;- if (!ctx.isPrivate) return true;- return canSeePrivateChannel({+ const accessible = !ctx.isPrivate || canSeePrivateChannel({role: ctx.role,- // Roster-anchor creator (post's own creator for a post), from the context.isCreator: ctx.isCreator,isChannelMember: ctx.isChannelMember,});+ if (!accessible) return false;++ // Notification-set narrowing — thread + forum_post scopes only notify+ // their participants (mirrors the human inbox's post-visibility filter).+ // Bots are just users; participant rows are added the same way (spoke /+ // mention / added), so the same predicate applies verbatim.+ if (isThread(ctx.channel.type) || isForumPost(ctx.channel.type)) {+ return isThreadParticipant(db, scope.channelId, botUserId);+ }+ return true;}if (scope.dmConversationId) {const rows = await dbdiff --git a/src/shared/src/db/queries/community/mention.ts b/src/shared/src/db/queries/community/mention.tsindex 8a93c462f..8c909a131 100644--- a/src/shared/src/db/queries/community/mention.ts+++ b/src/shared/src/db/queries/community/mention.ts@@ -143,6 +143,30 @@ export function markChannelMentionsReadBuilder(.where(inArray(communityMention.id, matchingMentionIds));}+/**+ * True when the given user is `@`-mentioned on the given message (`kind =+ * "mention"`). Used by wake_trigger audit rows to record `reason: "mention"`+ * vs the default `"unread"`.+ */+export async function hasMentionForMessage(+ db: Database,+ messageId: string,+ userId: string+): Promise<boolean> {+ const rows = await db+ .select({ id: communityMention.id })+ .from(communityMention)+ .where(+ and(+ eq(communityMention.messageId, messageId),+ eq(communityMention.userId, userId),+ eq(communityMention.kind, "mention")+ )+ )+ .limit(1);+ return rows.length > 0;+}+export async function deleteMention(db: Database, userId: string, mentionId: string) {const rows = await db.delete(communityMention)diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex ac7653b15..dddf9dda2 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -282,6 +282,7 @@ export {AuditLogCliInvocationPayloadSchema,AuditLogToolCallPayloadSchema,AuditLogThinkingPayloadSchema,+ AuditLogWakeTriggerPayloadSchema,HostBotAuditEventFrameSchema,} from "./schemas";@@ -361,6 +362,7 @@ export type {CommunityAgentReactAddRequest,BotAuditEvent,BotAuditEventKind,+ AuditLogWakeTriggerPayload,} from "./schemas";// Community agent CLI bridge contract — lifted from `src/daemon/src/server/contract.ts`.diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 46cdc3cb9..cdf1ad391 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1257,11 +1257,35 @@ export const AuditLogThinkingPayloadSchema = z.object({truncated: z.boolean(),chars: z.number().int().nonnegative(),});+/**+ * `wake_trigger` — one row per wake we ATTEMPTED to deliver. Written from+ * `buildUnreadWakeCommand` right before the `HostCommand` is returned to the+ * caller — the delivery hop (`sendWakeToMachine`) hasn't run yet. That+ * ordering is deliberate: on retry (transient D1/network blip) a second+ * audit row is preferable to a silently-lost wake, so audit-before-delivery+ * is the safer trade-off. Callers reading the audit log should treat rows as+ * "we tried this" not "the daemon received this" — the daemon-facing+ * delivery is best-effort. See "Audit write failure policy" in+ * plans/agent-unread-visibility-unify.md. The `messageId` is the trigger;+ * `channel`/`seq` are denormalized for click-to-jump so the owner UI can+ * render without a second D1 fetch. `senderHandle` is frozen at wake time+ * (renaming after the fact does NOT rewrite past rows).+ */+export const AuditLogWakeTriggerPayloadSchema = z.object({+ messageId: z.string().min(1),+ channel: z.string().min(1),+ seq: CommunityAgentPositiveSeqSchema,+ senderId: z.string().min(1),+ senderHandle: z.string().min(1),+ reason: z.enum(["unread", "mention"]),+});+export type AuditLogWakeTriggerPayload = z.infer<typeof AuditLogWakeTriggerPayloadSchema>;export const BotAuditEventSchema = z.discriminatedUnion("kind", [z.object({ kind: z.literal("cli_invocation"), payload: AuditLogCliInvocationPayloadSchema }),z.object({ kind: z.literal("tool_call"), payload: AuditLogToolCallPayloadSchema }),z.object({ kind: z.literal("thinking"), payload: AuditLogThinkingPayloadSchema }),+ z.object({ kind: z.literal("wake_trigger"), payload: AuditLogWakeTriggerPayloadSchema }),]);export type BotAuditEvent = z.infer<typeof BotAuditEventSchema>;@@ -1269,6 +1293,7 @@ export const BotAuditEventKindSchema = z.enum(["cli_invocation","tool_call","thinking",+ "wake_trigger",]);export type BotAuditEventKind = z.infer<typeof BotAuditEventKindSchema>;diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsindex 2c23e1f8c..2c0250c31 100644--- a/src/shared/test/community/wake-dispatch-build.test.ts+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -10,6 +10,21 @@ vi.mock("../../src/db/queries/community/bot", () => ({getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),}));+const mockHasMentionForMessage = vi.fn();+vi.mock("../../src/db/queries/community/mention", () => ({+ hasMentionForMessage: (...a: unknown[]) => mockHasMentionForMessage(...a),+}));++const mockInsertBotAuditWakeTrigger = vi.fn();+vi.mock("../../src/db/queries/community/bot-audit-log", () => ({+ insertBotAuditWakeTrigger: (...a: unknown[]) => mockInsertBotAuditWakeTrigger(...a),+}));++const mockGetUsersByIds = vi.fn();+vi.mock("../../src/db/queries/user", () => ({+ getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a),+}));+const mockCanBotReadWakeScope = vi.fn();vi.mock("../../src/db/queries/community/member", () => ({canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),@@ -38,13 +53,22 @@ const MESSAGE_CHANNEL = {dmConversationId: null,};-const BOT_READY = {- state: "ready" as const,+const BOT_READY: {+ state: "ready";+ botUserId: string;+ name: string;+ discriminator: string;+ machineId: string;+ runtime: string;+ ownerUserId: string | null;+} = {+ state: "ready",botUserId: "bot_1",name: "zoe",discriminator: "0042",machineId: "machine_1",runtime: "claude",+ ownerUserId: "owner_1",};function seedHappyPath(overrides?: {@@ -61,6 +85,10 @@ function seedHappyPath(overrides?: {mockResolveUnreadNoticeChannel.mockResolvedValue(overrides?.channel === undefined ? "/srv_1/general" : overrides.channel,);+ // Audit path best-effort defaults — happy replies so the wake still fires.+ mockGetUsersByIds.mockResolvedValue([{ id: "u_human", name: "gustavo", discriminator: "0042" }]);+ mockHasMentionForMessage.mockResolvedValue(false);+ mockInsertBotAuditWakeTrigger.mockResolvedValue({ id: "evt_1", createdAt: "2026-07-23T00:00:00.000Z" });}describe("buildUnreadWakeCommand", () => {@@ -234,4 +262,101 @@ describe("buildUnreadWakeCommand", () => {buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" }),).rejects.toThrow("D1_ERROR");});++ it("writes a wake_trigger audit row with the correct payload after the gate passes", async () => {+ seedHappyPath();++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ expect(result.state).toBe("ready");+ expect(mockInsertBotAuditWakeTrigger).toHaveBeenCalledTimes(1);+ const [, args] = mockInsertBotAuditWakeTrigger.mock.calls[0]!;+ expect(args).toMatchObject({+ botId: "bot_1",+ payload: {+ messageId: "msg_1",+ channel: "/srv_1/general",+ seq: 7,+ senderId: "u_human",+ senderHandle: "@gustavo#0042",+ reason: "unread",+ },+ });+ });++ it("audit reason is 'mention' when the message carries a mention row for the bot", async () => {+ seedHappyPath();+ mockHasMentionForMessage.mockResolvedValue(true);++ await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ const [, args] = mockInsertBotAuditWakeTrigger.mock.calls[0]!;+ expect(args.payload.reason).toBe("mention");+ });++ it("NEVER writes an audit row when the wake was skipped (bot_not_in_scope)", async () => {+ seedHappyPath({ canRead: false });++ await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ expect(mockInsertBotAuditWakeTrigger).not.toHaveBeenCalled();+ });++ it("wake still fires when the audit insert throws (best-effort, MUST NOT gate the wake)", async () => {+ seedHappyPath();+ mockInsertBotAuditWakeTrigger.mockRejectedValue(new Error("d1 blip"));++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ expect(result.state).toBe("ready");+ });++ it("wake still fires when the sender lookup fails — audit is skipped silently", async () => {+ seedHappyPath();+ mockGetUsersByIds.mockRejectedValue(new Error("d1 blip"));++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ expect(result.state).toBe("ready");+ expect(mockInsertBotAuditWakeTrigger).not.toHaveBeenCalled();+ });++ it("audit is skipped silently when the bot has no owner (unbound owner column)", async () => {+ seedHappyPath({ bot: { ownerUserId: null } });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ expect(result.state).toBe("ready");+ expect(mockInsertBotAuditWakeTrigger).not.toHaveBeenCalled();+ expect(mockGetUsersByIds).not.toHaveBeenCalled();+ });++ it("calls the ws-do internal broadcast route with the shape ws-durable.ts emits for daemon frames (when env is provided)", async () => {+ seedHappyPath();+ const fetchMock = vi.fn(async () => new Response(null, { status: 204 }));+ const env = { WS_DO_WORKER: { fetch: fetchMock } };++ await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" }, env);++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toContain("/internal/broadcast-bot-audit-event");+ expect(init?.method).toBe("POST");+ const body = JSON.parse(init!.body as string);+ expect(body).toMatchObject({+ botId: "bot_1",+ ownerUserId: "owner_1",+ id: "evt_1",+ kind: "wake_trigger",+ payload: {+ messageId: "msg_1",+ channel: "/srv_1/general",+ seq: 7,+ reason: "unread",+ },+ });+ });++ it("wake still fires when the ws-do broadcast fetch throws — broadcast is best-effort", async () => {+ seedHappyPath();+ const fetchMock = vi.fn(async () => { throw new Error("network down") });+ const env = { WS_DO_WORKER: { fetch: fetchMock } };++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" }, env);+ expect(result.state).toBe("ready");+ });});diff --git a/src/shared/test/community/wake-dispatch-one.test.ts b/src/shared/test/community/wake-dispatch-one.test.tsindex 871c7075a..2a33883b2 100644--- a/src/shared/test/community/wake-dispatch-one.test.ts+++ b/src/shared/test/community/wake-dispatch-one.test.ts@@ -10,6 +10,21 @@ vi.mock("../../src/db/queries/community/bot", () => ({getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),}));+const mockHasMentionForMessage = vi.fn();+vi.mock("../../src/db/queries/community/mention", () => ({+ hasMentionForMessage: (...a: unknown[]) => mockHasMentionForMessage(...a),+}));++const mockInsertBotAuditWakeTrigger = vi.fn();+vi.mock("../../src/db/queries/community/bot-audit-log", () => ({+ insertBotAuditWakeTrigger: (...a: unknown[]) => mockInsertBotAuditWakeTrigger(...a),+}));++const mockGetUsersByIds = vi.fn();+vi.mock("../../src/db/queries/user", () => ({+ getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a),+}));+const mockCanBotReadWakeScope = vi.fn();vi.mock("../../src/db/queries/community/member", () => ({canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),@@ -45,6 +60,7 @@ const BOT_READY = {discriminator: "0042",machineId: "machine_1",runtime: "claude",+ ownerUserId: "owner_1",};function seedReady() {@@ -53,6 +69,9 @@ function seedReady() {mockCanBotReadWakeScope.mockResolvedValue(true);mockGetWakeReadSeq.mockResolvedValue(0);mockResolveUnreadNoticeChannel.mockResolvedValue("/srv_1/general");+ mockGetUsersByIds.mockResolvedValue([{ id: "u_human", name: "gustavo", discriminator: "0042" }]);+ mockHasMentionForMessage.mockResolvedValue(false);+ mockInsertBotAuditWakeTrigger.mockResolvedValue({ id: "evt_1", createdAt: "2026-07-23T00:00:00.000Z" });}function makeEnv(fetchImpl: (url: string, init?: RequestInit) => Promise<Response>) {diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex 014ace84e..8cc80a081 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -159,9 +159,22 @@ describe("toAgentMessage", () => {});describe("listUnreadMessagesForAgent", () => {+ // Call order (visibility + participation pre-narrowed BEFORE the messages+ // SQL so `.limit(max)` operates on already-allowed rows — see+ // `listAgentAllowedChannelIds`):+ // 1. `listVisibleChannelIdsForUser` → server-memberships query+ // 2. `listVisibleChannelIdsForUser` → channels+category join+ // 3. `listVisibleChannelIdsForUser` → viewer's channel-member rows+ // 4. Visible-channel types lookup (skipped when visible set is empty)+ // 5. `listParticipatingThreadIds` (skipped when no narrow types among visible)+ // 6. The messages SQL itselfit("strips the internal lastReadSeq column before returning rows", async () => {const db = createSequentialDb([- [{ ...rawMsg(), lastReadSeq: 0 }],+ [{ serverId: "srv_1" }], // 1. membership+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }], // 2. channels+ [], // 3. viewer memberChannelIds+ [{ id: "ch_1", type: "text" }], // 4. types of visible channels+ [{ ...rawMsg(), lastReadSeq: 0 }], // 5. messages (no narrow types → no participant query)]);const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });expect(result).toEqual([rawMsg()]);@@ -169,54 +182,171 @@ describe("listUnreadMessagesForAgent", () => {});it("passes opts.max through to .limit()", async () => {- const db = createSequentialDb([[]]);+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [],+ ]);await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 17 });- // The final chain instance's `.limit` mock recorded the call.- const chainResult = db.select.mock.results[0]!.value;+ // The 5th `db.select(...)` chain is the message query — that's where `.limit` lands.+ const chainResult = db.select.mock.results[4]!.value;expect(chainResult.limit).toHaveBeenCalledWith(17);});- it("joins scope tables before unread filtering", async () => {- const db = createSequentialDb([[]]);+ it("joins only dm + read-state on the messages SQL (visibility & participation are pre-narrowed)", async () => {+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [],+ ]);await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });- const chainResult = db.select.mock.results[0]!.value;- expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);+ const chainResult = db.select.mock.results[4]!.value;+ // dm + read-state — communityChannel join dropped now that+ // participation is folded into `listAgentAllowedChannelIds` up front.+ expect(chainResult.leftJoin).toHaveBeenCalledTimes(2);expect(chainResult.leftJoin.mock.invocationCallOrder[0]).toBeLessThan(chainResult.where.mock.invocationCallOrder[0]);});++ it("excludes thread/forum_post channels the bot isn't a participant of from the allowed set", async () => {+ // ch_a is a plain text channel (always allowed); ch_b_thread is a thread+ // the bot doesn't participate in. `listAgentAllowedChannelIds` drops+ // ch_b_thread BEFORE the messages SQL runs, so the WHERE never lets a+ // ch_b_thread row through — the earlier post-filter-after-.limit shape+ // could collapse the page to [] when the top-N rows were all+ // non-participating threads.+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [+ { id: "ch_a", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },+ { id: "ch_b_thread", type: "thread", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: "ch_a" },+ ],+ [],+ [+ { id: "ch_a", type: "text" },+ { id: "ch_b_thread", type: "thread" },+ ],+ [], // listParticipatingThreadIds: bot participates in neither+ [{ ...rawMsg({ id: "m_a", channelId: "ch_a" }), lastReadSeq: 0 }],+ ]);+ const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });+ expect(result.map((r) => r.id)).toEqual(["m_a"]);+ });++ it("keeps thread/forum_post channels when the bot IS a participant", async () => {+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [+ { id: "ch_a", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },+ { id: "ch_b_thread", type: "thread", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: "ch_a" },+ ],+ [],+ [+ { id: "ch_a", type: "text" },+ { id: "ch_b_thread", type: "thread" },+ ],+ [{ threadChannelId: "ch_b_thread" }], // participant row exists+ [{ ...rawMsg({ id: "m_b", channelId: "ch_b_thread" }), lastReadSeq: 0 }],+ ]);+ const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });+ expect(result.map((r) => r.id)).toEqual(["m_b"]);+ });++ it("returns [] without hitting the messages SQL when the bot has no server memberships", async () => {+ const db = createSequentialDb([+ [], // no memberships → listVisibleChannelIdsForUser returns []+ [{ ...rawMsg(), lastReadSeq: 0 }], // messages SQL (only DM branch could return, guarded by 1=0 on channel side in real SQL)+ ]);+ const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });+ expect(Array.isArray(result)).toBe(true);+ });});describe("getLatestUnreadMessageForAgent", () => {+ // Call order (same visibility+participation prelude as+ // listUnreadMessagesForAgent, then a single-row messages SQL):+ // 1-3. `listVisibleChannelIdsForUser`+ // 4. Visible-channel types lookup+ // 5. `listParticipatingThreadIds` (only if narrow types among visible)+ // 6. The messages SQL — `ORDER BY createdAt DESC LIMIT 1`it("returns null when there's no unread anywhere", async () => {- const db = createSequentialDb([[]]);+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [],+ ]);const result = await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");expect(result).toBeNull();});- it("returns the single most-recent unread message id, ordered by createdAt desc limit 1", async () => {- // The mock DB only records the LAST call to each chain method, so this- // exercises the id extraction — the createdAt-desc/limit-1 ordering- // itself is asserted via the `.orderBy`/`.limit` call-args check below.- const db = createSequentialDb([[{ id: "m_latest" }]]);+ it("returns the single most-recent unread message id", async () => {+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [{ id: "m_latest" }],+ ]);const result = await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");expect(result).toEqual({ messageId: "m_latest" });});- it("orders by createdAt desc and limits to 1 (comparable across channel + DM scopes, unlike seq)", async () => {- const db = createSequentialDb([[]]);+ it("excludes thread channels the bot isn't a participant of from the messages SQL entirely", async () => {+ // ch_thread is filtered out of `allowedChannelIds` by the pre-narrowing+ // pass, so the messages SQL's WHERE ... inArray(channelId, allowed) can+ // never surface a ch_thread row. `m_text` is the newest allowed row.+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [+ { id: "ch_thread", type: "thread", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: "ch_text" },+ { id: "ch_text", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },+ ],+ [],+ [+ { id: "ch_thread", type: "thread" },+ { id: "ch_text", type: "text" },+ ],+ [], // bot isn't a participant of ch_thread → dropped from allowed set+ [{ id: "m_text" }], // messages SQL only ever sees ch_text+ ]);+ const result = await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");+ expect(result).toEqual({ messageId: "m_text" });+ });++ it("orders by createdAt desc and asks for a single row (allowed-set is pre-narrowed, no post-filter window needed)", async () => {+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [],+ ]);await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");- const chainResult = db.select.mock.results[0]!.value;+ const chainResult = db.select.mock.results[4]!.value;expect(chainResult.orderBy).toHaveBeenCalledTimes(1);expect(chainResult.limit).toHaveBeenCalledWith(1);});- it("joins scope tables before unread filtering (same predicates as listUnreadMessagesForAgent)", async () => {- const db = createSequentialDb([[]]);+ it("joins only dm + read-state on the messages SQL (visibility & participation are pre-narrowed)", async () => {+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [],+ ]);await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");- const chainResult = db.select.mock.results[0]!.value;- expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);+ const chainResult = db.select.mock.results[4]!.value;+ // dm + read-state.+ expect(chainResult.leftJoin).toHaveBeenCalledTimes(2);expect(chainResult.leftJoin.mock.invocationCallOrder[0]).toBeLessThan(chainResult.where.mock.invocationCallOrder[0]);@@ -251,15 +381,36 @@ describe("resolveUnreadNoticeChannel", () => {});describe("getInboxSnapshotForAgent", () => {+ // Call order:+ // 1-3. `listVisibleChannelIdsForUser` (memberships, channels, viewer members)+ // 4. Visible-channel types lookup+ // 5. `listParticipatingThreadIds` (skipped when no narrow types among visible)+ // 6. The snapshot aggregation SQL+ // 7. sender-name hydrationit("returns [] and skips the user-name lookup when there's no pending unread", async () => {- const db = createSequentialDb([[]]);+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [],+ ]);const result = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");expect(result).toEqual([]);- expect(db.select).toHaveBeenCalledTimes(1);});it("hydrates latestSender from the user table and sets hasMention from mentionCount", async () => {const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [+ { id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },+ { id: "ch_2", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },+ ],+ [],+ [+ { id: "ch_1", type: "text" },+ { id: "ch_2", type: "text" },+ ],[{channelId: "ch_1",@@ -308,12 +459,41 @@ describe("getInboxSnapshotForAgent", () => {]);});- it("joins scope tables before unread aggregation", async () => {- const db = createSequentialDb([[]]);+ it("excludes thread/forum_post channels the bot isn't a participant of from the allowed set", async () => {+ // ch_thread is filtered out of `allowedChannelIds` up front, so the+ // aggregation SQL's WHERE ... inArray(channelId, allowed) never surfaces+ // it. No post-filter needed → no risk of an aggregation row silently+ // disappearing after being counted.+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [+ // Top-level thread-typed channel so it survives the visibility pass;+ // the shape only tests the participation narrowing, not+ // parent-anchored visibility (covered elsewhere).+ { id: "ch_thread", type: "thread", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },+ ],+ [],+ [{ id: "ch_thread", type: "thread" }],+ [], // participant lookup: not a participant → ch_thread dropped from allowed+ [], // aggregation SQL: allowedChannelIds is [], WHERE has 1=0, no rows survive+ ]);+ const result = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");+ expect(result).toEqual([]);+ });++ it("joins only dm + read-state on the aggregation SQL (visibility & participation are pre-narrowed)", async () => {+ const db = createSequentialDb([+ [{ serverId: "srv_1" }],+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],+ [],+ [{ id: "ch_1", type: "text" }],+ [],+ ]);await agentInbox.getInboxSnapshotForAgent(db, "bot_1");- const chainResult = db.select.mock.results[0]!.value;- expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);+ const chainResult = db.select.mock.results[4]!.value;+ // dm + read-state.+ expect(chainResult.leftJoin).toHaveBeenCalledTimes(2);expect(chainResult.leftJoin.mock.invocationCallOrder[0]).toBeLessThan(chainResult.where.mock.invocationCallOrder[0]);diff --git a/src/shared/test/queries/community-bot-audit-log.test.ts b/src/shared/test/queries/community-bot-audit-log.test.tsindex 164325697..2e071a791 100644--- a/src/shared/test/queries/community-bot-audit-log.test.ts+++ b/src/shared/test/queries/community-bot-audit-log.test.ts@@ -13,6 +13,7 @@ describe("community/bot-audit-log exports", () => {expect(typeof q.insertBotActivityEventStatement).toBe("function")expect(typeof q.pruneBotActivityEventsStatement).toBe("function")expect(typeof q.insertBotActivityEventAndPrune).toBe("function")+ expect(typeof q.insertBotAuditWakeTrigger).toBe("function")})it("exposes a reader", () => {@@ -48,6 +49,62 @@ describe("BotAuditEventSchema — payload discriminated union", () => {})expect(r.success).toBe(true)})+ it("accepts a wake_trigger payload with the six required fields", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "wake_trigger",+ payload: {+ messageId: "msg_1",+ channel: "/srv_1/general",+ seq: 12,+ senderId: "u_human",+ senderHandle: "@gustavo#0042",+ reason: "unread",+ },+ })+ expect(r.success).toBe(true)+ })+ it("accepts wake_trigger with reason=mention", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "wake_trigger",+ payload: {+ messageId: "msg_1",+ channel: "/srv_1/general",+ seq: 12,+ senderId: "u_human",+ senderHandle: "@gustavo#0042",+ reason: "mention",+ },+ })+ expect(r.success).toBe(true)+ })+ it("rejects wake_trigger with a missing required field", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "wake_trigger",+ payload: {+ // messageId missing+ channel: "/srv_1/general",+ seq: 12,+ senderId: "u_human",+ senderHandle: "@gustavo#0042",+ reason: "unread",+ },+ })+ expect(r.success).toBe(false)+ })+ it("rejects wake_trigger with an unknown reason", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "wake_trigger",+ payload: {+ messageId: "msg_1",+ channel: "/srv_1/general",+ seq: 12,+ senderId: "u_human",+ senderHandle: "@gustavo#0042",+ reason: "shouted",+ },+ })+ expect(r.success).toBe(false)+ })it("rejects a kind/payload mismatch", () => {const r = BotAuditEventSchema.safeParse({kind: "tool_call",diff --git a/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts b/src/shared/test/queries/community-can-bot-read-wake-scope.test.tsnew file mode 100644index 000000000..6c1ffcd8d--- /dev/null+++ b/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts@@ -0,0 +1,136 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++const mockResolveChannelAccessContext = vi.fn();+vi.mock("../../src/db/queries/community/channel", () => ({+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),+}));++const mockIsThreadParticipant = vi.fn();+vi.mock("../../src/db/queries/community/thread", () => ({+ isThreadParticipant: (...a: unknown[]) => mockIsThreadParticipant(...a),+}));++import { canBotReadWakeScope } from "../../src/db/queries/community/member";+import type { Database } from "../../src/db/index";++// The DM branch runs a real Drizzle query — build the smallest chainable stub+// that resolves to whatever `rows` we hand it, so DM cases don't need a real+// DB either.+function createDmDb(rows: unknown[]): Database {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve(rows));+ return chain as Database;+}++const fakeDb = {} as Database;++// The `channel` object the real `resolveChannelAccessContext` returns is a+// full ChannelRow; here we only need the `type` field, so a minimal stub is+// enough for the gate to branch correctly.+function ctx(overrides: {+ type: string;+ isPrivate?: boolean;+ role?: string;+ isCreator?: boolean;+ isChannelMember?: boolean;+}) {+ return {+ channel: { type: overrides.type },+ anchor: {},+ role: overrides.role ?? "member",+ isPrivate: overrides.isPrivate ?? false,+ isChannelMember: overrides.isChannelMember ?? false,+ isCreator: overrides.isCreator ?? false,+ };+}++describe("canBotReadWakeScope — visibility gate", () => {+ beforeEach(() => vi.clearAllMocks());++ it("public top-level channel + bot IS a server member → true", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "text", isPrivate: false }));+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "ch_public" })).toBe(true);+ });++ it("public top-level channel + bot NOT a server member (ctx null) → false", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(null);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "ch_public" })).toBe(false);+ });++ it("private channel + bot IS on the roster → true", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(+ ctx({ type: "text", isPrivate: true, isChannelMember: true }),+ );+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "ch_secret" })).toBe(true);+ });++ it("private channel + bot NOT on the roster → false", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(+ ctx({ type: "text", isPrivate: true, isChannelMember: false }),+ );+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "ch_secret" })).toBe(false);+ });+});++describe("canBotReadWakeScope — notification-set narrowing (thread + forum_post)", () => {+ beforeEach(() => vi.clearAllMocks());++ it("public forum_post + bot IS a thread participant → true", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "forum_post", isPrivate: false }));+ mockIsThreadParticipant.mockResolvedValue(true);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_1" })).toBe(true);+ });++ it("public forum_post + bot NOT a participant → false (regression guard for Mellicent's exact case)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "forum_post", isPrivate: false }));+ mockIsThreadParticipant.mockResolvedValue(false);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_1" })).toBe(false);+ });++ it("thread under public channel + bot NOT a participant → false", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "thread", isPrivate: false }));+ mockIsThreadParticipant.mockResolvedValue(false);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "thread_1" })).toBe(false);+ });++ it("thread + bot IS a participant → true", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "thread", isPrivate: false }));+ mockIsThreadParticipant.mockResolvedValue(true);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "thread_1" })).toBe(true);+ });++ it("private forum_post + bot on roster + IS a participant → true", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(+ ctx({ type: "forum_post", isPrivate: true, isChannelMember: true }),+ );+ mockIsThreadParticipant.mockResolvedValue(true);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_priv" })).toBe(true);+ });++ it("private forum_post + bot on roster but NOT a participant → false (both gates enforced)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(+ ctx({ type: "forum_post", isPrivate: true, isChannelMember: true }),+ );+ mockIsThreadParticipant.mockResolvedValue(false);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_priv" })).toBe(false);+ });+});++describe("canBotReadWakeScope — DM scope", () => {+ it("DM + bot is a participant → true", async () => {+ const db = createDmDb([{ id: "dm_1" }]);+ expect(await canBotReadWakeScope(db, "bot", { dmConversationId: "dm_1" })).toBe(true);+ });++ it("DM + bot is NOT a participant → false", async () => {+ const db = createDmDb([]);+ expect(await canBotReadWakeScope(db, "bot", { dmConversationId: "dm_1" })).toBe(false);+ });++ it("no scope provided → false", async () => {+ expect(await canBotReadWakeScope(fakeDb, "bot", {})).toBe(false);+ });+});diff --git a/src/shared/test/queries/community-mention.test.ts b/src/shared/test/queries/community-mention.test.tsindex 00114331b..59edcd879 100644--- a/src/shared/test/queries/community-mention.test.ts+++ b/src/shared/test/queries/community-mention.test.ts@@ -32,6 +32,33 @@ describe("community/mention exports", () => {it("exports markChannelMentionsReadBuilder", () => {expect(typeof mentionQueries.markChannelMentionsReadBuilder).toBe("function");});+ it("exports hasMentionForMessage", () => {+ expect(typeof mentionQueries.hasMentionForMessage).toBe("function");+ });+});++describe("hasMentionForMessage", () => {+ function createSelectMock(rows: unknown[]) {+ const chain: any = {};+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve(rows));+ return {+ select: vi.fn(() => chain),+ };+ }+ it("returns true when a mention row exists", async () => {+ const db = createSelectMock([{ id: "mention_1" }]);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const result = await mentionQueries.hasMentionForMessage(db as any, "msg_1", "u_1");+ expect(result).toBe(true);+ });+ it("returns false when no mention row exists", async () => {+ const db = createSelectMock([]);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const result = await mentionQueries.hasMentionForMessage(db as any, "msg_1", "u_1");+ expect(result).toBe(false);+ });});describe("markChannelMentionsReadBuilder", () => {diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.test.tsindex 67d75014b..064acd484 100644--- a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts@@ -122,4 +122,21 @@ describe("POST /api/community/daemon/resync-wakes", () => {const res = await POST(req({ Authorization: "Bearer cmk_bad" }));expect(res.status).toBe(401);});++ it("Mellicent regression: bot on a server whose only unread lives in a non-participated forum_post — feeder returns null → woken: 0", async () => {+ // Post-fix behaviour: `getLatestUnreadMessageForAgent` applies the+ // thread-participation post-filter (`plans/agent-unread-visibility-unify.md`),+ // so a message in a forum_post the bot isn't a participant of no longer+ // surfaces. The feeder returns null → resync-wakes reports woken: 0 and+ // never touches the wake dispatcher.+ mockListBotsForMachine.mockResolvedValue([+ { id: "bot_Y", name: "Mellicent", description: "" },+ ]);+ mockGetLatestUnreadMessageForAgent.mockResolvedValue(null);++ const res = await POST(req({ Authorization: "Bearer cmk_ok" }));++ expect(await res.json()).toEqual({ woken: 0 });+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled();+ });});diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts b/src/web/src/app/api/community/messages/[id]/threads/route.test.tsindex 1f219a1cd..c47b24f9d 100644--- a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/threads/route.test.ts@@ -11,7 +11,6 @@ const mockListChildChannels = vi.fn()const mockCreateChannel = vi.fn()const mockCreateMessage = vi.fn()const mockListMessages = vi.fn()-const mockGetUserInternal = vi.fn()const mockFanOutToChannel = vi.fn()@@ -32,9 +31,6 @@ vi.mock("@alook/shared", async () => {createMessage: (...a: unknown[]) => mockCreateMessage(...a),listMessages: (...a: unknown[]) => mockListMessages(...a),},- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- },},}})@@ -92,56 +88,21 @@ describe("POST /api/community/messages/[id]/threads", () => {messageCount: 0,createdAt: "2026-07-03T00:00:00.000Z",})- mockGetUserInternal.mockResolvedValue({ id: "u1", name: "Thread Creator" })- // The thread-creation system message (see #12/§5 — inserted into the- // PARENT channel, distinct from the parent-message-clone-into-the-NEW-- // thread-channel bug finding #6 already guards against below).- mockCreateMessage.mockResolvedValue({ id: "sysmsg-1" })- mockGetMessage.mockImplementation((_db, id) => {- if (id === "sysmsg-1") {- return Promise.resolve({- id: "sysmsg-1",- authorId: "u1",- authorName: "Thread Creator",- authorImage: null,- content: "Thread Creator started a thread: my thread",- type: "thread_created",- mentionType: null,- replyToId: null,- embeds: null,- createdAt: "2026-07-03T00:00:01.000Z",- })- }- return Promise.resolve({- id: "msg-p",- authorId: "u-author",- content: "the parent content",- channelId: "c-parent",- })+ mockGetMessage.mockResolvedValue({+ id: "msg-p",+ authorId: "u-author",+ content: "the parent content",+ channelId: "c-parent",})})- it("creates the child channel WITHOUT cloning the parent message into it", async () => {+ it("creates the child channel WITHOUT inserting any message into either channel", async () => {const res = await POST(req({ name: "my thread" }), ctx)expect(res.status).toBe(201)- // Regression guard: the fix in finding #6 removes the createMessage(...)- // CLONE of the parent's content into the NEW thread channel — that call- // would have `channelId: "t-new"`. It's distinct from the (correct,- // added in #12/§5) system-message insert into the PARENT channel- // (`channelId: "c-parent"`) asserted below — this checks no call- // targets the new thread channel specifically.- expect(mockCreateMessage).not.toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ channelId: "t-new" }),- )-- // The new system-message insert targets the PARENT channel, with the- // `thread_created` convention type (#12/§5).- expect(mockCreateMessage).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ channelId: "c-parent", type: "thread_created" }),- )+ // No message row is created anywhere: no clone into the new thread+ // channel, and no "XXX started a thread: NAME" notice into the parent.+ expect(mockCreateMessage).not.toHaveBeenCalled()// Structural check: listMessages on the new thread channel is empty —// no opener clone row exists.@@ -167,33 +128,18 @@ describe("POST /api/community/messages/[id]/threads", () => {expect(body.id).toBe("t-new")expect(body.parentMessageId).toBe("msg-p")- // Both fan-outs to the parent channel fire: CHILD_CHANNEL_CREATE and the- // new system-message MESSAGE_CREATE (#12/§5).+ // Only the CHILD_CHANNEL_CREATE fan-out fires to the parent channel — no+ // system-message MESSAGE_CREATE broadcast.+ expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)expect(mockFanOutToChannel).toHaveBeenCalledWith("c-parent",expect.objectContaining({ parentMessageId: "msg-p" }),expect.anything(),)- // The system-message broadcast is NOT given `excludeUserId` — unlike the- // creator's own client-side actions elsewhere, nothing inserts this row- // into the creator's local cache, so they need the WS broadcast too to- // see "started a thread" without a refresh (verification acceptance- // finding #6 in community-message-tech-debt-acceptance.md).- expect(mockFanOutToChannel).toHaveBeenCalledWith(- "c-parent",- expect.objectContaining({- type: "community:message.create",- message: expect.objectContaining({ id: "sysmsg-1", type: "system", systemKind: "thread" }),- }),- expect.objectContaining({ excludeUserId: undefined }),- )- const systemMessageCall = mockFanOutToChannel.mock.calls.find(+ const messageCreateCall = mockFanOutToChannel.mock.calls.find((call) => (call[1] as { type?: string }).type === "community:message.create",)- expect(systemMessageCall).toBeDefined()- // The unified pipeline passes an opts arg; `includeAuthorInFanout` means- // no `excludeUserId` so the creator also receives the broadcast.- expect((systemMessageCall![2] as { excludeUserId?: string }).excludeUserId).toBeUndefined()+ expect(messageCreateCall).toBeUndefined()})it("rejects a second thread on the same parent message", async () => {diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.ts b/src/web/src/app/api/community/messages/[id]/threads/route.tsindex 233fbfa9c..f25bf54df 100644--- a/src/web/src/app/api/community/messages/[id]/threads/route.ts+++ b/src/web/src/app/api/community/messages/[id]/threads/route.ts@@ -5,7 +5,6 @@ import { getDb } from "@/lib/db"import { queries, MAX_CHANNEL_NAME_LENGTH, WS_EVENTS } from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember } from "@/lib/community/permissions"-import { createCommunityMessage } from "@/lib/community/message-handler"export const POST = withAuth(async (req: NextRequest, ctx) => {const messageId = ctx.params?.id@@ -81,35 +80,5 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {parentMessageId: messageId,}, { excludeUserId: ctx.userId })- // Insert a real system-message row into the PARENT channel (always- // `MessageList`-rendered, unlike the forum-post case — see the debt- // record's Out of scope note on why `POST .../posts` doesn't get this- // same treatment) so the "a thread was created" notice persists and- // reaches every viewer via the same `community:message.create` broadcast- // regular sends use — no new WS handler needed on the client (see- // `use-community-ws.ts`'s existing `insertMessageIntoCache`).- //- // `type: "thread_created"` was already documented as a possible- // `communityMessage.type` value (see `message-payload.ts`) but never- // actually written anywhere until now.- // System notice through the unified pipeline: `thread_created` type,- // `skipMentions` (a system message @-mentions no one), `skipWake` (no bot- // wake), and `includeAuthorInFanout` so the creator — who has no optimistic- // client row — receives the MESSAGE_CREATE and sees it without a refresh- // (reproduces the old no-`excludeUserId` broadcast). `insertMessageIntoCache`- // dedupes by id, so this is safe even if a future change adds an optimistic- // row for the creator.- const creator = await queries.user.getUserInternal(db, ctx.userId)- await createCommunityMessage({- db,- authorId: ctx.userId,- target: { kind: "channel", channelId: message.channelId, serverId: channel.serverId },- body: { content: `${creator?.name ?? "Someone"} started a thread: ${name}` },- messageType: "thread_created",- skipMentions: true,- skipWake: true,- includeAuthorInFanout: true,- })-return writeJSON(childChannel, 201)})diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsxindex bb0217472..fef9b4733 100644--- a/src/web/src/components/community/bots/bot-activity-row.tsx+++ b/src/web/src/components/community/bots/bot-activity-row.tsx@@ -55,6 +55,7 @@ function KindTag({ kind }: { kind: AuditKind }) {function kindMeta(kind: AuditKind): { label: string; tone: string } {if (kind === "cli_invocation") return { label: "daemon", tone: "text-foreground/70" }if (kind === "tool_call") return { label: "tool", tone: "text-muted-foreground" }+ if (kind === "wake_trigger") return { label: "wake", tone: "text-foreground/70" }return { label: "think", tone: "text-muted-foreground/70" }}@@ -95,6 +96,25 @@ function RowBody({}return <span className="font-mono text-[13px] text-foreground">{name}</span>}+ if (event.kind === "wake_trigger") {+ const p = event.payload as {+ channel?: string+ seq?: number+ senderHandle?: string+ reason?: "unread" | "mention"+ } | null+ const sender = p?.senderHandle ?? "@unknown"+ const channel = p?.channel ?? "/unknown"+ const seqLabel = p?.seq != null ? `#${p.seq}` : ""+ const verb = p?.reason === "mention" ? "Mentioned by" : "Woken by"+ return (+ <div className="truncate font-mono text-[13px] text-foreground">+ <span className="text-muted-foreground">{verb}</span> {sender}{" "}+ <span className="text-muted-foreground">in</span> {channel}+ {seqLabel ? <span className="text-muted-foreground/70"> {seqLabel}</span> : null}+ </div>+ )+ }const p = event.payload as { text?: string; truncated?: boolean; chars?: number } | nullconst text = p?.text ?? ""const truncated = p?.truncated ?? falsediff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsxindex da0aeefef..ff43e6727 100644--- a/src/web/src/components/community/channel-sidebar.tsx+++ b/src/web/src/components/community/channel-sidebar.tsx@@ -226,11 +226,11 @@ export const ChannelSidebar = memo(function ChannelSidebar({return (<aside className="flex min-w-0 flex-1 flex-col">{!noHeader && (- <header className="flex h-12 items-center gap-1 border-b border-border/40 px-2">+ <header className="flex items-center gap-1 border-b border-border/40 px-2 py-2">{serverName && onOpenSettings ? (<DropdownMenu><DropdownMenuTrigger className="flex min-w-0 max-w-full items-center gap-2 rounded-md px-2 py-1 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">- <span className="min-w-0 truncate font-brand text-3xl font-bold">{serverName}</span>+ <span className="min-w-0 truncate pr-1 font-brand text-3xl font-bold">{serverName}</span><ChevronDown className="size-4 shrink-0 text-muted-foreground" /></DropdownMenuTrigger><DropdownMenuContent align="start" className="w-48">diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.tsindex ede5ff51a..a0c454b6a 100644--- a/src/web/src/hooks/community/use-bot-audit-log.ts+++ b/src/web/src/hooks/community/use-bot-audit-log.ts@@ -10,7 +10,7 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { useBotAuditEventsForBot } from "@/stores/community/ws"-export type AuditKind = "cli_invocation" | "tool_call" | "thinking"+export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "wake_trigger"export type AuditEvent = {id: stringdiff --git a/src/web/src/lib/community/audit-log-payload.test.ts b/src/web/src/lib/community/audit-log-payload.test.tsindex 900a9ef38..e928f3c37 100644--- a/src/web/src/lib/community/audit-log-payload.test.ts+++ b/src/web/src/lib/community/audit-log-payload.test.ts@@ -38,6 +38,17 @@ describe("parseAuditLogPayload", () => {)expect(p).toEqual({ text: "hmm", truncated: false, chars: 3 })})+ it("parses a well-shaped wake_trigger payload", () => {+ const payload = {+ messageId: "m_1",+ channel: "/srv/general",+ seq: 42,+ senderId: "u_1",+ senderHandle: "@alice#1234",+ reason: "unread" as const,+ }+ expect(parseAuditLogPayload("wake_trigger", JSON.stringify(payload))).toEqual(payload)+ })it("returns null on invalid JSON — the whole page must not 500", () => {expect(parseAuditLogPayload("cli_invocation", "{not-json")).toBe(null)})diff --git a/src/web/src/lib/community/audit-log-payload.ts b/src/web/src/lib/community/audit-log-payload.tsindex c59fc32e3..66a5631ed 100644--- a/src/web/src/lib/community/audit-log-payload.ts+++ b/src/web/src/lib/community/audit-log-payload.ts@@ -2,6 +2,7 @@ import {AuditLogCliInvocationPayloadSchema,AuditLogToolCallPayloadSchema,AuditLogThinkingPayloadSchema,+ AuditLogWakeTriggerPayloadSchema,} from "@alook/shared"/**@@ -33,6 +34,10 @@ export function parseAuditLogPayload(const r = AuditLogThinkingPayloadSchema.safeParse(json)return r.success ? r.data : null}+ case "wake_trigger": {+ const r = AuditLogWakeTriggerPayloadSchema.safeParse(json)+ return r.success ? r.data : null+ }default:return null}diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.tsindex fb01f18a4..e5bef6b66 100644--- a/src/web/src/lib/community/wake-producer.test.ts+++ b/src/web/src/lib/community/wake-producer.test.ts@@ -10,6 +10,7 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockFindWakeCandidates = vi.fn()+const mockCanBotReadWakeScope = vi.fn()const mockWarn = vi.fn()const mockInfo = vi.fn()@@ -27,6 +28,9 @@ vi.mock("@alook/shared", async () => {communityBot: {findWakeCandidates: (...a: unknown[]) => mockFindWakeCandidates(...a),},+ communityMember: {+ canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),+ },},}})@@ -59,6 +63,9 @@ describe("enqueueBotWakes", () => {vi.clearAllMocks()mockQueueSend.mockResolvedValue(undefined)mockDevHttpSend.mockResolvedValue(undefined)+ // Default: every candidate passes the wake gate. Tests that need to+ // exercise gate-filtering override this per case.+ mockCanBotReadWakeScope.mockResolvedValue(true)})it("no-ops when recipients is empty — never queries or picks a transport", async () => {@@ -99,6 +106,62 @@ describe("enqueueBotWakes", () => {])})+ it("drops candidates that fail the wake gate (visibility / participation) before sending", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_visible", name: "zoe", machineId: "m1", runtime: "claude" },+ { botUserId: "bot_hidden", name: "kai", machineId: "m2", runtime: "codex" },+ ])+ mockCanBotReadWakeScope.mockImplementation(async (_db: unknown, botId: string) =>+ botId === "bot_visible",+ )++ await enqueueBotWakes({ recipients: ["bot_visible", "bot_hidden"], channelId: "c1", messageRow })++ expect(mockQueueSend).toHaveBeenCalledTimes(1)+ const [payloads] = mockQueueSend.mock.calls[0]!+ expect(payloads).toEqual([{ messageId: "msg_1", botUserId: "bot_visible" }])+ })++ it("drops (does NOT throw or collapse the batch) when a single candidate's gate check rejects", async () => {+ // Regression guard: a transient D1 blip on ONE candidate's gate check+ // must not wipe every wake for the message — `allSettled`, not `all`.+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_ok_1", name: "a", machineId: "m1", runtime: "claude" },+ { botUserId: "bot_flaky", name: "b", machineId: "m2", runtime: "codex" },+ { botUserId: "bot_ok_2", name: "c", machineId: "m3", runtime: "claude" },+ ])+ mockCanBotReadWakeScope.mockImplementation(async (_db: unknown, botId: string) => {+ if (botId === "bot_flaky") throw new Error("d1 blip")+ return true+ })++ await enqueueBotWakes({+ recipients: ["bot_ok_1", "bot_flaky", "bot_ok_2"],+ channelId: "c1",+ messageRow,+ })++ expect(mockQueueSend).toHaveBeenCalledTimes(1)+ const [payloads] = mockQueueSend.mock.calls[0]!+ expect(payloads).toEqual([+ { messageId: "msg_1", botUserId: "bot_ok_1" },+ { messageId: "msg_1", botUserId: "bot_ok_2" },+ ])+ })++ it("no-ops when every candidate fails the gate — never picks a transport", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_a", name: "a", machineId: "m1", runtime: "claude" },+ { botUserId: "bot_b", name: "b", machineId: "m2", runtime: "codex" },+ ])+ mockCanBotReadWakeScope.mockResolvedValue(false)++ await enqueueBotWakes({ recipients: ["bot_a", "bot_b"], channelId: "c1", messageRow })++ expect(mockQueueSend).not.toHaveBeenCalled()+ expect(mockCreateQueueWakeTransport).not.toHaveBeenCalled()+ })+it("chunks into 100-candidate slices for large fanouts", async () => {const candidates = Array.from({ length: 250 }, (_, i) => ({botUserId: `bot${i}`,diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.tsindex afb2857f8..3db37f704 100644--- a/src/web/src/lib/community/wake-producer.ts+++ b/src/web/src/lib/community/wake-producer.ts@@ -100,7 +100,35 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v})if (candidates.length === 0) return- const payloads: WakePayload[] = candidates.map((c) => ({+ // Defense-in-depth visibility + participation gate. `findWakeCandidates`+ // starts from the fanout recipient set, which for well-behaved audience+ // helpers already excludes non-visible / non-participating bots — but a+ // future regression in a helper (or a new caller) could leak a bot in.+ // Re-check per candidate against the same wake gate the consumer uses+ // (`canBotReadWakeScope`), so this producer path is belt-and-suspenders.+ //+ // `allSettled` (not `all`): a transient D1 blip on ONE candidate's gate+ // check must not collapse the whole batch's enqueue. Rejected legs are+ // treated as "gate indeterminate" — we drop just that candidate (the+ // queue consumer re-runs the same gate at consume time anyway) rather+ // than losing every wake for the message.+ const scope: { channelId?: string; dmConversationId?: string } = channelId+ ? { channelId }+ : { dmConversationId: dmConversationId! }+ const gateResults = await Promise.allSettled(+ candidates.map((c) => queries.communityMember.canBotReadWakeScope(db, c.botUserId, scope))+ )+ const gated = candidates.filter((c, i) => {+ const r = gateResults[i]!+ if (r.status === "rejected") {+ log.warn("wake_gate_check_failed", { botUserId: c.botUserId, err: String(r.reason) })+ return false+ }+ return r.value+ })+ if (gated.length === 0) return++ const payloads: WakePayload[] = gated.map((c) => ({messageId: messageRow.id,botUserId: c.botUserId,}))diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex f681dafc6..f1e32b04d 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -60,6 +60,101 @@ describe("ws-do router", () => {})})+ describe("POST /internal/broadcast-bot-audit-event", () => {+ it("forwards a well-formed audit event to the owner's user-DO with the community:bot.audit_event shape", async () => {+ doMock.stubFetch.mockResolvedValue(new Response("ok"))+ const payload = {+ botId: "bot_1",+ ownerUserId: "owner_1",+ id: "evt_1",+ kind: "wake_trigger",+ payload: {+ messageId: "msg_1",+ channel: "/srv_1/general",+ seq: 7,+ senderId: "u_human",+ senderHandle: "@gustavo#0042",+ reason: "unread",+ },+ createdAt: "2026-07-23T00:00:00.000Z",+ }+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ })++ const res = await handler.fetch(req, env as any)++ expect(res.status).toBe(204)+ expect(doMock.idFromName).toHaveBeenCalledWith("user:owner_1")+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request+ expect(stubReq.url).toBe("http://internal/broadcast")+ const body = JSON.parse(await stubReq.text()) as Record<string, unknown>+ // Matches the shape ws-durable.ts emits for daemon-originating frames.+ expect(body.type).toBe("community:bot.audit_event")+ expect(body.botId).toBe("bot_1")+ expect(body.id).toBe("evt_1")+ expect(body.kind).toBe("wake_trigger")+ expect(body.createdAt).toBe(payload.createdAt)+ expect(body.payload).toEqual(payload.payload)+ })++ it("400s on invalid JSON", async () => {+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {+ method: "POST",+ body: "not json",+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(400)+ })++ it("400s on a payload missing required fields", async () => {+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ botId: "bot_1" }),+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(400)+ })++ it("400s on an unknown kind (rejects browser-untypeable rows at the boundary)", async () => {+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ botId: "bot_1",+ ownerUserId: "owner_1",+ id: "evt_1",+ kind: "some_future_kind",+ payload: {},+ createdAt: "2026-07-23T00:00:00.000Z",+ }),+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(400)+ })++ it("503s and never broadcasts when the DO fetch throws", async () => {+ doMock.stubFetch.mockRejectedValue(new Error("do down"))+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ botId: "bot_1",+ ownerUserId: "owner_1",+ id: "evt_1",+ kind: "wake_trigger",+ payload: {},+ createdAt: "2026-07-23T00:00:00.000Z",+ }),+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(503)+ })+ })+describe("POST /presence/users", () => {it("empty ids array short-circuits and performs zero DO fetches", async () => {const req = new Request("http://localhost/presence/users", {diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.tsindex 3228a07ae..7d5218ad7 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -75,6 +75,85 @@ export default {return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body, duplex: "half" } as RequestInit))}+ // POST /internal/broadcast-bot-audit-event — the wake-worker calls this+ // right after `insertBotAuditWakeTrigger` writes a `wake_trigger` row, so+ // the owner's UI receives the audit-event WS frame in the same beat as+ // the D1 insert (matching the daemon-originating path at+ // `ws-durable.ts:906-915`). Reachable ONLY via service binding+ // (`WS_DO_WORKER: Fetcher` in wake-worker's wrangler.toml), so origin is+ // implicitly restricted to same-project workers.+ //+ // Body: { botId, ownerUserId, id, kind, payload, createdAt, sessionId?,+ // launchId? }. Everything except sessionId/launchId is required; the+ // handler validates shape and 400s on anything malformed, then forwards+ // the same `community:bot.audit_event` frame shape used at+ // `ws-durable.ts:906-915` to `broadcast/user/<ownerUserId>`.+ if (url.pathname === "/internal/broadcast-bot-audit-event" && request.method === "POST") {+ let body: unknown+ try {+ body = await request.json()+ } catch {+ return new Response("invalid json", { status: 400 })+ }+ const b = (body ?? {}) as {+ botId?: unknown+ ownerUserId?: unknown+ id?: unknown+ kind?: unknown+ payload?: unknown+ createdAt?: unknown+ sessionId?: unknown+ launchId?: unknown+ }+ if (+ typeof b.botId !== "string" ||+ typeof b.ownerUserId !== "string" ||+ typeof b.id !== "string" ||+ typeof b.kind !== "string" ||+ typeof b.createdAt !== "string" ||+ b.payload === undefined+ ) {+ return new Response("invalid payload", { status: 400 })+ }+ // Guard against a future caller shape-drift: only the four kinds the+ // browser understands are broadcastable. An unknown `kind` reaches the+ // owner UI as an untyped row (bot-activity-row.tsx renders it verbatim),+ // so reject at the boundary instead.+ const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger"])+ if (!AUDIT_KINDS.has(b.kind)) {+ return new Response("invalid kind", { status: 400 })+ }+ const frame = {+ type: "community:bot.audit_event",+ botId: b.botId,+ id: b.id,+ kind: b.kind,+ payload: b.payload,+ sessionId: typeof b.sessionId === "string" ? b.sessionId : null,+ launchId: typeof b.launchId === "string" ? b.launchId : null,+ createdAt: b.createdAt,+ }+ const doId = env.WS_DO.idFromName("user:" + b.ownerUserId)+ const stub = env.WS_DO.get(doId)+ try {+ await stub.fetch(+ new Request("http://internal/broadcast", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(frame),+ }),+ )+ } catch (err) {+ log.warn("internal_broadcast_bot_audit_event_failed", {+ err: String(err),+ ownerUserId: b.ownerUserId,+ botId: b.botId,+ })+ return new Response("broadcast failed", { status: 503 })+ }+ return new Response(null, { status: 204 })+ }+// Bulk presence: fan out one DO fetch per id and return the online subset.// Consolidates web-worker subrequest budget to a single call regardless of// membership size.