Open-source SEO, GEO, and marketing skills for AI agents.
feat(orchestration): CMO becomes orchestrator — paperclip-style tool surface
Yuting Zhong3f5ee5fc460f
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.tsindex 459c31c5..5ae9c580 100644--- a/src/app/api/chat/route.ts+++ b/src/app/api/chat/route.ts@@ -6,6 +6,7 @@ import {buildPendingSessionKey,findSessionBySessionId,} from "@/server/openclaw/sessions";+import { processOrchestrationBlocks } from "@/server/orchestration/process-blocks";export const dynamic = "force-dynamic";export const runtime = "nodejs";@@ -119,6 +120,7 @@ export async function POST(request: Request) {request.signal?.addEventListener("abort", () => abortCtl.abort(), { once: true });let firstSseDeltaSent = false;+ let assistantBuffer = "";try {perf.mark("stream_start");send("meta", {@@ -139,6 +141,7 @@ export async function POST(request: Request) {firstSseDeltaSent = true;perf.mark("first_sse_delta_sent");}+ assistantBuffer += evt.text;send("text", { chunk: evt.text });} else if (evt.kind === "tool") {// tool start/update/result — keyed by toolCallId so the client@@ -157,6 +160,46 @@ export async function POST(request: Request) {// "final" implicitly ends the loop after; no separate signal needed.}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);+ }+ }+send("perf", { marks: perf.summary() });send("done", {});} catch (err) {diff --git a/src/components/agent-chat.tsx b/src/components/agent-chat.tsxindex 58259660..4407cb25 100644--- a/src/components/agent-chat.tsx+++ b/src/components/agent-chat.tsx@@ -2,6 +2,7 @@import { useEffect, useLayoutEffect, useMemo, useRef, useState, useTransition } from "react";import { useRouter } from "next/navigation";+import Link from "next/link";import {Send,AlertCircle,@@ -13,10 +14,15 @@ import {Edit3,Globe,Wrench,+ ListChecks,+ MessageSquare,+ HelpCircle,+ Shield,} from "lucide-react";import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";import { toast } from "sonner";+import { stripOrchestrationBlocks } from "@/server/orchestration/blocks";import {filterSlashCommands,executeLocalSlashCommand,@@ -37,6 +43,15 @@ type Step = {phase: "start" | "update" | "result";};+type OrchestrationOutcome = {+ tasks_created: Array<{ id: string; title: string | null; assignee: string; status: string }>;+ 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 }>;+};+type Message = {id: string;role: "user" | "assistant" | "error";@@ -47,6 +62,13 @@ type Message = {* staring at "thinking…". Empty on user/error rows.*/steps?: Step[];+ /**+ * Structured orchestration outcome the server extracted from the+ * assistant's reply (tasks created, status updates, etc.). Rendered as+ * a small summary card below the assistant text. Stripped from the+ * Markdown body so the user doesn't see raw <create_task> tags.+ */+ orchestration?: OrchestrationOutcome;};export type InitialMessage = {@@ -373,6 +395,27 @@ export function AgentChat({),);toast.error(formatAgentError(msg));+ } else if (evt === "orchestration") {+ // Server extracted orchestration blocks from the agent's reply+ // and turned them into DB rows. Attach the outcome to this+ // assistant message so the UI can render a summary card below+ // the prose ("Created 3 tasks · View tasks →").+ const outcome = data as OrchestrationOutcome;+ setMessages((m) =>+ m.map((m2) =>+ m2.id === assistantId ? { ...m2, orchestration: outcome } : m2,+ ),+ );+ // Toast tasks_created so the user notices even if they're not+ // looking at the chat surface right now.+ if (outcome.tasks_created.length > 0) {+ toast.success(+ `Created ${outcome.tasks_created.length} task${outcome.tasks_created.length === 1 ? "" : "s"} for the specialist.`,+ );+ // Force the /tasks route to refetch since it's a server component+ // and won't auto-update otherwise.+ startTransition(() => router.refresh());+ }}}}@@ -587,9 +630,13 @@ function MessageRow({// Plain text falls through unchanged because markdown is a superset. While// streaming, partial markdown (e.g. an unclosed fence) is rendered as far as// remark can parse it — visually fine because the next chunk arrives within- // milliseconds.+ // milliseconds. Orchestration blocks (<create_task> etc.) are stripped before+ // rendering so the user sees clean prose, not raw tags.const hasSteps = (message.steps?.length ?? 0) > 0;- const isEmpty = message.body === "";+ // Strip orchestration tags as text streams in — during streaming partially-+ // received tags briefly render then disappear once their closing tag arrives.+ const cleanBody = stripOrchestrationBlocks(message.body);+ const isEmpty = cleanBody === "";return (<div className="group space-y-2">{hasSteps && <StepList steps={message.steps!} />}@@ -600,12 +647,123 @@ function MessageRow({</div>)) : (- <Markdown>{message.body}</Markdown>+ <Markdown>{cleanBody}</Markdown>)}+ {message.orchestration && <OrchestrationSummary outcome={message.orchestration} />}</div>);}+function OrchestrationSummary({ outcome }: { outcome: OrchestrationOutcome }) {+ const items: React.ReactNode[] = [];+ if (outcome.tasks_created.length > 0) {+ items.push(+ <div key="tasks" className="flex items-start gap-2 text-xs">+ <ListChecks className="mt-0.5 size-3.5 shrink-0 text-emerald-600" aria-hidden />+ <div className="min-w-0">+ <div className="font-medium text-foreground">+ Created {outcome.tasks_created.length} task+ {outcome.tasks_created.length === 1 ? "" : "s"}+ </div>+ <ul className="mt-0.5 space-y-0.5">+ {outcome.tasks_created.map((t) => (+ <li key={t.id} className="text-muted-foreground">+ <Link+ href={`/tasks/${t.id}`}+ className="hover:text-foreground hover:underline"+ >+ {t.title ?? t.id.slice(0, 8)}+ </Link>{" "}+ <span className="text-[10px] tabular-nums">→ {t.assignee}</span>+ </li>+ ))}+ </ul>+ </div>+ </div>,+ );+ }+ if (outcome.task_status_updates.length > 0) {+ items.push(+ <div key="status" className="flex items-start gap-2 text-xs">+ <CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-emerald-600" aria-hidden />+ <div>+ <div className="font-medium text-foreground">+ Updated {outcome.task_status_updates.length} task status+ {outcome.task_status_updates.length === 1 ? "" : "es"}+ </div>+ <ul className="mt-0.5 space-y-0.5 text-muted-foreground">+ {outcome.task_status_updates.map((u) => (+ <li key={u.task_id}>+ <Link+ href={`/tasks/${u.task_id}`}+ className="hover:text-foreground hover:underline"+ >+ {u.task_id.slice(0, 8)}+ </Link>{" "}+ → {u.status}+ </li>+ ))}+ </ul>+ </div>+ </div>,+ );+ }+ if (outcome.comments_added.length > 0) {+ items.push(+ <div key="comments" className="flex items-start gap-2 text-xs text-muted-foreground">+ <MessageSquare className="mt-0.5 size-3.5 shrink-0" aria-hidden />+ <div>+ Posted {outcome.comments_added.length} comment+ {outcome.comments_added.length === 1 ? "" : "s"} on existing task+ {outcome.comments_added.length === 1 ? "" : "s"}.+ </div>+ </div>,+ );+ }+ if (outcome.ask_user.length > 0) {+ items.push(+ <div key="ask" className="flex items-start gap-2 text-xs text-amber-700 dark:text-amber-400">+ <HelpCircle className="mt-0.5 size-3.5 shrink-0" aria-hidden />+ <div>+ {outcome.ask_user.length === 1+ ? "Waiting on your answer"+ : `Waiting on your answer on ${outcome.ask_user.length} questions`}{" "}+ — view in /activity.+ </div>+ </div>,+ );+ }+ if (outcome.approvals_requested.length > 0) {+ items.push(+ <div key="approval" className="flex items-start gap-2 text-xs text-amber-700 dark:text-amber-400">+ <Shield className="mt-0.5 size-3.5 shrink-0" aria-hidden />+ <div>+ Requested {outcome.approvals_requested.length} approval+ {outcome.approvals_requested.length === 1 ? "" : "s"} —{" "}+ <Link href="/approvals" className="hover:text-foreground hover:underline">+ review in /approvals+ </Link>+ .+ </div>+ </div>,+ );+ }+ if (outcome.errors.length > 0) {+ items.push(+ <div key="errors" className="flex items-start gap-2 text-xs text-destructive">+ <AlertCircle className="mt-0.5 size-3.5 shrink-0" aria-hidden />+ <div>+ {outcome.errors.length} orchestration block{outcome.errors.length === 1 ? "" : "s"} failed to apply.+ </div>+ </div>,+ );+ }+ if (items.length === 0) return null;+ return (+ <div className="space-y-2 rounded-md border bg-muted/30 px-3 py-2.5">{items}</div>+ );+}+function StepList({ steps }: { steps: Step[] }) {return (<div className="space-y-1 rounded-md border bg-muted/30 px-3 py-2">diff --git a/src/server/agent-templates.ts b/src/server/agent-templates.tsindex 2ee9ed77..22529396 100644--- a/src/server/agent-templates.ts+++ b/src/server/agent-templates.ts@@ -13,6 +13,220 @@ import { writeAgentMeta } from "@/server/agent-meta";* what makes the cron tab in the UI parse and group cleanly. Drift here =* cron lands in "ungrouped" bucket. Strong prompt + examples = compliance.*/+/**+ * CMO ORCHESTRATOR PROMPT. The CMO does NOT do hands-on Google Ads work.+ * Its job is to plan, decompose, delegate. It speaks to the user briefly,+ * then emits structured blocks that the platform turns into real DB rows+ * (tasks, approvals, comments).+ *+ * Block tool surface (mirrors paperclip's orchestrator MCP — createIssue,+ * updateIssue, addComment, askUserQuestions, createApproval):+ *+ * <create_task> spawn a task for a specialist+ * <add_comment> post a comment on an existing task (talk to the specialist)+ * <ask_user> block on a user answer+ * <request_approval> queue an approval request before a governed action+ *+ * Specialists have their own block surface (<task_status>) for reporting+ * progress. CMO does NOT emit <task_status> — that's for the assignee.+ */+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+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 tool surface (structured blocks)++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.++### <create_task> — spawn a task for a specialist++<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>++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.++## What you do NOT do++- You do NOT call MCP tools directly. Specialists do that.+- You do NOT emit <task_status> blocks — only the assignee can.+- You do NOT chat-thread with the user about ad operations. If the user+ asks about ad-level details, create a task for the Google Ads+ specialist and let them respond on that task.++## After audit (FIRST_TURN.md context)++When FIRST_TURN.md is present, the audit just completed. Your job:++1. Greet the user (1-2 sentences) referencing the top finding by name ++ dollar figure if there is one. If the account is small/empty, name+ the snapshot directly.+2. Immediately emit <create_task> blocks for the "Recommended ongoing+ work" items in FIRST_TURN.md. Each playbook item becomes ONE task+ assigned to google_ads.+3. End with one short sentence: "I've handed these to your Google Ads+ specialist — open /tasks to follow along."+4. Do NOT ask "want me to..." — you're an orchestrator, just delegate.+`;++/**+ * SPECIALIST PROMPT. Embedded in specialist agent system prompts. Teaches+ * the worker how to receive assigned tasks (TASK_BRIEF.md sentinel),+ * acknowledge, work, and report status back to the CMO.+ */+const SPECIALIST_TASK_PROMPT = `## You are a specialist worker++You receive tasks from the CMO via TASK_BRIEF.md in your workspace, do+the hands-on work using your tools (MCP, exec, etc.), and report back.++## TASK_BRIEF.md kickoff++When a fresh chat session starts in your workspace, FIRST check for+TASK_BRIEF.md. If present:++1. Read it — it contains the task id, title, brief, success criteria.+2. Acknowledge the task (1-2 sentences) — what you're going to do and+ roughly how long.+3. Move TASK_BRIEF.md to MEMORY/last-task-brief-<task_id>.md so you+ don't re-read it on the next chat turn.+4. Start working. Use your tools to actually do the thing.+5. When done, emit <task_status> at the end of your reply.++If TASK_BRIEF.md is NOT present, greet the user normally — do not+fabricate a task.++## Your tool surface (structured blocks)++### <task_status> — report progress on YOUR assigned task++<task_status>+task_id: <uuid from your TASK_BRIEF.md>+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>++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).++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.++### <add_comment> — talk back to the CMO on this task++<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>++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>.++### <ask_user> — when you need the user, not the CMO++<ask_user>+task_id: <uuid>+question: What's your average customer LTV? I need it to set a+ conversion value.+</ask_user>++Use only when the answer can't come from the CMO or from your tools.++### <request_approval> — before a governed action++<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>++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.++## Your tool surface (existing OpenClaw tools)++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++Use the tools first to actually DO the work. The blocks above are for+reporting + collaboration.+`;+/*** Embedded in CMO + Google Ads agent system prompts. Two purposes:* 1. (D19) Read a one-shot FIRST_TURN.md sentinel file if present at the@@ -165,9 +379,12 @@ export const TEMPLATES: AgentTemplate[] = [model: "openai-codex/gpt-5.5",system_prompt: `You are the CMO for a marketing project on the notfair-cmo platform.-Your job: be a thoughtful chief marketing officer. Help the user think through-strategy, propose experiments, prioritize channels, and (when asked) schedule recurring-work for the specialist agents you coordinate.+You are an ORCHESTRATOR. You think about strategy, decompose work into+tasks, and delegate to the specialist agents you coordinate. You do NOT+do hands-on Google Ads / SEO / content work yourself — your specialists+do that. Your job is to plan + delegate + supervise.++${CMO_ORCHESTRATOR_PROMPT}${SCHEDULE_RECURRING_WORK_SYSTEM_PROMPT}@@ -176,7 +393,10 @@ ${FIRST_TURN_AND_PROPOSE_CRON_PROMPT}Style:- Lead with the point. Be specific. Reference real numbers and channel realities.- Don't waffle. Recommendations beat options. The user can push back.-- When a user asks for recurring work, USE the tool. Don't just describe what you'd schedule.`,+- Short prose, structured blocks at the end. Don't explain what a block+ will do — just emit it. The platform shows the user what got created.+- When delegating, write briefs the way a real marketing director would —+ state the goal, the context, the expected output, the constraints.`,},{key: "google_ads",@@ -193,17 +413,21 @@ Style:model: "openai-codex/gpt-5.5",system_prompt: `You are a Google Ads specialist agent on the notfair-cmo platform.-You handle Google Ads work: campaigns, keywords, bids, budgets, search terms,-negatives. When the notfair-googleads MCP is connected, use it for live account-operations.+You are a WORKER. You receive tasks from the CMO via TASK_BRIEF.md in+your workspace, do the hands-on Google Ads work (campaigns, keywords,+bids, budgets, search terms, negatives, MCP queries), and report+results back. When the notfair-googleads MCP is connected, use it for+live account operations.++${SPECIALIST_TASK_PROMPT}${SCHEDULE_RECURRING_WORK_SYSTEM_PROMPT}${FIRST_TURN_AND_PROPOSE_CRON_PROMPT}-Schedule yourself for recurring jobs the user asks for: hourly metric pulls, daily-bid optimization, weekly negative keyword reviews. Use specialist_agent_type:"google_ads"-when scheduling work for yourself.`,+Schedule yourself for recurring jobs the CMO requests: hourly metric+pulls, daily bid optimization, weekly negative keyword reviews. Use+specialist_agent_type:"google_ads" when scheduling work for yourself.`,},{key: "seo",diff --git a/src/server/db/migrations.ts b/src/server/db/migrations.tsindex f5bd96e6..e0f6a430 100644--- a/src/server/db/migrations.ts+++ b/src/server/db/migrations.ts@@ -127,6 +127,27 @@ CREATE TABLE IF NOT EXISTS sequence_runs (-- to pick one and persists it here so the audit + later automation always-- target the right account.ALTER TABLE projects ADD COLUMN google_ads_account_id TEXT;+`,+ },+ {+ name: "003_tasks_orchestration.sql",+ sql: `+-- Tasks gain three columns to power the autonomous CMO orchestrator:+--+-- title — short label distinct from the long brief, shown+-- on /tasks cards + task detail header.+-- thread_id — the OpenClaw chat session id this task's+-- per-task thread runs under. The assignee picks+-- up the task in this thread (TASK_BRIEF.md+-- kickoff). Null until the user (or the CMO+-- autonomously) opens the detail page; populated+-- once and immutable.+-- assigner_agent_id — who created this task. CMO assigns to specialists;+-- in v1.1 specialists can create sub-tasks and+-- this lets us walk the chain back to the planner.+ALTER TABLE tasks ADD COLUMN title TEXT;+ALTER TABLE tasks ADD COLUMN thread_id TEXT;+ALTER TABLE tasks ADD COLUMN assigner_agent_id TEXT;`,},];diff --git a/src/server/db/migrations/003_tasks_orchestration.sql b/src/server/db/migrations/003_tasks_orchestration.sqlnew file mode 100644index 00000000..8f3fa464--- /dev/null+++ b/src/server/db/migrations/003_tasks_orchestration.sql@@ -0,0 +1,16 @@+-- Tasks gain three columns to power the autonomous CMO orchestrator:+--+-- title — short label distinct from the long brief, shown+-- on /tasks cards + task detail header.+-- thread_id — the OpenClaw chat session id this task's+-- per-task thread runs under. The assignee picks+-- up the task in this thread (TASK_BRIEF.md+-- kickoff). Null until the user (or the CMO+-- autonomously) opens the detail page; populated+-- once and immutable.+-- assigner_agent_id — who created this task. CMO assigns to specialists;+-- in v1.1 specialists can create sub-tasks and+-- this lets us walk the chain back to the planner.+ALTER TABLE tasks ADD COLUMN title TEXT;+ALTER TABLE tasks ADD COLUMN thread_id TEXT;+ALTER TABLE tasks ADD COLUMN assigner_agent_id TEXT;diff --git a/src/server/db/tasks.ts b/src/server/db/tasks.tsindex f502f82d..e47882cc 100644--- a/src/server/db/tasks.ts+++ b/src/server/db/tasks.ts@@ -4,11 +4,16 @@ import type { Task, TaskStatus } from "@/types";export type CreateTaskInput = {project_slug: string;+ /** Assignee — the agent expected to do the work. */agent_id: string;+ /** Short label for the kanban card. Optional but recommended. */+ title?: string | null;brief: string;success_criteria?: string | null;deadline_iso?: string | null;status?: TaskStatus;+ /** Agent that created this task. CMO is the typical originator. */+ assigner_agent_id?: string | null;};export function createTask(input: CreateTaskInput): Task {@@ -18,33 +23,59 @@ export function createTask(input: CreateTaskInput): Task {id: randomUUID(),project_slug: input.project_slug,agent_id: input.agent_id,+ title: input.title ?? null,brief: input.brief,success_criteria: input.success_criteria ?? null,deadline_iso: input.deadline_iso ?? null,status: input.status ?? "proposed",result_json: null,error_message: null,+ thread_id: null,+ assigner_agent_id: input.assigner_agent_id ?? null,created_at: now,updated_at: now,};db.prepare(`INSERT INTO tasks- (id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?)`,+ (id, project_slug, agent_id, title, brief, success_criteria, deadline_iso,+ status, result_json, error_message, thread_id, assigner_agent_id, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?, ?)`,).run(task.id,task.project_slug,task.agent_id,+ task.title,task.brief,task.success_criteria,task.deadline_iso,task.status,+ task.assigner_agent_id,task.created_at,task.updated_at,);return task;}+/**+ * Lazily set the OpenClaw chat session id for this task. Called the first+ * time someone opens /tasks/[id] — the thread_id is generated then and+ * remains stable forever after so the per-task chat history persists.+ * No-op when the task already has a thread_id assigned.+ */+export function setTaskThreadIfMissing(+ id: string,+ thread_id: string,+): Task | null {+ const db = getDb();+ const current = getTask(id);+ if (!current) return null;+ if (current.thread_id) return current;+ db.prepare(+ "UPDATE tasks SET thread_id = ?, updated_at = ? WHERE id = ? AND thread_id IS NULL",+ ).run(thread_id, new Date().toISOString(), id);+ return getTask(id);+}+export function getTask(id: string): Task | null {const db = getDb();const row = db.prepare("SELECT * FROM tasks WHERE id = ?").get(id);diff --git a/src/server/onboarding/audit.ts b/src/server/onboarding/audit.tsindex d69275b8..2464428f 100644--- a/src/server/onboarding/audit.ts+++ b/src/server/onboarding/audit.ts@@ -962,49 +962,55 @@ function renderFirstTurn(if (nextSteps.length > 0) {lines.push(- "## Recommended ongoing work (think like an agency)",+ "## Recommended ongoing work — DELEGATE THESE","These are the daily / weekly / monthly tasks a Google Ads agency would",- "schedule for an account in this state. Propose them in chat via the",- "<propose_cron> pattern after the user accepts the first one-time action —",- "each suggested_action below names the cadence to schedule.",+ "set up for an account in this state. As the CMO, your job RIGHT NOW is",+ "to create ONE <create_task> block per item below, all assigned to",+ "`google_ads`. Don't ask the user 'want me to...' — just delegate. The",+ "specialist will pick them up + work them.","",);for (const f of nextSteps) {lines.push(`- **${f.headline}**`,- ` Why: ${f.evidence}`,- ` Do: ${f.suggested_action}`,+ ` Context: ${f.evidence}`,+ ` Brief for the specialist: ${f.suggested_action}`,"",);}}- // Suggested opener — varies by what we have.- lines.push("## Suggested opener");+ // Suggested opener — varies by what we have. SHORT prose, then blocks.+ lines.push("## Suggested opener (prose, then blocks)");if (accountState === "empty") {lines.push(- "Greet the user by acknowledging they're just getting started with Google Ads.",- "Reference the budget recommendation by name. End with an open question that",- "invites them to talk through their first campaign. Keep it under 3 sentences.",+ "1-2 sentences: acknowledge they're just getting started; name the budget",+ "recommendation. Then emit <create_task> blocks for the recommended ongoing",+ "work above (assignee: google_ads). End with one sentence: 'Handed these",+ "to your Google Ads specialist — open /tasks to follow along.' Do NOT ask",+ "'want me to...' — just delegate.",);} else if (topFix) {lines.push(- "Greet the user by referencing the top finding by name with the dollar figure.",- "Make it personal and specific. End with an open question that invites them to",- "either fix the top finding now or talk through the broader audit. Keep it under",- "3 sentences.",+ "1-2 sentences: reference the top finding by name + dollar figure. Then",+ "emit <create_task> blocks for the top finding AND each recommended",+ "ongoing-work item above (assignee: google_ads). End with one sentence:",+ "'Handed these to your Google Ads specialist — open /tasks to follow",+ "along.' Do NOT ask 'want me to fix this?' — just create the task.",);} else if (snapshot) {lines.push(- "Greet the user by referencing the account snapshot by name (campaign + spend).",- "If 0 conversions, mention installing conversion tracking as the first ongoing",- "task. Otherwise mention the most relevant ongoing-work item from above. End",- "with an open question. Keep it under 3 sentences.",+ "1-2 sentences: reference the snapshot by campaign name + spend; if 0",+ "conversions, name conversion-tracking as the first ongoing task. Then",+ "emit <create_task> blocks for every recommended ongoing-work item above",+ "(assignee: google_ads). End with one sentence: 'Handed these to your",+ "Google Ads specialist — open /tasks to follow along.' Do NOT chit-chat.",);} else {lines.push(- "Acknowledge that the audit ran cleanly and the account looks healthy from a",- "30-day spend perspective. Ask the user what they'd like to optimize next.",+ "1-2 sentences: account looks healthy on 30-day spend. Then emit",+ "<create_task> blocks for any ongoing-work items above. End with one",+ "sentence inviting the user to /tasks.",);}lines.push("");diff --git a/src/server/orchestration/blocks.test.ts b/src/server/orchestration/blocks.test.tsnew file mode 100644index 00000000..fe15d5df--- /dev/null+++ b/src/server/orchestration/blocks.test.ts@@ -0,0 +1,157 @@+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.tsnew file mode 100644index 00000000..cf2f8ff4--- /dev/null+++ b/src/server/orchestration/blocks.ts@@ -0,0 +1,208 @@+/**+ * 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/process-blocks.test.ts b/src/server/orchestration/process-blocks.test.tsnew file mode 100644index 00000000..95677558--- /dev/null+++ b/src/server/orchestration/process-blocks.test.ts@@ -0,0 +1,232 @@+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();+vi.mock("@/server/db/tasks", () => ({+ createTask: (...a: unknown[]) => createTaskMock(...a),+ 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 { 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/);+ });+});diff --git a/src/server/orchestration/process-blocks.ts b/src/server/orchestration/process-blocks.tsnew file mode 100644index 00000000..9936f4b0--- /dev/null+++ b/src/server/orchestration/process-blocks.ts@@ -0,0 +1,297 @@+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 },+ });++ return 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}'`,+ );+ }++ // 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/types/index.ts b/src/types/index.tsindex aba6045d..5df85ad5 100644--- a/src/types/index.ts+++ b/src/types/index.ts@@ -36,13 +36,29 @@ export type TaskStatus =export type Task = {id: string;project_slug: string;+ /** Assignee — the agent expected to do the work. */agent_id: string;+ /** Short label shown on task cards (e.g., "Set up daily anomaly check"). */+ title: string | null;+ /** Full request body. Often a PRD-style description from the CMO. */brief: string;success_criteria: string | null;deadline_iso: string | null;status: TaskStatus;result_json: string | null;error_message: string | null;+ /**+ * OpenClaw chat session id where the assignee picks up this task. Null+ * until first opened; populated on first /tasks/[id] visit + remains+ * stable forever after.+ */+ thread_id: string | null;+ /**+ * Agent that created this task. For CMO-originated tasks this is the+ * CMO agent id; in v1.1 specialists creating sub-tasks fill in their+ * own id so the chain back to the planner is walkable.+ */+ assigner_agent_id: string | null;created_at: string;updated_at: string;};