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
refactor(shared): declarative channel-type trait model + CLI createPost
Genere2ebf2158a18
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex 221a8e0e1..8fba5baa3 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -27,6 +27,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {inboxSnapshot: async () => ({ rows: [], pendingChannels: 0, pendingMessages: 0 }),ack: async () => undefined,send: async () => ({ state: "sent", message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" } }),+ createPost: async () => ({ ref: "/s/c/post", name: "post", seq: 1 }),read: async () => ({ items: [], hasMore: false }),resolve: async () => null,listMembers: async () => ({ members: [] }),@@ -357,6 +358,74 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {});});+describe("message post", () => {+ const okRes = { ref: "/s/ideas/my-post", name: "my-post", seq: 1 };++ it("forwards forum ref + title + body, returns the canonical post ref", async () => {+ const postSpy = vi.fn(async () => okRes);+ setApiForTesting(stubApi({ createPost: postSpy }));+ await main(["message", "post", "--target", "/s/ideas", "--title", "My Post", "--text", "hello"]);+ const env = parseEnvelope(cap.lines());+ expect(env.success.posted).toBe("/s/ideas/my-post");+ expect(postSpy).toHaveBeenCalledWith(+ expect.objectContaining({ forum: "/s/ideas", title: "My Post", content: { text: "hello" } }),+ );+ });++ it("requires --target (forum ref), never calling createPost", async () => {+ const postSpy = vi.fn(async () => okRes);+ setApiForTesting(stubApi({ createPost: postSpy }));+ await main(["message", "post", "--title", "My Post", "--text", "hi"]);+ const env = parseEnvelope(cap.lines());+ expect(env.error).toContain("--target");+ expect(postSpy).not.toHaveBeenCalled();+ });++ it("requires --title, never calling createPost", async () => {+ const postSpy = vi.fn(async () => okRes);+ setApiForTesting(stubApi({ createPost: postSpy }));+ await main(["message", "post", "--target", "/s/ideas", "--text", "hi"]);+ const env = parseEnvelope(cap.lines());+ expect(env.error).toContain("--title");+ expect(postSpy).not.toHaveBeenCalled();+ });++ it("requires text OR an attachment (empty opener → error, never calls createPost)", async () => {+ const postSpy = vi.fn(async () => okRes);+ setApiForTesting(stubApi({ createPost: postSpy }));+ await main(["message", "post", "--target", "/s/ideas", "--title", "My Post"]);+ const env = parseEnvelope(cap.lines());+ expect(env.error).toContain("--text");+ expect(postSpy).not.toHaveBeenCalled();+ });++ it("allows an attachment-only post (no --text)", async () => {+ const postSpy = vi.fn(async () => okRes);+ setApiForTesting(stubApi({ createPost: postSpy }));+ await main(["message", "post", "--target", "/s/ideas", "--title", "My Post", "--attachment", "att_1"]);+ const env = parseEnvelope(cap.lines());+ expect(env.success.posted).toBe("/s/ideas/my-post");+ expect(postSpy).toHaveBeenCalledWith(expect.objectContaining({ attachments: ["att_1"] }));+ });++ it("attaches a nonce and reuses it across a transient-5xx retry (no duplicate post)", async () => {+ let calls = 0;+ const nonces: (string | undefined)[] = [];+ const postSpy = vi.fn(async (req: { nonce?: string }) => {+ nonces.push(req.nonce);+ calls++;+ if (calls === 1) throw new Error("upstream returned 502 with non-JSON body from /api/createPost");+ return okRes;+ });+ setApiForTesting(stubApi({ createPost: postSpy }));+ await main(["message", "post", "--target", "/s/ideas", "--title", "My Post", "--text", "hi"]);+ const env = parseEnvelope(cap.lines());+ expect(env.success.posted).toBe("/s/ideas/my-post");+ expect(calls).toBe(2);+ expect(nonces[0]).toBe(nonces[1]); // same nonce → server dedupes, no second post+ });+});+describe("server list", () => {it("prints {success:{servers:[...]}} from a stubbed listServers", async () => {setApiForTesting(diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex ad5be2fa4..328163250 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -311,6 +311,81 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {return { sent: `${res.message.channel}${res.message.seq}` };}+/**+ * createPost with the SAME bounded same-nonce transient retry as `sendWithRetry`+ * — createPost also carries a `nonce` the server dedupes on, so a+ * committed-but-response-lost create is absorbed here (server returns the+ * canonical post) instead of surfacing as an error the agent would re-run into a+ * second post. Only transient transport errors retry; a thrown 4xx (bad forum /+ * unauthorized / empty) passes straight through.+ */+async function createPostWithRetry(+ api: ServerApi,+ req: Parameters<ServerApi["createPost"]>[0],+): Promise<Awaited<ReturnType<ServerApi["createPost"]>>> {+ const MAX_ATTEMPTS = 4;+ const BASE_DELAY_MS = 150;+ const MAX_DELAY_MS = 2000;+ let lastErr: unknown;+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {+ try {+ return await api.createPost(req);+ } catch (err) {+ lastErr = err;+ if (!isTransientSendError(err) || attempt === MAX_ATTEMPTS - 1) throw err;+ const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);+ await new Promise((r) => setTimeout(r, cap));+ }+ }+ throw lastErr;+}++async function cmdMessagePost(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const agent = agentId(opts);+ const forum = opts.target as string;+ if (!forum) throw new CliError("message post: --target <forum-ref> is required (e.g. /demo/ideas)");+ const title = opts.title as string | undefined;+ if (!title || title.trim().length === 0) throw new CliError("message post: --title <name> is required");++ // Body: same --text/--file handling as `message send` (file = literal bytes,+ // never escape-decode; --text decodes shell escapes).+ let text: string | undefined;+ const fileFlag = opts.file as string | undefined;+ const textFlag = opts.text as string | undefined;+ if (fileFlag) {+ const fs = await import("fs");+ if (!fs.existsSync(fileFlag)) throw new CliError(`message post: file not found: ${fileFlag}`);+ text = fs.readFileSync(fileFlag, "utf8").trim();+ } else if (typeof textFlag === "string") {+ text = decodeTextEscapes(textFlag);+ }++ const attachmentIds = Array.isArray(opts.attachment) ? (opts.attachment as string[]) : [];+ const hasText = typeof text === "string" && text.trim().length > 0;+ // Opener contract: a post needs text OR at least one attachment (attachment-+ // only is a legitimate post — same as a forum post's first message).+ if (!hasText && attachmentIds.length === 0) {+ throw new CliError("message post: --text <text>, --file <path>, or --attachment <id> is required");+ }++ // One idempotency nonce per logical create, reused across sendWithRetry's+ // internal attempts (server dedupes on author+nonce) — same duplicate-guard+ // rationale as `message send`.+ const nonce = randomUUID();+ const res = await createPostWithRetry(api, {+ agentId: agent,+ forum,+ title: title.trim(),+ content: { text: text ?? "" },+ attachments: attachmentIds.length > 0 ? attachmentIds : undefined,+ nonce,+ });+ // Surface the canonical /server/forum/<real-slug> ref — the bot's handle for+ // the just-created post, usable directly as a `--target`.+ return { posted: res.ref };+}+async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const target = opts.target as string;@@ -591,6 +666,28 @@ function buildProgram(): Command {printEnvelope({ success: result });});+ message+ .command("post")+ .description("create a new forum post in a forum")+ .option("--target <forum-ref>", "the forum to post in (path-style ref, e.g. /demo/ideas)")+ .option("--title <name>", "the post title (its slug becomes the post's address)")+ .option("--text <text>", "inline post body (short)")+ .option("--file <path>", "read post body from a file (long)")+ .option(+ "-a, --attachment <id>",+ "attach an uploaded file by id (repeatable — order = body order)",+ (v, prev: string[] = []) => [...prev, v],+ [] as string[],+ )+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdMessagePost({ ...globalOpts, ...localOpts });+ printEnvelope({ success: result });+ });+message.command("emoji").description("react to a message with a single emoji")diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex bba7e248b..fa07e1fb3 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -31,6 +31,8 @@ import type {AckRequest,SendRequest,SendResponse,+ CreatePostRequest,+ CreatePostResponse,ReadRequest,ResolveRequest,ListChannelsRequest,@@ -245,6 +247,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {inboxSnapshot: (r: { agentId: AgentId }) => call<InboxSnapshot>("inboxSnapshot", r),ack: (r: AckRequest) => call<void>("ack", r),send: (r: SendRequest) => call<SendResponse>("send", r),+ createPost: (r: CreatePostRequest) => call<CreatePostResponse>("createPost", r),read: (r: ReadRequest) => call<Page<Message>>("read", r),resolve: (r: ResolveRequest) => call<{ message: Message }>("resolve", r),listMembers: (r: { agentId: AgentId; server: string }) => call<{ members: ServerMember[] }>("listMembers", r),diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex 0ab4b7986..10ae73888 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -239,7 +239,10 @@ export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (_method, pathnam// attach-only without granting `send`/`read`.if (pathname.includes("/attachment")) return "attach";if (pathname.includes("/friendRequest") || pathname.includes("/listFriends")) return "friend";- if (pathname.includes("/send") || pathname.includes("/reactAdd")) return "send";+ // `/createPost` is a create/write (a new forum post + its first message), same+ // write class as `/send`/`/reactAdd` — it needs the `send` capability so a+ // read-only or attach-only voucher can't create content.+ if (pathname.includes("/send") || pathname.includes("/reactAdd") || pathname.includes("/createPost")) return "send";if (pathname.includes("/history") || pathname.includes("/search") || pathname.includes("/inbox"))return "read";if (pathname.includes("/server") || pathname.includes("/channel")) return "server";diff --git a/src/daemon/src/runtime/runtimeSession.test.ts b/src/daemon/src/runtime/runtimeSession.test.tsindex 5eee4021d..87dabc82b 100644--- a/src/daemon/src/runtime/runtimeSession.test.ts+++ b/src/daemon/src/runtime/runtimeSession.test.ts@@ -54,6 +54,12 @@ afterEach(() => {describe("ChildProcessRuntimeSession — real subprocess exit fills the physical fact (T1 red-line-5b)", () => {it("a real SIGKILLed subprocess emits exit with signal=SIGKILL, null code, reason=runtime_exit", async () => {+ // POSIX-only: Windows has no real signals — `process.kill(pid, "SIGKILL")`+ // terminates the child but Node reports `code=1, signal=null`, so the+ // `signal === "SIGKILL"` contract this asserts can't hold there. Skip on+ // win32 (same platform-guard as killTree.test.ts). The clean-exit sibling+ // below (code=0/signal=null) is cross-platform and still runs.+ if (process.platform === "win32") return;const session = new ChildProcessRuntimeSession(realSpawnDriver(), minimalCtx());const exitInfo = await new Promise<{ code: number | null; signal: string | null; reason?: string }>((resolve) => {diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 72872b3ad..0b343e24c 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -43,6 +43,8 @@ export type {AckRequest,SendRequest,SendResponse,+ CreatePostRequest,+ CreatePostResponse,CommunityAgentReactAddResponse,ReadRequest,ResolveRequest,diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 2469673dc..cc9c57113 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -24,7 +24,8 @@import { z } from "zod";import type { RuntimeConfig } from "./runtime-config";-import type { ChannelType } from "./utils/community-roles";+import type { ChannelType, StoredChannelType } from "./utils/community-roles";+import { CHANNEL_TRAITS } from "./utils/community-roles";/* ------------------------------------------------------------------ *//* Identifiers */@@ -377,6 +378,35 @@ export interface CommunityAgentReactAddResponse {duplicate?: boolean;}+/**+ * Create a new forum post (`alook message post`). `forum` is a forum REF+ * (`/server/forum`), resolved server-side (bots hold refs, not ids — same reason+ * `send` takes a ref). `title` is the raw human title; its slug becomes the+ * post's addressing name. Content follows the forum-post opener contract: text+ * OR at least one attachment. `attachments` are pending ids the bot uploaded+ * bound to the FORUM (the post channel doesn't exist at upload time).+ */+export interface CreatePostRequest {+ agentId: AgentId;+ forum: ChannelRef;+ title: string;+ content: MessageContent;+ attachments?: string[];+ /** Idempotency key — reused across retries, server dedupes (same as `send`). */+ nonce?: string;+}++/**+ * The created post's canonical address. `ref` is the round-trippable+ * `/server/forum/<real-slug>` (the slug after create-time dedupe/bump) — the bot+ * hands it straight back as a target. `seq` is the body (first-message) seq.+ */+export interface CreatePostResponse {+ ref: ChannelRef;+ name: string;+ seq: Seq;+}+export interface ReadRequest {agentId: AgentId;channel: ChannelRef;@@ -532,6 +562,9 @@ export interface ServerApi {/** Send a message to a channel ref. May be held by the freshness guard. */send(req: SendRequest): Promise<SendResponse>;+ /** Create a new forum post in a forum ref, with its body as the first message. */+ createPost(req: CreatePostRequest): Promise<CreatePostResponse>;+/** Read history for a channel with seq-anchored pagination. */read(req: ReadRequest): Promise<Page<Message>>;@@ -1195,6 +1228,72 @@ export function formatRef(p: {return `${base}/#${p.threadRootSeq}#${p.seq}`;}+/**+ * The single canonical-ref EMITTER (trait model B1, red-line ①). Every place+ * that turns a stored channel into its addressable `ChannelRef` — the agent+ * inbox's `resolveScopeRefs` (per-message + per-scope refs), the wake notice's+ * `resolveUnreadNoticeChannel`, `listChannels` — used to hand-pick the+ * `formatRef` shape by re-branching on the channel's type, so the SAME+ * type→shape mapping lived in multiple copies and could drift (a post emitted+ * one way here, another way there → a ref that won't round-trip). This funnels+ * all of them through ONE dispatch keyed on `CHANNEL_TRAITS[type].addressing`,+ * so a channel type has exactly one addressing identity by construction.+ *+ * `scope` is the already-resolved context each caller gathers (server/parent+ * names, the DM peer segment, the thread root seq) — this function does no I/O,+ * it only selects the ref SHAPE from the addressing trait. A caller that can't+ * supply the field an addressing value needs (e.g. a thread with no resolvable+ * root seq) passes it `undefined` and gets `null` back, so the caller keeps its+ * existing "unresolvable → fallback/skip" handling rather than emitting a bogus+ * ref. The exhaustive `switch` (with the `never` tail) forces every new+ * addressing value to be handled here or the build fails.+ */+export type CanonicalRefScope = {+ type: StoredChannelType;+ /** Server display name (channel arm). Absent/irrelevant for a DM. */+ serverName?: string;+ /** The channel's own stored name — the top-level channel or the post slug. */+ name?: string;+ /** Parent forum/channel display name — for by-child-name / by-root-seq. */+ parentName?: string;+ /** Thread root message seq — for by-root-seq. */+ rootSeq?: Seq;+ /** DM peer handle segment (`name#0042`) — for by-peer-identity. */+ peerSegment?: string;+};++export function formatCanonicalRef(scope: CanonicalRefScope): ChannelRef | null {+ const addressing = CHANNEL_TRAITS[scope.type].addressing;+ switch (addressing) {+ case "by-server-name": {+ // Top-level channel/forum: `/server/<name>`.+ if (scope.serverName === undefined || scope.name === undefined) return null;+ return formatRef({ server: scope.serverName, channel: scope.name });+ }+ case "by-child-name": {+ // Forum post: `/server/<forum>/<post-slug>` — anchored on its own name+ // under the parent forum.+ if (scope.serverName === undefined || scope.parentName === undefined || scope.name === undefined) return null;+ return formatRef({ server: scope.serverName, channel: scope.parentName, childChannelName: scope.name });+ }+ case "by-root-seq": {+ // Thread: `/server/<parent-channel>/#<rootSeq>`.+ if (scope.serverName === undefined || scope.parentName === undefined || scope.rootSeq === undefined) return null;+ return formatRef({ server: scope.serverName, channel: scope.parentName, threadRootSeq: scope.rootSeq });+ }+ case "by-peer-identity": {+ // DM: `/.dm/<peer#0042>`.+ if (scope.peerSegment === undefined) return null;+ return formatRef({ server: DM_SERVER, channel: scope.peerSegment });+ }+ default: {+ // Exhaustiveness: a new AddressingTrait value must add a case above.+ const _never: never = addressing;+ return _never;+ }+ }+}+/** "#12" → 12 ; "12" → 12. */export function parseSeq(s: string): Seq {const n = Number(s.startsWith("#") ? s.slice(1) : s);diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 83674b068..ef86d1c64 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -61,6 +61,16 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(name: text("name"),type: text("type").notNull().default("text"),topic: text("topic").default(""),+ // Display-only original title of a forum post, captured verbatim BEFORE+ // `slugify` lossily derives `name` (the addressing slug). `name` stays the+ // single addressing identity; `display_title` only preserves the+ // human-readable original ("Q3 planning / roadmap", not+ // "q3-planning-roadmap") so a future "title as body-heading" render can use+ // it. NEVER an addressing axis: no resolve-by-name reads it, no unique index,+ // duplicates are legal, and it does NOT participate in slug dedupe/bump.+ // Nullable — only forum_post CREATE writes it; threads / top-level channels /+ // legacy rows leave it null.+ displayTitle: text("display_title"),position: integer("position").default(0),forumTags: text("forum_tags"), // JSONparentChannelId: text("parent_channel_id").references(() => communityChannel.id, {@@ -83,6 +93,21 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(uniqueIndex("idx_channel_server_name").on(t.serverId, t.name).where(sql`parent_channel_id IS NULL`),+ // Partial unique — a forum post's slug (`name`) is its addressing anchor+ // (`/server/forum/<slug>`), so it must be unique WITHIN its parent forum or+ // resolve-by-name goes ambiguous and read/send/ack on the post break. Scoped+ // to `type='forum_post'` ONLY (NOT all children): a thread's name is derived+ // from its root message and is display-only — threads address by+ // `parent_message_id` (uq_community_channel_parent_message, 0052), so+ // duplicate thread names are legal. Source of truth:+ // migration 0078_forum_post_unique_name.sql. Case-sensitive (plain `name`) to+ // match the forum-post resolver + dedupe (getChildChannelByName /+ // dedupeChildChannelSlug use plain `eq`), so the DB ruler folds identically+ // to resolution (the index/resolver alignment migration 0075 established for+ // top-level names). This is what makes pure-create's bump-retry race-safe.+ uniqueIndex("idx_forum_post_parent_name")+ .on(t.parentChannelId, t.name)+ .where(sql`type = 'forum_post'`),]);diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex 151129c81..484da6881 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -22,9 +22,8 @@ import {import { user } from "../../schema";import type { Database } from "../../index";import {- formatRef,+ formatCanonicalRef,formatSeq,- DM_SERVER,type AgentAttachmentRef,type Message,type MessageContent,@@ -36,7 +35,7 @@ import { formatHandle } from "../../../lib/discriminator";import { listVisibleChannelIdsForUser } from "./channel";import { listParticipatingThreadIds } from "./thread";import { getMessagesByIdsInScope, type MessageScope } from "./message";-import { isThread, isForumPost } from "../../../utils/community-roles";+import { reachIsParticipantSet, type StoredChannelType } from "../../../utils/community-roles";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";type RawAgentMessage = {@@ -179,47 +178,57 @@ async function resolveScopeRefs(const out = new Map<string, ScopeInfo>();for (const ch of channels) {- if (ch.type === "dm") {+ // Ref SHAPE is chosen by the single canonical-ref emitter, keyed on the+ // channel type's addressing trait (B1, red-line ①) — this loop only gathers+ // the resolved context each addressing value may need (server/parent names,+ // DM peer segment, thread root seq). The `isThread`/`isDm` flags are a+ // separate presentation concern (inbox-row flags) and stay type-derived.+ const storedType = (ch.type ?? "text") as StoredChannelType;+ const isDm = storedType === "dm";+ let peerSegment: string | undefined;+ if (isDm) {const peerId = peerByDmChannel.get(ch.id);const peer = peerId ? dmPeerById.get(peerId) : undefined;- const peerSegment = peer ? formatHandle(peer.name, peer.discriminator) : peerId || "unknown";- out.set(ch.id, {- ref: formatRef({ server: DM_SERVER, channel: peerSegment }),- isThread: false,- isDm: true,- });- continue;+ peerSegment = peer ? formatHandle(peer.name, peer.discriminator) : peerId || "unknown";}const serverName = ch.serverId ? (serverNameById.get(ch.serverId) ?? ch.serverId) : "unknown";- if (ch.parentChannelId && ch.parentMessageId) {- const parent = parentChannelById.get(ch.parentChannelId);- const rootSeq = parentSeqById.get(ch.parentMessageId);- if (parent && rootSeq !== undefined) {- out.set(ch.id, {- ref: formatRef({ server: serverName, channel: parent.name, threadRootSeq: rootSeq }),- isThread: true,- isDm: false,- });- continue;- }- }- // Forum post: a `forum_post` child channel has a parent forum but NO- // parentMessageId (unlike a thread), so it's anchored by its own name under- // the forum: `/server/<forum>/<post>`. Without this it fell through to the- // top-level fallback below (`/server/<post-name>`), which the name resolver- // — top-level only — can never parse back, 404ing send/read/ack on the post.- if (ch.type === "forum_post" && ch.parentChannelId) {- const parent = parentChannelById.get(ch.parentChannelId);- if (parent) {- out.set(ch.id, {- ref: formatRef({ server: serverName, channel: parent.name, childChannelName: ch.name }),- isThread: false,- isDm: false,- });- continue;- }- }- out.set(ch.id, { ref: formatRef({ server: serverName, channel: ch.name }), isThread: false, isDm: false });+ const parent = ch.parentChannelId ? parentChannelById.get(ch.parentChannelId) : undefined;+ const rootSeq = ch.parentMessageId ? parentSeqById.get(ch.parentMessageId) : undefined;+ // A thread and a forum_post are both `parent`-anchored children, but only a+ // thread carries a `parentMessageId` (→ root seq). Distinguish by whether a+ // root seq resolved so we hand the emitter the right addressing type: a+ // child WITH a root seq is a thread, WITHOUT is a forum_post.+ const emitType: StoredChannelType =+ ch.parentChannelId && ch.parentMessageId && parent && rootSeq !== undefined+ ? "thread"+ : ch.parentChannelId && storedType === "forum_post" && parent+ ? "forum_post"+ : storedType;+ const ref = formatCanonicalRef({+ type: emitType,+ serverName,+ name: ch.name,+ parentName: parent?.name,+ rootSeq,+ peerSegment,+ });+ // Degraded channel (emitter null — a required addressing field didn't+ // hydrate, e.g. a thread missing its parent/root): skip its ENTRY in this+ // channelId→ScopeInfo map. This is safe for never-drop: the map is looked+ // up per message row by the two callers as `scope?.ref ?? "/unknown/<id>"`,+ // which already keep the row and emit the explicit "/unknown/" sentinel when+ // the scope is absent. So a missing entry funnels into that existing+ // unresolvable path — the message row survives (nothing is dropped from the+ // page) and its channel reads as an explicit "unresolvable" sentinel, NOT a+ // hand-built top-level ref that looks addressable but 404s. This removes the+ // second place the top-level ref shape was built (B1.1): the shape now lives+ // ONLY in the emitter.+ if (ref === null) continue;+ out.set(ch.id, {+ ref,+ isThread: emitType === "thread",+ isDm,+ });}return out;}@@ -360,8 +369,17 @@ export async function resolveUnreadNoticeChannel(const ch = rows[0];if (!ch) return null;+ // Same single canonical-ref emitter as `resolveScopeRefs` (B1): this function+ // does the I/O to gather the addressing context (DM peer, thread parent+root,+ // forum parent, server name), then hands it to `formatCanonicalRef` to pick+ // the ref SHAPE from the addressing trait. Its stricter no-placeholder+ // contract (see doc comment: a missing field is `notice_channel_unresolvable`,+ // never a bogus ref) matches the emitter's `null`-on-missing-field return —+ // so any unresolved piece below returns null exactly as before.+ const storedType = (ch.type ?? "text") as StoredChannelType;+// DM channel — the notice ref is `/.dm/<peer#0042>`, the OTHER access member.- if (ch.type === "dm") {+ if (storedType === "dm") {const peerRows = await db.select({ name: user.name, discriminator: user.discriminator }).from(communityChannelMember)@@ -375,11 +393,8 @@ export async function resolveUnreadNoticeChannel().limit(1);const peer = peerRows[0];- // A wake command's notice channel must NEVER be a placeholder (see this- // function's doc comment) — a peer that no longer resolves is- // `notice_channel_unresolvable`, not a bare-peerId ref.if (!peer) return null;- return formatRef({ server: DM_SERVER, channel: formatHandle(peer.name, peer.discriminator) });+ return formatCanonicalRef({ type: "dm", peerSegment: formatHandle(peer.name, peer.discriminator) });}if (ch.parentChannelId && ch.parentMessageId) {@@ -400,14 +415,14 @@ export async function resolveUnreadNoticeChannel(if (!parent || !root || !parent.serverId) return null;const serverName = await getServerName(db, parent.serverId);if (!serverName) return null;- return formatRef({ server: serverName, channel: parent.name, threadRootSeq: root.seq });+ return formatCanonicalRef({ type: "thread", serverName, parentName: parent.name, rootSeq: root.seq });}// Forum post: parent forum but no parentMessageId — anchor by the post's own// name under the forum (`/server/<forum>/<post>`). A missing/serverless parent// resolves to null (notice_channel_unresolvable) rather than a bogus ref, per// this function's no-placeholder contract.- if (ch.type === "forum_post" && ch.parentChannelId) {+ if (storedType === "forum_post" && ch.parentChannelId) {const parentRows = await db.select({ name: communityChannel.name, serverId: communityChannel.serverId }).from(communityChannel)@@ -417,13 +432,13 @@ export async function resolveUnreadNoticeChannel(if (!parent || !parent.serverId) return null;const serverName = await getServerName(db, parent.serverId);if (!serverName) return null;- return formatRef({ server: serverName, channel: parent.name, childChannelName: ch.name });+ return formatCanonicalRef({ type: "forum_post", serverName, parentName: parent.name, name: ch.name });}if (!ch.serverId) return null;const serverName = await getServerName(db, ch.serverId);if (!serverName) return null;- return formatRef({ server: serverName, channel: ch.name });+ return formatCanonicalRef({ type: storedType, serverName, name: ch.name ?? undefined });}async function getServerName(db: Database, serverId: string): Promise<string | null> {@@ -503,8 +518,12 @@ async function listAgentAllowedChannelIds(db: Database, botUserId: string): Prom))).flat();+ // Participation-narrowed types = reach `participant-set` (B2 single source),+ // not a re-derived `isThread || isForumPost`. A participant-set channel is+ // deliverable to the bot only if it holds a notify row — the SAME reach value+ // the fan-out recipient set and the send-path enroll key on.const narrowIds = typeRows- .filter((r) => isThread(r.type) || isForumPost(r.type))+ .filter((r) => reachIsParticipantSet(r.type)).map((r) => r.id);const participating =narrowIds.length > 0@@ -666,7 +685,12 @@ export async function hasDeliverableUnreadForAgentScope(.where(eq(communityChannel.id, channelId)).limit(1);const type = typeRows[0]?.type;- if (isThread(type) || isForumPost(type)) {+ // Same reach `participant-set` narrowing as `listAgentAllowedChannelIds` — via+ // the SAME reachIsParticipantSet source (B2). This gate and the pull's allowed+ // set MUST agree on which channels need a notify row to be deliverable, or the+ // gate counts backlog the pull never delivers (the send-alignment deadlock).+ // Reading one shared reach value is what makes that agreement structural.+ if (reachIsParticipantSet(type)) {const participating = await listParticipatingThreadIds(db, [channelId], botUserId);if (participating.length === 0) return false;}diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex 6672bbc73..a71ff1815 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -9,7 +9,7 @@ import {import type { Database } from "../../index";import { PARTICIPANT_SOURCE } from "../../../constants/community";import { createLogger } from "../../../logger";-import { canManageServer, canSeePrivateChannel } from "../../../utils/community-roles";+import { canManageServer, canSeePrivateChannel, visibilityIsDmParticipant } from "../../../utils/community-roles";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";// Module-level logger — one tag per shared query module.@@ -72,6 +72,9 @@ export async function createChannel(parentChannelId?: string | null;creatorId?: string | null;parentMessageId?: string | null;+ // Display-only pre-slugify original title (forum_post CREATE only). Absent+ // for every other create path — leaves the column null.+ displayTitle?: string | null;}) {const rows = await db@@ -85,6 +88,7 @@ export async function createChannel(parentChannelId: data.parentChannelId ?? null,creatorId: data.creatorId ?? null,parentMessageId: data.parentMessageId ?? null,+ displayTitle: data.displayTitle ?? null,}).returning();return rows[0]!;@@ -126,16 +130,23 @@ export async function getChannelType(* predicate is in SQL, not a post-fetch check.*/export async function getChannelForMember(db: Database, channelId: string, userId: string) {- // DM (type=dm, server_id NULL) — Access resolution step 1: readable iff the- // user has a relation='access' member row. No server walk, no inheritance.+ // Fetch the channel row once, then dispatch on its VISIBILITY trait (B3): the+ // DM access rule (member-row check, no server walk, no inheritance) is keyed on+ // `visibilityIsDmParticipant`, the single source shared with+ // `resolveChannelAccessContext` — not a re-tested `type === 'dm'`. A missing+ // row → null (its 403/404 translation is the caller's surface-partitioned job,+ // untouched here).const dmRows = await db.select(CHANNEL_COLUMNS).from(communityChannel)- .where(and(eq(communityChannel.id, channelId), eq(communityChannel.type, "dm")))+ .where(eq(communityChannel.id, channelId)).limit(1);- if (dmRows[0]) {+ const dmRow = dmRows[0];+ if (dmRow && visibilityIsDmParticipant(dmRow.type)) {+ // DM (type=dm, server_id NULL) — readable iff the user has a+ // relation='access' member row.const isMember = await isChannelMember(db, channelId, userId, "access");- return isMember ? mapChannelRow(dmRows[0]) : null;+ return isMember ? mapChannelRow(dmRow) : null;}const rows = await db@@ -940,9 +951,11 @@ export async function resolveChannelAccessContext(const channel = mapChannelRow(target[0]!);const anchorId = channel.parentChannelId ?? channel.id;- // DM (type=dm, server_id NULL) — Access resolution step 1: access iff the- // user has a relation='access' member row. No server walk.- if (channel.type === "dm") {+ // DM (type=dm, server_id NULL) — access iff the user has a relation='access'+ // member row, no server walk. Keyed on the VISIBILITY trait (B3), the SAME+ // `visibilityIsDmParticipant` source `getChannelForMember` uses for its DM+ // path — the DM access rule now lives in one place, not re-tested per function.+ if (visibilityIsDmParticipant(channel.type)) {const isMember = await isChannelMember(db, channel.id, userId, "access");if (!isMember) return null;return {diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex 2096b2990..beeebd2b3 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -11,7 +11,7 @@ import {import { user } from "../../schema";import type { Database } from "../../index";import { listParticipatingThreadIds } from "./thread";-import { isThread, isForumPost } from "../../../utils/community-roles";+import { reachIsParticipantSet } from "../../../utils/community-roles";export interface UnreadChannelRow {channelId: string;@@ -157,7 +157,7 @@ export async function listUnreadChannels(// table (keyed by channel id), so one `listParticipatingThreadIds` covers// both. Top-level channels flow through the visibility path above unchanged.const notifyScopedIds = unread- .filter((r) => isThread(r.type) || isForumPost(r.type))+ .filter((r) => reachIsParticipantSet(r.type)).map((r) => r.channelId);const participatingIds =notifyScopedIds.length > 0@@ -167,7 +167,7 @@ export async function listUnreadChannels(return unread.filter((r) =>- (!isThread(r.type) && !isForumPost(r.type)) ||+ !reachIsParticipantSet(r.type) ||participatingIds.has(r.channelId),).map((r) => ({diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 7e01814b8..adfab30b8 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -7,7 +7,7 @@ import {MAX_MEMBERS_PAGE_SIZE,} from "../../../constants/community";import { escapeLikePattern } from "../../../utils/sql-like";-import { canSeePrivateChannel, isThread, isForumPost } from "../../../utils/community-roles";+import { canSeePrivateChannel, reachIsParticipantSet } from "../../../utils/community-roles";import { resolveChannelAccessContext } from "./channel";import { isThreadParticipant } from "./thread";@@ -458,7 +458,7 @@ export async function canBotReadWakeScope(// their participants (mirrors the human inbox's post-visibility filter).// Bots are just users; notify rows are added the same way (spoke /// mention / added), so the same predicate applies verbatim.- if (isThread(ctx.channel.type) || isForumPost(ctx.channel.type)) {+ if (reachIsParticipantSet(ctx.channel.type)) {return isThreadParticipant(db, scope.channelId, botUserId);}return true;diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 66732216f..21e217480 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -278,6 +278,7 @@ export {CommunityAgentReadRequestSchema,CommunityAgentResolveRequestSchema,CommunityAgentListChannelsRequestSchema,+ CommunityAgentCreatePostRequestSchema,CommunityAgentListMembersRequestSchema,CommunityAgentChannelMemberRequestSchema,CommunityAgentJoinServerRequestSchema,@@ -438,7 +439,8 @@ export type {HostBotAuditEventFrame,BotAuditEventPayload,} from "./community-cli-contract";-export { DM_SERVER, parseRef, formatRef, parseSeq, formatSeq } from "./community-cli-contract";+export { DM_SERVER, parseRef, formatRef, formatCanonicalRef, parseSeq, formatSeq } from "./community-cli-contract";+export type { CanonicalRefScope } from "./community-cli-contract";export type {ReasoningEffort,@@ -590,8 +592,25 @@ export {ROLES,ASSIGNABLE_ROLES,CHANNEL_TYPES,+ CHANNEL_TRAITS,+ channelReach,+ reachIsParticipantSet,+ isStoredChannelType,+ channelVisibility,+ visibilityIsDmParticipant,+ channelCreation,+} from "./utils/community-roles";+export type {+ CommunityRole,+ ChannelType,+ StoredChannelType,+ AssignableRole,+ AddressingTrait,+ VisibilityTrait,+ ReachTrait,+ CreationTrait,+ ChannelTraits,} from "./utils/community-roles";-export type { CommunityRole, ChannelType, StoredChannelType, AssignableRole } from "./utils/community-roles";export {isAccepted,isPending,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 0a6db95bf..13e539f9a 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1230,6 +1230,30 @@ export type CommunityAgentListChannelsRequest = z.infer<typeof CommunityAgentListChannelsRequestSchema>;+// Body for POST /api/community/createPost (`alook message post`). `forum` is a+// forum REF (`/server/forum`), resolved server-side like `send`'s `channel`.+// `title` is the raw human title — its slug becomes the post's addressing name,+// the original is captured into display_title (B4b). Content follows the same+// opener contract as a forum post: text OR at least one attachment (an+// attachment-only post is legitimate). `attachments` are pending ids the bot+// uploaded bound to the FORUM (the post channel doesn't exist at upload time).+export const CommunityAgentCreatePostRequestSchema = z+ .object({+ forum: z.string().min(1),+ title: z.string().min(1),+ content: CommunityAgentMessageContentSchema,+ attachments: z+ .array(z.string().min(1))+ .max(MAX_ATTACHMENTS_PER_MESSAGE)+ .default([]),+ nonce: z.string().min(1).max(128).optional(),+ })+ .refine(+ (d) => d.content.text.trim().length > 0 || d.attachments.length > 0,+ { message: "post must have text or attachments" }+ );+export type CommunityAgentCreatePostRequest = z.infer<typeof CommunityAgentCreatePostRequestSchema>;+export const CommunityAgentListMembersRequestSchema = z.object({server: z.string().min(1),});diff --git a/src/shared/src/utils/community-roles.test.ts b/src/shared/src/utils/community-roles.test.tsindex 257bf5c8c..0fee77bcf 100644--- a/src/shared/src/utils/community-roles.test.ts+++ b/src/shared/src/utils/community-roles.test.ts@@ -1,5 +1,15 @@import { describe, it, expect } from "vitest"-import { isMessageBearingSurface, isChannelType } from "./community-roles"+import {+ isMessageBearingSurface,+ isChannelType,+ CHANNEL_TRAITS,+ channelReach,+ reachIsParticipantSet,+ isStoredChannelType,+ channelVisibility,+ visibilityIsDmParticipant,+ type StoredChannelType,+} from "./community-roles"describe("isMessageBearingSurface", () => {it("is true for surfaces that bear messages: text, forum_post, thread, dm", () => {@@ -29,3 +39,104 @@ describe("isChannelType (creatable top-level types)", () => {expect(isChannelType("dm")).toBe(false)})})++// B0 trait table — lock each type's trait values to today's hand-branched+// behavior (the assignments Ingaborg #41 enumerated from current code). This is+// the "scan enum assignment vs current code" gate as an executable assertion:+// a later refactor that silently flips a type's axis fails here. B0 is behavior-+// inert (nothing consumes CHANNEL_TRAITS until B1), so this is the only consumer+// today and the guard that the extraction stayed behavior-invariant.+describe("CHANNEL_TRAITS (B0 trait model)", () => {+ it("maps each stored channel type to its extracted trait values", () => {+ expect(CHANNEL_TRAITS).toEqual({+ text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },+ forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },+ forum_post: { addressing: "by-child-name", visibility: "inherit-parent", reach: "participant-set", creation: "pure-create" },+ thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create" },+ dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create" },+ })+ })++ it("each CreationTrait value names exactly one collision contract (Aigneis #45 / Blondie #49)", () => {+ // reject-on-collision = top-level 409/0-rows (idx_channel_server_name);+ // pure-create = forum_post bump→N distinct; get-or-create = thread/dm+ // fetch-winner. A value spanning two contracts has no single oracle.+ expect(CHANNEL_TRAITS.text.creation).toBe("reject-on-collision")+ expect(CHANNEL_TRAITS.forum.creation).toBe("reject-on-collision")+ expect(CHANNEL_TRAITS.forum_post.creation).toBe("pure-create")+ expect(CHANNEL_TRAITS.thread.creation).toBe("get-or-create")+ expect(CHANNEL_TRAITS.dm.creation).toBe("get-or-create")+ })++ it("covers every stored channel type (no type left un-traited)", () => {+ const types: StoredChannelType[] = ["text", "forum", "forum_post", "thread", "dm"]+ for (const t of types) expect(CHANNEL_TRAITS[t]).toBeDefined()+ expect(Object.keys(CHANNEL_TRAITS).sort()).toEqual([...types].sort())+ })++ it("addressing values are distinct per addressing strategy (no accidental reuse across strategies)", () => {+ // forum_post addresses by its own child name, thread by root seq — the two+ // must NOT share an addressing value (they resolve on different keys; a+ // shared value would collapse the resolver's two branches, the exact+ // do-not-fold the resolver comment warns about).+ expect(CHANNEL_TRAITS.forum_post.addressing).not.toBe(CHANNEL_TRAITS.thread.addressing)+ })+})++// B2 reach axis — the single-source classification the three reach faces (fanout+// recipients / inbox deliverable-narrowing / send-path enroll) share.+describe("reach axis helpers", () => {+ it("channelReach reads the reach value straight from the trait table", () => {+ expect(channelReach("text")).toBe("server-or-roster")+ expect(channelReach("forum")).toBe("server-or-roster")+ expect(channelReach("forum_post")).toBe("participant-set")+ expect(channelReach("thread")).toBe("participant-set")+ expect(channelReach("dm")).toBe("dm-pair")+ })++ it("reachIsParticipantSet is true for exactly thread + forum_post (the enroll ⟷ read shared predicate)", () => {+ expect(reachIsParticipantSet("thread")).toBe(true)+ expect(reachIsParticipantSet("forum_post")).toBe(true)+ expect(reachIsParticipantSet("text")).toBe(false)+ expect(reachIsParticipantSet("forum")).toBe(false)+ expect(reachIsParticipantSet("dm")).toBe(false)+ })++ it("reachIsParticipantSet tolerates the loose null/unknown types from the query layer", () => {+ expect(reachIsParticipantSet(null)).toBe(false)+ expect(reachIsParticipantSet(undefined)).toBe(false)+ expect(reachIsParticipantSet("bogus")).toBe(false)+ })++ it("isStoredChannelType guards the five stored types", () => {+ for (const t of ["text", "forum", "forum_post", "thread", "dm"]) expect(isStoredChannelType(t)).toBe(true)+ expect(isStoredChannelType(null)).toBe(false)+ expect(isStoredChannelType("channel")).toBe(false)+ })+})++// B3 visibility axis — how the access check resolves (NOT the miss status, which+// is surface-partitioned and stays in the caller's translation layer).+describe("visibility axis helpers", () => {+ it("channelVisibility reads the visibility value straight from the trait table", () => {+ expect(channelVisibility("text")).toBe("own-roster")+ expect(channelVisibility("forum")).toBe("own-roster")+ expect(channelVisibility("forum_post")).toBe("inherit-parent")+ expect(channelVisibility("thread")).toBe("inherit-parent")+ expect(channelVisibility("dm")).toBe("dm-participant")+ })++ it("visibilityIsDmParticipant is true for exactly dm (the shared DM access-rule predicate)", () => {+ expect(visibilityIsDmParticipant("dm")).toBe(true)+ expect(visibilityIsDmParticipant("text")).toBe(false)+ expect(visibilityIsDmParticipant("forum")).toBe(false)+ expect(visibilityIsDmParticipant("forum_post")).toBe(false)+ expect(visibilityIsDmParticipant("thread")).toBe(false)+ })++ it("visibilityIsDmParticipant tolerates the loose null/unknown types from the query layer", () => {+ expect(visibilityIsDmParticipant(null)).toBe(false)+ expect(visibilityIsDmParticipant(undefined)).toBe(false)+ expect(visibilityIsDmParticipant("bogus")).toBe(false)+ })+})diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.tsindex a69f01693..54e7118a7 100644--- a/src/shared/src/utils/community-roles.ts+++ b/src/shared/src/utils/community-roles.ts@@ -78,3 +78,202 @@ export function isDm(t: string | null | undefined): boolean {export function isMessageBearingSurface(t: string | null | undefined): boolean {return t === "text" || t === "forum_post" || t === "thread" || t === "dm"}++// ─────────────────────────────────────────────────────────────────────────────+// Channel-type TRAIT model (plan: unify-forum-forumpost-channel-thread B0).+//+// A channel `type` is not one fact but a COMBINATION of orthogonal behavioral+// traits (Aigneis's decomposition, thread /Alook/discuss/#462): three read/+// routing axes — how you ADDRESS it, who can SEE it, who it REACHES — plus one+// write axis, how it's CREATED. Historically each axis was hand-branched on the+// `type` literal in four separate places (resolver / write-guard / inbox /+// permissions), so the SAME per-type fact lived in N copies and drifted (the+// agent thread-inbox deadlock was one axis — participation — written twice and+// diverging). This table makes each type = one row of trait VALUES, and every+// consuming face dispatches on the trait, not the type literal. Adding a type is+// picking existing values from closed enums; adding a value forces (via an+// exhaustive `switch` with a `never` check) every face to handle it or fail to+// compile — so a red-line (single addressing identity / existence+// non-disclosure / never-drop reach) holds BY CONSTRUCTION, not by prose.+//+// Each axis is a CLOSED enum, deliberately NOT an open config object: that is+// what forbids "configure this type to skip the block check / leak existence".+// The miss/collision semantics are welded to the enum VALUE, not tunable per+// type. Do NOT widen these to free-form options.+//+// Rollout is staged (B0 = this table, pure add, nothing reads it yet; B1 =+// addressing; B2 = reach incl. enroll; B3 = visibility/access; B4 = creation).+// So today NO face consumes CHANNEL_TRAITS — it is behavior-inert until B1+.++// How a channel is located from a CLI ref (read axis). Consumed by the resolver+// (parse → id) and the single canonical-ref emitter (id → ref), which must read+// the SAME value so a type can never have two addressing paths (red-line ①).+// by-server-name — `/server/<name>`; top-level, name unique per server.+// by-child-name — `/server/<forum>/<post>`; slug unique within parent forum.+// by-root-seq — `/server/<channel>/#<rootSeq>`; anchored on root msg seq.+// by-peer-identity— `/.dm/<peer#0042>`; the OTHER access member's handle.+export type AddressingTrait = "by-server-name" | "by-child-name" | "by-root-seq" | "by-peer-identity"++// Who can SEE the channel (read axis). The miss semantics (no access → 404, the+// existence-non-disclosure red-line ②) are welded to the value, not per-type.+// own-roster — its own server-membership / private-category roster.+// inherit-parent — climbs `parentChannelId` to the parent forum/channel's+// roster + privacy (a post/thread is not its own unit).+// dm-participant — the two `relation='access'` DM members; the sole surviving+// 403 (block of a known participant) lives inside this value.+export type VisibilityTrait = "own-roster" | "inherit-parent" | "dm-participant"++// Who a message REACHES / gets notified (read+write axis). One value drives BOTH+// halves from a single source (red-line ③): the read predicate (fanout + inbox+// "is this deliverable" agree) AND the write-side enroll (who gets a notify row+// on send). Splitting them is exactly the thread-deadlock drift.+// server-or-roster— the whole server (public) or private-category roster.+// participant-set — the notify set: author + spoke + @-mentioned enroll rows.+// dm-pair — the two DM participants.+export type ReachTrait = "server-or-roster" | "participant-set" | "dm-pair"++// How a channel is CREATED (write axis) — what a name/anchor COLLISION means.+// Consumed by the create path (B4). Misusing it is a silent-success illusion+// (a pure-create wrongly merged returns 200 for a post that was never made),+// which is why it is a first-class trait, not handler-buried logic. Each value+// names EXACTLY ONE observable collision contract, so it carries exactly one+// definition-level existence-oracle (Aigneis's B0 criterion, #45) — a value that+// spanned two contracts (e.g. 409-reject AND bump) would have two end states and+// no single assertable oracle, collapsing the by-construction win back to+// per-type hand-verification.+// pure-create — a slug collision BUMPS a new slug (`ideas`→`ideas-2`)+// and retries the insert → N distinct rows, never merged+// (forum_post). Contract: collision → bump → N distinct.+// get-or-create — the anchor identifies ONE unit; a collision re-selects+// and returns the existing winner (idempotent open — DM,+// thread). Contract: collision → fetch winner, 1 unit.+// reject-on-collision— a same-name create is REFUSED (409, 0 rows) by the+// `idx_channel_server_name` unique index; the caller must+// rename (top-level text/forum, human-admin-created). NOT+// a singleton (many channels may exist, just not same-name)+// and NOT "no create" (it is a real create path with a real+// 409 contract). Contract: collision → 0 rows + 409.+export type CreationTrait = "pure-create" | "get-or-create" | "reject-on-collision"++export type ChannelTraits = {+ addressing: AddressingTrait+ visibility: VisibilityTrait+ reach: ReachTrait+ creation: CreationTrait+}++// The single source of truth mapping each stored channel type to its trait+// values. Extracted from today's hand-branched behavior — B0 is behavior-+// invariant (see the axis docs above for where each value comes from).+//+// `text`/`forum` creation = `reject-on-collision`: a top-level channel create is+// human-admin-only and a same-name create is REFUSED (409, 0 rows) by the+// `idx_channel_server_name` unique index — a DIFFERENT observable contract from+// forum_post's `pure-create` (collision → bump → N distinct rows). The two must+// not share a value (Aigneis #45 / Ingaborg #46 / Blondie #49 — each verified in+// code): one value = one collision contract = one oracle. `forum_post` is the+// sole `pure-create` today (the bot content-create path this round).+export const CHANNEL_TRAITS: Record<StoredChannelType, ChannelTraits> = {+ text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },+ forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },+ forum_post: { addressing: "by-child-name", visibility: "inherit-parent", reach: "participant-set", creation: "pure-create" },+ thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create" },+ dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create" },+}++// ── reach axis (B2) — the SINGLE source for "who does a message here reach" ────+// The reach model of a channel type used to be re-derived as `isThread(t) ||+// isForumPost(t)` (→ participant set) vs `isDm(t)` (→ DM pair) vs else (→ server)+// in THREE places: fan-out recipients (who-receives), the agent-inbox+// deliverable-unread narrowing (which channels need participation), and the+// send-path enroll (who-enrolls into the notify set). Three copies of one+// classification = drift (the agent thread-inbox deadlock was two of them+// diverging). Now all three read the reach VALUE from CHANNEL_TRAITS via the+// helpers below, so the classification lives in exactly one place. Critically,+// the read side (who's-participant) and the write side (who-enrolls) key on the+// SAME value (`participant-set`) — a message enrolls participants iff its reach+// is participant-set, and the deliverable/fan-out predicate reads that same set,+// so enroll and read can never drift (red-line ③).++// The reach model for a stored channel type — the one classification the three+// reach faces branch on. A plain lookup so it's impossible to have a second+// copy of "which types are participant-set".+export function channelReach(t: StoredChannelType): ReachTrait {+ return CHANNEL_TRAITS[t].reach+}++// A message in a channel of this type ENROLLS participants on send (author ++// @-mentioned/replied) AND its recipients/deliverable set are read from that+// same participant set. True iff the reach value is `participant-set` (thread,+// forum_post today). This is the single predicate the enroll write-side and the+// participation-narrowing read-side share — they are two ends of one reach+// value, never separately maintained (red-line ③).+export function reachIsParticipantSet(t: string | null | undefined): boolean {+ return isStoredChannelType(t) && channelReach(t) === "participant-set"+}++// A narrow type guard so the reach helpers can accept the loosely-typed+// `type` columns/params (string | null) that flow through the query layer.+export function isStoredChannelType(t: string | null | undefined): t is StoredChannelType {+ return t === "text" || t === "forum" || t === "forum_post" || t === "thread" || t === "dm"+}++// ── visibility axis (B3) — how the ACCESS CHECK runs (NOT the miss status) ─────+// The visibility trait names HOW a channel resolves access, the one classification+// the access functions branch on. Deliberately does NOT cover the miss STATUS+// (no-access → 403 vs 404): that translation is surface-partitioned (human →+// 403 in requireChannelMember; agent → 404 via the existence-mask collapse), an+// axis ORTHOGONAL to type — welding it here would compress the surface dimension+// into the type dimension (a false convergence). So a null (not visible) is still+// returned by the access functions and translated by the caller per surface;+// this trait only picks the resolution STRATEGY.+// dm-participant → the `relation='access'` member check, no server walk, no+// parent inheritance (a DM is its own access unit).+// own-roster / inherit-parent → the server-membership + private-category path,+// with the anchor climb (`parentChannelId ?? id`) that makes a+// thread/forum_post inherit its parent's roster. That climb is+// already a single uniform idiom, so these two values share the+// same code path today; the value records the intent.+export function channelVisibility(t: StoredChannelType): VisibilityTrait {+ return CHANNEL_TRAITS[t].visibility+}++// The DM access rule: resolve access via the `relation='access'` member row with+// no server walk / no inheritance. True iff visibility is `dm-participant`. This+// is the single predicate the two access functions (`getChannelForMember`,+// `resolveChannelAccessContext`) share for their DM special-case, instead of each+// re-testing `type === 'dm'` (B3 — the DM access rule's 2→1). Does NOT decide the+// miss status (403/404) — that stays in the caller's surface-partitioned layer.+export function visibilityIsDmParticipant(t: string | null | undefined): boolean {+ return isStoredChannelType(t) && channelVisibility(t) === "dm-participant"+}++// ── creation axis (B4) — what a name/anchor COLLISION means ───────────────────+// The creation trait names the collision contract of a channel type, read by the+// create path so "what happens when the name/anchor already exists" is chosen+// from one place, not hand-branched per type. Each value = exactly one observable+// contract = exactly one existence-oracle (Aigneis's B0 criterion):+// pure-create → bump a new slug and retry the insert → N distinct rows,+// never merged (forum_post). ⚠ its race-safety REQUIRES+// the partial-unique index (migration, B4b) to catch a+// concurrent collision — without it a race silent-double-+// inserts. So a pure-create create path is only complete+// with that index in place.+// get-or-create → the anchor is ONE unit; a collision re-selects the+// existing winner (idempotent open — DM, thread).+// reject-on-collision→ a same-name create is refused (409, 0 rows) by a unique+// index (top-level text/forum).+export function channelCreation(t: StoredChannelType): CreationTrait {+ return CHANNEL_TRAITS[t].creation+}++// ── NOT a trait axis: display / human-readable title ──────────────────────────+// A forum post's `display_title` (its pre-slugify original title) is DELIBERATELY+// absent from this table. It is ZERO-behavior — no face (resolver / write-guard /+// inbox / permissions) reads it; it is pure presentation. Addressing always+// resolves via the key the `addressing` trait names (`name` = the slug), NEVER a+// human title. Do NOT "add display to a trait axis" when introducing a type+// (the tempting misread: "names address, so display belongs in addressing") —+// that would re-merge the slug (machine address) and the readable title (human+// display), the exact split this model keeps apart. Readable identity lives in a+// display-only column and never becomes a second addressable path.diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex f44295a04..7326a8afb 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { parseRef, formatRef, formatSeq, parseSeq, DM_SERVER } from "../src/community-cli-contract";+import { parseRef, formatRef, formatCanonicalRef, formatSeq, parseSeq, DM_SERVER } from "../src/community-cli-contract";describe("parseRef", () => {it('parses "/studio/general" as a plain channel ref', () => {@@ -262,3 +262,62 @@ describe("formatSeq / parseSeq", () => {expect(() => parseSeq("#abc")).toThrow();});});++// The single canonical-ref emitter (B1 trait model, red-line ①). Dispatches the+// ref SHAPE off the channel type's addressing trait so every emit site (agent+// inbox, wake notice, listChannels) produces one addressing identity per type.+describe("formatCanonicalRef", () => {+ it("by-server-name (text): /server/name", () => {+ expect(formatCanonicalRef({ type: "text", serverName: "studio", name: "general" })).toBe("/studio/general");+ });++ it("by-server-name (forum): /server/name", () => {+ expect(formatCanonicalRef({ type: "forum", serverName: "studio", name: "ideas" })).toBe("/studio/ideas");+ });++ it("by-child-name (forum_post): /server/forum/post", () => {+ expect(+ formatCanonicalRef({ type: "forum_post", serverName: "studio", parentName: "ideas", name: "my-post" }),+ ).toBe("/studio/ideas/my-post");+ });++ it("by-root-seq (thread): /server/channel/#rootSeq", () => {+ expect(+ formatCanonicalRef({ type: "thread", serverName: "studio", parentName: "general", rootSeq: 42 }),+ ).toBe("/studio/general/#42");+ });++ it("by-peer-identity (dm): /.dm/peer", () => {+ expect(formatCanonicalRef({ type: "dm", peerSegment: "gusye#1231" })).toBe("/.dm/gusye#1231");+ });++ // Round-trip: every emitted canonical ref must parse back to a ref that+ // resolves the same scope — the emitter and parser share the addressing model+ // so a ref a bot receives is one it can send/read/ack against (red-line ①).+ it("round-trips through parseRef for every addressing trait", () => {+ expect(parseRef(formatCanonicalRef({ type: "text", serverName: "studio", name: "general" })!)).toEqual({+ server: "studio",+ channel: "general",+ });+ expect(+ parseRef(formatCanonicalRef({ type: "forum_post", serverName: "studio", parentName: "ideas", name: "notes" })!),+ ).toEqual({ server: "studio", channel: "ideas", childChannelName: "notes" });+ expect(+ parseRef(formatCanonicalRef({ type: "thread", serverName: "studio", parentName: "general", rootSeq: 7 })!),+ ).toEqual({ server: "studio", channel: "general", threadRootSeq: 7 });+ expect(parseRef(formatCanonicalRef({ type: "dm", peerSegment: "gusye#1231" })!)).toEqual({+ server: DM_SERVER,+ channel: "gusye#1231",+ });+ });++ // Missing-field → null (not a bogus ref): a caller that can't resolve the+ // context an addressing value needs keeps its own fallback/skip handling+ // rather than emitting a ref that won't round-trip.+ it("returns null when a required addressing field is absent", () => {+ expect(formatCanonicalRef({ type: "text", serverName: "studio" })).toBeNull(); // no name+ expect(formatCanonicalRef({ type: "forum_post", serverName: "studio", name: "p" })).toBeNull(); // no parentName+ expect(formatCanonicalRef({ type: "thread", serverName: "studio", parentName: "g" })).toBeNull(); // no rootSeq+ expect(formatCanonicalRef({ type: "dm" })).toBeNull(); // no peerSegment+ });+});diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex 72f4736e0..bfa38a373 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -158,6 +158,33 @@ describe("toAgentMessages", () => {expect(msg!.channel).toBe("/unknown/ch_gone");});+ // B1.1 degraded-path (Ingaborg's assertion): a thread channel row EXISTS but+ // its parent/root didn't hydrate (parentChannels + parentMessages come back+ // empty — a dangling parent ref). The by-root-seq emitter can't build a ref+ // without the root seq, so it returns null and resolveScopeRefs sets no map+ // entry → the caller's `?? "/unknown/<id>"` sentinel takes over. Before B1.1+ // this row got a hand-built top-level `/studio/thread-x` ref that LOOKS+ // addressable but 404s on resolve; now it's an explicit unresolvable sentinel.+ // The message ROW still surfaces (never-drop) — only its channel is /unknown/.+ it("degraded thread (parent/root not hydrated) → /unknown/ sentinel, not a bogus top-level ref, row kept", async () => {+ // Call order: 1. channels (the thread row itself), 2. author names,+ // 3. parentChannels (EMPTY — parent didn't resolve), 4. servers,+ // 5. parentMessages (EMPTY — root seq didn't resolve).+ const db = createSequentialDb([+ [{ id: "thread_1", name: "thread-x", type: "thread", serverId: "srv_1", parentChannelId: "ch_gone_parent", parentMessageId: "m_gone_root" }],+ [{ id: "u_1", name: "Alice" }],+ [], // parentChannels: parent didn't hydrate+ [{ id: "srv_1", name: "studio" }],+ [], // parentMessages: root seq didn't hydrate+ ]);+ const [msg] = await agentInbox.toAgentMessages(db, [rawMsg({ channelId: "thread_1" })], "viewer_1");+ // Row survives (never-drop) and the channel is the explicit sentinel — NOT+ // a fabricated `/studio/thread-x` top-level ref.+ expect(msg).toBeDefined();+ expect(msg!.channel).toBe("/unknown/thread_1");+ expect(msg!.channel).not.toBe(formatRef({ server: "studio", channel: "thread-x" }));+ });+it("falls back to the raw authorId as sender when the user row is missing", async () => {const db = createSequentialDb([[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],diff --git a/src/web/migrations/0078_forum_post_unique_name.sql b/src/web/migrations/0078_forum_post_unique_name.sqlnew file mode 100644index 000000000..02229e794--- /dev/null+++ b/src/web/migrations/0078_forum_post_unique_name.sql@@ -0,0 +1,45 @@+-- Forum-post slug uniqueness + display-title capture (forum createPost, trait+-- model B4b). Pairs with the B4a-core pure-create collision policy: the+-- bump-retry loop's race-safety DEPENDS on this partial unique index catching a+-- concurrent duplicate slug — without it a race silently double-inserts. So this+-- migration and the B4a create code MUST ship together (ship-order constraint).+--+-- A forum post is a `forum_post` child channel addressed by a NAME ANCHOR+-- `/server/<forum>/<post-slug>`. That anchor only resolves if the slug (`name`)+-- is unique WITHIN its parent forum: two posts sharing a slug make+-- resolve-by-name ambiguous and read/send/ack on the post 400.+--+-- Scope: `type='forum_post'` ONLY, NOT a blanket (parent_channel_id, name) unique+-- over all children. A THREAD is also a child channel, but a thread's name is+-- auto-derived from its root message (display-only) and threads address by+-- `parent_message_id` (uq_community_channel_parent_message, 0052) — never by name+-- — so duplicate thread names are legal and a blanket unique would wrongly reject+-- them. Uniqueness belongs only on the type that addresses by name.+--+-- Case-sensitive (plain `name`, no COLLATE NOCASE): the forum-post resolver and+-- dedupe (getChildChannelByName / dedupeChildChannelSlug) compare names with a+-- plain `eq`, so the DB ruler must fold identically or it drifts from resolution+-- — the same index/resolver alignment migration 0075 established for top-level+-- names (there both NOCASE; here both case-sensitive). Consistency with the+-- resolver is the invariant, not the fold.+--+-- APPLY PREREQUISITE: zero duplicate (parent_channel_id, name) among forum_post+-- rows. Verified clean against live remote D1 on 2026-08-04 (Gener's online scan:+-- 0 duplicate slugs), so the index builds directly — no dedup pre-step needed.+-- Re-scan before applying to any OTHER environment:+-- SELECT parent_channel_id, name, COUNT(*) c FROM community_channel+-- WHERE type='forum_post' GROUP BY parent_channel_id, name HAVING c > 1;+-- and resolve any collision by RENAME (a forum_post row owns its post's messages,+-- so never delete) before this index will build.++-- 1. Display-only original title, captured pre-slugify at create time. Nullable;+-- only forum_post CREATE writes it (createForumPost). Never an addressing+-- axis — no index, duplicates legal, does not participate in slug dedupe.+-- Existing rows stay NULL.+ALTER TABLE community_channel ADD COLUMN display_title TEXT;++-- 2. Per-forum unique slug, forum_post only — the address anchor's uniqueness,+-- and what makes pure-create's bump-retry race-safe.+CREATE UNIQUE INDEX idx_forum_post_parent_name+ ON community_channel(parent_channel_id, name)+ WHERE type = 'forum_post';diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.tsindex cb79adfeb..214e97311 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts@@ -157,9 +157,12 @@ describe("POST /api/community/channels/[id]/posts — name normalization", () =>const res = await POST(postReq({ name: "My thoughts on this!", content: "hello" }), ctx)expect(res.status).toBe(201)+ // The addressing name is the slug; display_title captures the PRE-slugify+ // original verbatim (B4b) — the two MUST differ here, proving capture happens+ // before slugify (a slugified display_title would be worthless).expect(mockCreateChannel).toHaveBeenCalledWith(expect.anything(),- expect.objectContaining({ name: "My-thoughts-on-this!" }),+ expect.objectContaining({ name: "My-thoughts-on-this!", displayTitle: "My thoughts on this!" }),)})diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.tsindex 8355dc4d2..57c24d892 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts@@ -4,16 +4,13 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import {queries,- MAX_CHANNEL_NAME_LENGTH,- MAX_MESSAGE_CONTENT_LENGTH,MESSAGE_PREVIEW_LENGTH,WS_EVENTS,- slugify,} from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember, requireChannelAccess } from "@/lib/community/permissions"import { avatarInitial } from "@/lib/community/avatar"-import { createCommunityMessage } from "@/lib/community/message-handler"+import { createForumPost } from "@/lib/community/create-forum-post"export const GET = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -119,70 +116,31 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("invalid request body", 400)}- if (!body.name || typeof body.name !== "string" || body.name.trim().length === 0) {+ if (!body.name || typeof body.name !== "string") {return writeError("name is required", 400)}- const trimmedName = body.name.trim()- if (trimmedName.length > MAX_CHANNEL_NAME_LENGTH) {- return writeError(`name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters`, 400)- }- const name = slugify(trimmedName)- if (!name) {- return writeError("name is required", 400)- }-const content = typeof body.content === "string" ? body.content : ""- const hasContent = content.trim().length > 0- const hasAttachments = Array.isArray(body.attachments) && body.attachments.length > 0- if (!hasContent && !hasAttachments) {- return writeError("post is empty", 400)- }- if (hasContent && content.length > MAX_MESSAGE_CONTENT_LENGTH) {- return writeError(`content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters`, 400)- }- // Dedupe the slug within this forum so the post's name anchor- // (`/server/forum/<post>`) is a unique, resolvable address. Post names are- // NOT covered by the per-server unique index (top-level channels only), so- // uniqueness is enforced here, mirroring top-level channel naming: `ideas`- // → `ideas-2` → `ideas-3`. `name` is already slugified (no `/`/`#`/space),- // so the anchor round-trips cleanly through parseRef/formatRef.- const uniqueName = await queries.communityChannel.dedupeChildChannelSlug(db, channelId, name)-- // Create child channel for the forum post. Tags are NOT set at creation —- // they're added afterward from the post card's tag dialog.- const postChannel = await queries.communityChannel.createChannel(db, {- serverId: channel.serverId,- parentChannelId: channelId,- name: uniqueName,- type: "forum_post",- creatorId: ctx.userId,- })-- // Create the first message in the post through the unified pipeline. Route as- // `kind:"forum_post"` (NOT `kind:"channel"`) so the notify-set enroll runs- // exactly like a thread: the creator joins as "spoke" AND anyone the post- // body @-mentions joins as "mention" — so a person @-ed while creating the- // post lands in the members panel, matching reply behavior. `mentionType`- // still flows through for @everyone. `skipChildChannelUpdate` suppresses ONLY- // the parent CHILD_CHANNEL_UPDATE WS tick (enroll is unaffected) — this route- // already emits its own CHILD_CHANNEL_CREATE for the new post below, and the- // two would collide. The emitted MESSAGE_CREATE is deduped by id on the- // client against that CHILD_CHANNEL_CREATE.- const created = await createCommunityMessage({+ // Create via the shared core (B4 creation-axis convergence): slug dedupe ++ // forum_post child create + first-message-as-body, with the collision+ // contract dispatched on the forum_post `creation` trait (pure-create:+ // bump-and-retry, never merge). The bot verb (`createPost` / `alook message+ // post`) calls the SAME `createForumPost`, so the two can't drift on how a+ // post is created. This route keeps its own response projection + the human+ // CHILD_CHANNEL_CREATE fan-out below.+ const result = await createForumPost({db,+ forumChannelId: channelId,+ serverId: channel.serverId!,authorId: ctx.userId,- target: {- kind: "forum_post",- channelId: postChannel.id,- parentChannelId: channelId,- serverId: channel.serverId,- },- body: { content, attachments: body.attachments, mentionType: body.mentionType },- skipChildChannelUpdate: true,+ rawTitle: body.name,+ content,+ attachments: body.attachments,+ mentionType: body.mentionType,})- if (!created.ok) return writeError(created.error, created.status)- const message = created.row+ if (!result.ok) return writeError(result.error, result.status)+ const postChannel = result.postChannel+ const message = result.messageRow// Resolve author info for responseconst creator = await queries.user.getUserSelf(db, ctx.userId)diff --git a/src/web/src/app/api/community/createPost/route.test.ts b/src/web/src/app/api/community/createPost/route.test.tsnew file mode 100644index 000000000..979515a5e--- /dev/null+++ b/src/web/src/app/api/community/createPost/route.test.ts@@ -0,0 +1,155 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/auth", () => ({+ createAuth: vi.fn(() => ({+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },+ })),+}))++const mockFindActiveAgentRunnerKeyByBearer = vi.fn()+const mockGetUserInternal = vi.fn()+const mockGetBotBinding = vi.fn()+const mockResolveServerByNameForMember = vi.fn()+const mockResolveChannelByNameForMember = vi.fn()+const mockGetChannelForMember = vi.fn()+const mockGetServer = vi.fn()+const mockFindPendingAttachmentsForBot = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },+ user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityServer: {+ resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),+ getServer: (...a: unknown[]) => mockGetServer(...a),+ },+ communityChannel: {+ resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ },+ communityAttachment: {+ findPendingAttachmentsForBot: (...a: unknown[]) => mockFindPendingAttachmentsForBot(...a),+ },+ },+ }+})++const mockCreateForumPost = vi.fn()+vi.mock("@/lib/community/create-forum-post", () => ({+ createForumPost: (...a: unknown[]) => mockCreateForumPost(...a),+}))++import { POST } from "./route"++function req(body: unknown, headers: Record<string, string> = {}): NextRequest {+ return new NextRequest("http://localhost/api/community/createPost", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: typeof body === "string" ? body : JSON.stringify(body),+ })+}++const AUTH = { Authorization: "Bearer crk_abc" }++describe("POST /api/community/createPost", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })+ mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ // Forum ref resolves to a forum channel the bot can access.+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "forum_1" }])+ mockGetChannelForMember.mockResolvedValue({ id: "forum_1", serverId: "srv_1", type: "forum", name: "ideas", parentChannelId: null })+ mockGetServer.mockResolvedValue({ id: "srv_1", name: "studio" })+ mockFindPendingAttachmentsForBot.mockResolvedValue([])+ mockCreateForumPost.mockResolvedValue({+ ok: true,+ postChannel: { id: "post_1", name: "my-post", createdAt: "2026-08-04T00:00:00.000Z" },+ messageRow: { id: "m_1", seq: 1 },+ attachments: [],+ })+ })++ it("401 without Authorization (human path, no session)", async () => {+ const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hi" } }))+ expect(res.status).toBe(401)+ })++ it("400 on schema failure — empty title", async () => {+ const res = await POST(req({ forum: "/studio/ideas", title: "", content: { text: "hi" } }, AUTH))+ expect(res.status).toBe(400)+ })++ it("400 on opener empty — no text and no attachments (attachment-only IS allowed, empty is not)", async () => {+ const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "" } }, AUTH))+ expect(res.status).toBe(400)+ })++ it("201 + canonical /server/forum/<slug> ref on success (round-trippable as next --target)", async () => {+ const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hello" } }, AUTH))+ expect(res.status).toBe(201)+ const body = await res.json()+ expect(body.post.ref).toBe("/studio/ideas/my-post")+ expect(body.post.name).toBe("my-post")+ })++ it("authz symmetry: a bot that is NOT a member of the (private) forum → 403, same as a human", async () => {+ // requireChannelMember → getChannelForMember returns null when the bot can't+ // see the forum (private, not a member) → 403 "forbidden". This proves the+ // create gate runs requireChannelMember, not a requireBot shortcut.+ mockGetChannelForMember.mockResolvedValue(null)+ const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hi" } }, AUTH))+ expect(res.status).toBe(403)+ expect(mockCreateForumPost).not.toHaveBeenCalled()+ })++ it("400 when the resolved target is not a forum (e.g. a text channel)", async () => {+ mockGetChannelForMember.mockResolvedValue({ id: "forum_1", serverId: "srv_1", type: "text", name: "general", parentChannelId: null })+ const res = await POST(req({ forum: "/studio/general", title: "My Post", content: { text: "hi" } }, AUTH))+ expect(res.status).toBe(400)+ expect(mockCreateForumPost).not.toHaveBeenCalled()+ })++ it("(5b) attachment widen: a pending id NOT bound to this forum → 400, no cross-forum reuse", async () => {+ // Bound to forum A but this create targets forum_1 → findPendingAttachmentsForBot+ // (queried with targetId=forum_1) returns fewer rows than requested → 400.+ mockFindPendingAttachmentsForBot.mockResolvedValue([]) // 0 found for 1 requested+ const res = await POST(+ req({ forum: "/studio/ideas", title: "My Post", content: { text: "" }, attachments: ["att_from_other_forum"] }, AUTH),+ )+ expect(res.status).toBe(400)+ expect(mockCreateForumPost).not.toHaveBeenCalled()+ // Validated against THIS forum's id (the widen: bind-to-forum).+ expect(mockFindPendingAttachmentsForBot).toHaveBeenCalledWith(expect.anything(), {+ ids: ["att_from_other_forum"],+ uploaderId: "bot_1",+ targetId: "forum_1",+ })+ })++ it("attachment-only post (no text, valid forum-bound attachment) → succeeds", async () => {+ mockFindPendingAttachmentsForBot.mockResolvedValue([{ id: "att_1" }])+ const res = await POST(+ req({ forum: "/studio/ideas", title: "My Post", content: { text: "" }, attachments: ["att_1"] }, AUTH),+ )+ expect(res.status).toBe(201)+ expect(mockCreateForumPost).toHaveBeenCalled()+ })++ it("surfaces createForumPost's structured error (e.g. slug allocation 409)", async () => {+ mockCreateForumPost.mockResolvedValue({ ok: false, status: 409, error: "could not allocate a unique name after repeated collisions" })+ const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hi" } }, AUTH))+ expect(res.status).toBe(409)+ })+})diff --git a/src/web/src/app/api/community/createPost/route.ts b/src/web/src/app/api/community/createPost/route.tsnew file mode 100644index 000000000..d48248506--- /dev/null+++ b/src/web/src/app/api/community/createPost/route.ts@@ -0,0 +1,125 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, withD1Retry, CommunityAgentCreatePostRequestSchema, formatCanonicalRef } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { requireChannelMember } from "@/lib/community/permissions"+import { createForumPost } from "@/lib/community/create-forum-post"++/**+ * POST /api/community/createPost — bot verb behind `alook message post`. Creates+ * a NEW forum post: body `{ forum, title, content, attachments?, nonce? }` where+ * `forum` is a forum REF (`/server/forum`, resolved server-side like `send`'s+ * `channel`). Bot-only (`requireBot`); a human posts via the web New-Post button+ * (the human `channels/[id]/posts` route). Both call the SAME `createForumPost`+ * core, so the two creation paths can't drift.+ *+ * Gate order (thread /Alook/discuss/#462, Aigneis's authz red-line): resolve the+ * forum ref (NO create flags — we don't auto-create a forum) → assert it IS a+ * forum → really run `requireChannelMember(forum, botUserId)` (the CREATE authz+ * gate — a bot may create a post only in a forum it can access, same as a human;+ * a non-member 403s, NOT a requireBot shortcut) → createForumPost. NO alignment+ * gate: a fresh post is a new scope with no seq contention.+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate0 = requireBot(ctx.actor)+ if (!gate0.ok) return gate0.response+ const botUserId = gate0.bot.userId++ const db = getDb(ctx.env.DB)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentCreatePostRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const body = parsed.data++ // Resolve the forum ref WITHOUT create flags — a stale/typo ref must 404, never+ // materialize a channel. `/server/forum` resolves to the forum's own channel.+ const resolved = await resolveTargetForMember(db, botUserId, body.forum)+ if ("error" in resolved) return resolveErrorResponse(resolved)+ if (resolved.kind !== "channel") {+ return NextResponse.json({ error: "target is not a forum" }, { status: 400 })+ }++ // Authz gate = the SAME requireChannelMember(forum) a human create passes — a+ // bot creates a post only in a forum it can access (non-member → 403). This is+ // the create authorization gate, distinct from requireBot (which only answers+ // "is a bot") and from resolveTargetForMember's membership-scoped addressing.+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ const forum = gate.value+ if (forum.type !== "forum") {+ return NextResponse.json({ error: "target is not a forum" }, { status: 400 })+ }++ // Attachment ownership (坑1): a bot uploads a pending attachment BEFORE the post+ // channel exists, so it binds the pending row's `target_id` to the FORUM id.+ // Validate ownership against that forum id here (the widen: bind-to-forum for a+ // post, vs `send`'s bind-to-channel — the post channel doesn't exist yet at+ // upload time). This is the authorization check; the actual reservation+ // (`reserveAttachmentsForMessage`, inside createForumPost's first-message send)+ // then binds each pending row to the new message BY ID, so no target re-point+ // is needed — the forum-ownership gate is enforced right here, up front. A+ // mismatch → generic 400, no leak of which id failed.+ if (body.attachments.length > 0) {+ const rows = await withD1Retry(+ () => queries.communityAttachment.findPendingAttachmentsForBot(db, {+ ids: body.attachments,+ uploaderId: botUserId,+ targetId: resolved.channelId,+ }),+ { route: "community/createPost:attachments" },+ )+ if (rows.length !== body.attachments.length) {+ return NextResponse.json(+ { error: "attachment not found or not attachable to this forum" },+ { status: 400 },+ )+ }+ }++ const result = await createForumPost({+ db,+ forumChannelId: forum.id,+ serverId: forum.serverId!,+ authorId: botUserId,+ rawTitle: body.title,+ content: body.content.text,+ attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,+ clientNonce: body.nonce,+ })+ if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })++ // Return the canonical, addressable ref of the created post — `/server/forum/+ // <real-slug>` (the slug after dedupe/bump), which the bot can hand straight+ // back as a `--target`. Built by the single canonical-ref emitter (B1), the+ // same one inbox/send resolve against, so it round-trips by construction.+ const server = await withD1Retry(+ () => queries.communityServer.getServer(db, forum.serverId!),+ { route: "community/createPost:server" },+ )+ const serverName = server?.name ?? null+ const ref = serverName+ ? formatCanonicalRef({+ type: "forum_post",+ serverName,+ parentName: forum.name ?? undefined,+ name: result.postChannel.name,+ })+ : null++ return NextResponse.json({+ post: {+ ref,+ name: result.postChannel.name,+ seq: result.messageRow.seq,+ },+ }, { status: 201 })+})diff --git a/src/web/src/app/api/community/listChannels/route.ts b/src/web/src/app/api/community/listChannels/route.tsindex d2cdf2a3d..619234b6c 100644--- a/src/web/src/app/api/community/listChannels/route.ts+++ b/src/web/src/app/api/community/listChannels/route.ts@@ -1,5 +1,5 @@import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentListChannelsRequestSchema, formatRef } from "@alook/shared"+import { queries, CommunityAgentListChannelsRequestSchema, formatCanonicalRef, type StoredChannelType } from "@alook/shared"import type {CommunityCliChannelGroup as ChannelGroup,ChannelListItem,@@ -81,8 +81,22 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {for (const c of rows) {const cat = c.categoryId ? categoryById.get(c.categoryId) : nullconst isPrivate = !!(cat && (cat.private ?? 0) === 1)+ // Single canonical-ref emitter (B1): dispatch the ref shape off the+ // channel type's addressing trait, same emitter the agent inbox uses,+ // so listChannels can't drift from how send/read/ack resolve the ref.+ // These are top-level channels (`listChannelsForMember` filters+ // parent_channel_id IS NULL) → the `by-server-name` arm, which given+ // server+name never returns null; the non-null assertion documents that+ // (B1.1: the old `?? formatRef(...)` fallback was dead code — a second+ // hand-built top-level shape outside the emitter — and is removed so the+ // ref shape lives ONLY in formatCanonicalRef).+ const ref = formatCanonicalRef({+ type: (c.type ?? "text") as StoredChannelType,+ serverName: server.name,+ name: c.name,+ })const item: ChannelListItem = {- ref: formatRef({ server: server.name, channel: c.name }),+ ref: ref!,name: c.name,type: c.type,visibility: isPrivate ? "private" : "public",diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.tsindex be745a101..263848d49 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts@@ -6,14 +6,16 @@ import {queries,canManageServer,isChannelType,- isUniqueConstraintError,+ channelCreation,MAX_CHANNEL_NAME_LENGTH,MAX_CHANNEL_TOPIC_LENGTH,WS_EVENTS,slugify,type ChannelType,+ type StoredChannelType,} from "@alook/shared"import { fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"+import { createWithCollisionPolicy } from "@/lib/community/create-collision"import { logAudit } from "@/lib/community/audit"import { requireServerMember } from "@/lib/community/permissions"@@ -70,22 +72,31 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("admin permission required", 403)}- let row- try {- row = await queries.communityChannel.createChannel(db, {+ // Collision handling via the shared trait-keyed policy (B4 convergence): a+ // top-level channel's creation trait is reject-on-collision — a duplicate name+ // (idx_channel_server_name) is REFUSED with 409, never bumped or merged. Same+ // createWithCollisionPolicy dispatch that runs forum_post's pure-create+ // (bump-retry) and thread's get-or-create (fetch-winner); only the attempt+ // callback + the reject message are top-level-specific. Behavior is unchanged+ // — still 409 "already exists", still the admin/private gate above; only the+ // dispatch mechanism is shared now.+ // Effective stored type — validated to text/forum above; undefined defaults to+ // "text" (same default createChannel applies). Both top-level types are+ // reject-on-collision, so channelCreation resolves the same policy either way.+ const effectiveType: StoredChannelType = body.type === "forum" ? "forum" : "text"+ const createResult = await createWithCollisionPolicy(channelCreation(effectiveType), {+ attempt: () => queries.communityChannel.createChannel(db, {serverId,categoryId: body.categoryId || null,name,type: body.type,topic: body.topic,creatorId: ctx.userId,- })- } catch (err) {- if (isUniqueConstraintError(err)) {- return writeError("a channel with this name already exists", 409)- }- throw err- }+ }),+ onReject: () => ({ status: 409, error: "a channel with this name already exists" }),+ })+ if (!createResult.ok) return writeError(createResult.error, createResult.status)+ const row = createResult.value// Private-category channels track an explicit roster; seed the creator so// audience resolution + the manage-members list are single queries.diff --git a/src/web/src/lib/community/create-collision.test.ts b/src/web/src/lib/community/create-collision.test.tsnew file mode 100644index 000000000..c0217e128--- /dev/null+++ b/src/web/src/lib/community/create-collision.test.ts@@ -0,0 +1,103 @@+import { describe, it, expect, vi } from "vitest"+import { createWithCollisionPolicy } from "./create-collision"++// A unique-constraint error shaped like the ones isUniqueConstraintError detects.+// isUniqueConstraintError checks the message for the SQLite unique-violation+// signature, so mirror that here.+function uniqueErr(): Error {+ return new Error("D1_ERROR: UNIQUE constraint failed: community_channel.name")+}++describe("createWithCollisionPolicy — trait-keyed create collision dispatch (B4)", () => {+ describe("pure-create (forum_post): bump-and-retry, never merge", () => {+ it("returns the created value on a clean first attempt", async () => {+ const attempt = vi.fn().mockResolvedValue({ id: "p1" })+ const res = await createWithCollisionPolicy("pure-create", { attempt })+ expect(res).toEqual({ ok: true, value: { id: "p1" } })+ expect(attempt).toHaveBeenCalledTimes(1)+ })++ it("re-runs attempt (re-bump) on a unique collision, then succeeds", async () => {+ const attempt = vi+ .fn()+ .mockRejectedValueOnce(uniqueErr())+ .mockRejectedValueOnce(uniqueErr())+ .mockResolvedValueOnce({ id: "p3" })+ const res = await createWithCollisionPolicy("pure-create", { attempt })+ expect(res).toEqual({ ok: true, value: { id: "p3" } })+ expect(attempt).toHaveBeenCalledTimes(3)+ })++ it("NEVER re-selects a winner — pure-create ignores refetchWinner even if supplied", async () => {+ const refetchWinner = vi.fn().mockResolvedValue({ id: "someone-elses" })+ const attempt = vi.fn().mockRejectedValueOnce(uniqueErr()).mockResolvedValueOnce({ id: "mine" })+ const res = await createWithCollisionPolicy("pure-create", { attempt, refetchWinner })+ // The 2nd attempt (re-bump) wins — the caller's OWN row, not the winner.+ expect(res).toEqual({ ok: true, value: { id: "mine" } })+ expect(refetchWinner).not.toHaveBeenCalled()+ })++ it("gives up with 409 after maxAttempts collisions (index-missing / pathological)", async () => {+ const attempt = vi.fn().mockRejectedValue(uniqueErr())+ const res = await createWithCollisionPolicy("pure-create", { attempt, maxAttempts: 3 })+ expect(res.ok).toBe(false)+ if (!res.ok) expect(res.status).toBe(409)+ expect(attempt).toHaveBeenCalledTimes(3)+ })++ it("re-throws a non-unique error (real failure, not a collision)", async () => {+ const attempt = vi.fn().mockRejectedValue(new Error("boom"))+ await expect(createWithCollisionPolicy("pure-create", { attempt })).rejects.toThrow("boom")+ })+ })++ describe("get-or-create (thread/dm-anchor): fetch the winner, never make a second", () => {+ it("returns the created value on a clean attempt", async () => {+ const attempt = vi.fn().mockResolvedValue({ id: "t1" })+ const res = await createWithCollisionPolicy("get-or-create", { attempt, refetchWinner: vi.fn() })+ expect(res).toEqual({ ok: true, value: { id: "t1" } })+ })++ it("on a unique collision re-selects the winner — NOT a second unit", async () => {+ const attempt = vi.fn().mockRejectedValue(uniqueErr())+ const refetchWinner = vi.fn().mockResolvedValue({ id: "winner" })+ const res = await createWithCollisionPolicy("get-or-create", { attempt, refetchWinner })+ expect(res).toEqual({ ok: true, value: { id: "winner" } })+ expect(refetchWinner).toHaveBeenCalledTimes(1)+ expect(attempt).toHaveBeenCalledTimes(1) // no re-attempt/bump+ })++ it("re-throws if the winner can't be refetched (collision but no winner found)", async () => {+ const attempt = vi.fn().mockRejectedValue(uniqueErr())+ const refetchWinner = vi.fn().mockResolvedValue(null)+ await expect(createWithCollisionPolicy("get-or-create", { attempt, refetchWinner })).rejects.toThrow()+ })+ })++ describe("reject-on-collision (top-level text/forum): refuse with the caller's error", () => {+ it("returns the created value on a clean attempt", async () => {+ const attempt = vi.fn().mockResolvedValue({ id: "c1" })+ const res = await createWithCollisionPolicy("reject-on-collision", { attempt })+ expect(res).toEqual({ ok: true, value: { id: "c1" } })+ })++ it("on a unique collision returns the onReject error (409), never bumps or refetches", async () => {+ const attempt = vi.fn().mockRejectedValue(uniqueErr())+ const refetchWinner = vi.fn()+ const res = await createWithCollisionPolicy("reject-on-collision", {+ attempt,+ refetchWinner,+ onReject: () => ({ status: 409, error: "a channel with this name already exists" }),+ })+ expect(res).toEqual({ ok: false, status: 409, error: "a channel with this name already exists" })+ expect(attempt).toHaveBeenCalledTimes(1) // no re-bump+ expect(refetchWinner).not.toHaveBeenCalled() // no fetch-winner+ })+ })++ // Aigneis's "three contracts don't cross" — each value's collision end-state is+ // strictly its own: pure-create bumps (N distinct), get-or-create fetches (1+ // shared), reject-on-collision 409s (0 new). The per-value tests above already+ // assert none leaks another's behavior (pure-create ignores refetchWinner;+ // reject ignores both bump and refetch; get-or-create doesn't re-attempt).+})diff --git a/src/web/src/lib/community/create-collision.ts b/src/web/src/lib/community/create-collision.tsnew file mode 100644index 000000000..bd640d9b1--- /dev/null+++ b/src/web/src/lib/community/create-collision.ts@@ -0,0 +1,100 @@+import { isUniqueConstraintError, type CreationTrait } from "@alook/shared"++/**+ * The single collision-handling strategy for CREATING a channel, dispatched on+ * the channel type's `creation` trait (B4 convergence正题). Before this, "what a+ * name/anchor collision means" was hand-rolled in three places with three shapes:+ * - forum_post: dedupe-bump the slug and retry the insert (pure-create)+ * - thread: catch the unique-conflict and re-SELECT the winner (get-or-create)+ * - top-level text/forum: let the unique index 409 (reject-on-collision)+ * They collide on DIFFERENT keys (name / parent_message_id / server-name), so the+ * per-type CHANNEL-SHAPE construction stays with each caller — only the COLLISION+ * POLICY converges here, parameterized by callbacks the caller supplies. (DM is+ * NOT wired in this round: its collision is identity-collision on a user-pair, a+ * different key space — folding it would compress two collision-key axes into one+ * value, a false convergence. Its `creation: get-or-create` trait value stays in+ * the table describing the contract; its create entry `createOrGetDM` is untouched.)+ *+ * The caller provides:+ * - `attempt()`: try to create the row; may throw a unique-constraint error on+ * a concurrent collision.+ * - `refetchWinner()`: (get-or-create only) re-select the existing row that won+ * the race. Returns null if it somehow can't be found.+ * - `onReject()`: (reject-on-collision only) the structured error to return when+ * the create is refused.+ * - `maxAttempts`: (pure-create only) bump-retry cap.+ *+ * ⚠ pure-create's race-safety REQUIRES the partial-unique index that makes+ * `attempt()` throw on a concurrent duplicate (migration, B4b). Without it a race+ * silently double-inserts — this dispatch is only correct once that index exists.+ */++export type CollisionOutcome<T> =+ | { ok: true; value: T }+ | { ok: false; status: 400 | 409; error: string }++export async function createWithCollisionPolicy<T>(+ creation: CreationTrait,+ handlers: {+ attempt: () => Promise<T>+ refetchWinner?: () => Promise<T | null>+ onReject?: () => { status: 400 | 409; error: string }+ maxAttempts?: number+ },+): Promise<CollisionOutcome<T>> {+ switch (creation) {+ case "get-or-create": {+ // Anchor identifies ONE unit (thread on its parent_message_id). A concurrent+ // create that lost the race → re-select the winner and return it. NEVER+ // create a second unit.+ try {+ return { ok: true, value: await handlers.attempt() }+ } catch (err) {+ if (isUniqueConstraintError(err) && handlers.refetchWinner) {+ const winner = await handlers.refetchWinner()+ if (winner !== null) return { ok: true, value: winner }+ }+ throw err+ }+ }+ case "pure-create": {+ // Each create is a distinct unit; a collision means "this name is taken" →+ // the caller re-derives a bumped name inside `attempt()` on the next pass+ // and retries. NEVER re-select the winner (that's get-or-create — it would+ // silently hand this caller someone else's unit). The cap stops an unbounded+ // loop if the index is missing (a mis-shipped B4a without B4b) or contention+ // is pathological.+ const max = handlers.maxAttempts ?? 8+ let attempts = 0+ // eslint-disable-next-line no-constant-condition+ while (true) {+ try {+ return { ok: true, value: await handlers.attempt() }+ } catch (err) {+ attempts+++ if (isUniqueConstraintError(err) && attempts < max) continue+ if (isUniqueConstraintError(err)) {+ return { ok: false, status: 409, error: "could not allocate a unique name after repeated collisions" }+ }+ throw err+ }+ }+ }+ case "reject-on-collision": {+ // A same-name create is refused (the unique index 409s). Surface the+ // caller's structured rejection rather than merging or bumping.+ try {+ return { ok: true, value: await handlers.attempt() }+ } catch (err) {+ if (isUniqueConstraintError(err)) {+ return { ok: false, ...(handlers.onReject?.() ?? { status: 409, error: "a channel with this name already exists" }) }+ }+ throw err+ }+ }+ default: {+ const _never: never = creation+ return _never+ }+ }+}diff --git a/src/web/src/lib/community/create-forum-post.ts b/src/web/src/lib/community/create-forum-post.tsnew file mode 100644index 000000000..e1aaa5888--- /dev/null+++ b/src/web/src/lib/community/create-forum-post.ts@@ -0,0 +1,161 @@+import {+ queries,+ slugify,+ channelCreation,+ MAX_CHANNEL_NAME_LENGTH,+ MAX_MESSAGE_CONTENT_LENGTH,+ type Database,+} from "@alook/shared"+import { createCommunityMessage } from "./message-handler"+import { createWithCollisionPolicy } from "./create-collision"++/**+ * Shared core for CREATING a forum post — the single implementation both the+ * human New-Post route (`channels/[id]/posts` POST) and the bot verb+ * (`createPost` POST, `alook message post`) call. Extracting it is the B4+ * creation-axis convergence: "what a name collision means" is chosen ONCE, by+ * dispatching on the forum-post type's `creation` trait, instead of each caller+ * hand-rolling slug dedupe + create + first-message.+ *+ * `forum_post`'s creation trait is `pure-create`: each post is a distinct unit,+ * and a slug collision BUMPS a new slug (`ideas` → `ideas-2`) and retries the+ * insert — it NEVER merges into an existing post (that would be get-or-create,+ * a thread/DM contract). The retry loop below catches the partial-unique-index+ * violation and re-bumps.+ *+ * ⚠ SHIP-ORDER CONSTRAINT (Aigneis / Blondie, thread /Alook/discuss/#462): the+ * bump-retry's RACE-safety depends on the `(parent_channel_id, name)` partial+ * unique index (migration 0078, B4b). WITHOUT that index a concurrent+ * same-title create silently double-inserts (the original race — two posts,+ * both "succeed", sharing a slug, breaking name addressing). So this handler is+ * only correct once that index exists: B4a (this code) MUST NOT ship without+ * B4b (the index). The best-effort `dedupeChildChannelSlug` pre-check narrows+ * the window but does NOT close it — only the index does.+ */++export type CreateForumPostInput = {+ db: Database+ /** The parent forum channel (already membership-gated + asserted type=forum by the caller). */+ forumChannelId: string+ serverId: string+ /** The post creator (human userId or bot userId). */+ authorId: string+ /** Raw, pre-slugify title — its slug becomes the post's addressing name; the+ * original is captured verbatim into `display_title`. */+ rawTitle: string+ /** Post body text (may be empty when attachments carry the content). */+ content: string+ /** Attachment payloads (human route) — pending-id reservation is the bot route's concern. */+ attachments?: unknown+ mentionType?: unknown+ /** Bot-reserved attachment ids, validated by the caller (bot route). */+ attachmentIds?: string[]+ clientNonce?: string+}++// The success shape of createCommunityMessage — narrowed to its `ok:true` arm so+// we can reuse its exact `row`/`attachments` types without re-declaring them.+type CreateMessageSuccess = Extract<Awaited<ReturnType<typeof createCommunityMessage>>, { ok: true }>++type CreatedChannel = Awaited<ReturnType<typeof queries.communityChannel.createChannel>>++export type CreateForumPostResult =+ | { ok: true; postChannel: CreatedChannel; messageRow: CreateMessageSuccess["row"]; attachments: CreateMessageSuccess["attachments"] }+ | { ok: false; status: 400 | 409; error: string }++// How many times to re-bump a colliding slug before giving up. A forum with+// this many same-titled posts racing at once is pathological; the cap stops an+// unbounded loop if something (e.g. a missing index in a mis-shipped B4a) makes+// every insert collide.+const MAX_SLUG_BUMP_ATTEMPTS = 8++/**+ * Validate + create a forum post. Returns a structured error (never throws) for+ * the caller to translate into its surface's response shape. Does NOT do the+ * WS/fanout side effects beyond what `createCommunityMessage` fires — the caller+ * owns its own CHILD_CHANNEL_CREATE emission + response projection.+ */+export async function createForumPost(input: CreateForumPostInput): Promise<CreateForumPostResult> {+ const { db, forumChannelId, serverId, authorId, rawTitle, content } = input++ // ── validation (shared by both callers) ──────────────────────────────────+ const trimmedTitle = rawTitle.trim()+ if (trimmedTitle.length === 0) return { ok: false, status: 400, error: "title is required" }+ if (trimmedTitle.length > MAX_CHANNEL_NAME_LENGTH) {+ return { ok: false, status: 400, error: `title must be 1-${MAX_CHANNEL_NAME_LENGTH} characters` }+ }+ const baseSlug = slugify(trimmedTitle)+ if (!baseSlug) return { ok: false, status: 400, error: "title must contain at least one addressable character" }++ const hasContent = content.trim().length > 0+ const hasAttachments =+ (Array.isArray(input.attachments) && input.attachments.length > 0) ||+ (Array.isArray(input.attachmentIds) && input.attachmentIds.length > 0)+ // opener-body contract (thread consensus): a post needs text OR an attachment+ // — an attachment-only post is legitimate (the attachment is its body).+ if (!hasContent && !hasAttachments) return { ok: false, status: 400, error: "post is empty" }+ if (hasContent && content.length > MAX_MESSAGE_CONTENT_LENGTH) {+ return { ok: false, status: 400, error: `content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters` }+ }++ // ── collision handling via the shared trait-keyed strategy (B4 convergence) ──+ // forum_post's creation trait is pure-create → createWithCollisionPolicy runs+ // the bump-retry loop: each `attempt` re-derives a deduped slug and inserts;+ // a concurrent unique-constraint collision re-bumps (never re-selects a+ // winner — that's get-or-create). The SAME dispatch serves thread-create+ // (get-or-create) and top-level create (reject-on-collision); only this+ // callback (the forum_post channel-shape) is post-specific.+ const channelResult = await createWithCollisionPolicy<CreatedChannel>(channelCreation("forum_post"), {+ maxAttempts: MAX_SLUG_BUMP_ATTEMPTS,+ attempt: async () => {+ // Best-effort snapshot dedupe narrows the collision window; the partial+ // unique index (B4b) is what actually guarantees uniqueness under a race,+ // and is what makes this insert throw so the policy re-bumps. Re-run per+ // attempt against the now-updated table.+ const candidateSlug = await queries.communityChannel.dedupeChildChannelSlug(db, forumChannelId, baseSlug)+ return queries.communityChannel.createChannel(db, {+ serverId,+ parentChannelId: forumChannelId,+ name: candidateSlug,+ type: "forum_post",+ creatorId: authorId,+ // Display-only original title, captured BEFORE slugify (B0 decision, now+ // persisted in B4b's display_title column). `trimmedTitle` is the raw+ // human input ("Q3 planning / roadmap"), NOT the lossy slug — the point+ // is preserving what slugify destroys. Never an addressing axis.+ displayTitle: trimmedTitle,+ })+ },+ })+ if (!channelResult.ok) return channelResult+ const postChannel = channelResult.value++ // First message = the post body, routed kind:"forum_post" so notify-set enroll+ // runs (creator "spoke" + @-mentioned "mention"), matching a thread.+ // skipChildChannelUpdate: the caller emits its own CHILD_CHANNEL_CREATE.+ const created = await createCommunityMessage({+ db,+ authorId,+ target: { kind: "forum_post", channelId: postChannel.id, parentChannelId: forumChannelId, serverId },+ body: { content, attachments: input.attachments, mentionType: input.mentionType },+ attachmentIds: input.attachmentIds,+ clientNonce: input.clientNonce,+ skipChildChannelUpdate: true,+ })+ if (!created.ok) {+ // First-message failed — the post channel exists but has no body. Surface+ // the error. NOTE: full orphan-avoidance (folding channel + first-message+ // into ONE atomic batch) is a tracked hardening follow-up (Ingaborg's owed+ // work), NOT B4a — createCommunityMessage claims a seq in its own statement+ // so it can't fuse into the createChannel insert without the batch rework.+ // Non-regression: the human New-Post route has this same window today.+ return { ok: false, status: created.status, error: created.error }+ }++ return {+ ok: true,+ postChannel,+ messageRow: created.row,+ attachments: created.attachments,+ }+}diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 65bdf1319..3698e2335 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -13,7 +13,7 @@*/import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, createLogger, WS_EVENTS, isThread, isForumPost, isDm, withD1Retry } from "@alook/shared"+import { queries, createLogger, WS_EVENTS, channelReach, isStoredChannelType, withD1Retry } from "@alook/shared"import type { CommunityWsEvent, Database } from "@alook/shared"import { getDb } from "../db"import { broadcastToUser } from "../broadcast"@@ -59,26 +59,43 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s* The split lives here so fan-out and bot-wake use the same recipient set.*/async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {- const rows = await withD1Retry(+ const type = await withD1Retry(() => queries.communityChannel.getChannelType(db, channelId),{ route: "fanout:channel-type" },)- if (isThread(rows) || isForumPost(rows)) {- return withD1Retry(- () => queries.communityThread.listThreadParticipantUserIds(db, channelId),- { route: "fanout:thread-participants" },- )- }- if (isDm(rows)) {- return withD1Retry(- () => queries.communityChannel.listChannelMemberUserIds(db, channelId),- { route: "fanout:dm-members" },- )+ // Dispatch on the reach TRAIT, not a re-derived `isThread || isForumPost` /+ // `isDm` classification (B2 — the reach axis's single source). An unknown/null+ // type falls to `server-or-roster` (the historical default arm). The read side+ // here (who-receives) keys on the SAME reach value the send-path enroll keys on+ // (who-enrolls), so a participant-set channel's fan-out and its enroll can't+ // drift (red-line ③).+ const reach = isStoredChannelType(type) ? channelReach(type) : "server-or-roster"+ switch (reach) {+ case "participant-set":+ // Thread / forum_post: the unit's notify (participant) rows — the same set+ // the send-path enroll writes into.+ return withD1Retry(+ () => queries.communityThread.listThreadParticipantUserIds(db, channelId),+ { route: "fanout:thread-participants" },+ )+ case "dm-pair":+ // DM: its two relation='access' members (server_id is NULL, so it must not+ // fall through to the server-scoped resolver).+ return withD1Retry(+ () => queries.communityChannel.listChannelMemberUserIds(db, channelId),+ { route: "fanout:dm-members" },+ )+ case "server-or-roster":+ // Channel / forum: the access audience (public/private split).+ return withD1Retry(+ () => queries.communityMembersResolver.resolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId }),+ { route: "fanout:scope-members" },+ )+ default: {+ const _never: never = reach+ return _never+ }}- return withD1Retry(- () => queries.communityMembersResolver.resolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId }),- { route: "fanout:scope-members" },- )}/**diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 739403d6a..49c523c50 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -10,6 +10,7 @@ import {createLogger,isUniqueConstraintError,withD1Retry,+ reachIsParticipantSet,} from "@alook/shared"import type { MentionType } from "@alook/shared"import type { Database } from "@alook/shared"@@ -682,7 +683,18 @@ export async function createCommunityMessage(params: {// Admins are NOT auto-added — only real participation joins the set. System /// card messages (`skipMentions`) don't add the author. A forum post is// enrolled exactly like a thread so it notifies only its participants.- if (hasParentChannel(target) && !skipMentions) {+ // Enroll gate = the REACH axis (B2): a message enrolls participants iff its+ // channel's reach is `participant-set`. This is the WRITE side of red-line ③ —+ // it keys on the SAME reach value that the fan-out recipient set and the+ // agent-inbox deliverable narrowing (the READ side, who's-participant) key on,+ // so who-enrolls and who's-read can never drift (the class of bug the agent+ // thread-inbox deadlock was). `target.kind` is the channel's stored type here+ // (channel/thread/forum_post/dm). NOT folded with `hasParentChannel` below:+ // that is a distinct STRUCTURAL fact ("has a parent channel" → railChannelId /+ // parent CHILD_CHANNEL_UPDATE tick), which merely coincides with participant-set+ // for today's types — a future type could have a parent but server reach, or+ // participant reach without a parent, so the two rules stay separate.+ if (reachIsParticipantSet(target.kind) && !skipMentions) {const rows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.MENTION }[] = [{ userId: authorId, source: PARTICIPANT_SOURCE.SPOKE },]diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.tsindex d989fcc19..7f19e8766 100644--- a/src/web/src/lib/community/resolve-ref.ts+++ b/src/web/src/lib/community/resolve-ref.ts@@ -1,8 +1,8 @@import { NextResponse } from "next/server"-import { queries, parseRef, DM_SERVER, parseNameAndTag } from "@alook/shared"+import { queries, parseRef, DM_SERVER, parseNameAndTag, channelCreation } from "@alook/shared"import type { Database } from "@alook/shared"-import { isUniqueConstraintError } from "@alook/shared"import { guardDmOpen } from "./dm-guard"+import { createWithCollisionPolicy } from "./create-collision"export type TargetResolution =| { kind: "channel"; channelId: string }@@ -171,17 +171,25 @@ export async function resolveTargetForMember(return { error: 404, message: "thread not found" }}- try {- const created = await queries.communityChannel.createThreadChannel(db, channel.id, rootMessage.id, userId)- return { kind: "channel", channelId: created.id }- } catch (err) {- if (isUniqueConstraintError(err)) {- // Lost the race to a concurrent thread-create — re-select the winner.- const winner = await queries.communityChannel.getThreadChannelByParentMessage(db, channel.id, rootMessage.id)- if (winner) return { kind: "channel", channelId: winner.id }- }- throw err- }+ // Thread create via the shared trait-keyed collision policy (B4): thread's+ // creation trait is get-or-create — a concurrent create that loses the race on+ // the parent_message_id anchor (unique index, migration 0052) re-selects the+ // winner rather than making a second thread. This is the SAME dispatch+ // forum_post (pure-create) and top-level channels (reject-on-collision) use;+ // only these callbacks (the thread channel-shape + its anchor refetch) are+ // thread-specific. Anchor-collision (parent_message_id) and name-collision are+ // both "a structure anchor was taken → fetch the winner" — one get-or-create+ // value covers both; DM's identity-collision is a different key space and is+ // NOT wired here.+ const threadResult = await createWithCollisionPolicy(channelCreation("thread"), {+ attempt: () => queries.communityChannel.createThreadChannel(db, channel.id, rootMessage.id, userId),+ refetchWinner: () => queries.communityChannel.getThreadChannelByParentMessage(db, channel.id, rootMessage.id),+ })+ // get-or-create never returns a structured failure (it creates or re-selects+ // the winner, else throws) — a `!ok` here is unreachable for this policy;+ // map it to a 404 rather than widen TargetResolution's error union to 409.+ if (!threadResult.ok) return { error: 404, message: "thread not found" }+ return { kind: "channel", channelId: threadResult.value.id }}/**diff --git a/src/web/src/test/e2e/forum-post-slug-unique.test.ts b/src/web/src/test/e2e/forum-post-slug-unique.test.tsnew file mode 100644index 000000000..10ebb9b86--- /dev/null+++ b/src/web/src/test/e2e/forum-post-slug-unique.test.ts@@ -0,0 +1,112 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { sqlRun, sqlQuery } from "@alook/test-utils"++/**+ * Real-DB existence oracle for the forum-post slug unique index+ * (`idx_forum_post_parent_name`, migration 0078). This verifies the+ * LOAD-BEARING half of pure-create's concurrent no-merge contract that the+ * create-collision unit test can't: that the DB index ACTUALLY throws on a+ * duplicate `(parent_channel_id, name)` for a forum_post — not that the policy+ * re-bumps GIVEN a throw (that's the unit test's mocked half).+ *+ * The oracle is EXISTENCE-COUNT, not error-absence (Aigneis's #18 form): two+ * inserts of the same forum-post slug must leave exactly ONE row (the 2nd is+ * refused), and the bumped-slug retry must leave TWO distinct rows — never a+ * silent double-insert of the same slug (the original race this whole B4 guards).+ * Connects directly to the local D1 sqlite (bypassing the query wrapper), same+ * as community-bot-owner-fk.test.ts.+ */++const forumA = "e2e_slug_forum_a"+const forumB = "e2e_slug_forum_b"+const srv = "e2e_slug_srv"+const owner = "e2e_slug_owner"+const ids = ["e2e_slug_p1", "e2e_slug_p2", "e2e_slug_p3", "e2e_slug_p4", "e2e_slug_p5"]+const TS = "2026-08-04T00:00:00.000Z"++function insertPost(id: string, parent: string, name: string, type = "forum_post"): void {+ sqlRun(+ `INSERT INTO community_channel (id, server_id, parent_channel_id, name, type, created_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ id, srv, parent, name, type, TS,+ )+}++// FK parents: a user (server owner) → a server → the two top-level forum+// channels the posts hang under. The e2e connection enforces foreign keys, so+// these must exist before any forum_post row references them.+function cleanup(): void {+ sqlRun(`DELETE FROM community_channel WHERE id IN (${ids.map(() => "?").join(",")})`, ...ids)+ sqlRun(`DELETE FROM community_channel WHERE id IN (?, ?)`, forumA, forumB)+ sqlRun(`DELETE FROM community_server WHERE id = ?`, srv)+ sqlRun(`DELETE FROM user WHERE id = ?`, owner)+}++beforeAll(() => {+ cleanup()+ sqlRun(`INSERT INTO user (id, email, name) VALUES (?, ?, ?)`, owner, `${owner}@example.com`, "Slug Owner")+ sqlRun(+ `INSERT INTO community_server (id, name, description, owner_id, created_at) VALUES (?, ?, ?, ?, ?)`,+ srv, "Slug Srv", "", owner, TS,+ )+ // Two top-level forum channels (parent_channel_id NULL) — the posts' anchors.+ sqlRun(+ `INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, ?, ?, 'forum', ?)`,+ forumA, srv, "forum-a", TS,+ )+ sqlRun(+ `INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, ?, ?, 'forum', ?)`,+ forumB, srv, "forum-b", TS,+ )+})++afterAll(cleanup)++describe("idx_forum_post_parent_name — forum-post slug uniqueness (migration 0078)", () => {+ it("refuses a duplicate (parent, name) forum_post — existence count stays 1, no silent double-insert", () => {+ insertPost(ids[0]!, forumA, "ideas")+ // Second insert of the SAME slug under the SAME forum → the index refuses it.+ expect(() => insertPost(ids[1]!, forumA, "ideas")).toThrow(/UNIQUE constraint failed/i)++ // Existence oracle: exactly ONE "ideas" post exists under forumA — the+ // refused insert did NOT silently create a second (the original race).+ const rows = sqlQuery<{ id: string }>(+ `SELECT id FROM community_channel WHERE parent_channel_id = ? AND name = ? AND type = 'forum_post'`,+ forumA, "ideas",+ )+ expect(rows).toHaveLength(1)+ })++ it("a bumped slug creates a SECOND distinct post — pure-create yields N distinct, never a merge", () => {+ // The pure-create policy's response to the collision above: bump to+ // `ideas-2` and retry. That must succeed → two distinct addressable posts.+ insertPost(ids[2]!, forumA, "ideas-2")+ const rows = sqlQuery<{ name: string }>(+ `SELECT name FROM community_channel WHERE parent_channel_id = ? AND type = 'forum_post' ORDER BY name`,+ forumA,+ )+ expect(rows.map((r) => r.name)).toEqual(["ideas", "ideas-2"]) // 2 distinct, N-distinct not merged+ })++ it("does NOT restrict the same slug under a DIFFERENT forum (index is per-parent)", () => {+ // Same name "ideas" under forumB is legal — the anchor is (parent, name).+ expect(() => insertPost(ids[3]!, forumB, "ideas")).not.toThrow()+ const rows = sqlQuery<{ id: string }>(+ `SELECT id FROM community_channel WHERE name = ? AND type = 'forum_post'`,+ "ideas",+ )+ expect(rows).toHaveLength(2) // one per forum+ })++ it("does NOT restrict a duplicate name for a NON-forum_post child (WHERE type='forum_post' scoping — no thread false-positive)", () => {+ // A thread (or any non-forum_post child) may share a name freely — the+ // partial index's WHERE clause excludes it, so blanket-uniqueness never+ // wrongly rejects a legal duplicate thread name.+ insertPost(ids[4]!, forumA, "ideas", "thread")+ const threadRows = sqlQuery<{ id: string }>(+ `SELECT id FROM community_channel WHERE parent_channel_id = ? AND name = ? AND type = 'thread'`,+ forumA, "ideas",+ )+ expect(threadRows).toHaveLength(1) // the thread inserted fine despite forum_post "ideas" existing+ })+})diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex d3ff7cfda..7722d4843 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -271,10 +271,18 @@ vi.mock("@alook/shared", () => {},createDb: (d1: unknown) => mockCreateDb(d1),createLogger: () => noopLogger,- // Real type-guard impls — fanOutTyping branches on these to route a- // thread/forum_post to the participant set vs the access audience.- isThread: (t: unknown) => t === "thread",- isForumPost: (t: unknown) => t === "forum_post",+ // Real reach-trait impls — fanOutTyping's recipient split dispatches on+ // channelReach (B2 reach axis single source) to route a thread/forum_post to+ // the participant set, a dm to its members, else the access audience. Mirror+ // the real CHANNEL_TRAITS reach values + the stored-type guard.+ channelReach: (t: string) =>+ t === "forum_post" || t === "thread"+ ? "participant-set"+ : t === "dm"+ ? "dm-pair"+ : "server-or-roster",+ isStoredChannelType: (t: unknown) =>+ t === "text" || t === "forum" || t === "forum_post" || t === "thread" || t === "dm",// Minimal `readOrStale` shim — bypasses the classifier so tests can// inject arbitrary Error shapes at the query-fn boundary and observe// fail-closed semantics. Real production behavior (retry then fallback)diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 5d1c141a7..5c34c7924 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -16,8 +16,8 @@ import {pickBotActivityPreset,RUNNING_PRESETS,isBotActivityStatus,- isThread,- isForumPost,+ channelReach,+ isStoredChannelType,WS_EVENTS,} from "@alook/shared"import type { CommunityMachineRuntime, CommunityMachineSummary } from "@alook/shared"@@ -1413,6 +1413,32 @@ export class WebSocketDurableObject extends DurableObject<Env> {* branches fold the check into the same query that already resolves the* fan-out target, so this adds no extra DB round-trip versus before.*/+ /**+ * The typing-broadcast recipient set for a channel — the SAME reach+ * recipient-split as the message fan-out (`fanout.ts` getChannelRecipientUserIds).+ * Both dispatch on the channel type's reach trait (`channelReach`) so typing+ * reaches exactly whom a message would; they can't drift (B2 reach axis single+ * source — this was previously a hand-copied `isThread||isForumPost` split in+ * BOTH fanOutTyping and fanOutTypingStop, the reach rule's 7th/8th copies).+ * Does not exclude the sender — the callers filter that.+ */+ private async typingRecipientUserIds(db: ReturnType<typeof createDb>, channelId: string): Promise<string[]> {+ const channelType = await queries.communityChannel.getChannelType(db, channelId)+ const reach = isStoredChannelType(channelType) ? channelReach(channelType) : "server-or-roster"+ switch (reach) {+ case "participant-set":+ return queries.communityThread.listThreadParticipantUserIds(db, channelId)+ case "dm-pair":+ return queries.communityChannel.listChannelMemberUserIds(db, channelId)+ case "server-or-roster":+ return queries.communityMembersResolver.resolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId })+ default: {+ const _never: never = reach+ return _never+ }+ }+ }+private async fanOutTyping(senderUserId: string,channelId?: string,@@ -1431,24 +1457,9 @@ export class WebSocketDurableObject extends DurableObject<Env> {log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId })return}- // Recipient set — same split as the message fan-out (fanout.ts):- // - DM → the two relation='access' members.- // - THREAD / FORUM_POST → the participant NOTIFY set. Typing reaches- // only its participants, not the whole parent channel/server.- // - channel / forum → the access audience (public/private split).- const channelType = await queries.communityChannel.getChannelType(db, channelId)- if (channelType === "dm") {- recipientUserIds = await queries.communityChannel.listChannelMemberUserIds(db, channelId)- } else if (isThread(channelType) || isForumPost(channelType)) {- recipientUserIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)- } else {- recipientUserIds = await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {- scope: "channel",- scopeId: channelId,- })- }-- // Exclude the sender+ // Recipient set — the shared reach recipient-split (same as message+ // fan-out), then exclude the sender.+ recipientUserIds = await this.typingRecipientUserIds(db, channelId)recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)if (recipientUserIds.length === 0) return@@ -1484,18 +1495,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {log.warn("fanOutTypingStop: sender not a channel member", { senderUserId, channelId })return}- const channelType = await queries.communityChannel.getChannelType(db, channelId)- let recipientUserIds: string[]- if (channelType === "dm") {- recipientUserIds = await queries.communityChannel.listChannelMemberUserIds(db, channelId)- } else if (isThread(channelType) || isForumPost(channelType)) {- recipientUserIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)- } else {- recipientUserIds = await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {- scope: "channel",- scopeId: channelId,- })- }+ let recipientUserIds = await this.typingRecipientUserIds(db, channelId)recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)if (recipientUserIds.length === 0) returnconst body = JSON.stringify({diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.tsindex 22bca139e..994ef37c2 100644--- a/tests/integration/daemon/control-plane.test.ts+++ b/tests/integration/daemon/control-plane.test.ts@@ -37,6 +37,17 @@ import { nanoid, seedPairedBot, cleanupPairedBot, type DaemonItFixture } from ".const APP_URL = process.env.APP_URL ?? "http://localhost:3000"const WS_DO_URL = process.env.WS_DO_URL ?? "ws://localhost:8789"+// Assert a response is ok, but on failure surface the STATUS + body — a bare+// `expect(res.ok).toBe(true)` only tells you "false", which is undiagnosable in+// CI (is it a 401 key-timing? a 500 handler throw? a transport timeout?). This+// turns the opaque failure into an actionable signature.+async function assertResOk(res: Response, label: string): Promise<void> {+ if (res.ok) return+ let body = ""+ try { body = (await res.text()).slice(0, 500) } catch { body = "<unreadable body>" }+ throw new Error(`${label}: expected ok, got HTTP ${res.status} ${res.statusText} — body: ${body}`)+}+async function waitFor<T>(check: () => T | undefined, timeoutMs = 15_000, intervalMs = 200): Promise<T> {const deadline = Date.now() + timeoutMsfor (; ;) {@@ -148,8 +159,11 @@ describe("daemon control plane — real ws-do wake round-trip", () => {expect(wake.agentId).toBe(fixture.bot.botUserId)// Acting as the "agent" (no CLI spawned): mint the runner key, then- // pull the backlog, ack it, and send a reply — all real HTTP against- // /api/community/agent/*, exactly what a real agent's CLI would do.+ // pull the backlog, ack it, and send a reply — all real HTTP against the+ // flat /api/community/* bot verbs, exactly what a real agent's CLI would do.+ // (The `agent/*` path layer was removed when the bot verbs moved flat; this+ // test still hard-coded the stale `agent/*` paths → 404 HTML → the red on+ // main + here until this fix. enroll-agent stays under daemon/, unchanged.)const enrollRes = await fetchWithRetry(`${APP_URL}/api/community/daemon/enroll-agent`, {method: "POST",headers: { Authorization: `Bearer ${fixture.paired.credential}`, "content-type": "application/json" },@@ -159,19 +173,19 @@ describe("daemon control plane — real ws-do wake round-trip", () => {const { runnerKey } = (await enrollRes.json()) as { runnerKey: string; expiresAt: string | null }expect(runnerKey.startsWith("crk_")).toBe(true)- const pullRes = await fetchWithRetry(`${APP_URL}/api/community/agent/inboxPull`, {+ const pullRes = await fetchWithRetry(`${APP_URL}/api/community/inboxPull`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({}),})- expect(pullRes.ok).toBe(true)+ await assertResOk(pullRes, "inboxPull (:167 enroll→pull hop)")// Wire `seq` is formatted `"#N"` (see `formatSeq`/`toAgentMessages`) —// the ack cursor schema wants the bare number back (`parseSeq`).const pulled = (await pullRes.json()) as { messages: Array<{ seq: string; channel: string }> }expect(pulled.messages.length).toBeGreaterThan(0)const lastPulled = pulled.messages[pulled.messages.length - 1]!- const ackRes = await fetchWithRetry(`${APP_URL}/api/community/agent/ack`, {+ const ackRes = await fetchWithRetry(`${APP_URL}/api/community/ack`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({ cursors: [{ channel: lastPulled.channel, seq: parseSeq(lastPulled.seq) }] }),@@ -179,7 +193,7 @@ describe("daemon control plane — real ws-do wake round-trip", () => {expect(ackRes.ok).toBe(true)const replyText = `reply from the real credential chain ${nanoid()}`- const sendRes = await fetchWithRetry(`${APP_URL}/api/community/agent/send`, {+ const sendRes = await fetchWithRetry(`${APP_URL}/api/community/send`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelName}`, content: { text: replyText } }),@@ -271,24 +285,24 @@ describe("daemon control plane — real ws-do wake round-trip", () => {expect(enrollRes.ok).toBe(true)const { runnerKey } = (await enrollRes.json()) as { runnerKey: string }- const pullRes = await fetchWithRetry(`${APP_URL}/api/community/agent/inboxPull`, {+ const pullRes = await fetchWithRetry(`${APP_URL}/api/community/inboxPull`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({}),})- expect(pullRes.ok).toBe(true)+ await assertResOk(pullRes, "inboxPull (:279 multi-bot enroll→pull)")const pulled = (await pullRes.json()) as { messages: Array<{ seq: string; channel: string }> }expect(pulled.messages.length).toBeGreaterThan(0)const lastPulled = pulled.messages[pulled.messages.length - 1]!- await fetchWithRetry(`${APP_URL}/api/community/agent/ack`, {+ await fetchWithRetry(`${APP_URL}/api/community/ack`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({ cursors: [{ channel: lastPulled.channel, seq: parseSeq(lastPulled.seq) }] }),})const replyText = `reply from ${bot.botUserId} ${nanoid()}`- const sendRes = await fetchWithRetry(`${APP_URL}/api/community/agent/send`, {+ const sendRes = await fetchWithRetry(`${APP_URL}/api/community/send`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelName}`, content: { text: replyText } }),