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
fix: enforce SQL budgets and atomic server creation (#912)
Gener3977c2fb0182
diff --git a/scripts/ci/d1-dynamic-bind-contract.test.ts b/scripts/ci/d1-dynamic-bind-contract.test.tsindex e36ea6908..2ea580bfe 100644--- a/scripts/ci/d1-dynamic-bind-contract.test.ts+++ b/scripts/ci/d1-dynamic-bind-contract.test.ts@@ -3,12 +3,8 @@ import { resolve } from "node:path"import { describe, expect, it } from "vitest"import { scanDynamicBindSites } from "./d1-dynamic-bind-contract"-type Strategy = "fixed-literal" | "exact-chunk" | "json-set" | "subquery" | "bounded-public-input"interface ManifestEntry {key: string- strategy: Strategy- fixedParams?: number- maxExport?: string}const root = resolve(import.meta.dirname, "../..")@@ -16,40 +12,24 @@ const manifest = JSON.parse(readFileSync(resolve(import.meta.dirname, "fixtures/d1-dynamic-bind-sites.json"), "utf8"),) as ManifestEntry[]-describe("D1 dynamic bind strategy contract", () => {- it("requires every source site to have one reviewed strategy", () => {+describe("D1 dynamic bind site inventory", () => {+ it("requires every source site to have one reviewed inventory entry", () => {const sites = scanDynamicBindSites(root)const actual = sites.map((site) => site.key)const expected = manifest.map((entry) => entry.key).sort()expect(new Set(expected).size).toBe(expected.length)expect(actual).toEqual(expected)- const expectedSites = new Map(sites.map((site) => [site.key, site]))- for (const entry of manifest) {- const site = expectedSites.get(entry.key)- expect(entry.strategy).toBe(site?.strategyHint)- expect(entry.fixedParams).toBe(site?.fixedParamsHint)- }})- it("requires strategy-specific bind budgets", () => {- const exportedLimits = [- "src/shared/src/constants.ts",- "src/shared/src/constants/community.ts",- "src/shared/src/schemas.ts",- "src/shared/src/index.ts",- ].map((file) => readFileSync(resolve(root, file), "utf8")).join("\n")-- for (const entry of manifest) {- if (entry.strategy === "exact-chunk") {- expect(entry.fixedParams, `${entry.key} needs fixedParams`).toBeTypeOf("number")- expect(entry.fixedParams!, `${entry.key} has an invalid fixed-bind budget`).toBeGreaterThanOrEqual(0)- expect(entry.fixedParams!, `${entry.key} has an invalid fixed-bind budget`).toBeLessThan(100)- }- if (entry.strategy === "bounded-public-input") {- expect(entry.maxExport, `${entry.key} needs maxExport`).toMatch(/^[A-Z][A-Z0-9_]+$/)- expect(exportedLimits).toMatch(new RegExp(`export const ${entry.maxExport}\\b`))- }- }+ it("does not certify an unbounded array with an invented strategy or budget", () => {+ const [site] = scanDynamicBindSites(root, {+ file: "fixture.ts",+ source: "export function naked(db: any, ids: string[]) { return db.select().where(inArray(table.id, ids)); }",+ })+ expect(site).not.toHaveProperty("strategyHint")+ expect(site).not.toHaveProperty("fixedParamsHint")+ expect(Object.keys(site!).sort()).toEqual(["file", "functionName", "key", "operator"])+ expect(manifest.every((entry) => Object.keys(entry).length === 1)).toBe(true)})it("detects an unreviewed dynamic bind site", () => {diff --git a/scripts/ci/d1-dynamic-bind-contract.ts b/scripts/ci/d1-dynamic-bind-contract.tsindex 83efe7e75..10b8005cf 100644--- a/scripts/ci/d1-dynamic-bind-contract.ts+++ b/scripts/ci/d1-dynamic-bind-contract.ts@@ -9,8 +9,6 @@ export interface DynamicBindSite {file: stringfunctionName: stringoperator: DynamicBindOperator- strategyHint: "fixed-literal" | "exact-chunk" | "json-set" | "subquery" | "bounded-public-input"- fixedParamsHint?: number}function sourceFiles(directory: string): string[] {@@ -63,35 +61,6 @@ function enclosingFunctionName(node: ts.Node): string {return "<module>"}-function enclosingFunction(node: ts.Node): ts.FunctionLikeDeclaration | undefined {- for (let current: ts.Node | undefined = node.parent; current; current = current.parent) {- if (ts.isFunctionLike(current)) return current- }- return undefined-}--function bindStrategyHint(node: ts.CallExpression, operator: DynamicBindOperator) {- if (operator !== "inArray" && operator !== "notInArray") {- return { strategyHint: "exact-chunk" as const, fixedParamsHint: 10 }- }- const argument = node.arguments[1]- if (argument && ts.isArrayLiteralExpression(argument) && !argument.elements.some(ts.isSpreadElement)) {- return { strategyHint: "fixed-literal" as const }- }- const sourceFile = node.getSourceFile()- const argumentText = argument?.getText(sourceFile).replace(/!$/, "") ?? ""- const functionText = enclosingFunction(node)?.getText(sourceFile) ?? ""- if (argumentText.includes("jsonTextSet(")- || new RegExp(`(?:const|let)\\s+${argumentText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=[\\s\\S]{0,80}?jsonTextSet\\(`).test(functionText)) {- return { strategyHint: "json-set" as const }- }- if (argumentText.includes(".select(")- || new RegExp(`(?:const|let)\\s+${argumentText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=\\s*db[\\s\\S]{0,80}?\\.select\\(`).test(functionText)) {- return { strategyHint: "subquery" as const }- }- return { strategyHint: "exact-chunk" as const, fixedParamsHint: 10 }-}-function callOperator(node: ts.CallExpression): DynamicBindOperator | undefined {if (ts.isIdentifier(node.expression) && (node.expression.text === "inArray" || node.expression.text === "notInArray")) {return node.expression.text@@ -130,31 +99,12 @@ export function scanDynamicBindSites(root: string, sourceOverride?: { file: striordinals.set(scope, ordinal)const relativeFile = sourceOverride ? sourceOverride.file : relative(root, file).replaceAll("\\", "/")const key = `${relativeFile}:${functionName}:${operator}:${ordinal}`- const hint = bindStrategyHint(node, operator)- const fixedParamsByKey: Record<string, number> = {- "src/shared/src/db/queries/community/channel.ts:createChannel:values:1": 0,- "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:1": 0,- "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:2": 0,- "src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:1": 0,- "src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:2": 2,- "src/shared/src/db/queries/community/member.ts:getMembersByUserIds:inArray:1": 1,- "src/shared/src/db/queries/community/reaction.ts:listReactionsByMessageIds:inArray:1": 0,- }- const boundedAttachmentSites = new Set([- "src/shared/src/db/queries/community/message.ts:eligibleAttachments:inArray:1",- "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:1",- "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:2",- "src/shared/src/db/queries/community/message.ts:insertMessageRow:sql.join:1",- ])sites.push({key,file: relativeFile,functionName,operator,- ...(boundedAttachmentSites.has(key) ? { strategyHint: "bounded-public-input" as const } : hint),- ...(hint.strategyHint === "exact-chunk" && key in fixedParamsByKey- ? { fixedParamsHint: fixedParamsByKey[key] }- : {}),+})}}diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.jsonindex fe94c1657..3d14f797c 100644--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json@@ -1,1098 +1,746 @@[{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:1"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:10",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:10"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:11",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:11"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:12",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:12"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:13",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:13"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:14",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:14"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:15",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:15"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:16",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:16"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:17",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:17"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:18",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:18"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:19",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:19"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:2"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:20",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:20"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:21",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:21"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:22",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:22"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:23",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:23"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:24",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:24"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:25",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:25"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:26",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:26"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:27",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:27"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:28",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:28"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:29",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:29"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:3",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:3"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:30",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:30"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:31",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:31"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:32",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:32"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:33",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:33"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:34",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:34"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:35",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:35"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:36",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:36"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:37",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:37"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:4",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:4"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:5",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:5"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:6",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:6"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:7",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:7"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:8",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:8"},{- "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:9",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:9"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:1"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:10",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:10"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:11",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:11"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:12",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:12"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:13",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:13"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:14",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:14"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:15",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:15"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:16",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:16"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:17",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:17"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:18",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:18"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:19",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:19"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:2"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:20",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:20"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:21",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:21"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:22",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:22"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:23",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:23"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:24",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:24"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:25",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:25"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:26",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:26"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:27",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:27"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:28",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:28"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:29",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:29"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:3",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:3"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:30",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:30"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:31",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:31"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:32",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:32"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:33",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:33"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:34",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:34"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:35",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:35"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:36",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:36"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:37",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:37"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:38",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:38"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:4",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:4"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:5",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:5"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:6",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:6"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:7",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:7"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:8",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:8"},{- "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:9",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:9"},{- "key": "src/shared/src/db/queries/agent-skill.ts:syncAgentSkills:values:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/agent-skill.ts:syncAgentSkills:values:1"},{- "key": "src/shared/src/db/queries/agent-skill.ts:syncGlobalSkills:values:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/agent-skill.ts:syncGlobalSkills:values:1"},{- "key": "src/shared/src/db/queries/agent.ts:getAgentsByIds:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/agent.ts:getAgentsByIds:inArray:1"},{- "key": "src/shared/src/db/queries/agent.ts:getExistingHandles:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/agent.ts:getExistingHandles:inArray:1"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:getInboxSnapshotForAgent:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:getInboxSnapshotForAgent:inArray:1"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:getInboxSnapshotForAgent:or-map:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:listAgentAllowedChannelIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:listAgentAllowedChannelIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:1"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:2"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:3"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:3",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:4"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:4",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:5"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:5",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:6"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:resolveScopeRefs:inArray:6",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:runChunk:inArray:1"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:runChunk:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:runChunk:inArray:2"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:runChunk:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/agent-inbox.ts:toAgentMessages:inArray:1"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:runChunk:inArray:3",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/attachment.ts:findPendingAttachmentsForSender:inArray:1"},{- "key": "src/shared/src/db/queries/community/agent-inbox.ts:toAgentMessages:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/attachment.ts:listByMessageIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/attachment.ts:findPendingAttachmentsForSender:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:1"},{- "key": "src/shared/src/db/queries/community/attachment.ts:listByMessageIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:2"},{- "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:3"},{- "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:2",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:4"},{- "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:3",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/attachment.ts:reserveAttachmentsForMessage:inArray:1"},{- "key": "src/shared/src/db/queries/community/attachment.ts:rebindPendingAttachmentsToChild:inArray:4",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/community/attachment.ts:reserveAttachmentsForMessage:sql.join:1"},{- "key": "src/shared/src/db/queries/community/attachment.ts:reserveAttachmentsForMessage:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/attachment.ts:unreserveAttachments:inArray:1"},{- "key": "src/shared/src/db/queries/community/attachment.ts:reserveAttachmentsForMessage:sql.join:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/bot-audit-log.ts:pruneBotActivityEventsStatement:notInArray:1"},{- "key": "src/shared/src/db/queries/community/attachment.ts:unreserveAttachments:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/bot.ts:findWakeCandidates:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot-audit-log.ts:pruneBotActivityEventsStatement:notInArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:publishOwnedBotAvatar:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:findWakeCandidates:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/bot.ts:publishOwnedBotAvatar:inArray:2"},{- "key": "src/shared/src/db/queries/community/bot.ts:publishOwnedBotAvatar:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:setBotActive:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:publishOwnedBotAvatar:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:setBotActive:inArray:2"},{- "key": "src/shared/src/db/queries/community/bot.ts:setBotActive:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:setBotActive:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:2"},{- "key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:3"},{- "key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:updateBot:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:3",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:updateBot:inArray:2"},{- "key": "src/shared/src/db/queries/community/bot.ts:updateBot:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:updateBot:inArray:3"},{- "key": "src/shared/src/db/queries/community/bot.ts:updateBot:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:updateBotModel:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:updateBot:inArray:3",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:updateBotRuntime:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:updateBotModel:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/bot.ts:updateBotRuntimeConfig:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:updateBotRuntime:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/category.ts:getCategoriesByIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/bot.ts:updateBotRuntimeConfig:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/category.ts:reorderCategories:inArray:1"},{- "key": "src/shared/src/db/queries/community/category.ts:getCategoriesByIds:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/channel.ts:createChannel:values:1"},{- "key": "src/shared/src/db/queries/community/category.ts:reorderCategories:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/channel.ts:deleteChannelMemberAndChildParticipants:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:createChannel:values:1",- "strategy": "exact-chunk",- "fixedParams": 0+ "key": "src/shared/src/db/queries/community/channel.ts:filterChannelReadableUserIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:deleteChannelMemberAndChildParticipants:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/channel.ts:getChannelsByIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:filterChannelReadableUserIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/channel.ts:getDirectChildThreadsByIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:getChannelsByIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/channel.ts:listChildChannelsByParentMessageIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:getDirectChildThreadsByIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/channel.ts:listReadableChannelsForUser:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:listChildChannelsByParentMessageIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/channel.ts:listServerChannelDirectoryForAdmin:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:listReadableChannelsForUser:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/channel.ts:listServerChannelDirectoryForAdmin:inArray:2"},{- "key": "src/shared/src/db/queries/community/channel.ts:listServerChannelDirectoryForAdmin:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:listServerChannelDirectoryForAdmin:inArray:2",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:2"},{- "key": "src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 0+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:1"},{- "key": "src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 2+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:2"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:3"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:4"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:3",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:5"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:4",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:6"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:5",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:1"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteChannelWithMediaAttempt:inArray:6",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:2"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:3"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:4"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:3",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:5"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:4",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:6"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:5",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/forum-post-delete.ts:deleteForumPostAttempt:inArray:1"},{- "key": "src/shared/src/db/queries/community/delete-media.ts:deleteServerWithMediaAttempt:inArray:6",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/forum-post-delete.ts:deleteForumPostAttempt:inArray:2"},{- "key": "src/shared/src/db/queries/community/forum-post-delete.ts:deleteForumPostAttempt:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/friendship.ts:findActive:inArray:1"},{- "key": "src/shared/src/db/queries/community/forum-post-delete.ts:deleteForumPostAttempt:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/friendship.ts:getFriendUserIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/friendship.ts:findActive:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/community/friendship.ts:hydrateApprovalsForDmMessages:inArray:1"},{- "key": "src/shared/src/db/queries/community/friendship.ts:getFriendUserIds:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/friendship.ts:hydrateApprovalsForDmMessages:inArray:2"},{- "key": "src/shared/src/db/queries/community/friendship.ts:hydrateApprovalsForDmMessages:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/friendship.ts:listPending:inArray:1"},{- "key": "src/shared/src/db/queries/community/friendship.ts:hydrateApprovalsForDmMessages:inArray:2",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/friendship.ts:loadBotFlags:inArray:1"},{- "key": "src/shared/src/db/queries/community/friendship.ts:listPending:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/friendship.ts:loadProfiles:inArray:1"},{- "key": "src/shared/src/db/queries/community/friendship.ts:loadBotFlags:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/friendship.ts:sendRequest:inArray:1"},{- "key": "src/shared/src/db/queries/community/friendship.ts:loadProfiles:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/inbox.ts:listEligibleUnreadChannels:inArray:1"},{- "key": "src/shared/src/db/queries/community/friendship.ts:sendRequest:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/community/inbox.ts:listEligibleUnreadDms:inArray:1"},{- "key": "src/shared/src/db/queries/community/inbox.ts:listEligibleUnreadChannels:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/inbox.ts:listThreadOpenersByChildIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/inbox.ts:listEligibleUnreadDms:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/inbox.ts:listUnreadChannels:inArray:1"},{- "key": "src/shared/src/db/queries/community/inbox.ts:listThreadOpenersByChildIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/inbox.ts:listUnreadDms:inArray:1"},{- "key": "src/shared/src/db/queries/community/inbox.ts:listUnreadChannels:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/inbox.ts:listUnreadForumOpeners:inArray:1"},{- "key": "src/shared/src/db/queries/community/inbox.ts:listUnreadDms:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/machine-session-epoch.ts:transitionLiveLease:inArray:1"},{- "key": "src/shared/src/db/queries/community/inbox.ts:listUnreadForumOpeners:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/machine.ts:revokeRunnerKeysForAgentStatement:inArray:1"},{- "key": "src/shared/src/db/queries/community/machine-session-epoch.ts:transitionLiveLease:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/mark.ts:countMarksForUser:inArray:1"},{- "key": "src/shared/src/db/queries/community/machine.ts:revokeRunnerKeysForAgentStatement:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/mark.ts:listMarksForUser:inArray:1"},{- "key": "src/shared/src/db/queries/community/mark.ts:countMarksForUser:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/member.ts:getCoMemberUserIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/mark.ts:listMarksForUser:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/member.ts:getMembersByUserIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/member.ts:getCoMemberUserIds:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/member.ts:getMemberships:inArray:1"},{- "key": "src/shared/src/db/queries/community/member.ts:getMembersByUserIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 1+ "key": "src/shared/src/db/queries/community/mention.ts:createMentions:values:1"},{- "key": "src/shared/src/db/queries/community/member.ts:getMemberships:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentionScopes:inArray:1"},{- "key": "src/shared/src/db/queries/community/mention.ts:createMentions:values:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentions:inArray:1"},{- "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentionScopes:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/mention.ts:markChannelMentionsReadBuilder:inArray:1"},{- "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentions:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/message-tag.ts:filterMessageIdsByTag:inArray:1"},{- "key": "src/shared/src/db/queries/community/mention.ts:markChannelMentionsReadBuilder:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/community/message-tag.ts:listTagsForMessages:inArray:1"},{- "key": "src/shared/src/db/queries/community/message-tag.ts:filterMessageIdsByTag:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/message.ts:eligibleAttachments:inArray:1"},{- "key": "src/shared/src/db/queries/community/message-tag.ts:listTagsForMessages:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/message.ts:getFirstMessageResourcesByChannelIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/message.ts:eligibleAttachments:inArray:1",- "strategy": "bounded-public-input",- "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"+ "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/message.ts:getFirstMessageResourcesByChannelIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIdsInChannels:inArray:1"},{- "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIdsInChannels:inArray:2"},{- "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIdsInChannels:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:1"},{- "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIdsInChannels:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:2"},{- "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:1",- "strategy": "bounded-public-input",- "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:sql.join:1"},{- "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:2",- "strategy": "bounded-public-input",- "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:1"},{- "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:sql.join:1",- "strategy": "bounded-public-input",- "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:2"},{- "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:1",- "strategy": "exact-chunk",- "fixedParams": 0+ "key": "src/shared/src/db/queries/community/message.ts:listMessagesReferencingFriendship:inArray:1"},{- "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:2",- "strategy": "exact-chunk",- "fixedParams": 0+ "key": "src/shared/src/db/queries/community/message.ts:runChunk:inArray:1"},{- "key": "src/shared/src/db/queries/community/message.ts:listMessagesReferencingFriendship:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/notification-eligibility.ts:runChunk:inArray:1"},{- "key": "src/shared/src/db/queries/community/message.ts:runChunk:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/notification-setting.ts:loadScopedSettings:inArray:1"},{- "key": "src/shared/src/db/queries/community/notification-eligibility.ts:runChunk:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/notification-setting.ts:loadScopedSettings:inArray:2"},{- "key": "src/shared/src/db/queries/community/notification-setting.ts:loadScopedSettings:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/reaction.ts:listReactionsByMessageIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/notification-setting.ts:loadScopedSettings:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/read-state.ts:advanceReadStateRevisionWhenAnyBuilder:or-map:1"},{- "key": "src/shared/src/db/queries/community/reaction.ts:listReactionsByMessageIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 0+ "key": "src/shared/src/db/queries/community/search.ts:searchMessagesInServer:inArray:1"},{- "key": "src/shared/src/db/queries/community/read-state.ts:advanceReadStateRevisionWhenAnyBuilder:or-map:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/server-folder.ts:insertFolderItems:values:1"},{- "key": "src/shared/src/db/queries/community/search.ts:searchMessagesInServer:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/server.ts:getServersByIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/server-folder.ts:insertFolderItems:values:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/thread.ts:addThreadParticipants:values:1"},{- "key": "src/shared/src/db/queries/community/server.ts:getServersByIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/thread.ts:listParticipantsForChannels:inArray:1"},{- "key": "src/shared/src/db/queries/community/thread.ts:addThreadParticipants:values:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/thread.ts:listParticipantsForChannels:inArray:2"},{- "key": "src/shared/src/db/queries/community/thread.ts:listParticipantsForChannels:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/thread.ts:listParticipatingForumThreads:inArray:1"},{- "key": "src/shared/src/db/queries/community/thread.ts:listParticipantsForChannels:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/thread.ts:listParticipatingForumThreads:inArray:2"},{- "key": "src/shared/src/db/queries/community/thread.ts:listParticipatingForumThreads:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/thread.ts:listParticipatingThreadIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/thread.ts:listParticipatingForumThreads:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/community/thread.ts:removeParticipantFromChildChannels:inArray:1"},{- "key": "src/shared/src/db/queries/community/thread.ts:listParticipatingThreadIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/conversation.ts:getConversationsByIds:inArray:1"},{- "key": "src/shared/src/db/queries/community/thread.ts:removeParticipantFromChildChannels:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/conversation.ts:getThreadsByParentMessages:inArray:1"},{- "key": "src/shared/src/db/queries/conversation.ts:getConversationsByIds:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/email-account.ts:getEmailAccountsByAgents:inArray:1"},{- "key": "src/shared/src/db/queries/conversation.ts:getThreadsByParentMessages:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/issue.ts:listIssues:inArray:1"},{- "key": "src/shared/src/db/queries/email-account.ts:getEmailAccountsByAgents:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/issue.ts:listIssues:inArray:2"},{- "key": "src/shared/src/db/queries/inbox.ts:getUnreadCount:sql.join:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/meeting-session.ts:claimMeetingSessions:inArray:1"},{- "key": "src/shared/src/db/queries/inbox.ts:listUnreadConversations:sql.join:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/native-oauth.ts:cancelAttempt:inArray:1"},{- "key": "src/shared/src/db/queries/issue.ts:listIssues:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/native-oauth.ts:registerAttempt:inArray:1"},{- "key": "src/shared/src/db/queries/issue.ts:listIssues:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/native-oauth.ts:registerAttempt:inArray:2"},{- "key": "src/shared/src/db/queries/meeting-session.ts:claimMeetingSessions:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/overview.ts:getConversationCountsByAgent:inArray:1"},{- "key": "src/shared/src/db/queries/native-oauth.ts:cancelAttempt:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/overview.ts:getRecentTerminalTasks:inArray:1"},{- "key": "src/shared/src/db/queries/native-oauth.ts:registerAttempt:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/overview.ts:getRecentTerminalTasks:inArray:2"},{- "key": "src/shared/src/db/queries/native-oauth.ts:registerAttempt:inArray:2",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileActiveBotsBuilder:inArray:1"},{- "key": "src/shared/src/db/queries/overview.ts:getConversationCountsByAgent:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:1"},{- "key": "src/shared/src/db/queries/overview.ts:getRecentTerminalTasks:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:2"},{- "key": "src/shared/src/db/queries/overview.ts:getRecentTerminalTasks:inArray:2",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:3"},{- "key": "src/shared/src/db/queries/product-plan.ts:reconcileActiveBotsBuilder:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:4"},{- "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/product-plan.ts:setPlanEntitlement:inArray:1"},{- "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/runtime.ts:deleteRuntimesByDaemonId:inArray:1"},{- "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:3",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/runtime.ts:getAgentRuntimesForWorkspace:inArray:1"},{- "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:4",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/task-message.ts:listTaskMessages:notInArray:1"},{- "key": "src/shared/src/db/queries/product-plan.ts:setPlanEntitlement:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/task-message.ts:listTaskMessages:notInArray:2"},{- "key": "src/shared/src/db/queries/runtime.ts:deleteRuntimesByDaemonId:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/task-message.ts:listTaskMessagesSince:notInArray:1"},{- "key": "src/shared/src/db/queries/runtime.ts:getAgentRuntimesForWorkspace:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/task.ts:cancelActiveTasksByConversation:inArray:1"},{- "key": "src/shared/src/db/queries/task-message.ts:listTaskMessages:notInArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:cancelTask:inArray:1"},{- "key": "src/shared/src/db/queries/task-message.ts:listTaskMessages:notInArray:2",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:claimKillTasks:inArray:1"},{- "key": "src/shared/src/db/queries/task-message.ts:listTaskMessagesSince:notInArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:claimKillTasks:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:cancelActiveTasksByConversation:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:claimTask:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:cancelTask:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:claimTask:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:claimKillTasks:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/task.ts:countRunningTasks:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:claimKillTasks:inArray:2",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/task.ts:failStaleKillTasks:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:claimTask:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:failStaleRunningTasks:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:claimTask:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/task.ts:failTask:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:countRunningTasks:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:findSteerableReplacement:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:failStaleKillTasks:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:findSteerableReplacement:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:failStaleRunningTasks:inArray:1",- "strategy": "subquery"+ "key": "src/shared/src/db/queries/task.ts:getActiveTaskByConversation:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:failTask:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:getTraceAgentsByTaskIds:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:findSteerableReplacement:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:getTraceAgentsByTaskIds:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:findSteerableReplacement:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/task.ts:hasPendingTaskForConversation:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:getActiveTaskByConversation:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:listActiveTaskCountsByWorkspace:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:getTraceAgentsByTaskIds:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/task.ts:listActiveTaskCountsByWorkspace:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:getTraceAgentsByTaskIds:inArray:2",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/task.ts:listActiveTasksByAgent:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:hasPendingTaskForConversation:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:listActiveTasksByWorkspace:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:listActiveTaskCountsByWorkspace:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:listActiveTasksByWorkspace:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:listActiveTaskCountsByWorkspace:inArray:2",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/task.ts:listPendingTasksByRuntimes:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:listActiveTasksByAgent:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:listPendingTasksByRuntimes:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:listActiveTasksByWorkspace:inArray:1",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:listTaskHistory:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:listActiveTasksByWorkspace:inArray:2",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/task.ts:listTaskHistory:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:listPendingTasksByRuntimes:inArray:1",- "strategy": "json-set"+ "key": "src/shared/src/db/queries/task.ts:listTraces:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:listPendingTasksByRuntimes:inArray:2",- "strategy": "fixed-literal"+ "key": "src/shared/src/db/queries/task.ts:listTraces:inArray:2"},{- "key": "src/shared/src/db/queries/task.ts:listTaskHistory:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/task.ts:supersedeTask:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:listTaskHistory:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/user.ts:getUsersByIds:inArray:1"},{- "key": "src/shared/src/db/queries/task.ts:listTraces:inArray:1",- "strategy": "fixed-literal"- },- {- "key": "src/shared/src/db/queries/task.ts:listTraces:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10- },- {- "key": "src/shared/src/db/queries/task.ts:supersedeTask:inArray:1",- "strategy": "fixed-literal"- },- {- "key": "src/shared/src/db/queries/user.ts:getUsersByIds:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10- },- {- "key": "src/shared/src/db/queries/workspace-file-request.ts:markDispatched:inArray:1",- "strategy": "exact-chunk",- "fixedParams": 10+ "key": "src/shared/src/db/queries/workspace-file-request.ts:markDispatched:inArray:1"}]diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex 6f4c2eaae..8d1d360e2 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -9,7 +9,7 @@* self-message-excluding) — a different shape from `message.ts`'s* `createdAt`-ordered, DB-shaped human-UI queries.*/-import { eq, and, inArray, gt, lt, ne, asc, desc, or, sql } from "drizzle-orm";+import { eq, and, inArray, gt, lt, ne, asc, desc, sql } from "drizzle-orm";import {communityMessage,communityChannel,@@ -38,6 +38,7 @@ import { listParticipatingThreadIds } from "./thread";import { getMessagesByIdsInScope, type MessageScope } from "./message";import { reachIsParticipantSet, type StoredChannelType } from "../../../utils/community-roles";import { chunk, D1_MAX_IN_PARAMS, maxInParams } from "../_chunk";+import { jsonTextSet } from "../_json-set";import { withD1Retry } from "../../resilience";import { hasDirectMentionSql, notificationEligibleSql } from "./notification-eligibility";@@ -769,8 +770,7 @@ export type InboxSnapshotRow = {* `community_channel_member(relation='notify')` row for the bot. Readability,* notification eligibility, unread cursor, and join baseline are all applied* before GROUP BY; aggregate metadata therefore describes exactly the rows a- * pull can deliver. Latest sender is hydrated from each aggregate's exact- * `(channelId, latestSeq)` pair in bounded batches.+ * pull can deliver.*/export async function getInboxSnapshotForAgent(db: Database,@@ -784,120 +784,87 @@ export async function getInboxSnapshotForAgent();if (allowedChannelIds.length === 0) return [];- // Chunk the `inArray` for D1's 100-param limit. GROUP BY channelId partitions- // cleanly across chunks — a channel id lands in exactly one chunk, so its- // COUNT/MIN/MAX and the correlated subselects are complete within that chunk.- // Concat is loss-free (no channel appears in two chunks).- const runChunk = (ids: string[]) =>- db- .select({- channelId: communityMessage.channelId,- pendingCount: sql<number>`COUNT(*)`,- firstPendingSeq: sql<number>`MIN(${communityMessage.seq})`,- latestSeq: sql<number>`MAX(${communityMessage.seq})`,- mentionCount: sql<number>`SUM(CASE WHEN ${hasDirectMentionSql(botUserId, communityMessage.id)} THEN 1 ELSE 0 END)`,- })- .from(communityMessage)- .leftJoin(- communityReadState,- and(- eq(communityReadState.userId, botUserId),- eq(communityReadState.channelId, communityMessage.channelId)- )- )- .leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))- .leftJoin(- communityChannelMember,- and(- eq(communityChannelMember.channelId, communityMessage.channelId),- eq(communityChannelMember.userId, botUserId),- eq(communityChannelMember.relation, "access")- )+ const pending = db+ .select({+ channelId: communityMessage.channelId,+ pendingCount: sql<number>`COUNT(*)`.as("pending_count"),+ firstPendingSeq: sql<number>`MIN(${communityMessage.seq})`.as("first_pending_seq"),+ latestSeq: sql<number>`MAX(${communityMessage.seq})`.as("latest_seq"),+ mentionCount: sql<number>`SUM(CASE WHEN ${hasDirectMentionSql(botUserId, communityMessage.id)} THEN 1 ELSE 0 END)`.as("mention_count"),+ })+ .from(communityMessage)+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.userId, botUserId),+ eq(communityReadState.channelId, communityMessage.channelId))- .leftJoin(- communityServerMember,- and(- eq(communityServerMember.serverId, communityChannel.serverId),- eq(communityServerMember.userId, botUserId)- )+ )+ .leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .leftJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityMessage.channelId),+ eq(communityChannelMember.userId, botUserId),+ eq(communityChannelMember.relation, "access"))- .where(- and(- ne(communityMessage.authorId, botUserId),- sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,- inArray(communityMessage.channelId, ids),- channelJoinBaselineGuard,- notificationEligibleSql(- botUserId,- {- id: communityChannel.id,- serverId: communityChannel.serverId,- parentChannelId: communityChannel.parentChannelId,- },- {- id: communityMessage.id,- },- ),- )+ )+ .leftJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.userId, botUserId))- .groupBy(communityMessage.channelId);-- const rows = (- await Promise.all(chunk(allowedChannelIds, D1_MAX_IN_PARAMS).map(runChunk))- ).flat();-- if (rows.length === 0) return [];-- // Resolve the sender from each scope's exact latest ELIGIBLE seq. Looking up- // "latest message in channel" would let a newer muted row leak into the- // snapshot even though the aggregate above correctly excluded it.- const latestMessageRows = (- await Promise.all(- chunk(rows, Math.floor(D1_MAX_IN_PARAMS / 2)).map((pairs) =>- db- .select({- channelId: communityMessage.channelId,- seq: communityMessage.seq,- authorId: communityMessage.authorId,- })- .from(communityMessage)- .where(or(...pairs.map((r) => and(- eq(communityMessage.channelId, r.channelId),- eq(communityMessage.seq, r.latestSeq),- ))))+ )+ .where(+ and(+ ne(communityMessage.authorId, botUserId),+ sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,+ inArray(communityMessage.channelId, jsonTextSet(db, allowedChannelIds)),+ channelJoinBaselineGuard,+ notificationEligibleSql(+ botUserId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ },+ ),))- ).flat();- const latestSenderIdByChannel = new Map(- latestMessageRows.map((row) => [row.channelId, row.authorId]),- );+ .groupBy(communityMessage.channelId)+ .as("pending_inbox");- const senderIds = [...new Set(latestMessageRows.map((r) => r.authorId).filter(Boolean))];- // Chunk the `inArray` for D1's 100-param limit — one distinct sender per- // pending channel, so >100 channels yields >100 ids; no order/limit → concat.- const users = senderIds.length- ? (- await Promise.all(- chunk(senderIds, D1_MAX_IN_PARAMS).map((ids) =>- db- .select({ id: user.id, name: user.name, discriminator: user.discriminator })- .from(user)- .where(inArray(user.id, ids))- )- )- ).flat()- : [];- const userById = new Map(users.map((u) => [u.id, u]));+ const rows = await db+ .select({+ channelId: pending.channelId,+ pendingCount: pending.pendingCount,+ firstPendingSeq: pending.firstPendingSeq,+ latestSeq: pending.latestSeq,+ mentionCount: pending.mentionCount,+ sender: {+ id: user.id,+ name: user.name,+ discriminator: user.discriminator,+ },+ })+ .from(pending)+ .innerJoin(communityMessage, and(+ eq(communityMessage.channelId, pending.channelId),+ eq(communityMessage.seq, pending.latestSeq),+ ))+ .leftJoin(user, eq(user.id, communityMessage.authorId));return rows.map((r) => {- const senderId = latestSenderIdByChannel.get(r.channelId);- const sender = senderId ? userById.get(senderId) : undefined;return {channelId: r.channelId,pendingCount: r.pendingCount,firstPendingSeq: r.firstPendingSeq,latestSeq: r.latestSeq,- latestSender: sender ? `@${formatHandle(sender.name, sender.discriminator)}` : "Deleted user",+ latestSender: r.sender?.id ? `@${formatHandle(r.sender.name, r.sender.discriminator)}` : "Deleted user",hasMention: r.mentionCount > 0,};});diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex 1a535831f..240aef664 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -1,5 +1,6 @@import { aliasedTable, and, eq, gt, isNotNull, isNull, inArray, ne, or, sql } from "drizzle-orm";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";+import { jsonTextSet } from "../_json-set";import {communityChannel,communityChannelMember,@@ -333,84 +334,76 @@ export async function listUnreadForumOpeners(if (forumParentIds.length === 0) return [];const childChannel = aliasedTable(communityChannel, "forum_inbox_child");- const rows = (- await Promise.all(- chunk(forumParentIds, D1_MAX_IN_PARAMS).map((ids) =>- db- .select({- forumChannelId: communityMessage.channelId,- openerMessageId: communityMessage.id,- openerContent: communityMessage.content,- openerSeq: communityMessage.seq,- childChannelId: childChannel.id,- childName: childChannel.name,- createdAt: communityMessage.createdAt,- })- .from(communityMessage)- .innerJoin(- communityChannel,- eq(communityChannel.id, communityMessage.channelId)- )- .innerJoin(- childChannel,- and(- eq(childChannel.parentChannelId, communityChannel.id),- eq(childChannel.parentMessageId, communityMessage.id)- )- )- .innerJoin(- communityServerMember,- and(- eq(communityServerMember.serverId, communityChannel.serverId),- eq(communityServerMember.userId, userId)- )- )- .leftJoin(- communityReadState,- and(- eq(communityReadState.channelId, communityChannel.id),- eq(communityReadState.userId, userId)- )- )- .where(- and(- inArray(communityChannel.id, ids),- isNull(communityChannel.parentChannelId),- eq(communityChannel.type, "forum"),- eq(communityChannel.archived, 0),- eq(childChannel.archived, 0),- or(- and(- isNotNull(communityReadState.id),- gt(- communityMessage.seq,- sql<number>`COALESCE(${communityReadState.lastReadSeq}, 0)`- )- ),- and(- isNull(communityReadState.id),- gt(communityMessage.createdAt, communityServerMember.joinedAt)- )- ),- notificationEligibleSql(- userId,- {- id: communityChannel.id,- serverId: communityChannel.serverId,- parentChannelId: communityChannel.parentChannelId,- },- {- id: communityMessage.id,- }- )+ const rows = await db+ .select({+ forumChannelId: communityMessage.channelId,+ openerMessageId: communityMessage.id,+ openerContent: communityMessage.content,+ openerSeq: communityMessage.seq,+ childChannelId: childChannel.id,+ childName: childChannel.name,+ createdAt: communityMessage.createdAt,+ })+ .from(communityMessage)+ .innerJoin(+ communityChannel,+ eq(communityChannel.id, communityMessage.channelId)+ )+ .innerJoin(+ childChannel,+ and(+ eq(childChannel.parentChannelId, communityChannel.id),+ eq(childChannel.parentMessageId, communityMessage.id)+ )+ )+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.userId, userId)+ )+ )+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.channelId, communityChannel.id),+ eq(communityReadState.userId, userId)+ )+ )+ .where(+ and(+ inArray(communityChannel.id, jsonTextSet(db, forumParentIds)),+ isNull(communityChannel.parentChannelId),+ eq(communityChannel.type, "forum"),+ eq(communityChannel.archived, 0),+ eq(childChannel.archived, 0),+ or(+ and(+ isNotNull(communityReadState.id),+ gt(+ communityMessage.seq,+ sql<number>`COALESCE(${communityReadState.lastReadSeq}, 0)`)+ ),+ and(+ isNull(communityReadState.id),+ gt(communityMessage.createdAt, communityServerMember.joinedAt))+ ),+ notificationEligibleSql(+ userId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ }+ ))- )- ).flat();+ );- // D1 chunks are independent statements. Sort only after concatenation so a- // chunk boundary can never change the rows that survive the Inbox cap.rows.sort((a, b) =>b.createdAt.localeCompare(a.createdAt) ||@@ -447,74 +440,68 @@ export async function listThreadOpenersByChildIds(const childChannel = aliasedTable(communityChannel, "thread_inbox_child_lookup");const parentChannel = aliasedTable(communityChannel, "thread_inbox_parent_lookup");- const rows = (- await Promise.all(- chunk(childIds, D1_MAX_IN_PARAMS).map((ids) =>- db- .select({- parentChannelId: parentChannel.id,- parentType: parentChannel.type,- openerMessageId: communityMessage.id,- openerContent: communityMessage.content,- openerSeq: communityMessage.seq,- childChannelId: childChannel.id,- childName: childChannel.name,- createdAt: communityMessage.createdAt,- openerUnread: sql<number>`(- (- (${communityReadState.id} IS NOT NULL AND ${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0))- OR- (${communityReadState.id} IS NULL AND ${communityMessage.createdAt} > ${communityServerMember.joinedAt})- )- AND ${notificationEligibleSql(- userId,- {- id: parentChannel.id,- serverId: parentChannel.serverId,- parentChannelId: parentChannel.parentChannelId,- },- { id: communityMessage.id }- )}- )`,- })- .from(childChannel)- .innerJoin(- parentChannel,- eq(parentChannel.id, childChannel.parentChannelId)- )- .innerJoin(- communityMessage,- and(- eq(communityMessage.id, childChannel.parentMessageId),- eq(communityMessage.channelId, parentChannel.id)- )- )- .innerJoin(- communityServerMember,- and(- eq(communityServerMember.serverId, parentChannel.serverId),- eq(communityServerMember.userId, userId)- )- )- .leftJoin(- communityReadState,- and(- eq(communityReadState.channelId, parentChannel.id),- eq(communityReadState.userId, userId)- )- )- .where(- and(- inArray(childChannel.id, ids),- eq(childChannel.type, "thread"),- eq(childChannel.archived, 0),- eq(parentChannel.archived, 0),- isNull(parentChannel.parentChannelId)- )- )+ const rows = await db+ .select({+ parentChannelId: parentChannel.id,+ parentType: parentChannel.type,+ openerMessageId: communityMessage.id,+ openerContent: communityMessage.content,+ openerSeq: communityMessage.seq,+ childChannelId: childChannel.id,+ childName: childChannel.name,+ createdAt: communityMessage.createdAt,+ openerUnread: sql<number>`(+ (+ (${communityReadState.id} IS NOT NULL AND ${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0))+ OR+ (${communityReadState.id} IS NULL AND ${communityMessage.createdAt} > ${communityServerMember.joinedAt})+ )+ AND ${notificationEligibleSql(+ userId,+ {+ id: parentChannel.id,+ serverId: parentChannel.serverId,+ parentChannelId: parentChannel.parentChannelId,+ },+ { id: communityMessage.id }+ )}+ )`,+ })+ .from(childChannel)+ .innerJoin(+ parentChannel,+ eq(parentChannel.id, childChannel.parentChannelId)+ )+ .innerJoin(+ communityMessage,+ and(+ eq(communityMessage.id, childChannel.parentMessageId),+ eq(communityMessage.channelId, parentChannel.id)))- ).flat();+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, parentChannel.serverId),+ eq(communityServerMember.userId, userId)+ )+ )+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.channelId, parentChannel.id),+ eq(communityReadState.userId, userId)+ )+ )+ .where(+ and(+ inArray(childChannel.id, jsonTextSet(db, childIds)),+ eq(childChannel.type, "thread"),+ eq(childChannel.archived, 0),+ eq(parentChannel.archived, 0),+ isNull(parentChannel.parentChannelId)+ )+ );rows.sort((a, b) =>diff --git a/src/shared/src/db/queries/community/search.ts b/src/shared/src/db/queries/community/search.tsindex 3508eb831..f1660b9f3 100644--- a/src/shared/src/db/queries/community/search.ts+++ b/src/shared/src/db/queries/community/search.ts@@ -1,9 +1,9 @@-import { eq, and, inArray, sql } from "drizzle-orm";+import { eq, and, desc, inArray, sql } from "drizzle-orm";import { communityMessage, communityChannel } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";import { escapeLikePattern } from "../../../utils/sql-like";-import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";+import { jsonTextSet } from "../_json-set";const DEFAULT_LIMIT = 50;@@ -57,6 +57,7 @@ export async function searchMessages(.from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id)).where(and(...conditions))+ .orderBy(desc(communityMessage.createdAt)).limit(limit);}@@ -83,35 +84,22 @@ export async function searchMessagesInServer(eq(communityChannel.serverId, opts.serverId),];- const runQuery = (extra: ReturnType<typeof inArray>[] = []) =>- db- .select({- message: communityMessage,- author: user,- })- .from(communityMessage)- .innerJoin(user, eq(communityMessage.authorId, user.id))- .innerJoin(- communityChannel,- eq(communityMessage.channelId, communityChannel.id)- )- .where(and(...baseConditions, ...extra))- .limit(limit);-- if (!opts.visibleChannelIds) return runQuery();+ if (opts.visibleChannelIds !== undefined) {+ baseConditions.push(inArray(communityMessage.channelId, jsonTextSet(db, opts.visibleChannelIds)));+ }- // D1 caps a statement at 100 bound params; `visibleChannelIds` is unbounded.- // Chunk the `inArray` and merge. There's no ORDER BY contract today, so plain- // concat+slice would bias toward early-chunk channels (a match in a late chunk- // gets dropped once an early chunk fills `limit`). Sort the merged rows by- // createdAt desc before slicing → a defensible "most-recent matches" rule- // instead of chunk-order bias. `createdAt` is in the projection.- const chunks = chunk(opts.visibleChannelIds, D1_MAX_IN_PARAMS);- const merged = (- await Promise.all(- chunks.map((ids) => runQuery([inArray(communityMessage.channelId, ids)]))+ return db+ .select({+ message: communityMessage,+ author: user,+ })+ .from(communityMessage)+ .innerJoin(user, eq(communityMessage.authorId, user.id))+ .innerJoin(+ communityChannel,+ eq(communityMessage.channelId, communityChannel.id))- ).flat();- merged.sort((a, b) => (a.message.createdAt < b.message.createdAt ? 1 : -1));- return merged.slice(0, limit);+ .where(and(...baseConditions))+ .orderBy(desc(communityMessage.createdAt))+ .limit(limit);}diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.tsindex f49889c40..d804537d7 100644--- a/src/shared/src/db/queries/community/server.ts+++ b/src/shared/src/db/queries/community/server.ts@@ -34,95 +34,74 @@ export async function createServer(userDiscriminator: string;};}> {- // Mint the id up-front so the discriminator (an FNV-1a hash of the id) is- // written in the same INSERT — same pattern as createUser/createBot. Only the- // server row carries the discriminator, so wrap just that insert (not the- // whole batch): category/channel/member rows don't touch the (name,- // discriminator) unique index, so they run after the server row wins its- // discriminator. A collision against idx_community_server_name_discriminator- // salt-retries the server insert; throw-at-cap on exhaustion (loud, never a- // silent duplicate).const id = nanoid();- const server = await withUniqueDiscriminator(+ const publicCategoryId = nanoid();+ const privateCategoryId = nanoid();+ const privateChannelId = nanoid();+ const [serverRows, , , , , , memberRows] = await withUniqueDiscriminator(db,{ id, name: data.name },- async (discriminator) => {- const [row] = await db- .insert(communityServer)- .values({- id,- name: data.name,- discriminator,- description: data.description ?? "",- ownerId: data.ownerId,- })- .returning();- return row!;- }+ (discriminator) => db.batch([+ db.insert(communityServer).values({+ id,+ name: data.name,+ discriminator,+ description: data.description ?? "",+ ownerId: data.ownerId,+ }).returning(),+ db.insert(communityCategory).values({+ id: publicCategoryId,+ serverId: id,+ name: "Public",+ position: 0,+ private: 0,+ }),+ db.insert(communityChannel).values({+ serverId: id,+ categoryId: publicCategoryId,+ name: "all",+ type: "text",+ position: 0,+ }),+ db.insert(communityCategory).values({+ id: privateCategoryId,+ serverId: id,+ name: "Private",+ position: 1,+ private: 1,+ creatorId: data.ownerId,+ }),+ db.insert(communityChannel).values({+ id: privateChannelId,+ serverId: id,+ categoryId: privateCategoryId,+ name: "room",+ type: "text",+ position: 0,+ creatorId: data.ownerId,+ }),+ db.insert(communityChannelMember).values({+ channelId: privateChannelId,+ userId: data.ownerId,+ relation: "access",+ source: "added",+ addedBy: data.ownerId,+ }),+ db.insert(communityServerMember).values({+ serverId: id,+ userId: data.ownerId,+ role: "owner",+ railOrder: 0,+ }).returning({+ id: communityServerMember.id,+ userId: communityServerMember.userId,+ joinedAt: communityServerMember.joinedAt,+ }),+ ]),+ ["community_server.name", "community_server.discriminator"],);-- const [publicCategory] = await db- .insert(communityCategory)- .values({- serverId: server.id,- name: "Public",- position: 0,- private: 0,- })- .returning();-- await db.insert(communityChannel).values({- serverId: server.id,- categoryId: publicCategory!.id,- name: "all",- type: "text",- position: 0,- });-- const [privateCategory] = await db- .insert(communityCategory)- .values({- serverId: server.id,- name: "Private",- position: 1,- private: 1,- creatorId: data.ownerId,- })- .returning();-- const [privateChannel] = await db- .insert(communityChannel)- .values({- serverId: server.id,- categoryId: privateCategory!.id,- name: "room",- type: "text",- position: 0,- creatorId: data.ownerId,- })- .returning();-- await db.insert(communityChannelMember).values({- channelId: privateChannel!.id,- userId: data.ownerId,- relation: "access",- source: "added",- addedBy: data.ownerId,- });-- const [memberRow] = await db- .insert(communityServerMember)- .values({- serverId: server.id,- userId: data.ownerId,- role: "owner",- railOrder: 0,- })- .returning({- id: communityServerMember.id,- userId: communityServerMember.userId,- joinedAt: communityServerMember.joinedAt,- });+ const server = serverRows[0]!;+ const memberRow = memberRows[0]!;// Fetch the owner's display name + avatar directly instead of re-listing// members — a freshly-created server has exactly one member row, so adiff --git a/src/shared/src/db/queries/inbox.ts b/src/shared/src/db/queries/inbox.tsindex 702978d9f..20e1fb9f4 100644--- a/src/shared/src/db/queries/inbox.ts+++ b/src/shared/src/db/queries/inbox.ts@@ -1,6 +1,7 @@import { sql } from "drizzle-orm";import { nanoid } from "nanoid";import type { Database } from "../index";+import { jsonTextSet } from "./_json-set";const UNREAD_ELIGIBLE_TYPES = ["user_dm_message", "email_notification", "calendar_event"];@@ -131,7 +132,7 @@ export async function listUnreadConversations(: sql``;const types = opts?.types?.length ? opts.types : ["user_dm_message"];- const typePlaceholders = sql.join(types.map(t => sql`${t}`), sql`, `);+ const typeSet = jsonTextSet(db, types).getSQL();const rows = await db.all<{id: string;@@ -163,7 +164,7 @@ export async function listUnreadConversations(LEFT JOIN agent a ON a.id = u.agent_id AND a.workspace_id = u.workspace_idWHERE u.user_id = ${userId}AND u.workspace_id = ${workspaceId}- AND u.task_type IN (${typePlaceholders})+ AND u.task_type IN (${typeSet})${beforeClause}ORDER BY u.completed_at DESCLIMIT ${limit + 1}@@ -182,7 +183,7 @@ export async function getUnreadCount(types?: string[],) {const validTypes = types?.length ? types : ["user_dm_message"];- const typePlaceholders = sql.join(validTypes.map(t => sql`${t}`), sql`, `);+ const typeSet = jsonTextSet(db, validTypes).getSQL();const rows = await db.all<{ count: number }>(sql`SELECT COUNT(*) AS count@@ -190,7 +191,7 @@ export async function getUnreadCount(INNER JOIN conversation c ON c.id = u.conversation_idWHERE u.user_id = ${userId}AND u.workspace_id = ${workspaceId}- AND u.task_type IN (${typePlaceholders})+ AND u.task_type IN (${typeSet})`);return rows[0]?.count ?? 0;diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.tsindex d03f5493f..d257dd3e9 100644--- a/src/shared/src/db/queries/task.ts+++ b/src/shared/src/db/queries/task.ts@@ -737,11 +737,11 @@ export async function listTaskHistory(];if (opts?.status && opts.status.length > 0) {- conditions.push(inArray(agentTaskQueue.status, opts.status));+ conditions.push(inArray(agentTaskQueue.status, jsonTextSet(db, opts.status)));}if (opts?.type && opts.type.length > 0) {- conditions.push(inArray(agentTaskQueue.type, opts.type));+ conditions.push(inArray(agentTaskQueue.type, jsonTextSet(db, opts.type)));}if (opts?.before) {@@ -896,7 +896,7 @@ export async function listTraces(.where(and(eq(agentTaskQueue.workspaceId, workspaceId),- inArray(agentTaskQueue.traceId, traceIds),+ inArray(agentTaskQueue.traceId, jsonTextSet(db, traceIds)),ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),));diff --git a/src/shared/src/db/queries/user.ts b/src/shared/src/db/queries/user.tsindex 3f78448d8..68a8fbf73 100644--- a/src/shared/src/db/queries/user.ts+++ b/src/shared/src/db/queries/user.ts@@ -340,7 +340,8 @@ export async function getUserByNameAndDiscriminator(export async function withUniqueDiscriminator<T>(_db: Database,input: { id: string; name: string },- insertFn: (discriminator: string) => Promise<T>+ insertFn: (discriminator: string) => Promise<T>,+ collisionColumns?: readonly string[]): Promise<T> {for (let width = MIN_DISCRIMINATOR_WIDTH; width <= MAX_DISCRIMINATOR_WIDTH; width++) {for (let attempt = 0; attempt < MAX_DISCRIMINATOR_ATTEMPTS; attempt++) {@@ -351,7 +352,7 @@ export async function withUniqueDiscriminator<T>(try {return await insertFn(discriminator);} catch (err) {- if (!isUniqueConstraintError(err)) throw err;+ if (!isUniqueConstraintError(err, collisionColumns)) throw err;}}}diff --git a/src/shared/src/utils/db-errors.ts b/src/shared/src/utils/db-errors.tsindex d68f01136..37cda7816 100644--- a/src/shared/src/utils/db-errors.ts+++ b/src/shared/src/utils/db-errors.ts@@ -2,9 +2,16 @@* Returns true when the error represents a SQLite UNIQUE constraint violation,* whether thrown directly by the driver or wrapped by DrizzleQueryError (0.44+).*/-export function isUniqueConstraintError(err: unknown): boolean {+export function isUniqueConstraintError(err: unknown, expectedColumns?: readonly string[]): boolean {if (err instanceof Error) {const e = err as Error & { code?: string; cause?: unknown };+ if (expectedColumns) {+ if (e.cause instanceof Error) return isUniqueConstraintError(e.cause, expectedColumns);+ const signature = e.message.match(/UNIQUE constraint failed:\s*([^:\n]+)/)?.[1];+ const columns = signature?.split(",").map((column) => column.trim());+ if (!columns || expectedColumns.length === 0 || columns.length !== expectedColumns.length) return false;+ return expectedColumns.every((column, index) => columns[index] === column);+ }if (e.code === "SQLITE_CONSTRAINT_UNIQUE") return true;if (e.message.includes("UNIQUE")) return true;// DrizzleQueryError (0.44+) wraps the driver error as .causediff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex 99fefefe3..6b1deea36 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi } from "vitest";+import { createDb } from "../../src/db";import * as agentInbox from "../../src/db/queries/community/agent-inbox";import * as marks from "../../src/db/queries/community/mark";import { formatRef, formatSeq, DM_SERVER } from "../../src/community-cli-contract";@@ -19,10 +20,12 @@ import { formatRef, formatSeq, DM_SERVER } from "../../src/community-cli-contracfunction createSequentialDb(responses: unknown[][]) {let call = 0;const methods = ["from", "where", "leftJoin", "innerJoin", "orderBy", "limit", "groupBy", "as"];- const select = vi.fn(() => {+ const select = vi.fn((fields: any) => {+ if (fields?.value) return createDb({} as any).select(fields);const idx = call++;const chain: any = {};for (const m of methods) chain[m] = vi.fn(() => chain);+ chain.as = vi.fn(() => fields);chain.then = (resolve: any, reject: any) =>Promise.resolve(responses[idx] ?? []).then(resolve, reject);return chain;@@ -712,15 +715,7 @@ describe("resolveUnreadNoticeChannel", () => {});describe("getInboxSnapshotForAgent", () => {- // Call order:- // 1-3. `listVisibleChannelIdsForUser` (memberships, channels, viewer members)- // 4. DM channels the bot has an access row on- // 5. Blocked-DM anti-join inner builder (part of call 4's SQL)- // 6. Visible-channel types lookup- // 7. `listParticipatingThreadIds` (skipped when no narrow types among visible)- // 8. The snapshot aggregation SQL- // 9. sender-name hydration- it("returns [] and skips the user-name lookup when there's no pending unread", async () => {+ it("returns [] when the joined snapshot has no pending unread", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],@@ -734,31 +729,21 @@ describe("getInboxSnapshotForAgent", () => {expect(result).toEqual([]);});- it("preserves 101 snapshot rows across latest-sender chunks with a missing boundary identity", async () => {- const channels = Array.from({ length: 101 }, (_, i) => ({- id: `ch_${i}`, type: "text", categoryId: null, categoryPrivate: null,- creatorId: "u_owner", parentChannelId: null,- }));- const channelTypes = channels.map(({ id, type }) => ({ id, type }));- const aggregated = Array.from({ length: 101 }, (_, i) => ({- channelId: `ch_${i}`, pendingCount: i + 1, firstPendingSeq: i + 2,+ it("preserves 101 snapshot rows with a missing boundary identity", async () => {+ const channelTypes = Array.from({ length: 101 }, (_, i) => ({ id: `ch_${i}`, type: "text" }));+ const joined = channelTypes.map(({ id }, i) => ({+ channelId: id, pendingCount: i + 1, firstPendingSeq: i + 2,latestSeq: i + 3, mentionCount: i % 2,+ sender: i === 100 ? null : {+ id: `sender_${i}`, name: `Sender${i}`, discriminator: String(i).padStart(4, "0"),+ },}));- const latestMessages = Array.from({ length: 101 }, (_, i) => ({- channelId: `ch_${i}`, seq: i + 3, authorId: `sender_${i}`,- }));- const firstSenderChunk = Array.from({ length: 100 }, (_, i) => ({- id: `sender_${i}`, name: `Sender${i}`, discriminator: String(i).padStart(4, "0"),- }));- const db = createSequentialDb([- [{ serverId: "srv_1" }], channels, [], [], [], channelTypes.slice(0, 100), channelTypes.slice(100),- aggregated.slice(0, 100), aggregated.slice(100),- latestMessages.slice(0, 50), latestMessages.slice(50, 100), latestMessages.slice(100),- firstSenderChunk, [], // sender_100 is absent in the second hydration chunk- ]);- const out = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");+ const db = createSequentialDb([channelTypes.slice(0, 100), channelTypes.slice(100), [], joined]);+ const out = await agentInbox.getInboxSnapshotForAgent(db, "bot_1", {+ accessVisibleChannelIds: channelTypes.map(({ id }) => id),+ });expect(out).toHaveLength(101);- expect(out.map((r) => r.channelId)).toEqual(channels.map((c) => c.id));+ expect(out.map((r) => r.channelId)).toEqual(channelTypes.map((c) => c.id));expect(out[0]).toMatchObject({ latestSender: "@Sender0#0000", pendingCount: 1, latestSeq: 3 });expect(out[100]).toMatchObject({latestSender: "Deleted user", pendingCount: 101, firstPendingSeq: 102, latestSeq: 103,@@ -766,62 +751,25 @@ describe("getInboxSnapshotForAgent", () => {expect(JSON.stringify(out)).not.toContain("sender_100");});- it("hydrates latestSender from the user table and sets hasMention from mentionCount", async () => {+ it("projects latestSender and hasMention from the joined snapshot", async () => {const db = createSequentialDb([- [{ serverId: "srv_1" }],- [- { id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },- { id: "ch_2", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },- ],+ [{ id: "ch_1", type: "text" }, { id: "ch_2", type: "text" }],[],- [], // DM access channels- [], // blocked-DM anti-join inner builder; same SQL statement[- { id: "ch_1", type: "text" },- { id: "ch_2", type: "text" },- ],- [- {- channelId: "ch_1",- pendingCount: 3,- firstPendingSeq: 5,- latestSeq: 7,- mentionCount: 1,- },- {- channelId: "ch_2",- pendingCount: 1,- firstPendingSeq: 9,- latestSeq: 9,- mentionCount: 0,- },- ],- [- { channelId: "ch_1", seq: 7, authorId: "u_1" },- { channelId: "ch_2", seq: 9, authorId: "u_2" },- ],- [- { id: "u_1", name: "Alice", discriminator: "1234" },+ { channelId: "ch_1", pendingCount: 3, firstPendingSeq: 5, latestSeq: 7,+ mentionCount: 1, sender: { id: "u_1", name: "Alice", discriminator: "1234" } },+ { channelId: "ch_2", pendingCount: 1, firstPendingSeq: 9, latestSeq: 9,+ mentionCount: 0, sender: null },],]);- const result = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");+ const result = await agentInbox.getInboxSnapshotForAgent(db, "bot_1", {+ accessVisibleChannelIds: ["ch_1", "ch_2"],+ });expect(result).toEqual([- {- channelId: "ch_1",- pendingCount: 3,- firstPendingSeq: 5,- latestSeq: 7,- latestSender: "@Alice#1234",- hasMention: true,- },- {- channelId: "ch_2",- pendingCount: 1,- firstPendingSeq: 9,- latestSeq: 9,- latestSender: "Deleted user",- hasMention: false,- },+ { channelId: "ch_1", pendingCount: 3, firstPendingSeq: 5, latestSeq: 7,+ latestSender: "@Alice#1234", hasMention: true },+ { channelId: "ch_2", pendingCount: 1, firstPendingSeq: 9, latestSeq: 9,+ latestSender: "Deleted user", hasMention: false },]);});diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex 819c76501..a621ac136 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi } from "vitest";+import { createDb } from "../../src/db";import * as inboxQueries from "../../src/db/queries/community/inbox";import { isChannelUnread, isDmUnread } from "../../src/db/queries/community/inbox";@@ -223,7 +224,7 @@ describe("listUnreadForumOpeners — scoped forum projection", () => {function createForumOpenerMock(responseSets: any[][]) {let call = 0;const chain: any = {};- chain.select = vi.fn(() => chain);+ chain.select = vi.fn((fields: any) => fields?.value ? createDb({} as any).select(fields) : chain);chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);chain.leftJoin = vi.fn(() => chain);@@ -281,7 +282,7 @@ describe("listUnreadForumOpeners — scoped forum projection", () => {});});- it("chunks the authorized id scope and globally sorts createdAt, seq, then id", async () => {+ it("uses one authorized set predicate and globally sorts createdAt, seq, then id", async () => {const firstChunk = [raw({ openerMessageId: "opener_a", openerSeq: 4, createdAt: "2026-07-07T10:00:00.000Z" }),raw({ openerMessageId: "opener_z", openerSeq: 8, createdAt: "2026-07-07T09:00:00.000Z" }),@@ -290,11 +291,11 @@ describe("listUnreadForumOpeners — scoped forum projection", () => {raw({ openerMessageId: "opener_b", openerSeq: 5, createdAt: "2026-07-07T10:00:00.000Z" }),raw({ openerMessageId: "opener_c", openerSeq: 5, createdAt: "2026-07-07T10:00:00.000Z" }),];- const db = createForumOpenerMock([firstChunk, secondChunk]);+ const db = createForumOpenerMock([[...firstChunk, ...secondChunk]]);const ids = Array.from({ length: 91 }, (_, i) => `forum_${i}`);const result = await inboxQueries.listUnreadForumOpeners(db, "u1", ids);- expect(db.select).toHaveBeenCalledTimes(2);+ expect(db.where).toHaveBeenCalledTimes(1);expect(result.map((row) => row.openerMessageId)).toEqual(["opener_c","opener_b",@@ -308,7 +309,7 @@ describe("listThreadOpenersByChildIds — structurally validated child projectiofunction createChildOpenerMock(responseSets: any[][]) {let call = 0;const chain: any = {};- chain.select = vi.fn(() => chain);+ chain.select = vi.fn((fields: any) => fields?.value ? createDb({} as any).select(fields) : chain);chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);chain.leftJoin = vi.fn(() => chain);@@ -356,15 +357,14 @@ describe("listThreadOpenersByChildIds — structurally validated child projectioexpect(rows[1]?.openerUnread).toBe(false);});- it("chunks the bounded child id set and globally sorts results", async () => {+ it("uses one child set predicate and globally sorts results", async () => {const db = createChildOpenerMock([[raw({ openerMessageId: "older", childChannelId: "post_old", createdAt: "2026-07-07T09:00:00.000Z" }),- ], [raw({ openerMessageId: "newer", childChannelId: "post_new", createdAt: "2026-07-07T11:00:00.000Z" }),]]);const ids = Array.from({ length: 91 }, (_, index) => `post_${index}`);const rows = await inboxQueries.listThreadOpenersByChildIds(db, "u1", ids);- expect(db.select).toHaveBeenCalledTimes(2);+ expect(db.where).toHaveBeenCalledTimes(1);expect(rows.map((row) => row.openerMessageId)).toEqual(["newer", "older"]);});});diff --git a/src/shared/test/queries/community-search.test.ts b/src/shared/test/queries/community-search.test.tsindex 54c234203..64432d340 100644--- a/src/shared/test/queries/community-search.test.ts+++ b/src/shared/test/queries/community-search.test.ts@@ -1,5 +1,8 @@-import { describe, it, expect } from "vitest";-import { sanitizeFtsQuery } from "../../src/db/queries/community/search";+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 { sanitizeFtsQuery, searchMessagesInServer } from "../../src/db/queries/community/search";describe("sanitizeFtsQuery", () => {it("single word produces prefix match", () => {@@ -28,3 +31,70 @@ describe("sanitizeFtsQuery", () => {expect(sanitizeFtsQuery("AND OR NOT")).toBe('""');});});++describe("searchMessagesInServer against real SQLite", () => {+ let sqlite: Sqlite.Database;+ let db: Database;+ const quotedChannel = "visible'quoted";++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', email TEXT NOT NULL,+ emailVerified INTEGER, image TEXT, avatarVersion INTEGER NOT NULL DEFAULT 0,+ avatarObjectKey TEXT, createdAt TEXT NOT NULL, updatedAt TEXT NOT NULL,+ isBot INTEGER NOT NULL DEFAULT 0, ownerUserId TEXT, deletedAt TEXT,+ discriminator TEXT NOT NULL DEFAULT '0000', lastRefreshContextAt TEXT+ );+ CREATE TABLE community_channel (id TEXT PRIMARY KEY, server_id TEXT);+ CREATE TABLE community_message (+ id TEXT PRIMARY KEY, author_id TEXT NOT NULL, content TEXT NOT NULL,+ type TEXT NOT NULL DEFAULT 'default', mention_type TEXT, reply_to_id TEXT,+ embeds TEXT, created_at TEXT NOT NULL, channel_id TEXT NOT NULL,+ seq INTEGER NOT NULL DEFAULT 0, friendship_id TEXT, client_nonce TEXT+ );+ INSERT INTO user (id, email, createdAt, updatedAt)+ VALUES ('author', '[email protected]', '2026-09-01', '2026-09-01');+ `);+ const insertChannel = sqlite.prepare("INSERT INTO community_channel (id, server_id) VALUES (?, ?)");+ for (const channelId of ["visible", quotedChannel, "unauthorized"]) insertChannel.run(channelId, "server");+ insertChannel.run("outside", "other-server");+ const insertMessage = sqlite.prepare(`+ INSERT INTO community_message (id, author_id, content, channel_id, created_at)+ VALUES (?, 'author', ?, ?, ?)+ `);+ insertMessage.run("old-visible", "needle", "visible", "2026-09-01T00:01:00.000Z");+ insertMessage.run("new-visible", "needle", "visible", "2026-09-01T00:05:00.000Z");+ insertMessage.run("literal-visible", "needle", quotedChannel, "2026-09-01T00:03:00.000Z");+ insertMessage.run("hidden", "needle", "unauthorized", "2026-09-01T00:06:00.000Z");+ insertMessage.run("other-server", "needle", "outside", "2026-09-01T00:07:00.000Z");+ insertMessage.run("wrong-content", "haystack", "visible", "2026-09-01T00:08:00.000Z");+ db = drizzle(sqlite) as unknown as Database;+ });++ afterEach(() => sqlite.close());++ it("intersects server and visible channels before the global newest limit", async () => {+ const rows = await searchMessagesInServer(db, {+ query: "needle", serverId: "server", visibleChannelIds: ["visible", quotedChannel, "outside"], limit: 2,+ });+ expect(rows.map((row) => row.message.id)).toEqual(["new-visible", "literal-visible"]);+ });++ it("keeps undefined visibility trusted within the requested server", async () => {+ const rows = await searchMessagesInServer(db, { query: "needle", serverId: "server", limit: 3 });+ expect(rows.map((row) => row.message.id)).toEqual(["hidden", "new-visible", "literal-visible"]);+ });++ it("returns no rows for an explicitly empty visible set", async () => {+ const rows = await searchMessagesInServer(db, { query: "needle", serverId: "server", visibleChannelIds: [] });+ expect(rows).toEqual([]);+ });++ it("keeps large repeated visible sets literal, scoped and unique", async () => {+ const visibleChannelIds = ["visible", quotedChannel, "outside", ...Array.from({ length: 150 }, (_, i) => `missing-${i}`), "visible", quotedChannel];+ const rows = await searchMessagesInServer(db, { query: "needle", serverId: "server", visibleChannelIds, limit: 2 });+ expect(rows.map((row) => row.message.id)).toEqual(["new-visible", "literal-visible"]);+ });+});diff --git a/src/shared/test/queries/inbox.test.ts b/src/shared/test/queries/inbox.test.tsindex fb0fa0138..cc6e9a9f9 100644--- a/src/shared/test/queries/inbox.test.ts+++ b/src/shared/test/queries/inbox.test.ts@@ -1,8 +1,9 @@import { describe, it, expect, vi } from "vitest";+import { createDb } from "../../src/db";import * as inboxQueries from "../../src/db/queries/inbox";function createMockDb(rows: any[]) {- const chain: any = {};+ const chain: any = createDb({} as any);chain.all = vi.fn(() => Promise.resolve(rows));chain.run = vi.fn(() => Promise.resolve());return chain;diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.tsindex 19e9f6af2..4b4b58e2d 100644--- a/src/shared/test/queries/server.test.ts+++ b/src/shared/test/queries/server.test.ts@@ -34,6 +34,7 @@ function createDbMock(opts: {let selectIdx = 0;const db: any = {+ batch: vi.fn(async (queries: PromiseLike<unknown>[]) => Promise.all(queries)),insert(table: unknown) {const call: InsertCall = { table, values: {}, returningArg: undefined };insertCalls.push(call);@@ -47,7 +48,7 @@ function createDbMock(opts: {const thenable = {returning(arg?: unknown) {call.returningArg = arg;- return Promise.resolve(rowsForThisInsert);+ return thenable;},then(resolve: (v: unknown) => void) {resolve(rowsForThisInsert);@@ -199,6 +200,12 @@ describe("createServer", () => {});expect(insertCalls).toHaveLength(7);+ expect(db.batch).toHaveBeenCalledTimes(1);+ expect(db.batch.mock.calls[0][0]).toHaveLength(7);+ const serverId = insertCalls[0].values.id;+ const publicCategoryId = insertCalls[1].values.id;+ const privateCategoryId = insertCalls[3].values.id;+ const privateChannelId = insertCalls[4].values.id;// 1) communityServerexpect(insertCalls[0].table).toBe(communityServer);@@ -211,7 +218,7 @@ describe("createServer", () => {// 2) public communityCategoryexpect(insertCalls[1].table).toBe(communityCategory);expect(insertCalls[1].values).toMatchObject({- serverId: "srv_1",+ serverId,name: "Public",position: 0,private: 0,@@ -220,8 +227,8 @@ describe("createServer", () => {// 3) public communityChannel — /allexpect(insertCalls[2].table).toBe(communityChannel);expect(insertCalls[2].values).toMatchObject({- serverId: "srv_1",- categoryId: "cat_public",+ serverId,+ categoryId: publicCategoryId,name: "all",type: "text",position: 0,@@ -230,7 +237,7 @@ describe("createServer", () => {// 4) private communityCategoryexpect(insertCalls[3].table).toBe(communityCategory);expect(insertCalls[3].values).toMatchObject({- serverId: "srv_1",+ serverId,name: "Private",position: 1,private: 1,@@ -240,8 +247,8 @@ describe("createServer", () => {// 5) private communityChannel — /roomexpect(insertCalls[4].table).toBe(communityChannel);expect(insertCalls[4].values).toMatchObject({- serverId: "srv_1",- categoryId: "cat_private",+ serverId,+ categoryId: privateCategoryId,name: "room",type: "text",position: 0,@@ -251,7 +258,7 @@ describe("createServer", () => {// 6) private channel roster includes the ownerexpect(insertCalls[5].table).toBe(communityChannelMember);expect(insertCalls[5].values).toMatchObject({- channelId: "ch_room",+ channelId: privateChannelId,userId: ownerId,relation: "access",source: "added",@@ -261,7 +268,7 @@ describe("createServer", () => {// 7) communityServerMember — exactly one owner row, railOrder=0expect(insertCalls[6].table).toBe(communityServerMember);expect(insertCalls[6].values).toMatchObject({- serverId: "srv_1",+ serverId,userId: ownerId,role: "owner",railOrder: 0,diff --git a/src/shared/test/queries/task.test.ts b/src/shared/test/queries/task.test.tsindex c13f76818..2e8b986ca 100644--- a/src/shared/test/queries/task.test.ts+++ b/src/shared/test/queries/task.test.ts@@ -1,6 +1,8 @@import Sqlite from "better-sqlite3";import { drizzle } from "drizzle-orm/better-sqlite3";-import { describe, it, expect, vi } from "vitest";+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";+import type { Database } from "../../src/db";+import { TASK_TYPES } from "../../src/constants";import * as taskQueries from "../../src/db/queries/task";function createMockDb(rows: any[]) {@@ -264,3 +266,69 @@ describe("getTraceAgentsByTaskIds", () => {expect(result.size).toBe(0);});});++describe("listTaskHistory against real SQLite", () => {+ let sqlite: Sqlite.Database;+ let db: Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE agent_task_queue (+ id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, runtime_id TEXT NOT NULL,+ workspace_id TEXT NOT NULL, conversation_id TEXT NOT NULL, prompt TEXT NOT NULL,+ type TEXT NOT NULL, context_key TEXT, status TEXT NOT NULL, priority INTEGER DEFAULT 0,+ result TEXT, context TEXT, session_id TEXT, created_at TEXT NOT NULL,+ dispatched_at TEXT, started_at TEXT, completed_at TEXT, error TEXT,+ trace_id TEXT, parent_task_id TEXT+ );+ `);+ const insert = sqlite.prepare(`+ INSERT INTO agent_task_queue (+ id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, created_at+ ) VALUES (?, ?, 'runtime', ?, 'conversation', 'prompt', ?, ?, ?)+ `);+ insert.run("task-a", "agent", "workspace", "completed", TASK_TYPES.USER_DM_MESSAGE, "2026-09-01T00:00:00.000Z");+ insert.run("task-b", "agent", "workspace", "completed", TASK_TYPES.USER_DM_MESSAGE, "2026-09-01T00:00:00.000Z");+ insert.run("task-c", "agent", "workspace", "failed", TASK_TYPES.EMAIL_NOTIFICATION, "2026-09-01T00:01:00.000Z");+ insert.run("wrong-status", "agent", "workspace", "running", TASK_TYPES.EMAIL_NOTIFICATION, "2026-09-01T00:02:00.000Z");+ insert.run("wrong-type", "agent", "workspace", "completed", TASK_TYPES.CALENDAR_EVENT, "2026-09-01T00:03:00.000Z");+ insert.run("kill", "agent", "workspace", "failed", TASK_TYPES.KILL_TASK, "2026-09-01T00:04:00.000Z");+ insert.run("other-agent", "other-agent", "workspace", "completed", TASK_TYPES.USER_DM_MESSAGE, "2026-09-01T00:05:00.000Z");+ insert.run("other-workspace", "agent", "other-workspace", "failed", TASK_TYPES.EMAIL_NOTIFICATION, "2026-09-01T00:06:00.000Z");+ db = drizzle(sqlite) as unknown as Database;+ });++ afterEach(() => sqlite.close());++ it("combines status and type scopes while preserving chronological cursor pages", async () => {+ const filters = {+ status: ["completed", "failed"],+ type: [TASK_TYPES.USER_DM_MESSAGE, TASK_TYPES.EMAIL_NOTIFICATION, TASK_TYPES.KILL_TASK],+ limit: 2,+ };+ const first = await taskQueries.listTaskHistory(db, "agent", "workspace", filters);+ expect(first.tasks.map((row) => row.id)).toEqual(["task-b", "task-c"]);+ expect(first.hasMore).toBe(true);+ const second = await taskQueries.listTaskHistory(db, "agent", "workspace", {+ ...filters, before: first.tasks[0].createdAt, beforeId: first.tasks[0].id,+ });+ expect(second.tasks.map((row) => row.id)).toEqual(["task-a"]);+ expect(second.hasMore).toBe(false);+ });++ it.each([undefined, { status: [], type: [] }])("keeps omitted or empty filters unscoped without admitting kill or other owners: %j", async (opts) => {+ const page = await taskQueries.listTaskHistory(db, "agent", "workspace", opts);+ expect(page.tasks.map((row) => row.id)).toEqual(["task-a", "task-b", "task-c", "wrong-status", "wrong-type"]);+ expect(page.hasMore).toBe(false);+ });++ it("keeps both large repeated collections equivalent to their eligible values", async () => {+ const page = await taskQueries.listTaskHistory(db, "agent", "workspace", {+ status: ["completed", "failed", ...Array.from({ length: 150 }, (_, i) => `missing-status-${i}`), "completed"],+ type: [TASK_TYPES.USER_DM_MESSAGE, TASK_TYPES.EMAIL_NOTIFICATION, TASK_TYPES.KILL_TASK, ...Array.from({ length: 150 }, (_, i) => `missing-type-${i}`), TASK_TYPES.USER_DM_MESSAGE],+ });+ expect(page.tasks.map((row) => row.id)).toEqual(["task-a", "task-b", "task-c"]);+ expect(page.hasMore).toBe(false);+ });+});diff --git a/src/shared/test/queries/user.test.ts b/src/shared/test/queries/user.test.tsindex 9a1d93dac..e3d834a81 100644--- a/src/shared/test/queries/user.test.ts+++ b/src/shared/test/queries/user.test.ts@@ -376,6 +376,31 @@ describe("withUniqueDiscriminator", () => {).rejects.toBe(otherErr);expect(insertFn).toHaveBeenCalledTimes(1);});++ it("retries a selected server-handle signature and preserves the salted winner", async () => {+ const columns = ["community_server.name", "community_server.discriminator"];+ const error = new Error("Driver error", { cause: new Error("UNIQUE constraint failed: community_server.name, community_server.discriminator") });+ const insertFn = vi.fn<(discriminator: string) => Promise<string>>()+ .mockRejectedValueOnce(error)+ .mockImplementationOnce(async (discriminator) => discriminator);+ await expect(userQueries.withUniqueDiscriminator({} as any, { id: "selected", name: "Server" }, insertFn, columns))+ .resolves.toBe(computeDiscriminator("selected:4:1", 4));+ expect(insertFn).toHaveBeenCalledTimes(2);+ });++ it.each([+ new Error("UNIQUE constraint failed: community_category.server_id, community_category.name"),+ Object.assign(new Error("constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" }),+ new Error("FOREIGN KEY constraint failed"),+ new Error("injected abort"),+ ])("preserves a nonmatching batch error without salt retry: %s", async (error) => {+ const insertFn = vi.fn(async () => { throw error; });+ await expect(userQueries.withUniqueDiscriminator({} as any, { id: "selected", name: "Server" }, insertFn,+ ["community_server.name", "community_server.discriminator"]))+ .rejects.toBe(error);+ expect(insertFn).toHaveBeenCalledTimes(1);+ });+});describe("probeAvailableDiscriminator", () => {diff --git a/src/shared/test/utils/db-errors.test.ts b/src/shared/test/utils/db-errors.test.tsindex f99e65640..d578d5f8f 100644--- a/src/shared/test/utils/db-errors.test.ts+++ b/src/shared/test/utils/db-errors.test.ts@@ -40,4 +40,25 @@ describe("isUniqueConstraintError", () => {expect(isUniqueConstraintError(new Error("connection timeout"))).toBe(false);expect(isUniqueConstraintError(new Error("FOREIGN KEY constraint"))).toBe(false);});++ it("matches only the complete expected native UNIQUE column signature", () => {+ const columns = ["community_server.name", "community_server.discriminator"];+ expect(isUniqueConstraintError(new Error("D1_ERROR: UNIQUE constraint failed: community_server.name, community_server.discriminator: SQLITE_CONSTRAINT"), columns)).toBe(true);+ expect(isUniqueConstraintError(new Error("UNIQUE constraint failed: community_category.server_id, community_category.name"), columns)).toBe(false);+ expect(isUniqueConstraintError(new Error("UNIQUE constraint failed: community_server.name, community_server.discriminator_extra"), columns)).toBe(false);+ expect(isUniqueConstraintError(new Error("UNIQUE constraint failed: community_server.name, community_server.discriminator, community_server.id"), columns)).toBe(false);+ expect(isUniqueConstraintError(Object.assign(new Error("constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" }), columns)).toBe(false);+ expect(isUniqueConstraintError(new Error("FOREIGN KEY constraint failed"), columns)).toBe(false);+ expect(isUniqueConstraintError(new Error("UNIQUE constraint failed: community_server.name"), [])).toBe(false);+ });++ it("uses the actual nested driver cause rather than an outer query's text", () => {+ const columns = ["community_server.name", "community_server.discriminator"];+ const match = new Error("UNIQUE constraint failed: community_server.name, community_server.discriminator");+ const other = new Error("UNIQUE constraint failed: community_category.server_id, community_category.name");+ expect(isUniqueConstraintError(new Error("Query failed", { cause: new Error("Wrapped", { cause: match }) }), columns)).toBe(true);+ expect(isUniqueConstraintError(new Error(match.message, { cause: other }), columns)).toBe(false);+ expect(isUniqueConstraintError(null, columns)).toBe(false);+ });+});diff --git a/src/web/test-runtime/d1-sql-correctness.runtime.test.ts b/src/web/test-runtime/d1-sql-correctness.runtime.test.tsnew file mode 100644index 000000000..c6fb8b95a--- /dev/null+++ b/src/web/test-runtime/d1-sql-correctness.runtime.test.ts@@ -0,0 +1,371 @@+/// <reference types="@cloudflare/vitest-plugin/types" />++import { env } from "cloudflare:workers";+import { afterEach, describe, expect, it } from "vitest";+import { createDb, queries } from "@alook/shared";++const runtimeEnv = env as unknown as CloudflareEnv;+const prefixes: string[] = [];+const triggers: string[] = [];+const evidence: { label: string; statements: { sql: string; bindings: unknown[] }[]; batches: number[] }[] = [];+const baseline = "2026-09-01T00:00:00.000Z";+const later = "2026-09-02T00:00:00.000Z";++function fixturePrefix(label: string) {+ const prefix = `sql171_${label.slice(0, 8)}_${crypto.randomUUID().replaceAll("-", "")}`;+ prefixes.push(prefix);+ return prefix;+}++async function run(sql: string, ...bindings: unknown[]) {+ return runtimeEnv.DB.prepare(sql).bind(...bindings).run();+}++async function rows<T>(sql: string, ...bindings: unknown[]) {+ return (await runtimeEnv.DB.prepare(sql).bind(...bindings).all<T>()).results;+}++async function seedBatch(statements: D1PreparedStatement[]) {+ for (let i = 0; i < statements.length; i += 50) await runtimeEnv.DB.batch(statements.slice(i, i + 50));+}++function recordedDb(label: string, beforeBatch?: (attempt: number, statements: { sql: string; bindings: unknown[] }[]) => Promise<void>) {+ const record = { label, statements: [] as { sql: string; bindings: unknown[] }[], batches: [] as number[] };+ evidence.push(record);+ const d1 = new Proxy(runtimeEnv.DB, {+ get(target, key) {+ if (key === "prepare") return (sql: string) => new Proxy(target.prepare(sql), {+ get(statement, method) {+ if (method === "bind") return (...bindings: unknown[]) => {+ record.statements.push({ sql, bindings: [...bindings] });+ expect(bindings.length, `${label}: complete D1 binding array`).toBeLessThanOrEqual(100);+ return statement.bind(...bindings);+ };+ const value = Reflect.get(statement, method, statement);+ return typeof value === "function" ? value.bind(statement) : value;+ },+ });+ if (key === "batch") return async (statements: D1PreparedStatement[]) => {+ record.batches.push(statements.length);+ await beforeBatch?.(record.batches.length, record.statements.slice(-statements.length));+ return target.batch(statements);+ };+ const value = Reflect.get(target, key, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ return { db: createDb(d1), record };+}++function statementCount(record: ReturnType<typeof recordedDb>["record"], fragment: string, count: number) {+ const selected = record.statements.filter(({ sql }) => sql.includes(fragment));+ expect(selected.length).toBeGreaterThan(0);+ for (const statement of selected) expect(statement.bindings).toHaveLength(count);+}++async function seedUser(id: string, name = id, discriminator = "1710") {+ await run("INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, ?, ?)", id, `${id}@example.com`, name, discriminator);+}++async function seedCommunity(label: string, count = 125) {+ const prefix = fixturePrefix(label);+ const viewer = `${prefix}_viewer`;+ const sender = `${prefix}_sender`;+ const other = `${prefix}_other`;+ const server = `${prefix}_server`;+ await seedUser(viewer);+ await seedUser(sender, `${prefix}Alice`, "1711");+ await seedUser(other, `${prefix}Bob`, "1712");+ await run("INSERT INTO community_server (id, name, discriminator, owner_id, created_at) VALUES (?, ?, '1710', ?, ?)", server, prefix, viewer, baseline);+ await run("INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, 'owner', ?)", `${prefix}_member`, server, viewer, baseline);+ const channels = Array.from({ length: count }, (_, i) => `${prefix}_channel_${String(i).padStart(3, "0")}`);+ await seedBatch(channels.map((id, i) => runtimeEnv.DB.prepare("INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, ?, ?, 'text', ?)").bind(id, server, `channel-${i}`, baseline)));+ return { prefix, viewer, sender, other, server, channels };+}++async function seedWorkspace(label: string) {+ const prefix = fixturePrefix(label);+ const viewer = `${prefix}_viewer`;+ const workspace = `${prefix}_workspace`;+ const runtime = `${prefix}_runtime`;+ const agent = `${prefix}_agent`;+ const conversation = `${prefix}_conversation`;+ await seedUser(viewer);+ await run("INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES (?, 'Workspace', ?, ?, ?)", workspace, prefix, baseline, baseline);+ await run("INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, device_info, created_at, updated_at) VALUES (?, ?, 'sql171', 'local', 'codex', '', ?, ?)", runtime, workspace, baseline, baseline);+ await run("INSERT INTO agent (id, workspace_id, name, runtime_id, owner_id, created_at, updated_at) VALUES (?, ?, 'Agent', ?, ?, ?, ?)", agent, workspace, runtime, viewer, baseline, baseline);+ await run("INSERT INTO conversation (id, workspace_id, agent_id, user_id, title, type, channel, created_at) VALUES (?, ?, ?, ?, 'Conversation', 'user_dm_message', 'default', ?)", conversation, workspace, agent, viewer, baseline);+ return { prefix, viewer, workspace, runtime, agent, conversation };+}++async function graph(name: string) {+ return rows<{ servers: number; categories: number; channels: number; access: number; members: number }>(`+ SELECT+ (SELECT COUNT(*) FROM community_server WHERE name = ?) AS servers,+ (SELECT COUNT(*) FROM community_category c JOIN community_server s ON s.id = c.server_id WHERE s.name = ?) AS categories,+ (SELECT COUNT(*) FROM community_channel c JOIN community_server s ON s.id = c.server_id WHERE s.name = ?) AS channels,+ (SELECT COUNT(*) FROM community_channel_member m JOIN community_channel c ON c.id = m.channel_id JOIN community_server s ON s.id = c.server_id WHERE s.name = ?) AS access,+ (SELECT COUNT(*) FROM community_server_member m JOIN community_server s ON s.id = m.server_id WHERE s.name = ?) AS members+ `, name, name, name, name, name);+}++afterEach(async () => {+ for (const trigger of triggers.splice(0)) await run(`DROP TRIGGER IF EXISTS ${trigger}`);+ for (const prefix of prefixes.splice(0)) {+ await run("DELETE FROM community_server WHERE name GLOB ? OR id GLOB ?", `${prefix}*`, `${prefix}*`);+ await run("DELETE FROM community_channel WHERE id GLOB ?", `${prefix}*`);+ await run("DELETE FROM agent_task_queue WHERE id GLOB ?", `${prefix}*`);+ await run("DELETE FROM conversation WHERE id GLOB ?", `${prefix}*`);+ await run("DELETE FROM agent WHERE id GLOB ?", `${prefix}*`);+ await run("DELETE FROM agent_runtime WHERE id GLOB ?", `${prefix}*`);+ await run("DELETE FROM workspace WHERE id GLOB ?", `${prefix}*`);+ await run("DELETE FROM user WHERE id GLOB ?", `${prefix}*`);+ }+ expect(await rows("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name GLOB 'sql171_*'")).toEqual([]);+ for (const record of evidence.splice(0)) console.log("SQL171_NATIVE_BINDINGS", JSON.stringify(record));+});++describe("whole-statement SQL correctness on native D1", () => {+ it("hydrates 98/99/100 roots without cross-workspace or kill-task contamination", async () => {+ const f = await seedWorkspace("traces");+ const decoy = await seedWorkspace("trace_decoy");+ await seedBatch(Array.from({ length: 101 }, (_, i) => runtimeEnv.DB.prepare("INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, type, status, created_at, trace_id) VALUES (?, ?, ?, ?, ?, ?, 'user_dm_message', 'completed', ?, ?)").bind(`${f.prefix}_task_${i}`, f.agent, f.runtime, f.workspace, f.conversation, `root-${i}`, `2026-09-02T00:00:${String(i).padStart(3, "0")}Z`, `${f.prefix}_trace_${i}`)));+ await run("INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, type, status, trace_id, parent_task_id) VALUES (?, ?, ?, ?, ?, 'kill decoy', 'kill_task', 'running', ?, ?)", `${f.prefix}_kill`, f.agent, f.runtime, f.workspace, f.conversation, `${f.prefix}_trace_100`, `${f.prefix}_task_100`);+ await run("INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, type, status, trace_id) VALUES (?, ?, ?, ?, ?, 'workspace decoy', 'user_dm_message', 'running', ?)", `${decoy.prefix}_task`, decoy.agent, decoy.runtime, decoy.workspace, decoy.conversation, `${f.prefix}_trace_100`);+ const helper = `${f.prefix}_helper_agent`;+ await run("INSERT INTO agent (id, workspace_id, name, runtime_id, owner_id, created_at, updated_at) VALUES (?, ?, 'Helper', ?, ?, ?, ?)", helper, f.workspace, f.runtime, f.viewer, baseline, baseline);+ await run("INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, type, status, trace_id, parent_task_id) VALUES (?, ?, ?, ?, ?, 'helper', 'user_dm_message', 'failed', ?, ?)", `${f.prefix}_helper_task`, helper, f.runtime, f.workspace, f.conversation, `${f.prefix}_trace_100`, `${f.prefix}_task_100`);+ const { db, record } = recordedDb("K1");+ for (const limit of [1, 98, 99, 100]) {+ const result = await queries.task.listTraces(db, f.workspace, { limit });+ expect(result.hasMore).toBe(true);+ expect(result.traces).toHaveLength(limit);+ expect(result.traces[0]).toMatchObject({ traceId: `${f.prefix}_trace_100`, status: "failed", taskCount: 2, helperAgentIds: [helper] });+ }+ expect((await queries.task.listTraces(db, f.workspace, { agentId: f.agent, channel: "default", status: "failed", multiAgent: true })).traces).toMatchObject([{ traceId: `${f.prefix}_trace_100` }]);+ expect(await queries.task.listTraces(db, f.workspace, { agentId: helper })).toEqual({ traces: [], hasMore: false });+ expect(await queries.task.listTraces(db, f.workspace, { channel: "absent" })).toEqual({ traces: [], hasMore: false });+ expect(await queries.task.listTraces(db, f.workspace, { limit: 0 })).toEqual({ traces: [], hasMore: false });+ expect(await queries.task.listTraces(db, f.workspace, { before: baseline })).toEqual({ traces: [], hasMore: false });+ statementCount(record, 'json_each', 3);+ });++ it("preserves task cursor ties, empty filters, unknown filters and chronological output with 125 filter values", async () => {+ const f = await seedWorkspace("history");+ await seedBatch(["a", "b", "c", "kill"].map((suffix) => runtimeEnv.DB.prepare("INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, type, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'completed', ?)").bind(`${f.prefix}_${suffix}`, f.agent, f.runtime, f.workspace, f.conversation, suffix, suffix === "kill" ? "kill_task" : "user_dm_message", later)));+ const { db, record } = recordedDb("K2");+ const result = await queries.task.listTaskHistory(db, f.agent, f.workspace, {+ status: Array(125).fill("completed"), type: Array(125).fill("user_dm_message"), before: later, beforeId: `${f.prefix}_c`, limit: 1,+ });+ expect(result).toMatchObject({ hasMore: true, tasks: [{ id: `${f.prefix}_b` }] });+ statementCount(record, "json_each", 9);+ expect((await queries.task.listTaskHistory(db, f.agent, f.workspace, { status: [], type: [], limit: 2 })).tasks.map(({ prompt }) => prompt)).toEqual(["b", "c"]);+ expect((await queries.task.listTaskHistory(db, f.agent, f.workspace, { type: ["unknown"] })).tasks).toEqual([]);+ expect((await queries.task.listTaskHistory(db, f.agent, f.workspace, { status: ["unknown"] })).tasks).toEqual([]);+ expect((await queries.task.listTaskHistory(db, f.agent, `${f.prefix}_absent`)).tasks).toEqual([]);+ });++ it("uses all three inbox types in one raw SQL subquery and keeps defaults, scope and limit+1", async () => {+ const f = await seedWorkspace("inbox");+ const peer = `${f.prefix}_peer`;+ await seedUser(peer, "Peer", "1713");+ const types = ["user_dm_message", "email_notification", "calendar_event"];+ await seedBatch(types.flatMap((type, i) => {+ const conversation = `${f.prefix}_conversation_${i}`;+ return [+ runtimeEnv.DB.prepare("INSERT INTO conversation (id, workspace_id, agent_id, user_id, title, type, channel, created_at) VALUES (?, ?, ?, ?, ?, ?, 'default', ?)").bind(conversation, f.workspace, f.agent, f.viewer, type, type, later),+ runtimeEnv.DB.prepare("INSERT INTO inbox_unread (id, conversation_id, user_id, workspace_id, agent_id, task_id, task_type, task_status, completed_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'completed', ?)").bind(`${f.prefix}_inbox_${i}`, conversation, f.viewer, f.workspace, f.agent, `${f.prefix}_task_${i}`, type, `2026-09-02T00:00:0${i}.000Z`),+ ];+ }));+ await run("INSERT INTO inbox_unread (id, conversation_id, user_id, workspace_id, agent_id, task_id, task_type, task_status, completed_at) VALUES (?, ?, ?, ?, ?, 'decoy', 'user_dm_message', 'completed', ?)", `${f.prefix}_other_user`, `${f.prefix}_conversation_0`, peer, f.workspace, f.agent, later);+ await run("INSERT INTO inbox_unread (id, conversation_id, user_id, workspace_id, agent_id, task_id, task_type, task_status, completed_at) VALUES (?, ?, ?, ?, ?, 'decoy', 'calendar_event', 'completed', ?)", `${f.prefix}_other_workspace`, f.conversation, f.viewer, `${f.prefix}_wrong`, f.agent, later);+ const { db, record } = recordedDb("K3-K4");+ const filter = Array.from({ length: 126 }, (_, i) => types[i % 3]);+ const page = await queries.inbox.listUnreadConversations(db, f.viewer, f.workspace, { types: filter, limit: 2 });+ expect(page.hasMore).toBe(true);+ expect(page.items.map(({ root_task_type }) => root_task_type)).toEqual(["calendar_event", "email_notification"]);+ expect(await queries.inbox.getUnreadCount(db, f.viewer, f.workspace, filter)).toBe(3);+ expect(await queries.inbox.getUnreadCount(db, f.viewer, f.workspace, [])).toBe(1);+ expect(await queries.inbox.getUnreadCount(db, f.viewer, f.workspace, ["unknown"])).toBe(0);+ expect((await queries.inbox.listUnreadConversations(db, f.viewer, f.workspace)).items).toHaveLength(1);+ const before = await queries.inbox.listUnreadConversations(db, f.viewer, f.workspace, { types: filter, before: "2026-09-02T00:00:02.000Z" });+ expect(before.items.map(({ root_task_type }) => root_task_type)).toEqual(["email_notification", "user_dm_message"]);+ for (const statement of record.statements) expect(statement.bindings).toHaveLength(statement.sql.includes("COUNT(*)") ? 3 : statement.sql.includes("u.completed_at <") ? 5 : 4);+ });++ it("joins the latest eligible snapshot sender across 87/88/90/125 scopes and preserves read, join, policy and notify gates", async () => {+ const f = await seedCommunity("snapshot");+ await seedBatch(f.channels.map((id, i) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'pending', ?, ?, 1)").bind(`${f.prefix}_message_${i}`, i === 2 ? f.viewer : f.sender, i === 1 ? baseline : later, id)));+ await run("INSERT INTO community_read_state (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq) VALUES (?, ?, ?, ?, ?, 1)", `${f.prefix}_read`, f.viewer, f.channels[0], later, `${f.prefix}_message_0`);+ await run("INSERT INTO community_channel_member (id, channel_id, user_id, relation, source, added_at) VALUES (?, ?, ?, 'access', 'added', ?)", `${f.prefix}_access`, f.channels[6], f.viewer, "2026-09-03T00:00:00.000Z");+ await seedBatch([3, 4, 5].map((i) => runtimeEnv.DB.prepare("INSERT INTO community_notification_setting (id, user_id, channel_id, level) VALUES (?, ?, ?, ?)").bind(`${f.prefix}_policy_${i}`, f.viewer, f.channels[i], i === 3 ? "none" : "mentions")));+ await seedBatch([4, 5].flatMap((i) => [+ runtimeEnv.DB.prepare("INSERT INTO community_mention (id, message_id, user_id, kind) VALUES (?, ?, ?, ?)").bind(`${f.prefix}_mention_${i}`, `${f.prefix}_message_${i}`, f.viewer, i === 4 ? "mention" : "reply"),+ runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'newer ineligible', ?, ?, 2)").bind(`${f.prefix}_new_${i}`, f.other, later, f.channels[i]),+ ]));+ await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'legacy zero', ?, ?, 0)", `${f.prefix}_zero`, f.other, later, f.channels[7]);+ const privateId = `${f.prefix}_private`;+ await run("INSERT INTO community_category (id, server_id, name, private) VALUES (?, ?, 'Private', 1)", `${f.prefix}_category`, f.server);+ await run("INSERT INTO community_channel (id, server_id, category_id, name, type, created_at) VALUES (?, ?, ?, 'hidden', 'text', ?)", privateId, f.server, `${f.prefix}_category`, baseline);+ await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'hidden', ?, ?, 1)", `${f.prefix}_hidden_msg`, f.sender, later, privateId);+ const excluded = new Set([0, 1, 2, 3, 6].map((i) => f.channels[i]));+ const { db, record } = recordedDb("K5");+ for (const count of [1, 87, 88, 90, 125]) {+ const ids = f.channels.slice(0, count);+ const out = await queries.communityAgentInbox.getInboxSnapshotForAgent(db, f.viewer, { accessVisibleChannelIds: [...ids, ...ids] });+ expect(new Set(out.map(({ channelId }) => channelId))).toEqual(new Set(ids.filter((id) => !excluded.has(id))));+ if (count > 5) {+ expect(out.find(({ channelId }) => channelId === f.channels[4])).toMatchObject({ pendingCount: 1, latestSeq: 1, latestSender: `@${f.prefix}Alice#1711`, hasMention: true });+ expect(out.find(({ channelId }) => channelId === f.channels[5])).toMatchObject({ pendingCount: 1, latestSeq: 1, latestSender: `@${f.prefix}Alice#1711`, hasMention: false });+ }+ }+ expect(await queries.communityAgentInbox.getInboxSnapshotForAgent(db, f.viewer, { accessVisibleChannelIds: [] })).toEqual([]);+ const defaultOut = await queries.communityAgentInbox.getInboxSnapshotForAgent(db, f.viewer);+ expect(defaultOut.some(({ channelId }) => channelId === privateId)).toBe(false);+ expect(defaultOut.find(({ channelId }) => channelId === f.channels[7])).toMatchObject({ pendingCount: 1, firstPendingSeq: 1, latestSeq: 1 });+ await seedBatch([2, 3].map((seq) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'more pending', ?, ?, ?)").bind(`${f.prefix}_extra_${seq}`, f.other, later, f.channels[8], seq)));+ expect(await queries.communityAgentInbox.getInboxSnapshotForAgent(db, f.viewer, { accessVisibleChannelIds: [f.channels[8]] })).toMatchObject([{ pendingCount: 3, firstPendingSeq: 1, latestSeq: 3, latestSender: `@${f.prefix}Bob#1712` }]);+ const thread = `${f.prefix}_thread`;+ await run("INSERT INTO community_channel (id, server_id, parent_channel_id, name, type, created_at) VALUES (?, ?, ?, 'thread', 'thread', ?)", thread, f.server, f.channels[8], baseline);+ await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'thread', ?, ?, 1)", `${f.prefix}_thread_msg`, f.sender, later, thread);+ expect(await queries.communityAgentInbox.getInboxSnapshotForAgent(db, f.viewer, { accessVisibleChannelIds: [thread] })).toEqual([]);+ await run("INSERT INTO community_channel_member (id, channel_id, user_id, relation, source, added_at) VALUES (?, ?, ?, 'notify', 'added', ?)", `${f.prefix}_notify`, thread, f.viewer, baseline);+ expect(await queries.communityAgentInbox.getInboxSnapshotForAgent(db, f.viewer, { accessVisibleChannelIds: [thread] })).toMatchObject([{ channelId: thread, pendingCount: 1 }]);+ statementCount(record, 'pending_inbox', 14);+ expect(await rows("SELECT last_read_seq FROM community_read_state WHERE id = ?", `${f.prefix}_read`)).toEqual([{ last_read_seq: 1 }]);+ });++ it("keeps authorized forum/thread metadata and stable ordering across 88/89/90/125 IDs", async () => {+ const f = await seedCommunity("openers");+ await run("UPDATE community_channel SET type = 'forum' WHERE server_id = ?", f.server);+ const children = f.channels.map((_, i) => `${f.prefix}_child_${i}`);+ await seedBatch(f.channels.flatMap((parent, i) => [+ runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, ?, ?, ?, 1)").bind(`${f.prefix}_opener_${i}`, f.sender, i === 6 ? " " : `title-${i}`, i === 5 ? baseline : later, parent),+ runtimeEnv.DB.prepare("INSERT INTO community_channel (id, server_id, parent_channel_id, parent_message_id, name, type, created_at) VALUES (?, ?, ?, ?, ?, 'thread', ?)").bind(children[i], f.server, parent, `${f.prefix}_opener_${i}`, i === 6 ? "fallback" : `child-${i}`, later),+ ]));+ await run("UPDATE community_channel SET archived = 1 WHERE id IN (?, ?)", f.channels[0], children[1]);+ await run("UPDATE community_channel SET type = 'text' WHERE id IN (?, ?)", f.channels[2], children[3]);+ await run("INSERT INTO community_read_state (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq) VALUES (?, ?, ?, ?, ?, 1)", `${f.prefix}_read`, f.viewer, f.channels[4], later, `${f.prefix}_opener_4`);+ await run("INSERT INTO community_notification_setting (id, user_id, channel_id, level) VALUES (?, ?, ?, 'none')", `${f.prefix}_mute`, f.viewer, f.channels[7]);+ const { db, record } = recordedDb("K6-K7");+ for (const count of [1, 88, 89, 90, 125]) {+ const parents = f.channels.slice(0, count);+ const childIds = children.slice(0, count);+ const forum = await queries.communityInbox.listUnreadForumOpeners(db, f.viewer, [...parents, ...parents]);+ const thread = await queries.communityInbox.listThreadOpenersByChildIds(db, f.viewer, [...childIds, ...childIds]);+ expect(new Set(forum.map(({ openerMessageId }) => openerMessageId))).toEqual(new Set(parents.flatMap((_, i) => [0, 1, 2, 4, 5, 7].includes(i) ? [] : [`${f.prefix}_opener_${i}`])));+ expect(new Set(thread.map(({ childChannelId }) => childChannelId))).toEqual(new Set(childIds.filter((_, i) => ![0, 1, 3].includes(i))));+ expect(forum.map(({ openerMessageId }) => openerMessageId)).toEqual([...forum.map(({ openerMessageId }) => openerMessageId)].sort((a, b) => b.localeCompare(a)));+ if (count > 7) {+ expect(forum.find(({ childChannelId }) => childChannelId === children[6])).toMatchObject({ title: "fallback", forumChannelId: f.channels[6] });+ expect(thread.find(({ childChannelId }) => childChannelId === children[4])).toMatchObject({ openerUnread: false });+ expect(thread.find(({ childChannelId }) => childChannelId === children[7])).toMatchObject({ openerUnread: false });+ }+ }+ expect(await queries.communityInbox.listUnreadForumOpeners(db, f.viewer, [])).toEqual([]);+ expect(await queries.communityInbox.listThreadOpenersByChildIds(db, f.viewer, [])).toEqual([]);+ statementCount(record, 'forum_inbox_child', 13);+ statementCount(record, 'thread_inbox_child_lookup', 13);+ });++ it("selects newest scoped search rows before the global limit and escapes literal LIKE input", async () => {+ const f = await seedCommunity("search");+ await seedBatch(Array.from({ length: 60 }, (_, i) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle old', ?, ?, ?)").bind(`${f.prefix}_old_${i}`, f.sender, baseline, f.channels[0], i + 1)));+ await seedBatch(f.channels.map((channel, i) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle new', ?, ?, ?)").bind(`${f.prefix}_new_${i}`, f.sender, `2026-09-02T00:00:${String(i).padStart(3, "0")}Z`, channel, i === 0 ? 61 : 1)));+ const decoy = await seedCommunity("search_decoy", 1);+ await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle hidden', '2099-01-01', ?, 1)", `${decoy.prefix}_msg`, decoy.sender, decoy.channels[0]);+ await run("INSERT INTO community_category (id, server_id, name, private) VALUES (?, ?, 'Hidden', 1)", `${f.prefix}_hidden_category`, f.server);+ await run("INSERT INTO community_channel (id, server_id, category_id, name, type, created_at) VALUES (?, ?, ?, 'hidden', 'text', ?)", `${f.prefix}_hidden`, f.server, `${f.prefix}_hidden_category`, baseline);+ await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle private', '2099-01-01', ?, 1)", `${f.prefix}_hidden_msg`, f.sender, `${f.prefix}_hidden`);+ const { db, record } = recordedDb("search");+ const ids = f.channels.slice(0, 124);+ const serverResult = await queries.communitySearch.searchMessagesInServer(db, { query: "needle", serverId: f.server, visibleChannelIds: [...ids, ...ids], limit: 3 });+ expect(serverResult.map(({ message }) => message.id)).toEqual([123, 122, 121].map((i) => `${f.prefix}_new_${i}`));+ expect(await queries.communitySearch.searchMessagesInServer(db, { query: "needle", serverId: f.server, visibleChannelIds: [] })).toEqual([]);+ expect((await queries.communitySearch.searchMessagesInServer(db, { query: "needle", serverId: f.server, visibleChannelIds: f.channels })).map(({ message }) => message.id)).toEqual(Array.from({ length: 50 }, (_, i) => `${f.prefix}_new_${124 - i}`));+ expect((await queries.communitySearch.searchMessages(db, { query: "needle", channelId: f.channels[0], limit: 1 }))[0].message.id).toBe(`${f.prefix}_new_0`);+ statementCount(record, "json_each", 4);+ const literal = String.raw`100%_\end`;+ await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, ?, '2099-01-01', ?, 62)", `${f.prefix}_literal`, f.sender, literal, f.channels[0]);+ expect((await queries.communitySearch.searchMessages(db, { query: literal, channelId: f.channels[0] })).map(({ message }) => message.id)).toEqual([`${f.prefix}_literal`]);+ const dm = `${f.prefix}_dm`;+ await run("INSERT INTO community_channel (id, type, created_at) VALUES (?, 'dm', ?)", dm, baseline);+ await seedBatch([1, 2].map((seq) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle dm', ?, ?, ?)").bind(`${f.prefix}_dm_${seq}`, f.sender, seq === 1 ? baseline : later, dm, seq)));+ expect((await queries.communitySearch.searchMessages(db, { query: "needle", channelId: dm, limit: 1 }))[0].message.id).toBe(`${f.prefix}_dm_2`);+ const tied = [3, 4].map((seq) => `${f.prefix}_tie_${seq}`);+ await seedBatch(tied.map((id, i) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'tie', ?, ?, ?)").bind(id, f.sender, later, dm, i + 3)));+ expect(new Set((await queries.communitySearch.searchMessages(db, { query: "tie", channelId: dm, limit: 2 })).map(({ message }) => message.id))).toEqual(new Set(tied));+ });++ it("creates exactly one complete graph with a single native seven-statement batch", async () => {+ const prefix = fixturePrefix("server_success");+ const owner = `${prefix}_owner`;+ await seedUser(owner);+ const { db, record } = recordedDb("server-success");+ const result = await queries.communityServer.createServer(db, { name: prefix, ownerId: owner, description: "description" });+ expect(record.batches).toEqual([7]);+ expect(result.server).toMatchObject({ name: prefix, ownerId: owner, description: "description" });+ expect(result.ownerMember).toMatchObject({ userId: owner, userName: owner, userImage: null, userAvatarVersion: 0, userDiscriminator: "1710" });+ expect(await graph(prefix)).toEqual([{ servers: 1, categories: 2, channels: 2, access: 1, members: 1 }]);+ expect(await rows("SELECT c.name, k.name AS category, k.private FROM community_channel c JOIN community_category k ON k.id = c.category_id WHERE c.server_id = ? ORDER BY k.position", result.server.id)).toEqual([{ name: "all", category: "Public", private: 0 }, { name: "room", category: "Private", private: 1 }]);+ expect(await rows("SELECT role, rail_order FROM community_server_member WHERE server_id = ?", result.server.id)).toEqual([{ role: "owner", rail_order: 0 }]);+ });++ it.each([2, 3, 4, 5, 6, 7])("rolls back every graph row after a native failure at seed step %i", async (step) => {+ const prefix = fixturePrefix(`rollback_${step}`);+ const owner = `${prefix}_owner`;+ await seedUser(owner);+ const trigger = `${prefix}_trigger`;+ const table = step === 2 || step === 4 ? "community_category" : step === 3 || step === 5 ? "community_channel" : step === 6 ? "community_channel_member" : "community_server_member";+ const scope = step === 6 ? "(SELECT server_id FROM community_channel WHERE id = NEW.channel_id)" : "NEW.server_id";+ const extra = step === 2 ? "AND NEW.name = 'Public'" : step === 4 ? "AND NEW.name = 'Private'" : step === 3 ? "AND NEW.name = 'all'" : step === 5 ? "AND NEW.name = 'room'" : "";+ triggers.push(trigger);+ await run(`CREATE TRIGGER ${trigger} BEFORE INSERT ON ${table} WHEN ${scope} IN (SELECT id FROM community_server WHERE name = '${prefix}') ${extra} BEGIN SELECT RAISE(ABORT, 'sql171 injected step${step}'); END`);+ const { db, record } = recordedDb(`server-rollback-${step}`);+ await expect(queries.communityServer.createServer(db, { name: prefix, ownerId: owner })).rejects.toThrow(`sql171 injected step${step}`);+ expect(record.batches).toEqual([7]);+ expect(await graph(prefix)).toEqual([{ servers: 0, categories: 0, channels: 0, access: 0, members: 0 }]);+ });++ it("retries the complete batch only after a real server handle UNIQUE collision", async () => {+ const prefix = fixturePrefix("collision");+ const owner = `${prefix}_owner`;+ await seedUser(owner);+ let firstDiscriminator: unknown;+ const { db, record } = recordedDb("server-collision", async (attempt, statements) => {+ if (attempt !== 1) return;+ const insert = statements[0];+ expect(insert.sql).toContain('insert into "community_server" ("id", "name", "discriminator"');+ expect(insert.bindings[1]).toBe(prefix);+ firstDiscriminator = insert.bindings[2];+ await run("INSERT INTO community_server (id, name, discriminator, owner_id, created_at) VALUES (?, ?, ?, ?, ?)", `${prefix}_competitor`, prefix, firstDiscriminator, owner, baseline);+ });+ const result = await queries.communityServer.createServer(db, { name: prefix, ownerId: owner });+ expect(record.batches.length).toBeGreaterThanOrEqual(2);+ expect(record.batches.every((size) => size === 7)).toBe(true);+ expect(result.server.discriminator).not.toBe(firstDiscriminator);+ expect(await graph(prefix)).toEqual([{ servers: 2, categories: 2, channels: 2, access: 1, members: 1 }]);+ expect(await rows("SELECT COUNT(*) AS total FROM community_category WHERE server_id = ?", `${prefix}_competitor`)).toEqual([{ total: 0 }]);+ });++ it("propagates a real child UNIQUE error without salt retry or partial rows", async () => {+ const f = await seedCommunity("child_unique", 1);+ await run("INSERT INTO community_category (id, server_id, name) VALUES (?, ?, 'Existing')", `${f.prefix}_existing_category`, f.server);+ const name = `${f.prefix}_target`;+ const trigger = `${f.prefix}_trigger`;+ triggers.push(trigger);+ await run(`CREATE TRIGGER ${trigger} BEFORE INSERT ON community_category WHEN NEW.server_id IN (SELECT id FROM community_server WHERE name = '${name}') BEGIN INSERT INTO community_category (id, server_id, name) VALUES ('${f.prefix}_duplicate_category', '${f.server}', 'Existing'); END`);+ const { db, record } = recordedDb("server-child-unique");+ await expect(queries.communityServer.createServer(db, { name, ownerId: f.viewer })).rejects.toThrow("UNIQUE constraint failed: community_category.server_id, community_category.name");+ expect(record.batches).toEqual([7]);+ expect(await graph(name)).toEqual([{ servers: 0, categories: 0, channels: 0, access: 0, members: 0 }]);+ });++ it("propagates a native foreign-key failure without retry", async () => {+ const name = fixturePrefix("server_fk");+ const { db, record } = recordedDb("server-fk");+ await expect(queries.communityServer.createServer(db, { name, ownerId: `${name}_absent` })).rejects.toThrow("FOREIGN KEY constraint failed");+ expect(record.batches).toEqual([7]);+ expect(await graph(name)).toEqual([{ servers: 0, categories: 0, channels: 0, access: 0, members: 0 }]);+ });+});