Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): resolve channel refs by name only, top-level scoped

Gus4e13cbe0ec47
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index c58dd5ac9..2416885c9 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -117,6 +117,13 @@ export const DM_SERVER = ".dm";
* `<server>`/`<channel>` are server/channel display *names*, guaranteed free
* of whitespace, `/`, and `#` (normalized via `slugify()` at creation/rename
* time), so each segment is always a single, unambiguous token.
+ *
+ * On agent surfaces, segments are NAMES (or `#seq`) — raw ids are rejected.
+ * The `/c` UI's `resolveChannelRefBase` still accepts ids for pill
+ * navigation, since the wire type is a single string shared by both
+ * surfaces; the split is enforced by the resolver, not the type. To descend
+ * into a thread or forum post, use the canonical `<server>/<channel>/#N`
+ * grammar; the underlying row's id is never a valid ref for agents.
*/
export type ChannelRef = string;
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index 2778b1a68..c7302bce9 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -4,9 +4,11 @@ import {
integer,
index,
unique,
+ uniqueIndex,
primaryKey,
type SQLiteTableWithColumns,
} from "drizzle-orm/sqlite-core";
+import { sql } from "drizzle-orm";
import { nanoid } from "nanoid";
import { user } from "./schema";
@@ -72,6 +74,12 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(
index("idx_channel_server_position").on(t.serverId, t.position),
index("idx_channel_server_last_message").on(t.serverId, t.lastMessageAt),
index("idx_channel_parent").on(t.parentChannelId),
+ // Partial unique — top-level channel names are unique per server.
+ // Source of truth: migration 0057_channel_unique_name.sql. Threads and
+ // forum posts (parent_channel_id NOT NULL) are exempt by design.
+ uniqueIndex("idx_channel_server_name")
+ .on(t.serverId, t.name)
+ .where(sql`parent_channel_id IS NULL`),
]
);
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index d2ca118ed..806c5567b 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -215,19 +215,29 @@ export async function listServerChannels(db: Database, serverId: string) {
}
/**
- * `resolveTargetForMember`'s channel-name resolver: matches by ID or NAME
- * within one server, visibility-scoped to `userId`'s membership in that
- * server (same gate as `getChannelForMember`). Returns an ARRAY — like
- * `resolveServerByNameForMember`, ambiguity (2+ name matches) is not an
- * error; the caller returns a hint list (debt #5).
+ * `resolveTargetForMember`'s channel-name resolver: matches by NAME only,
+ * scoped to top-level channels (`parentChannelId IS NULL`) — mirrors the
+ * DB partial-unique index `idx_channel_server_name` from migration 0057.
+ *
+ * Ids are NOT accepted from agent surfaces. Agents address channels via
+ * the canonical ref grammar (`/server/channel`, `/server/channel/#seq`);
+ * ids are a `/c` UI internal. Threads and forum posts must be reached
+ * through their parent + `#seq`, never by direct name or id here.
+ *
+ * The returned array is length 0 or 1: the WHERE clause narrows to a single
+ * `(serverId, name)` slot within the top-level partition, and the partial
+ * unique index `idx_channel_server_name` (migration 0057) guarantees that
+ * slot holds at most one row. The caller returns `channel not found` on
+ * empty and passes the single row through otherwise. Visibility-scoped to
+ * `userId`'s server membership.
*/
export async function resolveChannelByNameForMember(
db: Database,
serverId: string,
userId: string,
- nameOrId: string
+ name: string
) {
- const byId = await db
+ const rows = await db
.select(CHANNEL_COLUMNS)
.from(communityChannel)
.innerJoin(
@@ -237,21 +247,14 @@ export async function resolveChannelByNameForMember(
eq(communityServerMember.userId, userId)
)
)
- .where(and(eq(communityChannel.serverId, serverId), eq(communityChannel.id, nameOrId)));
- if (byId.length > 0) return byId.map(mapChannelRow);
-
- const byName = await db
- .select(CHANNEL_COLUMNS)
- .from(communityChannel)
- .innerJoin(
- communityServerMember,
+ .where(
and(
- eq(communityServerMember.serverId, communityChannel.serverId),
- eq(communityServerMember.userId, userId)
+ eq(communityChannel.serverId, serverId),
+ eq(communityChannel.name, name),
+ isNull(communityChannel.parentChannelId)
)
- )
- .where(and(eq(communityChannel.serverId, serverId), eq(communityChannel.name, nameOrId)));
- return byName.map(mapChannelRow);
+ );
+ return rows.map(mapChannelRow);
}
/**
diff --git a/src/shared/test/queries/community-channel-resolve.test.ts b/src/shared/test/queries/community-channel-resolve.test.ts
new file mode 100644
index 000000000..cf8e60727
--- /dev/null
+++ b/src/shared/test/queries/community-channel-resolve.test.ts
@@ -0,0 +1,152 @@
+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
+// builder is fluent — `.select(...).from(...).innerJoin(...).where(expr)` —
+// and each stage returns the same chain object; `where` resolves with the
+// stubbed rows.
+function createSelectChain(rows: unknown[]) {
+ const chain: Record<string, unknown> = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.innerJoin = vi.fn(() => chain);
+ chain.where = vi.fn((_expr: unknown) => Promise.resolve(rows));
+ 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[] {
+ 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);
+ }
+ 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();
+}
+
+describe("resolveChannelByNameForMember — SQL invariants", () => {
+ it("filters by name AND parent_channel_id IS NULL (top-level only)", async () => {
+ const db = createSelectChain([]);
+ await channelQueries.resolveChannelByNameForMember(db as never, "srv_1", "u_1", "general");
+
+ expect(db.where).toHaveBeenCalledOnce();
+ const [whereExpr] = db.where.mock.calls[0]!;
+ const chunkStr = chunksToString(collectChunks(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");
+ });
+
+ it("does NOT fall back to matching by id (agent surfaces reject raw ids)", async () => {
+ const db = createSelectChain([]);
+ await channelQueries.resolveChannelByNameForMember(
+ db as never,
+ "srv_1",
+ "u_1",
+ "mFUplbfFL7PIzeiaP3Ysg",
+ );
+
+ // Exactly one SELECT — the deleted id-fallback would have made a second
+ // roundtrip if the first missed. `.where` fires once per SELECT.
+ expect(db.where).toHaveBeenCalledOnce();
+
+ const [whereExpr] = db.where.mock.calls[0]!;
+ const chunkStr = chunksToString(collectChunks(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");
+ });
+
+ it("scopes lookup to server AND caller's membership (no cross-server leak)", async () => {
+ const db = createSelectChain([]);
+ await channelQueries.resolveChannelByNameForMember(db as never, "srv_1", "u_1", "general");
+
+ // innerJoin is what enforces membership-scoping; dropping it would let a
+ // caller resolve channels on servers they don't belong to.
+ const chain = db as unknown as { innerJoin: ReturnType<typeof vi.fn> };
+ expect(chain.innerJoin).toHaveBeenCalledOnce();
+
+ const [whereExpr] = db.where.mock.calls[0]!;
+ const chunkStr = chunksToString(collectChunks(whereExpr));
+ expect(chunkStr).toContain("col:server_id");
+ });
+
+ it("returns [] when no top-level row matches — the DB partial-unique guarantees ≤1", async () => {
+ const db = createSelectChain([]);
+ const rows = await channelQueries.resolveChannelByNameForMember(
+ db as never,
+ "srv_1",
+ "u_1",
+ "general",
+ );
+ expect(rows).toEqual([]);
+ });
+
+ it("returns the single matched row", async () => {
+ const dbRow = {
+ id: "ch_top",
+ serverId: "srv_1",
+ categoryId: null,
+ name: "general",
+ type: "text",
+ topic: "",
+ position: 0,
+ forumTags: null,
+ parentChannelId: null,
+ creatorId: "u_1",
+ messageCount: 0,
+ archived: 0,
+ parentMessageId: null,
+ lastMessageAt: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+ const db = createSelectChain([dbRow]);
+ const rows = await channelQueries.resolveChannelByNameForMember(
+ db as never,
+ "srv_1",
+ "u_1",
+ "general",
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.id).toBe("ch_top");
+ expect(rows[0]!.parentChannelId).toBeNull();
+ // forumTags is projected as `tags: string[]` (safeParseForumTags).
+ expect(rows[0]!.tags).toEqual([]);
+ });
+});
diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.ts
index c72eaca8f..a3c78b7cd 100644
--- a/src/web/src/lib/community/channel-ref.ts
+++ b/src/web/src/lib/community/channel-ref.ts
@@ -3,9 +3,13 @@ import { parseRef } from "@alook/shared"
/**
* Client-side "directory" of every channel-ref-resolvable server + channel —
* built from already-fetched data (see `use-channel-ref-directory.ts`), not
- * a fresh fetch per ref. Mirrors the shape the backend resolves against
- * (`resolveServerByNameForMember`/`resolveChannelByNameForMember`), scoped to
- * whatever servers/channels the client already has loaded.
+ * a fresh fetch per ref. Scoped to whatever servers/channels the client
+ * already has loaded.
+ *
+ * This file is used by `/c` UI only and MAY accept raw ids (message-ref
+ * pill rendering, in-window navigation both round-trip channel ids). The
+ * agent-facing resolver (`resolveChannelByNameForMember`) does NOT accept
+ * ids — do not use this helper on agent code paths.
*/
type ChannelRefDirectoryChannel = { id: string; name: string }
export type ChannelRefDirectoryServer = {
@@ -24,10 +28,11 @@ export type ResolvedChannelRef = {
/**
* Resolve a raw `/server/channel` (or `/server/channel/#N`) ref string
- * against an already-fetched client-side directory. Mirrors
- * `resolveServerByNameForMember`/`resolveChannelByNameForMember`'s
- * id-then-exact-name lookup precedence, but purely in-memory — no network
- * call, and no ambiguity error.
+ * against an already-fetched client-side directory. UI-only: tries id
+ * first, then exact name — the id fallback exists here because pill links
+ * and in-window navigation store raw channel ids. Purely in-memory (no
+ * network call) and no ambiguity error. The agent-facing resolver is
+ * strictly name-only; this helper must not be used on agent code paths.
*
* Ambiguity tie-break (deliberately simpler than the backend): server/channel
* names aren't unique in the schema, and the backend surfaces 2+ name matches
@@ -74,9 +79,9 @@ export function resolveChannelRefBase(
/**
* Resolve a bare `/server` ref (one segment, no channel — `parseRef` throws
* on this shape since it requires `/<server>/<channel>`) against the
- * already-fetched directory. Id-then-exact-name lookup, same precedence and
- * duplicate-name simplification as `resolveChannelRefBase` — see that
- * function's doc comment.
+ * already-fetched directory. UI-only: id-then-exact-name lookup with the
+ * same duplicate-name simplification as `resolveChannelRefBase` — see that
+ * function's doc comment. Not for agent code paths.
*/
export function resolveServerRefBase(
directory: ChannelRefDirectory,
diff --git a/src/web/src/lib/community/resolve-ref.test.ts b/src/web/src/lib/community/resolve-ref.test.ts
index 7c97d5842..fca9660f8 100644
--- a/src/web/src/lib/community/resolve-ref.test.ts
+++ b/src/web/src/lib/community/resolve-ref.test.ts
@@ -148,25 +148,38 @@ describe("resolveTargetForMember", () => {
expect(res).toEqual({ error: 404, message: "channel not found: general" })
})
- it("400 ambiguous channel name returns hint list", async () => {
+ it("resolves a plain channel ref to { kind: channel, channelId }", async () => {
mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }, { id: "ch_2" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])
const res = await resolveTargetForMember(db, "u_1", "/studio/general")
- expect(res).toEqual({
- error: 400,
- message: "ambiguous channel name",
- hint: [
- { id: "ch_1", path: "/srv_1/ch_1" },
- { id: "ch_2", path: "/srv_1/ch_2" },
- ],
- })
+ expect(res).toEqual({ kind: "channel", channelId: "ch_1" })
})
- it("resolves a plain channel ref to { kind: channel, channelId }", async () => {
+ it("resolves to the top-level channel when a thread under it shares the same name", async () => {
+ // DB partial-unique guarantees the resolver returns at most one row for
+ // a name lookup — the top-level channel. Same-named thread stays
+ // unreachable via the name path.
mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_top" }])
const res = await resolveTargetForMember(db, "u_1", "/studio/general")
- expect(res).toEqual({ kind: "channel", channelId: "ch_1" })
+ expect(res).toEqual({ kind: "channel", channelId: "ch_top" })
+ expect(mockResolveChannelByNameForMember).toHaveBeenCalledWith(db, "srv_1", "u_1", "general")
+ })
+
+ it("404 channel not found when caller passes a raw top-level channel id (id refs rejected)", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
+ // Name-only resolver returns [] when the segment is an id — the DB
+ // lookup misses because the row's `name` column doesn't match the id.
+ mockResolveChannelByNameForMember.mockResolvedValue([])
+ const res = await resolveTargetForMember(db, "u_1", "/studio/mFUplbfFL7PIzeiaP3Ysg")
+ expect(res).toEqual({ error: 404, message: "channel not found: mFUplbfFL7PIzeiaP3Ysg" })
+ })
+
+ it("404 channel not found when caller passes a raw thread id (id refs rejected)", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([])
+ const res = await resolveTargetForMember(db, "u_1", "/studio/WyHlYFioUV_V9oRZXlSir")
+ expect(res).toEqual({ error: 404, message: "channel not found: WyHlYFioUV_V9oRZXlSir" })
})
})
diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.ts
index 03b09cbb0..2703b3475 100644
--- a/src/web/src/lib/community/resolve-ref.ts
+++ b/src/web/src/lib/community/resolve-ref.ts
@@ -28,11 +28,16 @@ export interface ResolveTargetOpts {
* `createCommunityMessage` — see plan §5's "MessageTarget reconstruction"
* note, this function intentionally does NOT do that itself.
*
- * Ambiguity (debt #5) is not a hard error: if a server/channel NAME matches
- * more than one candidate, this returns `{ error: 400, hint: [...] }` so the
- * agent can pick. `createDmIfMissing`/`createThreadIfMissing` are both
- * `true` for `send` only — every other route passes `false` so a stale ref
- * never materializes a DM/thread row as a side effect of a read.
+ * Channel names are unique per server for top-level channels (migration
+ * 0057's partial-unique index `idx_channel_server_name`) — the resolver
+ * enforces the same invariant by matching only where `parentChannelId IS
+ * NULL`. Threads and forum posts are unreachable from this helper by name
+ * or id; use the canonical `#seq` grammar to descend into a thread. Server
+ * NAME ambiguity is still possible (server names are non-unique) and still
+ * returns `{ error: 400, hint: [...] }` so the agent can pick.
+ * `createDmIfMissing`/`createThreadIfMissing` are both `true` for `send`
+ * only — every other route passes `false` so a stale ref never materializes
+ * a DM/thread row as a side effect of a read.
*/
export async function resolveTargetForMember(
db: Database,
@@ -96,25 +101,22 @@ export async function resolveTargetForMember(
}
const serverId = servers[0]!.id
- const channels = await queries.communityChannel.resolveChannelByNameForMember(db, serverId, userId, parsed.channel)
- if (channels.length === 0) return { error: 404, message: `channel not found: ${parsed.channel}` }
- if (channels.length > 1) {
- return {
- error: 400,
- message: "ambiguous channel name",
- hint: channels.map((c) => ({ id: c.id, path: `/${serverId}/${c.id}` })),
- }
- }
- const channel = channels[0]!
+ const matches = await queries.communityChannel.resolveChannelByNameForMember(db, serverId, userId, parsed.channel)
+ if (matches.length === 0) return { error: 404, message: `channel not found: ${parsed.channel}` }
+ const channel = matches[0]!
if (parsed.threadRootSeq === undefined) {
return { kind: "channel", channelId: channel.id }
}
- // A thread may only root on a TOP-LEVEL channel — never on a forum post or
- // another thread (that grandchild would defeat the single-level privacy
- // anchor climb and leak a private forum's thread server-wide). Reject with a
- // clean 400 here; `createThreadChannel` also enforces this as a last resort.
+ // Defense in depth: a thread may only root on a TOP-LEVEL channel — never
+ // on a forum post or another thread (that grandchild would defeat the
+ // single-level privacy anchor climb and leak a private forum's thread
+ // server-wide). This branch is provably unreachable via the current name
+ // resolver (`resolveChannelByNameForMember` filters `parent_channel_id IS
+ // NULL`, so `channel.parentChannelId` is always null here); it stays as a
+ // guard against future changes that widen that resolver, and mirrors what
+ // `createThreadChannel` enforces at the DB layer as a last resort.
if (channel.parentChannelId) {
return { error: 400, message: "can't start a thread inside a thread or forum post" }
}