Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): drop dead forum_post arms from agent surface

Gusd2efcd3c6e0a
diff --git a/src/shared/test/queries/community-channel-resolve.test.ts b/src/shared/test/queries/community-channel-resolve.test.ts
index cf8e60727..045486d25 100644
--- a/src/shared/test/queries/community-channel-resolve.test.ts
+++ b/src/shared/test/queries/community-channel-resolve.test.ts
@@ -1,7 +1,5 @@
import { describe, it, expect, vi } from "vitest";
-import { getTableColumns } from "drizzle-orm";
import * as channelQueries from "../../src/db/queries/community/channel";
-import { communityChannel } from "../../src/db/community-schema";
// Captures the SQL expression handed to `.where()` so we can prove the
// resolver's invariants without a live D1 instance. The Drizzle query
@@ -17,38 +15,50 @@ function createSelectChain(rows: unknown[]) {
return chain as unknown as { where: ReturnType<typeof vi.fn> };
}
-// Flatten a Drizzle `SQL` chunk tree into the leaf tokens/columns we care
-// about — enough to assert "this predicate references column X and uses IS
-// NULL semantics" without duplicating the compiler.
-function collectChunks(expr: unknown, out: unknown[] = []): unknown[] {
+// Render a single Drizzle chunk to a stable token we can pattern-match.
+// Column instances → `col:<name>`; StringChunk-like (`.value: string[]`) →
+// their inline SQL fragment(s); bind Param instances (`.encoder` present)
+// → `?`; anything else → `?` too. Bare-string `.value` chunks fall through
+// to their raw value — used by StringChunk in some drizzle versions.
+function renderChunk(c: unknown): string {
+ if (typeof c === "string") return c;
+ if (c && typeof c === "object") {
+ const rec = c as Record<string, unknown>;
+ if (rec.name && typeof rec.name === "string" && "table" in rec) return `col:${rec.name}`;
+ if ("encoder" in rec) return "?";
+ if (Array.isArray(rec.value)) {
+ return rec.value.filter((v) => typeof v === "string").map((v) => (v as string).trim()).join(" ").trim();
+ }
+ if (typeof rec.value === "string") return (rec.value as string).trim();
+ }
+ return "?";
+}
+
+// Flatten a Drizzle `SQL(...)` node into an ordered list of rendered tokens.
+// Each leaf keeps its position, so downstream assertions can match a
+// contiguous phrase like `[col:X, "is null"]` rather than checking two
+// unrelated substrings in one big string.
+function flattenTokens(expr: unknown, out: string[] = []): string[] {
if (expr == null || typeof expr !== "object") return out;
const e = expr as Record<string, unknown>;
if (Array.isArray(e.queryChunks)) {
- for (const chunk of e.queryChunks) collectChunks(chunk, out);
- } else if (Array.isArray(e.chunks)) {
- for (const chunk of e.chunks) collectChunks(chunk, out);
- } else {
- out.push(expr);
+ for (const chunk of e.queryChunks) flattenTokens(chunk, out);
+ return out;
}
+ out.push(renderChunk(expr));
return out;
}
-function chunksToString(chunks: unknown[]): string {
- return chunks
- .map((c) => {
- if (typeof c === "string") return c;
- if (c && typeof c === "object") {
- const rec = c as Record<string, unknown>;
- // Column reference (Drizzle Column instance).
- if (rec.name && typeof rec.name === "string" && "table" in rec) return `col:${rec.name}`;
- // Raw string chunk (StringChunk-like — `.value` is the SQL fragment).
- if (Array.isArray(rec.value)) return rec.value.filter((v) => typeof v === "string").join(" ");
- if (typeof rec.value === "string") return rec.value;
- }
- return "?";
- })
- .join(" ")
- .toLowerCase();
+// True iff the ordered token list contains a contiguous `[col:X, tail]`
+// phrase — i.e. `is null` is applied to X specifically, not to some other
+// column that happens to sit elsewhere in the predicate.
+function tokensContainPhrase(tokens: string[], colName: string, tail: string): boolean {
+ const wantCol = `col:${colName}`;
+ const wantTail = tail.toLowerCase();
+ for (let i = 0; i < tokens.length - 1; i++) {
+ if (tokens[i] === wantCol && tokens[i + 1]!.toLowerCase().startsWith(wantTail)) return true;
+ }
+ return false;
}
describe("resolveChannelByNameForMember — SQL invariants", () => {
@@ -58,17 +68,17 @@ describe("resolveChannelByNameForMember — SQL invariants", () => {
expect(db.where).toHaveBeenCalledOnce();
const [whereExpr] = db.where.mock.calls[0]!;
- const chunkStr = chunksToString(collectChunks(whereExpr));
+ const tokens = flattenTokens(whereExpr);
// The name predicate compares against the name column, not the id column.
- expect(chunkStr).toContain("col:name");
- expect(chunkStr).not.toMatch(/col:id\b/);
-
- // The parent_channel_id IS NULL predicate must be present — this is the
- // whole invariant of the fix. Without it, threads/forum_posts would leak
- // into name lookups and reintroduce the ambiguous-channel bug.
- expect(chunkStr).toContain("col:parent_channel_id");
- expect(chunkStr).toContain("is null");
+ expect(tokens).toContain("col:name");
+ expect(tokens).not.toContain("col:id");
+
+ // `IS NULL` must be applied to `parent_channel_id` specifically — a
+ // future refactor that swapped in `isNull(categoryId)` while still
+ // referencing `parentChannelId` elsewhere in the predicate would not
+ // reproduce the invariant. This is the whole point of the fix.
+ expect(tokensContainPhrase(tokens, "parent_channel_id", "is null")).toBe(true);
});
it("does NOT fall back to matching by id (agent surfaces reject raw ids)", async () => {
@@ -85,12 +95,10 @@ describe("resolveChannelByNameForMember — SQL invariants", () => {
expect(db.where).toHaveBeenCalledOnce();
const [whereExpr] = db.where.mock.calls[0]!;
- const chunkStr = chunksToString(collectChunks(whereExpr));
+ const tokens = flattenTokens(whereExpr);
// The id column of communityChannel must NOT be part of the predicate —
// that's the "no id back-door" guarantee the plan locks in.
- const idCol = getTableColumns(communityChannel).id;
- expect(idCol.name).toBe("id");
- expect(chunkStr).not.toContain("col:id");
+ expect(tokens).not.toContain("col:id");
});
it("scopes lookup to server AND caller's membership (no cross-server leak)", async () => {
@@ -103,8 +111,8 @@ describe("resolveChannelByNameForMember — SQL invariants", () => {
expect(chain.innerJoin).toHaveBeenCalledOnce();
const [whereExpr] = db.where.mock.calls[0]!;
- const chunkStr = chunksToString(collectChunks(whereExpr));
- expect(chunkStr).toContain("col:server_id");
+ const tokens = flattenTokens(whereExpr);
+ expect(tokens).toContain("col:server_id");
});
it("returns [] when no top-level row matches — the DB partial-unique guarantees ≤1", async () => {
diff --git a/src/web/src/app/api/community/agent/channelMember/route.test.ts b/src/web/src/app/api/community/agent/channelMember/route.test.ts
index fda0b9b9e..d389fc162 100644
--- a/src/web/src/app/api/community/agent/channelMember/route.test.ts
+++ b/src/web/src/app/api/community/agent/channelMember/route.test.ts
@@ -213,33 +213,9 @@ describe("POST /api/community/agent/channelMember", () => {
expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "th_1")
})
- it("forum post inside a PUBLIC forum → still private on the wire; roster is the PARTICIPANT set, not the whole server", async () => {
- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])
- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "post_1", name: "bug-42", type: "forum_post", parentChannelId: "forum_1" }])
- // Access context: public forum (isPrivate=false) but the channel itself is a
- // `forum_post` — the route must NOT fall into the public/hint branch. A post
- // is the NOTIFY dimension: its roster is the participant set (like a thread),
- // never the whole server.
- mockResolveChannelAccessContext.mockResolvedValue({
- channel: { id: "post_1", serverId: "srv_1", type: "forum_post", parentChannelId: "forum_1", creatorId: "bot_1", categoryId: null },
- anchor: { id: "forum_1", type: "forum", creatorId: "owner_1", categoryId: null },
- role: "member",
- isChannelMember: false,
- isCreator: true,
- isPrivate: false,
- })
- mockListThreadParticipantUserIds.mockResolvedValue(["u_bot", "u_alice"])
- mockGetMembersByUserIds.mockResolvedValue([
- { userName: "gus", discriminator: "4821", role: "member", nickname: null },
- { userName: "alice", discriminator: "0193", role: "member", nickname: null },
- ])
-
- const res = await POST(req({ channel: "/demo/bug-42" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(200)
- const body = await res.json()
- expect(body.visibility).toBe("private")
- expect(body.members).toHaveLength(2)
- expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "post_1")
- expect(mockResolveScopeMembers).not.toHaveBeenCalledWith(expect.anything(), { scope: "post", scopeId: "post_1" })
- })
+ // Forum posts are not agent-addressable via any current ref grammar
+ // (`resolveChannelByNameForMember` filters `parent_channel_id IS NULL`
+ // and `#N` refs materialize as `type: "thread"`), so there is no code
+ // path that reaches this handler with a `forum_post` row. If forum-post
+ // refs are ever reintroduced, add a test back here.
})
diff --git a/src/web/src/app/api/community/agent/channelMember/route.ts b/src/web/src/app/api/community/agent/channelMember/route.ts
index 53f162162..1d3c15b0b 100644
--- a/src/web/src/app/api/community/agent/channelMember/route.ts
+++ b/src/web/src/app/api/community/agent/channelMember/route.ts
@@ -4,7 +4,6 @@ import {
CommunityAgentChannelMemberRequestSchema,
DM_SERVER,
formatHandle,
- isForumPost,
isThread,
parseRef,
} from "@alook/shared"
@@ -25,11 +24,12 @@ import { requireChannelAccess } from "@/lib/community/permissions"
* - DM ref → 400 (channel-scoped). Rejected UP FRONT (before
* `resolveTargetForMember`) so an un-opened DM surfaces the correct
* channel-scoped 400 instead of a misleading 404 "dm not found".
- * - thread / forum post (`type = "thread" | "forum_post"`) → always private on
- * the wire; returns the participant roster (`community_thread_participant`).
- * Both are the NOTIFY dimension: a thread/post carries its own notify set
- * irrespective of its parent channel/forum's public/private state, so a
- * public post lists only its participants, never the whole server.
+ * - thread (`type = "thread"`) → always private on the wire; returns the
+ * participant roster (`community_thread_participant`). Threads are the
+ * NOTIFY dimension: they carry their own notify set irrespective of the
+ * parent channel's public/private state. Forum posts share this shape but
+ * are not agent-addressable via any current ref grammar, so this branch
+ * only fires for threads reached via `<server>/<channel>/#N`.
* - public top-level channel/forum → `{ visibility: "public", hint }` (no
* roster enumeration — every server member can see it, so the agent should
* use `alook server member --server <name>` instead).
@@ -85,11 +85,11 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
const { channel, isPrivate } = access.value
- // Thread / forum-post branch: both are the NOTIFY dimension — the roster is
- // the participant set (`community_thread_participant`), always private on the
- // wire, regardless of the parent channel/forum's public/private state. A
- // public forum post therefore lists only its participants, not the server.
- if (isThread(channel.type) || isForumPost(channel.type)) {
+ // Thread branch: the NOTIFY dimension — the roster is the participant set
+ // (`community_thread_participant`), always private on the wire regardless of
+ // the parent's public/private state. Forum posts are not agent-addressable,
+ // so this handler only sees `thread` or top-level channel rows here.
+ if (isThread(channel.type)) {
const userIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)
const members = await hydrateMembers(db, channel.serverId, userIds)
return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })
diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.ts
index cdefff217..2b1d3c4e3 100644
--- a/src/web/src/app/api/community/agent/send/route.ts
+++ b/src/web/src/app/api/community/agent/send/route.ts
@@ -76,9 +76,14 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)
if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })
const channel = gate.value
+ // Only threads have a non-null parentChannelId in this path — the ref
+ // resolver filters name lookups to top-level (parent_channel_id IS NULL)
+ // and thread refs (`#N`) create/reuse rows with type="thread". Forum
+ // posts are not addressable by any agent ref today, so no `forum_post`
+ // arm is needed here.
target = channel.parentChannelId
? {
- kind: channel.type === "forum_post" ? "forum_post" : "thread",
+ kind: "thread",
channelId: channel.id,
parentChannelId: channel.parentChannelId,
serverId: channel.serverId,