Open-source SEO, GEO, and marketing skills for AI agents.
feat(onboarding): PROJECT.md as shared agent context + task-blocks-task gating
Yuting Zhong7c6403c7690e
diff --git a/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts b/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.tsindex 5d0d8863..b33e823a 100644--- a/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts+++ b/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts@@ -32,6 +32,8 @@ function makeProject(overrides: Partial<Project> = {}): Project {created_at: "now",archived_at: null,google_ads_account_id: null,+ website_url: null,+ codebase_path: null,...overrides,};}diff --git a/src/app/api/chat/route.test.ts b/src/app/api/chat/route.test.tsindex 24483d6c..ab50bd8e 100644--- a/src/app/api/chat/route.test.ts+++ b/src/app/api/chat/route.test.ts@@ -50,6 +50,8 @@ function makeProject(overrides: Partial<Project> = {}): Project {created_at: "now",archived_at: null,google_ads_account_id: null,+ website_url: null,+ codebase_path: null,...overrides,};}diff --git a/src/app/api/fs/pick-folder/route.ts b/src/app/api/fs/pick-folder/route.tsnew file mode 100644index 00000000..5fb52a14--- /dev/null+++ b/src/app/api/fs/pick-folder/route.ts@@ -0,0 +1,43 @@+import { homedir } from "node:os";+import { NextResponse } from "next/server";+import { pickFolder } from "@/server/fs/pick-folder";++export const dynamic = "force-dynamic";+export const runtime = "nodejs";++/**+ * Open the OS-native folder picker on the local machine and return the+ * chosen absolute path. The client calls this once when the user clicks+ * "Browse..." in the onboarding form — the dialog appears on the user's+ * own screen because this server runs locally (loopback-only).+ *+ * Method: POST (state-changing in the sense that it spawns a UI dialog).+ * No request body — the prompt/default location are baked in here so the+ * surface stays minimal. Future extension can accept a JSON body.+ */+export async function POST(_request: Request) {+ const result = await pickFolder({+ prompt: "Select your project's codebase folder",+ defaultLocation: homedir(),+ });+ if (result.ok) {+ return NextResponse.json({ ok: true, path: result.path });+ }+ if (result.kind === "cancelled") {+ return NextResponse.json({ ok: false, kind: "cancelled" });+ }+ if (result.kind === "unsupported") {+ return NextResponse.json(+ {+ ok: false,+ kind: "unsupported",+ message: `Native folder picker not implemented for ${result.platform}. Type the path manually for now.`,+ },+ { status: 501 },+ );+ }+ return NextResponse.json(+ { ok: false, kind: "error", message: result.message },+ { status: 500 },+ );+}diff --git a/src/app/api/projects/[slug]/provision/route.test.ts b/src/app/api/projects/[slug]/provision/route.test.tsindex 3a0f45f7..0a308293 100644--- a/src/app/api/projects/[slug]/provision/route.test.ts+++ b/src/app/api/projects/[slug]/provision/route.test.ts@@ -22,6 +22,8 @@ function makeProject(overrides: Partial<Project> = {}): Project {created_at: "now",archived_at: null,google_ads_account_id: null,+ website_url: null,+ codebase_path: null,...overrides,};}diff --git a/src/components/agent-task-workspace.test.tsx b/src/components/agent-task-workspace.test.tsxindex 425e226f..59cf0f8f 100644--- a/src/components/agent-task-workspace.test.tsx+++ b/src/components/agent-task-workspace.test.tsx@@ -81,6 +81,7 @@ function makeTask(overrides: Partial<Task> = {}): Task {error_message: null,thread_id: null,assigner_agent_id: "demo-cmo",+ blocked_by_task_id: null,created_at: new Date(Date.now() - 5 * 60_000).toISOString(),updated_at: new Date(Date.now() - 60_000).toISOString(),...overrides,diff --git a/src/components/onboarding-flow.tsx b/src/components/onboarding-flow.tsxindex 91749373..6bb10f1b 100644--- a/src/components/onboarding-flow.tsx+++ b/src/components/onboarding-flow.tsx@@ -3,7 +3,7 @@import { useActionState, useEffect, useRef, useState } from "react";import { useRouter, useSearchParams } from "next/navigation";import Link from "next/link";-import { AlertCircle, ChevronRight, Loader2, Plug } from "lucide-react";+import { AlertCircle, ChevronRight, FolderOpen, Loader2, Plug } from "lucide-react";import { toast } from "sonner";import { Button } from "@/components/ui/button";@@ -54,6 +54,71 @@ export function OnboardingFlow() {);}+// ── Codebase folder picker (Step 1 helper) ─────────────────────────+//+// Browsers don't expose absolute paths from `<input type="file"+// webkitdirectory>` or `showDirectoryPicker()` — security. Since this+// server runs on the user's own machine (loopback only), we shell out+// to the OS-native folder dialog via POST /api/fs/pick-folder and let+// the OS handle the picker UI. The field stays editable so users on+// platforms we don't yet support natively (Linux, Windows) can paste.++function CodebasePathPicker({ disabled }: { disabled: boolean }) {+ const [value, setValue] = useState("");+ const [picking, setPicking] = useState(false);++ async function onBrowse() {+ setPicking(true);+ try {+ const res = await fetch("/api/fs/pick-folder", { method: "POST" });+ const body = (await res.json()) as+ | { ok: true; path: string }+ | { ok: false; kind: "cancelled" }+ | { ok: false; kind: "unsupported" | "error"; message?: string };+ if (body.ok) {+ setValue(body.path);+ return;+ }+ if (body.kind === "cancelled") return; // silent — user closed dialog+ toast.error(body.message ?? "Couldn't open the folder picker.");+ } catch (err) {+ toast.error(err instanceof Error ? err.message : String(err));+ } finally {+ setPicking(false);+ }+ }++ return (+ <div className="flex gap-2">+ <Input+ id="codebase_path"+ name="codebase_path"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ placeholder="No folder selected"+ maxLength={500}+ disabled={disabled || picking}+ readOnly={picking}+ aria-label="Local codebase folder"+ />+ <Button+ type="button"+ variant="outline"+ onClick={onBrowse}+ disabled={disabled || picking}+ aria-label="Browse for a folder"+ >+ {picking ? (+ <Loader2 className="mr-1.5 size-4 animate-spin" />+ ) : (+ <FolderOpen className="mr-1.5 size-4" />+ )}+ Browse…+ </Button>+ </div>+ );+}+// ── Step 1: Name ───────────────────────────────────────────────────function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {@@ -77,16 +142,17 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {Let’s set up your CMO.</h1><p className="text-sm text-muted-foreground">- What should we call this project?+ Tell me what this project is so I can hit the ground running.</p></header><Card><CardHeader>- <CardTitle className="text-base">Project name</CardTitle>+ <CardTitle className="text-base">Project basics</CardTitle><CardDescription>- A project groups the agents and crons your CMO will manage. The slug- (used in agent names) is set once and immutable.+ Name is required. Site and codebase are optional but help the+ CMO write a more accurate first plan. Slug (used in agent+ names) is derived from the name and immutable.</CardDescription></CardHeader><CardContent>@@ -103,6 +169,38 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {disabled={isPending}/></div>+ <div className="space-y-2">+ <Label htmlFor="website_url">+ Website URL{" "}+ <span className="text-xs font-normal text-muted-foreground">+ (optional)+ </span>+ </Label>+ <Input+ id="website_url"+ name="website_url"+ type="url"+ placeholder="https://acme.com"+ maxLength={500}+ disabled={isPending}+ />+ <p className="text-xs text-muted-foreground">+ The CMO will skim a few pages to learn what you sell.+ </p>+ </div>+ <div className="space-y-2">+ <Label htmlFor="codebase_path">+ Local codebase folder{" "}+ <span className="text-xs font-normal text-muted-foreground">+ (optional)+ </span>+ </Label>+ <CodebasePathPicker disabled={isPending} />+ <p className="text-xs text-muted-foreground">+ Folder the CMO can read locally — README, package.json,+ top-level files. Skim only, not a code review.+ </p>+ </div>{errorMessage && (<p role="alert" className="text-sm text-destructive">{errorMessage}diff --git a/src/components/project-switcher.test.tsx b/src/components/project-switcher.test.tsxindex eafbaf09..418beb73 100644--- a/src/components/project-switcher.test.tsx+++ b/src/components/project-switcher.test.tsx@@ -47,8 +47,8 @@ function openMenu() {}const projects = [- { id: "1", slug: "proj-a", display_name: "Alpha", created_at: "", archived_at: null, google_ads_account_id: null },- { id: "2", slug: "proj-b", display_name: "Beta", created_at: "", archived_at: null, google_ads_account_id: null },+ { id: "1", slug: "proj-a", display_name: "Alpha", created_at: "", archived_at: null, google_ads_account_id: null, website_url: null, codebase_path: null },+ { id: "2", slug: "proj-b", display_name: "Beta", created_at: "", archived_at: null, google_ads_account_id: null, website_url: null, codebase_path: null },];beforeEach(() => {diff --git a/src/server/actions/projects.ts b/src/server/actions/projects.tsindex a6202476..42215ce8 100644--- a/src/server/actions/projects.ts+++ b/src/server/actions/projects.ts@@ -77,6 +77,11 @@ export async function createProjectAction(formData: FormData): Promise<void> {* Onboarding-flow variant of createProjectAction. Same create + async* provision (D6) but returns the slug to the caller instead of redirecting* to /. The client navigates to ?step=connect&slug=... after success.+ *+ * Also creates and starts the CMO's first task ("Learn the project and+ * write PROJECT.md") in the background so it runs in parallel with the+ * user doing OAuth. The downstream Google Ads audit task (minted in+ * setOnboardingAccountAction) gates on this one via blocked_by_task_id.*/export async function createProjectForOnboardingAction(formData: FormData,@@ -84,7 +89,10 @@ export async function createProjectForOnboardingAction(const display_name = String(formData.get("display_name") ?? "").trim();if (!display_name) return { ok: false, error: "Please enter a project name." };- const result = createProject({ display_name });+ const website_url = String(formData.get("website_url") ?? "").trim() || null;+ const codebase_path = String(formData.get("codebase_path") ?? "").trim() || null;++ const result = createProject({ display_name, website_url, codebase_path });if (!result.ok) return { ok: false, error: result.reason };// Same async-provisioning policy as createProjectAction (D4 + D6).@@ -93,8 +101,12 @@ export async function createProjectForOnboardingAction("google_ads",]);startProvisioning(result.project.slug, provisionPromise);+ // After provisioning resolves, mint + start the CMO's project-onboarding+ // task. We chain off provisionPromise (not Promise.all) so a failed+ // provision doesn't try to assign a task to an agent that doesn't exist;+ // logAgentAction still fires regardless.provisionPromise- .then((prov) => {+ .then(async (prov) => {logAgentAction({project_slug: result.project.slug,agent_id: "system",@@ -102,6 +114,44 @@ export async function createProjectForOnboardingAction(summary: `Project '${result.project.display_name}' created. ${prov.created.length} agents provisioned${prov.failed.length > 0 ? `, ${prov.failed.length} failed` : ""}.`,payload: prov,});+ // Only kick off the onboarding task when the CMO agent actually exists.+ const { agentNameFor } = await import("@/server/agent-templates");+ const cmoAgentId = agentNameFor(result.project.slug, "cmo");+ const cmoOk =+ prov.created.includes(cmoAgentId) || prov.existed.includes(cmoAgentId);+ if (!cmoOk) {+ console.error(+ `[onboarding] CMO agent ${cmoAgentId} not provisioned; skipping onboarding task creation`,+ );+ return;+ }+ try {+ const { buildProjectOnboardingBrief } = await import(+ "@/server/onboarding/cmo-task-brief"+ );+ const { createTask } = await import("@/server/db/tasks");+ const { startTaskIfProposed } = await import(+ "@/server/orchestration/run-task"+ );+ const { title, brief, success_criteria } = buildProjectOnboardingBrief({+ project_slug: result.project.slug,+ project_display_name: result.project.display_name,+ website_url,+ codebase_path,+ });+ const task = createTask({+ project_slug: result.project.slug,+ agent_id: cmoAgentId,+ title,+ brief,+ success_criteria,+ assigner_agent_id: null,+ status: "proposed",+ });+ startTaskIfProposed(task);+ } catch (err) {+ console.error("[onboarding] failed to create CMO onboarding task:", err);+ }}).catch((err) => {console.error("Agent provisioning failed; project created but no agents:", err);diff --git a/src/server/actions/tasks.test.ts b/src/server/actions/tasks.test.tsindex 0d1cd381..220dc09a 100644--- a/src/server/actions/tasks.test.ts+++ b/src/server/actions/tasks.test.ts@@ -38,6 +38,8 @@ function makeProject(overrides: Partial<Project> = {}): Project {created_at: "2026-01-01T00:00:00.000Z",archived_at: null,google_ads_account_id: null,+ website_url: null,+ codebase_path: null,...overrides,};}@@ -57,6 +59,7 @@ function makeTask(overrides: Partial<Task> = {}): Task {error_message: null,thread_id: null,assigner_agent_id: "demo-cmo",+ blocked_by_task_id: null,created_at: "2026-05-19T00:00:00Z",updated_at: "2026-05-19T00:00:00Z",...overrides,diff --git a/src/server/active-project.test.ts b/src/server/active-project.test.tsindex 985a2e2e..c7662135 100644--- a/src/server/active-project.test.ts+++ b/src/server/active-project.test.ts@@ -39,6 +39,8 @@ function makeProject(overrides: Partial<Project> = {}): Project {created_at: "now",archived_at: null,google_ads_account_id: null,+ website_url: null,+ codebase_path: null,...overrides,};}diff --git a/src/server/agent-templates.ts b/src/server/agent-templates.tsindex a0d66efa..3fd5ab2b 100644--- a/src/server/agent-templates.ts+++ b/src/server/agent-templates.ts@@ -9,6 +9,7 @@ import {} from "@/server/mcp-server/registration";import { listProjects } from "@/server/db/projects";import { getOrchestrationSkill } from "@/server/skills/orchestration-skill";+import { readProjectBrief } from "@/server/onboarding/project-brief";/*** Role-specific behavior for the CMO. Concise — the procedural how-to@@ -344,13 +345,29 @@ async function writeIdentityFile(// in lockstep across all three agents.await writeFile(join(workspaceAbs, "SKILL.md"), skill, "utf8");+ // Project context: PROJECT.md is the single source of truth for "what+ // is this company / project". Written by the CMO during the first+ // onboarding task via `set_project_brief`. We inline it into IDENTITY.md+ // so every agent in the project (CMO + specialists) shares the same+ // context, and write a sidecar PROJECT.md copy so humans inspecting+ // the workspace see what the agent has. The canonical file lives at+ // ~/.notfair-cmo/projects/<slug>/PROJECT.md.+ let projectContextSection = "";+ if (project_slug) {+ const brief = await readProjectBrief(project_slug);+ if (brief !== null) {+ await writeFile(join(workspaceAbs, "PROJECT.md"), brief, "utf8");+ projectContextSection = `\n## Project context\n\nShared across every agent in this project — derived during onboarding\nand kept in sync via the \`set_project_brief\` MCP tool. Treat this as\nthe authoritative description of who the user is and what they sell.\n\n${brief.trim()}\n`;+ }+ }+// IDENTITY.md = role-specific bits on top, shared skill verbatim// below a separator. The separator makes it obvious which half is// per-agent and which is shared when a human reads the file.const body = `# ${template.display_name}${template.description}-${identityBlock}+${identityBlock}${projectContextSection}${template.system_prompt}---@@ -432,6 +449,71 @@ async function writeMinimalWorkspaceStubs(workspaceAbs: string): Promise<void> {]);}+/**+ * Re-write IDENTITY.md (and the PROJECT.md sidecar) for every agent in a+ * project, picking up the current canonical PROJECT.md. Called by the+ * `set_project_brief` MCP handler after writing the canonical file so+ * specialists get the updated project context without waiting for the+ * next ensureProjectAgents pass.+ *+ * Best-effort per agent: a write failure on one agent is logged but does+ * not abort the others — the new brief is at least canonical on disk, and+ * the next ensureProjectAgents will catch up.+ */+export async function syncProjectBriefToAgents(+ project_slug: string,+): Promise<{ synced: string[]; failed: Array<{ name: string; error: string }> }> {+ // Lazy import to avoid a static cycle: agent-meta -> agent-templates.+ const { listProjectAgents } = await import("./agent-meta");+ const synced: string[] = [];+ const failed: Array<{ name: string; error: string }> = [];++ const entries = await listProjectAgents(project_slug);+ for (const entry of entries) {+ if (!entry.template_key) {+ // Custom / cloned agent — we don't know its template, but it still+ // has an IDENTITY.md we shouldn't overwrite blindly. Just refresh+ // the sidecar PROJECT.md so a human inspecting sees the new brief.+ try {+ const workspaceAbs = workspaceDirFor(entry.agent_id);+ const { readProjectBrief } = await import("./onboarding/project-brief");+ const brief = await readProjectBrief(project_slug);+ if (brief !== null) {+ await mkdir(workspaceAbs, { recursive: true });+ await writeFile(join(workspaceAbs, "PROJECT.md"), brief, "utf8");+ synced.push(entry.agent_id);+ }+ } catch (err) {+ failed.push({+ name: entry.agent_id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ continue;+ }+ const template = TEMPLATES.find((t) => t.key === entry.template_key);+ if (!template) {+ failed.push({+ name: entry.agent_id,+ error: `Unknown template '${entry.template_key}'`,+ });+ continue;+ }+ try {+ const workspaceAbs = workspaceDirFor(entry.agent_id);+ await writeIdentityFile(workspaceAbs, template, project_slug, entry.agent_id);+ synced.push(entry.agent_id);+ } catch (err) {+ failed.push({+ name: entry.agent_id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }++ return { synced, failed };+}+export async function agentExists(name: string): Promise<boolean> {try {// `agents list` doesn't currently take a name filter, so list-all and grep.diff --git a/src/server/db/migrations.ts b/src/server/db/migrations.tsindex 57123225..b0dab7fa 100644--- a/src/server/db/migrations.ts+++ b/src/server/db/migrations.ts@@ -323,6 +323,32 @@ ALTER TABLE tasks_new RENAME TO tasks;CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);+`,+ },+ {+ name: "008_project_brief_and_task_blocks.sql",+ sql: `+-- Migration 008: project context inputs + task-blocks-task dependencies.+--+-- Two unrelated-looking changes ship together because they're the schema+-- side of the same product change: the new CMO onboarding task that learns+-- about the project (writes PROJECT.md), and the audit task gated on it.+--+-- 1. projects gains two optional inputs collected at onboarding time:+-- \`website_url\` and \`codebase_path\`. The CMO uses whichever are present+-- to research the project during its first task and produce PROJECT.md.+--+-- 2. tasks gains \`blocked_by_task_id\` — a generic "this task can't start+-- until that one finishes" pointer. When the blocker transitions to+-- \`done\`, the orchestrator clears the pointer, flips the dependent+-- blocked→proposed, and kicks it off. Co-exists with approval-blocking+-- (approval-blocked tasks have a null blocked_by_task_id and resolve+-- via the existing wakeTaskOnApprovalResolution path).+ALTER TABLE projects ADD COLUMN website_url TEXT;+ALTER TABLE projects ADD COLUMN codebase_path TEXT;++ALTER TABLE tasks ADD COLUMN blocked_by_task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL;+CREATE INDEX IF NOT EXISTS idx_tasks_blocked_by ON tasks(blocked_by_task_id) WHERE blocked_by_task_id IS NOT NULL;`,},];diff --git a/src/server/db/migrations/008_project_brief_and_task_blocks.sql b/src/server/db/migrations/008_project_brief_and_task_blocks.sqlnew file mode 100644index 00000000..2830aef9--- /dev/null+++ b/src/server/db/migrations/008_project_brief_and_task_blocks.sql@@ -0,0 +1,21 @@+-- Migration 008: project context inputs + task-blocks-task dependencies.+--+-- Two unrelated-looking changes ship together because they're the schema+-- side of the same product change: the new CMO onboarding task that learns+-- about the project (writes PROJECT.md), and the audit task gated on it.+--+-- 1. projects gains two optional inputs collected at onboarding time:+-- `website_url` and `codebase_path`. The CMO uses whichever are present+-- to research the project during its first task and produce PROJECT.md.+--+-- 2. tasks gains `blocked_by_task_id` — a generic "this task can't start+-- until that one finishes" pointer. When the blocker transitions to+-- `done`, the orchestrator clears the pointer, flips the dependent+-- blocked→proposed, and kicks it off. Co-exists with approval-blocking+-- (approval-blocked tasks have a null blocked_by_task_id and resolve+-- via the existing wakeTaskOnApprovalResolution path).+ALTER TABLE projects ADD COLUMN website_url TEXT;+ALTER TABLE projects ADD COLUMN codebase_path TEXT;++ALTER TABLE tasks ADD COLUMN blocked_by_task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL;+CREATE INDEX IF NOT EXISTS idx_tasks_blocked_by ON tasks(blocked_by_task_id) WHERE blocked_by_task_id IS NOT NULL;diff --git a/src/server/db/projects.ts b/src/server/db/projects.tsindex 3e5731c2..2ba2ffaf 100644--- a/src/server/db/projects.ts+++ b/src/server/db/projects.ts@@ -6,6 +6,9 @@ import { slugify } from "@/lib/slug";export type CreateProjectInput = {display_name: string;slug?: string;+ /** Optional onboarding hints. Free-text — CMO decides how to use them. */+ website_url?: string | null;+ codebase_path?: string | null;};export type CreateProjectResult =@@ -35,6 +38,9 @@ export function createProject(input: CreateProjectInput): CreateProjectResult {const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug.slug);if (existing) return { ok: false, reason: `project slug '${slug.slug}' already exists` };+ const website_url = trimOrNull(input.website_url);+ const codebase_path = trimOrNull(input.codebase_path);+const project: Project = {id: randomUUID(),slug: slug.slug,@@ -42,15 +48,30 @@ export function createProject(input: CreateProjectInput): CreateProjectResult {created_at: new Date().toISOString(),archived_at: null,google_ads_account_id: null,+ website_url,+ codebase_path,};db.prepare(- "INSERT INTO projects (id, slug, display_name, created_at, archived_at, google_ads_account_id) VALUES (?, ?, ?, ?, NULL, NULL)",- ).run(project.id, project.slug, project.display_name, project.created_at);+ "INSERT INTO projects (id, slug, display_name, created_at, archived_at, google_ads_account_id, website_url, codebase_path) VALUES (?, ?, ?, ?, NULL, NULL, ?, ?)",+ ).run(+ project.id,+ project.slug,+ project.display_name,+ project.created_at,+ project.website_url,+ project.codebase_path,+ );return { ok: true, project };}+function trimOrNull(value: string | null | undefined): string | null {+ if (value == null) return null;+ const trimmed = value.trim();+ return trimmed.length === 0 ? null : trimmed;+}+/*** Persist the chosen Google Ads customer ID for a project. Returns null when* the project doesn't exist or is archived. Idempotent — re-setting to thediff --git a/src/server/db/tasks.test.ts b/src/server/db/tasks.test.tsindex a47f305f..00bb251d 100644--- a/src/server/db/tasks.test.ts+++ b/src/server/db/tasks.test.ts@@ -12,10 +12,12 @@ vi.mock("./db", () => ({import {claimProposedTask,+ clearBlockerAndPromote,createTask,getTask,inFlightCountsByAgent,listTasks,+ listTasksBlockedBy,listTasksByAgent,markTaskBlocked,setTaskThreadIfMissing,@@ -495,3 +497,98 @@ describe("markTaskBlocked + unblockTask", () => {expect(inFlightCountsByAgent("acme").get("agent-1")).toBe(1);});});++describe("blocked_by_task_id (task-blocks-task)", () => {+ it("createTask with blocked_by_task_id forces status to 'blocked'", () => {+ seedProject();+ const blocker = createTask({+ project_slug: "acme",+ agent_id: "acme-cmo",+ brief: "first",+ });+ const dependent = createTask({+ project_slug: "acme",+ agent_id: "acme-google-ads",+ brief: "second",+ status: "proposed", // caller asked for proposed+ blocked_by_task_id: blocker.id,+ });+ expect(dependent.status).toBe("blocked");+ expect(dependent.blocked_by_task_id).toBe(blocker.id);+ });++ it("createTask drops the blocker pointer when blocker is already terminal", () => {+ seedProject();+ const blocker = createTask({+ project_slug: "acme",+ agent_id: "acme-cmo",+ brief: "first",+ });+ updateTask(blocker.id, { status: "done" });+ const dependent = createTask({+ project_slug: "acme",+ agent_id: "acme-google-ads",+ brief: "second",+ blocked_by_task_id: blocker.id,+ });+ expect(dependent.status).toBe("proposed");+ expect(dependent.blocked_by_task_id).toBeNull();+ });++ it("listTasksBlockedBy returns only blocked dependents", () => {+ seedProject();+ const blocker = createTask({+ project_slug: "acme",+ agent_id: "acme-cmo",+ brief: "b",+ });+ const dep1 = createTask({+ project_slug: "acme",+ agent_id: "x",+ brief: "d1",+ blocked_by_task_id: blocker.id,+ });+ const dep2 = createTask({+ project_slug: "acme",+ agent_id: "x",+ brief: "d2",+ blocked_by_task_id: blocker.id,+ });+ // Cancel dep2 — it should no longer appear in the blocked-by list even+ // though its pointer is still set.+ updateTask(dep2.id, { status: "cancelled" });++ const found = listTasksBlockedBy(blocker.id);+ expect(found.map((t) => t.id)).toEqual([dep1.id]);+ });++ it("clearBlockerAndPromote flips blocked→proposed and clears the pointer atomically", () => {+ seedProject();+ const blocker = createTask({+ project_slug: "acme",+ agent_id: "acme-cmo",+ brief: "b",+ });+ const dep = createTask({+ project_slug: "acme",+ agent_id: "x",+ brief: "d",+ blocked_by_task_id: blocker.id,+ });+ expect(dep.status).toBe("blocked");++ const promoted = clearBlockerAndPromote(dep.id);+ expect(promoted).not.toBeNull();+ expect(promoted!.status).toBe("proposed");+ expect(promoted!.blocked_by_task_id).toBeNull();+ });++ it("clearBlockerAndPromote is a no-op when the task isn't blocked", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ // status = proposed+ const result = clearBlockerAndPromote(t.id);+ expect(result).toBeNull();+ expect(getTask(t.id)!.status).toBe("proposed");+ });+});diff --git a/src/server/db/tasks.ts b/src/server/db/tasks.tsindex a58947d2..5a07e109 100644--- a/src/server/db/tasks.ts+++ b/src/server/db/tasks.ts@@ -14,6 +14,13 @@ export type CreateTaskInput = {status?: TaskStatus;/** Agent that created this task. CMO is the typical originator. */assigner_agent_id?: string | null;+ /**+ * Upstream task that must finish before this one can start. When set,+ * the task is forced into `blocked` status regardless of the `status`+ * input — caller intent to gate cannot be circumvented by leaving the+ * default. Cleared automatically on blocker resolution.+ */+ blocked_by_task_id?: string | null;};/**@@ -41,6 +48,25 @@ function nextDisplayId(project_slug: string): string {export function createTask(input: CreateTaskInput): Task {const db = getDb();const now = new Date().toISOString();++ // If a blocker is named AND it isn't already terminal, force this task+ // into `blocked` so it won't be picked up before the blocker resolves.+ // Race-free because better-sqlite3 is synchronous in this process: by+ // the time the propagation hook fires on the blocker's `done`, this+ // row exists and is visible to the SELECT inside the hook.+ let initialStatus: TaskStatus = input.status ?? "proposed";+ let blocked_by_task_id: string | null = input.blocked_by_task_id ?? null;+ if (blocked_by_task_id) {+ const blocker = getTask(blocked_by_task_id);+ if (blocker && !isTerminal(blocker.status)) {+ initialStatus = "blocked";+ } else {+ // Blocker already done / failed / cancelled — no point gating.+ // Drop the pointer so the dependent isn't permanently stuck.+ blocked_by_task_id = null;+ }+ }+const task: Task = {id: randomUUID(),display_id: nextDisplayId(input.project_slug),@@ -50,19 +76,20 @@ export function createTask(input: CreateTaskInput): Task {brief: input.brief,success_criteria: input.success_criteria ?? null,deadline_iso: input.deadline_iso ?? null,- status: input.status ?? "proposed",+ status: initialStatus,result_json: null,error_message: null,thread_id: null,assigner_agent_id: input.assigner_agent_id ?? null,+ blocked_by_task_id,created_at: now,updated_at: now,};db.prepare(`INSERT INTO tasks(id, display_id, project_slug, agent_id, title, brief, success_criteria, deadline_iso,- status, result_json, error_message, thread_id, assigner_agent_id, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?, ?)`,+ status, result_json, error_message, thread_id, assigner_agent_id, blocked_by_task_id, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?, ?, ?)`,).run(task.id,task.display_id,@@ -74,12 +101,17 @@ export function createTask(input: CreateTaskInput): Task {task.deadline_iso,task.status,task.assigner_agent_id,+ task.blocked_by_task_id,task.created_at,task.updated_at,);return task;}+function isTerminal(status: TaskStatus): boolean {+ return status === "done" || status === "failed" || status === "cancelled";+}+/*** Lazily set the OpenClaw chat session id for this task. Called the first* time someone opens /tasks/[id] — the thread_id is generated then and@@ -235,3 +267,38 @@ export function unblockTask(id: string): Task | null {).run(now, id);return getTask(id);}++/**+ * Tasks gated on the given blocker (i.e. blocked_by_task_id = id) that are+ * still in the `blocked` state. Used by the propagation hook in+ * handleTaskStatus to find dependents to wake when the blocker resolves.+ */+export function listTasksBlockedBy(blocker_task_id: string): Task[] {+ const db = getDb();+ return db+ .prepare(+ "SELECT * FROM tasks WHERE blocked_by_task_id = ? AND status = 'blocked' ORDER BY created_at ASC",+ )+ .all(blocker_task_id) as Task[];+}++/**+ * Atomically clear the blocked_by pointer and flip blocked→proposed so the+ * task becomes eligible for the standard `startTaskIfProposed` claim. Done+ * in one UPDATE so a concurrent kickoff can't observe an intermediate state+ * where the task is proposed-but-still-pointed-at-a-resolved-blocker.+ *+ * Returns the post-flip task on success, null when the row wasn't blocked+ * (e.g. someone cancelled it before the blocker finished).+ */+export function clearBlockerAndPromote(id: string): Task | null {+ const db = getDb();+ const now = new Date().toISOString();+ const info = db+ .prepare(+ "UPDATE tasks SET status = 'proposed', blocked_by_task_id = NULL, updated_at = ? WHERE id = ? AND status = 'blocked'",+ )+ .run(now, id);+ if (info.changes === 0) return null;+ return getTask(id);+}diff --git a/src/server/fs/pick-folder.test.ts b/src/server/fs/pick-folder.test.tsnew file mode 100644index 00000000..4e1cf516--- /dev/null+++ b/src/server/fs/pick-folder.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it, vi, beforeEach } from "vitest";++// child_process.execFile lives behind a barrier — mock it before importing+// the module under test so we exercise the parsing branches without+// actually opening a real Finder dialog during CI.+const execFileMock = vi.fn();+vi.mock("node:child_process", () => ({+ execFile: (...args: unknown[]) => execFileMock(...args),+}));++// Force platform=darwin for the macOS branch test. The unsupported-platform+// branch is exercised by overriding the mock in-test.+vi.mock("node:os", async () => {+ const actual = await vi.importActual<typeof import("node:os")>("node:os");+ return {+ ...actual,+ platform: vi.fn(() => "darwin"),+ };+});++import { pickFolder } from "./pick-folder";+import * as os from "node:os";++beforeEach(() => {+ execFileMock.mockReset();+ (os.platform as unknown as ReturnType<typeof vi.fn>).mockReturnValue("darwin");+});++describe("pickFolder (darwin)", () => {+ it("returns the chosen path with the trailing slash stripped", async () => {+ execFileMock.mockImplementation((_bin, _args, _opts, cb) => {+ cb(null, "/Users/yuting/Workspace/acme/\n", "");+ return { } as unknown;+ });+ const r = await pickFolder({ prompt: "Pick a folder" });+ expect(r).toEqual({ ok: true, path: "/Users/yuting/Workspace/acme" });+ });++ it("reports cancelled when the AppleScript returns the cancel sentinel", async () => {+ execFileMock.mockImplementation((_bin, _args, _opts, cb) => {+ cb(null, "__USER_CANCELLED__\n", "");+ return { } as unknown;+ });+ const r = await pickFolder({});+ expect(r).toEqual({ ok: false, kind: "cancelled" });+ });++ it("reports cancelled on empty stdout", async () => {+ execFileMock.mockImplementation((_bin, _args, _opts, cb) => {+ cb(null, "", "");+ return { } as unknown;+ });+ const r = await pickFolder({});+ expect(r).toEqual({ ok: false, kind: "cancelled" });+ });++ it("surfaces stderr when osascript exits non-zero", async () => {+ execFileMock.mockImplementation((_bin, _args, _opts, cb) => {+ const err: NodeJS.ErrnoException = new Error("boom");+ err.code = 1 as unknown as string;+ cb(err, "", "some applescript error\n");+ return { } as unknown;+ });+ const r = await pickFolder({});+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.kind).toBe("error");+ if (r.kind === "error") {+ expect(r.message).toContain("some applescript error");+ }+ });++ it("escapes prompt double-quotes so they can't break the AppleScript string", async () => {+ let captured: string | undefined;+ execFileMock.mockImplementation((_bin, args: string[], _opts, cb) => {+ captured = args[1]; // ["-e", "<script>"]+ cb(null, "/tmp/\n", "");+ return { } as unknown;+ });+ await pickFolder({ prompt: 'Quote " inside' });+ expect(captured).toContain('Quote \\" inside');+ });+});++describe("pickFolder (other platforms)", () => {+ it("returns unsupported on linux", async () => {+ (os.platform as unknown as ReturnType<typeof vi.fn>).mockReturnValue("linux");+ const r = await pickFolder({});+ expect(r).toEqual({ ok: false, kind: "unsupported", platform: "linux" });+ expect(execFileMock).not.toHaveBeenCalled();+ });++ it("returns unsupported on win32", async () => {+ (os.platform as unknown as ReturnType<typeof vi.fn>).mockReturnValue(+ "win32",+ );+ const r = await pickFolder({});+ expect(r).toEqual({ ok: false, kind: "unsupported", platform: "win32" });+ });+});diff --git a/src/server/fs/pick-folder.ts b/src/server/fs/pick-folder.tsnew file mode 100644index 00000000..1fe7bdbc--- /dev/null+++ b/src/server/fs/pick-folder.ts@@ -0,0 +1,110 @@+import { execFile } from "node:child_process";+import { platform } from "node:os";++/**+ * Open the OS-native folder-picker dialog on the user's local machine and+ * return the chosen absolute path. We rely on the fact that this server+ * runs in the same single-user session as the browser (loopback-only,+ * `npx notfair-cmo` model) — the dialog appears on the user's screen, in+ * front of the same person clicking the Browse button.+ *+ * Implementations are platform-specific because there is no cross-platform+ * native picker primitive in Node. macOS uses AppleScript's `choose folder`,+ * which returns a POSIX path. Linux + Windows fallbacks are TODO; callers+ * receive a clear `kind: "unsupported"` they can branch on (UI falls back+ * to a text input).+ *+ * The dialog is modal in the OS sense (blocks until the user picks or+ * cancels), so we set a generous timeout to avoid wedging the route if+ * something has gone wrong on the OS side.+ */++const DIALOG_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes — the user might think++export type PickFolderResult =+ | { ok: true; path: string }+ | { ok: false; kind: "cancelled" }+ | { ok: false; kind: "unsupported"; platform: string }+ | { ok: false; kind: "error"; message: string };++export async function pickFolder(opts: {+ prompt?: string;+ defaultLocation?: string;+}): Promise<PickFolderResult> {+ const p = platform();+ if (p === "darwin") {+ return pickFolderMac(opts);+ }+ // TODO: linux (zenity / kdialog), win32 (PowerShell FolderBrowserDialog).+ return { ok: false, kind: "unsupported", platform: p };+}++async function pickFolderMac(opts: {+ prompt?: string;+ defaultLocation?: string;+}): Promise<PickFolderResult> {+ // Build the AppleScript expression carefully: we control both args, so+ // there's no untrusted shell-injection vector, but we still escape any+ // embedded double quotes / backslashes so a path with quotes can't break+ // the script. Args reach osascript via execFile (not a shell) so no+ // additional shell-quoting is needed for the surrounding command line.+ const prompt = (opts.prompt ?? "Select a folder").replace(/["\\]/g, "\\$&");+ const defaultClause = opts.defaultLocation+ ? ` default location POSIX file "${opts.defaultLocation.replace(/["\\]/g, "\\$&")}"`+ : "";+ const script = `+ try+ set f to choose folder with prompt "${prompt}"${defaultClause}+ return POSIX path of f+ on error errMsg number errNum+ if errNum is -128 then+ return "__USER_CANCELLED__"+ else+ error errMsg number errNum+ end if+ end try+ `;++ const result = await new Promise<{+ stdout: string;+ stderr: string;+ code: number | null;+ }>((resolve) => {+ execFile(+ "/usr/bin/osascript",+ ["-e", script],+ { timeout: DIALOG_TIMEOUT_MS },+ (err, stdout, stderr) => {+ // With default options (no encoding override), Node returns+ // stdout/stderr as strings. err carries .code on timeout /+ // non-zero exit; we collapse it to a numeric code or 1 fallback.+ const errCode = err+ ? typeof (err as NodeJS.ErrnoException).code === "number"+ ? ((err as unknown as { code: number }).code as number)+ : 1+ : 0;+ resolve({ stdout, stderr, code: errCode });+ },+ );+ // We don't wire up an AbortSignal here; the DIALOG_TIMEOUT_MS ceiling+ // protects against a wedged osascript subprocess.+ });++ if (result.code !== 0) {+ return {+ ok: false,+ kind: "error",+ message:+ result.stderr.trim() ||+ `osascript exited with code ${result.code ?? "unknown"}`,+ };+ }+ const out = result.stdout.trim();+ if (out === "__USER_CANCELLED__" || out === "") {+ return { ok: false, kind: "cancelled" };+ }+ // AppleScript's `POSIX path of` returns a trailing slash for folders;+ // strip it for consistency with how users typically write paths.+ const normalized = out.replace(/\/+$/, "");+ return { ok: true, path: normalized };+}diff --git a/src/server/mcp-server/jsonrpc.test.ts b/src/server/mcp-server/jsonrpc.test.tsindex e1dc5263..bf81c01b 100644--- a/src/server/mcp-server/jsonrpc.test.ts+++ b/src/server/mcp-server/jsonrpc.test.ts@@ -2,9 +2,28 @@ import { describe, expect, it, vi, beforeEach } from "vitest";const getTaskMock = vi.fn();const updateTaskMock = vi.fn();+// Dependent-propagation helpers (handlers.ts calls these on every `done`+// transition). Default: no dependents — empty list keeps the propagation+// branch a no-op for the bulk of submit_task_status tests.+const listTasksBlockedByMock = vi.fn((..._a: unknown[]): unknown[] => []);+const clearBlockerAndPromoteMock = vi.fn(+ (..._a: unknown[]): unknown => null,+);vi.mock("@/server/db/tasks", () => ({getTask: (...a: unknown[]) => getTaskMock(...a),updateTask: (...a: unknown[]) => updateTaskMock(...a),+ listTasksBlockedBy: (...a: unknown[]) => listTasksBlockedByMock(...a),+ clearBlockerAndPromote: (...a: unknown[]) => clearBlockerAndPromoteMock(...a),+ // The rest of tasks.ts isn't called from handlers under test here, but+ // ESM requires the module to expose any named import handlers.ts uses.+ // Safe stubs — they'd throw if accidentally invoked, surfacing the gap.+ createTask: () => {+ throw new Error("createTask not mocked");+ },+ listTasks: () => [],+ listTasksByAgent: () => [],+ markTaskBlocked: () => null,+ unblockTask: () => null,}));const logAgentActionMock = vi.fn();diff --git a/src/server/mcp-server/tools.ts b/src/server/mcp-server/tools.tsindex e502aac7..972da0db 100644--- a/src/server/mcp-server/tools.ts+++ b/src/server/mcp-server/tools.ts@@ -19,6 +19,7 @@ import {handleListTaskStatuses,handleListTasks,handleRequestApproval,+ handleSetProjectBrief,handleTaskStatus,handleUpdateTask,TASK_STATUS_VALUES,@@ -556,6 +557,41 @@ async function handleListApprovalActionTypesTool(return txt(JSON.stringify({ action_types: r.data }));}+// ── Tool: set_project_brief ────────────────────────────────────────────++const setProjectBriefInput = z.object({+ project_slug: z+ .string()+ .min(1)+ .describe(+ "The project this brief belongs to. From your IDENTITY.md prompt header.",+ ),+ agent_id: z+ .string()+ .min(1)+ .describe(+ "Your agent_id (e.g. `acme-cmo`). From IDENTITY.md. The CMO is the expected caller — specialists should not write to PROJECT.md.",+ ),+ body: z+ .string()+ .min(1)+ .describe(+ "Full PROJECT.md content as markdown. Replaces any prior body. Capped at 64 KB. Aim for a 90-second read: what we sell, who we sell to, positioning, voice, key constraints.",+ ),+});++async function handleSetProjectBriefTool(input: unknown): Promise<ToolResult> {+ const parsed = setProjectBriefInput.safeParse(input);+ if (!parsed.success) return invalid(parsed.error);+ const { project_slug, agent_id, body } = parsed.data;+ const r = await handleSetProjectBrief(+ { body },+ { project_slug, agent_id },+ );+ if (!r.ok) return { ok: false, error: r.error };+ return txt(`PROJECT.md written; synced to project agents.`);+}+// ── Registry ───────────────────────────────────────────────────────────export const TOOLS: ToolDefinition[] = [@@ -692,6 +728,13 @@ export const TOOLS: ToolDefinition[] = [inputSchema: listApprovalActionTypesInput,handler: handleListApprovalActionTypesTool,},+ {+ name: "set_project_brief",+ description:+ "Write (or rewrite) PROJECT.md — the single source of truth for what this project sells, who it sells to, positioning, voice, and constraints. Synced into every agent's IDENTITY.md so the CMO + specialists share the same context. The CMO calls this once during its first onboarding task and again whenever the user surfaces a material change.",+ inputSchema: setProjectBriefInput,+ handler: handleSetProjectBriefTool,+ },];export function describeTool(tool: ToolDefinition): {diff --git a/src/server/onboarding/accounts.ts b/src/server/onboarding/accounts.tsindex f0c3f9ab..6eb316bc 100644--- a/src/server/onboarding/accounts.ts+++ b/src/server/onboarding/accounts.ts@@ -169,18 +169,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.+ // Mint the audit task — gated on the project-onboarding task that+ // createProjectForOnboardingAction kicked off in the background. The+ // audit can't run until PROJECT.md exists; the propagation hook in+ // handleTaskStatus auto-starts the audit the moment onboarding flips+ // to `done`.+ //+ // Avoid duplicates if the user navigates back and resubmits — reuse+ // the existing one when a CMO audit task is already present.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(+ const allTasks = listTasks(project_slug);+ const existingAudit = allTasks.find((t) => t.agent_id === cmoAgentId && t.title?.startsWith("Audit the account"),);- let task = existing;+ let task = existingAudit;if (!task) {+ // Find the project-onboarding task to gate on. Match by exact title+ // (createProjectForOnboardingAction uses a fixed string from+ // buildProjectOnboardingBrief). When it's missing or already terminal,+ // createTask drops the blocker automatically — the audit runs+ // immediately in that case.+ const onboardingTask = allTasks.find(+ (t) =>+ t.agent_id === cmoAgentId &&+ t.title === "Learn the project and write PROJECT.md",+ );+const { title, brief, success_criteria } = buildOnboardingBrief({project_slug,project_display_name: updated.display_name,@@ -194,14 +211,18 @@ export async function setOnboardingAccountAction(success_criteria,assigner_agent_id: null,status: "proposed",+ blocked_by_task_id: onboardingTask?.id ?? null,});}- // Leave the task in `proposed`. The task workspace the caller redirects- // the user to will auto-fire the kickoff client-side via /api/chat so- // the user sees live gateway events stream in. /api/chat atomically- // claims the task before sending, so the resubmit branch (existing task- // already running/done) is a safe no-op there.+ // Status now:+ // - If onboarding task was non-terminal at createTask time → audit is+ // `blocked`. The propagation hook in handleTaskStatus picks it up+ // when onboarding flips to `done`.+ // - Otherwise → audit is `proposed`. The task workspace the caller+ // redirects the user to auto-fires the kickoff client-side via+ // /api/chat (which atomically claims). For the resubmit branch+ // (audit already running/done) /api/chat is a safe no-op.revalidatePath("/", "layout");return { ok: true, project: updated, task_display_id: task.display_id };diff --git a/src/server/onboarding/cmo-task-brief.ts b/src/server/onboarding/cmo-task-brief.tsindex ce6db206..6a98558c 100644--- a/src/server/onboarding/cmo-task-brief.ts+++ b/src/server/onboarding/cmo-task-brief.ts@@ -1,3 +1,77 @@+/**+ * Build the brief for the CMO's project-onboarding task — the very first+ * turn for a new project. The CMO uses the optional website + codebase+ * hints to research what the company does, then writes PROJECT.md via the+ * `set_project_brief` MCP tool so every agent (CMO + specialists) shares+ * the same canonical context going forward. Audit tasks gate on this one+ * via `blocked_by_task_id`.+ */+export function buildProjectOnboardingBrief(args: {+ project_slug: string;+ project_display_name: string;+ website_url: string | null;+ codebase_path: string | null;+}): { title: string; brief: string; success_criteria: string } {+ const title = "Learn the project and write PROJECT.md";++ const hints: string[] = [];+ if (args.website_url) {+ hints.push(`- Website: ${args.website_url} — fetch + skim a few key pages (home, about, pricing if any) to understand positioning and offer.`);+ }+ if (args.codebase_path) {+ hints.push(`- Local codebase: ${args.codebase_path} — read README, package.json (or equivalent), top-level entry points. Skim only — you're looking for product shape, not a code review.`);+ }+ if (hints.length === 0) {+ hints.push("- No hints provided. Ask the user a focused question via `ask_user_question` or `add_task_comment` if you need one missing fact (target audience, what they sell). Otherwise make conservative assumptions and note them in PROJECT.md so the user can correct.");+ }++ const brief = [+ `Project: ${args.project_display_name} (${args.project_slug})`,+ "",+ "This is your very first turn for this project. Your job is to learn",+ "the company well enough that you (and every specialist you delegate",+ "to later) operates from a shared, accurate picture. Output: write",+ "PROJECT.md via the `set_project_brief` MCP tool.",+ "",+ "## 1. Gather context",+ "",+ ...hints,+ "",+ "Use the tools you have (web fetch, file read, shell exec) — there's",+ "no scraper or special infrastructure here, just you and your tools.",+ "",+ "## 2. Write PROJECT.md",+ "",+ "Call `set_project_brief` with a markdown body. Suggested sections —",+ "skip any you genuinely can't infer rather than padding:",+ "",+ "- **What we sell** — product or service in 1-2 sentences",+ "- **Who we sell to** — ICP, role, company size, geography if relevant",+ "- **Positioning / pitch** — the one-liner the homepage leads with",+ "- **Competitors / alternatives** — if visible",+ "- **Tone / voice** — quick read on how the brand writes",+ "- **Key constraints** — anything spend, compliance, or scope-related",+ " the user mentioned",+ "",+ "Keep it tight: a CMO who knew nothing about this company should",+ "understand it in 90 seconds of reading. Quote specifics from the",+ "site/codebase rather than handwaving.",+ "",+ "## 3. Close the task",+ "",+ "After `set_project_brief` returns ok, call `submit_task_status` with",+ "status=done and a one-line summary. Subsequent tasks (like the Google",+ "Ads audit) are gated on this one and auto-start the moment you close it.",+ ].join("\n");++ const success_criteria = [+ "PROJECT.md written via set_project_brief; task closed with",+ "submit_task_status status=done.",+ ].join(" ");++ return { title, brief, success_criteria };+}+/*** 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 thediff --git a/src/server/onboarding/project-brief.ts b/src/server/onboarding/project-brief.tsnew file mode 100644index 00000000..f5930f9c--- /dev/null+++ b/src/server/onboarding/project-brief.ts@@ -0,0 +1,61 @@+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { dirname, join } from "node:path";++/**+ * PROJECT.md — the single source of truth for "what is this project / who+ * is the company / what does the CMO know about it". Written once by the+ * CMO during the first onboarding task, then propagated into every agent's+ * IDENTITY.md so all specialists share the same context.+ *+ * Path layout (relative to the data dir, default ~/.notfair-cmo):+ *+ * projects/<slug>/PROJECT.md — canonical, edited by the CMO+ *+ * Per-agent copies live in each agent's workspace and are written by+ * `writeIdentityFile` so a human inspecting the workspace can see what the+ * agent actually has. The IDENTITY.md prompt inlines the same content+ * under a `## Project context` heading so it lands in the system prompt+ * regardless of which files OpenClaw chooses to load.+ */++/** Hard cap on PROJECT.md body size — keeps system prompts bounded. */+export const PROJECT_BRIEF_MAX_BYTES = 64 * 1024;++function dataDir(): string {+ return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");+}++export function projectBriefPath(project_slug: string): string {+ return join(dataDir(), "projects", project_slug, "PROJECT.md");+}++/**+ * Return the current PROJECT.md body for a project, or null when none has+ * been written yet. Errors (other than ENOENT) bubble up so callers can+ * surface fs problems instead of silently treating them as "no brief".+ */+export async function readProjectBrief(+ project_slug: string,+): Promise<string | null> {+ try {+ return await readFile(projectBriefPath(project_slug), "utf8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw err;+ }+}++/**+ * Persist a new PROJECT.md body to the canonical path. Idempotent — calling+ * with the same body is a no-op rewrite. Does NOT propagate to agent+ * workspaces; that's the caller's job (see set_project_brief handler).+ */+export async function writeProjectBrief(+ project_slug: string,+ body: string,+): Promise<void> {+ const path = projectBriefPath(project_slug);+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, body, "utf8");+}diff --git a/src/server/orchestration/handlers.test.ts b/src/server/orchestration/handlers.test.tsindex 07bafe46..bca09082 100644--- a/src/server/orchestration/handlers.test.ts+++ b/src/server/orchestration/handlers.test.ts@@ -40,6 +40,12 @@ vi.mock("./run-task", () => ({}),}));+const syncProjectBriefToAgentsMock = vi.fn(+ async (..._a: unknown[]) => ({+ synced: ["demo-cmo", "demo-google-ads"] as string[],+ failed: [] as Array<{ name: string; error: string }>,+ }),+);vi.mock("@/server/agent-templates", () => ({agentExists: async () => true,agentNameFor: (slug: string, key: string) =>@@ -50,8 +56,19 @@ vi.mock("@/server/agent-templates", () => ({: k === "cmo"? { key: "cmo", display_name: "CMO" }: undefined,+ syncProjectBriefToAgents: (...a: unknown[]) =>+ syncProjectBriefToAgentsMock(...a),}));+// Use a tmpdir for the PROJECT.md canonical path so set_project_brief+// tests don't litter the developer's real ~/.notfair-cmo.+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+process.env.NOTFAIR_CMO_DATA_DIR = mkdtempSync(+ join(tmpdir(), "notfair-cmo-handlers-test-"),+);+import {handleCancelTask,handleGetApproval,@@ -451,3 +468,159 @@ describe("enum discovery handlers", () => {expect(content.cost_estimate_required).toBe(false);});});++describe("handleSetProjectBrief", () => {+ it("persists PROJECT.md and fans out to agents", async () => {+ syncProjectBriefToAgentsMock.mockClear();+ const { handleSetProjectBrief } = await import("./handlers");+ const r = await handleSetProjectBrief(+ { body: "# Demo\n\nWe sell paperclips to office managers." },+ { project_slug: "demo", agent_id: "demo-cmo" },+ );+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.path).toMatch(/PROJECT\.md$/);+ expect(syncProjectBriefToAgentsMock).toHaveBeenCalledWith("demo");++ const { readProjectBrief } = await import(+ "@/server/onboarding/project-brief"+ );+ const persisted = await readProjectBrief("demo");+ expect(persisted).toContain("paperclips");+ });++ it("rejects empty body", async () => {+ const { handleSetProjectBrief } = await import("./handlers");+ const r = await handleSetProjectBrief(+ { body: " " },+ { project_slug: "demo", agent_id: "demo-cmo" },+ );+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.error).toMatch(/empty/i);+ });++ it("rejects unknown project", async () => {+ const { handleSetProjectBrief } = await import("./handlers");+ const r = await handleSetProjectBrief(+ { body: "valid body" },+ { project_slug: "no-such-project", agent_id: "x" },+ );+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.error).toMatch(/unknown project/i);+ });++ it("rejects oversized body", async () => {+ const { handleSetProjectBrief } = await import("./handlers");+ const huge = "x".repeat(70 * 1024); // 70 KB > 64 KB cap+ const r = await handleSetProjectBrief(+ { body: huge },+ { project_slug: "demo", agent_id: "demo-cmo" },+ );+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.error).toMatch(/exceeds/i);+ });+});++describe("handleTaskStatus — blocked_by_task_id propagation", () => {+ it("flipping a blocker to 'done' promotes its blocked dependents to 'proposed'", async () => {+ const { handleTaskStatus } = await import("./handlers");++ const blocker = createTask({+ project_slug: "demo",+ agent_id: "demo-cmo",+ brief: "first",+ title: "Learn the project",+ });+ const dependent = createTask({+ project_slug: "demo",+ agent_id: "demo-cmo",+ brief: "audit",+ title: "Audit the account",+ blocked_by_task_id: blocker.id,+ });+ expect(dependent.status).toBe("blocked");++ const r = handleTaskStatus(+ { task_id: blocker.id, status: "done", summary: "wrote PROJECT.md" },+ { project_slug: "demo", agent_id: "demo-cmo" },+ );+ expect(r.ok).toBe(true);++ // Synchronous DB flip: dependent is proposed with cleared pointer+ // before the (async) kickoff microtask runs.+ const after = testDb+ .prepare(+ "SELECT status, blocked_by_task_id FROM tasks WHERE id = ?",+ )+ .get(dependent.id) as { status: string; blocked_by_task_id: string | null };+ expect(after.status).toBe("proposed");+ expect(after.blocked_by_task_id).toBeNull();+ });++ it("does NOT propagate on 'failed' — dependents remain blocked", async () => {+ const { handleTaskStatus } = await import("./handlers");++ const blocker = createTask({+ project_slug: "demo",+ agent_id: "demo-cmo",+ brief: "first",+ });+ const dependent = createTask({+ project_slug: "demo",+ agent_id: "demo-cmo",+ brief: "second",+ blocked_by_task_id: blocker.id,+ });++ const r = handleTaskStatus(+ { task_id: blocker.id, status: "failed", summary: "couldn't fetch site" },+ { project_slug: "demo", agent_id: "demo-cmo" },+ );+ expect(r.ok).toBe(true);++ const after = testDb+ .prepare("SELECT status FROM tasks WHERE id = ?")+ .get(dependent.id) as { status: string };+ expect(after.status).toBe("blocked");+ });++ it("only promotes dependents that are still 'blocked' (skips cancelled ones)", async () => {+ const { handleTaskStatus } = await import("./handlers");++ const blocker = createTask({+ project_slug: "demo",+ agent_id: "demo-cmo",+ brief: "first",+ });+ const dep1 = createTask({+ project_slug: "demo",+ agent_id: "demo-cmo",+ brief: "d1",+ blocked_by_task_id: blocker.id,+ });+ const dep2 = createTask({+ project_slug: "demo",+ agent_id: "demo-cmo",+ brief: "d2",+ blocked_by_task_id: blocker.id,+ });+ // User cancels dep2 before the blocker resolves.+ testDb+ .prepare("UPDATE tasks SET status='cancelled' WHERE id = ?")+ .run(dep2.id);++ handleTaskStatus(+ { task_id: blocker.id, status: "done", summary: "ok" },+ { project_slug: "demo", agent_id: "demo-cmo" },+ );++ const a1 = testDb+ .prepare("SELECT status FROM tasks WHERE id = ?")+ .get(dep1.id) as { status: string };+ const a2 = testDb+ .prepare("SELECT status FROM tasks WHERE id = ?")+ .get(dep2.id) as { status: string };+ expect(a1.status).toBe("proposed");+ expect(a2.status).toBe("cancelled"); // untouched+ });+});diff --git a/src/server/orchestration/handlers.ts b/src/server/orchestration/handlers.tsindex 70f82f4b..f53bdcea 100644--- a/src/server/orchestration/handlers.ts+++ b/src/server/orchestration/handlers.ts@@ -15,9 +15,11 @@ import {import { getDb } from "@/server/db/db";import { getProject } from "@/server/db/projects";import {+ clearBlockerAndPromote,createTask,getTask,listTasks,+ listTasksBlockedBy,listTasksByAgent,markTaskBlocked,unblockTask,@@ -221,9 +223,103 @@ export function handleTaskStatus(payload: { task_id: task.id, status: newStatus, via: ctx ? "block" : "mcp" },});+ // Propagation: when a task resolves to `done`, wake any tasks that were+ // gated on it via blocked_by_task_id. The DB flip (blocked→proposed ++ // clear pointer) happens synchronously here so subsequent SELECTs in+ // the same process see the new state immediately; the kickoff itself+ // is fire-and-forget (it already runs the gateway stream async).+ //+ // We don't propagate on `failed`/`cancelled` — those leave dependents+ // stranded in `blocked`. That's deliberate: a failed prerequisite is a+ // signal to the user, not something to silently route around. They can+ // cancel the dependent or rerun the blocker.+ if (newStatus === "done") {+ const dependents = listTasksBlockedBy(task.id);+ const promoted: Task[] = [];+ for (const dep of dependents) {+ const p = clearBlockerAndPromote(dep.id);+ if (p) promoted.push(p);+ }+ if (promoted.length > 0) {+ void (async () => {+ const { startTaskIfProposed } = await import("./run-task");+ for (const p of promoted) {+ try {+ startTaskIfProposed(p);+ } catch (err) {+ console.error(+ `[block-prop] kickoff failed for ${p.display_id}:`,+ err,+ );+ }+ }+ })().catch((err) => {+ console.error("[block-prop] propagation IIFE failed:", err);+ });+ }+ }+return { ok: true, data: { task_id: task.id, status: newStatus } };}+// ── set_project_brief ──────────────────────────────────────────────────++export type SetProjectBriefInput = {+ body: string;+};++/**+ * Persist a new PROJECT.md body for this project, then propagate it into+ * every agent's IDENTITY.md so specialists pick up the updated context on+ * their next turn.+ *+ * The CMO calls this once during its project-onboarding task. It's+ * idempotent — calling again with a revised body replaces the prior one,+ * which is how PROJECT.md gets updated over the project's life (e.g. user+ * asks the CMO to "remember we're targeting EU now").+ */+export async function handleSetProjectBrief(+ input: SetProjectBriefInput,+ ctx: HandlerContext,+): Promise<HandlerResult<{ path: string }>> {+ const project = getProject(ctx.project_slug);+ if (!project) {+ return { ok: false, error: `Unknown project '${ctx.project_slug}'` };+ }++ const body = input.body;+ if (typeof body !== "string" || body.trim().length === 0) {+ return { ok: false, error: "PROJECT.md body cannot be empty." };+ }+ const { PROJECT_BRIEF_MAX_BYTES, writeProjectBrief, projectBriefPath } =+ await import("@/server/onboarding/project-brief");+ if (Buffer.byteLength(body, "utf8") > PROJECT_BRIEF_MAX_BYTES) {+ return {+ ok: false,+ error: `PROJECT.md exceeds ${PROJECT_BRIEF_MAX_BYTES} bytes — tighten it before resubmitting.`,+ };+ }++ await writeProjectBrief(ctx.project_slug, body);++ // Fan out into every agent workspace so the IDENTITY.md prompts pick+ // up the new context immediately. Best-effort per agent.+ const { syncProjectBriefToAgents } = await import(+ "@/server/agent-templates"+ );+ const sync = await syncProjectBriefToAgents(ctx.project_slug);++ logAgentAction({+ project_slug: ctx.project_slug,+ agent_id: ctx.agent_id,+ action_type: "project_brief_updated",+ summary: `Wrote PROJECT.md (${Buffer.byteLength(body, "utf8")} bytes); synced ${sync.synced.length} agents${sync.failed.length > 0 ? `, ${sync.failed.length} failed` : ""}.`,+ payload: { synced: sync.synced, failed: sync.failed },+ });++ return { ok: true, data: { path: projectBriefPath(ctx.project_slug) } };+}+// ── add_task_comment ───────────────────────────────────────────────────export type AddCommentInput = {diff --git a/src/server/orchestration/run-task.test.ts b/src/server/orchestration/run-task.test.tsindex 42a01815..7d3e5330 100644--- a/src/server/orchestration/run-task.test.ts+++ b/src/server/orchestration/run-task.test.ts@@ -53,6 +53,7 @@ function makeTask(overrides: Partial<Task> = {}): Task {error_message: null,thread_id: "thread-existing",assigner_agent_id: "demo-cmo",+ blocked_by_task_id: null,created_at: "2026-05-19T00:00:00Z",updated_at: "2026-05-19T00:00:00Z",...overrides,diff --git a/src/server/orchestration/task-kickoff.test.ts b/src/server/orchestration/task-kickoff.test.tsindex 189236d6..a7ac900b 100644--- a/src/server/orchestration/task-kickoff.test.ts+++ b/src/server/orchestration/task-kickoff.test.ts@@ -19,6 +19,7 @@ function makeTask(overrides: Partial<Task> = {}): Task {error_message: null,thread_id: "thread-1",assigner_agent_id: "demo-cmo",+ blocked_by_task_id: null,created_at: "2026-05-19T00:00:00Z",updated_at: "2026-05-19T00:00:00Z",...overrides,diff --git a/src/server/skills/orchestration-skill.ts b/src/server/skills/orchestration-skill.tsindex 7d1f1c1c..baa9c60c 100644--- a/src/server/skills/orchestration-skill.ts+++ b/src/server/skills/orchestration-skill.ts@@ -58,6 +58,11 @@ call the discovery tool first instead of guessing:- \`update_task\` — edit title / brief / success criteria on a task youcreated. Doesn't change status.- \`cancel_task\` — mark a task cancelled. Use when work is obsolete.+- \`set_project_brief\` — write (or rewrite) PROJECT.md, the single source+ of truth for what this project sells / who buys / positioning / voice.+ Synced into every agent's IDENTITY.md. The CMO calls this once during+ its first onboarding task and again whenever the user surfaces a+ material change to who/what the project is.### Reading tools (re-anchor context, check progress)diff --git a/src/types/index.ts b/src/types/index.tsindex f6fcb620..fc3c2ac6 100644--- a/src/types/index.ts+++ b/src/types/index.ts@@ -14,6 +14,13 @@ export type Project = {* Null until the user picks (or until /onboarding gets re-run).*/google_ads_account_id: string | null;+ /**+ * Optional inputs the user provided at onboarding so the CMO has a+ * starting point for its first task (writing PROJECT.md). Both are+ * free-text — the CMO uses whichever exist + decides how to explore.+ */+ website_url: string | null;+ codebase_path: string | null;};export type TaskStatus =@@ -72,6 +79,15 @@ export type Task = {* own id so the chain back to the planner is walkable.*/assigner_agent_id: string | null;+ /**+ * Task that must reach `done` before this one can start. When set, the+ * task is created in `blocked` status; the orchestrator clears this+ * pointer and flips blocked→proposed (then kicks off) when the blocker+ * resolves. Co-exists with approval-blocking: approval-blocked tasks+ * have a null blocked_by_task_id and resolve via the approval-wakeup+ * path. Null for tasks with no upstream dependency.+ */+ blocked_by_task_id: string | null;created_at: string;updated_at: string;};