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
feat(community): bot activity audit log — cli_invocation + tool_call + thinking
Gusa18df9988724
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex 6e9662254..1cab596f8 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -212,6 +212,46 @@ describe("startCredentialProxy (zero-trust end to end)", () => {expect(r.status).toBe(401);});+ it("fires onProxyRequest ONCE on verdict.ok, with (agentId, method, pathname), before upstream is dispatched", async () => {+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ const sightings: Array<{ agentId: string; method: string; pathname: string }> = [];+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ proxy = await startCredentialProxy(broker, {+ onProxyRequest: (agentId, method, pathname) => sightings.push({ agentId, method, pathname }),+ });+ const reg = broker.mint("agent-1", "l", ["send"], REAL_KEY);++ const r = await post(proxy.url, reg.voucher, "/api/send");+ expect(r.status).toBe(200);+ expect(sightings).toEqual([{ agentId: "agent-1", method: "POST", pathname: "/api/send" }]);+ });++ it("does NOT fire onProxyRequest on a rejected voucher (401/403)", async () => {+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ const sightings: Array<{ agentId: string }> = [];+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ proxy = await startCredentialProxy(broker, {+ onProxyRequest: (agentId, _method, _pathname) => sightings.push({ agentId }),+ });++ // Missing voucher entirely → 401.+ const bad = await fetch(`${proxy.url}/api/send`, { method: "POST" });+ expect(bad.status).toBe(401);++ // Invalid voucher → 401.+ const bogus = await post(proxy.url, "vch_bogus", "/api/send");+ expect(bogus.status).toBe(401);++ // Capability denied → 403 (still not fired).+ const scoped = broker.mint("agent-1", "l", ["read"], REAL_KEY);+ const denied = await post(proxy.url, scoped.voucher, "/api/send");+ expect(denied.status).toBe(403);++ expect(sightings).toEqual([]);+ });+it("surfaces the buffered inboxPull response AND fires onInboxPullResponse", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex 87236a42f..806227332 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -257,6 +257,16 @@ export interface CredentialProxyOptions {* regardless of whether the agent is an in-process stub or a real subprocess.*/onInboxPullResponse?: (agentId: string, messages: Message[]) => void;+ /**+ * Called once per successfully-authorized upstream proxy request, BEFORE the+ * upstream is dispatched. Fires only on `verdict.ok === true` — never on+ * failed/expired-voucher attempts (those short-circuit with a 401/403 and+ * MUST NOT be surfaced as bot activity). Purely observational: the daemon+ * uses this to emit a `cli_invocation` bot audit event derived from the+ * pathname. Host-neutral by design — no bodies, no upstream response+ * details.+ */+ onProxyRequest?: (agentId: string, method: string, pathname: string) => 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@@ -292,6 +302,7 @@ export async function startCredentialProxy(const upstreamClient = upstream.protocol === "https:" ? https : http;const onPull = options.onInboxPullResponse;+ const onProxyRequest = options.onProxyRequest;const server = http.createServer((req, res) => {const pathname = new URL(req.url ?? "/", "http://placeholder").pathname;@@ -309,6 +320,14 @@ export async function startCredentialProxy(const reg = verdict.reg;const isInboxPull = onPull && pathname.endsWith("/inboxPull");+ if (onProxyRequest) {+ try {+ onProxyRequest(reg.agentId, req.method ?? "GET", pathname);+ } catch {+ // observational callback — never disrupt the proxy.+ }+ }+// Build the upstream request: same method/path, this voucher's per-agent// runner key swapped in, identity + capability headers stamped, hop-specific// headers stripped.diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex fcd6cd860..1c89b2589 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, vi, afterEach } from "vitest";import { EventEmitter } from "events";-import { createDaemon } from "./createDaemon";+import { createDaemon, deriveAuditLogSubcommand } from "./createDaemon";import type { Driver } from "../types";import type { Logger } from "../logger";@@ -424,3 +424,80 @@ describe("createDaemon — logging", () => {await daemon.stop();});});++describe("deriveAuditLogSubcommand", () => {+ it("maps the CLI's bare /api/* pathnames to their subcommand suffix", () => {+ expect(deriveAuditLogSubcommand("/api/send")).toBe("send");+ expect(deriveAuditLogSubcommand("/api/read")).toBe("read");+ expect(deriveAuditLogSubcommand("/api/inboxPull")).toBe("inboxPull");+ expect(deriveAuditLogSubcommand("/api/inboxSnapshot")).toBe("inboxSnapshot");+ expect(deriveAuditLogSubcommand("/api/listChannels")).toBe("listChannels");+ expect(deriveAuditLogSubcommand("/api/listServers")).toBe("listServers");+ expect(deriveAuditLogSubcommand("/api/listMembers")).toBe("listMembers");+ expect(deriveAuditLogSubcommand("/api/joinServer")).toBe("joinServer");+ expect(deriveAuditLogSubcommand("/api/resolve")).toBe("resolve");+ });++ it("maps the rewritten /api/community/agent/* pathnames identically", () => {+ // The proxy's rewriteAgentPath fires AFTER onProxyRequest, so the sighting+ // may carry either shape depending on how the CLI called in. Both must+ // derive to the same subcommand string.+ expect(deriveAuditLogSubcommand("/api/community/agent/send")).toBe("send");+ expect(deriveAuditLogSubcommand("/api/community/agent/inboxPull")).toBe("inboxPull");+ });++ it("returns null for `ack` (dropped — paired with inboxPull, no user intent)", () => {+ expect(deriveAuditLogSubcommand("/api/ack")).toBe(null);+ expect(deriveAuditLogSubcommand("/api/community/agent/ack")).toBe(null);+ });++ it("returns null for non-/api pathnames", () => {+ expect(deriveAuditLogSubcommand("/health")).toBe(null);+ expect(deriveAuditLogSubcommand("/")).toBe(null);+ });+});++describe("AgentProcessManager.auditContext", () => {+ // Producer B (credential-proxy sighting) reads this so `cli_invocation`+ // rows carry the same context Producer A's tool_call / thinking rows do.+ it("returns nulls before any register() / session_init", async () => {+ const { AgentProcessManager } = await import("../manager/managerRuntime");+ const mgr = new AgentProcessManager({+ driverFor: () => ({} as never),+ baseContextFor: () => ({} as never),+ });+ expect(mgr.auditContext("unknown_agent")).toEqual({ sessionId: null, launchId: null });+ });++ it("reports launchId once register() has stashed one, and sessionId once a runtime session_init has landed", async () => {+ const { AgentProcessManager } = await import("../manager/managerRuntime");+ const listeners = new Map<string, Array<(...args: unknown[]) => void>>();+ const session = {+ on: (event: string, cb: (...args: unknown[]) => void) => {+ const arr = listeners.get(event) ?? [];+ arr.push(cb);+ listeners.set(event, arr);+ },+ start: () => new Promise<void>(() => { }),+ send: () => { },+ stop: () => { },+ get currentSessionId() { return null; },+ };+ const mgr = new AgentProcessManager({+ driverFor: () => ({+ id: "codex",+ lifecycle: { kind: "per_turn" },+ supportsStdinNotification: false,+ busyDeliveryMode: "none",+ } as never),+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", config: {} }) as never,+ sessionFactory: () => session as never,+ });+ mgr.register("a1", { launchId: "l_XYZ" });+ expect(mgr.auditContext("a1")).toEqual({ sessionId: null, launchId: "l_XYZ" });++ mgr.deliver("a1", { seq: 1, text: "hi" } as never);+ for (const cb of listeners.get("runtime_event") ?? []) cb({ kind: "session_init", sessionId: "s_ABC" });+ expect(mgr.auditContext("a1")).toEqual({ sessionId: "s_ABC", launchId: "l_XYZ" });+ });+});diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex a99dbf045..f0ba112b9 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -39,6 +39,27 @@ import { formatHandle } from "@alook/shared/lib/discriminator";const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;const WARMUP_CEILING_MS = 30_000;+/**+ * Derive the audit-log `cli_invocation` subcommand from a proxy request+ * pathname. The credential proxy rewrites the CLI's bare `/api/*` calls onto+ * `/api/community/agent/*` (see `rewriteAgentPath` in credentialProxy.ts) —+ * but the sighting fires BEFORE that rewrite runs (against the inbound+ * pathname), so we may see either shape here.+ *+ * `/api/ack` is a paired sibling of `inboxPull` with no user intent, so it's+ * dropped (returns `null`). Anything else outside the `/api/*` prefix returns+ * `null` too — the proxy is generic and could carry non-audit traffic in the+ * future.+ */+export function deriveAuditLogSubcommand(pathname: string): string | null {+ const stripped = pathname.replace(/^\/api\/community\/agent\//, "/api/");+ if (!stripped.startsWith("/api/")) return null;+ const sub = stripped.slice("/api/".length).split("/")[0]?.split("?")[0] ?? "";+ if (!sub) return null;+ if (sub === "ack") return null;+ return sub;+}+/** The minimal WebSocket the control channel needs (host injects a `ws` factory). */export type DaemonWebSocketFactory = (url: string, headers: Record<string, string>) => unknown;@@ -120,9 +141,47 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaproviderFor: () => opts.runtimeReport[0]?.id ?? null,});+ // Held in a mutable cell so the credential-proxy and manager audit hooks+ // (constructed above the WsControlChannel below) can call it lazily —+ // the closures fire on real traffic long after `channel` is populated.+ let channelRef: WsControlChannel | null = null;+ // Populated after `manager` is constructed below. Producer B reads+ // `auditContext(agentId)` off it inside `onProxyRequest`.+ let managerRef: AgentProcessManager | null = null;+ const emitBotAuditEvent = (+ agentId: string,+ event:+ | { kind: "cli_invocation"; payload: { subcommand: string } }+ | { kind: "tool_call"; payload: { name: string } }+ | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } },+ context?: { sessionId?: string | null; launchId?: string | null }+ ) => {+ void channelRef?.reportBotAuditEvent?.({+ type: "bot_audit_event",+ agentId,+ sessionId: context?.sessionId ?? null,+ launchId: context?.launchId ?? null,+ event,+ });+ };+const broker = new CredentialBroker({ upstreamBaseUrl: opts.serverUrl });const proxy = await startCredentialProxy(broker, {onInboxPullResponse: (agentId, messages) => timeline.appendEntryForAgent(agentId, messages),+ // Bot audit log — Producer B (authoritative for `alook <sub>`). Fires+ // ONLY on `verdict.ok === true`, before the upstream request is written.+ onProxyRequest: (agentId, _method, pathname) => {+ const subcommand = deriveAuditLogSubcommand(pathname);+ if (!subcommand) return;+ // Producer B: read the same audit context Producer A does so+ // cli_invocation rows carry launchId (and sessionId once the runtime+ // handshake has landed) — matches plan §Data model.+ const context = managerRef?.auditContext(agentId);+ emitBotAuditEvent(agentId, {+ kind: "cli_invocation",+ payload: { subcommand },+ }, context);+ },});// Per-agent enrolled runner keys (enrollment is async; stored before deliver).@@ -269,6 +328,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaonAuthRejected: opts.onAuthRejected,logger: log.child("ws"),});+ channelRef = channel;// Cache-side handler for bot:* frames. Runs BEFORE AgentRouter sees them,// via a channel wrapper (registered below).@@ -368,6 +428,9 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDatickIntervalMs: opts.tickIntervalMs ?? 2000,onAgentSession: (info) => void channel.reportAgentSession(info),onAgentActivity: (info) => void channel.reportAgentActivity?.(info),+ // Bot audit log — Producer A (runtime thinking + non-Bash tool_call).+ // Bash suppression + thinking truncation happen inside managerRuntime.+ onBotAuditEvent: (agentId, event, context) => emitBotAuditEvent(agentId, event, context),// Idle hibernation / stall-recovery stops the subprocess without a// server-sent agent:stop; keep AgentRouter.running aligned so the next// `ready` frame's `runningAgents` reflects what's actually live and the@@ -380,6 +443,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDawakePromptFooter: "Use `alook inbox pull` to read your messages, then reply with `alook message send`.",logger: log.child("manager"),});+ managerRef = manager;manager.start();router = new AgentRouter({diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex d10f81507..c5973b497 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, vi } from "vitest";-import { AgentProcessManager, type ManagedSession, type SessionFactory } from "./managerRuntime.js";+import { AgentProcessManager, truncateThinking, type ManagedSession, type SessionFactory } from "./managerRuntime.js";import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";import type { Logger } from "../logger.js";@@ -73,7 +73,7 @@ function fakeSession(): FakeSession {return s;}-function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeoutMs?: number; staleThresholdMs?: number; now?: () => number } = {}) {+function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeoutMs?: number; staleThresholdMs?: number; now?: () => number; onBotAuditEvent?: (agentId: string, event: unknown, context: { sessionId: string | null; launchId: string | null }) => void } = {}) {const session = fakeSession();const factory: SessionFactory = () => session;const onRuntimeSpawnFailed = vi.fn();@@ -90,6 +90,7 @@ function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeosessionFactory: factory,onRuntimeSpawnFailed,onRuntimeSessionEstablished,+ onBotAuditEvent: opts.onBotAuditEvent as never,...opts,});mgr.register("a1");@@ -736,3 +737,115 @@ describe("AgentProcessManager — in-process SDK driver dispatch (Driver.createSexpect(() => mgr.deliver("a1", { seq: 1, text: "hello" })).not.toThrow();});});++describe("truncateThinking", () => {+ it("returns text unchanged when under the byte budget", () => {+ const { text, truncated, chars } = truncateThinking("short");+ expect(text).toBe("short");+ expect(truncated).toBe(false);+ expect(chars).toBe(5);+ });++ it("truncates > 4KB text and reports the original char count", () => {+ const long = "a".repeat(5000);+ const { text, truncated, chars } = truncateThinking(long);+ expect(truncated).toBe(true);+ expect(chars).toBe(5000);+ expect(Buffer.byteLength(text, "utf8")).toBeLessThanOrEqual(4096);+ });++ it("never splits a multi-byte UTF-8 sequence", () => {+ // Build a string whose 4096-byte boundary lands inside a 4-byte emoji.+ // Each 😀 is 4 bytes. 1023 emojis = 4092 bytes; add "a" to get to 4093;+ // then more emojis to push past 4096 mid-glyph.+ const emoji = "😀";+ const prefix = "a".repeat(4093) + emoji + emoji + emoji;+ const { text } = truncateThinking(prefix);+ // The returned string must be decodable — i.e. no replacement chars+ // introduced by a mid-codepoint cut. `Buffer.from(text, "utf8")` and+ // reading it back should round-trip.+ expect(text).toBe(Buffer.from(text, "utf8").toString("utf8"));+ });+});++describe("AgentProcessManager — bot audit event emission", () => {+ it("emits `thinking` with truncated+chars fields", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ session.fire("runtime_event", { kind: "thinking", text: "think about it" });++ expect(onBotAuditEvent).toHaveBeenCalledWith(+ "a1",+ expect.objectContaining({+ kind: "thinking",+ payload: expect.objectContaining({+ text: "think about it",+ truncated: false,+ chars: 14,+ }),+ }),+ expect.objectContaining({ sessionId: null, launchId: null })+ );+ });++ it("emits `tool_call` with name only (strips input)", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { path: "/etc/passwd" } });++ expect(onBotAuditEvent).toHaveBeenCalledWith(+ "a1",+ { kind: "tool_call", payload: { name: "Read" } },+ expect.objectContaining({ sessionId: null, launchId: null })+ );+ });++ it("carries sessionId (populated after session_init) into the context arg", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ // Learn the runtime session id from the handshake.+ session.fire("runtime_event", { kind: "session_init", sessionId: "s_abc" });+ session.fire("runtime_event", { kind: "tool_call", name: "Read", input: {} });++ expect(onBotAuditEvent).toHaveBeenCalledWith(+ "a1",+ { kind: "tool_call", payload: { name: "Read" } },+ { sessionId: "s_abc", launchId: null }+ );+ });++ it("DROPS `tool_call { name: \"Bash\" }` regardless of proxy sightings (Bash suppression)", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "ls -la" } });++ // No audit event should be emitted for a Bash tool_call — the+ // credential-proxy sighting (Producer B) is the authoritative source+ // for `alook <sub>` invocations. Non-audit-hook side effects (progress+ // dispatch) are unaffected.+ const bashCalls = onBotAuditEvent.mock.calls.filter(+ ([, ev]) => (ev as { kind?: string })?.kind === "tool_call"+ );+ expect(bashCalls).toHaveLength(0);+ });++ it("does NOT emit for non-audit event kinds (session_init, text, turn_end)", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });+ session.fire("runtime_event", { kind: "text", text: "hi human" });+ session.fire("runtime_event", { kind: "turn_end" });++ expect(onBotAuditEvent).not.toHaveBeenCalled();+ });+});diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 71df1aee0..10d599829 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -98,6 +98,22 @@ export interface ManagerRuntimeOpts {* plans/community-bot-status-telemetry.md.*/onAgentActivity?: (info: { agentId: string; state: AgentActivityState }) => void;+ /**+ * Notified whenever a runtime `thinking` or non-`Bash` `tool_call` event+ * lands. Wired in `createDaemon` to send a `bot_audit_event` frame through+ * the WS control channel. Not called for `Bash` tool_calls — see the+ * "Bash suppression" branch inside `onRuntimeEvent`.+ *+ * Kept minimal on purpose: no `input`, no output — the audit log records+ * NAME only for tool_calls, and truncated `text` for thinking.+ */+ onBotAuditEvent?: (+ agentId: string,+ event:+ | { kind: "tool_call"; payload: { name: string } }+ | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } },+ context: { sessionId: string | null; launchId: string | null }+ ) => void;/*** Notified when the daemon itself terminates an agent (idle hibernation or* stall-recovery) — NOT for server-sent `agent:stop`, which the router@@ -161,6 +177,34 @@ export interface TimelineRecorder {resumeSessionId(agentId: string, provider: string | null): string | null;}+/** Max UTF-8 byte budget for `thinking` text in the audit log. */+const THINKING_MAX_BYTES = 4096;++/**+ * Truncate a `thinking` string to at most `THINKING_MAX_BYTES` UTF-8 bytes+ * without splitting a multi-byte sequence. Exported for tests. Callers get the+ * (possibly truncated) text plus the original char count so the UI can render+ * "+N more chars" without re-fetching.+ */+export function truncateThinking(+ text: string+): { text: string; truncated: boolean; chars: number } {+ // Count codepoints (user-facing characters), not UTF-16 code units — an+ // emoji-heavy string reports one "char" per emoji, matching the "Show N+ // more characters" affordance in the UI.+ const chars = [...text].length;+ const buf = Buffer.from(text, "utf8");+ if (buf.byteLength <= THINKING_MAX_BYTES) {+ return { text, truncated: false, chars };+ }+ // Walk back from the boundary to a safe UTF-8 char break. Continuation+ // bytes are `10xxxxxx` (0x80-0xBF); slice must land BEFORE one.+ let end = THINKING_MAX_BYTES;+ while (end > 0 && (buf[end] & 0xc0) === 0x80) end--;+ const truncatedText = buf.subarray(0, end).toString("utf8");+ return { text: truncatedText, truncated: true, chars };+}+export class AgentProcessManager {private state: ManagerState;private readonly sessions = new Map<string, ManagedSession>();@@ -190,6 +234,7 @@ export class AgentProcessManager {| "sdkDriverDepsFor"| "onAgentSession"| "onAgentActivity"+ | "onBotAuditEvent"| "onAgentLocallyStopped"| "timeline"| "wakePromptFooter"@@ -206,6 +251,7 @@ export class AgentProcessManager {| "sdkDriverDepsFor"| "onAgentSession"| "onAgentActivity"+ | "onBotAuditEvent"| "onAgentLocallyStopped"| "timeline"| "wakePromptFooter"@@ -284,6 +330,20 @@ export class AgentProcessManager {* Live agent sessions (agentId + sessionId + launchId) for control-plane* resync after a reconnect. Only agents whose runtime has reported a session.*/+ /**+ * Current (sessionId, launchId) for an agent, or nulls if not yet known.+ * Read by Producer B (credential-proxy sighting) so `cli_invocation` audit+ * events carry the same context Producer A's `tool_call` / `thinking`+ * events do — plan §Data model asks for launchId on every event where+ * known, and sessionId once the runtime handshake has landed.+ */+ auditContext(agentId: string): { sessionId: string | null; launchId: string | null } {+ return {+ sessionId: this.liveSessions.get(agentId) ?? null,+ launchId: this.launchIds.get(agentId) ?? null,+ };+ }+liveSessionReports(): Array<{ agentId: string; sessionId: string; launchId: string }> {return [...this.liveSessions.entries()].map(([agentId, sessionId]) => ({agentId,@@ -535,8 +595,41 @@ export class AgentProcessManager {}private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string): void {- const ev = e as { kind?: string; sessionId?: string; text?: string };+ const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string };if (!ev?.kind) return;+ // Bot audit hook — thinking + non-Bash tool_call, no correlation.+ // Context carries the sessionId/launchId learned so far this launch so+ // ws-do can persist them alongside each row (the plan's Data model calls+ // for both). `liveSessions` is populated on `session_init`; if this+ // event fires BEFORE the runtime has emitted its handshake, sessionId is+ // null and the row records the launch without a session id.+ if (this.opts.onBotAuditEvent) {+ const context = {+ sessionId: this.liveSessions.get(agentId) ?? null,+ launchId: this.launchIds.get(agentId) ?? null,+ };+ if (ev.kind === "thinking" && typeof ev.text === "string") {+ const { text, truncated, chars } = truncateThinking(ev.text);+ try {+ this.opts.onBotAuditEvent(agentId, {+ kind: "thinking",+ payload: { text, truncated, chars },+ }, context);+ } catch { /* observational */ }+ } else if (ev.kind === "tool_call" && typeof ev.name === "string") {+ // Bash suppression — the credential proxy emits the authoritative+ // `cli_invocation` when the agent invokes `alook` from a shell, and+ // raw non-`alook` Bash isn't user-visible in the audit spec.+ if (ev.name !== "Bash") {+ try {+ this.opts.onBotAuditEvent(agentId, {+ kind: "tool_call",+ payload: { name: ev.name },+ }, context);+ } catch { /* observational */ }+ }+ }+ }if (ev.kind === "session_init" && ev.sessionId) {this.dispatch({ type: "session", agentId, sessionId: ev.sessionId });this.liveSessions.set(agentId, ev.sessionId);diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex b1581a98e..0b7170ace 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -51,6 +51,8 @@ export type {HostControlChannel,AgentSessionReport,AgentActivityState,+ HostBotAuditEventFrame,+ BotAuditEventPayload,WebSocketLike,WebSocketFactory,AdminApi,diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.tsindex 7a79c928f..dd9a93ba6 100644--- a/src/daemon/src/server/wsControlChannel.test.ts+++ b/src/daemon/src/server/wsControlChannel.test.ts@@ -226,6 +226,38 @@ describe("WsControlChannel — agent activity reports", () => {});});+describe("WsControlChannel — bot audit event reports", () => {+ it("sends a well-formed bot_audit_event frame when open", async () => {+ const { ch, sockets } = makeChannel();+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));+ ch.connect();+ sockets[0].emit("open");+ await ch.reportBotAuditEvent({+ type: "bot_audit_event",+ agentId: "bot_1",+ event: { kind: "cli_invocation", payload: { subcommand: "send" } },+ });+ const frame = sockets[0].frames().find((f) => f.type === "bot_audit_event");+ expect(frame).toBeDefined();+ expect(frame.agentId).toBe("bot_1");+ expect(frame.event).toEqual({ kind: "cli_invocation", payload: { subcommand: "send" } });+ });++ it("no-ops when the socket isn't open", async () => {+ const { ch, sockets } = makeChannel();+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));+ ch.connect();+ await expect(+ ch.reportBotAuditEvent({+ type: "bot_audit_event",+ agentId: "bot_1",+ event: { kind: "tool_call", payload: { name: "Read" } },+ })+ ).resolves.toBeUndefined();+ expect(sockets[0].frames().some((f) => f.type === "bot_audit_event")).toBe(false);+ });+});+describe("WsControlChannel — HTTP 401s are non-terminal", () => {it("keeps reconnecting after 3+ consecutive 401 upgrade failures — no self-kill", async () => {const sockets: FakeSocket[] = [];diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.tsindex 8b67d2794..cfa597cee 100644--- a/src/daemon/src/server/wsControlChannel.ts+++ b/src/daemon/src/server/wsControlChannel.ts@@ -32,6 +32,7 @@ import type {WebSocketLike,WebSocketFactory,AgentActivityState,+ HostBotAuditEventFrame,} from "./contract.js";import { createLogger, type Logger } from "../logger.js";// Re-export so existing importers of these from this module keep working.@@ -109,6 +110,7 @@ type OutboundFrame =status: AgentCommandAckStatus;error?: AgentCommandAckError;}+ | HostBotAuditEventFrame| SessionErrorFrame;type ResyncProvider = () => { ready: HostReady; sessions: AgentSessionReport[] };@@ -211,6 +213,17 @@ export class WsControlChannel implements HostControlChannel {this.sendFrame({ type: "agent_activity", ...info });}+ /**+ * Emit a bot audit event upward — either from the credential proxy sighting+ * (`cli_invocation`) or from a runtime `thinking` / non-Bash `tool_call`+ * event. Frame is dropped when the socket isn't open; audit events are+ * point-in-time (not resynced on reconnect), matching the ready/session+ * policy above.+ */+ async reportBotAuditEvent(frame: HostBotAuditEventFrame): Promise<void> {+ this.sendFrame(frame);+ }+/*** Reply to an `agent:wake` HostCommand with the wake outcome — "daemon* accepted/handled the wake command", NOT "process started" (seediff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 25c64b1c0..f85297f70 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -478,6 +478,25 @@ export interface HostReady {*/export type AgentActivityState = "idle" | "starting" | "running" | "stopping";+/**+ * Bot audit-log event kinds/payloads mirrored from the wire zod schema+ * (`BotAuditEventSchema` in `./schemas.ts`). The daemon emits these upward+ * through `HostControlChannel.reportBotAuditEvent`; ws-do stamps `createdAt`+ * and appends to `community_bot_activity_event`.+ */+export type BotAuditEventPayload =+ | { kind: "cli_invocation"; payload: { subcommand: string } }+ | { kind: "tool_call"; payload: { name: string } }+ | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } };++export interface HostBotAuditEventFrame {+ type: "bot_audit_event";+ agentId: AgentId;+ sessionId?: string | null;+ launchId?: string | null;+ event: BotAuditEventPayload;+}+/*** `session.error` frame — daemon → server. Currently used by the daemon's* agent router when a runtime isn't available on the host.@@ -540,6 +559,12 @@ export interface HostControlChannel {* local mock channel can omit it.*/reportAgentActivity?(info: { agentId: AgentId; state: AgentActivityState }): Promise<void>;+ /**+ * Report a bot audit event (cli_invocation | tool_call | thinking) upward.+ * Optional so LocalControlChannel can omit — matches `reportAgentActivity?`+ * convention. ws-do stamps `createdAt` and enforces the 500-row retention.+ */+ reportBotAuditEvent?(frame: HostBotAuditEventFrame): Promise<void>;/*** Register a resync provider invoked on every (re)connect: it returns the* host's current `ready` snapshot + live agent sessions, which the channeldiff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 3589f9d64..1192ae8fb 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -428,6 +428,24 @@ export type CommunityMachineRemoved = {machineId: string}+// ── Bot audit-log events ─────────────────────────────────────────────────────+//+// Owner-only fan-out. When a daemon reports a bot activity event+// (cli_invocation | tool_call | thinking), ws-do inserts it into+// community_bot_activity_event and delivers a single frame to the bot owner's+// per-user DO. Non-owners never see these frames.++export type CommunityBotAuditEvent = {+ type: "community:bot.audit_event"+ botId: string+ id: string+ kind: "cli_invocation" | "tool_call" | "thinking"+ payload: unknown+ sessionId?: string | null+ launchId?: string | null+ createdAt: string+}+// ── Bot events ────────────────────────────────────────────────────────────────//// Server → daemon frames. Colon-namespaced to match the existing HostCommand@@ -506,6 +524,7 @@ export type CommunityWsEvent =| CommunityMachineStatus| CommunityMachineUpdated| CommunityMachineRemoved+ | CommunityBotAuditEvent/** Type guard: is this a community WS event? */export function isCommunityEvent(msg: { type: string }): msg is CommunityWsEvent {@@ -552,4 +571,5 @@ export const WS_EVENTS = {MACHINE_STATUS: "community:machine.status",MACHINE_UPDATED: "community:machine.updated",MACHINE_REMOVED: "community:machine.removed",+ BOT_AUDIT_EVENT: "community:bot.audit_event",} as constdiff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 991ce1bd8..7a0d84734 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -486,3 +486,33 @@ export const communityBotApprovalRequest = sqliteTable((t) => [index("idx_community_bot_approval_bot").on(t.botId, t.status)]);+// 21. community_bot_activity_event+// Per-bot audit trail. Rows are one of three kinds — cli_invocation, tool_call,+// thinking — recorded from the daemon (via the WS control channel) and stamped+// with `createdAt` server-side by ws-do. `payload` is JSON whose shape depends+// on `kind` (see AuditLogPayloadSchema in ../schemas.ts). Retention is a rolling+// last 500 rows per bot, pruned at write time in ws-do.+export const communityBotActivityEvent = sqliteTable(+ "community_bot_activity_event",+ {+ id: text("id").primaryKey().$defaultFn(() => "bae_" + nanoid()),+ botId: text("bot_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ sessionId: text("session_id"),+ launchId: text("launch_id"),+ kind: text("kind").notNull(),+ payload: text("payload").notNull(),+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ (t) => [+ // Migration 0058 writes this as `(bot_id, created_at DESC, id DESC)` to+ // match the read ORDER BY + retention prune (see plan §Retention).+ // Drizzle's TS-side index type doesn't carry direction; the composite+ // shape at this level is enough for Drizzle's own use — SQLite can walk+ // the index in either direction, and the migration is authoritative on+ // the direction the planner picks.+ index("idx_bot_activity_event_bot_created").on(t.botId, t.createdAt, t.id),+ ]+);+diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 9f5a6d625..650ecab08 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -53,3 +53,4 @@ export * as communityInbox from "./queries/community/inbox";export * as communityMachine from "./queries/community/machine";export * as communityBot from "./queries/community/bot";export * as communityAgentInbox from "./queries/community/agent-inbox";+export * as communityBotAuditLog from "./queries/community/bot-audit-log";diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.tsnew file mode 100644index 000000000..ee861a286--- /dev/null+++ b/src/shared/src/db/queries/community/bot-audit-log.ts@@ -0,0 +1,159 @@+/**+ * Bot activity audit log — per-bot append-only event log with 500-row-per-bot+ * retention. Rows are inserted via ws-do (single writer), read from the web+ * API's owner-scoped GET route, and pruned in the same D1 batch as the insert.+ *+ * Every read filters to `user.deletedAt IS NULL` on the joined bot user row+ * so a soft-deleted bot's activity is not surfaced (see plan §Data model).+ */++import { and, desc, eq, isNull, lt, notInArray, or } from "drizzle-orm";+import { communityBotActivityEvent } from "../../community-schema";+import { user } from "../../schema";+import type { Database } from "../../index";++const DEFAULT_LIMIT = 50;+const MAX_LIMIT = 100;+export const AUDIT_LOG_MAX_ROWS_PER_BOT = 500;++export type BotActivityEventRow = {+ id: string;+ botId: string;+ sessionId: string | null;+ launchId: string | null;+ kind: string;+ payload: string;+ createdAt: string;+};++export type BotActivityEventInput = {+ botId: string;+ sessionId?: string | null;+ launchId?: string | null;+ kind: "cli_invocation" | "tool_call" | "thinking";+ payload: string;+};++/**+ * Insert + retention prune in a single D1 batch. This is the writer ws-do+ * calls on every inbound `bot_audit_event` frame. Returns the inserted row+ * (or null if the INSERT didn't land — treat as "don't broadcast").+ */+export async function insertBotActivityEventAndPrune(+ db: Database,+ data: BotActivityEventInput+): Promise<{ id: string; createdAt: string } | null> {+ const insert = insertBotActivityEventStatement(db, data);+ const prune = pruneBotActivityEventsStatement(db, data.botId);+ const results = (await db.batch([insert, prune] as any)) as any[];+ const insertResult = results?.[0];+ const rows: Array<{ id: string; createdAt: string }> = Array.isArray(insertResult)+ ? insertResult+ : Array.isArray(insertResult?.rows)+ ? insertResult.rows+ : [];+ return rows[0] ?? null;+}++/**+ * Insert a single event. Prefer the atomic batch (insert + prune) invoked from+ * ws-do; this is exposed as a Drizzle statement builder so ws-do can compose+ * it into a `db.batch([...])` call.+ */+export function insertBotActivityEventStatement(+ db: Database,+ data: BotActivityEventInput+) {+ return db+ .insert(communityBotActivityEvent)+ .values({+ botId: data.botId,+ sessionId: data.sessionId ?? null,+ launchId: data.launchId ?? null,+ kind: data.kind,+ payload: data.payload,+ })+ .returning({+ id: communityBotActivityEvent.id,+ createdAt: communityBotActivityEvent.createdAt,+ });+}++/**+ * Delete rows older than the top-500 (by createdAt DESC, id DESC) for a bot.+ * Uses a `NOT IN (subquery)` shape built via Drizzle operators so the returned+ * value is a real Drizzle statement that composes into `db.batch([...])` —+ * `db.run(sql\`...\`)` returns a Promise, which is NOT batchable and would+ * throw `Cannot read properties of undefined (reading 'bind')` when D1's+ * batch adapter tries to call `.bind()` on it.+ */+export function pruneBotActivityEventsStatement(db: Database, botId: string) {+ const keepTopN = db+ .select({ id: communityBotActivityEvent.id })+ .from(communityBotActivityEvent)+ .where(eq(communityBotActivityEvent.botId, botId))+ .orderBy(desc(communityBotActivityEvent.createdAt), desc(communityBotActivityEvent.id))+ .limit(AUDIT_LOG_MAX_ROWS_PER_BOT);+ return db+ .delete(communityBotActivityEvent)+ .where(+ and(+ eq(communityBotActivityEvent.botId, botId),+ notInArray(communityBotActivityEvent.id, keepTopN)+ )+ );+}++/**+ * List events for a bot, newest first, with composite cursor pagination on+ * `(createdAt DESC, id DESC)`.+ *+ * The list is filtered to bots that are still live (`user.deletedAt IS NULL`);+ * a soft-deleted bot returns an empty list even if raw rows remain.+ */+export async function listBotActivityEvents(+ db: Database,+ opts: {+ botId: string;+ beforeCreatedAt?: string;+ beforeId?: string;+ limit?: number;+ }+): Promise<BotActivityEventRow[]> {+ const limit = Math.min(opts.limit ?? DEFAULT_LIMIT, MAX_LIMIT);+ const conds = [+ eq(communityBotActivityEvent.botId, opts.botId),+ isNull(user.deletedAt),+ ];+ if (opts.beforeCreatedAt !== undefined && opts.beforeId !== undefined) {+ conds.push(+ or(+ lt(communityBotActivityEvent.createdAt, opts.beforeCreatedAt),+ and(+ eq(communityBotActivityEvent.createdAt, opts.beforeCreatedAt),+ lt(communityBotActivityEvent.id, opts.beforeId)+ )+ )!+ );+ } else if (opts.beforeCreatedAt !== undefined) {+ conds.push(lt(communityBotActivityEvent.createdAt, opts.beforeCreatedAt));+ }++ const rows = await db+ .select({+ id: communityBotActivityEvent.id,+ botId: communityBotActivityEvent.botId,+ sessionId: communityBotActivityEvent.sessionId,+ launchId: communityBotActivityEvent.launchId,+ kind: communityBotActivityEvent.kind,+ payload: communityBotActivityEvent.payload,+ createdAt: communityBotActivityEvent.createdAt,+ })+ .from(communityBotActivityEvent)+ .innerJoin(user, eq(user.id, communityBotActivityEvent.botId))+ .where(and(...conds))+ .orderBy(desc(communityBotActivityEvent.createdAt), desc(communityBotActivityEvent.id))+ .limit(limit);++ return rows;+}diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex 9635ff007..5bb68e8ed 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -197,6 +197,37 @@ export async function getBotBinding(return rows[0] ?? null;}+/**+ * Combined lookup: bot's machine binding + owner userId. Used by ws-do's audit+ * event handler to (a) verify the frame originates from the machine that owns+ * the bot, and (b) address the owner-only fan-out.+ * Returns null if the bot is unknown, soft-deleted, or unbound.+ */+export async function getBotBindingWithOwner(+ db: Database,+ botId: string+): Promise<{ machineId: string; runtime: string; ownerUserId: string } | null> {+ const rows = await db+ .select({+ machineId: communityBotBinding.machineId,+ runtime: communityBotBinding.runtime,+ ownerUserId: user.ownerUserId,+ })+ .from(user)+ .innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))+ .where(+ and(+ eq(user.id, botId),+ eq(user.isBot, true),+ isNull(user.deletedAt)+ )+ )+ .limit(1);+ const r = rows[0];+ if (!r || !r.ownerUserId) return null;+ return { machineId: r.machineId, runtime: r.runtime, ownerUserId: r.ownerUserId };+}+/*** Wake-dispatch candidate filter — one D1 hit. Given a message's `recipients`* (all fanout recipients, human + bot) and the scope it landed in (exactlydiff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 8fa5495eb..447424994 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -268,6 +268,12 @@ export {CommunityAgentListChannelsRequestSchema,CommunityAgentListMembersRequestSchema,CommunityAgentJoinServerRequestSchema,+ BotAuditEventSchema,+ BotAuditEventKindSchema,+ AuditLogCliInvocationPayloadSchema,+ AuditLogToolCallPayloadSchema,+ AuditLogThinkingPayloadSchema,+ HostBotAuditEventFrameSchema,} from "./schemas";export type {@@ -340,6 +346,8 @@ export type {CommunityAgentListChannelsRequest,CommunityAgentListMembersRequest,CommunityAgentJoinServerRequest,+ BotAuditEvent,+ BotAuditEventKind,} from "./schemas";// Community agent CLI bridge contract — lifted from `src/daemon/src/server/contract.ts`.@@ -390,6 +398,8 @@ export type {AgentSessionReport,ParsedRef as CommunityCliParsedRef,AgentActivityState,+ HostBotAuditEventFrame,+ BotAuditEventPayload,} from "./community-cli-contract";export { DM_SERVER, parseRef, formatRef, parseSeq, formatSeq } from "./community-cli-contract";@@ -459,6 +469,7 @@ export type {CommunityMachineStatus,CommunityMachineUpdated,CommunityMachineRemoved,+ CommunityBotAuditEvent,CommunityWsEvent,} from "./community-ws-events";export { isCommunityEvent, WS_EVENTS } from "./community-ws-events";@@ -468,7 +479,7 @@ export { createDb } from "./db/index";export type { Database } from "./db/index";export * as schema from "./db/schema";export * as queries from "./db/queries-index";-export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem } from "./db/community-schema";+export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem, communityBotActivityEvent } from "./db/community-schema";// Loggerexport { Logger, createLogger } from "./logger"diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex be956d46f..52858097c 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -940,6 +940,7 @@ export const AgentActivityMessageSchema = z.object({});export type AgentActivityMessage = z.infer<typeof AgentActivityMessageSchema>;+export const CommunityPairTokenResponseSchema = z.object({tokenId: z.string(),expiresAt: z.string(),@@ -1128,3 +1129,55 @@ export type CommunityAgentJoinServerRequest = z.infer<typeof CommunityAgentJoinServerRequestSchema>;+// ---------------------------------------------------------------------------+// Bot activity audit log — event payload+// ---------------------------------------------------------------------------+//+// Shared between the daemon (producer), ws-do (persistence), and web+// (route reader). The `payload` column stores JSON matching one of these+// discriminated branches.+//+// - cli_invocation → the daemon's credential proxy handled an alook subcommand+// - tool_call → the runtime invoked a non-Bash tool (Bash is suppressed)+// - thinking → excerpted thinking text, truncated at 4096 UTF-8 bytes++export const AuditLogCliInvocationPayloadSchema = z.object({+ subcommand: z.string().min(1),+});+export const AuditLogToolCallPayloadSchema = z.object({+ name: z.string().min(1),+});+export const AuditLogThinkingPayloadSchema = z.object({+ text: z.string(),+ truncated: z.boolean(),+ chars: z.number().int().nonnegative(),+});++export const BotAuditEventSchema = z.discriminatedUnion("kind", [+ z.object({ kind: z.literal("cli_invocation"), payload: AuditLogCliInvocationPayloadSchema }),+ z.object({ kind: z.literal("tool_call"), payload: AuditLogToolCallPayloadSchema }),+ z.object({ kind: z.literal("thinking"), payload: AuditLogThinkingPayloadSchema }),+]);+export type BotAuditEvent = z.infer<typeof BotAuditEventSchema>;++export const BotAuditEventKindSchema = z.enum([+ "cli_invocation",+ "tool_call",+ "thinking",+]);+export type BotAuditEventKind = z.infer<typeof BotAuditEventKindSchema>;++/**+ * `bot_audit_event` frame — daemon → server. Two producers on the daemon side+ * feed this (credential proxy sighting for `cli_invocation`, runtime event+ * stream for `tool_call` / `thinking`); ws-do stamps `createdAt` and inserts.+ */+export const HostBotAuditEventFrameSchema = z.object({+ type: z.literal("bot_audit_event"),+ agentId: z.string().min(1),+ sessionId: z.string().nullable().optional(),+ launchId: z.string().nullable().optional(),+ event: BotAuditEventSchema,+});+export type HostBotAuditEventFrame = z.infer<typeof HostBotAuditEventFrameSchema>;+diff --git a/src/shared/test/queries/community-bot-audit-log.test.ts b/src/shared/test/queries/community-bot-audit-log.test.tsnew file mode 100644index 000000000..164325697--- /dev/null+++ b/src/shared/test/queries/community-bot-audit-log.test.ts@@ -0,0 +1,94 @@+import { describe, it, expect } from "vitest"+import * as q from "../../src/db/queries/community/bot-audit-log"+import { BotAuditEventSchema, HostBotAuditEventFrameSchema } from "../../src/schemas"++/**+ * Smoke test — verifies the bot-audit-log query module exports the documented+ * helpers. Integration-level behaviour (batch atomicity, retention prune,+ * cursor pagination, soft-delete filter) is exercised in the+ * `tests/e2e/community-bot-audit-log.e2e.test.ts` suite where a real D1 lives.+ */+describe("community/bot-audit-log exports", () => {+ it("exposes writers", () => {+ expect(typeof q.insertBotActivityEventStatement).toBe("function")+ expect(typeof q.pruneBotActivityEventsStatement).toBe("function")+ expect(typeof q.insertBotActivityEventAndPrune).toBe("function")+ })++ it("exposes a reader", () => {+ expect(typeof q.listBotActivityEvents).toBe("function")+ })++ it("exposes the retention cap constant", () => {+ // Plan §Retention: 500 rows per bot. Locked here so a refactor+ // changing the constant surfaces as a test failure.+ expect(q.AUDIT_LOG_MAX_ROWS_PER_BOT).toBe(500)+ })+})++describe("BotAuditEventSchema — payload discriminated union", () => {+ it("accepts a cli_invocation payload", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "cli_invocation",+ payload: { subcommand: "send" },+ })+ expect(r.success).toBe(true)+ })+ it("accepts a tool_call payload", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "tool_call",+ payload: { name: "Read" },+ })+ expect(r.success).toBe(true)+ })+ it("accepts a thinking payload with truncated + chars", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "thinking",+ payload: { text: "hmm", truncated: false, chars: 3 },+ })+ expect(r.success).toBe(true)+ })+ it("rejects a kind/payload mismatch", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "tool_call",+ payload: { subcommand: "send" },+ })+ expect(r.success).toBe(false)+ })+ it("rejects an unknown kind", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "shell",+ payload: { name: "bash" },+ })+ expect(r.success).toBe(false)+ })+})++describe("HostBotAuditEventFrameSchema", () => {+ it("accepts a frame with optional sessionId/launchId", () => {+ const r = HostBotAuditEventFrameSchema.safeParse({+ type: "bot_audit_event",+ agentId: "bot_1",+ sessionId: "s_1",+ launchId: "l_1",+ event: { kind: "cli_invocation", payload: { subcommand: "send" } },+ })+ expect(r.success).toBe(true)+ })+ it("accepts a frame without sessionId/launchId", () => {+ const r = HostBotAuditEventFrameSchema.safeParse({+ type: "bot_audit_event",+ agentId: "bot_1",+ event: { kind: "thinking", payload: { text: "x", truncated: false, chars: 1 } },+ })+ expect(r.success).toBe(true)+ })+ it("rejects an empty agentId (must be at least one char)", () => {+ const r = HostBotAuditEventFrameSchema.safeParse({+ type: "bot_audit_event",+ agentId: "",+ event: { kind: "tool_call", payload: { name: "Read" } },+ })+ expect(r.success).toBe(false)+ })+})diff --git a/src/web/migrations/0058_community_bot_activity_event.sql b/src/web/migrations/0058_community_bot_activity_event.sqlnew file mode 100644index 000000000..9f76ed685--- /dev/null+++ b/src/web/migrations/0058_community_bot_activity_event.sql@@ -0,0 +1,24 @@+-- Per-bot audit trail for the /community/me/bots activity modal.+-- Rows are one of three kinds — cli_invocation, tool_call, thinking.+-- Retention: rolling last 500 per bot, pruned at write time in ws-do.+-- FK cascades on the user row so a HARD delete removes activity rows;+-- production uses soft-delete (user.deleted_at set), so the query layer+-- filters to `user.deleted_at IS NULL` on reads (see queries/community/bot-audit-log.ts).++CREATE TABLE community_bot_activity_event (+ id TEXT PRIMARY KEY,+ bot_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ session_id TEXT,+ launch_id TEXT,+ kind TEXT NOT NULL,+ payload TEXT NOT NULL,+ created_at TEXT NOT NULL+);++-- Composite index: page reads AND retention prune ordering.+-- (bot_id, created_at DESC, id DESC) matches both the read query's ORDER BY+-- and the retention prune's tie-breaker (see plan §Retention). The `id DESC`+-- tail ensures same-millisecond ties break deterministically so paginated+-- cursors stay stable.+CREATE INDEX idx_bot_activity_event_bot_created+ ON community_bot_activity_event(bot_id, created_at DESC, id DESC);diff --git a/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.tsnew file mode 100644index 000000000..3524e8c85--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts@@ -0,0 +1,169 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const mockGetBotOwnedBy = vi.fn()+const mockListBotActivityEvents = vi.fn()++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityBot: {+ getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),+ },+ communityBotAuditLog: {+ listBotActivityEvents: (...a: unknown[]) => mockListBotActivityEvents(...a),+ },+ },+ }+})++let isAuthed = true++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any, ctx?: any) => {+ if (!isAuthed) {+ const { NextResponse } = require("next/server")+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })+ }+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, {+ env: { DB: {} },+ userId: "u1",+ email: "[email protected]",+ params,+ })+ },+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { GET } from "./route"++function req(qs = "") {+ const url = `http://localhost/api/community/bots/b1/audit-log${qs}`+ return new NextRequest(url, { method: "GET" })+}+function ctx(id?: string) {+ return { params: Promise.resolve(id ? { id } : {}) } as any+}++describe("GET /api/community/bots/[id]/audit-log", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ isAuthed = true+ })++ it("returns 401 for anonymous callers", async () => {+ isAuthed = false+ const res = await GET(req(), ctx("b1"))+ expect(res.status).toBe(401)+ expect(mockGetBotOwnedBy).not.toHaveBeenCalled()+ })++ it("returns 404 when the bot is missing or not owned by the session user (getBotOwnedBy filters both)", async () => {+ mockGetBotOwnedBy.mockResolvedValue(null)+ const res = await GET(req(), ctx("b1"))+ expect(res.status).toBe(404)+ expect(mockGetBotOwnedBy).toHaveBeenCalledWith(expect.anything(), "b1", "u1")+ expect(mockListBotActivityEvents).not.toHaveBeenCalled()+ })++ it("returns rows + a null nextCursor when fewer than `limit` results come back", async () => {+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })+ mockListBotActivityEvents.mockResolvedValue([+ {+ id: "bae_1",+ botId: "b1",+ sessionId: null,+ launchId: null,+ kind: "tool_call",+ payload: JSON.stringify({ name: "Read" }),+ createdAt: "2025-01-01T00:00:00.000Z",+ },+ ])+ const res = await GET(req(), ctx("b1"))+ expect(res.status).toBe(200)+ const body = (await res.json()) as { events: unknown[]; nextCursor: unknown }+ expect(body.events).toEqual([+ {+ id: "bae_1",+ kind: "tool_call",+ payload: { name: "Read" },+ sessionId: null,+ launchId: null,+ createdAt: "2025-01-01T00:00:00.000Z",+ },+ ])+ expect(body.nextCursor).toBe(null)+ })++ it("returns a composite nextCursor when the page fills to the limit", async () => {+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })+ const rows = Array.from({ length: 2 }).map((_, i) => ({+ id: `bae_${i}`,+ botId: "b1",+ sessionId: null,+ launchId: null,+ kind: "tool_call",+ payload: JSON.stringify({ name: "Read" }),+ createdAt: `2025-01-01T00:00:0${i}.000Z`,+ }))+ mockListBotActivityEvents.mockResolvedValue(rows)+ const res = await GET(req("?limit=2"), ctx("b1"))+ const body = (await res.json()) as { nextCursor: { beforeCreatedAt: string; beforeId: string } | null }+ // Composite cursor uses the LAST row (oldest in the newest-first page) so+ // the next page picks up strictly older events.+ expect(body.nextCursor).toEqual({+ beforeCreatedAt: "2025-01-01T00:00:01.000Z",+ beforeId: "bae_1",+ })+ })++ it("forwards beforeCreatedAt + beforeId to the query for cursor pagination", async () => {+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })+ mockListBotActivityEvents.mockResolvedValue([])+ await GET(+ req("?beforeCreatedAt=2025-01-01T00:00:00.000Z&beforeId=bae_x&limit=25"),+ ctx("b1"),+ )+ expect(mockListBotActivityEvents).toHaveBeenCalledWith(+ expect.anything(),+ {+ botId: "b1",+ beforeCreatedAt: "2025-01-01T00:00:00.000Z",+ beforeId: "bae_x",+ limit: 25,+ },+ )+ })++ it("caps limit at 100 and floors it at 1 (defends against unbounded page requests)", async () => {+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })+ mockListBotActivityEvents.mockResolvedValue([])+ await GET(req("?limit=99999"), ctx("b1"))+ expect(mockListBotActivityEvents).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ limit: 100 }),+ )+ await GET(req("?limit=0"), ctx("b1"))+ // 0 → falls back to default (50) via the || fallback.+ expect(mockListBotActivityEvents).toHaveBeenLastCalledWith(+ expect.anything(),+ expect.objectContaining({ limit: 50 }),+ )+ })+})diff --git a/src/web/src/app/api/community/bots/[id]/audit-log/route.ts b/src/web/src/app/api/community/bots/[id]/audit-log/route.tsnew file mode 100644index 000000000..fdb3967ad--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/audit-log/route.ts@@ -0,0 +1,62 @@+import type { NextRequest } from "next/server"+import { queries } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { parseAuditLogPayload } from "@/lib/community/audit-log-payload"++const DEFAULT_LIMIT = 50+const MAX_LIMIT = 100++/**+ * GET /api/community/bots/[id]/audit-log+ *+ * Owner-only. Returns a page of bot activity events, newest first, with+ * composite `(before_created_at, before_id)` cursor pagination — a single+ * timestamp cursor would drop events tied at the same millisecond, so both+ * halves are required and applied together in the query.+ *+ * 404 on: unknown bot, bot not owned by the session user, or bot soft-deleted+ * (per plan §API — the ownership + deletedAt filter is scoped up-front, never+ * fetch-then-check).+ */+export const GET = withAuth(async (req: NextRequest, ctx) => {+ const id = ctx.params?.id as string+ const db = getDb(ctx.env.DB)++ // Ownership + soft-delete gate — matches `getBotOwnedBy` predicate.+ const bot = await queries.communityBot.getBotOwnedBy(db, id, ctx.userId)+ if (!bot) return writeError("bot not found", 404)++ const url = new URL(req.url)+ const beforeCreatedAt = url.searchParams.get("beforeCreatedAt") ?? undefined+ const beforeId = url.searchParams.get("beforeId") ?? undefined+ const limitRaw = url.searchParams.get("limit")+ const limit = limitRaw+ ? Math.max(1, Math.min(MAX_LIMIT, Number.parseInt(limitRaw, 10) || DEFAULT_LIMIT))+ : DEFAULT_LIMIT++ const rows = await queries.communityBotAuditLog.listBotActivityEvents(db, {+ botId: id,+ beforeCreatedAt,+ beforeId,+ limit,+ })++ const events = rows.map((r) => ({+ id: r.id,+ kind: r.kind,+ payload: parseAuditLogPayload(r.kind, r.payload),+ sessionId: r.sessionId,+ launchId: r.launchId,+ createdAt: r.createdAt,+ }))++ const last = rows[rows.length - 1]+ const nextCursor =+ rows.length >= limit && last+ ? { beforeCreatedAt: last.createdAt, beforeId: last.id }+ : null++ return writeJSON({ events, nextCursor })+})diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsxnew file mode 100644index 000000000..b60411e24--- /dev/null+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx@@ -0,0 +1,256 @@+"use client"++import { useEffect, useLayoutEffect, useMemo, useRef } from "react"+import { AgentAvatar } from "@/components/avatar"+import {+ Dialog,+ DialogContent,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog"+import { useOnlineUserIds } from "@/stores/community/ws"+import {+ useBotAuditLog,+ type AuditEvent,+} from "@/hooks/community/use-bot-audit-log"+import type { BotSummary } from "@/hooks/community/use-bots"+import { BotActivityRow } from "./bot-activity-row"++/**+ * Modal audit log for one bot. Owner-only surface (the API enforces 404 for+ * non-owners); opens over the current /community/me/bots view rather than+ * pushing a route.+ *+ * Reads like a developer log tail:+ * - oldest at the top, newest at the bottom;+ * - auto-scrolls to the tail on open and on new live rows (only when the+ * user was already near the tail — a reader scrolled up to inspect+ * history is not yanked back);+ * - scroll UP to load the next (older) page; the scroll offset is+ * preserved across the prepend so the row under the eye stays fixed.+ *+ * Day dividers group rows chronologically without adding per-row chrome.+ */+export function BotActivityModal({+ bot,+ open,+ onOpenChange,+}: {+ bot: BotSummary | null+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ // "Live" here means the bot's daemon is currently connected (its WS+ // presence). A viewer with a broken WS wouldn't receive events either, but+ // the daemon-side signal is what determines whether new rows are actually+ // being produced right now.+ const online = useOnlineUserIds().has(bot?.id ?? "")+ const {+ events,+ isLoading,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = useBotAuditLog(open ? bot?.id : null)++ // The API returns newest-first (createdAt DESC). The UI wants+ // oldest-first at the top so the log reads chronologically — flip once here.+ const chronological = useMemo(() => [...events].reverse(), [events])++ // Chronologically-adjacent rows are grouped under a shared day header,+ // rendered when the day boundary changes. Cheap to compute at the render+ // scale we operate at (500-row cap per bot).+ const grouped = useMemo(() => groupByDay(chronological), [chronological])++ const scrollRef = useRef<HTMLDivElement | null>(null)+ const lastCountRef = useRef(0)+ const pendingOlderAnchorRef = useRef<number | null>(null)++ useEffect(() => {+ const el = scrollRef.current+ if (!el || !hasNextPage) return+ const onScroll = () => {+ if (isFetchingNextPage) return+ if (el.scrollTop < 80) {+ pendingOlderAnchorRef.current = el.scrollHeight+ void fetchNextPage()+ }+ }+ el.addEventListener("scroll", onScroll)+ return () => el.removeEventListener("scroll", onScroll)+ }, [fetchNextPage, hasNextPage, isFetchingNextPage])++ useLayoutEffect(() => {+ const el = scrollRef.current+ if (!el) return+ const prevCount = lastCountRef.current+ const nextCount = chronological.length+ lastCountRef.current = nextCount+ if (nextCount === 0) return++ if (pendingOlderAnchorRef.current !== null) {+ const delta = el.scrollHeight - pendingOlderAnchorRef.current+ el.scrollTop = el.scrollTop + delta+ pendingOlderAnchorRef.current = null+ return+ }++ const nearTail = el.scrollHeight - (el.scrollTop + el.clientHeight) < 80+ const firstPaint = prevCount === 0+ if (firstPaint || (nextCount > prevCount && nearTail)) {+ el.scrollTop = el.scrollHeight+ }+ }, [chronological.length])++ useEffect(() => {+ if (!open) {+ lastCountRef.current = 0+ pendingOlderAnchorRef.current = null+ }+ }, [open, bot?.id])++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ showCloseButton={false}+ className="flex h-[72vh] max-h-[680px] w-full max-w-2xl flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl"+ >+ <header className="flex shrink-0 items-center gap-3 border-b border-border/40 px-4 py-3">+ <AgentAvatar name={bot?.name ?? ""} avatarUrl={bot?.image ?? null} size={32} />+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <DialogTitle className="truncate text-sm font-medium">+ {bot?.name ?? "Bot"}+ </DialogTitle>+ <DialogDescription className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <span+ className={[+ "inline-block size-1.5 rounded-full",+ online ? "bg-status-online" : "bg-muted-foreground/60",+ ].join(" ")}+ aria-hidden+ />+ <span>{online ? "Live" : "Offline"}</span>+ <span aria-hidden className="text-muted-foreground/40">·</span>+ <span>Activity log</span>+ </DialogDescription>+ </div>+ <button+ type="button"+ onClick={() => onOpenChange(false)}+ className="rounded-md px-2 py-1 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"+ >+ Close+ </button>+ </header>++ <div ref={scrollRef} className="flex-1 overflow-y-auto thin-scrollbar bg-background">+ {isLoading && chronological.length === 0 ? (+ <SkeletonRows />+ ) : chronological.length === 0 ? (+ <EmptyState />+ ) : (+ <div className="pb-3">+ {isFetchingNextPage ? (+ <div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/60">+ Loading older+ </div>+ ) : hasNextPage ? (+ <div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/40">+ Scroll up for older+ </div>+ ) : (+ <div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/40">+ Beginning of log+ </div>+ )}+ {grouped.map((group) => (+ <section key={group.dayKey}>+ <DayDivider label={group.label} />+ {group.events.map((event) => (+ <BotActivityRow key={event.id} event={event} />+ ))}+ </section>+ ))}+ </div>+ )}+ </div>+ </DialogContent>+ </Dialog>+ )+}++function DayDivider({ label }: { label: string }) {+ return (+ <div className="sticky top-0 z-10 border-b border-border/40 bg-background/95 px-4 py-1 backdrop-blur supports-[backdrop-filter]:bg-background/80">+ <span className="font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground">+ {label}+ </span>+ </div>+ )+}++function SkeletonRows() {+ return (+ <div className="flex flex-col gap-2 p-4">+ {Array.from({ length: 8 }).map((_, i) => (+ <div key={i} className="flex items-center gap-3">+ <div className="h-3 w-16 animate-pulse rounded bg-muted/40" />+ <div className="h-3 w-10 animate-pulse rounded bg-muted/30" />+ <div className="h-3 flex-1 animate-pulse rounded bg-muted/40" />+ </div>+ ))}+ </div>+ )+}++function EmptyState() {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 p-8 text-center">+ <div className="font-mono text-[10px] uppercase tracking-wider text-muted-foreground/60">+ No activity yet+ </div>+ <p className="max-w-xs text-xs text-muted-foreground">+ This bot hasn't run since audit logging was enabled. New runs+ will stream in here as they happen.+ </p>+ </div>+ )+}++type DayGroup = { dayKey: string; label: string; events: AuditEvent[] }++function groupByDay(events: AuditEvent[]): DayGroup[] {+ const groups: DayGroup[] = []+ for (const event of events) {+ const key = dayKey(event.createdAt)+ const tail = groups[groups.length - 1]+ if (tail && tail.dayKey === key) {+ tail.events.push(event)+ } else {+ groups.push({ dayKey: key, label: formatDayLabel(event.createdAt), events: [event] })+ }+ }+ return groups+}++function dayKey(iso: string): string {+ const d = new Date(iso)+ return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`+}++function formatDayLabel(iso: string): string {+ const d = new Date(iso)+ const now = new Date()+ const startOfDay = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()+ const days = Math.round((startOfDay(now) - startOfDay(d)) / 86_400_000)+ if (days === 0) return "Today"+ if (days === 1) return "Yesterday"+ if (days < 7) {+ return d.toLocaleDateString(undefined, { weekday: "long" })+ }+ return d.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ year: d.getFullYear() === now.getFullYear() ? undefined : "numeric",+ })+}diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsxnew file mode 100644index 000000000..85b6cdb43--- /dev/null+++ b/src/web/src/components/community/bots/bot-activity-row.tsx@@ -0,0 +1,141 @@+"use client"++import { useState } from "react"+import type { AuditEvent, AuditKind } from "@/hooks/community/use-bot-audit-log"++/**+ * One audit-log entry. Rendered as a 3-column strip:+ *+ * [ HH:MM:SS ] [ kind glyph ] [ body … ]+ *+ * The kind glyph is a two-letter tag in muted mono (`>_`, `Tl`, `~~`) rather+ * than a lucide icon — icons at row scale compete with the body text and+ * make each row feel like a card. A tag is quieter and reads like a log+ * severity column.+ *+ * Height is stable per row (thinking rows collapse to 8 lines by default;+ * expanding grows in-place) so live appends don't shift already-visible+ * rows.+ */+export function BotActivityRow({ event }: { event: AuditEvent }) {+ const [expanded, setExpanded] = useState(false)++ return (+ <div className="group grid grid-cols-[64px_56px_1fr] items-baseline gap-x-3 px-4 py-1.5 hover:bg-accent/30">+ <time+ dateTime={event.createdAt}+ title={new Date(event.createdAt).toLocaleString()}+ className="font-mono text-[11px] tabular-nums text-muted-foreground/70"+ >+ {formatClock(event.createdAt)}+ </time>+ <KindTag kind={event.kind} />+ <div className="min-w-0 text-left">+ <RowBody event={event} expanded={expanded} onToggle={() => setExpanded((v) => !v)} />+ </div>+ </div>+ )+}++function KindTag({ kind }: { kind: AuditKind }) {+ const { label, tone } = kindMeta(kind)+ return (+ <span+ className={`select-none font-mono text-[10px] font-medium uppercase tracking-wider ${tone}`}+ aria-label={label}+ >+ {label}+ </span>+ )+}++function kindMeta(kind: AuditKind): { label: string; tone: string } {+ if (kind === "cli_invocation") return { label: "daemon", tone: "text-foreground/70" }+ if (kind === "tool_call") return { label: "tool", tone: "text-muted-foreground" }+ return { label: "think", tone: "text-muted-foreground/70" }+}++/** Thinking rows show up to this many lines before offering "Show more". */+const THINKING_COLLAPSED_LINES = 8++function RowBody({+ event,+ expanded,+ onToggle,+}: {+ event: AuditEvent+ expanded: boolean+ onToggle: () => void+}) {+ if (event.kind === "cli_invocation") {+ const p = event.payload as { subcommand?: string } | null+ const sub = p?.subcommand ?? "?"+ return (+ <span className="font-mono text-[13px] text-foreground">+ alook <span className="text-muted-foreground">{sub}</span>+ </span>+ )+ }+ if (event.kind === "tool_call") {+ const p = event.payload as { name?: string } | null+ return <span className="font-mono text-[13px] text-foreground">{p?.name ?? "?"}</span>+ }+ const p = event.payload as { text?: string; truncated?: boolean; chars?: number } | null+ const text = p?.text ?? ""+ const truncated = p?.truncated ?? false+ // `chars` from the daemon is the codepoint count of the pre-truncation+ // string; compare against the codepoint count of the shown slice so an+ // emoji-heavy body doesn't over-report the hidden remainder.+ const chars = p?.chars ?? countCodepoints(text)+ const lines = text.split("\n")+ const overflowsLineLimit = lines.length > THINKING_COLLAPSED_LINES+ const shownText = expanded+ ? text+ : overflowsLineLimit+ ? lines.slice(0, THINKING_COLLAPSED_LINES).join("\n")+ : text+ const canExpand = overflowsLineLimit || truncated+ const hiddenLines = overflowsLineLimit ? lines.length - THINKING_COLLAPSED_LINES : 0+ const hiddenChars = truncated ? Math.max(0, chars - countCodepoints(shownText)) : 0+ return (+ <div className="flex min-w-0 flex-col gap-1">+ <div className="whitespace-pre-wrap break-words font-mono text-[12.5px] leading-relaxed text-muted-foreground">+ {shownText}+ </div>+ {canExpand && !expanded ? (+ <button+ type="button"+ onClick={onToggle}+ className="self-start text-[11px] text-muted-foreground/70 underline-offset-2 hover:text-foreground hover:underline"+ >+ {overflowsLineLimit+ ? `Show ${hiddenLines} more line${hiddenLines === 1 ? "" : "s"}`+ : `Show ${hiddenChars} more character${hiddenChars === 1 ? "" : "s"}`}+ </button>+ ) : null}+ {expanded && canExpand ? (+ <button+ type="button"+ onClick={onToggle}+ className="self-start text-[11px] text-muted-foreground/70 underline-offset-2 hover:text-foreground hover:underline"+ >+ Collapse+ </button>+ ) : null}+ </div>+ )+}++/** Count Unicode codepoints (matches daemon's `truncateThinking` chars). */+function countCodepoints(s: string): number {+ return [...s].length+}++/** HH:MM:SS in local time — the reader is looking at their own workday. */+function formatClock(iso: string): string {+ const d = new Date(iso)+ const h = String(d.getHours()).padStart(2, "0")+ const m = String(d.getMinutes()).padStart(2, "0")+ const s = String(d.getSeconds()).padStart(2, "0")+ return `${h}:${m}:${s}`+}diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex 3c8afb82a..9f7663aec 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -31,6 +31,7 @@ import { useCreateOrGetDm } from "@/hooks/community/mutations"import { useOnlineUserIds } from "@/stores/community/ws"import { CreateBotSheet } from "./create-bot-sheet"import { EditBotSheet } from "./edit-bot-sheet"+import { BotActivityModal } from "./bot-activity-modal"/*** BotList — the /community/me/bots surface.@@ -59,6 +60,8 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {// harmlessly while the sheet is hidden.const [editingBot, setEditingBot] = useState<BotSummary | null>(null)const [editOpen, setEditOpen] = useState(false)+ const [activityBot, setActivityBot] = useState<BotSummary | null>(null)+ const [activityOpen, setActivityOpen] = useState(false)const [confirmDelete, setConfirmDelete] = useState<BotSummary | null>(null)const del = useDeleteBot()const createOrGetDm = useCreateOrGetDm()@@ -278,6 +281,14 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {<DropdownMenuItem onClick={() => chatWithBot(bot)}>Chat</DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ setActivityBot(bot)+ setActivityOpen(true)+ }}+ >+ View activity+ </DropdownMenuItem><DropdownMenuItemonClick={() => {setEditingBot(bot)@@ -307,6 +318,11 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {<CreateBotSheet open={createOpen} onOpenChange={setCreateOpen} /><EditBotSheet bot={editingBot} open={editOpen} onOpenChange={setEditOpen} />+ <BotActivityModal+ bot={activityBot}+ open={activityOpen}+ onOpenChange={setActivityOpen}+ /><AlertDialogopen={!!confirmDelete}onOpenChange={(open) => !open && setConfirmDelete(null)}diff --git a/src/web/src/hooks/community/use-bot-audit-log.test.ts b/src/web/src/hooks/community/use-bot-audit-log.test.tsnew file mode 100644index 000000000..739d935f7--- /dev/null+++ b/src/web/src/hooks/community/use-bot-audit-log.test.ts@@ -0,0 +1,145 @@+import { describe, it, expect, beforeEach, vi } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"+import { useBotAuditLog } from "./use-bot-audit-log"+import { useCommunityWsStore } from "@/stores/community/ws"++const mockApiFetch = vi.fn()+vi.mock("@/lib/api/client", () => ({+ apiFetch: (...a: unknown[]) => mockApiFetch(...a),+}))++function renderWithHook(hook: () => ReturnType<typeof useBotAuditLog>) {+ const result: { current: ReturnType<typeof useBotAuditLog> } = { current: null as never }+ const qc = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ })+ function Probe() {+ result.current = hook()+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(QueryClientProvider, { client: qc }, React.createElement(Probe)),+ )+ })+ return { result, renderer }+}++async function flush() {+ await act(async () => {+ await new Promise((r) => setTimeout(r, 0))+ })+}++beforeEach(() => {+ mockApiFetch.mockReset()+ useCommunityWsStore.getState().reset()+})++describe("useBotAuditLog", () => {+ it("dedups a WS-live event whose id also appears in the initial GET page", async () => {+ mockApiFetch.mockResolvedValueOnce({+ events: [+ {+ id: "e1",+ kind: "tool_call",+ payload: { name: "Read" },+ sessionId: null,+ launchId: null,+ createdAt: "2025-01-01T00:00:00.000Z",+ },+ ],+ nextCursor: null,+ })++ const { result } = renderWithHook(() => useBotAuditLog("b1"))+ await flush()+ await flush()+ expect(result.current.events.map((e) => e.id)).toEqual(["e1"])++ act(() => {+ useCommunityWsStore.getState().pushBotAuditEvent({+ id: "e1",+ botId: "b1",+ kind: "tool_call",+ payload: { name: "Read" },+ createdAt: "2025-01-01T00:00:00.000Z",+ })+ })+ await flush()+ expect(result.current.events.map((e) => e.id)).toEqual(["e1"])+ })++ it("prepends a FRESH WS-live event (id not in cache) into the first page", async () => {+ mockApiFetch.mockResolvedValueOnce({+ events: [+ {+ id: "e_old",+ kind: "tool_call",+ payload: { name: "Read" },+ sessionId: null,+ launchId: null,+ createdAt: "2025-01-01T00:00:00.000Z",+ },+ ],+ nextCursor: null,+ })++ const { result } = renderWithHook(() => useBotAuditLog("b1"))+ await flush()+ await flush()++ act(() => {+ useCommunityWsStore.getState().pushBotAuditEvent({+ id: "e_new",+ botId: "b1",+ kind: "cli_invocation",+ payload: { subcommand: "send" },+ createdAt: "2025-01-01T00:00:05.000Z",+ })+ })+ await flush()+ expect(result.current.events.map((e) => e.id)).toEqual(["e_new", "e_old"])+ })++ it("does NOT include events for a different botId (filter isolates)", async () => {+ mockApiFetch.mockResolvedValueOnce({+ events: [+ {+ id: "e1",+ kind: "tool_call",+ payload: { name: "Read" },+ sessionId: null,+ launchId: null,+ createdAt: "2025-01-01T00:00:00.000Z",+ },+ ],+ nextCursor: null,+ })++ const { result } = renderWithHook(() => useBotAuditLog("b1"))+ await flush()+ await flush()++ act(() => {+ useCommunityWsStore.getState().pushBotAuditEvent({+ id: "e_other_bot",+ botId: "b2",+ kind: "tool_call",+ payload: { name: "Write" },+ createdAt: "2025-01-01T00:00:05.000Z",+ })+ })+ await flush()+ expect(result.current.events.map((e) => e.id)).toEqual(["e1"])+ })++ it("is disabled when botId is null — no fetch happens", async () => {+ renderWithHook(() => useBotAuditLog(null))+ await flush()+ expect(mockApiFetch).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.tsnew file mode 100644index 000000000..fe0d47d85--- /dev/null+++ b/src/web/src/hooks/community/use-bot-audit-log.ts@@ -0,0 +1,110 @@+"use client"++import { useEffect, useMemo } from "react"+import {+ useInfiniteQuery,+ useQueryClient,+ type InfiniteData,+} from "@tanstack/react-query"+import { apiFetch } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"+import { useBotAuditEventsForBot } from "@/stores/community/ws"++export type AuditKind = "cli_invocation" | "tool_call" | "thinking"++export type AuditEvent = {+ id: string+ kind: AuditKind+ payload: unknown+ sessionId: string | null+ launchId: string | null+ createdAt: string+}++export type AuditLogPage = {+ events: AuditEvent[]+ nextCursor: { beforeCreatedAt: string; beforeId: string } | null+}++const PAGE_SIZE = 50++/**+ * React Query infinite hook for a bot's audit log. Live events from the+ * WS store (`useBotAuditEventsForBot`) are prepended into the first page —+ * de-duplicated by `event.id` across ALL cached pages so an event that also+ * arrives via the initial GET (which raced the WS push) is not rendered+ * twice.+ */+export function useBotAuditLog(botId: string | null | undefined) {+ const enabled = Boolean(botId)+ const qc = useQueryClient()++ const query = useInfiniteQuery<AuditLogPage>({+ enabled,+ queryKey: botId ? communityKeys.botAuditLog(botId) : ["disabled-bot-audit-log"],+ initialPageParam: null as AuditLogPage["nextCursor"],+ queryFn: async ({ pageParam }) => {+ const cursor = pageParam as AuditLogPage["nextCursor"]+ const search = new URLSearchParams()+ search.set("limit", String(PAGE_SIZE))+ if (cursor) {+ search.set("beforeCreatedAt", cursor.beforeCreatedAt)+ search.set("beforeId", cursor.beforeId)+ }+ return apiFetch<AuditLogPage>(+ `/api/community/bots/${botId}/audit-log?${search.toString()}`,+ )+ },+ getNextPageParam: (last) => last.nextCursor,+ })++ const liveEvents = useBotAuditEventsForBot(botId)++ // Fold live events into the first-page cache. Dedup on `event.id` across+ // ALL pages — the initial GET can race a WS push and land the same row in+ // both channels. Depend on `query.data` too: a live event that lands while+ // the initial GET is still in flight would otherwise see `prev === undefined`+ // and silently drop.+ useEffect(() => {+ if (!enabled || liveEvents.length === 0) return+ qc.setQueryData<InfiniteData<AuditLogPage>>(+ communityKeys.botAuditLog(botId as string),+ (prev) => {+ if (!prev || prev.pages.length === 0) return prev+ const seen = new Set<string>()+ for (const p of prev.pages) for (const e of p.events) seen.add(e.id)+ const fresh: AuditEvent[] = liveEvents+ .filter((e) => !seen.has(e.id))+ .map((e) => ({+ id: e.id,+ kind: e.kind,+ payload: e.payload,+ sessionId: e.sessionId ?? null,+ launchId: e.launchId ?? null,+ createdAt: e.createdAt,+ }))+ if (fresh.length === 0) return prev+ const [firstPage, ...rest] = prev.pages+ const merged: AuditLogPage = {+ nextCursor: firstPage.nextCursor,+ events: [...fresh, ...firstPage.events],+ }+ return { ...prev, pages: [merged, ...rest] }+ },+ )+ }, [botId, enabled, liveEvents, qc, query.data])++ const events = useMemo(() => {+ if (!query.data) return [] as AuditEvent[]+ return query.data.pages.flatMap((p) => p.events)+ }, [query.data])++ return {+ events,+ isLoading: query.isLoading,+ fetchNextPage: query.fetchNextPage,+ hasNextPage: query.hasNextPage,+ isFetchingNextPage: query.isFetchingNextPage,+ }+}+diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex fb3706216..62fc953a5 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -832,6 +832,21 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}+ // ── Bot audit event — push into the bounded ring; the audit-log+ // hook filters + prepends into its React Query cache. ────────────+ case "community:bot.audit_event": {+ useCommunityWsStore.getState().pushBotAuditEvent({+ id: event.id,+ botId: event.botId,+ kind: event.kind,+ payload: event.payload,+ sessionId: event.sessionId ?? null,+ launchId: event.launchId ?? null,+ createdAt: event.createdAt,+ })+ return+ }+// ── Mentions ────────────────────────────────────────────────────case "community:mention.create": {void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })@@ -961,6 +976,15 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// `message.create` events, none of which arrive while the socket is// down.void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ // Bot audit logs are WS-live-patched into the React Query cache; if+ // the socket dropped, any events emitted during the gap never entered+ // the store's ring and so never made it into the cache. Invalidating+ // all bot audit-log pages on reconnect lets an open modal catch up.+ void queryClient.invalidateQueries({+ queryKey: [...communityKeys.all, "bot"],+ // Fuzzy prefix match — communityKeys.botAuditLog is [all, "bot", botId, "audit-log"].+ exact: false,+ })}, [queryClient])const { send } = useUserWs(handleMessage, { onReconnect: handleReconnect })diff --git a/src/web/src/lib/community/audit-log-payload.test.ts b/src/web/src/lib/community/audit-log-payload.test.tsnew file mode 100644index 000000000..443f47388--- /dev/null+++ b/src/web/src/lib/community/audit-log-payload.test.ts@@ -0,0 +1,29 @@+import { describe, it, expect } from "vitest"+import { parseAuditLogPayload } from "./audit-log-payload"++describe("parseAuditLogPayload", () => {+ it("parses a well-shaped cli_invocation payload", () => {+ const p = parseAuditLogPayload("cli_invocation", JSON.stringify({ subcommand: "send" }))+ expect(p).toEqual({ subcommand: "send" })+ })+ it("parses a well-shaped tool_call payload", () => {+ const p = parseAuditLogPayload("tool_call", JSON.stringify({ name: "Read" }))+ expect(p).toEqual({ name: "Read" })+ })+ it("parses a well-shaped thinking payload", () => {+ const p = parseAuditLogPayload(+ "thinking",+ JSON.stringify({ text: "hmm", truncated: false, chars: 3 }),+ )+ expect(p).toEqual({ text: "hmm", truncated: false, chars: 3 })+ })+ it("returns null on invalid JSON — the whole page must not 500", () => {+ expect(parseAuditLogPayload("cli_invocation", "{not-json")).toBe(null)+ })+ it("returns null on a kind/payload mismatch", () => {+ expect(parseAuditLogPayload("tool_call", JSON.stringify({ subcommand: "send" }))).toBe(null)+ })+ it("returns null on an unknown kind", () => {+ expect(parseAuditLogPayload("shell", JSON.stringify({ name: "bash" }))).toBe(null)+ })+})diff --git a/src/web/src/lib/community/audit-log-payload.ts b/src/web/src/lib/community/audit-log-payload.tsnew file mode 100644index 000000000..c59fc32e3--- /dev/null+++ b/src/web/src/lib/community/audit-log-payload.ts@@ -0,0 +1,39 @@+import {+ AuditLogCliInvocationPayloadSchema,+ AuditLogToolCallPayloadSchema,+ AuditLogThinkingPayloadSchema,+} from "@alook/shared"++/**+ * Parse a stored audit-event `payload` (JSON in the DB) into the shape the+ * client expects for its `kind`. Kept intentionally lenient — a schema drift+ * (e.g. a row written before a payload shape change) collapses to a null+ * payload rather than 500-ing the whole page.+ */+export function parseAuditLogPayload(+ kind: string,+ raw: string+): unknown {+ let json: unknown+ try {+ json = JSON.parse(raw)+ } catch {+ return null+ }+ switch (kind) {+ case "cli_invocation": {+ const r = AuditLogCliInvocationPayloadSchema.safeParse(json)+ return r.success ? r.data : null+ }+ case "tool_call": {+ const r = AuditLogToolCallPayloadSchema.safeParse(json)+ return r.success ? r.data : null+ }+ case "thinking": {+ const r = AuditLogThinkingPayloadSchema.safeParse(json)+ return r.success ? r.data : null+ }+ default:+ return null+ }+}diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex a41d90b35..dff9e8812 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -96,6 +96,8 @@ export const communityKeys = {// ── Bots ────────────────────────────────────────────────────────────────bots: () => [...communityKeys.all, "bots"] as const,+ botAuditLog: (botId: string) =>+ [...communityKeys.all, "bot", botId, "audit-log"] as const,// ── Notification settings ───────────────────────────────────────────────notificationSettings: () =>diff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.tsindex 84ce75c4a..d2db4a4f7 100644--- a/src/web/src/stores/community/ws.test.ts+++ b/src/web/src/stores/community/ws.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it } from "vitest"import {+ BOT_AUDIT_RING_MAX,SEEN_MESSAGE_MAX,SEEN_MESSAGE_TRIM_TO,useCommunityWsStore,@@ -168,4 +169,67 @@ describe("useCommunityWsStore", () => {useCommunityWsStore.getState().reset()expect(useCommunityWsStore.getState().userStatuses.size).toBe(0)})++ it("pushBotAuditEvent prepends newest-first, dedups on id, and bounds each per-bot ring", () => {+ const push = useCommunityWsStore.getState().pushBotAuditEvent+ push({+ id: "e1",+ botId: "b1",+ kind: "tool_call",+ payload: { name: "Read" },+ createdAt: "2025-01-01T00:00:00.000Z",+ })+ push({+ id: "e2",+ botId: "b1",+ kind: "cli_invocation",+ payload: { subcommand: "send" },+ createdAt: "2025-01-01T00:00:01.000Z",+ })+ const events = useCommunityWsStore.getState().botAuditEvents.get("b1") ?? []+ expect(events[0]!.id).toBe("e2")+ expect(events[1]!.id).toBe("e1")++ // Dedup on id — a second push of e2 must not duplicate.+ push({+ id: "e2",+ botId: "b1",+ kind: "cli_invocation",+ payload: { subcommand: "send" },+ createdAt: "2025-01-01T00:00:01.000Z",+ })+ expect((useCommunityWsStore.getState().botAuditEvents.get("b1") ?? []).length).toBe(2)+ })++ it("bounds each bot's ring independently — a chatty bot doesn't evict a quiet bot's events", () => {+ const push = useCommunityWsStore.getState().pushBotAuditEvent+ // Chatty bot A: overflow the ring.+ for (let i = 0; i < BOT_AUDIT_RING_MAX + 5; i++) {+ push({+ id: `a${i}`,+ botId: "bot_a",+ kind: "tool_call",+ payload: { name: "Read" },+ createdAt: `2025-01-01T00:00:${String(i).padStart(2, "0")}.000Z`,+ })+ }+ // Quiet bot B: one event, way earlier in wall-clock, must survive.+ push({+ id: "b1",+ botId: "bot_b",+ kind: "cli_invocation",+ payload: { subcommand: "send" },+ createdAt: "2020-01-01T00:00:00.000Z",+ })+ const aRing = useCommunityWsStore.getState().botAuditEvents.get("bot_a") ?? []+ const bRing = useCommunityWsStore.getState().botAuditEvents.get("bot_b") ?? []+ expect(aRing.length).toBe(BOT_AUDIT_RING_MAX)+ expect(aRing[0]!.id).toBe(`a${BOT_AUDIT_RING_MAX + 4}`)+ // Oldest chatty-bot events dropped.+ expect(aRing.some((e) => e.id === "a0")).toBe(false)+ // Quiet bot untouched.+ expect(bRing).toEqual([+ expect.objectContaining({ id: "b1", botId: "bot_b" }),+ ])+ })})diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex d6c38d42b..dcda2a96a 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -27,6 +27,25 @@ import { create } from "zustand"export const SEEN_MESSAGE_MAX = 500export const SEEN_MESSAGE_TRIM_TO = 400+/**+ * Bounded ring for live bot-audit events, PER bot. The modal reads from here+ * and prepends into the React Query cache — the ring only holds enough for+ * the "in-flight" window while the modal is open. Older events are always+ * available via paginated GETs. Per-bot bounding prevents a chatty bot from+ * evicting a quiet bot's live events before the modal for that bot mounts.+ */+export const BOT_AUDIT_RING_MAX = 200++export type BotAuditEventEntry = {+ id: string+ botId: string+ kind: "cli_invocation" | "tool_call" | "thinking"+ payload: unknown+ sessionId?: string | null+ launchId?: string | null+ createdAt: string+}+type UserStatus = { emoji: string | null; text: string | null }export type CommunityWsStoreState = {@@ -47,6 +66,12 @@ export type CommunityWsStoreState = {* fetched row.*/userStatuses: Map<string, UserStatus>+ /**+ * Per-bot rings of recent audit events, each bounded by BOT_AUDIT_RING_MAX.+ * Newest first inside each bot's array. A chatty bot never evicts a quieter+ * bot's events. Absent-bot lookup returns an empty array.+ */+ botAuditEvents: Map<string, BotAuditEventEntry[]>setPresence: (userId: string, online: boolean) => void/** Atomic bulk seed — one notification for N users. Use on server switch. */@@ -56,16 +81,18 @@ export type CommunityWsStoreState = {markSeenMessage: (id: string) => voidsetUserStatus: (userId: string, emoji: string | null, text: string | null) => voidresetUserStatuses: () => void+ pushBotAuditEvent: (event: BotAuditEventEntry) => voidreset: () => void}const initialState = (): Pick<CommunityWsStoreState,- "onlineUserIds" | "seenMessageIds" | "userStatuses"+ "onlineUserIds" | "seenMessageIds" | "userStatuses" | "botAuditEvents"> => ({onlineUserIds: new Set(),seenMessageIds: new Set(),userStatuses: new Map(),+ botAuditEvents: new Map(),})export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => ({@@ -121,6 +148,20 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (set({ userStatuses: new Map() })},+ pushBotAuditEvent: (event) => {+ const current = get().botAuditEvents+ const perBot = current.get(event.botId) ?? []+ // Dedup by id — the same event can arrive via WS *and* be in the initial+ // GET response (the plan's cache-race case); the hook does its own+ // per-cache dedup too, but keeping the store honest costs nothing.+ if (perBot.some((e) => e.id === event.id)) return+ const nextPerBot = [event, ...perBot]+ if (nextPerBot.length > BOT_AUDIT_RING_MAX) nextPerBot.length = BOT_AUDIT_RING_MAX+ const next = new Map(current)+ next.set(event.botId, nextPerBot)+ set({ botAuditEvents: next })+ },+reset: () => set(initialState()),}))@@ -135,3 +176,18 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (export const useOnlineUserIds = (): ReadonlySet<string> => {return useCommunityWsStore((s) => s.onlineUserIds)}++const EMPTY_AUDIT_EVENTS: BotAuditEventEntry[] = []++/**+ * Live bot-audit events for a single botId. Newest first.+ *+ * The zustand selector reads only the per-bot slice of the ring map — a+ * presence/status update, or an event for a different bot, doesn't force a+ * re-render because zustand short-circuits on `Object.is` identity.+ */+export const useBotAuditEventsForBot = (botId: string | null | undefined): BotAuditEventEntry[] => {+ return useCommunityWsStore((s) =>+ botId ? s.botAuditEvents.get(botId) ?? EMPTY_AUDIT_EVENTS : EMPTY_AUDIT_EVENTS,+ )+}diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex 7b2660a66..ff97335a4 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -85,6 +85,8 @@ const mockListMembers = vi.fn()const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolean>>().mockResolvedValue(false)const mockGetBotBinding = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string } | null>>().mockResolvedValue(null)+const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string; ownerUserId: string } | null>>().mockResolvedValue(null)+const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)const mockUpdateProfile = vi.fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>().mockResolvedValue({})@@ -172,6 +174,34 @@ vi.mock("@alook/shared", () => {return { success: true as const, data: { type: "agent_activity" as const, agentId: m.agentId, state: m.state } }},}+ const HostBotAuditEventFrameSchema = {+ safeParse(v: unknown) {+ const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown; event?: unknown }+ if (m?.type !== "bot_audit_event") return { success: false } as const+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const+ const ev = m.event as { kind?: unknown; payload?: unknown }+ if (!ev || typeof ev !== "object") return { success: false } as const+ const kind = ev.kind+ const payload = ev.payload as Record<string, unknown> | undefined+ if (!payload || typeof payload !== "object") return { success: false } as const+ let ok = false+ if (kind === "cli_invocation") ok = typeof payload.subcommand === "string"+ else if (kind === "tool_call") ok = typeof payload.name === "string"+ else if (kind === "thinking")+ ok = typeof payload.text === "string" && typeof payload.truncated === "boolean" && typeof payload.chars === "number"+ if (!ok) return { success: false } as const+ return {+ success: true as const,+ data: {+ type: "bot_audit_event" as const,+ agentId: m.agentId,+ sessionId: typeof m.sessionId === "string" ? m.sessionId : m.sessionId === null ? null : undefined,+ launchId: typeof m.launchId === "string" ? m.launchId : m.launchId === null ? null : undefined,+ event: { kind, payload },+ },+ }+ },+ }return {createDb: (d1: unknown) => mockCreateDb(d1),createLogger: () => noopLogger,@@ -180,6 +210,7 @@ vi.mock("@alook/shared", () => {SessionErrorFrameSchema,HostReadyMessageSchema,AgentActivityMessageSchema,+ HostBotAuditEventFrameSchema,// Deterministic preset picker so the assertion can pin exact// `statusEmoji`/`statusText` values regardless of the injected `seed`.pickBotActivityPreset: (state: string) => {@@ -242,6 +273,10 @@ vi.mock("@alook/shared", () => {communityBot: {listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),getBotBinding: (...a: [unknown, string]) => mockGetBotBinding(...a),+ getBotBindingWithOwner: (...a: [unknown, string]) => mockGetBotBindingWithOwner(...a),+ },+ communityBotAuditLog: {+ insertBotActivityEventAndPrune: (...a: any[]) => mockInsertBotActivityEventAndPrune(...a),},user: {getUserInternal: (...a: [unknown, string]) => mockGetUserInternal(...a),@@ -1210,6 +1245,177 @@ describe("WebSocketDurableObject", () => {})})+ describe("community-machine — bot_audit_event frame", () => {+ beforeEach(() => {+ mockGetBotBindingWithOwner.mockReset()+ mockInsertBotActivityEventAndPrune.mockReset()+ mockStubFetch.mockClear()+ })++ it("inserts + prunes atomically and notifies the OWNER only when the machine owns the bot", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue({+ machineId: "cm_1",+ runtime: "codex",+ ownerUserId: "owner_1",+ })+ mockInsertBotActivityEventAndPrune.mockResolvedValue({+ id: "bae_abc",+ createdAt: "2025-01-01T00:00:00.000Z",+ })++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "bot_audit_event",+ agentId: "bot_1",+ sessionId: "s_1",+ launchId: "l_1",+ event: { kind: "tool_call", payload: { name: "Read" } },+ })+ await durable.webSocketMessage(ws as any, frame)++ // Insert was called with server-derived payload (not trust-the-daemon).+ expect(mockInsertBotActivityEventAndPrune).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ botId: "bot_1",+ sessionId: "s_1",+ launchId: "l_1",+ kind: "tool_call",+ payload: JSON.stringify({ name: "Read" }),+ }),+ )+ // Owner is notified via notifyUserDO — request goes to `user:owner_1`+ // and the payload carries the full audit event including createdAt+ // stamped server-side.+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ expect(call).toBeDefined()+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {+ type: string+ botId: string+ id: string+ kind: string+ payload: unknown+ createdAt: string+ }+ expect(body).toEqual({+ type: "community:bot.audit_event",+ botId: "bot_1",+ id: "bae_abc",+ kind: "tool_call",+ payload: { name: "Read" },+ sessionId: "s_1",+ launchId: "l_1",+ createdAt: "2025-01-01T00:00:00.000Z",+ })+ })++ it("drops a frame naming a bot bound to a different machine — no insert, no fan-out", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue({+ machineId: "cm_OTHER",+ runtime: "codex",+ ownerUserId: "owner_1",+ })++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "bot_audit_event",+ agentId: "bot_1",+ event: { kind: "cli_invocation", payload: { subcommand: "send" } },+ })+ await durable.webSocketMessage(ws as any, frame)++ expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ })++ it("drops a frame for a soft-deleted/unknown bot — no insert, no fan-out", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue(null)++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "bot_audit_event",+ agentId: "ghost_bot",+ event: { kind: "thinking", payload: { text: "hmm", truncated: false, chars: 3 } },+ })+ await durable.webSocketMessage(ws as any, frame)++ expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ })++ it("does not fan out when the INSERT returns null (empty batch result)", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue({+ machineId: "cm_1",+ runtime: "codex",+ ownerUserId: "owner_1",+ })+ // Simulate the D1 batch returning no rows for the primary statement.+ mockInsertBotActivityEventAndPrune.mockResolvedValue(null)++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "bot_audit_event",+ agentId: "bot_1",+ event: { kind: "tool_call", payload: { name: "Read" } },+ })+ await durable.webSocketMessage(ws as any, frame)++ expect(mockStubFetch).not.toHaveBeenCalled()+ })+ })+describe("community-machine — ready frame reconciles bot activity", () => {beforeEach(() => {mockUpsertMachineByMachineId.mockReset()diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 30647d714..b66f8daa4 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -8,6 +8,7 @@ import {HostReadyMessageSchema,SessionErrorFrameSchema,AgentActivityMessageSchema,+ HostBotAuditEventFrameSchema,pickBotActivityPreset,RUNNING_PRESETS,} from "@alook/shared"@@ -708,6 +709,45 @@ export class WebSocketDurableObject extends DurableObject<Env> {return}+ // `bot_audit_event` — daemon reports a bot activity event (cli_invocation,+ // tool_call, or thinking). Insert + rolling-500 prune land atomically via+ // `db.batch`; server stamps `createdAt` (never trust the daemon clock).+ // Fan the resulting row out to the OWNER ONLY (never `broadcastToAudience`+ // — that would leak per-bot activity to co-members + friends).+ const auditParse = HostBotAuditEventFrameSchema.safeParse(parsed)+ if (auditParse.success) {+ const frame = auditParse.data+ const db = createDb(this.env.DB)+ const binding = await queries.communityBot.getBotBindingWithOwner(db, frame.agentId)+ if (!binding || binding.machineId !== identity.machineId) {+ log.warn("bot_audit_event frame for a bot not bound to this machine — dropped", {+ agentId: frame.agentId,+ machineId: identity.machineId,+ })+ return+ }+ const payload = JSON.stringify(frame.event.payload)+ const inserted = await queries.communityBotAuditLog.insertBotActivityEventAndPrune(db, {+ botId: frame.agentId,+ sessionId: frame.sessionId ?? null,+ launchId: frame.launchId ?? null,+ kind: frame.event.kind,+ payload,+ })+ if (!inserted) return+ await this.notifyUserDO(binding.ownerUserId, {+ type: "community:bot.audit_event",+ botId: frame.agentId,+ id: inserted.id,+ kind: frame.event.kind,+ payload: frame.event.payload,+ sessionId: frame.sessionId ?? null,+ launchId: frame.launchId ?? null,+ createdAt: inserted.createdAt,+ }).catch(() => { })+ return+ }+// Otherwise: only `ready` frames drive DB updates. Zod-parse strictly —// legacy `runtimes: string[]`-only frames from pre-refactor daemons fail// validation and are silently dropped; MIN_CLI_VERSION will squeeze them