Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(db): enforce cascade constraints on agent.runtimeId, ownerId and workspaceFileRequest (#47)

Generbe1e29b29c74
diff --git a/src/shared/src/db/queries/agent.ts b/src/shared/src/db/queries/agent.ts
index b8cca9fd6..1c970ccf3 100644
--- a/src/shared/src/db/queries/agent.ts
+++ b/src/shared/src/db/queries/agent.ts
@@ -1,5 +1,5 @@
import { eq, and, desc, or, exists } from "drizzle-orm";
-import { agent, agentTaskQueue, agentAccess } from "../schema";
+import { agent, agentAccess } from "../schema";
import type { Database } from "../index";
export async function getAgent(db: Database, id: string, workspaceId: string, userId?: string) {
@@ -50,10 +50,10 @@ export async function createAgent(
data: {
workspaceId: string;
name: string;
+ runtimeId: string;
description?: string;
instructions?: string;
avatarUrl?: string | null;
- runtimeId?: string | null;
runtimeMode?: string;
runtimeConfig?: unknown;
visibility?: string;
@@ -69,10 +69,10 @@ export async function createAgent(
.values({
workspaceId: data.workspaceId,
name: data.name,
+ runtimeId: data.runtimeId,
description: data.description ?? "",
instructions: data.instructions ?? "",
avatarUrl: data.avatarUrl ?? null,
- runtimeId: data.runtimeId ?? null,
runtimeMode: data.runtimeMode ?? "local",
runtimeConfig: data.runtimeConfig ?? null,
visibility: data.visibility ?? "private",
@@ -92,9 +92,6 @@ export async function deleteAgent(
workspaceId: string,
ownerId?: string
) {
- await db
- .delete(agentTaskQueue)
- .where(and(eq(agentTaskQueue.agentId, id), eq(agentTaskQueue.workspaceId, workspaceId)));
const conditions = [eq(agent.id, id), eq(agent.workspaceId, workspaceId)];
if (ownerId) conditions.push(eq(agent.ownerId, ownerId));
const rows = await db
@@ -112,7 +109,7 @@ export async function updateAgent(
name?: string;
description?: string;
instructions?: string;
- runtimeId?: string | null;
+ runtimeId?: string;
runtimeConfig?: unknown;
visibility?: string;
},
diff --git a/src/shared/src/db/queries/runtime.ts b/src/shared/src/db/queries/runtime.ts
index 94de00b4a..acc725e20 100644
--- a/src/shared/src/db/queries/runtime.ts
+++ b/src/shared/src/db/queries/runtime.ts
@@ -1,5 +1,5 @@
import { eq, and, asc, sql } from "drizzle-orm";
-import { agentRuntime, agent, agentTaskQueue, machine } from "../schema";
+import { agentRuntime, machine } from "../schema";
import type { Database } from "../index";
export async function upsertAgentRuntime(
@@ -114,34 +114,6 @@ export async function deleteRuntimesByDaemonId(
daemonId: string,
workspaceId: string
) {
- // Find runtime IDs to delete
- const runtimes = await db
- .select({ id: agentRuntime.id })
- .from(agentRuntime)
- .where(
- and(
- eq(agentRuntime.daemonId, daemonId),
- eq(agentRuntime.workspaceId, workspaceId)
- )
- );
-
- if (runtimes.length === 0) return;
-
- const ids = runtimes.map((r) => r.id);
-
- // Null out agent references and delete tasks per runtime
- for (const id of ids) {
- await db
- .update(agent)
- .set({ runtimeId: null, updatedAt: new Date().toISOString() })
- .where(eq(agent.runtimeId, id));
-
- await db
- .delete(agentTaskQueue)
- .where(eq(agentTaskQueue.runtimeId, id));
- }
-
- // Delete the runtimes
await db
.delete(agentRuntime)
.where(
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 7bd379b1b..71bd67ebc 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -211,13 +211,15 @@ export const agent = sqliteTable(
description: text("description").notNull().default(""),
instructions: text("instructions").notNull().default(""),
avatarUrl: text("avatar_url"),
- runtimeId: text("runtime_id").references(() => agentRuntime.id),
+ runtimeId: text("runtime_id")
+ .notNull()
+ .references(() => agentRuntime.id, { onDelete: "cascade" }),
runtimeMode: text("runtime_mode").notNull().default("local"),
runtimeConfig: text("runtime_config", { mode: "json" }),
visibility: text("visibility").notNull().default("private"),
status: text("status").notNull().default("idle"),
maxConcurrentTasks: integer("max_concurrent_tasks").notNull().default(6),
- ownerId: text("owner_id").references(() => user.id),
+ ownerId: text("owner_id").references(() => user.id, { onDelete: "cascade" }),
tools: text("tools", { mode: "json" }),
triggers: text("triggers", { mode: "json" }),
emailHandle: text("email_handle").unique(),
@@ -580,5 +582,11 @@ export const workspaceFileRequest = sqliteTable(
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
},
- (t) => [index("idx_wfr_workspace_status").on(t.workspaceId, t.status)]
+ (t) => [
+ index("idx_wfr_workspace_status").on(t.workspaceId, t.status),
+ foreignKey({
+ columns: [t.agentId, t.workspaceId],
+ foreignColumns: [agent.id, agent.workspaceId],
+ }).onDelete("cascade"),
+ ]
);
diff --git a/src/web/migrations/0018_schema_cascade_cleanup.sql b/src/web/migrations/0018_schema_cascade_cleanup.sql
new file mode 100644
index 000000000..42dc92067
--- /dev/null
+++ b/src/web/migrations/0018_schema_cascade_cleanup.sql
@@ -0,0 +1,64 @@
+-- Fix FK cascade behavior for agent and workspace_file_request tables:
+-- 1. agent.runtime_id: NOT NULL + ON DELETE CASCADE — agent cannot exist without runtime
+-- 2. agent.owner_id: ON DELETE CASCADE — deleting user deletes their agents
+-- 3. workspace_file_request: add composite FK to agent(id, workspace_id) ON DELETE CASCADE
+
+PRAGMA foreign_keys = OFF;
+
+-- Rebuild agent table with corrected FK constraints
+CREATE TABLE agent_new (
+ id TEXT NOT NULL,
+ workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ instructions TEXT NOT NULL DEFAULT '',
+ avatar_url TEXT,
+ runtime_id TEXT NOT NULL REFERENCES agent_runtime(id) ON DELETE CASCADE,
+ runtime_mode TEXT NOT NULL DEFAULT 'local',
+ runtime_config TEXT,
+ visibility TEXT NOT NULL DEFAULT 'private',
+ status TEXT NOT NULL DEFAULT 'idle',
+ max_concurrent_tasks INTEGER NOT NULL DEFAULT 6,
+ owner_id TEXT REFERENCES user(id) ON DELETE CASCADE,
+ tools TEXT,
+ triggers TEXT,
+ email_handle TEXT UNIQUE,
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
+ PRIMARY KEY (id, workspace_id)
+);
+
+-- Clean up orphan agents with NULL runtime_id (previously set by deleteRuntimesByDaemonId)
+DELETE FROM agent WHERE runtime_id IS NULL;
+
+INSERT INTO agent_new SELECT * FROM agent;
+
+DROP TABLE agent;
+
+ALTER TABLE agent_new RENAME TO agent;
+
+-- Rebuild workspace_file_request with composite FK to agent
+CREATE TABLE workspace_file_request_new (
+ id TEXT PRIMARY KEY,
+ workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ agent_id TEXT NOT NULL,
+ request_type TEXT NOT NULL,
+ path TEXT NOT NULL DEFAULT '.',
+ status TEXT NOT NULL DEFAULT 'pending',
+ result TEXT,
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
+ FOREIGN KEY (agent_id, workspace_id) REFERENCES agent(id, workspace_id) ON DELETE CASCADE
+);
+
+INSERT INTO workspace_file_request_new SELECT * FROM workspace_file_request;
+
+DROP TABLE workspace_file_request;
+
+ALTER TABLE workspace_file_request_new RENAME TO workspace_file_request;
+
+CREATE INDEX idx_wfr_workspace_status ON workspace_file_request(workspace_id, status);
+
+PRAGMA foreign_keys = ON;
+
+PRAGMA foreign_key_check;