Open-source SEO, GEO, and marketing skills for AI agents.
fix(agents): relocation cleanup no longer dies on a phantom table
Yuting Zhong87666251c8d2
diff --git a/notfair/src/server/actions/agents.test.ts b/notfair/src/server/actions/agents.test.tsnew file mode 100644index 00000000..7f36c57e--- /dev/null+++ b/notfair/src/server/actions/agents.test.ts@@ -0,0 +1,91 @@+import { beforeAll, describe, expect, it, vi } from "vitest";+import { existsSync, mkdirSync } from "node:fs";+import { join } from "node:path";++// Real better-sqlite3 against a tmpdir DB, per repo test conventions.+// MUST be hoisted: static imports evaluate before module-level statements,+// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment+// here would silently point the suite at the developer's live ~/.notfair.+const h = vi.hoisted(() => {+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");+ const { tmpdir } = require("node:os") as typeof import("node:os");+ const { join } = require("node:path") as typeof import("node:path");+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-relocate-"));+ process.env.NOTFAIR_DATA_DIR = dataDir;+ return { dataDir, unregisterMcp: vi.fn(async () => {}) };+});++// Mock the harness boundary: the real adapter would edit the developer's+// actual ~/.codex / ~/.claude config when unregistering MCP servers.+vi.mock("@/server/adapters/registry", () => ({+ requireAdapter: () => ({ unregisterMcp: h.unregisterMcp }),+}));+vi.mock("@/server/mcp-catalog", () => ({ getMcpCatalog: () => [] }));+vi.mock("@/server/mcp-server/registration", () => ({+ GOALS_MCP_KEY: "notfair-goals",+ BROWSER_MCP_KEY: "notfair-browser",+}));++import { getDb } from "@/server/db/db";+import { writeAgentMeta, readAgentMeta } from "@/server/agent-meta";+import { relocateAgent } from "./agents";++const OLD_AGENT = "src-proj-goal-1";+const NEW_AGENT = "dst-proj-goal-1";++beforeAll(async () => {+ getDb()+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', 'src-proj', 'Src', ?, 'codex-local')",+ )+ .run(new Date().toISOString());+ // Old agent: workspace dir + meta sidecar + one chat session.+ mkdirSync(join(h.dataDir, "agents", OLD_AGENT), { recursive: true });+ await writeAgentMeta({+ agent_id: OLD_AGENT,+ project_slug: "src-proj",+ slug: "goal-1",+ name: "Goal 1",+ created_at: new Date().toISOString(),+ });+ getDb()+ .prepare(+ `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)+ VALUES ('s1', 'src-proj', ?, 'main', 'codex-local', ?, ?)`,+ )+ .run(OLD_AGENT, new Date().toISOString(), new Date().toISOString());+});++describe("relocateAgent", () => {+ it("moves the agent and fully cleans up the old one", async () => {+ const result = await relocateAgent({+ old_agent_id: OLD_AGENT,+ source_project_slug: "src-proj",+ new_project_slug: "dst-proj",+ new_slug: "goal-1",+ new_display_name: "Goal 1",+ });++ expect(result.new_agent_id).toBe(NEW_AGENT);+ // New workspace exists with a sidecar pointing at the new project.+ expect(existsSync(join(h.dataDir, "agents", NEW_AGENT))).toBe(true);+ expect(readAgentMeta(NEW_AGENT)?.project_slug).toBe("dst-proj");++ // Old artifacts are gone: workspace dir, session rows (this delete used+ // to throw on a nonexistent scheduled_jobs table and get swallowed,+ // stranding sessions forever), and harness MCP registrations.+ expect(existsSync(join(h.dataDir, "agents", OLD_AGENT))).toBe(false);+ const sessions = getDb()+ .prepare("SELECT COUNT(*) AS n FROM sessions WHERE agent_id = ?")+ .get(OLD_AGENT) as { n: number };+ expect(sessions.n).toBe(0);+ const unregistered = h.unregisterMcp.mock.calls.map(+ (c) => (c as unknown as [{ serverName: string; agentId: string }])[0],+ );+ expect(unregistered.every((u) => u.agentId === OLD_AGENT)).toBe(true);+ expect(unregistered.map((u) => u.serverName).sort()).toEqual([+ "notfair-browser",+ "notfair-goals",+ ]);+ });+});diff --git a/notfair/src/server/actions/agents.ts b/notfair/src/server/actions/agents.tsindex 8c3e245b..ca30022f 100644--- a/notfair/src/server/actions/agents.ts+++ b/notfair/src/server/actions/agents.ts@@ -1,6 +1,7 @@"use server";-import { cascadeDeleteAgent, cloneAgent } from "@/server/agents/clone";+import { cloneAgent } from "@/server/agents/clone";+import { cascadeDeleteAgentArtifacts } from "@/server/agents/cascade-delete";import { writeAgentMeta } from "@/server/agent-meta";// --- Relocate (used by project rename to move agents to the new slug) ---@@ -42,7 +43,16 @@ export async function relocateAgent(created_at: input.preserve_created_at ?? new Date().toISOString(),});- await cascadeDeleteAgent(input.old_agent_id, input.source_project_slug).catch(() => {});+ // Best-effort: the clone already succeeded, so a cleanup failure must not+ // fail the relocation — but it must not be invisible either (a silent+ // swallow here previously masked cleanup breaking entirely, stranding the+ // old agent's sessions and MCP registrations).+ await cascadeDeleteAgentArtifacts(+ input.source_project_slug,+ input.old_agent_id,+ ).catch((err) =>+ console.error(`[relocate] cleanup of old agent ${input.old_agent_id} failed:`, err),+ );return {new_agent_id: cloneResult.new_agent_id,diff --git a/notfair/src/server/actions/projects.ts b/notfair/src/server/actions/projects.tsindex 4b292aeb..50fcf08e 100644--- a/notfair/src/server/actions/projects.ts+++ b/notfair/src/server/actions/projects.ts@@ -297,8 +297,8 @@ export async function deleteProjectAction(// Single shot — drops every artifact tied to this project: agent workspace- // dirs, scheduled_jobs + runs, sessions + transcripts, mcp_tokens. Adapter- // MCP entries get unregistered too.+ // dirs, sessions + transcripts, mcp_tokens. Adapter MCP entries get+ // unregistered too.try {await cascadeDeleteProjectArtifacts(slug);} catch (err) {@@ -311,7 +311,7 @@ export async function deleteProjectAction(// 5) Canonical PROJECT.md directory at ~/.notfair/projects/<slug>/.// The per-agent sidecar copies inside each workspace were already wiped- // by cascadeDeleteAgent's `rm -rf` on the workspace dir; this is the+ // by the cascade's `rm -rf` on the workspace dirs; this is the// last surface that holds the project brief on disk. Without this,// recreating a project with the same slug later would silently inherit// the prior tenant's PROJECT.md (writeIdentityFile inlines it if itdiff --git a/notfair/src/server/agents/clone.ts b/notfair/src/server/agents/clone.tsindex c694ac21..58d8e21a 100644--- a/notfair/src/server/agents/clone.ts+++ b/notfair/src/server/agents/clone.ts@@ -4,7 +4,6 @@ import { randomUUID } from "node:crypto";import { slugify } from "@/lib/slug";import { workspaceDirFor } from "@/server/agents/provisioning";import { writeAgentMeta } from "@/server/agent-meta";-import { getDb } from "@/server/db/db";export interface CloneAgentInput {source_agent_id: string;@@ -25,9 +24,9 @@ export interface CloneAgentResult {/*** Clone an existing agent within a project.*- * Workspace dir copy via fs `cp -r`, scheduled jobs duplicated as new rows,- * sessions / transcript_events left ON the source (we don't carry chat history- * forward — the new agent starts with an empty thread list).+ * Workspace dir copy via fs `cp -r`; sessions / transcript_events left ON+ * the source (we don't carry chat history forward — the new agent starts+ * with an empty thread list).*/export async function cloneAgent(input: CloneAgentInput): Promise<CloneAgentResult> {let newSlug: string;@@ -91,19 +90,4 @@ export function agentExistsInProject(project_slug: string, slug: string): boolea}}-/** Cascade-delete an agent's workspace + sessions + scheduled jobs. */-export async function cascadeDeleteAgent(agent_id: string, project_slug: string): Promise<void> {- const dir = workspaceDirFor(agent_id);- const { rm } = await import("node:fs/promises");- if (existsSync(dir)) {- await rm(dir, { recursive: true, force: true });- }- getDb()- .prepare("DELETE FROM scheduled_jobs WHERE project_slug = ? AND agent_id = ?")- .run(project_slug, agent_id);- getDb()- .prepare("DELETE FROM sessions WHERE project_slug = ? AND agent_id = ?")- .run(project_slug, agent_id);-}-void randomUUID; // imported for future use (sessions cloning if we re-enable)