Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): remove server audit log (#456)

Gener353c4111b6ab
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index feb724499..414dc93bc 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -3,8 +3,6 @@ export const DEFAULT_MESSAGE_PAGE_SIZE = 50
export const MAX_MESSAGE_PAGE_SIZE = 100
export const DEFAULT_MEMBERS_PAGE_SIZE = 100
export const MAX_MEMBERS_PAGE_SIZE = 200
-export const DEFAULT_AUDIT_LOG_PAGE_SIZE = 50
-export const MAX_AUDIT_LOG_PAGE_SIZE = 100
export const DEFAULT_USER_SEARCH_LIMIT = 20
// Length limits — names, descriptions, profile text
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index bd8d139bc..e300868cd 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -502,32 +502,7 @@ export const communityNotificationSetting = sqliteTable(
(t) => [index("idx_notification_setting_user").on(t.userId)]
);
-// 19. community_audit_log
-export const communityAuditLog = sqliteTable(
- "community_audit_log",
- {
- id: text("id").primaryKey().$defaultFn(() => nanoid()),
- // Nullable — bot-lifecycle rows (created/updated/deleted, friend approval)
- // have no server scope. See migration 0050.
- serverId: text("server_id").references(() => communityServer.id, {
- onDelete: "cascade",
- }),
- actorId: text("actor_id").references(() => user.id, { onDelete: "set null" }),
- action: text("action").notNull(),
- targetType: text("target_type").notNull(),
- targetId: text("target_id").notNull(),
- changes: text("changes"),
- reason: text("reason"),
- createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
- },
- (t) => [
- index("idx_audit_log_server_created").on(t.serverId, t.createdAt),
- index("idx_audit_log_server_action").on(t.serverId, t.action),
- index("idx_audit_log_actor_created").on(t.actorId, t.createdAt),
- ]
-);
-
-// 20. community_bot_approval_request
+// 19. community_bot_approval_request
// Represents pending/resolved approval workflows a bot owner sees in the
// owner↔bot DM. After migration 0065 the ONLY live `kind` is:
// - "join_server": another user asked to add the bot to a server they're in
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 2135279c3..d38eea306 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -49,7 +49,6 @@ export * as communityReadState from "./queries/community/read-state";
export * as communityUserProfile from "./queries/community/user-profile";
export * as communitySearch from "./queries/community/search";
export * as communityNotificationSetting from "./queries/community/notification-setting";
-export * as communityAuditLog from "./queries/community/audit-log";
export * as communityServerFolder from "./queries/community/server-folder";
export * as communityInbox from "./queries/community/inbox";
export * as communityMachine from "./queries/community/machine";
diff --git a/src/shared/src/db/queries/community/audit-log.ts b/src/shared/src/db/queries/community/audit-log.ts
deleted file mode 100644
index b48d2d12f..000000000
--- a/src/shared/src/db/queries/community/audit-log.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { eq, and, desc, lt } from "drizzle-orm";
-import { communityAuditLog } from "../../community-schema";
-import { user } from "../../schema";
-import type { Database } from "../../index";
-
-const DEFAULT_LIMIT = 50;
-
-export async function logAction(
- db: Database,
- data: {
- /** Null for user-scoped rows (bot lifecycle, friend approvals). */
- serverId: string | null;
- actorId: string;
- action: string;
- targetType: string;
- targetId: string;
- changes?: string;
- reason?: string;
- }
-) {
- const [row] = await db
- .insert(communityAuditLog)
- .values({
- serverId: data.serverId,
- actorId: data.actorId,
- action: data.action,
- targetType: data.targetType,
- targetId: data.targetId,
- changes: data.changes ?? null,
- reason: data.reason ?? null,
- })
- .returning();
- return row!;
-}
-
-export async function listAuditLog(
- db: Database,
- serverId: string,
- opts?: { action?: string; before?: string; limit?: number }
-) {
- const limit = opts?.limit ?? DEFAULT_LIMIT;
- const conditions = [eq(communityAuditLog.serverId, serverId)];
-
- if (opts?.action) {
- conditions.push(eq(communityAuditLog.action, opts.action));
- }
-
- if (opts?.before) {
- conditions.push(lt(communityAuditLog.createdAt, opts.before));
- }
-
- return db
- .select({
- log: communityAuditLog,
- // Project only the fields needed to render audit log entries — never
- // leak full user PII (email, etc.) to server admins.
- actor: {
- id: user.id,
- name: user.name,
- image: user.image,
- },
- })
- .from(communityAuditLog)
- .leftJoin(user, eq(communityAuditLog.actorId, user.id))
- .where(and(...conditions))
- .orderBy(desc(communityAuditLog.createdAt))
- .limit(limit);
-}
diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.ts
index e430cf074..4f2dfc24e 100644
--- a/src/shared/src/db/queries/community/member.ts
+++ b/src/shared/src/db/queries/community/member.ts
@@ -334,7 +334,7 @@ export async function getMember(db: Database, serverId: string, userId: string)
// Scope-first single-member lookup. `WHERE id = ? AND server_id = ?` — cross
// server memberIds never resolve, so callers don't need to post-check
// ownership. Return shape mirrors `listMembers` (joined against `user` so
-// downstream broadcasts/audit calls have `userName` etc without a second
+// downstream broadcasts have `userName` etc without a second
// round-trip).
export async function getMemberById(
db: Database,
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 66dc98f14..dc7896414 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -116,8 +116,6 @@ export {
MAX_MESSAGE_PAGE_SIZE,
DEFAULT_MEMBERS_PAGE_SIZE,
MAX_MEMBERS_PAGE_SIZE,
- DEFAULT_AUDIT_LOG_PAGE_SIZE,
- MAX_AUDIT_LOG_PAGE_SIZE,
DEFAULT_USER_SEARCH_LIMIT,
MAX_SERVER_NAME_LENGTH,
MAX_SERVER_DESCRIPTION_LENGTH,
diff --git a/src/web/migrations/0084_drop_community_audit_log.sql b/src/web/migrations/0084_drop_community_audit_log.sql
new file mode 100644
index 000000000..4a035b31f
--- /dev/null
+++ b/src/web/migrations/0084_drop_community_audit_log.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS community_audit_log;
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
index 2c9438491..15623cb25 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
@@ -5,7 +5,6 @@ const mockGetApprovalRequest = vi.fn()
const mockGetMember = vi.fn()
const mockAddMember = vi.fn()
const mockResolveApprovalRequest = vi.fn()
-const mockLogAudit = vi.fn()
const mockFanOut = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -28,13 +27,6 @@ vi.mock("@alook/shared", async () => {
}
})
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
- COMMUNITY_AUDIT_ACTIONS: {
- BOT_JOIN_APPROVED: "bot_join_approved",
- BOT_ADDED_TO_SERVER: "bot_added_to_server",
- },
-}))
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts
index 9fa4f08a4..aac9d622d 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts
@@ -4,7 +4,6 @@ import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { fanOutToServerMembers } from "@/lib/community/fanout"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
/**
* Approve a pending bot approval request. After migration 0065 only the
@@ -59,25 +58,5 @@ export const POST = withAuth(async (_req, ctx) => {
fanOutToServerMembers(request.serverId, joinEvent)
}
await queries.communityBot.resolveApprovalRequest(db, requestId, "approved")
- logAudit(db, {
- serverId: request.serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_JOIN_APPROVED,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({ botId, serverId: request.serverId }),
- })
- logAudit(db, {
- serverId: request.serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_ADDED_TO_SERVER,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({
- botId,
- serverId: request.serverId,
- kind: "friend_of_bot_added",
- }),
- })
return writeJSON({ status: "approved", kind: "join_server" })
})
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
index 066a41620..1cbc825a9 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
@@ -3,7 +3,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
const mockGetBotOwnedBy = vi.fn()
const mockGetApprovalRequest = vi.fn()
const mockResolveApprovalRequest = vi.fn()
-const mockLogAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -17,12 +16,6 @@ vi.mock("@alook/shared", () => ({
},
}))
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
- COMMUNITY_AUDIT_ACTIONS: {
- BOT_JOIN_DENIED: "bot_join_denied",
- },
-}))
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (_req: any, ctx?: any) => {
@@ -65,7 +58,7 @@ describe("POST /api/community/bots/[id]/approval-requests/[requestId]/deny", ()
expect(res.status).toBe(404)
})
- it("denies a pending request and writes audit", async () => {
+ it("denies a pending request", async () => {
const res = await POST({} as any, ctx)
expect(res.status).toBe(200)
const body = await res.json()
@@ -75,6 +68,5 @@ describe("POST /api/community/bots/[id]/approval-requests/[requestId]/deny", ()
"req_1",
"denied",
)
- expect(mockLogAudit).toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts
index 8ed45797c..5a01d37c7 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts
@@ -2,11 +2,10 @@ import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
/**
* Deny a pending bot approval request. No side effects beyond flipping the
- * row to `denied` and writing an audit row. The requester is NOT notified —
+ * row to `denied`. The requester is NOT notified —
* they must observe the outcome indirectly (their earlier "Request sent"
* remains, but no accept event ever arrives).
*/
@@ -32,18 +31,6 @@ export const POST = withAuth(async (_req, ctx) => {
await queries.communityBot.resolveApprovalRequest(db, requestId, "denied")
- logAudit(db, {
- serverId: request.serverId ?? null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_JOIN_DENIED,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({
- botId,
- requestedByUserId: request.requestedByUserId,
- serverId: request.serverId ?? undefined,
- }),
- })
return writeJSON({ status: "denied", kind: request.kind })
})
diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.ts
index 1ea2bc4ec..30800619d 100644
--- a/src/web/src/app/api/community/bots/[id]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts
@@ -11,7 +11,6 @@ const mockGetUserPublic = vi.fn()
const mockPushBotEventToMachine = vi.fn()
const mockPushAgentModelSwitchToMachine = vi.fn()
const mockPushAgentProviderSwitchToMachine = vi.fn()
-const mockLogAudit = vi.fn()
const mockLogError = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
@@ -59,10 +58,6 @@ vi.mock("@/lib/broadcast", () => ({
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: vi.fn(),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: any, ctx?: any) => {
@@ -313,15 +308,11 @@ describe("PATCH /api/community/bots/[id]", () => {
expect(mockUpdateBotModel).toHaveBeenCalledWith(expect.anything(), "b1", "u1", null)
})
- it("name AND model changed: both bot:updated and model_switch pushed; fields include both", async () => {
+ it("name AND model changed: both bot:updated and model_switch are pushed", async () => {
const res = await PATCH(patchReq({ name: "New", model: "claude-sonnet-4-6" }), ctx)
expect(res.status).toBe(200)
expect(mockPushBotEventToMachine).toHaveBeenCalledWith(expect.anything(), "mac1", expect.objectContaining({ type: "bot:updated" }))
expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalled()
- const auditCall = mockLogAudit.mock.calls.at(-1)?.[1] as { changes: string }
- const fields = JSON.parse(auditCall.changes).fields as string[]
- expect(fields).toContain("name")
- expect(fields).toContain("model")
})
it("model on an antigravity bot → 400", async () => {
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index 619fb8baf..878f8bb25 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -14,7 +14,6 @@ import {
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
import {
pushBotEventToMachine,
pushAgentModelSwitchToMachine,
@@ -157,21 +156,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
}
}
- const changedFields: string[] = []
- if (body.name !== undefined) changedFields.push("name")
- if (body.description !== undefined) changedFields.push("description")
- if (body.image !== undefined) changedFields.push("image")
- if (runtimeChanged) changedFields.push("runtime")
- if (modelChanged) changedFields.push("model")
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_UPDATED,
- targetType: "user",
- targetId: id,
- changes: JSON.stringify({ botId: id, fields: changedFields }),
- })
-
return writeJSON({
bot: {
id,
@@ -215,14 +199,6 @@ export const DELETE = withAuth(async (_req, ctx) => {
})
}
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_DELETED,
- targetType: "user",
- targetId: id,
- changes: JSON.stringify({ botId: id }),
- })
if (before.machineId) {
await pushBotEventToMachine(ctx.env, before.machineId, {
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index ec4008023..37ca75c21 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -6,9 +6,9 @@ const mockGetMachineForOwner = vi.fn()
const mockCreateBot = vi.fn()
const mockGetUserPublic = vi.fn()
const mockPushBotEventToMachine = vi.fn()
-const mockLogAudit = vi.fn()
const mockListBotsForOwner = vi.fn()
const mockGetBotDailyActivityForOwner = vi.fn()
+const mockEnsureSiblingBotFriendship = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -28,6 +28,9 @@ vi.mock("@alook/shared", async () => {
listBotsForOwner: (...a: unknown[]) => mockListBotsForOwner(...a),
getBotDailyActivityForOwner: (...a: unknown[]) => mockGetBotDailyActivityForOwner(...a),
},
+ communityFriendship: {
+ ensureSiblingBotFriendship: (...a: unknown[]) => mockEnsureSiblingBotFriendship(...a),
+ },
user: {
getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),
},
@@ -38,10 +41,6 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/bot-push", () => ({
pushBotEventToMachine: (...a: unknown[]) => mockPushBotEventToMachine(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: any, ctx?: any) => {
@@ -93,6 +92,8 @@ describe("POST /api/community/bots — model", () => {
})
mockCreateBot.mockResolvedValue({ botId: "b1", name: "MyBot", discriminator: "0001", description: "", image: null })
mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })
+ mockListBotsForOwner.mockResolvedValue([{ id: "b1" }])
+ mockEnsureSiblingBotFriendship.mockResolvedValue({ blocked: false })
})
it("persists model_name and returns it in the 201 body", async () => {
@@ -117,6 +118,29 @@ describe("POST /api/community/bots — model", () => {
)
})
+ it("keeps same-owner sibling auto-friendship after removing server audit writes", async () => {
+ mockListBotsForOwner.mockResolvedValue([{ id: "b1" }, { id: "b2" }])
+
+ const res = await POST(postReq(base()), ctx)
+
+ expect(res.status).toBe(201)
+ expect(mockEnsureSiblingBotFriendship).toHaveBeenCalledOnce()
+ expect(mockEnsureSiblingBotFriendship).toHaveBeenCalledWith(
+ expect.anything(),
+ { botA: "b1", botB: "b2" },
+ )
+ })
+
+ it("still returns 201 when sibling auto-friendship fails", async () => {
+ mockListBotsForOwner.mockResolvedValue([{ id: "b1" }, { id: "b2" }])
+ mockEnsureSiblingBotFriendship.mockRejectedValue(new Error("D1 unavailable"))
+
+ const res = await POST(postReq(base()), ctx)
+
+ expect(res.status).toBe(201)
+ expect(mockPushBotEventToMachine).toHaveBeenCalledOnce()
+ })
+
it("rejects a model on runtime antigravity with 400", async () => {
const res = await POST(postReq(base("some-model", "antigravity")), ctx)
expect(res.status).toBe(400)
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index 0dc396bba..a6e04d61f 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -9,7 +9,6 @@ import {
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
import { pushBotEventToMachine } from "@/lib/community/bot-push"
export const GET = withAuth(async (_req, ctx) => {
@@ -100,7 +99,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
// Same-owner sibling auto-friendship fanout. After createBot commits, insert a
// real accepted community_friendship row for every existing live sibling.
// Idempotent (ON CONFLICT DO NOTHING) so a concurrent createBot race is
- // absorbed. A per-sibling failure is logged but never fails createBot — the
+ // absorbed. A per-sibling failure never fails createBot — the
// bot exists and is usable; siblings can reconcile via the CLI later. See
// plans/agent-friendship-approval-gate.md §Bot creation.
try {
@@ -108,39 +107,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
for (const sibling of siblings) {
if (sibling.id === created.botId) continue
try {
- const res = await queries.communityFriendship.ensureSiblingBotFriendship(db, {
+ await queries.communityFriendship.ensureSiblingBotFriendship(db, {
botA: created.botId,
botB: sibling.id,
})
- if (res.blocked) {
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_SIBLING_FRIENDSHIP_BACKFILL_FAILED,
- targetType: "user",
- targetId: created.botId,
- changes: JSON.stringify({
- newBotId: created.botId,
- ownerId: ctx.userId,
- siblingId: sibling.id,
- reason: "blocked",
- }),
- })
- }
} catch (err) {
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_SIBLING_FRIENDSHIP_BACKFILL_FAILED,
- targetType: "user",
- targetId: created.botId,
- changes: JSON.stringify({
- newBotId: created.botId,
- ownerId: ctx.userId,
- siblingId: sibling.id,
- error: err instanceof Error ? err.message : String(err),
- }),
- })
+ void err
}
}
} catch {
@@ -148,21 +120,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
// via the CLI. Nothing user-visible to fail here.
}
- // Audit — no serverId context (bot is created out-of-server). Queryable
- // via idx_audit_log_actor_created.
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_CREATED,
- targetType: "user",
- targetId: created.botId,
- changes: JSON.stringify({
- botId: created.botId,
- machineId: body.machineId,
- runtime: body.runtime,
- }),
- })
-
// Best-effort WS push — daemon may be offline. Cold-start warmup re-syncs
// authoritative state on reconnect.
await pushBotEventToMachine(ctx.env, body.machineId, {
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
index dd63dcd2c..fb90dcef9 100644
--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
@@ -9,7 +9,6 @@ const mockResolveChannelAccessContext = vi.fn()
const mockDeleteChannelMemberAndChildParticipants = vi.fn()
const mockGetPrivateChannelAudienceUserIds = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
-const mockLogAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -31,10 +30,6 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/fanout", () => ({
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
index 4016bd564..f5f92d94d 100644
--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
@@ -4,7 +4,6 @@ import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, WS_EVENTS, isThread } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-import { logAudit } from "@/lib/community/audit"
import { requireChannelAccess } from "@/lib/community/permissions"
/**
@@ -56,14 +55,6 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
[...new Set([...recipients, targetUserId])].map((uid) => broadcastToUserSafe(uid, event))
)
- logAudit(db, {
- serverId: channel.serverId,
- actorId: ctx.userId,
- action: "channel_member_remove",
- targetType: "channel",
- targetId: channelId,
- changes: JSON.stringify({ userId: targetUserId }),
- })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/channels/[id]/members/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/route.test.ts
index 5d98cd32d..c3fc25a51 100644
--- a/src/web/src/app/api/community/channels/[id]/members/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/route.test.ts
@@ -14,7 +14,6 @@ const mockGetUsersByIds = vi.fn()
const mockResolveScopeMembers = vi.fn()
const mockGetMembersByUserIds = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
-const mockLogAudit = vi.fn()
const mockAddThreadParticipants = vi.fn()
const mockListThreadParticipants = vi.fn()
const mockListThreadParticipantUserIds = vi.fn()
@@ -72,10 +71,6 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/fanout", () => ({
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
// Dual-actor: crk_ bearer → bot (folded channelMember), else human.
vi.mock("@/lib/middleware/community-actor", () => ({
diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.ts
index a73446fc0..2f3b2f3d7 100644
--- a/src/web/src/app/api/community/channels/[id]/members/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts
@@ -14,7 +14,6 @@ import {
} from "@alook/shared"
import type { CommunityCliServerMember as ServerMember } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-import { logAudit } from "@/lib/community/audit"
import { requireChannelAccess } from "@/lib/community/permissions"
import { resolveTargetForMember } from "@/lib/community/resolve-ref"
import { mapMemberForApi } from "@/lib/community/member-payload"
@@ -179,14 +178,6 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
const recipients = await queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId)
await Promise.all([...new Set([...recipients, targetUserId])].map((uid) => broadcastToUserSafe(uid, event)))
- logAudit(db, {
- serverId: channel.serverId,
- actorId: userId,
- action: "channel_member_add",
- targetType: "channel",
- targetId: channelId,
- changes: JSON.stringify({ userId: targetUserId }),
- })
return writeJSON({ ok: true }, 201)
})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index 5303ab9c0..2f6a48608 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -221,8 +221,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
// first to dispatch by surface; default = the same text channel.
mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })
mockCreateMessage.mockResolvedValue({ id: "m1" })
- // Human author by default — `createCommunityMessage`'s bot-authored audit
- // (plan §10) only fires when `isBot === true`, which none of these tests exercise.
+ // Human author by default.
mockGetUserInternal.mockResolvedValue({ isBot: false, deletedAt: null })
mockGetMessage.mockResolvedValue({
id: "m1",
diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts
index 23fea9678..9ddc7792f 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts
@@ -8,7 +8,6 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetChannel = vi.fn();
const mockGetMember = vi.fn();
const mockUnpinMessage = vi.fn();
-const mockLogAction = vi.fn();
const mockFanOut = vi.fn();
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
@@ -25,9 +24,6 @@ vi.mock("@alook/shared", async () => {
};
});
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAction(...a),
-}));
vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOut(...a),
diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
index 129055619..735cd18e9 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
@@ -6,7 +6,6 @@ import { queries, WS_EVENTS } from "@alook/shared"
import { fanOutToChannel } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
import { requirePinnableSurface } from "@/lib/community/channel-write-guard"
-import { logAudit } from "@/lib/community/audit"
export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
@@ -33,13 +32,6 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
messageId,
}, { excludeUserId: ctx.userId })
- logAudit(db, {
- serverId: channel.serverId,
- actorId: ctx.userId,
- action: "pin_remove",
- targetType: "message",
- targetId: messageId,
- })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
index 5c7e582ca..ec34ff54e 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
@@ -11,7 +11,6 @@ const mockGetMember = vi.fn();
const mockGetMessage = vi.fn();
const mockPinMessage = vi.fn();
const mockListPins = vi.fn();
-const mockLogAction = vi.fn();
const mockFanOut = vi.fn();
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
@@ -32,14 +31,10 @@ vi.mock("@alook/shared", async () => {
pinMessage: (...a: unknown[]) => mockPinMessage(...a),
listPins: (...a: unknown[]) => mockListPins(...a),
},
- communityAuditLog: { logAction: (...a: unknown[]) => mockLogAction(...a) },
},
};
});
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAction(...a),
-}));
vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOut(...a),
@@ -85,7 +80,6 @@ describe("POST /api/community/channels/[id]/pins", () => {
mockGetMember.mockResolvedValue({ userId: "u1", role: "admin" });
mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" });
mockFanOut.mockResolvedValue(undefined);
- mockLogAction.mockResolvedValue(undefined);
});
it("pins a message and returns 201", async () => {
diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.ts b/src/web/src/app/api/community/channels/[id]/pins/route.ts
index 735b98604..87e33e488 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/route.ts
@@ -6,7 +6,6 @@ import { queries, isUniqueConstraintError, WS_EVENTS } from "@alook/shared"
import { fanOutToChannel } from "@/lib/community/fanout"
import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"
import { requirePinnableSurface } from "@/lib/community/channel-write-guard"
-import { logAudit } from "@/lib/community/audit"
import { avatarInitial } from "@/lib/community/avatar"
export const GET = withAuth(async (_req: NextRequest, ctx) => {
@@ -87,13 +86,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
messageId: body.messageId,
}, { excludeUserId: ctx.userId })
- logAudit(db, {
- serverId: channel.serverId,
- actorId: ctx.userId,
- action: "pin_add",
- targetType: "message",
- targetId: body.messageId,
- })
return writeJSON(pin, 201)
})
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
index 9d44830ad..7c65f4a4f 100644
--- a/src/web/src/app/api/community/channels/[id]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -17,7 +17,6 @@ const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])
const mockFanOutToServerMembers = vi.fn()
const mockFanOutToChannel = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
-const mockLogAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -46,10 +45,6 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.ts
index e8e814c61..f74875155 100644
--- a/src/web/src/app/api/community/channels/[id]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.ts
@@ -14,7 +14,6 @@ import {
slugify,
} from "@alook/shared"
import { fanOutToServerMembers, fanOutToChannel, broadcastToUserSafe } from "@/lib/community/fanout"
-import { logAudit } from "@/lib/community/audit"
import { requireChannelAccess, requireChannelMember } from "@/lib/community/permissions"
/**
@@ -136,14 +135,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
})
}
- logAudit(db, {
- serverId: channel.serverId,
- actorId: ctx.userId,
- action: "channel_update",
- targetType: "channel",
- targetId: channelId,
- changes: JSON.stringify(changes),
- })
return writeJSON(updated)
})
@@ -198,13 +189,6 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
await fanOutToServerMembers(channel.serverId, event)
}
- logAudit(db, {
- serverId: channel.serverId,
- actorId: ctx.userId,
- action: "channel_delete",
- targetType: "channel",
- targetId: channelId,
- })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
index a294bb8ea..76cdfda4e 100644
--- a/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
+++ b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
@@ -14,7 +14,6 @@ const removeFriend = vi.fn()
const cancelPendingRequest = vi.fn()
const getUserInternal = vi.fn()
const broadcastToUserSafe = vi.fn()
-const logAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -35,10 +34,6 @@ vi.mock("@alook/shared", async () => {
}
})
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => logAudit(...a),
- COMMUNITY_AUDIT_ACTIONS: { BOT_FRIEND_CANCELLED: "community.bot.friend_cancelled" },
-}))
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
@@ -140,7 +135,7 @@ describe("DELETE — one path per role", () => {
expect(cancelPendingRequest).not.toHaveBeenCalled()
})
- it("requester cancels a gated pending request → soft-cancel + rehydrate owner's card + audit", async () => {
+ it("requester cancels a gated pending request → soft-cancel + rehydrate owner's card", async () => {
// Human→bot request gated on the bot's owner: an actionable Approve/Deny
// card is sitting in the owner's DM. Withdrawing must flip that card, not
// orphan it. See plans/friend-cancel-card-cleanup.md.
@@ -159,9 +154,6 @@ describe("DELETE — one path per role", () => {
expect(removeFriend).not.toHaveBeenCalled()
// Owner's card rehydrates; the bot (no session) gets nothing.
expect(broadcastToUserSafe).toHaveBeenCalledWith("owner_carol", expect.objectContaining({ type: "community:dm.message_updated" }))
- expect(logAudit).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
- action: "community.bot.friend_cancelled", actorId: "u_alice", targetId: "fr_1",
- }))
})
it("the bot's owner cancels a pending row their bot created → soft-cancel", async () => {
@@ -188,7 +180,7 @@ describe("DELETE — one path per role", () => {
expect(broadcastToUserSafe).toHaveBeenCalledWith("u_zoe", expect.objectContaining({ friendshipId: "fr_1" }))
})
- it("cancelPendingRequest no-ops (row already gone) → still 204, no broadcast/audit", async () => {
+ it("cancelPendingRequest no-ops (row already gone) → still 204 with no broadcast", async () => {
getFriendship.mockResolvedValue({
id: "fr_1", requesterId: "u_alice", addresseeId: "bot_yara", status: "pending", needsOwnerApproval: "owner_carol",
})
@@ -196,7 +188,6 @@ describe("DELETE — one path per role", () => {
const res = await deleteFriend(reqAs("u_alice"), ctx)
expect(res.status).toBe(204)
expect(broadcastToUserSafe).not.toHaveBeenCalled()
- expect(logAudit).not.toHaveBeenCalled()
})
it("target-owner may NOT DELETE an inbound pending (uses owner-decision) → 403", async () => {
diff --git a/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts b/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
index 12cb6e8ad..ecc2e78aa 100644
--- a/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
+++ b/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
@@ -3,7 +3,6 @@ import { NextRequest } from "next/server"
const mockOwnerDecideOnRow = vi.fn()
const mockBroadcastToUser = vi.fn(async () => undefined)
-const mockLogAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -20,10 +19,6 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/broadcast", () => ({
broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
@@ -60,7 +55,7 @@ describe("POST /api/community/friends/[id]/owner-decision", () => {
expect(mockOwnerDecideOnRow).not.toHaveBeenCalled()
})
- it("approve: relays broadcasts and writes an audit row", async () => {
+ it("approve: relays broadcasts and returns accepted status", async () => {
mockOwnerDecideOnRow.mockResolvedValue({
ok: true,
friendship: { id: "fr_1", status: "accepted" },
@@ -69,7 +64,6 @@ describe("POST /api/community/friends/[id]/owner-decision", () => {
const res = await POST(req({ decision: "approve" }), ctx)
expect(res.status).toBe(200)
expect(mockBroadcastToUser).toHaveBeenCalledWith("u_alice", expect.objectContaining({ type: "community:friend.accept" }))
- expect(mockLogAudit).toHaveBeenCalled()
})
it("deny: single-owner broadcast, denied status", async () => {
diff --git a/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
index 337f4ef20..d94129ed7 100644
--- a/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
@@ -4,7 +4,6 @@ import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
/**
* POST /api/community/friends/[id]/owner-decision — body `{ decision }`. The
@@ -45,17 +44,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
await broadcastToUserSafe(b.userId, b.event)
}
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action:
- body.decision === "approve"
- ? COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_APPROVED_BY_OWNER
- : COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_DENIED_BY_OWNER,
- targetType: "friendship",
- targetId: id,
- changes: JSON.stringify({ friendshipId: id, decision: body.decision }),
- })
return writeJSON({ status: result.friendship.status, friendshipId: id })
})
diff --git a/src/web/src/app/api/community/friends/[id]/route.ts b/src/web/src/app/api/community/friends/[id]/route.ts
index 5227839c7..82de0d3cb 100644
--- a/src/web/src/app/api/community/friends/[id]/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/route.ts
@@ -4,7 +4,6 @@ import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
export const DELETE = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
@@ -54,13 +53,6 @@ export const DELETE = withAuth(async (_req, ctx) => {
const { row, broadcasts } = await queries.communityFriendship.cancelPendingRequest(db, id)
if (row) {
for (const b of broadcasts) broadcastToUserSafe(b.userId, b.event)
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_CANCELLED,
- targetType: "friendship",
- targetId: id,
- })
}
return new NextResponse(null, { status: 204 })
}
diff --git a/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
index 6ab2d0e5e..a9202ed9d 100644
--- a/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
+++ b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
@@ -54,10 +54,6 @@ vi.mock("@/lib/middleware/helpers", async () => {
vi.mock("@/lib/community/fanout", () => ({ broadcastToUserSafe: vi.fn() }))
vi.mock("@/lib/community/permissions", () => ({ requireNotBlocked: vi.fn(async () => ({ ok: true })) }))
-vi.mock("@/lib/community/audit", () => ({
- logAudit: vi.fn(),
- COMMUNITY_AUDIT_ACTIONS: new Proxy({}, { get: (_t, p) => String(p) }),
-}))
import { POST as requestPost } from "./request/route"
import { POST as acceptPost } from "./[id]/accept/route"
diff --git a/src/web/src/app/api/community/friends/request/route.test.ts b/src/web/src/app/api/community/friends/request/route.test.ts
index ce4ea2548..898793a2b 100644
--- a/src/web/src/app/api/community/friends/request/route.test.ts
+++ b/src/web/src/app/api/community/friends/request/route.test.ts
@@ -9,7 +9,6 @@ const isBlocked = vi.fn()
const sendRequest = vi.fn()
const ensureSiblingBotFriendship = vi.fn()
const broadcastToUser = vi.fn()
-const mockLogAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -63,10 +62,6 @@ vi.mock("@/lib/broadcast", () => ({
broadcastToUser: (...a: unknown[]) => broadcastToUser(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
import { POST } from "./route"
diff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.ts
index 1667aa86f..3998b31cc 100644
--- a/src/web/src/app/api/community/friends/request/route.ts
+++ b/src/web/src/app/api/community/friends/request/route.ts
@@ -11,7 +11,6 @@ import type { BotActor, CommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { requireNotBlocked } from "@/lib/community/permissions"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
/**
* POST /api/community/friends/request — the friend-request door (route/disc
@@ -28,8 +27,8 @@ import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
* is the main gate; isBot→403 is the last-line backstop. BOTH stay.
* - bot → handleBotFriendRequest: {username} (name#tag only), sibling-bot
* auto-accept, ALWAYS owner-gated (needsOwnerApproval, never dropped), lean
- * {friendshipId,status,hint} response, audit BOT_FRIEND_REQUESTED/
- * SUPERSEDED. Folds the flat /friendRequest bot verb (flat verb deleted at
+ * {friendshipId,status,hint} response. Folds the flat /friendRequest bot
+ * verb (flat verb deleted at
* the flat-delete step). Self-scoped: requesterId = the credential's
* botUserId, never a body field.
*/
@@ -105,16 +104,6 @@ async function handleHumanFriendRequest(
for (const b of result.broadcasts) {
await broadcastToUserSafe(b.userId, b.event)
}
- for (const supersededId of result.supersededIds) {
- logAudit(db, {
- serverId: null,
- actorId: actor.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,
- targetType: "friendship",
- targetId: supersededId,
- changes: JSON.stringify({ supersededBy: result.friendship.id }),
- })
- }
if (result.kind === "auto_accepted") {
return writeJSON(result.friendship, 200)
}
@@ -220,25 +209,6 @@ async function handleBotFriendRequest(
await broadcastToUserSafe(b.userId, b.event)
}
- logAudit(db, {
- serverId: null,
- actorId: botUserId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUESTED,
- targetType: "user",
- targetId: target.id,
- changes: JSON.stringify({ requesterBotId: botUserId, addresseeId: target.id }),
- })
- for (const supersededId of result.supersededIds) {
- logAudit(db, {
- serverId: null,
- actorId: botUserId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,
- targetType: "friendship",
- targetId: supersededId,
- changes: JSON.stringify({ supersededBy: result.friendship.id }),
- })
- }
-
// Bot-origin sendRequest always sets needsOwnerApproval, so this is always
// the pending variant. Resolve the owner's display name for the hint copy.
const owner = await queries.user.getUserPublic(db, ownerUserId)
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
index 44a38d318..c17321549 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
@@ -24,7 +24,6 @@ const mockUseInvite = vi.fn()
const mockGetServer = vi.fn()
const mockFanOutToServerMembers = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
-const mockLogAudit = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -48,13 +47,6 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return {
- ...actual,
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
- }
-})
import { POST } from "./route"
import { isUniqueConstraintError } from "@alook/shared"
@@ -124,7 +116,7 @@ describe("POST /api/community/invites/[token]/join — bot path", () => {
expect((await res.json()).error).toBe("Already a member")
})
- it("200 superset {member, serverId, server} on success; fanOutToServerMembers excludes the bot; logAudit uses BOT_JOINED_VIA_INVITE + botUserId", async () => {
+ it("returns the server superset and excludes the bot from server fan-out", async () => {
mockGetInviteByToken.mockResolvedValue({ id: "inv_1", serverId: "srv_1", createdBy: "owner_1" })
mockUseInvite.mockResolvedValue({
invite: { id: "inv_1", serverId: "srv_1" },
@@ -153,14 +145,5 @@ describe("POST /api/community/invites/[token]/join — bot path", () => {
"owner_1",
expect.objectContaining({ serverId: "srv_1" }),
)
- expect(mockLogAudit).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- action: "community.bot.joined_via_invite",
- actorId: "bot_1",
- targetType: "invite",
- targetId: "inv_1",
- }),
- )
})
})
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
index 0981235fa..d2d91257c 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
@@ -3,15 +3,11 @@ import { NextRequest } from "next/server"
const mockUseInvite = vi.fn()
const mockFanOut = vi.fn().mockResolvedValue(undefined)
-const mockLogAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
}))
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
-}))
vi.mock("@/lib/middleware/auth", async () => {
return {
@@ -57,7 +53,6 @@ async function callPOST(token: string) {
beforeEach(() => {
mockUseInvite.mockReset()
mockFanOut.mockReset()
- mockLogAudit.mockReset()
mockFanOut.mockResolvedValue(undefined)
})
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.ts
index 001f0269b..0997771a2 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts
@@ -4,18 +4,16 @@ import { queries, ROLES, WS_EVENTS, isUniqueConstraintError } from "@alook/share
import type { CommunityMemberJoin } from "@alook/shared"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
/**
* POST /api/community/invites/[token]/join — the unified join route (plan §4
* FOLD, §9 phase 4). Serves both a human (session/al_) and a bot (crk_) via
* `withCommunityActor`; the old /agent/joinServer folds in here (batch1
- * cab6c3e7 did the same fold). Only three things branch on `actor.kind`:
+ * cab6c3e7 did the same fold). Two things branch on `actor.kind`:
* 1. owner-gate — a bot may only consume an invite created by ITS OWN owner
* (checked BEFORE useInvite, so a foreign/dead-creator invite is never
* consumed by a rejected attempt); a human joins any valid invite.
- * 2. audit action — BOT_JOINED_VIA_INVITE vs member_join.
- * 3. owner broadcast — the bot's owner isn't necessarily a member of the
+ * 2. owner broadcast — the bot's owner isn't necessarily a member of the
* joined server, so fanOutToServerMembers won't reach them; send the
* MEMBER_JOIN directly (dedup-safe on re-delivery).
* Response is a superset (Fork C): `{ member, serverId, server }` — the human
@@ -63,13 +61,6 @@ export const POST = withCommunityActor(async (_req, ctx) => {
return writeError("Invalid or expired invite", 400)
}
- logAudit(db, {
- serverId: result.invite.serverId,
- actorId: actor.userId,
- action: actor.kind === "bot" ? COMMUNITY_AUDIT_ACTIONS.BOT_JOINED_VIA_INVITE : "member_join",
- targetType: "invite",
- targetId: result.invite.id,
- })
const memberEvent: CommunityMemberJoin = {
type: WS_EVENTS.MEMBER_JOIN,
diff --git a/src/web/src/app/api/community/invites/[token]/route.ts b/src/web/src/app/api/community/invites/[token]/route.ts
index aa027c656..31241a44b 100644
--- a/src/web/src/app/api/community/invites/[token]/route.ts
+++ b/src/web/src/app/api/community/invites/[token]/route.ts
@@ -2,7 +2,6 @@ import { withAuth } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries } from "@alook/shared"
-import { logAudit } from "@/lib/community/audit"
import { requireServerAdmin } from "@/lib/community/permissions"
export const DELETE = withAuth(async (_req, ctx) => {
@@ -19,13 +18,6 @@ export const DELETE = withAuth(async (_req, ctx) => {
await queries.communityInvite.revokeInvite(db, invite.id)
- logAudit(db, {
- serverId: invite.serverId,
- actorId: ctx.userId,
- action: "invite_delete",
- targetType: "invite",
- targetId: invite.id,
- })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/servers/[id]/audit-log/route.ts b/src/web/src/app/api/community/servers/[id]/audit-log/route.ts
deleted file mode 100644
index a064f1856..000000000
--- a/src/web/src/app/api/community/servers/[id]/audit-log/route.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { NextRequest } from "next/server"
-import {
- queries,
- DEFAULT_AUDIT_LOG_PAGE_SIZE,
- MAX_AUDIT_LOG_PAGE_SIZE,
-} from "@alook/shared"
-import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
-import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { requireServerAdmin } from "@/lib/community/permissions"
-import { parseBoundedInt } from "@/lib/community/messages"
-
-export const GET = withAuth(async (req: NextRequest, ctx) => {
- const serverId = ctx.params?.id
- if (!serverId) return writeError("missing server id", 400)
-
- const db = getDb(ctx.env.DB)
- const auth = await requireServerAdmin(db, serverId, ctx.userId)
- if (!auth.ok) return writeError(auth.error, auth.status)
-
- const url = new URL(req.url)
- const action = url.searchParams.get("action") ?? undefined
- const before = url.searchParams.get("before") ?? undefined
- const limit = parseBoundedInt(
- url.searchParams.get("limit"),
- DEFAULT_AUDIT_LOG_PAGE_SIZE,
- MAX_AUDIT_LOG_PAGE_SIZE,
- )
-
- const logs = await queries.communityAuditLog.listAuditLog(db, serverId, {
- action,
- before,
- limit,
- })
-
- return writeJSON({ entries: logs })
-})
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts b/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
index 6e5e3fc6a..d6e4dc258 100644
--- a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
@@ -59,10 +59,6 @@ vi.mock("@/lib/community/fanout", () => ({
broadcastToUserSafe: vi.fn(),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: vi.fn() }
-})
const mockCreateCommunityMessage = vi.fn()
vi.mock("@/lib/community/message-handler", () => ({
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.ts
index 985238677..86dad2b66 100644
--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts
@@ -11,7 +11,6 @@ import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
import { createCommunityMessage } from "@/lib/community/message-handler"
const log = createLogger({ service: "community-bots-server-add" })
@@ -54,14 +53,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
userId: botId,
role: ROLES.MEMBER,
})
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_ADDED_TO_SERVER,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({ botId, serverId, kind: "owner_added" }),
- })
const bot = await queries.user.getUserSelf(db, botId)
const joinEvent: CommunityMemberJoin = {
type: WS_EVENTS.MEMBER_JOIN,
@@ -157,14 +148,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeJSON({ status: "pending" }, 200)
}
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_JOIN_REQUESTED,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({ botId, serverId, requestedByUserId: ctx.userId }),
- })
// Fan-out the DM to the owner so their DM view updates. DMs are channels
// now — key the MESSAGE_CREATE by the DM's channel id.
diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts
index 67c9d9f14..3c7a1c58d 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts
@@ -11,7 +11,6 @@ const mockUpdateCategory = vi.fn()
const mockDeleteCategory = vi.fn()
const mockHasChannels = vi.fn()
const mockFanOut = vi.fn()
-const mockLogAudit = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -35,10 +34,6 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
}))
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
@@ -77,7 +72,6 @@ describe("PATCH /api/community/servers/[id]/categories/[catId] — unique name",
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", creatorId: "u1" })
mockFanOut.mockResolvedValue(undefined)
- mockLogAudit.mockResolvedValue(undefined)
})
it("renames a category", async () => {
diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
index 1c3244b4a..d38b0be87 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
@@ -9,7 +9,6 @@ import {
WS_EVENTS,
} from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
-import { logAudit } from "@/lib/community/audit"
import { requireServerAdmin } from "@/lib/community/permissions"
export const PATCH = withAuth(async (req: NextRequest, ctx) => {
@@ -70,14 +69,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
changes,
})
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "category_update",
- targetType: "category",
- targetId: categoryId,
- changes: JSON.stringify(changes),
- })
return writeJSON(updated)
})
@@ -112,13 +103,6 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
categoryId,
})
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "category_delete",
- targetType: "category",
- targetId: categoryId,
- })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
index 815280e33..f23b61e98 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
@@ -3,7 +3,6 @@ import { NextRequest } from "next/server"
const mockGetMember = vi.fn()
const mockCreateCategory = vi.fn()
-const mockLogAction = vi.fn()
const mockFanOut = vi.fn()
const mockFindMany = vi.fn()
@@ -22,9 +21,6 @@ vi.mock("@alook/shared", async () => {
communityCategory: {
createCategory: (...a: unknown[]) => mockCreateCategory(...a),
},
- communityAuditLog: {
- logAction: (...a: unknown[]) => mockLogAction(...a),
- },
},
}
})
@@ -75,7 +71,6 @@ describe("POST /api/community/servers/[id]/categories", () => {
// Category creation is admin/owner-only in the permission model.
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
mockFanOut.mockResolvedValue(undefined)
- mockLogAction.mockResolvedValue(undefined)
})
it("creates a category", async () => {
diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.ts b/src/web/src/app/api/community/servers/[id]/categories/route.ts
index 4bfb268d9..12310cd30 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/route.ts
@@ -9,7 +9,6 @@ import {
WS_EVENTS,
} from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
-import { logAudit } from "@/lib/community/audit"
import { requireServerAdmin, requireServerMember } from "@/lib/community/permissions"
export const GET = withAuth(async (_req: NextRequest, ctx) => {
@@ -79,13 +78,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
category,
})
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "category_create",
- targetType: "category",
- targetId: category.id,
- })
return writeJSON({ category }, 201)
})
diff --git a/src/web/src/app/api/community/servers/[id]/invites/route.test.ts b/src/web/src/app/api/community/servers/[id]/invites/route.test.ts
index 0749e73a2..cc2d64044 100644
--- a/src/web/src/app/api/community/servers/[id]/invites/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/invites/route.test.ts
@@ -7,9 +7,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetMember = vi.fn()
const mockCreateInvite = vi.fn()
-const mockLogAction = vi.fn()
const mockFanOut = vi.fn()
-const mockWarn = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -17,20 +15,11 @@ vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
...actual,
- createLogger: () => ({
- info: vi.fn(),
- warn: (...a: unknown[]) => mockWarn(...a),
- error: vi.fn(),
- debug: vi.fn(),
- }),
queries: {
communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },
communityInvite: {
createInvite: (...a: unknown[]) => mockCreateInvite(...a),
},
- communityAuditLog: {
- logAction: (...a: unknown[]) => mockLogAction(...a),
- },
},
}
})
@@ -80,10 +69,9 @@ describe("POST /api/community/servers/[id]/invites", () => {
createdAt: "2026-07-02T00:00:00.000Z",
})
mockFanOut.mockResolvedValue(undefined)
- mockLogAction.mockResolvedValue(undefined)
})
- it("returns 201 with the invite and calls audit log", async () => {
+ it("returns 201 with the invite", async () => {
const res = await POST(postReq({}), ctx)
expect(res.status).toBe(201)
@@ -97,14 +85,6 @@ describe("POST /api/community/servers/[id]/invites", () => {
maxActive: 50,
})
- expect(mockLogAction).toHaveBeenCalledTimes(1)
- expect(mockLogAction).toHaveBeenCalledWith(expect.anything(), {
- serverId: "s1",
- actorId: "u1",
- action: "invite_create",
- targetType: "invite",
- targetId: "inv_1",
- })
})
it("returns 409 when the atomic insert reports the active invite cap", async () => {
@@ -113,32 +93,9 @@ describe("POST /api/community/servers/[id]/invites", () => {
const res = await POST(postReq({}), ctx)
expect(res.status).toBe(409)
- expect(mockLogAction).not.toHaveBeenCalled()
expect(mockFanOut).not.toHaveBeenCalled()
})
- it("still returns 201 when the audit write rejects (regression for the awaited outlier)", async () => {
- // Before the fix this call was `await queries.communityAuditLog.logAction(...)`
- // and would 500 the request. logAudit is fire-and-forget — the response
- // must succeed and the failure lands in log.warn.
- mockLogAction.mockRejectedValue(new Error("audit db offline"))
-
- const res = await POST(postReq({}), ctx)
-
- expect(res.status).toBe(201)
- // Flush the microtask queue so logAudit's `.catch` runs.
- await new Promise((r) => setTimeout(r, 0))
- expect(mockWarn).toHaveBeenCalledWith(
- "audit_write_failed",
- expect.objectContaining({
- action: "invite_create",
- serverId: "s1",
- targetType: "invite",
- targetId: "inv_1",
- }),
- )
- })
-
it("still returns 201 when fan-out rejects (route calls helper without await/.catch)", async () => {
// The fan-out helper's contract is to never reject; but even if it did,
// the route treats it as fire-and-forget so the response is unaffected.
diff --git a/src/web/src/app/api/community/servers/[id]/invites/route.ts b/src/web/src/app/api/community/servers/[id]/invites/route.ts
index ae38cc78e..eff0a076a 100644
--- a/src/web/src/app/api/community/servers/[id]/invites/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/invites/route.ts
@@ -11,7 +11,6 @@ import {
} from "@alook/shared"
import type { CommunityInviteCreate } from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
-import { logAudit } from "@/lib/community/audit"
import { requireServerMember } from "@/lib/community/permissions"
export const GET = withAuth(async (_req, ctx) => {
@@ -86,13 +85,6 @@ export const POST = withAuth(async (req, ctx) => {
)
}
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "invite_create",
- targetType: "invite",
- targetId: invite.id,
- })
const event: CommunityInviteCreate = {
type: WS_EVENTS.INVITE_CREATE,
diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts b/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
index cba49f33e..6588497f8 100644
--- a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
@@ -8,7 +8,6 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetMember = vi.fn()
const mockRemoveMemberAndOwnerBots = vi.fn()
const mockListOwnerBotsInServer = vi.fn()
-const mockLogAudit = vi.fn()
const mockFanOut = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
@@ -28,13 +27,6 @@ vi.mock("@alook/shared", async () => {
}
})
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return {
- ...actual,
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
- }
-})
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
@@ -76,35 +68,25 @@ describe("POST /api/community/servers/[id]/leave", () => {
mockBroadcastToUserSafe.mockResolvedValue(undefined)
})
- it("returns 204 and audits member_leave with the target member's id", async () => {
+ it("returns 204 after removing the member", async () => {
const res = await POST(postReq(), ctx)
expect(res.status).toBe(204)
- expect(mockLogAudit).toHaveBeenCalledTimes(1)
- expect(mockLogAudit).toHaveBeenCalledWith(expect.anything(), {
- serverId: "s1",
- actorId: "u1",
- action: "member_leave",
- targetType: "member",
- targetId: "mem_1",
- })
})
- it("returns 403 when the user is not a member (and does not audit)", async () => {
+ it("returns 403 when the user is not a member", async () => {
mockGetMember.mockResolvedValue(null)
const res = await POST(postReq(), ctx)
expect(res.status).toBe(403)
- expect(mockLogAudit).not.toHaveBeenCalled()
expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()
})
- it("returns 400 when the owner tries to leave (and does not audit)", async () => {
+ it("returns 400 when the owner tries to leave", async () => {
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
const res = await POST(postReq(), ctx)
expect(res.status).toBe(400)
- expect(mockLogAudit).not.toHaveBeenCalled()
expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()
})
diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.ts b/src/web/src/app/api/community/servers/[id]/leave/route.ts
index 7d19e8e59..edc0ef8ba 100644
--- a/src/web/src/app/api/community/servers/[id]/leave/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/leave/route.ts
@@ -3,7 +3,6 @@ import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import { queries, isServerOwner, WS_EVENTS } from "@alook/shared"
import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
import { requireServerMember } from "@/lib/community/permissions"
export const POST = withAuth(async (_req, ctx) => {
@@ -38,24 +37,6 @@ export const POST = withAuth(async (_req, ctx) => {
)
if (!removed) return writeError("member not found", 404)
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "member_leave",
- targetType: "member",
- targetId: member.id,
- })
- for (const botId of botIdsToCascade) {
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_REMOVED_FROM_SERVER,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({ botId, serverId, kind: "owner_left_cascade" }),
- })
- }
-
const viewerLeaveEvent = {
type: WS_EVENTS.MEMBER_LEAVE,
serverId,
diff --git a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts
index 544d75281..433efd4df 100644
--- a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts
@@ -15,7 +15,6 @@ const mockListMembers = vi.fn()
const mockUpdateRole = vi.fn()
const mockRemoveMemberAndOwnerBots = vi.fn()
const mockListOwnerBotsInServer = vi.fn()
-const mockLogAudit = vi.fn()
const mockFanOut = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
@@ -46,13 +45,6 @@ vi.mock("@alook/shared", async () => {
}
})
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return {
- ...actual,
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
- }
-})
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
@@ -132,7 +124,6 @@ describe("PATCH /api/community/servers/[id]/members/[memberId]", () => {
expect(mockListMembers).not.toHaveBeenCalled()
expect(mockUpdateRole).toHaveBeenCalledWith(expect.anything(), "mem_target", "admin")
- expect(mockLogAudit).toHaveBeenCalledTimes(1)
expect(mockFanOut).toHaveBeenCalledTimes(1)
})
@@ -211,7 +202,6 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {
"srv_1",
[],
)
- expect(mockLogAudit).toHaveBeenCalledTimes(1)
// Broadcast payload uses target.userId — proves the scoped helper's row
// is what the fan-out reads.
expect(mockFanOut).toHaveBeenCalledWith("srv_1", expect.objectContaining({ userId: "u_target" }))
diff --git a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts
index ed4bab50b..504bd387b 100644
--- a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts
@@ -11,7 +11,6 @@ import {
WS_EVENTS,
} from "@alook/shared"
import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
import { requireServerAdmin } from "@/lib/community/permissions"
export const PATCH = withAuth(async (req: NextRequest, ctx) => {
@@ -52,14 +51,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const updated = await queries.communityMember.updateRole(db, memberId, body.role)
if (!updated) return writeError("member not found", 404)
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "member_role_update",
- targetType: "member",
- targetId: memberId,
- changes: JSON.stringify({ role: body.role }),
- })
fanOutToServerMembers(serverId, {
type: WS_EVENTS.MEMBER_UPDATE,
@@ -120,29 +111,6 @@ export const DELETE = withAuth(async (_req, ctx) => {
)
if (!removed) return writeError("member not found", 404)
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: targetIsBot ? COMMUNITY_AUDIT_ACTIONS.BOT_REMOVED_FROM_SERVER : "member_kick",
- targetType: targetIsBot ? "user" : "member",
- targetId: targetIsBot ? target.userId : memberId,
- changes: JSON.stringify(
- targetIsBot
- ? { botId: target.userId, serverId, kind: "kicked" }
- : { userId: target.userId },
- ),
- })
- for (const botId of botIdsToCascade) {
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_REMOVED_FROM_SERVER,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({ botId, serverId, kind: "owner_left_cascade" }),
- })
- }
-
const targetLeaveEvent = {
type: WS_EVENTS.MEMBER_LEAVE,
serverId,
diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.ts
index adacb9d01..f0eb4ba2c 100644
--- a/src/web/src/app/api/community/servers/[id]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts
@@ -3,7 +3,6 @@ import { NextRequest } from "next/server"
const mockGetMember = vi.fn()
const mockUpdateServer = vi.fn()
-const mockLogAction = vi.fn()
const mockFanOut = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
@@ -23,9 +22,6 @@ vi.mock("@alook/shared", async () => {
communityServer: {
updateServer: (...a: unknown[]) => mockUpdateServer(...a),
},
- communityAuditLog: {
- logAction: (...a: unknown[]) => mockLogAction(...a),
- },
},
}
})
@@ -67,7 +63,6 @@ describe("PATCH /api/community/servers/[id]", () => {
vi.clearAllMocks()
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
mockFanOut.mockResolvedValue(undefined)
- mockLogAction.mockResolvedValue(undefined)
})
it("normalizes a spaced rename via slugify before calling updateServer", async () => {
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index 11b7d9679..673e87c52 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -11,7 +11,6 @@ import {
slugify,
} from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
-import { logAudit } from "@/lib/community/audit"
import { requireServerAdmin } from "@/lib/community/permissions"
export const PATCH = withAuth(async (req: NextRequest, ctx) => {
@@ -61,14 +60,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const updated = await queries.communityServer.updateServer(db, serverId, changes)
if (!updated) return writeError("server not found", 404)
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "server_update",
- targetType: "server",
- targetId: serverId,
- changes: JSON.stringify(changes),
- })
fanOutToServerMembers(serverId, {
type: WS_EVENTS.SERVER_UPDATE,
@@ -99,13 +90,6 @@ export const DELETE = withAuth(async (_req, ctx) => {
const deleted = await queries.communityServer.deleteServer(db, serverId)
if (!deleted) return writeError("server not found", 404)
- logAudit(db, {
- serverId,
- actorId: ctx.userId,
- action: "server_delete",
- targetType: "server",
- targetId: serverId,
- })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 207da9aeb..3e80581ac 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -91,15 +91,10 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
}),
[membersHook.members, onlineUserIds, currentUser.id, userStatuses],
)
- // Gate admin-only fetches on `isAdmin` so regular members don't fire
- // audit-log 403s and don't waste bandwidth on the invites feed they can't
- // see. `myMember` comes from the raw (not enriched) members list so this
- // stays stable across presence ticks.
+ // `myMember` comes from the raw (not enriched) members list so this stays
+ // stable across presence ticks.
const myMember = membersHook.members.find((m) => m.userId === currentUser.id)
const isAdmin = canManageServer(myMember?.role)
- // invites + audit-log are no longer fetched here (W-LAZY, necessity plan):
- // they're admin-only, low-frequency panel data, so ServerSettings fetches
- // them itself only when their tab opens — never eagerly on server entry.
const presence = usePresence(serverId)
const { online: initialOnline } = presence
const notifs = useNotificationSettings()
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 326ef7048..ff2bb57d1 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -25,7 +25,6 @@ export type SettingsSection =
| "members"
| "invites"
| "notifications"
- | "audit"
// ── Servers / rail ───────────────────────────────────────────────────────────
export type Server = {
@@ -295,13 +294,6 @@ export type InviteRow = {
}
-export type AuditEntry = {
- actor: string
- action: string
- target: string
- createdAt: string // ISO timestamp
-}
-
// ── Mentions / inbox ─────────────────────────────────────────────────────────
export type Mention = {
id: string
diff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsx
index 792785789..6a95d6e0a 100644
--- a/src/web/src/components/community/channel-sidebar.tsx
+++ b/src/web/src/components/community/channel-sidebar.tsx
@@ -1,7 +1,7 @@
"use client"
import { Fragment, memo, useRef, useState } from "react"
-import { Settings, Users, Link2, Bell, ScrollText, ChevronDown, UserPlus } from "lucide-react"
+import { Settings, Users, Link2, Bell, ChevronDown, UserPlus } from "lucide-react"
import {
DndContext, closestCenter, PointerSensor, useSensor, useSensors,
} from "@dnd-kit/core"
@@ -301,7 +301,6 @@ export const ChannelSidebar = memo(function ChannelSidebar({
<DropdownMenuItem onClick={() => onOpenSettings("members")}><Users className="size-4" /> Members</DropdownMenuItem>
<DropdownMenuItem onClick={() => onOpenSettings("invites")}><Link2 className="size-4" /> Invites</DropdownMenuItem>
<DropdownMenuItem onClick={() => onOpenSettings("notifications")}><Bell className="size-4" /> Notifications</DropdownMenuItem>
- <DropdownMenuItem onClick={() => onOpenSettings("audit")}><ScrollText className="size-4" /> Audit Log</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : (
diff --git a/src/web/src/components/community/server-audit-removal.contract.test.ts b/src/web/src/components/community/server-audit-removal.contract.test.ts
new file mode 100644
index 000000000..017f755b8
--- /dev/null
+++ b/src/web/src/components/community/server-audit-removal.contract.test.ts
@@ -0,0 +1,36 @@
+import { existsSync, readFileSync } from "node:fs"
+import { dirname, resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+import { describe, expect, it } from "vitest"
+
+const componentDirectory = dirname(fileURLToPath(import.meta.url))
+const webRoot = resolve(componentDirectory, "../../..")
+const repositoryRoot = resolve(webRoot, "../..")
+
+const readWeb = (path: string) => readFileSync(resolve(webRoot, path), "utf8")
+const readRepository = (path: string) => readFileSync(resolve(repositoryRoot, path), "utf8")
+
+describe("server audit removal contract", () => {
+ it("removes the server settings surface and client query", () => {
+ expect(readWeb("src/components/community/server-settings.tsx")).not.toContain("Audit Log")
+ expect(readWeb("src/components/community/channel-sidebar.tsx")).not.toContain("Audit Log")
+ expect(readWeb("src/components/community/_types.ts")).not.toContain('| "audit"')
+ expect(readWeb("src/hooks/community/use-server-panels.ts")).not.toContain("useAuditLog")
+ expect(readWeb("src/lib/query-keys.ts")).not.toContain("auditLog:")
+ })
+
+ it("removes the server API/query and drops only its table", () => {
+ expect(existsSync(resolve(webRoot, "src/app/api/community/servers/[id]/audit-log/route.ts"))).toBe(false)
+ expect(existsSync(resolve(repositoryRoot, "src/shared/src/db/queries/community/audit-log.ts"))).toBe(false)
+
+ const migration = readWeb("migrations/0084_drop_community_audit_log.sql")
+ expect(migration).toContain("DROP TABLE IF EXISTS community_audit_log")
+ expect(migration).not.toContain("community_bot_activity_event")
+ })
+
+ it("preserves the independent bot activity contract", () => {
+ expect(existsSync(resolve(webRoot, "src/app/api/community/bots/[id]/audit-log/route.ts"))).toBe(true)
+ expect(existsSync(resolve(repositoryRoot, "src/shared/src/db/queries/community/bot-audit-log.ts"))).toBe(true)
+ expect(readRepository("src/shared/src/db/community-schema.ts")).toContain("communityBotActivityEvent")
+ })
+})
diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsx
index a539551e4..e1412ea67 100644
--- a/src/web/src/components/community/server-settings.tsx
+++ b/src/web/src/components/community/server-settings.tsx
@@ -3,11 +3,11 @@
import { useEffect, useRef, useState } from "react"
import type { LucideIcon } from "lucide-react"
import { useVirtualizer } from "@tanstack/react-virtual"
-import { Settings, Users, Link2, Bell, ScrollText, Trash2, X, Shield, Search, Camera } from "lucide-react"
+import { Settings, Users, Link2, Bell, Trash2, X, Shield, Search, Camera } from "lucide-react"
import { NOTIF_LEVELS, notifLevelDisplay } from "@alook/shared"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { Button } from "@/components/ui/button"
-import { formatMessageTime, formatRelativeTime } from "./format-time"
+import { formatRelativeTime } from "./format-time"
import { Input } from "@/components/ui/input"
import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea"
import { Badge, badgeVariants } from "@/components/ui/badge"
@@ -20,9 +20,9 @@ import { avatarInitial } from "@/lib/community/avatar"
import { SlugHint } from "./slug-hint"
import { previewSlug } from "@/lib/community/slug-preview"
import { tid } from "@/lib/community/testids"
-import { useInvites, useAuditLog } from "@/hooks/community/use-server-panels"
+import { useInvites } from "@/hooks/community/use-server-panels"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
-import type { SettingsSection, Member, Role, InviteRow, AuditEntry, OpenProfile } from "./_types"
+import type { SettingsSection, Member, Role, InviteRow, OpenProfile } from "./_types"
import { isServerOwner } from "./_types"
import {
SETTINGS_NAV_CLASS,
@@ -71,21 +71,15 @@ export function ServerSettings({
}) {
const [confirmDelete, setConfirmDelete] = useState(false)
- // W-LAZY (necessity plan): invites + audit-log are low-frequency, admin-only
- // panel data — fetch them ONLY when their tab is actually open, never at
- // mount, never via WS (Gus, 架构 #25). Gating `enabled` on the active section
- // means opening Settings on any other tab fetches neither; switching TO the
- // Invites / Audit tab fetches it fresh then. Previously both were eager-
- // prefetched in the ServerLayout on every server entry.
+ // Invites are low-frequency, admin-only panel data. Fetch them only when
+ // their tab is open, never on settings mount or via WS.
const { invites, isLoading: invitesLoading } = useInvites(serverId, section === "invites")
- const { entries: auditLog, isLoading: auditLogLoading } = useAuditLog(serverId, section === "audit")
const nav: { id: SettingsSection; label: string; icon: LucideIcon }[] = [
{ id: "overview", label: "Overview", icon: Settings },
{ id: "members", label: "Members", icon: Users },
{ id: "invites", label: "Invites", icon: Link2 },
{ id: "notifications", label: "Notifications", icon: Bell },
- { id: "audit", label: "Audit Log", icon: ScrollText },
]
return (
<>
@@ -119,7 +113,7 @@ export function ServerSettings({
{/* settings body */}
<div className="flex min-w-0 flex-1 flex-col bg-background">
<header className="flex h-12 shrink-0 items-center border-b border-border px-4">
- <h1 className="flex-1 text-lg font-semibold capitalize">{section === "audit" ? "Audit Log" : section}</h1>
+ <h1 className="flex-1 text-lg font-semibold capitalize">{section}</h1>
<Button variant="ghost" size="icon-sm" onClick={onClose} aria-label="Close settings">
<X className="size-4" />
</Button>
@@ -129,7 +123,6 @@ export function ServerSettings({
<TabsContent value="members"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></TabsContent>
<TabsContent value="invites"><SettingsInvites invites={invites} loading={invitesLoading} onRevokeInvite={onRevokeInvite} onCopyInvite={onCopyInvite} /></TabsContent>
<TabsContent value="notifications"><SettingsNotifications level={notifLevel ?? notifLevelDisplay("mentions")} onSetLevel={onSetNotifLevel} /></TabsContent>
- <TabsContent value="audit"><SettingsAudit auditLog={auditLog} loading={auditLogLoading} /></TabsContent>
</div>
</div>
</Tabs>
@@ -422,28 +415,6 @@ function SettingsNotifications({ level, onSetLevel }: { level: string; onSetLeve
)
}
-function SettingsAudit({ auditLog, loading }: { auditLog: AuditEntry[]; loading?: boolean }) {
- if (loading && auditLog.length === 0) return <SettingsAuditSkeleton />
- return (
- <div className="mx-auto max-w-xl space-y-2">
- {auditLog.length === 0 && (
- <p className="text-sm text-muted-foreground">No audit log entries yet. Admin actions will be recorded here.</p>
- )}
- {auditLog.map((e, i) => (
- <div key={i} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">
- <ScrollText className="size-4 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1 text-sm">
- <span className="font-medium">{e.actor}</span>{" "}
- <span className="text-muted-foreground">{e.action}</span>{" "}
- <span className="font-medium">{e.target}</span>
- </div>
- <span className="shrink-0 text-xs text-muted-foreground" suppressHydrationWarning>{formatMessageTime(e.createdAt)}</span>
- </div>
- ))}
- </div>
- )
-}
-
// Loading placeholders for the settings panels — match the real row heights
// so the body doesn't shift when data lands.
function SettingsMembersSkeleton() {
@@ -482,17 +453,3 @@ function SettingsInvitesSkeleton() {
</div>
)
}
-
-function SettingsAuditSkeleton() {
- return (
- <div className="mx-auto max-w-xl space-y-2">
- {Array.from({ length: 6 }).map((_, i) => (
- <div key={i} className="flex items-center gap-3 rounded-md px-2 py-2">
- <Skeleton className="size-4 shrink-0 rounded" />
- <Skeleton className="h-4 flex-1 rounded" style={{ maxWidth: 360 + ((i * 37) % 80) }} />
- <Skeleton className="h-3 w-16 shrink-0 rounded" />
- </div>
- ))}
- </div>
- )
-}
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index c4b6deeb9..4da96212f 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -16,7 +16,6 @@ const EXACT_SERVER_QUERY_FAMILIES = new Set([
"forum-sidebar-unread-fallbacks",
"members",
"presence",
- "audit-log",
"invites",
"invitable-friends",
])
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index c632b5ddb..3f3c0e703 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -137,7 +137,7 @@ export function handleMentionCreate(
// The server rail badge counts unread mentions per server; refresh
// it on every new mention. `exact: true` is essential: the mention
// count lives in the `servers()` LIST query, but members/presence/
- // invites/audit-log/server(id) are all nested UNDER `servers()` in
+ // invites/server(id) are all nested UNDER `servers()` in
// the key hierarchy — a non-exact invalidate prefix-matches and
// force-refetches that whole subtree (and invalidate overrides the
// staleTime: Infinity those carry). With an active bot in the server,
diff --git a/src/web/src/hooks/community/use-eager-channel-read.ts b/src/web/src/hooks/community/use-eager-channel-read.ts
index 5734178b8..19dc350b8 100644
--- a/src/web/src/hooks/community/use-eager-channel-read.ts
+++ b/src/web/src/hooks/community/use-eager-channel-read.ts
@@ -87,7 +87,7 @@ export function useEagerChannelRead({
// The badge count lives in the `servers()` LIST query — NOT in
// `server(serverId)` (that's the detail: categories/channels, no
// count). So refresh `servers()` and, critically, with `exact: true`:
- // members/presence/invites/audit-log/server(id) are all nested under
+ // members/presence/invites/server(id) are all nested under
// `servers()` in the key hierarchy, and a non-exact invalidate
// prefix-matches and force-refetches that whole subtree (overriding
// their staleTime: Infinity). `exact` refreshes only the badge list.
diff --git a/src/web/src/hooks/community/use-server-panels.test.ts b/src/web/src/hooks/community/use-server-panels.test.ts
index 35938451b..d19173a64 100644
--- a/src/web/src/hooks/community/use-server-panels.test.ts
+++ b/src/web/src/hooks/community/use-server-panels.test.ts
@@ -50,42 +50,6 @@ describe("useInvites / invitesQueryFn", () => {
})
})
-describe("useAuditLog / auditLogQueryFn", () => {
- it("maps snake_case actions into space-separated display strings", async () => {
- apiFetchMock.mockResolvedValueOnce({
- entries: [
- {
- log: { action: "channel_delete", targetType: "channel", targetId: "ch_1", createdAt: "t" },
- actor: { name: "Alice" },
- },
- {
- log: { action: "member_kick", targetType: "member", targetId: "u_1", createdAt: "t" },
- actor: null,
- },
- ],
- })
- const { auditLogQueryFn } = await import("./use-server-panels")
- const data = await auditLogQueryFn("srv_1")()
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/audit-log")
- expect(data.entries[0]).toEqual({
- actor: "Alice",
- action: "channel delete",
- target: "channel",
- createdAt: "t",
- })
- expect(data.entries[1].actor).toBe("System")
- })
-
- it("populates queryClient at communityKeys.auditLog(serverId)", async () => {
- apiFetchMock.mockResolvedValueOnce({ entries: [] })
- const { auditLogQueryFn } = await import("./use-server-panels")
- const qc = new QueryClient()
- const key = communityKeys.auditLog("srv_1")
- await qc.fetchQuery({ queryKey: key, queryFn: auditLogQueryFn("srv_1") })
- expect(qc.getQueryData(key)).toEqual({ entries: [] })
- })
-})
-
describe("usePresence / presenceQueryFn", () => {
it("returns the online id list from the presence endpoint", async () => {
apiFetchMock.mockResolvedValueOnce({ online: ["u_1", "u_2"], truncated: false, limit: 1000 })
diff --git a/src/web/src/hooks/community/use-server-panels.ts b/src/web/src/hooks/community/use-server-panels.ts
index fea776e75..762df20e0 100644
--- a/src/web/src/hooks/community/use-server-panels.ts
+++ b/src/web/src/hooks/community/use-server-panels.ts
@@ -3,7 +3,7 @@
import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
-import type { InviteRow, AuditEntry } from "@/components/community/_types"
+import type { InviteRow } from "@/components/community/_types"
class StaleReadError extends Error {
constructor() { super("stale D1 read"); this.name = "StaleReadError" }
@@ -33,7 +33,6 @@ export type InvitesResponse = { invites: InviteRow[] }
// Frozen empty fallbacks — see `use-servers.ts` for the rationale.
const EMPTY_INVITES: readonly InviteRow[] = Object.freeze([])
-const EMPTY_AUDIT_ENTRIES: readonly AuditEntry[] = Object.freeze([])
export const invitesQueryFn = (serverId: string) => async (): Promise<InvitesResponse> => {
const data = await apiFetch<{ invites: RawInvite[] }>(
@@ -78,58 +77,6 @@ export function useInvites(
}
}
-/**
- * Fetches paginated audit-log entries. This hook returns the first page only;
- * the settings tab doesn't currently virtualise it — a future step can swap
- * this to `useInfiniteQuery` if larger pages are needed.
- */
-type RawAuditRow = {
- log: { action: string; targetType: string; targetId: string; createdAt: string }
- actor: { name: string | null } | null
-}
-
-export type AuditLogResponse = { entries: AuditEntry[] }
-
-export const auditLogQueryFn = (serverId: string) => async (): Promise<AuditLogResponse> => {
- const data = await apiFetch<{ entries: RawAuditRow[] }>(
- `/api/community/servers/${serverId}/audit-log`,
- )
- const entries: AuditEntry[] = data.entries.map((e) => ({
- actor: e.actor?.name ?? "System",
- action: e.log.action.replace(/_/g, " "),
- target: e.log.targetType,
- createdAt: e.log.createdAt,
- }))
- return { entries }
-}
-
-/**
- * The audit-log endpoint is admin-only (returns 403 for regular members).
- * Every server switch would otherwise fire two 403s (retry=1) for non-admin
- * members. Pass `isAdmin` to gate the fetch; the settings tab that renders
- * this data is admin-only anyway.
- */
-export function useAuditLog(
- serverId: string | null,
- isAdmin: boolean = true,
-): UseQueryResult<AuditLogResponse> & { entries: AuditEntry[] } {
- const enabled = !!serverId && isAdmin
- const query = useQuery({
- queryKey: enabled ? communityKeys.auditLog(serverId!) : communityKeys.auditLog("__none__"),
- queryFn: enabled
- ? auditLogQueryFn(serverId!)
- : (() => Promise.reject(new Error("disabled"))),
- enabled,
- // Not WS-live — audit rows aren't patched into this cache. A short
- // staleTime avoids a re-fetch on every settings-tab remount.
- staleTime: 60_000,
- })
- return {
- ...query,
- entries: query.data?.entries ?? (EMPTY_AUDIT_ENTRIES as AuditEntry[]),
- }
-}
-
/**
* Fetches the presence roster for a server — the list of online user ids
* cached at `communityKeys.presence(serverId)`. WS `presence.update` events
diff --git a/src/web/src/hooks/community/ws-live-query-config.test.ts b/src/web/src/hooks/community/ws-live-query-config.test.ts
index a572a8254..561ea4b77 100644
--- a/src/web/src/hooks/community/ws-live-query-config.test.ts
+++ b/src/web/src/hooks/community/ws-live-query-config.test.ts
@@ -10,8 +10,8 @@
* permanently stale. These tests pin that pairing so a future edit can't drop
* the reconnect backstop while keeping the infinite staleTime.
*
- * `useInvites` / `useAuditLog` are NOT WS-live — they get a short finite
- * staleTime instead, and must NOT be `Infinity`.
+ * `useInvites` is NOT WS-live — it gets a short finite staleTime instead,
+ * and must NOT be `Infinity`.
*
* The hooks are driven through a minimal react shim (the vitest env is node);
* `useQuery` / `useInfiniteQuery` are mocked to capture the options object.
@@ -78,7 +78,7 @@ describe("WS-live queries — staleTime: Infinity + refetchOnReconnect backstop"
const { useServer } = await import("./use-servers")
useServer("srv_1")
// The plain server-detail key ends at the serverId — no trailing segment
- // like "presence"/"members"/"audit-log" — so match it exactly.
+ // like "presence"/"members" — so match it exactly.
const cfg = queryConfigs.find(
(c) => JSON.stringify(c.queryKey) === JSON.stringify(["community", "servers", "srv_1"]),
)
@@ -117,11 +117,4 @@ describe("non-WS-live queries — finite staleTime, never Infinity", () => {
expect(cfg?.staleTime).not.toBe(Infinity)
})
- it("useAuditLog uses a finite staleTime", async () => {
- const { useAuditLog } = await import("./use-server-panels")
- useAuditLog("srv_1", true)
- const cfg = configFor("audit-log")
- expect(cfg?.staleTime).toBe(60_000)
- expect(cfg?.staleTime).not.toBe(Infinity)
- })
})
diff --git a/src/web/src/lib/community/audit.test.ts b/src/web/src/lib/community/audit.test.ts
deleted file mode 100644
index f3cab994c..000000000
--- a/src/web/src/lib/community/audit.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
-
-const mockLogAction = vi.fn()
-const mockWarn = vi.fn()
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return {
- ...actual,
- createLogger: () => ({
- info: vi.fn(),
- warn: (...a: unknown[]) => mockWarn(...a),
- error: vi.fn(),
- debug: vi.fn(),
- }),
- queries: {
- communityAuditLog: {
- logAction: (...a: unknown[]) => mockLogAction(...a),
- },
- },
- }
-})
-
-import { logAudit } from "./audit"
-
-describe("logAudit", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it("returns void immediately without awaiting the write", () => {
- // Never resolves — asserts logAudit does not await.
- mockLogAction.mockReturnValue(new Promise(() => { }))
- const result = logAudit({} as never, {
- serverId: "s1",
- actorId: "u1",
- action: "member_kick",
- targetType: "member",
- targetId: "m1",
- })
- expect(result).toBeUndefined()
- })
-
- it("swallows a rejection and logs warn once with action fields", async () => {
- mockLogAction.mockRejectedValue(new Error("db offline"))
- logAudit({} as never, {
- serverId: "s1",
- actorId: "u1",
- action: "member_kick",
- targetType: "member",
- targetId: "m1",
- })
- // Give the microtask queue a chance to flush the .catch handler.
- await new Promise((r) => setTimeout(r, 0))
-
- expect(mockWarn).toHaveBeenCalledTimes(1)
- expect(mockWarn).toHaveBeenCalledWith("audit_write_failed", {
- err: expect.stringContaining("db offline"),
- cause: "db offline",
- action: "member_kick",
- serverId: "s1",
- targetType: "member",
- targetId: "m1",
- })
- })
-
- it("surfaces the wrapped driver error via .cause (DrizzleQueryError shape)", async () => {
- // Mirrors drizzle-orm 0.44+: String(err) on the outer error only shows
- // "Failed query: ...", hiding the real SQLite failure on .cause.
- const outer = new Error("Failed query: insert into community_audit_log ...")
- ; (outer as Error & { cause?: unknown }).cause = new Error(
- "NOT NULL constraint failed: community_audit_log.server_id"
- )
- mockLogAction.mockRejectedValue(outer)
- logAudit({} as never, {
- serverId: null,
- actorId: "u1",
- action: "message_authored_as_bot",
- targetType: "message",
- targetId: "m1",
- })
- await new Promise((r) => setTimeout(r, 0))
-
- expect(mockWarn).toHaveBeenCalledWith("audit_write_failed", {
- err: expect.stringContaining("Failed query"),
- cause: "Failed query: insert into community_audit_log ... <- NOT NULL constraint failed: community_audit_log.server_id",
- action: "message_authored_as_bot",
- serverId: null,
- targetType: "message",
- targetId: "m1",
- })
- })
-
- it("does not log warn on success", async () => {
- mockLogAction.mockResolvedValue(undefined)
- logAudit({} as never, {
- serverId: "s1",
- actorId: "u1",
- action: "server_update",
- targetType: "server",
- targetId: "s1",
- })
- await new Promise((r) => setTimeout(r, 0))
- expect(mockWarn).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/lib/community/audit.ts b/src/web/src/lib/community/audit.ts
deleted file mode 100644
index 23eb37edc..000000000
--- a/src/web/src/lib/community/audit.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { queries, createLogger } from "@alook/shared"
-import type { Database } from "@alook/shared"
-
-const log = createLogger({ service: "community-audit" })
-
-/**
- * Typed audit-action union. Keep string-value stable across releases — old
- * rows in `community_audit_log.action` reference these verbatim.
- *
- * Bot-related actions are listed here so a) new call-sites get compile-time
- * feedback if they typo an action name; b) analytics can enumerate them.
- * `changes` is a JSON-encoded string with action-specific fields.
- */
-export const COMMUNITY_AUDIT_ACTIONS = {
- BOT_CREATED: "community.bot.created",
- BOT_UPDATED: "community.bot.updated",
- BOT_DELETED: "community.bot.deleted",
- BOT_ADDED_TO_SERVER: "community.bot.added_to_server",
- BOT_REMOVED_FROM_SERVER: "community.bot.removed_from_server",
- BOT_JOIN_REQUESTED: "community.bot.join_requested",
- BOT_JOIN_APPROVED: "community.bot.join_approved",
- BOT_JOIN_DENIED: "community.bot.join_denied",
- /** A bot joined a server via `alook server join --invite <link>` (owner-initiated CLI join). */
- BOT_JOINED_VIA_INVITE: "community.bot.joined_via_invite",
- BOT_FRIEND_REQUESTED: "community.bot.friend_requested",
- /** Requester withdrew their own pending bot friend-request. */
- BOT_FRIEND_CANCELLED: "community.bot.friend_cancelled",
- /** A pending friend row was superseded by a fresh request between the pair. */
- BOT_FRIEND_REQUEST_SUPERSEDED: "community.bot.friend_request_superseded",
- /** A gated friend row was approved by the requester's/target's owner. */
- BOT_FRIEND_APPROVED_BY_OWNER: "community.bot.friend_approved_by_owner",
- /** A gated friend row was denied by the deciding owner. */
- BOT_FRIEND_DENIED_BY_OWNER: "community.bot.friend_denied_by_owner",
- /** A sibling-bot friendship backfill (createBot fanout) failed for one sibling. */
- BOT_SIBLING_FRIENDSHIP_BACKFILL_FAILED: "community.bot.sibling_friendship_backfill_failed",
- MESSAGE_AUTHORED_AS_BOT: "community.message.authored_as_bot",
-} as const
-
-type AuditAction = {
- /** Null for user-scoped rows (bot lifecycle, friend approvals). */
- serverId: string | null
- actorId: string
- action: string
- targetType: string
- targetId: string
- changes?: string
-}
-
-/**
- * `String(err)` on a `DrizzleQueryError` only prints "Failed query: ...
- * params: ..." — the actual driver failure (e.g. a NOT NULL/FOREIGN KEY/
- * UNIQUE constraint message) lives on `.cause` (drizzle-orm 0.44+) and was
- * getting silently dropped from `audit_write_failed` logs, making every
- * past occurrence undiagnosable. Walk the chain so it's captured.
- */
-function causeChain(err: unknown): string[] {
- const messages: string[] = []
- let current: unknown = err
- for (let depth = 0; current && depth < 5; depth++) {
- if (current instanceof Error) {
- messages.push(current.message)
- current = (current as Error & { cause?: unknown }).cause
- } else {
- messages.push(String(current))
- break
- }
- }
- return messages
-}
-
-export function logAudit(db: Database, action: AuditAction): void {
- queries.communityAuditLog.logAction(db, action).catch((err) => {
- log.warn("audit_write_failed", {
- err: String(err),
- cause: causeChain(err).join(" <- "),
- action: action.action,
- serverId: action.serverId,
- targetType: action.targetType,
- targetId: action.targetId,
- })
- })
-}
diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.ts
index f157d70c0..91d150a46 100644
--- a/src/web/src/lib/community/create-channels.ts
+++ b/src/web/src/lib/community/create-channels.ts
@@ -15,7 +15,6 @@ import {
} from "@alook/shared"
import { fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"
import { createWithCollisionPolicy } from "@/lib/community/create-collision"
-import { logAudit } from "@/lib/community/audit"
import { requireServerMember, requireChannelMember } from "@/lib/community/permissions"
import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"
import { guardDmOpen } from "@/lib/community/dm-guard"
@@ -152,13 +151,6 @@ export async function createServerChannelForUser(
})
}
- logAudit(db, {
- serverId,
- actorId: actorUserId,
- action: "channel_create",
- targetType: "channel",
- targetId: channel.id,
- })
return { ok: true, value: channel }
}
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 599b78629..029717a35 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -85,14 +85,6 @@ vi.mock("../broadcast", () => ({
broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
}))
-const mockLogAudit = vi.fn()
-vi.mock("./audit", async () => {
- const actual = await vi.importActual<typeof import("./audit")>("./audit")
- return {
- ...actual,
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
- }
-})
import {
createCommunityMessage,
@@ -145,104 +137,6 @@ function messageRow(overrides: Partial<Record<string, unknown>> = {}) {
}
}
-describe("createCommunityMessage — audit relocation (plan §10)", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockCreateMessage.mockResolvedValue({ id: "msg_1" })
- mockGetMessage.mockResolvedValue(messageRow())
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockFanOutToDM.mockResolvedValue(undefined)
- mockBroadcastToUser.mockResolvedValue(undefined)
- })
-
- it("writes exactly ONE MESSAGE_AUTHORED_AS_BOT audit row for a bot author", async () => {
- mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: true, deletedAt: null })
-
- const result = await createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hello" },
- source: "cli",
- })
-
- expect(result.ok).toBe(true)
- expect(mockLogAudit).toHaveBeenCalledTimes(1)
- expect(mockLogAudit).toHaveBeenCalledWith(
- {},
- expect.objectContaining({
- serverId: "srv_1",
- actorId: "author_1",
- action: "community.message.authored_as_bot",
- targetType: "message",
- targetId: "msg_1",
- }),
- )
- const [, action] = mockLogAudit.mock.calls[0]!
- const changes = JSON.parse(action.changes)
- expect(changes).toEqual({
- botId: "author_1",
- target: "channel",
- targetId: "c1",
- messageId: "msg_1",
- source: "cli",
- })
- })
-
- it("does not write an audit row for a human author", async () => {
- mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
-
- await createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hello" },
- })
-
- expect(mockLogAudit).not.toHaveBeenCalled()
- })
-
- it("defaults source to 'web' when omitted", async () => {
- mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: true, deletedAt: null })
-
- await createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hello" },
- })
-
- const [, action] = mockLogAudit.mock.calls[0]!
- expect(JSON.parse(action.changes).source).toBe("web")
- })
-
- it("DM target: serverId is null and targetId is the dm channelId", async () => {
- mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: true, deletedAt: null })
- mockGetMessage.mockResolvedValue(messageRow({ channelId: "dm_1" }))
-
- await createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "dm", channelId: "dm_1", otherUserId: "u2" },
- body: { content: "hello" },
- source: "daemon-http",
- })
-
- expect(mockLogAudit).toHaveBeenCalledWith(
- {},
- expect.objectContaining({ serverId: null }),
- )
- const [, action] = mockLogAudit.mock.calls[0]!
- expect(JSON.parse(action.changes)).toEqual({
- botId: "author_1",
- target: "dm",
- targetId: "dm_1",
- messageId: "msg_1",
- source: "daemon-http",
- })
- })
-})
-
describe("createCommunityMessage — replyToId write-path scope validation (dangling-reply / #204 bot=user)", () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -401,7 +295,6 @@ describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-conditi
expect(mockCreateMentions).not.toHaveBeenCalled()
expect(mockFanOutToChannel).not.toHaveBeenCalled()
expect(mockFanOutToDM).not.toHaveBeenCalled()
- expect(mockLogAudit).not.toHaveBeenCalled()
})
it("passes expectedSeq through to createMessage when provided", async () => {
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 74f0381bd..7c6b15aab 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -18,7 +18,6 @@ import { broadcastToUserSafe, fanOutToChannel, resolveChannelRecipients } from "
import { dispatchMessageNotify } from "./notify"
import { mapMessageForWs } from "./message-payload"
import { attachmentUrl } from "./storage"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "./audit"
const log = createLogger({ service: "community-message-handler" })
@@ -166,7 +165,7 @@ export async function createCommunityMessage(params: {
authorId: string
target: MessageTarget
body: IncomingMessageBody
- /** Provenance tag threaded into the bot-authored audit row's `changes` (plan §10). */
+ /** Provenance tag included in diagnostics when a requested reply target is out of scope. */
source?: "cli" | "daemon-http" | "web"
/**
* CAS guard for the agent-send race fix
@@ -530,34 +529,6 @@ export async function createCommunityMessage(params: {
throw new Error("message not found after insert")
}
- // Bot-authored audit (plan §10) — moved here from individual call sites
- // (the daemon bot-message route used to log this itself) so EVERY caller,
- // present and future (the CLI `send` route included), gets it for free
- // with no duplicate-call risk. There's no standalone `isBot()` helper in
- // the repo; this mirrors the check the daemon route did before its own
- // `logAudit` call was removed. Fire-and-forget — `logAudit` already
- // swallows its own errors.
- const author = await withD1Retry(
- () => queries.user.getUserInternal(db, authorId),
- { route: "message-handler:author-lookup" },
- )
- if (author?.isBot === true) {
- logAudit(db, {
- serverId: isDmTarget(target) ? null : target.serverId,
- actorId: authorId,
- action: COMMUNITY_AUDIT_ACTIONS.MESSAGE_AUTHORED_AS_BOT,
- targetType: "message",
- targetId: row.id,
- changes: JSON.stringify({
- botId: authorId,
- target: target.kind,
- targetId: target.channelId,
- messageId: row.id,
- source: source ?? "web",
- }),
- })
- }
-
// Reply target for mention broadcasts. Scoped at the query level (not a
// post-hoc `.filter()`) so a caller can't attach a preview of a message
// from a different DM/channel by passing its id. The payload-side reply
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 89fe2dbbc..24721e3db 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -29,7 +29,6 @@ describe("communityKeys", () => {
expect(communityKeys.members("s1")).toEqual([...server, "members"])
expect(communityKeys.presence("s1")).toEqual([...server, "presence"])
- expect(communityKeys.auditLog("s1")).toEqual([...server, "audit-log"])
expect(communityKeys.invites("s1")).toEqual([...server, "invites"])
const sidebar = [...server, "forum-sidebar-base"]
expect(communityKeys.forumSidebarThreads("s1")).toEqual(sidebar)
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index e056b5590..70ee7f6a2 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -42,8 +42,6 @@ export const communityKeys = {
[...communityKeys.server(serverId), "members"] as const,
presence: (serverId: string) =>
[...communityKeys.server(serverId), "presence"] as const,
- auditLog: (serverId: string) =>
- [...communityKeys.server(serverId), "audit-log"] as const,
invites: (serverId: string) =>
[...communityKeys.server(serverId), "invites"] as const,
invitableFriends: (serverId: string) =>