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(daemon,community): plug credential-proxy connection leak, fix agent-send race, surface audit failures
Gus946c36119a71
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex 55db9ac7f..6e9662254 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -211,4 +211,223 @@ describe("startCredentialProxy (zero-trust end to end)", () => {const r = await post(proxy.url, reg.voucher, "/send");expect(r.status).toBe(401);});++ it("surfaces the buffered inboxPull response AND fires onInboxPullResponse", async () => {+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ const seen: Array<{ agentId: string; count: number }> = [];+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ proxy = await startCredentialProxy(broker, {+ onInboxPullResponse: (agentId, messages) => seen.push({ agentId, count: messages.length }),+ });+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);++ const r = await post(proxy.url, reg.voucher, "/api/inboxPull");+ expect(r.status).toBe(200);+ // `startUpstream()` always responds `{ ok: true }` — no `messages` field —+ // so the callback should NOT fire for a response that isn't shaped like+ // an inboxPull payload, but the response itself must still be forwarded.+ expect(seen).toEqual([]);+ });+});++/** A throwaway upstream that never responds — for timeout/leak tests below. */+async function startHungUpstream(): Promise<{+ url: string;+ close: () => Promise<void>;+ connectionsClosed: () => number;+}> {+ let connectionsClosed = 0;+ const server = http.createServer(() => {+ /* never respond */+ });+ server.on("connection", (socket) => {+ socket.on("close", () => {+ connectionsClosed++;+ });+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));+ const addr = server.address();+ const port = typeof addr === "object" && addr ? addr.port : 0;+ return {+ url: `http://127.0.0.1:${port}`,+ close: () => new Promise<void>((r) => server.close(() => r())),+ connectionsClosed: () => connectionsClosed,+ };+}++/** An upstream that sends headers + a partial body, then stalls forever without ending it. */+async function startStallingBodyUpstream(): Promise<{+ url: string;+ close: () => Promise<void>;+ connectionsClosed: () => number;+}> {+ let connectionsClosed = 0;+ const server = http.createServer((_req, res) => {+ res.writeHead(200, { "content-type": "application/json" });+ res.write("{"); // headers + partial body flushed, then never res.end()+ });+ server.on("connection", (socket) => {+ socket.on("close", () => {+ connectionsClosed++;+ });+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));+ const addr = server.address();+ const port = typeof addr === "object" && addr ? addr.port : 0;+ return {+ url: `http://127.0.0.1:${port}`,+ close: () => new Promise<void>((r) => server.close(() => r())),+ connectionsClosed: () => connectionsClosed,+ };+}++/** An upstream that sends headers + a partial body, then hard-resets the socket (not just idle). */+async function startResettingBodyUpstream(): Promise<{ url: string; close: () => Promise<void> }> {+ const server = http.createServer((_req, res) => {+ res.writeHead(200, { "content-type": "application/json" });+ res.write("{");+ // Destroy the raw socket (TCP-level reset), as opposed to merely going+ // idle — this fires 'error'/'close' on the client's IncomingMessage+ // immediately, unlike a stall which relies on the idle timer. The+ // short delay gives the client a chance to actually receive/parse the+ // headers first — this test targets the "headers already forwarded,+ // THEN reset" case, not a same-tick connection failure.+ setTimeout(() => res.socket?.destroy(), 50);+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));+ const addr = server.address();+ const port = typeof addr === "object" && addr ? addr.port : 0;+ return {+ url: `http://127.0.0.1:${port}`,+ close: () => new Promise<void>((r) => server.close(() => r())),+ };+}++describe("startCredentialProxy — upstream timeout / connection-leak fix", () => {+ let proxy: RunningProxy | undefined;+ let upstreamClose: (() => Promise<void>) | undefined;+ afterEach(async () => {+ await proxy?.close();+ await upstreamClose?.();+ proxy = undefined;+ upstreamClose = undefined;+ });++ it("returns 504 (not hanging forever) when the upstream never responds", async () => {+ const hung = await startHungUpstream();+ upstreamClose = hung.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: hung.url });+ proxy = await startCredentialProxy(broker, { upstreamTimeoutMs: 100 });+ const reg = broker.mint("a", "l", ["send"], REAL_KEY);++ const start = Date.now();+ const r = await post(proxy.url, reg.voucher, "/send");+ expect(r.status).toBe(504);+ expect(JSON.parse(r.body).code).toBe("upstream_timeout");+ // Bounded by the timeout, not hanging indefinitely.+ expect(Date.now() - start).toBeLessThan(1000);+ });++ it("destroys the outbound connection on timeout instead of leaking it", async () => {+ const hung = await startHungUpstream();+ upstreamClose = hung.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: hung.url });+ proxy = await startCredentialProxy(broker, { upstreamTimeoutMs: 100 });+ const reg = broker.mint("a", "l", ["send"], REAL_KEY);++ await post(proxy.url, reg.voucher, "/send");+ // Give the destroyed socket a moment to actually finish closing.+ await new Promise((r) => setTimeout(r, 300));+ expect(hung.connectionsClosed()).toBe(1);+ });++ it("destroys the upstream request when the downstream client disconnects early", async () => {+ const hung = await startHungUpstream();+ upstreamClose = hung.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: hung.url });+ // Deliberately no upstreamTimeoutMs override (long default) — only the+ // downstream-close handler should be what rescues this connection.+ proxy = await startCredentialProxy(broker);+ const reg = broker.mint("a", "l", ["send"], REAL_KEY);++ const controller = new AbortController();+ const pending = fetch(`${proxy.url}/send`, {+ method: "POST",+ headers: { Authorization: `Bearer ${reg.voucher}`, "content-type": "application/json" },+ body: JSON.stringify({}),+ signal: controller.signal,+ }).catch(() => undefined);+ await new Promise((r) => setTimeout(r, 100));+ controller.abort();+ await pending;++ await new Promise((r) => setTimeout(r, 300));+ expect(hung.connectionsClosed()).toBe(1);+ });++ it("bounds the downstream response too when upstream sends headers then stalls mid-body", async () => {+ // Regression guard: once upstream headers arrive, `responded` flips+ // true — the timeout handler must still destroy `res`, not just the+ // upstream socket, or the agent's own client hangs forever reading a+ // body that will never end (destroying the piped-FROM source does not+ // itself end the piped-TO destination).+ const stalling = await startStallingBodyUpstream();+ upstreamClose = stalling.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: stalling.url });+ proxy = await startCredentialProxy(broker, { upstreamTimeoutMs: 100 });+ const reg = broker.mint("a", "l", ["send"], REAL_KEY);++ const start = Date.now();+ const res = await fetch(`${proxy.url}/send`, {+ method: "POST",+ headers: { Authorization: `Bearer ${reg.voucher}`, "content-type": "application/json" },+ body: JSON.stringify({}),+ });+ // Headers were already forwarded before the stall — that part of the+ // response already committed and can't (and shouldn't) change.+ expect(res.status).toBe(200);+ // Reading the (otherwise never-ending) body must still be bounded.+ await expect(res.text()).rejects.toThrow();+ expect(Date.now() - start).toBeLessThan(1000);++ await new Promise((r) => setTimeout(r, 300));+ expect(stalling.connectionsClosed()).toBe(1);+ });++ it("bounds the downstream response when the upstream hard-resets mid-body (not just idles)", async () => {+ // `.pipe()` doesn't forward source errors to the destination, and a hard+ // reset fires 'error'/'close' immediately rather than waiting out the+ // idle timer — a distinct failure mode from the stalling-body test above,+ // and NOT covered by the `upstreamReq`-level timeout/close wiring alone.+ const resetting = await startResettingBodyUpstream();+ upstreamClose = resetting.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: resetting.url });+ // Long timeout — only the upstream-response error/close listener, not+ // the idle timer, should be what rescues this connection.+ proxy = await startCredentialProxy(broker, { upstreamTimeoutMs: 5000 });+ const reg = broker.mint("a", "l", ["send"], REAL_KEY);++ const start = Date.now();+ const res = await fetch(`${proxy.url}/send`, {+ method: "POST",+ headers: { Authorization: `Bearer ${reg.voucher}`, "content-type": "application/json" },+ body: JSON.stringify({}),+ });+ expect(res.status).toBe(200);+ await expect(res.text()).rejects.toThrow();+ expect(Date.now() - start).toBeLessThan(1000);+ });++ it("a fast upstream response is unaffected by the timeout/close wiring", async () => {+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ // A tight timeout that a real (fast) upstream should never come close to.+ proxy = await startCredentialProxy(broker, { upstreamTimeoutMs: 2000 });+ const reg = broker.mint("agent-1", "l", ["send"], REAL_KEY);++ const r = await post(proxy.url, reg.voucher, "/send");+ expect(r.status).toBe(200);+ });});diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex d60876b89..87236a42f 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -240,6 +240,9 @@ export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (_method, pathnamreturn undefined;};+/** Default cap on how long a forwarded upstream request may stay open. */+const DEFAULT_UPSTREAM_TIMEOUT_MS = 20_000;+export interface CredentialProxyOptions {/** Bind host (default loopback). Keep it loopback in production. */host?: string;@@ -254,6 +257,17 @@ export interface CredentialProxyOptions {* regardless of whether the agent is an in-process stub or a real subprocess.*/onInboxPullResponse?: (agentId: string, messages: Message[]) => void;+ /**+ * Max time (ms) a forwarded upstream request may stay open before the proxy+ * gives up on it. Without this, a slow/hung upstream (or an agent that+ * abandons its own request early) leaks the outbound connection FOREVER —+ * there is nothing else in this handler that ever times it out. Enough of+ * these piling up exhausts the daemon process's fds/sockets, at which point+ * the proxy can't accept ANY new local connection — surfacing to every+ * agent's CLI as a raw `fetch failed`, daemon-wide, until old leaked+ * connections eventually get reclaimed. Default 20s.+ */+ upstreamTimeoutMs?: number;}export interface RunningProxy {@@ -307,6 +321,17 @@ export async function startCredentialProxy(outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");+ // `responded` guards only against writing a second response to the+ // DOWNSTREAM client (writeHead/end can't fire twice) — it does NOT gate+ // upstream socket cleanup. Those are two separate concerns: headers can+ // arrive from upstream (responded=true) while the body is still+ // streaming, and a stall or client disconnect at that point is just as+ // much of a leak as one before headers ever arrived. `upstreamRes` is+ // tracked so close/timeout can destroy it too once it exists — an+ // in-flight `.pipe(res)` doesn't end `res` on a non-graceful destroy.+ let responded = false;+ let upstreamRes: http.IncomingMessage | undefined;+const upstreamReq = upstreamClient.request({protocol: upstream.protocol,@@ -316,14 +341,28 @@ export async function startCredentialProxy(path: joinPath(upstream.pathname, rewriteAgentPath(req.url ?? "/")),headers: outHeaders,},- (upstreamRes) => {- if (isInboxPull && upstreamRes.statusCode && upstreamRes.statusCode < 300) {+ (res_) => {+ responded = true;+ upstreamRes = res_;+ // `.pipe()` does NOT forward source errors to the destination, and a+ // hard upstream reset/crash mid-body (unlike a mere stall) fires+ // 'error'/'close' on `res_` immediately rather than waiting for the+ // idle timer above — without this, `res` would hang forever on a+ // reset exactly like it would on a stall. `res_.complete` is set by+ // Node once `'end'` has actually fired, so this is a no-op on the+ // normal successful-completion path.+ const destroyResIfIncomplete = () => {+ if (!res_.complete) res.destroy();+ };+ res_.on("error", destroyResIfIncomplete);+ res_.on("close", destroyResIfIncomplete);+ if (isInboxPull && res_.statusCode && res_.statusCode < 300) {// Buffer the inboxPull response to surface pulled messages to the daemon.const chunks: Buffer[] = [];- upstreamRes.on("data", (chunk: Buffer) => chunks.push(chunk));- upstreamRes.on("end", () => {+ res_.on("data", (chunk: Buffer) => chunks.push(chunk));+ res_.on("end", () => {const body = Buffer.concat(chunks);- res.writeHead(upstreamRes.statusCode!, upstreamRes.headers);+ res.writeHead(res_.statusCode!, res_.headers);res.end(body);try {const parsed = JSON.parse(body.toString()) as { messages?: Message[] };@@ -331,15 +370,53 @@ export async function startCredentialProxy(} catch { /* best-effort */ }});} else {- res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers);- upstreamRes.pipe(res);+ res.writeHead(res_.statusCode ?? 502, res_.headers);+ res_.pipe(res);}},);upstreamReq.on("error", (err) => {+ if (responded) return;+ responded = true;res.writeHead(502, { "content-type": "application/json" });res.end(JSON.stringify({ error: `upstream error: ${err.message}`, code: "upstream_error" }));});+ // Without a timeout, a slow/hung upstream (or one that stalls mid-body+ // after headers) leaks this outbound connection forever — nothing else+ // here ever destroys it. Enough of these pile up and the daemon can't+ // accept ANY new local connection (see module doc comment) — this is the+ // actual fix, not just cosmetic. `setTimeout` is a socket-idle timeout,+ // so it keeps firing across the whole exchange, not just while waiting+ // for headers — always destroy, but only write a 504 if we haven't+ // already committed to a response.+ const upstreamTimeoutMs = options.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS;+ upstreamReq.setTimeout(upstreamTimeoutMs, () => {+ upstreamReq.destroy();+ upstreamRes?.destroy();+ if (responded) {+ // Headers already went out (e.g. `res_.pipe(res)` is mid-flight and+ // stalled, or the inboxPull buffering never saw an `'end'`) — we+ // can't writeHead/end a response that's already started, but `res`+ // would otherwise hang on the destroyed source forever (destroying+ // `upstreamReq`/`upstreamRes` does NOT auto-end a stream piped FROM+ // them). `res.destroy()` is safe/idempotent, so unblock the agent's+ // own client the same way a downstream disconnect would.+ res.destroy();+ return;+ }+ responded = true;+ res.writeHead(504, { "content-type": "application/json" });+ res.end(JSON.stringify({ error: `upstream request timed out after ${upstreamTimeoutMs}ms`, code: "upstream_timeout" }));+ });+ // If the agent gives up (its own fetch aborts/times out) at ANY point —+ // before upstream responds, or mid-body after it started — stop pumping+ // into/from a request nobody's waiting on anymore. `.destroy()` on an+ // already-finished request/response is a safe no-op, so this can fire+ // unconditionally on every close, including the normal success path.+ res.on("close", () => {+ upstreamReq.destroy();+ upstreamRes?.destroy();+ });req.pipe(upstreamReq);});diff --git a/src/daemon/src/drivers/cliTransport.test.ts b/src/daemon/src/drivers/cliTransport.test.tsindex f07f2c6ef..47e8b5679 100644--- a/src/daemon/src/drivers/cliTransport.test.ts+++ b/src/daemon/src/drivers/cliTransport.test.ts@@ -95,6 +95,60 @@ describe("prepareCliTransport — layered spawn env", () => {const link = path.join(stateDir, "bin", "alook");expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);});++ it("revokes the agent's previous voucher before minting a new one on respawn", async () => {+ // Without this, every stop+respawn of the same agent leaves the OLD+ // voucher registered forever — an unbounded leak in the broker's map,+ // since revoke/revokeAgent is never called anywhere else in production+ // code (see plans/fix-credential-proxy-connection-leak.md).+ const cred = broker();+ const first = await prepareCliTransport(+ baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" } }),+ {},+ undefined,+ "linux",+ );+ expect(cred.size).toBe(1);+ const firstVoucher = fs.readFileSync(first.tokenFile, "utf8");+ expect(cred.check(`Bearer ${firstVoucher}`).ok).toBe(true);++ const second = await prepareCliTransport(+ baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" } }),+ {},+ undefined,+ "linux",+ );++ // Still exactly one live registration for this agent — the old one was+ // revoked, not left dangling, regardless of how many times it respawns.+ expect(cred.size).toBe(1);+ expect(cred.check(`Bearer ${firstVoucher}`).ok).toBe(false);+ const secondVoucher = fs.readFileSync(second.tokenFile, "utf8");+ expect(cred.check(`Bearer ${secondVoucher}`).ok).toBe(true);+ });++ it("does not revoke a DIFFERENT agent's voucher on respawn", async () => {+ const cred = broker();+ await prepareCliTransport(+ baseCtx(mkTmp(), {+ agentId: "agent_1",+ credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" },+ }),+ {},+ undefined,+ "linux",+ );+ await prepareCliTransport(+ baseCtx(mkTmp(), {+ agentId: "agent_2",+ credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" },+ }),+ {},+ undefined,+ "linux",+ );+ expect(cred.size).toBe(2);+ });});describe("prepareCliTransport — unified AGENTS.md packing", () => {diff --git a/src/daemon/src/drivers/cliTransport.ts b/src/daemon/src/drivers/cliTransport.tsindex a6dd223bd..fc1a56130 100644--- a/src/daemon/src/drivers/cliTransport.ts+++ b/src/daemon/src/drivers/cliTransport.ts@@ -172,6 +172,13 @@ export async function prepareCliTransport("(see src/credentials) and pass { broker, proxyUrl }. There is no plaintext mode.",);}+ // Revoke this agent's previous voucher(s) before minting a new one — an+ // agent has at most one live launch at a time, so this bounds the broker's+ // registration map to "one live entry per active agent" regardless of how+ // many times it gets stopped and respawned. Without this, every respawn+ // leaves the old registration behind forever (nothing else in production+ // code ever calls revoke/revokeAgent) — an unbounded memory leak.+ ctx.credentialProxy.broker.revokeAgent(ctx.agentId);const reg = ctx.credentialProxy.broker.mint(ctx.agentId,ctx.launchId ?? "default",diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex 45a412f09..b298ff01a 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -260,6 +260,67 @@ describe("AgentProcessManager — logging", () => {expect((ended[0]![1][0] as any).reason).toBe("turn_end");});+});++describe("AgentProcessManager — launchId threading", () => {+ // Regression test: `doSpawn` used to leave `ctx.launchId` as whatever+ // `baseContextFor` returned (almost always undefined, since no host wires+ // it there) instead of the launchId tracked from the latest agent:wake —+ // every real spawn's voucher silently collided on cliTransport's "default"+ // fallback path (see plans/fix-credential-proxy-connection-leak.md).+ it("passes the latest agent:wake's launchId into the spawned driver's LaunchContext", () => {+ let capturedCtx: LaunchContext | undefined;+ const factory: SessionFactory = ({ ctx }) => {+ capturedCtx = ctx;+ return fakeSession();+ };+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: factory,+ onRuntimeSpawnFailed: vi.fn(),+ onRuntimeSessionEstablished: vi.fn(),+ });+ mgr.register("a1", { launchId: "wake-launch-42" });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ expect(capturedCtx?.launchId).toBe("wake-launch-42");+ });++ it("falls back to baseContextFor's launchId when no wake launchId is tracked", () => {+ let capturedCtx: LaunchContext | undefined;+ const factory: SessionFactory = ({ ctx }) => {+ capturedCtx = ctx;+ return fakeSession();+ };+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ launchId: "base-fallback",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: factory,+ onRuntimeSpawnFailed: vi.fn(),+ onRuntimeSessionEstablished: vi.fn(),+ });+ mgr.register("a1"); // no launch metadata at all+ mgr.deliver("a1", { seq: 1, text: "hello" });++ expect(capturedCtx?.launchId).toBe("base-fallback");+ });+});++describe("AgentProcessManager — session race conditions", () => {// Regression test: a `stop()`/`terminate_stalled` effect can race a// still-in-flight `session.start()` and win — its `exit` handler runs// first, deleting the session from the manager's map and dispatchingdiff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 1500c8dd7..a5cdd1906 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -349,6 +349,12 @@ export class AgentProcessManager {prompt,standingPrompt,credentialProxy: base.credentialProxy ?? this.opts.credentialProxy,+ // The latest agent:wake's launchId (tracked in `this.launchIds`) — falls+ // back to whatever `baseContextFor` set, then undefined (cliTransport's+ // own "default" fallback). Without this, every real spawn left it+ // undefined, so every launch's voucher silently collided on the same+ // "default" voucher path (see plans/fix-credential-proxy-connection-leak.md).+ launchId: this.launchIds.get(agentId) ?? base.launchId,config,};diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 3e11f1ca9..1ea5c10d0 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -23,6 +23,13 @@ export function scopeKeyForTarget(target: { channelId?: string; dmConversationId* for uniqueness on its own, no CTE/transaction needed (see* plans/community-agent-cli-bridge.md design §3 for why the CTE-fusion* approach is not valid SQLite and was rejected).+ *+ * Unconditional claim: always advances the counter, no matter what the+ * caller's stale view of the world was. Callers with an `expectedSeq` to+ * verify against (the agent-send race, plans/fix-agent-send-race-condition.md)+ * must use the CAS sibling `claimNextSeqIfAligned` below instead — this+ * function alone cannot detect a stale-snapshot race, only guarantee+ * uniqueness.*/async function claimNextSeq(db: Database, scopeKey: string): Promise<number> {const rows = await db@@ -36,6 +43,36 @@ async function claimNextSeq(db: Database, scopeKey: string): Promise<number> {return rows[0]!.nextSeq;}+/**+ * Compare-and-swap claim: only advances `next_seq` if it currently equals+ * `expectedSeq` — the value the caller observed during its own alignment+ * check. Returns the newly claimed seq on success, or `null` if another+ * writer already advanced the counter (the caller lost the race and MUST+ * treat this as a no-op: no message row, no side effects of any kind).+ *+ * Safe for the very first message in a scope too: when no row exists yet,+ * the INSERT branch fires unconditionally (no conflict to gate), but that+ * branch can only ever be reached by the single first-ever writer for that+ * scope_key — every subsequent racer hits the conflict branch and is+ * correctly gated by `setWhere`.+ */+async function claimNextSeqIfAligned(+ db: Database,+ scopeKey: string,+ expectedSeq: number+): Promise<number | null> {+ const rows = await db+ .insert(communityMessageSeq)+ .values({ scopeKey, nextSeq: 1 })+ .onConflictDoUpdate({+ target: communityMessageSeq.scopeKey,+ set: { nextSeq: sql`${communityMessageSeq.nextSeq} + 1` },+ setWhere: sql`${communityMessageSeq.nextSeq} = ${expectedSeq}`,+ })+ .returning({ nextSeq: communityMessageSeq.nextSeq });+ return rows[0]?.nextSeq ?? null;+}+const DEFAULT_LIMIT = 50;// Module-level logger so every parse failure lands on the same service tag.@@ -55,21 +92,39 @@ function safeParseEmbeds(raw: string | null, messageId: string): unknown | undef}}+export type CreateMessageData = {+ authorId: string;+ content: string;+ channelId?: string;+ dmConversationId?: string;+ type?: string;+ mentionType?: string;+ replyToId?: string;+ embeds?: string;+};++/**+ * `createMessage` overloads (plans/fix-agent-send-race-condition.md design §2):+ * callers that never pass `expectedSeq` keep today's non-nullable return+ * type — no pointless null-checks forced onto the three direct callers+ * (`channels/[id]/posts/route.ts`, `servers/[id]/bots/route.ts`,+ * `friends/request/route.ts`) that never opt into the CAS guard. Only+ * callers that explicitly pass a numeric `expectedSeq` (the agent-send race+ * fix) see the nullable return — `null` means "lost the race, no row was+ * written, treat as a complete no-op".+ */export async function createMessage(db: Database,- data: {- authorId: string;- content: string;- channelId?: string;- dmConversationId?: string;- type?: string;- mentionType?: string;- replyToId?: string;- embeds?: string;- }+ data: CreateMessageData & { expectedSeq?: undefined }+): Promise<Awaited<ReturnType<typeof insertMessageRow>>>;+export async function createMessage(+ db: Database,+ data: CreateMessageData & { expectedSeq: number }+): Promise<Awaited<ReturnType<typeof insertMessageRow>> | null>;+export async function createMessage(+ db: Database,+ data: CreateMessageData & { expectedSeq?: number }) {- const now = new Date().toISOString();-// Step 0: atomically claim this scope's next seq (own top-level statement —// see design §3 for why this can't be fused into the INSERT below via a// CTE). Accepted trade-off: if the INSERT below fails after this succeeds,@@ -79,8 +134,28 @@ export async function createMessage(// doesn't support one that could express it. Kept outside the batch below// because D1 `batch()` cannot feed one statement's `.returning()` into a// later statement's values.+ //+ // When `expectedSeq` is present (plans/fix-agent-send-race-condition.md),+ // the claim is a compare-and-swap gated on the caller's own alignment-check+ // snapshot: `claimNextSeqIfAligned` returns `null` with ZERO rows written+ // anywhere if another writer already advanced the counter past what this+ // caller saw — return `null` immediately, before any insert/update below.const scopeKey = scopeKeyForTarget(data);- const seq = await claimNextSeq(db, scopeKey);+ const seq =+ data.expectedSeq !== undefined+ ? await claimNextSeqIfAligned(db, scopeKey, data.expectedSeq)+ : await claimNextSeq(db, scopeKey);+ if (seq === null) return null;+ return insertMessageRow(db, data, seq);+}++// Step 1+: everything after the seq claim above — message insert,+// channel/DM `lastMessageAt` bump, author read-state watermark. Split out of+// `createMessage` purely so the two overload signatures above can reference+// its return type instead of duplicating a hand-written row type; behavior+// is identical to having this inlined.+async function insertMessageRow(db: Database, data: CreateMessageData, seq: number) {+ const now = new Date().toISOString();// Pass `createdAt: now` explicitly so `msg.createdAt` matches the exact// string we write to `channel.lastMessageAt` / `dmConversation.lastMessageAt`diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.tsindex b086f1d33..951c3b70f 100644--- a/src/shared/test/queries/community-message.test.ts+++ b/src/shared/test/queries/community-message.test.ts@@ -528,6 +528,125 @@ describe("createMessage — seq assignment", () => {});});+describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-condition.md)", () => {+ /**+ * Same shape as `createSeqSpyDbMock` above, but scripts the CAS+ * `.returning()` call per-invocation from `seqResults`: a number resolves+ * `[{ nextSeq }]` (claim won), `null` resolves `[]` — the real+ * SQLite/Drizzle no-op shape when `onConflictDoUpdate`'s `setWhere`+ * evaluates false (claim lost the race).+ */+ function createCasSpyDbMock(opts?: { messageId?: string; seqResults?: Array<number | null> }) {+ const base = createCreateMessageDbMock(opts);+ const seqCalls: Array<{ values: any; onConflict: any }> = [];+ let seqIdx = 0;+ const seqResults = opts?.seqResults;+ const originalInsert = base.insert;+ base.insert = vi.fn((table: unknown) => {+ if (table === communityMessageSeq) {+ const rec: { values: any; onConflict: any } = { values: undefined, onConflict: undefined };+ seqCalls.push(rec);+ return {+ values: vi.fn((v: any) => {+ rec.values = v;+ return {+ onConflictDoUpdate: vi.fn((cfg: any) => {+ rec.onConflict = cfg;+ return {+ returning: vi.fn(() => {+ const next = seqResults ? seqResults[seqIdx++] : 1;+ return Promise.resolve(next === null || next === undefined ? [] : [{ nextSeq: next }]);+ }),+ };+ }),+ };+ }),+ };+ }+ return originalInsert(table);+ });+ base.__seqCalls = seqCalls;+ return base;+ }++ it("expectedSeq matching the current counter succeeds and returns a row with the expected seq", async () => {+ const db = createCasSpyDbMock({ seqResults: [20] });+ const msg = await messageQueries.createMessage(db, {+ authorId: "u_1",+ content: "hi",+ channelId: "ch_1",+ expectedSeq: 19,+ });+ expect(msg).not.toBeNull();+ expect(msg!.seq).toBe(20);+ // The CAS variant carries a setWhere gate — the unconditional claim does not.+ expect(db.__seqCalls[0].onConflict.setWhere).toBeDefined();+ });++ it("stale expectedSeq: CAS claim resolves [] → createMessage returns null, with ZERO message/channel/read-state writes", async () => {+ const db = createCasSpyDbMock({ seqResults: [null] });+ const result = await messageQueries.createMessage(db, {+ authorId: "u_1",+ content: "hi",+ channelId: "ch_1",+ expectedSeq: 19,+ });+ expect(result).toBeNull();+ // No message insert, no read-state upsert, no channel lastMessageAt bump.+ expect(db.__inserts).toHaveLength(0);+ expect(db.__updates).toHaveLength(0);+ });++ it("two racers with the same expectedSeq: first wins the CAS, second loses it", async () => {+ const db = createCasSpyDbMock({ seqResults: [20, null] });+ const first = await messageQueries.createMessage(db, {+ authorId: "u_1",+ content: "hi",+ channelId: "ch_1",+ expectedSeq: 19,+ });+ const second = await messageQueries.createMessage(db, {+ authorId: "u_2",+ content: "hi again",+ channelId: "ch_1",+ expectedSeq: 19,+ });+ expect(first?.seq).toBe(20);+ expect(second).toBeNull();+ // Both racers hit the seq-claim exactly once each, with the SAME+ // expectedSeq snapshot (they both read `latestSeq=19` before either claimed).+ expect(db.__seqCalls).toHaveLength(2);+ expect(db.__seqCalls[0].values).toEqual({ scopeKey: "channel:ch_1", nextSeq: 1 });+ expect(db.__seqCalls[1].values).toEqual({ scopeKey: "channel:ch_1", nextSeq: 1 });+ expect(db.__seqCalls[0].onConflict.setWhere).toBeDefined();+ expect(db.__seqCalls[1].onConflict.setWhere).toBeDefined();+ });++ it("expectedSeq: 0 on a scope with no prior messages succeeds (first-message-ever INSERT branch, no conflict to gate)", async () => {+ const db = createCasSpyDbMock({ seqResults: [1] });+ const msg = await messageQueries.createMessage(db, {+ authorId: "u_1",+ content: "hi",+ channelId: "ch_1",+ expectedSeq: 0,+ });+ expect(msg).not.toBeNull();+ expect(msg!.seq).toBe(1);+ });++ it("no expectedSeq behaves exactly as before (regression guard — web/human send path unaffected)", async () => {+ const db = createCasSpyDbMock({ seqResults: [1] });+ const msg = await messageQueries.createMessage(db, {+ authorId: "u_1",+ content: "hi",+ channelId: "ch_1",+ });+ expect(msg.seq).toBe(1);+ // The unconditional claim carries no setWhere gate.+ expect(db.__seqCalls[0].onConflict.setWhere).toBeUndefined();+ });+});+// ── getLatestMessage / getLatestMessagesByChannelIds ──────────────────────//// These feed the invariant unification (plan #4) — every mark-read path thatdiff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.tsindex 29047537c..12b4b008e 100644--- a/src/web/src/app/api/community/agent/send/route.test.ts+++ b/src/web/src/app/api/community/agent/send/route.test.ts@@ -121,6 +121,34 @@ describe("POST /api/community/agent/send", () => {expect(mockCreateCommunityMessage).not.toHaveBeenCalled()})+ it("propagates a CAS 409 conflict from createCommunityMessage as blocked/unaligned with a freshly re-fetched latestSeq", async () => {+ // Alignment gate passes (latestSeq=9, seen=9), but another agent's send+ // wins the race between the gate and the CAS claim — by the time this+ // request's claim runs, the counter has already moved to 10.+ mockGetLatestSeqForScope.mockResolvedValueOnce(9).mockResolvedValueOnce(10)+ mockGetReadState.mockResolvedValue({ lastReadSeq: 9 })+ mockCreateCommunityMessage.mockResolvedValue({ ok: false, status: 409, error: "seq_conflict" })+ const res = await POST(+ req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ state: "blocked", reason: "unaligned", unreadCount: 1, latestSeq: 10 })+ expect(mockGetLatestSeqForScope).toHaveBeenCalledTimes(2)+ })++ it("happy path: createCommunityMessage is called with expectedSeq equal to the alignment-check's latestSeq (regression guard against drift)", async () => {+ mockGetLatestSeqForScope.mockResolvedValue(5)+ mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "hi" } })+ const res = await POST(+ req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(res.status).toBe(200)+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(+ expect.objectContaining({ expectedSeq: 5 })+ )+ })+it("an explicit seenUpToSeq overrides the bot's own tracked lastReadSeq for the alignment check", async () => {mockGetLatestSeqForScope.mockResolvedValue(10)mockGetReadState.mockResolvedValue({ lastReadSeq: 2 }) // would block if useddiff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.tsindex 93252e2d4..d3f0d4837 100644--- a/src/web/src/app/api/community/agent/send/route.ts+++ b/src/web/src/app/api/community/agent/send/route.ts@@ -81,14 +81,31 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {: { kind: "channel", channelId: channel.id, serverId: channel.serverId }}+ // `expectedSeq: latestSeq` reuses the exact snapshot the alignment gate+ // above already fetched — no new query. If another agent's `send` wins+ // the race between that snapshot and this claim, `createCommunityMessage`+ // returns a 409 and we translate it into the SAME `blocked`/`unaligned`+ // shape the gate above returns, with a freshly re-fetched `latestSeq` (the+ // stale one is now off-by-at-least-one). The daemon's existing "blocked →+ // inbox pull → retry" handling needs no changes for this (plan §4).const result = await createCommunityMessage({db,authorId: ctx.botUserId,target,body: { content: body.content.text },source: "cli",+ expectedSeq: latestSeq,})if (!result.ok) {+ if (result.status === 409) {+ const freshLatestSeq = await queries.communityAgentInbox.getLatestSeqForScope(db, scopeKey)+ return NextResponse.json({+ state: "blocked",+ reason: "unaligned",+ unreadCount: Math.max(0, freshLatestSeq - seen),+ latestSeq: freshLatestSeq,+ })+ }return NextResponse.json({ error: result.error }, { status: result.status })}diff --git a/src/web/src/components/avatar/avatar-parts.test.ts b/src/web/src/components/avatar/avatar-parts.test.tsnew file mode 100644index 000000000..9567f9fc0--- /dev/null+++ b/src/web/src/components/avatar/avatar-parts.test.ts@@ -0,0 +1,144 @@+import { describe, it, expect } from "vitest"+import type React from "react"+import { renderToStaticMarkup } from "react-dom/server"+import {+ Shapes,+ Eyes,+ Noses,+ BG_COLORS,+ SHAPE_KEYS,+ EYE_KEYS,+ NOSE_KEYS,+ PRESETS,+ randomConfig,+ configFromName,+} from "./avatar-parts"++const NEW_SHAPE_KEYS = [+ "chat", "shield", "heart", "star", "diamond", "cloud",+ "pentagon", "octagon", "bolt", "flag", "leaf", "drop",+ "triangle", "crown", "gem", "moon", "trophy", "rocket",+]+const NEW_EYE_KEYS = [+ "cat", "glasses", "heart", "star", "surprised", "sparkle",+ "square", "cross", "triangle", "target", "puppy", "angry",+]+const NEW_NOSE_KEYS = ["grin", "gasp", "zigzag", "pucker", "smirk"]++describe("Shapes", () => {+ it("includes every new shape key", () => {+ for (const key of NEW_SHAPE_KEYS) expect(SHAPE_KEYS).toContain(key)+ })++ it("every shape renders without throwing and has a valid face box", () => {+ for (const key of SHAPE_KEYS) {+ const shape = Shapes[key]!+ expect(() => shape.render()).not.toThrow()+ expect(typeof shape.face.cx).toBe("number")+ expect(typeof shape.face.cy).toBe("number")+ expect(shape.face.w).toBeGreaterThan(0)+ }+ })+})++describe("Eyes", () => {+ it("includes every new eye key", () => {+ for (const key of NEW_EYE_KEYS) expect(EYE_KEYS).toContain(key)+ })++ it("every eye renders without throwing", () => {+ for (const key of EYE_KEYS) {+ const eyeDef = Eyes[key]!+ expect(() => eyeDef.render(16, "#27272a")).not.toThrow()+ }+ })+})++describe("Noses", () => {+ it("includes every new nose key", () => {+ for (const key of NEW_NOSE_KEYS) expect(NOSE_KEYS).toContain(key)+ })++ it("every nose renders without throwing", () => {+ for (const key of NOSE_KEYS) {+ const noseDef = Noses[key]!+ expect(() => noseDef.render("#27272a")).not.toThrow()+ }+ })+})++describe("BG_COLORS", () => {+ it("has at least the 16 newly added palette entries (8 + 8 across two rounds)", () => {+ expect(BG_COLORS.length).toBeGreaterThanOrEqual(28)+ })++ it("every entry has a 3-stop gradient and a face color", () => {+ for (const c of BG_COLORS) {+ expect(c.gradient).toHaveLength(3)+ expect(typeof c.faceColor).toBe("string")+ expect(c.faceColor.length).toBeGreaterThan(0)+ }+ })+})++describe("randomConfig", () => {+ it("always returns keys/index present in the (expanded) lookup tables", () => {+ for (let i = 0; i < 50; i++) {+ const cfg = randomConfig()+ expect(SHAPE_KEYS).toContain(cfg.shape)+ expect(EYE_KEYS).toContain(cfg.eye)+ expect(NOSE_KEYS).toContain(cfg.nose)+ expect(cfg.bg).toBeGreaterThanOrEqual(0)+ expect(cfg.bg).toBeLessThan(BG_COLORS.length)+ }+ })+})++describe("configFromName", () => {+ it("is deterministic for the same name", () => {+ expect(configFromName("alook-bot")).toEqual(configFromName("alook-bot"))+ })++ it("always returns keys/index present in the (expanded) lookup tables", () => {+ for (const name of ["alice", "bob", "charlie", "delta-agent", "email-bot", "z"]) {+ const cfg = configFromName(name)+ expect(SHAPE_KEYS).toContain(cfg.shape)+ expect(EYE_KEYS).toContain(cfg.eye)+ expect(NOSE_KEYS).toContain(cfg.nose)+ expect(cfg.bg).toBeGreaterThanOrEqual(0)+ expect(cfg.bg).toBeLessThan(BG_COLORS.length)+ }+ })+})++describe("PRESETS", () => {+ it("every preset references valid shape/eye/nose keys and a valid bg index", () => {+ for (const preset of PRESETS) {+ expect(SHAPE_KEYS).toContain(preset.config.shape)+ expect(EYE_KEYS).toContain(preset.config.eye)+ expect(NOSE_KEYS).toContain(preset.config.nose)+ expect(preset.config.bg).toBeGreaterThanOrEqual(0)+ expect(preset.config.bg).toBeLessThan(BG_COLORS.length)+ }+ })++ it("includes the new presets built from the new parts", () => {+ const names = PRESETS.map((p) => p.name)+ expect(names).toEqual(+ expect.arrayContaining([+ "Chat", "Guard", "Adore", "Shine", "Energy", "Milestone", "Growth", "Flow",+ "Champion", "Royalty", "Launch", "Night", "Sharp", "Precious",+ ])+ )+ })+})++describe("star shape", () => {+ it("uses rounded (curved) corners instead of sharp straight-line points", () => {+ const markup = renderToStaticMarkup(Shapes.star!.render() as React.ReactElement)+ const d = markup.match(/d="([^"]+)"/)?.[1] ?? ""+ expect(d).toContain("Q")+ // A pure straight-edge polygon star would have no curve commands at all.+ expect(d.match(/Q/g)?.length).toBeGreaterThanOrEqual(10)+ })+})diff --git a/src/web/src/components/avatar/avatar-parts.tsx b/src/web/src/components/avatar/avatar-parts.tsxindex 085b8a726..d5091a42f 100644--- a/src/web/src/components/avatar/avatar-parts.tsx+++ b/src/web/src/components/avatar/avatar-parts.tsx@@ -11,6 +11,73 @@ const DEFAULT_FACE_COLOR = "#27272a";const shapeStyle = { fill: SHAPE_FILL, stroke: SHAPE_STROKE, strokeWidth: SHAPE_SW };+// ─────────────────────────────────────────────────────────────+// GEOMETRY HELPERS — build rounded-corner polygon paths (used for+// star/pentagon/octagon/bolt so every vertex reads as soft, not spiky)+// ─────────────────────────────────────────────────────────────+type Point = [number, number];++function pointDist(a: Point, b: Point): number {+ return Math.hypot(b[0] - a[0], b[1] - a[1]);+}++function lerpTowards(from: Point, to: Point, distance: number): Point {+ const d = pointDist(from, to);+ if (d === 0) return from;+ const t = Math.min(distance, d) / d;+ return [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t];+}++function fmtPoint([x, y]: Point): string {+ return `${x.toFixed(1)} ${y.toFixed(1)}`;+}++function roundedPolygonPath(pts: Point[], radius: number | ((i: number) => number)): string {+ const n = pts.length;+ const d: string[] = [];+ for (let i = 0; i < n; i++) {+ const prev = pts[(i - 1 + n) % n]!;+ const curr = pts[i]!;+ const next = pts[(i + 1) % n]!;+ const r = typeof radius === "function" ? radius(i) : radius;+ const pa = lerpTowards(curr, prev, r);+ const pb = lerpTowards(curr, next, r);+ d.push(i === 0 ? `M${fmtPoint(pa)}` : `L${fmtPoint(pa)}`);+ d.push(`Q${fmtPoint(curr)} ${fmtPoint(pb)}`);+ }+ d.push("Z");+ return d.join(" ");+}++function polygonPoints(cx: number, cy: number, radii: number[], startDeg: number): Point[] {+ const step = 360 / radii.length;+ return radii.map((r, i) => {+ const a = ((startDeg + i * step) * Math.PI) / 180;+ return [cx + r * Math.cos(a), cy + r * Math.sin(a)];+ });+}++const STAR_PATH = roundedPolygonPath(+ polygonPoints(100, 100, [74, 36, 74, 36, 74, 36, 74, 36, 74, 36], -90),+ (i) => (i % 2 === 0 ? 15 : 9)+);+const PENTAGON_PATH = roundedPolygonPath(polygonPoints(100, 104, [74, 74, 74, 74, 74], -90), 16);+const OCTAGON_PATH = roundedPolygonPath(polygonPoints(100, 100, new Array(8).fill(72), -67.5), 14);+const BOLT_PATH = roundedPolygonPath(+ [[112, 28], [66, 104], [96, 104], [82, 174], [140, 92], [108, 92]],+ 7+);+const TRIANGLE_PATH = roundedPolygonPath(polygonPoints(100, 110, [80, 80, 80], -90), 20);+const CROWN_PATH = roundedPolygonPath(+ [[40, 130], [54, 60], [74, 100], [100, 40], [126, 100], [146, 60], [160, 130], [160, 172], [40, 172]],+ (i) => (i === 7 || i === 8 ? 12 : 7)+);+const GEM_PATH = roundedPolygonPath(+ [[58, 66], [86, 38], [114, 38], [142, 66], [100, 172]],+ 9+);+const MOON_PATH = "M163.8 105.6 A63.75 63.75 0 1 1 94.4 36.3 A49.6 49.6 0 0 0 163.8 105.6 Z";+// ─────────────────────────────────────────────────────────────// PALETTES// ─────────────────────────────────────────────────────────────@@ -22,18 +89,34 @@ export interface ColorOption {}export const BG_COLORS: ColorOption[] = [- { name: "Purple", value: "#a855f7", gradient: ["#c084fc", "#a855f7", "#7c3aed"], faceColor: "#2e1065" },- { name: "Teal", value: "#14b8a6", gradient: ["#5eead4", "#14b8a6", "#0d9488"], faceColor: "#134e4a" },- { name: "Orange", value: "#f97316", gradient: ["#fdba74", "#f97316", "#c2410c"], faceColor: "#7c2d12" },- { name: "Blue", value: "#3b82f6", gradient: ["#93c5fd", "#3b82f6", "#1d4ed8"], faceColor: "#1e3a5f" },- { name: "Pink", value: "#f472b6", gradient: ["#fda4af", "#f472b6", "#be185d"], faceColor: "#831843" },- { name: "Yellow", value: "#eab308", gradient: ["#fde047", "#eab308", "#a16207"], faceColor: "#713f12" },- { name: "Green", value: "#22c55e", gradient: ["#86efac", "#22c55e", "#15803d"], faceColor: "#14532d" },- { name: "Beige", value: "#d6ccb8", gradient: ["#e8e0d4", "#d6ccb8", "#b8a990"], faceColor: "#57534e" },- { name: "Red", value: "#ef4444", gradient: ["#fca5a5", "#ef4444", "#991b1b"], faceColor: "#7f1d1d" },- { name: "Lake Blue", value: "#6366f1", gradient: ["#a5b4fc", "#6366f1", "#3730a3"], faceColor: "#312e81" },- { name: "Gray", value: "#9ca3af", gradient: ["#d4d4d8", "#9ca3af", "#6b7280"], faceColor: "#374151" },+ { name: "Purple", value: "#a855f7", gradient: ["#c084fc", "#a855f7", "#7c3aed"], faceColor: "#2e1065" },+ { name: "Teal", value: "#14b8a6", gradient: ["#5eead4", "#14b8a6", "#0d9488"], faceColor: "#134e4a" },+ { name: "Orange", value: "#f97316", gradient: ["#fdba74", "#f97316", "#c2410c"], faceColor: "#7c2d12" },+ { name: "Blue", value: "#3b82f6", gradient: ["#93c5fd", "#3b82f6", "#1d4ed8"], faceColor: "#1e3a5f" },+ { name: "Pink", value: "#f472b6", gradient: ["#fda4af", "#f472b6", "#be185d"], faceColor: "#831843" },+ { name: "Yellow", value: "#eab308", gradient: ["#fde047", "#eab308", "#a16207"], faceColor: "#713f12" },+ { name: "Green", value: "#22c55e", gradient: ["#86efac", "#22c55e", "#15803d"], faceColor: "#14532d" },+ { name: "Beige", value: "#d6ccb8", gradient: ["#e8e0d4", "#d6ccb8", "#b8a990"], faceColor: "#57534e" },+ { name: "Red", value: "#ef4444", gradient: ["#fca5a5", "#ef4444", "#991b1b"], faceColor: "#7f1d1d" },+ { name: "Lake Blue", value: "#6366f1", gradient: ["#a5b4fc", "#6366f1", "#3730a3"], faceColor: "#312e81" },+ { name: "Gray", value: "#9ca3af", gradient: ["#d4d4d8", "#9ca3af", "#6b7280"], faceColor: "#374151" },{ name: "Deep Purple", value: "#8b5cf6", gradient: ["#c4b5fd", "#8b5cf6", "#5b21b6"], faceColor: "#3b0764" },+ { name: "Coral", value: "#fb7185", gradient: ["#fecdd3", "#fb7185", "#be123c"], faceColor: "#881337" },+ { name: "Mint", value: "#2dd4bf", gradient: ["#99f6e4", "#2dd4bf", "#0f766e"], faceColor: "#134e4a" },+ { name: "Indigo", value: "#4f46e5", gradient: ["#a5b4fc", "#4f46e5", "#3730a3"], faceColor: "#1e1b4b" },+ { name: "Rose", value: "#e11d48", gradient: ["#fda4af", "#e11d48", "#881337"], faceColor: "#4c0519" },+ { name: "Amber", value: "#f59e0b", gradient: ["#fcd34d", "#f59e0b", "#b45309"], faceColor: "#78350f" },+ { name: "Cyan", value: "#06b6d4", gradient: ["#67e8f9", "#06b6d4", "#0e7490"], faceColor: "#164e63" },+ { name: "Slate", value: "#64748b", gradient: ["#cbd5e1", "#64748b", "#334155"], faceColor: "#1e293b" },+ { name: "Lime", value: "#84cc16", gradient: ["#d9f99d", "#84cc16", "#4d7c0f"], faceColor: "#365314" },+ { name: "Sky", value: "#0ea5e9", gradient: ["#7dd3fc", "#0ea5e9", "#0369a1"], faceColor: "#0c4a6e" },+ { name: "Fuchsia", value: "#d946ef", gradient: ["#f0abfc", "#d946ef", "#a21caf"], faceColor: "#4a044e" },+ { name: "Emerald", value: "#059669", gradient: ["#6ee7b7", "#059669", "#047857"], faceColor: "#022c22" },+ { name: "Sand", value: "#d4a373", gradient: ["#f0dcc4", "#d4a373", "#a67c52"], faceColor: "#4a2e17" },+ { name: "Copper", value: "#c2703d", gradient: ["#e8b088", "#c2703d", "#8a4a1f"], faceColor: "#431f0a" },+ { name: "Charcoal", value: "#52525b", gradient: ["#a1a1aa", "#52525b", "#27272a"], faceColor: "#18181b" },+ { name: "Denim", value: "#4a7ba6", gradient: ["#93b8d4", "#4a7ba6", "#2c5170"], faceColor: "#16283a" },+ { name: "Plum", value: "#8e4585", gradient: ["#d8a8d1", "#8e4585", "#5c2a55"], faceColor: "#2e1330" },];// ─────────────────────────────────────────────────────────────@@ -106,6 +189,120 @@ export const Shapes: Record<string, ShapeDef> = {<path d="M92 36 C120 32 156 48 164 78 C172 108 156 148 124 160 C92 172 48 156 38 124 C28 92 62 40 92 36 Z" {...shapeStyle} />),},+ chat: {+ name: "Chat",+ face: { cx: 100, cy: 86, w: 76 },+ render: () => (+ <path d="M54 34 L146 34 C162 34 174 46 174 62 L174 118 C174 134 162 146 146 146 L90 146 L58 176 L54 146 C38 146 26 134 26 118 L26 62 C26 46 38 34 54 34 Z" {...shapeStyle} />+ ),+ },+ shield: {+ name: "Shield",+ face: { cx: 100, cy: 94, w: 74 },+ render: () => (+ <path d="M100 30 L156 50 C160 52 162 56 162 60 L162 96 C162 132 136 158 100 172 C64 158 38 132 38 96 L38 60 C38 56 40 52 44 50 Z" {...shapeStyle} />+ ),+ },+ heart: {+ name: "Heart",+ face: { cx: 100, cy: 92, w: 78 },+ render: () => (+ <path d="M100 168 C40 128 24 92 34 66 C44 40 78 34 100 62 C122 34 156 40 166 66 C176 92 160 128 100 168 Z" {...shapeStyle} />+ ),+ },+ star: {+ name: "Star",+ face: { cx: 100, cy: 100, w: 60 },+ render: () => <path d={STAR_PATH} {...shapeStyle} />,+ },+ diamond: {+ name: "Diamond",+ face: { cx: 100, cy: 103, w: 78 },+ render: () => (+ <path d="M100 26 C106 26 111 29 115 34 L168 92 C174 98 174 108 168 114 L115 172 C111 177 106 180 100 180 C94 180 89 177 85 172 L32 114 C26 108 26 98 32 92 L85 34 C89 29 94 26 100 26 Z" {...shapeStyle} />+ ),+ },+ cloud: {+ name: "Cloud",+ face: { cx: 100, cy: 106, w: 80 },+ render: () => (+ <path d="M60 140 C42 140 30 126 30 110 C30 96 40 84 54 82 C58 62 76 48 98 48 C118 48 134 60 140 78 C158 78 172 92 172 110 C172 126 160 138 144 140 Z" {...shapeStyle} />+ ),+ },+ pentagon: {+ name: "Pentagon",+ face: { cx: 100, cy: 106, w: 76 },+ render: () => <path d={PENTAGON_PATH} {...shapeStyle} />,+ },+ octagon: {+ name: "Octagon",+ face: { cx: 100, cy: 100, w: 82 },+ render: () => <path d={OCTAGON_PATH} {...shapeStyle} />,+ },+ bolt: {+ name: "Bolt",+ face: { cx: 103, cy: 90, w: 66 },+ render: () => <path d={BOLT_PATH} {...shapeStyle} />,+ },+ flag: {+ name: "Flag",+ face: { cx: 100, cy: 84, w: 76 },+ render: () => (+ <path d="M62 30 L138 30 C146 30 152 36 152 44 L152 150 L100 122 L48 150 L48 44 C48 36 54 30 62 30 Z" {...shapeStyle} />+ ),+ },+ leaf: {+ name: "Leaf",+ face: { cx: 103, cy: 102, w: 76 },+ render: () => (+ <path d="M100 26 C136 44 162 74 162 108 C162 144 132 172 104 176 C98 177 92 174 92 168 C68 160 48 136 44 108 C40 74 64 44 100 26 Z" {...shapeStyle} />+ ),+ },+ drop: {+ name: "Drop",+ face: { cx: 100, cy: 122, w: 74 },+ render: () => (+ <path d="M100 28 C130 66 152 96 152 124 C152 152 128 172 100 172 C72 172 48 152 48 124 C48 96 70 66 100 28 Z" {...shapeStyle} />+ ),+ },+ triangle: {+ name: "Triangle",+ face: { cx: 100, cy: 122, w: 64 },+ render: () => <path d={TRIANGLE_PATH} {...shapeStyle} />,+ },+ crown: {+ name: "Crown",+ face: { cx: 100, cy: 150, w: 72 },+ render: () => <path d={CROWN_PATH} {...shapeStyle} />,+ },+ gem: {+ name: "Gem",+ face: { cx: 100, cy: 86, w: 64 },+ render: () => <path d={GEM_PATH} {...shapeStyle} />,+ },+ moon: {+ name: "Moon",+ face: { cx: 86, cy: 82, w: 40 },+ render: () => <path d={MOON_PATH} {...shapeStyle} />,+ },+ trophy: {+ name: "Trophy",+ face: { cx: 100, cy: 72, w: 76 },+ render: () => (+ <path d="M54 34 L146 34 C146 34 150 34 150 40 C150 78 130 104 108 110 L108 128 L134 128 C140 128 144 132 144 138 L144 158 C144 164 140 168 134 168 L66 168 C60 168 56 164 56 158 L56 138 C56 132 60 128 66 128 L92 128 L92 110 C70 104 50 78 50 40 C50 34 54 34 54 34 Z" {...shapeStyle} />+ ),+ },+ rocket: {+ name: "Rocket",+ face: { cx: 100, cy: 88, w: 54 },+ render: () => (+ <g>+ <path d="M100 30 C118 30 132 62 132 96 C132 108 128 118 124 126 L124 150 L76 150 L76 126 C72 118 68 108 68 96 C68 62 82 30 100 30 Z" {...shapeStyle} />+ <path d="M68 118 C50 118 40 140 44 158 C52 148 62 140 74 138 Z" {...shapeStyle} />+ <path d="M132 118 C150 118 160 140 156 158 C148 148 138 140 126 138 Z" {...shapeStyle} />+ </g>+ ),+ },};export const SHAPE_KEYS = Object.keys(Shapes);@@ -152,6 +349,35 @@ export const Noses: Record<string, NoseDef> = {name: "o",render: (c = DEFAULT_FACE_COLOR) => <ellipse cx="0" cy="0" rx="7" ry="7.5" fill="none" stroke={c} strokeWidth="4.5" />,},+ grin: {+ name: "Grin",+ render: (c = DEFAULT_FACE_COLOR) => (+ <g>+ <path d="M-11 0 Q0 10 11 0" fill="none" stroke={c} strokeWidth="5" strokeLinecap="round" />+ <line x1="-7" y1="4" x2="7" y2="4" stroke={c} strokeWidth="3" strokeLinecap="round" />+ </g>+ ),+ },+ gasp: {+ name: "Gasp",+ render: (c = DEFAULT_FACE_COLOR) => <rect x="-6" y="-2" width="12" height="13" rx="6" fill={c} />,+ },+ zigzag: {+ name: "Zigzag",+ render: (c = DEFAULT_FACE_COLOR) => (+ <path d="M-11 0 L-5 4 L1 -3 L7 4 L11 0" fill="none" stroke={c} strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round" />+ ),+ },+ pucker: {+ name: "Pucker",+ render: (c = DEFAULT_FACE_COLOR) => <path d="M-3 -5 Q4 -5 4 0 Q4 5 -3 5 Q2 0 -3 -5 Z" fill={c} />,+ },+ smirk: {+ name: "Smirk",+ render: (c = DEFAULT_FACE_COLOR) => (+ <path d="M-9 2 Q-2 2 3 -5 L11 -5" fill="none" stroke={c} strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round" />+ ),+ },};export const NOSE_KEYS = Object.keys(Noses);@@ -223,6 +449,110 @@ export const Eyes: Record<string, EyeDef> = {</g>),},+ cat: {+ name: "Cat",+ render: (dx: number, c = DEFAULT_FACE_COLOR) => (+ <g>+ <g transform={`translate(${-dx}, 0)`}>+ <path d="M-11 2 C-11 -6 -2 -10 7 -6 C12 -3 10 4 4 6 C-3 9 -11 8 -11 2 Z" fill={c} />+ </g>+ <g transform={`translate(${dx}, 0) scale(-1, 1)`}>+ <path d="M-11 2 C-11 -6 -2 -10 7 -6 C12 -3 10 4 4 6 C-3 9 -11 8 -11 2 Z" fill={c} />+ </g>+ </g>+ ),+ },+ glasses: {+ name: "Glasses",+ render: (dx: number, c = DEFAULT_FACE_COLOR) => (+ <g>+ <line x1={-dx + 9} y1="0" x2={dx - 9} y2="0" stroke={c} strokeWidth="3.5" />+ <g transform={`translate(${-dx}, 0)`}><circle cx="0" cy="0" r="9" fill="none" stroke={c} strokeWidth="4.5" /></g>+ <g transform={`translate(${dx}, 0)`}><circle cx="0" cy="0" r="9" fill="none" stroke={c} strokeWidth="4.5" /></g>+ </g>+ ),+ },+ heart: {+ name: "Heart",+ render: eye(() => (+ <path+ d="M0 5 C-6 0 -10 -4 -6 -8 C-3 -10 0 -8 0 -6 C0 -8 3 -10 6 -8 C10 -4 6 0 0 5 Z"+ fill="#f472b6"+ />+ )),+ },+ star: {+ name: "Star",+ render: eye((c) => (+ <path d="M0 -9 C1 -3 3 -1 9 0 C3 1 1 3 0 9 C-1 3 -3 1 -9 0 C-3 -1 -1 -3 0 -9 Z" fill={c} />+ )),+ },+ surprised: {+ name: "Surprised",+ render: eye((c) => (+ <g>+ <circle cx="0" cy="0" r="11" fill="none" stroke={c} strokeWidth="4" />+ <circle cx="0" cy="0" r="4" fill={c} />+ </g>+ )),+ },+ sparkle: {+ name: "Sparkle",+ render: eye((c) => (+ <g>+ <circle cx="0" cy="0" r="9" fill={c} />+ <path+ d="M3 -7 C3.5 -4 4 -3.5 7 -3 C4 -2.5 3.5 -2 3 1 C2.5 -2 2 -2.5 -1 -3 C2 -3.5 2.5 -4 3 -7 Z"+ fill="rgba(255,255,255,0.9)"+ />+ </g>+ )),+ },+ square: {+ name: "Square",+ render: eye((c) => <rect x="-7" y="-7" width="14" height="14" rx="4" fill={c} />),+ },+ cross: {+ name: "Cross",+ render: eye((c) => (+ <g>+ <line x1="-7" y1="-7" x2="7" y2="7" stroke={c} strokeWidth="4" strokeLinecap="round" />+ <line x1="-7" y1="7" x2="7" y2="-7" stroke={c} strokeWidth="4" strokeLinecap="round" />+ </g>+ )),+ },+ triangle: {+ name: "Triangle",+ render: eye((c) => <path d="M0 -9 Q2 -9 3 -7 L8 6 Q9 8 7 8 L-7 8 Q-9 8 -8 6 L-3 -7 Q-2 -9 0 -9 Z" fill={c} />),+ },+ target: {+ name: "Target",+ render: eye((c) => (+ <g>+ <circle cx="0" cy="0" r="9" fill="none" stroke={c} strokeWidth="2.5" />+ <circle cx="0" cy="0" r="4" fill="none" stroke={c} strokeWidth="2.5" />+ </g>+ )),+ },+ puppy: {+ name: "Puppy",+ render: eye((c) => (+ <g>+ <ellipse cx="0" cy="1" rx="9" ry="10" fill={c} />+ <circle cx="-3" cy="-4" r="3" fill="rgba(255,255,255,0.9)" />+ <circle cx="3.5" cy="1" r="1.8" fill="rgba(255,255,255,0.7)" />+ </g>+ )),+ },+ angry: {+ name: "Angry",+ render: (dx: number, c = DEFAULT_FACE_COLOR) => (+ <g>+ <g transform={`translate(${-dx}, 0)`}><path d="M-8 -6 L8 2" stroke={c} strokeWidth="5" strokeLinecap="round" /></g>+ <g transform={`translate(${dx}, 0) scale(-1, 1)`}><path d="M-8 -6 L8 2" stroke={c} strokeWidth="5" strokeLinecap="round" /></g>+ </g>+ ),+ },};export const EYE_KEYS = Object.keys(Eyes);@@ -253,18 +583,32 @@ export interface Preset {}export const PRESETS: Preset[] = [- { name: "Task", config: { shape: "task", nose: "dot", eye: "dots", bg: 0 } },- { name: "Notes", config: { shape: "book", nose: "dash", eye: "happy", bg: 1 } },- { name: "Mail", config: { shape: "mail", nose: "smile", eye: "dots", bg: 3 } },- { name: "Schedule", config: { shape: "calendar", nose: "dot", eye: "dots", bg: 4 } },- { name: "Idea", config: { shape: "bulb", nose: "oh", eye: "rings", bg: 5 } },- { name: "Project", config: { shape: "folder", nose: "dash", eye: "lines", bg: 7 } },- { name: "Goal", config: { shape: "mountain", nose: "caret", eye: "arches", bg: 8 } },- { name: "Dream", config: { shape: "circle", nose: "smile", eye: "shy", bg: 11 } },- { name: "Organize", config: { shape: "rounded", nose: "dot", eye: "sleepy", bg: 6 } },- { name: "Explore", config: { shape: "hexagon", nose: "hookL", eye: "wink", bg: 9 } },- { name: "Focus", config: { shape: "task", nose: "caret", eye: "lines", bg: 2 } },- { name: "Collect", config: { shape: "book", nose: "oh", eye: "rings", bg: 10 } },+ { name: "Task", config: { shape: "task", nose: "dot", eye: "dots", bg: 0 } },+ { name: "Notes", config: { shape: "book", nose: "dash", eye: "happy", bg: 1 } },+ { name: "Mail", config: { shape: "mail", nose: "smile", eye: "dots", bg: 3 } },+ { name: "Schedule", config: { shape: "calendar", nose: "dot", eye: "dots", bg: 4 } },+ { name: "Idea", config: { shape: "bulb", nose: "oh", eye: "rings", bg: 5 } },+ { name: "Project", config: { shape: "folder", nose: "dash", eye: "lines", bg: 7 } },+ { name: "Goal", config: { shape: "mountain", nose: "caret", eye: "arches", bg: 8 } },+ { name: "Dream", config: { shape: "circle", nose: "smile", eye: "shy", bg: 11 } },+ { name: "Organize", config: { shape: "rounded", nose: "dot", eye: "sleepy", bg: 6 } },+ { name: "Explore", config: { shape: "hexagon", nose: "hookL", eye: "wink", bg: 9 } },+ { name: "Focus", config: { shape: "task", nose: "caret", eye: "lines", bg: 2 } },+ { name: "Collect", config: { shape: "book", nose: "oh", eye: "rings", bg: 10 } },+ { name: "Chat", config: { shape: "chat", nose: "grin", eye: "surprised", bg: 12 } },+ { name: "Guard", config: { shape: "shield", nose: "smirk", eye: "glasses", bg: 18 } },+ { name: "Adore", config: { shape: "heart", nose: "pucker", eye: "heart", bg: 15 } },+ { name: "Shine", config: { shape: "star", nose: "gasp", eye: "sparkle", bg: 16 } },+ { name: "Energy", config: { shape: "bolt", nose: "zigzag", eye: "big", bg: 5 } },+ { name: "Milestone", config: { shape: "flag", nose: "smile", eye: "happy", bg: 26 } },+ { name: "Growth", config: { shape: "leaf", nose: "dot", eye: "sleepy", bg: 22 } },+ { name: "Flow", config: { shape: "drop", nose: "oh", eye: "shy", bg: 20 } },+ { name: "Champion", config: { shape: "trophy", nose: "grin", eye: "puppy", bg: 16 } },+ { name: "Royalty", config: { shape: "crown", nose: "smirk", eye: "target", bg: 21 } },+ { name: "Launch", config: { shape: "rocket", nose: "gasp", eye: "cross", bg: 8 } },+ { name: "Night", config: { shape: "moon", nose: "dash", eye: "square", bg: 14 } },+ { name: "Sharp", config: { shape: "triangle", nose: "zigzag", eye: "angry", bg: 25 } },+ { name: "Precious", config: { shape: "gem", nose: "oh", eye: "sparkle", bg: 17 } },];// ─────────────────────────────────────────────────────────────diff --git a/src/web/src/lib/community/audit.test.ts b/src/web/src/lib/community/audit.test.tsindex 3642854fd..f3cab994c 100644--- a/src/web/src/lib/community/audit.test.ts+++ b/src/web/src/lib/community/audit.test.ts@@ -30,7 +30,7 @@ describe("logAudit", () => {it("returns void immediately without awaiting the write", () => {// Never resolves — asserts logAudit does not await.- mockLogAction.mockReturnValue(new Promise(() => {}))+ mockLogAction.mockReturnValue(new Promise(() => { }))const result = logAudit({} as never, {serverId: "s1",actorId: "u1",@@ -56,6 +56,7 @@ describe("logAudit", () => {expect(mockWarn).toHaveBeenCalledTimes(1)expect(mockWarn).toHaveBeenCalledWith("audit_write_failed", {err: expect.stringContaining("db offline"),+ cause: "db offline",action: "member_kick",serverId: "s1",targetType: "member",@@ -63,6 +64,33 @@ describe("logAudit", () => {})})+ it("surfaces the wrapped driver error via .cause (DrizzleQueryError shape)", async () => {+ // Mirrors drizzle-orm 0.44+: String(err) on the outer error only shows+ // "Failed query: ...", hiding the real SQLite failure on .cause.+ const outer = new Error("Failed query: insert into community_audit_log ...")+ ; (outer as Error & { cause?: unknown }).cause = new Error(+ "NOT NULL constraint failed: community_audit_log.server_id"+ )+ mockLogAction.mockRejectedValue(outer)+ logAudit({} as never, {+ serverId: null,+ actorId: "u1",+ action: "message_authored_as_bot",+ targetType: "message",+ targetId: "m1",+ })+ await new Promise((r) => setTimeout(r, 0))++ expect(mockWarn).toHaveBeenCalledWith("audit_write_failed", {+ err: expect.stringContaining("Failed query"),+ cause: "Failed query: insert into community_audit_log ... <- NOT NULL constraint failed: community_audit_log.server_id",+ action: "message_authored_as_bot",+ serverId: null,+ targetType: "message",+ targetId: "m1",+ })+ })+it("does not log warn on success", async () => {mockLogAction.mockResolvedValue(undefined)logAudit({} as never, {diff --git a/src/web/src/lib/community/audit.ts b/src/web/src/lib/community/audit.tsindex 4c602f835..a9ffb9bac 100644--- a/src/web/src/lib/community/audit.ts+++ b/src/web/src/lib/community/audit.ts@@ -38,10 +38,33 @@ type AuditAction = {changes?: string}+/**+ * `String(err)` on a `DrizzleQueryError` only prints "Failed query: ...+ * params: ..." — the actual driver failure (e.g. a NOT NULL/FOREIGN KEY/+ * UNIQUE constraint message) lives on `.cause` (drizzle-orm 0.44+) and was+ * getting silently dropped from `audit_write_failed` logs, making every+ * past occurrence undiagnosable. Walk the chain so it's captured.+ */+function causeChain(err: unknown): string[] {+ const messages: string[] = []+ let current: unknown = err+ for (let depth = 0; current && depth < 5; depth++) {+ if (current instanceof Error) {+ messages.push(current.message)+ current = (current as Error & { cause?: unknown }).cause+ } else {+ messages.push(String(current))+ break+ }+ }+ return messages+}+export function logAudit(db: Database, action: AuditAction): void {queries.communityAuditLog.logAction(db, action).catch((err) => {log.warn("audit_write_failed", {err: String(err),+ cause: causeChain(err).join(" <- "),action: action.action,serverId: action.serverId,targetType: action.targetType,diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 8e7900d6a..cacb310f4 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -180,6 +180,73 @@ describe("createCommunityMessage — audit relocation (plan §10)", () => {})})+describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-condition.md)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFanOutToChannel.mockResolvedValue(undefined)+ mockFanOutToDM.mockResolvedValue(undefined)+ mockBroadcastToUser.mockResolvedValue(undefined)+ })++ it("expectedSeq mismatch (createMessage returns null) → { ok: false, status: 409, error: 'seq_conflict' }, no side effects", async () => {+ mockCreateMessage.mockResolvedValue(null)++ const result = await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hello" },+ source: "cli",+ expectedSeq: 19,+ })++ expect(result).toEqual({ ok: false, status: 409, error: "seq_conflict" })+ // Lost the race — none of the downstream pipeline steps should fire.+ expect(mockGetMessage).not.toHaveBeenCalled()+ expect(mockCreateAttachment).not.toHaveBeenCalled()+ expect(mockCreateMentions).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ expect(mockFanOutToDM).not.toHaveBeenCalled()+ expect(mockLogAudit).not.toHaveBeenCalled()+ })++ it("passes expectedSeq through to createMessage when provided", async () => {+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })+ mockGetMessage.mockResolvedValue(messageRow())+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })++ await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hello" },+ source: "cli",+ expectedSeq: 19,+ })++ expect(mockCreateMessage).toHaveBeenCalledWith(+ {},+ expect.objectContaining({ expectedSeq: 19 }),+ )+ })++ it("omits expectedSeq entirely from the createMessage call when not provided (regression — web/human sends unaffected)", async () => {+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })+ mockGetMessage.mockResolvedValue(messageRow())+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })++ await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hello" },+ })++ const callArgs = mockCreateMessage.mock.calls[0]![1]+ expect("expectedSeq" in callArgs).toBe(false)+ })+})+describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {beforeEach(() => {vi.clearAllMocks()diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 9a788b760..e98cf5d7b 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -51,7 +51,7 @@ type FullMessageRow = NonNullable<type CreateMessageError = {ok: false- status: 400+ status: 400 | 409error: string}@@ -80,8 +80,16 @@ export async function createCommunityMessage(params: {body: IncomingMessageBody/** Provenance tag threaded into the bot-authored audit row's `changes` (plan §10). */source?: "cli" | "daemon-http" | "web"+ /**+ * CAS guard for the agent-send race fix+ * (plans/fix-agent-send-race-condition.md). Only the agent `send` route+ * passes this — it's the `latestSeq` snapshot that route's own alignment+ * check already computed. Omitted by every other caller (web/human sends,+ * thread posts), which keep the unconditional, always-succeeds claim.+ */+ expectedSeq?: number}): Promise<CreateMessageResult> {- const { db, authorId, target, body, source } = params+ const { db, authorId, target, body, source, expectedSeq } = paramsconst content = typeof body.content === "string" ? body.content : ""if (content.length > MAX_MESSAGE_CONTENT_LENGTH) {@@ -120,14 +128,29 @@ export async function createCommunityMessage(params: {? body.mentionType: undefined- const created = await queries.communityMessage.createMessage(db, {+ const baseMessageData = {authorId,content,channelId: target.kind === "dm" ? undefined : target.channelId,dmConversationId: target.kind === "dm" ? target.dmId : undefined,replyToId,mentionType,- })+ }+ // `createMessage`'s overloads key off whether the `expectedSeq` property+ // is present at all, not just its runtime value — a `number | undefined`+ // typed property doesn't cleanly resolve against either overload, so the+ // pass-through branches explicitly instead of spreading `expectedSeq` in.+ const created =+ expectedSeq !== undefined+ ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })+ : await queries.communityMessage.createMessage(db, baseMessageData)++ // Lost the CAS race (plans/fix-agent-send-race-condition.md) — zero rows+ // were written anywhere (no message, no channel/DM bump, no read-state+ // watermark). Return immediately, before attachments/mentions/fan-out/audit.+ if (created === null) {+ return { ok: false, status: 409, error: "seq_conflict" }+ }const attachments: CreatedAttachment[] = incomingAttachments?.length? await Promise.all(