Skip to content

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

feat(orchestration): MCP-first agent coordination + comprehensive approvals

Yuting Zhong94db9d2ef083
diff --git a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
index ca913753..306cc919 100644
--- a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
@@ -3,14 +3,15 @@ import { notFound } from "next/navigation";
import { AgentTaskWorkspace } from "@/components/agent-task-workspace";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
+import { listApprovalsForTask } from "@/server/db/approvals";
import { getTask, listTasksByAgent, setTaskThreadIfMissing } from "@/server/db/tasks";
import { buildPendingSessionKey, findSessionBySessionId } from "@/server/openclaw/sessions";
import {
readTranscriptTail,
type TranscriptEvent,
} from "@/server/openclaw/transcript-tail";
-import { generateTaskThreadId } from "@/server/orchestration/process-blocks";
-import type { Task } from "@/types";
+import { generateTaskThreadId } from "@/server/orchestration/task-kickoff";
+import type { Approval, Task } from "@/types";
type Props = {
params: Promise<{ agent: string; project: string }>;
@@ -23,6 +24,13 @@ type SelectedBundle = {
sessionKey: string;
initialEvents: TranscriptEvent[];
initialByteOffset: number;
+ /**
+ * Every approval ever requested on this task, newest first. The chat view
+ * renders these above the transcript so the user can act on a pending
+ * approval without leaving the task. Resolved rows show too — they're
+ * the audit trail for "what did I approve here?".
+ */
+ approvals: Approval[];
};
export default async function AgentTasksPage({ params, searchParams }: Props) {
@@ -87,6 +95,7 @@ async function loadSelectedBundle(
session?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);
const { events, byteOffset } = readTranscriptTail(agentFullId, threadId, 0);
+ const approvals = listApprovalsForTask(task.id);
return {
task,
@@ -94,5 +103,6 @@ async function loadSelectedBundle(
sessionKey,
initialEvents: events,
initialByteOffset: byteOffset,
+ approvals,
};
}
diff --git a/src/app/(app)/[project]/approvals/page.tsx b/src/app/(app)/[project]/approvals/page.tsx
index 425ac8de..f6c35ced 100644
--- a/src/app/(app)/[project]/approvals/page.tsx
+++ b/src/app/(app)/[project]/approvals/page.tsx
@@ -1,51 +1,174 @@
+import Link from "next/link";
import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
import { getProject } from "@/server/db/projects";
-import { listPendingApprovals } from "@/server/db/approvals";
+import {
+ listActionableApprovals,
+ listPolicies,
+ listResolvedApprovals,
+} from "@/server/db/approvals";
import { ApprovalCard } from "@/components/approval-card";
+import { PolicyList } from "@/components/policy-list";
import { projectHref } from "@/lib/project-href";
+type TabKey = "pending" | "resolved" | "policies";
+
+function parseTab(raw: string | string[] | undefined): TabKey {
+ const value = Array.isArray(raw) ? raw[0] : raw;
+ if (value === "resolved" || value === "policies") return value;
+ return "pending";
+}
+
export default async function ApprovalsPage({
params,
+ searchParams,
}: {
params: Promise<{ project: string }>;
+ searchParams: Promise<{ tab?: string | string[] }>;
}) {
const { project: slug } = await params;
+ const { tab } = await searchParams;
+ const activeTab = parseTab(tab);
+
const project = getProject(slug);
if (!project || project.archived_at) notFound();
- const pending = listPendingApprovals(project.slug);
+ // Bulk-fetch everything we render — better-sqlite3 is synchronous and the
+ // page is small enough that one round-trip per panel keeps the code simple.
+ const actionable = listActionableApprovals(project.slug);
+ const resolved =
+ activeTab === "resolved" ? listResolvedApprovals(project.slug, 50) : [];
+ const policies = activeTab === "policies" ? listPolicies(project.slug) : [];
+
+ const counts = {
+ pending: actionable.length,
+ resolved: resolved.length,
+ policies: policies.length,
+ };
return (
<div className="mx-auto max-w-3xl space-y-4">
<header className="space-y-1">
<h1 className="text-2xl font-semibold tracking-tight">Approvals</h1>
<p className="text-sm text-muted-foreground">
- Project <span className="font-mono">{project.slug}</span> · {pending.length} pending
+ Inbox for the project <span className="font-mono">{project.slug}</span>. Approvals
+ surface here when an agent wants to make a write that the project's policies
+ don't already cover.
</p>
</header>
- {pending.length === 0 ? (
- <Card>
- <CardContent className="py-16 text-center">
- <h2 className="text-lg font-medium">All caught up.</h2>
- <p className="mt-2 text-sm text-muted-foreground">
- CMO will surface decisions here. Items above your thresholds appear
- here for approval. Adjust thresholds in{" "}
- <a href={projectHref(slug, "/settings")} className="underline">
- Settings
- </a>
- .
- </p>
- </CardContent>
- </Card>
- ) : (
- <div className="space-y-3">
- {pending.map((a) => (
- <ApprovalCard key={a.id} approval={a} />
- ))}
- </div>
+ <nav className="flex gap-1 border-b border-border" role="tablist" aria-label="Approval tabs">
+ <TabLink
+ slug={slug}
+ tab="pending"
+ active={activeTab}
+ label="Inbox"
+ count={counts.pending}
+ highlightCount
+ />
+ <TabLink slug={slug} tab="resolved" active={activeTab} label="Resolved" />
+ <TabLink
+ slug={slug}
+ tab="policies"
+ active={activeTab}
+ label="Auto-approve rules"
+ />
+ </nav>
+
+ {activeTab === "pending" && (
+ actionable.length === 0 ? (
+ <Card>
+ <CardContent className="py-16 text-center">
+ <h2 className="text-lg font-medium">All caught up.</h2>
+ <p className="mt-2 text-sm text-muted-foreground">
+ Agents will surface decisions here. Manage auto-approve rules in the
+ <span className="px-1">
+ <Link
+ href={`${projectHref(slug, "/approvals")}?tab=policies`}
+ className="underline"
+ >
+ Auto-approve rules
+ </Link>
+ </span>
+ tab.
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-3">
+ {actionable.map((a) => (
+ <ApprovalCard key={a.id} approval={a} />
+ ))}
+ </div>
+ )
+ )}
+
+ {activeTab === "resolved" && (
+ resolved.length === 0 ? (
+ <Card>
+ <CardContent className="py-16 text-center">
+ <h2 className="text-lg font-medium">No resolved approvals yet.</h2>
+ <p className="mt-2 text-sm text-muted-foreground">
+ Decisions show up here after they're approved, rejected, or auto-handled.
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-3">
+ {resolved.map((a) => (
+ <ApprovalCard key={a.id} approval={a} />
+ ))}
+ </div>
+ )
+ )}
+
+ {activeTab === "policies" && (
+ <PolicyList projectSlug={project.slug} policies={policies} />
)}
</div>
);
}
+
+function TabLink({
+ slug,
+ tab,
+ active,
+ label,
+ count,
+ highlightCount = false,
+}: {
+ slug: string;
+ tab: TabKey;
+ active: TabKey;
+ label: string;
+ count?: number;
+ highlightCount?: boolean;
+}) {
+ const isActive = active === tab;
+ const href = tab === "pending"
+ ? projectHref(slug, "/approvals")
+ : `${projectHref(slug, "/approvals")}?tab=${tab}`;
+ return (
+ <Link
+ href={href}
+ role="tab"
+ aria-selected={isActive}
+ className={`inline-flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm transition-colors ${
+ isActive
+ ? "border-foreground font-medium text-foreground"
+ : "border-transparent text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {label}
+ {count !== undefined && count > 0 && (
+ <Badge
+ variant={highlightCount ? "default" : "secondary"}
+ className="h-5 px-1.5 text-[10px]"
+ >
+ {count}
+ </Badge>
+ )}
+ </Link>
+ );
+}
diff --git a/src/app/(app)/[project]/tasks/page.tsx b/src/app/(app)/[project]/tasks/page.tsx
index dfe2a162..4ef48d52 100644
--- a/src/app/(app)/[project]/tasks/page.tsx
+++ b/src/app/(app)/[project]/tasks/page.tsx
@@ -13,6 +13,7 @@ const STATUS_GROUPS: Array<{ status: TaskStatus; label: string }> = [
{ status: "proposed", label: "Proposed" },
{ status: "approved", label: "Approved" },
{ status: "running", label: "Running" },
+ { status: "blocked", label: "Blocked on approval" },
{ status: "succeeded", label: "Succeeded" },
{ status: "failed", label: "Failed" },
{ status: "cancelled", label: "Cancelled" },
@@ -22,6 +23,7 @@ const STATUS_VARIANT: Record<TaskStatus, "default" | "secondary" | "outline" | "
proposed: "outline",
approved: "secondary",
running: "default",
+ blocked: "secondary",
succeeded: "secondary",
failed: "destructive",
cancelled: "outline",
diff --git a/src/app/api/chat/route.test.ts b/src/app/api/chat/route.test.ts
index 7bf9a28b..f7580a2b 100644
--- a/src/app/api/chat/route.test.ts
+++ b/src/app/api/chat/route.test.ts
@@ -33,12 +33,6 @@ vi.mock("@/server/openclaw/gateway-client", () => ({
streamChatViaGateway: (...args: unknown[]) => streamChatViaGatewayMock(...args),
}));
-const processOrchestrationBlocksMock = vi.fn();
-vi.mock("@/server/orchestration/process-blocks", () => ({
- processOrchestrationBlocks: (...args: unknown[]) =>
- processOrchestrationBlocksMock(...args),
-}));
-
import { POST } from "./route";
function makeProject(overrides: Partial<Project> = {}): Project {
@@ -93,17 +87,6 @@ async function readSse(res: Response): Promise<{
return { events, raw };
}
-function emptyOrchestrationOutcome() {
- return {
- tasks_created: [],
- task_status_updates: [],
- comments_added: [],
- ask_user: [],
- approvals_requested: [],
- errors: [],
- };
-}
-
// Stream-builder helper: yields the given events one at a time.
async function* makeAgentStream(
evts: Array<{
@@ -118,7 +101,6 @@ describe("POST /api/chat", () => {
beforeEach(() => {
vi.clearAllMocks();
streamChatViaGatewayMock.mockReset();
- processOrchestrationBlocksMock.mockReset();
});
it("returns 400 when body is not valid JSON", async () => {
@@ -204,10 +186,6 @@ describe("POST /api/chat", () => {
slug: "cmo",
});
streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(
makeReq({
message: "hello",
@@ -245,10 +223,6 @@ describe("POST /api/chat", () => {
pending: false,
});
streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
await readSse(res);
expect(findSessionBySessionIdMock).toHaveBeenCalledWith("acme-cmo", "s1");
@@ -267,10 +241,6 @@ describe("POST /api/chat", () => {
});
findSessionBySessionIdMock.mockReturnValueOnce(null);
streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(makeReq({ message: "hi", sessionId: "new-id" }));
await readSse(res);
expect(buildPendingSessionKeyMock).toHaveBeenCalledWith(
@@ -297,10 +267,6 @@ describe("POST /api/chat", () => {
{ kind: "delta", text: "world!" },
]),
);
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toBe("text/event-stream");
@@ -354,10 +320,6 @@ describe("POST /api/chat", () => {
{ kind: "lifecycle", phase: "end" },
]),
);
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
const { events } = await readSse(res);
@@ -383,10 +345,6 @@ describe("POST /api/chat", () => {
);
// The route only invokes orchestration when assistantBuffer has content;
// an error-only stream skips orchestration entirely.
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
const { events } = await readSse(res);
const errEvent = events.find((e) => e.event === "error");
@@ -410,10 +368,6 @@ describe("POST /api/chat", () => {
throw new Error("ws disconnected");
}
streamChatViaGatewayMock.mockReturnValueOnce(throwingStream());
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
const { events } = await readSse(res);
const errEvent = events.find((e) => e.event === "error");
@@ -423,70 +377,12 @@ describe("POST /api/chat", () => {
);
});
- it("emits orchestration event when orchestration produces outcomes", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(
- makeAgentStream([{ kind: "delta", text: "I'll create a task." }]),
- );
- processOrchestrationBlocksMock.mockResolvedValueOnce({
- tasks_created: [
- {
- id: "task-1",
- title: "Install conversion tracking",
- agent_id: "acme-google-ads",
- status: "running",
- },
- ],
- task_status_updates: [],
- comments_added: [],
- ask_user: [],
- approvals_requested: [],
- errors: [],
- });
-
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- const { events } = await readSse(res);
- const orch = events.find((e) => e.event === "orchestration");
- expect(orch).toBeDefined();
- const data = orch!.data as {
- tasks_created: Array<{ id: string; assignee: string }>;
- };
- expect(data.tasks_created[0]!.id).toBe("task-1");
- expect(data.tasks_created[0]!.assignee).toBe("acme-google-ads");
-
- expect(processOrchestrationBlocksMock).toHaveBeenCalledWith(
- "I'll create a task.",
- { project_slug: "acme", agent_id: "acme-cmo" },
- );
- });
-
- it("skips orchestration when the assistant produced no text", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(
- makeAgentStream([
- { kind: "lifecycle", phase: "start" },
- { kind: "lifecycle", phase: "end" },
- ]),
- );
-
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- await readSse(res);
- expect(processOrchestrationBlocksMock).not.toHaveBeenCalled();
- });
-
- it("does NOT emit orchestration event when outcome is empty", async () => {
+ // Orchestration side effects no longer run via post-stream regex parsing —
+ // they happen via the notfair-orchestration MCP server while the agent's
+ // turn is streaming. The chat route is now pure pipe + perf instrumentation,
+ // so the only thing left to assert is that no `orchestration` SSE event is
+ // ever emitted (it's no longer part of the protocol).
+ it("never emits an `orchestration` SSE event (MCP-based now)", async () => {
getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
resolveAgentBySlugMock.mockResolvedValueOnce({
agent_id: "acme-cmo",
@@ -497,36 +393,9 @@ describe("POST /api/chat", () => {
streamChatViaGatewayMock.mockReturnValueOnce(
makeAgentStream([{ kind: "delta", text: "Just chatting." }]),
);
- processOrchestrationBlocksMock.mockResolvedValueOnce(
- emptyOrchestrationOutcome(),
- );
-
const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
const { events } = await readSse(res);
expect(events.find((e) => e.event === "orchestration")).toBeUndefined();
- // Still ends cleanly with done.
expect(events.find((e) => e.event === "done")).toBeDefined();
});
-
- it("survives orchestration throwing — chat reply still completes", async () => {
- getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
- resolveAgentBySlugMock.mockResolvedValueOnce({
- agent_id: "acme-cmo",
- display_name: "CMO",
- slug: "cmo",
- });
- findSessionBySessionIdMock.mockReturnValueOnce(null);
- streamChatViaGatewayMock.mockReturnValueOnce(
- makeAgentStream([{ kind: "delta", text: "hello" }]),
- );
- processOrchestrationBlocksMock.mockRejectedValueOnce(
- new Error("parse failure"),
- );
-
- const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
- const { events } = await readSse(res);
- expect(events.find((e) => e.event === "done")).toBeDefined();
- // No orchestration event when it failed.
- expect(events.find((e) => e.event === "orchestration")).toBeUndefined();
- });
});
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts
index 96fcdfe5..f3ca2a25 100644
--- a/src/app/api/chat/route.ts
+++ b/src/app/api/chat/route.ts
@@ -7,7 +7,6 @@ import {
buildPendingSessionKey,
findSessionBySessionId,
} from "@/server/openclaw/sessions";
-import { processOrchestrationBlocks } from "@/server/orchestration/process-blocks";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -193,44 +192,12 @@ export async function POST(request: Request) {
}
perf.mark("stream_done");
- // Process orchestration blocks emitted by the agent during the turn.
- // Tasks created, status updates, comments, ask_user, approval requests
- // all materialize as DB rows here. Failures are non-fatal — the user
- // still sees the assistant reply; orchestration just doesn't apply.
- if (assistantBuffer.trim().length > 0) {
- try {
- const outcome = await processOrchestrationBlocks(assistantBuffer, {
- project_slug: project.slug,
- agent_id: agentName,
- });
- perf.mark("orchestration_done");
- if (
- outcome.tasks_created.length > 0 ||
- outcome.task_status_updates.length > 0 ||
- outcome.comments_added.length > 0 ||
- outcome.ask_user.length > 0 ||
- outcome.approvals_requested.length > 0 ||
- outcome.errors.length > 0
- ) {
- send("orchestration", {
- tasks_created: outcome.tasks_created.map((t) => ({
- id: t.id,
- title: t.title,
- assignee: t.agent_id,
- status: t.status,
- })),
- task_status_updates: outcome.task_status_updates,
- comments_added: outcome.comments_added,
- ask_user: outcome.ask_user,
- approvals_requested: outcome.approvals_requested,
- errors: outcome.errors,
- });
- }
- } catch (orchErr) {
- // Don't let an orchestration parse failure break the chat reply.
- console.error("[chat] orchestration processing failed:", orchErr);
- }
- }
+ // Orchestration side effects (task creation, status updates,
+ // comments, approvals) now happen via the notfair-orchestration MCP
+ // server — the agent calls those tools mid-stream and the handler
+ // mutates DB rows directly. We no longer regex-scan the assistant
+ // reply for pseudo-XML blocks. See agent-templates.ts for the
+ // procedural teaching pattern.
send("perf", { marks: perf.summary() });
send("done", {});
diff --git a/src/app/api/mcp/orchestration/route.test.ts b/src/app/api/mcp/orchestration/route.test.ts
new file mode 100644
index 00000000..ccc356b7
--- /dev/null
+++ b/src/app/api/mcp/orchestration/route.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+
+const verifyMock = vi.fn();
+vi.mock("@/server/mcp-server/secret", () => ({
+ verifyMcpServerSecret: (...a: unknown[]) => verifyMock(...a),
+}));
+
+const handleJsonRpcMock = vi.fn();
+vi.mock("@/server/mcp-server/jsonrpc", () => ({
+ handleJsonRpc: (...a: unknown[]) => handleJsonRpcMock(...a),
+}));
+
+import { GET, POST } from "./route";
+
+function makePost(headers: Record<string, string>, body: unknown): Request {
+ return new Request("http://localhost/api/mcp/orchestration", {
+ method: "POST",
+ headers,
+ body: typeof body === "string" ? body : JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("POST /api/mcp/orchestration — auth", () => {
+ it("401 when Authorization is missing", async () => {
+ verifyMock.mockReturnValue(false);
+ const res = await POST(makePost({}, { jsonrpc: "2.0", id: 1, method: "ping" }));
+ expect(res.status).toBe(401);
+ });
+
+ it("401 when bearer doesn't verify", async () => {
+ verifyMock.mockReturnValue(false);
+ const res = await POST(
+ makePost(
+ { Authorization: "Bearer wrong" },
+ { jsonrpc: "2.0", id: 1, method: "ping" },
+ ),
+ );
+ expect(res.status).toBe(401);
+ expect(verifyMock).toHaveBeenCalledWith("wrong");
+ });
+
+ it("passes verified bearer through to dispatcher", async () => {
+ verifyMock.mockReturnValue(true);
+ handleJsonRpcMock.mockResolvedValue({
+ jsonrpc: "2.0",
+ id: 1,
+ result: { pong: true },
+ });
+ const res = await POST(
+ makePost(
+ { Authorization: "Bearer ok", "Content-Type": "application/json" },
+ { jsonrpc: "2.0", id: 1, method: "ping" },
+ ),
+ );
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { result: { pong: boolean } };
+ expect(body.result.pong).toBe(true);
+ });
+});
+
+describe("POST /api/mcp/orchestration — body validation", () => {
+ beforeEach(() => {
+ verifyMock.mockReturnValue(true);
+ });
+
+ it("returns Parse error envelope when body isn't valid JSON", async () => {
+ const res = await POST(
+ makePost({ Authorization: "Bearer ok" }, "not json"),
+ );
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { error: { code: number } };
+ expect(body.error.code).toBe(-32700);
+ });
+
+ it("rejects batched requests (array body) with Invalid Request", async () => {
+ const res = await POST(
+ makePost({ Authorization: "Bearer ok" }, [
+ { jsonrpc: "2.0", id: 1, method: "ping" },
+ ]),
+ );
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { error: { code: number; message: string } };
+ expect(body.error.code).toBe(-32600);
+ expect(body.error.message).toMatch(/Batched/);
+ });
+
+ it("rejects non-2.0 jsonrpc payloads", async () => {
+ const res = await POST(
+ makePost({ Authorization: "Bearer ok" }, {
+ jsonrpc: "1.0",
+ id: 1,
+ method: "ping",
+ }),
+ );
+ const body = (await res.json()) as { error: { code: number } };
+ expect(body.error.code).toBe(-32600);
+ });
+
+ it("returns 204 for notifications (handler returns null)", async () => {
+ handleJsonRpcMock.mockResolvedValue(null);
+ const res = await POST(
+ makePost(
+ { Authorization: "Bearer ok" },
+ { jsonrpc: "2.0", method: "notifications/initialized" },
+ ),
+ );
+ expect(res.status).toBe(204);
+ });
+});
+
+describe("GET /api/mcp/orchestration", () => {
+ it("returns the server descriptor without leaking the secret", async () => {
+ const res = await GET();
+ const body = (await res.json()) as { name: string; transport: string };
+ expect(body.name).toBe("notfair-cmo");
+ expect(body.transport).toBe("streamable-http");
+ });
+});
diff --git a/src/app/api/mcp/orchestration/route.ts b/src/app/api/mcp/orchestration/route.ts
new file mode 100644
index 00000000..4c77076f
--- /dev/null
+++ b/src/app/api/mcp/orchestration/route.ts
@@ -0,0 +1,97 @@
+import { NextResponse } from "next/server";
+
+import { handleJsonRpc, type JsonRpcRequest } from "@/server/mcp-server/jsonrpc";
+import { verifyMcpServerSecret } from "@/server/mcp-server/secret";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+/**
+ * MCP server endpoint for OpenClaw-side specialist agents.
+ *
+ * Transport: streamable-http with single-shot JSON responses (no SSE; the
+ * orchestration tools are short-lived and don't stream). OpenClaw accepts
+ * either; plain JSON keeps the code small.
+ *
+ * Auth: shared secret in ~/.notfair-cmo/mcp-server-secret. Loopback-only +
+ * single-user CLI, so a shared bearer is sufficient. Agents pick up the
+ * secret via the per-project `openclaw mcp set` registration step.
+ */
+
+function unauthorized(): Response {
+ return new NextResponse("Unauthorized", { status: 401 });
+}
+
+function bearerFrom(req: Request): string | null {
+ const header = req.headers.get("authorization") ?? req.headers.get("Authorization");
+ if (!header) return null;
+ const m = header.match(/^Bearer\s+(.+)$/i);
+ return m ? m[1]!.trim() : null;
+}
+
+export async function POST(req: Request): Promise<Response> {
+ const bearer = bearerFrom(req);
+ if (!verifyMcpServerSecret(bearer)) return unauthorized();
+
+ let body: unknown;
+ try {
+ body = await req.json();
+ } catch {
+ return NextResponse.json(
+ {
+ jsonrpc: "2.0",
+ id: null,
+ error: { code: -32700, message: "Parse error" },
+ },
+ { status: 200 },
+ );
+ }
+
+ // Batched calls are part of JSON-RPC but MCP's tool flow is one-at-a-time;
+ // we don't need to support arrays today. Reject explicitly so callers see
+ // a clean error rather than a silent miss.
+ if (Array.isArray(body)) {
+ return NextResponse.json(
+ {
+ jsonrpc: "2.0",
+ id: null,
+ error: {
+ code: -32600,
+ message: "Batched requests are not supported by this server.",
+ },
+ },
+ { status: 200 },
+ );
+ }
+
+ const request = body as JsonRpcRequest;
+ if (!request || typeof request !== "object" || request.jsonrpc !== "2.0") {
+ return NextResponse.json(
+ {
+ jsonrpc: "2.0",
+ id: request?.id ?? null,
+ error: { code: -32600, message: "Invalid Request" },
+ },
+ { status: 200 },
+ );
+ }
+
+ const response = await handleJsonRpc(request);
+ if (response === null) {
+ // Notification — JSON-RPC mandates no body. Return 204 so the client
+ // doesn't try to parse anything.
+ return new Response(null, { status: 204 });
+ }
+ return NextResponse.json(response, { status: 200 });
+}
+
+export async function GET(): Promise<Response> {
+ // Some MCP clients ping with GET first to discover the endpoint. Return a
+ // tiny shape so they know this is an MCP HTTP server (without leaking the
+ // secret-check; auth still applies to POST).
+ return NextResponse.json({
+ name: "notfair-cmo",
+ transport: "streamable-http",
+ note: "POST JSON-RPC with Bearer auth. See ~/.notfair-cmo/mcp-server-secret.",
+ });
+}
diff --git a/src/components/agent-task-workspace.test.tsx b/src/components/agent-task-workspace.test.tsx
index 726c5fba..17a11289 100644
--- a/src/components/agent-task-workspace.test.tsx
+++ b/src/components/agent-task-workspace.test.tsx
@@ -262,7 +262,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "agent:demo-google-ads:thr-1",
initialEvents: [],
- initialByteOffset: 0,
+ initialByteOffset: 0, approvals: [],
},
})}
/>,
@@ -286,7 +286,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "agent:demo-google-ads:thr-1",
initialEvents: [],
- initialByteOffset: 0,
+ initialByteOffset: 0, approvals: [],
},
})}
/>,
@@ -309,7 +309,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0,
+ initialByteOffset: 0, approvals: [],
},
})}
/>,
@@ -330,7 +330,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0,
+ initialByteOffset: 0, approvals: [],
},
})}
/>,
@@ -351,7 +351,7 @@ describe("AgentTaskWorkspace CancelTaskButton", () => {
threadId: "thr",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0,
+ initialByteOffset: 0, approvals: [],
},
})}
/>,
diff --git a/src/components/agent-task-workspace.tsx b/src/components/agent-task-workspace.tsx
index 63593ed9..05f2c435 100644
--- a/src/components/agent-task-workspace.tsx
+++ b/src/components/agent-task-workspace.tsx
@@ -13,6 +13,7 @@ import {
} from "lucide-react";
import { toast } from "sonner";
+import { ApprovalCard } from "@/components/approval-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { LiveTranscript } from "@/components/live-transcript";
@@ -22,12 +23,13 @@ import { cancelTaskAction } from "@/server/actions/tasks";
import { cn } from "@/lib/utils";
import { projectHref } from "@/lib/project-href";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
-import type { Task, TaskStatus } from "@/types";
+import type { Approval, Task, TaskStatus } from "@/types";
-const TASK_IN_FLIGHT: TaskStatus[] = ["proposed", "approved", "running"];
+const TASK_IN_FLIGHT: TaskStatus[] = ["proposed", "approved", "running", "blocked"];
const STATUS_GROUPS: Array<{ status: TaskStatus; label: string }> = [
{ status: "running", label: "Running" },
+ { status: "blocked", label: "Waiting on approval" },
{ status: "proposed", label: "Proposed" },
{ status: "approved", label: "Approved" },
{ status: "succeeded", label: "Done" },
@@ -42,6 +44,7 @@ const STATUS_VARIANT: Record<
proposed: "outline",
approved: "secondary",
running: "default",
+ blocked: "secondary",
succeeded: "secondary",
failed: "destructive",
cancelled: "outline",
@@ -53,6 +56,9 @@ type SelectedTaskBundle = {
sessionKey: string;
initialEvents: TranscriptEvent[];
initialByteOffset: number;
+ /** Approvals attached to this task, newest first. Rendered above the
+ * transcript so the user can act on a pending one without leaving the chat. */
+ approvals: Approval[];
};
type Props = {
@@ -295,19 +301,52 @@ function SelectedTaskPanel({
},
[isInFlight, router],
);
+ // Surface the actionable approval up front so the user doesn't have to
+ // navigate to /approvals to unblock the agent. Resolved rows would only
+ // add noise here, so they're filtered out — the audit trail lives on the
+ // dedicated Resolved tab. Most blocked tasks have exactly one pending
+ // request at a time; render whichever's actionable, plus any
+ // revision_requested that's still in play.
+ const liveApprovals = selected.approvals.filter(
+ (a) => a.status === "pending" || a.status === "revision_requested",
+ );
+ // When the task is parked in `blocked`, build a short "why" string so the
+ // LiveTranscript can replace its forward-motion indicator ("thinking…",
+ // "wrapping up…") with an honest paused-state pill. The most common reason
+ // is a pending approval, and we have those right here.
+ const blockedReason =
+ selected.task.status === "blocked"
+ ? liveApprovals.length > 0
+ ? liveApprovals.length === 1
+ ? "waiting on approval"
+ : `waiting on ${liveApprovals.length} approvals`
+ : "waiting for the gating condition to resolve"
+ : undefined;
return (
- <LiveTranscript
- key={selected.task.id}
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- agentDisplayName={agentDisplayName}
- threadId={selected.threadId}
- sessionKey={selected.sessionKey}
- initialEvents={selected.initialEvents}
- initialByteOffset={selected.initialByteOffset}
- composerDisabled={isInFlight}
- onPolled={onPolled}
- />
+ <div className="flex h-full min-h-0 flex-col">
+ {liveApprovals.length > 0 && (
+ <div className="mx-auto w-full max-w-3xl space-y-3 px-6 pt-4">
+ {liveApprovals.map((a) => (
+ <ApprovalCard key={a.id} approval={a} />
+ ))}
+ </div>
+ )}
+ <div className="min-h-0 flex-1">
+ <LiveTranscript
+ key={selected.task.id}
+ projectSlug={projectSlug}
+ agentSlug={agentSlug}
+ agentDisplayName={agentDisplayName}
+ threadId={selected.threadId}
+ sessionKey={selected.sessionKey}
+ initialEvents={selected.initialEvents}
+ initialByteOffset={selected.initialByteOffset}
+ composerDisabled={isInFlight}
+ blockedReason={blockedReason}
+ onPolled={onPolled}
+ />
+ </div>
+ </div>
);
}
@@ -425,6 +464,8 @@ function StatusGlyph({ status }: { status: TaskStatus }) {
return <CircleDot className="size-3.5 text-sky-600" />;
case "running":
return <Loader2 className="size-3.5 animate-spin text-sky-600" />;
+ case "blocked":
+ return <CircleDot className="size-3.5 text-amber-600" />;
case "proposed":
default:
return <Circle className="size-3.5 text-muted-foreground" />;
diff --git a/src/components/app-sidebar.test.tsx b/src/components/app-sidebar.test.tsx
index 2e2d540d..5eee1fef 100644
--- a/src/components/app-sidebar.test.tsx
+++ b/src/components/app-sidebar.test.tsx
@@ -4,7 +4,7 @@ import { render, screen, cleanup } from "@testing-library/react";
const listProjects = vi.fn();
const getActiveProject = vi.fn();
-const pendingApprovalCount = vi.fn();
+const actionableApprovalCount = vi.fn();
const listProjectAgents = vi.fn();
const inFlightCountsByAgent = vi.fn();
const discoverGateway = vi.fn();
@@ -18,7 +18,7 @@ vi.mock("@/server/active-project", () => ({
}));
vi.mock("@/server/db/approvals", () => ({
- pendingApprovalCount: (...args: unknown[]) => pendingApprovalCount(...args),
+ actionableApprovalCount: (...args: unknown[]) => actionableApprovalCount(...args),
}));
vi.mock("@/server/agent-meta", () => ({
@@ -120,7 +120,7 @@ const projects = [
beforeEach(() => {
listProjects.mockReset();
getActiveProject.mockReset();
- pendingApprovalCount.mockReset();
+ actionableApprovalCount.mockReset();
listProjectAgents.mockReset();
inFlightCountsByAgent.mockReset();
discoverGateway.mockReset();
@@ -142,7 +142,7 @@ describe("AppSidebar", () => {
it("renders the project switcher with the active slug", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(0);
+ actionableApprovalCount.mockReturnValue(0);
listProjectAgents.mockResolvedValue([]);
inFlightCountsByAgent.mockReturnValue(new Map());
await renderSidebar();
@@ -163,7 +163,7 @@ describe("AppSidebar", () => {
it("renders project navigation links scoped to the active slug", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(0);
+ actionableApprovalCount.mockReturnValue(0);
listProjectAgents.mockResolvedValue([]);
inFlightCountsByAgent.mockReturnValue(new Map());
await renderSidebar();
@@ -200,7 +200,7 @@ describe("AppSidebar", () => {
it("shows the approvals badge with the pending count when non-zero", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(7);
+ actionableApprovalCount.mockReturnValue(7);
listProjectAgents.mockResolvedValue([]);
inFlightCountsByAgent.mockReturnValue(new Map());
await renderSidebar();
@@ -210,7 +210,7 @@ describe("AppSidebar", () => {
it("omits the badge when approvals are zero", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(0);
+ actionableApprovalCount.mockReturnValue(0);
listProjectAgents.mockResolvedValue([]);
inFlightCountsByAgent.mockReturnValue(new Map());
await renderSidebar();
@@ -220,7 +220,7 @@ describe("AppSidebar", () => {
it("forwards agents and in-flight counts to AgentNav", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(0);
+ actionableApprovalCount.mockReturnValue(0);
listProjectAgents.mockResolvedValue([
{
agent_id: "alpha-cmo",
@@ -241,7 +241,7 @@ describe("AppSidebar", () => {
it("flips the liveness flag on when any agent has in-flight work", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(0);
+ actionableApprovalCount.mockReturnValue(0);
listProjectAgents.mockResolvedValue([]);
inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 1]]));
await renderSidebar();
@@ -251,7 +251,7 @@ describe("AppSidebar", () => {
it("keeps the liveness flag off when nothing is running", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(0);
+ actionableApprovalCount.mockReturnValue(0);
listProjectAgents.mockResolvedValue([]);
inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 0]]));
await renderSidebar();
@@ -261,7 +261,7 @@ describe("AppSidebar", () => {
it("shows the CreateAgentButton when a project is active", async () => {
listProjects.mockReturnValue(projects);
getActiveProject.mockResolvedValue(projects[0]);
- pendingApprovalCount.mockReturnValue(0);
+ actionableApprovalCount.mockReturnValue(0);
listProjectAgents.mockResolvedValue([]);
inFlightCountsByAgent.mockReturnValue(new Map());
await renderSidebar();
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index adaf617c..3fe98afe 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -25,7 +25,7 @@ import {
} from "lucide-react";
import { listProjects } from "@/server/db/projects";
import { getActiveProject } from "@/server/active-project";
-import { pendingApprovalCount } from "@/server/db/approvals";
+import { actionableApprovalCount } from "@/server/db/approvals";
import { listProjectAgents } from "@/server/agent-meta";
import { inFlightCountsByAgent } from "@/server/db/tasks";
import { projectHref } from "@/lib/project-href";
@@ -56,7 +56,8 @@ const NAV: NavItem[] = [
export async function AppSidebar() {
const projects = listProjects();
const active = await getActiveProject();
- const approvalsBadge = active ? pendingApprovalCount(active.slug) : 0;
+ // Badge counts anything actionable: pending + revision_requested.
+ const approvalsBadge = active ? actionableApprovalCount(active.slug) : 0;
const agentEntries = active ? await listProjectAgents(active.slug) : [];
const inFlightCounts: Record<string, number> = {};
if (active) {
diff --git a/src/components/approval-card.test.tsx b/src/components/approval-card.test.tsx
index c1eeb3ab..5ad264b8 100644
--- a/src/components/approval-card.test.tsx
+++ b/src/components/approval-card.test.tsx
@@ -4,12 +4,14 @@ import { render, screen, fireEvent, waitFor } from "@testing-library/react";
const approveMock = vi.fn();
const rejectMock = vi.fn();
+const createPolicyMock = vi.fn();
const toastErrorMock = vi.fn();
const toastSuccessMock = vi.fn();
vi.mock("@/server/actions/approvals", () => ({
approveAction: (...a: unknown[]) => approveMock(...a),
rejectAction: (...a: unknown[]) => rejectMock(...a),
+ createPolicyAction: (...a: unknown[]) => createPolicyMock(...a),
}));
vi.mock("sonner", () => ({
@@ -27,12 +29,16 @@ function makeApproval(overrides: Partial<Approval> = {}): Approval {
id: "ap-1",
project_slug: "demo",
agent_id: "demo-google-ads",
+ task_id: null,
action_summary: "Raise CPC bid on /signup keyword",
action_type: "bid_change",
cost_estimate_usd: 12.5,
reasoning: null,
payload_json: "{}",
status: "pending",
+ decision_note: null,
+ decided_by_kind: null,
+ decided_by_id: null,
created_at: new Date(Date.now() - 90_000).toISOString(),
resolved_at: null,
...overrides,
@@ -42,15 +48,17 @@ function makeApproval(overrides: Partial<Approval> = {}): Approval {
beforeEach(() => {
approveMock.mockReset();
rejectMock.mockReset();
+ createPolicyMock.mockReset();
toastErrorMock.mockReset();
toastSuccessMock.mockReset();
});
-describe("ApprovalCard", () => {
- it("renders summary, action-type label, cost, agent, and a relative timestamp", () => {
+describe("ApprovalCard — header & metadata", () => {
+ it("renders summary, action-type label, status pill, cost, agent, timestamp", () => {
render(<ApprovalCard approval={makeApproval()} />);
expect(screen.getByText("Raise CPC bid on /signup keyword")).toBeInTheDocument();
expect(screen.getByText("Bid change")).toBeInTheDocument();
+ expect(screen.getByText("Pending")).toBeInTheDocument();
expect(screen.getByText("$12.50")).toBeInTheDocument();
expect(screen.getByText("demo-google-ads")).toBeInTheDocument();
expect(screen.getByText(/m ago|s ago/)).toBeInTheDocument();
@@ -61,93 +69,166 @@ describe("ApprovalCard", () => {
expect(screen.queryByText(/Cost:/)).not.toBeInTheDocument();
});
- it("hides the Why? toggle when reasoning is null", () => {
- render(<ApprovalCard approval={makeApproval({ reasoning: null })} />);
- expect(screen.queryByText("Why?")).not.toBeInTheDocument();
+ it("renders reasoning inline (no Why? toggle)", () => {
+ render(
+ <ApprovalCard approval={makeApproval({ reasoning: "Predicted +18% CTR" })} />,
+ );
+ expect(screen.getByText("Predicted +18% CTR")).toBeInTheDocument();
+ // Old "Why?" toggle should be gone.
+ expect(screen.queryByRole("button", { name: "Why?" })).not.toBeInTheDocument();
+ });
+
+ it("does NOT render a thread or comment input (removed in this iteration)", () => {
+ render(<ApprovalCard approval={makeApproval()} />);
+ expect(screen.queryByPlaceholderText("Add a comment…")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Comment" })).not.toBeInTheDocument();
});
- it("toggles reasoning visibility when Why? is clicked", () => {
+ it("shows the 'Auto by policy' badge when decided_by_kind=policy", () => {
render(
<ApprovalCard
- approval={makeApproval({ reasoning: "Predicted +18% CTR" })}
+ approval={makeApproval({
+ status: "approved",
+ decided_by_kind: "policy",
+ decided_by_id: "pol-1",
+ resolved_at: new Date().toISOString(),
+ })}
/>,
);
- expect(screen.queryByText("Predicted +18% CTR")).not.toBeInTheDocument();
- fireEvent.click(screen.getByText("Why?"));
- expect(screen.getByText("Predicted +18% CTR")).toBeInTheDocument();
- fireEvent.click(screen.getByText("Why?"));
- expect(screen.queryByText("Predicted +18% CTR")).not.toBeInTheDocument();
+ expect(screen.getByText("Auto by policy")).toBeInTheDocument();
+ });
+
+ it("sets the region aria-label to action_summary", () => {
+ render(<ApprovalCard approval={makeApproval({ action_summary: "X-summary" })} />);
+ expect(screen.getByRole("region", { name: "X-summary" })).toBeInTheDocument();
});
+});
- it("approve button calls approveAction and shows success toast on ok", async () => {
+describe("ApprovalCard — approve (one-click)", () => {
+ it("calls approveAction with just the id and shows success toast", async () => {
approveMock.mockResolvedValue({ ok: true });
render(<ApprovalCard approval={makeApproval()} />);
fireEvent.click(screen.getByRole("button", { name: "Approve" }));
await waitFor(() => {
expect(approveMock).toHaveBeenCalledWith("ap-1");
- expect(toastSuccessMock).toHaveBeenCalledWith("Approved — running now");
+ expect(toastSuccessMock).toHaveBeenCalledWith(
+ "Approved — agent is being notified",
+ );
});
});
- it("approve button surfaces server error via toast", async () => {
+ it("surfaces server error via toast", async () => {
approveMock.mockResolvedValue({ ok: false, error: "boom" });
render(<ApprovalCard approval={makeApproval()} />);
fireEvent.click(screen.getByRole("button", { name: "Approve" }));
await waitFor(() => {
expect(toastErrorMock).toHaveBeenCalledWith("boom");
});
- expect(toastSuccessMock).not.toHaveBeenCalled();
});
+});
- it("approve uses fallback error string when server omits one", async () => {
- approveMock.mockResolvedValue({ ok: false });
+describe("ApprovalCard — Deny modal", () => {
+ it("clicking Deny opens the modal but does not call rejectAction yet", () => {
render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Approve" }));
- await waitFor(() => {
- expect(toastErrorMock).toHaveBeenCalledWith("Failed to approve");
- });
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ expect(screen.getByText("What do you want to change?")).toBeInTheDocument();
+ expect(rejectMock).not.toHaveBeenCalled();
});
- it("reject button calls rejectAction and shows success toast", async () => {
+ it("'Reject without comments' rejects with no note", async () => {
rejectMock.mockResolvedValue({ ok: true });
render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Reject" }));
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ fireEvent.click(
+ screen.getByRole("button", { name: "Reject without comments" }),
+ );
await waitFor(() => {
- expect(rejectMock).toHaveBeenCalledWith("ap-1");
+ expect(rejectMock).toHaveBeenCalledWith("ap-1", undefined);
expect(toastSuccessMock).toHaveBeenCalledWith("Rejected");
});
});
- it("reject surfaces server error with fallback string", async () => {
- rejectMock.mockResolvedValue({ ok: false });
+ it("'Reject with comment' sends the typed note", async () => {
+ rejectMock.mockResolvedValue({ ok: true });
render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Reject" }));
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ fireEvent.change(
+ screen.getByPlaceholderText(/Wait until next week/),
+ { target: { value: "Hold off until legal review" } },
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Reject with comment" }));
await waitFor(() => {
- expect(toastErrorMock).toHaveBeenCalledWith("Failed to reject");
+ expect(rejectMock).toHaveBeenCalledWith(
+ "ap-1",
+ "Hold off until legal review",
+ );
+ expect(toastSuccessMock).toHaveBeenCalledWith("Rejected with feedback");
});
});
- it("renders different action-type labels", () => {
- const { rerender } = render(
- <ApprovalCard approval={makeApproval({ action_type: "spend" })} />,
- );
- expect(screen.getByText("Spend")).toBeInTheDocument();
- rerender(
- <ApprovalCard approval={makeApproval({ action_type: "content_publishing" })} />,
- );
- expect(screen.getByText("Content")).toBeInTheDocument();
- rerender(
- <ApprovalCard approval={makeApproval({ action_type: "new_channel" })} />,
+ it("'Reject with comment' button is disabled until the user types something", () => {
+ render(<ApprovalCard approval={makeApproval()} />);
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ const withCommentBtn = screen.getByRole("button", {
+ name: "Reject with comment",
+ });
+ expect(withCommentBtn).toBeDisabled();
+ fireEvent.change(
+ screen.getByPlaceholderText(/Wait until next week/),
+ { target: { value: "x" } },
);
- expect(screen.getByText("New channel")).toBeInTheDocument();
- rerender(<ApprovalCard approval={makeApproval({ action_type: "other" })} />);
- expect(screen.getByText("Other")).toBeInTheDocument();
+ expect(withCommentBtn).not.toBeDisabled();
});
+});
- it("sets the region aria-label to action_summary", () => {
- render(<ApprovalCard approval={makeApproval({ action_summary: "X-summary" })} />);
- expect(
- screen.getByRole("region", { name: "X-summary" }),
- ).toBeInTheDocument();
+describe("ApprovalCard — Always approve policy", () => {
+ it("opens the policy form scoped to this agent by default", () => {
+ render(<ApprovalCard approval={makeApproval()} />);
+ fireEvent.click(screen.getByRole("button", { name: /Always approve/ }));
+ expect(screen.getByText("Create auto-approval policy")).toBeInTheDocument();
+ });
+
+ it("Save policy calls createPolicyAction with the right shape", async () => {
+ createPolicyMock.mockResolvedValue({ ok: true, policy_id: "pol-1" });
+ render(<ApprovalCard approval={makeApproval()} />);
+ fireEvent.click(screen.getByRole("button", { name: /Always approve/ }));
+ fireEvent.click(screen.getByRole("button", { name: "Save policy" }));
+ await waitFor(() => {
+ const payload = createPolicyMock.mock.calls[0]![0]!;
+ expect(payload.project_slug).toBe("demo");
+ expect(payload.action_type).toBe("bid_change");
+ expect(payload.agent_id).toBe("demo-google-ads");
+ expect(payload.auto_decision).toBe("approve");
+ });
+ });
+
+ it("scope=any sets agent_id to null", async () => {
+ createPolicyMock.mockResolvedValue({ ok: true });
+ render(<ApprovalCard approval={makeApproval()} />);
+ fireEvent.click(screen.getByRole("button", { name: /Always approve/ }));
+ fireEvent.click(screen.getByLabelText(/From any agent/));
+ fireEvent.click(screen.getByRole("button", { name: "Save policy" }));
+ await waitFor(() => {
+ const payload = createPolicyMock.mock.calls[0]![0]!;
+ expect(payload.agent_id).toBeNull();
+ });
+ });
+});
+
+describe("ApprovalCard — resolved state", () => {
+ it("hides decision buttons and shows decision_note when resolved", () => {
+ render(
+ <ApprovalCard
+ approval={makeApproval({
+ status: "approved",
+ decision_note: "Ship it.",
+ resolved_at: new Date().toISOString(),
+ })}
+ />,
+ );
+ expect(screen.queryByRole("button", { name: "Approve" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Deny" })).not.toBeInTheDocument();
+ expect(screen.getByText("Decision note")).toBeInTheDocument();
+ expect(screen.getByText("Ship it.")).toBeInTheDocument();
});
});
diff --git a/src/components/approval-card.tsx b/src/components/approval-card.tsx
index c8c71687..8cd0c80b 100644
--- a/src/components/approval-card.tsx
+++ b/src/components/approval-card.tsx
@@ -1,12 +1,25 @@
"use client";
import { useState, useTransition } from "react";
-import { ChevronDown } from "lucide-react";
+import { ShieldCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { toast } from "sonner";
-import { approveAction, rejectAction } from "@/server/actions/approvals";
+import {
+ approveAction,
+ createPolicyAction,
+ rejectAction,
+} from "@/server/actions/approvals";
import type { Approval } from "@/types";
const ACTION_TYPE_LABEL: Record<Approval["action_type"], string> = {
@@ -18,6 +31,17 @@ const ACTION_TYPE_LABEL: Record<Approval["action_type"], string> = {
other: "Other",
};
+const STATUS_VARIANT: Record<
+ Approval["status"],
+ { label: string; variant: "default" | "secondary" | "outline" | "destructive" }
+> = {
+ pending: { label: "Pending", variant: "default" },
+ revision_requested: { label: "Revision requested", variant: "secondary" },
+ approved: { label: "Approved", variant: "outline" },
+ rejected: { label: "Rejected", variant: "destructive" },
+ expired: { label: "Expired", variant: "outline" },
+};
+
function formatUsd(n: number) {
return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
}
@@ -30,70 +54,253 @@ function timeAgo(iso: string) {
return `${Math.floor(seconds / 86400)}d ago`;
}
-export function ApprovalCard({ approval }: { approval: Approval }) {
- const [expanded, setExpanded] = useState(false);
+export type ApprovalCardProps = {
+ approval: Approval;
+};
+
+export function ApprovalCard({ approval }: ApprovalCardProps) {
+ const [denyOpen, setDenyOpen] = useState(false);
+ const [denyNote, setDenyNote] = useState("");
+ const [showPolicyForm, setShowPolicyForm] = useState(false);
+ const [policyCostCap, setPolicyCostCap] = useState("");
+ const [policyScope, setPolicyScope] = useState<"agent" | "any">("agent");
const [pending, start] = useTransition();
+ const actionable =
+ approval.status === "pending" || approval.status === "revision_requested";
+ const statusBadge = STATUS_VARIANT[approval.status];
+
function approve() {
start(async () => {
const r = await approveAction(approval.id);
if (!r.ok) toast.error(r.error ?? "Failed to approve");
- else toast.success("Approved — running now");
+ else toast.success("Approved — agent is being notified");
});
}
- function reject() {
+ function rejectWith(note: string | undefined) {
start(async () => {
- const r = await rejectAction(approval.id);
+ const r = await rejectAction(approval.id, note);
if (!r.ok) toast.error(r.error ?? "Failed to reject");
- else toast.success("Rejected");
+ else {
+ toast.success(note ? "Rejected with feedback" : "Rejected");
+ setDenyOpen(false);
+ setDenyNote("");
+ }
+ });
+ }
+ function alwaysApprove() {
+ start(async () => {
+ const cap = policyCostCap.trim();
+ const max = cap ? Number(cap) : null;
+ if (cap && (!Number.isFinite(max) || max! < 0)) {
+ toast.error("Cost cap must be a non-negative number.");
+ return;
+ }
+ const r = await createPolicyAction({
+ project_slug: approval.project_slug,
+ action_type: approval.action_type,
+ agent_id: policyScope === "agent" ? approval.agent_id : null,
+ max_cost_usd: max,
+ auto_decision: "approve",
+ note: `Always approve ${ACTION_TYPE_LABEL[approval.action_type]} requests${
+ policyScope === "agent" ? ` from ${approval.agent_id}` : ""
+ }${max != null ? ` ≤ ${formatUsd(max)}` : ""}.`,
+ });
+ if (!r.ok) toast.error(r.error ?? "Failed to save policy");
+ else {
+ toast.success("Saved. Future matching requests are auto-approved.");
+ setShowPolicyForm(false);
+ setPolicyCostCap("");
+ }
});
}
return (
- <Card className="overflow-hidden" role="region" aria-label={approval.action_summary}>
- <CardContent className="space-y-3 py-4">
- <div className="flex items-start justify-between gap-3">
- <div className="space-y-1">
- <Badge variant="outline" className="text-[10px]">
- {ACTION_TYPE_LABEL[approval.action_type]}
- </Badge>
- <p className="text-sm font-medium">{approval.action_summary}</p>
- <p className="text-xs text-muted-foreground">
- {approval.cost_estimate_usd > 0 && (
- <>
- Cost: <span className="font-medium">{formatUsd(approval.cost_estimate_usd)}</span> ·{" "}
- </>
- )}
- Agent <span className="font-mono">{approval.agent_id}</span> · {timeAgo(approval.created_at)}
- </p>
+ <>
+ <Card
+ className="overflow-hidden"
+ role="region"
+ aria-label={approval.action_summary}
+ data-status={approval.status}
+ >
+ <CardContent className="space-y-3 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <Badge variant="outline" className="text-[10px]">
+ {ACTION_TYPE_LABEL[approval.action_type]}
+ </Badge>
+ <Badge variant={statusBadge.variant} className="text-[10px]">
+ {statusBadge.label}
+ </Badge>
+ {approval.decided_by_kind === "policy" && (
+ <Badge variant="outline" className="gap-1 text-[10px]">
+ <ShieldCheck className="size-3" />
+ Auto by policy
+ </Badge>
+ )}
+ </div>
+ <p className="text-sm font-medium leading-snug">
+ {approval.action_summary}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {approval.cost_estimate_usd > 0 && (
+ <>
+ Cost:{" "}
+ <span className="font-medium">
+ {formatUsd(approval.cost_estimate_usd)}
+ </span>{" "}
+ ·{" "}
+ </>
+ )}
+ Agent <span className="font-mono">{approval.agent_id}</span> ·{" "}
+ {timeAgo(approval.created_at)}
+ </p>
+ </div>
</div>
- </div>
- {approval.reasoning && (
- <button
- type="button"
- onClick={() => setExpanded((e) => !e)}
- className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
- >
- <ChevronDown className={`size-3 transition-transform ${expanded ? "rotate-180" : ""}`} />
- Why?
- </button>
- )}
- {expanded && approval.reasoning && (
- <p className="rounded-md bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap">
- {approval.reasoning}
- </p>
- )}
+ {/* Reasoning is shown inline (no toggle) when present — there's no
+ separate Why? button to discover the rationale. */}
+ {approval.reasoning && (
+ <p className="rounded-md bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap">
+ {approval.reasoning}
+ </p>
+ )}
+
+ {approval.decision_note && !actionable && (
+ <div className="rounded-md border border-dashed border-border bg-muted/30 p-3 text-xs">
+ <div className="text-[10px] uppercase tracking-wide text-muted-foreground">
+ Decision note
+ </div>
+ <p className="mt-1 whitespace-pre-wrap leading-relaxed">
+ {approval.decision_note}
+ </p>
+ </div>
+ )}
+
+ {actionable && (
+ <div className="space-y-3">
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" onClick={approve} disabled={pending}>
+ Approve
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setDenyOpen(true)}
+ disabled={pending}
+ >
+ Deny
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => setShowPolicyForm((s) => !s)}
+ disabled={pending}
+ >
+ <ShieldCheck className="size-3.5" />
+ Always approve
+ </Button>
+ </div>
+
+ {showPolicyForm && (
+ <div className="space-y-2 rounded-md border border-border bg-muted/40 p-3 text-xs">
+ <p className="font-medium">Create auto-approval policy</p>
+ <p className="text-muted-foreground">
+ Future{" "}
+ <span className="font-mono">
+ {ACTION_TYPE_LABEL[approval.action_type]}
+ </span>{" "}
+ requests that match will be approved without asking.
+ </p>
+ <fieldset className="flex flex-wrap items-center gap-3 pt-1">
+ <label className="flex items-center gap-1.5">
+ <input
+ type="radio"
+ name={`scope-${approval.id}`}
+ checked={policyScope === "agent"}
+ onChange={() => setPolicyScope("agent")}
+ />
+ Only from{" "}
+ <span className="font-mono">{approval.agent_id}</span>
+ </label>
+ <label className="flex items-center gap-1.5">
+ <input
+ type="radio"
+ name={`scope-${approval.id}`}
+ checked={policyScope === "any"}
+ onChange={() => setPolicyScope("any")}
+ />
+ From any agent
+ </label>
+ </fieldset>
+ <label className="flex items-center gap-2">
+ Cost cap (USD, optional):
+ <Input
+ type="number"
+ min="0"
+ step="0.01"
+ value={policyCostCap}
+ onChange={(e) => setPolicyCostCap(e.target.value)}
+ placeholder="∞"
+ className="h-7 w-28 text-xs"
+ />
+ </label>
+ <div className="flex gap-2 pt-1">
+ <Button size="sm" onClick={alwaysApprove} disabled={pending}>
+ Save policy
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => setShowPolicyForm(false)}
+ disabled={pending}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </CardContent>
+ </Card>
- <div className="flex gap-2">
- <Button size="sm" onClick={approve} disabled={pending}>
- Approve
- </Button>
- <Button size="sm" variant="outline" onClick={reject} disabled={pending}>
- Reject
- </Button>
- </div>
- </CardContent>
- </Card>
+ <Dialog open={denyOpen} onOpenChange={(open) => !pending && setDenyOpen(open)}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>What do you want to change?</DialogTitle>
+ <DialogDescription>
+ Optional. Anything you type here is sent back to the agent so it
+ can adjust its next attempt.
+ </DialogDescription>
+ </DialogHeader>
+ <textarea
+ value={denyNote}
+ onChange={(e) => setDenyNote(e.target.value)}
+ placeholder="e.g. Wait until next week so we can review the landing page first."
+ rows={4}
+ className="w-full resize-y rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
+ disabled={pending}
+ autoFocus
+ />
+ <DialogFooter className="gap-2 sm:gap-2">
+ <Button
+ variant="outline"
+ onClick={() => rejectWith(undefined)}
+ disabled={pending}
+ >
+ Reject without comments
+ </Button>
+ <Button
+ onClick={() => rejectWith(denyNote.trim() || undefined)}
+ disabled={pending || !denyNote.trim()}
+ >
+ Reject with comment
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
);
}
diff --git a/src/components/live-transcript.test.tsx b/src/components/live-transcript.test.tsx
index a176d77c..e1c853a4 100644
--- a/src/components/live-transcript.test.tsx
+++ b/src/components/live-transcript.test.tsx
@@ -32,10 +32,6 @@ vi.mock("@/components/markdown", () => ({
),
}));
-vi.mock("@/server/orchestration/blocks", () => ({
- stripOrchestrationBlocks: (s: string) => s,
-}));
-
import { LiveTranscript } from "./live-transcript";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
@@ -213,18 +209,12 @@ describe("LiveTranscript rendering events", () => {
expect(screen.getByText(/2 steps/i)).toBeInTheDocument();
});
- it("ignores assistant text that becomes empty after orchestration stripping", async () => {
- // Override the mock just for this test by temporarily replacing strip fn.
- const blocks = await import("@/server/orchestration/blocks");
- const spy = vi
- .spyOn(blocks, "stripOrchestrationBlocks")
- .mockImplementation(() => " ");
+ it("renders nothing for an assistant message whose body is whitespace-only", () => {
const events: TranscriptEvent[] = [
- { kind: "assistant_text", id: "a1", ts: 1, body: "<task>only block</task>" },
+ { kind: "assistant_text", id: "a1", ts: 1, body: " " },
];
render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-strip" })} />);
expect(screen.queryByTestId("markdown")).not.toBeInTheDocument();
- spy.mockRestore();
});
it("returns null for system 'unknown' events (renders no row)", () => {
diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsx
index 61288bef..2c7d5aef 100644
--- a/src/components/live-transcript.tsx
+++ b/src/components/live-transcript.tsx
@@ -36,7 +36,6 @@ import {
parseSlashMessage,
type SlashCommand,
} from "@/lib/slash-commands";
-import { stripOrchestrationBlocks } from "@/server/orchestration/blocks";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
import { projectHref } from "@/lib/project-href";
@@ -59,6 +58,12 @@ type Props = {
* shouldn't send mid-run input). Default: composer always enabled.
*/
composerDisabled?: boolean;
+ /**
+ * Set when the agent's task is parked in `blocked` (e.g., waiting on a
+ * pending approval). Replaces the "thinking…" / "wrapping up…" indicator
+ * — those imply forward motion, but a blocked task is dormant by design.
+ */
+ blockedReason?: string;
/**
* When set, on each successful poll we call this so the parent can
* react to JSONL growth (e.g., trigger router.refresh to refetch task
@@ -88,6 +93,7 @@ export function LiveTranscript({
initialEvents,
initialByteOffset,
composerDisabled = false,
+ blockedReason,
onPolled,
autoKickoff = false,
kickoffMessage,
@@ -430,11 +436,15 @@ export function LiveTranscript({
)}
{showThinking && (
<li>
- <WorkingStatus
- agentDisplayName={agentDisplayName}
- events={events}
- turnStartedAt={turnStartedAt}
- />
+ {blockedReason ? (
+ <BlockedStatus reason={blockedReason} />
+ ) : (
+ <WorkingStatus
+ agentDisplayName={agentDisplayName}
+ events={events}
+ turnStartedAt={turnStartedAt}
+ />
+ )}
</li>
)}
</ol>
@@ -768,11 +778,12 @@ function UserBubble({ body }: { body: string }) {
}
function AssistantText({ body }: { body: string }) {
- const cleanBody = stripOrchestrationBlocks(body);
- if (cleanBody.trim() === "") return null;
+ // Orchestration side effects now go through MCP tool calls, not
+ // pseudo-XML blocks. We render the assistant's prose as-is.
+ if (body.trim() === "") return null;
return (
<div className="text-sm leading-relaxed">
- <Markdown>{cleanBody}</Markdown>
+ <Markdown>{body}</Markdown>
</div>
);
}
@@ -909,6 +920,32 @@ function ToolRow({ entry }: { entry: ToolEntry }) {
);
}
+/**
+ * Replaces WorkingStatus when the task is parked in `blocked`. The agent
+ * isn't currently running — it's dormant until the gating condition (most
+ * often a pending approval) resolves. Showing "thinking…" or "wrapping
+ * up…" here misleads the user into thinking work is still happening.
+ */
+function BlockedStatus({ reason }: { reason: string }) {
+ return (
+ <div className="flex items-start gap-2.5 rounded-md border border-dashed border-amber-500/40 bg-amber-50/40 px-3 py-2 text-xs dark:bg-amber-950/20">
+ <span
+ className="mt-1 inline-block size-2 shrink-0 rounded-full bg-amber-500"
+ aria-hidden
+ />
+ <div className="min-w-0 flex-1">
+ <div className="font-medium text-amber-900 dark:text-amber-200">
+ Paused — {reason}
+ </div>
+ <div className="mt-0.5 text-[11px] text-amber-700/80 dark:text-amber-300/70">
+ The agent will resume automatically when the gating condition
+ resolves.
+ </div>
+ </div>
+ </div>
+ );
+}
+
/**
* Live "agent is working" indicator. Beyond just a pulse, surfaces:
* - what phase we're in (starting / thinking / wrapping up / running a tool)
diff --git a/src/components/policy-list.tsx b/src/components/policy-list.tsx
new file mode 100644
index 00000000..edf6276e
--- /dev/null
+++ b/src/components/policy-list.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { Trash2, ShieldCheck } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Card, CardContent } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { toast } from "sonner";
+import {
+ createPolicyAction,
+ deletePolicyAction,
+} from "@/server/actions/approvals";
+import type { ApprovalPolicy, ApprovalType } from "@/types";
+
+const ACTION_TYPES: { key: ApprovalType; label: string }[] = [
+ { key: "spend", label: "Spend" },
+ { key: "content_publishing", label: "Content publishing" },
+ { key: "new_channel", label: "New channel" },
+ { key: "bid_change", label: "Bid change" },
+ { key: "audience_change", label: "Audience change" },
+ { key: "other", label: "Other" },
+];
+
+function formatUsd(n: number) {
+ return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
+}
+
+export function PolicyList({
+ projectSlug,
+ policies,
+}: {
+ projectSlug: string;
+ policies: ApprovalPolicy[];
+}) {
+ const [showForm, setShowForm] = useState(false);
+ const [actionType, setActionType] = useState<ApprovalType>("spend");
+ const [agentId, setAgentId] = useState("");
+ const [maxCost, setMaxCost] = useState("");
+ const [autoDecision, setAutoDecision] = useState<"approve" | "reject">("approve");
+ const [note, setNote] = useState("");
+ const [pending, start] = useTransition();
+
+ function submit() {
+ start(async () => {
+ const cap = maxCost.trim() ? Number(maxCost) : null;
+ if (maxCost.trim() && (!Number.isFinite(cap) || cap! < 0)) {
+ toast.error("Cost cap must be non-negative number");
+ return;
+ }
+ const r = await createPolicyAction({
+ project_slug: projectSlug,
+ action_type: actionType,
+ agent_id: agentId.trim() || null,
+ max_cost_usd: cap,
+ auto_decision: autoDecision,
+ note: note.trim() || null,
+ });
+ if (!r.ok) toast.error(r.error ?? "Failed to create policy");
+ else {
+ toast.success("Policy saved");
+ setShowForm(false);
+ setAgentId("");
+ setMaxCost("");
+ setNote("");
+ }
+ });
+ }
+ function remove(id: string) {
+ start(async () => {
+ const r = await deletePolicyAction(id);
+ if (!r.ok) toast.error(r.error ?? "Failed to delete policy");
+ else toast.success("Policy removed");
+ });
+ }
+
+ return (
+ <div className="space-y-4">
+ <Card>
+ <CardContent className="space-y-3 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="space-y-1">
+ <p className="text-sm font-medium">Auto-approve rules</p>
+ <p className="text-xs text-muted-foreground">
+ When an agent requests a matching action, it's auto-decided without
+ surfacing in the inbox. Tighter rules win first (specific agent, lower
+ cost cap).
+ </p>
+ </div>
+ <Button size="sm" onClick={() => setShowForm((s) => !s)} disabled={pending}>
+ {showForm ? "Cancel" : "New rule"}
+ </Button>
+ </div>
+
+ {showForm && (
+ <div className="space-y-3 rounded-md border border-border bg-muted/30 p-3">
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className="space-y-1 text-xs">
+ <span className="block font-medium">Action type</span>
+ <select
+ value={actionType}
+ onChange={(e) => setActionType(e.target.value as ApprovalType)}
+ className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
+ disabled={pending}
+ >
+ {ACTION_TYPES.map((t) => (
+ <option key={t.key} value={t.key}>
+ {t.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="space-y-1 text-xs">
+ <span className="block font-medium">Decision</span>
+ <select
+ value={autoDecision}
+ onChange={(e) => setAutoDecision(e.target.value as "approve" | "reject")}
+ className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
+ disabled={pending}
+ >
+ <option value="approve">Auto-approve</option>
+ <option value="reject">Auto-reject</option>
+ </select>
+ </label>
+ <label className="space-y-1 text-xs">
+ <span className="block font-medium">
+ Agent ID <span className="text-muted-foreground">(optional)</span>
+ </span>
+ <Input
+ value={agentId}
+ onChange={(e) => setAgentId(e.target.value)}
+ placeholder="Any agent"
+ disabled={pending}
+ />
+ </label>
+ <label className="space-y-1 text-xs">
+ <span className="block font-medium">
+ Cost cap USD <span className="text-muted-foreground">(optional)</span>
+ </span>
+ <Input
+ type="number"
+ min="0"
+ step="0.01"
+ value={maxCost}
+ onChange={(e) => setMaxCost(e.target.value)}
+ placeholder="No cap"
+ disabled={pending}
+ />
+ </label>
+ </div>
+ <label className="space-y-1 text-xs">
+ <span className="block font-medium">Note (shown to the agent)</span>
+ <Input
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ placeholder="Why does this rule exist?"
+ disabled={pending}
+ />
+ </label>
+ <div>
+ <Button size="sm" onClick={submit} disabled={pending}>
+ Save rule
+ </Button>
+ </div>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {policies.length === 0 ? (
+ <Card>
+ <CardContent className="py-12 text-center text-sm text-muted-foreground">
+ No rules yet. Without rules, every write surfaces in the inbox.
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-2">
+ {policies.map((p) => (
+ <Card key={p.id}>
+ <CardContent className="flex items-start justify-between gap-3 py-3">
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <Badge variant="outline" className="text-[10px]">
+ {p.action_type}
+ </Badge>
+ <Badge
+ variant={p.auto_decision === "approve" ? "default" : "destructive"}
+ className="gap-1 text-[10px]"
+ >
+ <ShieldCheck className="size-3" />
+ Auto-{p.auto_decision}
+ </Badge>
+ {p.agent_id ? (
+ <Badge variant="secondary" className="text-[10px] font-mono">
+ {p.agent_id}
+ </Badge>
+ ) : (
+ <Badge variant="outline" className="text-[10px]">
+ any agent
+ </Badge>
+ )}
+ {p.max_cost_usd != null && (
+ <Badge variant="outline" className="text-[10px]">
+ ≤ {formatUsd(p.max_cost_usd)}
+ </Badge>
+ )}
+ </div>
+ {p.note && (
+ <p className="text-sm leading-snug">{p.note}</p>
+ )}
+ </div>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => remove(p.id)}
+ disabled={pending}
+ aria-label="Delete policy"
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/server/actions/approvals.test.ts b/src/server/actions/approvals.test.ts
index 83a5efec..a9a3263b 100644
--- a/src/server/actions/approvals.test.ts
+++ b/src/server/actions/approvals.test.ts
@@ -5,74 +5,229 @@ vi.mock("next/cache", () => ({
revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),
}));
+const getApprovalMock = vi.fn();
const resolveApprovalMock = vi.fn();
+const requestApprovalRevisionMock = vi.fn();
+const appendCommentMock = vi.fn();
+const createPolicyMock = vi.fn();
+const deletePolicyMock = vi.fn();
vi.mock("@/server/db/approvals", () => ({
+ getApproval: (...a: unknown[]) => getApprovalMock(...a),
resolveApproval: (...a: unknown[]) => resolveApprovalMock(...a),
+ requestApprovalRevision: (...a: unknown[]) => requestApprovalRevisionMock(...a),
+ appendComment: (...a: unknown[]) => appendCommentMock(...a),
+ createPolicy: (...a: unknown[]) => createPolicyMock(...a),
+ deletePolicy: (...a: unknown[]) => deletePolicyMock(...a),
}));
-import { approveAction, rejectAction } from "./approvals";
+const wakeMock = vi.fn();
+vi.mock("@/server/orchestration/approval-wakeup", () => ({
+ wakeTaskOnApprovalResolution: (...a: unknown[]) => wakeMock(...a),
+}));
+
+import {
+ addApprovalCommentAction,
+ approveAction,
+ createPolicyAction,
+ deletePolicyAction,
+ rejectAction,
+ requestRevisionAction,
+} from "./approvals";
function makeApproval(overrides: Record<string, unknown> = {}) {
return {
id: "ap-1",
project_slug: "demo",
agent_id: "demo-cmo",
+ task_id: null,
action_summary: "raise bid",
action_type: "bid_change",
cost_estimate_usd: 0,
reasoning: null,
payload_json: "{}",
- status: "approved",
+ status: "pending",
+ decision_note: null,
+ decided_by_kind: null,
+ decided_by_id: null,
created_at: "2026-05-01T00:00:00Z",
- resolved_at: "2026-05-02T00:00:00Z",
+ resolved_at: null,
...overrides,
};
}
-describe("approveAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
+beforeEach(() => {
+ vi.clearAllMocks();
+ wakeMock.mockResolvedValue(undefined);
+});
- it("calls resolveApproval with 'approved' and revalidates layout on success", async () => {
+describe("approveAction", () => {
+ it("resolves approval, appends a user comment, and triggers wake-up", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
resolveApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
- const out = await approveAction("ap-1");
+ const out = await approveAction("ap-1", "looks good");
expect(out).toEqual({ ok: true });
- expect(resolveApprovalMock).toHaveBeenCalledWith("ap-1", "approved");
+ expect(resolveApprovalMock).toHaveBeenCalledWith(
+ "ap-1",
+ "approved",
+ expect.objectContaining({
+ decision_note: "looks good",
+ decided_by_kind: "user",
+ }),
+ );
+ expect(appendCommentMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ approval_id: "ap-1",
+ author_kind: "user",
+ body: "looks good",
+ }),
+ );
+ expect(wakeMock).toHaveBeenCalled();
expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
});
- it("returns ok:false with descriptive error when resolveApproval returns null", async () => {
- resolveApprovalMock.mockReturnValue(null);
+ it("defaults comment body to 'Approved.' when no note given", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
+ resolveApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
+ await approveAction("ap-1");
+ expect(appendCommentMock).toHaveBeenCalledWith(
+ expect.objectContaining({ body: "Approved." }),
+ );
+ });
+
+ it("returns ok:false when the approval is missing", async () => {
+ getApprovalMock.mockReturnValue(null);
const out = await approveAction("missing");
- expect(out).toEqual({
- ok: false,
- error: "Approval not found or already resolved.",
- });
- expect(revalidatePathMock).not.toHaveBeenCalled();
+ expect(out).toEqual({ ok: false, error: "Approval not found." });
+ expect(resolveApprovalMock).not.toHaveBeenCalled();
+ });
+
+ it("returns ok:false when the approval is already resolved", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
+ const out = await approveAction("ap-1");
+ expect(out).toEqual({ ok: false, error: "Approval is already approved." });
+ expect(resolveApprovalMock).not.toHaveBeenCalled();
});
});
describe("rejectAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
+ it("resolves approval to rejected with note and triggers wake-up", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
+ resolveApprovalMock.mockReturnValue(makeApproval({ status: "rejected" }));
+ const out = await rejectAction("ap-1", "too risky");
+ expect(out).toEqual({ ok: true });
+ expect(resolveApprovalMock).toHaveBeenCalledWith(
+ "ap-1",
+ "rejected",
+ expect.objectContaining({
+ decision_note: "too risky",
+ decided_by_kind: "user",
+ }),
+ );
+ expect(wakeMock).toHaveBeenCalled();
});
- it("calls resolveApproval with 'rejected' and revalidates layout on success", async () => {
+ it("defaults comment body to 'Rejected.' when no note", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
resolveApprovalMock.mockReturnValue(makeApproval({ status: "rejected" }));
- const out = await rejectAction("ap-1");
+ await rejectAction("ap-1");
+ expect(appendCommentMock).toHaveBeenCalledWith(
+ expect.objectContaining({ body: "Rejected." }),
+ );
+ });
+});
+
+describe("requestRevisionAction", () => {
+ it("requires a non-empty note", async () => {
+ const out = await requestRevisionAction("ap-1", " ");
+ expect(out.ok).toBe(false);
+ expect(out.error).toMatch(/note is required/);
+ expect(requestApprovalRevisionMock).not.toHaveBeenCalled();
+ });
+
+ it("transitions pending → revision_requested with the note", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
+ requestApprovalRevisionMock.mockReturnValue(
+ makeApproval({ status: "revision_requested" }),
+ );
+ const out = await requestRevisionAction("ap-1", "shrink scope");
expect(out).toEqual({ ok: true });
- expect(resolveApprovalMock).toHaveBeenCalledWith("ap-1", "rejected");
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
+ expect(requestApprovalRevisionMock).toHaveBeenCalledWith("ap-1", {
+ decision_note: "shrink scope",
+ decided_by_kind: "user",
+ });
+ expect(appendCommentMock).toHaveBeenCalledWith(
+ expect.objectContaining({ body: "shrink scope" }),
+ );
+ expect(wakeMock).toHaveBeenCalled();
+ });
+
+ it("refuses revision on a non-pending row", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
+ const out = await requestRevisionAction("ap-1", "x");
+ expect(out.ok).toBe(false);
+ expect(out.error).toMatch(/pending/);
+ });
+});
+
+describe("addApprovalCommentAction", () => {
+ it("appends a user comment when the approval exists", async () => {
+ getApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
+ const out = await addApprovalCommentAction("ap-1", "fyi");
+ expect(out.ok).toBe(true);
+ expect(appendCommentMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ approval_id: "ap-1",
+ author_kind: "user",
+ body: "fyi",
+ }),
+ );
});
- it("returns ok:false with descriptive error when resolveApproval returns null", async () => {
- resolveApprovalMock.mockReturnValue(null);
- const out = await rejectAction("missing");
- expect(out).toEqual({
- ok: false,
- error: "Approval not found or already resolved.",
+ it("rejects empty bodies", async () => {
+ const out = await addApprovalCommentAction("ap-1", " ");
+ expect(out.ok).toBe(false);
+ expect(appendCommentMock).not.toHaveBeenCalled();
+ });
+
+ it("returns ok:false when approval is missing", async () => {
+ getApprovalMock.mockReturnValue(null);
+ const out = await addApprovalCommentAction("ap-1", "hi");
+ expect(out.ok).toBe(false);
+ });
+});
+
+describe("createPolicyAction + deletePolicyAction", () => {
+ it("create returns the policy id when DB returns one", async () => {
+ createPolicyMock.mockReturnValue({ id: "pol-1" });
+ const out = await createPolicyAction({
+ project_slug: "demo",
+ action_type: "spend",
+ auto_decision: "approve",
+ max_cost_usd: 50,
});
- expect(revalidatePathMock).not.toHaveBeenCalled();
+ expect(out).toEqual({ ok: true, policy_id: "pol-1" });
+ expect(createPolicyMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ project_slug: "demo",
+ action_type: "spend",
+ max_cost_usd: 50,
+ auto_decision: "approve",
+ created_by_kind: "user",
+ }),
+ );
+ });
+
+ it("create validates inputs", async () => {
+ // @ts-expect-error invalid on purpose
+ const out = await createPolicyAction({ project_slug: "", action_type: "" });
+ expect(out.ok).toBe(false);
+ });
+
+ it("delete returns ok:true on success and ok:false on missing", async () => {
+ deletePolicyMock.mockReturnValueOnce(true);
+ expect(await deletePolicyAction("pol-1")).toEqual({ ok: true });
+ deletePolicyMock.mockReturnValueOnce(false);
+ const out = await deletePolicyAction("missing");
+ expect(out.ok).toBe(false);
});
});
diff --git a/src/server/actions/approvals.ts b/src/server/actions/approvals.ts
index 06d35a86..25d2bd46 100644
--- a/src/server/actions/approvals.ts
+++ b/src/server/actions/approvals.ts
@@ -1,18 +1,165 @@
"use server";
import { revalidatePath } from "next/cache";
-import { resolveApproval } from "@/server/db/approvals";
+import {
+ appendComment,
+ createPolicy,
+ deletePolicy,
+ getApproval,
+ requestApprovalRevision,
+ resolveApproval,
+} from "@/server/db/approvals";
+import { wakeTaskOnApprovalResolution } from "@/server/orchestration/approval-wakeup";
+import type { ApprovalType } from "@/types";
+
+export type ActionResult = { ok: boolean; error?: string };
+
+/**
+ * Centralized "decide and wake" path for human-driven approvals. Resolves
+ * the row, posts a comment trail (so the inbox shows the decision), and
+ * kicks the task wake-up fire-and-forget so the agent picks up the
+ * decision on its next turn.
+ */
+async function decideApproval(
+ id: string,
+ status: "approved" | "rejected",
+ options: { decision_note?: string; decided_by_id?: string } = {},
+): Promise<ActionResult> {
+ const before = getApproval(id);
+ if (!before) return { ok: false, error: "Approval not found." };
+ if (before.status !== "pending" && before.status !== "revision_requested") {
+ return { ok: false, error: `Approval is already ${before.status}.` };
+ }
+
+ const after = resolveApproval(id, status, {
+ decision_note: options.decision_note ?? null,
+ decided_by_kind: "user",
+ decided_by_id: options.decided_by_id ?? null,
+ });
+ if (!after) return { ok: false, error: "Approval row vanished." };
+
+ appendComment({
+ approval_id: id,
+ author_kind: "user",
+ author_id: options.decided_by_id ?? null,
+ body:
+ options.decision_note?.trim() ||
+ (status === "approved" ? "Approved." : "Rejected."),
+ });
+
+ // Fire-and-forget wake-up so the form post returns instantly.
+ void wakeTaskOnApprovalResolution(after).catch((err) => {
+ console.error("[approve-action] wake-up failed:", err);
+ });
-export async function approveAction(id: string): Promise<{ ok: boolean; error?: string }> {
- const result = resolveApproval(id, "approved");
- if (!result) return { ok: false, error: "Approval not found or already resolved." };
revalidatePath("/", "layout");
return { ok: true };
}
-export async function rejectAction(id: string): Promise<{ ok: boolean; error?: string }> {
- const result = resolveApproval(id, "rejected");
- if (!result) return { ok: false, error: "Approval not found or already resolved." };
+export async function approveAction(
+ id: string,
+ decision_note?: string,
+): Promise<ActionResult> {
+ return decideApproval(id, "approved", { decision_note });
+}
+
+export async function rejectAction(
+ id: string,
+ decision_note?: string,
+): Promise<ActionResult> {
+ return decideApproval(id, "rejected", { decision_note });
+}
+
+/**
+ * Push back on the agent with a comment + revision_requested status. The
+ * agent's next turn sees the feedback and is expected to emit a fresh
+ * <request_approval> with a refined plan.
+ */
+export async function requestRevisionAction(
+ id: string,
+ decision_note: string,
+): Promise<ActionResult> {
+ if (!decision_note.trim()) {
+ return { ok: false, error: "A note is required when requesting revision." };
+ }
+ const before = getApproval(id);
+ if (!before) return { ok: false, error: "Approval not found." };
+ if (before.status !== "pending") {
+ return {
+ ok: false,
+ error: `Can only request revision on a pending approval (got ${before.status}).`,
+ };
+ }
+ const after = requestApprovalRevision(id, {
+ decision_note,
+ decided_by_kind: "user",
+ });
+ if (!after) return { ok: false, error: "Revision request failed." };
+
+ appendComment({
+ approval_id: id,
+ author_kind: "user",
+ body: decision_note,
+ });
+
+ void wakeTaskOnApprovalResolution(after).catch((err) => {
+ console.error("[request-revision-action] wake-up failed:", err);
+ });
+
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/** Free-form comment without changing the approval status. */
+export async function addApprovalCommentAction(
+ id: string,
+ body: string,
+): Promise<ActionResult> {
+ const trimmed = body.trim();
+ if (!trimmed) return { ok: false, error: "Comment cannot be empty." };
+ const approval = getApproval(id);
+ if (!approval) return { ok: false, error: "Approval not found." };
+
+ appendComment({
+ approval_id: id,
+ author_kind: "user",
+ body: trimmed,
+ });
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+export type CreatePolicyActionInput = {
+ project_slug: string;
+ action_type: ApprovalType;
+ agent_id?: string | null;
+ max_cost_usd?: number | null;
+ auto_decision: "approve" | "reject";
+ note?: string | null;
+};
+
+export async function createPolicyAction(
+ input: CreatePolicyActionInput,
+): Promise<ActionResult & { policy_id?: string }> {
+ if (!input.project_slug || !input.action_type) {
+ return { ok: false, error: "project_slug and action_type are required." };
+ }
+ const policy = createPolicy({
+ project_slug: input.project_slug,
+ action_type: input.action_type,
+ agent_id: input.agent_id ?? null,
+ max_cost_usd: input.max_cost_usd ?? null,
+ auto_decision: input.auto_decision,
+ note: input.note ?? null,
+ created_by_kind: "user",
+ });
+ revalidatePath("/", "layout");
+ return { ok: true, policy_id: policy.id };
+}
+
+export async function deletePolicyAction(id: string): Promise<ActionResult> {
+ const ok = deletePolicy(id);
+ if (!ok) return { ok: false, error: "Policy not found." };
revalidatePath("/", "layout");
return { ok: true };
}
diff --git a/src/server/agent-templates.ts b/src/server/agent-templates.ts
index 1ee7d8ab..ac251c0d 100644
--- a/src/server/agent-templates.ts
+++ b/src/server/agent-templates.ts
@@ -3,6 +3,11 @@ import { homedir } from "node:os";
import { join } from "node:path";
import { openclaw } from "@/server/openclaw/cli";
import { writeAgentMeta } from "@/server/agent-meta";
+import {
+ cleanupLegacyOrchestrationRows,
+ ensureOrchestrationMcpInstalled,
+} from "@/server/mcp-server/registration";
+import { listProjects } from "@/server/db/projects";
/**
* Embedded in every agent's system prompt so the agent knows how to create
@@ -34,106 +39,113 @@ const CMO_ORCHESTRATOR_PROMPT = `## You are an orchestrator, not a doer
Your job is to plan, decompose work into tasks, and delegate to the
specialist agents you coordinate. You do NOT log into Google Ads, write
-ad copy, or run scripts. The specialist agents do that. You think about
+ad copy, or run scripts. The specialists do that. You think about
strategy and prioritization, then you create tasks.
-When the user opens chat with you (or you wake from a scheduled
-heartbeat), your output should be SHORT prose + structured blocks. The
-prose orients the user; the blocks are how you actually delegate.
+Your output is SHORT prose. The user reads prose; coordination happens
+through the notfair-orchestration MCP tools below. Never emit pseudo-
+XML "blocks" like <create_task>, <task_status>, <add_comment>,
+<request_approval>, <ask_user> — those are legacy and the platform no
+longer parses them. Tasks, comments, approvals, and questions only
+happen through tool calls.
-## Your tool surface (structured blocks)
+## How to coordinate (notfair-orchestration MCP tools)
-The platform parses these blocks out of your reply and turns them into
-real DB rows. Always place blocks at the END of your reply, never mid-
-prose. Multi-line values are supported by indenting continuation lines.
+Every tool requires \`project_slug\` and (where applicable) \`agent_id\`
+or \`assigner_agent_id\` — use the EXACT values from the "Your runtime
+identity" section above.
-### <create_task> — spawn a task for a specialist
+When you don't know which value to use, call the relevant discovery
+tool FIRST: \`list_project_agents\`, \`list_task_statuses\`,
+\`list_approval_action_types\`. Don't guess at enums.
-<create_task>
-title: Install Google Ads conversion tracking
-assignee: google_ads
-brief: We have $39/mo running on NotFair - Google Ads + Claude with 0
- recorded conversions. Install the Google Ads conversion tag (or import
- GA4 conversion events) so optimization has real signal. Confirm the
- tag fires on the relevant pages and report which events you set up.
-success_criteria: Test conversion fires + appears in Google Ads within
- 24h. Conversion type + value mapping documented.
-</create_task>
+### To delegate work to a specialist
-Rules:
-- assignee MUST be a specialist template key. Today: only "google_ads".
- Never assign to "cmo" (yourself) or "seo" (not provisioned in V1).
-- title is a short label (under 60 chars) shown on the kanban card.
-- brief is a PRD-style description. Be specific about goal, context,
- expected output, constraints. The specialist works from this alone.
-- success_criteria is optional but recommended — one line on "how does
- the specialist know it's done?".
-- Create 1-3 tasks per reply, not 10. Pick what matters.
-
-### <add_comment> — talk to a specialist on an existing task
-
-<add_comment>
-task_id: <uuid from a previous create_task>
-body: Quick context update: the conversion you should track is form
- submission on /demo-request, not pricing page clicks. Adjust if needed.
-</add_comment>
-
-Use this to add context to a task you previously created, answer a
-specialist's <ask_user>, or unblock a specialist that posted a
-<task_status status:blocked>.
-
-### <ask_user> — block on the user's answer
-
-<ask_user>
-question: Should the daily anomaly check page you on Slack, or just
- email a summary at 9am?
-options: Slack, Email, Both
-</ask_user>
-
-Use sparingly. Only when you genuinely need the user to choose between
-real alternatives that affect downstream tasks. The user sees this as
-a prompt in the chat or task UI; their answer flows back to you.
-
-### <request_approval> — needs explicit user sign-off
-
-<request_approval>
-action_type: spend
-action_summary: Raise daily budget on Brand-US from $20/day to $80/day.
-cost_estimate_usd: 1800
-reasoning: Current $20/day is exhausted by 11am every weekday — we're
- losing afternoon impressions. $80/day projects to ~$2,400/mo at current
- CPC; tracking + alerts already in place.
-</request_approval>
-
-action_type must be one of: spend, content_publishing, new_channel,
-bid_change, audience_change, other. cost_estimate_usd is required for
-spend-typed actions. The platform creates an approval row the user can
-accept/reject from /approvals.
+Call \`create_task\`:
+ project_slug: <your project_slug>
+ assigner_agent_id: <your agent_id>
+ assignee: <template key — e.g. "google_ads"; never "cmo" (yourself)>
+ title: short kanban label (under 60 chars)
+ brief: PRD-style description. Be specific about goal, context, output,
+ constraints. The specialist works from this brief alone.
+ success_criteria: (optional) one line on "how does the specialist
+ know it's done?"
+
+The task auto-starts: status flips proposed → running and a kickoff
+message is delivered to the assignee. Don't follow up with a "I just
+created the task" message — the user already sees it on the kanban.
+
+Use \`list_project_agents\` once if you need to discover which template
+keys are provisioned. Create 1-3 tasks per reply, not 10 — pick what
+matters.
+
+### To add context to an existing task (talk to the specialist)
+
+Call \`add_task_comment\`:
+ project_slug: <your project_slug>
+ agent_id: <your agent_id>
+ task_id: <id of the existing task>
+ body: the note
+
+Use when the specialist asked a follow-up question, or you want them
+to pivot. The specialist sees this on their next turn.
+
+### To ask the user a question
+
+Call \`ask_user_question\`:
+ project_slug, agent_id, question, options? (comma-separated)
+
+Use sparingly. Only when you genuinely need a choice between real
+alternatives that affect downstream tasks. The user's answer comes
+back as a regular chat turn.
+
+### To request user sign-off on a governed action
+
+Call \`request_approval\`:
+ project_slug, agent_id, action_summary, action_type, cost_estimate_usd?,
+ reasoning?, task_id? (if it gates a specific task)
+
+Required before any spend change, content publish, new channel,
+bid change, or audience change. The user accepts/rejects from
+/approvals; you'll be woken on resolution with the decision in
+context. Call \`list_approval_action_types\` if you're unsure which
+type fits.
+
+### To check progress / context
+
+- \`list_tasks\` — project-wide kanban view
+- \`get_task\` — fetch a specific task by id (after your context window
+ rotates, use this to re-anchor)
+- \`list_pending_approvals\` — what's awaiting decision
+- \`list_task_comments\` — comment thread on a task
## When a chat turn begins with "(task assignment)"
-That's the brief the user (or another agent) assigned to YOU. The body
-includes a task_id, title, brief, and success criteria. Do this:
+That's a brief the user (or another agent) assigned to YOU. Do this:
1. Acknowledge in 1-2 sentences (what you'll do + roughly how long).
2. Do the work the brief specifies. Yes — when the brief asks you to
- audit, research, or otherwise gather data, you can call MCP tools
+ audit, research, or gather data, call your domain MCP tools
directly (notfair-googleads runScript, etc.). The "delegate, don't
- do" rule applies to ONGOING ad operations after the initial planning
- pass, not to research you need to plan well.
+ do" rule applies to ONGOING ad operations, not to research you need
+ to plan well.
3. Report findings inline (markdown, scannable).
-4. Delegate the ongoing work via <create_task> blocks for the
- appropriate specialist.
-5. End the reply with <task_status>task_id: <id> status: done
- summary: ...</task_status>.
+4. Delegate the ongoing work by calling \`create_task\` once per
+ downstream specialist.
+5. End the turn by calling \`submit_task_status\` with
+ project_slug, agent_id, task_id (from the assignment), status="done",
+ and a one-line summary.
## What you do NOT do
- You do NOT chat-thread with the user about ad operations once the
- planning is done. If the user asks about ad-level details later,
- create a task for the Google Ads specialist and let them handle it.
-- You do NOT emit <task_status> blocks for tasks you didn't claim —
+ planning is done. If the user asks ad-level details later, call
+ \`create_task\` and let the specialist handle it.
+- You do NOT call \`submit_task_status\` on tasks you didn't claim —
only the assignee reports status.
+- You do NOT emit "<create_task>" / "<task_status>" / "<add_comment>" /
+ "<ask_user>" / "<request_approval>" pseudo-blocks in your prose.
+ These are NOT parsed. Always use the MCP tools above.
`;
/**
@@ -145,89 +157,104 @@ includes a task_id, title, brief, and success criteria. Do this:
const SPECIALIST_TASK_PROMPT = `## You are a specialist worker
You receive tasks from the CMO via chat messages that begin with
-"(task assignment)" — they contain a task_id, title, brief, and success
-criteria. Do the hands-on work using your tools (MCP, exec, etc.) and
-report back via <task_status>.
+"(task assignment)" — they carry your project_slug, agent_id, task_id,
+title, brief, and success criteria. Do the hands-on work using your
+domain tools (notfair-googleads MCP, exec, etc.) and coordinate through
+the notfair-orchestration MCP tools below.
-## "(task assignment)" kickoff
+NEVER emit pseudo-XML blocks like <task_status>, <add_comment>,
+<ask_user>, <request_approval>. The platform no longer parses them.
+Coordination happens through MCP tool calls only.
-When a chat turn opens with "(task assignment)":
+## "(task assignment)" kickoff procedure
1. Acknowledge in 1-2 sentences — what you'll do and roughly how long.
-2. Start working. Use your tools to actually do the thing — don't just
- describe what you'd do.
-3. When done, emit <task_status> at the end of your reply.
+2. Start working. Use your domain tools to actually do the thing —
+ don't just describe what you'd do.
+3. End the turn by calling \`submit_task_status\`:
+ project_slug: <from the assignment message>
+ agent_id: <from the assignment message>
+ task_id: <from the assignment message>
+ status: working | done | blocked | failed
+ summary: one-line note (required for done / failed)
+
+You can post progress updates across multiple turns
+(working → working → done). Each call updates the task row atomically.
Any chat turn that does NOT begin with "(task assignment)" is the user
(or CMO) chatting with you about prior work. Respond normally; don't
fabricate a new task.
-## Your tool surface (structured blocks)
+## How to coordinate (notfair-orchestration MCP tools)
-### <task_status> — report progress on YOUR assigned task
+Every tool requires \`project_slug\` and \`agent_id\` — use the values
+from the "Your runtime identity" section at the top of this file, or
+from the kickoff message.
-<task_status>
-task_id: <id from the "(task assignment)" message>
-status: done
-summary: Installed the conversion tag on /thanks and /demo-request.
- Test conv fired at 14:02 PT. Conversion type: "Demo request", value
- $80. Visible in Google Ads conversion settings.
-</task_status>
+When unsure of an enum (status, action_type), call the discovery tool
+first: \`list_task_statuses\`, \`list_approval_action_types\`. Don't
+guess.
-status must be one of: working (you're mid-task, posting an update),
-done (task complete), blocked (need user input or CMO unblock — pair
-with <ask_user> or wait), failed (couldn't complete; explain why).
+### To report task status
-Emit <task_status> at the end of your reply, AFTER any prose updates.
-You can post multiple status updates over time (one per chat turn).
-The platform updates the task row each time.
+Call \`submit_task_status\` (see kickoff above). Use:
+- working — still progressing; post an update before the status changes
+- done — task complete; summary explains what shipped
+- blocked — waiting on user / CMO / approval; pair with
+ \`ask_user_question\` or \`request_approval\` BEFORE this
+- failed — couldn't complete; summary must explain why
-### <add_comment> — talk back to the CMO on this task
+### To get user sign-off BEFORE a governed action
-<add_comment>
-task_id: <uuid>
-body: I see a CallRail event already firing — should I use that instead
- of installing a new tag? Asking before I duplicate.
-</add_comment>
+Call \`request_approval\`:
+ project_slug, agent_id
+ task_id: <id from the assignment, if scoped to this task>
+ action_summary: one-line description of what you want to do
+ action_type: spend | content_publishing | new_channel | bid_change |
+ audience_change | other
+ cost_estimate_usd: monthly $ impact (required for spend / bid_change /
+ new_channel)
+ reasoning: why — be concrete
-Use this when you want the CMO to see your reasoning or to ask the CMO
-a question. The CMO sees it in the task's activity log and can reply
-with their own <add_comment>.
+Required before any keyword pause, bid change, budget change, content
+publish, or new channel launch. When called WITH a task_id, the task
+parks in "blocked" until the user (or an auto-approval policy)
+resolves. You'll be woken on resolution with the decision in your
+context. Don't execute the gated action until then.
-### <ask_user> — when you need the user, not the CMO
+### To talk to the CMO about an existing task
-<ask_user>
-task_id: <uuid>
-question: What's your average customer LTV? I need it to set a
- conversion value.
-</ask_user>
+Call \`add_task_comment\`:
+ project_slug, agent_id, task_id, body
-Use only when the answer can't come from the CMO or from your tools.
+Use when you want the CMO to see your reasoning, share a finding, or
+ask a clarifying question. The CMO sees the comment on the next turn.
-### <request_approval> — before a governed action
+### To ask the user (not the CMO) a question
-<request_approval>
-task_id: <uuid>
-action_type: bid_change
-action_summary: Pause 4 zero-conv keywords in Brand-US (saves ~$42/day).
-reasoning: Last 30 days: $1,260 spent, 0 conversions. Concrete keywords
- + IDs in the task brief above.
-</request_approval>
+Call \`ask_user_question\`:
+ project_slug, agent_id, question, task_id?, options?
-Required before any keyword pause, bid change > 25%, budget change,
-content publish, or new channel launch. The user accepts from
-/approvals; you wake when accepted and execute.
+Use only when the answer can't come from the CMO, your tools, or the
+brief. The user's reply lands as the next chat turn.
-## Your tool surface (existing OpenClaw tools)
+### To check progress / re-anchor context
-You also have the standard tools the OpenClaw runtime gives you:
-- exec — run shell commands (incl. notfair-googleads MCP calls via the
- notfair-googleads MCP if connected to this project)
-- read / edit / write — files in your workspace
-- everything from SCHEDULE_RECURRING_WORK below — schedule recurring jobs
+- \`get_task\` — fetch your assigned task by id (use when your context
+ window rotates and you've lost the brief)
+- \`list_my_tasks\` — what's currently on your plate
+- \`list_task_comments\` — comment history on a task
+- \`get_approval\` / \`list_my_approvals\` — check whether an approval
+ you requested has resolved
+- \`list_project_agents\` — discover other specialists you can ask
+ the CMO to engage
-Use the tools first to actually DO the work. The blocks above are for
-reporting + collaboration.
+## Your domain tools
+
+You also have the standard OpenClaw tools (exec, read/edit/write,
+web_search, etc.) plus any per-project MCPs the user has connected
+(notfair-googleads, etc.). Use those first to actually DO the work —
+the orchestration MCP is for coordination, not domain logic.
`;
/**
@@ -486,7 +513,7 @@ export async function ensureProjectAgents(
if (already) {
// Idempotently refresh the IDENTITY.md so prompt edits propagate to
// existing agents without forcing the user to delete + recreate.
- await writeIdentityFile(workspaceAbs, template);
+ await writeIdentityFile(workspaceAbs, template, project_slug, name);
// Backfill the notfair meta sidecar in case this agent was created
// before we started writing it (so the sidebar still finds them).
await writeAgentMeta({
@@ -516,7 +543,7 @@ export async function ensureProjectAgents(
"--workspace",
workspaceAbs,
]);
- await writeIdentityFile(workspaceAbs, template);
+ await writeIdentityFile(workspaceAbs, template, project_slug, name);
await writeAgentMeta({
agent_id: name,
project_slug,
@@ -534,6 +561,28 @@ export async function ensureProjectAgents(
}
}
+ // Register the orchestration MCP server with OpenClaw — once, globally.
+ // Tools are project-scoped via a required `project_slug` argument on every
+ // call, so a single registration serves every project + every agent in
+ // this install. ensureOrchestrationMcpInstalled checks the existing row
+ // first and is a no-op when already correct.
+ //
+ // Also opportunistically prune the legacy per-project rows we wrote
+ // before going global. Idempotent — does nothing on fresh installs.
+ //
+ // Failure is non-fatal: agents fall back to the legacy text-block protocol
+ // (still parsed server-side in process-blocks.ts).
+ try {
+ const r = await ensureOrchestrationMcpInstalled();
+ if (!r.ok) {
+ console.error(`[provision] orchestration MCP install failed: ${r.error}`);
+ }
+ const allSlugs = listProjects({ includeArchived: true }).map((p) => p.slug);
+ await cleanupLegacyOrchestrationRows(allSlugs);
+ } catch (err) {
+ console.error("[provision] orchestration MCP install threw:", err);
+ }
+
return { created, existed, failed };
}
@@ -542,13 +591,25 @@ function workspaceDirFor(name: string): string {
return join(dataDir, "agents", name);
}
-async function writeIdentityFile(workspaceAbs: string, template: AgentTemplate): Promise<void> {
+async function writeIdentityFile(
+ workspaceAbs: string,
+ template: AgentTemplate,
+ project_slug?: string,
+ agent_id?: string,
+): Promise<void> {
try {
await mkdir(workspaceAbs, { recursive: true });
+ // Per-agent identity block — every MCP tool requires the agent to pass
+ // its own `project_slug` and `agent_id`, so pin both right at the top
+ // of the prompt so the model can fill them into tool calls without
+ // guessing. The block is plain text so it's stable across model versions.
+ const identityBlock = project_slug && agent_id
+ ? `\n## Your runtime identity\n\nWhen calling notfair-orchestration MCP tools, pass these exact values:\n\n- \`project_slug\`: \`${project_slug}\`\n- \`agent_id\`: \`${agent_id}\`\n\nDo NOT invent other values. Every orchestration tool call requires both.\n`
+ : "";
const body = `# ${template.display_name}
${template.description}
-
+${identityBlock}
${template.system_prompt}
`;
await writeFile(join(workspaceAbs, "IDENTITY.md"), body, "utf8");
diff --git a/src/server/db/approvals.test.ts b/src/server/db/approvals.test.ts
index b562e788..2b02253e 100644
--- a/src/server/db/approvals.test.ts
+++ b/src/server/db/approvals.test.ts
@@ -11,9 +11,20 @@ vi.mock("./db", () => ({
}));
import {
+ actionableApprovalCount,
+ appendComment,
createApproval,
+ createPolicy,
+ deletePolicy,
+ findMatchingPolicy,
+ getApproval,
+ listActionableApprovals,
+ listComments,
listPendingApprovals,
+ listPolicies,
+ listResolvedApprovals,
pendingApprovalCount,
+ requestApprovalRevision,
resolveApproval,
} from "./approvals";
@@ -328,4 +339,440 @@ describe("resolveApproval", () => {
it("returns null when the approval id doesn't exist", () => {
expect(resolveApproval("missing-id", "approved")).toBeNull();
});
+
+ it("persists decision_note + decided_by_kind + decided_by_id on resolve", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ const out = resolveApproval(a.id, "approved", {
+ decision_note: "Looks good",
+ decided_by_kind: "user",
+ decided_by_id: "[email protected]",
+ });
+ expect(out!.decision_note).toBe("Looks good");
+ expect(out!.decided_by_kind).toBe("user");
+ expect(out!.decided_by_id).toBe("[email protected]");
+ });
+});
+
+describe("createApproval + policies", () => {
+ it("creates a pending row by default with task_id null and no decision metadata", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "acme-google-ads",
+ action_summary: "raise bid",
+ action_type: "bid_change",
+ cost_estimate_usd: 5,
+ payload: {},
+ });
+ expect(a.task_id).toBeNull();
+ expect(a.status).toBe("pending");
+ expect(a.decided_by_kind).toBeNull();
+ expect(a.decided_by_id).toBeNull();
+ expect(a.decision_note).toBeNull();
+ });
+
+ it("auto-approves when a matching policy exists", () => {
+ seedProject();
+ const policy = createPolicy({
+ project_slug: "acme",
+ action_type: "bid_change",
+ agent_id: null,
+ max_cost_usd: null,
+ auto_decision: "approve",
+ note: "trusted",
+ created_by_kind: "user",
+ });
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "acme-google-ads",
+ action_summary: "raise bid",
+ action_type: "bid_change",
+ cost_estimate_usd: 50,
+ payload: {},
+ });
+ expect(a.status).toBe("approved");
+ expect(a.decided_by_kind).toBe("policy");
+ expect(a.decided_by_id).toBe(policy.id);
+ expect(a.resolved_at).not.toBeNull();
+
+ // System comment recorded so the thread shows the trail.
+ const comments = listComments(a.id);
+ expect(comments).toHaveLength(1);
+ expect(comments[0]!.author_kind).toBe("system");
+ expect(comments[0]!.body).toContain("Auto-approved");
+ });
+
+ it("does NOT auto-approve when cost exceeds max_cost_usd", () => {
+ seedProject();
+ createPolicy({
+ project_slug: "acme",
+ action_type: "bid_change",
+ agent_id: null,
+ max_cost_usd: 10,
+ auto_decision: "approve",
+ created_by_kind: "user",
+ });
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "acme-google-ads",
+ action_summary: "expensive bid raise",
+ action_type: "bid_change",
+ cost_estimate_usd: 50,
+ payload: {},
+ });
+ expect(a.status).toBe("pending");
+ expect(a.decided_by_kind).toBeNull();
+ });
+
+ it("auto-rejects when a matching reject policy exists", () => {
+ seedProject();
+ createPolicy({
+ project_slug: "acme",
+ action_type: "content_publishing",
+ agent_id: null,
+ max_cost_usd: null,
+ auto_decision: "reject",
+ note: "human approval required for content",
+ created_by_kind: "user",
+ });
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "acme-seo",
+ action_summary: "publish landing page",
+ action_type: "content_publishing",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ expect(a.status).toBe("rejected");
+ expect(a.decided_by_kind).toBe("policy");
+ });
+
+ it("ignores policies from another project", () => {
+ seedProject("acme");
+ seedProject("other");
+ createPolicy({
+ project_slug: "other",
+ action_type: "bid_change",
+ agent_id: null,
+ max_cost_usd: null,
+ auto_decision: "approve",
+ created_by_kind: "user",
+ });
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "acme-google-ads",
+ action_summary: "bid",
+ action_type: "bid_change",
+ cost_estimate_usd: 1,
+ payload: {},
+ });
+ expect(a.status).toBe("pending");
+ });
+
+ it("prefers an agent-scoped policy over a wildcard policy", () => {
+ seedProject();
+ createPolicy({
+ project_slug: "acme",
+ action_type: "bid_change",
+ agent_id: null,
+ max_cost_usd: null,
+ auto_decision: "approve",
+ note: "wildcard",
+ created_by_kind: "user",
+ });
+ const scoped = createPolicy({
+ project_slug: "acme",
+ action_type: "bid_change",
+ agent_id: "acme-google-ads",
+ max_cost_usd: null,
+ auto_decision: "reject",
+ note: "specific reject",
+ created_by_kind: "user",
+ });
+ // Specific reject must win for this agent.
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "acme-google-ads",
+ action_summary: "bid",
+ action_type: "bid_change",
+ cost_estimate_usd: 1,
+ payload: {},
+ });
+ expect(a.status).toBe("rejected");
+ expect(a.decided_by_id).toBe(scoped.id);
+ });
+
+ it("persists task_id when provided", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ task_id: "task-uuid-123",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ expect(a.task_id).toBe("task-uuid-123");
+ });
+});
+
+describe("requestApprovalRevision", () => {
+ it("flips pending → revision_requested with a note", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ const out = requestApprovalRevision(a.id, {
+ decision_note: "narrow the audience first",
+ decided_by_kind: "user",
+ });
+ expect(out!.status).toBe("revision_requested");
+ expect(out!.decision_note).toBe("narrow the audience first");
+ expect(out!.resolved_at).toBeNull(); // not terminal yet
+ });
+
+ it("no-ops on a non-pending row", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ resolveApproval(a.id, "approved");
+ const out = requestApprovalRevision(a.id, {
+ decision_note: "second thoughts",
+ decided_by_kind: "user",
+ });
+ // Status is still approved — revision can't undo a terminal decision.
+ expect(out!.status).toBe("approved");
+ });
+
+ it("approved/rejected work after revision_requested transition (pending+revision_requested both resolvable)", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ requestApprovalRevision(a.id, {
+ decision_note: "smaller scope",
+ decided_by_kind: "user",
+ });
+ const out = resolveApproval(a.id, "approved");
+ expect(out!.status).toBe("approved");
+ });
+});
+
+describe("listActionableApprovals + listResolvedApprovals + actionableApprovalCount", () => {
+ it("actionable includes pending and revision_requested but not terminal", () => {
+ seedProject();
+ const pending = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "pending",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ const revising = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "revising",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ requestApprovalRevision(revising.id, {
+ decision_note: "x",
+ decided_by_kind: "user",
+ });
+ const approved = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "approved",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ resolveApproval(approved.id, "approved");
+
+ const ids = listActionableApprovals("acme")
+ .map((a) => a.id)
+ .sort();
+ expect(ids).toEqual([pending.id, revising.id].sort());
+ expect(actionableApprovalCount("acme")).toBe(2);
+ });
+
+ it("resolved lists approved/rejected/expired, excluding pending+revision_requested", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p1",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ const b = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p2",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ resolveApproval(a.id, "approved");
+ resolveApproval(b.id, "rejected");
+
+ const resolved = listResolvedApprovals("acme");
+ const statuses = new Set(resolved.map((r) => r.status));
+ expect(statuses).toEqual(new Set(["approved", "rejected"]));
+ });
+});
+
+describe("appendComment + listComments", () => {
+ it("round-trips a comment with author metadata", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ appendComment({
+ approval_id: a.id,
+ author_kind: "user",
+ author_id: "alice",
+ body: "let's push back here",
+ });
+ const c = listComments(a.id);
+ expect(c).toHaveLength(1);
+ expect(c[0]!.author_kind).toBe("user");
+ expect(c[0]!.author_id).toBe("alice");
+ expect(c[0]!.body).toBe("let's push back here");
+ });
+
+ it("orders comments by created_at ASC (chat-like)", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ appendComment({ approval_id: a.id, author_kind: "user", body: "first" });
+ appendComment({ approval_id: a.id, author_kind: "agent", author_id: "bot", body: "second" });
+ appendComment({ approval_id: a.id, author_kind: "system", body: "third" });
+ const ordered = listComments(a.id).map((c) => c.body);
+ expect(ordered).toEqual(["first", "second", "third"]);
+ });
+
+ it("comments cascade-delete with the parent approval", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ appendComment({ approval_id: a.id, author_kind: "user", body: "hi" });
+ testDb.prepare("DELETE FROM approvals WHERE id = ?").run(a.id);
+ expect(listComments(a.id)).toEqual([]);
+ });
+});
+
+describe("policies CRUD + findMatchingPolicy", () => {
+ it("creates + lists + deletes a policy", () => {
+ seedProject();
+ const p = createPolicy({
+ project_slug: "acme",
+ action_type: "spend",
+ agent_id: null,
+ max_cost_usd: 100,
+ auto_decision: "approve",
+ note: "anything under $100",
+ created_by_kind: "user",
+ });
+ expect(listPolicies("acme")).toHaveLength(1);
+ expect(listPolicies("acme")[0]!.id).toBe(p.id);
+ expect(deletePolicy(p.id)).toBe(true);
+ expect(listPolicies("acme")).toHaveLength(0);
+ expect(deletePolicy("missing")).toBe(false);
+ });
+
+ it("findMatchingPolicy respects cost cap (≤ semantics)", () => {
+ seedProject();
+ createPolicy({
+ project_slug: "acme",
+ action_type: "spend",
+ agent_id: null,
+ max_cost_usd: 100,
+ auto_decision: "approve",
+ created_by_kind: "user",
+ });
+ // 100 is OK (≤ cap), 101 is not.
+ expect(findMatchingPolicy("acme", "spend", "x", 100)).not.toBeNull();
+ expect(findMatchingPolicy("acme", "spend", "x", 99.99)).not.toBeNull();
+ expect(findMatchingPolicy("acme", "spend", "x", 100.01)).toBeNull();
+ });
+
+ it("findMatchingPolicy returns null when project, type, or agent mismatch", () => {
+ seedProject("acme");
+ seedProject("other");
+ createPolicy({
+ project_slug: "acme",
+ action_type: "spend",
+ agent_id: "agent-1",
+ max_cost_usd: null,
+ auto_decision: "approve",
+ created_by_kind: "user",
+ });
+ expect(findMatchingPolicy("other", "spend", "agent-1", 0)).toBeNull();
+ expect(findMatchingPolicy("acme", "bid_change", "agent-1", 0)).toBeNull();
+ expect(findMatchingPolicy("acme", "spend", "agent-2", 0)).toBeNull();
+ });
+});
+
+describe("getApproval", () => {
+ it("returns the row by id", () => {
+ seedProject();
+ const a = createApproval({
+ project_slug: "acme",
+ agent_id: "x",
+ action_summary: "p",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ expect(getApproval(a.id)?.id).toBe(a.id);
+ });
+ it("returns null for unknown id", () => {
+ expect(getApproval("nope")).toBeNull();
+ });
});
diff --git a/src/server/db/approvals.ts b/src/server/db/approvals.ts
index 004e4893..a695a418 100644
--- a/src/server/db/approvals.ts
+++ b/src/server/db/approvals.ts
@@ -1,10 +1,19 @@
import { randomUUID } from "node:crypto";
import { getDb } from "./db";
-import type { Approval, ApprovalStatus, ApprovalType } from "@/types";
+import type {
+ Approval,
+ ApprovalComment,
+ ApprovalCommentAuthorKind,
+ ApprovalDecidedByKind,
+ ApprovalPolicy,
+ ApprovalStatus,
+ ApprovalType,
+} from "@/types";
export type CreateApprovalInput = {
project_slug: string;
agent_id: string;
+ task_id?: string | null;
action_summary: string;
action_type: ApprovalType;
cost_estimate_usd: number;
@@ -12,39 +21,88 @@ export type CreateApprovalInput = {
payload: unknown;
};
+/**
+ * Returns the inserted approval row. When a matching auto-approve/reject
+ * policy fired, the row comes back already in its terminal state with
+ * `decided_by_kind = 'policy'` and `decided_by_id = policy.id` — callers
+ * that need to fire wake-up logic can detect that without an extra read.
+ */
export function createApproval(input: CreateApprovalInput): Approval {
const db = getDb();
- const approval: Approval = {
- id: randomUUID(),
- project_slug: input.project_slug,
- agent_id: input.agent_id,
- action_summary: input.action_summary,
- action_type: input.action_type,
- cost_estimate_usd: input.cost_estimate_usd,
- reasoning: input.reasoning ?? null,
- payload_json: JSON.stringify(input.payload ?? {}),
- status: "pending",
- created_at: new Date().toISOString(),
- resolved_at: null,
- };
+ const id = randomUUID();
+ const createdAt = new Date().toISOString();
+
+ // Consult the "always allow / always reject" policies BEFORE writing a
+ // pending row. If a policy matches, write the row in its terminal state
+ // straight away so the agent can be woken in the same tick. Mirrors
+ // paperclip's intent of decoupling the decision from human latency.
+ const policy = findMatchingPolicy(
+ input.project_slug,
+ input.action_type,
+ input.agent_id,
+ input.cost_estimate_usd,
+ );
+
+ const initialStatus: ApprovalStatus = policy
+ ? policy.auto_decision === "approve"
+ ? "approved"
+ : "rejected"
+ : "pending";
+
db.prepare(
`INSERT INTO approvals
- (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL)`,
+ (id, project_slug, agent_id, task_id, action_summary, action_type,
+ cost_estimate_usd, reasoning, payload_json, status,
+ decision_note, decided_by_kind, decided_by_id,
+ created_at, resolved_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
- approval.id,
- approval.project_slug,
- approval.agent_id,
- approval.action_summary,
- approval.action_type,
- approval.cost_estimate_usd,
- approval.reasoning,
- approval.payload_json,
- approval.created_at,
+ id,
+ input.project_slug,
+ input.agent_id,
+ input.task_id ?? null,
+ input.action_summary,
+ input.action_type,
+ input.cost_estimate_usd,
+ input.reasoning ?? null,
+ JSON.stringify(input.payload ?? {}),
+ initialStatus,
+ policy ? (policy.note ?? "Auto-decided by policy.") : null,
+ policy ? "policy" : null,
+ policy ? policy.id : null,
+ createdAt,
+ policy ? createdAt : null,
);
- return approval;
+
+ // If a policy auto-resolved, append a system comment so the thread shows
+ // a clear trail of "why was this approved without me clicking anything?".
+ if (policy) {
+ appendComment({
+ approval_id: id,
+ author_kind: "system",
+ author_id: policy.id,
+ body: `Auto-${policy.auto_decision === "approve" ? "approved" : "rejected"} by policy: ${policy.note ?? "(no note)"}`,
+ });
+ }
+
+ const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id) as Approval;
+ return row;
+}
+
+/** Pending OR revision_requested — anything still needing human attention. */
+export function listActionableApprovals(project_slug: string): Approval[] {
+ const db = getDb();
+ return db
+ .prepare(
+ `SELECT * FROM approvals
+ WHERE project_slug = ?
+ AND status IN ('pending','revision_requested')
+ ORDER BY created_at DESC`,
+ )
+ .all(project_slug) as Approval[];
}
+/** Back-compat: caller wanted only strictly-pending rows. */
export function listPendingApprovals(project_slug: string): Approval[] {
const db = getDb();
return db
@@ -54,6 +112,48 @@ export function listPendingApprovals(project_slug: string): Approval[] {
.all(project_slug) as Approval[];
}
+/** Resolved approvals (approved | rejected | expired) — for the history tab. */
+export function listResolvedApprovals(project_slug: string, limit = 50): Approval[] {
+ const db = getDb();
+ return db
+ .prepare(
+ `SELECT * FROM approvals
+ WHERE project_slug = ?
+ AND status IN ('approved','rejected','expired')
+ ORDER BY resolved_at DESC NULLS LAST, created_at DESC
+ LIMIT ?`,
+ )
+ .all(project_slug, limit) as Approval[];
+}
+
+export function listApprovalsForTask(task_id: string): Approval[] {
+ const db = getDb();
+ return db
+ .prepare("SELECT * FROM approvals WHERE task_id = ? ORDER BY created_at DESC")
+ .all(task_id) as Approval[];
+}
+
+export function getApproval(id: string): Approval | null {
+ const db = getDb();
+ const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id);
+ return (row as Approval) ?? null;
+}
+
+/** Count of actionable (pending + revision_requested) approvals — sidebar badge. */
+export function actionableApprovalCount(project_slug: string): number {
+ const db = getDb();
+ const row = db
+ .prepare(
+ `SELECT COUNT(*) AS n FROM approvals
+ WHERE project_slug = ? AND status IN ('pending','revision_requested')`,
+ )
+ .get(project_slug) as { n: number };
+ return row.n;
+}
+
+/** Back-compat shim: pendingApprovalCount counts strict 'pending'. The sidebar
+ * badge has been switched to actionableApprovalCount so this is unused inside
+ * the repo but exported so external callers (tests, scripts) keep working. */
export function pendingApprovalCount(project_slug: string): number {
const db = getDb();
const row = db
@@ -62,12 +162,211 @@ export function pendingApprovalCount(project_slug: string): number {
return row.n;
}
-export function resolveApproval(id: string, status: Exclude<ApprovalStatus, "pending">): Approval | null {
+export type ResolveApprovalOptions = {
+ decision_note?: string | null;
+ decided_by_kind?: ApprovalDecidedByKind;
+ decided_by_id?: string | null;
+};
+
+/**
+ * Conditional update: only flips a row that's still actionable (pending or
+ * revision_requested). The WHERE clause prevents a stale caller from
+ * re-resolving an already-terminal approval. Returns the post-update row
+ * (which may be unchanged if the transition didn't apply) or null when the
+ * id is missing.
+ *
+ * Wakeup logic should NOT live here — call `decideApproval()` in the
+ * actions layer if you want the post-resolution task wake-up.
+ */
+export function resolveApproval(
+ id: string,
+ status: Exclude<ApprovalStatus, "pending" | "revision_requested">,
+ options: ResolveApprovalOptions = {},
+): Approval | null {
const db = getDb();
const now = new Date().toISOString();
db.prepare(
- "UPDATE approvals SET status = ?, resolved_at = ? WHERE id = ? AND status = 'pending'",
- ).run(status, now, id);
+ `UPDATE approvals
+ SET status = ?,
+ resolved_at = ?,
+ decision_note = COALESCE(?, decision_note),
+ decided_by_kind = COALESCE(?, decided_by_kind),
+ decided_by_id = COALESCE(?, decided_by_id)
+ WHERE id = ?
+ AND status IN ('pending','revision_requested')`,
+ ).run(
+ status,
+ now,
+ options.decision_note ?? null,
+ options.decided_by_kind ?? null,
+ options.decided_by_id ?? null,
+ id,
+ );
const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id);
return (row as Approval) ?? null;
}
+
+/**
+ * Push back on the agent: flip pending → revision_requested with a note.
+ * The agent's next turn sees the note + can resubmit a new <request_approval>.
+ * From revision_requested the only forward transitions are approved/rejected.
+ */
+export function requestApprovalRevision(
+ id: string,
+ options: ResolveApprovalOptions & { decision_note: string },
+): Approval | null {
+ const db = getDb();
+ db.prepare(
+ `UPDATE approvals
+ SET status = 'revision_requested',
+ decision_note = ?,
+ decided_by_kind = COALESCE(?, decided_by_kind),
+ decided_by_id = COALESCE(?, decided_by_id)
+ WHERE id = ?
+ AND status = 'pending'`,
+ ).run(
+ options.decision_note,
+ options.decided_by_kind ?? null,
+ options.decided_by_id ?? null,
+ id,
+ );
+ const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id);
+ return (row as Approval) ?? null;
+}
+
+// ── Comments ────────────────────────────────────────────────────────
+
+export type AppendCommentInput = {
+ approval_id: string;
+ author_kind: ApprovalCommentAuthorKind;
+ author_id?: string | null;
+ body: string;
+};
+
+export function appendComment(input: AppendCommentInput): ApprovalComment {
+ const db = getDb();
+ const comment: ApprovalComment = {
+ id: randomUUID(),
+ approval_id: input.approval_id,
+ author_kind: input.author_kind,
+ author_id: input.author_id ?? null,
+ body: input.body,
+ created_at: new Date().toISOString(),
+ };
+ db.prepare(
+ `INSERT INTO approval_comments (id, approval_id, author_kind, author_id, body, created_at)
+ VALUES (?, ?, ?, ?, ?, ?)`,
+ ).run(
+ comment.id,
+ comment.approval_id,
+ comment.author_kind,
+ comment.author_id,
+ comment.body,
+ comment.created_at,
+ );
+ return comment;
+}
+
+export function listComments(approval_id: string): ApprovalComment[] {
+ const db = getDb();
+ return db
+ .prepare(
+ "SELECT * FROM approval_comments WHERE approval_id = ? ORDER BY created_at ASC",
+ )
+ .all(approval_id) as ApprovalComment[];
+}
+
+// ── Policies ────────────────────────────────────────────────────────
+
+export type CreatePolicyInput = {
+ project_slug: string;
+ action_type: ApprovalType;
+ agent_id?: string | null;
+ max_cost_usd?: number | null;
+ auto_decision: "approve" | "reject";
+ note?: string | null;
+ created_by_kind: "user" | "agent";
+ created_by_id?: string | null;
+};
+
+export function createPolicy(input: CreatePolicyInput): ApprovalPolicy {
+ const db = getDb();
+ const policy: ApprovalPolicy = {
+ id: randomUUID(),
+ project_slug: input.project_slug,
+ action_type: input.action_type,
+ agent_id: input.agent_id ?? null,
+ max_cost_usd: input.max_cost_usd ?? null,
+ auto_decision: input.auto_decision,
+ note: input.note ?? null,
+ created_at: new Date().toISOString(),
+ created_by_kind: input.created_by_kind,
+ created_by_id: input.created_by_id ?? null,
+ };
+ db.prepare(
+ `INSERT INTO approval_policies
+ (id, project_slug, action_type, agent_id, max_cost_usd, auto_decision, note, created_at, created_by_kind, created_by_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ).run(
+ policy.id,
+ policy.project_slug,
+ policy.action_type,
+ policy.agent_id,
+ policy.max_cost_usd,
+ policy.auto_decision,
+ policy.note,
+ policy.created_at,
+ policy.created_by_kind,
+ policy.created_by_id,
+ );
+ return policy;
+}
+
+export function listPolicies(project_slug: string): ApprovalPolicy[] {
+ const db = getDb();
+ return db
+ .prepare(
+ "SELECT * FROM approval_policies WHERE project_slug = ? ORDER BY created_at DESC",
+ )
+ .all(project_slug) as ApprovalPolicy[];
+}
+
+export function deletePolicy(id: string): boolean {
+ const db = getDb();
+ const info = db.prepare("DELETE FROM approval_policies WHERE id = ?").run(id);
+ return info.changes > 0;
+}
+
+/**
+ * Find the first policy that matches a candidate approval. Matching rules:
+ * - same project_slug
+ * - same action_type
+ * - agent_id matches (NULL agent_id in policy = any agent)
+ * - cost ≤ max_cost_usd (NULL max_cost_usd = no cap)
+ *
+ * Most-specific wins: agent-scoped policies are preferred over wildcard;
+ * cost-capped policies preferred over uncapped (tighter cap first).
+ */
+export function findMatchingPolicy(
+ project_slug: string,
+ action_type: ApprovalType,
+ agent_id: string,
+ cost_estimate_usd: number,
+): ApprovalPolicy | null {
+ const db = getDb();
+ const rows = db
+ .prepare(
+ `SELECT * FROM approval_policies
+ WHERE project_slug = ?
+ AND action_type = ?
+ AND (agent_id IS NULL OR agent_id = ?)
+ AND (max_cost_usd IS NULL OR max_cost_usd >= ?)
+ ORDER BY
+ CASE WHEN agent_id IS NULL THEN 1 ELSE 0 END,
+ CASE WHEN max_cost_usd IS NULL THEN 1 ELSE 0 END,
+ max_cost_usd ASC NULLS LAST,
+ created_at DESC`,
+ )
+ .all(project_slug, action_type, agent_id, cost_estimate_usd) as ApprovalPolicy[];
+ return rows[0] ?? null;
+}
diff --git a/src/server/db/migrations.ts b/src/server/db/migrations.ts
index da736e5d..7db3c4c1 100644
--- a/src/server/db/migrations.ts
+++ b/src/server/db/migrations.ts
@@ -184,6 +184,96 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
-- exposes per-project autonomy knobs and no runtime code reads/writes
-- this table, so drop it to keep the schema honest.
DROP TABLE IF EXISTS guardrails;
+`,
+ },
+ {
+ name: "006_approvals_v2.sql",
+ sql: `
+-- Approval system v2: blocked task state, comments, auto-policies, decision tracking.
+--
+-- Changes:
+-- 1. tasks.status CHECK gains 'blocked' (task is waiting on an approval).
+-- SQLite can't ALTER CHECK in place, so recreate the table.
+-- 2. approvals gains task_id, decision_note, decided_by_kind, decided_by_id;
+-- status CHECK gains 'revision_requested' (paperclip-style push-back loop).
+-- 3. New approval_comments table — discussion thread per approval.
+-- 4. New approval_policies table — "always allow" / "always reject" rules
+-- consulted before pending rows are created.
+
+CREATE TABLE tasks_new (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ brief TEXT NOT NULL,
+ success_criteria TEXT,
+ deadline_iso TEXT,
+ status TEXT NOT NULL CHECK (status IN ('proposed','approved','running','blocked','succeeded','failed','cancelled')),
+ result_json TEXT,
+ error_message TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ title TEXT,
+ thread_id TEXT,
+ assigner_agent_id TEXT,
+ display_id TEXT
+);
+INSERT INTO tasks_new (id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id)
+SELECT id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id
+FROM tasks;
+DROP TABLE tasks;
+ALTER TABLE tasks_new RENAME TO tasks;
+CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
+CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
+
+CREATE TABLE approvals_new (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ task_id TEXT,
+ action_summary TEXT NOT NULL,
+ action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
+ cost_estimate_usd REAL NOT NULL DEFAULT 0,
+ reasoning TEXT,
+ payload_json TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('pending','revision_requested','approved','rejected','expired')),
+ decision_note TEXT,
+ decided_by_kind TEXT CHECK (decided_by_kind IN ('user','agent','policy')),
+ decided_by_id TEXT,
+ created_at TEXT NOT NULL,
+ resolved_at TEXT
+);
+INSERT INTO approvals_new (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at)
+SELECT id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at
+FROM approvals;
+DROP TABLE approvals;
+ALTER TABLE approvals_new RENAME TO approvals;
+CREATE INDEX IF NOT EXISTS idx_approvals_actionable ON approvals(project_slug, status) WHERE status IN ('pending','revision_requested');
+CREATE INDEX IF NOT EXISTS idx_approvals_task ON approvals(task_id) WHERE task_id IS NOT NULL;
+
+CREATE TABLE IF NOT EXISTS approval_comments (
+ id TEXT PRIMARY KEY,
+ approval_id TEXT NOT NULL REFERENCES approvals(id) ON DELETE CASCADE,
+ author_kind TEXT NOT NULL CHECK (author_kind IN ('user','agent','system')),
+ author_id TEXT,
+ body TEXT NOT NULL,
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_approval_comments_approval ON approval_comments(approval_id, created_at);
+
+CREATE TABLE IF NOT EXISTS approval_policies (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
+ agent_id TEXT,
+ max_cost_usd REAL,
+ auto_decision TEXT NOT NULL CHECK (auto_decision IN ('approve','reject')),
+ note TEXT,
+ created_at TEXT NOT NULL,
+ created_by_kind TEXT NOT NULL CHECK (created_by_kind IN ('user','agent')),
+ created_by_id TEXT
+);
+CREATE INDEX IF NOT EXISTS idx_approval_policies_project ON approval_policies(project_slug, action_type);
`,
},
];
diff --git a/src/server/db/migrations/006_approvals_v2.sql b/src/server/db/migrations/006_approvals_v2.sql
new file mode 100644
index 00000000..9e9d5475
--- /dev/null
+++ b/src/server/db/migrations/006_approvals_v2.sql
@@ -0,0 +1,94 @@
+-- Approval system v2: blocked task state, comments, auto-policies, decision tracking.
+--
+-- Changes:
+-- 1. tasks.status CHECK gains 'blocked' (task is waiting on an approval).
+-- SQLite can't ALTER CHECK in place, so recreate the table.
+-- 2. approvals gains task_id, decision_note, decided_by_kind, decided_by_id;
+-- status CHECK gains 'revision_requested' (paperclip-style push-back loop).
+-- 3. New approval_comments table — discussion thread per approval.
+-- 4. New approval_policies table — "always allow" / "always reject" rules
+-- consulted before pending rows are created.
+
+-- ── tasks: add 'blocked' to status CHECK ──────────────────────────────
+CREATE TABLE tasks_new (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ brief TEXT NOT NULL,
+ success_criteria TEXT,
+ deadline_iso TEXT,
+ status TEXT NOT NULL CHECK (status IN ('proposed','approved','running','blocked','succeeded','failed','cancelled')),
+ result_json TEXT,
+ error_message TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ title TEXT,
+ thread_id TEXT,
+ assigner_agent_id TEXT,
+ display_id TEXT
+);
+INSERT INTO tasks_new (id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id)
+SELECT id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id
+FROM tasks;
+DROP TABLE tasks;
+ALTER TABLE tasks_new RENAME TO tasks;
+CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
+CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
+
+-- ── approvals: task_id, decision_note, decided_by_*, 'revision_requested' status ──
+CREATE TABLE approvals_new (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ task_id TEXT,
+ action_summary TEXT NOT NULL,
+ action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
+ cost_estimate_usd REAL NOT NULL DEFAULT 0,
+ reasoning TEXT,
+ payload_json TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('pending','revision_requested','approved','rejected','expired')),
+ decision_note TEXT,
+ decided_by_kind TEXT CHECK (decided_by_kind IN ('user','agent','policy')),
+ decided_by_id TEXT,
+ created_at TEXT NOT NULL,
+ resolved_at TEXT
+);
+INSERT INTO approvals_new (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at)
+SELECT id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at
+FROM approvals;
+DROP TABLE approvals;
+ALTER TABLE approvals_new RENAME TO approvals;
+-- Partial index: rows that still need attention (pending OR revision_requested).
+CREATE INDEX IF NOT EXISTS idx_approvals_actionable ON approvals(project_slug, status) WHERE status IN ('pending','revision_requested');
+CREATE INDEX IF NOT EXISTS idx_approvals_task ON approvals(task_id) WHERE task_id IS NOT NULL;
+
+-- ── approval_comments: discussion thread per approval ─────────────────
+-- Author kinds: 'user' = human, 'agent' = the requesting/deciding agent,
+-- 'system' = automated notes (e.g., "auto-approved by policy <id>").
+CREATE TABLE IF NOT EXISTS approval_comments (
+ id TEXT PRIMARY KEY,
+ approval_id TEXT NOT NULL REFERENCES approvals(id) ON DELETE CASCADE,
+ author_kind TEXT NOT NULL CHECK (author_kind IN ('user','agent','system')),
+ author_id TEXT,
+ body TEXT NOT NULL,
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_approval_comments_approval ON approval_comments(approval_id, created_at);
+
+-- ── approval_policies: auto-decide rules consulted before pending row is created ──
+-- agent_id IS NULL means "any agent". max_cost_usd IS NULL means "no cost cap".
+-- auto_decision='approve' auto-approves matching requests; ='reject' blocks them.
+CREATE TABLE IF NOT EXISTS approval_policies (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
+ agent_id TEXT,
+ max_cost_usd REAL,
+ auto_decision TEXT NOT NULL CHECK (auto_decision IN ('approve','reject')),
+ note TEXT,
+ created_at TEXT NOT NULL,
+ created_by_kind TEXT NOT NULL CHECK (created_by_kind IN ('user','agent')),
+ created_by_id TEXT
+);
+CREATE INDEX IF NOT EXISTS idx_approval_policies_project ON approval_policies(project_slug, action_type);
diff --git a/src/server/db/projects.ts b/src/server/db/projects.ts
index b4deb052..3e5731c2 100644
--- a/src/server/db/projects.ts
+++ b/src/server/db/projects.ts
@@ -112,6 +112,7 @@ export function changeProjectSlug(
const childTables = [
"tasks",
"approvals",
+ "approval_policies",
"cost_events",
"oauth_tokens",
"agent_actions",
@@ -184,7 +185,10 @@ export function deleteProjectRow(slug: string): void {
const db = getDb();
const childTables = [
"tasks",
+ // approval_comments is cleaned up by FK ON DELETE CASCADE when we drop
+ // the parent approvals rows below.
"approvals",
+ "approval_policies",
"cost_events",
"oauth_tokens",
"agent_actions",
diff --git a/src/server/db/tasks.test.ts b/src/server/db/tasks.test.ts
index c7993904..9b9d6e30 100644
--- a/src/server/db/tasks.test.ts
+++ b/src/server/db/tasks.test.ts
@@ -17,7 +17,9 @@ import {
inFlightCountsByAgent,
listTasks,
listTasksByAgent,
+ markTaskBlocked,
setTaskThreadIfMissing,
+ unblockTask,
updateTask,
} from "./tasks";
@@ -439,3 +441,57 @@ describe("claimProposedTask", () => {
expect(claimProposedTask(t.id)).toBeNull();
});
});
+
+describe("markTaskBlocked + unblockTask", () => {
+ it("flips a running task to blocked, then unblockTask flips it back to running", () => {
+ seedProject();
+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
+ claimProposedTask(t.id); // proposed → running
+ const blocked = markTaskBlocked(t.id);
+ expect(blocked?.status).toBe("blocked");
+ const unblocked = unblockTask(t.id);
+ expect(unblocked?.status).toBe("running");
+ });
+
+ it("markTaskBlocked accepts proposed + approved as source states", () => {
+ seedProject();
+ const a = createTask({ project_slug: "acme", agent_id: "x", brief: "a" });
+ // proposed → blocked
+ expect(markTaskBlocked(a.id)?.status).toBe("blocked");
+
+ const b = createTask({
+ project_slug: "acme",
+ agent_id: "x",
+ brief: "b",
+ status: "approved",
+ });
+ expect(markTaskBlocked(b.id)?.status).toBe("blocked");
+ });
+
+ it("markTaskBlocked does NOT regress a terminal task", () => {
+ seedProject();
+ const t = createTask({
+ project_slug: "acme",
+ agent_id: "x",
+ brief: "b",
+ status: "succeeded",
+ });
+ const after = markTaskBlocked(t.id);
+ expect(after?.status).toBe("succeeded");
+ });
+
+ it("unblockTask is a no-op when the task isn't blocked", () => {
+ seedProject();
+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
+ claimProposedTask(t.id);
+ const after = unblockTask(t.id);
+ expect(after?.status).toBe("running"); // unchanged
+ });
+
+ it("inFlightCountsByAgent counts blocked tasks too", () => {
+ seedProject();
+ const t = createTask({ project_slug: "acme", agent_id: "agent-1", brief: "b" });
+ markTaskBlocked(t.id);
+ expect(inFlightCountsByAgent("acme").get("agent-1")).toBe(1);
+ });
+});
diff --git a/src/server/db/tasks.ts b/src/server/db/tasks.ts
index fdd8b3b8..425a3291 100644
--- a/src/server/db/tasks.ts
+++ b/src/server/db/tasks.ts
@@ -156,7 +156,7 @@ export function inFlightCountsByAgent(
.prepare(
`SELECT agent_id, COUNT(*) as count
FROM tasks
- WHERE project_slug = ? AND status IN ('proposed', 'approved', 'running')
+ WHERE project_slug = ? AND status IN ('proposed', 'approved', 'running', 'blocked')
GROUP BY agent_id`,
)
.all(project_slug) as Array<{ agent_id: string; count: number }>;
@@ -208,3 +208,30 @@ export function claimProposedTask(id: string): Task | null {
if (info.changes === 0) return null;
return getTask(id);
}
+
+/**
+ * Flip a running task to `blocked` (waiting on an approval). Only transitions
+ * from `running` or `proposed` so we don't undo a terminal state. Returns
+ * the post-flip row, or the current row when the transition didn't apply.
+ */
+export function markTaskBlocked(id: string): Task | null {
+ const db = getDb();
+ const now = new Date().toISOString();
+ db.prepare(
+ "UPDATE tasks SET status = 'blocked', updated_at = ? WHERE id = ? AND status IN ('running','proposed','approved')",
+ ).run(now, id);
+ return getTask(id);
+}
+
+/**
+ * Flip a blocked task back to running once its approval resolves. No-op when
+ * the task isn't blocked (e.g., already terminal because the user cancelled).
+ */
+export function unblockTask(id: string): Task | null {
+ const db = getDb();
+ const now = new Date().toISOString();
+ db.prepare(
+ "UPDATE tasks SET status = 'running', updated_at = ? WHERE id = ? AND status = 'blocked'",
+ ).run(now, id);
+ return getTask(id);
+}
diff --git a/src/server/mcp-server/jsonrpc.test.ts b/src/server/mcp-server/jsonrpc.test.ts
new file mode 100644
index 00000000..181324cc
--- /dev/null
+++ b/src/server/mcp-server/jsonrpc.test.ts
@@ -0,0 +1,317 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+
+const getTaskMock = vi.fn();
+const updateTaskMock = vi.fn();
+vi.mock("@/server/db/tasks", () => ({
+ getTask: (...a: unknown[]) => getTaskMock(...a),
+ updateTask: (...a: unknown[]) => updateTaskMock(...a),
+}));
+
+const logAgentActionMock = vi.fn();
+vi.mock("@/server/db/agent-actions", () => ({
+ logAgentAction: (...a: unknown[]) => logAgentActionMock(...a),
+}));
+
+import { handleJsonRpc, type JsonRpcRequest } from "./jsonrpc";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+function call(req: JsonRpcRequest) {
+ return handleJsonRpc(req);
+}
+
+describe("handleJsonRpc — initialize", () => {
+ it("returns protocolVersion + serverInfo + tools capability", async () => {
+ const r = await call({ jsonrpc: "2.0", id: 1, method: "initialize" });
+ expect(r).not.toBeNull();
+ if (!r || "error" in r) throw new Error("expected ok result");
+ const result = r.result as {
+ protocolVersion: string;
+ serverInfo: { name: string };
+ capabilities: { tools: object };
+ };
+ expect(result.protocolVersion).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ expect(result.serverInfo.name).toBe("notfair-cmo");
+ expect(result.capabilities.tools).toEqual({});
+ });
+
+ it("notifications (id null) return null with no response body", async () => {
+ const r = await call({
+ jsonrpc: "2.0",
+ id: null,
+ method: "notifications/initialized",
+ });
+ expect(r).toBeNull();
+ });
+});
+
+describe("handleJsonRpc — tools/list", () => {
+ it("includes submit_task_status with the right enum + required fields", async () => {
+ const r = await call({ jsonrpc: "2.0", id: 1, method: "tools/list" });
+ if (!r || "error" in r) throw new Error("expected ok result");
+ const { tools } = r.result as {
+ tools: Array<{
+ name: string;
+ description: string;
+ inputSchema: {
+ properties: Record<string, { type: string; enum?: string[] }>;
+ required: string[];
+ };
+ }>;
+ };
+ const submit = tools.find((t) => t.name === "submit_task_status")!;
+ expect(submit).toBeDefined();
+ expect(submit.inputSchema.properties.task_id.type).toBe("string");
+ expect(submit.inputSchema.properties.status.enum).toEqual([
+ "working",
+ "done",
+ "blocked",
+ "failed",
+ ]);
+ // summary is optional → not in required
+ expect(submit.inputSchema.required).toEqual(
+ expect.arrayContaining(["task_id", "status"]),
+ );
+ expect(submit.inputSchema.required).not.toContain("summary");
+ });
+});
+
+describe("handleJsonRpc — tools/call submit_task_status", () => {
+ it("rejects an invalid status value with isError content (no JSON-RPC error)", async () => {
+ const r = await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "submit_task_status",
+ arguments: {
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ task_id: "t1",
+ status: "closed",
+ },
+ },
+ });
+ if (!r || "error" in r) throw new Error("expected ok envelope");
+ const result = r.result as {
+ isError: boolean;
+ content: Array<{ type: string; text: string }>;
+ };
+ expect(result.isError).toBe(true);
+ expect(result.content[0]!.text).toMatch(/Invalid arguments/);
+ expect(updateTaskMock).not.toHaveBeenCalled();
+ });
+
+ it("updates the task and logs an action on valid `done` status", async () => {
+ getTaskMock.mockReturnValue({
+ id: "t-uuid",
+ display_id: "demo-1",
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ status: "running",
+ });
+ const r = await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "submit_task_status",
+ arguments: {
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ task_id: "demo-1",
+ status: "done",
+ summary: "shipped the change",
+ },
+ },
+ });
+ if (!r || "error" in r) throw new Error("expected ok envelope");
+ const result = r.result as { isError: boolean };
+ expect(result.isError).toBe(false);
+ expect(updateTaskMock).toHaveBeenCalledWith(
+ "t-uuid",
+ expect.objectContaining({
+ status: "succeeded",
+ result: { summary: "shipped the change" },
+ }),
+ );
+ expect(logAgentActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action_type: "task_done",
+ task_id: "t-uuid",
+ }),
+ );
+ });
+
+ it("maps status=blocked to TaskStatus blocked (not running)", async () => {
+ getTaskMock.mockReturnValue({
+ id: "t1",
+ display_id: "x-1",
+ project_slug: "x",
+ agent_id: "x-agent",
+ status: "running",
+ });
+ await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "submit_task_status",
+ arguments: {
+ project_slug: "x",
+ agent_id: "x-agent",
+ task_id: "t1",
+ status: "blocked",
+ },
+ },
+ });
+ expect(updateTaskMock).toHaveBeenCalledWith(
+ "t1",
+ expect.objectContaining({ status: "blocked" }),
+ );
+ });
+
+ it("maps status=failed and stores summary in error_message", async () => {
+ getTaskMock.mockReturnValue({
+ id: "t1",
+ display_id: "x-1",
+ project_slug: "x",
+ agent_id: "x-agent",
+ status: "running",
+ });
+ await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "submit_task_status",
+ arguments: {
+ project_slug: "x",
+ agent_id: "x-agent",
+ task_id: "t1",
+ status: "failed",
+ summary: "MCP returned 401",
+ },
+ },
+ });
+ expect(updateTaskMock).toHaveBeenCalledWith(
+ "t1",
+ expect.objectContaining({
+ status: "failed",
+ error_message: "MCP returned 401",
+ }),
+ );
+ });
+
+ it("returns isError when task_id is unknown", async () => {
+ getTaskMock.mockReturnValue(null);
+ const r = await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "submit_task_status",
+ arguments: {
+ project_slug: "x",
+ agent_id: "x-agent",
+ task_id: "missing",
+ status: "done",
+ summary: "x",
+ },
+ },
+ });
+ if (!r || "error" in r) throw new Error("expected ok envelope");
+ const result = r.result as { isError: boolean; content: { text: string }[] };
+ expect(result.isError).toBe(true);
+ expect(result.content[0]!.text).toMatch(/Unknown task_id/);
+ expect(updateTaskMock).not.toHaveBeenCalled();
+ });
+
+ it("returns isError when project_slug doesn't match the task's (cross-project guard)", async () => {
+ getTaskMock.mockReturnValue({
+ id: "t1",
+ display_id: "x-1",
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ status: "running",
+ });
+ const r = await call({
+ jsonrpc: "2.0",
+ id: 99,
+ method: "tools/call",
+ params: {
+ name: "submit_task_status",
+ arguments: {
+ project_slug: "evil-other",
+ agent_id: "demo-google-ads",
+ task_id: "t1",
+ status: "done",
+ summary: "x",
+ },
+ },
+ });
+ if (!r || "error" in r) throw new Error("expected ok envelope");
+ const result = r.result as { isError: boolean; content: { text: string }[] };
+ expect(result.isError).toBe(true);
+ expect(result.content[0]!.text).toMatch(/Cross-project/);
+ expect(updateTaskMock).not.toHaveBeenCalled();
+ });
+
+ it("is a no-op on terminal tasks (already succeeded/failed/cancelled)", async () => {
+ getTaskMock.mockReturnValue({
+ id: "t1",
+ display_id: "x-1",
+ project_slug: "x",
+ agent_id: "x-agent",
+ status: "succeeded",
+ });
+ const r = await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "submit_task_status",
+ arguments: {
+ project_slug: "x",
+ agent_id: "x-agent",
+ task_id: "t1",
+ status: "done",
+ },
+ },
+ });
+ if (!r || "error" in r) throw new Error("expected ok envelope");
+ const result = r.result as { isError: boolean };
+ expect(result.isError).toBe(false);
+ // Terminal status is preserved — no DB write happens.
+ expect(updateTaskMock).not.toHaveBeenCalled();
+ });
+
+ it("returns Method-not-found for unknown tools", async () => {
+ const r = await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: "wat", arguments: {} },
+ });
+ if (!r || "error" in r) {
+ expect(r?.error?.code).toBe(-32601);
+ return;
+ }
+ throw new Error("expected error envelope");
+ });
+
+ it("returns Method-not-found for unknown methods", async () => {
+ const r = await call({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "wat/nope",
+ });
+ if (!r || "error" in r) {
+ expect(r?.error?.code).toBe(-32601);
+ return;
+ }
+ throw new Error("expected error envelope");
+ });
+});
diff --git a/src/server/mcp-server/jsonrpc.ts b/src/server/mcp-server/jsonrpc.ts
new file mode 100644
index 00000000..ea54daf2
--- /dev/null
+++ b/src/server/mcp-server/jsonrpc.ts
@@ -0,0 +1,112 @@
+import { describeTool, findTool, TOOLS } from "./tools";
+
+/**
+ * JSON-RPC 2.0 dispatcher for notfair-cmo's outbound MCP server.
+ *
+ * MCP methods we implement:
+ * - initialize: handshake; reports protocol version + server info
+ * - tools/list: returns the available tool defs (name + JSON-schema)
+ * - tools/call: executes a named tool with arguments
+ *
+ * Notifications (no id) we no-op so older clients that send
+ * `notifications/initialized` don't error.
+ *
+ * Auth is upstream of this dispatcher (the route checks the Bearer first);
+ * callers reaching here are already authenticated.
+ */
+
+export type JsonRpcRequest = {
+ jsonrpc: "2.0";
+ id?: string | number | null;
+ method: string;
+ params?: Record<string, unknown>;
+};
+
+export type JsonRpcResponse =
+ | {
+ jsonrpc: "2.0";
+ id: string | number | null;
+ result: unknown;
+ }
+ | {
+ jsonrpc: "2.0";
+ id: string | number | null;
+ error: { code: number; message: string; data?: unknown };
+ };
+
+const PROTOCOL_VERSION = "2025-06-18";
+
+export async function handleJsonRpc(
+ req: JsonRpcRequest,
+): Promise<JsonRpcResponse | null> {
+ // Notifications (no id): handle the side-effecting ones but never reply.
+ if (req.id === undefined || req.id === null) {
+ return null;
+ }
+ const id = req.id;
+
+ try {
+ switch (req.method) {
+ case "initialize":
+ return ok(id, {
+ protocolVersion: PROTOCOL_VERSION,
+ serverInfo: { name: "notfair-cmo", version: "0.1.0" },
+ capabilities: { tools: {} },
+ });
+ case "tools/list":
+ return ok(id, { tools: TOOLS.map(describeTool) });
+ case "tools/call":
+ return await handleToolsCall(id, req.params ?? {});
+ case "ping":
+ return ok(id, {});
+ default:
+ return err(id, -32601, `Method not found: ${req.method}`);
+ }
+ } catch (cause) {
+ return err(
+ id,
+ -32603,
+ `Internal error: ${cause instanceof Error ? cause.message : String(cause)}`,
+ );
+ }
+}
+
+async function handleToolsCall(
+ id: string | number,
+ params: Record<string, unknown>,
+): Promise<JsonRpcResponse> {
+ const name = params.name;
+ const args = params.arguments ?? {};
+ if (typeof name !== "string") {
+ return err(id, -32602, "Invalid params: 'name' must be a string");
+ }
+ const tool = findTool(name);
+ if (!tool) {
+ return err(id, -32601, `Unknown tool: ${name}`);
+ }
+ // The handler does its own schema validation and returns a structured
+ // result. For MCP tools/call, we surface errors via `isError: true` on the
+ // result envelope (per spec) rather than as JSON-RPC errors, so the agent's
+ // model sees the failure as a tool-call response it can react to.
+ const result = await tool.handler(args, {});
+ if (!result.ok) {
+ return ok(id, {
+ isError: true,
+ content: [{ type: "text", text: result.error }],
+ });
+ }
+ return ok(id, { isError: false, content: result.content });
+}
+
+function ok(id: string | number, result: unknown): JsonRpcResponse {
+ return { jsonrpc: "2.0", id, result };
+}
+
+function err(
+ id: string | number,
+ code: number,
+ message: string,
+ data?: unknown,
+): JsonRpcResponse {
+ return { jsonrpc: "2.0", id, error: { code, message, data } };
+}
diff --git a/src/server/mcp-server/registration.test.ts b/src/server/mcp-server/registration.test.ts
new file mode 100644
index 00000000..cec697d5
--- /dev/null
+++ b/src/server/mcp-server/registration.test.ts
@@ -0,0 +1,175 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const openclawMock = vi.fn();
+vi.mock("@/server/openclaw/cli", () => {
+ class FakeOpenClawError extends Error {
+ exitCode: number | null;
+ stderr: string;
+ constructor(message: string, stderr = "", exitCode = 1) {
+ super(message);
+ this.name = "OpenClawError";
+ this.stderr = stderr;
+ this.exitCode = exitCode;
+ }
+ }
+ return {
+ openclaw: (...a: unknown[]) => openclawMock(...a),
+ OpenClawError: FakeOpenClawError,
+ };
+});
+import { OpenClawError } from "@/server/openclaw/cli";
+
+const getSecretMock = vi.fn(() => "deadbeef".repeat(8));
+vi.mock("./secret", () => ({
+ getOrCreateMcpServerSecret: () => getSecretMock(),
+}));
+
+import {
+ cleanupLegacyOrchestrationRows,
+ ensureOrchestrationMcpInstalled,
+ getOrchestrationMcpUrl,
+ installOrchestrationMcp,
+ ORCHESTRATION_MCP_KEY,
+} from "./registration";
+
+const ORIGINAL_ENV = { ...process.env };
+
+beforeEach(() => {
+ openclawMock.mockReset();
+ getSecretMock.mockClear();
+});
+
+afterEach(() => {
+ process.env = { ...ORIGINAL_ENV };
+});
+
+describe("ORCHESTRATION_MCP_KEY", () => {
+ it("is a stable global key (no project prefix)", () => {
+ expect(ORCHESTRATION_MCP_KEY).toBe("notfair-orchestration");
+ });
+});
+
+describe("getOrchestrationMcpUrl", () => {
+ it("defaults to http://127.0.0.1:3326/api/mcp/orchestration", () => {
+ delete process.env.NOTFAIR_CMO_PORT;
+ delete process.env.NOTFAIR_CMO_MCP_URL;
+ expect(getOrchestrationMcpUrl()).toBe(
+ "http://127.0.0.1:3326/api/mcp/orchestration",
+ );
+ });
+
+ it("respects NOTFAIR_CMO_PORT", () => {
+ process.env.NOTFAIR_CMO_PORT = "4001";
+ delete process.env.NOTFAIR_CMO_MCP_URL;
+ expect(getOrchestrationMcpUrl()).toBe(
+ "http://127.0.0.1:4001/api/mcp/orchestration",
+ );
+ });
+
+ it("NOTFAIR_CMO_MCP_URL overrides the host:port construction", () => {
+ process.env.NOTFAIR_CMO_MCP_URL = "https://example.invalid/mcp";
+ expect(getOrchestrationMcpUrl()).toBe("https://example.invalid/mcp");
+ });
+});
+
+describe("ensureOrchestrationMcpInstalled", () => {
+ it("installs when the row is missing (mcp show fails)", async () => {
+ // First call: openclaw mcp show → throws OpenClawError (row missing).
+ // Second call: openclaw mcp set → resolves.
+ openclawMock
+ .mockRejectedValueOnce(new OpenClawError("not found", "", 1))
+ .mockResolvedValueOnce(undefined);
+ const r = await ensureOrchestrationMcpInstalled();
+ if (!r.ok) throw new Error("expected ok");
+ expect(r.status).toBe("installed");
+ expect(r.key).toBe("notfair-orchestration");
+ expect(openclawMock).toHaveBeenLastCalledWith(
+ ["mcp", "set", "notfair-orchestration", expect.any(String)],
+ { json: false },
+ );
+ });
+
+ it("no-ops with status 'already_installed' when row matches desired config", async () => {
+ const url = "http://127.0.0.1:3326/api/mcp/orchestration";
+ delete process.env.NOTFAIR_CMO_PORT;
+ delete process.env.NOTFAIR_CMO_MCP_URL;
+ openclawMock.mockResolvedValueOnce({
+ url,
+ transport: "streamable-http",
+ headers: { Authorization: `Bearer ${"deadbeef".repeat(8)}` },
+ });
+ const r = await ensureOrchestrationMcpInstalled();
+ if (!r.ok) throw new Error("expected ok");
+ expect(r.status).toBe("already_installed");
+ // Only the show call happened — no set.
+ expect(openclawMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("re-installs with status 'updated' when stored config drifts (URL changed)", async () => {
+ openclawMock
+ .mockResolvedValueOnce({
+ url: "http://old.invalid/mcp",
+ transport: "streamable-http",
+ headers: { Authorization: `Bearer ${"deadbeef".repeat(8)}` },
+ })
+ .mockResolvedValueOnce(undefined);
+ const r = await ensureOrchestrationMcpInstalled();
+ if (!r.ok) throw new Error("expected ok");
+ expect(r.status).toBe("updated");
+ expect(openclawMock).toHaveBeenLastCalledWith(
+ ["mcp", "set", "notfair-orchestration", expect.any(String)],
+ { json: false },
+ );
+ });
+
+ it("returns ok:false with the OpenClaw error on set failure", async () => {
+ openclawMock
+ .mockRejectedValueOnce(new OpenClawError("not found", "", 1))
+ .mockRejectedValueOnce(new OpenClawError("write blew up", "perm denied", 1));
+ const r = await ensureOrchestrationMcpInstalled();
+ expect(r.ok).toBe(false);
+ if (r.ok) throw new Error("unreachable");
+ expect(r.error).toMatch(/write blew up/);
+ });
+});
+
+describe("installOrchestrationMcp (unconditional)", () => {
+ it("always writes the row", async () => {
+ openclawMock.mockResolvedValue(undefined);
+ const r = await installOrchestrationMcp();
+ if (!r.ok) throw new Error("expected ok");
+ expect(r.status).toBe("installed");
+ expect(openclawMock).toHaveBeenCalledWith(
+ ["mcp", "set", "notfair-orchestration", expect.any(String)],
+ { json: false },
+ );
+ });
+});
+
+describe("cleanupLegacyOrchestrationRows", () => {
+ it("unsets one row per slug; swallows per-row errors", async () => {
+ openclawMock
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new OpenClawError("not found", "", 1))
+ .mockResolvedValueOnce(undefined);
+ await expect(
+ cleanupLegacyOrchestrationRows(["a", "b", "c"]),
+ ).resolves.toBeUndefined();
+ expect(openclawMock).toHaveBeenCalledTimes(3);
+ expect(openclawMock).toHaveBeenNthCalledWith(
+ 1,
+ ["mcp", "unset", "a-notfair-orchestration"],
+ { json: false },
+ );
+ expect(openclawMock).toHaveBeenNthCalledWith(
+ 3,
+ ["mcp", "unset", "c-notfair-orchestration"],
+ { json: false },
+ );
+ });
+
+ it("no-op on empty slug list", async () => {
+ await cleanupLegacyOrchestrationRows([]);
+ expect(openclawMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/mcp-server/registration.ts b/src/server/mcp-server/registration.ts
new file mode 100644
index 00000000..070e5f27
--- /dev/null
+++ b/src/server/mcp-server/registration.ts
@@ -0,0 +1,147 @@
+import { openclaw, OpenClawError } from "@/server/openclaw/cli";
+
+import { getOrCreateMcpServerSecret } from "./secret";
+
+/**
+ * Register notfair-cmo's outbound MCP server with OpenClaw — once, globally.
+ *
+ * The orchestration tools (`create_task`, `submit_task_status`,
+ * `request_approval`, etc.) are project-scoped via a required `project_slug`
+ * argument on every tool call, so a SINGLE OpenClaw MCP registration is
+ * enough for every project + every agent in this install. Wasteful + brittle
+ * to write one MCP row per project (every row points at the same URL with
+ * the same secret).
+ *
+ * Behavior:
+ * - `ensureOrchestrationMcpInstalled()` — idempotent. Calls `openclaw mcp show`
+ * first; only writes if the row is missing OR points at a stale URL/secret.
+ * Safe to call from every provisioning step.
+ * - `installOrchestrationMcp()` — unconditional set (used by a future CLI
+ * reinstall command).
+ * - `cleanupLegacyOrchestrationRows(slugs)` — one-time migration helper that
+ * removes the per-project `<slug>-notfair-orchestration` rows we used to
+ * create. Called from provisioning so old installs heal on next provision.
+ *
+ * URL: `NOTFAIR_CMO_MCP_URL` if set, else
+ * `http://127.0.0.1:${NOTFAIR_CMO_PORT||3326}/api/mcp/orchestration`.
+ */
+
+export const ORCHESTRATION_MCP_KEY = "notfair-orchestration";
+
+function defaultMcpUrl(): string {
+ if (process.env.NOTFAIR_CMO_MCP_URL?.trim()) {
+ return process.env.NOTFAIR_CMO_MCP_URL.trim();
+ }
+ const port = process.env.NOTFAIR_CMO_PORT?.trim() || "3326";
+ return `http://127.0.0.1:${port}/api/mcp/orchestration`;
+}
+
+function buildConfig(): { url: string; transport: string; headers: Record<string, string> } {
+ return {
+ url: defaultMcpUrl(),
+ transport: "streamable-http",
+ headers: { Authorization: `Bearer ${getOrCreateMcpServerSecret()}` },
+ };
+}
+
+export type InstallResult =
+ | { ok: true; status: "already_installed" | "installed" | "updated"; key: string; url: string }
+ | { ok: false; key: string; url: string; error: string };
+
+/**
+ * Idempotent install. Reads the current row; writes only when missing or
+ * stale (URL changed via NOTFAIR_CMO_MCP_URL, secret rotated, etc.).
+ */
+export async function ensureOrchestrationMcpInstalled(): Promise<InstallResult> {
+ const desired = buildConfig();
+ const key = ORCHESTRATION_MCP_KEY;
+ const current = await readMcpRow(key);
+ if (current && configMatches(current, desired)) {
+ return { ok: true, status: "already_installed", key, url: desired.url };
+ }
+ try {
+ await openclaw(["mcp", "set", key, JSON.stringify(desired)], { json: false });
+ return {
+ ok: true,
+ status: current ? "updated" : "installed",
+ key,
+ url: desired.url,
+ };
+ } catch (err) {
+ const message =
+ err instanceof OpenClawError
+ ? err.message
+ : err instanceof Error
+ ? err.message
+ : String(err);
+ return { ok: false, key, url: desired.url, error: message };
+ }
+}
+
+/** Unconditional install — overwrites whatever's there. */
+export async function installOrchestrationMcp(): Promise<InstallResult> {
+ const desired = buildConfig();
+ const key = ORCHESTRATION_MCP_KEY;
+ try {
+ await openclaw(["mcp", "set", key, JSON.stringify(desired)], { json: false });
+ return { ok: true, status: "installed", key, url: desired.url };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return { ok: false, key, url: desired.url, error: message };
+ }
+}
+
+/**
+ * Remove the legacy per-project `<slug>-notfair-orchestration` rows we wrote
+ * before the registration went global. Pass the list of project slugs that
+ * may have stale rows. Errors per-slug are swallowed (the row may already be
+ * gone). Safe + idempotent — no-op on a fresh install.
+ */
+export async function cleanupLegacyOrchestrationRows(
+ slugs: string[],
+): Promise<void> {
+ for (const slug of slugs) {
+ const legacyKey = `${slug}-notfair-orchestration`;
+ try {
+ await openclaw(["mcp", "unset", legacyKey], { json: false });
+ } catch {
+ // Row didn't exist or unset failed; ignore.
+ }
+ }
+}
+
+async function readMcpRow(key: string): Promise<{
+ url?: string;
+ transport?: string;
+ headers?: Record<string, string>;
+} | null> {
+ try {
+ const out = await openclaw(["mcp", "show", key], { json: true });
+ if (!out || typeof out !== "object") return null;
+ return out as {
+ url?: string;
+ transport?: string;
+ headers?: Record<string, string>;
+ };
+ } catch (err) {
+ if (err instanceof OpenClawError) return null;
+ throw err;
+ }
+}
+
+function configMatches(
+ current: { url?: string; transport?: string; headers?: Record<string, string> },
+ desired: { url: string; transport: string; headers: Record<string, string> },
+): boolean {
+ if (current.url !== desired.url) return false;
+ if (current.transport !== desired.transport) return false;
+ const currentAuth =
+ current.headers?.Authorization ?? current.headers?.authorization;
+ if (currentAuth !== desired.headers.Authorization) return false;
+ return true;
+}
+
+/** Read-only URL accessor for CLI/tooling. */
+export function getOrchestrationMcpUrl(): string {
+ return defaultMcpUrl();
+}
diff --git a/src/server/mcp-server/secret.test.ts b/src/server/mcp-server/secret.test.ts
new file mode 100644
index 00000000..d84fddaf
--- /dev/null
+++ b/src/server/mcp-server/secret.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { mkdtempSync, rmSync, existsSync, statSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+type SecretModule = typeof import("./secret");
+
+async function loadSecret(): Promise<SecretModule> {
+ return (await import("./secret")) as SecretModule;
+}
+
+let tmpDir: string;
+
+beforeEach(() => {
+ vi.resetModules();
+ tmpDir = mkdtempSync(join(tmpdir(), "notfair-cmo-secret-"));
+ process.env.NOTFAIR_CMO_DATA_DIR = tmpDir;
+});
+
+afterEach(() => {
+ delete process.env.NOTFAIR_CMO_DATA_DIR;
+ if (tmpDir && existsSync(tmpDir)) rmSync(tmpDir, { recursive: true, force: true });
+});
+
+describe("getOrCreateMcpServerSecret", () => {
+ it("mints + persists a 64-char hex secret on first call", async () => {
+ const { getOrCreateMcpServerSecret, getMcpServerSecretPath } = await loadSecret();
+ const s = getOrCreateMcpServerSecret();
+ expect(s).toMatch(/^[0-9a-f]{64}$/);
+ expect(existsSync(getMcpServerSecretPath())).toBe(true);
+ const onDisk = readFileSync(getMcpServerSecretPath(), "utf8").trim();
+ expect(onDisk).toBe(s);
+ });
+
+ it("returns the same secret on subsequent calls (in-process and after reload)", async () => {
+ const { getOrCreateMcpServerSecret } = await loadSecret();
+ const first = getOrCreateMcpServerSecret();
+ const second = getOrCreateMcpServerSecret();
+ expect(second).toBe(first);
+ // Simulate process restart by re-importing.
+ vi.resetModules();
+ const reloaded = await loadSecret();
+ expect(reloaded.getOrCreateMcpServerSecret()).toBe(first);
+ });
+
+ it("writes the secret file with 0600 perms (POSIX only)", async () => {
+ if (process.platform === "win32") return;
+ const { getOrCreateMcpServerSecret, getMcpServerSecretPath } = await loadSecret();
+ getOrCreateMcpServerSecret();
+ const mode = statSync(getMcpServerSecretPath()).mode & 0o777;
+ expect(mode).toBe(0o600);
+ });
+});
+
+describe("verifyMcpServerSecret", () => {
+ it("returns true for the stored secret", async () => {
+ const { getOrCreateMcpServerSecret, verifyMcpServerSecret } = await loadSecret();
+ const s = getOrCreateMcpServerSecret();
+ expect(verifyMcpServerSecret(s)).toBe(true);
+ });
+
+ it("returns false for a wrong-but-same-length value", async () => {
+ const { getOrCreateMcpServerSecret, verifyMcpServerSecret } = await loadSecret();
+ const s = getOrCreateMcpServerSecret();
+ const wrong = "0".repeat(s.length);
+ expect(verifyMcpServerSecret(wrong)).toBe(false);
+ });
+
+ it("returns false for mismatched length (avoids timingSafeEqual throw)", async () => {
+ const { verifyMcpServerSecret } = await loadSecret();
+ expect(verifyMcpServerSecret("short")).toBe(false);
+ });
+
+ it("returns false for null/undefined/empty", async () => {
+ const { verifyMcpServerSecret } = await loadSecret();
+ expect(verifyMcpServerSecret(null)).toBe(false);
+ expect(verifyMcpServerSecret(undefined)).toBe(false);
+ expect(verifyMcpServerSecret("")).toBe(false);
+ });
+});
diff --git a/src/server/mcp-server/secret.ts b/src/server/mcp-server/secret.ts
new file mode 100644
index 00000000..ac966843
--- /dev/null
+++ b/src/server/mcp-server/secret.ts
@@ -0,0 +1,53 @@
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { randomBytes, timingSafeEqual } from "node:crypto";
+
+/**
+ * Shared secret used to authenticate calls from OpenClaw-side agents into our
+ * outbound-facing MCP server. Lives in a file with 0600 perms inside the
+ * notfair-cmo data dir (NOT the project SQLite DB — keeping it in a small
+ * dedicated file lets the file's own mode bits enforce single-user access
+ * and lets the OpenClaw registration step read it with a one-liner).
+ *
+ * Single-user local CLI: we mint one secret per install and reuse it across
+ * every project + every agent. No rotation in V1 — easy to add later by
+ * deleting the file and re-running `notfair-cmo mcp register`.
+ */
+
+const DATA_DIR = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+const SECRET_PATH = join(DATA_DIR, "mcp-server-secret");
+
+/** Read the secret, minting + persisting one the first time. */
+export function getOrCreateMcpServerSecret(): string {
+ if (!existsSync(DATA_DIR)) {
+ mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
+ }
+ if (existsSync(SECRET_PATH)) {
+ const value = readFileSync(SECRET_PATH, "utf8").trim();
+ if (value) return value;
+ }
+ const minted = randomBytes(32).toString("hex");
+ writeFileSync(SECRET_PATH, `${minted}\n`, { mode: 0o600 });
+ return minted;
+}
+
+/**
+ * Constant-time compare of a presented bearer against the stored secret.
+ * Returns false rather than throwing when the input is malformed so callers
+ * can map all unauth paths to 401 without special-casing exceptions.
+ */
+export function verifyMcpServerSecret(presented: string | null | undefined): boolean {
+ if (!presented) return false;
+ const expected = getOrCreateMcpServerSecret();
+ if (presented.length !== expected.length) return false;
+ return timingSafeEqual(
+ Buffer.from(presented, "utf8"),
+ Buffer.from(expected, "utf8"),
+ );
+}
+
+/** Where the secret lives on disk — surfaced for CLI registration helpers. */
+export function getMcpServerSecretPath(): string {
+ return SECRET_PATH;
+}
diff --git a/src/server/mcp-server/tools.ts b/src/server/mcp-server/tools.ts
new file mode 100644
index 00000000..42629c5e
--- /dev/null
+++ b/src/server/mcp-server/tools.ts
@@ -0,0 +1,763 @@
+import { z } from "zod";
+
+import {
+ APPROVAL_ACTION_TYPE_VALUES,
+ handleAddTaskComment,
+ handleAskUser,
+ handleCancelTask,
+ handleCreateTask,
+ handleGetApproval,
+ handleGetProject,
+ handleGetTask,
+ handleListApprovalActionTypes,
+ handleListApprovalsForTask,
+ handleListMyApprovals,
+ handleListMyTasks,
+ handleListPendingApprovals,
+ handleListProjectAgents,
+ handleListTaskComments,
+ handleListTaskStatuses,
+ handleListTasks,
+ handleRequestApproval,
+ handleTaskStatus,
+ handleUpdateTask,
+ TASK_STATUS_VALUES,
+} from "@/server/orchestration/handlers";
+import type { TaskStatus } from "@/types";
+
+/**
+ * Tool definitions exposed by notfair-cmo's MCP server to OpenClaw-side
+ * agents. The MCP server is **globally installed** (one OpenClaw row,
+ * shared across every project), so every tool takes a required
+ * `project_slug` argument the caller MUST fill in. We never derive
+ * project from the bearer because every project's agents use the same
+ * bearer — that's the whole point of "globally shared." The agent learns
+ * its `project_slug` + `agent_id` from its IDENTITY.md prompt header and
+ * from the task kickoff message.
+ *
+ * Schema enforcement (zod) prevents the kind of drift that stranded
+ * `superpublic-test-1`: an agent emitting `status: closed` instead of a
+ * valid enum. The provider rejects invalid values before the model emits
+ * them; we double-check server-side so a misbehaving runtime can't slip
+ * past.
+ */
+
+// ── Shared scaffolding ─────────────────────────────────────────────────
+
+export type ToolHandlerContext = {
+ /** Reserved for future per-agent bearer scoping. Unused today. */
+ agentId?: string;
+};
+
+export type ToolResult =
+ | { ok: true; content: { type: "text"; text: string }[] }
+ | { ok: false; error: string };
+
+export type ToolDefinition = {
+ name: string;
+ description: string;
+ inputSchema: z.ZodObject<z.ZodRawShape>;
+ handler: (input: unknown, ctx: ToolHandlerContext) => Promise<ToolResult>;
+};
+
+function invalid(err: z.ZodError): ToolResult {
+ return {
+ ok: false,
+ error: `Invalid arguments: ${err.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`,
+ };
+}
+
+function txt(text: string): ToolResult {
+ return { ok: true, content: [{ type: "text", text }] };
+}
+
+// ── Tool: submit_task_status ───────────────────────────────────────────
+
+const submitTaskStatusInput = z.object({
+ project_slug: z
+ .string()
+ .min(1)
+ .describe(
+ "The project this task belongs to. From your IDENTITY.md prompt header / kickoff message.",
+ ),
+ agent_id: z
+ .string()
+ .min(1)
+ .describe(
+ "Your agent_id (e.g. `superpublic-google-ads`). From IDENTITY.md. Used to enforce 'only the assignee can update'.",
+ ),
+ task_id: z
+ .string()
+ .min(1)
+ .describe("UUID or display_id of the task you were assigned."),
+ status: z
+ .enum(TASK_STATUS_VALUES)
+ .describe(
+ "working = still progressing, done = task complete, blocked = waiting on user/CMO/approval, failed = couldn't complete.",
+ ),
+ summary: z
+ .string()
+ .optional()
+ .describe(
+ "One-paragraph progress note. Required when status is 'done' or 'failed'.",
+ ),
+});
+
+async function handleSubmitTaskStatus(input: unknown): Promise<ToolResult> {
+ const parsed = submitTaskStatusInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, task_id, status, summary } = parsed.data;
+ const r = handleTaskStatus(
+ { task_id, status, summary },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(`task ${r.data.task_id} updated to ${r.data.status}.`);
+}
+
+// ── Tool: create_task ──────────────────────────────────────────────────
+
+const createTaskInput = z.object({
+ project_slug: z
+ .string()
+ .min(1)
+ .describe("The project you are operating in. From your IDENTITY.md."),
+ assigner_agent_id: z
+ .string()
+ .min(1)
+ .describe(
+ "Your own agent_id — the one creating the task (e.g. `demo-cmo`). From IDENTITY.md.",
+ ),
+ assignee: z
+ .string()
+ .min(1)
+ .describe(
+ "Template key of the assignee (e.g. `google_ads`, `seo`). Must be a specialist provisioned in this project; CMO can't assign to itself.",
+ ),
+ title: z
+ .string()
+ .min(1)
+ .describe("Short label shown on task cards."),
+ brief: z
+ .string()
+ .min(1)
+ .describe(
+ "Full request body. PRD-style description with context, target outcome, constraints.",
+ ),
+ success_criteria: z
+ .string()
+ .optional()
+ .describe("Measurable definition of done."),
+});
+
+async function handleCreateTaskTool(input: unknown): Promise<ToolResult> {
+ const parsed = createTaskInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, assigner_agent_id, assignee, title, brief, success_criteria } = parsed.data;
+ const r = await handleCreateTask(
+ { assignee, title, brief, success_criteria },
+ { project_slug, agent_id: assigner_agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `task ${r.data.display_id} ("${r.data.title}") created for ${r.data.agent_id}. Status: ${r.data.status}.`,
+ );
+}
+
+// ── Tool: request_approval ─────────────────────────────────────────────
+
+const requestApprovalInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id."),
+ task_id: z
+ .string()
+ .optional()
+ .describe(
+ "Task this approval is gating, if any. Setting this parks the task in `blocked` until resolved.",
+ ),
+ action_summary: z
+ .string()
+ .min(1)
+ .describe("One-line description of what you want to do."),
+ action_type: z
+ .enum(APPROVAL_ACTION_TYPE_VALUES)
+ .describe(
+ "Category of the action. Used by auto-approval policies and to label the inbox card.",
+ ),
+ cost_estimate_usd: z
+ .number()
+ .optional()
+ .describe(
+ "Estimated monthly cost in USD. Required for spend / bid_change / new_channel.",
+ ),
+ reasoning: z
+ .string()
+ .optional()
+ .describe(
+ "Why you want to do this. Shown in the approval card; the more concrete the better.",
+ ),
+});
+
+async function handleRequestApprovalTool(input: unknown): Promise<ToolResult> {
+ const parsed = requestApprovalInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, task_id, action_summary, action_type, cost_estimate_usd, reasoning } = parsed.data;
+ const r = await handleRequestApproval(
+ { task_id, action_summary, action_type, cost_estimate_usd, reasoning },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ const suffix = r.data.auto_resolved
+ ? ` (auto-${r.data.status} by policy)`
+ : "";
+ return txt(
+ `approval ${r.data.approval_id} created${suffix}. status=${r.data.status}.`,
+ );
+}
+
+// ── Tool: add_task_comment ─────────────────────────────────────────────
+
+const addTaskCommentInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id."),
+ task_id: z.string().min(1).describe("Task you're commenting on."),
+ body: z.string().min(1).describe("Comment text. Visible in /activity."),
+});
+
+async function handleAddTaskCommentTool(input: unknown): Promise<ToolResult> {
+ const parsed = addTaskCommentInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, task_id, body } = parsed.data;
+ const r = handleAddTaskComment(
+ { task_id, body },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(`comment added to task ${r.data.task_id}.`);
+}
+
+// ── Tool: ask_user_question ────────────────────────────────────────────
+
+const askUserInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id."),
+ question: z.string().min(1).describe("The question to surface to the user."),
+ task_id: z
+ .string()
+ .optional()
+ .describe("Optional — anchor the question to a task."),
+ options: z
+ .string()
+ .optional()
+ .describe("Optional comma-separated multiple-choice hints (rendered as buttons)."),
+});
+
+async function handleAskUserTool(input: unknown): Promise<ToolResult> {
+ const parsed = askUserInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, question, task_id, options } = parsed.data;
+ const r = handleAskUser(
+ { question, task_id, options },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `question recorded${r.data.task_id ? ` on task ${r.data.task_id}` : ""}.`,
+ );
+}
+
+// ── Tool: get_task ─────────────────────────────────────────────────────
+
+const getTaskInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ task_id: z.string().min(1).describe("UUID or display_id."),
+});
+
+async function handleGetTaskTool(input: unknown): Promise<ToolResult> {
+ const parsed = getTaskInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleGetTask(
+ { task_id: parsed.data.task_id },
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify(r.data));
+}
+
+// ── Tool: list_my_tasks ────────────────────────────────────────────────
+
+const TASK_STATUS_FILTER_VALUES = [
+ "proposed",
+ "approved",
+ "running",
+ "blocked",
+ "succeeded",
+ "failed",
+ "cancelled",
+ "in_flight",
+ "all",
+] as const;
+
+const listMyTasksInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id."),
+ status: z
+ .enum(TASK_STATUS_FILTER_VALUES)
+ .optional()
+ .describe(
+ "Filter by status. 'in_flight' (default) = proposed|approved|running|blocked; 'all' = no filter.",
+ ),
+});
+
+async function handleListMyTasksTool(input: unknown): Promise<ToolResult> {
+ const parsed = listMyTasksInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, status } = parsed.data;
+ const filter = status as
+ | TaskStatus
+ | "in_flight"
+ | "all"
+ | undefined;
+ const r = handleListMyTasks(
+ { status: filter },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ tasks: r.data, count: r.data.length }));
+}
+
+// ── Tool: list_tasks (project-wide) ────────────────────────────────────
+
+const listTasksInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ status: z
+ .enum([
+ "proposed",
+ "approved",
+ "running",
+ "blocked",
+ "succeeded",
+ "failed",
+ "cancelled",
+ ])
+ .optional()
+ .describe("Optional status filter."),
+});
+
+async function handleListTasksTool(input: unknown): Promise<ToolResult> {
+ const parsed = listTasksInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleListTasks(
+ { status: parsed.data.status as TaskStatus | undefined },
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ tasks: r.data, count: r.data.length }));
+}
+
+// ── Tool: update_task ──────────────────────────────────────────────────
+
+const updateTaskInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id."),
+ task_id: z.string().min(1).describe("UUID or display_id of the task to update."),
+ title: z.string().optional().describe("New title."),
+ brief: z.string().optional().describe("New brief / description."),
+ success_criteria: z.string().optional().describe("New success criteria."),
+});
+
+async function handleUpdateTaskTool(input: unknown): Promise<ToolResult> {
+ const parsed = updateTaskInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, task_id, title, brief, success_criteria } = parsed.data;
+ const r = handleUpdateTask(
+ { task_id, title, brief, success_criteria },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(`task ${r.data.display_id} updated.`);
+}
+
+// ── Tool: cancel_task ──────────────────────────────────────────────────
+
+const cancelTaskInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id."),
+ task_id: z.string().min(1).describe("UUID or display_id of the task to cancel."),
+ reason: z
+ .string()
+ .optional()
+ .describe("Why you're cancelling. Stored on the task's error_message."),
+});
+
+async function handleCancelTaskTool(input: unknown): Promise<ToolResult> {
+ const parsed = cancelTaskInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, task_id, reason } = parsed.data;
+ const r = handleCancelTask(
+ { task_id, reason },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(`task ${r.data.display_id} cancelled.`);
+}
+
+// ── Tool: get_project ──────────────────────────────────────────────────
+
+const getProjectInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+});
+
+async function handleGetProjectTool(input: unknown): Promise<ToolResult> {
+ const parsed = getProjectInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleGetProject(
+ {},
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify(r.data));
+}
+
+// ── Tool: list_project_agents ──────────────────────────────────────────
+
+const listProjectAgentsInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+});
+
+async function handleListProjectAgentsTool(input: unknown): Promise<ToolResult> {
+ const parsed = listProjectAgentsInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = await handleListProjectAgents(
+ {},
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ agents: r.data, count: r.data.length }));
+}
+
+// ── Tool: list_task_comments ───────────────────────────────────────────
+
+const listTaskCommentsInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ task_id: z.string().min(1).describe("Task whose comment thread you want."),
+ limit: z.number().optional().describe("Max comments to return (default 50)."),
+});
+
+async function handleListTaskCommentsTool(input: unknown): Promise<ToolResult> {
+ const parsed = listTaskCommentsInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleListTaskComments(
+ { task_id: parsed.data.task_id, limit: parsed.data.limit },
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ comments: r.data, count: r.data.length }));
+}
+
+// ── Tool: get_approval ─────────────────────────────────────────────────
+
+const getApprovalInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ approval_id: z.string().min(1).describe("Approval UUID."),
+});
+
+async function handleGetApprovalTool(input: unknown): Promise<ToolResult> {
+ const parsed = getApprovalInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleGetApproval(
+ { approval_id: parsed.data.approval_id },
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify(r.data));
+}
+
+// ── Tool: list_my_approvals ────────────────────────────────────────────
+
+const listMyApprovalsInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id."),
+});
+
+async function handleListMyApprovalsTool(input: unknown): Promise<ToolResult> {
+ const parsed = listMyApprovalsInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleListMyApprovals(
+ {},
+ { project_slug: parsed.data.project_slug, agent_id: parsed.data.agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ approvals: r.data, count: r.data.length }));
+}
+
+// ── Tool: list_pending_approvals ───────────────────────────────────────
+
+const listPendingApprovalsInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+});
+
+async function handleListPendingApprovalsTool(input: unknown): Promise<ToolResult> {
+ const parsed = listPendingApprovalsInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleListPendingApprovals(
+ {},
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ approvals: r.data, count: r.data.length }));
+}
+
+// ── Tool: list_approvals_for_task ──────────────────────────────────────
+
+const listApprovalsForTaskInput = z.object({
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ task_id: z.string().min(1).describe("Task whose approvals you want."),
+});
+
+async function handleListApprovalsForTaskTool(
+ input: unknown,
+): Promise<ToolResult> {
+ const parsed = listApprovalsForTaskInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleListApprovalsForTask(
+ { task_id: parsed.data.task_id },
+ { project_slug: parsed.data.project_slug, agent_id: "" },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ approvals: r.data, count: r.data.length }));
+}
+
+// ── Tool: list_task_statuses (enum discovery) ──────────────────────────
+// No project_slug — this is a static enum, not project-scoped state. Agents
+// query it once to learn the workflow.
+
+const listTaskStatusesInput = z.object({});
+
+async function handleListTaskStatusesTool(input: unknown): Promise<ToolResult> {
+ const parsed = listTaskStatusesInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleListTaskStatuses();
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ statuses: r.data }));
+}
+
+// ── Tool: list_approval_action_types ───────────────────────────────────
+
+const listApprovalActionTypesInput = z.object({});
+
+async function handleListApprovalActionTypesTool(
+ input: unknown,
+): Promise<ToolResult> {
+ const parsed = listApprovalActionTypesInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const r = handleListApprovalActionTypes();
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify({ action_types: r.data }));
+}
+
+// ── Registry ───────────────────────────────────────────────────────────
+
+export const TOOLS: ToolDefinition[] = [
+ {
+ name: "submit_task_status",
+ description:
+ "Report progress on the task you were assigned. Call at the END of any turn that finishes work, blocks, or fails. Replaces the legacy `<task_status>` text block — same semantics, strict enum.",
+ inputSchema: submitTaskStatusInput,
+ handler: handleSubmitTaskStatus,
+ },
+ {
+ name: "create_task",
+ description:
+ "Spawn a new task and assign it to a specialist. CMO uses this to delegate; specialists can use it to chain follow-up work. The task auto-starts (proposed → running) so the assignee picks it up immediately.",
+ inputSchema: createTaskInput,
+ handler: handleCreateTaskTool,
+ },
+ {
+ name: "request_approval",
+ description:
+ "Ask the user (or an auto-approve policy) to sign off on a governed action before you execute it. Required before any spend change, content publish, new channel, bid change, or audience change. Setting `task_id` parks the task in `blocked` until the user (or policy) resolves it; on approve the agent receives a wake-up message to proceed.",
+ inputSchema: requestApprovalInput,
+ handler: handleRequestApprovalTool,
+ },
+ {
+ name: "add_task_comment",
+ description:
+ "Leave a note on a task — for the CMO to see, or to record your reasoning. Visible in /activity. Use this for cross-agent communication that doesn't need user attention.",
+ inputSchema: addTaskCommentInput,
+ handler: handleAddTaskCommentTool,
+ },
+ {
+ name: "ask_user_question",
+ description:
+ "Surface a question to the user (not the CMO). Use sparingly — only when the answer can't come from the CMO, your tools, or the brief. Provide `options` for multiple-choice.",
+ inputSchema: askUserInput,
+ handler: handleAskUserTool,
+ },
+ {
+ name: "get_task",
+ description:
+ "Fetch a task by id (UUID or display_id). Use this to re-anchor when your context window rotates and you've lost the brief, or to check the latest state of a task you previously touched.",
+ inputSchema: getTaskInput,
+ handler: handleGetTaskTool,
+ },
+ {
+ name: "list_my_tasks",
+ description:
+ "List tasks assigned to YOU (filtered to your project). Default returns in-flight tasks (proposed | approved | running | blocked). Use this to see what's on your plate.",
+ inputSchema: listMyTasksInput,
+ handler: handleListMyTasksTool,
+ },
+ {
+ name: "list_tasks",
+ description:
+ "List ALL tasks in the project — across every agent. Optional status filter. Use this to understand cross-agent activity or, as the CMO, to plan.",
+ inputSchema: listTasksInput,
+ handler: handleListTasksTool,
+ },
+ {
+ name: "update_task",
+ description:
+ "Edit a task's title, brief, or success criteria. Used by the CMO to clarify a delegation after the fact. Doesn't change task status — use submit_task_status / cancel_task for that.",
+ inputSchema: updateTaskInput,
+ handler: handleUpdateTaskTool,
+ },
+ {
+ name: "cancel_task",
+ description:
+ "Mark a task `cancelled`. Use when the work is no longer relevant or has been superseded. Optional `reason` is stored on error_message.",
+ inputSchema: cancelTaskInput,
+ handler: handleCancelTaskTool,
+ },
+ {
+ name: "get_project",
+ description:
+ "Fetch the current project's metadata (display name, Google Ads account id, etc.). Useful when you need project-level context for an answer.",
+ inputSchema: getProjectInput,
+ handler: handleGetProjectTool,
+ },
+ {
+ name: "list_project_agents",
+ description:
+ "List the agents available in this project (CMO + specialists + any custom clones). Use this to discover valid `assignee` template_keys for create_task.",
+ inputSchema: listProjectAgentsInput,
+ handler: handleListProjectAgentsTool,
+ },
+ {
+ name: "list_task_comments",
+ description:
+ "Fetch the comment thread on a task (added via add_task_comment / <add_comment>). Use to catch up on cross-agent conversation when you re-engage with a task.",
+ inputSchema: listTaskCommentsInput,
+ handler: handleListTaskCommentsTool,
+ },
+ {
+ name: "get_approval",
+ description:
+ "Fetch an approval row by id. Use when an earlier wake-up message gave you an approval_id and you need the latest state (decision_note, decided_by, etc.).",
+ inputSchema: getApprovalInput,
+ handler: handleGetApprovalTool,
+ },
+ {
+ name: "list_my_approvals",
+ description:
+ "List approvals YOU requested (pending and revision_requested). Use to check whether any of your prior asks are still parked.",
+ inputSchema: listMyApprovalsInput,
+ handler: handleListMyApprovalsTool,
+ },
+ {
+ name: "list_pending_approvals",
+ description:
+ "List every actionable approval in the project (pending + revision_requested), across all agents. Useful for the CMO to triage.",
+ inputSchema: listPendingApprovalsInput,
+ handler: handleListPendingApprovalsTool,
+ },
+ {
+ name: "list_approvals_for_task",
+ description:
+ "List every approval ever requested on a specific task — history of governed actions for that task.",
+ inputSchema: listApprovalsForTaskInput,
+ handler: handleListApprovalsForTaskTool,
+ },
+ {
+ name: "list_task_statuses",
+ description:
+ "Discover the task workflow state machine: every status value, what it means, whether it's terminal, and what transitions are allowed FROM it. Call once when you're unsure which status to use.",
+ inputSchema: listTaskStatusesInput,
+ handler: handleListTaskStatusesTool,
+ },
+ {
+ name: "list_approval_action_types",
+ description:
+ "Discover valid `action_type` values for request_approval, with descriptions and which require a cost estimate. Call once if you're unsure which type fits your action.",
+ inputSchema: listApprovalActionTypesInput,
+ handler: handleListApprovalActionTypesTool,
+ },
+];
+
+export function describeTool(tool: ToolDefinition): {
+ name: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+} {
+ return {
+ name: tool.name,
+ description: tool.description,
+ inputSchema: zodObjectToJsonSchema(tool.inputSchema),
+ };
+}
+
+export function findTool(name: string): ToolDefinition | undefined {
+ return TOOLS.find((t) => t.name === name);
+}
+
+/**
+ * Minimal zod → JSON-Schema converter for the shapes we actually use:
+ * z.object with z.string / z.number / z.string().optional / z.enum / .describe.
+ * Anything richer falls back to {type:"string"} — the handler's safeParse
+ * catches real violations either way.
+ */
+function zodObjectToJsonSchema(
+ schema: z.ZodObject<z.ZodRawShape>,
+): Record<string, unknown> {
+ const shape = schema.shape;
+ const properties: Record<string, unknown> = {};
+ const required: string[] = [];
+ for (const [key, value] of Object.entries(shape)) {
+ const node = leafSchema(value as z.ZodTypeAny);
+ properties[key] = node.schema;
+ if (!node.optional) required.push(key);
+ }
+ return {
+ type: "object",
+ properties,
+ required,
+ additionalProperties: false,
+ };
+}
+
+function leafSchema(
+ schema: z.ZodTypeAny,
+): { schema: Record<string, unknown>; optional: boolean } {
+ let optional = false;
+ let inner: z.ZodTypeAny = schema;
+ if (inner instanceof z.ZodOptional) {
+ optional = true;
+ inner = inner._def.innerType as z.ZodTypeAny;
+ }
+ const description = (schema as { description?: string }).description;
+ const out: Record<string, unknown> = {};
+ if (inner instanceof z.ZodString) {
+ out.type = "string";
+ } else if (inner instanceof z.ZodEnum) {
+ out.type = "string";
+ out.enum = (inner._def as { values: string[] }).values;
+ } else if (inner instanceof z.ZodNumber) {
+ out.type = "number";
+ } else if (inner instanceof z.ZodBoolean) {
+ out.type = "boolean";
+ } else {
+ out.type = "string";
+ }
+ if (description) out.description = description;
+ return { schema: out, optional };
+}
diff --git a/src/server/onboarding/cmo-task-brief.ts b/src/server/onboarding/cmo-task-brief.ts
index db03b876..ce6db206 100644
--- a/src/server/onboarding/cmo-task-brief.ts
+++ b/src/server/onboarding/cmo-task-brief.ts
@@ -1,9 +1,10 @@
/**
* Build the brief for the CMO's first task — the audit that used to be its
* own special-purpose code path in src/server/onboarding/audit.ts. Now the
- * audit IS a task: the CMO does the GAQL probes itself using the Google
- * Ads MCP, writes findings inline, and delegates ongoing work via
- * <create_task> blocks the same way it would for any other planning turn.
+ * audit IS a task: the CMO does the GAQL probes itself via the Google Ads
+ * MCP, writes findings inline, and delegates ongoing work via the
+ * notfair-orchestration MCP tools (the same surface the CMO uses for every
+ * other planning turn — see agent-templates.ts for the full teaching).
*
* Keeping this server-side so the wording stays in lockstep with the CMO
* system prompt; templated rather than free-form so each new project
@@ -14,9 +15,7 @@ export function buildOnboardingBrief(args: {
project_display_name: string;
google_ads_account_id: string | null;
}): { title: string; brief: string; success_criteria: string } {
- const account =
- args.google_ads_account_id ??
- "(none picked — ask the user via <ask_user> before running probes)";
+ const account = args.google_ads_account_id ?? "(none picked — ask the user)";
const title = "Audit the account and propose a starter playbook";
@@ -26,7 +25,7 @@ export function buildOnboardingBrief(args: {
"",
"This is your first turn as CMO for this project. Audit the connected",
"Google Ads account, present findings, then delegate ongoing work to",
- "the google-ads specialist via <create_task> blocks.",
+ "the google-ads specialist.",
"",
"## 1. Probe the account",
"",
@@ -62,21 +61,19 @@ export function buildOnboardingBrief(args: {
"",
"## 4. Delegate the ongoing work",
"",
- "For each Next Step that's actionable + repeatable, emit a <create_task>",
- "block assigned to google_ads. Include the cadence in the brief itself",
- "(\"daily 9am Pacific anomaly check on enabled campaigns\", \"weekly",
- "Monday search-term review\", etc.) — the specialist will schedule it.",
+ "For each Next Step that's actionable + repeatable, delegate it to the",
+ "google_ads specialist. Include the cadence in the brief itself (\"daily",
+ "9am Pacific anomaly check on enabled campaigns\", \"weekly Monday",
+ "search-term review\", etc.) — the specialist will schedule its own cron.",
"",
- "Tight one-line tail after the create_task blocks: \"Handed these to",
- "your Google Ads specialist — open the agent's Tasks tab to follow",
- 'along."',
+ "Tight one-line tail after delegating: \"Handed these to your Google Ads",
+ 'specialist — open the agent\'s Tasks tab to follow along."',
].join("\n");
const success_criteria = [
- "Findings reported as inline markdown, one or more <create_task> blocks",
- "emitted for ongoing work (skip when archetype = empty + no creative",
- "approach is possible without account spend), <task_status>status: done</task_status>",
- "at the end.",
+ "Findings reported as inline markdown; ongoing work delegated to",
+ "google_ads (skip delegation when archetype = empty); this audit task",
+ "marked done.",
].join(" ");
return { title, brief, success_criteria };
diff --git a/src/server/orchestration/approval-wakeup.test.ts b/src/server/orchestration/approval-wakeup.test.ts
new file mode 100644
index 00000000..2ca5add6
--- /dev/null
+++ b/src/server/orchestration/approval-wakeup.test.ts
@@ -0,0 +1,188 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// ── Mocks ──────────────────────────────────────────────────────────
+// approval-wakeup pulls in the gateway, sessions, tasks DB, and approval
+// comments. We don't want any real I/O here — every dependency is stubbed.
+
+const getTaskMock = vi.fn();
+const unblockTaskMock = vi.fn();
+const setTaskThreadIfMissingMock = vi.fn();
+vi.mock("@/server/db/tasks", () => ({
+ getTask: (...a: unknown[]) => getTaskMock(...a),
+ unblockTask: (...a: unknown[]) => unblockTaskMock(...a),
+ setTaskThreadIfMissing: (...a: unknown[]) => setTaskThreadIfMissingMock(...a),
+}));
+
+const appendCommentMock = vi.fn();
+const listCommentsMock = vi.fn();
+vi.mock("@/server/db/approvals", () => ({
+ appendComment: (...a: unknown[]) => appendCommentMock(...a),
+ listComments: (...a: unknown[]) => listCommentsMock(...a),
+}));
+
+const buildPendingSessionKeyMock = vi.fn(
+ (agent: string, session: string) => `agent:${agent}:${session}`,
+);
+const findSessionBySessionIdMock = vi.fn();
+vi.mock("@/server/openclaw/sessions", () => ({
+ buildPendingSessionKey: (...a: unknown[]) => buildPendingSessionKeyMock(...(a as [string, string])),
+ findSessionBySessionId: (...a: unknown[]) => findSessionBySessionIdMock(...a),
+}));
+
+// streamChatViaGateway is an async iterable. The stub yields a single delta
+// event so the wakeup body has something to drain.
+const streamMock = vi.fn();
+vi.mock("@/server/openclaw/gateway-client", () => ({
+ streamChatViaGateway: (...a: unknown[]) => streamMock(...a),
+}));
+
+vi.mock("./task-kickoff", async () => {
+ const actual =
+ await vi.importActual<typeof import("./task-kickoff")>("./task-kickoff");
+ return {
+ ...actual,
+ generateTaskThreadId: () => "minted-thread-id",
+ };
+});
+
+import { wakeTaskOnApprovalResolution } from "./approval-wakeup";
+
+function makeApproval(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "ap-deadbeef0123",
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ task_id: "task-1",
+ action_summary: "Raise CPC bid",
+ action_type: "bid_change" as const,
+ cost_estimate_usd: 0,
+ reasoning: null,
+ payload_json: "{}",
+ status: "approved" as const,
+ decision_note: "ok",
+ decided_by_kind: "user" as const,
+ decided_by_id: null,
+ created_at: "2026-05-01T00:00:00Z",
+ resolved_at: "2026-05-02T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function makeTask(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "task-1",
+ display_id: "demo-1",
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ title: "t",
+ brief: "b",
+ success_criteria: null,
+ deadline_iso: null,
+ status: "blocked" as const,
+ result_json: null,
+ error_message: null,
+ thread_id: "thread-abc",
+ assigner_agent_id: null,
+ created_at: "2026-05-01T00:00:00Z",
+ updated_at: "2026-05-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+async function* yieldDelta(text: string) {
+ yield { kind: "delta", text } as const;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ streamMock.mockImplementation(() => yieldDelta("agent reply"));
+});
+
+describe("wakeTaskOnApprovalResolution", () => {
+ it("is a no-op when the approval has no task_id", async () => {
+ await wakeTaskOnApprovalResolution(makeApproval({ task_id: null }));
+ expect(getTaskMock).not.toHaveBeenCalled();
+ expect(streamMock).not.toHaveBeenCalled();
+ });
+
+ it("is a no-op when the task is terminal (succeeded/failed/cancelled)", async () => {
+ getTaskMock.mockReturnValue(makeTask({ status: "succeeded" }));
+ await wakeTaskOnApprovalResolution(makeApproval());
+ expect(streamMock).not.toHaveBeenCalled();
+ expect(unblockTaskMock).not.toHaveBeenCalled();
+ });
+
+ it("unblocks the task on approve and streams a green-light message", async () => {
+ getTaskMock.mockReturnValue(makeTask());
+ await wakeTaskOnApprovalResolution(makeApproval({ status: "approved" }));
+ expect(unblockTaskMock).toHaveBeenCalledWith("task-1");
+ expect(streamMock).toHaveBeenCalledTimes(1);
+ const arg = streamMock.mock.calls[0]![0]!;
+ expect(arg.message).toMatch(/APPROVED/);
+ });
+
+ it("unblocks on reject too (agent decides next step)", async () => {
+ getTaskMock.mockReturnValue(makeTask());
+ await wakeTaskOnApprovalResolution(makeApproval({ status: "rejected" }));
+ expect(unblockTaskMock).toHaveBeenCalledWith("task-1");
+ const arg = streamMock.mock.calls[0]![0]!;
+ expect(arg.message).toMatch(/REJECTED/);
+ });
+
+ it("does NOT unblock on revision_requested (task stays blocked)", async () => {
+ getTaskMock.mockReturnValue(makeTask());
+ await wakeTaskOnApprovalResolution(
+ makeApproval({ status: "revision_requested", decision_note: "narrow scope" }),
+ );
+ expect(unblockTaskMock).not.toHaveBeenCalled();
+ const arg = streamMock.mock.calls[0]![0]!;
+ expect(arg.message).toMatch(/needs revision/);
+ expect(arg.message).toMatch(/narrow scope/);
+ });
+
+ it("appends a system comment recording the delivery", async () => {
+ getTaskMock.mockReturnValue(makeTask());
+ await wakeTaskOnApprovalResolution(makeApproval({ status: "approved" }));
+ expect(appendCommentMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ approval_id: "ap-deadbeef0123",
+ author_kind: "system",
+ body: expect.stringContaining("Delivered to demo-google-ads"),
+ }),
+ );
+ });
+
+ it("mints a thread when the task has none yet", async () => {
+ getTaskMock.mockReturnValue(makeTask({ thread_id: null }));
+ setTaskThreadIfMissingMock.mockReturnValue({
+ ...makeTask(),
+ thread_id: "minted-thread-id",
+ });
+ await wakeTaskOnApprovalResolution(makeApproval());
+ expect(setTaskThreadIfMissingMock).toHaveBeenCalledWith(
+ "task-1",
+ "minted-thread-id",
+ );
+ const arg = streamMock.mock.calls[0]![0]!;
+ expect(arg.sessionId).toBe("minted-thread-id");
+ });
+
+ it("drains the gateway stream so the agent's MCP tool calls during the turn can fire", async () => {
+ getTaskMock.mockReturnValue(makeTask());
+ streamMock.mockImplementation(() => yieldDelta("ack — proceeding"));
+ await wakeTaskOnApprovalResolution(makeApproval({ status: "approved" }));
+ expect(streamMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("swallows gateway stream errors without throwing", async () => {
+ getTaskMock.mockReturnValue(makeTask());
+ streamMock.mockImplementation(async function* () {
+ yield { kind: "error", message: "boom" } as const;
+ });
+ await expect(
+ wakeTaskOnApprovalResolution(makeApproval({ status: "approved" })),
+ ).resolves.toBeUndefined();
+ // Comment about delivery is still recorded so the inbox thread has a trail.
+ expect(appendCommentMock).toHaveBeenCalled();
+ });
+});
diff --git a/src/server/orchestration/approval-wakeup.ts b/src/server/orchestration/approval-wakeup.ts
new file mode 100644
index 00000000..2c885f91
--- /dev/null
+++ b/src/server/orchestration/approval-wakeup.ts
@@ -0,0 +1,137 @@
+import {
+ buildPendingSessionKey,
+ findSessionBySessionId,
+} from "@/server/openclaw/sessions";
+import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
+import { appendComment, listComments } from "@/server/db/approvals";
+import { getTask, setTaskThreadIfMissing, unblockTask } from "@/server/db/tasks";
+import type { Approval } from "@/types";
+
+import { generateTaskThreadId } from "./task-kickoff";
+
+/**
+ * After an approval is resolved (approve / reject / revision_requested),
+ * deliver a system message into the task thread so the agent can pick up
+ * the decision on its next turn. Mirrors paperclip's heartbeat.wakeup()
+ * pattern: the agent doesn't poll — we push a turn with the decision in
+ * its context, and side effects (next submit_task_status, follow-up
+ * request_approval, etc.) happen via MCP tool calls during the turn.
+ *
+ * - approved/rejected → task unblocks, agent receives a green/red light.
+ * - revision_requested → task stays `blocked`, agent receives the revision
+ * note and is expected to call request_approval again with the revised
+ * plan.
+ *
+ * No-op when the approval isn't linked to a task. Free-standing
+ * approvals (without task_id) surface only in the inbox.
+ */
+export async function wakeTaskOnApprovalResolution(approval: Approval): Promise<void> {
+ if (!approval.task_id) return;
+ const task = getTask(approval.task_id);
+ if (!task) return;
+ // Don't restart agents on terminal tasks — the user may have cancelled
+ // while the approval was outstanding.
+ if (
+ task.status === "succeeded" ||
+ task.status === "failed" ||
+ task.status === "cancelled"
+ ) {
+ return;
+ }
+
+ // Approved/rejected both unblock the task. Revision keeps it blocked so
+ // the UI continues to show "Waiting on approval" while the agent reworks.
+ if (approval.status === "approved" || approval.status === "rejected") {
+ unblockTask(task.id);
+ }
+
+ // Lazy thread mint — usually already set by an earlier kickoff, but a
+ // free-floating approval (no prior message yet) won't have one.
+ let threadId = task.thread_id;
+ if (!threadId) {
+ const minted = setTaskThreadIfMissing(task.id, generateTaskThreadId());
+ if (minted?.thread_id) threadId = minted.thread_id;
+ }
+ if (!threadId) {
+ console.error(`[approval-wakeup] no thread_id for task ${task.id}`);
+ return;
+ }
+
+ const known = findSessionBySessionId(task.agent_id, threadId);
+ const sessionKey =
+ known?.sessionKey ?? buildPendingSessionKey(task.agent_id, threadId);
+
+ const message = buildWakeupMessage(approval);
+ // Persist the wake-up payload as a system comment for the inbox thread.
+ appendComment({
+ approval_id: approval.id,
+ author_kind: "system",
+ body: `Delivered to ${task.agent_id} on thread ${threadId}.`,
+ });
+
+ // Drain the gateway stream so the agent's turn fully runs. Side effects
+ // (submit_task_status etc.) happen via MCP tool calls during the turn —
+ // we no longer regex-scan the reply.
+ try {
+ for await (const evt of streamChatViaGateway({
+ sessionKey,
+ sessionId: threadId,
+ message,
+ })) {
+ if (evt.kind === "error") throw new Error(evt.message);
+ }
+ } catch (err) {
+ console.error(`[approval-wakeup] gateway stream failed for task ${task.id}:`, err);
+ }
+}
+
+function buildWakeupMessage(approval: Approval): string {
+ const decidedBy =
+ approval.decided_by_kind === "user"
+ ? "the user"
+ : approval.decided_by_kind === "agent"
+ ? `another agent (${approval.decided_by_id ?? "unknown"})`
+ : approval.decided_by_kind === "policy"
+ ? "an auto-approval policy"
+ : "an unknown party";
+
+ const note = approval.decision_note?.trim();
+
+ switch (approval.status) {
+ case "approved":
+ return [
+ `[SYSTEM] Approval #${approval.id.slice(0, 8)} has been APPROVED by ${decidedBy}.`,
+ `Action: ${approval.action_summary}`,
+ note ? `Note: ${note}` : null,
+ "",
+ "You may now proceed with the action. When you're finished, call the `submit_task_status` MCP tool with status `done` (or `working` if you're posting an interim update). Do NOT invent new status values.",
+ ]
+ .filter(Boolean)
+ .join("\n");
+ case "rejected":
+ return [
+ `[SYSTEM] Approval #${approval.id.slice(0, 8)} has been REJECTED by ${decidedBy}.`,
+ `Action: ${approval.action_summary}`,
+ note ? `Reason: ${note}` : null,
+ "",
+ "Do NOT perform the rejected action. Decide whether to propose an alternative or stop here. Either way, call the `submit_task_status` MCP tool — use status `done` if you have nothing further to do, or `working` if you're proposing an alternative. The valid statuses are exactly: working, done, blocked, failed.",
+ ]
+ .filter(Boolean)
+ .join("\n");
+ case "revision_requested":
+ return [
+ `[SYSTEM] Approval #${approval.id.slice(0, 8)} needs revision per ${decidedBy}.`,
+ `Action: ${approval.action_summary}`,
+ note ? `Feedback: ${note}` : "Feedback: (no note left — re-read the request and propose a refined version)",
+ "",
+ "Re-evaluate the request given the feedback, then call the notfair-orchestration `request_approval` MCP tool again with the revised plan. Keep status `working` via `submit_task_status` in the meantime. Do NOT emit pseudo-XML blocks.",
+ ]
+ .filter(Boolean)
+ .join("\n");
+ default:
+ return `[SYSTEM] Approval #${approval.id.slice(0, 8)} resolved (${approval.status}). Continue.`;
+ }
+}
+
+/** Re-export for tests / future code that wants the inbox thread. */
+export { listComments };
diff --git a/src/server/orchestration/blocks.test.ts b/src/server/orchestration/blocks.test.ts
deleted file mode 100644
index fe15d5df..00000000
--- a/src/server/orchestration/blocks.test.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- parseCreateTaskBlocks,
- parseTaskStatusBlocks,
- stripOrchestrationBlocks,
-} from "./blocks";
-
-describe("parseCreateTaskBlocks", () => {
- it("parses a single well-formed block", () => {
- const text = `
-Here are the tasks I'm creating:
-
-<create_task>
-title: Install conversion tracking
-assignee: google_ads
-brief: Add the Google Ads conversion tag or import GA4 conversion events.
- Confirm the tag fires on the thank-you page; report the conversion type
- and value mapping.
-success_criteria: One test conversion fires + appears in Google Ads within 24h.
-</create_task>
-`;
- const blocks = parseCreateTaskBlocks(text);
- expect(blocks).toHaveLength(1);
- expect(blocks[0]).toEqual({
- title: "Install conversion tracking",
- assignee: "google_ads",
- brief:
- "Add the Google Ads conversion tag or import GA4 conversion events.\nConfirm the tag fires on the thank-you page; report the conversion type\nand value mapping.",
- success_criteria:
- "One test conversion fires + appears in Google Ads within 24h.",
- });
- });
-
- it("parses multiple blocks", () => {
- const text = `
-<create_task>
-title: A
-assignee: google_ads
-brief: Do A.
-</create_task>
-<create_task>
-title: B
-assignee: google_ads
-brief: Do B.
-</create_task>
-`;
- expect(parseCreateTaskBlocks(text)).toHaveLength(2);
- });
-
- it("skips blocks missing required fields", () => {
- const text = `
-<create_task>
-title: incomplete
-brief: no assignee
-</create_task>
-<create_task>
-title: good
-assignee: google_ads
-brief: ok
-</create_task>
-`;
- const blocks = parseCreateTaskBlocks(text);
- expect(blocks).toHaveLength(1);
- expect(blocks[0]?.title).toBe("good");
- });
-
- it("returns empty array when no blocks present", () => {
- expect(parseCreateTaskBlocks("hello world")).toEqual([]);
- });
-});
-
-describe("parseTaskStatusBlocks", () => {
- it("parses a done status block", () => {
- const text = `Working on it.
-
-<task_status>
-task_id: abc-123
-status: done
-summary: Conversion tag installed on /thanks; test conv fired at 14:02 PT.
-</task_status>`;
- const blocks = parseTaskStatusBlocks(text);
- expect(blocks).toEqual([
- {
- task_id: "abc-123",
- status: "done",
- summary: "Conversion tag installed on /thanks; test conv fired at 14:02 PT.",
- },
- ]);
- });
-
- it("rejects unknown status values", () => {
- const text = `<task_status>
-task_id: abc-123
-status: maybe
-</task_status>`;
- expect(parseTaskStatusBlocks(text)).toEqual([]);
- });
-
- it("rejects blocks without a task_id", () => {
- const text = `<task_status>
-status: done
-</task_status>`;
- expect(parseTaskStatusBlocks(text)).toEqual([]);
- });
-});
-
-describe("stripOrchestrationBlocks", () => {
- it("removes create_task blocks from the displayed text", () => {
- const text = `Greeting prose here.
-
-<create_task>
-title: A
-assignee: google_ads
-brief: x
-</create_task>
-
-More prose.`;
- const stripped = stripOrchestrationBlocks(text);
- expect(stripped).not.toContain("<create_task>");
- expect(stripped).toContain("Greeting prose here.");
- expect(stripped).toContain("More prose.");
- });
-
- it("removes task_status blocks", () => {
- const text = `Done.
-
-<task_status>
-task_id: abc
-status: done
-</task_status>`;
- expect(stripOrchestrationBlocks(text)).toBe("Done.");
- });
-
- it("collapses 3+ consecutive blank lines left behind by stripping", () => {
- const text = `Hi.
-
-
-
-<create_task>
-title: A
-assignee: x
-brief: y
-</create_task>
-
-
-
-Bye.`;
- const out = stripOrchestrationBlocks(text);
- // No more than one blank line between paragraphs.
- expect(/\n{3,}/.test(out)).toBe(false);
- });
-
- it("leaves prose unchanged when no blocks present", () => {
- expect(stripOrchestrationBlocks("just text")).toBe("just text");
- });
-});
diff --git a/src/server/orchestration/blocks.ts b/src/server/orchestration/blocks.ts
deleted file mode 100644
index cf2f8ff4..00000000
--- a/src/server/orchestration/blocks.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-/**
- * Structured-block protocol the agents emit in their replies. Server-side
- * parses them out of the assistant text after the chat stream completes;
- * client-side strips them from the rendered markdown so the user never sees
- * the raw <create_task>...</create_task> tags.
- *
- * Block types in V1 — mirror paperclip's MCP orchestrator tools (createIssue,
- * updateIssue, addComment, askUserQuestions, createApproval):
- * - <create_task> CMO spawns tasks for specialists. (paperclipCreateIssue)
- * - <task_status> Specialists update task state. (paperclipUpdateIssue)
- * - <add_comment> Cross-agent comms on an existing task. (paperclipAddComment)
- * - <ask_user> Agent blocked on user input — needs an answer. (paperclipAskUserQuestions)
- * - <request_approval> Agent needs a governed action approved. (paperclipCreateApproval)
- *
- * All blocks use the same key:value-per-line shape (mirrors <propose_cron>)
- * so the parser is one shared implementation.
- */
-
-export type CreateTaskBlock = {
- title: string;
- /** Template key of the assignee (e.g., "google_ads"). */
- assignee: string;
- brief: string;
- success_criteria?: string;
-};
-
-export type TaskStatusBlock = {
- /** Task ID — the specialist receives this in its kickoff context. */
- task_id: string;
- status: "working" | "done" | "blocked" | "failed";
- summary?: string;
-};
-
-export type AddCommentBlock = {
- task_id: string;
- body: string;
-};
-
-export type AskUserBlock = {
- /** Optional task scope. When set, the question is anchored to a task. */
- task_id?: string;
- question: string;
- /** Optional comma-separated multiple-choice hints to render as buttons. */
- options?: string;
-};
-
-export type RequestApprovalBlock = {
- task_id?: string;
- action_summary: string;
- action_type:
- | "spend"
- | "content_publishing"
- | "new_channel"
- | "bid_change"
- | "audience_change"
- | "other";
- cost_estimate_usd?: number;
- reasoning?: string;
-};
-
-const CREATE_TASK_RE = /<create_task>([\s\S]*?)<\/create_task>/gi;
-const TASK_STATUS_RE = /<task_status>([\s\S]*?)<\/task_status>/gi;
-const ADD_COMMENT_RE = /<add_comment>([\s\S]*?)<\/add_comment>/gi;
-const ASK_USER_RE = /<ask_user>([\s\S]*?)<\/ask_user>/gi;
-const REQUEST_APPROVAL_RE = /<request_approval>([\s\S]*?)<\/request_approval>/gi;
-
-/**
- * Strip every recognized orchestration block out of an assistant message so
- * the client renders clean prose. Used by the chat UI as a markdown
- * preprocessor.
- */
-export function stripOrchestrationBlocks(text: string): string {
- return text
- .replace(CREATE_TASK_RE, "")
- .replace(TASK_STATUS_RE, "")
- .replace(ADD_COMMENT_RE, "")
- .replace(ASK_USER_RE, "")
- .replace(REQUEST_APPROVAL_RE, "")
- .replace(/\n{3,}/g, "\n\n")
- .trim();
-}
-
-/**
- * Parse the body of one block into a {key: value} map. Lines are trimmed;
- * multi-line values are supported by indenting the continuation lines.
- * Keys are lowercased.
- */
-function parseBlockBody(body: string): Record<string, string> {
- const out: Record<string, string> = {};
- const lines = body.split(/\r?\n/);
- let currentKey: string | null = null;
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (!trimmed) {
- currentKey = null;
- continue;
- }
- // New key — "key: value" on one line (value can be empty for multi-line keys below).
- const m = trimmed.match(/^([a-z_][a-z0-9_]*)\s*:\s*(.*)$/i);
- if (m) {
- const key = m[1]!.toLowerCase();
- const value = m[2]!.trim();
- out[key] = value;
- currentKey = key;
- continue;
- }
- // Continuation line for the current key.
- if (currentKey) {
- out[currentKey] = `${out[currentKey] ?? ""}\n${trimmed}`.trim();
- }
- }
- return out;
-}
-
-export function parseCreateTaskBlocks(text: string): CreateTaskBlock[] {
- const out: CreateTaskBlock[] = [];
- for (const match of text.matchAll(CREATE_TASK_RE)) {
- const fields = parseBlockBody(match[1] ?? "");
- const title = fields.title?.trim();
- const assignee = fields.assignee?.trim();
- const brief = fields.brief?.trim();
- if (!title || !assignee || !brief) continue;
- const block: CreateTaskBlock = { title, assignee, brief };
- if (fields.success_criteria) {
- block.success_criteria = fields.success_criteria.trim();
- }
- out.push(block);
- }
- return out;
-}
-
-export function parseTaskStatusBlocks(text: string): TaskStatusBlock[] {
- const out: TaskStatusBlock[] = [];
- for (const match of text.matchAll(TASK_STATUS_RE)) {
- const fields = parseBlockBody(match[1] ?? "");
- const task_id = fields.task_id?.trim();
- const status = fields.status?.trim().toLowerCase();
- if (!task_id) continue;
- if (
- status !== "working" &&
- status !== "done" &&
- status !== "blocked" &&
- status !== "failed"
- ) {
- continue;
- }
- const block: TaskStatusBlock = { task_id, status };
- if (fields.summary) block.summary = fields.summary.trim();
- out.push(block);
- }
- return out;
-}
-
-export function parseAddCommentBlocks(text: string): AddCommentBlock[] {
- const out: AddCommentBlock[] = [];
- for (const match of text.matchAll(ADD_COMMENT_RE)) {
- const fields = parseBlockBody(match[1] ?? "");
- const task_id = fields.task_id?.trim();
- const body = fields.body?.trim();
- if (!task_id || !body) continue;
- out.push({ task_id, body });
- }
- return out;
-}
-
-export function parseAskUserBlocks(text: string): AskUserBlock[] {
- const out: AskUserBlock[] = [];
- for (const match of text.matchAll(ASK_USER_RE)) {
- const fields = parseBlockBody(match[1] ?? "");
- const question = fields.question?.trim();
- if (!question) continue;
- const block: AskUserBlock = { question };
- if (fields.task_id) block.task_id = fields.task_id.trim();
- if (fields.options) block.options = fields.options.trim();
- out.push(block);
- }
- return out;
-}
-
-export function parseRequestApprovalBlocks(text: string): RequestApprovalBlock[] {
- const out: RequestApprovalBlock[] = [];
- const ALLOWED_TYPES = new Set([
- "spend",
- "content_publishing",
- "new_channel",
- "bid_change",
- "audience_change",
- "other",
- ]);
- for (const match of text.matchAll(REQUEST_APPROVAL_RE)) {
- const fields = parseBlockBody(match[1] ?? "");
- const action_summary = fields.action_summary?.trim();
- const action_type = fields.action_type?.trim().toLowerCase();
- if (!action_summary || !action_type || !ALLOWED_TYPES.has(action_type)) continue;
- const block: RequestApprovalBlock = {
- action_summary,
- action_type: action_type as RequestApprovalBlock["action_type"],
- };
- if (fields.task_id) block.task_id = fields.task_id.trim();
- if (fields.cost_estimate_usd) {
- const n = Number(fields.cost_estimate_usd);
- if (Number.isFinite(n)) block.cost_estimate_usd = n;
- }
- if (fields.reasoning) block.reasoning = fields.reasoning.trim();
- out.push(block);
- }
- return out;
-}
diff --git a/src/server/orchestration/handlers.test.ts b/src/server/orchestration/handlers.test.ts
new file mode 100644
index 00000000..56813ba7
--- /dev/null
+++ b/src/server/orchestration/handlers.test.ts
@@ -0,0 +1,453 @@
+import Database from "better-sqlite3";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { MIGRATIONS } from "@/server/db/migrations";
+
+let testDb: Database.Database;
+
+vi.mock("@/server/db/db", () => ({
+ getDb: () => testDb,
+ getDbPath: () => ":memory:",
+}));
+
+vi.mock("@/server/agent-meta", () => ({
+ listProjectAgents: vi.fn(async (slug: string) => [
+ {
+ agent_id: `${slug}-cmo`,
+ slug: "cmo",
+ display_name: "CMO",
+ description: "Chief Marketing Officer.",
+ template_key: "cmo",
+ is_template_default: true,
+ },
+ {
+ agent_id: `${slug}-google-ads`,
+ slug: "google-ads",
+ display_name: "Google Ads",
+ description: "Google Ads specialist.",
+ template_key: "google_ads",
+ is_template_default: true,
+ },
+ ]),
+}));
+
+// Most handler tests don't need run-task; mock it so the dynamic import in
+// handleCreateTask doesn't reach OpenClaw.
+vi.mock("./run-task", () => ({
+ startTaskIfProposed: (task: { id: string; status: string }) => ({
+ ...task,
+ status: "running",
+ }),
+}));
+
+vi.mock("@/server/agent-templates", () => ({
+ agentExists: async () => true,
+ agentNameFor: (slug: string, key: string) =>
+ `${slug}-${key.replace(/_/g, "-")}`,
+ templateForKey: (k: string) =>
+ k === "google_ads"
+ ? { key: "google_ads", display_name: "Google Ads" }
+ : k === "cmo"
+ ? { key: "cmo", display_name: "CMO" }
+ : undefined,
+}));
+
+import {
+ handleCancelTask,
+ handleGetApproval,
+ handleGetProject,
+ handleGetTask,
+ handleListApprovalActionTypes,
+ handleListMyApprovals,
+ handleListMyTasks,
+ handleListPendingApprovals,
+ handleListProjectAgents,
+ handleListTaskComments,
+ handleListTaskStatuses,
+ handleListTasks,
+ handleUpdateTask,
+} from "./handlers";
+import { createTask } from "@/server/db/tasks";
+import { createApproval } from "@/server/db/approvals";
+import { logAgentAction } from "@/server/db/agent-actions";
+
+function createTestDb(): Database.Database {
+ const db = new Database(":memory:");
+ db.pragma("foreign_keys = ON");
+ for (const m of MIGRATIONS) db.exec(m.sql);
+ return db;
+}
+
+function seedProject(slug: string) {
+ testDb
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
+ )
+ .run(`p-${slug}`, slug, slug, "2026-05-20T00:00:00Z");
+}
+
+beforeEach(() => {
+ testDb = createTestDb();
+ seedProject("demo");
+ seedProject("other");
+});
+
+afterEach(() => {
+ testDb.close();
+});
+
+describe("handleGetTask", () => {
+ it("returns the task when project_slug matches", () => {
+ const t = createTask({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ brief: "do x",
+ title: "T1",
+ });
+ const r = handleGetTask(
+ { task_id: t.id },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok && r.data.id).toBe(t.id);
+ });
+
+ it("rejects cross-project reads", () => {
+ const t = createTask({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ brief: "do x",
+ });
+ const r = handleGetTask(
+ { task_id: t.id },
+ { project_slug: "other", agent_id: "other-google-ads" },
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toMatch(/Cross-project/);
+ });
+
+ it("returns ok:false for unknown task_id", () => {
+ const r = handleGetTask(
+ { task_id: "nope" },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok).toBe(false);
+ });
+});
+
+describe("handleTaskStatus — cannot-close-with-pending-approval invariant", () => {
+ it("refuses status='done' when the task has a pending approval", async () => {
+ const { handleTaskStatus } = await import("./handlers");
+ const t = createTask({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ brief: "x",
+ });
+ testDb.prepare("UPDATE tasks SET status='blocked' WHERE id = ?").run(t.id);
+ createApproval({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ task_id: t.id,
+ action_summary: "Pause keyword",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ const r = handleTaskStatus(
+ { task_id: t.id, status: "done" },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toMatch(/unresolved approval/i);
+ // Task should NOT have been flipped to succeeded.
+ const after = testDb
+ .prepare("SELECT status FROM tasks WHERE id = ?")
+ .get(t.id) as { status: string };
+ expect(after.status).toBe("blocked");
+ });
+
+ it("allows status='failed' even with pending approvals (bail-out hatch)", async () => {
+ const { handleTaskStatus } = await import("./handlers");
+ const t = createTask({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ brief: "x",
+ });
+ testDb.prepare("UPDATE tasks SET status='blocked' WHERE id = ?").run(t.id);
+ createApproval({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ task_id: t.id,
+ action_summary: "x",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ const r = handleTaskStatus(
+ { task_id: t.id, status: "failed", summary: "user is unreachable" },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.data.status).toBe("failed");
+ });
+
+ it("allows status='done' once the approval is resolved", async () => {
+ const { handleTaskStatus } = await import("./handlers");
+ const { resolveApproval } = await import("@/server/db/approvals");
+ const t = createTask({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ brief: "x",
+ });
+ testDb.prepare("UPDATE tasks SET status='blocked' WHERE id = ?").run(t.id);
+ const a = createApproval({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ task_id: t.id,
+ action_summary: "x",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ resolveApproval(a.id, "approved");
+ const r = handleTaskStatus(
+ { task_id: t.id, status: "done", summary: "shipped" },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok && r.data.status).toBe("succeeded");
+ });
+});
+
+describe("handleListMyTasks", () => {
+ it("returns only in-flight tasks by default, filtered to this project + agent", () => {
+ createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a", title: "A" });
+ const t2 = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "b", title: "B" });
+ testDb.prepare("UPDATE tasks SET status='succeeded' WHERE id = ?").run(t2.id);
+ createTask({ project_slug: "demo", agent_id: "demo-seo", brief: "not mine" });
+ createTask({ project_slug: "other", agent_id: "other-google-ads", brief: "other proj" });
+
+ const r = handleListMyTasks(
+ {},
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.data.map((t) => t.title).sort()).toEqual(["A"]);
+ });
+
+ it("status='all' returns terminal + in-flight", () => {
+ createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a", title: "A" });
+ const t2 = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "b", title: "B" });
+ testDb.prepare("UPDATE tasks SET status='succeeded' WHERE id = ?").run(t2.id);
+
+ const r = handleListMyTasks(
+ { status: "all" },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok && r.data.length).toBe(2);
+ });
+
+ it("status='succeeded' narrows", () => {
+ const t1 = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a" });
+ testDb.prepare("UPDATE tasks SET status='succeeded' WHERE id = ?").run(t1.id);
+ createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "b" });
+
+ const r = handleListMyTasks(
+ { status: "succeeded" },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(r.ok && r.data.length).toBe(1);
+ });
+});
+
+describe("handleListTasks", () => {
+ it("returns all project tasks regardless of agent", () => {
+ createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a" });
+ createTask({ project_slug: "demo", agent_id: "demo-seo", brief: "b" });
+ createTask({ project_slug: "other", agent_id: "other-seo", brief: "c" });
+ const r = handleListTasks(
+ {},
+ { project_slug: "demo", agent_id: "" },
+ );
+ expect(r.ok && r.data.length).toBe(2);
+ });
+});
+
+describe("handleUpdateTask", () => {
+ it("patches the requested fields and logs an action", () => {
+ const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "old", title: "Old" });
+ const r = handleUpdateTask(
+ { task_id: t.id, title: "New", brief: "fresh" },
+ { project_slug: "demo", agent_id: "demo-cmo" },
+ );
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.data.title).toBe("New");
+ expect(r.data.brief).toBe("fresh");
+ const log = testDb
+ .prepare("SELECT action_type FROM agent_actions WHERE task_id = ?")
+ .all(t.id) as Array<{ action_type: string }>;
+ expect(log.some((l) => l.action_type === "task_updated")).toBe(true);
+ });
+
+ it("rejects updates with no fields", () => {
+ const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
+ const r = handleUpdateTask(
+ { task_id: t.id },
+ { project_slug: "demo", agent_id: "demo-cmo" },
+ );
+ expect(r.ok).toBe(false);
+ });
+
+ it("rejects cross-project updates", () => {
+ const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
+ const r = handleUpdateTask(
+ { task_id: t.id, title: "z" },
+ { project_slug: "other", agent_id: "other-cmo" },
+ );
+ expect(r.ok).toBe(false);
+ });
+});
+
+describe("handleCancelTask", () => {
+ it("flips a running task to cancelled with reason", () => {
+ const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
+ testDb.prepare("UPDATE tasks SET status='running' WHERE id = ?").run(t.id);
+ const r = handleCancelTask(
+ { task_id: t.id, reason: "no longer needed" },
+ { project_slug: "demo", agent_id: "demo-cmo" },
+ );
+ expect(r.ok && r.data.status).toBe("cancelled");
+ expect(r.ok && r.data.error_message).toBe("no longer needed");
+ });
+
+ it("is a no-op on already-terminal tasks", () => {
+ const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
+ testDb.prepare("UPDATE tasks SET status='succeeded' WHERE id = ?").run(t.id);
+ const r = handleCancelTask(
+ { task_id: t.id },
+ { project_slug: "demo", agent_id: "demo-cmo" },
+ );
+ expect(r.ok && r.data.status).toBe("succeeded");
+ });
+});
+
+describe("handleGetProject + handleListProjectAgents", () => {
+ it("returns the project metadata for the caller's project", () => {
+ const r = handleGetProject({}, { project_slug: "demo", agent_id: "" });
+ expect(r.ok && r.data.slug).toBe("demo");
+ });
+
+ it("listProjectAgents returns the seeded mock", async () => {
+ const r = await handleListProjectAgents({}, { project_slug: "demo", agent_id: "" });
+ expect(r.ok && r.data.map((a) => a.slug)).toEqual(["cmo", "google-ads"]);
+ });
+});
+
+describe("handleListTaskComments", () => {
+ it("returns task_comment rows scoped to the task", () => {
+ const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
+ logAgentAction({
+ project_slug: "demo",
+ agent_id: "demo-cmo",
+ task_id: t.id,
+ action_type: "task_comment",
+ summary: "first",
+ });
+ logAgentAction({
+ project_slug: "demo",
+ agent_id: "demo-cmo",
+ task_id: t.id,
+ action_type: "task_done", // not a comment
+ summary: "should be filtered",
+ });
+ const r = handleListTaskComments(
+ { task_id: t.id },
+ { project_slug: "demo", agent_id: "demo-cmo" },
+ );
+ expect(r.ok && r.data.map((c) => c.summary)).toEqual(["first"]);
+ });
+});
+
+describe("handleGetApproval + handleListMyApprovals + handleListPendingApprovals", () => {
+ it("returns the approval and filters by agent for list_my_approvals", () => {
+ const a1 = createApproval({
+ project_slug: "demo",
+ agent_id: "demo-google-ads",
+ action_summary: "raise bid",
+ action_type: "bid_change",
+ cost_estimate_usd: 10,
+ payload: {},
+ });
+ createApproval({
+ project_slug: "demo",
+ agent_id: "demo-seo",
+ action_summary: "publish",
+ action_type: "content_publishing",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+
+ const got = handleGetApproval(
+ { approval_id: a1.id },
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(got.ok && got.data.id).toBe(a1.id);
+
+ const mine = handleListMyApprovals(
+ {},
+ { project_slug: "demo", agent_id: "demo-google-ads" },
+ );
+ expect(mine.ok && mine.data.length).toBe(1);
+ expect(mine.ok && mine.data[0]!.agent_id).toBe("demo-google-ads");
+
+ const pending = handleListPendingApprovals(
+ {},
+ { project_slug: "demo", agent_id: "" },
+ );
+ expect(pending.ok && pending.data.length).toBe(2);
+ });
+
+ it("rejects cross-project get_approval", () => {
+ const a = createApproval({
+ project_slug: "demo",
+ agent_id: "demo-cmo",
+ action_summary: "x",
+ action_type: "other",
+ cost_estimate_usd: 0,
+ payload: {},
+ });
+ const r = handleGetApproval(
+ { approval_id: a.id },
+ { project_slug: "other", agent_id: "" },
+ );
+ expect(r.ok).toBe(false);
+ });
+});
+
+describe("enum discovery handlers", () => {
+ it("list_task_statuses returns 7 entries with transitions", () => {
+ const r = handleListTaskStatuses();
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.data.map((s) => s.value).sort()).toEqual(
+ ["approved", "blocked", "cancelled", "failed", "proposed", "running", "succeeded"].sort(),
+ );
+ const succeeded = r.data.find((s) => s.value === "succeeded")!;
+ expect(succeeded.terminal).toBe(true);
+ expect(succeeded.next).toEqual([]);
+ const running = r.data.find((s) => s.value === "running")!;
+ expect(running.terminal).toBe(false);
+ expect(running.next).toContain("blocked");
+ expect(running.next).toContain("succeeded");
+ });
+
+ it("list_approval_action_types marks cost-required types", () => {
+ const r = handleListApprovalActionTypes();
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ const spend = r.data.find((a) => a.value === "spend")!;
+ expect(spend.cost_estimate_required).toBe(true);
+ const content = r.data.find((a) => a.value === "content_publishing")!;
+ expect(content.cost_estimate_required).toBe(false);
+ });
+});
diff --git a/src/server/orchestration/handlers.ts b/src/server/orchestration/handlers.ts
new file mode 100644
index 00000000..87b53f11
--- /dev/null
+++ b/src/server/orchestration/handlers.ts
@@ -0,0 +1,698 @@
+import {
+ agentExists,
+ agentNameFor,
+ templateForKey,
+ type AgentTemplateKey,
+} from "@/server/agent-templates";
+import { listProjectAgents } from "@/server/agent-meta";
+import { listAgentActions, logAgentAction } from "@/server/db/agent-actions";
+import {
+ createApproval,
+ getApproval,
+ listActionableApprovals,
+ listApprovalsForTask,
+} from "@/server/db/approvals";
+import { getDb } from "@/server/db/db";
+import { getProject } from "@/server/db/projects";
+import {
+ createTask,
+ getTask,
+ listTasks,
+ listTasksByAgent,
+ markTaskBlocked,
+ unblockTask,
+ updateTask,
+} from "@/server/db/tasks";
+import type {
+ AgentAction,
+} from "@/server/db/agent-actions";
+import type {
+ Approval,
+ Project,
+ Task,
+ TaskStatus,
+} from "@/types";
+
+/**
+ * Shared orchestration handlers. Both the legacy text-block parser
+ * (`process-blocks.ts`) and the MCP server tools (`mcp-server/tools.ts`)
+ * dispatch through these so the two entry points stay in sync — same
+ * validation, same logging, same side effects.
+ *
+ * Inputs are already-parsed/validated payloads (schema enforcement happens
+ * upstream — regex in the block parser, zod in the MCP layer). Context
+ * carries the caller's identity which the handler uses for authorization
+ * checks (cross-project rejection, assignee-only updates).
+ *
+ * Return shape is the `HandlerResult` discriminated union so callers can
+ * surface failures consistently — the MCP layer maps `ok: false` to the
+ * tool-call `isError: true` envelope; the block parser maps it to an
+ * `outcome.errors[]` entry.
+ */
+
+export type HandlerContext = {
+ /** Project the caller is operating in. */
+ project_slug: string;
+ /** Caller's agent_id (the one making the change). */
+ agent_id: string;
+};
+
+export type HandlerResult<T> =
+ | { ok: true; data: T }
+ | { ok: false; error: string };
+
+const TASK_STATUS_ENUM = ["working", "done", "blocked", "failed"] as const;
+export type TaskStatusValue = (typeof TASK_STATUS_ENUM)[number];
+
+const APPROVAL_ACTION_TYPES = [
+ "spend",
+ "content_publishing",
+ "new_channel",
+ "bid_change",
+ "audience_change",
+ "other",
+] as const;
+export type ApprovalActionType = (typeof APPROVAL_ACTION_TYPES)[number];
+
+export {
+ TASK_STATUS_ENUM as TASK_STATUS_VALUES,
+ APPROVAL_ACTION_TYPES as APPROVAL_ACTION_TYPE_VALUES,
+};
+
+// ── create_task ────────────────────────────────────────────────────────
+
+export type CreateTaskInput = {
+ title: string;
+ /** Template key (e.g. `google_ads`). Normalized through templateForKey. */
+ assignee: string;
+ brief: string;
+ success_criteria?: string;
+};
+
+export async function handleCreateTask(
+ input: CreateTaskInput,
+ ctx: HandlerContext,
+): Promise<HandlerResult<Task>> {
+ const template = templateForKey(input.assignee);
+ if (!template) {
+ return { ok: false, error: `Unknown assignee template '${input.assignee}'` };
+ }
+ if (template.key === "cmo") {
+ return { ok: false, error: "CMO cannot assign tasks to itself — pick a specialist" };
+ }
+
+ const assigneeAgentId = agentNameFor(
+ ctx.project_slug,
+ template.key as AgentTemplateKey,
+ );
+ if (!(await agentExists(assigneeAgentId))) {
+ return {
+ ok: false,
+ error: `Assignee agent ${assigneeAgentId} is not provisioned for this project`,
+ };
+ }
+
+ const task = createTask({
+ project_slug: ctx.project_slug,
+ agent_id: assigneeAgentId,
+ title: input.title,
+ brief: input.brief,
+ success_criteria: input.success_criteria ?? null,
+ assigner_agent_id: ctx.agent_id,
+ status: "proposed",
+ });
+
+ logAgentAction({
+ project_slug: ctx.project_slug,
+ agent_id: ctx.agent_id,
+ action_type: "task_created",
+ summary: `Created task '${task.title}' for ${template.display_name}.`,
+ payload: { task_id: task.id, assignee: assigneeAgentId },
+ });
+
+ // Auto-start the delegated task. Lazy import keeps the orchestration →
+ // run-task → gateway chain out of modules that just want createTask.
+ const { startTaskIfProposed } = await import("./run-task");
+ const started = startTaskIfProposed(task);
+ return { ok: true, data: started };
+}
+
+// ── submit_task_status ──────────────────────────────────────────────────
+
+export type TaskStatusInput = {
+ task_id: string;
+ status: TaskStatusValue;
+ summary?: string;
+};
+
+/** Used by the MCP submit_task_status handler; the text-block path is in
+ * process-blocks.ts and shares this logic. */
+export function handleTaskStatus(
+ input: TaskStatusInput,
+ ctx: HandlerContext | null,
+): HandlerResult<{ task_id: string; status: TaskStatus }> {
+ const task = getTask(input.task_id);
+ if (!task) {
+ return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ }
+ // For MCP calls ctx is null (we trust the bearer; status updates are
+ // intrinsically agent-scoped via task.agent_id). The block-parser path
+ // passes ctx so it can enforce cross-project / wrong-assignee rules.
+ if (ctx) {
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project task update rejected: task '${input.task_id}' belongs to '${task.project_slug}' but emitter is in '${ctx.project_slug}'`,
+ };
+ }
+ if (task.agent_id !== ctx.agent_id) {
+ return {
+ ok: false,
+ error: `Only the assignee (${task.agent_id}) can update task '${input.task_id}'; got update from '${ctx.agent_id}'`,
+ };
+ }
+ }
+ if (
+ task.status === "cancelled" ||
+ task.status === "failed" ||
+ task.status === "succeeded"
+ ) {
+ return { ok: true, data: { task_id: task.id, status: task.status } };
+ }
+
+ // Closing a task that's gated on an unresolved approval is almost always
+ // a mistake — the agent thinks "I queued the approval, my work is done"
+ // and prematurely marks the task succeeded, orphaning the approval in the
+ // inbox. Refuse the transition and tell the agent what's blocking it.
+ // The exception is `failed`, which we DO allow even with pending
+ // approvals (an agent should be able to bail out of a stuck flow).
+ if (input.status === "done") {
+ const pendingApprovals = listApprovalsForTask(task.id).filter(
+ (a) => a.status === "pending" || a.status === "revision_requested",
+ );
+ if (pendingApprovals.length > 0) {
+ const ids = pendingApprovals.map((a) => a.id.slice(0, 8)).join(", ");
+ return {
+ ok: false,
+ error: `Cannot close task ${task.display_id} — ${pendingApprovals.length} unresolved approval(s) still pending: ${ids}. Stay in 'blocked' until the user resolves them; the platform will wake you up on resolution with the decision in context.`,
+ };
+ }
+ }
+
+ const newStatus: TaskStatus =
+ input.status === "working"
+ ? "running"
+ : input.status === "done"
+ ? "succeeded"
+ : input.status === "blocked"
+ ? "blocked"
+ : "failed";
+
+ updateTask(task.id, {
+ status: newStatus,
+ result: input.summary ? { summary: input.summary } : undefined,
+ error_message:
+ input.status === "failed"
+ ? (input.summary ?? "agent reported failure")
+ : null,
+ });
+
+ logAgentAction({
+ project_slug: task.project_slug,
+ agent_id: task.agent_id,
+ task_id: task.id,
+ action_type: `task_${input.status}`,
+ summary: input.summary ?? `Task ${input.status}.`,
+ payload: { task_id: task.id, status: newStatus, via: ctx ? "block" : "mcp" },
+ });
+
+ return { ok: true, data: { task_id: task.id, status: newStatus } };
+}
+
+// ── add_task_comment ───────────────────────────────────────────────────
+
+export type AddCommentInput = {
+ task_id: string;
+ body: string;
+};
+
+export function handleAddTaskComment(
+ input: AddCommentInput,
+ ctx: HandlerContext,
+): HandlerResult<{ task_id: string }> {
+ const task = getTask(input.task_id);
+ if (!task) {
+ return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ }
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project comment rejected on task '${input.task_id}'`,
+ };
+ }
+ logAgentAction({
+ project_slug: ctx.project_slug,
+ agent_id: ctx.agent_id,
+ task_id: task.id,
+ action_type: "task_comment",
+ summary: input.body,
+ payload: { task_id: task.id },
+ });
+ return { ok: true, data: { task_id: task.id } };
+}
+
+// ── ask_user_question ──────────────────────────────────────────────────
+
+export type AskUserInput = {
+ question: string;
+ task_id?: string;
+ /** Comma-separated multi-choice hints rendered as buttons in the UI. */
+ options?: string;
+};
+
+export function handleAskUser(
+ input: AskUserInput,
+ ctx: HandlerContext,
+): HandlerResult<{ question: string; task_id: string | null }> {
+ let resolvedTaskId: string | null = null;
+ if (input.task_id) {
+ const task = getTask(input.task_id);
+ if (!task) {
+ return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ }
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project ask_user rejected on task '${input.task_id}'`,
+ };
+ }
+ resolvedTaskId = task.id;
+ }
+ logAgentAction({
+ project_slug: ctx.project_slug,
+ agent_id: ctx.agent_id,
+ task_id: resolvedTaskId,
+ action_type: "ask_user",
+ summary: input.question,
+ payload: { task_id: resolvedTaskId, options: input.options ?? null },
+ });
+ return {
+ ok: true,
+ data: { question: input.question, task_id: resolvedTaskId },
+ };
+}
+
+// ── request_approval ────────────────────────────────────────────────────
+
+export type RequestApprovalInput = {
+ action_summary: string;
+ action_type: ApprovalActionType;
+ task_id?: string;
+ cost_estimate_usd?: number;
+ reasoning?: string;
+};
+
+export async function handleRequestApproval(
+ input: RequestApprovalInput,
+ ctx: HandlerContext,
+): Promise<HandlerResult<{
+ approval_id: string;
+ action_type: ApprovalActionType;
+ status: string;
+ auto_resolved: boolean;
+}>> {
+ let resolvedTaskId: string | null = null;
+ if (input.task_id) {
+ const task = getTask(input.task_id);
+ if (!task) {
+ return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ }
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project approval rejected on task '${input.task_id}'`,
+ };
+ }
+ resolvedTaskId = task.id;
+ }
+
+ const approval = createApproval({
+ project_slug: ctx.project_slug,
+ agent_id: ctx.agent_id,
+ task_id: resolvedTaskId,
+ action_summary: input.action_summary,
+ action_type: input.action_type,
+ cost_estimate_usd: input.cost_estimate_usd ?? 0,
+ reasoning: input.reasoning ?? null,
+ payload: { task_id: resolvedTaskId },
+ });
+
+ const autoResolved = approval.decided_by_kind === "policy";
+
+ if (resolvedTaskId) {
+ if (autoResolved) {
+ unblockTask(resolvedTaskId);
+ } else {
+ markTaskBlocked(resolvedTaskId);
+ }
+ }
+
+ if (autoResolved) {
+ void (async () => {
+ try {
+ const { wakeTaskOnApprovalResolution } = await import("./approval-wakeup");
+ await wakeTaskOnApprovalResolution(approval);
+ } catch (err) {
+ console.error("[request-approval] auto-resolve wake-up failed:", err);
+ }
+ })();
+ }
+
+ return {
+ ok: true,
+ data: {
+ approval_id: approval.id,
+ action_type: input.action_type,
+ status: approval.status,
+ auto_resolved: autoResolved,
+ },
+ };
+}
+
+// ── Read handlers (paperclip-aligned context surface) ──────────────────
+//
+// These let agents ask "what's my task?", "what's pending?", "who can I
+// delegate to?" instead of relying solely on the one-shot kickoff message.
+// Without them, an agent whose context window rotates loses task anchoring.
+
+export function handleGetTask(
+ input: { task_id: string },
+ ctx: HandlerContext,
+): HandlerResult<Task> {
+ const task = getTask(input.task_id);
+ if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project read rejected: task '${input.task_id}' belongs to '${task.project_slug}'`,
+ };
+ }
+ return { ok: true, data: task };
+}
+
+export function handleListMyTasks(
+ input: { status?: TaskStatus | "in_flight" | "all" },
+ ctx: HandlerContext,
+): HandlerResult<Task[]> {
+ // "in_flight" = anything not terminal; the common case for an agent asking
+ // "what's on my plate?". "all" disables the filter; a specific TaskStatus
+ // narrows to that state.
+ const status = input.status ?? "in_flight";
+ let all: Task[];
+ if (status === "in_flight" || status === "all") {
+ all = listTasksByAgent(ctx.agent_id);
+ } else {
+ all = listTasksByAgent(ctx.agent_id, status);
+ }
+ if (status === "in_flight") {
+ const inFlight = new Set<TaskStatus>([
+ "proposed",
+ "approved",
+ "running",
+ "blocked",
+ ]);
+ all = all.filter((t) => inFlight.has(t.status));
+ }
+ const projectScoped = all.filter((t) => t.project_slug === ctx.project_slug);
+ return { ok: true, data: projectScoped };
+}
+
+export function handleListTasks(
+ input: { status?: TaskStatus },
+ ctx: HandlerContext,
+): HandlerResult<Task[]> {
+ const rows = listTasks(ctx.project_slug, input.status);
+ return { ok: true, data: rows };
+}
+
+// ── update_task ────────────────────────────────────────────────────────
+
+export type UpdateTaskInput = {
+ task_id: string;
+ title?: string;
+ brief?: string;
+ success_criteria?: string;
+};
+
+export function handleUpdateTask(
+ input: UpdateTaskInput,
+ ctx: HandlerContext,
+): HandlerResult<Task> {
+ const task = getTask(input.task_id);
+ if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project update rejected on task '${input.task_id}'`,
+ };
+ }
+ if (
+ input.title === undefined &&
+ input.brief === undefined &&
+ input.success_criteria === undefined
+ ) {
+ return { ok: false, error: "At least one field (title/brief/success_criteria) must be provided." };
+ }
+ // Patch via raw SQL inline so we don't widen the public updateTask
+ // surface (which only supports status/result/error_message) for this
+ // one tool. better-sqlite3 is synchronous so the read-after-write is
+ // race-free in this process.
+ const db = getDb();
+ const now = new Date().toISOString();
+ const sets: string[] = ["updated_at = ?"];
+ const args: unknown[] = [now];
+ if (input.title !== undefined) {
+ sets.push("title = ?");
+ args.push(input.title);
+ }
+ if (input.brief !== undefined) {
+ sets.push("brief = ?");
+ args.push(input.brief);
+ }
+ if (input.success_criteria !== undefined) {
+ sets.push("success_criteria = ?");
+ args.push(input.success_criteria);
+ }
+ args.push(task.id);
+ db.prepare(`UPDATE tasks SET ${sets.join(", ")} WHERE id = ?`).run(...args);
+ const after = getTask(task.id);
+ if (!after) return { ok: false, error: "Task vanished after update." };
+ logAgentAction({
+ project_slug: ctx.project_slug,
+ agent_id: ctx.agent_id,
+ task_id: task.id,
+ action_type: "task_updated",
+ summary: "Task fields updated.",
+ payload: {
+ task_id: task.id,
+ fields: Object.fromEntries(
+ Object.entries(input).filter(([k, v]) => k !== "task_id" && v !== undefined),
+ ),
+ },
+ });
+ return { ok: true, data: after };
+}
+
+// ── cancel_task ────────────────────────────────────────────────────────
+
+export function handleCancelTask(
+ input: { task_id: string; reason?: string },
+ ctx: HandlerContext,
+): HandlerResult<Task> {
+ const task = getTask(input.task_id);
+ if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project cancel rejected on task '${input.task_id}'`,
+ };
+ }
+ if (
+ task.status === "succeeded" ||
+ task.status === "failed" ||
+ task.status === "cancelled"
+ ) {
+ return { ok: true, data: task }; // already terminal — no-op
+ }
+ updateTask(task.id, {
+ status: "cancelled",
+ error_message: input.reason ?? null,
+ });
+ logAgentAction({
+ project_slug: ctx.project_slug,
+ agent_id: ctx.agent_id,
+ task_id: task.id,
+ action_type: "task_cancelled",
+ summary: input.reason ?? "Task cancelled.",
+ payload: { task_id: task.id, reason: input.reason ?? null },
+ });
+ const after = getTask(task.id);
+ if (!after) return { ok: false, error: "Task vanished after cancel." };
+ return { ok: true, data: after };
+}
+
+// ── project + agents context ───────────────────────────────────────────
+
+export function handleGetProject(
+ _input: Record<string, never>,
+ ctx: HandlerContext,
+): HandlerResult<Project> {
+ const project = getProject(ctx.project_slug);
+ if (!project) return { ok: false, error: `Unknown project '${ctx.project_slug}'` };
+ return { ok: true, data: project };
+}
+
+export type ProjectAgentSummary = {
+ agent_id: string;
+ slug: string;
+ display_name: string;
+ description: string;
+ template_key: string | null;
+ is_template_default: boolean;
+};
+
+export async function handleListProjectAgents(
+ _input: Record<string, never>,
+ ctx: HandlerContext,
+): Promise<HandlerResult<ProjectAgentSummary[]>> {
+ const entries = await listProjectAgents(ctx.project_slug);
+ return {
+ ok: true,
+ data: entries.map((e) => ({
+ agent_id: e.agent_id,
+ slug: e.slug,
+ display_name: e.display_name,
+ description: e.description ?? "",
+ template_key: e.template_key ?? null,
+ is_template_default: Boolean(e.is_template_default),
+ })),
+ };
+}
+
+// ── activity / comments ────────────────────────────────────────────────
+
+export function handleListTaskComments(
+ input: { task_id: string; limit?: number },
+ ctx: HandlerContext,
+): HandlerResult<AgentAction[]> {
+ const task = getTask(input.task_id);
+ if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project read rejected on task '${input.task_id}'`,
+ };
+ }
+ // Comments are stored on the agent_actions log keyed by task_id and
+ // action_type. Filter both client-side; a dedicated table is in scope
+ // for v1.1 (paperclip parity — see comments in process-blocks.ts).
+ const limit = input.limit ?? 50;
+ const rows = listAgentActions(ctx.project_slug, 500).filter(
+ (a) => a.task_id === task.id && a.action_type === "task_comment",
+ );
+ return { ok: true, data: rows.slice(0, limit) };
+}
+
+// ── approvals ─────────────────────────────────────────────────────────
+
+export function handleGetApproval(
+ input: { approval_id: string },
+ ctx: HandlerContext,
+): HandlerResult<Approval> {
+ const approval = getApproval(input.approval_id);
+ if (!approval) {
+ return { ok: false, error: `Unknown approval_id '${input.approval_id}'` };
+ }
+ if (approval.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project read rejected on approval '${input.approval_id}'`,
+ };
+ }
+ return { ok: true, data: approval };
+}
+
+export function handleListMyApprovals(
+ _input: Record<string, never>,
+ ctx: HandlerContext,
+): HandlerResult<Approval[]> {
+ // Approvals requested by this agent across all states. Caller filters
+ // status client-side if needed.
+ const rows = listActionableApprovals(ctx.project_slug).filter(
+ (a) => a.agent_id === ctx.agent_id,
+ );
+ return { ok: true, data: rows };
+}
+
+export function handleListPendingApprovals(
+ _input: Record<string, never>,
+ ctx: HandlerContext,
+): HandlerResult<Approval[]> {
+ return { ok: true, data: listActionableApprovals(ctx.project_slug) };
+}
+
+export function handleListApprovalsForTask(
+ input: { task_id: string },
+ ctx: HandlerContext,
+): HandlerResult<Approval[]> {
+ const task = getTask(input.task_id);
+ if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
+ if (task.project_slug !== ctx.project_slug) {
+ return {
+ ok: false,
+ error: `Cross-project read rejected on task '${input.task_id}'`,
+ };
+ }
+ return { ok: true, data: listApprovalsForTask(task.id) };
+}
+
+// ── enum discovery ─────────────────────────────────────────────────────
+
+export type TaskStatusInfo = {
+ value: TaskStatus;
+ description: string;
+ terminal: boolean;
+ /** Statuses you can transition INTO from this one. Empty for terminal. */
+ next: TaskStatus[];
+};
+
+const TASK_STATUS_INFO: TaskStatusInfo[] = [
+ { value: "proposed", description: "Task created, awaiting kickoff or user approval.", terminal: false, next: ["approved", "running", "cancelled"] },
+ { value: "approved", description: "User approved a guarded task; ready for the assignee to pick up.", terminal: false, next: ["running", "cancelled"] },
+ { value: "running", description: "Assignee is actively working.", terminal: false, next: ["blocked", "succeeded", "failed", "cancelled"] },
+ { value: "blocked", description: "Waiting on a user decision, an approval, or a missing input.", terminal: false, next: ["running", "succeeded", "failed", "cancelled"] },
+ { value: "succeeded", description: "Task complete (terminal).", terminal: true, next: [] },
+ { value: "failed", description: "Task could not complete (terminal). error_message has the reason.", terminal: true, next: [] },
+ { value: "cancelled", description: "User or CMO cancelled before completion (terminal).", terminal: true, next: [] },
+];
+
+export function handleListTaskStatuses(): HandlerResult<TaskStatusInfo[]> {
+ return { ok: true, data: TASK_STATUS_INFO };
+}
+
+const APPROVAL_ACTION_TYPE_INFO: Array<{
+ value: ApprovalActionType;
+ description: string;
+ cost_estimate_required: boolean;
+}> = [
+ { value: "spend", description: "Increase or shift advertising spend.", cost_estimate_required: true },
+ { value: "content_publishing", description: "Publish public-facing content (landing page, blog post, ad copy).", cost_estimate_required: false },
+ { value: "new_channel", description: "Launch a new marketing channel (new ad platform, new geo, etc.).", cost_estimate_required: true },
+ { value: "bid_change", description: "Modify keyword bids or bidding strategy.", cost_estimate_required: true },
+ { value: "audience_change", description: "Change campaign targeting / audience.", cost_estimate_required: false },
+ { value: "other", description: "Any other governed action not covered above.", cost_estimate_required: false },
+];
+
+export function handleListApprovalActionTypes(): HandlerResult<typeof APPROVAL_ACTION_TYPE_INFO> {
+ return { ok: true, data: APPROVAL_ACTION_TYPE_INFO };
+}
diff --git a/src/server/orchestration/process-blocks.test.ts b/src/server/orchestration/process-blocks.test.ts
deleted file mode 100644
index 4b9a71a0..00000000
--- a/src/server/orchestration/process-blocks.test.ts
+++ /dev/null
@@ -1,708 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const agentExistsMock = vi.fn();
-const templateForKeyMock = vi.fn();
-const agentNameForMock = vi.fn();
-vi.mock("@/server/agent-templates", () => ({
- agentExists: (...a: unknown[]) => agentExistsMock(...a),
- templateForKey: (...a: unknown[]) => templateForKeyMock(...a),
- agentNameFor: (...a: unknown[]) => agentNameForMock(...a),
-}));
-
-const createTaskMock = vi.fn();
-const getTaskMock = vi.fn();
-const updateTaskMock = vi.fn();
-const claimProposedTaskMock = vi.fn();
-const setTaskThreadIfMissingMock = vi.fn();
-vi.mock("@/server/db/tasks", () => ({
- createTask: (...a: unknown[]) => createTaskMock(...a),
- getTask: (...a: unknown[]) => getTaskMock(...a),
- updateTask: (...a: unknown[]) => updateTaskMock(...a),
- claimProposedTask: (...a: unknown[]) => claimProposedTaskMock(...a),
- setTaskThreadIfMissing: (...a: unknown[]) => setTaskThreadIfMissingMock(...a),
-}));
-
-const logAgentActionMock = vi.fn();
-vi.mock("@/server/db/agent-actions", () => ({
- logAgentAction: (...a: unknown[]) => logAgentActionMock(...a),
-}));
-
-const createApprovalMock = vi.fn();
-vi.mock("@/server/db/approvals", () => ({
- createApproval: (...a: unknown[]) => createApprovalMock(...a),
-}));
-
-import { generateTaskThreadId, processOrchestrationBlocks } from "./process-blocks";
-
-const CMO_ID = "demo-cmo";
-
-describe("processOrchestrationBlocks — create_task", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- templateForKeyMock.mockImplementation((k: string) =>
- k === "google_ads"
- ? { key: "google_ads", display_name: "Google Ads" }
- : k === "cmo"
- ? { key: "cmo", display_name: "CMO" }
- : undefined,
- );
- agentNameForMock.mockImplementation(
- (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,
- );
- agentExistsMock.mockResolvedValue(true);
- createTaskMock.mockImplementation((input) => ({
- id: "task-1",
- project_slug: input.project_slug,
- agent_id: input.agent_id,
- title: input.title,
- brief: input.brief,
- success_criteria: input.success_criteria ?? null,
- status: input.status ?? "proposed",
- assigner_agent_id: input.assigner_agent_id ?? null,
- created_at: "now",
- updated_at: "now",
- deadline_iso: null,
- result_json: null,
- error_message: null,
- thread_id: null,
- }));
- });
-
- it("creates a task when block is well-formed and assignee exists", async () => {
- const text = `<create_task>
-title: Install conversion tracking
-assignee: google_ads
-brief: Add the tag.
-</create_task>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: CMO_ID,
- });
- expect(outcome.tasks_created).toHaveLength(1);
- expect(outcome.errors).toHaveLength(0);
- expect(createTaskMock).toHaveBeenCalledWith(
- expect.objectContaining({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- title: "Install conversion tracking",
- brief: "Add the tag.",
- assigner_agent_id: CMO_ID,
- status: "proposed",
- }),
- );
- expect(logAgentActionMock).toHaveBeenCalledWith(
- expect.objectContaining({
- action_type: "task_created",
- agent_id: CMO_ID,
- }),
- );
- });
-
- it("rejects assigning to an unknown template", async () => {
- templateForKeyMock.mockReturnValueOnce(undefined);
- const text = `<create_task>
-title: x
-assignee: nope
-brief: y
-</create_task>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: CMO_ID,
- });
- expect(outcome.tasks_created).toHaveLength(0);
- expect(outcome.errors[0]?.message).toMatch(/Unknown assignee/);
- expect(createTaskMock).not.toHaveBeenCalled();
- });
-
- it("rejects CMO assigning a task to itself", async () => {
- const text = `<create_task>
-title: x
-assignee: cmo
-brief: y
-</create_task>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: CMO_ID,
- });
- expect(outcome.errors[0]?.message).toMatch(/cannot assign tasks to itself/);
- });
-
- it("rejects when the assignee agent isn't provisioned", async () => {
- agentExistsMock.mockResolvedValueOnce(false);
- const text = `<create_task>
-title: x
-assignee: google_ads
-brief: y
-</create_task>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: CMO_ID,
- });
- expect(outcome.errors[0]?.message).toMatch(/not provisioned/);
- });
-
- it("processes multiple blocks in order", async () => {
- const text = `
-<create_task>
-title: A
-assignee: google_ads
-brief: a
-</create_task>
-<create_task>
-title: B
-assignee: google_ads
-brief: b
-</create_task>
-<create_task>
-title: C
-assignee: google_ads
-brief: c
-</create_task>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: CMO_ID,
- });
- expect(outcome.tasks_created).toHaveLength(3);
- });
-});
-
-describe("processOrchestrationBlocks — task_status", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getTaskMock.mockReturnValue({
- id: "task-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- });
-
- it("updates status to succeeded on status=done", async () => {
- const text = `<task_status>
-task_id: task-1
-status: done
-summary: Conv tag installed; tested.
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({ status: "succeeded" }),
- );
- expect(outcome.task_status_updates[0]).toEqual({
- task_id: "task-1",
- status: "succeeded",
- });
- });
-
- it("rejects status update from a non-assignee", async () => {
- const text = `<task_status>
-task_id: task-1
-status: done
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-seo", // not the assignee
- });
- expect(outcome.errors[0]?.message).toMatch(/Only the assignee/);
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("rejects cross-project task updates", async () => {
- getTaskMock.mockReturnValueOnce({
- id: "task-1",
- project_slug: "OTHER",
- agent_id: "demo-google-ads",
- });
- const text = `<task_status>
-task_id: task-1
-status: done
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors[0]?.message).toMatch(/Cross-project/);
- });
-
- it("rejects unknown task_id", async () => {
- getTaskMock.mockReturnValueOnce(null);
- const text = `<task_status>
-task_id: missing
-status: done
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors[0]?.message).toMatch(/Unknown task_id/);
- });
-
- it("maps status=working to running", async () => {
- const text = `<task_status>
-task_id: task-1
-status: working
-summary: still on it
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({ status: "running" }),
- );
- expect(outcome.task_status_updates[0]).toEqual({
- task_id: "task-1",
- status: "running",
- });
- });
-
- it("maps status=blocked to running (still active, just stalled)", async () => {
- const text = `<task_status>
-task_id: task-1
-status: blocked
-summary: waiting on user
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({ status: "running" }),
- );
- expect(outcome.task_status_updates[0]?.status).toBe("running");
- });
-
- it("maps status=failed to failed and surfaces summary into error_message", async () => {
- const text = `<task_status>
-task_id: task-1
-status: failed
-summary: tag fetch returned 500
-</task_status>`;
- await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({
- status: "failed",
- error_message: "tag fetch returned 500",
- }),
- );
- });
-
- it("uses default error_message when failed status has no summary", async () => {
- const text = `<task_status>
-task_id: task-1
-status: failed
-</task_status>`;
- await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(updateTaskMock).toHaveBeenCalledWith(
- "task-1",
- expect.objectContaining({
- status: "failed",
- error_message: "agent reported failure",
- }),
- );
- });
-
- it.each(["cancelled", "failed", "succeeded"] as const)(
- "skips writes when task is already terminal (%s)",
- async (terminal) => {
- getTaskMock.mockReturnValueOnce({
- id: "task-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- status: terminal,
- });
- const text = `<task_status>
-task_id: task-1
-status: done
-summary: late
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- // No write happens — the existing terminal status is preserved.
- expect(updateTaskMock).not.toHaveBeenCalled();
- // Outcome still reports the existing status for observability.
- expect(outcome.task_status_updates[0]).toEqual({
- task_id: "task-1",
- status: terminal,
- });
- expect(outcome.errors).toHaveLength(0);
- },
- );
-
- it("captures thrown errors from getTask as task_status errors (not exceptions)", async () => {
- getTaskMock.mockImplementationOnce(() => {
- throw new Error("db boom");
- });
- const text = `<task_status>
-task_id: task-1
-status: done
-</task_status>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors).toEqual([
- { kind: "task_status", message: "db boom" },
- ]);
- });
-});
-
-describe("processOrchestrationBlocks — add_comment", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getTaskMock.mockReturnValue({
- id: "task-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- });
-
- it("logs a task_comment agent_action on success", async () => {
- const text = `<add_comment>
-task_id: task-1
-body: Picked up; running the audit now.
-</add_comment>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.comments_added).toEqual([{ task_id: "task-1" }]);
- expect(logAgentActionMock).toHaveBeenCalledWith(
- expect.objectContaining({
- action_type: "task_comment",
- summary: "Picked up; running the audit now.",
- payload: { task_id: "task-1" },
- }),
- );
- expect(outcome.errors).toHaveLength(0);
- });
-
- it("rejects comments on unknown task_id", async () => {
- getTaskMock.mockReturnValueOnce(null);
- const text = `<add_comment>
-task_id: missing
-body: hi
-</add_comment>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.comments_added).toHaveLength(0);
- expect(outcome.errors[0]).toEqual({
- kind: "add_comment",
- message: expect.stringMatching(/Unknown task_id/),
- });
- });
-
- it("rejects cross-project comments", async () => {
- getTaskMock.mockReturnValueOnce({
- id: "task-1",
- project_slug: "OTHER",
- agent_id: "demo-google-ads",
- });
- const text = `<add_comment>
-task_id: task-1
-body: hi
-</add_comment>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors[0]?.message).toMatch(/Cross-project comment/);
- });
-});
-
-describe("processOrchestrationBlocks — ask_user", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getTaskMock.mockReturnValue({
- id: "task-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- });
-
- it("logs an ask_user agent_action anchored to a task", async () => {
- const text = `<ask_user>
-task_id: task-1
-question: What's the daily budget cap?
-options: 50, 100, 250
-</ask_user>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.ask_user).toEqual([
- { task_id: "task-1", question: "What's the daily budget cap?" },
- ]);
- expect(logAgentActionMock).toHaveBeenCalledWith(
- expect.objectContaining({
- action_type: "ask_user",
- summary: "What's the daily budget cap?",
- payload: { task_id: "task-1", options: "50, 100, 250" },
- }),
- );
- });
-
- it("allows an ask_user with no task_id (unanchored)", async () => {
- const text = `<ask_user>
-question: General preference question?
-</ask_user>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-cmo",
- });
- expect(getTaskMock).not.toHaveBeenCalled();
- expect(outcome.ask_user[0]).toEqual({
- task_id: undefined,
- question: "General preference question?",
- });
- expect(logAgentActionMock).toHaveBeenCalledWith(
- expect.objectContaining({
- action_type: "ask_user",
- payload: { task_id: null, options: null },
- }),
- );
- });
-
- it("rejects ask_user on unknown task_id", async () => {
- getTaskMock.mockReturnValueOnce(null);
- const text = `<ask_user>
-task_id: missing
-question: hi?
-</ask_user>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors[0]?.message).toMatch(/Unknown task_id/);
- });
-
- it("rejects cross-project ask_user", async () => {
- getTaskMock.mockReturnValueOnce({
- id: "task-1",
- project_slug: "OTHER",
- agent_id: "demo-google-ads",
- });
- const text = `<ask_user>
-task_id: task-1
-question: hi?
-</ask_user>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors[0]?.message).toMatch(/Cross-project ask_user/);
- });
-});
-
-describe("processOrchestrationBlocks — request_approval", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getTaskMock.mockReturnValue({
- id: "task-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- createApprovalMock.mockImplementation((input) => ({
- id: "approval-1",
- project_slug: input.project_slug,
- agent_id: input.agent_id,
- action_summary: input.action_summary,
- action_type: input.action_type,
- cost_estimate_usd: input.cost_estimate_usd,
- reasoning: input.reasoning ?? null,
- payload_json: JSON.stringify(input.payload ?? {}),
- status: "pending",
- created_at: "now",
- resolved_at: null,
- }));
- });
-
- it("creates an approval row and reports it on the outcome", async () => {
- const text = `<request_approval>
-task_id: task-1
-action_summary: Raise the daily cap on Brand to $200.
-action_type: bid_change
-cost_estimate_usd: 200
-reasoning: Brand is throttled; observed CPC stable.
-</request_approval>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(createApprovalMock).toHaveBeenCalledWith(
- expect.objectContaining({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- action_type: "bid_change",
- cost_estimate_usd: 200,
- reasoning: "Brand is throttled; observed CPC stable.",
- payload: { task_id: "task-1" },
- }),
- );
- expect(outcome.approvals_requested).toEqual([
- { approval_id: "approval-1", action_type: "bid_change" },
- ]);
- });
-
- it("defaults cost_estimate_usd to 0 when not provided", async () => {
- const text = `<request_approval>
-action_summary: Publish a new blog post.
-action_type: content_publishing
-</request_approval>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-cmo",
- });
- expect(createApprovalMock).toHaveBeenCalledWith(
- expect.objectContaining({
- cost_estimate_usd: 0,
- reasoning: null,
- payload: { task_id: null },
- }),
- );
- expect(outcome.approvals_requested).toHaveLength(1);
- });
-
- it("rejects request_approval on unknown task_id", async () => {
- getTaskMock.mockReturnValueOnce(null);
- const text = `<request_approval>
-task_id: missing
-action_summary: x
-action_type: spend
-</request_approval>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors[0]).toEqual({
- kind: "request_approval",
- message: expect.stringMatching(/Unknown task_id/),
- });
- expect(createApprovalMock).not.toHaveBeenCalled();
- });
-
- it("rejects cross-project request_approval", async () => {
- getTaskMock.mockReturnValueOnce({
- id: "task-1",
- project_slug: "OTHER",
- agent_id: "demo-google-ads",
- });
- const text = `<request_approval>
-task_id: task-1
-action_summary: x
-action_type: spend
-</request_approval>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- expect(outcome.errors[0]?.message).toMatch(/Cross-project approval/);
- });
-
- it("captures unexpected createApproval errors as request_approval errors", async () => {
- createApprovalMock.mockImplementationOnce(() => {
- throw new Error("db down");
- });
- const text = `<request_approval>
-action_summary: x
-action_type: spend
-</request_approval>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-cmo",
- });
- expect(outcome.errors).toEqual([
- { kind: "request_approval", message: "db down" },
- ]);
- expect(outcome.approvals_requested).toHaveLength(0);
- });
-
- /**
- * Known open issue: when a specialist emits <request_approval> without a
- * corresponding <task_status status: blocked>, the task stays "running"
- * forever (see MEMORY.md). This test documents the current behavior —
- * processing the approval does NOT also flip the task's status. Marked
- * `.fails` so when the bug is fixed, the test breaks and someone has to
- * decide whether to delete or invert the assertion.
- */
- it.fails(
- "BUG: emitting request_approval alone does not flip the task to blocked",
- async () => {
- const text = `<request_approval>
-task_id: task-1
-action_summary: Raise budget
-action_type: spend
-</request_approval>`;
- await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- });
- // We *expect* the task to be marked blocked/paused once the bug is
- // fixed. Today, no task update happens at all.
- expect(updateTaskMock).toHaveBeenCalled();
- },
- );
-});
-
-describe("processOrchestrationBlocks — create_task error capture", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- templateForKeyMock.mockReturnValue({
- key: "google_ads",
- display_name: "Google Ads",
- });
- agentNameForMock.mockImplementation(
- (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,
- );
- agentExistsMock.mockResolvedValue(true);
- });
-
- it("captures thrown errors from createTask as create_task errors", async () => {
- createTaskMock.mockImplementationOnce(() => {
- throw new Error("constraint violation");
- });
- const text = `<create_task>
-title: A
-assignee: google_ads
-brief: do the thing
-</create_task>`;
- const outcome = await processOrchestrationBlocks(text, {
- project_slug: "demo",
- agent_id: CMO_ID,
- });
- expect(outcome.tasks_created).toHaveLength(0);
- expect(outcome.errors).toEqual([
- { kind: "create_task", message: "constraint violation" },
- ]);
- });
-});
-
-describe("generateTaskThreadId", () => {
- it("returns a UUID-shaped string", () => {
- const id = generateTaskThreadId();
- expect(id).toMatch(
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
- );
- });
-
- it("returns a new UUID on each call", () => {
- const a = generateTaskThreadId();
- const b = generateTaskThreadId();
- expect(a).not.toBe(b);
- });
-});
diff --git a/src/server/orchestration/process-blocks.ts b/src/server/orchestration/process-blocks.ts
deleted file mode 100644
index 394293c2..00000000
--- a/src/server/orchestration/process-blocks.ts
+++ /dev/null
@@ -1,315 +0,0 @@
-import { randomUUID } from "node:crypto";
-
-import { agentExists, agentNameFor, templateForKey, type AgentTemplateKey } from "@/server/agent-templates";
-import { logAgentAction } from "@/server/db/agent-actions";
-import { createApproval } from "@/server/db/approvals";
-import { createTask, getTask, updateTask } from "@/server/db/tasks";
-import type { Task } from "@/types";
-
-import {
- parseAddCommentBlocks,
- parseAskUserBlocks,
- parseCreateTaskBlocks,
- parseRequestApprovalBlocks,
- parseTaskStatusBlocks,
- type AddCommentBlock,
- type AskUserBlock,
- type CreateTaskBlock,
- type RequestApprovalBlock,
- type TaskStatusBlock,
-} from "./blocks";
-
-/**
- * After an assistant turn completes, scan the full reply text for
- * orchestration blocks and apply them. CMO emits <create_task> to spawn
- * work for specialists; specialists emit <task_status> to update progress.
- *
- * Failures are non-fatal — invalid blocks are logged and skipped. The
- * chat itself is unaffected; the user still sees the assistant reply.
- */
-
-export type ProcessContext = {
- project_slug: string;
- /** Agent emitting the blocks. CMO for create_task; specialists for status. */
- agent_id: string;
-};
-
-export type ProcessOutcome = {
- tasks_created: Task[];
- task_status_updates: Array<{ task_id: string; status: string }>;
- comments_added: Array<{ task_id: string }>;
- ask_user: Array<{ task_id?: string; question: string }>;
- approvals_requested: Array<{ approval_id: string; action_type: string }>;
- errors: Array<{ kind: string; message: string }>;
-};
-
-export async function processOrchestrationBlocks(
- text: string,
- context: ProcessContext,
-): Promise<ProcessOutcome> {
- const outcome: ProcessOutcome = {
- tasks_created: [],
- task_status_updates: [],
- comments_added: [],
- ask_user: [],
- approvals_requested: [],
- errors: [],
- };
-
- for (const block of parseCreateTaskBlocks(text)) {
- try {
- const task = await applyCreateTaskBlock(block, context);
- if (task) outcome.tasks_created.push(task);
- } catch (err) {
- outcome.errors.push({
- kind: "create_task",
- message: err instanceof Error ? err.message : String(err),
- });
- }
- }
-
- for (const block of parseTaskStatusBlocks(text)) {
- try {
- const update = applyTaskStatusBlock(block, context);
- if (update) outcome.task_status_updates.push(update);
- } catch (err) {
- outcome.errors.push({
- kind: "task_status",
- message: err instanceof Error ? err.message : String(err),
- });
- }
- }
-
- for (const block of parseAddCommentBlocks(text)) {
- try {
- applyAddCommentBlock(block, context);
- outcome.comments_added.push({ task_id: block.task_id });
- } catch (err) {
- outcome.errors.push({
- kind: "add_comment",
- message: err instanceof Error ? err.message : String(err),
- });
- }
- }
-
- for (const block of parseAskUserBlocks(text)) {
- try {
- applyAskUserBlock(block, context);
- outcome.ask_user.push({ task_id: block.task_id, question: block.question });
- } catch (err) {
- outcome.errors.push({
- kind: "ask_user",
- message: err instanceof Error ? err.message : String(err),
- });
- }
- }
-
- for (const block of parseRequestApprovalBlocks(text)) {
- try {
- const result = applyRequestApprovalBlock(block, context);
- if (result) outcome.approvals_requested.push(result);
- } catch (err) {
- outcome.errors.push({
- kind: "request_approval",
- message: err instanceof Error ? err.message : String(err),
- });
- }
- }
-
- return outcome;
-}
-
-async function applyCreateTaskBlock(
- block: CreateTaskBlock,
- ctx: ProcessContext,
-): Promise<Task | null> {
- // Validate the assignee template exists (allows synonyms like "google-ads"
- // vs "google_ads" via templateForKey's normalization).
- const template = templateForKey(block.assignee);
- if (!template) {
- throw new Error(`Unknown assignee template '${block.assignee}'`);
- }
- if (template.key === "cmo") {
- throw new Error("CMO cannot assign tasks to itself — pick a specialist");
- }
-
- const assigneeAgentId = agentNameFor(ctx.project_slug, template.key as AgentTemplateKey);
- if (!(await agentExists(assigneeAgentId))) {
- throw new Error(
- `Assignee agent ${assigneeAgentId} is not provisioned for this project`,
- );
- }
-
- const task = createTask({
- project_slug: ctx.project_slug,
- agent_id: assigneeAgentId,
- title: block.title,
- brief: block.brief,
- success_criteria: block.success_criteria ?? null,
- assigner_agent_id: ctx.agent_id,
- status: "proposed",
- });
-
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- action_type: "task_created",
- summary: `Created task '${task.title}' for ${template.display_name}.`,
- payload: { task_id: task.id, assignee: assigneeAgentId },
- });
-
- // Auto-start the delegated task. When the CMO emits <create_task>, the
- // user expects work to be in flight immediately — not parked as
- // "proposed" until someone clicks Start. The kickoff is fire-and-forget;
- // status flips proposed → running so the sidebar badge + workspace task
- // list reflect activity on the very next poll cycle.
- // Lazy import to avoid pulling the orchestration → run-task → gateway
- // chain into modules that just want createTask.
- const { startTaskIfProposed } = await import("./run-task");
- return startTaskIfProposed(task);
-}
-
-function applyTaskStatusBlock(
- block: TaskStatusBlock,
- ctx: ProcessContext,
-): { task_id: string; status: string } | null {
- const task = getTask(block.task_id);
- if (!task) {
- throw new Error(`Unknown task_id '${block.task_id}'`);
- }
- if (task.project_slug !== ctx.project_slug) {
- throw new Error(
- `Cross-project task update rejected: task '${block.task_id}' belongs to '${task.project_slug}' but emitter is in '${ctx.project_slug}'`,
- );
- }
- if (task.agent_id !== ctx.agent_id) {
- throw new Error(
- `Only the assignee (${task.agent_id}) can update task '${block.task_id}'; got update from '${ctx.agent_id}'`,
- );
- }
- // Already terminal? Skip — user cancellations + earlier failure updates
- // shouldn't get overwritten by a late "done" from an agent that kept
- // running for a bit after the user moved on.
- if (
- task.status === "cancelled" ||
- task.status === "failed" ||
- task.status === "succeeded"
- ) {
- return { task_id: block.task_id, status: task.status };
- }
-
- // Map the agent's status vocabulary to our TaskStatus enum.
- const newStatus =
- block.status === "working"
- ? ("running" as const)
- : block.status === "done"
- ? ("succeeded" as const)
- : block.status === "blocked"
- ? ("running" as const) // still active, just stalled — caller decides
- : ("failed" as const);
-
- updateTask(block.task_id, {
- status: newStatus,
- result: block.summary ? { summary: block.summary } : undefined,
- error_message: block.status === "failed" ? (block.summary ?? "agent reported failure") : null,
- });
-
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- action_type: `task_${block.status}`,
- summary: block.summary ?? `Task ${block.status}.`,
- payload: { task_id: block.task_id, status: newStatus },
- });
-
- return { task_id: block.task_id, status: newStatus };
-}
-
-/**
- * V1 add_comment handler. Comments live on the agent_actions log keyed by
- * task_id so they're visible in /activity and queryable per task. A
- * dedicated task_comments table can be added in v1.1 if richer threading
- * is needed (paperclip parity).
- */
-function applyAddCommentBlock(
- block: AddCommentBlock,
- ctx: ProcessContext,
-): void {
- const task = getTask(block.task_id);
- if (!task) throw new Error(`Unknown task_id '${block.task_id}'`);
- if (task.project_slug !== ctx.project_slug) {
- throw new Error(`Cross-project comment rejected on task '${block.task_id}'`);
- }
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- action_type: "task_comment",
- summary: block.body,
- payload: { task_id: block.task_id },
- });
-}
-
-/**
- * V1 ask_user handler. Logged to agent_actions; the task detail page can
- * render any pending ask_user from the activity log. V1.1 should wire a
- * dedicated "answer" surface so the user's reply flows back into the
- * agent's next turn (paperclip's ask_user_questions interaction kind).
- */
-function applyAskUserBlock(
- block: AskUserBlock,
- ctx: ProcessContext,
-): void {
- if (block.task_id) {
- const task = getTask(block.task_id);
- if (!task) throw new Error(`Unknown task_id '${block.task_id}'`);
- if (task.project_slug !== ctx.project_slug) {
- throw new Error(`Cross-project ask_user rejected on task '${block.task_id}'`);
- }
- }
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- action_type: "ask_user",
- summary: block.question,
- payload: { task_id: block.task_id ?? null, options: block.options ?? null },
- });
-}
-
-/**
- * V1 request_approval handler. Creates a row in the approvals table that
- * the /approvals page already renders (per the existing inbox UI in
- * CEO Section 11). When the user approves, v1.1 wires the response back
- * to the agent so it can proceed; for V1 the approval is created + the
- * agent waits for the user to act manually.
- */
-function applyRequestApprovalBlock(
- block: RequestApprovalBlock,
- ctx: ProcessContext,
-): { approval_id: string; action_type: string } | null {
- if (block.task_id) {
- const task = getTask(block.task_id);
- if (!task) throw new Error(`Unknown task_id '${block.task_id}'`);
- if (task.project_slug !== ctx.project_slug) {
- throw new Error(`Cross-project approval rejected on task '${block.task_id}'`);
- }
- }
- const approval = createApproval({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- action_summary: block.action_summary,
- action_type: block.action_type,
- cost_estimate_usd: block.cost_estimate_usd ?? 0,
- reasoning: block.reasoning ?? null,
- payload: { task_id: block.task_id ?? null },
- });
- return { approval_id: approval.id, action_type: block.action_type };
-}
-
-/**
- * Generate a UUID for a per-task chat thread. Stable per-call; callers
- * persist it via setTaskThreadIfMissing once they decide to materialize
- * the thread (typically on the first /tasks/[id] page visit).
- */
-export function generateTaskThreadId(): string {
- return randomUUID();
-}
diff --git a/src/server/orchestration/run-task.test.ts b/src/server/orchestration/run-task.test.ts
index bf61fc37..146f85cb 100644
--- a/src/server/orchestration/run-task.test.ts
+++ b/src/server/orchestration/run-task.test.ts
@@ -23,16 +23,18 @@ vi.mock("@/server/openclaw/sessions", () => ({
`agent:${agent}:${thread}`,
}));
-const processOrchestrationBlocksMock = vi.fn();
+// generateTaskThreadId lives on task-kickoff now. Mock just that one symbol
+// while letting the real buildTaskKickoffMessage run — we want to catch
+// contract drift between run-task and the kickoff format.
const generateTaskThreadIdMock = vi.fn(() => "thread-fresh");
-vi.mock("./process-blocks", () => ({
- processOrchestrationBlocks: (...a: unknown[]) =>
- processOrchestrationBlocksMock(...a),
- generateTaskThreadId: () => generateTaskThreadIdMock(),
-}));
-
-// task-kickoff is small + pure — let the real implementation run so we don't
-// silently mask a contract change between run-task and the kickoff message.
+vi.mock("./task-kickoff", async () => {
+ const actual =
+ await vi.importActual<typeof import("./task-kickoff")>("./task-kickoff");
+ return {
+ ...actual,
+ generateTaskThreadId: () => generateTaskThreadIdMock(),
+ };
+});
import { runTaskKickoffServerSide, startTaskIfProposed } from "./run-task";
@@ -120,22 +122,13 @@ describe("startTaskIfProposed", () => {
describe("runTaskKickoffServerSide", () => {
beforeEach(() => {
vi.clearAllMocks();
- processOrchestrationBlocksMock.mockResolvedValue({
- tasks_created: [],
- task_status_updates: [],
- comments_added: [],
- ask_user: [],
- approvals_requested: [],
- errors: [],
- });
});
- it("consumes the gateway stream, accumulates deltas, and forwards them to orchestration", async () => {
+ it("consumes the gateway stream and passes the kickoff message + session context", async () => {
streamChatViaGatewayMock.mockImplementation(() =>
eventStream([
- { kind: "delta", text: "On it. " },
- { kind: "delta", text: "Wrapping up.\n" },
- { kind: "delta", text: "<task_status>\ntask_id: task-1\nstatus: done\n</task_status>" },
+ { kind: "delta", text: "On it." },
+ { kind: "delta", text: " Wrapping up." },
]),
);
@@ -152,14 +145,10 @@ describe("runTaskKickoffServerSide", () => {
message: expect.stringContaining("Add the Google Ads conversion tag."),
}),
);
- expect(call?.[0].message).toContain("Task ID: task-1");
-
- // Orchestration sees the full accumulated buffer and the correct context.
- expect(processOrchestrationBlocksMock).toHaveBeenCalledWith(
- "On it. Wrapping up.\n<task_status>\ntask_id: task-1\nstatus: done\n</task_status>",
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
+ expect(call?.[0].message).toContain("task_id: task-1");
+ // run-task no longer post-processes the buffer — side effects now happen
+ // via MCP tool calls during the stream.
expect(updateTaskMock).not.toHaveBeenCalled();
});
@@ -190,7 +179,7 @@ describe("runTaskKickoffServerSide", () => {
expect(streamChatViaGatewayMock).not.toHaveBeenCalled();
});
- it("on gateway error event: marks task failed and skips orchestration", async () => {
+ it("on gateway error event: marks task failed with the gateway's message", async () => {
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
streamChatViaGatewayMock.mockImplementation(() =>
eventStream([
@@ -208,7 +197,6 @@ describe("runTaskKickoffServerSide", () => {
error_message: "gateway exploded",
}),
);
- expect(processOrchestrationBlocksMock).not.toHaveBeenCalled();
errSpy.mockRestore();
});
@@ -252,7 +240,7 @@ describe("runTaskKickoffServerSide", () => {
errSpy.mockRestore();
});
- it("skips orchestration entirely when the buffered text is blank", async () => {
+ it("no-ops cleanly when the stream is blank (no failure update)", async () => {
streamChatViaGatewayMock.mockImplementation(() =>
eventStream([
{ kind: "delta", text: " " },
@@ -260,25 +248,9 @@ describe("runTaskKickoffServerSide", () => {
]),
);
await runTaskKickoffServerSide(makeTask());
- expect(processOrchestrationBlocksMock).not.toHaveBeenCalled();
expect(updateTaskMock).not.toHaveBeenCalled();
});
- it("logs but does not rethrow when orchestration processing itself fails", async () => {
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- streamChatViaGatewayMock.mockImplementation(() =>
- eventStream([{ kind: "delta", text: "hello" }]),
- );
- processOrchestrationBlocksMock.mockRejectedValue(new Error("parse boom"));
-
- await expect(runTaskKickoffServerSide(makeTask())).resolves.toBeUndefined();
- expect(errSpy).toHaveBeenCalledWith(
- expect.stringContaining("orchestration processing failed"),
- expect.any(Error),
- );
- errSpy.mockRestore();
- });
-
it("keeps the existing thread_id when the task already has one (no lazy mint)", async () => {
streamChatViaGatewayMock.mockImplementation(() => eventStream([]));
await runTaskKickoffServerSide(makeTask({ thread_id: "thread-existing" }));
diff --git a/src/server/orchestration/run-task.ts b/src/server/orchestration/run-task.ts
index 26788abe..3fe472a4 100644
--- a/src/server/orchestration/run-task.ts
+++ b/src/server/orchestration/run-task.ts
@@ -5,8 +5,10 @@ import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
import { claimProposedTask, setTaskThreadIfMissing, updateTask } from "@/server/db/tasks";
import type { Task } from "@/types";
-import { generateTaskThreadId, processOrchestrationBlocks } from "./process-blocks";
-import { buildTaskKickoffMessage } from "./task-kickoff";
+import {
+ buildTaskKickoffMessage,
+ generateTaskThreadId,
+} from "./task-kickoff";
/**
* Idempotent "claim and kickoff" — atomically flips a proposed task to
@@ -55,14 +57,16 @@ export async function runTaskKickoffServerSide(task: Task): Promise<void> {
const sessionKey = buildPendingSessionKey(finalTask.agent_id, finalTask.thread_id);
const kickoffMessage = buildTaskKickoffMessage(finalTask);
- let buffer = "";
+ // We drain the stream so the agent's turn fully runs, but we no longer
+ // post-process the buffer for pseudo-XML blocks — any side effects
+ // (task_status, comments, approvals) happen via the agent calling
+ // notfair-orchestration MCP tools mid-stream.
try {
for await (const evt of streamChatViaGateway({
sessionKey,
sessionId: finalTask.thread_id,
message: kickoffMessage,
})) {
- if (evt.kind === "delta") buffer += evt.text;
if (evt.kind === "error") {
throw new Error(evt.message);
}
@@ -74,20 +78,5 @@ export async function runTaskKickoffServerSide(task: Task): Promise<void> {
status: "failed",
error_message: message,
});
- return;
- }
-
- if (buffer.trim().length > 0) {
- try {
- await processOrchestrationBlocks(buffer, {
- project_slug: finalTask.project_slug,
- agent_id: finalTask.agent_id,
- });
- } catch (err) {
- console.error(
- `[run-task] orchestration processing failed for ${finalTask.id}:`,
- err,
- );
- }
}
}
diff --git a/src/server/orchestration/task-kickoff.test.ts b/src/server/orchestration/task-kickoff.test.ts
index 1ad9f496..e60b851a 100644
--- a/src/server/orchestration/task-kickoff.test.ts
+++ b/src/server/orchestration/task-kickoff.test.ts
@@ -34,8 +34,10 @@ describe("buildTaskKickoffMessage", () => {
it("includes the canonical task fields in a stable order", () => {
const msg = buildTaskKickoffMessage(makeTask());
// Each piece appears, and the brief comes before success criteria.
- expect(msg).toContain("Task ID: task-123");
- expect(msg).toContain("Title: Install conversion tracking");
+ expect(msg).toContain("task_id: task-123");
+ expect(msg).toContain("project_slug: demo");
+ expect(msg).toContain("agent_id: demo-google-ads");
+ expect(msg).toContain("Title: Install conversion tracking");
expect(msg).toContain("Brief:");
expect(msg).toContain("Add the Google Ads conversion tag to /thanks.");
expect(msg).toContain("Success criteria:");
@@ -47,7 +49,7 @@ describe("buildTaskKickoffMessage", () => {
it("falls back to '(untitled)' when title is null", () => {
const msg = buildTaskKickoffMessage(makeTask({ title: null }));
- expect(msg).toContain("Title: (untitled)");
+ expect(msg).toContain("Title: (untitled)");
});
it("omits the Success criteria section entirely when success_criteria is null", () => {
@@ -59,32 +61,26 @@ describe("buildTaskKickoffMessage", () => {
expect(msg).toContain("Acknowledge this task");
});
- it("teaches the agent the <task_status> done emission contract with the right task_id", () => {
- const msg = buildTaskKickoffMessage(makeTask({ id: "task-xyz" }));
- expect(msg).toContain("<task_status>");
- expect(msg).toContain("task_id: task-xyz");
- expect(msg).toContain("status: done");
- expect(msg).toContain("</task_status>");
- });
-
- it("mentions the blocked/ask_user/request_approval escape hatches so agents know how to bail", () => {
+ it("tells the agent to actually use its tools, not just describe, and to close out when done", () => {
const msg = buildTaskKickoffMessage(makeTask());
- expect(msg).toMatch(/status:\s*blocked/);
- expect(msg).toContain("<ask_user>");
- expect(msg).toContain("<add_comment>");
- expect(msg).toContain("<request_approval>");
+ expect(msg).toContain("Use your domain tools");
+ expect(msg).toContain("don't just describe what you'd do");
+ expect(msg).toMatch(/close the task out/i);
});
- it("tells the agent to actually use its tools, not just describe", () => {
+ it("does NOT re-teach the MCP tool surface — that's the system prompt's job", () => {
const msg = buildTaskKickoffMessage(makeTask());
- expect(msg).toContain("Use your tools");
- expect(msg).toContain("don't just describe what you'd do");
+ // Schema-shaped lines like `status: "done"` belong in the system prompt;
+ // every brief shouldn't duplicate them. Same for the pseudo-XML rule.
+ expect(msg).not.toMatch(/status:\s*"done"/);
+ expect(msg).not.toMatch(/do NOT emit/i);
+ expect(msg).not.toContain("not parsed");
});
it("returns a multi-line string (joined with \\n, not \\r\\n)", () => {
const msg = buildTaskKickoffMessage(makeTask());
expect(msg).not.toContain("\r");
- expect(msg.split("\n").length).toBeGreaterThan(10);
+ expect(msg.split("\n").length).toBeGreaterThan(6);
});
it("preserves multi-line brief content verbatim", () => {
diff --git a/src/server/orchestration/task-kickoff.ts b/src/server/orchestration/task-kickoff.ts
index 8c6cb79f..74935165 100644
--- a/src/server/orchestration/task-kickoff.ts
+++ b/src/server/orchestration/task-kickoff.ts
@@ -1,5 +1,18 @@
+import { randomUUID } from "node:crypto";
+
import type { Task } from "@/types";
+/**
+ * Generate a UUID for a per-task chat thread. Stable per-call; callers
+ * persist it via setTaskThreadIfMissing once they decide to materialize
+ * the thread (typically on the first /tasks/[id] page visit, or when
+ * approval-wakeup needs to push a system message into a task that's
+ * never been opened in the UI).
+ */
+export function generateTaskThreadId(): string {
+ return randomUUID();
+}
+
/**
* Build the hidden kickoff message the assignee receives on first open of
* a task's per-task chat thread. Carries the brief + operating
@@ -14,8 +27,10 @@ export function buildTaskKickoffMessage(task: Task): string {
const lines: string[] = [
"(task assignment)",
"",
- `Task ID: ${task.id}`,
- `Title: ${task.title ?? "(untitled)"}`,
+ `project_slug: ${task.project_slug}`,
+ `agent_id: ${task.agent_id}`,
+ `task_id: ${task.id}`,
+ `Title: ${task.title ?? "(untitled)"}`,
"",
"Brief:",
task.brief,
@@ -26,21 +41,9 @@ export function buildTaskKickoffMessage(task: Task): string {
}
lines.push(
"Acknowledge this task in 1-2 sentences (what you'll do + roughly how",
- "long), then start working. Use your tools (MCP, exec, etc.) to actually",
- "do the thing — don't just describe what you'd do.",
- "",
- "When the task is complete, emit at the END of your reply:",
- "",
- "<task_status>",
- `task_id: ${task.id}`,
- "status: done",
- "summary: <one line on what you did>",
- "</task_status>",
- "",
- "If you hit a real blocker, emit status: blocked + an <ask_user> or",
- "<add_comment> to the CMO. If you need user sign-off on a governed",
- "action (spend, content publish, bid change), use <request_approval>",
- "before executing.",
+ "long), then start working. Use your domain tools to actually do the",
+ "thing — don't just describe what you'd do. Close the task out when",
+ "you're done.",
);
return lines.join("\n");
}
diff --git a/src/types/index.ts b/src/types/index.ts
index e6ced44c..0fb7a93e 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -20,16 +20,22 @@ export type TaskStatus =
| "proposed"
| "approved"
| "running"
+ | "blocked"
| "succeeded"
| "failed"
| "cancelled";
// ┌──────────┐ user approves ┌──────────┐ agent picks up ┌─────────┐
-// │ proposed │ ─────────────────────────────▶│ approved │ ────────────────▶│ running │
-// └──────────┘ needs_approval └──────────┘ └────┬────┘
-// │ ▲ │
-// │ └── user approves from inbox ──────────────────────────────┐ │
-// │ │ ▼
+// │ proposed │ ─────────────────────────────▶│ approved │ ────────────────▶│ running │◀─┐
+// └──────────┘ needs_approval └──────────┘ └────┬────┘ │
+// │ ▲ │ │
+// │ └── user approves from inbox ──────────────────────────────┐ │ │
+// │ │ ▼ │
+// │ ┌───────────────┐ │
+// │ │ blocked │────────┘
+// │ └───────────────┘ approval resolved
+// │ │
+// │ ▼
// │ ┌───────────────┐
// └─ user/CMO cancels ───────────────────────────────────▶│ cancelled / failed / succeeded │
// └───────────────┘
@@ -70,7 +76,12 @@ export type Task = {
updated_at: string;
};
-export type ApprovalStatus = "pending" | "approved" | "rejected" | "expired";
+export type ApprovalStatus =
+ | "pending"
+ | "revision_requested"
+ | "approved"
+ | "rejected"
+ | "expired";
export type ApprovalType =
| "spend"
@@ -80,20 +91,59 @@ export type ApprovalType =
| "audience_change"
| "other";
+/** Who made the decision on an approval. 'policy' = auto-decided by a rule. */
+export type ApprovalDecidedByKind = "user" | "agent" | "policy";
+
+/** Author of a comment on an approval thread. 'system' = automated note. */
+export type ApprovalCommentAuthorKind = "user" | "agent" | "system";
+
export type Approval = {
id: string;
project_slug: string;
agent_id: string;
+ /** Task this approval is gating, if any. Filled when the agent emits
+ * <request_approval> inside a task context; null for free-standing asks. */
+ task_id: string | null;
action_summary: string;
action_type: ApprovalType;
cost_estimate_usd: number;
reasoning: string | null;
payload_json: string;
status: ApprovalStatus;
+ /** Free-text reason the decider attached on resolve/revision_requested. */
+ decision_note: string | null;
+ decided_by_kind: ApprovalDecidedByKind | null;
+ decided_by_id: string | null;
created_at: string;
resolved_at: string | null;
};
+export type ApprovalComment = {
+ id: string;
+ approval_id: string;
+ author_kind: ApprovalCommentAuthorKind;
+ author_id: string | null;
+ body: string;
+ created_at: string;
+};
+
+/** "Always allow / reject" rule consulted before a pending approval is created.
+ * Matches by (project_slug, action_type) + optional agent_id + optional cost cap. */
+export type ApprovalPolicy = {
+ id: string;
+ project_slug: string;
+ action_type: ApprovalType;
+ /** Restrict to a single agent. Null = applies to any agent in the project. */
+ agent_id: string | null;
+ /** Maximum cost the policy auto-decides for. Null = no cap. */
+ max_cost_usd: number | null;
+ auto_decision: "approve" | "reject";
+ note: string | null;
+ created_at: string;
+ created_by_kind: "user" | "agent";
+ created_by_id: string | null;
+};
+
export type CostEventSource = "llm" | "google_ads" | "gsc" | "other";
export type CostEvent = {