Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

fix(projects): full delete audit — FK fix, MCP cleanup, prov-state drain

Yuting Zhong800c282ba7df
diff --git a/src/components/danger-zone.tsx b/src/components/danger-zone.tsx
index 55ad9478..2fa052fb 100644
--- a/src/components/danger-zone.tsx
+++ b/src/components/danger-zone.tsx
@@ -121,10 +121,11 @@ export function DangerZone({ projectSlug, projectName }: Props) {
</div>
) : summary ? (
<div className="space-y-3">
- <div className="grid grid-cols-3 divide-x rounded-lg border bg-card">
+ <div className="grid grid-cols-4 divide-x rounded-lg border bg-card">
<Stat label="Agents" value={summary.totals.agents} />
<Stat label="Threads" value={summary.totals.threads} />
<Stat label="Crons" value={summary.totals.crons} />
+ <Stat label="MCPs" value={summary.totals.mcps} />
</div>
{summary.agents.some((a) => a.exists) && (
<ul className="space-y-1 text-xs">
diff --git a/src/server/actions/projects.ts b/src/server/actions/projects.ts
index 7a999b61..a6202476 100644
--- a/src/server/actions/projects.ts
+++ b/src/server/actions/projects.ts
@@ -26,6 +26,9 @@ import {
getProjectDeletionSummary,
type ProjectDeletionSummary,
} from "@/server/openclaw/project-delete";
+import { MCP_CATALOG, storedMcpKey } from "@/server/mcp-catalog";
+import { disconnectMcp } from "@/server/mcp-state";
+import { clearProvisioning } from "@/server/onboarding/provisioning-state";
export type ActionResult<T = void> =
| { ok: true; data: T }
@@ -328,6 +331,8 @@ export type DeleteProjectData = {
agentsFailed: Array<{ agentId: string; error: string }>;
crons: number;
cronsFailed: number;
+ mcps: number;
+ mcpsFailed: number;
};
export async function deleteProjectAction(
@@ -382,10 +387,35 @@ export async function deleteProjectAction(
}
}
- // 3) Local DB rows.
+ // 3) Revoke per-project MCP connections (bearer tokens live in OpenClaw's
+ // mcp config under `<slug>-<catalog-key>`). Per-MCP best-effort so one
+ // unreachable MCP doesn't block the rest of the cascade.
+ let mcpsRevoked = 0;
+ let mcpsFailed = 0;
+ for (const spec of MCP_CATALOG) {
+ const key = storedMcpKey(slug, spec.key);
+ try {
+ await disconnectMcp(key);
+ mcpsRevoked++;
+ } catch (err) {
+ // disconnectMcp is already idempotent for "not configured" — anything
+ // hitting this path is a real openclaw-cli failure we want to surface.
+ const message = err instanceof Error ? err.message : String(err);
+ // "not found" / "unknown" responses are swallowed by disconnectMcp;
+ // anything else counts as a failure but doesn't abort delete.
+ console.warn(`[delete-project] failed to revoke MCP ${key}: ${message}`);
+ mcpsFailed++;
+ }
+ }
+
+ // 4) Drop the in-memory provisioning Promise so a re-created project with
+ // the same slug starts fresh (and we don't leak the old Promise).
+ clearProvisioning(slug);
+
+ // 5) Local DB rows.
deleteProjectRow(slug);
- // 4) Clear active-project cookie if it pointed at this one.
+ // 6) Clear active-project cookie if it pointed at this one.
const c = await cookies();
if (c.get("notfair_active_project")?.value === slug) {
await clearActiveProject();
@@ -404,6 +434,8 @@ export async function deleteProjectAction(
agentsFailed,
crons: cronsDeleted,
cronsFailed,
+ mcps: mcpsRevoked,
+ mcpsFailed,
},
};
}
diff --git a/src/server/db/projects.test.ts b/src/server/db/projects.test.ts
new file mode 100644
index 00000000..727902db
--- /dev/null
+++ b/src/server/db/projects.test.ts
@@ -0,0 +1,165 @@
+import Database from "better-sqlite3";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { MIGRATIONS } from "./migrations";
+
+// Use a real in-memory better-sqlite3 instance so SQLite's FK constraint
+// actually engages — mocking the DB would defeat the point (the bug was a
+// real FK violation our code wasn't catching).
+let testDb: Database.Database;
+
+vi.mock("./db", () => ({
+ getDb: () => testDb,
+ getDbPath: () => ":memory:",
+}));
+
+import { createProject, deleteProjectRow } from "./projects";
+
+function applyMigrations(db: Database.Database): void {
+ for (const migration of MIGRATIONS) {
+ db.exec(migration.sql);
+ }
+}
+
+function createDb(): Database.Database {
+ const db = new Database(":memory:");
+ db.pragma("foreign_keys = ON");
+ applyMigrations(db);
+ return db;
+}
+
+beforeEach(() => {
+ testDb = createDb();
+});
+
+afterEach(() => {
+ testDb.close();
+});
+
+describe("deleteProjectRow", () => {
+ it("cleans the project row when no child rows exist", () => {
+ const result = createProject({ display_name: "Acme" });
+ expect(result.ok).toBe(true);
+ expect(() => deleteProjectRow("acme")).not.toThrow();
+ expect(testDb.prepare("SELECT 1 FROM projects WHERE slug = ?").get("acme")).toBeUndefined();
+ });
+
+ describe("regression: FOREIGN KEY constraint failure on delete", () => {
+ // The bug: deleteProjectRow's childTables list was stale — it deleted
+ // from guardrails/approvals/agent_actions/cost_snapshots/connections
+ // (the last two don't even exist in our migrations), missing tasks,
+ // cost_events, oauth_tokens, sequence_runs. With orchestration adding
+ // task rows aggressively, deletes started tripping the FK constraint.
+ // This block populates every FK-bearing table and asserts the delete
+ // succeeds + nothing is left behind.
+
+ it("cleans tasks rows (the table that exposed the bug)", () => {
+ createProject({ display_name: "Acme" });
+ testDb
+ .prepare(
+ `INSERT INTO tasks
+ (id, project_slug, agent_id, brief, status, created_at, updated_at)
+ VALUES ('t1', 'acme', 'acme-google-ads', 'do x', 'proposed', 'now', 'now')`,
+ )
+ .run();
+
+ expect(() => deleteProjectRow("acme")).not.toThrow();
+ expect(testDb.prepare("SELECT 1 FROM tasks WHERE project_slug = ?").get("acme")).toBeUndefined();
+ expect(testDb.prepare("SELECT 1 FROM projects WHERE slug = ?").get("acme")).toBeUndefined();
+ });
+
+ it("cleans every FK-bearing child table without tripping FK", () => {
+ createProject({ display_name: "Acme" });
+
+ // One row per FK-bearing table from the migrations. If any new
+ // migration adds a project_slug FK and forgets to update
+ // deleteProjectRow's list, this test fails immediately.
+ testDb
+ .prepare(
+ `INSERT INTO tasks
+ (id, project_slug, agent_id, brief, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run("t1", "acme", "acme-google-ads", "do x", "proposed", "now", "now");
+ testDb
+ .prepare(
+ `INSERT INTO approvals
+ (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run("ap1", "acme", "acme-google-ads", "raise bid", "bid_change", 0, "{}", "pending", "now");
+ testDb
+ .prepare(
+ `INSERT INTO cost_events
+ (id, project_slug, agent_id, source, amount_usd, occurred_at)
+ VALUES (?, ?, ?, ?, ?, ?)`,
+ )
+ .run("c1", "acme", "acme-google-ads", "llm", 0.01, "now");
+ testDb
+ .prepare(
+ `INSERT INTO oauth_tokens
+ (id, project_slug, provider, account_label, access_token_enc, refresh_token_enc, expires_at, scope, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run("o1", "acme", "google_ads", "acme", "x", "y", "later", "scope", "now", "now");
+ testDb
+ .prepare(
+ `INSERT INTO guardrails (project_slug, config_json, updated_at)
+ VALUES (?, ?, ?)`,
+ )
+ .run("acme", "{}", "now");
+ testDb
+ .prepare(
+ `INSERT INTO agent_actions
+ (id, project_slug, agent_id, action_type, summary, occurred_at)
+ VALUES (?, ?, ?, ?, ?, ?)`,
+ )
+ .run("a1", "acme", "system", "project_created", "x", "now");
+ testDb
+ .prepare(
+ `INSERT INTO sequence_runs
+ (id, project_slug, agent_id, sequence_kind, cursor, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run("s1", "acme", "acme-cmo", "k", "0", "pending", "now", "now");
+
+ // Pre-condition: every child table has a row keyed to acme.
+ for (const table of [
+ "tasks",
+ "approvals",
+ "cost_events",
+ "oauth_tokens",
+ "guardrails",
+ "agent_actions",
+ "sequence_runs",
+ ]) {
+ expect(
+ testDb.prepare(`SELECT 1 FROM ${table} WHERE project_slug = ?`).get("acme"),
+ `${table} should have a pre-existing row`,
+ ).toBeTruthy();
+ }
+
+ // The actual fix: delete should NOT throw FOREIGN KEY constraint failed.
+ expect(() => deleteProjectRow("acme")).not.toThrow();
+
+ // Post-condition: project + every child row gone.
+ expect(
+ testDb.prepare("SELECT 1 FROM projects WHERE slug = ?").get("acme"),
+ ).toBeUndefined();
+ for (const table of [
+ "tasks",
+ "approvals",
+ "cost_events",
+ "oauth_tokens",
+ "guardrails",
+ "agent_actions",
+ "sequence_runs",
+ ]) {
+ expect(
+ testDb.prepare(`SELECT 1 FROM ${table} WHERE project_slug = ?`).get("acme"),
+ `${table} should have no rows after delete`,
+ ).toBeUndefined();
+ }
+ });
+ });
+});
diff --git a/src/server/db/projects.ts b/src/server/db/projects.ts
index 2542d137..ac1a40f8 100644
--- a/src/server/db/projects.ts
+++ b/src/server/db/projects.ts
@@ -171,24 +171,33 @@ export function unarchiveProject(slug: string): Project | null {
}
/**
- * Hard-delete a project row plus any rows in tables that key off project_slug
- * (guardrails, approvals, agent_actions, etc.). OpenClaw-side state — agents,
- * sessions, crons — is cleaned up by the deleteProject orchestrator, not here.
+ * Hard-delete a project row plus any rows in tables that key off
+ * project_slug. OpenClaw-side state — agents, sessions, crons — is cleaned
+ * up by the deleteProject orchestrator, not here.
+ *
+ * MUST match the FK-bearing tables from the migrations (mirrored exactly by
+ * the changeProjectSlug helper above). Adding a new migration that FKs to
+ * projects(slug) requires adding the table name here too — otherwise delete
+ * trips a SqliteError FOREIGN KEY constraint failed (the bug we just
+ * shipped a regression test for).
*/
export function deleteProjectRow(slug: string): void {
const db = getDb();
const childTables = [
- "guardrails",
+ "tasks",
"approvals",
+ "cost_events",
+ "oauth_tokens",
+ "guardrails",
"agent_actions",
- "cost_snapshots",
- "connections",
+ "sequence_runs",
];
for (const table of childTables) {
try {
db.prepare(`DELETE FROM ${table} WHERE project_slug = ?`).run(slug);
} catch {
- // table missing on this install; skip.
+ // table missing on this install (e.g., older DB pre-migration).
+ // Per-table try/catch so one missing table doesn't block the rest.
}
}
db.prepare("DELETE FROM projects WHERE slug = ?").run(slug);
diff --git a/src/server/onboarding/provisioning-state.test.ts b/src/server/onboarding/provisioning-state.test.ts
index 2be50d95..4eb52fcc 100644
--- a/src/server/onboarding/provisioning-state.test.ts
+++ b/src/server/onboarding/provisioning-state.test.ts
@@ -8,6 +8,7 @@ vi.mock("@/server/agent-templates", () => ({
import {
__resetProvisioningForTesting,
awaitProvisioning,
+ clearProvisioning,
startProvisioning,
type ProvisionResult,
} from "./provisioning-state";
@@ -68,6 +69,25 @@ describe("provisioning-state", () => {
});
});
+ describe("clearProvisioning (called from deleteProjectAction)", () => {
+ it("drops an in-flight Promise so a re-created slug starts fresh", async () => {
+ const slowPromise = new Promise<ProvisionResult>((resolve) =>
+ setTimeout(() => resolve(okResult), 1_000),
+ );
+ startProvisioning("acme", slowPromise);
+ clearProvisioning("acme");
+ // After clear, the Map is empty for this slug → next awaitProvisioning
+ // hits the cold-start fallback path.
+ agentExistsMock.mockResolvedValue(false);
+ const r = await awaitProvisioning("acme", 5_000);
+ expect(r).toEqual({ kind: "no-agents", via_fallback: true });
+ });
+
+ it("is a no-op when slug isn't in the Map (deleteProjectAction can call defensively)", () => {
+ expect(() => clearProvisioning("never-seen")).not.toThrow();
+ });
+ });
+
describe("cold-start fallback (Map empty)", () => {
it("returns ready when both expected agents exist on disk", async () => {
agentExistsMock.mockImplementation(async (name) =>
diff --git a/src/server/onboarding/provisioning-state.ts b/src/server/onboarding/provisioning-state.ts
index a976a6ca..63e881ca 100644
--- a/src/server/onboarding/provisioning-state.ts
+++ b/src/server/onboarding/provisioning-state.ts
@@ -102,6 +102,16 @@ export async function awaitProvisioning(
return { kind: "no-agents", via_fallback: true };
}
+/**
+ * Drop any in-flight or stale provisioning Promise for a slug. Called by
+ * deleteProjectAction so a deleted project doesn't leak its Promise entry
+ * in the global Map (and so re-creating a project with the same slug
+ * later starts from a clean state).
+ */
+export function clearProvisioning(slug: string): void {
+ STORE.delete(slug);
+}
+
/** Test helper: drain the global Map. Never call in production code. */
export function __resetProvisioningForTesting(): void {
STORE.clear();
diff --git a/src/server/openclaw/project-delete.ts b/src/server/openclaw/project-delete.ts
index 9857c344..960d6ccc 100644
--- a/src/server/openclaw/project-delete.ts
+++ b/src/server/openclaw/project-delete.ts
@@ -3,6 +3,8 @@ import { homedir } from "node:os";
import { join } from "node:path";
import type { AgentTemplate } from "@/server/agent-templates";
import { listProjectAgents } from "@/server/agent-meta";
+import { MCP_CATALOG, storedMcpKey } from "@/server/mcp-catalog";
+import { readMcpConfigRow } from "@/server/mcp/rpc";
import { listSessionsForAgent } from "@/server/openclaw/sessions";
import { listCronsForProject } from "@/server/openclaw/crons";
@@ -17,13 +19,23 @@ export type ProjectDeletionAgentSummary = {
threadCount: number;
};
+export type ProjectDeletionMcpSummary = {
+ catalog_key: string;
+ display_name: string;
+ stored_key: string;
+ /** True when an MCP config row exists for this project + catalog entry. */
+ configured: boolean;
+};
+
export type ProjectDeletionSummary = {
project_slug: string;
agents: ProjectDeletionAgentSummary[];
+ mcps: ProjectDeletionMcpSummary[];
totals: {
agents: number;
threads: number;
crons: number;
+ mcps: number;
};
};
@@ -60,13 +72,39 @@ export async function getProjectDeletionSummary(
// OpenClaw cron service unreachable — show 0 and let the user decide.
}
+ // MCP connections live in OpenClaw's mcp config under per-project keys
+ // (`<slug>-<catalog-key>`). Deleting the project means revoking these
+ // bearer tokens — surface a count in the confirmation so the user knows
+ // what's about to disconnect.
+ const mcps: ProjectDeletionMcpSummary[] = await Promise.all(
+ MCP_CATALOG.map(async (spec) => {
+ const stored_key = storedMcpKey(project_slug, spec.key);
+ let configured = false;
+ try {
+ const row = await readMcpConfigRow(stored_key);
+ configured = Boolean(row);
+ } catch {
+ // OpenClaw mcp command unavailable — treat as unconfigured for
+ // summary purposes; the actual delete is also best-effort.
+ }
+ return {
+ catalog_key: spec.key,
+ display_name: spec.display_name,
+ stored_key,
+ configured,
+ };
+ }),
+ );
+
return {
project_slug,
agents,
+ mcps,
totals: {
agents: agents.filter((a) => a.exists).length,
threads: agents.reduce((acc, a) => acc + a.threadCount, 0),
crons: cronCount,
+ mcps: mcps.filter((m) => m.configured).length,
},
};
}