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
test(shared): strengthen scoped query and policy guards (#1191)
Genera1df97ca8b92
diff --git a/src/shared/test/queries/community-channel-resolve.test.ts b/src/shared/test/queries/community-channel-resolve.test.tsindex 7c03c1850..c37162602 100644--- a/src/shared/test/queries/community-channel-resolve.test.ts+++ b/src/shared/test/queries/community-channel-resolve.test.ts@@ -1,133 +1,84 @@-import { describe, it, expect, vi } from "vitest";-import * as channelQueries from "../../src/db/queries/community/channel";--// 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> };-}--// 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) flattenTokens(chunk, out);- return out;- }- out.push(renderChunk(expr));- return out;-}+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, it, expect } from "vitest";+import type { Database } from "../../src/db";+import { resolveChannelByNameForMember } from "../../src/db/queries/community/channel";++describe("resolveChannelByNameForMember — native SQLite scope", () => {+ let sqlite: Sqlite.Database;+ let db: Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE user (id TEXT PRIMARY KEY);+ CREATE TABLE community_server (id TEXT PRIMARY KEY);+ CREATE TABLE community_server_member (+ id TEXT PRIMARY KEY, server_id TEXT NOT NULL, user_id TEXT NOT NULL,+ role TEXT NOT NULL DEFAULT 'member', joined_at TEXT NOT NULL,+ UNIQUE(server_id, user_id)+ );+ CREATE TABLE community_channel (+ id TEXT PRIMARY KEY, server_id TEXT NOT NULL, category_id TEXT,+ name TEXT NOT NULL, type TEXT NOT NULL DEFAULT 'text',+ topic TEXT NOT NULL DEFAULT '', position INTEGER NOT NULL DEFAULT 0,+ parent_channel_id TEXT, creator_id TEXT NOT NULL DEFAULT 'u_1',+ message_count INTEGER NOT NULL DEFAULT 0, archived INTEGER NOT NULL DEFAULT 0,+ parent_message_id TEXT, last_message_at TEXT,+ created_at TEXT NOT NULL DEFAULT '2026-01-01T00:00:00.000Z'+ );+ CREATE TABLE community_message (id TEXT PRIMARY KEY, channel_id TEXT NOT NULL);+ INSERT INTO user VALUES ('u_1'), ('u_2'), ('u_peer'), ('u_none');+ INSERT INTO community_server VALUES ('srv_1'), ('srv_2');+ INSERT INTO community_server_member (id, server_id, user_id, joined_at) VALUES+ ('m_1a', 'srv_1', 'u_1', '2025-01-01T00:00:00.000Z'),+ ('m_1b', 'srv_2', 'u_1', '2025-01-01T00:00:00.000Z'),+ ('m_2', 'srv_2', 'u_2', '2025-01-01T00:00:00.000Z'),+ ('m_peer', 'srv_1', 'u_peer', '2025-01-01T00:00:00.000Z');+ INSERT INTO community_channel (id, server_id, name) VALUES+ ('ch_top', 'srv_1', 'general'),+ ('ch_foreign', 'srv_2', 'general'),+ ('ch_random', 'srv_1', 'random'),+ ('mFUplbfFL7PIzeiaP3Ysg', 'srv_1', 'opaque-name');+ INSERT INTO community_message VALUES ('opener', 'ch_top');+ INSERT INTO community_channel (id, server_id, name, type, parent_channel_id, parent_message_id)+ VALUES ('ch_child', 'srv_1', 'general', 'thread', 'ch_top', 'opener');+ `);+ db = drizzle(sqlite) as unknown as Database;+ });-// 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;-}+ afterEach(() => sqlite.close());-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 tokens = flattenTokens(whereExpr);-- // The name predicate compares against the name column, not the id column.- 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);+ const rows = await resolveChannelByNameForMember(db, "srv_1", "u_1", "general");+ expect(rows.map(({ id, name, parentChannelId }) => ({ id, name, parentChannelId })))+ .toEqual([{ id: "ch_top", name: "general", parentChannelId: 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 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.- expect(tokens).not.toContain("col:id");+ expect(await resolveChannelByNameForMember(db, "srv_1", "u_1", "mFUplbfFL7PIzeiaP3Ysg"))+ .toEqual([]);+ expect((await resolveChannelByNameForMember(db, "srv_1", "u_1", "opaque-name")).map((row) => row.id))+ .toEqual(["mFUplbfFL7PIzeiaP3Ysg"]);});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 tokens = flattenTokens(whereExpr);- expect(tokens).toContain("col:server_id");+ expect((await resolveChannelByNameForMember(db, "srv_1", "u_1", "general")).map((row) => row.id))+ .toEqual(["ch_top"]);+ expect((await resolveChannelByNameForMember(db, "srv_2", "u_1", "general")).map((row) => row.id))+ .toEqual(["ch_foreign"]);+ expect(await resolveChannelByNameForMember(db, "srv_1", "u_2", "general")).toEqual([]);+ expect((await resolveChannelByNameForMember(db, "srv_2", "u_2", "general")).map((row) => row.id))+ .toEqual(["ch_foreign"]);+ expect(await resolveChannelByNameForMember(db, "srv_1", "u_none", "general")).toEqual([]);});- 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 [] when no top-level row matches", async () => {+ expect(await resolveChannelByNameForMember(db, "srv_1", "u_1", "missing")).toEqual([]);});it("returns the single matched row", async () => {- const dbRow = {+ expect(await resolveChannelByNameForMember(db, "srv_1", "u_1", "general")).toEqual([{id: "ch_top",serverId: "srv_1",categoryId: null,@@ -142,16 +93,6 @@ describe("resolveChannelByNameForMember — SQL invariants", () => {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();+ }]);});});diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex af6906710..47bc56414 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -3,10 +3,6 @@ import { createDb } from "../../src/db";import * as inboxQueries from "../../src/db/queries/community/inbox";import { isChannelUnread, isDmUnread } from "../../src/db/queries/community/inbox";-// These tests pin the shape of the public API; SQL behavior is covered by-// integration runs against D1. The fact that this file imports cleanly-// also surfaces accidental query syntax regressions at typecheck time.-//// ref/id read-model seq unification: the unread predicate now compares SEQ// (`EXISTS(message.seq > lastReadSeq)`, computed in SQL) instead of the old// `lastMessageAt > lastReadAt` timestamp. The pure predicates take the SQL@@ -14,16 +10,6 @@ import { isChannelUnread, isDmUnread } from "../../src/db/queries/community/inbo// (the EXISTS result) — and the no-read-state branch still uses `joinedAt`// (channels) / "any message" (DMs), which are orthogonal to the seq switch.-describe("community/inbox exports", () => {- it("exports isChannelUnread", () => {- expect(typeof inboxQueries.isChannelUnread).toBe("function");- });- it("exports isDmUnread", () => {- expect(typeof inboxQueries.isDmUnread).toBe("function");- });--});-describe("isChannelUnread — two-branch predicate (seq)", () => {const j = "2026-07-06T00:00:00.000Z"; // joinedAtconst before = "2026-07-05T00:00:00.000Z"; // before join@@ -73,13 +59,13 @@ describe("isChannelUnread — two-branch predicate (seq)", () => {).toBe(false);});- it("has read-state takes the seq branch even when lastMessageAt < joinedAt (branch precedence)", () => {- // With a read-state row, the joinedAt branch never runs — the seq EXISTS- // is authoritative. A pre-join lastMessageAt with hasUnreadBeyondSeq=false- // is not unread; the joinedAt comparison is irrelevant here.+ it.each([+ [false, false],+ [true, true],+ ] as const)("has read-state takes the seq branch even when lastMessageAt < joinedAt (branch precedence): unread=%s → %s", (hasUnreadBeyondSeq, expected) => {expect(- isChannelUnread({ archived: false, lastMessageAt: before, hasReadState: true, hasUnreadBeyondSeq: false, joinedAt: j }),- ).toBe(false);+ isChannelUnread({ archived: false, lastMessageAt: before, hasReadState: true, hasUnreadBeyondSeq, joinedAt: j }),+ ).toBe(expected);});});@@ -98,7 +84,6 @@ describe("listUnreadChannels — seq read-watermark behaviour", () => {chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);chain.leftJoin = vi.fn(() => chain);- chain.leftJoin = vi.fn(() => chain);chain.where = vi.fn(() => Promise.resolve(rows));return chain;}@@ -138,7 +123,7 @@ describe("listUnreadChannels — seq read-watermark behaviour", () => {const db = createUnreadRowMock([{channelId: "ch_archived", channelName: "old", serverId: "srv_1", serverName: "server 1",- parentChannelId: null, lastMessageAt: "2026-07-06T00:00:00.000Z", hasReadState: 0, hasUnreadBeyondSeq: 0, archived: true, joinedAt: j,+ parentChannelId: null, lastMessageAt: "2026-07-06T00:00:05.000Z", hasReadState: 1, hasUnreadBeyondSeq: 1, archived: true, joinedAt: j,},]);const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_archived"]);diff --git a/src/shared/test/queries/community-notification-cursor-clear.test.ts b/src/shared/test/queries/community-notification-cursor-clear.test.tsindex e9a761f3c..5d9d3f08e 100644--- a/src/shared/test/queries/community-notification-cursor-clear.test.ts+++ b/src/shared/test/queries/community-notification-cursor-clear.test.ts@@ -218,6 +218,8 @@ describe("notification setting read-state isolation contract", () => {});expect(result.readStateRevision).toBeNull();+ expect(sqlite.prepare("SELECT level FROM community_notification_setting WHERE user_id='u' AND channel_id='parent'").get())+ .toEqual({ level: "nothing" });expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_read_state_revision").get()).toEqual({ count: 0 });});diff --git a/src/shared/test/queries/community-notification-setting.test.ts b/src/shared/test/queries/community-notification-setting.test.tsindex a53a6438e..99b9fd62e 100644--- a/src/shared/test/queries/community-notification-setting.test.ts+++ b/src/shared/test/queries/community-notification-setting.test.ts@@ -17,21 +17,6 @@ const POST = { id: "p1", serverId: "s1", parentChannelId: "c1" };// has serverId null and parentChannelId null).const DM = { id: "dm1", serverId: null as unknown as string, parentChannelId: null };-describe("community/notification-setting exports", () => {--- it("keeps the CRUD helpers", () => {- expect(typeof notif.getSettings).toBe("function");- expect(typeof notif.setServerLevel).toBe("function");- expect(typeof notif.setChannelLevel).toBe("function");- expect(typeof notif.removeChannelOverride).toBe("function");- });-- it("no longer exports the dead getMutedUserIds", () => {- expect((notif as Record<string, unknown>).getMutedUserIds).toBeUndefined();- });-});-describe("computeEffectiveLevel — 3-tier climb", () => {it("no setting rows at all → global default 'all'", () => {expect(notif.computeEffectiveLevel([], TEXT_CHANNEL)).toBe("all");diff --git a/src/shared/test/queries/community-realtime-audiences.test.ts b/src/shared/test/queries/community-realtime-audiences.test.tsindex 8a56e34ab..e048d1792 100644--- a/src/shared/test/queries/community-realtime-audiences.test.ts+++ b/src/shared/test/queries/community-realtime-audiences.test.ts@@ -8,7 +8,6 @@ import { filterChannelReadableUserIds, listReadableChannelsForUser, getReadableMdescribe("realtime channel audiences with canonical SQLite permissions", () => {let sqlite: Sqlite.Database;let db: Database;- let queryCount: number;beforeEach(() => {sqlite = new Sqlite(":memory:");sqlite.exec(`@@ -40,8 +39,7 @@ describe("realtime channel audiences with canonical SQLite permissions", () => {('da','dm','author','access'),('dr','dm','reader','access');INSERT INTO community_message VALUES ('message','private-thread');`);- queryCount = 0;- db = drizzle(sqlite, { logger: { logQuery: () => { queryCount++; } } }) as unknown as Database;+ db = drizzle(sqlite) as unknown as Database;});afterEach(() => sqlite.close());@@ -76,37 +74,11 @@ describe("realtime channel audiences with canonical SQLite permissions", () => {sqlite.prepare("DELETE FROM community_channel_member WHERE channel_id='private-post' AND relation='notify'").run();expect(await resolveChannelNotificationRecipientUserIds(db, "private-post")).toEqual([]);expect(await resolveChannelContentRecipientUserIds(db, "private-post")).toContain("participant");- expect(await listReadableChannelsForUser(db, "reader", ["private-thread", "post", "missing", "post"])).toHaveLength(2);+ expect((await listReadableChannelsForUser(db, "reader", ["private-thread", "post", "missing", "post"]))+ .map((row) => row.id).sort()).toEqual(["post", "private-thread"]);expect(await filterChannelReadableUserIds(db, "thread", [])).toEqual([]);});- it("preserves audience semantics while avoiding duplicate membership reads for 100 members", async () => {- for (let i = 0; i < 96; i++) {- const id = `extra-${i}`;- sqlite.prepare("INSERT INTO user VALUES (?)").run(id);- sqlite.prepare("INSERT INTO community_server_member VALUES (?, 'server', ?, 'member')").run(id, id);- }- const counts = [];- for (const id of ["text", "forum", "private-text", "private-forum", "dm", "thread", "private-thread"]) {- queryCount = 0;- const oldContent = await resolveChannelContentRecipientUserIds(db, id);- const oldNotifications = await resolveChannelNotificationRecipientUserIds(db, id);- const before = queryCount;- queryCount = 0;- const content = await resolveChannelContentRecipientUserIds(db, id);- const notifications = id.includes("thread")- ? await resolveChannelNotificationRecipientUserIds(db, id)- : content;- expect(content).toEqual(oldContent);- expect(notifications.filter((userId) => content.includes(userId)).sort())- .toEqual(oldNotifications.filter((userId) => oldContent.includes(userId)).sort());- if (id.includes("thread")) expect(queryCount).toBe(before);- else expect(queryCount).toBeLessThan(before);- counts.push({ scope: id, members: content.length, before, after: queryCount });- }- process.stdout.write("audience-query-counts " + JSON.stringify(counts) + "\n");- });-it("chunks a large readable audience without dropping or duplicating users", async () => {const ids = Array.from({ length: 200 }, (_, i) => `reader-${i}`);for (const id of ids) {diff --git a/src/shared/test/queries/community-wake-candidates.test.ts b/src/shared/test/queries/community-wake-candidates.test.tsindex 4db4c4e43..c906cd205 100644--- a/src/shared/test/queries/community-wake-candidates.test.ts+++ b/src/shared/test/queries/community-wake-candidates.test.ts@@ -1,4 +1,7 @@import { describe, it, expect, vi } from "vitest";+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import type { Database } from "../../src/db";import { findWakeCandidates } from "../../src/db/queries/community/bot";// Terminal-where mock — the module chains@@ -56,9 +59,10 @@ describe("findWakeCandidates", () => {const db = createSelectMock([row({ lastReadSeq: 3 }),row({ botUserId: "bot2", name: "kai", discriminator: "0002", machineId: "m2", runtime: "codex", lastReadSeq: 10 }),+ row({ botUserId: "bot3", name: "equal", discriminator: "0003", machineId: "m3", lastReadSeq: 7 }),]);const result = await findWakeCandidates(db as never, {- recipients: ["bot1", "bot2"],+ recipients: ["bot1", "bot2", "bot3"],channelId: "c1",newSeq: 7,});@@ -77,16 +81,48 @@ describe("findWakeCandidates", () => {expect(result).toEqual([candidate]);});- it("supports dmConversationId scope", async () => {- const db = createSelectMock([- row(),- ]);- const result = await findWakeCandidates(db as never, {- recipients: ["bot1"],- dmConversationId: "dm1",- newSeq: 1,- });- expect(result).toEqual([candidate]);+ it("isolates wake cursors with canonical channelId in a DM", async () => {+ const sqlite = new Sqlite(":memory:");+ try {+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY, name TEXT, discriminator TEXT NOT NULL,+ isBot INTEGER NOT NULL, deletedAt TEXT+ );+ CREATE TABLE community_bot_binding (+ user_id TEXT PRIMARY KEY, machine_id TEXT NOT NULL, runtime TEXT NOT NULL,+ instruction TEXT NOT NULL, is_active INTEGER NOT NULL+ );+ CREATE TABLE community_channel (id TEXT PRIMARY KEY, type TEXT NOT NULL);+ CREATE TABLE community_message (+ id TEXT PRIMARY KEY, channel_id TEXT NOT NULL, seq INTEGER NOT NULL, created_at TEXT NOT NULL+ );+ CREATE TABLE community_read_state (+ id TEXT PRIMARY KEY, user_id TEXT NOT NULL, channel_id TEXT NOT NULL,+ last_read_seq INTEGER NOT NULL, last_read_message_id TEXT NOT NULL,+ last_read_at TEXT NOT NULL, UNIQUE(user_id, channel_id)+ );+ INSERT INTO user VALUES ('bot1', 'zoe', '0001', 1, NULL), ('bot_neighbor', 'other', '0002', 1, NULL);+ INSERT INTO community_bot_binding VALUES+ ('bot1', 'm1', 'claude', 'Own triage', 1),+ ('bot_neighbor', 'm2', 'codex', 'Other triage', 1);+ INSERT INTO community_channel VALUES ('dm1', 'dm'), ('c1', 'text');+ INSERT INTO community_message VALUES+ ('dm-7', 'dm1', 7, '2026-01-01T00:00:07.000Z'),+ ('c-1', 'c1', 1, '2026-01-01T00:00:01.000Z'),+ ('c-7', 'c1', 7, '2026-01-01T00:00:07.000Z');+ INSERT INTO community_read_state VALUES+ ('rs-dm', 'bot1', 'dm1', 7, 'dm-7', '2026-01-01T00:00:07.000Z'),+ ('rs-c', 'bot1', 'c1', 1, 'c-1', '2026-01-01T00:00:01.000Z');+ `);+ const db = drizzle(sqlite) as unknown as Database;+ expect(await findWakeCandidates(db, { recipients: ["bot1"], channelId: "dm1", newSeq: 7 }))+ .toEqual([]);+ expect(await findWakeCandidates(db, { recipients: ["bot1"], channelId: "c1", newSeq: 7 }))+ .toEqual([candidate]);+ } finally {+ sqlite.close();+ }});it("issues exactly one db.select call — no notification-setting/mention lookups", async () => {