Open-source SEO, GEO, and marketing skills for AI agents.
refactor(onboarding): replace audit pipeline with a CMO task
Yuting Zhongf3941d14bf16
diff --git a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsxindex 319df15c..b5380e0e 100644--- a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx+++ b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx@@ -1,7 +1,3 @@-import { existsSync } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";-import Link from "next/link";import { notFound } from "next/navigation";import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";@@ -20,19 +16,6 @@ import { GoogleAdsMcpBanner } from "@/components/google-ads-mcp-banner";import { McpFlashBanner } from "@/components/mcp-flash-banner";import { ThreadSelector } from "@/components/thread-selector";-/**- * The onboarding audit module drops FIRST_TURN.md in the CMO's workspace so- * the agent can weave the audit into its opening greeting (per D19). But the- * chat client doesn't run the agent until the user types — so without this- * gate the user lands on a silent empty chat. Detect server-side: when the- * thread has no history AND FIRST_TURN.md exists, signal the client to- * auto-send a hidden kickoff so the agent produces its opener.- */-function firstTurnPendingForAgent(agentId: string): boolean {- const dataDir = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");- return existsSync(join(dataDir, "agents", agentId, "FIRST_TURN.md"));-}-type Params = { agent: string; thread: string };type Search = { mcp_connected?: string; mcp_error?: string };@@ -107,12 +90,10 @@ export default async function AgentChatThreadPage({? await getMcpStatus(storedMcpKey(project.slug, "notfair-googleads")): null;- // Auto-kickoff: only on a brand-new thread for an agent with a FIRST_TURN.md- // sentinel (dropped by the onboarding audit). The agent's system prompt- // tells it to read the file + move it to MEMORY/ after, so subsequent- // sessions won't re-fire even though we keep the simple history-empty check.- const autoKickoff =- initialEvents.length === 0 && firstTurnPendingForAgent(agentFullId);+ // Free-form chat never auto-kickoffs. Task-driven kickoffs happen in the+ // task workspace's startTaskIfProposed path; the FIRST_TURN.md sentinel+ // from the old onboarding audit is gone now that audit IS a task.+ const autoKickoff = false;return (<div className="flex h-full flex-col">diff --git a/src/app/api/onboarding/stream/route.ts b/src/app/api/onboarding/stream/route.tsdeleted file mode 100644index dedf9961..00000000--- a/src/app/api/onboarding/stream/route.ts+++ /dev/null@@ -1,122 +0,0 @@-import { NextRequest } from "next/server";--import { getActiveProject } from "@/server/active-project";-import { getProject } from "@/server/db/projects";-import { runAudit } from "@/server/onboarding/audit";-import { awaitProvisioning } from "@/server/onboarding/provisioning-state";-import type { StreamEvent } from "@/lib/onboarding/events";--export const runtime = "nodejs";-export const dynamic = "force-dynamic";--/**- * SSE stream powering the onboarding magic moment.- *- * Phases (per D13 + D17):- * 1. Provisioning gate — await `ensureProjectAgents` (fired async by- * createProjectAction) for up to 8s. Emits provision:waiting →- * provision:ready | provision:timeout | provision:no-agents.- * 2. Audit — pipe `runAudit` events to the client with ~200ms stagger- * between per-finding events for visual rhythm.- *- * Security (per design Pass 3.3): the slug query param MUST match the- * active-project cookie. Otherwise the caller could read another project's- * audit by guessing slugs.- *- * Cancellation: when the client closes the EventSource, req.signal fires;- * we cascade to runAudit's AbortSignal so the in-flight MCP fetch cancels.- */--const PROVISION_TIMEOUT_MS = 8_000;-const FINDING_STAGGER_MS = 200;--export async function GET(req: NextRequest) {- const slug = req.nextUrl.searchParams.get("slug")?.trim() || "";- const active = await getActiveProject();- if (!slug || !active || active.slug !== slug) {- return new Response("forbidden", { status: 403 });- }-- const encoder = new TextEncoder();-- const stream = new ReadableStream<Uint8Array>({- async start(controller) {- let closed = false;- const send = (event: StreamEvent) => {- if (closed) return;- try {- controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));- } catch {- // Controller closed underneath us (client disconnected mid-flight).- closed = true;- }- };- const close = () => {- if (closed) return;- closed = true;- try {- controller.close();- } catch {- // Already closed.- }- };-- const abortAudit = new AbortController();- const onClientAbort = () => abortAudit.abort();- req.signal.addEventListener("abort", onClientAbort, { once: true });-- try {- // Phase 1: provisioning gate.- send({ type: "provision:waiting", elapsed_ms: 0 });- const provision = await awaitProvisioning(slug, PROVISION_TIMEOUT_MS);- if (closed) return;- if (provision.kind === "timeout") {- send({ type: "provision:timeout" });- close();- return;- }- if (provision.kind === "no-agents") {- send({ type: "provision:no-agents" });- close();- return;- }- send({ type: "provision:ready" });-- // Phase 2: stream audit events. Pass the user's selected Google Ads- // account ID so MCP runScript targets the right customer; null when- // the user hasn't picked yet (single-account bearer case).- const project = getProject(slug);- const accountId = project?.google_ads_account_id ?? null;- for await (const event of runAudit(slug, abortAudit.signal, {- accountId,- })) {- if (closed) break;- send(event);- if (event.type === "audit:finding") {- // Small stagger so per-finding cards land with rhythm in the UI.- await new Promise((r) => setTimeout(r, FINDING_STAGGER_MS));- }- }- } catch (err) {- if (!closed) {- send({- type: "audit:error",- kind: "unreachable",- message: err instanceof Error ? err.message : String(err),- });- }- } finally {- req.signal.removeEventListener("abort", onClientAbort);- close();- }- },- });-- return new Response(stream, {- headers: {- "Content-Type": "text/event-stream; charset=utf-8",- "Cache-Control": "no-cache, no-transform",- Connection: "keep-alive",- },- });-}diff --git a/src/components/agent-nav.tsx b/src/components/agent-nav.tsxindex 751b50ec..2cb02275 100644--- a/src/components/agent-nav.tsx+++ b/src/components/agent-nav.tsx@@ -43,12 +43,11 @@ export function AgentNav({ agents, inFlightCounts = {} }: Props) {return (<SidebarMenu>{agents.map((a) => {- // Specialists land on Tasks; CMO lands on Chat. The CMO doesn't own- // tasks (it delegates them) so Tasks would be empty for it.- const href =- a.template_key === "cmo"- ? `/agents/${a.slug}/chat`- : `/agents/${a.slug}/tasks`;+ // Every agent lands on Tasks now. The CMO's tasks are typically+ // its own first-turn work (onboarding audit, user-assigned planning+ // jobs); the work it delegates to specialists shows up in those+ // specialists' tabs. Chat tab is still one click away for free-form.+ const href = `/agents/${a.slug}/tasks`;const agentBase = `/agents/${a.slug}`;const isActive =pathname === agentBase || pathname?.startsWith(`${agentBase}/`);diff --git a/src/components/onboarding-flow.tsx b/src/components/onboarding-flow.tsxindex 7e4f0851..5280174e 100644--- a/src/components/onboarding-flow.tsx+++ b/src/components/onboarding-flow.tsx@@ -3,18 +3,7 @@import { useActionState, useEffect, useRef, useState } from "react";import { useRouter, useSearchParams } from "next/navigation";import Link from "next/link";-import {- AlertCircle,- AlertTriangle,- BarChart3,- ChevronRight,- Gauge,- ListChecks,- Loader2,- Plug,- Search,- TrendingUp,-} from "lucide-react";+import { AlertCircle, ChevronRight, Loader2, Plug } from "lucide-react";import { toast } from "sonner";import { Button } from "@/components/ui/button";@@ -29,14 +18,8 @@ import {setOnboardingAccountAction,type GoogleAdsAccount,} from "@/server/onboarding/accounts";-import type {- AuditSummary,- Finding,- FindingCategory,- StreamEvent,-} from "@/lib/onboarding/events";-type Step = "name" | "connect" | "account" | "audit";+type Step = "name" | "connect" | "account";export function OnboardingFlow() {const router = useRouter();@@ -44,11 +27,7 @@ export function OnboardingFlow() {const stepParam = params.get("step");const slug = params.get("slug") ?? null;const step: Step =- stepParam === "connect" ||- stepParam === "account" ||- stepParam === "audit"- ? stepParam- : "name";+ stepParam === "connect" || stepParam === "account" ? stepParam : "name";return (<div className="mx-auto w-full max-w-[720px] space-y-6 pt-8 pb-12">@@ -68,9 +47,7 @@ export function OnboardingFlow() {)}{step === "connect" && slug && <ConnectStep slug={slug} />}{step === "account" && slug && <AccountStep slug={slug} />}- {step === "audit" && slug && <AuditStep slug={slug} />}- {(step === "connect" || step === "account" || step === "audit") &&- !slug && <MissingSlug />}+ {(step === "connect" || step === "account") && !slug && <MissingSlug />}</main></div>);@@ -168,7 +145,10 @@ function ConnectStep({ slug }: { slug: string }) {}function onSkip() {- router.push("/agents/cmo/chat");+ // Without Google Ads connected, there's nothing for the CMO to audit+ // yet — drop the user on the CMO's task tab so they can see "no tasks+ // assigned, connect Google Ads to start".+ router.push("/agents/cmo/tasks");}return (@@ -269,7 +249,12 @@ function AccountStep({ slug }: { slug: string }) {setState({ phase: "error", message: result.error });return;}- router.replace(`/onboarding?step=audit&slug=${encodeURIComponent(slug)}`);+ // Land on the CMO's task workspace with the freshly-created audit+ // task pre-selected — startTaskIfProposed kicks it off, the user+ // watches it run live in the standard task UX.+ router.replace(+ `/agents/cmo/tasks?task=${encodeURIComponent(result.task_display_id)}`,+ );})();}, [state, slug, router]);@@ -282,7 +267,9 @@ function AccountStep({ slug }: { slug: string }) {setPickingId(null);return;}- router.replace(`/onboarding?step=audit&slug=${encodeURIComponent(slug)}`);+ router.replace(+ `/agents/cmo/tasks?task=${encodeURIComponent(result.task_display_id)}`,+ );} catch (err) {toast.error(err instanceof Error ? err.message : String(err));setPickingId(null);@@ -435,516 +422,6 @@ function AccountStep({ slug }: { slug: string }) {);}-// ── Step 4: Audit (terminal) ───────────────────────────────────────--type AuditState =- | { phase: "provisioning" }- | { phase: "provision-timeout" }- | { phase: "no-agents" }- | { phase: "streaming" }- | { phase: "complete-normal"; summary: AuditSummary }- | { phase: "complete-empty"; summary: AuditSummary }- | { phase: "error"; kind: string; message: string }- | { phase: "persist-failed"; message: string };--function AuditStep({ slug }: { slug: string }) {- const [audit, setAudit] = useState<AuditState>({ phase: "provisioning" });- const [findings, setFindings] = useState<Finding[]>([]);- const [categoryErrors, setCategoryErrors] = useState<- Array<{ category: string; message: string }>- >([]);- const completeFocusRef = useRef<HTMLButtonElement | null>(null);- const esRef = useRef<EventSource | null>(null);-- useEffect(() => {- const es = new EventSource(- `/api/onboarding/stream?slug=${encodeURIComponent(slug)}`,- );- esRef.current = es;-- es.onmessage = (msg) => {- let event: StreamEvent;- try {- event = JSON.parse(msg.data) as StreamEvent;- } catch {- return;- }- switch (event.type) {- case "provision:waiting":- // Already showing the provisioning UI; nothing to do.- break;- case "provision:ready":- setAudit({ phase: "streaming" });- break;- case "provision:timeout":- setAudit({ phase: "provision-timeout" });- es.close();- break;- case "provision:no-agents":- setAudit({ phase: "no-agents" });- es.close();- break;- case "audit:start":- setAudit({ phase: "streaming" });- break;- case "audit:finding":- setFindings((prev) => [...prev, event.finding]);- break;- case "audit:finding-error":- setCategoryErrors((prev) => [- ...prev,- { category: event.category, message: event.message },- ]);- break;- case "audit:empty":- // The audit:complete event will set state to complete-empty with- // the summary. Nothing to render eagerly here.- break;- case "audit:complete":- setAudit(- event.summary.account_state === "empty"- ? { phase: "complete-empty", summary: event.summary }- : { phase: "complete-normal", summary: event.summary },- );- es.close();- break;- case "audit:error":- setAudit({ phase: "error", kind: event.kind, message: event.message });- es.close();- break;- case "audit:persist-failed":- setAudit({ phase: "persist-failed", message: event.message });- es.close();- break;- }- };-- es.onerror = () => {- setAudit((prev) =>- prev.phase === "complete-normal" ||- prev.phase === "complete-empty" ||- prev.phase === "error" ||- prev.phase === "persist-failed"- ? prev- : {- phase: "error",- kind: "unreachable",- message: "Lost connection to onboarding stream.",- },- );- es.close();- };-- return () => {- es.close();- esRef.current = null;- };- }, [slug]);-- useEffect(() => {- if (- (audit.phase === "complete-normal" || audit.phase === "complete-empty") &&- completeFocusRef.current- ) {- completeFocusRef.current.focus();- }- }, [audit.phase]);-- return (- <>- <AuditHeader phase={audit.phase} findingsCount={findings.length} />-- {audit.phase === "provisioning" && <ProvisioningCard />}-- {audit.phase === "provision-timeout" && (- <TimeoutCard- title="Setting up took longer than expected."- message="Your project is created but OpenClaw is slow."- />- )}-- {audit.phase === "no-agents" && (- <TimeoutCard- title="Setting up the project hasn't finished."- message="Open this onboarding again from your project home to retry."- />- )}-- {(audit.phase === "streaming" ||- audit.phase === "complete-normal" ||- audit.phase === "complete-empty") &&- findings.length > 0 && (- <FindingsList- findings={findings}- topFixId={- audit.phase === "complete-normal"- ? audit.summary.top_fix_id- : null- }- categoryErrors={categoryErrors}- />- )}-- {(audit.phase === "streaming" ||- audit.phase === "complete-normal" ||- audit.phase === "complete-empty") &&- findings.length === 0 &&- categoryErrors.length > 0 && (- <PartialErrorBanner errors={categoryErrors} />- )}-- {audit.phase === "complete-empty" && (- <EmptyAccountRoadmap focusRef={completeFocusRef} />- )}-- {audit.phase === "complete-normal" && (- <CompleteFooterCtas focusRef={completeFocusRef} />- )}-- {audit.phase === "error" && (- <AuditErrorCard kind={audit.kind} message={audit.message} />- )}-- {audit.phase === "persist-failed" && (- <PersistFailedCard message={audit.message} />- )}-- {/* One-shot announcement for screen readers. */}- <div role="status" aria-live="polite" className="sr-only">- {audit.phase === "complete-normal" &&- `Audit complete. ${audit.summary.count} findings.`}- {audit.phase === "complete-empty" &&- "Audit complete. Looks like you're just getting started."}- </div>- </>- );-}--function AuditHeader({- phase,- findingsCount,-}: {- phase: AuditState["phase"];- findingsCount: number;-}) {- if (phase === "provisioning") return null;- if (phase === "provision-timeout" || phase === "no-agents") return null;- if (phase === "error" || phase === "persist-failed") return null;- if (phase === "complete-empty") {- return (- <header className="space-y-1">- <h1 className="text-3xl font-semibold tracking-tight text-foreground">- Looks like you’re just getting started.- </h1>- <p className="text-sm text-muted-foreground">- I didn’t find spend or campaigns in the last 30 days. Here’s- what I’d build with you next.- </p>- </header>- );- }- if (phase === "complete-normal") {- return (- <header className="space-y-1">- <h1 className="text-3xl font-semibold tracking-tight text-foreground">- Here’s what I found.- </h1>- <p className="text-sm text-muted-foreground tabular-nums">- Audit complete · {findingsCount} finding- {findingsCount === 1 ? "" : "s"}- </p>- </header>- );- }- // streaming- return (- <header className="space-y-1" role="status">- <h1 className="text-3xl font-semibold tracking-tight text-foreground">- Looking at your Google Ads account…- </h1>- <p className="text-sm text-muted-foreground">- Findings will land here as I work through your account.- </p>- </header>- );-}--function ProvisioningCard() {- return (- <Card>- <CardContent className="space-y-2 pt-6 pb-6">- <div className="flex items-center gap-3 text-sm">- <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />- <span className="font-medium">Connecting your CMO to your account…</span>- </div>- <p className="text-xs text-muted-foreground pl-7">- Just a few seconds. You’ll see findings as soon as we’re in.- </p>- </CardContent>- </Card>- );-}--function TimeoutCard({ title, message }: { title: string; message: string }) {- return (- <Card role="alert">- <CardContent className="space-y-3 pt-6 pb-6">- <div className="flex items-center gap-2">- <AlertCircle className="size-4 text-amber-600" aria-hidden />- <span className="font-medium text-sm">{title}</span>- </div>- <p className="text-xs text-muted-foreground">{message}</p>- <div className="flex gap-2">- <Button asChild>- <Link href="/onboarding">Retry</Link>- </Button>- <Button variant="outline" asChild>- <Link href="/agents/cmo/chat">Skip to chat</Link>- </Button>- </div>- </CardContent>- </Card>- );-}--function FindingsList({- findings,- topFixId,- categoryErrors,-}: {- findings: Finding[];- topFixId: string | null;- categoryErrors: Array<{ category: string; message: string }>;-}) {- // Pull the top fix to the top, keep others in order.- const top = topFixId ? findings.find((f) => f.id === topFixId) : null;- const rest = top ? findings.filter((f) => f.id !== top.id) : findings;- return (- <ol- aria-live="polite"- aria-relevant="additions"- className="space-y-3 list-none p-0"- >- {top && <FindingCard finding={top} isTopFix />}- {rest.map((f) => (- <FindingCard key={f.id} finding={f} />- ))}- {categoryErrors.map((ce) => (- <li key={`err:${ce.category}`} className="text-xs text-muted-foreground pl-7">- <span className="inline-flex items-center gap-2">- <AlertCircle className="size-3.5" aria-hidden />- Couldn’t check {ce.category.toLowerCase().replace(/_/g, " ")} —- continuing with the rest.- </span>- </li>- ))}- </ol>- );-}--const CATEGORY_ICON: Record<FindingCategory, React.ComponentType<{ className?: string }>> = {- WASTED_SPEND: AlertTriangle,- LOW_QS: Gauge,- SEARCH_TERM_GAP: Search,- BUDGET_PACING: TrendingUp,- ACCOUNT_SNAPSHOT: BarChart3,- NEXT_STEPS: ListChecks,-};--function FindingCard({- finding,- isTopFix,-}: {- finding: Finding;- isTopFix?: boolean;-}) {- const Icon = CATEGORY_ICON[finding.category];- return (- <li className="animate-in fade-in slide-in-from-bottom-1 duration-300">- <Card className={cn(isTopFix && "ring-1 ring-foreground/10")}>- <CardHeader className="pt-4 pb-2">- <div className="flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">- <Icon className="size-4" aria-hidden />- <span>- {isTopFix && "TOP FIX · "}- {finding.category.replace(/_/g, " ")}- </span>- </div>- </CardHeader>- <CardContent className="pt-0 pb-4 space-y-2">- <p className="text-sm font-medium leading-snug text-foreground">- {finding.headline}- </p>- <p className="text-xs text-muted-foreground tabular-nums">- {finding.evidence}- </p>- {finding.suggested_action && (- <p className="text-xs leading-snug text-muted-foreground">- {finding.suggested_action}- </p>- )}- {isTopFix ? (- <Button asChild size="lg" className="mt-2">- <Link- href={`/agents/cmo/chat?propose=${encodeURIComponent(finding.id)}`}- >- Fix this now- </Link>- </Button>- ) : (- <Button asChild variant="link" size="sm" className="px-0">- <Link- href={`/agents/cmo/chat?propose=${encodeURIComponent(finding.id)}`}- >- {actionLabelFor(finding)}{" "}- <ChevronRight className="ml-0.5 size-3.5" aria-hidden />- </Link>- </Button>- )}- </CardContent>- </Card>- </li>- );-}--/** Action-link copy per category — "I'll fix this" only fits actionable findings. */-function actionLabelFor(finding: Finding): string {- if (finding.category === "ACCOUNT_SNAPSHOT") return "Talk it through with CMO";- if (finding.category === "NEXT_STEPS") return "Set this up with CMO";- return "I’ll fix this";-}--function CompleteFooterCtas({- focusRef,-}: {- focusRef: React.RefObject<HTMLButtonElement | null>;-}) {- return (- <div className="flex flex-wrap gap-2 pt-2">- <Button asChild variant="outline" size="lg">- <Link- href="/agents/cmo/chat"- ref={focusRef as unknown as React.Ref<HTMLAnchorElement>}- >- Chat with CMO about all of this- </Link>- </Button>- </div>- );-}--function EmptyAccountRoadmap({- focusRef,-}: {- focusRef: React.RefObject<HTMLButtonElement | null>;-}) {- return (- <>- <Card>- <CardHeader>- <CardTitle className="text-base">Where I’d start</CardTitle>- </CardHeader>- <CardContent className="space-y-3 text-sm">- <p>- <strong>Set a daily budget for your first campaign.</strong> Most B2B- starts at $50–100/day to gather signal.- </p>- <p>- <strong>Decide your first goal:</strong> leads vs. traffic vs. brand.- I can help you pick.- </p>- <p>- <strong>Talk it through with me.</strong> Thirty minutes and- you’ll have a campaign brief.- </p>- </CardContent>- </Card>- <div className="flex flex-wrap gap-2 pt-2">- <Button asChild size="lg">- <Link- href="/agents/cmo/chat"- ref={focusRef as unknown as React.Ref<HTMLAnchorElement>}- >- Plan with CMO- </Link>- </Button>- <Button asChild variant="ghost">- <Link href="/">I’ll come back</Link>- </Button>- </div>- </>- );-}--function AuditErrorCard({ kind, message }: { kind: string; message: string }) {- const headline =- kind === "stale_token"- ? "Google Ads token expired."- : kind === "mcp_not_configured"- ? "Google Ads isn't connected for this project."- : kind === "timeout"- ? "Audit timed out."- : "Couldn't reach your Google Ads account.";- return (- <Card role="alert">- <CardContent className="space-y-3 pt-6 pb-6">- <div className="flex items-center gap-2">- <AlertCircle className="size-4 text-amber-600" aria-hidden />- <span className="font-medium text-sm">{headline}</span>- </div>- <p className="text-xs text-muted-foreground">{message}</p>- <div className="flex gap-2">- <Button asChild>- <Link href="/onboarding">Retry</Link>- </Button>- <Button variant="outline" asChild>- <Link href="/agents/cmo/chat">Skip to chat</Link>- </Button>- </div>- </CardContent>- </Card>- );-}--function PersistFailedCard({ message }: { message: string }) {- return (- <Card role="alert">- <CardContent className="space-y-3 pt-6 pb-6">- <div className="flex items-center gap-2">- <AlertCircle className="size-4 text-destructive" aria-hidden />- <span className="font-medium text-sm">Couldn’t save your audit.</span>- </div>- <p className="text-xs text-muted-foreground">- Check disk space or restart and try again. Detail: {message}- </p>- <Button asChild>- <Link href="/onboarding">Retry</Link>- </Button>- </CardContent>- </Card>- );-}--function PartialErrorBanner({- errors,-}: {- errors: Array<{ category: string; message: string }>;-}) {- return (- <Card>- <CardContent className="space-y-2 pt-6 pb-6 text-sm">- <div className="flex items-center gap-2">- <AlertCircle className="size-4 text-muted-foreground" aria-hidden />- <span className="text-muted-foreground">- Couldn’t check {errors.length} categor- {errors.length === 1 ? "y" : "ies"} — the rest came back clean.- </span>- </div>- </CardContent>- </Card>- );-}-function MissingSlug() {return (<Card>diff --git a/src/lib/onboarding/events.ts b/src/lib/onboarding/events.tsdeleted file mode 100644index 8736947a..00000000--- a/src/lib/onboarding/events.ts+++ /dev/null@@ -1,21 +0,0 @@-/**- * Streamed event types for /api/onboarding/stream. Shared between the SSE- * route handler and the onboarding UI. AuditEvent comes from the server-side- * audit module; ProvisionEvent is local to this flow.- *- * Why a type-only re-export: audit.ts pulls in node:fs/promises + openclaw- * subprocess + better-sqlite3 (server-only). Importing the TYPE only from- * the client bundle is safe because `import type` is erased at compile time.- */--import type { AuditEvent, Finding, FindingCategory, AuditSummary } from "@/server/onboarding/audit";--export type ProvisionEvent =- | { type: "provision:waiting"; elapsed_ms: number }- | { type: "provision:ready" }- | { type: "provision:timeout" }- | { type: "provision:no-agents" };--export type StreamEvent = ProvisionEvent | AuditEvent;--export type { AuditEvent, Finding, FindingCategory, AuditSummary };diff --git a/src/server/agent-templates.ts b/src/server/agent-templates.tsindex 22529396..32a7d68d 100644--- a/src/server/agent-templates.ts+++ b/src/server/agent-templates.ts@@ -110,61 +110,64 @@ bid_change, audience_change, other. cost_estimate_usd is required forspend-typed actions. The platform creates an approval row the user canaccept/reject from /approvals.+## 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:++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+ 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.+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>.+## 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.+- 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 —+ only the assignee reports status.`;/*** 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.+ * the worker how to receive assigned tasks (delivered as a chat message+ * beginning "(task assignment)"), 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.+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_BRIEF.md kickoff+## "(task assignment)" kickoff-When a fresh chat session starts in your workspace, FIRST check for-TASK_BRIEF.md. If present:+When a chat turn opens with "(task assignment)":-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.+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.-If TASK_BRIEF.md is NOT present, greet the user normally — do not-fabricate a task.+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)### <task_status> — report progress on YOUR assigned task<task_status>-task_id: <uuid from your TASK_BRIEF.md>+task_id: <id from the "(task assignment)" message>status: donesummary: Installed the conversion tag on /thanks and /demo-request.Test conv fired at 14:02 PT. Conversion type: "Demo request", value@@ -238,23 +241,7 @@ reporting + collaboration.* when the user accepts, not when the agent proposes — earned trust,* not premature autonomy.*/-const FIRST_TURN_AND_PROPOSE_CRON_PROMPT = `## First-turn context on a fresh chat session--On every new chat session in this workspace, your FIRST action MUST be:--1. Check whether \`FIRST_TURN.md\` exists in your current workspace directory.-2. If it exists: read it, weave its contents into your opening reply per the- "Suggested opener" section it specifies, then move it to- \`MEMORY/last-first-turn-<YYYY-MM-DD>.md\` so you don't repeat the greeting- on subsequent sessions.-3. If it does not exist: greet the user normally — do NOT fabricate audit- findings or pretend you have account context you don't have.--This file is dropped by the onboarding magic-moment flow when a fresh Google-Ads audit completes. It contains the structured audit summary, top finding,-and a suggested opener. The contract is one-shot: read, weave, move.--## Proposing recurring work after an approved action+const PROPOSE_CRON_PROMPT = `## Proposing recurring work after an approved actionWhen the user just approved an action that produces a one-time outcome(e.g., pausing wasted-spend keywords), your next response should ALSO@@ -388,7 +375,7 @@ ${CMO_ORCHESTRATOR_PROMPT}${SCHEDULE_RECURRING_WORK_SYSTEM_PROMPT}-${FIRST_TURN_AND_PROPOSE_CRON_PROMPT}+${PROPOSE_CRON_PROMPT}Style:- Lead with the point. Be specific. Reference real numbers and channel realities.@@ -423,7 +410,7 @@ ${SPECIALIST_TASK_PROMPT}${SCHEDULE_RECURRING_WORK_SYSTEM_PROMPT}-${FIRST_TURN_AND_PROPOSE_CRON_PROMPT}+${PROPOSE_CRON_PROMPT}Schedule yourself for recurring jobs the CMO requests: hourly metricpulls, daily bid optimization, weekly negative keyword reviews. Usediff --git a/src/server/onboarding/accounts.test.ts b/src/server/onboarding/accounts.test.tsindex d13d5a2e..16483f9b 100644--- a/src/server/onboarding/accounts.test.ts+++ b/src/server/onboarding/accounts.test.ts@@ -21,6 +21,37 @@ vi.mock("next/cache", () => ({revalidatePath: vi.fn(),}));+// Dynamic imports inside setOnboardingAccountAction need mocks too — it+// auto-creates the CMO's onboarding task as the final step of the action.+const createTaskMock = vi.fn();+const listTasksMock = vi.fn(() => [] as unknown[]);+vi.mock("@/server/db/tasks", () => ({+ createTask: (input: unknown) => {+ createTaskMock(input);+ return {+ id: "task-uuid",+ display_id: "acme-1",+ project_slug: "acme",+ agent_id: "acme-cmo",+ title: "Audit the account and propose a starter playbook",+ brief: "...",+ success_criteria: null,+ deadline_iso: null,+ status: "proposed",+ result_json: null,+ error_message: null,+ thread_id: null,+ assigner_agent_id: null,+ created_at: "now",+ updated_at: "now",+ };+ },+ listTasks: (...args: unknown[]) => listTasksMock(...args),+}));+vi.mock("@/server/agent-templates", () => ({+ agentNameFor: (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,+}));+import {listGoogleAdsAccounts,setOnboardingAccountAction,@@ -157,6 +188,42 @@ describe("setOnboardingAccountAction", () => {);});+ it("mints the CMO onboarding task and returns its display_id for the redirect", async () => {+ const r = await setOnboardingAccountAction("acme", "3251706605");+ expect(r.ok).toBe(true);+ if (r.ok) {+ // Caller redirects to /agents/cmo/tasks?task=<this>.+ expect(r.task_display_id).toBe("acme-1");+ }+ expect(createTaskMock).toHaveBeenCalledTimes(1);+ expect(createTaskMock).toHaveBeenCalledWith(+ expect.objectContaining({+ project_slug: "acme",+ agent_id: "acme-cmo",+ status: "proposed",+ title: expect.stringContaining("Audit"),+ brief: expect.stringContaining("3251706605"),+ }),+ );+ });++ it("does NOT double-create the task when a prior audit task already exists", async () => {+ listTasksMock.mockReturnValueOnce([+ {+ id: "prior-uuid",+ display_id: "acme-7",+ project_slug: "acme",+ agent_id: "acme-cmo",+ title: "Audit the account and propose a starter playbook",+ status: "running",+ },+ ]);+ const r = await setOnboardingAccountAction("acme", "3251706605");+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.task_display_id).toBe("acme-7");+ expect(createTaskMock).not.toHaveBeenCalled();+ });+it("rejects an account id NOT in the bearer's list (tamper defense)", async () => {const r = await setOnboardingAccountAction("acme", "9999999999");expect(r.ok).toBe(false);diff --git a/src/server/onboarding/accounts.ts b/src/server/onboarding/accounts.tsindex 5ffc5092..bc44ebf0 100644--- a/src/server/onboarding/accounts.ts+++ b/src/server/onboarding/accounts.ts@@ -121,13 +121,21 @@ function parseAccountsPayload(}export type SetAccountResult =- | { ok: true; project: Project }+ | { ok: true; project: Project; task_display_id: string }| { ok: false; error: string };/**- * Persist the selected Google Ads customer ID on the project row. Validates- * the account_id against the MCP's accounts list to prevent the UI from- * stashing a stale or fabricated id.+ * Finishes onboarding in one round-trip:+ *+ * 1. Validates the account_id against the MCP's reachable list+ * (anti-tamper for the form submit).+ * 2. Persists it on the project row.+ * 3. Mints the CMO's first task with the audit brief.+ *+ * The caller redirects to /agents/cmo/tasks?task=<display_id>; the+ * workspace's startTaskIfProposed fires the kickoff so the agent does the+ * audit live in the standard task UX. Replaces the one-off audit.ts+ * pipeline that used to drive its own SSE stream + FIRST_TURN.md sentinel.*/export async function setOnboardingAccountAction(project_slug: string,@@ -158,6 +166,35 @@ export async function setOnboardingAccountAction(const updated = setProjectGoogleAdsAccount(project_slug, match.id);if (!updated) return { ok: false, error: "Project not found." };++ // Mint the onboarding task. Avoid duplicates if the user navigates back+ // and resubmits — reuse the existing one when a CMO audit task is+ // already pending for this project.+ const { buildOnboardingBrief } = await import("./cmo-task-brief");+ const { listTasks, createTask } = await import("@/server/db/tasks");+ const { agentNameFor } = await import("@/server/agent-templates");+ const cmoAgentId = agentNameFor(project_slug, "cmo");+ const existing = listTasks(project_slug).find(+ (t) => t.agent_id === cmoAgentId && t.title?.startsWith("Audit the account"),+ );+ let task = existing;+ if (!task) {+ const { title, brief, success_criteria } = buildOnboardingBrief({+ project_slug,+ project_display_name: updated.display_name,+ google_ads_account_id: match.id,+ });+ task = createTask({+ project_slug,+ agent_id: cmoAgentId,+ title,+ brief,+ success_criteria,+ assigner_agent_id: null,+ status: "proposed",+ });+ }+revalidatePath("/", "layout");- return { ok: true, project: updated };+ return { ok: true, project: updated, task_display_id: task.display_id };}diff --git a/src/server/onboarding/audit.test.ts b/src/server/onboarding/audit.test.tsdeleted file mode 100644index 41db4642..00000000--- a/src/server/onboarding/audit.test.ts+++ /dev/null@@ -1,538 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--// ── Mocks ──────────────────────────────────────────────────────────--const getMcpConfigMock = vi.fn();-const mcpRpcMock = vi.fn();-vi.mock("@/server/mcp/rpc", () => ({- getMcpConfig: (...args: unknown[]) => getMcpConfigMock(...args),- mcpRpc: (...args: unknown[]) => mcpRpcMock(...args),-}));--const logAgentActionMock = vi.fn();-vi.mock("@/server/db/agent-actions", () => ({- logAgentAction: (...args: unknown[]) => logAgentActionMock(...args),-}));--const writeFileMock = vi.fn();-const mkdirMock = vi.fn();-vi.mock("node:fs/promises", () => ({- writeFile: (...args: unknown[]) => writeFileMock(...args),- mkdir: (...args: unknown[]) => mkdirMock(...args),-}));--const openclawMock = vi.fn();-vi.mock("@/server/openclaw/cli", () => ({- openclaw: (...args: unknown[]) => openclawMock(...args),- OpenClawError: class OpenClawError extends Error {},-}));--import { runAudit, type AuditEvent } from "./audit";--// ── Fixtures ───────────────────────────────────────────────────────--/**- * Fixtures mirror the REAL `ads.gaqlParallel` envelope shape (verified live- * against notfair.co/api/mcp/google_ads on 2026-05-19): the script's return- * is wrapped in `{ ok, result, resultTruncated, logs, timedOut, elapsedMs }`.- * Campaign status comes as numeric enum + `status_name` string companion.- * Rows use object-nested shape (campaign.name, metrics.cost_micros) — NOT- * dotted keys. Bugs that ship under fixtures that don't match the live shape- * silently classify accounts as empty (the regression that triggered this- * test rewrite).- */-const NORMAL_REPORTS_INNER = {- wasted_spend: {- rowCount: 4,- rows: [- {- ad_group_criterion: { keyword: { text: "marketing automation" } },- ad_group: { name: "Brand" },- campaign: { name: "Brand-US" },- metrics: { cost_micros: 420_000_000, conversions: 0, clicks: 300 },- },- {- ad_group_criterion: { keyword: { text: "saas crm" } },- ad_group: { name: "Brand" },- campaign: { name: "Brand-US" },- metrics: { cost_micros: 420_000_000, conversions: 0, clicks: 300 },- },- {- ad_group_criterion: { keyword: { text: "best crm" } },- ad_group: { name: "Brand" },- campaign: { name: "Brand-US" },- metrics: { cost_micros: 210_000_000, conversions: 0, clicks: 150 },- },- {- ad_group_criterion: { keyword: { text: "ad ops" } },- ad_group: { name: "Brand" },- campaign: { name: "Brand-US" },- metrics: { cost_micros: 210_000_000, conversions: 0, clicks: 450 },- },- ],- },- low_qs: {- rowCount: 1,- rows: [- {- ad_group_criterion: {- keyword: { text: "kw1" },- quality_info: { quality_score: 3 },- },- ad_group: { name: "Generic" },- campaign: { name: "Generic-US" },- metrics: { impressions: 500, cost_micros: 50_000_000 },- },- ],- },- search_term_gap: { rowCount: 0, rows: [] },- budget_pacing: { rowCount: 0, rows: [] },- campaigns_summary: {- rowCount: 1,- rows: [- {- campaign: { name: "Brand-US", status: 2, status_name: "ENABLED" },- metrics: { cost_micros: 3_000_000_000, impressions: 50_000 },- },- ],- },-};--const EMPTY_REPORTS_INNER = {- wasted_spend: { rowCount: 0, rows: [] },- low_qs: { rowCount: 0, rows: [] },- search_term_gap: { rowCount: 0, rows: [] },- budget_pacing: { rowCount: 0, rows: [] },- campaigns_summary: { rowCount: 0, rows: [] },-};--/** Wrap inner reports in the runScript envelope and the MCP tool-call envelope. */-function mockToolCallResult(reports: unknown): {- ok: true;- result: { content: Array<{ type: string; text: string }>; isError: boolean };-} {- const scriptEnvelope = {- ok: true,- result: reports,- resultTruncated: false,- logs: [],- logsTruncated: false,- timedOut: false,- elapsedMs: 950,- };- return {- ok: true,- result: {- content: [{ type: "text", text: JSON.stringify(scriptEnvelope) }],- isError: false,- },- };-}--const NORMAL_REPORTS = NORMAL_REPORTS_INNER;-const EMPTY_REPORTS = EMPTY_REPORTS_INNER;--async function collect(slug: string, signal?: AbortSignal): Promise<AuditEvent[]> {- const out: AuditEvent[] = [];- for await (const e of runAudit(slug, signal)) out.push(e);- return out;-}--// ── Tests ──────────────────────────────────────────────────────────--describe("runAudit", () => {- beforeEach(() => {- vi.clearAllMocks();- getMcpConfigMock.mockResolvedValue({- url: "https://notfair.co/api/mcp/google_ads",- token: "tok",- });- mkdirMock.mockResolvedValue(undefined);- writeFileMock.mockResolvedValue(undefined);- openclawMock.mockResolvedValue(undefined);- });-- describe("happy path (normal account)", () => {- beforeEach(() => {- mcpRpcMock.mockResolvedValue(mockToolCallResult(NORMAL_REPORTS));- });-- it("emits start → findings → complete in order", async () => {- const events = await collect("acme");- expect(events[0]).toEqual({ type: "audit:start" });- expect(events.at(-1)).toMatchObject({ type: "audit:complete" });- const findingEvents = events.filter((e) => e.type === "audit:finding");- expect(findingEvents.length).toBeGreaterThan(0);- });-- it("WASTED_SPEND finding references the offending campaign by name", async () => {- const events = await collect("acme");- const wasted = events.find(- (e) => e.type === "audit:finding" && e.finding.category === "WASTED_SPEND",- );- expect(wasted).toBeDefined();- if (wasted && wasted.type === "audit:finding") {- expect(wasted.finding.headline).toContain("Brand-US");- expect(wasted.finding.headline).toMatch(/burn/);- }- });-- it("persists the audit to agent_actions with category-errored count", async () => {- await collect("acme");- expect(logAgentActionMock).toHaveBeenCalledTimes(1);- const call = logAgentActionMock.mock.calls[0]![0];- expect(call.project_slug).toBe("acme");- expect(call.action_type).toBe("audit_completed");- expect(call.agent_id).toBe("acme-google-ads");- expect(call.payload.summary.count).toBeGreaterThan(0);- });-- it("writes FIRST_TURN.md to the CMO workspace", async () => {- await collect("acme");- expect(writeFileMock).toHaveBeenCalled();- const [path, body] = writeFileMock.mock.calls[0]!;- expect(String(path)).toMatch(/acme-cmo[\\/]FIRST_TURN\.md$/);- expect(String(body)).toContain("# First-turn context for the CMO");- expect(String(body)).toContain("acme");- expect(String(body)).toContain("Top finding");- });-- it("writes a memory tag via openclaw subprocess", async () => {- await collect("acme");- expect(openclawMock).toHaveBeenCalled();- const [args] = openclawMock.mock.calls[0]!;- expect(args).toContain("memory");- expect(args).toContain("write");- expect(args).toContain("--agent");- expect(args).toContain("acme-cmo");- });-- it("picks the highest-$-impact finding as top_fix", async () => {- const events = await collect("acme");- const complete = events.find((e) => e.type === "audit:complete");- if (complete && complete.type === "audit:complete") {- expect(complete.summary.top_fix_id).toMatch(/^wasted_spend:/);- }- });- });-- describe("empty account (D5)", () => {- beforeEach(() => {- mcpRpcMock.mockResolvedValue(mockToolCallResult(EMPTY_REPORTS));- });-- it("emits audit:empty before audit:complete", async () => {- const events = await collect("acme");- const emptyIdx = events.findIndex((e) => e.type === "audit:empty");- const completeIdx = events.findIndex((e) => e.type === "audit:complete");- expect(emptyIdx).toBeGreaterThan(-1);- expect(completeIdx).toBeGreaterThan(emptyIdx);- });-- it("records account_state='empty' on the agent_actions row", async () => {- await collect("acme");- const call = logAgentActionMock.mock.calls[0]![0];- expect(call.payload.summary.account_state).toBe("empty");- });-- it("FIRST_TURN.md contains the empty-account roadmap content", async () => {- await collect("acme");- const [, body] = writeFileMock.mock.calls[0]!;- expect(String(body)).toContain("Set a daily budget");- expect(String(body)).toContain("just getting started");- });- });-- describe("MCP failure modes", () => {- it("emits stale_token error on 401", async () => {- mcpRpcMock.mockResolvedValue({ ok: false, kind: "http_error", status: 401 });- const events = await collect("acme");- const err = events.find((e) => e.type === "audit:error");- expect(err).toMatchObject({ type: "audit:error", kind: "stale_token" });- // Did NOT persist or write FIRST_TURN.md when MCP failed.- expect(logAgentActionMock).not.toHaveBeenCalled();- expect(writeFileMock).not.toHaveBeenCalled();- });-- it("emits unreachable error on 500", async () => {- mcpRpcMock.mockResolvedValue({ ok: false, kind: "http_error", status: 500 });- const events = await collect("acme");- expect(events.find((e) => e.type === "audit:error")).toMatchObject({- kind: "unreachable",- });- });-- it("emits timeout error on timeout", async () => {- mcpRpcMock.mockResolvedValue({ ok: false, kind: "timeout" });- const events = await collect("acme");- expect(events.find((e) => e.type === "audit:error")).toMatchObject({- kind: "timeout",- });- });-- it("emits rpc_error on JSON-RPC error envelope", async () => {- mcpRpcMock.mockResolvedValue({- ok: false,- kind: "rpc_error",- code: -32601,- message: "Method not found",- });- const events = await collect("acme");- expect(events.find((e) => e.type === "audit:error")).toMatchObject({- kind: "rpc_error",- });- });-- it("emits malformed_response when MCP returns non-text content", async () => {- mcpRpcMock.mockResolvedValue({- ok: true,- result: { content: [], isError: false },- });- const events = await collect("acme");- expect(events.find((e) => e.type === "audit:error")).toMatchObject({- kind: "malformed_response",- });- });-- it("emits mcp_not_configured when getMcpConfig returns null", async () => {- getMcpConfigMock.mockResolvedValueOnce(null);- mcpRpcMock.mockResolvedValue(mockToolCallResult(NORMAL_REPORTS));- const events = await collect("acme");- expect(events.find((e) => e.type === "audit:error")).toMatchObject({- kind: "mcp_not_configured",- });- expect(mcpRpcMock).not.toHaveBeenCalled();- });- });-- describe("category-level errors (partial audit)", () => {- it("emits audit:finding-error per failing category but continues", async () => {- const mixed = {- ...NORMAL_REPORTS,- low_qs: { error: "quota exceeded for this surface" },- };- mcpRpcMock.mockResolvedValue(mockToolCallResult(mixed));- const events = await collect("acme");- const findingErr = events.find((e) => e.type === "audit:finding-error");- expect(findingErr).toMatchObject({ category: "LOW_QS" });- // Other findings still emitted + completion still fired.- expect(events.some((e) => e.type === "audit:finding")).toBe(true);- expect(events.some((e) => e.type === "audit:complete")).toBe(true);- });- });-- describe("D12: load-bearing SQLite write fail-loud", () => {- beforeEach(() => {- mcpRpcMock.mockResolvedValue(mockToolCallResult(NORMAL_REPORTS));- });-- it("emits audit:persist-failed and stops (no complete) when logAgentAction throws", async () => {- logAgentActionMock.mockImplementationOnce(() => {- throw new Error("disk is full");- });- const events = await collect("acme");- expect(events.some((e) => e.type === "audit:persist-failed")).toBe(true);- expect(events.some((e) => e.type === "audit:complete")).toBe(false);- // FIRST_TURN.md and memory writes did NOT run after persist failed.- expect(writeFileMock).not.toHaveBeenCalled();- expect(openclawMock).not.toHaveBeenCalled();- });- });-- describe("ACCOUNT_SNAPSHOT (small-account audit always finds something)", () => {- it("emits a snapshot finding for low-activity accounts (NotFair-shape regression)", async () => {- // Real NotFair-account shape observed 2026-05-20: 1 enabled campaign,- // $39.39 / 42 imp / 0 conv in 30d. None of the actionable queries- // returned rows under the strict filters, but the user still saw- // "0 findings" which felt broken. ACCOUNT_SNAPSHOT must surface- // proof-of-work whenever campaigns_summary has rows.- const notfairShape = {- wasted_spend: { rowCount: 0, rows: [] },- low_qs: { rowCount: 0, rows: [] },- search_term_gap: { rowCount: 0, rows: [] },- budget_pacing: { rowCount: 0, rows: [] },- campaigns_summary: {- rowCount: 1,- rows: [- {- campaign: {- name: "NotFair - Google Ads + Claude",- status: 2,- status_name: "ENABLED",- },- metrics: { cost_micros: 39_390_000, impressions: 42, conversions: 0 },- },- ],- },- };- mcpRpcMock.mockResolvedValueOnce(mockToolCallResult(notfairShape));- const events = await collect("acme");- const snapshot = events.find(- (e) => e.type === "audit:finding" && e.finding.category === "ACCOUNT_SNAPSHOT",- );- expect(snapshot, "snapshot finding must be emitted even when other queries return 0 rows").toBeDefined();- if (snapshot && snapshot.type === "audit:finding") {- expect(snapshot.finding.headline).toContain("NotFair");- expect(snapshot.finding.headline).toContain("$39.39");- // 0 conversions on real spend → suggested action calls out tracking.- expect(snapshot.finding.suggested_action).toMatch(/conversion tracking|low impressions|scale/i);- }- const complete = events.find((e) => e.type === "audit:complete");- if (complete && complete.type === "audit:complete") {- expect(complete.summary.account_state).toBe("normal");- // ACCOUNT_SNAPSHOT must NOT be promoted to Top Fix.- expect(complete.summary.top_fix_id).toBeNull();- // Snapshot finding counts toward the total.- expect(complete.summary.count).toBeGreaterThanOrEqual(1);- }- });-- it("snapshot is NEVER promoted to Top Fix when actionable findings exist", async () => {- mcpRpcMock.mockResolvedValueOnce(mockToolCallResult(NORMAL_REPORTS));- const events = await collect("acme");- const complete = events.find((e) => e.type === "audit:complete");- if (complete && complete.type === "audit:complete") {- expect(complete.summary.top_fix_id).toMatch(/^wasted_spend:/);- }- });-- it("does NOT emit a snapshot when campaigns_summary is empty (D5 path)", async () => {- mcpRpcMock.mockResolvedValueOnce(mockToolCallResult(EMPTY_REPORTS));- const events = await collect("acme");- const snapshot = events.find(- (e) => e.type === "audit:finding" && e.finding.category === "ACCOUNT_SNAPSHOT",- );- expect(snapshot).toBeUndefined();- expect(events.some((e) => e.type === "audit:empty")).toBe(true);- });- });-- describe("accountId plumbing (multi-account bearers, Demo2 fix)", () => {- beforeEach(() => {- mcpRpcMock.mockResolvedValue(mockToolCallResult(NORMAL_REPORTS));- });-- it("omits accountId from runScript args when option is null/undefined", async () => {- await collect("acme");- const [, , , params] = mcpRpcMock.mock.calls[0]!;- const args = (params as { arguments: Record<string, unknown> }).arguments;- expect(args).not.toHaveProperty("accountId");- });-- it("passes accountId to runScript when option is provided", async () => {- const events: AuditEvent[] = [];- for await (const e of runAudit("acme", undefined, { accountId: "7073485715" })) {- events.push(e);- }- const [, , , params] = mcpRpcMock.mock.calls[0]!;- const args = (params as { arguments: Record<string, unknown> }).arguments;- expect(args.accountId).toBe("7073485715");- expect(events.some((e) => e.type === "audit:complete")).toBe(true);- });- });-- describe("regression — real MCP envelope shape", () => {- it("unwraps the runScript {ok, result} envelope (Demo2 bug — 2026-05-19)", async () => {- // Build a payload WITHOUT the helper so we can exercise the unwrap path- // explicitly. Live MCP wraps the script's return in {ok, result, ...}.- // Before the fix, our parser returned the wrapper as the category dict- // and findings disappeared (classified as empty).- const inner = {- wasted_spend: NORMAL_REPORTS_INNER.wasted_spend,- low_qs: NORMAL_REPORTS_INNER.low_qs,- search_term_gap: { rows: [] },- budget_pacing: { rows: [] },- campaigns_summary: NORMAL_REPORTS_INNER.campaigns_summary,- };- const envelopeText = JSON.stringify({- ok: true,- result: inner,- resultTruncated: false,- logs: [],- timedOut: false,- elapsedMs: 950,- });- mcpRpcMock.mockResolvedValueOnce({- ok: true,- result: {- content: [{ type: "text", text: envelopeText }],- isError: false,- },- });- const events = await collect("acme");- const complete = events.find((e) => e.type === "audit:complete");- expect(complete, "should reach audit:complete with findings, not classify empty").toBeDefined();- if (complete && complete.type === "audit:complete") {- expect(complete.summary.account_state).toBe("normal");- expect(complete.summary.count).toBeGreaterThan(0);- }- });-- it("treats campaign.status_name='ENABLED' as enabled even when status is the numeric enum (Demo2 bug — 2026-05-19)", async () => {- // Live shape: campaign.status is the integer enum (2 = ENABLED) and- // campaign.status_name is the string companion. Before the fix, the- // classifier checked .status === 'ENABLED' (string compare against- // an integer), got false, and classified the account empty even- // when a real campaign was running.- const numericOnly = {- ...EMPTY_REPORTS_INNER,- campaigns_summary: {- rowCount: 1,- rows: [- {- campaign: { name: "NotFair - Google Ads", status: 2, status_name: "ENABLED" },- metrics: { cost_micros: 39_390_000, impressions: 42 },- },- ],- },- };- mcpRpcMock.mockResolvedValueOnce(mockToolCallResult(numericOnly));- const events = await collect("acme");- // Spend is $39 (over the $10 threshold) and status enum says ENABLED,- // so account_state should NOT be 'empty'.- const complete = events.find((e) => e.type === "audit:complete");- if (complete && complete.type === "audit:complete") {- expect(complete.summary.account_state).toBe("normal");- }- });-- it("classifies as empty when ok=false (script-side error in envelope)", async () => {- // Defensive: if the runScript envelope reports ok=false, treat as- // malformed_response so the user sees a real error instead of silent- // 'empty' misclassification.- const errorEnvelope = JSON.stringify({- ok: false,- error: { message: "GAQL syntax error" },- });- mcpRpcMock.mockResolvedValueOnce({- ok: true,- result: {- content: [{ type: "text", text: errorEnvelope }],- isError: false,- },- });- const events = await collect("acme");- expect(events.find((e) => e.type === "audit:error")).toMatchObject({- kind: "malformed_response",- });- });- });-- describe("D7: best-effort FIRST_TURN.md + memory writes", () => {- beforeEach(() => {- mcpRpcMock.mockResolvedValue(mockToolCallResult(NORMAL_REPORTS));- });-- it("completes audit even when FIRST_TURN.md write fails", async () => {- writeFileMock.mockRejectedValueOnce(new Error("ENOSPC"));- const events = await collect("acme");- expect(events.some((e) => e.type === "audit:complete")).toBe(true);- });-- it("completes audit even when memory write fails", async () => {- openclawMock.mockRejectedValueOnce(new Error("memory service down"));- const events = await collect("acme");- expect(events.some((e) => e.type === "audit:complete")).toBe(true);- });- });-});diff --git a/src/server/onboarding/audit.ts b/src/server/onboarding/audit.tsdeleted file mode 100644index 2464428f..00000000--- a/src/server/onboarding/audit.ts+++ /dev/null@@ -1,1089 +0,0 @@-import { mkdir, writeFile } from "node:fs/promises";-import { homedir } from "node:os";-import { join } from "node:path";--import { logAgentAction } from "@/server/db/agent-actions";-import { getMcpConfig, mcpRpc } from "@/server/mcp/rpc";-import { openclaw } from "@/server/openclaw/cli";-import { storedMcpKey } from "@/server/mcp-catalog";--/**- * Google Ads onboarding audit.- *- * Flow:- * 1. Read project-scoped MCP credentials via getMcpConfig- * 2. Call MCP `tools/call runScript` with a fixed GAQL fan-out script- * (deterministic, no LLM in critical path per D11)- * 3. Iterate categories, classify findings, emit per-finding events- * 4. Persist canonical record to agent_actions (D10 + D12: load-bearing)- * 5. Best-effort write FIRST_TURN.md for the CMO + memory tag (D7)- *- * Events are emitted via an AsyncGenerator. The SSE route (Lane A4) pipes- * them to the client with small stagger for visual rhythm (D17).- *- * Decisions wired in:- * - D7 — FIRST_TURN.md sentinel for CMO first-turn greeting- * - D10 — agent_actions canonical record; OpenClaw memory derived- * - D11 — direct HTTP to MCP runScript via shared rpc helper- * - D12 — fail-loud on SQLite write; best-effort on memory/file- * - D17 — backend constructs the stream; MCP returns bulk- * - D5 — empty-account branch when no campaigns or near-zero spend- */--export type FindingCategory =- | "WASTED_SPEND"- | "LOW_QS"- | "SEARCH_TERM_GAP"- | "BUDGET_PACING"- | "ACCOUNT_SNAPSHOT"- | "NEXT_STEPS";--/**- * Category-display order and Top Fix tie-break order.- *- * ACCOUNT_SNAPSHOT is informational — it always fires when the account has- * any spend and gives the user proof-of-work ("the audit looked at real- * data"). NEXT_STEPS is the agency-playbook category: for any non-empty- * account, it surfaces 1-3 archetype-tailored recommendations with explicit- * cron cadences (daily/weekly/monthly) the CMO can then propose in chat via- * the existing propose_cron pattern (D8).- *- * Listed LAST so actionable categories render above them in the UI.- */-const CATEGORY_PRIORITY: FindingCategory[] = [- "WASTED_SPEND",- "LOW_QS",- "SEARCH_TERM_GAP",- "BUDGET_PACING",- "ACCOUNT_SNAPSHOT",- "NEXT_STEPS",-];--/** Categories eligible to be promoted to "Top Fix" (must be actionable). */-const TOP_FIX_ELIGIBLE: ReadonlySet<FindingCategory> = new Set([- "WASTED_SPEND",- "LOW_QS",- "SEARCH_TERM_GAP",- "BUDGET_PACING",-]);--/**- * Map each FindingCategory to the GAQL query name in AUDIT_SCRIPT that it- * transforms. Most are 1:1 (lowercased category = query name). The- * snapshot + playbook categories both aggregate over campaigns_summary.- */-const SOURCE_REPORT_FOR: Record<FindingCategory, string> = {- WASTED_SPEND: "wasted_spend",- LOW_QS: "low_qs",- SEARCH_TERM_GAP: "search_term_gap",- BUDGET_PACING: "budget_pacing",- ACCOUNT_SNAPSHOT: "campaigns_summary",- NEXT_STEPS: "campaigns_summary",-};--export type Finding = {- id: string;- category: FindingCategory;- headline: string;- evidence: string;- suggested_action: string;- /** Estimated dollar impact per month — used for Top Fix promotion. */- dollar_impact_usd: number;-};--export type AccountState = "normal" | "empty";--export type AuditSummary = {- count: number;- account_state: AccountState;- top_fix_id: string | null;- category_errors: Array<{ category: string; message: string }>;-};--export type AuditEvent =- | { type: "audit:start" }- | { type: "audit:finding"; finding: Finding }- | { type: "audit:finding-error"; category: string; message: string }- | { type: "audit:empty" }- | { type: "audit:complete"; summary: AuditSummary }- | {- type: "audit:error";- kind: "mcp_not_configured" | "stale_token" | "unreachable" | "rpc_error" | "malformed_response" | "timeout" | "aborted";- message: string;- }- | { type: "audit:persist-failed"; message: string };--const MCP_CATALOG_KEY = "notfair-googleads";-const MCP_TIMEOUT_MS = 30_000;--/**- * GAQL fan-out script. Runs ~5 SELECT queries in parallel inside the MCP's- * QuickJS sandbox via `ads.gaqlParallel`. Returns one object keyed by query- * name. All queries have LIMIT 50–100 to bound response size on large- * advertiser accounts (per §2 GAP 2.4). Scoped to LAST_30_DAYS for recency.- *- * Iterate on the SQL strings as you observe real accounts — the orchestration- * code in this file only cares about the response shape, not the WHERE- * clauses.- */-const AUDIT_SCRIPT = `-return await ads.gaqlParallel([- {- name: "wasted_spend",- query: \`- SELECT- ad_group_criterion.keyword.text,- ad_group_criterion.keyword.match_type,- ad_group.name,- campaign.name,- metrics.cost_micros,- metrics.conversions,- metrics.clicks- FROM keyword_view- WHERE segments.date DURING LAST_30_DAYS- AND metrics.cost_micros > 100000- AND metrics.conversions = 0- AND ad_group_criterion.status = 'ENABLED'- AND campaign.status = 'ENABLED'- ORDER BY metrics.cost_micros DESC- LIMIT 50- \`,- },- {- name: "low_qs",- query: \`- SELECT- ad_group_criterion.keyword.text,- ad_group.name,- campaign.name,- ad_group_criterion.quality_info.quality_score,- metrics.impressions,- metrics.cost_micros- FROM keyword_view- WHERE ad_group_criterion.quality_info.quality_score < 5- AND ad_group_criterion.quality_info.quality_score > 0- AND segments.date DURING LAST_30_DAYS- AND metrics.impressions > 100- ORDER BY metrics.impressions DESC- LIMIT 50- \`,- },- {- name: "search_term_gap",- query: \`- SELECT- search_term_view.search_term,- metrics.conversions,- metrics.cost_micros,- campaign.name,- search_term_view.status- FROM search_term_view- WHERE segments.date DURING LAST_30_DAYS- AND metrics.conversions > 0- AND search_term_view.status = 'NONE'- ORDER BY metrics.conversions DESC- LIMIT 50- \`,- },- {- name: "budget_pacing",- query: \`- SELECT- campaign.name,- campaign_budget.amount_micros,- metrics.cost_micros,- metrics.impressions- FROM campaign- WHERE segments.date DURING YESTERDAY- AND campaign.status = 'ENABLED'- ORDER BY metrics.cost_micros DESC- LIMIT 50- \`,- },- {- name: "campaigns_summary",- query: \`- SELECT- campaign.name,- campaign.status,- metrics.cost_micros,- metrics.impressions- FROM campaign- WHERE segments.date DURING LAST_30_DAYS- LIMIT 100- \`,- },-], { partial: true });-`;--type GaqlRow = Record<string, unknown>;-type GaqlReport = { rows?: GaqlRow[]; error?: string };-type ScriptResult = Record<string, GaqlReport | { error: string }>;--/**- * The MCP runScript tool wraps the script's return value in this envelope.- * Real shape observed against notfair.co/api/mcp/google_ads:- * { ok: true, result: { <name>: GaqlReport }, resultTruncated, logs,- * logsTruncated, timedOut, elapsedMs }- * Our script returns the `ads.gaqlParallel([...])` result; the MCP server- * wraps it. We must unwrap `result` before treating it as the category dict.- */-type RunScriptEnvelope = {- ok?: boolean;- result?: ScriptResult;- resultTruncated?: boolean;- timedOut?: boolean;- error?: { message?: string };-};--type McpToolCallResult = {- content?: Array<{ type?: string; text?: string }>;- isError?: boolean;-};--export type RunAuditOptions = {- /**- * The Google Ads customer ID to audit. When omitted, MCP picks the bearer's- * default account — fine for single-account bearers but the multi-account- * Demo2 case made this misleading. The onboarding flow now stores the- * user's selection on projects.google_ads_account_id and passes it here.- */- accountId?: string | null;-};--/**- * Run the audit and yield events. Caller is responsible for piping events- * to whichever surface the user is watching (SSE, log, etc).- */-export async function* runAudit(- project_slug: string,- signal?: AbortSignal,- options: RunAuditOptions = {},-): AsyncGenerator<AuditEvent, void, void> {- yield { type: "audit:start" };-- const cfg = await getMcpConfig(storedMcpKey(project_slug, MCP_CATALOG_KEY));- if (!cfg) {- yield {- type: "audit:error",- kind: "mcp_not_configured",- message: "Google Ads MCP is not configured for this project.",- };- return;- }-- const runScriptArgs: Record<string, unknown> = {- code: AUDIT_SCRIPT,- timeoutMs: 45_000,- };- if (options.accountId) {- runScriptArgs.accountId = options.accountId;- }-- const rpcResult = await mcpRpc<McpToolCallResult>(- cfg.url,- cfg.token,- "tools/call",- { name: "runScript", arguments: runScriptArgs },- { timeoutMs: MCP_TIMEOUT_MS, signal },- );-- if (!rpcResult.ok) {- yield mapRpcError(rpcResult);- return;- }-- const reports = parseScriptResult(rpcResult.result);- if (!reports) {- yield {- type: "audit:error",- kind: "malformed_response",- message: "MCP runScript returned an unexpected payload shape.",- };- return;- }-- const findings: Finding[] = [];- const categoryErrors: Array<{ category: string; message: string }> = [];-- for (const category of CATEGORY_PRIORITY) {- const reportKey = SOURCE_REPORT_FOR[category];- const report = reports[reportKey];- if (!report) continue;- if ("error" in report && report.error) {- // ACCOUNT_SNAPSHOT sourcing from campaigns_summary inherits its error;- // surface it under the snapshot category so the user sees the failure- // in context.- yield {- type: "audit:finding-error",- category,- message: report.error,- };- categoryErrors.push({ category, message: report.error });- continue;- }- const rows = (report as GaqlReport).rows ?? [];- const transformed = TRANSFORMERS[category](rows);- for (const f of transformed) {- findings.push(f);- yield { type: "audit:finding", finding: f };- }- }-- const accountState = classifyAccountState(reports, findings);- if (accountState === "empty") {- yield { type: "audit:empty" };- }-- const topFix = pickTopFix(findings);- const summary: AuditSummary = {- count: findings.length,- account_state: accountState,- top_fix_id: topFix?.id ?? null,- category_errors: categoryErrors,- };-- // D12: agent_actions write is load-bearing. If it throws, fail loud.- try {- logAgentAction({- project_slug,- agent_id: `${project_slug}-google-ads`,- action_type: "audit_completed",- summary: buildSummaryLine(findings, accountState, topFix),- reasoning: buildReasoningLine(summary),- payload: { findings, summary, category_errors: categoryErrors },- });- } catch (err) {- yield {- type: "audit:persist-failed",- message: err instanceof Error ? err.message : String(err),- };- return;- }-- // D7: FIRST_TURN.md + OpenClaw memory writes are best-effort projections.- // Failure must NOT block the completion event — the canonical record is- // already in agent_actions.- await safeWriteFirstTurn(project_slug, findings, topFix, accountState);- await safeWriteMemoryTag(project_slug, summary);-- yield { type: "audit:complete", summary };-}--function mapRpcError(- r: Extract<Awaited<ReturnType<typeof mcpRpc>>, { ok: false }>,-): AuditEvent {- if (r.kind === "http_error" && (r.status === 401 || r.status === 403)) {- return {- type: "audit:error",- kind: "stale_token",- message: `Google Ads token rejected (HTTP ${r.status}).`,- };- }- if (r.kind === "http_error") {- return {- type: "audit:error",- kind: "unreachable",- message: `MCP returned HTTP ${r.status}.`,- };- }- if (r.kind === "timeout") {- return { type: "audit:error", kind: "timeout", message: "MCP call timed out." };- }- if (r.kind === "aborted") {- return { type: "audit:error", kind: "aborted", message: "Audit cancelled." };- }- if (r.kind === "rpc_error") {- return {- type: "audit:error",- kind: "rpc_error",- message: `RPC error ${r.code}: ${r.message}`,- };- }- if (r.kind === "malformed_response") {- return {- type: "audit:error",- kind: "malformed_response",- message: r.message,- };- }- return {- type: "audit:error",- kind: "unreachable",- message: r.message,- };-}--/**- * MCP wraps the runScript return value in `{content: [{type: 'text', text: <JSON>}], isError}`.- * Inside that, the script's return value is itself wrapped by the runScript- * tool in `{ ok, result, resultTruncated, ... }` (verified live against- * notfair.co/api/mcp/google_ads). We unwrap both layers and return just the- * category dict (`result`). Returns null when any layer is missing or shaped- * unexpectedly (treat as malformed_response upstream).- */-function parseScriptResult(payload: McpToolCallResult): ScriptResult | null {- if (!payload || typeof payload !== "object") return null;- if (payload.isError) return null;- const content = payload.content;- if (!Array.isArray(content) || content.length === 0) return null;- const text = content[0]?.text;- if (typeof text !== "string") return null;- let parsed: unknown;- try {- parsed = JSON.parse(text);- } catch {- return null;- }- if (!parsed || typeof parsed !== "object") return null;- const envelope = parsed as RunScriptEnvelope & ScriptResult;- // Preferred path: the runScript envelope with `result`.- if (envelope.ok === true && envelope.result && typeof envelope.result === "object") {- return envelope.result;- }- // Tool-side script error — surface as malformed_response so the caller- // emits a clear audit:error event rather than silently classifying empty.- if (envelope.ok === false) return null;- // Tolerate older or alternate shapes where the script returned the dict- // directly. Safe because the runScript envelope always carries `ok`; if- // it's absent we assume the body IS the category dict.- return envelope as ScriptResult;-}--function classifyAccountState(- reports: ScriptResult,- findings: Finding[],-): AccountState {- const summary = reports.campaigns_summary;- if (!summary || "error" in summary) {- // No summary data — fall back to findings count.- return findings.length === 0 ? "empty" : "normal";- }- const rows = (summary as GaqlReport).rows ?? [];- if (rows.length === 0) return "empty";- const last30Spend = rows.reduce(- (acc, r) => acc + microsAsDollars(getMetric(r, "metrics.cost_micros")),- 0,- );- if (last30Spend < 10) return "empty";- if (!rows.some(isEnabledCampaign)) return "empty";- return "normal";-}--/**- * Google Ads returns campaign.status as BOTH a numeric protobuf enum and a- * string-named convenience field. The numeric value of ENABLED is 2; the- * gaqlParallel result includes a `status_name: "ENABLED"` companion field.- * We accept either shape so behavior survives MCP/library upgrades that- * tighten or loosen the response. Numeric enum reference:- * UNSPECIFIED=0, UNKNOWN=1, ENABLED=2, PAUSED=3, REMOVED=4- */-const CAMPAIGN_STATUS_ENABLED_ENUM = 2;-function isEnabledCampaign(row: GaqlRow): boolean {- const nameStr = getString(row, "campaign.status_name");- if (nameStr === "ENABLED") return true;- const numeric = getMetric(row, "campaign.status");- if (numeric === CAMPAIGN_STATUS_ENABLED_ENUM) return true;- const statusStr = getString(row, "campaign.status");- if (statusStr === "ENABLED") return true;- return false;-}--/**- * Top Fix = highest dollar_impact_usd among actionable findings (snapshot- * categories are skipped). Tie-break by CATEGORY_PRIORITY order. Returns- * null when only informational findings exist.- */-function pickTopFix(findings: Finding[]): Finding | null {- const actionable = findings.filter((f) => TOP_FIX_ELIGIBLE.has(f.category));- if (actionable.length === 0) return null;- return actionable.slice().sort((a, b) => {- if (a.dollar_impact_usd !== b.dollar_impact_usd) {- return b.dollar_impact_usd - a.dollar_impact_usd;- }- return (- CATEGORY_PRIORITY.indexOf(a.category) -- CATEGORY_PRIORITY.indexOf(b.category)- );- })[0]!;-}--/**- * Account archetypes for the NEXT_STEPS playbook. Pure rule-based classifier- * — what a real agency would say after 30 seconds of looking at this account.- *- * empty — 0 enabled campaigns or campaigns_summary empty- * no_tracking — has impressions + spend but 0 conversions in 30d- * (most common new-advertiser failure mode)- * low_volume — has conversions but < 1000 impressions/mo- * (not enough signal to optimize yet)- * active — sustained activity, conversions, real volume- */-type AccountArchetype = "empty" | "no_tracking" | "low_volume" | "active";--function classifyArchetype(rows: GaqlRow[]): AccountArchetype {- const enabled = rows.filter(isEnabledCampaign);- if (enabled.length === 0) return "empty";- const totalConversions = rows.reduce(- (acc, r) => acc + (getMetric(r, "metrics.conversions") ?? 0),- 0,- );- const totalImpressions = rows.reduce(- (acc, r) => acc + (getMetric(r, "metrics.impressions") ?? 0),- 0,- );- if (totalConversions === 0 && totalImpressions > 0) return "no_tracking";- if (totalImpressions < 1000) return "low_volume";- return "active";-}--/**- * Agency-style playbook per archetype. Each entry is a single Finding the- * UI renders as a card and the CMO chat picks up from FIRST_TURN.md. The- * `suggested_action` includes the explicit cron cadence — daily/weekly/- * monthly — so the CMO can propose it via the propose_cron pattern (D8).- *- * Source: distilled from common agency onboarding playbooks (e.g., Google- * Ads Editor onboarding flows, Optmyzr account audits, Wordstream- * "First 90 days" checklist). Conservative defaults — won't suggest- * anything an agency wouldn't.- */-const NEXT_STEPS_PLAYBOOK: Record<AccountArchetype, Finding[]> = {- empty: [- // Empty accounts use the D26 roadmap card in the UI; NEXT_STEPS adds- // ongoing-ops context for when the user does start campaigns.- {- id: "next:setup_conv_tracking",- category: "NEXT_STEPS",- headline: "Install conversion tracking before your first $10 of spend.",- evidence:- "No campaigns running yet — installing tracking now means your first dollar generates optimization signal.",- suggested_action:- "Add the Google Ads conversion tag (or GA4 events) on your site. Once installed, I can run a daily 'is tracking firing?' health check at 9am.",- dollar_impact_usd: 0,- },- ],- no_tracking: [- {- id: "next:install_conv_tracking",- category: "NEXT_STEPS",- headline: "Install conversion tracking — 0 conversions on real spend.",- evidence:- "Your account is running ads and getting impressions, but no conversions are recorded. Without tracking, optimization is blind.",- suggested_action:- "Add the Google Ads conversion tag (or import GA4 events). I can schedule a daily 9am check that alerts you if conv tracking goes silent again.",- dollar_impact_usd: 0,- },- {- id: "next:weekly_search_term_review",- category: "NEXT_STEPS",- headline: "Set up a weekly search-term review.",- evidence:- "New accounts collect broad-match noise fast — by week 2 you usually have 5-15 negative-keyword candidates.",- suggested_action:- "Schedule a Monday 9am cron: pull last week's search terms with cost > $0 and 0 conversions; surface as a one-click negative-keyword list.",- dollar_impact_usd: 0,- },- {- id: "next:daily_anomaly",- category: "NEXT_STEPS",- headline: "Daily spend anomaly check.",- evidence:- "Small accounts can hit budget mid-morning if a competitor bids up an auction. Catching it day-of beats finding out Monday.",- suggested_action:- "Schedule a daily 9am cron: alert if yesterday's spend > 2× trailing-7-day average, or if a campaign hit its daily cap before noon.",- dollar_impact_usd: 0,- },- ],- low_volume: [- {- id: "next:raise_bids_or_budget",- category: "NEXT_STEPS",- headline:- "Bid or budget may be too low — under 1,000 impressions/month is not enough to optimize.",- evidence:- "Optimization algorithms need ~30 conversions/month to learn. Increase bids on the top 3 keywords or raise the daily budget for 1-2 weeks to gather signal.",- suggested_action:- "Want me to pull bid simulator data for your top 3 keywords + recommend an adjustment? Then a weekly Friday 9am pacing check.",- dollar_impact_usd: 0,- },- {- id: "next:weekly_search_term_review",- category: "NEXT_STEPS",- headline: "Set up a weekly search-term review.",- evidence:- "Even low-volume accounts benefit from cleaning broad-match noise early — sets the foundation for when you scale.",- suggested_action:- "Schedule a Monday 9am cron: pull last week's search terms with cost > $0 and 0 conversions.",- dollar_impact_usd: 0,- },- {- id: "next:daily_anomaly",- category: "NEXT_STEPS",- headline: "Daily spend anomaly check.",- evidence:- "Even quiet accounts get budget spikes from auction-time changes.",- suggested_action:- "Schedule a daily 9am cron: alert if yesterday's spend > 2× the trailing 7-day average.",- dollar_impact_usd: 0,- },- ],- active: [- {- id: "next:daily_wasted_spend",- category: "NEXT_STEPS",- headline: "Daily wasted-spend monitor.",- evidence:- "Active accounts accumulate $5-50/day of wasted spend on keywords that stop converting. Daily catch beats weekly cleanup.",- suggested_action:- "Schedule a daily 9am cron: surface keywords with > $5 yesterday spend and 0 conversions in the last 7 days for one-click pause.",- dollar_impact_usd: 0,- },- {- id: "next:weekly_bid_optimization",- category: "NEXT_STEPS",- headline: "Weekly bid-optimization pass.",- evidence:- "Small adjustments compound — agencies typically see 8-15% CPA improvement from disciplined weekly bid management.",- suggested_action:- "Schedule a Monday 9am cron: review top 20 keywords by spend; suggest bid adjustments based on last 14 days of conversion data.",- dollar_impact_usd: 0,- },- {- id: "next:monthly_structure_review",- category: "NEXT_STEPS",- headline: "Monthly campaign-structure review.",- evidence:- "Account drift is real — after 90 days, most accounts benefit from re-segmenting ad groups by search intent.",- suggested_action:- "Schedule a first-Monday-of-the-month cron: review ad group structure + propose 1-2 refactor opportunities.",- dollar_impact_usd: 0,- },- ],-};--const TRANSFORMERS: Record<FindingCategory, (rows: GaqlRow[]) => Finding[]> = {- NEXT_STEPS: (rows) => {- // Always fire — even empty accounts get the "install tracking first"- // recommendation. The classifier maps account state to a 1-3 finding- // playbook; the UI renders them as cards under the NEXT_STEPS label.- const archetype = classifyArchetype(rows);- return NEXT_STEPS_PLAYBOOK[archetype];- },- ACCOUNT_SNAPSHOT: (rows) => {- if (rows.length === 0) return [];- // Aggregate across all rows the campaigns_summary returned.- const totalSpend = rows.reduce(- (acc, r) => acc + microsAsDollars(getMetric(r, "metrics.cost_micros")),- 0,- );- const totalImpressions = rows.reduce(- (acc, r) => acc + (getMetric(r, "metrics.impressions") ?? 0),- 0,- );- const totalConversions = rows.reduce(- (acc, r) => acc + (getMetric(r, "metrics.conversions") ?? 0),- 0,- );- const enabled = rows.filter(isEnabledCampaign);- const enabledCount = enabled.length;- const totalCount = rows.length;- const topCampaign = rows- .slice()- .sort(- (a, b) =>- (getMetric(b, "metrics.cost_micros") ?? 0) -- (getMetric(a, "metrics.cost_micros") ?? 0),- )[0];- const topName = topCampaign- ? (getString(topCampaign, "campaign.name") ?? "your top campaign")- : "your top campaign";-- const headline =- enabledCount === 1- ? `${topName}: $${totalSpend.toFixed(2)} spent in the last 30 days`- : `${enabledCount} active campaign${enabledCount === 1 ? "" : "s"} spent $${totalSpend.toFixed(2)} in the last 30 days`;-- const evidenceParts = [- `${totalImpressions.toLocaleString()} impressions`,- `${totalConversions.toFixed(0)} conversion${totalConversions === 1 ? "" : "s"}`,- `${enabledCount}/${totalCount} campaign${totalCount === 1 ? "" : "s"} enabled`,- ];-- // Suggested action varies by what we see — never just "looks fine."- let suggested: string;- if (totalConversions === 0 && totalImpressions > 0) {- suggested =- "0 conversions in 30 days — install conversion tracking or revisit your offer/landing page.";- } else if (totalImpressions < 100) {- suggested =- "Very low impressions — your bids or budget may be capping reach. Want me to check?";- } else if (totalConversions > 0 && totalSpend / totalConversions > 100) {- suggested = `High CPA at $${(totalSpend / totalConversions).toFixed(2)} per conversion — let me look at where the spend is going.`;- } else {- suggested = "Want me to look for ways to scale this campaign?";- }-- return [- {- id: "account_snapshot",- category: "ACCOUNT_SNAPSHOT",- headline,- evidence: evidenceParts.join(" · "),- suggested_action: suggested,- dollar_impact_usd: 0,- },- ];- },- WASTED_SPEND: (rows) => {- if (rows.length === 0) return [];- // Group by campaign — one finding per campaign with multiple wasted kws.- const byCampaign = new Map<string, GaqlRow[]>();- for (const r of rows) {- const cn = getString(r, "campaign.name") ?? "(unknown)";- const arr = byCampaign.get(cn) ?? [];- arr.push(r);- byCampaign.set(cn, arr);- }- // Pick the campaign with the biggest wasted spend total — one finding.- let top: { campaign: string; rows: GaqlRow[]; spend: number } | null = null;- for (const [campaign, group] of byCampaign) {- const spend = group.reduce(- (acc, r) => acc + microsAsDollars(getMetric(r, "metrics.cost_micros")),- 0,- );- if (!top || spend > top.spend) top = { campaign, rows: group, spend };- }- if (!top) return [];- const dailyBurn = top.spend / 30;- const monthlyBurn = top.spend;- const clicks = top.rows.reduce(- (acc, r) => acc + (getMetric(r, "metrics.clicks") ?? 0),- 0,- );- return [- {- id: `wasted_spend:${slugifyForId(top.campaign)}`,- category: "WASTED_SPEND",- headline: `${top.campaign} is burning $${dailyBurn.toFixed(0)}/day on ${top.rows.length} zero-conv keyword${top.rows.length === 1 ? "" : "s"}`,- evidence: `Last 30 days · ${clicks.toLocaleString()} clicks · $${top.spend.toFixed(0)} spent · 0 conv`,- suggested_action: `Pause those ${top.rows.length} keywords; expected savings $${monthlyBurn.toFixed(0)}/mo`,- dollar_impact_usd: monthlyBurn,- },- ];- },- LOW_QS: (rows) => {- if (rows.length === 0) return [];- const count = rows.length;- const impressions = rows.reduce(- (acc, r) => acc + (getMetric(r, "metrics.impressions") ?? 0),- 0,- );- const monthlySpend = rows.reduce(- (acc, r) => acc + microsAsDollars(getMetric(r, "metrics.cost_micros")),- 0,- );- // Low QS roughly costs 20% extra in CPC — back-of-envelope impact.- const impact = monthlySpend * 0.2;- return [- {- id: "low_qs",- category: "LOW_QS",- headline: `${count} keyword${count === 1 ? "" : "s"} below Quality Score 5 — check ad relevance`,- evidence: `${impressions.toLocaleString()} impressions, ~$${monthlySpend.toFixed(0)}/mo spend with QS penalty`,- suggested_action: `Tighten ad copy + landing page match; ~$${impact.toFixed(0)}/mo recoverable`,- dollar_impact_usd: impact,- },- ];- },- SEARCH_TERM_GAP: (rows) => {- if (rows.length === 0) return [];- const count = rows.length;- const conversions = rows.reduce(- (acc, r) => acc + (getMetric(r, "metrics.conversions") ?? 0),- 0,- );- const spend = rows.reduce(- (acc, r) => acc + microsAsDollars(getMetric(r, "metrics.cost_micros")),- 0,- );- // Adding converting terms as keywords typically improves CPA 10-25%.- const impact = spend * 0.15;- return [- {- id: "search_term_gap",- category: "SEARCH_TERM_GAP",- headline: `${count} converting search term${count === 1 ? "" : "s"} not in your keyword list`,- evidence: `${conversions.toFixed(0)} conversions from $${spend.toFixed(0)} spend in 30d on unmatched terms`,- suggested_action: `Add as exact-match keywords; ~$${impact.toFixed(0)}/mo CPA upside`,- dollar_impact_usd: impact,- },- ];- },- BUDGET_PACING: (rows) => {- if (rows.length === 0) return [];- // Filter for campaigns that hit ≥95% of yesterday's budget.- const capped = rows.filter((r) => {- const spend = microsAsDollars(getMetric(r, "metrics.cost_micros"));- const budget = microsAsDollars(getMetric(r, "campaign_budget.amount_micros"));- return budget > 0 && spend >= budget * 0.95;- });- if (capped.length === 0) return [];- const monthlyImpact = capped.reduce((acc, r) => {- const budget = microsAsDollars(getMetric(r, "campaign_budget.amount_micros"));- // Budget-capped campaigns typically lose ~30% of available impressions.- return acc + budget * 30 * 0.3;- }, 0);- return [- {- id: "budget_pacing",- category: "BUDGET_PACING",- headline: `${capped.length} campaign${capped.length === 1 ? "" : "s"} hit daily cap yesterday`,- evidence: `Budget-capped at ≥95% by end of day — missed impressions`,- suggested_action: `Raise daily cap or shift budget across campaigns; ~$${monthlyImpact.toFixed(0)}/mo recoverable reach`,- dollar_impact_usd: monthlyImpact,- },- ];- },-};--function buildSummaryLine(- findings: Finding[],- state: AccountState,- topFix: Finding | null,-): string {- if (state === "empty") return "Audit complete — account is empty or just getting started.";- if (topFix) {- return `Audit complete — ${findings.length} finding${findings.length === 1 ? "" : "s"}. Top: ${topFix.headline}`;- }- return `Audit complete — ${findings.length} findings.`;-}--function buildReasoningLine(summary: AuditSummary): string {- const parts = [- `${summary.count} actionable findings`,- `account_state=${summary.account_state}`,- ];- if (summary.category_errors.length > 0) {- parts.push(- `${summary.category_errors.length} category error${summary.category_errors.length === 1 ? "" : "s"}`,- );- }- return parts.join("; ");-}--/**- * Drop FIRST_TURN.md in the CMO's workspace per D19. Best-effort: never throw.- * The contract is the markdown shape in the CEO plan's D19 section.- */-async function safeWriteFirstTurn(- project_slug: string,- findings: Finding[],- topFix: Finding | null,- accountState: AccountState,-): Promise<void> {- try {- const dataDir = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");- const cmoWorkspace = join(dataDir, "agents", `${project_slug}-cmo`);- await mkdir(cmoWorkspace, { recursive: true });- const body = renderFirstTurn(project_slug, findings, topFix, accountState);- await writeFile(join(cmoWorkspace, "FIRST_TURN.md"), body, "utf8");- } catch (err) {- console.warn(`FIRST_TURN.md write failed for ${project_slug}:`, err);- }-}--function renderFirstTurn(- project_slug: string,- findings: Finding[],- topFix: Finding | null,- accountState: AccountState,-): string {- const ts = new Date().toISOString();- const snapshot = findings.find((f) => f.category === "ACCOUNT_SNAPSHOT");- const nextSteps = findings.filter((f) => f.category === "NEXT_STEPS");- const actionable = findings.filter(- (f) => f.category !== "ACCOUNT_SNAPSHOT" && f.category !== "NEXT_STEPS",- );-- const lines: string[] = [- "# First-turn context for the CMO",- "",- "You have just connected the user's Google Ads account and run a baseline audit.",- "This is a one-shot context: on your FIRST chat turn after the user opens this",- "project's CMO chat, weave the highlights into your greeting, then move this",- "file to MEMORY/last-first-turn-<YYYY-MM-DD>.md so you don't repeat it.",- "",- "## Audit metadata",- `- Project: ${project_slug}`,- `- Audit run at: ${ts}`,- `- Account state: ${accountState}`,- `- Findings count: ${findings.length}`,- "",- ];-- if (snapshot) {- lines.push(- "## Account snapshot",- `- ${snapshot.headline}`,- `- ${snapshot.evidence}`,- "",- );- }-- if (accountState === "empty") {- lines.push(- "## Top suggestion (new account — empty audit)",- `- Set a daily budget for your first campaign — most B2B starts at $50-100/day to gather signal.`,- "",- "## Other roadmap items",- `- Decide your first goal: leads vs traffic vs brand. I can help you pick.`,- `- Talk it through with me — 30 minutes and you'll have a campaign brief.`,- "",- );- } else if (topFix) {- const others = actionable.filter((f) => f.id !== topFix.id);- lines.push(- "## Top finding (actionable)",- `- Category: ${topFix.category}`,- `- Headline: ${topFix.headline}`,- `- Evidence: ${topFix.evidence}`,- `- Suggested action: ${topFix.suggested_action}`,- "",- );- if (others.length > 0) {- lines.push("## Other actionable findings");- for (const f of others) {- lines.push(`- ${f.category} — ${f.headline}`);- }- lines.push("");- }- }-- if (nextSteps.length > 0) {- lines.push(- "## Recommended ongoing work — DELEGATE THESE",- "These are the daily / weekly / monthly tasks a Google Ads agency would",- "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}**`,- ` Context: ${f.evidence}`,- ` Brief for the specialist: ${f.suggested_action}`,- "",- );- }- }-- // Suggested opener — varies by what we have. SHORT prose, then blocks.- lines.push("## Suggested opener (prose, then blocks)");- if (accountState === "empty") {- lines.push(- "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(- "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(- "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(- "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("");- return lines.join("\n");-}--/**- * Write a tagged memory entry on the CMO agent so later sessions can recall- * the audit via REM. Best-effort: subprocess failure does not block the- * audit's completion event. Logged for debugging.- */-async function safeWriteMemoryTag(- project_slug: string,- summary: AuditSummary,-): Promise<void> {- try {- const date = new Date().toISOString().slice(0, 10);- const tag = `google-ads-baseline:${date}`;- const content = `Google Ads baseline audit for ${project_slug} on ${date}: ${summary.count} findings, account_state=${summary.account_state}.`;- await openclaw(- [- "memory",- "write",- "--agent",- `${project_slug}-cmo`,- "--tag",- tag,- "--content",- content,- ],- { json: false },- );- } catch (err) {- console.warn(`OpenClaw memory write failed for ${project_slug}:`, err);- }-}--// ── tiny accessors ──────────────────────────────────────────────────--function getMetric(row: GaqlRow, dotted: string): number | undefined {- const v = getNested(row, dotted);- if (typeof v === "number") return v;- if (typeof v === "string") {- const n = Number(v);- return Number.isFinite(n) ? n : undefined;- }- return undefined;-}--function getString(row: GaqlRow, dotted: string): string | undefined {- const v = getNested(row, dotted);- return typeof v === "string" ? v : undefined;-}--function getNested(row: GaqlRow, dotted: string): unknown {- const parts = dotted.split(".");- let cur: unknown = row;- for (const p of parts) {- if (!cur || typeof cur !== "object") return undefined;- cur = (cur as Record<string, unknown>)[p];- }- return cur;-}--function microsAsDollars(micros: number | undefined): number {- if (typeof micros !== "number" || !Number.isFinite(micros)) return 0;- return micros / 1_000_000;-}--function slugifyForId(s: string): string {- return s- .toLowerCase()- .replace(/[^a-z0-9]+/g, "-")- .replace(/^-|-$/g, "")- .slice(0, 40);-}diff --git a/src/server/onboarding/cmo-task-brief.ts b/src/server/onboarding/cmo-task-brief.tsnew file mode 100644index 00000000..db03b876--- /dev/null+++ b/src/server/onboarding/cmo-task-brief.ts@@ -0,0 +1,83 @@+/**+ * 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.+ *+ * Keeping this server-side so the wording stays in lockstep with the CMO+ * system prompt; templated rather than free-form so each new project+ * onboarding receives the same expectations.+ */+export function buildOnboardingBrief(args: {+ project_slug: string;+ 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 title = "Audit the account and propose a starter playbook";++ const brief = [+ `Project: ${args.project_display_name} (${args.project_slug})`,+ `Google Ads account: ${account}`,+ "",+ "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.",+ "",+ "## 1. Probe the account",+ "",+ "Use the notfair-googleads MCP `runScript` tool to gather (GAQL via",+ "`ads.gaql`, fan out with `ads.gaqlParallel`):",+ "- Customer info: status, currency, time zone",+ "- Last 30 days per enabled campaign: cost, impressions, clicks,",+ " conversions, conversion_value",+ "- Conversion tracking: count of conversion_actions + recent_conversions",+ "- Search terms (last 30d) with cost > $10 and conversions = 0",+ "- Keywords with quality_score < 5",+ "- Campaigns within $5 of their daily budget cap",+ "",+ "## 2. Classify the archetype",+ "",+ "One of:",+ "- empty — no enabled campaigns",+ "- no_tracking — campaigns but zero conversion_actions",+ "- low_volume — < 50 clicks / month or < $200 spend",+ "- active — meaningful data to optimize on",+ "",+ "## 3. Report findings to the user (in this reply)",+ "",+ "Markdown, scannable. Sections (skip any with no findings, don't pad):",+ "- **Account snapshot** — 1-2 sentences naming the archetype + spend",+ "- **Wasted spend** — top 3 search-term gaps with $ amounts",+ "- **Low quality scores** — top 3 keywords + their QS",+ "- **Budget pacing** — campaigns hitting cap",+ "- **Next steps** — 3 concrete actions tailored to the archetype",+ "",+ "Lead with the dollar figure or the most actionable finding. Don't ask",+ '"want me to..." — you\'re an orchestrator; delegate, don\'t advise.',+ "",+ "## 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.",+ "",+ "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."',+ ].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.",+ ].join(" ");++ return { title, brief, success_criteria };+}