Skip to content

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

feat(notfair): goal-driven pivot — one goal, one agent, one loop

Yuting Zhonge0566191ac97
diff --git a/README.md b/README.md
index b55b2aff..32722da1 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@ NotFair gives your AI agent direct access to Google Search Console, Google Ads,
The NotFair plugin is the CLI side — the skills that run inside Claude Code (and other AI agent hosts). [notfair.co](https://notfair.co) is the companion web app: sign in once, connect your Google Ads and Meta Ads accounts, and run audits through a browser UI. Both sides share the same engine, so an audit you run from the CLI uses the same tooling as the one on the web.
-There's also **[NotFair CMO](#notfair-cmo--a-local-marketing-team-in-your-browser)** — a local web portal that runs a team of specialist marketing agents (CMO, Google Ads, Meta Ads, SEO, X Ads) on top of your existing Claude Code or Codex login.
+There's also the **[NotFair app](#the-notfair-app--goal-driven-marketing-agents-in-your-browser)** — a local web portal where a goal-driven agent runs a measured improvement loop against one ambition ("cut CAC to $30") on top of your existing Claude Code or Codex login.
> *"Am I wasting money on ads right now?"*
> *"Why did my traffic drop and how do I fix it?"*
@@ -164,26 +164,26 @@ Your data is preserved — the runtime state directory (`~/.toprank/`, holding p
---
-## NotFair CMO — a local marketing team in your browser
+## The NotFair app — goal-driven marketing agents in your browser
-[NotFair CMO](notfair-cmo/) is a local web portal that turns the skills above into an always-on marketing team. Instead of invoking skills one at a time from the CLI, you get named specialist agents per project — a **CMO** who owns strategy and delegates, plus **Google Ads**, **Meta Ads**, **SEO**, and **X Ads** specialists — each in its own isolated workspace, running on top of the Claude Code or Codex login you already have. Chat with them, watch tasks move across a kanban board, approve governed actions (spend, publishes, bid changes) from an approvals inbox, and let them schedule their own recurring jobs on a native cron scheduler.
+[NotFair](notfair/) is a local web portal built around one idea: state a goal, get a loop. A dedicated agent turns your ambition into a server-verified metric with a measured baseline, you confirm the target, and the agent runs a disciplined improvement cycle on your cadence — the platform measures the number mechanically each tick, the agent scores its past moves against their predictions, makes at most one new move, and every governed action (spend, publishes, bid changes) parks in an approvals inbox until you decide. The Goal page shows the whole loop: metric sparkline vs. target, tick diary, open actions with review dates, and the learnings the agent accumulates.
-Open source, runs entirely on your machine, published to npm as [`notfair-cmo`](https://www.npmjs.com/package/notfair-cmo).
+Open source, runs entirely on your machine, published to npm as [`notfair`](https://www.npmjs.com/package/notfair).
### Get started
**Prerequisites:** Node 20+ and at least one harness installed and authenticated — [Claude Code](https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview) (recommended) or [Codex CLI](https://github.com/openai/codex).
```bash
-npx notfair-cmo@latest doctor # preflight: Node, harnesses, data dir, port
-npx notfair-cmo@latest # launch the UI at http://127.0.0.1:3327
+npx notfair@latest doctor # preflight: Node, harnesses, data dir, port
+npx notfair@latest # launch the UI at http://127.0.0.1:3327
```
-Or install globally with `npm install -g notfair-cmo`, then run `notfair-cmo`.
+Or install globally with `npm install -g notfair`, then run `notfair`.
-Create a project, pick your harness, and connect platforms during onboarding — each MCP you connect (Google Ads, Meta Ads, Search Console, X Ads) provisions the matching specialist agent automatically. Already using the plugin? `/notfair:cmo` launches the portal straight from Claude Code.
+Create a project, pick your harness, connect platforms during onboarding, then open **Goal** and state an ambition — the agent works out how to measure it and shows you the baseline before anything runs. Already using the plugin? `/notfair:cmo` launches the portal straight from Claude Code.
-Full docs, CLI reference, and architecture notes: [`notfair-cmo/README.md`](notfair-cmo/README.md).
+Full docs, CLI reference, and architecture notes: [`notfair/README.md`](notfair/README.md).
## Skills
@@ -257,7 +257,7 @@ notfair/
│ ├── geo-optimizer/ <- GEO for AI search engines
│ └── setup-cms/ <- CMS connector
├── gemini/ <- cross-model review via Gemini CLI
-├── notfair-cmo/ <- local marketing portal (npm: notfair-cmo)
+├── notfair/ <- local goal-loop agent app (npm: notfair)
├── notfair-upgrade-skill/ <- self-updater
├── test/ <- unit + LLM-judge eval tests
└── VERSION
diff --git a/notfair-cmo/ARCHITECTURE.md b/notfair-cmo/ARCHITECTURE.md
deleted file mode 100644
index 57b79b49..00000000
--- a/notfair-cmo/ARCHITECTURE.md
+++ /dev/null
@@ -1,252 +0,0 @@
-# Architecture
-
-> Single-user local app. No auth, no multi-tenancy, no hosted backend.
-
-## Process layout
-
-```
-USER'S MACHINE
-┌──────────────────────────────────────────────────────────────────────┐
-│ │
-│ ┌────────────────────────────────────┐ ┌──────────────────────┐ │
-│ │ notfair-cmo (Next.js) │ │ OpenClaw daemon │ │
-│ │ npx notfair-cmo → localhost:3000 │◀──▶│ WebSocket gateway │ │
-│ │ │ │ on loopback │ │
-│ │ ┌──────────────────────────────┐ │ └──────────┬───────────┘ │
-│ │ │ Frontend (React + shadcn) │ │ │ subprocess │
-│ │ │ - Sidebar + project switcher│ │ ▼ │
-│ │ │ - Per-agent chat (SSE) │ │ ┌──────────────────────┐ │
-│ │ │ + threads + tool steps │ │ │ openclaw CLI │ │
-│ │ │ - Cron tab + calendar │ │ │ - agents add/list │ │
-│ │ │ - Approvals inbox (V1.1) │ │ │ - cron add/list/rm │ │
-│ │ │ - Tasks board (V1.1) │ │ │ - mcp set/show/unset│ │
-│ │ │ - Activity (audit log) │ │ │ - agent (chat turn) │ │
-│ │ │ - Connections (MCP catalog) │ │ │ - memory search │ │
-│ │ │ - Settings (guardrails) │ │ │ - skills add/rm │ │
-│ │ │ - Paired OpenClaw pill │ │ └──────────────────────┘ │
-│ │ │ - Onboarding (SSE stream) │ │ │
-│ │ └──────────────────────────────┘ │ │
-│ │ ┌──────────────────────────────┐ │ │
-│ │ │ Server actions + API routes │ │ │
-│ │ │ - createProject (provisions │ │ │
-│ │ │ 3 agents + MCPs) │ │ │
-│ │ │ - clone/create/rename/ │ │ │
-│ │ │ delete agent │ │ │
-│ │ │ - schedule/pause/resume/ │ │ │
-│ │ │ delete cron │ │ │
-│ │ │ - archive project (cascade │ │ │
-│ │ │ disables crons) │ │ │
-│ │ │ - MCP connect/disconnect │ │ │
-│ │ │ (one-click PKCE OAuth) │ │ │
-│ │ │ - /api/chat (SSE) │ │ │
-│ │ │ - /api/onboarding/stream │ │ │
-│ │ │ - /api/mcp-oauth/callback │ │ │
-│ │ │ - /api/oauth/{provider}/* │ │ │
-│ │ │ (env-var scaffold, V1.1) │ │ │
-│ │ └──────────────────────────────┘ │ │
-│ │ ┌──────────────────────────────┐ │ │
-│ │ │ Local SQLite │ │ │
-│ │ │ ~/.notfair-cmo/db.sqlite │ │ │
-│ │ │ - projects │ │ │
-│ │ │ - tasks (V1.1 wires up) │ │ │
-│ │ │ - approvals (V1.1) │ │ │
-│ │ │ - cost_events (V1.1) │ │ │
-│ │ │ - oauth_tokens (encrypted) │ │ │
-│ │ │ - guardrails (config) │ │ │
-│ │ │ - agent_actions (audit log) │ │ │
-│ │ │ - sequence_runs │ │ │
-│ │ └──────────────────────────────┘ │ │
-│ └────────────────────────────────────┘ │
-└──────────────────────────────────────────────────────────────────────┘
-```
-
-## Why this shape
-
-**Don't rebuild the wheels.** OpenClaw already provides:
-- Agent runtime (per-agent isolated workspaces, model fallback chains)
-- Cron scheduler with agent attribution + run history
-- Built-in memory subsystem with REM (reflective episodic memory)
-- WebSocket gateway with auth modes
-- MCP client (`openclaw mcp set/show/unset`) with per-agent allowlists
-- Multi-channel delivery (Telegram, Slack, iMessage, etc.)
-
-We don't reimplement any of that. notfair-cmo adds:
-- A product-shaped chat + management UI scoped per marketing project
-- A consistent naming convention (`<project> / <agent> / <cron>`) so OpenClaw's flat namespace becomes hierarchical to the user
-- A project-scoped MCP catalog with one-click PKCE OAuth onboarding (`/connections`)
-- Local SQLite for product-specific state (tasks, approvals, cost events, OAuth tokens) that doesn't belong in OpenClaw's model
-- AES-256-GCM encrypted OAuth token vault with OS-keychain master key
-- An append-only `agent_actions` audit log surfaced as the Activity tab
-
-## Agent ↔ notfair-cmo interaction (V1)
-
-Two interaction layers:
-
-1. **Chat turn over the gateway WebSocket.** `/api/chat` proxies to OpenClaw's gateway via a pooled WS connection (`server/openclaw/gateway-client.ts`), streams tool calls + assistant text back as SSE, and persists the thread file through the gateway so reloads see full history.
-
-2. **Cron creation by the agent.** Agents are taught (via system prompt in `IDENTITY.md`) to use OpenClaw's built-in `exec` tool to run `openclaw cron add ...` directly. The system prompt enforces the project-namespaced naming convention so our cron tab parses + groups correctly.
-
-**No MCP server hosted by notfair-cmo.** We don't expose tools as an MCP server — agents call third-party MCP servers (e.g. `notfair-googleads`) that OpenClaw connects to on their behalf. The Connections page is the UI for that wiring; cross-project visibility is enforced by OpenClaw's `codex.agents` allowlist which `actions/mcp.ts` keeps in sync with the active project's agent ids.
-
-The autonomy/cost/approval features land in V1.1 — the SQLite tables, server helpers, and UI stubs are in place; the agent-side `record_cost` / `approve_action` enforcement hooks aren't wired yet.
-
-## Distribution
-
-- npm package (`notfair-cmo` bin)
-- Next.js standalone build (`.next/standalone/server.js` shipped, started by `bin/cli.mjs`)
-- Native deps: `better-sqlite3` (Node 24 prebuilds available), `keytar` (prebuilds for major platforms)
-- Runtime requires: Node 20+, OpenClaw installed and gateway running
-- `scripts/copy-standalone-assets.mjs` runs after `next build` so the npm tarball ships a runnable `.next/standalone` tree (Next omits `.next/static` + `public` by default).
-
-## Module map
-
-```
-bin/
- cli.mjs # CLI entry: `notfair-cmo` (start, doctor, stop)
-
-scripts/
- copy-standalone-assets.mjs # post-build: dereference symlinks into standalone tree
- e2e-provision.ts # dev helper: create a project + provision its agents
-
-src/
- app/
- layout.tsx # Root layout (TooltipProvider, Toaster, theme)
- globals.css
- (app)/ # Sidebar-shell route group
- layout.tsx # SidebarProvider + AppSidebar + main
- page.tsx # Project home (KPIs + recent actions)
- agents/ # Per-agent surface
- page.tsx # Agent index for the active project
- [agent]/
- page.tsx # Agent overview
- chat/ # Threaded chat (SSE)
- page.tsx
- [thread]/page.tsx
- cron/page.tsx # Per-agent crons
- files/page.tsx # Workspace files
- settings/page.tsx # Rename + danger zone
- skills/page.tsx # OpenClaw skills assigned to this agent
- activity/page.tsx # Append-only agent_actions audit log
- approvals/page.tsx # Pending approvals (V1.1 wires fully)
- tasks/page.tsx # Task board (V1.1 wires fully)
- crons/page.tsx # All crons for the project (calendar + list)
- connections/page.tsx # MCP catalog: connect/disconnect per project
- settings/page.tsx # Autonomy guardrails + project rename/danger
- projects/ # List + new
- page.tsx
- new/page.tsx
- onboarding/ # Magic-moment first run
- layout.tsx
- page.tsx
- api/
- chat/route.ts # POST → SSE stream via gateway WS
- onboarding/stream/route.ts # SSE: magic-moment provisioning
- mcp-oauth/callback/route.ts # One-click MCP PKCE callback
- oauth/[provider]/start/route.ts # Env-var direct OAuth (scaffold)
- oauth/[provider]/callback/route.ts # Env-var direct OAuth (scaffold)
- projects/[slug]/provision/route.ts # Re-provision agents for a project
-
- server/
- active-project.ts # cookie-backed current project
- agent-meta.ts # per-agent display metadata (name, role, color)
- agent-templates.ts # CMO / google_ads / seo definitions + IDENTITY.md writer
- mcp-catalog.ts # static known-MCP catalog (notfair-googleads, …)
- mcp-pending.ts # in-memory pending OAuth flows (PKCE state)
- mcp-state.ts # merged config + health probe per MCP
- actions/
- projects.ts # create (+provision), archive (cascade), rename, switch
- agents.ts # clone, create, rename, delete (cascade)
- crons.ts # schedule, pause, resume, delete
- cron-runs.ts # surface run history from OpenClaw
- approvals.ts # approve, reject (V1.1 fully wired)
- guardrails.ts # update thresholds
- mcp.ts # one-click PKCE connect/disconnect
- skills.ts # assign/remove OpenClaw skills on agents
- openclaw/
- cli.ts # subprocess wrapper: openclaw(args)
- gateway-client.ts # pooled WebSocket client + token discovery
- gateway-rpc.ts # request/response over the gateway WS
- agent-turn.ts # streaming agent invocation
- sessions.ts # chat-session lookup + pending-key registry
- crons.ts # cron list parser + naming convention + cache
- cron-schedule.ts # next-fire calculation (cron-parser)
- clone-agent.ts # `openclaw agents clone` wrapper
- project-delete.ts # cascade-delete a project's agents + crons
- db/
- db.ts # better-sqlite3 singleton + migration runner
- migrations.ts # embedded SQL migration manifest
- migrations/001_init.sql # canonical SQL (mirrored into migrations.ts)
- projects.ts, tasks.ts, approvals.ts, cost.ts,
- oauth.ts, guardrails.ts, agent-actions.ts
- secrets/
- master-key.ts # OS keychain (keytar) master key
- cipher.ts # AES-256-GCM encrypt / decrypt
-
- components/
- app-sidebar.tsx # Sidebar with project switcher + nav + status pill
- project-switcher.tsx
- paired-openclaw-pill.tsx # Sidebar pill → opens gateway dashboard with token
- agent-nav.tsx # Sidebar's per-agent navigation
- agent-tabs.tsx # Agent sub-nav (chat / cron / files / settings / skills)
- agent-chat.tsx # Streamed chat with Stop button + inline tool steps
- thread-selector.tsx # Thread picker in the agent chat
- markdown.tsx # GFM markdown renderer (assistant output)
- slash-command-popover.tsx # /command popover in chat composer
- schedule-cron-dialog.tsx
- cron-row-actions.tsx
- cron-calendar.tsx
- create-agent-button.tsx
- create-agent-dialog.tsx
- agent-rename-card.tsx
- agent-danger-zone.tsx
- reprovision-button.tsx
- project-rename-card.tsx
- danger-zone.tsx
- disable-source-crons-dialog.tsx
- mcp-card.tsx # Per-MCP card on the Connections page
- mcp-flash-banner.tsx # Post-redirect success/error banner
- google-ads-mcp-banner.tsx # Inline prompt in Google Ads chat to connect MCP
- approval-card.tsx
- skills-list.tsx
- onboarding-flow.tsx
- client-mount-gate.tsx # Defer client-only children until after mount
- ui/ # shadcn primitives
-
- hooks/
- use-mobile.ts
-
- lib/
- slug.ts # slugify + reserved-word check
- utils.ts # cn() for shadcn
- agent-colors.ts # deterministic per-agent accent
- slash-commands.ts # /command registry for the chat composer
- onboarding/steps.ts # magic-moment step definitions
-
- types/
- index.ts # Project, Task, Approval, CostEvent, etc.
-```
-
-## What we deliberately don't have
-
-- No auth, no sessions, no users table — single-user local
-- No multi-tenancy, no RLS — single SQLite file
-- No webhook signing / reconciliation — loopback only, trusted
-- No notfair-hosted MCP server — agents talk to OpenClaw's MCP clients
-- No telemetry — opt-in only when added in a later version
-- No Docker / Tauri distribution (V1) — npm only
-
-## Deferred to V1.1
-
-- Approval enforcement: the `approvals` table + UI are live; agent-side `approve_action` gating isn't wired
-- Cost tracking: `cost_events` + helpers + Settings thresholds exist; per-LLM-call middleware that records cost isn't wired (the sidebar shows a Paired OpenClaw pill instead of a cost meter in V1)
-- Task lifecycle UI: the `tasks` table + types exist; the board reflects them, but the proposer/approver loop isn't end-to-end
-- Cross-project signal sharing (agents reading each other's REM)
-- Eval harness + test suite (Vitest unit + Playwright E2E; mocked at the `openclaw/cli.ts` boundary)
-- Direct env-var OAuth UI (Google Ads / GSC) — the API routes scaffold the flow; no Connections-page UI surface yet (the MCP one-click flow covers the V1 Google Ads path)
-
-## Trade-offs to know about
-
-- **Agent name discipline depends on system prompt.** If the agent forgets the `<project> / <agent> / <name>` convention, the cron lands in our "ungrouped" bucket — graceful degradation, not broken.
-- **Connections is project-scoped, but OpenClaw's `mcp` config is workspace-global.** We namespace stored keys with the project slug (`<slug>-<catalog-key>`) and rewrite `codex.agents` to that project's agents so tokens don't bleed across projects.
-- **No agent ↔ agent direct messaging.** Agents coordinate by reading each other's OpenClaw memory entries (which agents already do natively via `memory search`).
-- **Gateway WS is pooled and reused per request.** Cold-start cost lives in the first chat turn; subsequent turns hit a warm connection via `gateway-client.ts`.
diff --git a/notfair-cmo/CLAUDE.md b/notfair-cmo/CLAUDE.md
deleted file mode 100644
index 4b12baca..00000000
--- a/notfair-cmo/CLAUDE.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# CLAUDE.md
-
-Project conventions and notes for AI assistants working on notfair-cmo.
-
-## Testing
-
-Test runner: **vitest** (added 2026-05-19 as part of the onboarding rework, the first test infrastructure in the repo).
-
-- Run tests once: `pnpm test`
-- Watch mode: `pnpm test:watch`
-- Vitest UI: `pnpm test:ui`
-
-Test files live next to the code they test: `src/lib/slug.ts` → `src/lib/slug.test.ts`.
-
-Environment selection (configured in `vitest.config.ts`):
-- Default: `node` (server modules, libs)
-- Components under `src/components/**`: `jsdom`
-- Page tests `src/app/**/*.test.tsx`: `jsdom`
-
-Setup file `vitest.setup.ts` imports `@testing-library/jest-dom/vitest` so jest-dom matchers (`toBeInTheDocument`, etc.) are available in component tests.
-
-### What to test
-
-- **Server modules** (anything under `src/server/`): unit-test pure functions, integration-test handlers with mocked subprocess (`openclaw`) and mocked `fetch` (MCP).
-- **Lib utilities** (`src/lib/`): pure-function unit tests with full branch coverage.
-- **Components** (`src/components/`): user-facing interaction tests via `@testing-library/react` (render → fire events → assert visible state). Avoid implementation-detail assertions.
-- **API routes** (`src/app/api/`): integration tests that POST to the handler with mocked dependencies.
-
-### Mocking external systems
-
-- **Harness adapters**: under `src/server/adapters/`. The `claude-code-local` and `codex-local` execute paths spawn a real subprocess; in tests, mock the parser modules (`parse.ts`) for unit coverage, or stub `child_process.spawn` in integration tests.
-- **MCP HTTP**: mock `fetch` globally. The MCP responds with JSON-RPC envelope `{jsonrpc, id, result | error}`.
-- **SQLite**: use the real better-sqlite3 against an in-memory DB or a tmpdir DB — better-sqlite3 is synchronous + fast enough that mocking adds friction without value.
-
-### Prompt/LLM changes (eval suites required)
-
-If you touch any of these files, an eval pass is required before shipping:
-
-- `src/server/agent-templates.ts` (CMO + Google Ads + SEO system prompts)
-- `src/server/agent-chat.tsx` chat orchestration if it adds new tool-call patterns
-- Any new file under `src/server/onboarding/` that constructs prompt context (e.g., `audit.ts` writing `FIRST_TURN.md`)
-
-Light eval harness lives at `tests/evals/`. Pattern: golden scenario JSON + expected-shape assertions. Run via `pnpm eval`. Skips entirely when `OPENAI_API_KEY` is absent. See `tests/evals/README.md` for details.
-
-## Project structure conventions
-
-- **Database**: SQLite via `better-sqlite3` at `~/.notfair-cmo/db.sqlite` (overridable via `NOTFAIR_CMO_DATA_DIR`). Migrations are forward-only in `src/server/db/migrations.ts` (mirrored in `src/server/db/migrations/`).
-- **Agent state**: agent workspaces live at `~/.notfair-cmo/agents/<agent-id>/`. notfair-cmo owns the workspace; the chosen harness adapter writes whatever files it expects (CLAUDE.md for Claude Code, AGENTS.md for Codex, plus the shared IDENTITY.md / SKILL.md / PROJECT.md notfair-cmo writes).
-- **Sessions / transcripts**: stored in SQLite (`sessions`, `transcript_events`). Replaces the OpenClaw JSONL transcript files. The chat route persists every adapter event there; the UI replays them on attach.
-- **MCP tokens**: stored project-scoped in the `mcp_tokens` SQLite table. Adapters expose `registerMcp` / `unregisterMcp` to wire the chosen harness's MCP config to point at the right tokens.
-- **Cron schedules**: stored in the `scheduled_jobs` SQLite table. A node-cron-style tick loop in `src/server/scheduler/tick.ts` polls due jobs every 30s and dispatches them through the project's adapter.
-- **Project memory**: per-agent workspace files (e.g. files the agent writes in its workspace dir). No proprietary REM/memory layer yet; if an agent needs durable memory across sessions it writes to its workspace.
-
-## Architectural tenets
-
-- **Harness-agnostic.** notfair-cmo runs on top of any local AI coding agent that conforms to the `HarnessAdapter` contract under `src/server/adapters/`. Today: Claude Code (`claude-code-local`) and Codex (`codex-local`). Recommended path mirrors paperclip's adapter-registry pattern.
-- **notfair-cmo owns the runtime services.** Cron scheduling, MCP token storage, agent provisioning, session/transcript persistence — all in SQLite + Node. Adapters only handle: (1) spawning the harness to stream a turn, (2) writing harness-specific workspace config, (3) registering MCP servers for the harness to find.
-- **Single-user local CLI.** V1 is a local Next.js process launched via `notfair-cmo` bin. No multi-tenant code paths, no auth, no multi-process state coordination.
-- **Don't rebuild the wheels.** Before proposing any new abstraction, identify whether AI SDK, the existing skill ecosystem, or another off-the-shelf tool already solves the sub-problem. Prefer thin attribution/glue layers over custom infrastructure.
-
-## Commit style
-
-Conventional commits with type-scope-description: `feat(onboarding): add real audit stream`, `fix(cron): preserve agent prefix on rename`, `chore(deps): bump next to 16.2.7`.
-
-Co-author trailer when AI-assisted:
-```
-Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
-```
diff --git a/notfair-cmo/README.md b/notfair-cmo/README.md
deleted file mode 100644
index eabfd396..00000000
--- a/notfair-cmo/README.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# notfair-cmo
-
-> Local AI marketing portal. Spin up specialist marketing agents per project on top of Claude Code or Codex, chat with them, manage their scheduled work, connect their tools.
-
-Open source. Runs entirely on your machine. Bring your own LLM credentials (via the harness CLI you already authenticate to) and your own ad-platform OAuth.
-
-## What it gives you
-
-- **Per-agent chat** scoped to each project — talk to a marketing-shaped agent that can launch campaigns, audit SEO, propose recurring jobs. Tool calls + MCP invocations stream inline as collapsible step rows.
-- **Specialist agents** (CMO + Google Ads + Meta Ads + SEO + X Ads), each isolated in its own workspace dir. The CMO is provisioned on project create; each specialist appears when you connect the matching platform MCP. Clone or create more from the sidebar.
-- A **cron tab** (calendar + list) backed by a native SQLite scheduler. Agents create jobs via the `schedule_recurring_work` MCP tool; the tick loop in the Next.js process fires them on time.
-- **Project-scoped MCP connections** — one-click PKCE OAuth to bring third-party tools (Google Ads via NotFair's hosted MCP) into the agents' toolbox. Tokens stored in SQLite, never in env vars, and wired into the chosen harness automatically.
-- A **live audit log** of every autonomous decision and scheduled run, append-only.
-- An **approvals inbox**, **abandoned-task recovery**, and **task board** — when an agent forgets to close a task, you get Resume / Mark done / Cancel actions instead of an infinite spinner.
-
-## Pick your harness
-
-At onboarding you pick which local AI coding agent runs the work:
-
-| Harness | Status | Notes |
-|---|---|---|
-| **Claude Code** | Recommended | Uses your existing `claude` login. Per-agent `.mcp.json` for isolation. |
-| **Codex** | Supported | Uses your existing `codex` login. Per-server env-var bearers. Requires `--dangerously-bypass-approvals-and-sandbox` (set by the adapter) so tool calls and loopback reach your local orchestration MCP. |
-
-Different projects can run on different harnesses; the choice persists on the project row.
-
-## Prerequisites
-
-- **Node 20+** (Node 24 recommended for native-module prebuilds).
-- **At least one harness installed and authenticated**:
- - [Claude Code](https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview), or
- - [Codex CLI](https://github.com/openai/codex)
-
-Run `notfair-cmo doctor` to verify Node, both harnesses, data dir, and port.
-
-## Install + run
-
-```bash
-# One-shot, no install:
-npx notfair-cmo@latest doctor # verify env
-npx notfair-cmo@latest # launch UI on http://127.0.0.1:3327
-
-# Or install globally:
-npm install -g notfair-cmo
-notfair-cmo
-```
-
-The UI opens in your browser. Sidebar is project-scoped; create one to start.
-
-## CLI
-
-```
-notfair-cmo Launch local server + open UI (default)
-notfair-cmo start Same as above
-notfair-cmo doctor Run preflight checks (see below)
-notfair-cmo --version
-notfair-cmo --help
-```
-
-Options on `start`: `--port <n>` (default 3327), `--no-open`, `--data-dir <path>`.
-Options on `doctor`: `--port <n>`, `--data-dir <path>`.
-
-`doctor` runs five checks: Node ≥ 20 (24 recommended), Claude Code on PATH, Codex on PATH, at least one harness ready, data dir writable, and the preferred port free. Exits 0 if every check is passing, 1 otherwise, with a `Fix:` line under each failure naming the exact command to run.
-
-## What happens when you create a project
-
-1. SQLite row written at `~/.notfair-cmo/db.sqlite` with your harness choice (`projects.harness_adapter`).
-2. Agents provisioned under the project's slug:
- - `<slug>-cmo-<name>` — Chief Marketing Officer, created immediately.
- - Specialists (`google-ads`, `meta-ads`, `seo`, `x-ads`) are gated on
- connecting the matching platform MCP — each OAuth connect provisions
- its agent (Search Console provisions the SEO specialist).
-
- Each gets its own workspace at `~/.notfair-cmo/agents/<id>/` with an `IDENTITY.md` system prompt scoped to its role + the chosen harness's native config (`.mcp.json` for Claude Code, sections in `~/.codex/config.toml` for Codex).
-3. The orchestration MCP server (`/api/mcp/orchestration`) is registered for every agent so they can call `create_task`, `submit_task_status`, `set_project_brief`, `schedule_recurring_work`, etc.
-4. The onboarding stream walks you through the "magic moment" preview steps over SSE, then redirects to the project home.
-
-## Scheduling recurring work
-
-Agents call the `schedule_recurring_work` MCP tool to create cron-style jobs that fire as synthetic task assignments to themselves (or another agent in the project). The tick loop is a `setInterval` in the Next.js process polling `scheduled_jobs` every 30 s; due jobs are dispatched through the project's harness adapter.
-
-You can also schedule manually via the **+ New cron** button on the Crons tab.
-
-## Connecting MCP servers (for live ad-platform data)
-
-The Connections page lists the MCP servers in our catalog (NotFair Google Ads, Meta Ads, Google Search Console, Google Analytics, X Ads — plus browseable extras like Stripe and Supabase, or any custom MCP URL). Click **Connect** to start a one-click PKCE OAuth flow — no environment variables to set, no Google Cloud project of your own to register.
-
-The token is persisted into `mcp_tokens` (SQLite) and the catalog MCP is automatically registered with every agent in the project via the chosen harness's config. New agents provisioned later get the same wiring.
-
-OAuth refresh tokens are AES-256-GCM encrypted with a master key stored in your OS keychain (via `keytar`) and persisted to your local SQLite.
-
-## Live transcript
-
-Chat events (deltas, tool calls, lifecycle) are persisted to `transcript_events` and **also** pushed through an in-process `EventEmitter` keyed by session id. Open tabs subscribe via SSE; new events land in milliseconds. Re-attach to a streaming thread (open the URL in a second tab while the agent is mid-turn) is race-free: the server backfills from cursor=0 before attaching the live subscription, with dedup-by-seq.
-
-## Data location
-
-- App state: `~/.notfair-cmo/db.sqlite` (override with `--data-dir` or `NOTFAIR_CMO_DATA_DIR`)
-- Agent workspaces: `~/.notfair-cmo/agents/<agent-id>/`
-- Harness configs: `~/.claude/` for Claude Code; `~/.codex/config.toml` for Codex (managed by the respective CLI)
-- Orchestration MCP secret: `~/.notfair-cmo/mcp-server-secret` (0600 perms)
-
-## What V1 is and isn't
-
-**Is:** an agent runner + per-agent chat portal + native cron scheduler + MCP connection hub + activity audit log + abandoned-task recovery. Runs on Claude Code or Codex, no proprietary agent runtime.
-
-**Isn't (yet):** a fully autonomous CMO. Auto-approve rule editor, per-LLM-call cost tracking, eval harness, and cross-channel portfolio coordination are scaffolded but not wired end-to-end. They land in subsequent releases.
-
-See `ARCHITECTURE.md` for the design and `CONTRIBUTING.md` for development setup.
-
-## License
-
-MIT — see LICENSE.
diff --git a/notfair-cmo/scripts/e2e-provision.ts b/notfair-cmo/scripts/e2e-provision.ts
deleted file mode 100644
index 5f4da1ed..00000000
--- a/notfair-cmo/scripts/e2e-provision.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { ensureProjectAgents } from "../src/server/agent-templates";
-
-async function main() {
- const r = await ensureProjectAgents("e2e-test-brand");
- console.log(JSON.stringify(r, null, 2));
-}
-
-main().catch((err) => {
- console.error(err);
- process.exit(1);
-});
diff --git a/notfair-cmo/src/app/(app)/[project]/activity/page.tsx b/notfair-cmo/src/app/(app)/[project]/activity/page.tsx
deleted file mode 100644
index e614c1c9..00000000
--- a/notfair-cmo/src/app/(app)/[project]/activity/page.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { listAgentActions } from "@/server/db/agent-actions";
-
-function timeAgo(iso: string) {
- const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
- if (seconds < 60) return `${Math.floor(seconds)}s ago`;
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
- return `${Math.floor(seconds / 86400)}d ago`;
-}
-
-export default async function ActivityPage({
- params,
-}: {
- params: Promise<{ project: string }>;
-}) {
- const { project: slug } = await params;
- const project = getProject(slug);
- if (!project || project.archived_at) notFound();
- const actions = listAgentActions(project.slug, 200);
-
- return (
- <div className="ns-app-wide" style={{ maxWidth: 900 }}>
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">Activity</h1>
- <p className="ns-page-sub">
- <b>{actions.length}</b> {actions.length === 1 ? "action" : "actions"}
- {" "}· append-only audit log of every autonomous decision and
- scheduled run.
- </p>
- </div>
- </header>
-
- {actions.length === 0 ? (
- <div className="ns-empty">
- <p className="ns-empty-title">No activity yet.</p>
- <p className="ns-empty-sub">
- Every autonomous decision and scheduled job lands here for auditing.
- When you provision agents or schedule crons, the events show up.
- </p>
- </div>
- ) : (
- <ol className="ns-group">
- {actions.map((a) => (
- <li key={a.id} className="ns-row flex-col items-start gap-2">
- <div className="flex w-full flex-wrap items-baseline gap-2">
- <span className="ns-tag-mono">{a.action_type}</span>
- <span className="font-mono text-[11px] text-[hsl(var(--notfair-ink-4))]">
- {a.agent_id}
- </span>
- <span className="ml-auto text-[11.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
- {timeAgo(a.occurred_at)} ·{" "}
- {new Date(a.occurred_at).toLocaleString()}
- </span>
- </div>
- <p className="m-0 text-[13px] leading-snug text-[hsl(var(--notfair-ink-2))]">
- {a.summary}
- </p>
- {a.reasoning && (
- <p className="m-0 w-full whitespace-pre-wrap rounded-lg bg-[hsl(var(--notfair-surface-2))] px-3 py-2 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-3))]">
- {a.reasoning}
- </p>
- )}
- </li>
- ))}
- </ol>
- )}
- </div>
- );
-}
-
-export const dynamic = "force-dynamic";
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
deleted file mode 100644
index 2011f755..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/registry";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import {
- buildPendingSessionKey,
- findSessionBySessionId,
- listSessionsForAgent,
-} from "@/server/sessions/view";
-import { classifySessions } from "@/server/sessions/view";
-import { getMcpStatus } from "@/server/mcp/state";
-import { getMcpCatalog } from "@/server/mcp-catalog";
-import { readTranscriptTail } from "@/server/sessions/transcript-tail";
-import { LiveTranscript } from "@/components/live-transcript";
-import { GoogleAdsMcpBanner } from "@/components/google-ads-mcp-banner";
-import { McpFlashBanner } from "@/components/mcp-flash-banner";
-import { ChatThreadRail, type SessionLite } from "@/components/chat-thread-rail";
-
-type Params = { agent: string; thread: string; project: string };
-type Search = { mcp_connected?: string; mcp_error?: string };
-
-export default async function AgentChatThreadPage({
- params,
- searchParams,
-}: {
- params: Promise<Params>;
- searchParams: Promise<Search>;
-}) {
- const { agent: agentSlug, thread: threadId, project: projectSlug } = await params;
- const { mcp_connected, mcp_error } = await searchParams;
-
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
-
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
- const agentFullId = resolved.agent_id;
- const allSessions = listSessionsForAgent(project.slug, agentFullId);
- const existing = findSessionBySessionId(project.slug, agentFullId, threadId);
-
- // sessionKey is now just the label string (the notfair-cmo `sessions.id`
- // is opaque to the UI; the label drives URLs + transcript lookups).
- const sessionKey =
- existing?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);
- const { events: initialEvents, byteOffset: initialByteOffset } =
- readTranscriptTail(project.slug, agentFullId, threadId, 0);
-
- // Classify existing sessions by origin (task / cron / chat) so the
- // dropdown can show the task display_id, cron name, or first-message
- // preview instead of opaque UUIDs.
- const origins = await classifySessions(agentFullId, project.slug, allSessions);
- const enriched: SessionLite[] = allSessions.map((s) => ({
- sessionId: s.sessionId,
- label: s.label,
- sessionKey: s.sessionKey,
- lastInteractionAt: s.lastInteractionAt,
- pending: s.pending,
- title: s.title,
- pinned: s.pinned,
- origin: origins.get(s.label),
- }));
-
- // For the rail: surface the pending thread at the top so the user sees
- // it's "selected" even before sending the first message.
- const sessionsForRail: SessionLite[] = existing
- ? enriched
- : [
- {
- sessionId: threadId,
- label: threadId.slice(0, 8),
- sessionKey,
- lastInteractionAt: 0,
- pending: true,
- },
- ...enriched,
- ];
-
- // The Google Ads agent depends on the notfair-googleads MCP for live
- // account operations. When it isn't connected yet (or the token is stale),
- // surface a banner so the user can fix it in one click without leaving
- // the chat. Probe runs server-side with its own 2s timeout — same as the
- // Connections page — so a slow upstream can't gate the chat render.
- const googleAdsMcpStatus =
- resolved.template_key === "google_ads"
- ? await getMcpStatus(project.slug, "notfair-googleads")
- : null;
-
- // 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;
-
- // MCP catalog — pass through the minimum shape the chat needs to
- // render an MCP server's brand favicon next to its tool calls.
- // Mapping is by server key, so the resource_url is the brand domain
- // we feed faviconV2.
- // Provider-fed model list for the composer's selector (codex reads its
- // account-scoped cache; claude uses its documented tier aliases).
- const modelOptions = await requireAdapter(
- project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,
- ).listModels();
- const mcpCatalog = getMcpCatalog(project.slug).map((m) => ({
- key: m.key,
- display_name: m.display_name,
- resource_url: m.resource_url,
- }));
-
- return (
- <div className="flex h-full flex-col">
- <McpFlashBanner connected={mcp_connected} error={mcp_error} />
-
- {googleAdsMcpStatus && googleAdsMcpStatus.state !== "connected" && (
- <GoogleAdsMcpBanner status={googleAdsMcpStatus} projectSlug={projectSlug} />
- )}
-
- {/* Same two-pane shape as the task workspace: thread rail on the
- left (New chat on top), live transcript on the right. */}
- <div className="flex min-h-0 flex-1">
- <ChatThreadRail
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- sessions={sessionsForRail}
- activeSessionId={threadId}
- />
- <section className="flex min-w-0 flex-1 flex-col">
- <LiveTranscript
- key={threadId}
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- agentDisplayName={resolved.name}
- threadId={threadId}
- sessionKey={sessionKey}
- initialEvents={initialEvents}
- initialByteOffset={initialByteOffset}
- autoKickoff={autoKickoff}
- mcpCatalog={mcpCatalog}
- modelOptions={modelOptions}
- />
- </section>
- </div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
deleted file mode 100644
index fcebb840..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { redirect, notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import {
- listSessionsForAgent,
- newSessionId,
-} from "@/server/sessions/view";
-import { pickLatestChatSession } from "@/server/sessions/view";
-import { listTasksByAgent } from "@/server/db/tasks";
-import { projectHref } from "@/lib/project-href";
-
-/**
- * Default landing for /<project>/agents/[agent]/chat — pick a free-form
- * chat thread (NOT a task workspace or cron run) and redirect into the
- * per-thread URL so refresh/share/back-button all keep the thread context.
- * Task and cron threads have their own entry points (kanban card, cron
- * calendar) and shouldn't hijack the agent's "chat" landing.
- */
-export default async function ChatIndexPage({
- params,
-}: {
- params: Promise<{ agent: string; project: string }>;
-}) {
- const { agent: agentSlug, project: projectSlug } = await params;
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
-
- // Build a set of every thread_id that belongs to a task so we can
- // exclude those sessions. Cron sessions self-identify via OpenClaw's
- // `cron:<jobId>:run:<id>` label prefix.
- const taskThreadIds = new Set<string>();
- for (const t of listTasksByAgent(resolved.agent_id)) {
- if (t.thread_id) taskThreadIds.add(t.thread_id);
- }
-
- const sessions = listSessionsForAgent(project.slug, resolved.agent_id);
- const latestChat = pickLatestChatSession(sessions, taskThreadIds);
- const target = latestChat?.sessionId ?? newSessionId();
- redirect(projectHref(projectSlug, `/agents/${agentSlug}/chat/${target}`));
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/cron/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/cron/page.tsx
deleted file mode 100644
index fff50a05..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/cron/page.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import { listCronsForProject } from "@/server/scheduler/display";
-import {
- annotateOccurrencesWithRunStatus,
- expandSchedule,
-} from "@/server/scheduler/display";
-import {
- CronCalendar,
- type CalendarCron,
- type CalendarOccurrence,
-} from "@/components/cron-calendar";
-import { ScheduleCronDialog } from "@/components/schedule-cron-dialog";
-import type { ScheduleInput } from "@/server/actions/cron-runs";
-
-const NUM_DAYS = 14;
-
-function scheduleForCalendar(s: unknown): ScheduleInput | null {
- if (!s || typeof s !== "object") return null;
- const obj = s as { kind?: string; expr?: unknown; tz?: unknown };
- if (obj.kind === "cron" && typeof obj.expr === "string") {
- return { kind: "cron", expr: obj.expr, ...(typeof obj.tz === "string" ? { tz: obj.tz } : {}) };
- }
- return null;
-}
-
-type Params = { agent: string; project: string };
-
-export default async function AgentCronPage({
- params,
-}: {
- params: Promise<Params>;
-}) {
- const { agent: agentSlug, project: projectSlug } = await params;
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
-
- const templateSlug = resolved.slug;
-
- let error: string | null = null;
- let view: Awaited<ReturnType<typeof listCronsForProject>>;
- try {
- view = await listCronsForProject(project.slug);
- } catch (err) {
- view = { project_slug: project.slug, groups: [] };
- error = err instanceof Error ? err.message : String(err);
- }
-
- const myGroup = view.groups.find((g) => g.agent === templateSlug);
- const allCrons = myGroup?.crons ?? [];
-
- const today = new Date();
- today.setHours(0, 0, 0, 0);
- const startOfFirstDay = today.getTime();
- const dayMs = 24 * 60 * 60 * 1000;
- const until = startOfFirstDay + NUM_DAYS * dayMs;
-
- const occurrences: CalendarOccurrence[] = [];
- const schedulesByCronId = new Map<string, ReturnType<typeof scheduleForCalendar>>();
- for (const cron of allCrons) {
- const occs = expandSchedule(
- cron.id,
- cron.schedule_raw,
- // Never expand before the cron existed — avoids phantom occurrences on
- // days earlier in the window than the cron's creation.
- { from: Math.max(startOfFirstDay, cron.created_at_ms ?? startOfFirstDay), until },
- {
- name: cron.name,
- short_name: cron.short_name,
- agent_id: cron.agent_id,
- agent_slug: cron.agent_slug,
- schedule_text: cron.schedule_text,
- },
- );
- for (const o of occs) occurrences.push({ ...o, cron_disabled: cron.disabled });
- schedulesByCronId.set(cron.id, scheduleForCalendar(cron.schedule_raw));
- }
- annotateOccurrencesWithRunStatus(
- occurrences,
- new Map(
- [...schedulesByCronId.entries()].map(([k, v]) => [k, v ?? undefined]),
- ),
- );
-
- const cronsById: Record<string, CalendarCron> = {};
- for (const cron of allCrons) {
- cronsById[cron.id] = {
- id: cron.id,
- short_name: cron.short_name,
- full_name: cron.name,
- agent_id: cron.agent_id,
- agent_slug: cron.agent_slug,
- schedule_text: cron.schedule_text,
- disabled: cron.disabled,
- status_text: cron.status_text,
- message: cron.message,
- description: cron.description,
- last_run_at_ms: cron.last_run_at_ms,
- last_status: cron.last_status,
- last_error: cron.last_error,
- schedule_raw: scheduleForCalendar(cron.schedule_raw),
- };
- }
-
- const totalActive = allCrons.filter((c) => !c.disabled).length;
- const totalDisabled = allCrons.length - totalActive;
-
- return (
- <div className="h-full overflow-y-auto">
- <div className="ns-app-wide">
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">{resolved.name}&rsquo;s schedule</h1>
- <p className="ns-page-sub">
- <b>{totalActive}</b> active
- {totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""}
- </p>
- </div>
- <div className="ns-page-actions">
- <ScheduleCronDialog projectSlug={project.slug} />
- </div>
- </header>
-
- {error && (
- <div className="ns-card">
- <div className="ns-card-body">
- <p className="text-[14px] font-semibold text-destructive">
- Could not load crons.
- </p>
- <p className="mt-1 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- {error}
- </p>
- </div>
- </div>
- )}
-
- {!error && allCrons.length === 0 && (
- <div className="ns-empty">
- <p className="ns-empty-title">
- No scheduled work for {resolved.name} yet.
- </p>
- <p className="ns-empty-sub">
- Ask the agent in chat (&ldquo;run a daily bid review at 9am&rdquo;)
- or schedule one directly.
- </p>
- <div className="ns-empty-action">
- <ScheduleCronDialog projectSlug={project.slug} />
- </div>
- </div>
- )}
-
- {!error && allCrons.length > 0 && (
- <CronCalendar
- startOfFirstDay={startOfFirstDay}
- numDays={NUM_DAYS}
- occurrences={occurrences}
- cronsById={cronsById}
- agentSlugs={[templateSlug]}
- />
- )}
- </div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/files/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/files/page.tsx
deleted file mode 100644
index 143ea458..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/files/page.tsx
+++ /dev/null
@@ -1,184 +0,0 @@
-import Link from "next/link";
-import { notFound } from "next/navigation";
-import { FileText, FileX } from "lucide-react";
-import { getProject } from "@/server/db/projects";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import { listAgentFiles, getAgentFile } from "@/server/agents/files";
-import { cn } from "@/lib/utils";
-import { projectHref } from "@/lib/project-href";
-
-type AugmentedFile = Awaited<ReturnType<typeof listAgentFiles>>["files"][number];
-
-type Params = { agent: string; project: string };
-type Search = { file?: string };
-
-export default async function AgentFilesPage({
- params,
- searchParams,
-}: {
- params: Promise<Params>;
- searchParams: Promise<Search>;
-}) {
- const { agent: agentSlug, project: projectSlug } = await params;
- const { file: requestedFile } = await searchParams;
-
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
-
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
- const agentFullId = resolved.agent_id;
-
- let error: string | null = null;
- let files: AugmentedFile[] = [];
- let workspace = "";
- try {
- const list = await listAgentFiles(agentFullId);
- files = list.files;
- workspace = list.workspace;
- } catch (err) {
- error = err instanceof Error ? err.message : String(err);
- }
-
- const identityIdx = files.findIndex((f) => f.name === "IDENTITY.md");
- const projectIdx = files.findIndex((f) => f.name === "PROJECT.md");
- if (identityIdx >= 0 && projectIdx >= 0 && projectIdx !== identityIdx + 1) {
- const projectFile = files[projectIdx]!;
- const without = files.filter((_, i) => i !== projectIdx);
- const insertAt = without.findIndex((f) => f.name === "IDENTITY.md") + 1;
- files = [...without.slice(0, insertAt), projectFile, ...without.slice(insertAt)];
- }
-
- const selectedName =
- (requestedFile && files.find((f) => f.name === requestedFile)?.name) ||
- files.find((f) => !f.missing)?.name ||
- files[0]?.name;
-
- let selectedContent: string | null = null;
- let selectedSize: number | undefined;
- let selectedUpdatedAtMs: number | undefined;
- let selectedMissing = false;
- let selectedError: string | null = null;
- if (selectedName) {
- const entry = files.find((f) => f.name === selectedName);
- selectedMissing = entry?.missing ?? true;
- if (!selectedMissing) {
- try {
- const got = await getAgentFile(agentFullId, selectedName);
- selectedContent = got.file.content;
- selectedSize = got.file.size;
- selectedUpdatedAtMs = got.file.updatedAtMs;
- } catch (err) {
- selectedError = err instanceof Error ? err.message : String(err);
- }
- }
- }
-
- return (
- <div className="grid h-full grid-cols-[260px_minmax(0,1fr)] divide-x divide-border bg-background">
- {/* Left rail — file list */}
- <aside className="flex min-h-0 flex-col bg-[hsl(var(--notfair-sidebar))]">
- <div className="border-b border-border/60 px-4 py-3">
- <div className="text-[11px] font-semibold uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">
- Workspace files
- </div>
- {workspace && (
- <div className="mt-1 truncate font-mono text-[10px] text-[hsl(var(--notfair-ink-4))]">
- {workspace}
- </div>
- )}
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto py-2">
- {error && (
- <div className="px-4 py-3 text-xs text-destructive">{error}</div>
- )}
- {!error && files.length === 0 && (
- <div className="px-4 py-3 text-xs text-[hsl(var(--notfair-ink-4))]">
- No files yet.
- </div>
- )}
- {files.map((f) => {
- const isActive = f.name === selectedName;
- return (
- <Link
- key={f.name}
- href={projectHref(
- projectSlug,
- `/agents/${agentSlug}/files?file=${encodeURIComponent(f.name)}`,
- )}
- className={cn(
- "mx-2 flex items-center gap-2 rounded-md px-2 py-1.5 text-[13px] transition-colors",
- isActive
- ? "bg-[hsl(var(--notfair-accent-soft))] text-[hsl(var(--notfair-accent))]"
- : "text-[hsl(var(--notfair-ink-3))] hover:bg-[hsl(var(--notfair-surface-2))] hover:text-[hsl(var(--notfair-ink))]",
- f.missing && !isActive && "opacity-60",
- )}
- >
- {f.missing ? (
- <FileX className="size-3.5 shrink-0 opacity-70" />
- ) : (
- <FileText className="size-3.5 shrink-0" />
- )}
- <span className="truncate font-mono">{f.name}</span>
- {f.missing && (
- <span className="ml-auto rounded-[4px] bg-[hsl(var(--notfair-surface-2))] px-1 py-px text-[9px] font-medium uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">
- empty
- </span>
- )}
- </Link>
- );
- })}
- </div>
- </aside>
-
- {/* Right pane — file viewer */}
- <section className="flex min-h-0 flex-col bg-background">
- {!selectedName ? (
- <div className="flex h-full items-center justify-center p-6 text-sm text-[hsl(var(--notfair-ink-4))]">
- Select a file to view its contents.
- </div>
- ) : selectedMissing ? (
- <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
- <FileX className="size-7 text-[hsl(var(--notfair-ink-4))] opacity-60" />
- <div className="text-[14px] font-medium text-[hsl(var(--notfair-ink-2))]">
- <span className="font-mono">{selectedName}</span> doesn&rsquo;t exist
- yet.
- </div>
- <div className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- The agent may create it during onboarding or when first invoked.
- </div>
- </div>
- ) : selectedError ? (
- <div className="p-6 text-sm text-destructive">{selectedError}</div>
- ) : (
- <>
- <header className="flex items-center justify-between border-b border-border/60 px-6 py-3">
- <div className="min-w-0">
- <div className="truncate font-mono text-[13.5px] text-[hsl(var(--notfair-ink))]">
- {selectedName}
- </div>
- <div className="mt-0.5 text-[11px] text-[hsl(var(--notfair-ink-4))]">
- {selectedSize !== undefined && `${formatBytes(selectedSize)}`}
- {selectedSize !== undefined && selectedUpdatedAtMs && " · "}
- {selectedUpdatedAtMs &&
- `updated ${new Date(selectedUpdatedAtMs).toLocaleString()}`}
- </div>
- </div>
- </header>
- <div className="min-h-0 flex-1 overflow-y-auto">
- <pre className="whitespace-pre-wrap break-words p-6 font-mono text-[13px] leading-relaxed text-[hsl(var(--notfair-ink-2))]">
- {selectedContent}
- </pre>
- </div>
- </>
- )}
- </section>
- </div>
- );
-}
-
-function formatBytes(n: number): string {
- if (n < 1024) return `${n} B`;
- if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
- return `${(n / (1024 * 1024)).toFixed(2)} MB`;
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/layout.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/layout.tsx
deleted file mode 100644
index e98bb9fa..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/layout.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import { resolveAgentMcpBlocker } from "@/server/onboarding/agent-mcp-blocker";
-import { AgentTabs } from "@/components/agent-tabs";
-import { AgentMcpBlockerCard } from "@/components/agent-mcp-blocker-card";
-
-type Params = { agent: string; project: string };
-
-export default async function AgentLayout({
- children,
- params,
-}: {
- children: React.ReactNode;
- params: Promise<Params>;
-}) {
- const { agent: agentSlug, project: projectSlug } = await params;
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
-
- // Specialists whose required MCP isn't connected for this project
- // render a "Connect <platform>" blocker in place of the chat/tasks UI.
- // The tab strip is suppressed too — there's nothing actionable inside
- // any of the tabs until the MCP is wired.
- const blocker = resolveAgentMcpBlocker(project.slug, resolved.template_key);
- if (blocker) {
- return (
- <div className="absolute inset-0 flex flex-col">
- <AgentMcpBlockerCard projectSlug={projectSlug} blocker={blocker} />
- </div>
- );
- }
-
- return (
- // Escape parent main's p-6 so the tab strip + content area can own the
- // full viewport region. Children pick their own scroll/padding strategy.
- <div className="absolute inset-0 flex flex-col">
- <AgentTabs projectSlug={projectSlug} agentSlug={agentSlug} />
- <div className="min-h-0 flex-1">{children}</div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/page.tsx
deleted file mode 100644
index 86279ac7..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/page.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { redirect } from "next/navigation";
-import { projectHref } from "@/lib/project-href";
-
-export default async function AgentIndexPage({
- params,
-}: {
- params: Promise<{ agent: string; project: string }>;
-}) {
- const { agent, project } = await params;
- redirect(projectHref(project, `/agents/${agent}/chat`));
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/settings/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/settings/page.tsx
deleted file mode 100644
index b4a50d50..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/settings/page.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { notFound } from "next/navigation";
-import { TEMPLATES } from "@/server/agent-templates";
-import { getProject } from "@/server/db/projects";
-import { resolveAgentBySlug, readAgentMeta } from "@/server/agent-meta";
-import { AgentDangerZone } from "@/components/agent-danger-zone";
-
-type Params = { agent: string; project: string };
-
-export default async function AgentSettingsPage({
- params,
-}: {
- params: Promise<Params>;
-}) {
- const { agent: agentSlug, project: projectSlug } = await params;
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
-
- const meta = readAgentMeta(resolved.agent_id);
- const role = resolved.template_key
- ? TEMPLATES.find((t) => t.key === resolved.template_key)
- : undefined;
-
- return (
- <div className="h-full overflow-y-auto">
- <div className="ns-app-narrow">
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">Settings</h1>
- <p className="ns-page-sub">
- <b>{resolved.name}</b>{" "}
- <span className="font-mono text-[12px]">· {resolved.agent_id}</span>
- </p>
- </div>
- </header>
-
- <section>
- <h2 className="ns-h2">
- <span>Identity</span>
- <span className="ns-h2-meta">Immutable for the life of the project</span>
- </h2>
- <div className="ns-card">
- <dl className="grid grid-cols-[auto_1fr] gap-x-6 gap-y-3 p-[18px]">
- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- Name
- </dt>
- <dd className="text-[13px] font-medium text-[hsl(var(--notfair-ink-2))]">
- {resolved.name}
- </dd>
-
- {role && (
- <>
- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- Role
- </dt>
- <dd className="text-[13px] text-[hsl(var(--notfair-ink-2))]">
- {role.display_name}
- </dd>
- </>
- )}
-
- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- URL slug
- </dt>
- <dd>
- <span className="ns-tag-mono">{resolved.slug}</span>
- </dd>
-
- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- Agent id
- </dt>
- <dd>
- <span className="ns-tag-mono">{resolved.agent_id}</span>
- </dd>
-
- {meta?.source_agent_id && (
- <>
- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- Cloned from
- </dt>
- <dd>
- <span className="ns-tag-mono">{meta.source_agent_id}</span>
- </dd>
- </>
- )}
-
- {meta?.created_at && (
- <>
- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- Created
- </dt>
- <dd className="text-[13px] tabular-nums text-[hsl(var(--notfair-ink-2))]">
- {new Date(meta.created_at).toLocaleString()}
- </dd>
- </>
- )}
- </dl>
- </div>
- </section>
-
- <section>
- <h2 className="ns-h2">
- <span>Danger zone</span>
- </h2>
- <AgentDangerZone
- agentId={resolved.agent_id}
- agentDisplayName={resolved.name}
- />
- </section>
- </div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/skills/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/skills/page.tsx
deleted file mode 100644
index fbe18d8f..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/skills/page.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import { getSkillStatus } from "@/server/agents/skills";
-import { SkillsList } from "@/components/skills-list";
-
-type Params = { agent: string; project: string };
-
-export default async function AgentSkillsPage({
- params,
-}: {
- params: Promise<Params>;
-}) {
- const { agent: agentSlug, project: projectSlug } = await params;
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
-
- const agentFullId = resolved.agent_id;
- let report: Awaited<ReturnType<typeof getSkillStatus>> | null = null;
- let error: string | null = null;
- try {
- report = await getSkillStatus(agentFullId);
- } catch (err) {
- error = err instanceof Error ? err.message : String(err);
- }
-
- const skills = report?.skills ?? [];
-
- return (
- <div className="h-full overflow-y-auto">
- <div className="ns-app-wide" style={{ maxWidth: 880 }}>
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">Skills</h1>
- <p className="ns-page-sub">
- Capabilities available to <b>{resolved.name}</b> from this
- workspace.
- </p>
- </div>
- </header>
-
- {error && (
- <div className="ns-card">
- <div className="ns-card-body">
- <p className="text-[14px] font-semibold text-destructive">
- Could not load skills.
- </p>
- <p className="mt-1 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- {error}
- </p>
- </div>
- </div>
- )}
-
- {!error && <SkillsList skills={skills} />}
- </div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
deleted file mode 100644
index b98e3831..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import { notFound } from "next/navigation";
-
-import { AgentTaskWorkspace } from "@/components/agent-task-workspace";
-import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/registry";
-import { getProject } from "@/server/db/projects";
-import { getMcpCatalog } from "@/server/mcp-catalog";
-import { resolveAgentBySlug } from "@/server/agent-meta";
-import { listApprovalsForTask } from "@/server/db/approvals";
-import { attentionByTaskForAgent } from "@/server/db/attention";
-import { listQuestionsForTask } from "@/server/db/questions";
-import { getTask, listTasksByAgent, setTaskThreadIfMissing } from "@/server/db/tasks";
-import { buildPendingSessionKey, findSessionBySessionId } from "@/server/sessions/view";
-import {
- readTranscriptTail,
- type TranscriptEvent,
-} from "@/server/sessions/transcript-tail";
-import {
- buildTaskKickoffMessage,
- generateTaskThreadId,
- getProjectPlatformFacts,
-} from "@/server/orchestration/task-kickoff";
-import type { Approval, Question, Task } from "@/types";
-
-type Props = {
- params: Promise<{ agent: string; project: string }>;
- searchParams: Promise<{ task?: string }>;
-};
-
-type SelectedBundle = {
- task: Task;
- threadId: string;
- sessionKey: string;
- initialEvents: TranscriptEvent[];
- initialByteOffset: number;
- /**
- * Every approval ever requested on this task, newest first. The chat view
- * renders these above the transcript so the user can act on a pending
- * approval without leaving the task. Resolved rows show too — they're
- * the audit trail for "what did I approve here?".
- */
- approvals: Approval[];
- /**
- * Every question ever raised on this task via `ask_user_question`,
- * newest first. The chat view renders the pending one inline so the
- * user can answer without leaving the task; resolved rows stay as the
- * audit trail.
- */
- questions: Question[];
- /**
- * Auto-kickoff payload for tasks that haven't started yet. The page
- * builds the full assignment brief server-side so the client can just
- * hand it to /api/chat — no business logic on the browser. `null` for
- * any task already past `proposed` (kickoff already happened or never
- * will).
- */
- kickoff: { taskId: string; message: string } | null;
-};
-
-export default async function AgentTasksPage({ params, searchParams }: Props) {
- const [{ agent: agentSlug, project: projectSlug }, { task: selectedTaskId }] =
- await Promise.all([params, searchParams]);
-
- const project = getProject(projectSlug);
- if (!project || project.archived_at) notFound();
-
- const resolved = await resolveAgentBySlug(project.slug, agentSlug);
- if (!resolved) notFound();
-
- const agentFullId = resolved.agent_id;
-
- // Load the selected task's brief + transcript bundle if `?task=` is set.
- // For tasks still in `proposed`, we hand the client a kickoff payload it
- // fires through /api/chat on mount — the SSE path streams gateway events
- // live (JSONL polling alone misses the run because OpenClaw's codex
- // mode flushes the transcript once per turn). For tasks already past
- // proposed (delegated via MCP, restarted via Start all, or finished),
- // this path is read-only.
- let selected: SelectedBundle | null = null;
- if (selectedTaskId) {
- selected = await loadSelectedBundle(project.slug, agentFullId, selectedTaskId);
- // Guard: drop selection if it's not on this agent (cross-agent links etc).
- if (selected && selected.task.agent_id !== agentFullId) selected = null;
- }
-
- const tasks = listTasksByAgent(agentFullId);
- const proposedCount = tasks.filter((t) => t.status === "proposed").length;
- const attentionByTask = attentionByTaskForAgent(project.slug, agentFullId);
- // Provider-fed model list for the composer's selector (codex reads its
- // account-scoped cache; claude uses its documented tier aliases).
- const modelOptions = await requireAdapter(
- project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,
- ).listModels();
- // Brand-favicon lookup table for MCP tool calls in the transcript.
- const mcpCatalog = getMcpCatalog(project.slug).map((m) => ({
- key: m.key,
- display_name: m.display_name,
- resource_url: m.resource_url,
- }));
-
- return (
- <AgentTaskWorkspace
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- agentFullId={agentFullId}
- agentDisplayName={resolved.name}
- tasks={tasks}
- selected={selected}
- proposedCount={proposedCount}
- attentionByTask={attentionByTask}
- mcpCatalog={mcpCatalog}
- modelOptions={modelOptions}
- />
- );
-}
-
-async function loadSelectedBundle(
- projectSlug: string,
- agentFullId: string,
- taskId: string,
-): Promise<SelectedBundle | null> {
- let task = getTask(taskId);
- if (!task) return null;
-
- // Lazily mint a per-task chat thread on first open. Stable forever after.
- if (!task.thread_id) {
- const updated = setTaskThreadIfMissing(task.id, generateTaskThreadId());
- if (updated) task = updated;
- }
- if (!task.thread_id) return null;
- const threadId = task.thread_id;
-
- // Resolve canonical sessionKey for /api/chat composer sends (when task
- // is done and user wants to keep chatting). The pending key is a safe
- // fallback for brand-new threads.
- const session = findSessionBySessionId(projectSlug, agentFullId, threadId);
- const sessionKey =
- session?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);
-
- const { events, byteOffset } = readTranscriptTail(projectSlug, agentFullId, threadId, 0);
- const approvals = listApprovalsForTask(task.id);
- const questions = listQuestionsForTask(task.id);
-
- // Only minted for `proposed` tasks. The client uses this to fire the
- // first turn via /api/chat (which streams gateway events live), and
- // /api/chat atomically claims the task on the server before forwarding
- // — so reloads / concurrent tabs can't double-fire the agent.
- const kickoff =
- task.status === "proposed"
- ? {
- taskId: task.id,
- message: buildTaskKickoffMessage(
- task,
- getProjectPlatformFacts(projectSlug),
- ),
- }
- : null;
-
- return {
- task,
- threadId,
- sessionKey,
- initialEvents: events,
- initialByteOffset: byteOffset,
- approvals,
- questions,
- kickoff,
- };
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
deleted file mode 100644
index 5df7bcf4..00000000
--- a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import Link from "next/link";
-import { Bot, Check, Clock, MessageSquare } from "lucide-react";
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { TEMPLATES } from "@/server/agent-templates";
-import { listProjectAgents } from "@/server/agent-meta";
-import { listCronsForProject } from "@/server/scheduler/display";
-import { reprovisionAgentsAction } from "@/server/actions/projects";
-import { ReprovisionButton } from "@/components/reprovision-button";
-import { AgentAvatar } from "@/components/agent-avatar";
-import { projectHref } from "@/lib/project-href";
-
-export default async function AgentsPage({
- params,
-}: {
- params: Promise<{ project: string }>;
-}) {
- const { project: slug } = await params;
- const project = getProject(slug);
- if (!project || project.archived_at) notFound();
-
- const cronByAgent = new Map<string, number>();
- try {
- const view = await listCronsForProject(project.slug);
- for (const g of view.groups) cronByAgent.set(g.agent, g.crons.length);
- } catch {}
-
- const projectAgents = await listProjectAgents(project.slug);
- const reprovision = reprovisionAgentsAction.bind(null, project.slug);
-
- return (
- <div className="ns-app-wide" style={{ maxWidth: 880 }}>
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">Agents</h1>
- <p className="ns-page-sub">
- <b>{projectAgents.length}</b> agent
- {projectAgents.length === 1 ? "" : "s"} · running on{" "}
- <b>
- {project.harness_adapter === "codex-local" ? "Codex" : "Claude Code"}
- </b>
- </p>
- </div>
- <div className="ns-page-actions">
- <ReprovisionButton action={reprovision} />
- </div>
- </header>
-
- <div className="grid gap-4">
- {projectAgents.map((agent) => {
- const role = agent.template_key
- ? TEMPLATES.find((t) => t.key === agent.template_key)
- : undefined;
- const crons = cronByAgent.get(agent.agent_id) ?? 0;
- return (
- <div key={agent.agent_id} className="ns-card">
- <div className="flex items-start gap-4 p-[18px]">
- {agent.template_key ? (
- <AgentAvatar role={agent.template_key} size={44} />
- ) : (
- <span className="ns-glyph" aria-hidden>
- <Bot className="size-[18px] text-[hsl(var(--notfair-ink-2))]" />
- </span>
- )}
- <div className="min-w-0 flex-1">
- <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
- <h2 className="m-0 text-[15.5px] font-semibold tracking-tight text-[hsl(var(--notfair-ink))]">
- {agent.name}
- </h2>
- {role && <span className="ns-tag">{role.display_name}</span>}
- <span className="ns-tag-mono">{agent.agent_id}</span>
- </div>
- <p className="mt-1 text-[13px] leading-snug text-[hsl(var(--notfair-ink-3))]">
- {role?.description ?? agent.description ?? "Custom agent."}
- </p>
- </div>
- <div className="flex shrink-0 items-center gap-2">
- {crons > 0 && (
- <Link
- href={projectHref(slug, "/crons")}
- className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[12px] text-[hsl(var(--notfair-ink-4))] transition-colors hover:bg-[hsl(var(--notfair-surface-2))] hover:text-[hsl(var(--notfair-ink-2))]"
- >
- <Clock className="size-3" />
- {crons}
- </Link>
- )}
- <Link
- href={projectHref(slug, `/agents/${agent.slug}/chat`)}
- className="ns-btn ns-btn-primary ns-btn-sm"
- >
- <MessageSquare className="size-3.5" />
- Chat
- </Link>
- </div>
- </div>
- {role && (
- <div className="border-t border-border/60 px-[18px] py-3">
- <ul className="grid grid-cols-1 gap-1.5 text-[13px] text-[hsl(var(--notfair-ink-3))] md:grid-cols-2">
- {role.capabilities.map((c) => (
- <li key={c} className="flex items-start gap-2">
- <Check className="mt-0.5 size-3.5 shrink-0 text-[hsl(var(--notfair-accent))]" />
- <span>{c}</span>
- </li>
- ))}
- </ul>
- </div>
- )}
- </div>
- );
- })}
- </div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/approvals/page.tsx b/notfair-cmo/src/app/(app)/[project]/approvals/page.tsx
deleted file mode 100644
index fccb4505..00000000
--- a/notfair-cmo/src/app/(app)/[project]/approvals/page.tsx
+++ /dev/null
@@ -1,172 +0,0 @@
-import Link from "next/link";
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import {
- listActionableApprovals,
- listPolicies,
- listResolvedApprovals,
-} from "@/server/db/approvals";
-import { ApprovalCard } from "@/components/approval-card";
-import { PolicyList } from "@/components/policy-list";
-import { projectHref } from "@/lib/project-href";
-
-type TabKey = "pending" | "resolved" | "policies";
-
-function parseTab(raw: string | string[] | undefined): TabKey {
- const value = Array.isArray(raw) ? raw[0] : raw;
- if (value === "resolved" || value === "policies") return value;
- return "pending";
-}
-
-export default async function ApprovalsPage({
- params,
- searchParams,
-}: {
- params: Promise<{ project: string }>;
- searchParams: Promise<{ tab?: string | string[] }>;
-}) {
- const { project: slug } = await params;
- const { tab } = await searchParams;
- const activeTab = parseTab(tab);
-
- const project = getProject(slug);
- if (!project || project.archived_at) notFound();
-
- const actionable = listActionableApprovals(project.slug);
- const resolved =
- activeTab === "resolved" ? listResolvedApprovals(project.slug, 50) : [];
- const policies = activeTab === "policies" ? listPolicies(project.slug) : [];
-
- const counts = {
- pending: actionable.length,
- resolved: resolved.length,
- policies: policies.length,
- };
-
- return (
- <div className="ns-app-narrow">
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">Approvals</h1>
- <p className="ns-page-sub">
- Your inbox for agent decisions. Anything not already covered by an
- <b> auto-approve rule</b> lands here for a quick yes or no.
- </p>
- </div>
- </header>
-
- <nav
- className="ns-tabs mb-6"
- role="tablist"
- aria-label="Approval tabs"
- >
- <TabLink
- slug={slug}
- tab="pending"
- active={activeTab}
- label="Inbox"
- count={counts.pending}
- />
- <TabLink
- slug={slug}
- tab="resolved"
- active={activeTab}
- label="Resolved"
- />
- <TabLink
- slug={slug}
- tab="policies"
- active={activeTab}
- label="Auto-approve rules"
- />
- </nav>
-
- {activeTab === "pending" &&
- (actionable.length === 0 ? (
- <div className="ns-empty">
- <p className="ns-empty-title">All caught up.</p>
- <p className="ns-empty-sub">
- When an agent needs your go-ahead, it&rsquo;ll show up here.
- Manage rules in{" "}
- <Link
- href={`${projectHref(slug, "/approvals")}?tab=policies`}
- className="ns-link"
- >
- Auto-approve rules
- </Link>
- .
- </p>
- </div>
- ) : (
- <div className="space-y-3">
- {actionable.map((a) => (
- <ApprovalCard key={a.id} approval={a} />
- ))}
- </div>
- ))}
-
- {activeTab === "resolved" &&
- (resolved.length === 0 ? (
- <div className="ns-empty">
- <p className="ns-empty-title">No resolved approvals yet.</p>
- <p className="ns-empty-sub">
- Decisions show up here after they&rsquo;re approved, rejected, or
- auto-handled.
- </p>
- </div>
- ) : (
- <div className="space-y-3">
- {resolved.map((a) => (
- <ApprovalCard key={a.id} approval={a} />
- ))}
- </div>
- ))}
-
- {activeTab === "policies" && (
- <PolicyList projectSlug={project.slug} policies={policies} />
- )}
- </div>
- );
-}
-
-function TabLink({
- slug,
- tab,
- active,
- label,
- count,
-}: {
- slug: string;
- tab: TabKey;
- active: TabKey;
- label: string;
- count?: number;
-}) {
- const isActive = active === tab;
- const href =
- tab === "pending"
- ? projectHref(slug, "/approvals")
- : `${projectHref(slug, "/approvals")}?tab=${tab}`;
- return (
- <Link
- href={href}
- role="tab"
- aria-selected={isActive}
- className="ns-tab"
- data-active={isActive}
- >
- {label}
- {count !== undefined && count > 0 && (
- <span
- className={`ml-1 inline-flex h-[16px] min-w-[16px] items-center justify-center rounded-full px-1 text-[10px] font-semibold tabular-nums leading-none ${
- isActive
- ? "bg-card text-foreground shadow-sm"
- : "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))]"
- }`}
- >
- {count}
- </span>
- )}
- </Link>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/crons/page.tsx b/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
deleted file mode 100644
index 2cb31716..00000000
--- a/notfair-cmo/src/app/(app)/[project]/crons/page.tsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import { notFound } from "next/navigation";
-import { getProject } from "@/server/db/projects";
-import { listCronsForProject } from "@/server/scheduler/display";
-import {
- annotateOccurrencesWithRunStatus,
- expandSchedule,
-} from "@/server/scheduler/display";
-import { ScheduleCronDialog } from "@/components/schedule-cron-dialog";
-import {
- CronCalendar,
- type CalendarCron,
- type CalendarOccurrence,
-} from "@/components/cron-calendar";
-import type { ScheduleInput } from "@/server/actions/cron-runs";
-
-function scheduleForCalendar(s: unknown): ScheduleInput | null {
- if (!s || typeof s !== "object") return null;
- const obj = s as { kind?: string; expr?: unknown; tz?: unknown };
- if (obj.kind === "cron" && typeof obj.expr === "string") {
- return { kind: "cron", expr: obj.expr, ...(typeof obj.tz === "string" ? { tz: obj.tz } : {}) };
- }
- return null;
-}
-
-const NUM_DAYS = 14;
-
-export default async function CronsPage({
- params,
-}: {
- params: Promise<{ project: string }>;
-}) {
- const { project: slug } = await params;
- const project = getProject(slug);
- if (!project || project.archived_at) notFound();
-
- let error: string | null = null;
- let view: Awaited<ReturnType<typeof listCronsForProject>>;
- try {
- view = await listCronsForProject(project.slug);
- } catch (err) {
- view = { project_slug: project.slug, groups: [] };
- error = err instanceof Error ? err.message : String(err);
- }
-
- const allCrons = view.groups.flatMap((g) => g.crons);
- const agentSlugs = view.groups.map((g) => g.agent);
-
- // Start the calendar on Monday of the current week, not on today.
- const start = new Date();
- start.setHours(0, 0, 0, 0);
- start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
- const startOfFirstDay = start.getTime();
- const dayMs = 24 * 60 * 60 * 1000;
- const until = startOfFirstDay + NUM_DAYS * dayMs;
-
- const occurrences: CalendarOccurrence[] = [];
- const schedulesByCronId = new Map<string, ReturnType<typeof scheduleForCalendar>>();
- for (const cron of allCrons) {
- const occs = expandSchedule(
- cron.id,
- cron.schedule_raw,
- // Never expand before the cron existed — the calendar window can reach
- // back to Monday, which would otherwise render phantom past occurrences.
- { from: Math.max(startOfFirstDay, cron.created_at_ms ?? startOfFirstDay), until },
- {
- name: cron.name,
- short_name: cron.short_name,
- agent_id: cron.agent_id,
- agent_slug: cron.agent_slug,
- schedule_text: cron.schedule_text,
- },
- );
- for (const o of occs) occurrences.push({ ...o, cron_disabled: cron.disabled });
- schedulesByCronId.set(cron.id, scheduleForCalendar(cron.schedule_raw));
- }
- annotateOccurrencesWithRunStatus(
- occurrences,
- new Map([...schedulesByCronId.entries()].map(([k, v]) => [k, v ?? undefined])),
- );
-
- const cronsById: Record<string, CalendarCron> = {};
- for (const cron of allCrons) {
- cronsById[cron.id] = {
- id: cron.id,
- short_name: cron.short_name,
- full_name: cron.name,
- agent_id: cron.agent_id,
- agent_slug: cron.agent_slug,
- schedule_text: cron.schedule_text,
- disabled: cron.disabled,
- status_text: cron.status_text,
- message: cron.message,
- description: cron.description,
- last_run_at_ms: cron.last_run_at_ms,
- last_status: cron.last_status,
- last_error: cron.last_error,
- schedule_raw: scheduleForCalendar(cron.schedule_raw),
- };
- }
-
- const totalActive = allCrons.filter((c) => !c.disabled).length;
- const totalDisabled = allCrons.length - totalActive;
-
- return (
- <div className="ns-app-wide">
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">Crons</h1>
- <p className="ns-page-sub">
- <b>{totalActive}</b> active
- {totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""} ·
- recurring work scheduled across your agents.
- </p>
- </div>
- <div className="ns-page-actions">
- <ScheduleCronDialog projectSlug={project.slug} />
- </div>
- </header>
-
- {error && (
- <div className="ns-card">
- <div className="ns-card-body">
- <p className="text-[14px] font-semibold text-destructive">
- Could not load crons.
- </p>
- <p className="mt-1 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- {error}
- </p>
- <p className="mt-2 text-[12px] text-[hsl(var(--notfair-ink-4))]">
- Run{" "}
- <code className="rounded bg-[hsl(var(--notfair-surface-2))] px-1.5 py-px font-mono">
- notfair-cmo doctor
- </code>{" "}
- for help.
- </p>
- </div>
- </div>
- )}
-
- {!error && allCrons.length === 0 && (
- <div className="ns-empty">
- <p className="ns-empty-title">No scheduled work yet.</p>
- <p className="ns-empty-sub">
- Schedule a recurring job for one of this project&rsquo;s agents.
- </p>
- <div className="ns-empty-action">
- <ScheduleCronDialog projectSlug={project.slug} />
- </div>
- </div>
- )}
-
- {!error && allCrons.length > 0 && (
- <CronCalendar
- startOfFirstDay={startOfFirstDay}
- numDays={NUM_DAYS}
- occurrences={occurrences}
- cronsById={cronsById}
- agentSlugs={agentSlugs}
- />
- )}
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/page.tsx b/notfair-cmo/src/app/(app)/[project]/page.tsx
deleted file mode 100644
index 70f1b63c..00000000
--- a/notfair-cmo/src/app/(app)/[project]/page.tsx
+++ /dev/null
@@ -1,278 +0,0 @@
-import Link from "next/link";
-import { notFound } from "next/navigation";
-import { Bot, MessageSquare } from "lucide-react";
-import { getProject } from "@/server/db/projects";
-import { listPendingApprovals } from "@/server/db/approvals";
-import { listTasks } from "@/server/db/tasks";
-import { listAgentActions } from "@/server/db/agent-actions";
-import { TEMPLATES } from "@/server/agent-templates";
-import { listProjectAgents } from "@/server/agent-meta";
-import { colorForRole } from "@/lib/agent-colors";
-import { cn } from "@/lib/utils";
-import { projectHref } from "@/lib/project-href";
-import { AgentAvatar } from "@/components/agent-avatar";
-
-function timeAgo(iso: string) {
- const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
- if (seconds < 60) return `${Math.floor(seconds)}s ago`;
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
- return `${Math.floor(seconds / 86400)}d ago`;
-}
-
-export default async function ProjectHomePage({
- params,
-}: {
- params: Promise<{ project: string }>;
-}) {
- const { project: slug } = await params;
- const project = getProject(slug);
- if (!project || project.archived_at) notFound();
-
- const pending = listPendingApprovals(project.slug);
- const tasks = listTasks(project.slug);
- const recent = listAgentActions(project.slug, 8);
- const projectAgents = await listProjectAgents(project.slug);
- const cmoAgent = projectAgents.find((a) => a.template_key === "cmo");
- const cmoChatHref = cmoAgent
- ? projectHref(slug, `/agents/${cmoAgent.slug}/chat`)
- : projectHref(slug, "");
-
- const running = tasks.filter((t) => t.status === "working").length;
- const nothingHappened = tasks.length === 0 && recent.length === 0;
-
- return (
- <div className="ns-app-wide">
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">{project.display_name}</h1>
- <p className="ns-page-sub">
- Your local AI marketing team. Hand a goal to the CMO and they&rsquo;ll
- delegate.
- </p>
- </div>
- <div className="ns-page-actions">
- <Link href={cmoChatHref} className="ns-btn ns-btn-primary">
- <MessageSquare className="size-4" />
- Chat with CMO
- </Link>
- </div>
- </header>
-
- {/* KPI strip. Spend tracking lives elsewhere now; the home tiles
- surface only the counters the user has a direct action on. */}
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- <KpiTile
- label="Active tasks"
- value={String(running)}
- hint={`${tasks.length} total`}
- href={projectHref(slug, "/tasks")}
- />
- <KpiTile
- label="Pending approvals"
- value={String(pending.length)}
- hint={pending.length === 0 ? "all caught up" : "review →"}
- href={projectHref(slug, "/approvals")}
- accent={pending.length > 0}
- />
- <KpiTile
- label="Crons"
- value="·"
- hint="scheduled work"
- href={projectHref(slug, "/crons")}
- />
- </div>
-
- {/* Two-up: agents on the left, recent activity on the right. */}
- <div className="mt-8 grid gap-6 lg:grid-cols-3">
- <section className="lg:col-span-2">
- <div className="ns-h2">
- <span>Your agents</span>
- <Link href={projectHref(slug, "/agents")} className="ns-link ns-h2-meta">
- View all ›
- </Link>
- </div>
- <ol className="ns-group">
- {projectAgents.map((agent) => {
- const role = agent.template_key
- ? TEMPLATES.find((t) => t.key === agent.template_key)
- : undefined;
- const rolePalette = agent.template_key
- ? colorForRole(agent.template_key)
- : null;
- return (
- <li key={agent.agent_id}>
- <Link
- href={projectHref(slug, `/agents/${agent.slug}/chat`)}
- className="ns-row-button"
- >
- {agent.template_key ? (
- <AgentAvatar role={agent.template_key} size={40} />
- ) : (
- <span className="ns-glyph" aria-hidden>
- <Bot className="size-[18px] text-[hsl(var(--notfair-ink-2))]" />
- </span>
- )}
- <span className="ns-row-body">
- <span className="ns-row-title-row">
- <span className="ns-row-title">{agent.name}</span>
- {role && (
- <span
- className={cn(
- "inline-flex items-center rounded-[5px] border px-1.5 py-[2px] text-[10.5px] font-medium uppercase tracking-wide leading-none",
- rolePalette?.chip ?? "ns-tag",
- )}
- >
- {role.display_name}
- </span>
- )}
- </span>
- <span className="ns-row-desc block">
- {role?.description ?? agent.description ?? "Custom agent."}
- </span>
- </span>
- <span className="ns-row-meta">
- <span className="chev" aria-hidden>
- ›
- </span>
- </span>
- </Link>
- </li>
- );
- })}
- </ol>
- </section>
-
- <section>
- <div className="ns-h2">
- <span>Recent activity</span>
- <Link
- href={projectHref(slug, "/activity")}
- className="ns-link ns-h2-meta"
- >
- All ›
- </Link>
- </div>
- {recent.length === 0 ? (
- <div className="ns-empty">
- <p className="ns-empty-title">Nothing yet.</p>
- <p className="ns-empty-sub">
- Autonomous decisions and scheduled work will show up here.
- </p>
- </div>
- ) : (
- <ol className="ns-group">
- {recent.map((a) => (
- <li key={a.id} className="ns-row flex-col items-start gap-1">
- <div className="flex w-full items-baseline justify-between gap-2">
- <span className="ns-tag-mono">{a.action_type}</span>
- <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
- {timeAgo(a.occurred_at)}
- </span>
- </div>
- <p className="m-0 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-3))] line-clamp-2">
- {a.summary}
- </p>
- </li>
- ))}
- </ol>
- )}
- </section>
- </div>
-
- {nothingHappened && (
- <section className="mt-10">
- <div className="ns-h2">
- <span>Getting started</span>
- </div>
- <ol className="ns-group">
- <GettingStartedStep
- n="1"
- title="Connect your data sources"
- desc="Wire up Google Ads, Meta Ads, or Search Console so agents can do real work."
- href={projectHref(slug, "/connections")}
- />
- <GettingStartedStep
- n="2"
- title="Chat with your CMO"
- desc="Brief them on goals, audience, and constraints. They&rsquo;ll plan from there."
- href={cmoChatHref}
- />
- <GettingStartedStep
- n="3"
- title="Schedule recurring work"
- desc="Daily bid review, weekly SEO audit — whatever cadence you want."
- href={projectHref(slug, "/crons")}
- />
- </ol>
- </section>
- )}
- </div>
- );
-}
-
-function KpiTile({
- label,
- value,
- hint,
- href,
- accent,
-}: {
- label: string;
- value: string;
- hint: string;
- href?: string;
- accent?: boolean;
-}) {
- const body = (
- <>
- <p className="ns-kpi-label">{label}</p>
- <p
- className={`ns-kpi-value ${
- accent ? "text-[hsl(var(--notfair-accent))]" : ""
- }`}
- >
- {value}
- </p>
- <p className="ns-kpi-hint">{hint}</p>
- </>
- );
- if (href)
- return (
- <Link href={href} className="ns-kpi">
- {body}
- </Link>
- );
- return <div className="ns-kpi">{body}</div>;
-}
-
-function GettingStartedStep({
- n,
- title,
- desc,
- href,
-}: {
- n: string;
- title: string;
- desc: string;
- href: string;
-}) {
- return (
- <li>
- <Link href={href} className="ns-row-button">
- <span className="ns-glyph ns-glyph-accent" aria-hidden>
- {n}
- </span>
- <span className="ns-row-body">
- <span className="ns-row-title">{title}</span>
- <span className="ns-row-desc block">{desc}</span>
- </span>
- <span className="ns-row-meta">
- <span className="chev" aria-hidden>
- ›
- </span>
- </span>
- </Link>
- </li>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/tasks/[id]/page.tsx b/notfair-cmo/src/app/(app)/[project]/tasks/[id]/page.tsx
deleted file mode 100644
index ce58ed1f..00000000
--- a/notfair-cmo/src/app/(app)/[project]/tasks/[id]/page.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { notFound, redirect } from "next/navigation";
-
-import { readAgentMeta } from "@/server/agent-meta";
-import { getProject } from "@/server/db/projects";
-import { getTask } from "@/server/db/tasks";
-import {
- TEMPLATES,
- agentUrlSlug,
- type AgentTemplateKey,
-} from "@/server/agent-templates";
-import { projectHref } from "@/lib/project-href";
-
-/**
- * Deep-link destination for task IDs. The canonical view lives in the agent
- * workspace, so we resolve the task's owning agent and redirect there with
- * the task pre-selected.
- */
-export default async function TaskDetailPage({
- params,
-}: {
- params: Promise<{ id: string; project: string }>;
-}) {
- const { id, project: slug } = await params;
- const project = getProject(slug);
- if (!project || project.archived_at) notFound();
-
- const task = getTask(id);
- if (!task || task.project_slug !== project.slug) notFound();
-
- // Resolve the assignee's URL slug. For template agents the slug is
- // `<role>-<personal-name>`; for clones we use the slug stored on the
- // meta sidecar.
- const meta = readAgentMeta(task.agent_id);
- let agentSlug: string;
- if (meta?.template_key) {
- const template = TEMPLATES.find((t) => t.key === meta.template_key);
- const role = (meta.template_key as AgentTemplateKey) ?? "google_ads";
- const name = meta.name ?? template?.default_name ?? "agent";
- agentSlug = agentUrlSlug(role, name);
- } else if (meta?.slug) {
- agentSlug = meta.slug;
- } else {
- // No meta on disk yet — fall back to the agent_id's tail.
- agentSlug = task.agent_id.replace(`${slug}-`, "");
- }
-
- // Use the human-readable display_id in the canonical URL so the path
- // someone bookmarks reads "?task=demo7-3" not a UUID. getTask in the
- // workspace accepts either form.
- redirect(
- projectHref(slug, `/agents/${agentSlug}/tasks?task=${task.display_id}`),
- );
-}
diff --git a/notfair-cmo/src/app/(app)/[project]/tasks/page.tsx b/notfair-cmo/src/app/(app)/[project]/tasks/page.tsx
deleted file mode 100644
index fc13ed81..00000000
--- a/notfair-cmo/src/app/(app)/[project]/tasks/page.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { notFound } from "next/navigation";
-
-import { TasksBoard } from "@/components/tasks-board";
-import { listProjectAgents } from "@/server/agent-meta";
-import { getProject } from "@/server/db/projects";
-import { listTasks } from "@/server/db/tasks";
-
-export default async function TasksPage({
- params,
-}: {
- params: Promise<{ project: string }>;
-}) {
- const { project: slug } = await params;
- const project = getProject(slug);
- if (!project || project.archived_at) notFound();
-
- const [tasks, agents] = await Promise.all([
- Promise.resolve(listTasks(project.slug)),
- listProjectAgents(project.slug),
- ]);
-
- return (
- <div className="ns-app-wide">
- <header className="ns-page-head">
- <div className="ns-page-head-stack">
- <h1 className="ns-page-title">Tasks</h1>
- <p className="ns-page-sub">
- <b>{tasks.length}</b> {tasks.length === 1 ? "task" : "tasks"} ·
- CMO and specialists create work here as they delegate.
- </p>
- </div>
- </header>
-
- <TasksBoard projectSlug={project.slug} tasks={tasks} agents={agents} />
- </div>
- );
-}
diff --git a/notfair-cmo/src/app/(app)/layout.tsx b/notfair-cmo/src/app/(app)/layout.tsx
deleted file mode 100644
index d5cefe10..00000000
--- a/notfair-cmo/src/app/(app)/layout.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
-import { AppSidebar } from "@/components/app-sidebar";
-import { ClientMountGate } from "@/components/client-mount-gate";
-import { LiveCountsProvider } from "@/components/live-counts-context";
-import { getActiveProject } from "@/server/active-project";
-import { actionableApprovalCount } from "@/server/db/approvals";
-import { attentionByAgent } from "@/server/db/attention";
-import { inFlightCountsByAgent } from "@/server/db/tasks";
-
-export default async function AppLayout({ children }: { children: React.ReactNode }) {
- // Server-side initial values for the live-counts context. After the
- // client mounts, the context polls /api/in-flight-counts and updates
- // badges in place — no router.refresh, no sidebar reconciliation.
- const active = await getActiveProject();
- const initialAgents: Record<string, number> = {};
- if (active) {
- for (const [agentId, count] of inFlightCountsByAgent(active.slug)) {
- initialAgents[agentId] = count;
- }
- }
- const initialApprovals = active ? actionableApprovalCount(active.slug) : 0;
- const initialAttention = active ? attentionByAgent(active.slug) : {};
-
- return (
- <ClientMountGate
- fallback={
- <div className="min-h-screen bg-background" suppressHydrationWarning>
- {/* Empty shell during hydration — children mount client-side */}
- </div>
- }
- >
- <LiveCountsProvider
- initial={{
- project: active?.slug ?? null,
- agents: initialAgents,
- approvals: initialApprovals,
- attention: initialAttention,
- }}
- >
- <SidebarProvider>
- <AppSidebar />
- <SidebarInset>
- <a href="#main-content" className="sr-only focus:not-sr-only">
- Skip to content
- </a>
- <main id="main-content" className="relative flex-1">
- {children}
- </main>
- </SidebarInset>
- </SidebarProvider>
- </LiveCountsProvider>
- </ClientMountGate>
- );
-}
diff --git a/notfair-cmo/src/app/api/browser/launch/route.test.ts b/notfair-cmo/src/app/api/browser/launch/route.test.ts
deleted file mode 100644
index ac539780..00000000
--- a/notfair-cmo/src/app/api/browser/launch/route.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-
-vi.mock("@/server/browser/session", () => ({
- getOrLaunchBrowser: vi.fn(async () => ({})),
- getSessionStatus: vi.fn(() => ({
- projectSlug: "acme",
- running: true,
- cdpPort: 19042,
- userDataDir: "/tmp/profile",
- launchedAt: 1_000,
- uptimeMs: 5_000,
- idleTimeoutMs: 300_000,
- })),
-}));
-
-vi.mock("@/server/browser/tabs", () => ({
- openTab: vi.fn(async (_slug: string, opts: { label?: string; url?: string }) => ({
- id: opts.label ?? "t1",
- label: opts.label ?? "t1",
- url: opts.url ?? "about:blank",
- title: "",
- })),
-}));
-
-import { POST } from "./route";
-import * as session from "@/server/browser/session";
-import * as tabs from "@/server/browser/tabs";
-
-function makeReq(body: unknown): Request {
- return new Request("http://localhost/api/browser/launch", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- });
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe("POST /api/browser/launch", () => {
- it("400s when project_slug is missing", async () => {
- const res = await POST(makeReq({}));
- expect(res.status).toBe(400);
- });
-
- it("launches the browser headed by default and returns status", async () => {
- const res = await POST(makeReq({ project_slug: "acme" }));
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.status.running).toBe(true);
- expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("acme", { headless: false });
- });
-
- it("honors headless=true when provided", async () => {
- await POST(makeReq({ project_slug: "acme", headless: true }));
- expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("acme", { headless: true });
- });
-
- it("opens a signin tab when signin_url is provided", async () => {
- const res = await POST(
- makeReq({ project_slug: "acme", signin_url: "https://accounts.google.com" }),
- );
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.signin_tab).toEqual({ id: "signin", url: "https://accounts.google.com" });
- expect(tabs.openTab).toHaveBeenCalledWith("acme", {
- label: "signin",
- url: "https://accounts.google.com",
- });
- });
-
- it("500s with the error message when launch fails", async () => {
- (session.getOrLaunchBrowser as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
- new Error("Chrome not found"),
- );
- const res = await POST(makeReq({ project_slug: "acme" }));
- expect(res.status).toBe(500);
- const body = await res.json();
- expect(body.error).toBe("Chrome not found");
- });
-});
diff --git a/notfair-cmo/src/app/api/browser/shutdown/route.test.ts b/notfair-cmo/src/app/api/browser/shutdown/route.test.ts
deleted file mode 100644
index e849ff03..00000000
--- a/notfair-cmo/src/app/api/browser/shutdown/route.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-
-vi.mock("@/server/browser/session", () => ({
- stopBrowser: vi.fn(async () => {}),
-}));
-
-import { POST } from "./route";
-import * as session from "@/server/browser/session";
-
-function makeReq(body: unknown): Request {
- return new Request("http://localhost/api/browser/shutdown", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- });
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe("POST /api/browser/shutdown", () => {
- it("400s when project_slug is missing", async () => {
- const res = await POST(makeReq({}));
- expect(res.status).toBe(400);
- });
-
- it("calls stopBrowser and returns ok", async () => {
- const res = await POST(makeReq({ project_slug: "acme" }));
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.ok).toBe(true);
- expect(session.stopBrowser).toHaveBeenCalledWith("acme");
- });
-
- it("500s with the error message when stopBrowser throws", async () => {
- (session.stopBrowser as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
- new Error("kill failed"),
- );
- const res = await POST(makeReq({ project_slug: "acme" }));
- expect(res.status).toBe(500);
- const body = await res.json();
- expect(body.error).toBe("kill failed");
- });
-});
diff --git a/notfair-cmo/src/app/api/browser/status/route.test.ts b/notfair-cmo/src/app/api/browser/status/route.test.ts
deleted file mode 100644
index 161a9393..00000000
--- a/notfair-cmo/src/app/api/browser/status/route.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-
-vi.mock("@/server/browser/session", () => ({
- getSessionStatus: vi.fn(() => ({
- projectSlug: "acme",
- running: true,
- cdpPort: 19042,
- userDataDir: "/tmp/profile",
- launchedAt: 1_000,
- uptimeMs: 5_000,
- idleMs: 2_000,
- idleTimeoutMs: 300_000,
- })),
-}));
-
-vi.mock("@/server/browser/tabs", () => ({
- listTabs: vi.fn(async () => [
- { id: "greg", label: "greg", url: "https://example.com", title: "Example" },
- ]),
-}));
-
-import { GET } from "./route";
-import * as session from "@/server/browser/session";
-import * as tabs from "@/server/browser/tabs";
-
-function makeReq(qs: string): Request {
- return new Request(`http://localhost/api/browser/status${qs}`);
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe("GET /api/browser/status", () => {
- it("400s when project_slug is missing", async () => {
- const res = await GET(makeReq(""));
- expect(res.status).toBe(400);
- });
-
- it("returns status + tabs when running", async () => {
- const res = await GET(makeReq("?project_slug=acme"));
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.status.running).toBe(true);
- expect(body.tabs).toHaveLength(1);
- expect(body.tabs[0].id).toBe("greg");
- });
-
- it("returns status without tabs when not running", async () => {
- (session.getSessionStatus as ReturnType<typeof vi.fn>).mockReturnValueOnce({
- projectSlug: "acme",
- running: false,
- cdpPort: 19042,
- userDataDir: "/tmp/profile",
- idleTimeoutMs: 300_000,
- });
- const res = await GET(makeReq("?project_slug=acme"));
- const body = await res.json();
- expect(body.status.running).toBe(false);
- expect(body.tabs).toEqual([]);
- expect(tabs.listTabs).not.toHaveBeenCalled();
- });
-
- it("returns empty tab list when listTabs throws (doesn't fail the whole probe)", async () => {
- (tabs.listTabs as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("boom"));
- const res = await GET(makeReq("?project_slug=acme"));
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.tabs).toEqual([]);
- });
-});
diff --git a/notfair-cmo/src/app/api/in-flight-counts/route.ts b/notfair-cmo/src/app/api/in-flight-counts/route.ts
deleted file mode 100644
index 1cc3fe80..00000000
--- a/notfair-cmo/src/app/api/in-flight-counts/route.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { NextResponse } from "next/server";
-
-import { getActiveProject } from "@/server/active-project";
-import { actionableApprovalCount } from "@/server/db/approvals";
-import { attentionByAgent } from "@/server/db/attention";
-import { inFlightCountsByAgent } from "@/server/db/tasks";
-
-export const dynamic = "force-dynamic";
-export const runtime = "nodejs";
-
-/**
- * Lightweight liveness probe used by LiveCountsProvider to keep sidebar
- * badge counts fresh client-side. Replaces the previous router.refresh
- * approach — only the badge text nodes update, the server-rendered
- * sidebar tree never reconciles, so there's no visual flicker.
- */
-export async function GET() {
- const project = await getActiveProject();
- if (!project) {
- return NextResponse.json({
- project: null,
- agents: {},
- approvals: 0,
- attention: {},
- });
- }
- const countsMap = inFlightCountsByAgent(project.slug);
- const agents: Record<string, number> = {};
- for (const [agentId, count] of countsMap) agents[agentId] = count;
- const approvals = actionableApprovalCount(project.slug);
- const attention = attentionByAgent(project.slug);
- return NextResponse.json({ project: project.slug, agents, approvals, attention });
-}
diff --git a/notfair-cmo/src/app/api/mcp/orchestration/route.test.ts b/notfair-cmo/src/app/api/mcp/orchestration/route.test.ts
deleted file mode 100644
index ccc356b7..00000000
--- a/notfair-cmo/src/app/api/mcp/orchestration/route.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-
-const verifyMock = vi.fn();
-vi.mock("@/server/mcp-server/secret", () => ({
- verifyMcpServerSecret: (...a: unknown[]) => verifyMock(...a),
-}));
-
-const handleJsonRpcMock = vi.fn();
-vi.mock("@/server/mcp-server/jsonrpc", () => ({
- handleJsonRpc: (...a: unknown[]) => handleJsonRpcMock(...a),
-}));
-
-import { GET, POST } from "./route";
-
-function makePost(headers: Record<string, string>, body: unknown): Request {
- return new Request("http://localhost/api/mcp/orchestration", {
- method: "POST",
- headers,
- body: typeof body === "string" ? body : JSON.stringify(body),
- });
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe("POST /api/mcp/orchestration — auth", () => {
- it("401 when Authorization is missing", async () => {
- verifyMock.mockReturnValue(false);
- const res = await POST(makePost({}, { jsonrpc: "2.0", id: 1, method: "ping" }));
- expect(res.status).toBe(401);
- });
-
- it("401 when bearer doesn't verify", async () => {
- verifyMock.mockReturnValue(false);
- const res = await POST(
- makePost(
- { Authorization: "Bearer wrong" },
- { jsonrpc: "2.0", id: 1, method: "ping" },
- ),
- );
- expect(res.status).toBe(401);
- expect(verifyMock).toHaveBeenCalledWith("wrong");
- });
-
- it("passes verified bearer through to dispatcher", async () => {
- verifyMock.mockReturnValue(true);
- handleJsonRpcMock.mockResolvedValue({
- jsonrpc: "2.0",
- id: 1,
- result: { pong: true },
- });
- const res = await POST(
- makePost(
- { Authorization: "Bearer ok", "Content-Type": "application/json" },
- { jsonrpc: "2.0", id: 1, method: "ping" },
- ),
- );
- expect(res.status).toBe(200);
- const body = (await res.json()) as { result: { pong: boolean } };
- expect(body.result.pong).toBe(true);
- });
-});
-
-describe("POST /api/mcp/orchestration — body validation", () => {
- beforeEach(() => {
- verifyMock.mockReturnValue(true);
- });
-
- it("returns Parse error envelope when body isn't valid JSON", async () => {
- const res = await POST(
- makePost({ Authorization: "Bearer ok" }, "not json"),
- );
- expect(res.status).toBe(200);
- const body = (await res.json()) as { error: { code: number } };
- expect(body.error.code).toBe(-32700);
- });
-
- it("rejects batched requests (array body) with Invalid Request", async () => {
- const res = await POST(
- makePost({ Authorization: "Bearer ok" }, [
- { jsonrpc: "2.0", id: 1, method: "ping" },
- ]),
- );
- expect(res.status).toBe(200);
- const body = (await res.json()) as { error: { code: number; message: string } };
- expect(body.error.code).toBe(-32600);
- expect(body.error.message).toMatch(/Batched/);
- });
-
- it("rejects non-2.0 jsonrpc payloads", async () => {
- const res = await POST(
- makePost({ Authorization: "Bearer ok" }, {
- jsonrpc: "1.0",
- id: 1,
- method: "ping",
- }),
- );
- const body = (await res.json()) as { error: { code: number } };
- expect(body.error.code).toBe(-32600);
- });
-
- it("returns 204 for notifications (handler returns null)", async () => {
- handleJsonRpcMock.mockResolvedValue(null);
- const res = await POST(
- makePost(
- { Authorization: "Bearer ok" },
- { jsonrpc: "2.0", method: "notifications/initialized" },
- ),
- );
- expect(res.status).toBe(204);
- });
-});
-
-describe("GET /api/mcp/orchestration", () => {
- it("returns the server descriptor without leaking the secret", async () => {
- const res = await GET();
- const body = (await res.json()) as { name: string; transport: string };
- expect(body.name).toBe("notfair-cmo");
- expect(body.transport).toBe("streamable-http");
- });
-});
diff --git a/notfair-cmo/src/app/api/oauth/[provider]/callback/route.test.ts b/notfair-cmo/src/app/api/oauth/[provider]/callback/route.test.ts
deleted file mode 100644
index d691216a..00000000
--- a/notfair-cmo/src/app/api/oauth/[provider]/callback/route.test.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-const storeOAuthTokenMock = vi.fn();
-vi.mock("@/server/db/oauth", () => ({
- storeOAuthToken: (...args: unknown[]) => storeOAuthTokenMock(...args),
-}));
-
-// vi.hoisted runs before any ESM `import` statement, so TOKEN_CONFIG can
-// snapshot a properly-configured process.env at module-load time.
-const { ORIGINAL_ENV } = vi.hoisted(() => {
- const orig = { ...process.env };
- process.env.GOOGLE_ADS_CLIENT_ID = "id";
- process.env.GOOGLE_ADS_CLIENT_SECRET = "secret";
- delete process.env.GSC_CLIENT_ID;
- delete process.env.GSC_CLIENT_SECRET;
- return { ORIGINAL_ENV: orig };
-});
-
-import { GET } from "./route";
-
-function makeReq(url: string): Request {
- return new Request(url, { method: "GET" });
-}
-
-function buildState(project: string): string {
- return Buffer.from(JSON.stringify({ project, ts: Date.now() })).toString(
- "base64url",
- );
-}
-
-describe("GET /api/oauth/[provider]/callback", () => {
- const fetchMock = vi.fn();
- const originalFetch = globalThis.fetch;
-
- beforeEach(() => {
- vi.clearAllMocks();
- fetchMock.mockReset();
- globalThis.fetch = fetchMock as unknown as typeof fetch;
- });
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- afterAll(() => {
- process.env = { ...ORIGINAL_ENV };
- });
-
- it("returns 400 HTML when provider sends an error param", async () => {
- const res = await GET(
- makeReq(
- "http://localhost/api/oauth/google_ads/callback?error=access_denied",
- ),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(400);
- expect(res.headers.get("Content-Type")).toContain("text/html");
- const text = await res.text();
- expect(text).toContain("OAuth denied");
- expect(text).toContain("access_denied");
- });
-
- it("escapes HTML in the error param", async () => {
- const res = await GET(
- makeReq(
- "http://localhost/api/oauth/google_ads/callback?error=" +
- encodeURIComponent("<script>x</script>"),
- ),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- const text = await res.text();
- expect(text).not.toContain("<script>x</script>");
- expect(text).toContain("&lt;script&gt;");
- });
-
- it("returns 400 when code or state is missing", async () => {
- const res = await GET(
- makeReq("http://localhost/api/oauth/google_ads/callback?code=abc"),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(400);
- const text = await res.text();
- expect(text).toContain("Missing code or state");
- });
-
- it("returns 400 when state token is malformed base64", async () => {
- const res = await GET(
- makeReq(
- "http://localhost/api/oauth/google_ads/callback?code=abc&state=not-base64-json!!!",
- ),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(400);
- const text = await res.text();
- expect(text).toContain("Invalid state token");
- });
-
- it("returns 503 when provider is known but client id is not configured (gsc)", async () => {
- const res = await GET(
- makeReq(
- `http://localhost/api/oauth/gsc/callback?code=abc&state=${buildState("acme")}`,
- ),
- { params: Promise.resolve({ provider: "gsc" }) },
- );
- expect(res.status).toBe(503);
- const text = await res.text();
- expect(text).toContain("OAuth not configured");
- expect(text).toContain("GSC_CLIENT_ID");
- });
-
- it("returns 503 when provider key is entirely unknown (config undefined)", async () => {
- const res = await GET(
- makeReq(
- `http://localhost/api/oauth/whatever/callback?code=abc&state=${buildState("acme")}`,
- ),
- { params: Promise.resolve({ provider: "whatever" }) },
- );
- expect(res.status).toBe(503);
- const text = await res.text();
- expect(text).toContain("OAuth not configured");
- });
-
- it("returns 502 when token exchange request fails", async () => {
- fetchMock.mockResolvedValueOnce(
- new Response("invalid_grant detail", { status: 400 }),
- );
- const res = await GET(
- makeReq(
- `http://localhost/api/oauth/google_ads/callback?code=abc&state=${buildState("acme")}`,
- ),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(502);
- const text = await res.text();
- expect(text).toContain("Token exchange failed");
- expect(text).toContain("invalid_grant detail");
- });
-
- it("returns 400 when token response is missing refresh_token", async () => {
- fetchMock.mockResolvedValueOnce(
- new Response(
- JSON.stringify({
- access_token: "at",
- expires_in: 3600,
- scope: "scope",
- token_type: "Bearer",
- }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- );
- const res = await GET(
- makeReq(
- `http://localhost/api/oauth/google_ads/callback?code=abc&state=${buildState("acme")}`,
- ),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(400);
- const text = await res.text();
- expect(text).toContain("No refresh token");
- });
-
- it("returns 500 when token storage fails", async () => {
- fetchMock.mockResolvedValueOnce(
- new Response(
- JSON.stringify({
- access_token: "at",
- refresh_token: "rt",
- expires_in: 3600,
- scope: "scope",
- token_type: "Bearer",
- }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- );
- storeOAuthTokenMock.mockRejectedValueOnce(new Error("keychain failed"));
-
- const res = await GET(
- makeReq(
- `http://localhost/api/oauth/google_ads/callback?code=abc&state=${buildState("acme")}`,
- ),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(500);
- const text = await res.text();
- expect(text).toContain("Could not store token");
- expect(text).toContain("keychain failed");
- });
-
- it("redirects to /<project>/connections on full success", async () => {
- fetchMock.mockResolvedValueOnce(
- new Response(
- JSON.stringify({
- access_token: "at",
- refresh_token: "rt",
- expires_in: 3600,
- scope: "scope1 scope2",
- token_type: "Bearer",
- }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- );
- storeOAuthTokenMock.mockResolvedValueOnce(undefined);
-
- const res = await GET(
- makeReq(
- `http://localhost/api/oauth/google_ads/callback?code=mycode&state=${buildState("acme")}`,
- ),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(307);
- expect(res.headers.get("location")).toBe(
- "http://localhost/acme/connections?connected=google_ads",
- );
-
- expect(storeOAuthTokenMock).toHaveBeenCalledTimes(1);
- const stored = storeOAuthTokenMock.mock.calls[0]![0] as {
- project_slug: string;
- provider: string;
- access_token: string;
- refresh_token: string;
- scope: string;
- };
- expect(stored.project_slug).toBe("acme");
- expect(stored.provider).toBe("google_ads");
- expect(stored.access_token).toBe("at");
- expect(stored.refresh_token).toBe("rt");
- expect(stored.scope).toBe("scope1 scope2");
-
- const [tokenUrl, init] = fetchMock.mock.calls[0]!;
- expect(tokenUrl).toBe("https://oauth2.googleapis.com/token");
- expect((init as RequestInit).method).toBe("POST");
- const bodyAsString = ((init as RequestInit).body as URLSearchParams).toString();
- expect(bodyAsString).toContain("code=mycode");
- expect(bodyAsString).toContain("grant_type=authorization_code");
- expect(bodyAsString).toContain(
- "redirect_uri=http%3A%2F%2Flocalhost%2Fapi%2Foauth%2Fgoogle_ads%2Fcallback",
- );
- });
-});
diff --git a/notfair-cmo/src/app/api/oauth/[provider]/callback/route.ts b/notfair-cmo/src/app/api/oauth/[provider]/callback/route.ts
deleted file mode 100644
index e6451736..00000000
--- a/notfair-cmo/src/app/api/oauth/[provider]/callback/route.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import { NextResponse } from "next/server";
-import { storeOAuthToken } from "@/server/db/oauth";
-import type { OAuthProvider } from "@/types";
-
-export const runtime = "nodejs";
-
-/**
- * GET /api/oauth/[provider]/callback?code=...&state=...
- *
- * Provider redirects here after the user grants consent. We exchange the code
- * for tokens, encrypt with the master key, and persist to SQLite.
- */
-export async function GET(
- request: Request,
- { params }: { params: Promise<{ provider: string }> },
-) {
- const { provider } = await params;
- const url = new URL(request.url);
- const code = url.searchParams.get("code");
- const state = url.searchParams.get("state");
- const errorParam = url.searchParams.get("error");
-
- if (errorParam) {
- return htmlResponse(
- `<h1>OAuth denied</h1><p>The provider returned: <code>${escapeHtml(errorParam)}</code></p><p><a href="/">Back to app</a></p>`,
- 400,
- );
- }
- if (!code || !state) {
- return htmlResponse(`<h1>OAuth error</h1><p>Missing code or state.</p>`, 400);
- }
-
- let project: string;
- try {
- const decoded = JSON.parse(Buffer.from(state, "base64url").toString("utf8")) as {
- project: string;
- };
- project = decoded.project;
- } catch {
- return htmlResponse(`<h1>OAuth error</h1><p>Invalid state token.</p>`, 400);
- }
-
- const config = TOKEN_CONFIG[provider];
- if (!config || !config.clientId || !config.clientSecret) {
- return htmlResponse(
- `<h1>OAuth not configured</h1><p>Set ${config?.envClientId ?? "(client id env var)"} + secret in your environment.</p>`,
- 503,
- );
- }
-
- const callbackBase = url.origin;
- const tokenRes = await fetch(config.tokenEndpoint, {
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body: new URLSearchParams({
- code,
- client_id: config.clientId,
- client_secret: config.clientSecret,
- redirect_uri: `${callbackBase}/api/oauth/${provider}/callback`,
- grant_type: "authorization_code",
- }),
- });
-
- if (!tokenRes.ok) {
- const detail = await tokenRes.text();
- return htmlResponse(
- `<h1>Token exchange failed</h1><pre>${escapeHtml(detail)}</pre>`,
- 502,
- );
- }
-
- const tokenData = (await tokenRes.json()) as {
- access_token: string;
- refresh_token?: string;
- expires_in: number;
- scope: string;
- token_type: string;
- };
-
- if (!tokenData.refresh_token) {
- return htmlResponse(
- `<h1>No refresh token</h1><p>Re-authorize and ensure the consent screen prompts for offline access.</p><p><a href="/${encodeURIComponent(project)}/connections">Back</a></p>`,
- 400,
- );
- }
-
- try {
- await storeOAuthToken({
- project_slug: project,
- provider: provider as OAuthProvider,
- account_label: "default",
- access_token: tokenData.access_token,
- refresh_token: tokenData.refresh_token,
- expires_at: new Date(Date.now() + tokenData.expires_in * 1000).toISOString(),
- scope: tokenData.scope ?? config.scopes.join(" "),
- });
- } catch (err) {
- return htmlResponse(
- `<h1>Could not store token</h1><pre>${escapeHtml(err instanceof Error ? err.message : String(err))}</pre><p>This usually means OS keychain is unavailable.</p>`,
- 500,
- );
- }
-
- return NextResponse.redirect(
- `${callbackBase}/${encodeURIComponent(project)}/connections?connected=${provider}`,
- );
-}
-
-type TokenConfig = {
- clientId: string | undefined;
- clientSecret: string | undefined;
- envClientId: string;
- tokenEndpoint: string;
- scopes: string[];
-};
-
-const TOKEN_CONFIG: Record<string, TokenConfig> = {
- google_ads: {
- clientId: process.env.GOOGLE_ADS_CLIENT_ID,
- clientSecret: process.env.GOOGLE_ADS_CLIENT_SECRET,
- envClientId: "GOOGLE_ADS_CLIENT_ID",
- tokenEndpoint: "https://oauth2.googleapis.com/token",
- scopes: ["https://www.googleapis.com/auth/adwords"],
- },
- gsc: {
- clientId: process.env.GSC_CLIENT_ID,
- clientSecret: process.env.GSC_CLIENT_SECRET,
- envClientId: "GSC_CLIENT_ID",
- tokenEndpoint: "https://oauth2.googleapis.com/token",
- scopes: ["https://www.googleapis.com/auth/webmasters.readonly"],
- },
-};
-
-function htmlResponse(html: string, status = 200): Response {
- return new Response(
- `<!doctype html><meta charset="utf-8"><style>body{font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#18181b}h1{font-size:1.2rem}a{color:#2563eb}pre{background:#f4f4f5;padding:.75rem;border-radius:.5rem;overflow:auto}</style>${html}`,
- { status, headers: { "Content-Type": "text/html; charset=utf-8" } },
- );
-}
-
-function escapeHtml(s: string): string {
- return s
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")
- .replace(/"/g, "&quot;");
-}
diff --git a/notfair-cmo/src/app/api/oauth/[provider]/start/route.test.ts b/notfair-cmo/src/app/api/oauth/[provider]/start/route.test.ts
deleted file mode 100644
index b37fe877..00000000
--- a/notfair-cmo/src/app/api/oauth/[provider]/start/route.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { afterAll, describe, expect, it, vi } from "vitest";
-
-// Set env BEFORE the route is imported. vi.hoisted runs before any ESM
-// `import` statement, including the import below — without this the
-// OAUTH_CONFIG closure snapshots an empty env and every google_ads test
-// hits the 503 "not configured" branch.
-const { ORIGINAL_ENV } = vi.hoisted(() => {
- const orig = { ...process.env };
- process.env.GOOGLE_ADS_CLIENT_ID = "my-google-client-id";
- process.env.GOOGLE_ADS_CLIENT_SECRET = "my-secret";
- delete process.env.GSC_CLIENT_ID;
- delete process.env.GSC_CLIENT_SECRET;
- return { ORIGINAL_ENV: orig };
-});
-
-import { GET } from "./route";
-
-function makeReq(url: string): Request {
- return new Request(url, { method: "GET" });
-}
-
-describe("GET /api/oauth/[provider]/start", () => {
- afterAll(() => {
- process.env = { ...ORIGINAL_ENV };
- });
-
- it("returns 400 when project query param is missing", async () => {
- const res = await GET(
- makeReq("http://localhost/api/oauth/google_ads/start"),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(400);
- const body = (await res.json()) as { error: string };
- expect(body.error).toContain("project");
- });
-
- it("returns 404 when provider is unknown", async () => {
- const res = await GET(
- makeReq("http://localhost/api/oauth/unknown_provider/start?project=acme"),
- { params: Promise.resolve({ provider: "unknown_provider" }) },
- );
- expect(res.status).toBe(404);
- const body = (await res.json()) as { error: string };
- expect(body.error).toMatch(/unknown_provider/i);
- });
-
- it("returns 503 with helpful text for a known-but-unconfigured provider (gsc)", async () => {
- const res = await GET(
- makeReq("http://localhost/api/oauth/gsc/start?project=acme"),
- { params: Promise.resolve({ provider: "gsc" }) },
- );
- expect(res.status).toBe(503);
- expect(res.headers.get("Content-Type")).toContain("text/plain");
- const text = await res.text();
- expect(text).toContain("GSC_CLIENT_ID");
- expect(text).toContain("GSC_CLIENT_SECRET");
- });
-
- it("redirects to Google's OAuth consent screen for google_ads when configured", async () => {
- const res = await GET(
- makeReq("http://localhost/api/oauth/google_ads/start?project=acme"),
- { params: Promise.resolve({ provider: "google_ads" }) },
- );
- expect(res.status).toBe(307);
- const location = res.headers.get("location");
- expect(location).toBeTruthy();
- const redirect = new URL(location!);
- expect(redirect.origin).toBe("https://accounts.google.com");
- expect(redirect.pathname).toBe("/o/oauth2/v2/auth");
- expect(redirect.searchParams.get("client_id")).toBe("my-google-client-id");
- expect(redirect.searchParams.get("redirect_uri")).toBe(
- "http://localhost/api/oauth/google_ads/callback",
- );
- expect(redirect.searchParams.get("response_type")).toBe("code");
- expect(redirect.searchParams.get("scope")).toContain("adwords");
- expect(redirect.searchParams.get("access_type")).toBe("offline");
- expect(redirect.searchParams.get("prompt")).toBe("consent");
-
- const state = redirect.searchParams.get("state");
- expect(state).toBeTruthy();
- const decoded = JSON.parse(
- Buffer.from(state!, "base64url").toString("utf8"),
- ) as { project: string; ts: number };
- expect(decoded.project).toBe("acme");
- expect(typeof decoded.ts).toBe("number");
- });
-});
diff --git a/notfair-cmo/src/app/api/oauth/[provider]/start/route.ts b/notfair-cmo/src/app/api/oauth/[provider]/start/route.ts
deleted file mode 100644
index 80e16580..00000000
--- a/notfair-cmo/src/app/api/oauth/[provider]/start/route.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { NextResponse } from "next/server";
-
-export const runtime = "nodejs";
-
-/**
- * GET /api/oauth/[provider]/start?project=<slug>
- *
- * V1 scaffold: redirects to the provider's OAuth consent screen with our
- * localhost callback URL. The actual provider client IDs + scopes are
- * env-driven so users can register their own OAuth app.
- *
- * Required env vars (per provider):
- * GOOGLE_ADS_CLIENT_ID, GOOGLE_ADS_CLIENT_SECRET
- * GSC_CLIENT_ID, GSC_CLIENT_SECRET
- *
- * If not set, this returns a helpful 503 explaining setup steps instead of
- * silently sending the user to a broken page.
- */
-export async function GET(
- request: Request,
- { params }: { params: Promise<{ provider: string }> },
-) {
- const { provider } = await params;
- const url = new URL(request.url);
- const project = url.searchParams.get("project");
- if (!project) {
- return NextResponse.json({ error: "project query param required" }, { status: 400 });
- }
-
- const config = OAUTH_CONFIG[provider];
- if (!config) {
- return NextResponse.json({ error: `Unknown provider: ${provider}` }, { status: 404 });
- }
-
- if (!config.clientId) {
- return new Response(
- `OAuth not configured for '${provider}'. Set ${config.envClientId} and ${config.envClientSecret} in your environment, then restart notfair-cmo.\n\nSee: README#oauth-setup`,
- { status: 503, headers: { "Content-Type": "text/plain" } },
- );
- }
-
- const callbackBase = url.origin;
- const callback = `${callbackBase}/api/oauth/${provider}/callback`;
- const state = encodeStateToken(project);
-
- const authUrl = new URL(config.authEndpoint);
- authUrl.searchParams.set("client_id", config.clientId);
- authUrl.searchParams.set("redirect_uri", callback);
- authUrl.searchParams.set("response_type", "code");
- authUrl.searchParams.set("scope", config.scopes.join(" "));
- authUrl.searchParams.set("access_type", "offline");
- authUrl.searchParams.set("prompt", "consent");
- authUrl.searchParams.set("state", state);
-
- return NextResponse.redirect(authUrl.toString());
-}
-
-type ProviderConfig = {
- clientId: string | undefined;
- envClientId: string;
- envClientSecret: string;
- authEndpoint: string;
- scopes: string[];
-};
-
-const OAUTH_CONFIG: Record<string, ProviderConfig> = {
- google_ads: {
- clientId: process.env.GOOGLE_ADS_CLIENT_ID,
- envClientId: "GOOGLE_ADS_CLIENT_ID",
- envClientSecret: "GOOGLE_ADS_CLIENT_SECRET",
- authEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
- scopes: ["https://www.googleapis.com/auth/adwords"],
- },
- gsc: {
- clientId: process.env.GSC_CLIENT_ID,
- envClientId: "GSC_CLIENT_ID",
- envClientSecret: "GSC_CLIENT_SECRET",
- authEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
- scopes: ["https://www.googleapis.com/auth/webmasters.readonly"],
- },
-};
-
-function encodeStateToken(project: string): string {
- // Simple state encoding; in production add CSRF nonce verification.
- return Buffer.from(JSON.stringify({ project, ts: Date.now() })).toString("base64url");
-}
diff --git a/notfair-cmo/src/app/api/projects/[slug]/provision/route.test.ts b/notfair-cmo/src/app/api/projects/[slug]/provision/route.test.ts
deleted file mode 100644
index 0a308293..00000000
--- a/notfair-cmo/src/app/api/projects/[slug]/provision/route.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { Project } from "@/types";
-
-const getProjectMock = vi.fn();
-vi.mock("@/server/db/projects", () => ({
- getProject: (...args: unknown[]) => getProjectMock(...args),
-}));
-
-const ensureProjectAgentsMock = vi.fn();
-vi.mock("@/server/agent-templates", () => ({
- ensureProjectAgents: (...args: unknown[]) => ensureProjectAgentsMock(...args),
-}));
-
-import { POST } from "./route";
-
-function makeProject(overrides: Partial<Project> = {}): Project {
- return {
- id: "uuid",
- slug: "acme",
- display_name: "Acme",
- created_at: "now",
- archived_at: null,
- google_ads_account_id: null,
- website_url: null,
- codebase_path: null,
- ...overrides,
- };
-}
-
-function makeReq(): Request {
- return new Request("http://localhost/api/projects/acme/provision", {
- method: "POST",
- });
-}
-
-describe("POST /api/projects/[slug]/provision", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("returns 404 when project not found", async () => {
- getProjectMock.mockReturnValueOnce(null);
- const res = await POST(makeReq(), { params: Promise.resolve({ slug: "ghost" }) });
- expect(res.status).toBe(404);
- const body = (await res.json()) as { error: string };
- expect(body.error).toBe("Project not found");
- expect(ensureProjectAgentsMock).not.toHaveBeenCalled();
- });
-
- it("returns ok with ensureProjectAgents result on success", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- ensureProjectAgentsMock.mockResolvedValueOnce({
- created: ["acme-cmo"],
- existed: [],
- failed: [],
- });
- const res = await POST(makeReq(), { params: Promise.resolve({ slug: "acme" }) });
- expect(res.status).toBe(200);
- const body = (await res.json()) as {
- ok: boolean;
- created: string[];
- existed: string[];
- failed: unknown[];
- };
- expect(body).toEqual({
- ok: true,
- created: ["acme-cmo"],
- existed: [],
- failed: [],
- });
- expect(ensureProjectAgentsMock).toHaveBeenCalledWith("acme");
- });
-
- it("returns ok even when ensureProjectAgents reports partial failures", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));
- ensureProjectAgentsMock.mockResolvedValueOnce({
- created: [],
- existed: ["acme-cmo"],
- failed: [{ name: "acme-google-ads", error: "boom" }],
- });
- const res = await POST(makeReq(), { params: Promise.resolve({ slug: "acme" }) });
- expect(res.status).toBe(200);
- const body = (await res.json()) as {
- ok: boolean;
- failed: Array<{ name: string; error: string }>;
- };
- expect(body.ok).toBe(true);
- expect(body.failed).toHaveLength(1);
- });
-
- it("propagates the slug from params to getProject + ensureProjectAgents", async () => {
- getProjectMock.mockReturnValueOnce(makeProject({ slug: "other" }));
- ensureProjectAgentsMock.mockResolvedValueOnce({ created: [], existed: [], failed: [] });
- await POST(makeReq(), { params: Promise.resolve({ slug: "other" }) });
- expect(getProjectMock).toHaveBeenCalledWith("other");
- expect(ensureProjectAgentsMock).toHaveBeenCalledWith("other");
- });
-});
diff --git a/notfair-cmo/src/app/api/projects/[slug]/provision/route.ts b/notfair-cmo/src/app/api/projects/[slug]/provision/route.ts
deleted file mode 100644
index 4f164c69..00000000
--- a/notfair-cmo/src/app/api/projects/[slug]/provision/route.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { NextResponse } from "next/server";
-import { getProject } from "@/server/db/projects";
-import { ensureProjectAgents } from "@/server/agent-templates";
-
-export const runtime = "nodejs";
-
-/**
- * POST /api/projects/[slug]/provision
- * Idempotently creates OpenClaw agents for this project (CMO + specialists).
- * Called from onboarding flow once after project creation.
- */
-export async function POST(
- _request: Request,
- { params }: { params: Promise<{ slug: string }> },
-) {
- const { slug } = await params;
- const project = getProject(slug);
- if (!project) {
- return NextResponse.json({ error: "Project not found" }, { status: 404 });
- }
- const result = await ensureProjectAgents(slug);
- return NextResponse.json({ ok: true, ...result });
-}
diff --git a/notfair-cmo/src/components/agent-avatar.tsx b/notfair-cmo/src/components/agent-avatar.tsx
deleted file mode 100644
index 5e1a9b86..00000000
--- a/notfair-cmo/src/components/agent-avatar.tsx
+++ /dev/null
@@ -1,302 +0,0 @@
-import type { AgentTemplateKey } from "@/server/agent-templates";
-
-/**
- * Cute pixel-art avatars for each specialist role. Hand-designed on a
- * 16×16 grid so the faces stay crisp at any render size (the SVG uses
- * shape-rendering="crispEdges"). Each character has:
- *
- * - a role-tinted soft background circle, matching the colored chip
- * used elsewhere in the system (CMO blue, Google Ads amber, Meta
- * pink, SEO emerald, X Ads sky)
- * - a per-character palette (hair colour, accent) so the five faces
- * are visually distinct at small sizes
- * - one signature accessory (glasses, headset, hair clip, magnifying
- * glass) so the role reads in one glance
- *
- * The grids are intentionally schematic — at 38px (the glyph slot) the
- * eye is roughly 2×2 pixels, so we lean on the silhouette + hair +
- * accessory rather than fine facial detail.
- */
-
-type Avatar = {
- grid: readonly string[];
- palette: Record<string, string>;
- /** Background wash behind the face — subtle role colour. */
- bg: string;
-};
-
-const SKIN = "#F2C8A0";
-const SKIN_SHADOW = "#E0AE85";
-const EYE = "#1E1E22";
-const MOUTH = "#C36A6A";
-const CHEEK = "#F9B7A6";
-
-/**
- * Greg — CMO. Neat side part, glasses, navy collar peeking. The
- * executive of the four. Blue background to match the sidebar CMO chip.
- */
-const CMO: Avatar = {
- bg: "#DBE7FB",
- palette: {
- h: "#5B3A1F", // hair (warm brown)
- H: "#3F2916", // hair shadow
- s: SKIN,
- S: SKIN_SHADOW,
- e: EYE,
- g: "#6B7280", // glasses frame
- m: MOUTH,
- c: CHEEK,
- t: "#1F3A8A", // tie/jacket navy
- w: "#FFFFFF", // shirt collar
- },
- grid: [
- "................",
- "................",
- ".....HHHHHH.....",
- "....HhhhhhhH....",
- "...HhhhhhhhhH...",
- "...Hhssssshhh...",
- "...hsSssssShh...",
- "...gsegssges....", // glasses
- "...hsesssesh....",
- "....hssssssh....",
- "....cssmsscs....",
- ".....ssssss.....",
- "....wsssssw.....",
- "...twwwwwwwt....", // collar + tie
- "..tttttttttt....",
- "..tttttttttt....",
- ],
-};
-
-/**
- * Ana — Google Ads specialist. Auburn ponytail, headset (the call-rep
- * vibe of running campaigns), warm amber background. Energetic.
- */
-const GOOGLE_ADS: Avatar = {
- bg: "#FCE7C7",
- palette: {
- h: "#B85820", // auburn hair
- H: "#8A3F12",
- s: SKIN,
- S: SKIN_SHADOW,
- e: EYE,
- m: MOUTH,
- c: CHEEK,
- y: "#F59E0B", // headset accent
- Y: "#92400E",
- p: "#FFD9C2", // earring highlight
- },
- grid: [
- "................",
- "................",
- "....HHHHHHH.....",
- "...HhhhhhhhH....",
- "..yHhhhhhhhHy...", // headset over hair
- "..ysshhhhhssy...",
- "..ysSsssssSsy...",
- "..yseSsssSesy...",
- "..ssssesessss...",
- "...ssssssssp....", // earring dot
- "...cssmmsscs....",
- "....ssssssss....",
- "....ssssssss....",
- "...HhhhhhhhH....", // hair flows behind shoulders
- "..HhhhhhhhhhH...",
- "..hhhhhhhhhhhh..",
- ],
-};
-
-/**
- * Mia — Meta Ads specialist. Pink bob, side bangs, a sparkle decoration
- * (creative/social vibe). Pink background to match the chip.
- */
-const META_ADS: Avatar = {
- bg: "#FCD5E2",
- palette: {
- h: "#E45A8A", // pink hair
- H: "#B83465",
- s: SKIN,
- S: SKIN_SHADOW,
- e: EYE,
- m: MOUTH,
- c: CHEEK,
- p: "#FCE7F0", // hair highlight
- "*": "#F472B6", // sparkle
- },
- grid: [
- "................",
- "................",
- "...HHHHHHHHH....",
- "..HhhhhhhhhhH...",
- ".Hhhhhhhhhhhh*..", // sparkle
- ".HhpssssspphhH..",
- ".Hhsssssssshh...",
- ".Hheseeesssh....",
- ".Hssseessshh....",
- "..hssSsssShh....",
- "..cssmmmssc.....",
- "...ssssssss.....",
- "...ssssssss.....",
- "..HhsssssshH....",
- ".HhhhhhhhhhhH...",
- "..hhhhhhhhhh....",
- ],
-};
-
-/**
- * Sam — SEO specialist. Green hair, round glasses with a magnifying-
- * glass handle peeking off one side (the search motif). Emerald
- * background.
- */
-const SEO: Avatar = {
- bg: "#D4EEDD",
- palette: {
- h: "#3F8A4F", // green hair
- H: "#2A5E36",
- s: SKIN,
- S: SKIN_SHADOW,
- e: EYE,
- m: MOUTH,
- c: CHEEK,
- g: "#374151", // glasses + handle
- G: "#9CA3AF", // glasses inside highlight
- },
- grid: [
- "................",
- "................",
- "....HHHHHHH.....",
- "...HhhhhhhhH....",
- "..HhhhhhhhhhH...",
- "..Hhssssssshh...",
- "..hssSsssssSh...",
- "..gggssssgggh...", // glasses arms
- "..gGgeggeGgg....", // glasses lenses + eyes
- "...gggssgggg....",
- "...hsmmmsshg....", // handle of magnifier
- "....ssssssg.....",
- "....csscssg.....",
- "...hssssshg.....",
- "..hhhhhhhhh.....",
- "..hhhhhhhhh.....",
- ],
-};
-
-/**
- * Max — X Ads specialist. Jet-black hair and dark shades over a black
- * tee (the platform's monochrome brand), on a sky wash so the chip
- * still reads friendly next to the others.
- */
-const X_ADS: Avatar = {
- bg: "#D6ECF8",
- palette: {
- h: "#3F3F46", // near-black hair
- H: "#18181B",
- s: SKIN,
- S: SKIN_SHADOW,
- m: MOUTH,
- c: CHEEK,
- x: "#0A0A0B", // shades frame
- w: "#52525B", // lens highlight
- t: "#18181B", // black tee
- },
- grid: [
- "................",
- "................",
- ".....HHHHHH.....",
- "....HhhhhhhH....",
- "...HhhhhhhhhH...",
- "...Hhssssshhh...",
- "...hsSssssShh...",
- "...xxxxsxxxx....", // shades band
- "...xwwxsxwwx....", // lenses + highlight
- "....hssssssh....",
- "....cssmsscs....",
- ".....ssssss.....",
- "....tssssst.....",
- "...tttttttt.....", // black tee
- "..tttttttttt....",
- "..tttttttttt....",
- ],
-};
-
-const AVATARS: Record<AgentTemplateKey, Avatar> = {
- cmo: CMO,
- google_ads: GOOGLE_ADS,
- meta_ads: META_ADS,
- seo: SEO,
- x_ads: X_ADS,
-};
-
-/**
- * Render the pixel-art avatar for a template-backed agent. Pass the
- * pixel size (defaults to 38, matching `.ns-glyph`). The component
- * collapses to a `null` if no avatar exists for the role — callers
- * should fall back to a generic icon in that case.
- */
-export function AgentAvatar({
- role,
- size = 38,
- className,
-}: {
- role: AgentTemplateKey | null | undefined;
- size?: number;
- className?: string;
-}) {
- const avatar = role ? AVATARS[role] : undefined;
- if (!avatar) return null;
- const grid = avatar.grid;
- const cols = grid[0]!.length;
- const rows = grid.length;
- const cellPx = size / Math.max(cols, rows);
-
- // One <rect> per non-transparent pixel. We also draw a background
- // circle (a 16-wide rounded rect that fills the viewBox) so the
- // avatar reads as a single chip the way our other ns-glyph slots do.
- const rects: React.ReactNode[] = [];
- rects.push(
- <rect
- key="bg"
- x={0}
- y={0}
- width={cols}
- height={rows}
- rx={cols * 0.22}
- ry={rows * 0.22}
- fill={avatar.bg}
- />,
- );
- for (let y = 0; y < rows; y++) {
- const row = grid[y]!;
- for (let x = 0; x < cols; x++) {
- const ch = row[x]!;
- const color = avatar.palette[ch];
- if (!color) continue;
- rects.push(
- <rect
- key={`${x}-${y}`}
- x={x}
- y={y}
- width={1.01} // tiny overlap kills sub-pixel seams when zoomed
- height={1.01}
- fill={color}
- />,
- );
- }
- }
-
- return (
- <svg
- role="img"
- aria-hidden
- width={size}
- height={size}
- viewBox={`0 0 ${cols} ${rows}`}
- shapeRendering="crispEdges"
- style={{ width: size, height: size, display: "block" }}
- className={className}
- >
- {rects}
- </svg>
- );
-}
diff --git a/notfair-cmo/src/components/agent-danger-zone.test.tsx b/notfair-cmo/src/components/agent-danger-zone.test.tsx
deleted file mode 100644
index f41f1b09..00000000
--- a/notfair-cmo/src/components/agent-danger-zone.test.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const router = {
- push: vi.fn(),
- refresh: vi.fn(),
-};
-const getAgentDeletionSummaryAction = vi.fn();
-const deleteAgentCascadeAction = vi.fn();
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
- warning: vi.fn(),
-};
-
-vi.mock("next/navigation", () => ({
- useRouter: () => router,
-}));
-
-vi.mock("@/server/actions/agents", () => ({
- getAgentDeletionSummaryAction: (...args: unknown[]) =>
- getAgentDeletionSummaryAction(...args),
- deleteAgentCascadeAction: (...args: unknown[]) =>
- deleteAgentCascadeAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- warning: (...args: unknown[]) => toast.warning(...args),
- },
-}));
-
-import { AgentDangerZone } from "./agent-danger-zone";
-
-const fullSummary = {
- agent_id: "proj-cmo",
- template_key: "cmo",
- source_agent_id: "src",
- exists_in_openclaw: true,
- crons: [
- { id: "c1", name: "proj/cmo/daily", disabled: false },
- { id: "c2", name: "proj/cmo/weekly", disabled: true },
- ],
- threads: [
- { session_id: "s1", label: "main", last_interaction_at: Date.now() - 30_000 },
- { session_id: "s2", label: "another-thread-name-that-is-much-too-long", last_interaction_at: 0 },
- ],
-};
-
-beforeEach(() => {
- router.push.mockReset();
- router.refresh.mockReset();
- getAgentDeletionSummaryAction.mockReset();
- deleteAgentCascadeAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
- toast.warning.mockReset();
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("AgentDangerZone", () => {
- it("renders the delete-agent CTA", () => {
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- expect(screen.getByText("Delete this agent")).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /delete agent/i })).toBeInTheDocument();
- });
-
- it("opens the confirm dialog and shows loading state", async () => {
- getAgentDeletionSummaryAction.mockImplementation(
- () => new Promise(() => {}),
- );
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- expect(
- await screen.findByText(/counting what will be removed/i),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("heading", { name: /Delete .*CMO/i }),
- ).toBeInTheDocument();
- });
-
- it("shows the summary error when loading the summary fails", async () => {
- getAgentDeletionSummaryAction.mockResolvedValue({
- ok: false,
- error: "could not load",
- });
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- expect(await screen.findByText("could not load")).toBeInTheDocument();
- });
-
- it("renders cron jobs and thread rows from the deletion summary", async () => {
- getAgentDeletionSummaryAction.mockResolvedValue({
- ok: true,
- data: fullSummary,
- });
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- expect(await screen.findByText(/Cron jobs \(2\)/)).toBeInTheDocument();
- expect(screen.getByText(/Threads \(2\)/)).toBeInTheDocument();
- expect(screen.getByText("proj/cmo/daily")).toBeInTheDocument();
- expect(screen.getByText("disabled")).toBeInTheDocument();
- expect(screen.getByText("Main thread")).toBeInTheDocument();
- expect(screen.getByText("new")).toBeInTheDocument();
- });
-
- it("shows the empty-state hint when an item list is empty", async () => {
- getAgentDeletionSummaryAction.mockResolvedValue({
- ok: true,
- data: { ...fullSummary, crons: [], threads: [] },
- });
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- expect(
- await screen.findByText(/No scheduled jobs target this agent/i),
- ).toBeInTheDocument();
- expect(screen.getByText(/No chat threads yet/i)).toBeInTheDocument();
- });
-
- it("calls deleteAgentCascadeAction and routes home on success", async () => {
- getAgentDeletionSummaryAction.mockResolvedValue({
- ok: true,
- data: fullSummary,
- });
- deleteAgentCascadeAction.mockResolvedValue({
- ok: true,
- data: { crons_removed: 2, crons_failed: 0 },
- });
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- await screen.findByText(/Cron jobs \(2\)/);
- fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
- await waitFor(() =>
- expect(deleteAgentCascadeAction).toHaveBeenCalledWith("proj-cmo"),
- );
- await waitFor(() =>
- expect(toast.success).toHaveBeenCalledWith(
- "Deleted CMO. 2 crons removed.",
- ),
- );
- await waitFor(() => expect(router.push).toHaveBeenCalledWith("/"));
- });
-
- it("warns when some crons fail to remove during delete", async () => {
- getAgentDeletionSummaryAction.mockResolvedValue({
- ok: true,
- data: fullSummary,
- });
- deleteAgentCascadeAction.mockResolvedValue({
- ok: true,
- data: { crons_removed: 1, crons_failed: 1 },
- });
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- await screen.findByText(/Cron jobs \(2\)/);
- fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
- await waitFor(() =>
- expect(toast.warning).toHaveBeenCalledWith(
- "Deleted CMO. 1 crons removed, 1 failed.",
- ),
- );
- });
-
- it("toasts the server error when delete fails", async () => {
- getAgentDeletionSummaryAction.mockResolvedValue({
- ok: true,
- data: fullSummary,
- });
- deleteAgentCascadeAction.mockResolvedValue({
- ok: false,
- error: "nope",
- });
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- await screen.findByText(/Cron jobs \(2\)/);
- fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("nope"));
- expect(router.push).not.toHaveBeenCalled();
- });
-
- it("closes the dialog when Cancel is clicked", async () => {
- getAgentDeletionSummaryAction.mockResolvedValue({
- ok: true,
- data: fullSummary,
- });
- render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);
- fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));
- await screen.findByText(/Cron jobs \(2\)/);
- fireEvent.click(screen.getByRole("button", { name: /cancel/i }));
- await waitFor(() =>
- expect(screen.queryByText(/Cron jobs/)).not.toBeInTheDocument(),
- );
- });
-});
diff --git a/notfair-cmo/src/components/agent-danger-zone.tsx b/notfair-cmo/src/components/agent-danger-zone.tsx
deleted file mode 100644
index e048ab74..00000000
--- a/notfair-cmo/src/components/agent-danger-zone.tsx
+++ /dev/null
@@ -1,268 +0,0 @@
-"use client";
-
-import { useEffect, useState, useTransition } from "react";
-import { useRouter } from "next/navigation";
-import { AlertTriangle, Loader2, Trash2 } from "lucide-react";
-import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import {
- getAgentDeletionSummaryAction,
- deleteAgentCascadeAction,
- type AgentDeletionSummary,
-} from "@/server/actions/agents";
-
-type Props = {
- agentId: string;
- agentDisplayName: string;
-};
-
-export function AgentDangerZone({ agentId, agentDisplayName }: Props) {
- const router = useRouter();
- const [open, setOpen] = useState(false);
- const [summary, setSummary] = useState<AgentDeletionSummary | null>(null);
- const [summaryError, setSummaryError] = useState<string | null>(null);
- const [loading, setLoading] = useState(false);
- const [pending, startTransition] = useTransition();
-
- useEffect(() => {
- if (!open) {
- setSummary(null);
- setSummaryError(null);
- return;
- }
- setLoading(true);
- (async () => {
- const r = await getAgentDeletionSummaryAction(agentId);
- if (r.ok) setSummary(r.data);
- else setSummaryError(r.error);
- setLoading(false);
- })();
- }, [open, agentId]);
-
- function onConfirm() {
- startTransition(async () => {
- const r = await deleteAgentCascadeAction(agentId);
- if (!r.ok) {
- toast.error(r.error);
- return;
- }
- const d = r.data;
- if (d.crons_failed > 0) {
- toast.warning(
- `Deleted ${agentDisplayName}. ${d.crons_removed} crons removed, ${d.crons_failed} failed.`,
- );
- } else {
- toast.success(
- `Deleted ${agentDisplayName}. ${d.crons_removed} cron${d.crons_removed === 1 ? "" : "s"} removed.`,
- );
- }
- setOpen(false);
- router.push("/");
- router.refresh();
- });
- }
-
- function shortLabel(s: string): string {
- if (s === "main") return "Main thread";
- return s.length > 28 ? `${s.slice(0, 28)}…` : s;
- }
-
- function timeAgo(ms: number): string {
- if (!ms) return "new";
- const sec = Math.max(0, (Date.now() - ms) / 1000);
- if (sec < 60) return `${Math.floor(sec)}s ago`;
- if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
- if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;
- return `${Math.floor(sec / 86400)}d ago`;
- }
-
- const canDelete = !pending && !loading;
-
- return (
- <>
- <div
- className="ns-card"
- style={{
- boxShadow:
- "inset 0 0 0 0.5px hsl(0 72% 51% / 0.25), 0 1px 2px rgba(0,0,0,.04)",
- }}
- >
- <div className="flex items-start gap-4 p-[18px]">
- <span
- aria-hidden
- className="grid size-9 shrink-0 place-items-center rounded-[9px] bg-[hsl(0_92%_96%)] text-[hsl(0_72%_42%)]"
- >
- <AlertTriangle className="size-4" />
- </span>
- <div className="min-w-0 flex-1">
- <h3 className="text-[14.5px] font-semibold tracking-tight text-[hsl(0_72%_42%)]">
- Delete this agent
- </h3>
- <p className="mt-1 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">
- Removes the agent&rsquo;s workspace along with every chat thread
- and every scheduled job that targets it. This cannot be undone.
- </p>
- </div>
- <button
- type="button"
- onClick={() => setOpen(true)}
- className="ns-btn ns-btn-danger ns-btn-sm shrink-0"
- >
- <Trash2 className="size-3.5" />
- Delete agent
- </button>
- </div>
- </div>
-
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent className="max-w-md">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2 text-base">
- <AlertTriangle className="size-4 text-destructive" />
- Delete &ldquo;{agentDisplayName}&rdquo;?
- </DialogTitle>
- <DialogDescription>
- This permanently removes the items below from notfair-cmo&apos;s
- local store.
- </DialogDescription>
- </DialogHeader>
-
- {loading ? (
- <div className="flex items-center gap-2 py-4 text-sm text-muted-foreground">
- <Loader2 className="size-3.5 animate-spin" />
- Counting what will be removed…
- </div>
- ) : summaryError ? (
- <div className="rounded border border-destructive/40 bg-destructive/5 p-3 text-xs text-destructive">
- {summaryError}
- </div>
- ) : summary ? (
- <div className="space-y-4">
- <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">
- <dt className="text-muted-foreground">Agent id</dt>
- <dd className="truncate font-mono">{summary.agent_id}</dd>
-
- {summary.template_key && (
- <>
- <dt className="text-muted-foreground">Template</dt>
- <dd className="font-mono">{summary.template_key}</dd>
- </>
- )}
-
- {summary.source_agent_id && (
- <>
- <dt className="text-muted-foreground">Cloned from</dt>
- <dd className="font-mono">{summary.source_agent_id}</dd>
- </>
- )}
-
- {!summary.exists_in_openclaw && (
- <>
- <dt className="text-muted-foreground">Workspace</dt>
- <dd className="text-[hsl(var(--notfair-warn))]">
- already removed
- </dd>
- </>
- )}
- </dl>
-
- <ItemList
- title={`Cron jobs (${summary.crons.length})`}
- emptyHint="No scheduled jobs target this agent."
- >
- {summary.crons.map((c) => (
- <li key={c.id} className="flex items-center justify-between gap-2 px-3 py-1.5">
- <span className="truncate font-mono text-[11px]">{c.name}</span>
- {c.disabled && (
- <span className="shrink-0 rounded border px-1 text-[9px] uppercase tracking-wide text-muted-foreground">
- disabled
- </span>
- )}
- </li>
- ))}
- </ItemList>
-
- <ItemList
- title={`Threads (${summary.threads.length})`}
- emptyHint="No chat threads yet."
- >
- {summary.threads.map((t) => (
- <li key={t.session_id} className="flex items-center justify-between gap-2 px-3 py-1.5">
- <span className="truncate text-[11px]">{shortLabel(t.label)}</span>
- <span className="shrink-0 text-[10px] text-muted-foreground tabular-nums">
- {timeAgo(t.last_interaction_at)}
- </span>
- </li>
- ))}
- </ItemList>
- </div>
- ) : null}
-
- <DialogFooter className="gap-2 sm:gap-2">
- <Button
- type="button"
- variant="outline"
- onClick={() => setOpen(false)}
- disabled={pending}
- >
- Cancel
- </Button>
- <Button
- type="button"
- variant="destructive"
- onClick={onConfirm}
- disabled={!canDelete}
- >
- {pending ? (
- <>
- <Loader2 className="mr-1.5 size-3.5 animate-spin" />
- Deleting…
- </>
- ) : (
- <>
- <Trash2 className="mr-1.5 size-3.5" />
- Delete forever
- </>
- )}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </>
- );
-}
-
-function ItemList({
- title,
- emptyHint,
- children,
-}: {
- title: string;
- emptyHint: string;
- children: React.ReactNode;
-}) {
- const items = Array.isArray(children) ? children : [children];
- const empty = items.filter(Boolean).length === 0;
- return (
- <div className="space-y-1.5">
- <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
- {title}
- </div>
- <ul className="max-h-40 divide-y overflow-y-auto rounded-md border bg-card text-xs">
- {empty ? (
- <li className="px-3 py-2 text-muted-foreground">{emptyHint}</li>
- ) : (
- children
- )}
- </ul>
- </div>
- );
-}
diff --git a/notfair-cmo/src/components/agent-mcp-blocker-card.tsx b/notfair-cmo/src/components/agent-mcp-blocker-card.tsx
deleted file mode 100644
index c0fce784..00000000
--- a/notfair-cmo/src/components/agent-mcp-blocker-card.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import Link from "next/link";
-import { Plug } from "lucide-react";
-import { projectHref } from "@/lib/project-href";
-import type { AgentMcpBlocker } from "@/server/onboarding/agent-mcp-blocker";
-
-/**
- * Rendered when an agent's required MCP isn't connected for this project.
- * Server-rendered — no client state. The "Connect" button is just a link
- * into the Connections page where the OAuth flow takes over.
- */
-export function AgentMcpBlockerCard({
- projectSlug,
- blocker,
-}: {
- projectSlug: string;
- blocker: AgentMcpBlocker;
-}) {
- return (
- <div className="mx-auto flex h-full max-w-[440px] flex-col items-center justify-center px-6 py-12 text-center">
- <div
- aria-hidden
- className="grid size-14 place-items-center rounded-[14px] bg-[hsl(var(--notfair-accent-soft))] text-[hsl(var(--notfair-accent))]"
- >
- <Plug className="size-6" />
- </div>
- <h1 className="mt-5 text-[22px] font-semibold tracking-tight text-[hsl(var(--notfair-ink))]">
- Connect {blocker.mcp_display_name}
- </h1>
- <p className="mt-2 text-[14px] leading-relaxed text-[hsl(var(--notfair-ink-3))]">
- The <b className="font-semibold text-[hsl(var(--notfair-ink-2))]">
- {blocker.agent_display_name}
- </b>{" "}
- agent needs the {blocker.mcp_display_name} MCP before it can run.
- Connecting takes a single OAuth round-trip; we&rsquo;ll bring you back
- here when it&rsquo;s done.
- </p>
- <Link
- href={projectHref(projectSlug, "/connections")}
- className="ns-btn ns-btn-primary mt-6"
- >
- Connect {blocker.mcp_display_name}
- </Link>
- </div>
- );
-}
diff --git a/notfair-cmo/src/components/agent-nav.test.tsx b/notfair-cmo/src/components/agent-nav.test.tsx
deleted file mode 100644
index 4ddd8d61..00000000
--- a/notfair-cmo/src/components/agent-nav.test.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, cleanup } from "@testing-library/react";
-
-const pathnameRef: { current: string } = { current: "/proj" };
-
-vi.mock("next/navigation", () => ({
- usePathname: () => pathnameRef.current,
-}));
-
-vi.mock("@/components/ui/sidebar", () => ({
- SidebarMenu: ({ children }: { children: React.ReactNode }) => <ul>{children}</ul>,
- SidebarMenuItem: ({ children }: { children: React.ReactNode }) => <li>{children}</li>,
- SidebarMenuButton: ({
- children,
- isActive,
- }: {
- children: React.ReactNode;
- isActive?: boolean;
- asChild?: boolean;
- }) => (
- <div data-active={isActive ? "true" : "false"} data-testid="sidebar-button">
- {children}
- </div>
- ),
-}));
-
-import { AgentNav } from "./agent-nav";
-
-const agents = [
- {
- key: "proj-cmo",
- slug: "cmo-greg",
- name: "Greg",
- role_label: "CMO",
- template_key: "cmo" as const,
- },
- {
- key: "proj-google-ads",
- slug: "google-ads-ana",
- name: "Ana",
- role_label: "Google Ads",
- template_key: "google_ads" as const,
- },
- {
- key: "proj-custom",
- slug: "custom",
- name: "Custom Bot",
- },
-];
-
-beforeEach(() => {
- pathnameRef.current = "/proj";
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("AgentNav", () => {
- it("renders one entry per agent linking to the chat tab", () => {
- render(<AgentNav projectSlug="proj" agents={agents} />);
- // The link's accessible name includes the personal name + role pill
- // text, so /Greg|CMO/i / /Ana|Google Ads/i both match.
- expect(screen.getByRole("link", { name: /Greg/i })).toHaveAttribute(
- "href",
- "/proj/agents/cmo-greg/chat",
- );
- expect(screen.getByRole("link", { name: /Ana/i })).toHaveAttribute(
- "href",
- "/proj/agents/google-ads-ana/chat",
- );
- expect(screen.getByRole("link", { name: /Custom Bot/i })).toHaveAttribute(
- "href",
- "/proj/agents/custom/chat",
- );
- });
-
- it("marks the active agent when the pathname equals the agent base", () => {
- pathnameRef.current = "/proj/agents/cmo-greg";
- render(<AgentNav projectSlug="proj" agents={agents} />);
- const buttons = screen.getAllByTestId("sidebar-button");
- const cmoButton = buttons.find((b) => b.textContent?.includes("Greg"));
- expect(cmoButton?.getAttribute("data-active")).toBe("true");
- const customButton = buttons.find((b) => b.textContent?.includes("Custom Bot"));
- expect(customButton?.getAttribute("data-active")).toBe("false");
- });
-
- it("marks the active agent when the pathname is nested under the agent base", () => {
- pathnameRef.current = "/proj/agents/google-ads-ana/skills";
- render(<AgentNav projectSlug="proj" agents={agents} />);
- const buttons = screen.getAllByTestId("sidebar-button");
- const target = buttons.find((b) => b.textContent?.includes("Ana"));
- expect(target?.getAttribute("data-active")).toBe("true");
- });
-
- it("renders the red attention badge and deep-links to the blocked task", () => {
- render(
- <AgentNav
- projectSlug="proj"
- agents={agents}
- attention={{ "proj-cmo": { count: 1, task_id: "demo1-1" } }}
- />,
- );
- expect(
- screen.getByLabelText("1 waiting on your answer"),
- ).toBeInTheDocument();
- expect(screen.getByRole("link", { name: /Greg/i })).toHaveAttribute(
- "href",
- "/proj/agents/cmo-greg/tasks?task=demo1-1",
- );
- // Other agents keep the default chat link.
- expect(screen.getByRole("link", { name: /Ana/i })).toHaveAttribute(
- "href",
- "/proj/agents/google-ads-ana/chat",
- );
- });
-
- it("falls back to the Tasks tab when no waiting item is task-anchored", () => {
- render(
- <AgentNav
- projectSlug="proj"
- agents={agents}
- attention={{ "proj-cmo": { count: 2, task_id: null } }}
- />,
- );
- expect(
- screen.getByLabelText("2 waiting on your answer"),
- ).toBeInTheDocument();
- expect(screen.getByRole("link", { name: /Greg/i })).toHaveAttribute(
- "href",
- "/proj/agents/cmo-greg/tasks",
- );
- });
-
- it("renders no indicator at all when nothing needs the user", () => {
- render(<AgentNav projectSlug="proj" agents={agents} />);
- expect(screen.queryByRole("status")).not.toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/agent-nav.tsx b/notfair-cmo/src/components/agent-nav.tsx
deleted file mode 100644
index b0aee040..00000000
--- a/notfair-cmo/src/components/agent-nav.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import { usePathname } from "next/navigation";
-import { Bot } from "lucide-react";
-import {
- SidebarMenu,
- SidebarMenuButton,
- SidebarMenuItem,
-} from "@/components/ui/sidebar";
-import type { AgentTemplateKey } from "@/server/agent-templates";
-import { colorForRole } from "@/lib/agent-colors";
-import { cn } from "@/lib/utils";
-import { projectHref } from "@/lib/project-href";
-import { AgentAvatar } from "./agent-avatar";
-import { useLiveCounts } from "./live-counts-context";
-
-type AgentNavEntry = {
- /** Stable key for React, e.g. the agent_id. */
- key: string;
- slug: string;
- /** Personal name shown as the primary sidebar label (e.g. "Greg"). */
- name: string;
- /** Role label for the pill next to the name (e.g. "CMO"). Undefined for
- * cloned/custom agents that aren't backed by a template. */
- role_label?: string;
- description?: string;
- /** Filled for template agents; undefined for cloned/custom ones. */
- template_key?: AgentTemplateKey;
-};
-
-type Props = {
- projectSlug: string;
- agents: AgentNavEntry[];
- /**
- * Optional server-side initial map (agent_id → attention entry) used
- * for the first paint only. After mount, live values come from
- * LiveCountsContext so we don't re-render the parent server component
- * just to flip a number.
- */
- attention?: Record<string, { count: number; task_id: string | null }>;
-};
-
-export function AgentNav({ projectSlug, agents, attention = {} }: Props) {
- const pathname = usePathname();
- const live = useLiveCounts();
- const attentionByAgent = { ...attention, ...live.attention };
-
- return (
- <SidebarMenu>
- {agents.map((a) => {
- // Slack model: when the agent is blocked on the user, the row IS
- // the notification — red badge, and the click lands directly in
- // the decision space (the blocked task's page) instead of Chat.
- const agentAttention = attentionByAgent[a.key];
- const needsYou = (agentAttention?.count ?? 0) > 0;
- // Every agent lands on Chat by default — users start by talking to
- // the agent. Tasks tab (the audit/history view of filed work) is one
- // click away.
- const href = needsYou
- ? projectHref(
- projectSlug,
- `/agents/${a.slug}/tasks${
- agentAttention?.task_id
- ? `?task=${encodeURIComponent(agentAttention.task_id)}`
- : ""
- }`,
- )
- : projectHref(projectSlug, `/agents/${a.slug}/chat`);
- const agentBase = `/${projectSlug}/agents/${a.slug}`;
- const isActive =
- pathname === agentBase || pathname?.startsWith(`${agentBase}/`);
- const rolePalette = a.template_key ? colorForRole(a.template_key) : null;
- return (
- <SidebarMenuItem key={a.key}>
- <SidebarMenuButton asChild isActive={isActive}>
- <Link href={href}>
- {a.template_key ? (
- <AgentAvatar role={a.template_key} size={20} />
- ) : (
- <Bot />
- )}
- <span className="truncate">{a.name}</span>
- {a.role_label && rolePalette && (
- <span
- className={cn(
- "ml-1 rounded-[4px] border px-1.5 py-[1px] text-[9.5px] font-medium uppercase tracking-wide leading-none",
- rolePalette.chip,
- )}
- >
- {a.role_label}
- </span>
- )}
- {needsYou && (
- <span
- role="status"
- aria-label={`${agentAttention!.count} waiting on your answer`}
- className="ml-auto inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-[hsl(var(--destructive))] px-1 text-[10px] font-semibold tabular-nums leading-none text-white"
- >
- {agentAttention!.count}
- </span>
- )}
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
- })}
- </SidebarMenu>
- );
-}
diff --git a/notfair-cmo/src/components/agent-rename-card.test.tsx b/notfair-cmo/src/components/agent-rename-card.test.tsx
deleted file mode 100644
index 4cea2c96..00000000
--- a/notfair-cmo/src/components/agent-rename-card.test.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const router = {
- push: vi.fn(),
- refresh: vi.fn(),
-};
-const renameAgentAction = vi.fn();
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
-};
-
-vi.mock("next/navigation", () => ({
- useRouter: () => router,
-}));
-
-vi.mock("@/server/actions/agents", () => ({
- renameAgentAction: (...args: unknown[]) => renameAgentAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- },
-}));
-
-import { AgentRenameCard } from "./agent-rename-card";
-
-beforeEach(() => {
- router.push.mockReset();
- router.refresh.mockReset();
- renameAgentAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
-});
-
-afterEach(() => {
- cleanup();
-});
-
-function defaultProps() {
- return {
- agentId: "proj-bot",
- projectSlug: "proj",
- currentDisplayName: "Bot",
- currentSlug: "bot",
- };
-}
-
-describe("AgentRenameCard", () => {
- it("seeds the input with the current display name", () => {
- render(<AgentRenameCard {...defaultProps()} />);
- expect(screen.getByLabelText(/display name/i)).toHaveValue("Bot");
- });
-
- it("renders the project slug as a non-editable prefix", () => {
- render(<AgentRenameCard {...defaultProps()} />);
- expect(screen.getByText("proj-")).toBeInTheDocument();
- });
-
- it("disables Save when the name is unchanged", () => {
- render(<AgentRenameCard {...defaultProps()} />);
- const btn = screen.getByRole("button", { name: /save name/i });
- expect(btn).toBeDisabled();
- });
-
- it("shows 'same slug' hint when only display-name casing changes (same slug)", () => {
- render(<AgentRenameCard {...defaultProps()} />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "BOT" } });
- expect(screen.getByText(/same slug/i)).toBeInTheDocument();
- });
-
- it("enables Save with a 'Save name' label when only the display name changes (same slug)", () => {
- render(<AgentRenameCard {...defaultProps()} />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "BOT" } });
- const btn = screen.getByRole("button", { name: /save name/i });
- expect(btn).not.toBeDisabled();
- });
-
- it("switches the button label to 'Rename agent' when the slug changes", () => {
- render(<AgentRenameCard {...defaultProps()} />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "marketing-lead" } });
- expect(
- screen.getByRole("button", { name: /rename agent/i }),
- ).toBeInTheDocument();
- expect(screen.getByText(/slug changes from/i)).toBeInTheDocument();
- });
-
- it("flags invalid slug input and disables the button", () => {
- render(<AgentRenameCard {...defaultProps()} />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "!!!" } });
- expect(screen.getByText(/invalid name/i)).toBeInTheDocument();
- const btn = screen.getByRole("button", { name: /save name|rename agent/i });
- expect(btn).toBeDisabled();
- });
-
- it("calls renameAgentAction and routes on a full-rename success", async () => {
- renameAgentAction.mockResolvedValue({
- ok: true,
- data: { full_rename: true, slug: "marketer", display_name: "Marketer" },
- });
- render(<AgentRenameCard {...defaultProps()} />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "Marketer" } });
- fireEvent.click(screen.getByRole("button", { name: /rename agent/i }));
- await waitFor(() =>
- expect(renameAgentAction).toHaveBeenCalledWith({
- agent_id: "proj-bot",
- new_display_name: "Marketer",
- }),
- );
- await waitFor(() =>
- expect(router.push).toHaveBeenCalledWith("/proj/agents/marketer/settings"),
- );
- expect(toast.success).toHaveBeenCalled();
- });
-
- it("only refreshes (no push) on a same-slug rename success", async () => {
- renameAgentAction.mockResolvedValue({
- ok: true,
- data: { full_rename: false, slug: "bot", display_name: "BOT" },
- });
- render(<AgentRenameCard {...defaultProps()} />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "BOT" } });
- fireEvent.click(screen.getByRole("button", { name: /save name/i }));
- await waitFor(() => expect(renameAgentAction).toHaveBeenCalled());
- expect(router.push).not.toHaveBeenCalled();
- await waitFor(() => expect(router.refresh).toHaveBeenCalled());
- });
-
- it("toasts the server error when rename fails", async () => {
- renameAgentAction.mockResolvedValue({ ok: false, error: "name taken" });
- render(<AgentRenameCard {...defaultProps()} />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "x-newname" } });
- fireEvent.click(screen.getByRole("button", { name: /rename agent/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("name taken"));
- expect(router.push).not.toHaveBeenCalled();
- });
-});
diff --git a/notfair-cmo/src/components/agent-rename-card.tsx b/notfair-cmo/src/components/agent-rename-card.tsx
deleted file mode 100644
index e46ec85f..00000000
--- a/notfair-cmo/src/components/agent-rename-card.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-"use client";
-
-import { useEffect, useState, useTransition } from "react";
-import { useRouter } from "next/navigation";
-import { Loader2 } from "lucide-react";
-import { toast } from "sonner";
-import { Label } from "@/components/ui/label";
-import { cn } from "@/lib/utils";
-import { slugify } from "@/lib/slug";
-import { projectHref } from "@/lib/project-href";
-import { renameAgentAction } from "@/server/actions/agents";
-
-type Props = {
- agentId: string;
- projectSlug: string;
- currentDisplayName: string;
- currentSlug: string;
-};
-
-export function AgentRenameCard({
- agentId,
- projectSlug,
- currentDisplayName,
- currentSlug,
-}: Props) {
- const router = useRouter();
- const [name, setName] = useState(currentDisplayName);
- const [pending, startTransition] = useTransition();
-
- useEffect(() => {
- setName(currentDisplayName);
- }, [currentDisplayName]);
-
- const trimmed = name.trim();
- const slugAttempt = trimmed ? slugify(trimmed) : null;
- const derivedSlug = slugAttempt?.ok ? slugAttempt.slug : null;
- const slugError = slugAttempt && !slugAttempt.ok ? slugAttempt.reason : null;
- const slugChanged = !!derivedSlug && derivedSlug !== currentSlug;
- const nameChanged = trimmed !== currentDisplayName;
-
- function save() {
- if (!nameChanged && !slugChanged) return;
- startTransition(async () => {
- const r = await renameAgentAction({
- agent_id: agentId,
- new_display_name: trimmed,
- });
- if (!r.ok) {
- toast.error(r.error);
- return;
- }
- const d = r.data;
- toast.success(
- d.full_rename
- ? `Renamed to "${d.display_name}" (new URL: ${projectHref(projectSlug, `/agents/${d.slug}`)})`
- : `Renamed to "${d.display_name}"`,
- );
- if (d.full_rename) {
- // agent_id and URL slug changed — route to the new settings page.
- router.push(projectHref(projectSlug, `/agents/${d.slug}/settings`));
- router.refresh();
- } else {
- router.refresh();
- }
- });
- }
-
- const canSave =
- !pending && !slugError && trimmed.length > 0 && (nameChanged || slugChanged);
-
- return (
- <div className="ns-card">
- <div className="space-y-3 p-[18px]">
- <div>
- <h3 className="text-[14.5px] font-semibold tracking-tight text-[hsl(var(--notfair-ink))]">
- Rename this agent
- </h3>
- <p className="mt-1 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">
- Changing the slug rewrites the URL, workspace path, sessions
- location, and every cron name. Chat history and prompts come along.
- </p>
- </div>
-
- <div className="space-y-1.5">
- <Label
- htmlFor="rename-display-name"
- className="text-[12px] font-medium text-[hsl(var(--notfair-ink-3))]"
- >
- Display name
- </Label>
- <div
- className={cn(
- "flex h-9 items-stretch overflow-hidden rounded-lg border bg-background text-sm shadow-sm focus-within:ring-2 focus-within:ring-[hsl(var(--notfair-accent-border))]",
- slugError && "border-destructive focus-within:ring-destructive",
- pending && "opacity-50",
- )}
- >
- <span
- className="flex select-none items-center border-r bg-[hsl(var(--notfair-surface-2))] px-3 font-mono text-[12px] text-[hsl(var(--notfair-ink-4))]"
- aria-hidden
- >
- {projectSlug}-
- </span>
- <input
- id="rename-display-name"
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- disabled={pending}
- className="flex-1 bg-transparent px-3 font-mono text-[13px] placeholder:text-muted-foreground/60 focus-visible:outline-none disabled:cursor-not-allowed"
- placeholder={currentSlug}
- aria-invalid={!!slugError}
- />
- </div>
- {slugError ? (
- <p className="text-[11.5px] text-destructive">
- Invalid name: {slugError}
- </p>
- ) : slugChanged ? (
- <p className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
- Slug changes from{" "}
- <code className="rounded bg-[hsl(var(--notfair-surface-2))] px-1.5 py-px font-mono text-[11px]">
- {currentSlug}
- </code>{" "}
- to{" "}
- <code className="rounded bg-[hsl(var(--notfair-accent-soft))] px-1.5 py-px font-mono text-[11px] text-[hsl(var(--notfair-accent))]">
- {derivedSlug}
- </code>
- . Full rename: clones into the new id, then deletes the old.
- </p>
- ) : (
- <p className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
- Same slug — only the display name changes.
- </p>
- )}
- </div>
-
- <div className="flex justify-end pt-1">
- <button
- type="button"
- onClick={save}
- disabled={!canSave}
- className="ns-btn ns-btn-primary ns-btn-sm"
- >
- {pending ? (
- <>
- <Loader2 className="size-3.5 animate-spin" />
- {slugChanged ? "Renaming…" : "Saving…"}
- </>
- ) : slugChanged ? (
- "Rename agent"
- ) : (
- "Save name"
- )}
- </button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/components/agent-tabs.test.tsx b/notfair-cmo/src/components/agent-tabs.test.tsx
deleted file mode 100644
index 9d105b0b..00000000
--- a/notfair-cmo/src/components/agent-tabs.test.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, cleanup } from "@testing-library/react";
-
-const pathnameRef: { current: string } = { current: "/proj/agents/cmo/tasks" };
-
-vi.mock("next/navigation", () => ({
- usePathname: () => pathnameRef.current,
-}));
-
-import { AgentTabs } from "./agent-tabs";
-
-beforeEach(() => {
- pathnameRef.current = "/proj/agents/cmo/tasks";
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("AgentTabs", () => {
- it("renders all six tabs as links pointing under the agent base path", () => {
- render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);
- const tasks = screen.getByRole("link", { name: /tasks/i });
- const chat = screen.getByRole("link", { name: /chat/i });
- const files = screen.getByRole("link", { name: /files/i });
- const skills = screen.getByRole("link", { name: /skills/i });
- const cron = screen.getByRole("link", { name: /cron/i });
- const settings = screen.getByRole("link", { name: /settings/i });
- expect(tasks).toHaveAttribute("href", "/proj/agents/cmo/tasks");
- expect(chat).toHaveAttribute("href", "/proj/agents/cmo/chat");
- expect(files).toHaveAttribute("href", "/proj/agents/cmo/files");
- expect(skills).toHaveAttribute("href", "/proj/agents/cmo/skills");
- expect(cron).toHaveAttribute("href", "/proj/agents/cmo/cron");
- expect(settings).toHaveAttribute("href", "/proj/agents/cmo/settings");
- });
-
- it("marks the tab as active when the pathname equals the tab href", () => {
- pathnameRef.current = "/proj/agents/cmo/chat";
- render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);
- const chat = screen.getByRole("link", { name: /chat/i });
- expect(chat.className).toContain("text-foreground");
- expect(chat.className).not.toContain("text-muted-foreground");
- const tasks = screen.getByRole("link", { name: /tasks/i });
- expect(tasks.className).toContain("text-muted-foreground");
- });
-
- it("marks the tab as active for nested subpaths under it", () => {
- pathnameRef.current = "/proj/agents/cmo/tasks/abc123";
- render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);
- const tasks = screen.getByRole("link", { name: /tasks/i });
- expect(tasks.className).toContain("text-foreground");
- });
-
- it("renders the inset pill fill only on the active tab", () => {
- pathnameRef.current = "/proj/agents/cmo/skills";
- render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);
- const skills = screen.getByRole("link", { name: /skills/i });
- expect(skills.className).toContain("bg-[hsl(var(--notfair-surface-2))]");
- const others = ["chat", "tasks", "files", "cron", "settings"].map((t) =>
- screen.getByRole("link", { name: new RegExp(t, "i") }),
- );
- for (const link of others) {
- expect(link.className).not.toContain(
- "bg-[hsl(var(--notfair-surface-2))]",
- );
- }
- });
-
- it("treats no-match pathname as no active tab", () => {
- pathnameRef.current = "/some/other/place";
- render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);
- const tasks = screen.getByRole("link", { name: /tasks/i });
- expect(tasks.className).toContain("text-muted-foreground");
- });
-});
diff --git a/notfair-cmo/src/components/agent-tabs.tsx b/notfair-cmo/src/components/agent-tabs.tsx
deleted file mode 100644
index e344837b..00000000
--- a/notfair-cmo/src/components/agent-tabs.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import { usePathname } from "next/navigation";
-import {
- MessageSquare,
- FileText,
- Sparkles,
- Clock,
- Settings,
- ListChecks,
-} from "lucide-react";
-import { cn } from "@/lib/utils";
-
-type Tab = {
- key: string;
- label: string;
- icon: React.ComponentType<{ className?: string }>;
-};
-
-// Chat leads — users start by talking to the agent; tasks materialize from
-// that conversation. The Tasks tab is the audit/history view of work the
-// agent (or its orchestrator) has filed, not a place to create work.
-const TABS: Tab[] = [
- { key: "chat", label: "Chat", icon: MessageSquare },
- { key: "tasks", label: "Tasks", icon: ListChecks },
- { key: "files", label: "Files", icon: FileText },
- { key: "skills", label: "Skills", icon: Sparkles },
- { key: "cron", label: "Cron", icon: Clock },
- { key: "settings", label: "Settings", icon: Settings },
-];
-
-export function AgentTabs({
- projectSlug,
- agentSlug,
-}: {
- projectSlug: string;
- agentSlug: string;
-}) {
- const pathname = usePathname();
- const base = `/${projectSlug}/agents/${agentSlug}`;
-
- return (
- <nav
- className="sticky top-0 z-20 flex items-center gap-1 bg-[hsl(var(--background)/0.82)] px-4 py-1.5 backdrop-blur-md"
- aria-label="Agent sections"
- style={{
- backdropFilter: "saturate(180%) blur(20px)",
- WebkitBackdropFilter: "saturate(180%) blur(20px)",
- }}
- >
- {TABS.map(({ key, label, icon: Icon }) => {
- const href = `${base}/${key}`;
- const isActive =
- pathname === href || pathname?.startsWith(`${href}/`);
- return (
- <Link
- key={key}
- href={href}
- className={cn(
- "relative flex items-center gap-1.5 rounded-[7px] px-3 py-1.5 text-[13px] font-medium tracking-tight transition-colors",
- isActive
- ? "bg-[hsl(var(--notfair-surface-2))] text-foreground"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- <Icon className="size-3.5" />
- {label}
- </Link>
- );
- })}
- </nav>
- );
-}
diff --git a/notfair-cmo/src/components/agent-task-workspace.test.tsx b/notfair-cmo/src/components/agent-task-workspace.test.tsx
deleted file mode 100644
index bdc79f2e..00000000
--- a/notfair-cmo/src/components/agent-task-workspace.test.tsx
+++ /dev/null
@@ -1,402 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
-
-// ── next/navigation -------------------------------------------------------
-const replaceMock = vi.fn();
-const refreshMock = vi.fn();
-const searchParamsState: { qs: string } = { qs: "" };
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ replace: replaceMock, refresh: refreshMock, push: vi.fn() }),
- useSearchParams: () => new URLSearchParams(searchParamsState.qs),
-}));
-
-// next/link → plain anchor (no router behavior in jsdom).
-vi.mock("next/link", () => ({
- default: ({
- href,
- children,
- ...rest
- }: {
- href: string;
- children: React.ReactNode;
- }) => (
- <a href={href} {...rest}>
- {children}
- </a>
- ),
-}));
-
-// ── server actions --------------------------------------------------------
-const cancelTaskMock = vi.fn();
-vi.mock("@/server/actions/tasks", () => ({
- cancelTaskAction: (...a: unknown[]) => cancelTaskMock(...a),
- // StartAllTasksButton imports this too — give it a benign default.
- startAllProposedTasksAction: vi.fn().mockResolvedValue({
- ok: true,
- data: { started: 0, task_ids: [] },
- }),
-}));
-
-// ── sonner toasts ---------------------------------------------------------
-const toastMocks = { success: vi.fn(), error: vi.fn(), info: vi.fn() };
-vi.mock("sonner", () => ({
- toast: {
- success: (...a: unknown[]) => toastMocks.success(...a),
- error: (...a: unknown[]) => toastMocks.error(...a),
- info: (...a: unknown[]) => toastMocks.info(...a),
- },
-}));
-
-// ── LiveTranscript: heavy fetch / SSE component. Stub to a marker so we
-// can assert it mounts with the right props without dragging in its
-// polling machinery.
-vi.mock("@/components/live-transcript", () => ({
- LiveTranscript: (props: Record<string, unknown>) => (
- <div
- data-testid="live-transcript"
- data-thread={String(props.threadId)}
- data-disabled={String(props.composerDisabled)}
- >
- {/* Render the leading slot so brief-card assertions see it the way
- the real transcript mounts it at the top of the scroll log. */}
- {props.leadingContent as React.ReactNode}
- LiveTranscript stub
- </div>
- ),
-}));
-
-import { AgentTaskWorkspace } from "./agent-task-workspace";
-import type { Task } from "@/types";
-
-function makeTask(overrides: Partial<Task> = {}): Task {
- return {
- id: "uuid-1",
- display_id: "demo-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- title: "Set up daily anomaly check",
- brief: "Detect daily spend anomalies",
- success_criteria: "Send slack alert on 3σ deviation",
- deadline_iso: null,
- status: "proposed",
- result_json: null,
- 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,
- };
-}
-
-function baseProps(overrides: Partial<Parameters<typeof AgentTaskWorkspace>[0]> = {}) {
- return {
- projectSlug: "demo",
- agentSlug: "google-ads",
- agentFullId: "demo-google-ads",
- agentDisplayName: "Google Ads",
- tasks: [] as Task[],
- selected: null,
- proposedCount: 0,
- ...overrides,
- };
-}
-
-beforeEach(() => {
- replaceMock.mockReset();
- refreshMock.mockReset();
- cancelTaskMock.mockReset();
- toastMocks.success.mockReset();
- toastMocks.error.mockReset();
- toastMocks.info.mockReset();
- searchParamsState.qs = "";
-});
-
-describe("AgentTaskWorkspace empty state", () => {
- it("shows the empty rail message when tasks is empty", () => {
- render(<AgentTaskWorkspace {...baseProps()} />);
- expect(screen.getByText("The CMO will delegate tasks here.")).toBeInTheDocument();
- // Right pane empty state for hasTasks=false.
- expect(screen.getByText(/Google Ads has no tasks yet/)).toBeInTheDocument();
- });
-
- it("renders the 'Select a task' right-pane state when tasks exist but none selected", () => {
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [makeTask({ status: "done" })],
- })}
- />,
- );
- expect(screen.getByText("Select a task")).toBeInTheDocument();
- expect(screen.getByText(/Pick one from the left/)).toBeInTheDocument();
- });
-});
-
-describe("AgentTaskWorkspace StartAllTasksButton", () => {
- it("hides the start-all button when proposedCount=0", () => {
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [
- makeTask({ id: "a", display_id: "demo-1", status: "working" }),
- makeTask({ id: "c", display_id: "demo-3", status: "done" }),
- ],
- proposedCount: 0,
- })}
- />,
- );
- expect(screen.queryByRole("button", { name: /Start all/ })).not.toBeInTheDocument();
- });
-
- it("renders the StartAllTasksButton when proposedCount > 0", () => {
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [makeTask({ status: "proposed" })],
- proposedCount: 1,
- })}
- />,
- );
- expect(screen.getByRole("button", { name: /Start all 1 task/ })).toBeInTheDocument();
- });
-});
-
-describe("AgentTaskWorkspace task list", () => {
- it("renders one flat list — no status group headers", () => {
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [
- makeTask({ id: "1", display_id: "demo-1", status: "working", title: "one" }),
- makeTask({ id: "2", display_id: "demo-2", status: "proposed", title: "two" }),
- makeTask({ id: "3", display_id: "demo-3", status: "done", title: "three" }),
- makeTask({ id: "4", display_id: "demo-4", status: "failed", title: "four", error_message: "boom" }),
- ],
- })}
- />,
- );
- // All four rows render in a single list without section labels.
- expect(screen.getAllByRole("listitem")).toHaveLength(4);
- for (const label of ["Working", "Proposed", "Done", "Failed"]) {
- expect(screen.queryByText(label)).not.toBeInTheDocument();
- }
- // Failed task still surfaces the error message in the row.
- expect(screen.getByText("boom")).toBeInTheDocument();
- });
-
- it("shows the red attention badge on rows whose task waits on the user", () => {
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [
- makeTask({ id: "b1", display_id: "demo-1", status: "blocked", title: "needs me" }),
- makeTask({ id: "ok", display_id: "demo-2", status: "working", title: "fine" }),
- ],
- attentionByTask: { b1: 2 },
- })}
- />,
- );
- expect(screen.getByLabelText("2 waiting on your answer")).toBeInTheDocument();
- // The badge sits inside the row of the blocked task, not the other one.
- expect(
- screen.getByText("needs me").closest("button"),
- ).toContainElement(screen.getByLabelText("2 waiting on your answer"));
- });
-
- it("falls back to a brief excerpt when task.title is null", () => {
- const brief = "This is a fallback brief shown when the task has no title field at all and we need text.";
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [makeTask({ title: null, brief })],
- })}
- />,
- );
- expect(screen.getByText(brief.slice(0, 160))).toBeInTheDocument();
- });
-
- it("clicking a task row calls router.replace with the display_id as ?task=", () => {
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [makeTask({ display_id: "demo-7", status: "proposed" })],
- })}
- />,
- );
- fireEvent.click(screen.getByText("Set up daily anomaly check"));
- expect(replaceMock).toHaveBeenCalledTimes(1);
- expect(replaceMock).toHaveBeenCalledWith(
- "?task=demo-7",
- { scroll: false },
- );
- });
-
- it("marks selected row via aria-current when ?task= matches display_id", () => {
- searchParamsState.qs = "task=demo-9";
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [
- makeTask({ id: "x", display_id: "demo-9", status: "proposed", title: "alpha" }),
- makeTask({ id: "y", display_id: "demo-10", status: "proposed", title: "beta" }),
- ],
- })}
- />,
- );
- const alphaBtn = screen.getByText("alpha").closest("button");
- const betaBtn = screen.getByText("beta").closest("button");
- expect(alphaBtn).toHaveAttribute("aria-current", "true");
- expect(betaBtn).not.toHaveAttribute("aria-current");
- });
-});
-
-describe("AgentTaskWorkspace selected-task panel", () => {
- it("renders title, display_id, status badge, and the live transcript stub", () => {
- const task = makeTask({
- display_id: "demo-42",
- title: "Audit yesterday's spend",
- status: "working",
- });
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [task],
- selected: {
- task,
- threadId: "thr-1",
- sessionKey: "agent:demo-google-ads:thr-1",
- initialEvents: [],
- initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
- },
- })}
- />,
- );
- expect(screen.getAllByText("DEMO-42").length).toBeGreaterThan(0);
- expect(screen.getAllByText("Audit yesterday's spend").length).toBeGreaterThan(0);
- expect(screen.getAllByText("working").length).toBeGreaterThan(0);
- const stub = screen.getByTestId("live-transcript");
- expect(stub.getAttribute("data-thread")).toBe("thr-1");
- expect(stub.getAttribute("data-disabled")).toBe("true");
- });
-
- it("renders '(untitled task)' fallback when selected task title is null", () => {
- const task = makeTask({ title: null });
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [task],
- selected: {
- task,
- threadId: "thr-1",
- sessionKey: "agent:demo-google-ads:thr-1",
- initialEvents: [],
- initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
- },
- })}
- />,
- );
- expect(screen.getByText("(untitled task)")).toBeInTheDocument();
- });
-
- it("renders the always-expanded brief card (with success criteria) inside the transcript", () => {
- const task = makeTask({
- brief: "Brief body text",
- success_criteria: "Success criteria text",
- status: "done",
- });
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [task],
- selected: {
- task,
- threadId: "thr-1",
- sessionKey: "k",
- initialEvents: [],
- initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
- },
- })}
- />,
- );
- expect(screen.getByText(/Brief body text/)).toBeInTheDocument();
- expect(screen.getByText("Success criteria")).toBeInTheDocument();
- expect(screen.getByText(/Success criteria text/)).toBeInTheDocument();
- });
-
- it("does not render the Cancel button on terminal-status tasks", () => {
- const task = makeTask({ status: "done" });
- render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [task],
- selected: {
- task,
- threadId: "thr-1",
- sessionKey: "k",
- initialEvents: [],
- initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
- },
- })}
- />,
- );
- expect(screen.queryByRole("button", { name: /Cancel/ })).not.toBeInTheDocument();
- });
-});
-
-describe("AgentTaskWorkspace CancelTaskButton", () => {
- function renderWithRunningSelected() {
- const task = makeTask({ display_id: "demo-77", status: "working" });
- return render(
- <AgentTaskWorkspace
- {...baseProps({
- tasks: [task],
- selected: {
- task,
- threadId: "thr",
- sessionKey: "k",
- initialEvents: [],
- initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
- },
- })}
- />,
- );
- }
-
- it("first click toggles to confirm state without calling the action", () => {
- renderWithRunningSelected();
- const btn = screen.getByRole("button", { name: /Cancel/ });
- fireEvent.click(btn);
- expect(screen.getByRole("button", { name: /Click again to cancel/ })).toBeInTheDocument();
- expect(cancelTaskMock).not.toHaveBeenCalled();
- });
-
- it("second click calls cancelTaskAction with display_id and refreshes on success", async () => {
- cancelTaskMock.mockResolvedValue({ ok: true });
- renderWithRunningSelected();
- fireEvent.click(screen.getByRole("button", { name: /Cancel/ }));
- fireEvent.click(screen.getByRole("button", { name: /Click again to cancel/ }));
- await waitFor(() => {
- expect(cancelTaskMock).toHaveBeenCalledWith("demo-77");
- expect(toastMocks.success).toHaveBeenCalledWith("Task cancelled.");
- expect(refreshMock).toHaveBeenCalled();
- });
- });
-
- it("surfaces server error via toast and resets the confirm state", async () => {
- cancelTaskMock.mockResolvedValue({ ok: false, error: "nope" });
- renderWithRunningSelected();
- fireEvent.click(screen.getByRole("button", { name: /Cancel/ }));
- fireEvent.click(screen.getByRole("button", { name: /Click again to cancel/ }));
- await waitFor(() => {
- expect(toastMocks.error).toHaveBeenCalledWith("nope");
- });
- expect(refreshMock).not.toHaveBeenCalled();
- // Confirm state cleared.
- await waitFor(() => {
- expect(screen.getByRole("button", { name: /Cancel/ })).toBeInTheDocument();
- });
- });
-});
diff --git a/notfair-cmo/src/components/agent-task-workspace.tsx b/notfair-cmo/src/components/agent-task-workspace.tsx
deleted file mode 100644
index a8d2330c..00000000
--- a/notfair-cmo/src/components/agent-task-workspace.tsx
+++ /dev/null
@@ -1,730 +0,0 @@
-"use client";
-
-import { startTransition, useCallback, useMemo, useState, useTransition } from "react";
-import { useRouter, useSearchParams } from "next/navigation";
-import {
- CheckCircle2,
- Circle,
- CircleDot,
- Loader2,
- StopCircle,
- XCircle,
-} from "lucide-react";
-import { toast } from "sonner";
-
-import { ApprovalCard } from "@/components/approval-card";
-import { QuestionCard } from "@/components/question-card";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
-import { LiveTranscript, type McpCatalogEntryLite } from "@/components/live-transcript";
-import { Markdown } from "@/components/markdown";
-import { RunningDot } from "@/components/running-dot";
-import { StartAllTasksButton } from "@/components/start-all-tasks-button";
-import {
- cancelTaskAction,
- markTaskDoneAction,
- resumeBlockedTaskAction,
-} from "@/server/actions/tasks";
-import { cn } from "@/lib/utils";
-import { projectHref } from "@/lib/project-href";
-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
-import type { Approval, Question, Task, TaskStatus } from "@/types";
-
-const TASK_IN_FLIGHT: TaskStatus[] = ["proposed", "approved", "working", "blocked"];
-
-// Composer is locked only while the agent is actively running. `blocked`
-// is dormant by design (waiting on approval or an upstream task) — the
-// user must be able to type into it to give context, answer a question
-// the agent posed, or steer the next attempt. Approve/Deny on the
-// ApprovalCard remains the canonical way to resolve the block; the
-// composer is a parallel channel for free-form direction.
-const COMPOSER_LOCKED: TaskStatus[] = ["proposed", "approved", "working"];
-
-const STATUS_VARIANT: Record<
- TaskStatus,
- "default" | "secondary" | "outline" | "destructive"
-> = {
- proposed: "outline",
- approved: "secondary",
- working: "default",
- blocked: "secondary",
- done: "secondary",
- failed: "destructive",
- cancelled: "outline",
-};
-
-type SelectedTaskBundle = {
- task: Task;
- threadId: string;
- sessionKey: string;
- initialEvents: TranscriptEvent[];
- initialByteOffset: number;
- /** Approvals attached to this task, newest first. Rendered above the
- * transcript so the user can act on a pending one without leaving the chat. */
- approvals: Approval[];
- /** Questions attached to this task, newest first. Pending ones render
- * as a QuestionCard above the transcript. */
- questions: Question[];
- /**
- * Set when this task is still in `proposed` and the workspace should
- * auto-fire the kickoff via /api/chat on mount. Null once the task has
- * been claimed (working / done / etc.) so a reload doesn't re-send.
- */
- kickoff: { taskId: string; message: string } | null;
-};
-
-type Props = {
- projectSlug: string;
- agentSlug: string;
- agentFullId: string;
- agentDisplayName: string;
- tasks: Task[];
- selected: SelectedTaskBundle | null;
- proposedCount: number;
- /** task_id → count of pending questions/approvals waiting on the user.
- * Rows in the rail show the Slack-style red badge when > 0. */
- attentionByTask?: Record<string, number>;
- /** Composer model choices for this project's harness — forwarded to
- * LiveTranscript's selector. */
- modelOptions?: Array<{ value: string; label: string }>;
- /** MCP catalog forwarded to the per-task LiveTranscript so tool calls
- * that resolve to an MCP server render the server's brand favicon. */
- mcpCatalog?: McpCatalogEntryLite[];
-};
-
-export function AgentTaskWorkspace({
- projectSlug,
- agentSlug,
- agentFullId,
- agentDisplayName,
- tasks,
- selected,
- proposedCount,
- attentionByTask = {},
- mcpCatalog,
- modelOptions,
-}: Props) {
- const router = useRouter();
- const search = useSearchParams();
- const selectedId = search.get("task");
-
- // Resolve blocker → blocker task. Used by TaskRow to show a
- // "Waiting on <display_id>" subline on tasks blocked by an upstream
- // task (vs. tasks blocked by an approval). Internal-only — only the
- // sidebar list needs this; the chat-side blockedReason is computed
- // separately further below.
- const taskById = useMemo(() => {
- const m = new Map<string, Task>();
- for (const t of tasks) m.set(t.id, t);
- return m;
- }, [tasks]);
-
- const totalCount = tasks.length;
-
- function selectTask(displayId: string) {
- const params = new URLSearchParams(search?.toString() ?? "");
- params.set("task", displayId);
- router.replace(`?${params.toString()}`, { scroll: false });
- }
-
- return (
- <div className="flex h-full min-h-0">
- {/* Background liveness polling is handled at the sidebar level
- (GlobalLivenessPoller) so it covers every route, not just this
- workspace. The per-thread LiveTranscript polling still handles
- the open transcript. */}
- {/* ── Left pane: task list ─────────────────────────────────────── */}
- <aside className="flex w-72 shrink-0 flex-col bg-[hsl(var(--notfair-sidebar))]">
- {proposedCount > 0 && (
- <div className="px-4 py-3">
- <StartAllTasksButton
- agentId={agentFullId}
- proposedCount={proposedCount}
- />
- </div>
- )}
-
- <div className="min-h-0 flex-1 overflow-y-auto py-1">
- {totalCount === 0 ? (
- <div className="px-4 py-8 text-center text-xs text-muted-foreground">
- The CMO will delegate tasks here.
- </div>
- ) : (
- /* gap-1 matches SidebarMenu's item spacing so the task rail
- reads like the agent list. */
- <ul className="flex flex-col gap-1">
- {tasks.map((t) => (
- <li key={t.id}>
- <TaskRow
- task={t}
- blocker={
- t.blocked_by_task_id
- ? taskById.get(t.blocked_by_task_id)
- : undefined
- }
- attentionCount={attentionByTask[t.id] ?? 0}
- selected={
- t.display_id === selectedId || t.id === selectedId
- }
- onSelect={() => selectTask(t.display_id)}
- />
- </li>
- ))}
- </ul>
- )}
- </div>
- </aside>
-
- {/* ── Right pane: brief header + live transcript ───────────────── */}
- <section className="flex min-w-0 flex-1 flex-col">
- {selected ? (
- <>
- <header className="bg-background/60 backdrop-blur">
- <div className="mx-auto w-full max-w-3xl px-6 py-3">
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0 flex-1">
- <div className="text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
- <span className="font-mono">{selected.task.display_id.toUpperCase()}</span>
- </div>
- <h1 className="mt-0.5 text-base font-semibold tracking-tight truncate">
- {selected.task.title ?? "(untitled task)"}
- </h1>
- </div>
- <div className="flex shrink-0 items-center gap-2">
- {(selected.task.status === "working" ||
- selected.task.status === "proposed" ||
- selected.task.status === "approved") && (
- <>
- <RunningDot size="md" />
- <CancelTaskButton
- taskDisplayId={selected.task.display_id}
- />
- </>
- )}
- <Badge
- variant={STATUS_VARIANT[selected.task.status]}
- className="text-[10px]"
- >
- {selected.task.status}
- </Badge>
- </div>
- </div>
- </div>
- </header>
-
- <div className="min-h-0 flex-1">
- <SelectedTaskPanel
- selected={selected}
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- agentDisplayName={agentDisplayName}
- taskById={taskById}
- mcpCatalog={mcpCatalog}
- modelOptions={modelOptions}
- />
- </div>
- </>
- ) : (
- <EmptyRightPane
- agentDisplayName={agentDisplayName}
- hasTasks={totalCount > 0}
- />
- )}
- </section>
- </div>
- );
-}
-
-function SelectedTaskPanel({
- selected,
- projectSlug,
- agentSlug,
- agentDisplayName,
- taskById,
- mcpCatalog,
- modelOptions,
-}: {
- selected: SelectedTaskBundle;
- projectSlug: string;
- agentSlug: string;
- agentDisplayName: string;
- taskById: Map<string, Task>;
- mcpCatalog?: McpCatalogEntryLite[];
- modelOptions?: Array<{ value: string; label: string }>;
-}) {
- const router = useRouter();
- const isInFlight = TASK_IN_FLIGHT.includes(selected.task.status);
- const composerLocked = COMPOSER_LOCKED.includes(selected.task.status);
- // We refresh the server tree on every in-flight poll so the status
- // badge + sidebar in-flight counters track the DB even when nothing
- // has landed in the JSONL transcript yet.
- //
- // Why: OpenClaw doesn't flush session.jsonl until session.ended —
- // and even after the task flips to `done` in our DB, the flush can
- // land seconds or minutes later (and isn't guaranteed at all if the
- // user opens the task page after-the-fact). Auto-stopping polling
- // on terminal status meant the transcript stayed blank until a
- // manual refresh; even a generous grace window can't cover a flush
- // that happens after the user navigates in.
- //
- // Resolution: never auto-stop polling. Cost is cheap (one HTTP fetch
- // every 2 s while the user is on this page), and the unmount/effect
- // cleanup tears the timer down the moment they navigate away.
- const onPolled = useCallback(
- ({ newEvents }: { newEvents: number; fileSize: number }) => {
- void newEvents;
- // Mark as a transition so React keeps the rendered tree alive while
- // the new RSC payload streams in — prevents the sidebar (and any
- // sibling subtree) from flickering on every transcript tick.
- if (isInFlight) startTransition(() => router.refresh());
- // Never returns true → polling continues for the lifetime of the
- // mounted page.
- return false;
- },
- [isInFlight, router],
- );
- // Surface the actionable approval up front so the user doesn't have to
- // navigate to /approvals to unblock the agent. Resolved rows would only
- // add noise here, so they're filtered out — the audit trail lives on the
- // dedicated Resolved tab. Most blocked tasks have exactly one pending
- // request at a time; render whichever's actionable, plus any
- // revision_requested that's still in play.
- const liveApprovals = selected.approvals.filter(
- (a) => a.status === "pending" || a.status === "revision_requested",
- );
- const openQuestions = selected.questions.filter(
- (q) => q.status === "pending",
- );
- // When the task is parked in `blocked`, build a short "why" string so
- // the LiveTranscript can replace its forward-motion indicator
- // ("thinking…", "wrapping up…") with an honest paused-state pill.
- // Three distinct reasons: (a) question pending (b) approval pending
- // (c) gated on another task.
- // Specific blocked sub-state: the agent's turn ended without it calling
- // submit_task_status, so the task is parked with no upstream blocker,
- // no question, and no approval. The error_message carries our marker.
- // Surfaces a dedicated recovery card with Resume / Mark done buttons.
- const isAbandoned =
- selected.task.status === "blocked" &&
- !selected.task.blocked_by_task_id &&
- openQuestions.length === 0 &&
- liveApprovals.length === 0 &&
- (selected.task.error_message?.includes("submit_task_status") ?? false);
-
- let blockedReason: string | undefined;
- if (selected.task.status === "blocked") {
- if (selected.task.blocked_by_task_id) {
- const blocker = taskById.get(selected.task.blocked_by_task_id);
- blockedReason = blocker
- ? `waiting on ${blocker.display_id.toUpperCase()}`
- : "waiting on an upstream task";
- } else if (openQuestions.length > 0) {
- blockedReason =
- openQuestions.length === 1
- ? "waiting on your answer"
- : `waiting on ${openQuestions.length} answers`;
- } else if (liveApprovals.length > 0) {
- blockedReason =
- liveApprovals.length === 1
- ? "waiting on approval"
- : `waiting on ${liveApprovals.length} approvals`;
- } else if (isAbandoned) {
- // Recovery card above the transcript already explains the state and
- // surfaces the action buttons; suppressing the in-transcript pill
- // avoids two pieces of UI saying the same thing in slightly
- // different ways.
- blockedReason = undefined;
- } else {
- blockedReason = "waiting for the gating condition to resolve";
- }
- }
- return (
- <div className="flex h-full min-h-0 flex-col">
- {(openQuestions.length > 0 || liveApprovals.length > 0 || isAbandoned) && (
- <div className="mx-auto w-full max-w-3xl space-y-3 px-6 pt-4">
- {openQuestions.map((q) => (
- <QuestionCard
- key={q.id}
- question={q}
- options={parseOptionsJson(q.options_json)}
- />
- ))}
- {liveApprovals.map((a) => (
- <ApprovalCard key={a.id} approval={a} />
- ))}
- {isAbandoned && (
- <AbandonedTaskCard
- taskDisplayId={selected.task.display_id}
- />
- )}
- </div>
- )}
- <div className="min-h-0 flex-1">
- <LiveTranscript
- key={selected.task.id}
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- agentDisplayName={agentDisplayName}
- threadId={selected.threadId}
- sessionKey={selected.sessionKey}
- initialEvents={selected.initialEvents}
- initialByteOffset={selected.initialByteOffset}
- composerDisabled={composerLocked}
- blockedReason={blockedReason}
- onPolled={onPolled}
- autoKickoff={selected.kickoff !== null}
- kickoffMessage={selected.kickoff?.message}
- taskId={selected.kickoff?.taskId}
- mcpCatalog={mcpCatalog}
- modelOptions={modelOptions}
- // The brief lives INSIDE the scrollable history: scroll to the
- // top of the conversation and the full brief card is there,
- // always expanded — it no longer eats header space.
- leadingContent={<TaskBriefCard task={selected.task} />}
- />
- </div>
- </div>
- );
-}
-
-/**
- * Fully-expanded brief card rendered as the first item of the task's
- * chat history (via LiveTranscript's leadingContent). Scrolling the
- * conversation to the top reveals the whole brief — no <details>
- * toggle, no max-height clamp.
- */
-function TaskBriefCard({ task }: { task: Task }) {
- return (
- <section
- aria-label="Task brief"
- className="mb-6 rounded-xl border border-border/60 bg-card p-4 shadow-[var(--notfair-shadow-sm)]"
- >
- <div className="mb-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
- Brief
- </div>
- <div className="text-sm text-muted-foreground">
- <Markdown>{task.brief}</Markdown>
- </div>
- {task.success_criteria && (
- <div className="mt-4">
- <div className="mb-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
- Success criteria
- </div>
- <div className="text-sm text-muted-foreground">
- <Markdown>{task.success_criteria}</Markdown>
- </div>
- </div>
- )}
- </section>
- );
-}
-
-function CancelTaskButton({ taskDisplayId }: { taskDisplayId: string }) {
- const router = useRouter();
- const [pending, startTransition] = useTransition();
- const [confirming, setConfirming] = useState(false);
- function onClick() {
- if (!confirming) {
- setConfirming(true);
- // Auto-clear the confirm prompt after a few seconds so the button
- // doesn't sit in a scary "click again to cancel" state forever.
- setTimeout(() => setConfirming(false), 3000);
- return;
- }
- startTransition(async () => {
- const r = await cancelTaskAction(taskDisplayId);
- if (!r.ok) {
- toast.error(r.error);
- setConfirming(false);
- return;
- }
- toast.success("Task cancelled.");
- setConfirming(false);
- router.refresh();
- });
- }
- return (
- <Button
- type="button"
- variant={confirming ? "destructive" : "outline"}
- size="sm"
- disabled={pending}
- onClick={onClick}
- className="h-7 px-2 text-[11px]"
- >
- {pending ? (
- <Loader2 className="size-3 animate-spin" />
- ) : (
- <StopCircle className="size-3" />
- )}
- {confirming ? "Click again to cancel" : "Cancel"}
- </Button>
- );
-}
-
-function TaskRow({
- task,
- blocker,
- attentionCount = 0,
- selected,
- onSelect,
-}: {
- task: Task;
- /** When this task is blocked by another task, the blocker (for the
- * "Waiting on <id>" subline). Undefined for approval-blocked tasks. */
- blocker?: Task;
- /** Pending questions/approvals on this task waiting on the user —
- * renders the Slack-style red badge when > 0. */
- attentionCount?: number;
- selected: boolean;
- onSelect: () => void;
-}) {
- const isRunning = task.status === "working";
- return (
- <button
- type="button"
- onClick={onSelect}
- aria-current={selected ? "true" : undefined}
- className={cn(
- // Mirror the sidebar's SidebarMenuButton look (rounded-md, inset,
- // sidebar-accent fill on hover/selected) so picking a task reads
- // the same as picking an agent.
- "group mx-2 block w-[calc(100%-1rem)] rounded-md px-2.5 py-2 text-left transition-colors",
- "hover:bg-sidebar-accent focus-visible:outline-none focus-visible:bg-sidebar-accent",
- selected && "bg-sidebar-accent",
- )}
- >
- {/* Line 1: glyph + task id (+ red badge). Line 2: title, clamped to
- two rows with an ellipsis so long briefs never overflow the rail. */}
- <div className="flex items-center gap-2.5">
- <span className="flex size-3.5 shrink-0 items-center justify-center">
- {isRunning ? (
- <RunningDot size="md" aria-label="Running" />
- ) : (
- <StatusGlyph status={task.status} />
- )}
- </span>
- <span className="min-w-0 flex-1 truncate font-mono text-[10px] font-medium text-muted-foreground tabular-nums">
- {task.display_id.toUpperCase()}
- </span>
- {attentionCount > 0 && (
- <span
- role="status"
- aria-label={`${attentionCount} waiting on your answer`}
- className="inline-flex h-[18px] min-w-[18px] shrink-0 items-center justify-center rounded-full bg-[hsl(var(--destructive))] px-1 text-[10px] font-semibold tabular-nums leading-none text-white"
- >
- {attentionCount}
- </span>
- )}
- </div>
- <div
- className={cn(
- // leading-4 (1rem) × 2 lines = min-h-8: one-line titles reserve
- // the second line's space so every row is the same height.
- // Unselected rows use the same text tone as chat-rail rows —
- // terminal tasks are no longer dimmed (the glyph carries status).
- "ml-6 mt-0.5 line-clamp-2 min-h-8 text-xs leading-4",
- selected ? "font-medium text-foreground" : "text-foreground/90",
- )}
- >
- {task.title ?? task.brief.slice(0, 160)}
- </div>
- {task.status === "failed" && task.error_message && (
- <div className="ml-6 mt-1 line-clamp-1 text-[10px] text-destructive/80">
- {task.error_message}
- </div>
- )}
- {task.status === "blocked" && (
- <div className="ml-6 mt-1 line-clamp-1 text-[10px] text-muted-foreground">
- {blocker ? (
- <>
- Waiting on{" "}
- <span className="font-mono tabular-nums">
- {blocker.display_id.toUpperCase()}
- </span>
- </>
- ) : (
- "Waiting on approval"
- )}
- </div>
- )}
- </button>
- );
-}
-
-function StatusGlyph({ status }: { status: TaskStatus }) {
- switch (status) {
- case "done":
- return <CheckCircle2 className="size-3.5 text-[hsl(var(--notfair-accent))]" />;
- case "failed":
- return <XCircle className="size-3.5 text-destructive" />;
- case "cancelled":
- return <Circle className="size-3.5 text-muted-foreground" />;
- case "approved":
- return <CircleDot className="size-3.5 text-sky-600" />;
- case "working":
- return <Loader2 className="size-3.5 animate-spin text-sky-600" />;
- case "blocked":
- return <CircleDot className="size-3.5 text-[hsl(var(--notfair-warn))]" />;
- case "proposed":
- default:
- return <Circle className="size-3.5 text-muted-foreground" />;
- }
-}
-
-function EmptyRightPane({
- agentDisplayName,
- hasTasks,
-}: {
- agentDisplayName: string;
- hasTasks: boolean;
-}) {
- return (
- <div className="flex h-full flex-col items-center justify-center px-6 text-center">
- <div className="space-y-2 max-w-sm">
- <h3 className="text-sm font-medium">
- {hasTasks ? "Select a task" : `${agentDisplayName} has no tasks yet`}
- </h3>
- <p className="text-xs text-muted-foreground">
- {hasTasks
- ? "Pick one from the left to see its brief and live transcript."
- : "When the CMO delegates work to this specialist, tasks will land here. Open the CMO and ask it to plan the next move."}
- </p>
- </div>
- </div>
- );
-}
-
-/** Parse Question.options_json into a string[] in a client-safe way.
- * Mirrors @/server/db/questions#parseQuestionOptions but avoids importing
- * the server module from a client component. */
-function parseOptionsJson(json: string): string[] {
- try {
- const parsed = JSON.parse(json);
- if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) {
- return parsed;
- }
- } catch {
- // fall through
- }
- return [];
-}
-
-/**
- * Recovery card for the specific blocked sub-state where the agent's
- * turn ended without it calling submit_task_status. Surfaces three
- * actions so the user always knows what to do:
- *
- * - Resume: flip the task back to `proposed` and re-fire the kickoff.
- * The prior transcript stays intact; the agent picks up where it
- * stopped.
- * - Mark done: close the task manually (e.g. the agent did the work
- * in its last reply but just forgot the closing tool call).
- * - Cancel: drop the task entirely.
- *
- * Without this card, an abandoned task showed only a generic "Paused"
- * pill and the user had no obvious way to act on it.
- */
-function AbandonedTaskCard({ taskDisplayId }: { taskDisplayId: string }) {
- const router = useRouter();
- const [resumePending, startResume] = useTransition();
- const [donePending, startDone] = useTransition();
- const [cancelPending, startCancel] = useTransition();
-
- function onResume() {
- startResume(async () => {
- const r = await resumeBlockedTaskAction(taskDisplayId);
- if (!r.ok) {
- toast.error(r.error);
- return;
- }
- toast.success("Resuming — the agent will pick up from where it stopped.");
- router.refresh();
- });
- }
- function onDone() {
- startDone(async () => {
- const r = await markTaskDoneAction(taskDisplayId);
- if (!r.ok) {
- toast.error(r.error);
- return;
- }
- toast.success("Marked done.");
- router.refresh();
- });
- }
- function onCancel() {
- startCancel(async () => {
- const r = await cancelTaskAction(taskDisplayId);
- if (!r.ok) {
- toast.error(r.error);
- return;
- }
- toast.success("Cancelled.");
- router.refresh();
- });
- }
-
- const anyPending = resumePending || donePending || cancelPending;
-
- return (
- <div className="rounded-lg bg-[hsl(var(--notfair-warn-soft))] p-4">
- <div className="flex items-start gap-3">
- <StopCircle className="mt-0.5 size-4 shrink-0 text-[hsl(var(--notfair-warn))]" />
- <div className="min-w-0 flex-1 space-y-2">
- <div>
- <p className="text-sm font-medium text-foreground">
- Agent stopped without closing this task
- </p>
- <p className="mt-0.5 text-xs text-[hsl(var(--notfair-ink-3))]">
- The last turn finished cleanly but the agent didn’t call
- <code className="mx-1 rounded bg-amber-500/15 px-1 py-0.5 font-mono text-[11px]">
- submit_task_status
- </code>
- . Pick how to recover:
- </p>
- </div>
- <div className="flex flex-wrap gap-2">
- <Button
- size="sm"
- variant="default"
- onClick={onResume}
- disabled={anyPending}
- >
- {resumePending ? (
- <Loader2 className="mr-1.5 size-3.5 animate-spin" />
- ) : null}
- Resume
- </Button>
- <Button
- size="sm"
- variant="outline"
- onClick={onDone}
- disabled={anyPending}
- >
- {donePending ? (
- <Loader2 className="mr-1.5 size-3.5 animate-spin" />
- ) : (
- <CheckCircle2 className="mr-1.5 size-3.5" />
- )}
- Mark done
- </Button>
- <Button
- size="sm"
- variant="outline"
- onClick={onCancel}
- disabled={anyPending}
- >
- {cancelPending ? (
- <Loader2 className="mr-1.5 size-3.5 animate-spin" />
- ) : (
- <XCircle className="mr-1.5 size-3.5" />
- )}
- Cancel
- </Button>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/notfair-cmo/src/components/approval-card.test.tsx b/notfair-cmo/src/components/approval-card.test.tsx
deleted file mode 100644
index 5ad264b8..00000000
--- a/notfair-cmo/src/components/approval-card.test.tsx
+++ /dev/null
@@ -1,234 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
-
-const approveMock = vi.fn();
-const rejectMock = vi.fn();
-const createPolicyMock = vi.fn();
-const toastErrorMock = vi.fn();
-const toastSuccessMock = vi.fn();
-
-vi.mock("@/server/actions/approvals", () => ({
- approveAction: (...a: unknown[]) => approveMock(...a),
- rejectAction: (...a: unknown[]) => rejectMock(...a),
- createPolicyAction: (...a: unknown[]) => createPolicyMock(...a),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- error: (...a: unknown[]) => toastErrorMock(...a),
- success: (...a: unknown[]) => toastSuccessMock(...a),
- },
-}));
-
-import { ApprovalCard } from "./approval-card";
-import type { Approval } from "@/types";
-
-function makeApproval(overrides: Partial<Approval> = {}): Approval {
- return {
- id: "ap-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- task_id: null,
- action_summary: "Raise CPC bid on /signup keyword",
- action_type: "bid_change",
- cost_estimate_usd: 12.5,
- reasoning: null,
- payload_json: "{}",
- status: "pending",
- decision_note: null,
- decided_by_kind: null,
- decided_by_id: null,
- created_at: new Date(Date.now() - 90_000).toISOString(),
- resolved_at: null,
- ...overrides,
- };
-}
-
-beforeEach(() => {
- approveMock.mockReset();
- rejectMock.mockReset();
- createPolicyMock.mockReset();
- toastErrorMock.mockReset();
- toastSuccessMock.mockReset();
-});
-
-describe("ApprovalCard — header & metadata", () => {
- it("renders summary, action-type label, status pill, cost, agent, timestamp", () => {
- render(<ApprovalCard approval={makeApproval()} />);
- expect(screen.getByText("Raise CPC bid on /signup keyword")).toBeInTheDocument();
- expect(screen.getByText("Bid change")).toBeInTheDocument();
- expect(screen.getByText("Pending")).toBeInTheDocument();
- expect(screen.getByText("$12.50")).toBeInTheDocument();
- expect(screen.getByText("demo-google-ads")).toBeInTheDocument();
- expect(screen.getByText(/m ago|s ago/)).toBeInTheDocument();
- });
-
- it("hides the cost line when cost_estimate_usd is zero", () => {
- render(<ApprovalCard approval={makeApproval({ cost_estimate_usd: 0 })} />);
- expect(screen.queryByText(/Cost:/)).not.toBeInTheDocument();
- });
-
- it("renders reasoning inline (no Why? toggle)", () => {
- render(
- <ApprovalCard approval={makeApproval({ reasoning: "Predicted +18% CTR" })} />,
- );
- expect(screen.getByText("Predicted +18% CTR")).toBeInTheDocument();
- // Old "Why?" toggle should be gone.
- expect(screen.queryByRole("button", { name: "Why?" })).not.toBeInTheDocument();
- });
-
- it("does NOT render a thread or comment input (removed in this iteration)", () => {
- render(<ApprovalCard approval={makeApproval()} />);
- expect(screen.queryByPlaceholderText("Add a comment…")).not.toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "Comment" })).not.toBeInTheDocument();
- });
-
- it("shows the 'Auto by policy' badge when decided_by_kind=policy", () => {
- render(
- <ApprovalCard
- approval={makeApproval({
- status: "approved",
- decided_by_kind: "policy",
- decided_by_id: "pol-1",
- resolved_at: new Date().toISOString(),
- })}
- />,
- );
- expect(screen.getByText("Auto by policy")).toBeInTheDocument();
- });
-
- it("sets the region aria-label to action_summary", () => {
- render(<ApprovalCard approval={makeApproval({ action_summary: "X-summary" })} />);
- expect(screen.getByRole("region", { name: "X-summary" })).toBeInTheDocument();
- });
-});
-
-describe("ApprovalCard — approve (one-click)", () => {
- it("calls approveAction with just the id and shows success toast", async () => {
- approveMock.mockResolvedValue({ ok: true });
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Approve" }));
- await waitFor(() => {
- expect(approveMock).toHaveBeenCalledWith("ap-1");
- expect(toastSuccessMock).toHaveBeenCalledWith(
- "Approved — agent is being notified",
- );
- });
- });
-
- it("surfaces server error via toast", async () => {
- approveMock.mockResolvedValue({ ok: false, error: "boom" });
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Approve" }));
- await waitFor(() => {
- expect(toastErrorMock).toHaveBeenCalledWith("boom");
- });
- });
-});
-
-describe("ApprovalCard — Deny modal", () => {
- it("clicking Deny opens the modal but does not call rejectAction yet", () => {
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Deny" }));
- expect(screen.getByText("What do you want to change?")).toBeInTheDocument();
- expect(rejectMock).not.toHaveBeenCalled();
- });
-
- it("'Reject without comments' rejects with no note", async () => {
- rejectMock.mockResolvedValue({ ok: true });
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Deny" }));
- fireEvent.click(
- screen.getByRole("button", { name: "Reject without comments" }),
- );
- await waitFor(() => {
- expect(rejectMock).toHaveBeenCalledWith("ap-1", undefined);
- expect(toastSuccessMock).toHaveBeenCalledWith("Rejected");
- });
- });
-
- it("'Reject with comment' sends the typed note", async () => {
- rejectMock.mockResolvedValue({ ok: true });
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Deny" }));
- fireEvent.change(
- screen.getByPlaceholderText(/Wait until next week/),
- { target: { value: "Hold off until legal review" } },
- );
- fireEvent.click(screen.getByRole("button", { name: "Reject with comment" }));
- await waitFor(() => {
- expect(rejectMock).toHaveBeenCalledWith(
- "ap-1",
- "Hold off until legal review",
- );
- expect(toastSuccessMock).toHaveBeenCalledWith("Rejected with feedback");
- });
- });
-
- it("'Reject with comment' button is disabled until the user types something", () => {
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: "Deny" }));
- const withCommentBtn = screen.getByRole("button", {
- name: "Reject with comment",
- });
- expect(withCommentBtn).toBeDisabled();
- fireEvent.change(
- screen.getByPlaceholderText(/Wait until next week/),
- { target: { value: "x" } },
- );
- expect(withCommentBtn).not.toBeDisabled();
- });
-});
-
-describe("ApprovalCard — Always approve policy", () => {
- it("opens the policy form scoped to this agent by default", () => {
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: /Always approve/ }));
- expect(screen.getByText("Create auto-approval policy")).toBeInTheDocument();
- });
-
- it("Save policy calls createPolicyAction with the right shape", async () => {
- createPolicyMock.mockResolvedValue({ ok: true, policy_id: "pol-1" });
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: /Always approve/ }));
- fireEvent.click(screen.getByRole("button", { name: "Save policy" }));
- await waitFor(() => {
- const payload = createPolicyMock.mock.calls[0]![0]!;
- expect(payload.project_slug).toBe("demo");
- expect(payload.action_type).toBe("bid_change");
- expect(payload.agent_id).toBe("demo-google-ads");
- expect(payload.auto_decision).toBe("approve");
- });
- });
-
- it("scope=any sets agent_id to null", async () => {
- createPolicyMock.mockResolvedValue({ ok: true });
- render(<ApprovalCard approval={makeApproval()} />);
- fireEvent.click(screen.getByRole("button", { name: /Always approve/ }));
- fireEvent.click(screen.getByLabelText(/From any agent/));
- fireEvent.click(screen.getByRole("button", { name: "Save policy" }));
- await waitFor(() => {
- const payload = createPolicyMock.mock.calls[0]![0]!;
- expect(payload.agent_id).toBeNull();
- });
- });
-});
-
-describe("ApprovalCard — resolved state", () => {
- it("hides decision buttons and shows decision_note when resolved", () => {
- render(
- <ApprovalCard
- approval={makeApproval({
- status: "approved",
- decision_note: "Ship it.",
- resolved_at: new Date().toISOString(),
- })}
- />,
- );
- expect(screen.queryByRole("button", { name: "Approve" })).not.toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "Deny" })).not.toBeInTheDocument();
- expect(screen.getByText("Decision note")).toBeInTheDocument();
- expect(screen.getByText("Ship it.")).toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/approval-card.tsx b/notfair-cmo/src/components/approval-card.tsx
deleted file mode 100644
index aa2cfad9..00000000
--- a/notfair-cmo/src/components/approval-card.tsx
+++ /dev/null
@@ -1,303 +0,0 @@
-"use client";
-
-import { useState, useTransition } from "react";
-import { ShieldCheck } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { toast } from "sonner";
-import {
- approveAction,
- createPolicyAction,
- rejectAction,
-} from "@/server/actions/approvals";
-import type { Approval } from "@/types";
-
-const ACTION_TYPE_LABEL: Record<Approval["action_type"], string> = {
- spend: "Spend",
- content_publishing: "Content",
- new_channel: "New channel",
- bid_change: "Bid change",
- audience_change: "Audience",
- other: "Other",
-};
-
-const STATUS_TAG: Record<Approval["status"], { label: string; cls: string }> = {
- pending: { label: "Pending", cls: "ns-tag-accent" },
- revision_requested: { label: "Revision requested", cls: "ns-tag-amber" },
- approved: { label: "Approved", cls: "ns-tag-accent" },
- rejected: { label: "Rejected", cls: "ns-tag-red" },
- expired: { label: "Expired", cls: "ns-tag" },
-};
-
-function formatUsd(n: number) {
- return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
-}
-
-function timeAgo(iso: string) {
- const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
- if (seconds < 60) return `${Math.floor(seconds)}s ago`;
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
- return `${Math.floor(seconds / 86400)}d ago`;
-}
-
-export type ApprovalCardProps = {
- approval: Approval;
-};
-
-export function ApprovalCard({ approval }: ApprovalCardProps) {
- const [denyOpen, setDenyOpen] = useState(false);
- const [denyNote, setDenyNote] = useState("");
- const [showPolicyForm, setShowPolicyForm] = useState(false);
- const [policyCostCap, setPolicyCostCap] = useState("");
- const [policyScope, setPolicyScope] = useState<"agent" | "any">("agent");
- const [pending, start] = useTransition();
-
- const actionable =
- approval.status === "pending" || approval.status === "revision_requested";
- const statusTag = STATUS_TAG[approval.status];
-
- function approve() {
- start(async () => {
- const r = await approveAction(approval.id);
- if (!r.ok) toast.error(r.error ?? "Failed to approve");
- else toast.success("Approved — agent is being notified");
- });
- }
- function rejectWith(note: string | undefined) {
- start(async () => {
- const r = await rejectAction(approval.id, note);
- if (!r.ok) toast.error(r.error ?? "Failed to reject");
- else {
- toast.success(note ? "Rejected with feedback" : "Rejected");
- setDenyOpen(false);
- setDenyNote("");
- }
- });
- }
- function alwaysApprove() {
- start(async () => {
- const cap = policyCostCap.trim();
- const max = cap ? Number(cap) : null;
- if (cap && (!Number.isFinite(max) || max! < 0)) {
- toast.error("Cost cap must be a non-negative number.");
- return;
- }
- const r = await createPolicyAction({
- project_slug: approval.project_slug,
- action_type: approval.action_type,
- agent_id: policyScope === "agent" ? approval.agent_id : null,
- max_cost_usd: max,
- auto_decision: "approve",
- note: `Always approve ${ACTION_TYPE_LABEL[approval.action_type]} requests${
- policyScope === "agent" ? ` from ${approval.agent_id}` : ""
- }${max != null ? ` ≤ ${formatUsd(max)}` : ""}.`,
- });
- if (!r.ok) toast.error(r.error ?? "Failed to save policy");
- else {
- toast.success("Saved. Future matching requests are auto-approved.");
- setShowPolicyForm(false);
- setPolicyCostCap("");
- }
- });
- }
-
- return (
- <>
- <article
- className="ns-card"
- role="region"
- aria-label={approval.action_summary}
- data-status={approval.status}
- >
- <div className="space-y-3 p-[18px]">
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="ns-tag">{ACTION_TYPE_LABEL[approval.action_type]}</span>
- <span className={statusTag.cls}>{statusTag.label}</span>
- {approval.decided_by_kind === "policy" && (
- <span className="ns-tag inline-flex items-center gap-1">
- <ShieldCheck className="size-3" />
- Auto by policy
- </span>
- )}
- </div>
- <p className="m-0 text-[14.5px] font-medium leading-snug text-[hsl(var(--notfair-ink))]">
- {approval.action_summary}
- </p>
- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
- {approval.cost_estimate_usd > 0 && (
- <>
- Cost:{" "}
- <span className="font-medium text-[hsl(var(--notfair-ink-2))]">
- {formatUsd(approval.cost_estimate_usd)}
- </span>{" "}
- ·{" "}
- </>
- )}
- Agent <span className="font-mono">{approval.agent_id}</span> ·{" "}
- {timeAgo(approval.created_at)}
- </p>
-
- {approval.reasoning && (
- <p className="m-0 whitespace-pre-wrap rounded-lg bg-[hsl(var(--notfair-surface-2))] p-3 text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-3))]">
- {approval.reasoning}
- </p>
- )}
-
- {approval.decision_note && !actionable && (
- <div className="rounded-lg bg-[hsl(var(--notfair-surface-2))]/60 p-3 text-[12px]">
- <div className="text-[10px] font-semibold uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">
- Decision note
- </div>
- <p className="mt-1 whitespace-pre-wrap leading-relaxed text-[hsl(var(--notfair-ink-2))]">
- {approval.decision_note}
- </p>
- </div>
- )}
-
- {actionable && (
- <div className="space-y-3 pt-1">
- <div className="flex flex-wrap gap-2">
- <button
- type="button"
- onClick={approve}
- disabled={pending}
- className="ns-btn ns-btn-primary ns-btn-sm"
- >
- Approve
- </button>
- <button
- type="button"
- onClick={() => setDenyOpen(true)}
- disabled={pending}
- className="ns-btn ns-btn-outline ns-btn-sm"
- >
- Deny
- </button>
- <button
- type="button"
- onClick={() => setShowPolicyForm((s) => !s)}
- disabled={pending}
- className="ns-btn ns-btn-ghost ns-btn-sm"
- >
- <ShieldCheck className="size-3.5" />
- Always approve
- </button>
- </div>
-
- {showPolicyForm && (
- <div className="space-y-2 rounded-lg bg-[hsl(var(--notfair-surface-2))]/60 p-3 text-[12px]">
- <p className="m-0 font-semibold text-[hsl(var(--notfair-ink))]">
- Create auto-approval policy
- </p>
- <p className="m-0 text-[hsl(var(--notfair-ink-4))]">
- Future{" "}
- <span className="font-mono">
- {ACTION_TYPE_LABEL[approval.action_type]}
- </span>{" "}
- requests that match will be approved without asking.
- </p>
- <fieldset className="flex flex-wrap items-center gap-3 pt-1">
- <label className="flex items-center gap-1.5">
- <input
- type="radio"
- name={`scope-${approval.id}`}
- checked={policyScope === "agent"}
- onChange={() => setPolicyScope("agent")}
- />
- Only from{" "}
- <span className="font-mono">{approval.agent_id}</span>
- </label>
- <label className="flex items-center gap-1.5">
- <input
- type="radio"
- name={`scope-${approval.id}`}
- checked={policyScope === "any"}
- onChange={() => setPolicyScope("any")}
- />
- From any agent
- </label>
- </fieldset>
- <label className="flex items-center gap-2">
- Cost cap (USD, optional):
- <Input
- type="number"
- min="0"
- step="0.01"
- value={policyCostCap}
- onChange={(e) => setPolicyCostCap(e.target.value)}
- placeholder="∞"
- className="h-7 w-28 text-xs"
- />
- </label>
- <div className="flex gap-2 pt-1">
- <button
- type="button"
- onClick={alwaysApprove}
- disabled={pending}
- className="ns-btn ns-btn-primary ns-btn-sm"
- >
- Save policy
- </button>
- <button
- type="button"
- onClick={() => setShowPolicyForm(false)}
- disabled={pending}
- className="ns-btn ns-btn-ghost ns-btn-sm"
- >
- Cancel
- </button>
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- </article>
-
- <Dialog open={denyOpen} onOpenChange={(open) => !pending && setDenyOpen(open)}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>What do you want to change?</DialogTitle>
- <DialogDescription>
- Optional. Anything you type here is sent back to the agent so it
- can adjust its next attempt.
- </DialogDescription>
- </DialogHeader>
- <textarea
- value={denyNote}
- onChange={(e) => setDenyNote(e.target.value)}
- placeholder="e.g. Wait until next week so we can review the landing page first."
- rows={4}
- className="w-full resize-y rounded-md border border-transparent bg-[hsl(var(--notfair-surface-2))] px-3 py-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
- disabled={pending}
- autoFocus
- />
- <DialogFooter className="gap-2 sm:gap-2">
- <Button
- variant="outline"
- onClick={() => rejectWith(undefined)}
- disabled={pending}
- >
- Reject without comments
- </Button>
- <Button
- onClick={() => rejectWith(denyNote.trim() || undefined)}
- disabled={pending || !denyNote.trim()}
- >
- Reject with comment
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </>
- );
-}
diff --git a/notfair-cmo/src/components/chat-thread-rail.test.tsx b/notfair-cmo/src/components/chat-thread-rail.test.tsx
deleted file mode 100644
index b6373adb..00000000
--- a/notfair-cmo/src/components/chat-thread-rail.test.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, afterEach } from "vitest";
-import { render, screen, cleanup } from "@testing-library/react";
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),
-}));
-
-vi.mock("@/server/actions/chat-threads", () => ({
- renameThreadAction: vi.fn(async () => ({ ok: true })),
- setThreadPinnedAction: vi.fn(async () => ({ ok: true })),
- deleteThreadAction: vi.fn(async () => ({ ok: true })),
-}));
-
-vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
-}));
-
-import { ChatThreadRail, type SessionLite } from "./chat-thread-rail";
-
-function makeSession(overrides: Partial<SessionLite> = {}): SessionLite {
- return {
- sessionId: "aaaa1111-0000-0000-0000-000000000000",
- label: "aaaa1111",
- sessionKey: "aaaa1111",
- lastInteractionAt: Date.now(),
- pending: false,
- ...overrides,
- };
-}
-
-afterEach(() => {
- cleanup();
-});
-
-describe("ChatThreadRail", () => {
- it("renders the New chat button on top, text-only rows, and hides task threads", () => {
- render(
- <ChatThreadRail
- projectSlug="demo"
- agentSlug="cmo-greg"
- activeSessionId="aaaa1111-0000-0000-0000-000000000000"
- sessions={[
- makeSession({
- origin: { kind: "chat", preview: "What should we launch first?" },
- }),
- // Task-kickoff threads live on the Tasks tab — not here.
- makeSession({
- sessionId: "bbbb2222-0000-0000-0000-000000000000",
- label: "bbbb2222",
- sessionKey: "bbbb2222",
- origin: { kind: "task", display_id: "demo-1", title: "Audit the account" },
- }),
- ]}
- />,
- );
- expect(screen.getByRole("button", { name: /New chat/i })).toBeInTheDocument();
- expect(screen.getAllByRole("listitem")).toHaveLength(1);
- expect(screen.getByText("What should we launch first?")).toBeInTheDocument();
- expect(screen.queryByText(/Audit the account/)).not.toBeInTheDocument();
- // Text only — no thread-id line on the rows.
- expect(screen.queryByText("aaaa1111")).not.toBeInTheDocument();
- });
-
- it("links each row to its thread and marks the active one", () => {
- render(
- <ChatThreadRail
- projectSlug="demo"
- agentSlug="cmo-greg"
- activeSessionId="aaaa1111-0000-0000-0000-000000000000"
- sessions={[
- makeSession({ origin: { kind: "chat", preview: "alpha" } }),
- makeSession({
- sessionId: "bbbb2222-0000-0000-0000-000000000000",
- label: "bbbb2222",
- sessionKey: "bbbb2222",
- origin: { kind: "chat", preview: "beta" },
- }),
- ]}
- />,
- );
- const active = screen.getByText("alpha").closest("a");
- const other = screen.getByText("beta").closest("a");
- expect(active).toHaveAttribute(
- "href",
- "/demo/agents/cmo-greg/chat/aaaa1111-0000-0000-0000-000000000000",
- );
- expect(active).toHaveAttribute("aria-current", "true");
- expect(other).not.toHaveAttribute("aria-current");
- });
-
- it("prefers the user-set title and marks pinned threads", () => {
- render(
- <ChatThreadRail
- projectSlug="demo"
- agentSlug="cmo-greg"
- activeSessionId="x"
- sessions={[
- makeSession({
- title: "Q4 planning",
- pinned: true,
- origin: { kind: "chat", preview: "ignored preview" },
- }),
- ]}
- />,
- );
- expect(screen.getByText("Q4 planning")).toBeInTheDocument();
- expect(screen.queryByText("ignored preview")).not.toBeInTheDocument();
- expect(screen.getByLabelText("Pinned")).toBeInTheDocument();
- });
-
- it("opens the ⋮ menu with Rename / Pin / Delete", async () => {
- const { fireEvent } = await import("@testing-library/react");
- render(
- <ChatThreadRail
- projectSlug="demo"
- agentSlug="cmo-greg"
- activeSessionId="x"
- sessions={[makeSession({ origin: { kind: "chat", preview: "alpha" } })]}
- />,
- );
- const trigger = screen.getByRole("button", { name: /Thread actions for alpha/i });
- fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });
- fireEvent.click(trigger);
- expect(await screen.findByText("Rename")).toBeInTheDocument();
- expect(screen.getByText("Pin")).toBeInTheDocument();
- expect(screen.getByText("Delete")).toBeInTheDocument();
- // Delete routes through an explicit confirm dialog.
- fireEvent.click(screen.getByText("Delete"));
- expect(await screen.findByText("Delete thread?")).toBeInTheDocument();
- });
-
- it("labels pending threads as new and shows the empty state without threads", () => {
- const { unmount } = render(
- <ChatThreadRail
- projectSlug="demo"
- agentSlug="cmo-greg"
- activeSessionId="cccc3333-0000-0000-0000-000000000000"
- sessions={[
- makeSession({
- sessionId: "cccc3333-0000-0000-0000-000000000000",
- pending: true,
- }),
- ]}
- />,
- );
- expect(screen.getByText("New thread")).toBeInTheDocument();
- unmount();
-
- render(
- <ChatThreadRail
- projectSlug="demo"
- agentSlug="cmo-greg"
- activeSessionId="x"
- sessions={[]}
- />,
- );
- expect(screen.getByText(/No threads yet/)).toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/chat-thread-rail.tsx b/notfair-cmo/src/components/chat-thread-rail.tsx
deleted file mode 100644
index 2359d899..00000000
--- a/notfair-cmo/src/components/chat-thread-rail.tsx
+++ /dev/null
@@ -1,359 +0,0 @@
-"use client";
-
-import { useState, useTransition } from "react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { MoreVertical, Pin, PinOff, Plus } from "lucide-react";
-import { toast } from "sonner";
-
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Input } from "@/components/ui/input";
-import {
- deleteThreadAction,
- renameThreadAction,
- setThreadPinnedAction,
-} from "@/server/actions/chat-threads";
-import { cn } from "@/lib/utils";
-import { projectHref } from "@/lib/project-href";
-
-/**
- * Left rail for the agent chat page — mirrors the task workspace's rail:
- * a full-width "New chat" row on top, then a flat scrollable list of
- * threads. Rows are one line high; hovering a row slides overflowing
- * titles horizontally (marquee) to reveal the rest, and surfaces a ⋮
- * menu with Rename / Pin / Delete.
- */
-
-export type SessionOriginLite =
- | { kind: "task"; display_id: string; title: string | null }
- | { kind: "cron"; cron_name: string }
- | { kind: "chat"; preview: string };
-
-export type SessionLite = {
- sessionId: string;
- label: string;
- sessionKey: string;
- lastInteractionAt: number;
- pending: boolean;
- /** User-set display title (rename). Overrides the derived preview. */
- title?: string | null;
- /** True when pinned — the server sorts pinned threads first. */
- pinned?: boolean;
- /**
- * Server-classified origin. Drives the row title so users see a cron
- * name or first-message preview instead of a raw UUID. Undefined for
- * pending threads (no transcript yet).
- */
- origin?: SessionOriginLite;
-};
-
-function displayTitle(s: SessionLite): string {
- if (s.title) return s.title;
- if (s.pending) return "New thread";
- if (s.origin?.kind === "cron") return s.origin.cron_name;
- if (s.origin?.kind === "chat" && s.origin.preview) return s.origin.preview;
- if (s.label === "main") return "Main thread";
- return s.label;
-}
-
-/** Row shell shared by thread rows and the New chat button. */
-const ROW_CLASS =
- "ns-thread-row group/row relative mx-2 block w-[calc(100%-1rem)] rounded-md px-2.5 py-2 text-left text-xs leading-4 transition-colors hover:bg-sidebar-accent focus-visible:outline-none focus-visible:bg-sidebar-accent";
-
-/**
- * Measure how far the row's title overflows its clip box and stash it as
- * a CSS var; the .ns-marquee hover rule animates the text by exactly that
- * distance. Runs on mouseenter so it always reflects current widths.
- */
-function primeMarquee(e: React.MouseEvent<HTMLElement>) {
- const clip = e.currentTarget.querySelector<HTMLElement>(".ns-marquee");
- const text = clip?.firstElementChild as HTMLElement | null;
- if (!clip || !text) return;
- const overflow = Math.max(0, text.scrollWidth - clip.clientWidth);
- text.style.setProperty("--ns-marquee-shift", `-${overflow}px`);
- // Constant reading speed regardless of title length — a fixed duration
- // made long titles whip past.
- const PX_PER_SECOND = 25;
- text.style.setProperty(
- "--ns-marquee-duration",
- `${Math.max(1.5, overflow / PX_PER_SECOND)}s`,
- );
-}
-
-export function ChatThreadRail({
- projectSlug,
- agentSlug,
- sessions,
- activeSessionId,
-}: {
- projectSlug: string;
- agentSlug: string;
- sessions: SessionLite[];
- activeSessionId: string;
-}) {
- const router = useRouter();
- const [pending, startTransition] = useTransition();
- const [renaming, setRenaming] = useState<SessionLite | null>(null);
- const [deleting, setDeleting] = useState<SessionLite | null>(null);
-
- // Task-kickoff threads belong to the Tasks tab (each task page shows
- // its own transcript) — listing them here would double-surface them.
- const visible = sessions.filter((s) => s.origin?.kind !== "task");
-
- function newThread() {
- const id = crypto.randomUUID();
- startTransition(() =>
- router.push(projectHref(projectSlug, `/agents/${agentSlug}/chat/${id}`)),
- );
- }
-
- function togglePin(s: SessionLite) {
- startTransition(async () => {
- const r = await setThreadPinnedAction({
- projectSlug,
- agentSlug,
- threadLabel: s.sessionId,
- pinned: !s.pinned,
- });
- if (!r.ok) toast.error(r.error);
- else router.refresh();
- });
- }
-
- function confirmDelete(s: SessionLite) {
- startTransition(async () => {
- const r = await deleteThreadAction({
- projectSlug,
- agentSlug,
- threadLabel: s.sessionId,
- });
- setDeleting(null);
- if (!r.ok) {
- toast.error(r.error);
- return;
- }
- toast.success("Thread deleted.");
- if (s.sessionId === activeSessionId) {
- // The open thread just vanished — move to a fresh one.
- newThread();
- } else {
- router.refresh();
- }
- });
- }
-
- return (
- <aside className="flex w-72 shrink-0 flex-col bg-[hsl(var(--notfair-sidebar))]">
- <div className="pt-2">
- {/* Same shell as a thread row so the rail reads as one list. */}
- <button
- type="button"
- onClick={newThread}
- disabled={pending}
- className={cn(ROW_CLASS, "disabled:opacity-50")}
- >
- <span className="inline-flex items-center gap-1.5 font-medium text-muted-foreground group-hover/row:text-foreground">
- <Plus className="size-3.5" />
- New chat
- </span>
- </button>
- </div>
-
- <div className="min-h-0 flex-1 overflow-y-auto py-1">
- {visible.length === 0 ? (
- <div className="px-4 py-8 text-center text-xs text-muted-foreground">
- No threads yet — say hi below.
- </div>
- ) : (
- /* gap-1 matches SidebarMenu's item spacing, same as the task rail. */
- <ul className="flex flex-col gap-1">
- {visible.map((s) => {
- const isActive = s.sessionId === activeSessionId;
- return (
- <li key={s.sessionId} className="relative">
- <Link
- href={projectHref(
- projectSlug,
- `/agents/${agentSlug}/chat/${s.sessionId}`,
- )}
- aria-current={isActive ? "true" : undefined}
- onMouseEnter={primeMarquee}
- className={cn(
- ROW_CLASS,
- // Reserve space for the ⋮ button (and pin glyph).
- "pr-8",
- isActive && "bg-sidebar-accent",
- )}
- >
- <span className="flex items-center gap-1.5">
- {s.pinned && (
- <Pin
- aria-label="Pinned"
- className="size-3 shrink-0 text-muted-foreground"
- />
- )}
- <span className="ns-marquee min-w-0 flex-1">
- <span
- className={cn(
- isActive
- ? "font-medium text-foreground"
- : "text-foreground/90",
- )}
- >
- {displayTitle(s)}
- </span>
- </span>
- </span>
- </Link>
- {/* ⋮ menu — a sibling of the Link (not a child: nested
- interactive elements are invalid HTML), absolutely
- positioned into the row's reserved right padding. */}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- aria-label={`Thread actions for ${displayTitle(s)}`}
- className="absolute right-3.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[state=open]:opacity-100 [li:hover_&]:opacity-100"
- >
- <MoreVertical className="size-3.5" />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" side="right">
- <DropdownMenuItem onSelect={() => setRenaming(s)}>
- Rename
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => togglePin(s)}>
- {s.pinned ? (
- <>
- <PinOff className="mr-1.5 size-3.5" /> Unpin
- </>
- ) : (
- <>
- <Pin className="mr-1.5 size-3.5" /> Pin
- </>
- )}
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- onSelect={() => setDeleting(s)}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </li>
- );
- })}
- </ul>
- )}
- </div>
-
- {renaming && (
- <RenameThreadDialog
- session={renaming}
- onClose={() => setRenaming(null)}
- onSubmit={(title) => {
- const target = renaming;
- startTransition(async () => {
- const r = await renameThreadAction({
- projectSlug,
- agentSlug,
- threadLabel: target.sessionId,
- title,
- });
- setRenaming(null);
- if (!r.ok) toast.error(r.error);
- else router.refresh();
- });
- }}
- />
- )}
-
- <Dialog open={deleting !== null} onOpenChange={(o) => !o && setDeleting(null)}>
- <DialogContent className="sm:max-w-sm">
- <DialogHeader>
- <DialogTitle>Delete thread?</DialogTitle>
- <DialogDescription>
- This permanently deletes the conversation
- {deleting ? ` "${displayTitle(deleting)}"` : ""} and its
- transcript. There is no undo.
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" size="sm" onClick={() => setDeleting(null)}>
- Cancel
- </Button>
- <Button
- variant="destructive"
- size="sm"
- disabled={pending}
- onClick={() => deleting && confirmDelete(deleting)}
- >
- Delete
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </aside>
- );
-}
-
-function RenameThreadDialog({
- session,
- onClose,
- onSubmit,
-}: {
- session: SessionLite;
- onClose: () => void;
- onSubmit: (title: string) => void;
-}) {
- const [value, setValue] = useState(session.title ?? "");
- return (
- <Dialog open onOpenChange={(o) => !o && onClose()}>
- <DialogContent className="sm:max-w-sm">
- <DialogHeader>
- <DialogTitle>Rename thread</DialogTitle>
- <DialogDescription>
- Leave empty to go back to the automatic title.
- </DialogDescription>
- </DialogHeader>
- <form
- onSubmit={(e) => {
- e.preventDefault();
- onSubmit(value.trim());
- }}
- >
- <Input
- autoFocus
- value={value}
- onChange={(e) => setValue(e.target.value)}
- placeholder={displayTitle({ ...session, title: null })}
- aria-label="Thread title"
- />
- <DialogFooter className="mt-4">
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" size="sm">
- Save
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/notfair-cmo/src/components/client-mount-gate.test.tsx b/notfair-cmo/src/components/client-mount-gate.test.tsx
deleted file mode 100644
index 768b9c22..00000000
--- a/notfair-cmo/src/components/client-mount-gate.test.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, describe, it, expect } from "vitest";
-import { act, cleanup, render, screen } from "@testing-library/react";
-import { renderToString } from "react-dom/server";
-
-import { ClientMountGate } from "./client-mount-gate";
-
-afterEach(() => cleanup());
-
-describe("ClientMountGate", () => {
- it("renders the fallback during SSR (no useEffect has fired yet)", () => {
- const html = renderToString(
- <ClientMountGate fallback={<span>loading skeleton</span>}>
- <span>real content</span>
- </ClientMountGate>,
- );
- expect(html).toContain("loading skeleton");
- expect(html).not.toContain("real content");
- });
-
- it("renders an empty shell during SSR when no fallback is supplied", () => {
- const html = renderToString(
- <ClientMountGate>
- <span>real content</span>
- </ClientMountGate>,
- );
- expect(html).not.toContain("real content");
- expect(html.replace(/<!--.*?-->/g, "")).toBe("");
- });
-
- it("swaps the fallback for the children after the client mounts", () => {
- render(
- <ClientMountGate fallback={<span data-testid="fallback">loading…</span>}>
- <span data-testid="content">real content</span>
- </ClientMountGate>,
- );
- expect(screen.getByTestId("content")).toBeInTheDocument();
- expect(screen.queryByTestId("fallback")).not.toBeInTheDocument();
- });
-
- it("renders children even with no fallback once mounted", () => {
- render(
- <ClientMountGate>
- <span data-testid="content">visible</span>
- </ClientMountGate>,
- );
- expect(screen.getByTestId("content")).toBeInTheDocument();
- });
-
- it("remains rendering children across re-renders", () => {
- const { rerender } = render(
- <ClientMountGate>
- <span data-testid="content">first</span>
- </ClientMountGate>,
- );
- expect(screen.getByTestId("content").textContent).toBe("first");
- act(() => {
- rerender(
- <ClientMountGate>
- <span data-testid="content">second</span>
- </ClientMountGate>,
- );
- });
- expect(screen.getByTestId("content").textContent).toBe("second");
- });
-});
diff --git a/notfair-cmo/src/components/cron-calendar.test.tsx b/notfair-cmo/src/components/cron-calendar.test.tsx
deleted file mode 100644
index bfb31b19..00000000
--- a/notfair-cmo/src/components/cron-calendar.test.tsx
+++ /dev/null
@@ -1,566 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup, within } from "@testing-library/react";
-
-if (typeof Element !== "undefined") {
- // @ts-expect-error - jsdom shim
- Element.prototype.hasPointerCapture ??= () => false;
- // @ts-expect-error - jsdom shim
- Element.prototype.setPointerCapture ??= () => {};
- // @ts-expect-error - jsdom shim
- Element.prototype.releasePointerCapture ??= () => {};
- // @ts-expect-error - jsdom shim
- Element.prototype.scrollIntoView ??= () => {};
-}
-
-const pauseCronAction = vi.fn();
-const resumeCronAction = vi.fn();
-const deleteCronAction = vi.fn();
-const updateCronPromptAction = vi.fn();
-const getCronRunsAction = vi.fn();
-
-const toast = { success: vi.fn(), error: vi.fn() };
-
-vi.mock("@/server/actions/crons", () => ({
- pauseCronAction: (...a: unknown[]) => pauseCronAction(...a),
- resumeCronAction: (...a: unknown[]) => resumeCronAction(...a),
- deleteCronAction: (...a: unknown[]) => deleteCronAction(...a),
- updateCronPromptAction: (...a: unknown[]) => updateCronPromptAction(...a),
-}));
-
-vi.mock("@/server/actions/cron-runs", () => ({
- getCronRunsAction: (...a: unknown[]) => getCronRunsAction(...a),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...a: unknown[]) => toast.success(...a),
- error: (...a: unknown[]) => toast.error(...a),
- },
-}));
-
-import { CronCalendar, type CalendarCron, type CalendarOccurrence } from "./cron-calendar";
-
-beforeEach(() => {
- pauseCronAction.mockReset();
- resumeCronAction.mockReset();
- deleteCronAction.mockReset();
- updateCronPromptAction.mockReset();
- getCronRunsAction.mockReset();
- getCronRunsAction.mockResolvedValue({ ok: true, runs: [] });
- toast.success.mockReset();
- toast.error.mockReset();
-});
-
-afterEach(() => cleanup());
-
-// Build a fixed test world. startOfFirstDay is 14 days ago at local midnight,
-// so we can have past + future occurrences relative to a stable "now".
-function todayStart(): number {
- const d = new Date();
- d.setHours(0, 0, 0, 0);
- return d.getTime();
-}
-
-const DAY = 24 * 60 * 60 * 1000;
-const HOUR = 60 * 60 * 1000;
-
-function buildWorld() {
- const start = todayStart() - 3 * DAY; // window covers 3 days before today through day 3 (today is day 3)
- const todayAt9 = todayStart() + 9 * HOUR;
- const todayAt15 = todayStart() + 15 * HOUR;
- const yesterdayAt9 = todayStart() - 1 * DAY + 9 * HOUR;
- const tomorrowAt9 = todayStart() + 1 * DAY + 9 * HOUR;
-
- const cronsById: Record<string, CalendarCron> = {
- "cron-a": {
- id: "cron-a",
- short_name: "daily-opt",
- full_name: "acme/google-ads/daily-opt",
- agent_id: "acme-google-ads",
- agent_slug: "google-ads",
- schedule_text: "0 9 * * *",
- disabled: false,
- status_text: "ok",
- message: "Run the daily optimization sweep.",
- description: "Tunes bids each morning.",
- schedule_raw: { kind: "cron", expr: "0 9 * * *", tz: "America/Los_Angeles" },
- },
- "cron-b": {
- id: "cron-b",
- short_name: "weekly-review",
- full_name: "acme/seo/weekly-review",
- agent_id: "acme-seo",
- agent_slug: "seo",
- schedule_text: "0 9 * * 1",
- disabled: true,
- status_text: "paused",
- message: "Weekly SEO review.",
- schedule_raw: null,
- },
- "cron-c": {
- id: "cron-c",
- short_name: "hourly-ping",
- full_name: "acme/cmo/hourly-ping",
- agent_id: "acme-cmo",
- agent_slug: "cmo",
- schedule_text: "every 1h",
- disabled: false,
- status_text: "ok",
- // No message — the Prompt section should NOT render
- schedule_raw: { kind: "every", everyMs: 3_600_000 },
- },
- };
-
- const occurrences: CalendarOccurrence[] = [
- {
- at: yesterdayAt9,
- cron_id: "cron-a",
- cron_name: cronsById["cron-a"]!.full_name,
- short_name: "daily-opt",
- agent_id: "acme-google-ads",
- agent_slug: "google-ads",
- schedule_text: "0 9 * * *",
- run_status: "ok",
- },
- {
- at: todayAt9,
- cron_id: "cron-a",
- cron_name: cronsById["cron-a"]!.full_name,
- short_name: "daily-opt",
- agent_id: "acme-google-ads",
- agent_slug: "google-ads",
- schedule_text: "0 9 * * *",
- run_status: "error",
- },
- {
- at: todayAt15,
- cron_id: "cron-b",
- cron_name: cronsById["cron-b"]!.full_name,
- short_name: "weekly-review",
- agent_id: "acme-seo",
- agent_slug: "seo",
- schedule_text: "0 9 * * 1",
- cron_disabled: true,
- },
- {
- at: tomorrowAt9,
- cron_id: "cron-c",
- cron_name: cronsById["cron-c"]!.full_name,
- short_name: "hourly-ping",
- agent_id: "acme-cmo",
- agent_slug: "cmo",
- schedule_text: "every 1h",
- },
- ];
-
- return {
- start,
- numDays: 14,
- occurrences,
- cronsById,
- agentSlugs: ["cmo", "google-ads", "seo"],
- todayAt9,
- todayAt15,
- yesterdayAt9,
- tomorrowAt9,
- };
-}
-
-function renderCalendar() {
- const w = buildWorld();
- render(
- <CronCalendar
- startOfFirstDay={w.start}
- numDays={w.numDays}
- occurrences={w.occurrences}
- cronsById={w.cronsById}
- agentSlugs={w.agentSlugs}
- />,
- );
- return w;
-}
-
-describe("CronCalendar — filter chips", () => {
- it("defaults to 'Enabled' filter and hides disabled crons", () => {
- renderCalendar();
- const enabledTab = screen.getByRole("tab", { name: "Enabled" });
- expect(enabledTab).toHaveAttribute("aria-selected", "true");
- // disabled cron-b's chip should not be on the board
- expect(screen.queryAllByText("weekly-review")).toHaveLength(0);
- // enabled chips visible
- expect(screen.getAllByText("daily-opt").length).toBeGreaterThan(0);
- expect(screen.getByText("hourly-ping")).toBeInTheDocument();
- });
-
- it("switching to 'Disabled' shows only disabled crons", () => {
- renderCalendar();
- fireEvent.click(screen.getByRole("tab", { name: "Disabled" }));
- expect(screen.getByText("weekly-review")).toBeInTheDocument();
- expect(screen.queryAllByText("daily-opt")).toHaveLength(0);
- expect(screen.queryByText("hourly-ping")).not.toBeInTheDocument();
- });
-
- it("switching to 'All' shows enabled and disabled chips together", () => {
- renderCalendar();
- fireEvent.click(screen.getByRole("tab", { name: "All" }));
- expect(screen.getByText("weekly-review")).toBeInTheDocument();
- expect(screen.getAllByText("daily-opt").length).toBeGreaterThan(0);
- expect(screen.getByText("hourly-ping")).toBeInTheDocument();
- });
-
- it("shows an empty-state when the active filter has no occurrences", () => {
- render(
- <CronCalendar
- startOfFirstDay={todayStart()}
- numDays={14}
- occurrences={[]}
- cronsById={{}}
- agentSlugs={[]}
- />,
- );
- expect(screen.getByText(/Nothing to show with this filter/i)).toBeInTheDocument();
- });
-});
-
-describe("CronCalendar — legend", () => {
- it("shows only the slugs that are currently visible (filtered by enabled crons)", () => {
- renderCalendar();
- // Enabled filter: cron-a (google-ads) + cron-c (cmo). Not seo.
- // Legend entries are font-mono spans with the slug text.
- const legend = screen.getAllByText(/^(google-ads|cmo|seo)$/i);
- const slugs = legend.map((el) => el.textContent);
- expect(slugs).toContain("google-ads");
- expect(slugs).toContain("cmo");
- expect(slugs).not.toContain("seo");
- });
-
- it("legend updates when filter switches to 'Disabled'", () => {
- renderCalendar();
- fireEvent.click(screen.getByRole("tab", { name: "Disabled" }));
- const legend = screen.getAllByText(/^(google-ads|cmo|seo)$/i);
- const slugs = legend.map((el) => el.textContent);
- expect(slugs).toContain("seo");
- expect(slugs).not.toContain("cmo");
- expect(slugs).not.toContain("google-ads");
- });
-});
-
-describe("CronCalendar — week navigator", () => {
- it("Prev is disabled at offset 0 (window already at start)", () => {
- renderCalendar();
- expect(screen.getByLabelText("Previous week")).toBeDisabled();
- });
-
- it("Next becomes disabled once we scroll one week (numDays=14, visible=7)", () => {
- renderCalendar();
- const next = screen.getByLabelText("Next week");
- expect(next).not.toBeDisabled();
- fireEvent.click(next);
- expect(next).toBeDisabled();
- });
-
- it("'Today' button resets back to offset 0", () => {
- renderCalendar();
- fireEvent.click(screen.getByLabelText("Next week"));
- expect(screen.getByLabelText("Previous week")).not.toBeDisabled();
- fireEvent.click(screen.getByRole("button", { name: /^today$/i }));
- expect(screen.getByLabelText("Previous week")).toBeDisabled();
- });
-});
-
-describe("CronCalendar — occurrence detail dialog", () => {
- it("clicking an occurrence chip opens the detail dialog with cron metadata", async () => {
- renderCalendar();
- const chips = screen.getAllByText("daily-opt");
- fireEvent.click(chips[0]!.closest("button")!);
- await waitFor(() => {
- expect(screen.getByRole("dialog")).toBeInTheDocument();
- });
- // Heading uses the short_name
- expect(screen.getAllByText("daily-opt").length).toBeGreaterThan(0);
- expect(screen.getByText("Tunes bids each morning.")).toBeInTheDocument();
- // Details rows
- expect(screen.getByText("acme/google-ads/daily-opt")).toBeInTheDocument();
- expect(screen.getByText("acme-google-ads")).toBeInTheDocument();
- expect(screen.getByText("0 9 * * *")).toBeInTheDocument();
- });
-
- it("loads runs via getCronRunsAction when a cron is selected", async () => {
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt")[0]!.closest("button")!);
- await waitFor(() => {
- expect(getCronRunsAction).toHaveBeenCalledWith(
- "cron-a",
- { kind: "cron", expr: "0 9 * * *", tz: "America/Los_Angeles" },
- 200,
- );
- });
- });
-
- it("shows past-tick fallback when no matched run and time is in the past", async () => {
- renderCalendar();
- // yesterday's tick had run_status="ok" but our mocked runs are empty, so
- // matchedRun is null AND occ.at < Date.now() → "No run log for this occurrence."
- const chips = screen.getAllByText("daily-opt").map((n) => n.closest("button")!);
- fireEvent.click(chips[0]!); // first one is the older occurrence (yesterday)
- await waitFor(() => expect(getCronRunsAction).toHaveBeenCalled());
- // Result section should reflect "no run log" — first matching node wins.
- expect(await screen.findByText(/No run log for this occurrence|Not fired yet/i)).toBeInTheDocument();
- });
-
- it("shows 'Not fired yet' for future occurrences with no matched run", async () => {
- renderCalendar();
- // Click the tomorrow chip (hourly-ping)
- fireEvent.click(screen.getByText("hourly-ping").closest("button")!);
- await waitFor(() => expect(getCronRunsAction).toHaveBeenCalled());
- expect(await screen.findByText(/Not fired yet/i)).toBeInTheDocument();
- });
-
- it("shows 'scheduled' badge for future occurrences", async () => {
- renderCalendar();
- fireEvent.click(screen.getByText("hourly-ping").closest("button")!);
- expect(await screen.findByText("scheduled")).toBeInTheDocument();
- });
-
- it("shows 'past' badge for past occurrences with no matching run", async () => {
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- expect(await screen.findByText("past")).toBeInTheDocument();
- });
-
- it("shows raw status badge for a past occurrence with a matching run (exact tick)", async () => {
- const w = buildWorld();
- getCronRunsAction.mockResolvedValue({
- ok: true,
- runs: [
- {
- status: "ok",
- run_at_ms: w.yesterdayAt9,
- finished_at_ms: w.yesterdayAt9 + 30_000,
- duration_ms: 30_000,
- owning_occurrence_at_ms: w.yesterdayAt9,
- model: "claude-opus",
- provider: "anthropic",
- usage: { total_tokens: 12345 },
- summary: "Bid changes applied.",
- },
- ],
- });
- render(
- <CronCalendar
- startOfFirstDay={w.start}
- numDays={w.numDays}
- occurrences={w.occurrences}
- cronsById={w.cronsById}
- agentSlugs={w.agentSlugs}
- />,
- );
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- await waitFor(() => expect(getCronRunsAction).toHaveBeenCalled());
- // Badge shows raw status "ok"
- const badges = await screen.findAllByText(/^ok$/);
- expect(badges.length).toBeGreaterThan(0);
- // Result section shows the summary
- expect(await screen.findByText("Bid changes applied.")).toBeInTheDocument();
- // Tokens row
- expect(await screen.findByText("12,345")).toBeInTheDocument();
- // Model row
- expect(await screen.findByText(/claude-opus/)).toBeInTheDocument();
- });
-
- it("renders an Error section when the matched run has an error", async () => {
- const w = buildWorld();
- getCronRunsAction.mockResolvedValue({
- ok: true,
- runs: [
- {
- status: "error",
- run_at_ms: w.yesterdayAt9,
- finished_at_ms: w.yesterdayAt9 + 1_000,
- duration_ms: 1_000,
- owning_occurrence_at_ms: w.yesterdayAt9,
- error: "MCP token missing",
- },
- ],
- });
- render(
- <CronCalendar
- startOfFirstDay={w.start}
- numDays={w.numDays}
- occurrences={w.occurrences}
- cronsById={w.cronsById}
- agentSlugs={w.agentSlugs}
- />,
- );
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- expect(await screen.findByText("MCP token missing")).toBeInTheDocument();
- });
-
- it("renders the runs-error message when getCronRunsAction returns ok=false", async () => {
- getCronRunsAction.mockResolvedValue({ ok: false, error: "DB locked" });
- renderCalendar();
- fireEvent.click(screen.getByText("hourly-ping").closest("button")!);
- expect(await screen.findByText("DB locked")).toBeInTheDocument();
- });
-
- it("does NOT render a Prompt section when cron.message is undefined", async () => {
- renderCalendar();
- fireEvent.click(screen.getByText("hourly-ping").closest("button")!);
- await screen.findByRole("dialog");
- // No "Prompt" section header
- expect(screen.queryByRole("button", { name: /^prompt$/i, expanded: true })).not.toBeInTheDocument();
- });
-
- it("renders the prompt text in read-only mode by default", async () => {
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- expect(await screen.findByText(/Run the daily optimization sweep\./)).toBeInTheDocument();
- expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
- });
-
- it("clicking Edit reveals the textarea; Cancel restores read-only without calling the action", async () => {
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- expect(textarea.value).toBe("Run the daily optimization sweep.");
- fireEvent.change(textarea, { target: { value: "totally new prompt" } });
- fireEvent.click(screen.getByRole("button", { name: /cancel/i }));
- expect(updateCronPromptAction).not.toHaveBeenCalled();
- expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
- });
-
- it("Save with empty prompt toasts an error and does not call the action", async () => {
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- fireEvent.change(textarea, { target: { value: " " } });
- fireEvent.click(screen.getByRole("button", { name: /^save$/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Prompt cannot be empty."));
- expect(updateCronPromptAction).not.toHaveBeenCalled();
- });
-
- it("Save with unchanged prompt closes the editor without calling the action", async () => {
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));
- // value unchanged
- fireEvent.click(screen.getByRole("button", { name: /^save$/i }));
- expect(updateCronPromptAction).not.toHaveBeenCalled();
- await waitFor(() => expect(screen.queryByRole("textbox")).not.toBeInTheDocument());
- });
-
- it("Save with new prompt calls updateCronPromptAction and toasts success", async () => {
- updateCronPromptAction.mockResolvedValue({ ok: true });
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));
- fireEvent.change(screen.getByRole("textbox"), { target: { value: "new prompt text" } });
- fireEvent.click(screen.getByRole("button", { name: /^save$/i }));
- await waitFor(() =>
- expect(updateCronPromptAction).toHaveBeenCalledWith("cron-a", "new prompt text"),
- );
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Prompt updated"));
- });
-
- it("Save with server error toasts the error and keeps the editor open", async () => {
- updateCronPromptAction.mockResolvedValue({ ok: false, error: "openclaw rejected" });
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));
- fireEvent.change(screen.getByRole("textbox"), { target: { value: "another" } });
- fireEvent.click(screen.getByRole("button", { name: /^save$/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("openclaw rejected"));
- // editor still mounted
- expect(screen.getByRole("textbox")).toBeInTheDocument();
- });
-});
-
-describe("CronCalendar — collapsible sections", () => {
- it("a section's chevron button toggles open/closed", async () => {
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- const detailsHeader = await screen.findByRole("button", { name: /details/i, expanded: true });
- fireEvent.click(detailsHeader);
- expect(detailsHeader).toHaveAttribute("aria-expanded", "false");
- fireEvent.click(detailsHeader);
- expect(detailsHeader).toHaveAttribute("aria-expanded", "true");
- });
-});
-
-describe("CronCalendar — cron actions (footer)", () => {
- it("shows Disable on an enabled cron and pauses it", async () => {
- pauseCronAction.mockResolvedValue({ ok: true });
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /disable/i }));
- await waitFor(() => expect(pauseCronAction).toHaveBeenCalledWith("cron-a"));
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Disabled: daily-opt"));
- });
-
- it("shows Enable on a disabled cron and resumes it", async () => {
- resumeCronAction.mockResolvedValue({ ok: true });
- renderCalendar();
- fireEvent.click(screen.getByRole("tab", { name: "Disabled" }));
- fireEvent.click(screen.getByText("weekly-review").closest("button")!);
- fireEvent.click(await screen.findByRole("button", { name: /enable/i }));
- await waitFor(() => expect(resumeCronAction).toHaveBeenCalledWith("cron-b"));
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Enabled: weekly-review"));
- });
-
- it("Delete prompts for confirmation; cancel skips the action", async () => {
- const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false);
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /delete/i }));
- expect(deleteCronAction).not.toHaveBeenCalled();
- confirmSpy.mockRestore();
- });
-
- it("Delete invokes the action when confirmed", async () => {
- const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true);
- deleteCronAction.mockResolvedValue({ ok: true });
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /delete/i }));
- await waitFor(() => expect(deleteCronAction).toHaveBeenCalledWith("cron-a"));
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Deleted: daily-opt"));
- confirmSpy.mockRestore();
- });
-
- it("toasts the server error when the cron action fails", async () => {
- pauseCronAction.mockResolvedValue({ ok: false, error: "nope" });
- renderCalendar();
- fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);
- fireEvent.click(await screen.findByRole("button", { name: /disable/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("nope"));
- });
-});
-
-describe("CronCalendar — chip rendering", () => {
- it("disabled occurrences render a strike-through time", () => {
- renderCalendar();
- fireEvent.click(screen.getByRole("tab", { name: "All" }));
- // Disabled chip wraps its time in a span with line-through class
- const allChips = screen.getAllByRole("button");
- const disabledChip = allChips.find((b) => b.textContent?.includes("weekly-review"));
- expect(disabledChip).toBeDefined();
- const timeSpan = within(disabledChip!).getAllByText(/\d/)[0];
- expect(timeSpan?.className).toMatch(/line-through/);
- });
-
- it("ok status occurrence has aria-label='success' glyph", () => {
- renderCalendar();
- const yesterdayChip = screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!;
- expect(within(yesterdayChip).getByLabelText("success")).toBeInTheDocument();
- });
-
- it("error status occurrence has aria-label='error' glyph", () => {
- renderCalendar();
- const chips = screen.getAllByText("daily-opt").map((n) => n.closest("button")!);
- // The second daily-opt is today's "error" run
- expect(within(chips[1]!).getByLabelText("error")).toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/cron-calendar.tsx b/notfair-cmo/src/components/cron-calendar.tsx
deleted file mode 100644
index e3718275..00000000
--- a/notfair-cmo/src/components/cron-calendar.tsx
+++ /dev/null
@@ -1,877 +0,0 @@
-"use client";
-
-import { useEffect, useMemo, useState, useTransition } from "react";
-import {
- AlertCircle,
- Check,
- ChevronLeft,
- ChevronRight,
- ChevronRight as ChevronRightSmall,
- Loader2,
- Pause,
- Pencil,
- Play,
- Save,
- Trash2,
- X,
-} from "lucide-react";
-/* note: ExternalLink import removed with the OpenClaw docs button */
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Badge } from "@/components/ui/badge";
-import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import { colorForAgentSlug } from "@/lib/agent-colors";
-import {
- pauseCronAction,
- resumeCronAction,
- deleteCronAction,
- updateCronPromptAction,
-} from "@/server/actions/crons";
-import { getCronRunsAction, type CronRunWithTick, type ScheduleInput } from "@/server/actions/cron-runs";
-
-/**
- * Pre-computed cron occurrence used by the calendar. Server computes these
- * with `expandSchedule()` so the client just renders.
- */
-export type CalendarOccurrence = {
- at: number;
- cron_id: string;
- cron_name: string;
- short_name: string;
- agent_id: string;
- agent_slug: string;
- schedule_text: string;
- /** Raw OpenClaw status when this occurrence has fired (e.g. "ok", "error"). */
- run_status?: string;
- /** True when the underlying cron is currently paused/disabled. */
- cron_disabled?: boolean;
-};
-
-export type CalendarCron = {
- id: string;
- short_name: string;
- full_name: string;
- agent_id: string;
- agent_slug: string;
- schedule_text: string;
- disabled: boolean;
- status_text: string;
- /** Prompt sent to the agent on every tick. */
- message?: string;
- description?: string;
- /** Last execution time (ms epoch). */
- last_run_at_ms?: number;
- /** Raw OpenClaw status string for the most recent run (e.g. "ok", "error"). */
- last_status?: string;
- last_error?: string;
- /** Schedule shape — used to attribute runs to occurrences via nominal ticks. */
- schedule_raw?: ScheduleInput | null;
-};
-
-type Props = {
- /** ms epoch of the first day shown (00:00 local). */
- startOfFirstDay: number;
- numDays: number;
- occurrences: CalendarOccurrence[];
- cronsById: Record<string, CalendarCron>;
- /** Distinct agents for the legend. */
- agentSlugs: string[];
-};
-
-const DAY_MS = 24 * 60 * 60 * 1000;
-
-type CronFilter = "all" | "enabled" | "disabled";
-
-export function CronCalendar({
- startOfFirstDay,
- numDays,
- occurrences,
- cronsById,
- agentSlugs,
-}: Props) {
- const [focusDayOffset, setFocusDayOffset] = useState(0);
- const [selected, setSelected] = useState<CalendarOccurrence | null>(null);
- const [filter, setFilter] = useState<CronFilter>("enabled");
-
- const visibleOccurrences = useMemo(() => {
- if (filter === "all") return occurrences;
- return occurrences.filter((o) => {
- const d = cronsById[o.cron_id]?.disabled;
- return filter === "disabled" ? !!d : !d;
- });
- }, [occurrences, filter, cronsById]);
-
- // Agent slugs visible right now drive the legend.
- const visibleAgentSlugs = useMemo(() => {
- if (filter === "all") return agentSlugs;
- const set = new Set<string>();
- for (const o of visibleOccurrences) set.add(o.agent_slug);
- return Array.from(set).sort();
- }, [agentSlugs, visibleOccurrences, filter]);
-
- // Group filtered occurrences into days.
- const days = useMemo(() => {
- const buckets: CalendarOccurrence[][] = Array.from(
- { length: numDays },
- () => [],
- );
- for (const o of visibleOccurrences) {
- const idx = Math.floor((o.at - startOfFirstDay) / DAY_MS);
- if (idx >= 0 && idx < numDays) buckets[idx]!.push(o);
- }
- for (const day of buckets) day.sort((a, b) => a.at - b.at);
- return buckets;
- }, [visibleOccurrences, numDays, startOfFirstDay]);
-
- // 7-day window navigation (we keep numDays at 14 to allow scrolling).
- const visibleDays = Math.min(7, numDays);
- const offsetMax = Math.max(0, numDays - visibleDays);
- const clampedOffset = Math.max(0, Math.min(focusDayOffset, offsetMax));
-
- const selectedCron = selected ? cronsById[selected.cron_id] : null;
-
- return (
- <>
- <div className="space-y-3">
- {/* Legend + filter chips + window navigator */}
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex flex-wrap items-center gap-3">
- <FilterChips filter={filter} onChange={setFilter} />
- <span className="h-4 w-px bg-border" aria-hidden />
- {visibleAgentSlugs.map((slug) => {
- const color = colorForAgentSlug(slug);
- return (
- <div key={slug} className="flex items-center gap-1.5 text-xs">
- <span className={cn("inline-block size-2 rounded-full", color.dot)} />
- <span className="font-mono text-muted-foreground">{slug}</span>
- </div>
- );
- })}
- {visibleAgentSlugs.length === 0 && (
- <span className="text-xs text-muted-foreground">
- Nothing to show with this filter.
- </span>
- )}
- </div>
- <div className="flex items-center gap-1">
- <Button
- variant="outline"
- size="sm"
- className="h-7 w-7 p-0"
- onClick={() => setFocusDayOffset((o) => Math.max(0, o - visibleDays))}
- disabled={clampedOffset === 0}
- aria-label="Previous week"
- >
- <ChevronLeft className="size-3.5" />
- </Button>
- <Button
- variant="outline"
- size="sm"
- className="h-7 px-2 text-xs"
- onClick={() => setFocusDayOffset(0)}
- disabled={clampedOffset === 0}
- >
- Today
- </Button>
- <Button
- variant="outline"
- size="sm"
- className="h-7 w-7 p-0"
- onClick={() => setFocusDayOffset((o) => Math.min(offsetMax, o + visibleDays))}
- disabled={clampedOffset >= offsetMax}
- aria-label="Next week"
- >
- <ChevronRight className="size-3.5" />
- </Button>
- </div>
- </div>
-
- {/* Day grid — borderless day wells separated by gaps; today is
- an elevated card (Codex elevation instead of grid lines). */}
- <div>
- <div
- className="grid gap-1.5"
- style={{ gridTemplateColumns: `repeat(${visibleDays}, minmax(0, 1fr))` }}
- >
- {Array.from({ length: visibleDays }).map((_, i) => {
- const dayIndex = clampedOffset + i;
- const dayStart = startOfFirstDay + dayIndex * DAY_MS;
- const dayOccs = days[dayIndex] ?? [];
- return (
- <DayColumn
- key={dayIndex}
- dayStart={dayStart}
- occurrences={dayOccs}
- onSelect={(o) => setSelected(o)}
- />
- );
- })}
- </div>
- </div>
- </div>
-
- <CronDetailDialog
- occurrence={selected}
- cron={selectedCron}
- onClose={() => setSelected(null)}
- />
- </>
- );
-}
-
-// --- Day column ---
-
-function FilterChips({
- filter,
- onChange,
-}: {
- filter: CronFilter;
- onChange: (f: CronFilter) => void;
-}) {
- const items: Array<{ key: CronFilter; label: string }> = [
- { key: "enabled", label: "Enabled" },
- { key: "disabled", label: "Disabled" },
- { key: "all", label: "All" },
- ];
- return (
- <div
- className="inline-flex items-center gap-0.5 rounded-md bg-[hsl(var(--notfair-surface-2))] p-0.5"
- role="tablist"
- aria-label="Filter crons"
- >
- {items.map(({ key, label }) => {
- const isActive = filter === key;
- return (
- <button
- key={key}
- type="button"
- role="tab"
- aria-selected={isActive}
- onClick={() => onChange(key)}
- className={cn(
- "rounded px-2 py-0.5 text-[11px] font-medium transition-colors",
- isActive
- ? "bg-card text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- {label}
- </button>
- );
- })}
- </div>
- );
-}
-
-function DayColumn({
- dayStart,
- occurrences,
- onSelect,
-}: {
- dayStart: number;
- occurrences: CalendarOccurrence[];
- onSelect: (o: CalendarOccurrence) => void;
-}) {
- const date = new Date(dayStart);
- const today = new Date();
- const isToday =
- date.getFullYear() === today.getFullYear() &&
- date.getMonth() === today.getMonth() &&
- date.getDate() === today.getDate();
- const dayLabel = date.toLocaleDateString(undefined, { weekday: "short" });
- const dateLabel = date.toLocaleDateString(undefined, { month: "numeric", day: "numeric" });
-
- return (
- <div
- className={cn(
- "flex min-h-[280px] flex-col rounded-[10px]",
- isToday
- ? "bg-card shadow-[var(--notfair-shadow)]"
- : "bg-[hsl(var(--notfair-ink)/0.035)]",
- )}
- >
- <div className="px-2 py-1.5 text-center">
- <div
- className={cn(
- "text-[10px] uppercase tracking-wide text-muted-foreground",
- isToday && "text-foreground font-medium",
- )}
- >
- {dayLabel}
- </div>
- <div
- className={cn(
- "text-sm tabular-nums",
- isToday ? "font-semibold text-foreground" : "text-foreground/80",
- )}
- >
- {dateLabel}
- </div>
- </div>
- <div className="flex-1 space-y-1 overflow-y-auto p-1.5">
- {occurrences.length === 0 ? (
- <div className="flex h-full items-center justify-center pb-6">
- <span className="text-[10px] text-muted-foreground/60">·</span>
- </div>
- ) : (
- occurrences.map((o, idx) => (
- <OccurrenceChip
- key={`${o.cron_id}-${o.at}-${idx}`}
- occurrence={o}
- onClick={() => onSelect(o)}
- />
- ))
- )}
- </div>
- </div>
- );
-}
-
-function OccurrenceChip({
- occurrence,
- onClick,
-}: {
- occurrence: CalendarOccurrence;
- onClick: () => void;
-}) {
- const color = colorForAgentSlug(occurrence.agent_slug);
- const time = new Date(occurrence.at).toLocaleTimeString(undefined, {
- hour: "numeric",
- minute: "2-digit",
- });
- return (
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "block w-full rounded-[7px] px-2 py-1 text-left text-[11px] leading-tight transition-colors",
- "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] hover:bg-[hsl(var(--notfair-hover))]",
- occurrence.cron_disabled && "opacity-50",
- )}
- title={`${occurrence.cron_name} · ${occurrence.schedule_text}${
- occurrence.cron_disabled ? " · disabled" : ""
- }${occurrence.run_status ? ` · ${occurrence.run_status}` : ""}`}
- >
- <div className="flex items-center justify-between gap-1 font-mono tabular-nums font-medium">
- <span
- className={cn(
- "flex items-center gap-1.5",
- occurrence.cron_disabled && "line-through",
- )}
- >
- <span
- aria-hidden
- className={cn("inline-block size-1.5 shrink-0 rounded-full", color.dot)}
- />
- {time}
- </span>
- {occurrence.cron_disabled ? (
- <Pause className="size-3 shrink-0 text-muted-foreground" />
- ) : (
- <RunStatusGlyph status={occurrence.run_status} />
- )}
- </div>
- <div className="truncate font-mono opacity-80">{occurrence.short_name}</div>
- </button>
- );
-}
-
-function RunStatusGlyph({ status }: { status: string | undefined }) {
- if (!status) return null;
- const lower = status.toLowerCase();
- if (lower === "ok") {
- return (
- <span
- className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-full bg-[hsl(var(--notfair-accent))] text-white"
- aria-label="success"
- >
- <Check className="size-2.5" strokeWidth={3} />
- </span>
- );
- }
- if (lower === "error") {
- return (
- <span
- className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-full bg-destructive text-white"
- aria-label="error"
- >
- <AlertCircle className="size-2.5" strokeWidth={3} />
- </span>
- );
- }
- // Other statuses (e.g. "skipped"): show a neutral dot to flag "ran but
- // neither ok nor error". Keeps the chip honest without picking a color.
- return (
- <span
- className="inline-flex size-2 shrink-0 rounded-full bg-[hsl(var(--notfair-ink-4))]"
- aria-label={status}
- />
- );
-}
-
-// --- Detail dialog with pause/resume/delete ---
-
-function CronDetailDialog({
- occurrence,
- cron,
- onClose,
-}: {
- occurrence: CalendarOccurrence | null;
- cron: CalendarCron | null;
- onClose: () => void;
-}) {
- const [runs, setRuns] = useState<CronRunWithTick[] | null>(null);
- const [runsLoading, setRunsLoading] = useState(false);
- const [runsError, setRunsError] = useState<string | null>(null);
-
- // Fetch this cron's run history when the dialog opens. Stays mounted across
- // occurrence clicks for the same cron, so cache by id.
- useEffect(() => {
- if (!cron) {
- setRuns(null);
- setRunsError(null);
- return;
- }
- let cancelled = false;
- setRunsLoading(true);
- setRunsError(null);
- (async () => {
- const r = await getCronRunsAction(cron.id, cron.schedule_raw ?? null, 200);
- if (cancelled) return;
- if (r.ok) setRuns(r.runs);
- else setRunsError(r.error);
- setRunsLoading(false);
- })();
- return () => {
- cancelled = true;
- };
- }, [cron]);
-
- // Prompt-edit state lives here (not in EditablePrompt) so the section
- // header can host the Edit / Save / Cancel buttons next to the title.
- const [promptEditing, setPromptEditing] = useState(false);
- const [promptDraft, setPromptDraft] = useState(cron?.message ?? "");
- const [promptPending, startPromptTransition] = useTransition();
- useEffect(() => {
- setPromptEditing(false);
- setPromptDraft(cron?.message ?? "");
- }, [cron?.id, cron?.message]);
-
- if (!occurrence || !cron) return null;
- const matchedRun = findRunForOccurrence(runs, occurrence.at);
- const occStatus = computeOccurrenceStatus(occurrence, matchedRun);
-
- function savePrompt() {
- const trimmed = promptDraft.trim();
- if (!trimmed) {
- toast.error("Prompt cannot be empty.");
- return;
- }
- if (trimmed === cron!.message) {
- setPromptEditing(false);
- return;
- }
- startPromptTransition(async () => {
- const r = await updateCronPromptAction(cron!.id, trimmed);
- if (!r.ok) {
- toast.error(r.error ?? "Could not update prompt");
- return;
- }
- setPromptEditing(false);
- toast.success("Prompt updated");
- });
- }
-
- function cancelPromptEdit() {
- setPromptDraft(cron!.message ?? "");
- setPromptEditing(false);
- }
-
- return (
- <Dialog open={!!occurrence} onOpenChange={(o) => !o && onClose()}>
- <DialogContent className="flex max-h-[80vh] max-w-xl flex-col gap-0 p-0">
- {/* Header — single row: title + status pill, tight padding. */}
- <DialogHeader className="shrink-0 space-y-0 border-b px-4 py-2.5">
- <div className="flex items-center gap-2">
- <DialogTitle className="truncate text-sm font-semibold leading-tight">
- {cron.short_name}
- </DialogTitle>
- <OccurrenceStatusBadge status={occStatus} />
- </div>
- {cron.description && (
- <DialogDescription className="mt-0.5 truncate text-[11px] text-muted-foreground">
- {cron.description}
- </DialogDescription>
- )}
- </DialogHeader>
-
- {/* Body — scrolls. Sections are flat (no card chrome) to keep the
- modal short when collapsed. */}
- <div className="min-h-0 flex-1 divide-y overflow-y-auto">
- <CollapsibleSection title="Details" defaultOpen>
- <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-[11px]">
- <dt className="text-muted-foreground">Full name</dt>
- <dd className="truncate font-mono">{cron.full_name}</dd>
-
- <dt className="text-muted-foreground">Agent</dt>
- <dd className="font-mono">{cron.agent_id}</dd>
-
- <dt className="text-muted-foreground">Schedule</dt>
- <dd className="font-mono">{cron.schedule_text}</dd>
-
- <dt className="text-muted-foreground">Occurrence</dt>
- <dd className="tabular-nums">{new Date(occurrence.at).toLocaleString()}</dd>
-
- {matchedRun && (
- <>
- <dt className="text-muted-foreground">Finished</dt>
- <dd className="tabular-nums">
- {new Date(matchedRun.finished_at_ms).toLocaleString()}
- {matchedRun.duration_ms != null && (
- <span className="ml-1 text-muted-foreground">
- ({formatDuration(matchedRun.duration_ms)})
- </span>
- )}
- </dd>
- {matchedRun.model && (
- <>
- <dt className="text-muted-foreground">Model</dt>
- <dd className="font-mono">
- {matchedRun.model}
- {matchedRun.provider && (
- <span className="ml-1 text-muted-foreground">
- · {matchedRun.provider}
- </span>
- )}
- </dd>
- </>
- )}
- {matchedRun.usage?.total_tokens != null && (
- <>
- <dt className="text-muted-foreground">Tokens</dt>
- <dd className="tabular-nums">
- {matchedRun.usage.total_tokens.toLocaleString()}
- </dd>
- </>
- )}
- </>
- )}
- </dl>
- </CollapsibleSection>
-
- {cron.message != null && (
- <CollapsibleSection
- title="Prompt"
- defaultOpen
- actions={
- promptEditing ? (
- <>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={cancelPromptEdit}
- disabled={promptPending}
- className="h-6 px-2 text-[11px]"
- >
- <X className="mr-1 size-3" />
- Cancel
- </Button>
- <Button
- type="button"
- size="sm"
- onClick={savePrompt}
- disabled={promptPending}
- className="h-6 px-2 text-[11px]"
- >
- {promptPending ? (
- <Loader2 className="mr-1 size-3 animate-spin" />
- ) : (
- <Save className="mr-1 size-3" />
- )}
- Save
- </Button>
- </>
- ) : (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => setPromptEditing(true)}
- className="h-6 px-2 text-[11px]"
- >
- <Pencil className="mr-1 size-3" />
- Edit
- </Button>
- )
- }
- >
- {promptEditing ? (
- <textarea
- value={promptDraft}
- onChange={(e) => setPromptDraft(e.target.value)}
- disabled={promptPending}
- className="max-h-64 min-h-[80px] w-full resize-y overflow-y-auto rounded border bg-background p-2 font-mono text-[11px] leading-relaxed focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50"
- rows={6}
- autoFocus
- />
- ) : (
- <pre className="max-h-56 overflow-y-auto whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed">
- {cron.message}
- </pre>
- )}
- </CollapsibleSection>
- )}
-
- {matchedRun?.error && (
- <CollapsibleSection title="Error" tone="destructive" defaultOpen>
- <div className="whitespace-pre-wrap break-words font-mono text-[11px] text-muted-foreground">
- {matchedRun.error}
- </div>
- </CollapsibleSection>
- )}
-
- <CollapsibleSection title="Result" defaultOpen>
- {matchedRun ? (
- matchedRun.summary ? (
- <div className="max-h-64 overflow-y-auto whitespace-pre-wrap break-words text-[12px] leading-relaxed">
- {matchedRun.summary}
- </div>
- ) : (
- <div className="text-[11px] text-muted-foreground">
- Run finished with no summary.
- </div>
- )
- ) : runsLoading ? (
- <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
- <Loader2 className="size-3 animate-spin" /> Loading…
- </div>
- ) : runsError ? (
- <div className="text-[11px] text-destructive">{runsError}</div>
- ) : occurrence.at <= Date.now() ? (
- <div className="text-[11px] text-muted-foreground">
- No run log for this occurrence.
- </div>
- ) : (
- <div className="text-[11px] text-muted-foreground">
- Not fired yet.
- </div>
- )}
- </CollapsibleSection>
- </div>
-
- {/* Footer — sticky, tight. */}
- <DialogFooter className="shrink-0 gap-2 border-t bg-background/95 px-4 py-2 sm:gap-2">
- <CronActions cronId={cron.id} cronName={cron.short_name} disabled={cron.disabled} onAfter={onClose} />
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
-
-function CollapsibleSection({
- title,
- tone = "default",
- defaultOpen,
- actions,
- children,
-}: {
- title: string;
- tone?: "default" | "destructive";
- defaultOpen?: boolean;
- /** Right-aligned controls in the section header (don't toggle the section). */
- actions?: React.ReactNode;
- children: React.ReactNode;
-}) {
- const [open, setOpen] = useState(!!defaultOpen);
- useEffect(() => {
- setOpen(!!defaultOpen);
- }, [defaultOpen]);
-
- return (
- <section className={cn(tone === "destructive" && "bg-destructive/5")}>
- <div className="flex items-center gap-2 pr-2">
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- className={cn(
- "flex flex-1 items-center gap-1.5 px-4 py-1.5 text-left text-[10px] font-semibold uppercase tracking-wide",
- tone === "destructive" ? "text-destructive" : "text-muted-foreground hover:text-foreground",
- )}
- aria-expanded={open}
- >
- <ChevronRightSmall
- className={cn("size-3 transition-transform", open && "rotate-90")}
- />
- {title}
- </button>
- {actions && (
- <div className="flex shrink-0 items-center gap-1">{actions}</div>
- )}
- </div>
- {open && <div className="px-4 pb-3">{children}</div>}
- </section>
- );
-}
-
-
-function findRunForOccurrence(
- runs: CronRunWithTick[] | null,
- occAt: number,
-): CronRunWithTick | null {
- if (!runs?.length) return null;
- // Preferred path: server tagged each run with its owning nominal tick via
- // the cron schedule. Exact match handles late-fires (e.g., a 11:00 tick
- // whose run actually ran at 11:06:20) without time-window guesswork.
- const exact = runs.find((r) => r.owning_occurrence_at_ms === occAt);
- if (exact) return exact;
- // Fallback for older schedules we couldn't parse: pick the closest run
- // within ±15 minutes — wide enough to cover scheduler drift but tight
- // enough to keep adjacent hourly ticks from cross-matching.
- let best: CronRunWithTick | null = null;
- let bestDelta = Number.POSITIVE_INFINITY;
- for (const r of runs) {
- const delta = Math.abs(r.run_at_ms - occAt);
- if (delta < bestDelta && delta < 15 * 60_000) {
- best = r;
- bestDelta = delta;
- }
- }
- return best;
-}
-
-function formatDuration(ms: number): string {
- if (ms < 1000) return `${ms} ms`;
- if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
- return `${Math.round(ms / 60_000)}m`;
-}
-
-type OccurrenceStatus =
- /** Future tick the scheduler hasn't fired yet. */
- | { kind: "scheduled"; at: number }
- /** Past tick we have a status string for from OpenClaw (verbatim). */
- | { kind: "ran"; at: number; raw: string }
- /** Past tick but no status from OpenClaw (the cron has never run here, or we
- * don't have a recent enough run to align). */
- | { kind: "past"; at: number };
-
-/**
- * Decide how to label this occurrence using OpenClaw's own status vocabulary:
- * - future → "scheduled"
- * - past tick with a matching entry in the run log → show that run's raw
- * status string (e.g. "ok", "error", "skipped")
- * - past tick with no matching run → "past"
- */
-function computeOccurrenceStatus(
- occ: CalendarOccurrence,
- run: CronRunWithTick | null,
-): OccurrenceStatus {
- if (occ.at > Date.now()) return { kind: "scheduled", at: occ.at };
- if (run) return { kind: "ran", at: occ.at, raw: run.status };
- return { kind: "past", at: occ.at };
-}
-
-function OccurrenceStatusBadge({ status }: { status: OccurrenceStatus }) {
- // Monochrome chrome: only run outcomes carry color (green ok / red
- // error). "scheduled" and "past" are neutral inset pills.
- if (status.kind === "scheduled") {
- return <Pill cls="ns-tag-mono">scheduled</Pill>;
- }
- if (status.kind === "past") {
- return <Pill cls="ns-tag-mono opacity-70">past</Pill>;
- }
- // Past run with a known status — show OpenClaw's raw string, color by it.
- return <Pill cls={colorForRawStatus(status.raw)}>{status.raw}</Pill>;
-}
-
-function colorForRawStatus(raw: string): string {
- const lower = raw.toLowerCase();
- if (lower === "ok") {
- return "ns-tag-accent font-mono";
- }
- if (lower === "error") {
- return "ns-tag-red font-mono";
- }
- return "ns-tag-mono";
-}
-
-function Pill({ cls, children }: { cls: string; children: React.ReactNode }) {
- return (
- <span
- className={cn(
- "inline-flex w-fit items-center gap-1 rounded-md px-2 py-0.5 font-mono text-[11px] font-medium",
- cls,
- )}
- >
- {children}
- </span>
- );
-}
-
-function CronActions({
- cronId,
- cronName,
- disabled,
- onAfter,
-}: {
- cronId: string;
- cronName: string;
- disabled: boolean;
- onAfter: () => void;
-}) {
- function run(
- label: string,
- fn: () => Promise<{ ok: boolean; error?: string }>,
- ) {
- void (async () => {
- const r = await fn();
- if (!r.ok) toast.error(r.error ?? `Failed to ${label}`);
- else toast.success(`${label}: ${cronName}`);
- onAfter();
- })();
- }
-
- return (
- <>
- {disabled ? (
- <Button
- variant="outline"
- size="sm"
- onClick={() => run("Enabled", () => resumeCronAction(cronId))}
- >
- <Play className="mr-1.5 size-3.5" />
- Enable
- </Button>
- ) : (
- <Button
- variant="outline"
- size="sm"
- onClick={() => run("Disabled", () => pauseCronAction(cronId))}
- >
- <Pause className="mr-1.5 size-3.5" />
- Disable
- </Button>
- )}
- <Button
- variant="outline"
- size="sm"
- onClick={() => {
- if (typeof window !== "undefined" && !window.confirm(`Delete cron "${cronName}"?`)) return;
- run("Deleted", () => deleteCronAction(cronId));
- }}
- className="text-destructive hover:text-destructive"
- >
- <Trash2 className="mr-1.5 size-3.5" />
- Delete
- </Button>
- </>
- );
-}
diff --git a/notfair-cmo/src/components/cron-row-actions.test.tsx b/notfair-cmo/src/components/cron-row-actions.test.tsx
deleted file mode 100644
index e49764f4..00000000
--- a/notfair-cmo/src/components/cron-row-actions.test.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-// Radix DropdownMenu / Dialog depend on a few DOM APIs jsdom doesn't ship.
-// Polyfill them on Element so Radix can mount and respond to pointer events.
-if (typeof Element !== "undefined") {
- // @ts-expect-error - jsdom shim
- Element.prototype.hasPointerCapture ??= () => false;
- // @ts-expect-error - jsdom shim
- Element.prototype.setPointerCapture ??= () => {};
- // @ts-expect-error - jsdom shim
- Element.prototype.releasePointerCapture ??= () => {};
- // @ts-expect-error - jsdom shim
- Element.prototype.scrollIntoView ??= () => {};
-}
-
-const pauseCronAction = vi.fn();
-const resumeCronAction = vi.fn();
-const deleteCronAction = vi.fn();
-
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
-};
-
-vi.mock("@/server/actions/crons", () => ({
- pauseCronAction: (...args: unknown[]) => pauseCronAction(...args),
- resumeCronAction: (...args: unknown[]) => resumeCronAction(...args),
- deleteCronAction: (...args: unknown[]) => deleteCronAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- },
-}));
-
-import { CronRowActions } from "./cron-row-actions";
-
-function openMenu() {
- const trigger = screen.getByRole("button", { name: /cron actions/i });
- fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });
- fireEvent.click(trigger);
-}
-
-beforeEach(() => {
- pauseCronAction.mockReset();
- resumeCronAction.mockReset();
- deleteCronAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("CronRowActions", () => {
- it("shows a 'Pause' menu item when the cron is enabled", () => {
- render(<CronRowActions cronId="c1" cronName="daily-bid-opt" disabled={false} />);
- openMenu();
- expect(screen.getByText("Pause")).toBeInTheDocument();
- expect(screen.queryByText("Resume")).not.toBeInTheDocument();
- });
-
- it("shows a 'Resume' menu item when the cron is disabled", () => {
- render(<CronRowActions cronId="c1" cronName="daily-bid-opt" disabled={true} />);
- openMenu();
- expect(screen.getByText("Resume")).toBeInTheDocument();
- expect(screen.queryByText("Pause")).not.toBeInTheDocument();
- });
-
- it("calls pauseCronAction and toasts success when Pause is clicked", async () => {
- pauseCronAction.mockResolvedValue({ ok: true });
- render(<CronRowActions cronId="c-pause" cronName="hourly-sweep" disabled={false} />);
- openMenu();
- fireEvent.click(screen.getByText("Pause"));
- await waitFor(() => expect(pauseCronAction).toHaveBeenCalledWith("c-pause"));
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Paused: hourly-sweep"));
- });
-
- it("calls resumeCronAction and toasts success when Resume is clicked", async () => {
- resumeCronAction.mockResolvedValue({ ok: true });
- render(<CronRowActions cronId="c-resume" cronName="weekly-roundup" disabled={true} />);
- openMenu();
- fireEvent.click(screen.getByText("Resume"));
- await waitFor(() => expect(resumeCronAction).toHaveBeenCalledWith("c-resume"));
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Resumed: weekly-roundup"));
- });
-
- it("toasts the server error when pause fails", async () => {
- pauseCronAction.mockResolvedValue({ ok: false, error: "openclaw exploded" });
- render(<CronRowActions cronId="c1" cronName="x" disabled={false} />);
- openMenu();
- fireEvent.click(screen.getByText("Pause"));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("openclaw exploded"));
- expect(toast.success).not.toHaveBeenCalled();
- });
-
- it("falls back to a generic error when the action returns ok=false without a message", async () => {
- resumeCronAction.mockResolvedValue({ ok: false });
- render(<CronRowActions cronId="c1" cronName="x" disabled={true} />);
- openMenu();
- fireEvent.click(screen.getByText("Resume"));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Failed to Resumed"));
- });
-
- it("deletes when the user confirms the prompt", async () => {
- const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true);
- deleteCronAction.mockResolvedValue({ ok: true });
- render(<CronRowActions cronId="c-del" cronName="goner" disabled={false} />);
- openMenu();
- fireEvent.click(screen.getByText("Delete"));
- expect(confirmSpy).toHaveBeenCalledWith('Delete cron "goner"?');
- await waitFor(() => expect(deleteCronAction).toHaveBeenCalledWith("c-del"));
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Deleted: goner"));
- confirmSpy.mockRestore();
- });
-
- it("does not call deleteCronAction when the user cancels the confirm prompt", () => {
- const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false);
- render(<CronRowActions cronId="c-del" cronName="lucky" disabled={false} />);
- openMenu();
- fireEvent.click(screen.getByText("Delete"));
- expect(deleteCronAction).not.toHaveBeenCalled();
- confirmSpy.mockRestore();
- });
-});
diff --git a/notfair-cmo/src/components/cron-row-actions.tsx b/notfair-cmo/src/components/cron-row-actions.tsx
deleted file mode 100644
index 9c27b93f..00000000
--- a/notfair-cmo/src/components/cron-row-actions.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-"use client";
-
-import { useTransition } from "react";
-import { MoreHorizontal, Pause, Play, Trash2 } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { toast } from "sonner";
-import { pauseCronAction, resumeCronAction, deleteCronAction } from "@/server/actions/crons";
-
-type Props = {
- cronId: string;
- cronName: string;
- disabled: boolean;
-};
-
-export function CronRowActions({ cronId, cronName, disabled }: Props) {
- const [pending, start] = useTransition();
-
- function run(label: string, fn: () => Promise<{ ok: boolean; error?: string }>) {
- start(async () => {
- const r = await fn();
- if (!r.ok) toast.error(r.error ?? `Failed to ${label}`);
- else toast.success(`${label}: ${cronName}`);
- });
- }
-
- function confirmDelete() {
- if (typeof window !== "undefined" && !window.confirm(`Delete cron "${cronName}"?`)) return;
- run("Deleted", () => deleteCronAction(cronId));
- }
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-7 w-7 p-0" disabled={pending}>
- <MoreHorizontal className="size-4" />
- <span className="sr-only">Cron actions</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-40">
- {disabled ? (
- <DropdownMenuItem
- onSelect={() => run("Resumed", () => resumeCronAction(cronId))}
- disabled={pending}
- >
- <Play className="mr-2 size-3.5" />
- Resume
- </DropdownMenuItem>
- ) : (
- <DropdownMenuItem
- onSelect={() => run("Paused", () => pauseCronAction(cronId))}
- disabled={pending}
- >
- <Pause className="mr-2 size-3.5" />
- Pause
- </DropdownMenuItem>
- )}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={confirmDelete}
- disabled={pending}
- className="text-destructive focus:text-destructive"
- >
- <Trash2 className="mr-2 size-3.5" />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/notfair-cmo/src/components/danger-zone.test.tsx b/notfair-cmo/src/components/danger-zone.test.tsx
deleted file mode 100644
index e9efbe73..00000000
--- a/notfair-cmo/src/components/danger-zone.test.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const router = {
- push: vi.fn(),
- refresh: vi.fn(),
-};
-const getProjectDeletionSummaryAction = vi.fn();
-const deleteProjectAction = vi.fn();
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
- warning: vi.fn(),
-};
-
-vi.mock("next/navigation", () => ({
- useRouter: () => router,
-}));
-
-vi.mock("@/server/actions/projects", () => ({
- getProjectDeletionSummaryAction: (...args: unknown[]) =>
- getProjectDeletionSummaryAction(...args),
- deleteProjectAction: (...args: unknown[]) => deleteProjectAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- warning: (...args: unknown[]) => toast.warning(...args),
- },
-}));
-
-import { DangerZone } from "./danger-zone";
-
-const summary = {
- totals: { agents: 3, threads: 5, crons: 2, mcps: 1 },
- agents: [
- {
- agentId: "proj-cmo",
- display_name: "CMO",
- threadCount: 4,
- exists: true,
- },
- {
- agentId: "proj-old",
- display_name: "Old",
- threadCount: 0,
- exists: false,
- },
- ],
-};
-
-beforeEach(() => {
- router.push.mockReset();
- router.refresh.mockReset();
- getProjectDeletionSummaryAction.mockReset();
- deleteProjectAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
- toast.warning.mockReset();
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("DangerZone (project)", () => {
- it("renders the delete-workspace CTA card", () => {
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- expect(screen.getByText("Delete this workspace")).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /delete workspace/i }),
- ).toBeInTheDocument();
- });
-
- it("opens the confirm dialog with loading state", async () => {
- getProjectDeletionSummaryAction.mockImplementation(
- () => new Promise(() => {}),
- );
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
- expect(
- await screen.findByText(/counting what will be removed/i),
- ).toBeInTheDocument();
- });
-
- it("shows summary stats and existing agents in the dialog", async () => {
- getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
- expect(await screen.findByText("3")).toBeInTheDocument();
- expect(screen.getByText("Agents")).toBeInTheDocument();
- expect(screen.getByText("Threads")).toBeInTheDocument();
- expect(screen.getByText("Crons")).toBeInTheDocument();
- expect(screen.getByText("MCPs")).toBeInTheDocument();
- expect(screen.getByText("CMO")).toBeInTheDocument();
- expect(screen.getByText("proj-cmo")).toBeInTheDocument();
- expect(screen.getByText(/4 threads/)).toBeInTheDocument();
- expect(screen.queryByText("Old")).not.toBeInTheDocument();
- });
-
- it("renders the error message when summary load fails", async () => {
- getProjectDeletionSummaryAction.mockResolvedValue({
- ok: false,
- error: "boom",
- });
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
- expect(
- await screen.findByText(/could not load deletion summary: boom/i),
- ).toBeInTheDocument();
- });
-
- it("deletes the project and routes home on success", async () => {
- getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
- deleteProjectAction.mockResolvedValue({
- ok: true,
- data: {
- agents: [{ agentId: "a" }, { agentId: "b" }],
- crons: 2,
- agentsFailed: [],
- cronsFailed: 0,
- },
- });
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
- await screen.findByText("CMO");
- fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
- await waitFor(() =>
- expect(deleteProjectAction).toHaveBeenCalledWith("alpha", "alpha"),
- );
- await waitFor(() =>
- expect(toast.success).toHaveBeenCalledWith(
- "Deleted Alpha. 2 agents, 2 crons removed.",
- ),
- );
- await waitFor(() => expect(router.push).toHaveBeenCalledWith("/"));
- });
-
- it("warns when partial failures happen on delete", async () => {
- getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
- deleteProjectAction.mockResolvedValue({
- ok: true,
- data: {
- agents: [{ agentId: "a" }],
- crons: 1,
- agentsFailed: ["x"],
- cronsFailed: 2,
- },
- });
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
- await screen.findByText("CMO");
- fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
- await waitFor(() =>
- expect(toast.warning.mock.calls[0][0]).toMatch(/3 issues/),
- );
- });
-
- it("toasts the server error on delete failure", async () => {
- getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
- deleteProjectAction.mockResolvedValue({ ok: false, error: "denied" });
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
- await screen.findByText("CMO");
- fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("denied"));
- expect(router.push).not.toHaveBeenCalled();
- });
-
- it("closes the dialog on Cancel", async () => {
- getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });
- render(<DangerZone projectSlug="alpha" projectName="Alpha" />);
- fireEvent.click(screen.getByRole("button", { name: /delete workspace/i }));
- await screen.findByText("CMO");
- fireEvent.click(screen.getByRole("button", { name: /cancel/i }));
- await waitFor(() => expect(screen.queryByText("CMO")).not.toBeInTheDocument());
- });
-});
diff --git a/notfair-cmo/src/components/disable-source-crons-dialog.test.tsx b/notfair-cmo/src/components/disable-source-crons-dialog.test.tsx
deleted file mode 100644
index a354dcf0..00000000
--- a/notfair-cmo/src/components/disable-source-crons-dialog.test.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-if (typeof Element !== "undefined") {
- // @ts-expect-error - jsdom shim
- Element.prototype.hasPointerCapture ??= () => false;
- // @ts-expect-error - jsdom shim
- Element.prototype.setPointerCapture ??= () => {};
- // @ts-expect-error - jsdom shim
- Element.prototype.releasePointerCapture ??= () => {};
- // @ts-expect-error - jsdom shim
- Element.prototype.scrollIntoView ??= () => {};
-}
-
-const disableCronsAction = vi.fn();
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
- warning: vi.fn(),
-};
-
-vi.mock("@/server/actions/agents", () => ({
- disableCronsAction: (...args: unknown[]) => disableCronsAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- warning: (...args: unknown[]) => toast.warning(...args),
- },
-}));
-
-import { DisableSourceCronsDialog } from "./disable-source-crons-dialog";
-
-beforeEach(() => {
- disableCronsAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
- toast.warning.mockReset();
-});
-
-afterEach(() => cleanup());
-
-function renderDialog(overrides: Partial<Parameters<typeof DisableSourceCronsDialog>[0]> = {}) {
- const onOpenChange = vi.fn();
- const onDone = vi.fn();
- const sourceCrons = overrides.sourceCrons ?? [
- { id: "c1", name: "daily-sweep", disabled: false },
- { id: "c2", name: "weekly-report", disabled: false },
- { id: "c3", name: "already-off", disabled: true },
- ];
- render(
- <DisableSourceCronsDialog
- open
- onOpenChange={onOpenChange}
- sourceLabel="acme-ads"
- newAgentId="new-ads"
- sourceCrons={sourceCrons}
- onDone={onDone}
- {...overrides}
- />,
- );
- return { onOpenChange, onDone };
-}
-
-describe("DisableSourceCronsDialog", () => {
- it("renders the source label, count, and new agent id in the description", () => {
- renderDialog();
- // dialog title escapes apostrophe
- expect(screen.getByRole("heading", { name: /Disable acme-ads.*cron jobs\?/i })).toBeInTheDocument();
- expect(screen.getByText(/We just copied 3 cron jobs/)).toBeInTheDocument();
- expect(screen.getByText("acme-ads")).toBeInTheDocument();
- expect(screen.getByText("new-ads")).toBeInTheDocument();
- });
-
- it("uses singular 'cron job' when there is exactly one", () => {
- renderDialog({ sourceCrons: [{ id: "c1", name: "just-one", disabled: false }] });
- expect(screen.getByText(/We just copied 1 cron job(?!s)/)).toBeInTheDocument();
- });
-
- it("lists each source cron's name and marks the already-disabled ones", () => {
- renderDialog();
- expect(screen.getByText("daily-sweep")).toBeInTheDocument();
- expect(screen.getByText("weekly-report")).toBeInTheDocument();
- expect(screen.getByText("already-off")).toBeInTheDocument();
- expect(screen.getByText(/already off/i)).toBeInTheDocument();
- });
-
- it("hides the list when there are no source crons", () => {
- renderDialog({ sourceCrons: [] });
- // No <ul> rendered → the rows should not exist
- expect(screen.queryByRole("list")).not.toBeInTheDocument();
- });
-
- it('"Keep them running" closes the dialog and signals done without calling the action', () => {
- const { onOpenChange, onDone } = renderDialog();
- fireEvent.click(screen.getByRole("button", { name: /keep them running/i }));
- expect(disableCronsAction).not.toHaveBeenCalled();
- expect(onOpenChange).toHaveBeenCalledWith(false);
- expect(onDone).toHaveBeenCalled();
- });
-
- it('"Disable on source" only disables the currently-enabled source crons', async () => {
- disableCronsAction.mockResolvedValue({ ok: true, data: { disabled: 2, failed: 0 } });
- const { onOpenChange, onDone } = renderDialog();
- fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));
- await waitFor(() => expect(disableCronsAction).toHaveBeenCalledWith(["c1", "c2"]));
- await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Disabled 2 crons on acme-ads"));
- expect(onOpenChange).toHaveBeenCalledWith(false);
- expect(onDone).toHaveBeenCalled();
- });
-
- it("uses singular wording when only one cron is disabled", async () => {
- disableCronsAction.mockResolvedValue({ ok: true, data: { disabled: 1, failed: 0 } });
- renderDialog({ sourceCrons: [{ id: "only", name: "only-one", disabled: false }] });
- fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));
- await waitFor(() =>
- expect(toast.success).toHaveBeenCalledWith("Disabled 1 cron on acme-ads"),
- );
- });
-
- it("emits a warning toast when some disables fail", async () => {
- disableCronsAction.mockResolvedValue({ ok: true, data: { disabled: 1, failed: 1 } });
- renderDialog({
- sourceCrons: [
- { id: "c1", name: "ok-one", disabled: false },
- { id: "c2", name: "bad-one", disabled: false },
- ],
- });
- fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));
- await waitFor(() =>
- expect(toast.warning).toHaveBeenCalledWith("Disabled 1 crons (1 failed)"),
- );
- expect(toast.success).not.toHaveBeenCalled();
- });
-
- it("toasts the server error when the action returns ok=false", async () => {
- disableCronsAction.mockResolvedValue({ ok: false, error: "Permission denied" });
- const { onOpenChange, onDone } = renderDialog();
- fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Permission denied"));
- // Returns early — dialog stays open
- expect(onOpenChange).not.toHaveBeenCalledWith(false);
- expect(onDone).not.toHaveBeenCalled();
- });
-
- it("short-circuits and closes when every source cron is already disabled", () => {
- const { onOpenChange, onDone } = renderDialog({
- sourceCrons: [
- { id: "c1", name: "off1", disabled: true },
- { id: "c2", name: "off2", disabled: true },
- ],
- });
- fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));
- expect(disableCronsAction).not.toHaveBeenCalled();
- expect(onOpenChange).toHaveBeenCalledWith(false);
- expect(onDone).toHaveBeenCalled();
- });
-});
diff --git a/notfair-cmo/src/components/disable-source-crons-dialog.tsx b/notfair-cmo/src/components/disable-source-crons-dialog.tsx
deleted file mode 100644
index 46c7d0d2..00000000
--- a/notfair-cmo/src/components/disable-source-crons-dialog.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-"use client";
-
-import { useState, useTransition } from "react";
-import { Loader2, Pause } from "lucide-react";
-import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { disableCronsAction } from "@/server/actions/agents";
-import type { CloneSourceCron } from "@/server/agents/clone";
-
-type Props = {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- sourceLabel: string;
- newAgentId: string;
- sourceCrons: CloneSourceCron[];
- onDone: () => void;
-};
-
-export function DisableSourceCronsDialog({
- open,
- onOpenChange,
- sourceLabel,
- newAgentId,
- sourceCrons,
- onDone,
-}: Props) {
- const [pending, startTransition] = useTransition();
- const [completed, setCompleted] = useState(false);
-
- const enabledSource = sourceCrons.filter((c) => !c.disabled);
-
- function disableAll() {
- if (enabledSource.length === 0) {
- finish();
- return;
- }
- startTransition(async () => {
- const r = await disableCronsAction(enabledSource.map((c) => c.id));
- if (!r.ok) {
- toast.error(r.error);
- return;
- }
- if (r.data.failed > 0) {
- toast.warning(`Disabled ${r.data.disabled} crons (${r.data.failed} failed)`);
- } else {
- toast.success(`Disabled ${r.data.disabled} cron${r.data.disabled === 1 ? "" : "s"} on ${sourceLabel}`);
- }
- setCompleted(true);
- finish();
- });
- }
-
- function keepRunning() {
- finish();
- }
-
- function finish() {
- onOpenChange(false);
- onDone();
- }
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-w-md">
- <DialogHeader>
- <DialogTitle className="text-base">Disable {sourceLabel}&rsquo;s cron jobs?</DialogTitle>
- <DialogDescription>
- We just copied {sourceCrons.length} cron job
- {sourceCrons.length === 1 ? "" : "s"} from <span className="font-mono text-xs">{sourceLabel}</span>{" "}
- onto your new agent <span className="font-mono text-xs">{newAgentId}</span>. Leaving the originals
- running will fire both copies on schedule.
- </DialogDescription>
- </DialogHeader>
-
- {sourceCrons.length > 0 && (
- <ul className="max-h-44 space-y-1 overflow-y-auto rounded-lg border bg-card p-2 text-xs">
- {sourceCrons.map((c) => (
- <li key={c.id} className="flex items-center justify-between gap-2 px-2 py-1">
- <span className="truncate">{c.name}</span>
- {c.disabled && (
- <span className="shrink-0 rounded border px-1 text-[9px] uppercase tracking-wide text-muted-foreground">
- already off
- </span>
- )}
- </li>
- ))}
- </ul>
- )}
-
- <DialogFooter className="gap-2 sm:gap-2">
- <Button type="button" variant="outline" onClick={keepRunning} disabled={pending}>
- Keep them running
- </Button>
- <Button type="button" onClick={disableAll} disabled={pending || completed}>
- {pending ? (
- <>
- <Loader2 className="mr-1.5 size-3.5 animate-spin" />
- Disabling…
- </>
- ) : (
- <>
- <Pause className="mr-1.5 size-3.5" />
- Disable on source (recommended)
- </>
- )}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/notfair-cmo/src/components/google-ads-mcp-banner.test.tsx b/notfair-cmo/src/components/google-ads-mcp-banner.test.tsx
deleted file mode 100644
index 8cb4c5c7..00000000
--- a/notfair-cmo/src/components/google-ads-mcp-banner.test.tsx
+++ /dev/null
@@ -1,213 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const { startMcpConnect, toastFns } = vi.hoisted(() => ({
- startMcpConnect: vi.fn(),
- toastFns: {
- success: vi.fn(),
- error: vi.fn(),
- },
-}));
-
-vi.mock("@/server/actions/mcp", () => ({
- startMcpConnect: (...args: unknown[]) => startMcpConnect(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: toastFns,
-}));
-
-import { GoogleAdsMcpBanner } from "./google-ads-mcp-banner";
-import type { McpRuntimeStatus } from "@/server/mcp/state";
-
-const SLUG = "acme";
-
-function setLocation(href: string) {
- const url = new URL(href);
- const fake = {
- pathname: url.pathname,
- search: url.search,
- href: url.href,
- } as Location;
- Object.defineProperty(window, "location", {
- writable: true,
- configurable: true,
- value: fake,
- });
- return fake;
-}
-
-beforeEach(() => {
- startMcpConnect.mockReset();
- toastFns.success.mockReset();
- toastFns.error.mockReset();
- setLocation("http://localhost:3000/acme/agents/google_ads/chat?task=t1");
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("GoogleAdsMcpBanner", () => {
- it("renders nothing when status is connected", () => {
- const { container } = render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{
- state: "connected",
- url: "https://x",
- tools_count: 5,
- last_checked_at: new Date().toISOString(),
- }}
- />,
- );
- expect(container.firstChild).toBeNull();
- });
-
- it("renders the 'connect' copy for not_configured status", () => {
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{ state: "not_configured" }}
- />,
- );
- expect(
- screen.getByText(/Connect NotFair Google Ads to go live/i),
- ).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /^Connect$/ })).toBeInTheDocument();
- });
-
- it("renders the 'reconnect' copy for stale_token status", () => {
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{
- state: "stale_token",
- url: "https://x",
- http_status: 401,
- last_checked_at: new Date().toISOString(),
- }}
- />,
- );
- expect(
- screen.getByText(/Google Ads connection expired/i),
- ).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /Reconnect/i })).toBeInTheDocument();
- });
-
- it("renders the 'unreachable' copy with reconnect action", () => {
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{
- state: "unreachable",
- url: "https://x",
- error: "ECONNRESET",
- last_checked_at: new Date().toISOString(),
- }}
- />,
- );
- expect(
- screen.getByText(/Google Ads connection is unreachable/i),
- ).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /Reconnect/i })).toBeInTheDocument();
- });
-
- it("renders the 'configured_no_token' headline", () => {
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{ state: "configured_no_token", url: "https://x" }}
- />,
- );
- expect(
- screen.getByText(/Google Ads MCP needs a token/i),
- ).toBeInTheDocument();
- });
-
- it("links Manage connections to the project-scoped connections page", () => {
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{ state: "not_configured" }}
- />,
- );
- const link = screen.getByRole("link", { name: /Manage connections/i });
- expect(link).toHaveAttribute("href", `/${SLUG}/connections`);
- });
-
- it("posts the current URL as return_to and redirects on Connect success", async () => {
- startMcpConnect.mockResolvedValue({
- ok: true,
- authorize_url: "https://issuer.example/oauth?state=zzz",
- });
- const loc = setLocation(
- "http://localhost:3000/acme/agents/google_ads/chat?task=abc",
- );
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{ state: "not_configured" }}
- />,
- );
- fireEvent.click(screen.getByRole("button", { name: /^Connect$/ }));
- await waitFor(() =>
- expect(startMcpConnect).toHaveBeenCalledWith({
- mcp_key: "notfair-googleads",
- return_to: "/acme/agents/google_ads/chat?task=abc",
- }),
- );
- await waitFor(() =>
- expect(loc.href).toBe("https://issuer.example/oauth?state=zzz"),
- );
- });
-
- it("toasts and re-enables the button when Connect returns ok=false", async () => {
- startMcpConnect.mockResolvedValue({ ok: false, error: "discovery failed" });
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{ state: "not_configured" }}
- />,
- );
- const button = screen.getByRole("button", { name: /^Connect$/ });
- fireEvent.click(button);
- await waitFor(() =>
- expect(toastFns.error).toHaveBeenCalledWith("discovery failed"),
- );
- expect(button).not.toBeDisabled();
- });
-
- it("toasts the thrown error message when Connect throws", async () => {
- startMcpConnect.mockRejectedValue(new Error("boom"));
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{ state: "not_configured" }}
- />,
- );
- fireEvent.click(screen.getByRole("button", { name: /^Connect$/ }));
- await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("boom"));
- });
-
- it("disables the Connect button while a request is in flight", async () => {
- let resolve: (v: { ok: true; authorize_url: string }) => void = () => {};
- startMcpConnect.mockImplementation(
- () =>
- new Promise<{ ok: true; authorize_url: string }>((res) => {
- resolve = res;
- }),
- );
- render(
- <GoogleAdsMcpBanner
- projectSlug={SLUG}
- status={{ state: "not_configured" }}
- />,
- );
- const button = screen.getByRole("button", { name: /^Connect$/ });
- fireEvent.click(button);
- await waitFor(() => expect(button).toBeDisabled());
- resolve({ ok: true, authorize_url: "https://issuer.example" });
- });
-});
diff --git a/notfair-cmo/src/components/google-ads-mcp-banner.tsx b/notfair-cmo/src/components/google-ads-mcp-banner.tsx
deleted file mode 100644
index 229f4a31..00000000
--- a/notfair-cmo/src/components/google-ads-mcp-banner.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import Link from "next/link";
-import { Loader2, Plug, AlertTriangle } from "lucide-react";
-import { toast } from "sonner";
-import { startMcpConnect } from "@/server/actions/mcp";
-import type { McpRuntimeStatus } from "@/server/mcp/state";
-import { projectHref } from "@/lib/project-href";
-
-type Props = {
- status: McpRuntimeStatus;
- projectSlug: string;
-};
-
-/**
- * Shown above the chat for the Google Ads agent when the notfair-googleads
- * MCP isn't usable yet. The Connect button kicks off the same OAuth flow as
- * the Connections page, but threads the current chat URL through as
- * `return_to` so the user lands back here on success.
- */
-export function GoogleAdsMcpBanner({ status, projectSlug }: Props) {
- const [busy, setBusy] = useState(false);
-
- if (status.state === "connected") return null;
-
- const isStale = status.state === "stale_token";
- const isUnreachable = status.state === "unreachable";
-
- async function onConnect() {
- setBusy(true);
- try {
- // Captured at click time (vs. via useSearchParams) so we don't pull in
- // a hook that would force a Suspense boundary in the page above us.
- const return_to = window.location.pathname + window.location.search;
- const result = await startMcpConnect({
- mcp_key: "notfair-googleads",
- return_to,
- });
- if (!result.ok) {
- toast.error(result.error);
- setBusy(false);
- return;
- }
- // Cross-origin redirect: leave the SPA and head to the issuer.
- window.location.href = result.authorize_url;
- } catch (err) {
- toast.error(err instanceof Error ? err.message : String(err));
- setBusy(false);
- }
- }
-
- const { headline, detail, action } = copyFor(status);
-
- return (
- <div
- className="bg-[hsl(var(--notfair-warn-soft))] px-6 py-3"
- role="status"
- >
- <div className="mx-auto flex w-full max-w-3xl items-start gap-3">
- <div className="mt-0.5 grid size-7 shrink-0 place-items-center rounded-[8px] bg-[hsl(38_92%_92%)] text-[hsl(28_76%_38%)]">
- {isStale || isUnreachable ? (
- <AlertTriangle className="size-4" />
- ) : (
- <Plug className="size-4" />
- )}
- </div>
- <div className="min-w-0 flex-1">
- <div className="text-[13.5px] font-semibold tracking-tight text-[hsl(28_76%_28%)]">
- {headline}
- </div>
- <p className="mt-0.5 text-[12px] text-[hsl(28_55%_36%)]">
- {detail}{" "}
- <Link
- href={projectHref(projectSlug, "/connections")}
- className="underline underline-offset-2 hover:text-[hsl(28_76%_22%)]"
- >
- Manage connections
- </Link>
- </p>
- </div>
- <button
- type="button"
- onClick={onConnect}
- disabled={busy}
- className="ns-btn ns-btn-primary ns-btn-sm shrink-0"
- >
- {busy ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <Plug className="size-3.5" />
- )}
- {action}
- </button>
- </div>
- </div>
- );
-}
-
-function copyFor(status: McpRuntimeStatus): {
- headline: string;
- detail: string;
- action: string;
-} {
- switch (status.state) {
- case "stale_token":
- return {
- headline: "Google Ads connection expired",
- action: "Reconnect",
- detail:
- "The NotFair Google Ads token was rejected. Reconnect to resume live account operations.",
- };
- case "unreachable":
- return {
- headline: "Google Ads connection is unreachable",
- action: "Reconnect",
- detail:
- "Couldn't reach the NotFair Google Ads MCP. The agent will run blind until this is restored.",
- };
- case "configured_no_token":
- return {
- headline: "Google Ads MCP needs a token",
- action: "Connect",
- detail:
- "Connect to enable live campaign, keyword, bid, and budget operations against your account.",
- };
- case "not_configured":
- default:
- return {
- headline: "Connect NotFair Google Ads to go live",
- action: "Connect",
- detail:
- "Connect the MCP to let this agent run campaigns, manage keywords, and pull real metrics from your account.",
- };
- }
-}
diff --git a/notfair-cmo/src/components/live-badge.tsx b/notfair-cmo/src/components/live-badge.tsx
deleted file mode 100644
index 77e4f8cd..00000000
--- a/notfair-cmo/src/components/live-badge.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-"use client";
-
-import { useApprovalsBadge } from "./live-counts-context";
-
-/**
- * Live-updating approvals count badge. Reads from LiveCountsContext so
- * the number refreshes without re-rendering the parent server component.
- * Apple-styled: pill chip in brand-accent green, small and quiet.
- */
-export function ApprovalsLiveBadge() {
- const count = useApprovalsBadge();
- if (count <= 0) return null;
- return (
- <span
- aria-label={`${count} pending approval${count === 1 ? "" : "s"}`}
- className="ml-auto inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-[hsl(var(--notfair-accent))] px-1 text-[10px] font-semibold tabular-nums leading-none text-white"
- >
- {count}
- </span>
- );
-}
diff --git a/notfair-cmo/src/components/live-counts-context.test.tsx b/notfair-cmo/src/components/live-counts-context.test.tsx
deleted file mode 100644
index 7d9169db..00000000
--- a/notfair-cmo/src/components/live-counts-context.test.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * @vitest-environment jsdom
- */
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
-import {
- LiveCountsProvider,
- useApprovalsBadge,
- useInFlightCount,
- type LiveCounts,
-} from "./live-counts-context";
-
-function Probe({ agentId }: { agentId: string }) {
- const approvals = useApprovalsBadge();
- const inFlight = useInFlightCount(agentId);
- return (
- <div>
- <span data-testid="approvals">{approvals}</span>
- <span data-testid="inflight">{inFlight}</span>
- </div>
- );
-}
-
-const initial: LiveCounts = {
- project: "demo1",
- agents: { "demo1-cmo": 0, "demo1-google-ads": 1 },
- approvals: 0,
- attention: {},
-};
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe("LiveCountsProvider", () => {
- it("renders initial server-side counts on first paint", () => {
- vi.spyOn(global, "fetch").mockResolvedValue(
- new Response(JSON.stringify(initial), { status: 200 }),
- );
- render(
- <LiveCountsProvider initial={initial}>
- <Probe agentId="demo1-google-ads" />
- </LiveCountsProvider>,
- );
- expect(screen.getByTestId("approvals").textContent).toBe("0");
- expect(screen.getByTestId("inflight").textContent).toBe("1");
- });
-
- it("updates badges when the polled response differs", async () => {
- vi.spyOn(global, "fetch").mockResolvedValue(
- new Response(
- JSON.stringify({
- project: "demo1",
- agents: { "demo1-google-ads": 3 },
- approvals: 5,
- }),
- { status: 200 },
- ),
- );
- render(
- <LiveCountsProvider initial={initial}>
- <Probe agentId="demo1-google-ads" />
- </LiveCountsProvider>,
- );
- // Initial paint shows the server-side initial values.
- expect(screen.getByTestId("inflight").textContent).toBe("1");
- expect(screen.getByTestId("approvals").textContent).toBe("0");
- // The provider's useEffect fires an immediate `tick()` on mount;
- // wait for the resulting setState to flush through.
- await waitFor(() => {
- expect(screen.getByTestId("approvals").textContent).toBe("5");
- expect(screen.getByTestId("inflight").textContent).toBe("3");
- });
- });
-
- it("does not re-render children when the polled signature is identical", async () => {
- vi.spyOn(global, "fetch").mockResolvedValue(
- new Response(JSON.stringify(initial), { status: 200 }),
- );
- let renders = 0;
- function Counter() {
- renders++;
- const c = useInFlightCount("demo1-google-ads");
- return <span data-testid="c">{c}</span>;
- }
- render(
- <LiveCountsProvider initial={initial}>
- <Counter />
- </LiveCountsProvider>,
- );
- // Give the immediate tick + any state updates a chance to fire.
- await new Promise((r) => setTimeout(r, 50));
- const baseline = renders;
- // Another wait. Multiple ticks happen because vitest doesn't run the
- // interval, but the immediate tick already returned identical data —
- // so the provider should NOT have called setState, and Counter
- // should not have re-rendered beyond the initial mount.
- await new Promise((r) => setTimeout(r, 50));
- expect(renders).toBe(baseline);
- expect(screen.getByTestId("c").textContent).toBe("1");
- });
-});
diff --git a/notfair-cmo/src/components/live-counts-context.tsx b/notfair-cmo/src/components/live-counts-context.tsx
deleted file mode 100644
index a9028298..00000000
--- a/notfair-cmo/src/components/live-counts-context.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-"use client";
-
-import {
- createContext,
- useContext,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-
-/**
- * Client-side live counts for the sidebar. Replaces the previous
- * `router.refresh()`-driven badge updates — the sidebar's structure
- * never changes between polls, only the numbers do, so we keep the
- * server tree stable and just push fresh numbers through context.
- *
- * Stability is the whole point: when the polled response identical to
- * what's already in state, we DON'T call setState, so no descendant
- * re-renders. When the response differs, only the badge nodes that
- * read the new value actually update.
- */
-export interface AgentAttentionEntry {
- /** Pending questions + actionable approvals waiting on the user. */
- count: number;
- /** Oldest waiting item's task id — deep-link target so the badge
- * lands directly in the decision space. Null when none of the
- * waiting items is anchored to a task. */
- task_id: string | null;
-}
-
-export interface LiveCounts {
- /** Project slug the counts belong to. null when no active project. */
- project: string | null;
- /** Map of agent_id → in-flight task count. */
- agents: Record<string, number>;
- /** Project-level actionable approvals count. */
- approvals: number;
- /** Map of agent_id → blocked-on-you signal (Slack-style red badge). */
- attention: Record<string, AgentAttentionEntry>;
-}
-
-const LiveCountsContext = createContext<LiveCounts>({
- project: null,
- agents: {},
- approvals: 0,
- attention: {},
-});
-
-export function useLiveCounts(): LiveCounts {
- return useContext(LiveCountsContext);
-}
-
-export function useInFlightCount(agentId: string): number {
- const { agents } = useLiveCounts();
- return agents[agentId] ?? 0;
-}
-
-export function useApprovalsBadge(): number {
- return useLiveCounts().approvals;
-}
-
-/**
- * Provider that owns the polling loop. Mounted high in the layout so
- * the sidebar + any other consumers (per-agent badges, future
- * dashboard cards) read fresh values without triggering a server
- * round-trip. Polling cadence: 2 s while any agent has in-flight work,
- * 8 s when idle (still useful for cron-driven kickoffs to surface
- * promptly without burning cycles).
- */
-export function LiveCountsProvider({
- initial,
- children,
-}: {
- initial: LiveCounts;
- children: React.ReactNode;
-}) {
- const [counts, setCounts] = useState<LiveCounts>(initial);
- const sigRef = useRef<string>(JSON.stringify(initial));
- const anyInFlight = Object.values(counts.agents).some((n) => n > 0);
-
- useEffect(() => {
- let cancelled = false;
-
- async function tick() {
- try {
- const r = await fetch("/api/in-flight-counts", {
- cache: "no-store",
- credentials: "same-origin",
- });
- if (!r.ok || cancelled) return;
- const body = (await r.json()) as LiveCounts;
- // Canonical signature: same data → same string. Sort agent keys
- // so dictionary-iteration order doesn't create a false diff.
- const sig = JSON.stringify({
- p: body.project,
- a: Object.entries(body.agents)
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([k, v]) => [k, v]),
- v: body.approvals,
- n: Object.entries(body.attention ?? {})
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([k, v]) => [k, v.count, v.task_id]),
- });
- if (sigRef.current === sig) return;
- sigRef.current = sig;
- setCounts({ ...body, attention: body.attention ?? {} });
- } catch {
- // Network hiccup — skip this tick.
- }
- }
-
- // First tick on mount so server-rendered initial values catch up
- // if anything changed between layout-render and effect-fire.
- void tick();
- const interval = setInterval(tick, anyInFlight ? 2_000 : 8_000);
- return () => {
- cancelled = true;
- clearInterval(interval);
- };
- }, [anyInFlight]);
-
- // Stable context value: only changes when counts actually change.
- const value = useMemo(() => counts, [counts]);
-
- return (
- <LiveCountsContext.Provider value={value}>
- {children}
- </LiveCountsContext.Provider>
- );
-}
diff --git a/notfair-cmo/src/components/live-transcript.test.tsx b/notfair-cmo/src/components/live-transcript.test.tsx
deleted file mode 100644
index f3f998b2..00000000
--- a/notfair-cmo/src/components/live-transcript.test.tsx
+++ /dev/null
@@ -1,961 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, act, cleanup } from "@testing-library/react";
-
-const { routerPush, toastFns } = vi.hoisted(() => ({
- routerPush: vi.fn(),
- toastFns: {
- info: vi.fn(),
- error: vi.fn(),
- message: vi.fn(),
- },
-}));
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({
- push: routerPush,
- replace: vi.fn(),
- refresh: vi.fn(),
- back: vi.fn(),
- forward: vi.fn(),
- prefetch: vi.fn(),
- }),
-}));
-
-vi.mock("sonner", () => ({
- toast: toastFns,
-}));
-
-vi.mock("@/components/markdown", () => ({
- Markdown: ({ children }: { children: string }) => (
- <div data-testid="markdown">{children}</div>
- ),
-}));
-
-import { LiveTranscript } from "./live-transcript";
-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
-
-type FetchHandler = (url: string, init?: RequestInit) => Promise<Response>;
-
-function setFetch(handler: FetchHandler) {
- // @ts-expect-error vitest jsdom env
- global.fetch = vi.fn(handler);
-}
-
-function defaultProps(overrides: Partial<React.ComponentProps<typeof LiveTranscript>> = {}) {
- return {
- projectSlug: "demo",
- agentSlug: "cmo",
- agentDisplayName: "CMO",
- threadId: "t1",
- sessionKey: "agent:cmo:t1",
- initialEvents: [] as TranscriptEvent[],
- initialByteOffset: 0,
- ...overrides,
- };
-}
-
-function makeEmptyTranscriptResponse(byteOffset = 0) {
- return new Response(
- JSON.stringify({ events: [], byteOffset, file_size: byteOffset }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- );
-}
-
-beforeEach(() => {
- routerPush.mockClear();
- toastFns.info.mockClear();
- toastFns.error.mockClear();
- toastFns.message.mockClear();
- setFetch(async () => makeEmptyTranscriptResponse());
- // jsdom doesn't implement scrollIntoView; the slash popover calls it inside
- // a useEffect after render. Polyfill once to avoid spurious crashes.
- // @ts-expect-error jsdom polyfill
- if (!Element.prototype.scrollIntoView) {
- // @ts-expect-error jsdom polyfill
- Element.prototype.scrollIntoView = () => {};
- }
- // Stable threadId per test won't pollute KICKOFF_FIRED guard for other tests.
-});
-
-afterEach(() => {
- cleanup();
- vi.useRealTimers();
-});
-
-describe("LiveTranscript empty state", () => {
- it("renders the empty state when no events and composer is idle", () => {
- render(<LiveTranscript {...defaultProps()} />);
- expect(
- screen.getByText(/no messages yet\. say hi to cmo/i),
- ).toBeInTheDocument();
- });
-
- it("hides the empty state when composerDisabled (task in flight)", () => {
- render(<LiveTranscript {...defaultProps({ composerDisabled: true, threadId: "t-disabled" })} />);
- expect(
- screen.queryByText(/no messages yet/i),
- ).not.toBeInTheDocument();
- // WorkingIndicator renders the agent display name as the accent
- // header and a verb-only headline next to it. With no events yet,
- // mood is "waiting" and the headline reads "Starting".
- expect(screen.getByText("CMO")).toBeInTheDocument();
- expect(screen.getByText(/^Starting$/)).toBeInTheDocument();
- });
-});
-
-describe("LiveTranscript working indicator staleness", () => {
- it("shows 'Wrapping up' while the last assistant message is fresh", () => {
- const events: TranscriptEvent[] = [
- { kind: "assistant_text", id: "a1", ts: Date.now() - 2_000, body: "Almost done." },
- ];
- render(
- <LiveTranscript
- {...defaultProps({
- initialEvents: events,
- composerDisabled: true,
- threadId: "t-wrap-fresh",
- })}
- />,
- );
- expect(screen.getByText(/^Wrapping up$/)).toBeInTheDocument();
- });
-
- it("degrades to 'Still working' once the last assistant message goes stale", () => {
- // Codex-style silent stretch: an intermediate narration message is the
- // newest event for minutes while the agent reasons toward its next
- // tool call. The indicator must not claim "Wrapping up" through that.
- const events: TranscriptEvent[] = [
- { kind: "assistant_text", id: "a1", ts: Date.now() - 5 * 60_000, body: "Setting this up now." },
- ];
- render(
- <LiveTranscript
- {...defaultProps({
- initialEvents: events,
- composerDisabled: true,
- threadId: "t-wrap-stale",
- })}
- />,
- );
- expect(screen.getByText(/^Still working$/)).toBeInTheDocument();
- expect(screen.getByText(/quiet for 5m/)).toBeInTheDocument();
- expect(screen.queryByText(/^Wrapping up$/)).not.toBeInTheDocument();
- });
-});
-
-describe("LiveTranscript rendering events", () => {
- it("renders user, assistant text and tool group bubbles", () => {
- const events: TranscriptEvent[] = [
- { kind: "user_message", id: "u1", ts: 1, body: "hello there" },
- { kind: "assistant_text", id: "a1", ts: 2, body: "hi back" },
- {
- kind: "tool_call",
- id: "t1",
- ts: 3,
- tool_call_id: "call-1",
- name: "read",
- label: "/etc/passwd",
- },
- {
- kind: "tool_result",
- id: "r1",
- ts: 4,
- tool_call_id: "call-1",
- name: "read",
- summary: "ok output",
- ok: true,
- },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-render" })} />);
- expect(screen.getByText("hello there")).toBeInTheDocument();
- expect(screen.getByTestId("markdown")).toHaveTextContent("hi back");
- // Tool group now leads with the humanized intent ("Read file") in
- // both summary and expanded row; raw tool identifier ("read") is
- // tucked into a small mono tag on the row, and the label path
- // surfaces as the target detail.
- expect(screen.getAllByText("Read file").length).toBeGreaterThanOrEqual(1);
- expect(screen.getAllByText(/\/etc\/passwd/).length).toBeGreaterThanOrEqual(1);
- expect(screen.getByText(/ok output/)).toBeInTheDocument();
- expect(screen.getByText(/→ result/)).toBeInTheDocument();
- });
-
- it("hides kickoff-style user messages from the transcript", () => {
- const events: TranscriptEvent[] = [
- { kind: "user_message", id: "u1", ts: 1, body: "(task assignment) audit the account" },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-kickoff" })} />);
- expect(screen.queryByText(/Task brief sent to agent/i)).not.toBeInTheDocument();
- expect(screen.queryByText(/audit the account/)).not.toBeInTheDocument();
- });
-
- it("shows error-status icon when the latest tool result failed", () => {
- const events: TranscriptEvent[] = [
- {
- kind: "tool_call",
- id: "t1",
- ts: 1,
- tool_call_id: "call-1",
- name: "fetch",
- label: "https://example.com",
- },
- {
- kind: "tool_result",
- id: "r1",
- ts: 2,
- tool_call_id: "call-1",
- name: "fetch",
- summary: "boom",
- ok: false,
- },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-err" })} />);
- expect(screen.getByText(/→ error/)).toBeInTheDocument();
- expect(screen.getByText("boom")).toBeInTheDocument();
- });
-
- it("humanizes a wrapped shell command into a verb phrase (rg → Searched files)", () => {
- const events: TranscriptEvent[] = [
- {
- kind: "tool_call",
- id: "t1",
- ts: 1,
- tool_call_id: "call-rg",
- name: "shell",
- label: `/bin/zsh -lc "rg --files -g '!*node_modules*' | head -200"`,
- },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-shell-rg" })} />);
- expect(screen.getAllByText("Searched files").length).toBeGreaterThanOrEqual(1);
- // Raw command remains accessible in the expanded body.
- expect(screen.getAllByText(/rg --files/).length).toBeGreaterThanOrEqual(1);
- });
-
- it("humanizes legacy transcript rows where the raw command was stored as the tool name", () => {
- // Pre-0.4.3 codex events landed in SQLite with `name` = first line of
- // the shell command. The new humanizer should sniff the shell wrapper
- // out of the name when the label is missing/duplicated and surface
- // the intent verb instead of "Called md\"".
- const events: TranscriptEvent[] = [
- {
- kind: "tool_call",
- id: "t1",
- ts: 1,
- tool_call_id: "call-legacy",
- name: `/bin/zsh -lc "sed -n '1,220p' notfair-meta.json && sed -n '1,260p' IDENTITY.md"`,
- label: `/bin/zsh -lc "sed -n '1,220p' notfair-meta.json && sed -n '1,260p' IDENTITY.md"`,
- },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-legacy-shell" })} />);
- expect(screen.queryByText(/Called md/)).not.toBeInTheDocument();
- expect(screen.getAllByText("Transformed text").length).toBeGreaterThanOrEqual(1);
- });
-
- it("humanizes a git subcommand from a wrapped shell line", () => {
- const events: TranscriptEvent[] = [
- {
- kind: "tool_call",
- id: "t1",
- ts: 1,
- tool_call_id: "call-git",
- name: "shell",
- label: `/bin/zsh -lc "git status --porcelain"`,
- },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-shell-git" })} />);
- expect(screen.getAllByText("Ran git status").length).toBeGreaterThanOrEqual(1);
- });
-
- it("matches an MCP catalog entry via codex's <namespaced-server>.<tool> name shape", () => {
- // Codex 0.132+ ships MCP invocations as `<configKey>.<tool>` where
- // configKey is the namespaced TOML section name we registered
- // (`notfair_<projectSlug>__<serverNameUnderscored>`). The favicon
- // matcher needs to peel that wrapper off so the bare server key
- // hits the catalog.
- const events: TranscriptEvent[] = [
- {
- kind: "tool_call",
- id: "t1",
- ts: 1,
- tool_call_id: "call-mcp-codex",
- name: "notfair_demo__notfair_googleads.listAdAccounts",
- label: "active campaigns",
- },
- ];
- render(
- <LiveTranscript
- {...defaultProps({
- initialEvents: events,
- threadId: "t-mcp-codex",
- mcpCatalog: [
- {
- key: "notfair-googleads",
- display_name: "NotFair Google Ads",
- resource_url: "https://notfair.co/api/mcp/google_ads",
- },
- ],
- })}
- />,
- );
- const imgs = screen.getAllByRole("img", { name: /NotFair Google Ads/ });
- expect(imgs.length).toBeGreaterThanOrEqual(1);
- expect(imgs[0]!.getAttribute("src")).toMatch(/notfair\.co/);
- });
-
- it("renders an MCP brand favicon when a tool name matches a catalog entry", () => {
- const events: TranscriptEvent[] = [
- {
- kind: "tool_call",
- id: "t1",
- ts: 1,
- tool_call_id: "call-mcp",
- name: "mcp__notfair-googleads__listAdAccounts",
- label: "active campaigns",
- },
- ];
- render(
- <LiveTranscript
- {...defaultProps({
- initialEvents: events,
- threadId: "t-mcp-icon",
- mcpCatalog: [
- {
- key: "notfair-googleads",
- display_name: "NotFair Google Ads",
- resource_url: "https://notfair.co/api/mcp/google_ads",
- },
- ],
- })}
- />,
- );
- // Favicon img comes from the catalog entry's brand domain (notfair.co).
- const imgs = screen.getAllByRole("img", { name: /NotFair Google Ads/ });
- expect(imgs.length).toBeGreaterThanOrEqual(1);
- expect(imgs[0]!.getAttribute("src")).toMatch(/notfair\.co/);
- // Humanized action verb.
- expect(screen.getAllByText(/list ad accounts/i).length).toBeGreaterThanOrEqual(1);
- });
-
- it("groups multiple consecutive tool calls into a single tool group with step count", () => {
- const events: TranscriptEvent[] = [
- {
- kind: "tool_call",
- id: "t1",
- ts: 1,
- tool_call_id: "c1",
- name: "read",
- label: "a.txt",
- },
- {
- kind: "tool_result",
- id: "r1",
- ts: 2,
- tool_call_id: "c1",
- name: "read",
- summary: "result a",
- ok: true,
- },
- {
- kind: "tool_call",
- id: "t2",
- ts: 3,
- tool_call_id: "c2",
- name: "read",
- label: "b.txt",
- },
- {
- kind: "tool_result",
- id: "r2",
- ts: 4,
- tool_call_id: "c2",
- name: "read",
- summary: "result b",
- ok: true,
- },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-grp" })} />);
- expect(screen.getByText(/2 steps/i)).toBeInTheDocument();
- });
-
- it("renders nothing for an assistant message whose body is whitespace-only", () => {
- const events: TranscriptEvent[] = [
- { kind: "assistant_text", id: "a1", ts: 1, body: " " },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-strip" })} />);
- expect(screen.queryByTestId("markdown")).not.toBeInTheDocument();
- });
-
- it("returns null for system 'unknown' events (renders no row)", () => {
- const events: TranscriptEvent[] = [
- { kind: "unknown", id: "x1", ts: 1, raw_type: "session_metadata" },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-unknown" })} />);
- // No empty state (events.length > 0) and no rendered content.
- expect(screen.queryByText(/no messages yet/i)).not.toBeInTheDocument();
- expect(screen.queryByText("session_metadata")).not.toBeInTheDocument();
- });
-});
-
-describe("LiveTranscript composer", () => {
- it("disables submit button when input is empty", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-sub" })} />);
- const submit = screen.getByRole("button", { name: /send/i });
- expect(submit).toBeDisabled();
- });
-
- it("enables submit once the user types", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-typ" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "hi" } });
- expect(screen.getByRole("button", { name: /send/i })).not.toBeDisabled();
- });
-
- it("disables the composer textarea when composerDisabled is true", () => {
- render(<LiveTranscript {...defaultProps({ composerDisabled: true, threadId: "t-cd" })} />);
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- expect(textarea).toBeDisabled();
- expect(textarea.placeholder).toMatch(/CMO is on a task/i);
- });
-
- it("keeps the composer enabled when the task is blocked and surfaces the paused pill + helper placeholder", () => {
- render(
- <LiveTranscript
- {...defaultProps({
- composerDisabled: false,
- blockedReason: "waiting on approval",
- threadId: "t-blocked",
- })}
- />,
- );
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- expect(textarea).not.toBeDisabled();
- expect(textarea.placeholder).toMatch(/Reply to CMO/i);
- // BlockedStatus pill replaces the live working indicator.
- expect(screen.getByText(/Paused — waiting on approval/)).toBeInTheDocument();
- expect(screen.queryByText(/^Starting$/)).not.toBeInTheDocument();
- });
-
- it("model dropdown lists all models next to send and includes the pick in the send body", async () => {
- window.localStorage.clear();
- render(
- <LiveTranscript
- {...defaultProps({
- threadId: "t-model",
- modelOptions: [
- { value: "opus", label: "Opus" },
- { value: "sonnet", label: "Sonnet" },
- ],
- })}
- />,
- );
- const trigger = screen.getByRole("button", { name: /model/i });
- expect(trigger).toHaveTextContent("Default");
- // Radix menus open on pointerdown → click.
- fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });
- fireEvent.click(trigger);
- // Every available model + the Default reset are in the dropdown.
- const items = await screen.findAllByRole("menuitemradio");
- expect(items.map((i) => i.textContent)).toEqual([
- "Default",
- "Opus",
- "Sonnet",
- ]);
- fireEvent.click(screen.getByRole("menuitemradio", { name: "Opus" }));
- expect(trigger).toHaveTextContent("Opus");
- // Persisted per project+agent so the choice sticks across visits.
- expect(
- window.localStorage.getItem("notfair-cmo:model:demo:cmo"),
- ).toBe("opus");
-
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "hi" } });
- fireEvent.keyDown(textarea, { key: "Enter" });
- await vi.waitFor(() => {
- const f = global.fetch as ReturnType<typeof vi.fn>;
- const chatCall = f.mock.calls.find(
- ([u]) => typeof u === "string" && u.includes("/api/chat"),
- );
- expect(chatCall).toBeTruthy();
- const body = JSON.parse((chatCall![1] as RequestInit).body as string);
- expect(body.model).toBe("opus");
- });
- });
-
- it("renders no model selector when modelOptions are absent", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-no-model" })} />);
- expect(
- screen.queryByRole("button", { name: /model/i }),
- ).not.toBeInTheDocument();
- });
-
- it("submitting Shift+Enter inserts a newline and does NOT send", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-shift" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "line 1" } });
- fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });
- // Should NOT have called fetch with /api/chat — only background poll URLs.
- const f = global.fetch as ReturnType<typeof vi.fn>;
- const chatCalls = f.mock.calls.filter(
- ([u]) => typeof u === "string" && u.includes("/api/chat"),
- );
- expect(chatCalls.length).toBe(0);
- });
-});
-
-describe("LiveTranscript slash commands", () => {
- it("opens slash popover and filters as user types", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-slash" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "/" } });
- expect(screen.getByRole("listbox", { name: /slash commands/i })).toBeInTheDocument();
- // /clear should appear in essential local commands
- expect(screen.getByText("/clear")).toBeInTheDocument();
- });
-
- it("clicking a slash command inserts the canonical text into the input", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-slash-click" })} />);
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- fireEvent.change(textarea, { target: { value: "/cle" } });
- const option = screen.getByRole("option", { name: /\/clear/i });
- fireEvent.click(option);
- expect(textarea.value).toBe("/clear ");
- });
-
- it("clears the local view when /clear is submitted", async () => {
- const events: TranscriptEvent[] = [
- { kind: "user_message", id: "u1", ts: 1, body: "old turn" },
- { kind: "assistant_text", id: "a1", ts: 2, body: "old reply" },
- ];
- render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-clear" })} />);
- expect(screen.getByText("old turn")).toBeInTheDocument();
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "/clear" } });
- // Close popover by adding a trailing space so the form-submit path runs.
- fireEvent.change(textarea, { target: { value: "/clear " } });
- fireEvent.submit(textarea.closest("form")!);
- await waitFor(() => {
- expect(screen.queryByText("old turn")).not.toBeInTheDocument();
- });
- expect(toastFns.info).toHaveBeenCalled();
- // After clearing, idle empty state should reappear.
- expect(screen.getByText(/no messages yet/i)).toBeInTheDocument();
- });
-
- it("pushes a new chat URL when /new is submitted", async () => {
- // jsdom doesn't ship crypto.randomUUID in older versions — guarantee it.
- if (typeof crypto.randomUUID !== "function") {
- // @ts-expect-error patch for jsdom
- crypto.randomUUID = () => "11111111-1111-1111-1111-111111111111";
- }
- render(<LiveTranscript {...defaultProps({ threadId: "t-new" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "/new " } });
- fireEvent.submit(textarea.closest("form")!);
- await waitFor(() => {
- expect(routerPush).toHaveBeenCalled();
- });
- const target = routerPush.mock.calls[0]![0];
- expect(target).toMatch(/^\/demo\/agents\/cmo\/chat\//);
- });
-
- it("renders the help toast when /help is submitted", async () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-help" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "/help " } });
- fireEvent.submit(textarea.closest("form")!);
- await waitFor(() => expect(toastFns.message).toHaveBeenCalled());
- });
-
- it("escape closes the popover and clears the input", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-esc" })} />);
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- fireEvent.change(textarea, { target: { value: "/cl" } });
- expect(screen.getByRole("listbox")).toBeInTheDocument();
- fireEvent.keyDown(textarea, { key: "Escape" });
- expect(textarea.value).toBe("");
- });
-
- it("arrow keys cycle the slash command selection", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-arrow" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "/" } });
- const items = screen.getAllByRole("option");
- expect(items.length).toBeGreaterThan(1);
- // First option is selected initially.
- expect(items[0]).toHaveAttribute("aria-selected", "true");
- fireEvent.keyDown(textarea, { key: "ArrowDown" });
- const afterDown = screen.getAllByRole("option");
- expect(afterDown[1]).toHaveAttribute("aria-selected", "true");
- fireEvent.keyDown(textarea, { key: "ArrowUp" });
- const afterUp = screen.getAllByRole("option");
- expect(afterUp[0]).toHaveAttribute("aria-selected", "true");
- });
-
- it("Tab in the popover inserts the highlighted command", () => {
- render(<LiveTranscript {...defaultProps({ threadId: "t-tab" })} />);
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- fireEvent.change(textarea, { target: { value: "/" } });
- fireEvent.keyDown(textarea, { key: "Tab" });
- expect(textarea.value).toMatch(/^\/\S+\s$/);
- });
-});
-
-describe("LiveTranscript /api/chat send path", () => {
- it("posts the user message, streams SSE text into a pending bubble, and shows a stop button", async () => {
- const encoder = new TextEncoder();
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(
- encoder.encode("event: text\ndata: {\"chunk\":\"Hello \"}\n\n"),
- );
- controller.enqueue(
- encoder.encode("event: text\ndata: {\"chunk\":\"world\"}\n\n"),
- );
- controller.close();
- },
- });
-
- setFetch(async (url) => {
- if (url.includes("/api/chat")) {
- return new Response(stream, { status: 200 });
- }
- return makeEmptyTranscriptResponse();
- });
-
- render(<LiveTranscript {...defaultProps({ threadId: "t-send" })} />);
- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
- fireEvent.change(textarea, { target: { value: "Hi agent" } });
- fireEvent.submit(textarea.closest("form")!);
-
- // Optimistic user bubble appears immediately.
- await waitFor(() => {
- expect(screen.getByText("Hi agent")).toBeInTheDocument();
- });
- // Stream chunks should be rendered through Markdown stub.
- await waitFor(() => {
- const md = screen.getAllByTestId("markdown").pop();
- expect(md?.textContent).toContain("Hello world");
- });
- // Stop button is visible while sending.
- expect(screen.getByRole("button", { name: /stop/i })).toBeInTheDocument();
- });
-
- it("renders an SSE-reported error and toasts when the stream emits an error event", async () => {
- const encoder = new TextEncoder();
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(
- encoder.encode(
- "event: error\ndata: {\"message\":\"upstream failed\"}\n\n",
- ),
- );
- controller.close();
- },
- });
- setFetch(async (url) => {
- if (url.includes("/api/chat")) {
- return new Response(stream, { status: 200 });
- }
- return makeEmptyTranscriptResponse();
- });
-
- render(<LiveTranscript {...defaultProps({ threadId: "t-sse-err" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "go" } });
- fireEvent.submit(textarea.closest("form")!);
- await waitFor(() => {
- expect(screen.getByText("upstream failed")).toBeInTheDocument();
- });
- expect(screen.getByText(/Couldn.t reach CMO/i)).toBeInTheDocument();
- });
-
- it("renders a thrown fetch error and surfaces a toast", async () => {
- setFetch(async (url) => {
- if (url.includes("/api/chat")) {
- return new Response("kaboom", { status: 500 });
- }
- return makeEmptyTranscriptResponse();
- });
- render(<LiveTranscript {...defaultProps({ threadId: "t-http-err" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "go" } });
- fireEvent.submit(textarea.closest("form")!);
- await waitFor(() => {
- expect(toastFns.error).toHaveBeenCalled();
- });
- expect(screen.getByText("kaboom")).toBeInTheDocument();
- });
-
- it("streams a tool start event into the live tool group", async () => {
- const encoder = new TextEncoder();
- let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null;
- const stream = new ReadableStream({
- start(controller) {
- controllerRef = controller;
- controller.enqueue(
- encoder.encode(
- "event: tool\ndata: {\"phase\":\"start\",\"tool_call_id\":\"c-1\",\"name\":\"shell\",\"label\":\"ls\"}\n\n",
- ),
- );
- },
- });
- setFetch(async (url) => {
- if (url.includes("/api/chat")) {
- return new Response(stream, { status: 200 });
- }
- return makeEmptyTranscriptResponse();
- });
- render(<LiveTranscript {...defaultProps({ threadId: "t-tool-stream" })} />);
- const textarea = screen.getByRole("textbox");
- fireEvent.change(textarea, { target: { value: "ls" } });
- fireEvent.submit(textarea.closest("form")!);
- await waitFor(() => {
- // Streamed tool starts now render with the humanized intent —
- // "ls" is recognized as a `Listed files` invocation.
- expect(screen.getAllByText("Listed files").length).toBeGreaterThanOrEqual(1);
- });
- // Raw "shell" identifier shows as a small mono tag on the expanded row.
- expect(screen.getAllByText("shell").length).toBeGreaterThanOrEqual(1);
- // Wrap up the stream so the send promise finishes before unmount.
- controllerRef!.close();
- });
-});
-
-describe("LiveTranscript polling", () => {
- it("polls the transcript endpoint and appends fresh events", async () => {
- const calls: string[] = [];
- let polled = 0;
- setFetch(async (url) => {
- const u = String(url);
- calls.push(u);
- if (u.includes("/transcript")) {
- polled++;
- if (polled === 1) {
- const fresh: TranscriptEvent[] = [
- { kind: "assistant_text", id: "poll-a1", ts: 5, body: "polled in" },
- ];
- return new Response(
- JSON.stringify({ events: fresh, byteOffset: 200, file_size: 200 }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- );
- }
- return makeEmptyTranscriptResponse(200);
- }
- return makeEmptyTranscriptResponse();
- });
-
- vi.useFakeTimers();
- render(<LiveTranscript {...defaultProps({ threadId: "t-poll" })} />);
- // Advance past the default poll interval.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2_100);
- });
- vi.useRealTimers();
- await waitFor(() => {
- expect(screen.getByTestId("markdown")).toHaveTextContent("polled in");
- });
- expect(calls.some((u) => u.includes("/transcript"))).toBe(true);
- });
-
- it("invokes onPolled with new event counts and stops polling when it returns true", async () => {
- let polled = 0;
- setFetch(async (url) => {
- if (String(url).includes("/transcript")) {
- polled++;
- return new Response(
- JSON.stringify({ events: [], byteOffset: 0, file_size: 42 }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- );
- }
- return makeEmptyTranscriptResponse();
- });
- const onPolled = vi.fn(() => true);
- vi.useFakeTimers();
- render(
- <LiveTranscript
- {...defaultProps({ threadId: "t-onpolled", onPolled })}
- />,
- );
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2_100);
- });
- expect(onPolled).toHaveBeenCalledWith({ newEvents: 0, fileSize: 42 });
- // After stop, additional ticks shouldn't add more polls.
- const before = polled;
- await act(async () => {
- await vi.advanceTimersByTimeAsync(5_000);
- });
- vi.useRealTimers();
- expect(polled).toBe(before);
- });
-
- it("dedupes events by id across overlapping poll cycles", async () => {
- let polled = 0;
- setFetch(async (url) => {
- if (String(url).includes("/transcript")) {
- polled++;
- // Always return the same single event — second poll would duplicate.
- return new Response(
- JSON.stringify({
- events: [
- { kind: "assistant_text", id: "dup-1", ts: 1, body: "once" },
- ],
- byteOffset: 0,
- file_size: 1,
- }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- );
- }
- return makeEmptyTranscriptResponse();
- });
- vi.useFakeTimers();
- render(<LiveTranscript {...defaultProps({ threadId: "t-dedupe" })} />);
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2_100);
- });
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2_100);
- });
- vi.useRealTimers();
- await waitFor(() => {
- const mds = screen.getAllByTestId("markdown");
- expect(mds.filter((m) => m.textContent === "once").length).toBe(1);
- });
- expect(polled).toBeGreaterThanOrEqual(2);
- });
-
- it("tolerates a non-OK transcript poll response", async () => {
- setFetch(async (url) => {
- if (String(url).includes("/transcript")) {
- return new Response("nope", { status: 500 });
- }
- return makeEmptyTranscriptResponse();
- });
- vi.useFakeTimers();
- render(<LiveTranscript {...defaultProps({ threadId: "t-poll-500" })} />);
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2_100);
- });
- vi.useRealTimers();
- // No crash, empty state still rendered.
- expect(screen.getByText(/no messages yet/i)).toBeInTheDocument();
- });
-});
-
-describe("LiveTranscript autoKickoff", () => {
- it("fires a hidden first message via /api/chat when autoKickoff is true and transcript is empty", async () => {
- const encoder = new TextEncoder();
- let chatCalled = false;
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(
- encoder.encode("event: text\ndata: {\"chunk\":\"hi\"}\n\n"),
- );
- controller.close();
- },
- });
- setFetch(async (url, init) => {
- if (String(url).includes("/api/chat")) {
- chatCalled = true;
- const body = JSON.parse((init?.body as string) ?? "{}");
- // Carries the kickoff override.
- expect(body.message).toBe("kickoff!");
- return new Response(stream, { status: 200 });
- }
- return makeEmptyTranscriptResponse();
- });
- render(
- <LiveTranscript
- {...defaultProps({
- autoKickoff: true,
- kickoffMessage: "kickoff!",
- threadId: "t-kickoff-unique-1",
- })}
- />,
- );
- await waitFor(() => expect(chatCalled).toBe(true));
- // Hidden: no visible user bubble should show the kickoff text.
- expect(screen.queryByText("kickoff!")).not.toBeInTheDocument();
- });
-
- it("forwards taskId in the /api/chat body when autoKickoff fires", async () => {
- let observedBody: Record<string, unknown> | null = null;
- const encoder = new TextEncoder();
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(encoder.encode("event: text\ndata: {\"chunk\":\"hi\"}\n\n"));
- controller.close();
- },
- });
- setFetch(async (url, init) => {
- if (String(url).includes("/api/chat")) {
- observedBody = JSON.parse((init?.body as string) ?? "{}");
- return new Response(stream, { status: 200 });
- }
- return makeEmptyTranscriptResponse();
- });
- render(
- <LiveTranscript
- {...defaultProps({
- autoKickoff: true,
- kickoffMessage: "kickoff body",
- taskId: "task-uuid-7",
- threadId: "t-kickoff-with-task-id",
- })}
- />,
- );
- await waitFor(() => expect(observedBody).not.toBeNull());
- expect(observedBody!.task_id).toBe("task-uuid-7");
- });
-
- it("treats a 409 from /api/chat as a benign no-op (no error toast, no thrown error)", async () => {
- setFetch(async (url) => {
- if (String(url).includes("/api/chat")) {
- return new Response(
- JSON.stringify({ error: "task already claimed", status: "working" }),
- { status: 409 },
- );
- }
- return makeEmptyTranscriptResponse();
- });
- render(
- <LiveTranscript
- {...defaultProps({
- autoKickoff: true,
- kickoffMessage: "kickoff body",
- taskId: "task-uuid-8",
- threadId: "t-kickoff-409",
- })}
- />,
- );
- // No error row should appear — 409 means "someone else claimed it"
- // and is expected during reloads / concurrent tabs.
- await new Promise((r) => setTimeout(r, 30));
- expect(
- screen.queryByText(/couldn[’']t reach/i),
- ).not.toBeInTheDocument();
- });
-
- it("does not auto-kickoff a second time for the same threadId (module guard)", async () => {
- // Re-uses the same threadId as the previous test which already added to KICKOFF_FIRED.
- let chatCalled = false;
- setFetch(async (url) => {
- if (String(url).includes("/api/chat")) {
- chatCalled = true;
- return new Response("", { status: 200 });
- }
- return makeEmptyTranscriptResponse();
- });
- render(
- <LiveTranscript
- {...defaultProps({
- autoKickoff: true,
- kickoffMessage: "kickoff!",
- threadId: "t-kickoff-unique-1",
- })}
- />,
- );
- // Give the effect a tick to run.
- await new Promise((r) => setTimeout(r, 20));
- expect(chatCalled).toBe(false);
- });
-});
diff --git a/notfair-cmo/src/components/markdown.test.tsx b/notfair-cmo/src/components/markdown.test.tsx
deleted file mode 100644
index e9e24674..00000000
--- a/notfair-cmo/src/components/markdown.test.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect } from "vitest";
-import { render } from "@testing-library/react";
-
-import { Markdown } from "./markdown";
-
-describe("Markdown", () => {
- it("renders a paragraph with leading-relaxed styling", () => {
- const { container } = render(<Markdown>Hello **world**</Markdown>);
- const p = container.querySelector("p");
- expect(p).not.toBeNull();
- expect(p?.className).toContain("leading-relaxed");
- expect(p?.querySelector("strong")?.textContent).toBe("world");
- });
-
- it("renders unordered and ordered lists", () => {
- const { container } = render(<Markdown>{"- a\n- b\n\n1. one\n2. two"}</Markdown>);
- const ul = container.querySelector("ul");
- const ol = container.querySelector("ol");
- expect(ul?.querySelectorAll("li").length).toBe(2);
- expect(ol?.querySelectorAll("li").length).toBe(2);
- expect(ul?.className).toContain("list-disc");
- expect(ol?.className).toContain("list-decimal");
- });
-
- it("renders headings h1-h4 as semibold elements", () => {
- const { container } = render(
- <Markdown>{"# H1\n\n## H2\n\n### H3\n\n#### H4"}</Markdown>,
- );
- expect(container.querySelector("h1")?.textContent).toBe("H1");
- expect(container.querySelector("h2")?.textContent).toBe("H2");
- expect(container.querySelector("h3")?.textContent).toBe("H3");
- expect(container.querySelector("h4")?.textContent).toBe("H4");
- expect(container.querySelector("h1")?.className).toContain("font-semibold");
- });
-
- it("links open in a new tab with noopener/noreferrer", () => {
- const { container } = render(
- <Markdown>{"[click](https://example.com)"}</Markdown>,
- );
- const a = container.querySelector("a");
- expect(a).not.toBeNull();
- expect(a?.getAttribute("href")).toBe("https://example.com");
- expect(a?.getAttribute("target")).toBe("_blank");
- expect(a?.getAttribute("rel")).toBe("noopener noreferrer");
- });
-
- it("renders inline code with rounded muted background", () => {
- const { container } = render(<Markdown>{"Use `npm` here"}</Markdown>);
- const code = container.querySelector("code");
- expect(code).not.toBeNull();
- expect(code?.textContent).toBe("npm");
- // Inline (no language-) -> uses rounded bg-muted; fenced uses leading-relaxed only.
- expect(code?.className).toContain("rounded");
- expect(code?.className).toContain("bg-muted");
- });
-
- it("renders fenced code blocks inside <pre> with language hint", () => {
- const md = "```json\n{\"a\":1}\n```";
- const { container } = render(<Markdown>{md}</Markdown>);
- const pre = container.querySelector("pre");
- const code = pre?.querySelector("code");
- expect(pre).not.toBeNull();
- expect(code?.className).toContain("language-json");
- expect(code?.className).toContain("font-mono");
- expect(pre?.className).toContain("overflow-x-auto");
- });
-
- it("renders blockquote, hr, and gfm table elements", () => {
- const md = [
- "> quoted",
- "",
- "---",
- "",
- "| a | b |",
- "| --- | --- |",
- "| 1 | 2 |",
- ].join("\n");
- const { container } = render(<Markdown>{md}</Markdown>);
- expect(container.querySelector("blockquote")?.textContent).toContain("quoted");
- expect(container.querySelector("hr")).not.toBeNull();
- const table = container.querySelector("table");
- expect(table).not.toBeNull();
- expect(table?.parentElement?.className).toContain("overflow-x-auto");
- expect(container.querySelectorAll("th").length).toBe(2);
- expect(container.querySelectorAll("td").length).toBe(2);
- });
-
- it("emphasis renders as <em>", () => {
- const { container } = render(<Markdown>{"This is *italic* text"}</Markdown>);
- expect(container.querySelector("em")?.textContent).toBe("italic");
- });
-
- it("does not render raw HTML (script tags are escaped, not executed)", () => {
- const { container } = render(
- <Markdown>{"hi <script>alert(1)</script> bye"}</Markdown>,
- );
- // react-markdown without rehype-raw renders HTML as literal text.
- expect(container.querySelector("script")).toBeNull();
- expect(container.textContent).toContain("alert(1)");
- });
-
- it("applies a user-supplied className to the wrapper", () => {
- const { container } = render(
- <Markdown className="custom-x">hello</Markdown>,
- );
- const wrapper = container.firstChild as HTMLElement;
- expect(wrapper.className).toContain("custom-x");
- expect(wrapper.className).toContain("text-sm");
- });
-});
diff --git a/notfair-cmo/src/components/mcp-card.test.tsx b/notfair-cmo/src/components/mcp-card.test.tsx
deleted file mode 100644
index ef9db103..00000000
--- a/notfair-cmo/src/components/mcp-card.test.tsx
+++ /dev/null
@@ -1,244 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const { startMcpConnect, disconnectMcpAction, routerRefresh, toastFns } = vi.hoisted(() => ({
- startMcpConnect: vi.fn(),
- disconnectMcpAction: vi.fn(),
- routerRefresh: vi.fn(),
- toastFns: {
- success: vi.fn(),
- error: vi.fn(),
- },
-}));
-
-vi.mock("@/server/actions/mcp", () => ({
- startMcpConnect: (...args: unknown[]) => startMcpConnect(...args),
- disconnectMcpAction: (...args: unknown[]) => disconnectMcpAction(...args),
-}));
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({
- push: vi.fn(),
- replace: vi.fn(),
- refresh: routerRefresh,
- back: vi.fn(),
- forward: vi.fn(),
- prefetch: vi.fn(),
- }),
-}));
-
-vi.mock("sonner", () => ({
- toast: toastFns,
-}));
-
-import { McpCard } from "./mcp-card";
-import type { McpSpec } from "@/server/mcp-catalog";
-import type { McpRuntimeStatus } from "@/server/mcp/state";
-
-const spec: McpSpec = {
- key: "notfair-googleads",
- display_name: "NotFair Google Ads",
- description: "Live Google Ads operations.",
- resource_url: "https://notfair.co/api/mcp/google_ads",
- discovery_url:
- "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",
- source: "preset",
-};
-
-function connected(overrides: Partial<Extract<McpRuntimeStatus, { state: "connected" }>> = {}): McpRuntimeStatus {
- return {
- state: "connected",
- url: "https://notfair.co/api/mcp/google_ads",
- tools_count: 12,
- last_checked_at: new Date().toISOString(),
- ...overrides,
- };
-}
-
-function setLocationHref() {
- const original = window.location;
- const fake = { ...original, href: "" } as Location & { href: string };
- Object.defineProperty(window, "location", {
- writable: true,
- configurable: true,
- value: fake,
- });
- return fake;
-}
-
-beforeEach(() => {
- startMcpConnect.mockReset();
- disconnectMcpAction.mockReset();
- routerRefresh.mockReset();
- toastFns.success.mockReset();
- toastFns.error.mockReset();
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("McpCard", () => {
- it("shows spec metadata (name, description, host)", () => {
- render(<McpCard spec={spec} status={{ state: "not_configured" }} />);
- expect(screen.getByText(spec.display_name)).toBeInTheDocument();
- expect(screen.getByText(spec.description)).toBeInTheDocument();
- // The row shows the resource URL's host, not the full URL.
- expect(screen.getByText("notfair.co")).toBeInTheDocument();
- });
-
- it("renders a 'connected' indicator and just the host when connected", () => {
- render(<McpCard spec={spec} status={connected({ tools_count: null })} />);
- expect(screen.getByText("connected")).toBeInTheDocument();
- // The "connected" tag carries the live signal; the status line shows
- // only the host so the row doesn't repeat itself.
- expect(screen.getByText("notfair.co")).toBeInTheDocument();
- expect(screen.queryByText(/verified/)).not.toBeInTheDocument();
- });
-
- it("shows a Disconnect button when connected and a Connect button otherwise", () => {
- const { rerender } = render(
- <McpCard spec={spec} status={connected()} />,
- );
- expect(
- screen.getByRole("button", { name: /disconnect/i }),
- ).toBeInTheDocument();
- rerender(<McpCard spec={spec} status={{ state: "not_configured" }} />);
- expect(
- screen.getByRole("button", { name: /^connect$/i }),
- ).toBeInTheDocument();
- });
-
- it("labels the action button 'Reconnect' on stale_token", () => {
- render(
- <McpCard
- spec={spec}
- status={{
- state: "stale_token",
- url: "https://x",
- http_status: 401,
- last_checked_at: new Date().toISOString(),
- }}
- />,
- );
- expect(
- screen.getByRole("button", { name: /reconnect/i }),
- ).toBeInTheDocument();
- expect(screen.getByText(/token expired/i)).toBeInTheDocument();
- expect(screen.getByText(/HTTP 401/)).toBeInTheDocument();
- });
-
- it("renders the unreachable status with the underlying error", () => {
- render(
- <McpCard
- spec={spec}
- status={{
- state: "unreachable",
- url: "https://x",
- error: "ECONNREFUSED",
- last_checked_at: new Date().toISOString(),
- }}
- />,
- );
- expect(screen.getByText(/unreachable/i)).toBeInTheDocument();
- expect(screen.getByText(/ECONNREFUSED/)).toBeInTheDocument();
- });
-
- it("renders the configured_no_token status with helper text", () => {
- render(
- <McpCard
- spec={spec}
- status={{ state: "configured_no_token", url: "https://x" }}
- />,
- );
- expect(screen.getByText(/no token/i)).toBeInTheDocument();
- expect(
- screen.getByText(/config saved, awaiting bearer/i),
- ).toBeInTheDocument();
- });
-
- it("redirects the browser to authorize_url when Connect succeeds", async () => {
- const loc = setLocationHref();
- startMcpConnect.mockResolvedValue({
- ok: true,
- authorize_url: "https://issuer.example/oauth?state=abc",
- });
- render(<McpCard spec={spec} status={{ state: "not_configured" }} />);
- fireEvent.click(screen.getByRole("button", { name: /^connect$/i }));
- await waitFor(() =>
- expect(startMcpConnect).toHaveBeenCalledWith({
- mcp_key: spec.key,
- return_to: "/",
- }),
- );
- await waitFor(() =>
- expect(loc.href).toBe("https://issuer.example/oauth?state=abc"),
- );
- expect(toastFns.error).not.toHaveBeenCalled();
- });
-
- it("toasts and stays on-page when Connect returns ok=false", async () => {
- startMcpConnect.mockResolvedValue({ ok: false, error: "discovery failed" });
- render(<McpCard spec={spec} status={{ state: "not_configured" }} />);
- fireEvent.click(screen.getByRole("button", { name: /^connect$/i }));
- await waitFor(() =>
- expect(toastFns.error).toHaveBeenCalledWith("discovery failed"),
- );
- // Button is re-enabled.
- expect(screen.getByRole("button", { name: /^connect$/i })).not.toBeDisabled();
- });
-
- it("toasts the thrown error message when Connect throws", async () => {
- startMcpConnect.mockRejectedValue(new Error("network down"));
- render(<McpCard spec={spec} status={{ state: "not_configured" }} />);
- fireEvent.click(screen.getByRole("button", { name: /^connect$/i }));
- await waitFor(() =>
- expect(toastFns.error).toHaveBeenCalledWith("network down"),
- );
- });
-
- it("disconnects, toasts success, and refreshes the router", async () => {
- disconnectMcpAction.mockResolvedValue({ ok: true });
- render(<McpCard spec={spec} status={connected()} />);
- fireEvent.click(screen.getByRole("button", { name: /disconnect/i }));
- await waitFor(() =>
- expect(disconnectMcpAction).toHaveBeenCalledWith({ mcp_key: spec.key }),
- );
- await waitFor(() =>
- expect(toastFns.success).toHaveBeenCalledWith(
- `${spec.display_name} disconnected`,
- ),
- );
- expect(routerRefresh).toHaveBeenCalled();
- });
-
- it("toasts the error and skips router.refresh when Disconnect returns ok=false", async () => {
- disconnectMcpAction.mockResolvedValue({
- ok: false,
- error: "openclaw permission denied",
- });
- render(<McpCard spec={spec} status={connected()} />);
- fireEvent.click(screen.getByRole("button", { name: /disconnect/i }));
- await waitFor(() =>
- expect(toastFns.error).toHaveBeenCalledWith("openclaw permission denied"),
- );
- expect(routerRefresh).not.toHaveBeenCalled();
- });
-
- it("disables the Connect button while the connect call is in flight", async () => {
- setLocationHref();
- let resolve: (v: { ok: true; authorize_url: string }) => void = () => {};
- startMcpConnect.mockImplementation(
- () =>
- new Promise<{ ok: true; authorize_url: string }>((res) => {
- resolve = res;
- }),
- );
- render(<McpCard spec={spec} status={{ state: "not_configured" }} />);
- const button = screen.getByRole("button", { name: /^connect$/i });
- fireEvent.click(button);
- await waitFor(() => expect(button).toBeDisabled());
- resolve({ ok: true, authorize_url: "https://issuer.example" });
- });
-});
diff --git a/notfair-cmo/src/components/mcp-flash-banner.test.tsx b/notfair-cmo/src/components/mcp-flash-banner.test.tsx
deleted file mode 100644
index 1c00bcde..00000000
--- a/notfair-cmo/src/components/mcp-flash-banner.test.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, cleanup, waitFor } from "@testing-library/react";
-
-const { routerReplace, toastFns } = vi.hoisted(() => ({
- routerReplace: vi.fn(),
- toastFns: {
- success: vi.fn(),
- error: vi.fn(),
- },
-}));
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({
- push: vi.fn(),
- replace: routerReplace,
- refresh: vi.fn(),
- back: vi.fn(),
- forward: vi.fn(),
- prefetch: vi.fn(),
- }),
-}));
-
-vi.mock("sonner", () => ({
- toast: toastFns,
-}));
-
-import { McpFlashBanner } from "./mcp-flash-banner";
-
-function setLocation(href: string) {
- Object.defineProperty(window, "location", {
- writable: true,
- value: new URL(href),
- });
-}
-
-beforeEach(() => {
- routerReplace.mockReset();
- toastFns.success.mockReset();
- toastFns.error.mockReset();
- setLocation(
- "http://localhost:3000/connections?mcp_connected=NotFair&other=keep",
- );
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("McpFlashBanner", () => {
- it("renders nothing (returns null)", () => {
- const { container } = render(<McpFlashBanner />);
- expect(container.firstChild).toBeNull();
- });
-
- it("toasts a success message and strips ?mcp_connected from the URL", async () => {
- render(<McpFlashBanner connected="NotFair Google Ads" />);
- await waitFor(() =>
- expect(toastFns.success).toHaveBeenCalledWith(
- "Connected: NotFair Google Ads",
- ),
- );
- expect(routerReplace).toHaveBeenCalledWith("/connections?other=keep");
- });
-
- it("toasts an error and strips ?mcp_error when an error is provided", async () => {
- setLocation("http://localhost:3000/connections?mcp_error=boom&keep=1");
- render(<McpFlashBanner error="boom" />);
- await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("boom"));
- expect(toastFns.success).not.toHaveBeenCalled();
- expect(routerReplace).toHaveBeenCalledWith("/connections?keep=1");
- });
-
- it("prefers the error toast when both connected and error are supplied", async () => {
- render(<McpFlashBanner connected="x" error="bad" />);
- await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("bad"));
- expect(toastFns.success).not.toHaveBeenCalled();
- });
-
- it("does nothing when neither connected nor error is supplied", () => {
- render(<McpFlashBanner />);
- expect(toastFns.success).not.toHaveBeenCalled();
- expect(toastFns.error).not.toHaveBeenCalled();
- expect(routerReplace).not.toHaveBeenCalled();
- });
-
- it("returns a pathname-only URL when no query params remain after stripping", async () => {
- setLocation("http://localhost:3000/connections?mcp_connected=x");
- render(<McpFlashBanner connected="x" />);
- await waitFor(() =>
- expect(routerReplace).toHaveBeenCalledWith("/connections"),
- );
- });
-});
diff --git a/notfair-cmo/src/components/mcp-icon.test.tsx b/notfair-cmo/src/components/mcp-icon.test.tsx
deleted file mode 100644
index 3d1f4953..00000000
--- a/notfair-cmo/src/components/mcp-icon.test.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-// @vitest-environment jsdom
-import { describe, expect, it, afterEach } from "vitest";
-import { cleanup, render, screen } from "@testing-library/react";
-
-import { McpIcon, brandDomain, platformLogoForResourceUrl } from "./mcp-icon";
-
-afterEach(() => {
- cleanup();
-});
-
-describe("platformLogoForResourceUrl", () => {
- it("maps every NotFair-hosted platform MCP to its bundled logo", () => {
- expect(
- platformLogoForResourceUrl("https://notfair.co/api/mcp/google_ads"),
- ).toBe("/mcp-logos/google-ads-icon.svg");
- expect(
- platformLogoForResourceUrl("https://notfair.co/api/mcp/meta_ads"),
- ).toBe("/mcp-logos/meta-icon.svg");
- expect(
- platformLogoForResourceUrl(
- "https://notfair.co/api/mcp/google_search_console",
- ),
- ).toBe("/mcp-logos/search-console-icon.svg");
- expect(
- platformLogoForResourceUrl("https://notfair.co/api/mcp/google_analytics"),
- ).toBe("/mcp-logos/google-analytics-icon.svg");
- expect(platformLogoForResourceUrl("https://notfair.co/api/mcp/x_ads")).toBe(
- "/mcp-logos/x-ads-icon.svg",
- );
- });
-
- it("tolerates a trailing slash and www-style subdomains", () => {
- expect(
- platformLogoForResourceUrl("https://www.notfair.co/api/mcp/google_ads/"),
- ).toBe("/mcp-logos/google-ads-icon.svg");
- });
-
- it("returns null for third-party servers, unknown platforms, and junk", () => {
- expect(platformLogoForResourceUrl("https://mcp.stripe.com/")).toBeNull();
- expect(
- platformLogoForResourceUrl("https://notfair.co/api/mcp/unknown_platform"),
- ).toBeNull();
- expect(platformLogoForResourceUrl("https://notfair.co/")).toBeNull();
- expect(platformLogoForResourceUrl("not a url")).toBeNull();
- });
-
- it("does not match notfair.co paths outside /api/mcp/", () => {
- expect(
- platformLogoForResourceUrl("https://notfair.co/blog/google_ads"),
- ).toBeNull();
- });
-});
-
-describe("McpIcon", () => {
- it("renders the bundled platform logo for a NotFair platform MCP", () => {
- render(
- <McpIcon
- resourceUrl="https://notfair.co/api/mcp/x_ads"
- alt="NotFair X Ads"
- />,
- );
- expect(screen.getByAltText("NotFair X Ads")).toHaveAttribute(
- "src",
- "/mcp-logos/x-ads-icon.svg",
- );
- });
-
- it("falls back to the brand favicon for third-party servers", () => {
- render(<McpIcon resourceUrl="https://mcp.stripe.com/" alt="Stripe" />);
- expect(screen.getByAltText("Stripe").getAttribute("src")).toContain(
- "stripe.com",
- );
- });
-});
-
-describe("brandDomain", () => {
- it("collapses subdomains to the registrable domain", () => {
- expect(brandDomain("mcp.stripe.com")).toBe("stripe.com");
- expect(brandDomain("notfair.co")).toBe("notfair.co");
- });
-});
diff --git a/notfair-cmo/src/components/onboarding-flow.test.tsx b/notfair-cmo/src/components/onboarding-flow.test.tsx
deleted file mode 100644
index d32e16d3..00000000
--- a/notfair-cmo/src/components/onboarding-flow.test.tsx
+++ /dev/null
@@ -1,755 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup, act } from "@testing-library/react";
-
-const {
- createProjectForOnboardingAction,
- startMcpConnect,
- listGoogleAdsAccounts,
- setOnboardingAccountAction,
- getOnboardingTaskForSkipAction,
- getProvisioningProgressAction,
- getConnectStepStateAction,
- listMetaAdsAccounts,
- setOnboardingMetaAdsAccountAction,
- listGscProperties,
- setOnboardingGscPropertyAction,
- addUserMcpServerAction,
- routerPush,
- routerReplace,
- toastFns,
- searchParamsRef,
-} = vi.hoisted(() => ({
- createProjectForOnboardingAction: vi.fn(),
- startMcpConnect: vi.fn(),
- listGoogleAdsAccounts: vi.fn(),
- setOnboardingAccountAction: vi.fn(),
- getOnboardingTaskForSkipAction: vi.fn(),
- getProvisioningProgressAction: vi.fn(),
- getConnectStepStateAction: vi.fn(),
- listMetaAdsAccounts: vi.fn(),
- setOnboardingMetaAdsAccountAction: vi.fn(),
- listGscProperties: vi.fn(),
- setOnboardingGscPropertyAction: vi.fn(),
- addUserMcpServerAction: vi.fn(),
- routerPush: vi.fn(),
- routerReplace: vi.fn(),
- toastFns: {
- success: vi.fn(),
- error: vi.fn(),
- },
- searchParamsRef: { current: new URLSearchParams() },
-}));
-
-vi.mock("@/server/actions/projects", () => ({
- createProjectForOnboardingAction: (...args: unknown[]) =>
- createProjectForOnboardingAction(...args),
-}));
-
-vi.mock("@/server/actions/mcp", () => ({
- startMcpConnect: (...args: unknown[]) => startMcpConnect(...args),
- addUserMcpServerAction: (...args: unknown[]) => addUserMcpServerAction(...args),
-}));
-
-vi.mock("@/server/onboarding/accounts", () => ({
- listGoogleAdsAccounts: (...args: unknown[]) => listGoogleAdsAccounts(...args),
- setOnboardingAccountAction: (...args: unknown[]) =>
- setOnboardingAccountAction(...args),
- getOnboardingTaskForSkipAction: (...args: unknown[]) =>
- getOnboardingTaskForSkipAction(...args),
- getProvisioningProgressAction: (...args: unknown[]) =>
- getProvisioningProgressAction(...args),
- getConnectStepStateAction: (...args: unknown[]) =>
- getConnectStepStateAction(...args),
- listMetaAdsAccounts: (...args: unknown[]) => listMetaAdsAccounts(...args),
- setOnboardingMetaAdsAccountAction: (...args: unknown[]) =>
- setOnboardingMetaAdsAccountAction(...args),
- listGscProperties: (...args: unknown[]) => listGscProperties(...args),
- setOnboardingGscPropertyAction: (...args: unknown[]) =>
- setOnboardingGscPropertyAction(...args),
-}));
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({
- push: routerPush,
- replace: routerReplace,
- refresh: vi.fn(),
- back: vi.fn(),
- forward: vi.fn(),
- prefetch: vi.fn(),
- }),
- useSearchParams: () => searchParamsRef.current,
-}));
-
-vi.mock("sonner", () => ({
- toast: toastFns,
-}));
-
-import { OnboardingFlow } from "./onboarding-flow";
-
-function setStep(step: string | null, slug?: string | null) {
- const p = new URLSearchParams();
- if (step) p.set("step", step);
- if (slug) p.set("slug", slug);
- searchParamsRef.current = p;
-}
-
-function setLocationHref() {
- const fake = { href: "" } as Location & { href: string };
- Object.defineProperty(window, "location", {
- writable: true,
- configurable: true,
- value: fake,
- });
- return fake;
-}
-
-beforeEach(() => {
- createProjectForOnboardingAction.mockReset();
- startMcpConnect.mockReset();
- listGoogleAdsAccounts.mockReset();
- setOnboardingAccountAction.mockReset();
- getOnboardingTaskForSkipAction.mockReset();
- getProvisioningProgressAction.mockReset();
- getConnectStepStateAction.mockReset();
- listMetaAdsAccounts.mockReset();
- setOnboardingMetaAdsAccountAction.mockReset();
- listGscProperties.mockReset();
- setOnboardingGscPropertyAction.mockReset();
- addUserMcpServerAction.mockReset();
- routerPush.mockReset();
- routerReplace.mockReset();
- toastFns.success.mockReset();
- toastFns.error.mockReset();
- searchParamsRef.current = new URLSearchParams();
- // Sensible default — connect-step renders need this to resolve.
- getConnectStepStateAction.mockResolvedValue({
- ok: true,
- state: {
- googleads: { connected: false, account_selected: false },
- metaads: { connected: false, account_selected: false },
- gsc: { connected: false, account_selected: false },
- xads: { connected: false, account_selected: false },
- extras: [],
- extra_connected_count: 0,
- website_url: null,
- },
- });
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("OnboardingFlow — NameStep (default step)", () => {
- it("renders the project-name form when no step param is set", () => {
- render(<OnboardingFlow />);
- expect(
- screen.getByRole("heading", { name: /Let.s set up your workspace/i }),
- ).toBeInTheDocument();
- expect(screen.getByLabelText(/Name/i)).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /Continue/i })).toBeInTheDocument();
- });
-
- it("renders the skip-to-content link for keyboard users", () => {
- render(<OnboardingFlow />);
- const skip = screen.getByText(/Skip to content/i);
- expect(skip).toHaveAttribute("href", "#onboarding-main");
- });
-
- it("invokes createProjectForOnboardingAction and pushes to ?step=connect on success", async () => {
- createProjectForOnboardingAction.mockResolvedValue({
- ok: true,
- data: { slug: "acme-q4", display_name: "Acme Q4" },
- });
- render(<OnboardingFlow />);
- fireEvent.change(screen.getByLabelText(/Name/i), {
- target: { value: "Acme Q4" },
- });
- fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
- await waitFor(() =>
- expect(createProjectForOnboardingAction).toHaveBeenCalled(),
- );
- await waitFor(() =>
- expect(routerPush).toHaveBeenCalledWith(
- "/onboarding?step=connect&slug=acme-q4",
- ),
- );
- });
-
- it("renders an inline error alert when the server action returns ok=false", async () => {
- createProjectForOnboardingAction.mockResolvedValue({
- ok: false,
- error: "Please enter a workspace name.",
- });
- render(<OnboardingFlow />);
- fireEvent.change(screen.getByLabelText(/Name/i), {
- target: { value: "x" },
- });
- fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
- const alert = await screen.findByRole("alert");
- expect(alert).toHaveTextContent("Please enter a workspace name.");
- expect(routerPush).not.toHaveBeenCalled();
- });
-
- it("URL-encodes the slug returned from the server action", async () => {
- createProjectForOnboardingAction.mockResolvedValue({
- ok: true,
- data: { slug: "weird slug/with chars", display_name: "Weird" },
- });
- render(<OnboardingFlow />);
- fireEvent.change(screen.getByLabelText(/Name/i), {
- target: { value: "Weird" },
- });
- fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
- await waitFor(() =>
- expect(routerPush).toHaveBeenCalledWith(
- `/onboarding?step=connect&slug=${encodeURIComponent("weird slug/with chars")}`,
- ),
- );
- });
-});
-
-describe("OnboardingFlow — MissingSlug", () => {
- it("renders the missing-slug card when step=connect but no slug", () => {
- setStep("connect", null);
- render(<OnboardingFlow />);
- expect(
- screen.getByText(/This step needs a workspace. Start from the beginning./i),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("link", { name: /Start over/i }),
- ).toHaveAttribute("href", "/onboarding");
- });
-
- it("renders the missing-slug card when step=account but no slug", () => {
- setStep("account", null);
- render(<OnboardingFlow />);
- expect(
- screen.getByText(/This step needs a workspace. Start from the beginning./i),
- ).toBeInTheDocument();
- });
-});
-
-describe("OnboardingFlow — ConnectStep", () => {
- it("renders the four recommended-MCP tiles + Skip when nothing is connected", async () => {
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- expect(
- await screen.findByRole("heading", { name: /Connect MCPs to your agents/i }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /^Google Ads/i }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /^Meta Ads/i }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /Google Search Console/i }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /^X Ads/i }),
- ).toBeInTheDocument();
- // Google Analytics powers no specialist — it lives under "More
- // tools" now, not as a first-class tile.
- expect(
- screen.queryByRole("button", { name: /^Google Analytics/i }),
- ).not.toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /More tools/i }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /^Skip/i }),
- ).toBeInTheDocument();
- });
-
- it("starts OAuth for a no-picker MCP (X Ads) with a connect-step return_to", async () => {
- const loc = setLocationHref();
- startMcpConnect.mockResolvedValue({
- ok: true,
- authorize_url: "https://issuer.example/oauth",
- });
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- fireEvent.click(
- await screen.findByRole("button", { name: /^X Ads/i }),
- );
- await waitFor(() =>
- expect(startMcpConnect).toHaveBeenCalledWith({
- mcp_key: "notfair-xads",
- return_to: "/onboarding?step=connect&slug=acme",
- }),
- );
- await waitFor(() => expect(loc.href).toBe("https://issuer.example/oauth"));
- });
-
- it("starts OAuth for Google Ads with a connect-step return_to", async () => {
- const loc = setLocationHref();
- startMcpConnect.mockResolvedValue({
- ok: true,
- authorize_url: "https://issuer.example/oauth",
- });
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- fireEvent.click(await screen.findByRole("button", { name: /^Google Ads/i }));
- await waitFor(() =>
- expect(startMcpConnect).toHaveBeenCalledWith({
- mcp_key: "notfair-googleads",
- return_to: "/onboarding?step=account&slug=acme",
- }),
- );
- await waitFor(() =>
- expect(loc.href).toBe("https://issuer.example/oauth"),
- );
- });
-
- it("toasts and re-enables the tile when startMcpConnect returns ok=false", async () => {
- startMcpConnect.mockResolvedValue({ ok: false, error: "registration failed" });
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- const tile = await screen.findByRole("button", { name: /^Google Ads/i });
- fireEvent.click(tile);
- await waitFor(() =>
- expect(toastFns.error).toHaveBeenCalledWith("registration failed"),
- );
- expect(tile).not.toBeDisabled();
- });
-
- it("toasts the thrown error when startMcpConnect throws", async () => {
- startMcpConnect.mockRejectedValue(new Error("offline"));
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- fireEvent.click(await screen.findByRole("button", { name: /^Google Ads/i }));
- await waitFor(() =>
- expect(toastFns.error).toHaveBeenCalledWith("offline"),
- );
- });
-
- it("hands off to the setup screen via Skip when zero MCPs are connected", async () => {
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- fireEvent.click(await screen.findByRole("button", { name: /^Skip/i }));
- expect(routerReplace).toHaveBeenCalledWith(
- "/onboarding?step=setup&slug=acme&from=skip",
- );
- });
-
- it("flips Skip → 'Next' once at least one MCP is connected", async () => {
- getConnectStepStateAction.mockResolvedValue({
- ok: true,
- state: {
- googleads: { connected: true, account_selected: true },
- metaads: { connected: false, account_selected: false },
- gsc: { connected: false, account_selected: false },
- xads: { connected: false, account_selected: false },
- extras: [],
- extra_connected_count: 0,
- website_url: null,
- },
- });
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- const done = await screen.findByRole("button", { name: /^Next/i });
- expect(done).toBeInTheDocument();
- expect(
- screen.queryByRole("button", { name: /^Skip/i }),
- ).not.toBeInTheDocument();
- fireEvent.click(done);
- expect(routerReplace).toHaveBeenCalledWith(
- "/onboarding?step=setup&slug=acme&from=connect",
- );
- });
-
- it("renders a row for each extra MCP connected via the More dialog", async () => {
- getConnectStepStateAction.mockResolvedValue({
- ok: true,
- state: {
- googleads: { connected: false, account_selected: false },
- metaads: { connected: false, account_selected: false },
- gsc: { connected: false, account_selected: false },
- xads: { connected: false, account_selected: false },
- extras: [
- {
- key: "stripe",
- display_name: "Stripe",
- description: "Payments.",
- resource_url: "https://mcp.stripe.com/",
- },
- {
- key: "supabase",
- display_name: "Supabase",
- description: "Postgres.",
- resource_url: "https://mcp.supabase.com/mcp",
- },
- ],
- extra_connected_count: 2,
- website_url: null,
- },
- });
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- // Both extras render as new rows in the grouped list, each with their
- // display name visible.
- expect(await screen.findByText("Stripe")).toBeInTheDocument();
- expect(screen.getByText("Supabase")).toBeInTheDocument();
- // The "More tools" tile still surfaces the count so the user can see
- // at a glance how many extras are wired up.
- expect(screen.getByText(/2 connected/)).toBeInTheDocument();
- });
-
- it("shows a 'Select Google Ads account' sub-action when the MCP is connected but no account is picked", async () => {
- getConnectStepStateAction.mockResolvedValue({
- ok: true,
- state: {
- googleads: { connected: true, account_selected: false },
- metaads: { connected: false, account_selected: false },
- gsc: { connected: false, account_selected: false },
- xads: { connected: false, account_selected: false },
- extras: [],
- extra_connected_count: 0,
- website_url: null,
- },
- });
- setStep("connect", "acme");
- render(<OnboardingFlow />);
- const pick = await screen.findByRole("button", {
- name: /Select Google Ads account/i,
- });
- fireEvent.click(pick);
- expect(routerPush).toHaveBeenCalledWith(
- "/onboarding?step=account&slug=acme",
- );
- });
-});
-
-describe("OnboardingFlow — SetupStep", () => {
- it("renders the per-template checklist while provisioning runs", async () => {
- getProvisioningProgressAction.mockResolvedValue({
- ok: true,
- overall: "running",
- steps: [
- { key: "cmo", label: "Setting up CMO", status: "in_progress" },
- {
- key: "google_ads",
- label: "Setting up Google Ads Specialist",
- status: "pending",
- },
- {
- key: "gateway",
- label: "Connecting agents to gateway",
- status: "pending",
- },
- ],
- });
- setStep("setup", "acme");
- render(<OnboardingFlow />);
- expect(
- await screen.findByText(/Setting up CMO/i),
- ).toBeInTheDocument();
- expect(screen.getByText(/Setting up Google Ads Specialist/i)).toBeInTheDocument();
- expect(screen.getByText(/Connecting agents to gateway/i)).toBeInTheDocument();
- expect(routerReplace).not.toHaveBeenCalled();
- });
-
- it("redirects to the task workspace once provisioning is done", async () => {
- getProvisioningProgressAction.mockResolvedValue({
- ok: true,
- overall: "done",
- steps: [
- { key: "cmo", label: "Setting up CMO", status: "done" },
- {
- key: "google_ads",
- label: "Setting up Google Ads Specialist",
- status: "done",
- },
- {
- key: "gateway",
- label: "Connecting agents to gateway",
- status: "done",
- },
- ],
- });
- getOnboardingTaskForSkipAction.mockResolvedValue({
- ok: true,
- task_display_id: "acme-1",
- cmo_agent_slug: "cmo-greg",
- });
- setStep("setup", "acme");
- render(<OnboardingFlow />);
- await waitFor(() =>
- expect(routerReplace).toHaveBeenCalledWith(
- "/acme/agents/cmo-greg/tasks?task=acme-1",
- ),
- );
- });
-
- it("surfaces an error when provisioning fails", async () => {
- getProvisioningProgressAction.mockResolvedValue({
- ok: true,
- overall: "failed",
- steps: [
- {
- key: "cmo",
- label: "Setting up CMO",
- status: "failed",
- error: "openclaw agents add failed",
- },
- {
- key: "google_ads",
- label: "Setting up Google Ads Specialist",
- status: "pending",
- },
- {
- key: "gateway",
- label: "Connecting agents to gateway",
- status: "pending",
- },
- ],
- });
- setStep("setup", "acme");
- render(<OnboardingFlow />);
- await waitFor(() =>
- expect(
- screen.getAllByText(/openclaw agents add failed/i).length,
- ).toBeGreaterThan(0),
- );
- // The failing row stays visible (red status icon) and a top-level
- // error alert summarises the failure so it can't be missed.
- expect(screen.getByRole("alert")).toHaveTextContent(
- /openclaw agents add failed/i,
- );
- });
-});
-
-describe("OnboardingFlow — AccountStep", () => {
- it("shows a loading card while listGoogleAdsAccounts is pending", () => {
- listGoogleAdsAccounts.mockReturnValue(new Promise(() => {}));
- setStep("account", "acme");
- render(<OnboardingFlow />);
- expect(
- screen.getByText(/Loading your Google Ads accounts/i),
- ).toBeInTheDocument();
- });
-
- it("renders an error card with retry + skip when listGoogleAdsAccounts fails", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: false,
- kind: "rpc",
- error: "HTTP 500",
- });
- setStep("account", "acme");
- render(<OnboardingFlow />);
- expect(
- await screen.findByText(/Couldn.t load your Google Ads accounts/i),
- ).toBeInTheDocument();
- expect(screen.getByText(/HTTP 500/)).toBeInTheDocument();
- expect(
- screen.getByRole("link", { name: /Retry from start/i }),
- ).toHaveAttribute("href", "/onboarding");
- expect(
- screen.getByRole("link", { name: /Skip to project/i }),
- ).toHaveAttribute("href", "/acme");
- });
-
- it("renders the no-accounts state with reconnect link when the list is empty", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [],
- default_account_id: null,
- });
- setStep("account", "acme");
- render(<OnboardingFlow />);
- expect(
- await screen.findByText(/No Google Ads accounts found/i),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("link", { name: /Reconnect/i }),
- ).toHaveAttribute(
- "href",
- "/onboarding?step=connect&slug=acme",
- );
- });
-
- it("auto-selects the only account and routes back to the connect step", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [{ id: "123-456-7890", name: "Solo Account" }],
- default_account_id: "123-456-7890",
- });
- setOnboardingAccountAction.mockResolvedValue({
- ok: true,
- project: {},
- task_display_id: "AUDIT-1",
- cmo_agent_slug: "cmo-greg",
- });
- setStep("account", "acme");
- render(<OnboardingFlow />);
- await waitFor(() =>
- expect(setOnboardingAccountAction).toHaveBeenCalledWith("acme", "123-456-7890"),
- );
- await waitFor(() =>
- expect(routerReplace).toHaveBeenCalledWith(
- "/onboarding?step=connect&slug=acme",
- ),
- );
- });
-
- it("falls back to the error state when auto-select setOnboardingAccountAction fails", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [{ id: "1", name: "Solo" }],
- default_account_id: null,
- });
- setOnboardingAccountAction.mockResolvedValue({
- ok: false,
- error: "permission denied",
- });
- setStep("account", "acme");
- render(<OnboardingFlow />);
- expect(
- await screen.findByText(/Couldn.t load your Google Ads accounts/i),
- ).toBeInTheDocument();
- expect(toastFns.error).toHaveBeenCalledWith("permission denied");
- });
-
- it("renders the picker with a 'default' badge when multiple accounts are returned", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [
- { id: "111", name: "Alpha" },
- { id: "222", name: "Bravo" },
- ],
- default_account_id: "222",
- });
- setStep("account", "acme");
- render(<OnboardingFlow />);
- expect(
- await screen.findByRole("heading", { name: /Which Google Ads account/i }),
- ).toBeInTheDocument();
- expect(screen.getByText("Alpha")).toBeInTheDocument();
- expect(screen.getByText("Bravo")).toBeInTheDocument();
- expect(screen.getByText("default")).toBeInTheDocument();
- expect(screen.getByText(/Customer ID 111/)).toBeInTheDocument();
- expect(screen.getByText(/Customer ID 222/)).toBeInTheDocument();
- });
-
- it("picks the chosen account and routes back to the connect step", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [
- { id: "111", name: "Alpha" },
- { id: "222", name: "Bravo" },
- ],
- default_account_id: null,
- });
- setOnboardingAccountAction.mockResolvedValue({
- ok: true,
- project: {},
- task_display_id: "TASK-9",
- cmo_agent_slug: "cmo-greg",
- });
- setStep("account", "acme");
- render(<OnboardingFlow />);
- const alphaBtn = await screen.findByRole("button", {
- name: /Audit Alpha \(111\)/,
- });
- fireEvent.click(alphaBtn);
- await waitFor(() =>
- expect(setOnboardingAccountAction).toHaveBeenCalledWith("acme", "111"),
- );
- await waitFor(() =>
- expect(routerReplace).toHaveBeenCalledWith(
- "/onboarding?step=connect&slug=acme",
- ),
- );
- });
-
- it("toasts and re-enables the pick buttons when setOnboardingAccountAction returns ok=false", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [
- { id: "111", name: "Alpha" },
- { id: "222", name: "Bravo" },
- ],
- default_account_id: null,
- });
- setOnboardingAccountAction.mockResolvedValue({
- ok: false,
- error: "boom",
- });
- setStep("account", "acme");
- render(<OnboardingFlow />);
- const alphaBtn = await screen.findByRole("button", {
- name: /Audit Alpha/,
- });
- fireEvent.click(alphaBtn);
- await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("boom"));
- expect(alphaBtn).not.toBeDisabled();
- });
-
- it("toasts the thrown error when onPick throws", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [
- { id: "111", name: "Alpha" },
- { id: "222", name: "Bravo" },
- ],
- default_account_id: null,
- });
- setOnboardingAccountAction.mockRejectedValue(new Error("network"));
- setStep("account", "acme");
- render(<OnboardingFlow />);
- const alphaBtn = await screen.findByRole("button", {
- name: /Audit Alpha/,
- });
- fireEvent.click(alphaBtn);
- await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("network"));
- });
-
- it("disables all picker buttons while one selection is in flight", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [
- { id: "111", name: "Alpha" },
- { id: "222", name: "Bravo" },
- ],
- default_account_id: null,
- });
- let resolve: (v: { ok: true; project: object; task_display_id: string }) => void = () => {};
- setOnboardingAccountAction.mockImplementation(
- () =>
- new Promise<{ ok: true; project: object; task_display_id: string }>(
- (res) => {
- resolve = res;
- },
- ),
- );
- setStep("account", "acme");
- render(<OnboardingFlow />);
- const alphaBtn = await screen.findByRole("button", {
- name: /Audit Alpha/,
- });
- const bravoBtn = screen.getByRole("button", { name: /Audit Bravo/ });
- fireEvent.click(alphaBtn);
- await waitFor(() => expect(alphaBtn).toBeDisabled());
- expect(bravoBtn).toBeDisabled();
- act(() => {
- resolve({ ok: true, project: {}, task_display_id: "TASK-1" });
- });
- });
-
- it("renders the auto-select loading card when exactly one account exists", async () => {
- listGoogleAdsAccounts.mockResolvedValue({
- ok: true,
- accounts: [{ id: "1", name: "Solo" }],
- default_account_id: null,
- });
- // setOnboardingAccountAction never resolves: keeps the auto-select card visible.
- setOnboardingAccountAction.mockReturnValue(new Promise(() => {}));
- setStep("account", "acme");
- render(<OnboardingFlow />);
- expect(
- await screen.findByText(/Using your only Google Ads account/i),
- ).toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/policy-list.tsx b/notfair-cmo/src/components/policy-list.tsx
deleted file mode 100644
index 5fcb58f6..00000000
--- a/notfair-cmo/src/components/policy-list.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-"use client";
-
-import { useState, useTransition } from "react";
-import { Trash2, ShieldCheck } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Card, CardContent } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import { toast } from "sonner";
-import {
- createPolicyAction,
- deletePolicyAction,
-} from "@/server/actions/approvals";
-import type { ApprovalPolicy, ApprovalType } from "@/types";
-
-const ACTION_TYPES: { key: ApprovalType; label: string }[] = [
- { key: "spend", label: "Spend" },
- { key: "content_publishing", label: "Content publishing" },
- { key: "new_channel", label: "New channel" },
- { key: "bid_change", label: "Bid change" },
- { key: "audience_change", label: "Audience change" },
- { key: "other", label: "Other" },
-];
-
-function formatUsd(n: number) {
- return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
-}
-
-export function PolicyList({
- projectSlug,
- policies,
-}: {
- projectSlug: string;
- policies: ApprovalPolicy[];
-}) {
- const [showForm, setShowForm] = useState(false);
- const [actionType, setActionType] = useState<ApprovalType>("spend");
- const [agentId, setAgentId] = useState("");
- const [maxCost, setMaxCost] = useState("");
- const [autoDecision, setAutoDecision] = useState<"approve" | "reject">("approve");
- const [note, setNote] = useState("");
- const [pending, start] = useTransition();
-
- function submit() {
- start(async () => {
- const cap = maxCost.trim() ? Number(maxCost) : null;
- if (maxCost.trim() && (!Number.isFinite(cap) || cap! < 0)) {
- toast.error("Cost cap must be non-negative number");
- return;
- }
- const r = await createPolicyAction({
- project_slug: projectSlug,
- action_type: actionType,
- agent_id: agentId.trim() || null,
- max_cost_usd: cap,
- auto_decision: autoDecision,
- note: note.trim() || null,
- });
- if (!r.ok) toast.error(r.error ?? "Failed to create policy");
- else {
- toast.success("Policy saved");
- setShowForm(false);
- setAgentId("");
- setMaxCost("");
- setNote("");
- }
- });
- }
- function remove(id: string) {
- start(async () => {
- const r = await deletePolicyAction(id);
- if (!r.ok) toast.error(r.error ?? "Failed to delete policy");
- else toast.success("Policy removed");
- });
- }
-
- return (
- <div className="space-y-4">
- <Card>
- <CardContent className="space-y-3 py-4">
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div className="space-y-1">
- <p className="text-sm font-medium">Auto-approve rules</p>
- <p className="text-xs text-muted-foreground">
- When an agent requests a matching action, it's auto-decided without
- surfacing in the inbox. Tighter rules win first (specific agent, lower
- cost cap).
- </p>
- </div>
- <Button size="sm" onClick={() => setShowForm((s) => !s)} disabled={pending}>
- {showForm ? "Cancel" : "New rule"}
- </Button>
- </div>
-
- {showForm && (
- <div className="space-y-3 rounded-md bg-muted/40 p-3">
- <div className="grid gap-3 sm:grid-cols-2">
- <label className="space-y-1 text-xs">
- <span className="block font-medium">Action type</span>
- <select
- value={actionType}
- onChange={(e) => setActionType(e.target.value as ApprovalType)}
- className="h-9 w-full rounded-md border border-transparent bg-[hsl(var(--notfair-surface-2))] px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
- disabled={pending}
- >
- {ACTION_TYPES.map((t) => (
- <option key={t.key} value={t.key}>
- {t.label}
- </option>
- ))}
- </select>
- </label>
- <label className="space-y-1 text-xs">
- <span className="block font-medium">Decision</span>
- <select
- value={autoDecision}
- onChange={(e) => setAutoDecision(e.target.value as "approve" | "reject")}
- className="h-9 w-full rounded-md border border-transparent bg-[hsl(var(--notfair-surface-2))] px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
- disabled={pending}
- >
- <option value="approve">Auto-approve</option>
- <option value="reject">Auto-reject</option>
- </select>
- </label>
- <label className="space-y-1 text-xs">
- <span className="block font-medium">
- Agent ID <span className="text-muted-foreground">(optional)</span>
- </span>
- <Input
- value={agentId}
- onChange={(e) => setAgentId(e.target.value)}
- placeholder="Any agent"
- disabled={pending}
- />
- </label>
- <label className="space-y-1 text-xs">
- <span className="block font-medium">
- Cost cap USD <span className="text-muted-foreground">(optional)</span>
- </span>
- <Input
- type="number"
- min="0"
- step="0.01"
- value={maxCost}
- onChange={(e) => setMaxCost(e.target.value)}
- placeholder="No cap"
- disabled={pending}
- />
- </label>
- </div>
- <label className="space-y-1 text-xs">
- <span className="block font-medium">Note (shown to the agent)</span>
- <Input
- value={note}
- onChange={(e) => setNote(e.target.value)}
- placeholder="Why does this rule exist?"
- disabled={pending}
- />
- </label>
- <div>
- <Button size="sm" onClick={submit} disabled={pending}>
- Save rule
- </Button>
- </div>
- </div>
- )}
- </CardContent>
- </Card>
-
- {policies.length === 0 ? (
- <Card>
- <CardContent className="py-12 text-center text-sm text-muted-foreground">
- No rules yet. Without rules, every write surfaces in the inbox.
- </CardContent>
- </Card>
- ) : (
- <div className="space-y-2">
- {policies.map((p) => (
- <Card key={p.id}>
- <CardContent className="flex items-start justify-between gap-3 py-3">
- <div className="min-w-0 flex-1 space-y-1.5">
- <div className="flex flex-wrap items-center gap-1.5">
- <Badge variant="outline" className="text-[10px]">
- {p.action_type}
- </Badge>
- <Badge
- variant={p.auto_decision === "approve" ? "default" : "destructive"}
- className="gap-1 text-[10px]"
- >
- <ShieldCheck className="size-3" />
- Auto-{p.auto_decision}
- </Badge>
- {p.agent_id ? (
- <Badge variant="secondary" className="text-[10px] font-mono">
- {p.agent_id}
- </Badge>
- ) : (
- <Badge variant="outline" className="text-[10px]">
- any agent
- </Badge>
- )}
- {p.max_cost_usd != null && (
- <Badge variant="outline" className="text-[10px]">
- ≤ {formatUsd(p.max_cost_usd)}
- </Badge>
- )}
- </div>
- {p.note && (
- <p className="text-sm leading-snug">{p.note}</p>
- )}
- </div>
- <Button
- size="sm"
- variant="ghost"
- onClick={() => remove(p.id)}
- disabled={pending}
- aria-label="Delete policy"
- >
- <Trash2 className="size-4" />
- </Button>
- </CardContent>
- </Card>
- ))}
- </div>
- )}
- </div>
- );
-}
diff --git a/notfair-cmo/src/components/project-cookie-sync.test.tsx b/notfair-cmo/src/components/project-cookie-sync.test.tsx
deleted file mode 100644
index ba245bf1..00000000
--- a/notfair-cmo/src/components/project-cookie-sync.test.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, cleanup } from "@testing-library/react";
-
-const switchProjectAction = vi.fn();
-
-vi.mock("@/server/actions/projects", () => ({
- switchProjectAction: (...args: unknown[]) => switchProjectAction(...args),
-}));
-
-import { ProjectCookieSync } from "./project-cookie-sync";
-
-beforeEach(() => {
- switchProjectAction.mockReset();
- switchProjectAction.mockResolvedValue({ ok: true });
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("ProjectCookieSync", () => {
- it("calls switchProjectAction with the slug on first mount", () => {
- render(<ProjectCookieSync slug="alpha" />);
- expect(switchProjectAction).toHaveBeenCalledTimes(1);
- expect(switchProjectAction).toHaveBeenCalledWith("alpha");
- });
-
- it("renders nothing visible", () => {
- const { container } = render(<ProjectCookieSync slug="alpha" />);
- expect(container.firstChild).toBeNull();
- });
-
- it("does not re-fire when the same slug is re-rendered", () => {
- const { rerender } = render(<ProjectCookieSync slug="alpha" />);
- expect(switchProjectAction).toHaveBeenCalledTimes(1);
- rerender(<ProjectCookieSync slug="alpha" />);
- expect(switchProjectAction).toHaveBeenCalledTimes(1);
- });
-
- it("fires again when the slug changes", () => {
- const { rerender } = render(<ProjectCookieSync slug="alpha" />);
- rerender(<ProjectCookieSync slug="beta" />);
- expect(switchProjectAction).toHaveBeenCalledTimes(2);
- expect(switchProjectAction).toHaveBeenLastCalledWith("beta");
- });
-});
diff --git a/notfair-cmo/src/components/project-rename-card.test.tsx b/notfair-cmo/src/components/project-rename-card.test.tsx
deleted file mode 100644
index c5bbcea1..00000000
--- a/notfair-cmo/src/components/project-rename-card.test.tsx
+++ /dev/null
@@ -1,142 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const router = {
- push: vi.fn(),
- refresh: vi.fn(),
-};
-const renameProjectFullAction = vi.fn();
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
-};
-
-vi.mock("next/navigation", () => ({
- useRouter: () => router,
-}));
-
-vi.mock("@/server/actions/projects", () => ({
- renameProjectFullAction: (...args: unknown[]) => renameProjectFullAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- },
-}));
-
-import { ProjectRenameCard } from "./project-rename-card";
-
-beforeEach(() => {
- router.refresh.mockReset();
- router.push.mockReset();
- renameProjectFullAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("ProjectRenameCard", () => {
- it("seeds the input with the current display name", () => {
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- expect(screen.getByLabelText(/display name/i)).toHaveValue("Alpha");
- });
-
- it("disables Save when name is unchanged", () => {
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- expect(screen.getByRole("button", { name: /save name/i })).toBeDisabled();
- });
-
- it("flips the button to 'Rename workspace' when the slug changes", () => {
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "Bravo" } });
- expect(
- screen.getByRole("button", { name: /rename workspace/i }),
- ).toBeInTheDocument();
- expect(screen.getByText(/slug changes from/i)).toBeInTheDocument();
- });
-
- it("shows invalid-name error and disables save on bad input", () => {
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "@@@" } });
- expect(screen.getByText(/invalid name/i)).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /save name|rename workspace/i }),
- ).toBeDisabled();
- });
-
- it("calls renameProjectFullAction and toasts on partial-success (failures present)", async () => {
- renameProjectFullAction.mockResolvedValue({
- ok: true,
- data: {
- full_rename: true,
- display_name: "Bravo",
- agents_relocated: ["a", "b"],
- agents_failed: ["c"],
- },
- });
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "Bravo" } });
- fireEvent.click(screen.getByRole("button", { name: /rename workspace/i }));
- await waitFor(() =>
- expect(renameProjectFullAction).toHaveBeenCalledWith({
- current_slug: "alpha",
- new_display_name: "Bravo",
- }),
- );
- await waitFor(() =>
- expect(toast.success.mock.calls[0][0]).toMatch(/2 agents moved, 1 failed/),
- );
- await waitFor(() => expect(router.refresh).toHaveBeenCalled());
- });
-
- it("toasts a clean success when no agents failed", async () => {
- renameProjectFullAction.mockResolvedValue({
- ok: true,
- data: {
- full_rename: true,
- display_name: "Bravo",
- agents_relocated: ["a"],
- agents_failed: [],
- },
- });
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "Bravo" } });
- fireEvent.click(screen.getByRole("button", { name: /rename workspace/i }));
- await waitFor(() =>
- expect(toast.success.mock.calls[0][0]).toMatch(/1 agents moved/),
- );
- });
-
- it("uses the display-name-only success toast when full_rename is false", async () => {
- renameProjectFullAction.mockResolvedValue({
- ok: true,
- data: { full_rename: false, display_name: "ALPHA" },
- });
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "ALPHA" } });
- fireEvent.click(screen.getByRole("button", { name: /save name/i }));
- await waitFor(() =>
- expect(toast.success).toHaveBeenCalledWith('Renamed to "ALPHA"'),
- );
- });
-
- it("toasts the server error when rename fails", async () => {
- renameProjectFullAction.mockResolvedValue({ ok: false, error: "boom" });
- render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);
- const input = screen.getByLabelText(/display name/i);
- fireEvent.change(input, { target: { value: "Bravo" } });
- fireEvent.click(screen.getByRole("button", { name: /rename workspace/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("boom"));
- });
-});
diff --git a/notfair-cmo/src/components/project-switcher.test.tsx b/notfair-cmo/src/components/project-switcher.test.tsx
deleted file mode 100644
index ca9abf31..00000000
--- a/notfair-cmo/src/components/project-switcher.test.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const pathnameRef: { current: string } = { current: "/proj-a/agents/cmo/tasks" };
-const router = {
- push: vi.fn(),
- refresh: vi.fn(),
-};
-
-vi.mock("next/navigation", () => ({
- useRouter: () => router,
- usePathname: () => pathnameRef.current,
-}));
-
-const switchProjectAction = vi.fn();
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
-};
-
-vi.mock("@/server/actions/projects", () => ({
- switchProjectAction: (...args: unknown[]) => switchProjectAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- },
-}));
-
-vi.mock("@/components/ui/sidebar", () => ({
- SidebarMenuButton: ({ children, ...rest }: { children: React.ReactNode }) => (
- <button type="button" {...rest}>
- {children}
- </button>
- ),
-}));
-
-import { ProjectSwitcher } from "./project-switcher";
-
-function openMenu() {
- const trigger = screen.getByRole("button");
- fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });
- fireEvent.click(trigger);
-}
-
-const projects = [
- { 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(() => {
- switchProjectAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
- router.push.mockReset();
- router.refresh.mockReset();
- pathnameRef.current = "/proj-a/agents/cmo/tasks";
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("ProjectSwitcher", () => {
- it("shows the active project display name (and not the slug)", () => {
- render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
- expect(screen.getByText("Alpha")).toBeInTheDocument();
- // The slug subtitle was redundant — only the avatar + display name
- // render in the trigger now.
- expect(screen.queryByText("proj-a")).not.toBeInTheDocument();
- });
-
- it("falls back to placeholder text when no project is active", () => {
- render(<ProjectSwitcher projects={[]} activeSlug={null} />);
- expect(screen.getByText("No workspace")).toBeInTheDocument();
- });
-
- it("shows the project initials in the avatar", () => {
- render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
- expect(screen.getAllByText("AL").length).toBeGreaterThan(0);
- });
-
- it("renders a 'New workspace' link to /onboarding", () => {
- render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
- openMenu();
- expect(screen.getByText("New workspace")).toBeInTheDocument();
- });
-
- it("opens the menu and lists all projects", () => {
- render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
- openMenu();
- expect(screen.getAllByText("Alpha").length).toBeGreaterThan(0);
- expect(screen.getByText("Beta")).toBeInTheDocument();
- });
-
- it("switches projects when picking a non-active item", async () => {
- switchProjectAction.mockResolvedValue({ ok: true });
- render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
- openMenu();
- fireEvent.click(screen.getByText("Beta"));
- await waitFor(() => expect(switchProjectAction).toHaveBeenCalledWith("proj-b"));
- await waitFor(() =>
- expect(router.push).toHaveBeenCalledWith("/proj-b/agents/cmo/tasks"),
- );
- });
-
- it("does not call switchProject when picking the active project", () => {
- render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
- openMenu();
- const items = screen.getAllByText("Alpha");
- const item = items[items.length - 1];
- fireEvent.click(item);
- expect(switchProjectAction).not.toHaveBeenCalled();
- });
-
- it("toasts the error when switchProjectAction fails", async () => {
- switchProjectAction.mockResolvedValue({ ok: false, error: "nope" });
- render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);
- openMenu();
- fireEvent.click(screen.getByText("Beta"));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("nope"));
- expect(router.push).not.toHaveBeenCalled();
- });
-
- it("shows 'No workspaces yet' when projects list is empty", () => {
- render(<ProjectSwitcher projects={[]} activeSlug={null} />);
- openMenu();
- expect(screen.getByText("No workspaces yet")).toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/question-card.test.tsx b/notfair-cmo/src/components/question-card.test.tsx
deleted file mode 100644
index 1f469ca1..00000000
--- a/notfair-cmo/src/components/question-card.test.tsx
+++ /dev/null
@@ -1,199 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
-
-const answerMock = vi.fn();
-const cancelMock = vi.fn();
-const toastSuccessMock = vi.fn();
-const toastErrorMock = vi.fn();
-const toastInfoMock = vi.fn();
-
-vi.mock("@/server/actions/questions", () => ({
- answerQuestionAction: (...a: unknown[]) => answerMock(...a),
- cancelQuestionAction: (...a: unknown[]) => cancelMock(...a),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...a: unknown[]) => toastSuccessMock(...a),
- error: (...a: unknown[]) => toastErrorMock(...a),
- info: (...a: unknown[]) => toastInfoMock(...a),
- },
-}));
-
-import { QuestionCard } from "./question-card";
-import type { Question } from "@/types";
-
-function makeQuestion(overrides: Partial<Question> = {}): Question {
- return {
- id: "q-1",
- project_slug: "demo",
- agent_id: "demo-cmo",
- task_id: "t-1",
- prompt: "Which channel should we test first?",
- options_json: JSON.stringify(["Google Ads", "Meta", "TikTok"]),
- status: "pending",
- answer_option_index: null,
- answer_text: null,
- resolved_by_kind: null,
- created_at: new Date(Date.now() - 60_000).toISOString(),
- resolved_at: null,
- ...overrides,
- };
-}
-
-beforeEach(() => {
- answerMock.mockReset();
- cancelMock.mockReset();
- toastSuccessMock.mockReset();
- toastErrorMock.mockReset();
- toastInfoMock.mockReset();
-});
-
-describe("QuestionCard — pending state", () => {
- it("renders prompt, agent, status badge, and each option as a radio button", () => {
- render(
- <QuestionCard
- question={makeQuestion()}
- options={["Google Ads", "Meta", "TikTok"]}
- />,
- );
- expect(screen.getByText("Which channel should we test first?")).toBeInTheDocument();
- expect(screen.getByText("Question")).toBeInTheDocument();
- expect(screen.getByText("Needs answer")).toBeInTheDocument();
- expect(screen.getByText("demo-cmo")).toBeInTheDocument();
-
- const radios = screen.getAllByRole("radio");
- expect(radios).toHaveLength(3);
- expect(radios[0]).toHaveTextContent("Google Ads");
- expect(radios[2]).toHaveTextContent("TikTok");
- });
-
- it("Send is disabled until an option is picked or text is typed", () => {
- render(
- <QuestionCard
- question={makeQuestion()}
- options={["Google Ads", "Meta"]}
- />,
- );
- const send = screen.getByRole("button", { name: /send answer/i });
- expect(send).toBeDisabled();
- fireEvent.click(screen.getByRole("radio", { name: /Meta/ }));
- expect(send).not.toBeDisabled();
- });
-
- it("clicking a selected option deselects it", () => {
- render(
- <QuestionCard
- question={makeQuestion()}
- options={["Google Ads", "Meta"]}
- />,
- );
- const metaRadio = screen.getByRole("radio", { name: /Meta/ });
- fireEvent.click(metaRadio);
- expect(metaRadio).toHaveAttribute("aria-checked", "true");
- fireEvent.click(metaRadio);
- expect(metaRadio).toHaveAttribute("aria-checked", "false");
- expect(screen.getByRole("button", { name: /send answer/i })).toBeDisabled();
- });
-
- it("submitting calls answerQuestionAction with the chosen index + text", async () => {
- answerMock.mockResolvedValue({ ok: true });
- render(
- <QuestionCard
- question={makeQuestion()}
- options={["Google Ads", "Meta", "TikTok"]}
- />,
- );
- fireEvent.click(screen.getByRole("radio", { name: /Meta/ }));
- fireEvent.change(screen.getByPlaceholderText(/add nuance|Type your answer/), {
- target: { value: "Start lean — $200 daily" },
- });
- fireEvent.click(screen.getByRole("button", { name: /send answer/i }));
- await waitFor(() => {
- expect(answerMock).toHaveBeenCalledWith("q-1", {
- option_index: 1,
- text: "Start lean — $200 daily",
- });
- expect(toastSuccessMock).toHaveBeenCalled();
- });
- });
-
- it("surfaces server errors via toast and does not show success", async () => {
- answerMock.mockResolvedValue({ ok: false, error: "boom" });
- render(
- <QuestionCard
- question={makeQuestion()}
- options={["Google Ads"]}
- />,
- );
- fireEvent.click(screen.getByRole("radio", { name: /Google Ads/ }));
- fireEvent.click(screen.getByRole("button", { name: /send answer/i }));
- await waitFor(() => {
- expect(toastErrorMock).toHaveBeenCalledWith("boom");
- });
- expect(toastSuccessMock).not.toHaveBeenCalled();
- });
-
- it("Dismiss calls cancelQuestionAction and shows the info toast", async () => {
- cancelMock.mockResolvedValue({ ok: true });
- render(
- <QuestionCard
- question={makeQuestion()}
- options={["Google Ads"]}
- />,
- );
- fireEvent.click(screen.getByRole("button", { name: /Dismiss/ }));
- await waitFor(() => {
- expect(cancelMock).toHaveBeenCalledWith("q-1");
- expect(toastInfoMock).toHaveBeenCalled();
- });
- });
-
- it("renders a free-text only mode when no options are supplied", () => {
- render(
- <QuestionCard
- question={makeQuestion({ options_json: "[]" })}
- options={[]}
- />,
- );
- expect(screen.queryAllByRole("radio")).toHaveLength(0);
- expect(screen.getByPlaceholderText(/Type your answer/)).toBeInTheDocument();
- });
-});
-
-describe("QuestionCard — resolved state", () => {
- it("renders the chosen option + free-text on an answered row", () => {
- render(
- <QuestionCard
- question={makeQuestion({
- status: "answered",
- answer_option_index: 1,
- answer_text: "with $200/day cap",
- resolved_by_kind: "user",
- resolved_at: new Date().toISOString(),
- })}
- options={["Google Ads", "Meta"]}
- />,
- );
- expect(screen.getByText("Answered")).toBeInTheDocument();
- expect(screen.getByText("Meta")).toBeInTheDocument();
- expect(screen.getByText("with $200/day cap")).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: /send answer/i })).not.toBeInTheDocument();
- });
-
- it("renders 'Dismissed without answer.' on a cancelled row", () => {
- render(
- <QuestionCard
- question={makeQuestion({
- status: "cancelled",
- resolved_by_kind: "user",
- resolved_at: new Date().toISOString(),
- })}
- options={["Google Ads"]}
- />,
- );
- expect(screen.getByText("Dismissed")).toBeInTheDocument();
- expect(screen.getByText(/Dismissed without answer/)).toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/question-card.tsx b/notfair-cmo/src/components/question-card.tsx
deleted file mode 100644
index 26af85f5..00000000
--- a/notfair-cmo/src/components/question-card.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-"use client";
-
-import { useState, useTransition } from "react";
-import { MessageSquareQuote } from "lucide-react";
-import { toast } from "sonner";
-
-import { cn } from "@/lib/utils";
-import {
- answerQuestionAction,
- cancelQuestionAction,
-} from "@/server/actions/questions";
-import type { Question } from "@/types";
-
-function timeAgo(iso: string) {
- const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
- if (seconds < 60) return `${Math.floor(seconds)}s ago`;
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
- return `${Math.floor(seconds / 86400)}d ago`;
-}
-
-export type QuestionCardProps = {
- question: Question;
- /** Options parsed from question.options_json. Empty array = free-text only. */
- options: string[];
-};
-
-/**
- * Renders an open `ask_user_question` row as a structured card above the
- * task transcript. The user can pick one of the agent-provided options
- * AND/OR type a free-text answer. Submit fires answerQuestionAction,
- * which streams a [SYSTEM] wake-up turn to the agent and unblocks the
- * task. Cancel dismisses without delivering — task stays blocked.
- *
- * Mirrors ApprovalCard structurally so the workspace renders a consistent
- * "what does the agent need from me" stack when both card kinds are open.
- */
-export function QuestionCard({ question, options }: QuestionCardProps) {
- const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
- const [text, setText] = useState("");
- const [pending, start] = useTransition();
-
- const actionable = question.status === "pending";
- const canSubmit = actionable && (selectedIndex != null || text.trim().length > 0);
-
- function submit() {
- if (!canSubmit) return;
- start(async () => {
- const r = await answerQuestionAction(question.id, {
- option_index: selectedIndex,
- text: text.trim() || null,
- });
- if (!r.ok) {
- toast.error(r.error ?? "Failed to send answer");
- return;
- }
- toast.success("Sent — agent is being notified");
- // No local reset: the server action revalidates and the next render
- // shows the row with status='answered' (or it disappears from the
- // open list, depending on the wrapping component).
- });
- }
-
- function dismiss() {
- start(async () => {
- const r = await cancelQuestionAction(question.id);
- if (!r.ok) {
- toast.error(r.error ?? "Failed to dismiss");
- return;
- }
- toast.info(
- "Question dismissed. The task stays blocked until the agent or user takes another step.",
- );
- });
- }
-
- return (
- <article
- className="ns-card"
- role="region"
- aria-label={question.prompt}
- data-status={question.status}
- >
- <div className="space-y-3 p-[18px]">
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="ns-tag inline-flex items-center gap-1">
- <MessageSquareQuote className="size-3" />
- Question
- </span>
- <span className={actionable ? "ns-tag-accent" : "ns-tag"}>
- {actionable
- ? "Needs answer"
- : question.status === "answered"
- ? "Answered"
- : "Dismissed"}
- </span>
- </div>
- <p className="m-0 whitespace-pre-wrap text-[14.5px] font-medium leading-snug text-[hsl(var(--notfair-ink))]">
- {question.prompt}
- </p>
- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
- Agent <span className="font-mono">{question.agent_id}</span> ·{" "}
- {timeAgo(question.created_at)}
- </p>
-
- {!actionable && (
- <ResolvedAnswer question={question} options={options} />
- )}
-
- {actionable && (
- <div className="space-y-3 pt-1">
- {options.length > 0 && (
- <div
- className="grid gap-2"
- role="radiogroup"
- aria-label="Suggested answers"
- >
- {options.map((opt, idx) => {
- const selected = idx === selectedIndex;
- return (
- <button
- key={`${opt}-${idx}`}
- type="button"
- role="radio"
- aria-checked={selected}
- onClick={() =>
- setSelectedIndex((cur) => (cur === idx ? null : idx))
- }
- disabled={pending}
- className={cn(
- "w-full rounded-lg border px-3 py-2.5 text-left text-[13.5px] transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent-border))] disabled:cursor-not-allowed disabled:opacity-50",
- selected
- ? "border-[hsl(var(--notfair-accent-border))] bg-[hsl(var(--notfair-accent-soft))] text-[hsl(var(--notfair-ink))]"
- : "border-border bg-card hover:border-[hsl(var(--notfair-accent-border))] hover:bg-[hsl(var(--notfair-accent-soft))]/40",
- )}
- >
- {opt}
- </button>
- );
- })}
- </div>
- )}
-
- <div className="space-y-1.5">
- <label
- htmlFor={`q-${question.id}-text`}
- className="text-[11px] font-semibold uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]"
- >
- {options.length > 0 ? "Or add a comment" : "Your answer"}
- </label>
- <textarea
- id={`q-${question.id}-text`}
- value={text}
- onChange={(e) => setText(e.target.value)}
- rows={3}
- placeholder={
- options.length > 0
- ? "Optional — add nuance to the option you picked, or answer free-form."
- : "Type your answer…"
- }
- disabled={pending}
- className="w-full resize-y rounded-lg border border-input bg-transparent px-3 py-2 text-[13.5px] shadow-sm outline-none placeholder:text-muted-foreground focus-visible:border-[hsl(var(--notfair-accent-border))] focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent-border))] disabled:cursor-not-allowed disabled:opacity-50"
- />
- </div>
-
- <div className="flex flex-wrap gap-2">
- <button
- type="button"
- onClick={submit}
- disabled={pending || !canSubmit}
- className="ns-btn ns-btn-primary ns-btn-sm"
- >
- Send answer
- </button>
- <button
- type="button"
- onClick={dismiss}
- disabled={pending}
- className="ns-btn ns-btn-outline ns-btn-sm"
- >
- Dismiss
- </button>
- </div>
- </div>
- )}
- </div>
- </article>
- );
-}
-
-function ResolvedAnswer({
- question,
- options,
-}: {
- question: Question;
- options: string[];
-}) {
- if (question.status === "cancelled") {
- return (
- <p className="rounded-lg border border-dashed border-border bg-[hsl(var(--notfair-surface-2))]/60 px-3 py-2 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
- Dismissed without answer.
- </p>
- );
- }
- const chosen =
- question.answer_option_index != null
- ? (options[question.answer_option_index] ?? null)
- : null;
- const text = question.answer_text?.trim() || null;
- return (
- <div className="rounded-lg border border-dashed border-border bg-[hsl(var(--notfair-surface-2))]/60 p-3 text-[12.5px]">
- <div className="text-[10.5px] font-semibold uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">
- Answer
- </div>
- {chosen && (
- <p className="mt-1 font-medium leading-relaxed text-[hsl(var(--notfair-ink-2))]">
- {chosen}
- </p>
- )}
- {text && (
- <p
- className={cn(
- "whitespace-pre-wrap leading-relaxed",
- chosen
- ? "mt-1 text-[hsl(var(--notfair-ink-4))]"
- : "mt-1 text-[hsl(var(--notfair-ink-2))]",
- )}
- >
- {text}
- </p>
- )}
- {!chosen && !text && (
- <p className="mt-1 italic text-[hsl(var(--notfair-ink-4))]">
- (empty answer)
- </p>
- )}
- </div>
- );
-}
diff --git a/notfair-cmo/src/components/reprovision-button.test.tsx b/notfair-cmo/src/components/reprovision-button.test.tsx
deleted file mode 100644
index 2a146e64..00000000
--- a/notfair-cmo/src/components/reprovision-button.test.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-const { toastFns } = vi.hoisted(() => ({
- toastFns: {
- success: vi.fn(),
- error: vi.fn(),
- },
-}));
-
-vi.mock("sonner", () => ({
- toast: toastFns,
-}));
-
-import { ReprovisionButton } from "./reprovision-button";
-
-beforeEach(() => {
- toastFns.success.mockReset();
- toastFns.error.mockReset();
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("ReprovisionButton", () => {
- it("renders the idle label by default", () => {
- const action = vi.fn();
- render(<ReprovisionButton action={action} />);
- expect(
- screen.getByRole("button", { name: /reprovision agents/i }),
- ).toBeInTheDocument();
- expect(screen.queryByText(/provisioning/i)).not.toBeInTheDocument();
- });
-
- it("toasts a success message when new agents are provisioned", async () => {
- const action = vi.fn().mockResolvedValue({
- ok: true,
- created: ["cmo", "google_ads"],
- existed: [],
- });
- render(<ReprovisionButton action={action} />);
- fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));
- await waitFor(() =>
- expect(toastFns.success).toHaveBeenCalledWith("Provisioned 2 new agents."),
- );
- expect(toastFns.error).not.toHaveBeenCalled();
- });
-
- it("uses singular agent in success copy when exactly one is created", async () => {
- const action = vi.fn().mockResolvedValue({
- ok: true,
- created: ["cmo"],
- existed: [],
- });
- render(<ReprovisionButton action={action} />);
- fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));
- await waitFor(() =>
- expect(toastFns.success).toHaveBeenCalledWith("Provisioned 1 new agent."),
- );
- });
-
- it("toasts a no-op message when all agents already exist", async () => {
- const action = vi.fn().mockResolvedValue({
- ok: true,
- created: [],
- existed: ["cmo", "google_ads"],
- });
- render(<ReprovisionButton action={action} />);
- fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));
- await waitFor(() =>
- expect(toastFns.success).toHaveBeenCalledWith("All 2 agents already exist."),
- );
- });
-
- it("toasts the server error when action returns ok=false", async () => {
- const action = vi
- .fn()
- .mockResolvedValue({ ok: false, error: "openclaw exploded" });
- render(<ReprovisionButton action={action} />);
- fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));
- await waitFor(() =>
- expect(toastFns.error).toHaveBeenCalledWith("openclaw exploded"),
- );
- expect(toastFns.success).not.toHaveBeenCalled();
- });
-
- it("disables the button and swaps the label while the transition is pending", async () => {
- let resolveAction: (v: { ok: true; created: string[]; existed: string[] }) => void = () => {};
- const action = vi.fn(
- () =>
- new Promise<{ ok: true; created: string[]; existed: string[] }>((resolve) => {
- resolveAction = resolve;
- }),
- );
- render(<ReprovisionButton action={action} />);
- const button = screen.getByRole("button", { name: /reprovision agents/i });
- fireEvent.click(button);
- await waitFor(() => {
- expect(
- screen.getByRole("button", { name: /provisioning/i }),
- ).toBeDisabled();
- });
- resolveAction({ ok: true, created: [], existed: [] });
- await waitFor(() =>
- expect(
- screen.getByRole("button", { name: /reprovision agents/i }),
- ).not.toBeDisabled(),
- );
- });
-});
diff --git a/notfair-cmo/src/components/running-dot.test.tsx b/notfair-cmo/src/components/running-dot.test.tsx
deleted file mode 100644
index 3bc5ac61..00000000
--- a/notfair-cmo/src/components/running-dot.test.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, describe, it, expect } from "vitest";
-import { cleanup, render, screen } from "@testing-library/react";
-
-import { RunningDot } from "./running-dot";
-
-afterEach(() => cleanup());
-
-describe("RunningDot", () => {
- it("renders a status role with the default 'Running' aria-label", () => {
- render(<RunningDot />);
- const status = screen.getByRole("status");
- expect(status).toBeInTheDocument();
- expect(status).toHaveAccessibleName("Running");
- });
-
- it("uses the small sizing class by default", () => {
- render(<RunningDot />);
- const status = screen.getByRole("status");
- expect(status.className).toMatch(/\bh-2\b/);
- expect(status.className).toMatch(/\bw-2\b/);
- expect(status.className).not.toMatch(/h-2\.5/);
- });
-
- it("uses the larger sizing class when size='md'", () => {
- render(<RunningDot size="md" />);
- const status = screen.getByRole("status");
- expect(status.className).toMatch(/h-2\.5/);
- expect(status.className).toMatch(/w-2\.5/);
- });
-
- it("forwards a caller-supplied className alongside the size classes", () => {
- render(<RunningDot className="extra-thing" />);
- const status = screen.getByRole("status");
- expect(status.className).toMatch(/extra-thing/);
- expect(status.className).toMatch(/inline-flex/);
- });
-
- it("overrides the aria-label when one is supplied", () => {
- render(<RunningDot aria-label="Task in flight" />);
- expect(screen.getByRole("status")).toHaveAccessibleName("Task in flight");
- });
-
- it("includes the pulsing ping layer underneath the solid dot", () => {
- const { container } = render(<RunningDot />);
- const inner = container.querySelectorAll("span span");
- expect(inner.length).toBe(2);
- const [ping, solid] = inner;
- expect(ping.className).toMatch(/animate-ping/);
- expect(ping.className).toMatch(/bg-sky-400/);
- expect(solid.className).toMatch(/bg-sky-500/);
- });
-});
diff --git a/notfair-cmo/src/components/schedule-cron-dialog.test.tsx b/notfair-cmo/src/components/schedule-cron-dialog.test.tsx
deleted file mode 100644
index c19d7c06..00000000
--- a/notfair-cmo/src/components/schedule-cron-dialog.test.tsx
+++ /dev/null
@@ -1,208 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
-
-if (typeof Element !== "undefined") {
- // jsdom shims — newer @types/jsdom now declares these on Element, so
- // @ts-expect-error would be flagged unused. The ??= is harmless if the
- // prototype already has them.
- Element.prototype.hasPointerCapture ??= () => false;
- Element.prototype.setPointerCapture ??= () => {};
- Element.prototype.releasePointerCapture ??= () => {};
- Element.prototype.scrollIntoView ??= () => {};
-}
-
-const scheduleCronAction = vi.fn();
-const toast = {
- success: vi.fn(),
- error: vi.fn(),
-};
-
-vi.mock("@/server/actions/crons", () => ({
- scheduleCronAction: (...args: unknown[]) => scheduleCronAction(...args),
-}));
-
-vi.mock("sonner", () => ({
- toast: {
- success: (...args: unknown[]) => toast.success(...args),
- error: (...args: unknown[]) => toast.error(...args),
- },
-}));
-
-import { ScheduleCronDialog } from "./schedule-cron-dialog";
-
-function openDialog() {
- const trigger = screen.getAllByRole("button").find((b) => b.textContent?.includes("New cron"));
- if (!trigger) throw new Error("Trigger not found");
- fireEvent.pointerDown(trigger, { button: 0 });
- fireEvent.click(trigger);
-}
-
-beforeEach(() => {
- scheduleCronAction.mockReset();
- toast.success.mockReset();
- toast.error.mockReset();
-});
-
-afterEach(() => cleanup());
-
-describe("ScheduleCronDialog", () => {
- it("renders the default 'button' trigger with 'New cron' label", () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- expect(screen.getByRole("button", { name: /new cron/i })).toBeInTheDocument();
- });
-
- it("renders an icon trigger with sr-only label when variant='icon'", () => {
- render(<ScheduleCronDialog projectSlug="acme" variant="icon" />);
- expect(screen.getByText(/schedule recurring work/i)).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "New cron" })).not.toBeInTheDocument();
- });
-
- it("opens the dialog when the trigger is clicked", async () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- await waitFor(() => {
- expect(screen.getByText("Schedule recurring work")).toBeInTheDocument();
- });
- expect(screen.getByLabelText(/Agent/i)).toBeInTheDocument();
- expect(screen.getByLabelText(/Name/i)).toBeInTheDocument();
- expect(screen.getByLabelText(/Brief/i)).toBeInTheDocument();
- });
-
- it("defaults the specialist to google_ads when no override is provided", async () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- const select = (await screen.findByLabelText(/Agent/i)) as HTMLSelectElement;
- expect(select.value).toBe("google_ads");
- });
-
- it("honors defaultSpecialist", async () => {
- render(<ScheduleCronDialog projectSlug="acme" defaultSpecialist="seo" />);
- openDialog();
- const select = (await screen.findByLabelText(/Agent/i)) as HTMLSelectElement;
- expect(select.value).toBe("seo");
- });
-
- it("defaults schedule to '0 9 * * *' with timezone visible", async () => {
- // Crons was simplified in 0.3.0 to a single `cron` kind — there's no
- // longer an "every"/"cron" mode select and the timezone input is
- // always visible. Default value matches the placeholder copy.
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- const scheduleInput = (await screen.findByPlaceholderText("0 9 * * *")) as HTMLInputElement;
- expect(scheduleInput.value).toBe("0 9 * * *");
- expect(screen.getByPlaceholderText(/Timezone/i)).toBeInTheDocument();
- });
-
- it("defaults timezone to America/Los_Angeles", async () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- const tzInput = (await screen.findByPlaceholderText(/Timezone/i)) as HTMLInputElement;
- expect(tzInput.value).toBe("America/Los_Angeles");
- });
-
- it("disables the Schedule button until name and brief are filled", async () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- const submit = await screen.findByRole("button", { name: /^schedule$/i });
- expect(submit).toBeDisabled();
- fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: "daily-opt" } });
- expect(submit).toBeDisabled();
- fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "do the thing" } });
- expect(submit).not.toBeDisabled();
- });
-
- it("treats whitespace-only name and brief as empty (still disabled)", async () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: " " } });
- fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: " " } });
- const submit = await screen.findByRole("button", { name: /^schedule$/i });
- expect(submit).toBeDisabled();
- });
-
- it("submits with the default cron schedule and toasts success on ok", async () => {
- scheduleCronAction.mockResolvedValue({ ok: true, cron_id: "c1", cron_name: "acme-google_ads-daily-opt" });
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- fireEvent.change(await screen.findByLabelText(/Name/i), { target: { value: "daily-opt" } });
- fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "do the thing" } });
- fireEvent.click(screen.getByRole("button", { name: /^schedule$/i }));
- await waitFor(() =>
- expect(scheduleCronAction).toHaveBeenCalledWith({
- project_slug: "acme",
- specialist: "google_ads",
- name: "daily-opt",
- schedule_kind: "cron",
- schedule_value: "0 9 * * *",
- tz: "America/Los_Angeles",
- brief: "do the thing",
- }),
- );
- await waitFor(() =>
- expect(toast.success).toHaveBeenCalledWith("Scheduled acme-google_ads-daily-opt"),
- );
- });
-
- it("submits with an edited schedule value and timezone", async () => {
- scheduleCronAction.mockResolvedValue({ ok: true, cron_id: "c1", cron_name: "x" });
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- fireEvent.change(await screen.findByLabelText(/Name/i), { target: { value: "cron-job" } });
- fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "tick" } });
- fireEvent.change(screen.getByPlaceholderText("0 9 * * *"), {
- target: { value: "*/15 * * * *" },
- });
- fireEvent.change(screen.getByPlaceholderText(/Timezone/i), {
- target: { value: "America/New_York" },
- });
- fireEvent.click(screen.getByRole("button", { name: /^schedule$/i }));
- await waitFor(() =>
- expect(scheduleCronAction).toHaveBeenCalledWith(
- expect.objectContaining({
- schedule_kind: "cron",
- schedule_value: "*/15 * * * *",
- tz: "America/New_York",
- }),
- ),
- );
- });
-
- it("toasts the server error when the action returns ok=false and keeps the dialog open", async () => {
- scheduleCronAction.mockResolvedValue({ ok: false, error: "invalid cron" });
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- fireEvent.change(await screen.findByLabelText(/Name/i), { target: { value: "x" } });
- fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "y" } });
- fireEvent.click(screen.getByRole("button", { name: /^schedule$/i }));
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("invalid cron"));
- expect(toast.success).not.toHaveBeenCalled();
- // Dialog still visible
- expect(screen.getByText("Schedule recurring work")).toBeInTheDocument();
- });
-
- it("Cancel button closes the dialog without invoking the action", async () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- fireEvent.click(await screen.findByRole("button", { name: /cancel/i }));
- expect(scheduleCronAction).not.toHaveBeenCalled();
- await waitFor(() =>
- expect(screen.queryByText("Schedule recurring work")).not.toBeInTheDocument(),
- );
- });
-
- it("preset menu items apply their schedule value and timezone", async () => {
- render(<ScheduleCronDialog projectSlug="acme" />);
- openDialog();
- const presetsBtn = await screen.findByRole("button", { name: /presets/i });
- fireEvent.pointerDown(presetsBtn, { button: 0 });
- fireEvent.click(presetsBtn);
- // Pick a non-default preset so the assertion catches the actual write
- // (the default schedule value is already "0 9 * * *", so picking the
- // identically-named preset would pass trivially).
- const preset = await screen.findByText("Every 15 minutes");
- fireEvent.click(preset);
- expect(screen.getByDisplayValue("*/15 * * * *")).toBeInTheDocument();
- expect(screen.getByDisplayValue("America/Los_Angeles")).toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/schedule-cron-dialog.tsx b/notfair-cmo/src/components/schedule-cron-dialog.tsx
deleted file mode 100644
index 4c166ddb..00000000
--- a/notfair-cmo/src/components/schedule-cron-dialog.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-"use client";
-
-import { useState, useTransition } from "react";
-import { Plus, Loader2 } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { ChevronDown } from "lucide-react";
-import { scheduleCronAction } from "@/server/actions/crons";
-import { toast } from "sonner";
-
-type Specialist = "cmo" | "google_ads" | "seo";
-
-const SPECIALIST_LABEL: Record<Specialist, string> = {
- cmo: "CMO",
- google_ads: "Google Ads",
- seo: "SEO",
-};
-
-type Props = {
- projectSlug: string;
- defaultSpecialist?: Specialist;
- variant?: "button" | "icon";
-};
-
-const PRESET_SCHEDULES: Array<{ label: string; value: string; tz?: string }> = [
- { label: "Every hour", value: "0 * * * *", tz: "America/Los_Angeles" },
- { label: "Every 15 minutes", value: "*/15 * * * *", tz: "America/Los_Angeles" },
- { label: "Daily at 9am (Los Angeles)", value: "0 9 * * *", tz: "America/Los_Angeles" },
- { label: "Weekdays at 8am (Los Angeles)", value: "0 8 * * 1-5", tz: "America/Los_Angeles" },
- { label: "Mondays at 6am (Los Angeles)", value: "0 6 * * 1", tz: "America/Los_Angeles" },
-];
-
-export function ScheduleCronDialog({ projectSlug, defaultSpecialist, variant = "button" }: Props) {
- const [open, setOpen] = useState(false);
- const [specialist, setSpecialist] = useState<Specialist>(defaultSpecialist ?? "google_ads");
- const [name, setName] = useState("");
- const [scheduleValue, setScheduleValue] = useState("0 9 * * *");
- const [tz, setTz] = useState("America/Los_Angeles");
- const [brief, setBrief] = useState("");
- const [pending, start] = useTransition();
-
- function reset() {
- setName("");
- setBrief("");
- setScheduleValue("0 9 * * *");
- }
-
- function pickPreset(p: (typeof PRESET_SCHEDULES)[number]) {
- setScheduleValue(p.value);
- if (p.tz) setTz(p.tz);
- }
-
- function submit() {
- start(async () => {
- const result = await scheduleCronAction({
- project_slug: projectSlug,
- specialist,
- name,
- schedule_kind: "cron",
- schedule_value: scheduleValue,
- tz,
- brief,
- });
- if (!result.ok) {
- toast.error(result.error);
- return;
- }
- toast.success(`Scheduled ${result.cron_name}`);
- reset();
- setOpen(false);
- });
- }
-
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild>
- {variant === "icon" ? (
- <button
- type="button"
- className="ns-btn ns-btn-outline ns-btn-sm"
- >
- <Plus className="size-4" />
- <span className="sr-only">Schedule recurring work</span>
- </button>
- ) : (
- <button type="button" className="ns-btn ns-btn-primary">
- <Plus className="size-4" />
- New cron
- </button>
- )}
- </DialogTrigger>
- <DialogContent className="max-w-lg">
- <DialogHeader>
- <DialogTitle>Schedule recurring work</DialogTitle>
- <DialogDescription>
- Creates a scheduled job under this workspace. The brief is the message the
- agent will receive on each tick.
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4">
- <div className="grid gap-2">
- <Label htmlFor="specialist">Agent</Label>
- <select
- id="specialist"
- value={specialist}
- onChange={(e) => setSpecialist(e.target.value as Specialist)}
- className="h-9 rounded-md border bg-background px-3 text-sm"
- disabled={pending}
- >
- {(Object.keys(SPECIALIST_LABEL) as Specialist[]).map((s) => (
- <option key={s} value={s}>
- {SPECIALIST_LABEL[s]}
- </option>
- ))}
- </select>
- </div>
-
- <div className="grid gap-2">
- <Label htmlFor="cron-name">Name</Label>
- <Input
- id="cron-name"
- placeholder="daily-bid-opt"
- value={name}
- onChange={(e) => setName(e.target.value)}
- disabled={pending}
- maxLength={64}
- />
- <p className="text-[11px] text-muted-foreground">
- Kebab-case. Becomes the scheduled job's display name.
- </p>
- </div>
-
- <div className="grid gap-2">
- <div className="flex items-center justify-between">
- <Label htmlFor="schedule">Schedule</Label>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-7 text-xs" disabled={pending}>
- Presets <ChevronDown className="ml-1 size-3" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-64">
- {PRESET_SCHEDULES.map((p) => (
- <DropdownMenuItem key={p.label} onSelect={() => pickPreset(p)}>
- {p.label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- <Input
- id="schedule"
- placeholder="0 9 * * *"
- value={scheduleValue}
- onChange={(e) => setScheduleValue(e.target.value)}
- disabled={pending}
- className="font-mono text-sm"
- />
- <Input
- placeholder="Timezone (IANA)"
- value={tz}
- onChange={(e) => setTz(e.target.value)}
- disabled={pending}
- className="font-mono text-sm"
- />
- </div>
-
- <div className="grid gap-2">
- <Label htmlFor="brief">Brief</Label>
- <textarea
- id="brief"
- placeholder="RUN: review yesterday's campaign performance and propose bid adjustments."
- value={brief}
- onChange={(e) => setBrief(e.target.value)}
- disabled={pending}
- rows={3}
- className="min-h-[80px] resize-none rounded-md border bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
- />
- </div>
- </div>
-
- <DialogFooter>
- <Button variant="outline" onClick={() => setOpen(false)} disabled={pending}>
- Cancel
- </Button>
- <Button onClick={submit} disabled={pending || !name.trim() || !brief.trim()}>
- {pending && <Loader2 className="mr-1.5 size-4 animate-spin" />}
- {pending ? "Scheduling..." : "Schedule"}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/notfair-cmo/src/components/sidebar-version.test.tsx b/notfair-cmo/src/components/sidebar-version.test.tsx
deleted file mode 100644
index 04891aee..00000000
--- a/notfair-cmo/src/components/sidebar-version.test.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-
-import { SidebarVersion } from "./sidebar-version";
-
-vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: vi.fn() },
-}));
-
-const originalFetch = globalThis.fetch;
-
-function mockFetch(handler: (url: string, init?: RequestInit) => unknown) {
- globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- const url =
- typeof input === "string"
- ? input
- : input instanceof URL
- ? input.toString()
- : input.url;
- const value = handler(url, init);
- return new Response(JSON.stringify(value), {
- status: typeof value === "object" && value && "__status" in value
- ? (value as { __status: number }).__status
- : 200,
- headers: { "content-type": "application/json" },
- });
- }) as typeof fetch;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- globalThis.fetch = originalFetch;
-});
-
-describe("SidebarVersion", () => {
- it("renders just the version when no update is available", async () => {
- mockFetch(() => ({ current: "0.7.0", latest: "0.7.0", has_update: false }));
- render(<SidebarVersion />);
- await waitFor(() =>
- expect(screen.getByText(/notfair-cmo v0\.7\.0/)).toBeInTheDocument(),
- );
- expect(screen.queryByRole("button")).not.toBeInTheDocument();
- });
-
- it("shows the Update button when has_update=true", async () => {
- mockFetch(() => ({ current: "0.7.0", latest: "0.8.1", has_update: true }));
- render(<SidebarVersion />);
- await waitFor(() =>
- expect(screen.getByRole("button", { name: /v0\.8\.1 available/ })).toBeInTheDocument(),
- );
- });
-
- it("POSTs /api/upgrade on click and shows 'Restart to apply' on success", async () => {
- const fetchSpy = vi.fn(
- async (input: RequestInfo | URL, _init?: RequestInit): Promise<Response> => {
- const url =
- typeof input === "string"
- ? input
- : input instanceof URL
- ? input.toString()
- : input.url;
- if (url.endsWith("/api/version")) {
- return new Response(
- JSON.stringify({ current: "0.7.0", latest: "0.8.0", has_update: true }),
- { status: 200 },
- );
- }
- if (url.endsWith("/api/upgrade")) {
- return new Response(JSON.stringify({ ok: true, note: "Upgraded." }), {
- status: 200,
- });
- }
- return new Response("{}", { status: 200 });
- },
- );
- globalThis.fetch = fetchSpy as typeof fetch;
-
- render(<SidebarVersion />);
- const btn = await screen.findByRole("button", { name: /v0\.8\.0 available/ });
- fireEvent.click(btn);
-
- await waitFor(() => expect(screen.getByText(/Restart to apply/)).toBeInTheDocument());
- const upgradeCall = fetchSpy.mock.calls.find(([u]) => String(u).endsWith("/api/upgrade"));
- expect(upgradeCall).toBeDefined();
- expect(upgradeCall![1]!.method).toBe("POST");
- });
-
- it("keeps the Upgrade button enabled when the API errors (so the user can retry)", async () => {
- const fetchSpy = vi.fn(async (input: RequestInfo | URL) => {
- const url =
- typeof input === "string"
- ? input
- : input instanceof URL
- ? input.toString()
- : input.url;
- if (url.endsWith("/api/version")) {
- return new Response(
- JSON.stringify({ current: "0.7.0", latest: "0.8.0", has_update: true }),
- { status: 200 },
- );
- }
- return new Response(
- JSON.stringify({ ok: false, error: "npm not on PATH", command: "npm i -g notfair-cmo@latest" }),
- { status: 500 },
- );
- });
- globalThis.fetch = fetchSpy as typeof fetch;
-
- render(<SidebarVersion />);
- const btn = await screen.findByRole("button", { name: /v0\.8\.0 available/ });
- fireEvent.click(btn);
-
- // After the failed upgrade, the button label resets and stays clickable.
- await waitFor(() =>
- expect(screen.getByRole("button", { name: /v0\.8\.0 available/ })).not.toBeDisabled(),
- );
- });
-
- it("falls back to a minimal label when /api/version is unreachable", async () => {
- globalThis.fetch = vi.fn(async () => {
- throw new Error("offline");
- }) as typeof fetch;
- render(<SidebarVersion />);
- // Initial render shows the fallback before fetch resolves; offline keeps it.
- await waitFor(() =>
- expect(screen.getByText(/notfair-cmo/)).toBeInTheDocument(),
- );
- expect(screen.queryByRole("button")).not.toBeInTheDocument();
- });
-});
diff --git a/notfair-cmo/src/components/skills-list.tsx b/notfair-cmo/src/components/skills-list.tsx
deleted file mode 100644
index 72b2694b..00000000
--- a/notfair-cmo/src/components/skills-list.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { Sparkles } from "lucide-react";
-import type { SkillEntry } from "@/server/agents/skills";
-
-type Props = {
- skills: SkillEntry[];
-};
-
-export function SkillsList({ skills }: Props) {
- if (skills.length === 0) {
- return (
- <div className="ns-empty">
- <p className="ns-empty-title">No skills installed.</p>
- <p className="ns-empty-sub">
- Skills are reusable capabilities the agent picks up from this
- workspace. Install one to extend what this agent can do.
- </p>
- </div>
- );
- }
- return (
- <ol className="ns-group">
- {skills.map((s) => (
- <li key={s.key} className="ns-row">
- <span className="ns-glyph ns-glyph-sm" aria-hidden>
- <Sparkles className="size-[14px] text-[hsl(var(--notfair-ink-2))]" />
- </span>
- <div className="ns-row-body">
- <div className="ns-row-title-row">
- <span className="ns-row-title font-mono">{s.name}</span>
- <span className="ns-tag">{s.scope}</span>
- </div>
- {s.description && (
- <p className="ns-row-desc">{s.description}</p>
- )}
- {s.source && (
- <p className="mt-1 truncate font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">
- {s.source}
- </p>
- )}
- </div>
- </li>
- ))}
- </ol>
- );
-}
diff --git a/notfair-cmo/src/components/slash-command-popover.test.tsx b/notfair-cmo/src/components/slash-command-popover.test.tsx
deleted file mode 100644
index 34394fb3..00000000
--- a/notfair-cmo/src/components/slash-command-popover.test.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent } from "@testing-library/react";
-
-import { SlashCommandPopover } from "./slash-command-popover";
-import {
- SLASH_COMMANDS,
- filterSlashCommands,
- type SlashCommand,
-} from "@/lib/slash-commands";
-
-// jsdom doesn't implement scrollIntoView; the popover calls it on every render.
-beforeEach(() => {
- Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
- configurable: true,
- writable: true,
- value: vi.fn(),
- });
-});
-
-describe("SlashCommandPopover", () => {
- it("renders the empty state when no commands match", () => {
- render(
- <SlashCommandPopover
- commands={[]}
- selectedIndex={0}
- onSelect={() => {}}
- onHover={() => {}}
- />,
- );
- expect(screen.getByText("No matching slash commands.")).toBeInTheDocument();
- // Empty-state container is still a listbox.
- const empty = screen.getByRole("listbox", { name: "Slash commands" });
- expect(empty).toBeInTheDocument();
- });
-
- it("renders every command name with category label", () => {
- render(
- <SlashCommandPopover
- commands={SLASH_COMMANDS}
- selectedIndex={0}
- onSelect={() => {}}
- onHover={() => {}}
- />,
- );
- expect(screen.getByRole("listbox", { name: "Slash commands" })).toBeInTheDocument();
- // Each command shows up as an option with its `/name` displayed.
- for (const cmd of SLASH_COMMANDS) {
- const matches = screen.getAllByText((_, node) => {
- if (!node) return false;
- return node.tagName === "SPAN" && node.textContent?.startsWith(`/${cmd.name}`) === true;
- });
- expect(matches.length).toBeGreaterThan(0);
- }
- // Category labels are surfaced.
- expect(screen.getAllByText("Session").length).toBeGreaterThan(0);
- expect(screen.getAllByText("Model").length).toBeGreaterThan(0);
- });
-
- it("marks the selected row with aria-selected and styles it active", () => {
- render(
- <SlashCommandPopover
- commands={SLASH_COMMANDS.slice(0, 3)}
- selectedIndex={1}
- onSelect={() => {}}
- onHover={() => {}}
- />,
- );
- const options = screen.getAllByRole("option");
- expect(options).toHaveLength(3);
- expect(options[0]).toHaveAttribute("aria-selected", "false");
- expect(options[1]).toHaveAttribute("aria-selected", "true");
- expect(options[1].className).toContain("bg-accent");
- });
-
- it("calls onSelect with the clicked command", () => {
- const onSelect = vi.fn();
- const subset: SlashCommand[] = SLASH_COMMANDS.slice(0, 2);
- render(
- <SlashCommandPopover
- commands={subset}
- selectedIndex={0}
- onSelect={onSelect}
- onHover={() => {}}
- />,
- );
- fireEvent.click(screen.getAllByRole("option")[1]);
- expect(onSelect).toHaveBeenCalledTimes(1);
- expect(onSelect).toHaveBeenCalledWith(subset[1]);
- });
-
- it("calls onHover with the row index on mouse enter", () => {
- const onHover = vi.fn();
- render(
- <SlashCommandPopover
- commands={SLASH_COMMANDS.slice(0, 3)}
- selectedIndex={0}
- onSelect={() => {}}
- onHover={onHover}
- />,
- );
- fireEvent.mouseEnter(screen.getAllByRole("option")[2]);
- expect(onHover).toHaveBeenCalledWith(2);
- });
-
- it("renders a 'local' badge on every command — the catalog is all-local now", () => {
- render(
- <SlashCommandPopover
- commands={SLASH_COMMANDS}
- selectedIndex={0}
- onSelect={() => {}}
- onHover={() => {}}
- />,
- );
- const localBadges = screen.getAllByText("local");
- expect(localBadges).toHaveLength(SLASH_COMMANDS.length);
- });
-
- it("shows the args hint next to commands that declare one", () => {
- const withArgs = SLASH_COMMANDS.find((c) => c.args)!;
- render(
- <SlashCommandPopover
- commands={[withArgs]}
- selectedIndex={0}
- onSelect={() => {}}
- onHover={() => {}}
- />,
- );
- expect(screen.getByText(withArgs.args!)).toBeInTheDocument();
- });
-
- it("filterSlashCommands prefix-matches /cl to /clear", () => {
- // Sanity-check on the filter that drives the popover.
- const filtered = filterSlashCommands("/cl");
- expect(filtered.map((c) => c.name)).toContain("clear");
- });
-
- it("filterSlashCommands falls back to substring match", () => {
- const filtered = filterSlashCommands("/ode"); // no prefix; substring "ode" → model
- expect(filtered.map((c) => c.name)).toContain("model");
- });
-
- it("calls scrollIntoView on the selected row after mount", () => {
- const scrollIntoView = vi.fn();
- Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
- configurable: true,
- writable: true,
- value: scrollIntoView,
- });
- render(
- <SlashCommandPopover
- commands={SLASH_COMMANDS.slice(0, 4)}
- selectedIndex={2}
- onSelect={() => {}}
- onHover={() => {}}
- />,
- );
- expect(scrollIntoView).toHaveBeenCalled();
- });
-});
diff --git a/notfair-cmo/src/components/start-all-tasks-button.test.tsx b/notfair-cmo/src/components/start-all-tasks-button.test.tsx
deleted file mode 100644
index 99ba1969..00000000
--- a/notfair-cmo/src/components/start-all-tasks-button.test.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
-
-const refreshMock = vi.fn();
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ refresh: refreshMock }),
-}));
-
-const startAllMock = vi.fn();
-vi.mock("@/server/actions/tasks", () => ({
- startAllProposedTasksAction: (...a: unknown[]) => startAllMock(...a),
-}));
-
-const toastErrorMock = vi.fn();
-const toastSuccessMock = vi.fn();
-const toastInfoMock = vi.fn();
-vi.mock("sonner", () => ({
- toast: {
- error: (...a: unknown[]) => toastErrorMock(...a),
- success: (...a: unknown[]) => toastSuccessMock(...a),
- info: (...a: unknown[]) => toastInfoMock(...a),
- },
-}));
-
-import { StartAllTasksButton } from "./start-all-tasks-button";
-
-beforeEach(() => {
- refreshMock.mockReset();
- startAllMock.mockReset();
- toastErrorMock.mockReset();
- toastSuccessMock.mockReset();
- toastInfoMock.mockReset();
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe("StartAllTasksButton", () => {
- it("renders the count and is disabled when proposedCount is 0", () => {
- render(<StartAllTasksButton agentId="demo-cmo" proposedCount={0} />);
- const btn = screen.getByRole("button");
- expect(btn).toBeDisabled();
- expect(btn.textContent).toContain("Start all 0 tasks");
- });
-
- it("renders singular noun for count == 1", () => {
- render(<StartAllTasksButton agentId="demo-cmo" proposedCount={1} />);
- expect(screen.getByRole("button").textContent).toContain("Start all 1 task");
- expect(screen.getByRole("button").textContent).not.toContain("tasks");
- });
-
- it("renders plural noun for count > 1", () => {
- render(<StartAllTasksButton agentId="demo-cmo" proposedCount={3} />);
- expect(screen.getByRole("button").textContent).toContain("Start all 3 tasks");
- });
-
- it("shows an error toast when the action fails", async () => {
- startAllMock.mockResolvedValue({ ok: false, error: "no project" });
- render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);
- fireEvent.click(screen.getByRole("button"));
- await waitFor(() => {
- expect(toastErrorMock).toHaveBeenCalledWith("no project");
- });
- expect(refreshMock).not.toHaveBeenCalled();
- });
-
- it("shows an info toast and skips polling when started == 0", async () => {
- startAllMock.mockResolvedValue({ ok: true, data: { started: 0, task_ids: [] } });
- render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);
- fireEvent.click(screen.getByRole("button"));
- await waitFor(() => {
- expect(toastInfoMock).toHaveBeenCalledWith("No proposed tasks to start.");
- });
- expect(refreshMock).not.toHaveBeenCalled();
- });
-
- it("toasts singular when only one task was started", async () => {
- startAllMock.mockResolvedValue({ ok: true, data: { started: 1, task_ids: ["t-1"] } });
- render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);
- fireEvent.click(screen.getByRole("button"));
- await waitFor(() => {
- expect(toastSuccessMock).toHaveBeenCalledWith("Started 1 task.");
- });
- });
-
- it("toasts plural and triggers refresh and entries polling on success", async () => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- startAllMock.mockResolvedValue({ ok: true, data: { started: 2, task_ids: ["t-1", "t-2"] } });
- render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);
- fireEvent.click(screen.getByRole("button"));
- await waitFor(() => {
- expect(toastSuccessMock).toHaveBeenCalledWith("Started 2 tasks.");
- });
- // First refresh is the immediate one from the action's success branch.
- expect(refreshMock.mock.calls.length).toBeGreaterThanOrEqual(1);
- // Advance 3s — one polling interval — to trigger another refresh.
- const before = refreshMock.mock.calls.length;
- vi.advanceTimersByTime(3_000);
- expect(refreshMock.mock.calls.length).toBeGreaterThan(before);
- // While polling, the button stays disabled and the label is "Working…".
- await waitFor(() => {
- expect(screen.getByRole("button")).toBeDisabled();
- expect(screen.getByRole("button").textContent).toContain("Working…");
- });
- // After the 2-minute timeout, polling stops and button re-enables.
- vi.advanceTimersByTime(120_000);
- await waitFor(() => {
- expect(screen.getByRole("button")).not.toBeDisabled();
- });
- });
-});
diff --git a/notfair-cmo/src/components/start-all-tasks-button.tsx b/notfair-cmo/src/components/start-all-tasks-button.tsx
deleted file mode 100644
index 063e3150..00000000
--- a/notfair-cmo/src/components/start-all-tasks-button.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-"use client";
-
-import { startTransition as scheduleTransition, useState, useTransition } from "react";
-import { useRouter } from "next/navigation";
-import { Loader2, Play } from "lucide-react";
-import { toast } from "sonner";
-
-import { startAllProposedTasksAction } from "@/server/actions/tasks";
-
-/**
- * Kicks off every proposed task for an agent in one click. Server action
- * marks tasks running and fires background kickoffs; this button then
- * starts a short polling loop (router.refresh every 3s for 2 minutes) so
- * the user sees status flip from proposed → running → succeeded as each
- * agent run finishes, without staring at a stale page.
- */
-export function StartAllTasksButton({
- agentId,
- proposedCount,
-}: {
- agentId: string;
- proposedCount: number;
-}) {
- const router = useRouter();
- const [pending, startTransition] = useTransition();
- const [polling, setPolling] = useState(false);
-
- async function onClick() {
- startTransition(async () => {
- const result = await startAllProposedTasksAction(agentId);
- if (!result.ok) {
- toast.error(result.error);
- return;
- }
- if (result.data.started === 0) {
- toast.info("No proposed tasks to start.");
- return;
- }
- toast.success(
- `Started ${result.data.started} task${result.data.started === 1 ? "" : "s"}.`,
- );
- // Mark every refresh as a transition so React keeps the visible
- // tree alive while the new RSC payload streams in — prevents the
- // sidebar from flickering on each 3-second tick.
- scheduleTransition(() => router.refresh());
- // Poll for ~2 minutes so the page reflects status flips without the
- // user needing to refresh manually. Long enough for most tasks (3 ×
- // 30-60s each) but bounded so we don't burn cycles forever.
- setPolling(true);
- const intervalId = setInterval(
- () => scheduleTransition(() => router.refresh()),
- 3_000,
- );
- const timeoutId = setTimeout(() => {
- clearInterval(intervalId);
- setPolling(false);
- }, 120_000);
- // Belt + suspenders cleanup if component unmounts (rare here).
- void timeoutId;
- });
- }
-
- const disabled = pending || polling || proposedCount === 0;
- const label = polling
- ? "Working…"
- : pending
- ? "Starting…"
- : `Start all ${proposedCount} task${proposedCount === 1 ? "" : "s"}`;
-
- return (
- <button
- type="button"
- onClick={onClick}
- disabled={disabled}
- className="ns-btn ns-btn-primary ns-btn-sm"
- >
- {pending || polling ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <Play className="size-3.5" />
- )}
- {label}
- </button>
- );
-}
diff --git a/notfair-cmo/src/components/tasks-board.tsx b/notfair-cmo/src/components/tasks-board.tsx
deleted file mode 100644
index 8e21153b..00000000
--- a/notfair-cmo/src/components/tasks-board.tsx
+++ /dev/null
@@ -1,663 +0,0 @@
-"use client";
-
-import { useEffect, useMemo, useState } from "react";
-import Link from "next/link";
-import {
- Check,
- Columns3,
- LayoutGrid,
- List as ListIcon,
- Users,
- X,
-} from "lucide-react";
-
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { cn } from "@/lib/utils";
-import { projectHref } from "@/lib/project-href";
-import type { ProjectAgentEntry } from "@/server/agent-meta";
-import type { Task, TaskStatus } from "@/types";
-
-/**
- * /tasks board.
- *
- * Server hands us the full task list + the project's agent roster; this
- * component owns all interaction state — filters, visible status columns,
- * kanban-vs-list perspective — and persists them to localStorage keyed by
- * project slug so each project can have its own layout.
- *
- * Status columns: we show every column the user has enabled (default
- * "working / blocked / done", since those are what's interesting day-to-
- * day). Empty enabled columns still render as placeholders so the layout
- * doesn't jitter as cards move; columns the user disabled simply do not
- * appear in the kanban.
- *
- * Filters: agent multi-select (chips in the toolbar). An empty filter
- * means "all agents". Filter applies in both perspectives.
- *
- * Perspective: kanban (default) is the standard horizontal column layout;
- * list is a compact table-like view sorted by updated_at desc — useful
- * when the user wants a single sorted feed instead of per-column groups.
- */
-
-type Perspective = "kanban" | "list";
-
-type Prefs = {
- columns: TaskStatus[];
- view: Perspective;
- agents: string[]; // agent_ids, empty = show all
-};
-
-const STATUS_ORDER: TaskStatus[] = [
- "proposed",
- "approved",
- "working",
- "blocked",
- "done",
- "failed",
- "cancelled",
-];
-
-const STATUS_LABEL: Record<TaskStatus, string> = {
- proposed: "Proposed",
- approved: "Approved",
- working: "Working",
- blocked: "Blocked",
- done: "Done",
- failed: "Failed",
- cancelled: "Cancelled",
-};
-
-// Small color cues per status. Kept muted — the dot is a 6px circle the
-// eye picks up at a glance; the column header still wears it as a thin
-// left border so the kanban reads at a glance.
-const STATUS_TONE: Record<TaskStatus, string> = {
- proposed: "bg-zinc-400",
- approved: "bg-sky-500",
- working: "bg-amber-500",
- blocked: "bg-rose-500",
- done: "bg-emerald-500",
- failed: "bg-red-700",
- cancelled: "bg-zinc-300",
-};
-
-const DEFAULT_PREFS: Prefs = {
- columns: ["working", "blocked", "done"],
- view: "kanban",
- agents: [],
-};
-
-function prefsKey(projectSlug: string): string {
- return `notfair-cmo:tasks-prefs:${projectSlug}`;
-}
-
-function loadPrefs(projectSlug: string): Prefs {
- if (typeof window === "undefined") return DEFAULT_PREFS;
- try {
- const raw = window.localStorage.getItem(prefsKey(projectSlug));
- if (!raw) return DEFAULT_PREFS;
- const parsed = JSON.parse(raw) as Partial<Prefs>;
- return {
- columns:
- Array.isArray(parsed.columns) && parsed.columns.every(isStatus)
- ? parsed.columns
- : DEFAULT_PREFS.columns,
- view: parsed.view === "list" ? "list" : "kanban",
- agents: Array.isArray(parsed.agents)
- ? parsed.agents.filter((a): a is string => typeof a === "string")
- : [],
- };
- } catch {
- return DEFAULT_PREFS;
- }
-}
-
-function isStatus(v: unknown): v is TaskStatus {
- return typeof v === "string" && STATUS_ORDER.includes(v as TaskStatus);
-}
-
-type Props = {
- projectSlug: string;
- tasks: Task[];
- agents: ProjectAgentEntry[];
-};
-
-export function TasksBoard({ projectSlug, tasks, agents }: Props) {
- const [prefs, setPrefs] = useState<Prefs>(DEFAULT_PREFS);
- // Hydrate from localStorage after mount — server render uses defaults
- // so SSR + first paint stay stable. The brief flash from default →
- // restored prefs is acceptable for an internal dashboard.
- const [hydrated, setHydrated] = useState(false);
- useEffect(() => {
- setPrefs(loadPrefs(projectSlug));
- setHydrated(true);
- }, [projectSlug]);
- // Persist on any change after hydration.
- useEffect(() => {
- if (!hydrated) return;
- try {
- window.localStorage.setItem(prefsKey(projectSlug), JSON.stringify(prefs));
- } catch {
- // Storage full / disabled — fall through, the UI still works.
- }
- }, [hydrated, projectSlug, prefs]);
-
- const agentById = useMemo(() => {
- const m = new Map<string, ProjectAgentEntry>();
- for (const a of agents) m.set(a.agent_id, a);
- return m;
- }, [agents]);
-
- // Apply agent filter (empty = all).
- const filteredTasks = useMemo(() => {
- if (prefs.agents.length === 0) return tasks;
- const set = new Set(prefs.agents);
- return tasks.filter((t) => set.has(t.agent_id));
- }, [tasks, prefs.agents]);
-
- const counts = useMemo(() => {
- const out: Partial<Record<TaskStatus, number>> = {};
- for (const t of filteredTasks) {
- out[t.status] = (out[t.status] ?? 0) + 1;
- }
- return out;
- }, [filteredTasks]);
-
- const visibleColumns = STATUS_ORDER.filter((s) => prefs.columns.includes(s));
-
- // ── Toolbar handlers ────────────────────────────────────────────────
- function toggleColumn(s: TaskStatus) {
- setPrefs((p) =>
- p.columns.includes(s)
- ? { ...p, columns: p.columns.filter((x) => x !== s) }
- : { ...p, columns: [...p.columns, s] },
- );
- }
- function resetColumns() {
- setPrefs((p) => ({ ...p, columns: DEFAULT_PREFS.columns }));
- }
- function toggleAgent(agentId: string) {
- setPrefs((p) =>
- p.agents.includes(agentId)
- ? { ...p, agents: p.agents.filter((a) => a !== agentId) }
- : { ...p, agents: [...p.agents, agentId] },
- );
- }
- function clearAgents() {
- setPrefs((p) => ({ ...p, agents: [] }));
- }
- function setView(view: Perspective) {
- setPrefs((p) => ({ ...p, view }));
- }
-
- // ── Render ──────────────────────────────────────────────────────────
-
- return (
- <div className="space-y-4">
- {/* Toolbar */}
- <div className="flex flex-wrap items-center gap-2 pb-3">
- {/* Agent filter */}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- className="ns-btn ns-btn-outline ns-btn-sm"
- >
- <Users className="size-3.5" />
- {prefs.agents.length === 0
- ? "All agents"
- : prefs.agents.length === 1
- ? agentLabel(agentById, prefs.agents[0])
- : `${prefs.agents.length} agents`}
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="w-56">
- <DropdownMenuLabel className="text-[11px] font-normal text-muted-foreground uppercase tracking-wide">
- Filter by agent
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- {agents.map((a) => {
- const active = prefs.agents.includes(a.agent_id);
- return (
- <DropdownMenuItem
- key={a.agent_id}
- onSelect={(e) => {
- e.preventDefault();
- toggleAgent(a.agent_id);
- }}
- className="flex items-center gap-2 text-xs"
- >
- <span
- aria-hidden
- className={cn(
- "flex size-3.5 shrink-0 items-center justify-center rounded-sm border",
- active
- ? "border-foreground bg-foreground text-background"
- : "border-muted-foreground/40",
- )}
- >
- {active && <Check className="size-2.5" />}
- </span>
- <span className="truncate">{a.name}</span>
- <span className="ml-auto font-mono text-[10px] text-muted-foreground">
- {countForAgent(filteredTasks, tasks, a.agent_id)}
- </span>
- </DropdownMenuItem>
- );
- })}
- {prefs.agents.length > 0 && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={(e) => {
- e.preventDefault();
- clearAgents();
- }}
- className="text-xs text-muted-foreground"
- >
- Clear filter
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
-
- {/* Column visibility */}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- className="ns-btn ns-btn-outline ns-btn-sm"
- >
- <Columns3 className="size-3.5" />
- {prefs.columns.length} columns
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="w-52">
- <DropdownMenuLabel className="text-[11px] font-normal text-muted-foreground uppercase tracking-wide">
- Visible columns
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- {STATUS_ORDER.map((s) => {
- const active = prefs.columns.includes(s);
- return (
- <DropdownMenuItem
- key={s}
- onSelect={(e) => {
- e.preventDefault();
- toggleColumn(s);
- }}
- className="flex items-center gap-2 text-xs"
- >
- <span
- aria-hidden
- className={cn(
- "flex size-3.5 shrink-0 items-center justify-center rounded-sm border",
- active
- ? "border-foreground bg-foreground text-background"
- : "border-muted-foreground/40",
- )}
- >
- {active && <Check className="size-2.5" />}
- </span>
- <span
- aria-hidden
- className={cn("size-1.5 rounded-full", STATUS_TONE[s])}
- />
- <span>{STATUS_LABEL[s]}</span>
- <span className="ml-auto font-mono text-[10px] text-muted-foreground tabular-nums">
- {counts[s] ?? 0}
- </span>
- </DropdownMenuItem>
- );
- })}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={(e) => {
- e.preventDefault();
- resetColumns();
- }}
- className="text-xs text-muted-foreground"
- >
- Reset to defaults
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
-
- <div
- className="ml-auto inline-flex overflow-hidden rounded-full bg-[hsl(var(--notfair-surface-2))] p-0.5"
- >
- <button
- type="button"
- aria-label="Kanban view"
- aria-pressed={prefs.view === "kanban"}
- onClick={() => setView("kanban")}
- className={cn(
- "flex h-7 w-9 items-center justify-center rounded-full transition-colors",
- prefs.view === "kanban"
- ? "bg-card text-foreground shadow-sm"
- : "text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink))]",
- )}
- >
- <LayoutGrid className="size-3.5" />
- </button>
- <button
- type="button"
- aria-label="List view"
- aria-pressed={prefs.view === "list"}
- onClick={() => setView("list")}
- className={cn(
- "flex h-7 w-9 items-center justify-center rounded-full transition-colors",
- prefs.view === "list"
- ? "bg-card text-foreground shadow-sm"
- : "text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink))]",
- )}
- >
- <ListIcon className="size-3.5" />
- </button>
- </div>
- </div>
-
- {/* Active-filter chips (only show when non-default) */}
- {prefs.agents.length > 0 && (
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="text-[11px] uppercase tracking-wide text-muted-foreground">
- Filtered by
- </span>
- {prefs.agents.map((id) => (
- <button
- key={id}
- type="button"
- onClick={() => toggleAgent(id)}
- className="inline-flex items-center gap-1 rounded-full bg-[hsl(var(--notfair-surface-2))] px-2 py-0.5 text-[11px] hover:bg-[hsl(var(--notfair-hover))]"
- >
- {agentLabel(agentById, id)}
- <X className="size-2.5 opacity-60" />
- </button>
- ))}
- </div>
- )}
-
- {/* Body */}
- {tasks.length === 0 ? (
- <div className="ns-empty">
- <p className="ns-empty-title">No tasks yet.</p>
- <p className="ns-empty-sub">
- Ask your CMO to do something in chat to populate this board.
- </p>
- </div>
- ) : filteredTasks.length === 0 ? (
- <div className="ns-empty">
- <p className="ns-empty-title">No tasks match the current filter.</p>
- <button
- type="button"
- onClick={clearAgents}
- className="ns-btn ns-btn-ghost ns-btn-sm mt-3"
- >
- Clear filter
- </button>
- </div>
- ) : prefs.view === "kanban" ? (
- <KanbanView
- projectSlug={projectSlug}
- tasks={filteredTasks}
- visibleColumns={visibleColumns}
- counts={counts}
- agentById={agentById}
- />
- ) : (
- <ListView
- projectSlug={projectSlug}
- tasks={filteredTasks}
- agentById={agentById}
- enabledStatuses={new Set(prefs.columns)}
- />
- )}
- </div>
- );
-}
-
-// ── Kanban ────────────────────────────────────────────────────────────
-
-function KanbanView({
- projectSlug,
- tasks,
- visibleColumns,
- counts,
- agentById,
-}: {
- projectSlug: string;
- tasks: Task[];
- visibleColumns: TaskStatus[];
- counts: Partial<Record<TaskStatus, number>>;
- agentById: Map<string, ProjectAgentEntry>;
-}) {
- if (visibleColumns.length === 0) {
- return (
- <div className="ns-empty">
- <p className="ns-empty-title">No columns selected.</p>
- <p className="ns-empty-sub">
- Open the Columns menu and pick at least one status to display.
- </p>
- </div>
- );
- }
- return (
- <div className="flex gap-3 overflow-x-auto pb-2">
- {visibleColumns.map((status) => {
- const items = tasks.filter((t) => t.status === status);
- return (
- <section
- key={status}
- className="flex w-72 shrink-0 flex-col rounded-[14px] bg-[hsl(var(--notfair-ink)/0.035)]"
- aria-label={`${STATUS_LABEL[status]} column`}
- >
- <header className="flex items-center justify-between px-3 py-2.5">
- <div className="flex items-center gap-2">
- <span
- aria-hidden
- className={cn("size-1.5 rounded-full", STATUS_TONE[status])}
- />
- <h2 className="text-[12px] font-semibold tracking-tight text-[hsl(var(--notfair-ink-2))]">
- {STATUS_LABEL[status]}
- </h2>
- </div>
- <span className="font-mono text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
- {counts[status] ?? 0}
- </span>
- </header>
- <div className="min-h-[120px] flex-1 space-y-2 p-2">
- {items.length === 0 ? (
- <p className="px-2 py-6 text-center text-[11px] text-[hsl(var(--notfair-ink-4))]/70">
- No tasks.
- </p>
- ) : (
- items.map((t) => (
- <TaskCard
- key={t.id}
- task={t}
- projectSlug={projectSlug}
- assignee={agentById.get(t.agent_id)?.name ?? t.agent_id}
- />
- ))
- )}
- </div>
- </section>
- );
- })}
- </div>
- );
-}
-
-function TaskCard({
- task,
- projectSlug,
- assignee,
-}: {
- task: Task;
- projectSlug: string;
- assignee: string;
-}) {
- return (
- <Link
- href={projectHref(projectSlug, `/tasks/${task.id}`)}
- className="block rounded-[10px] bg-card p-3 shadow-[var(--notfair-shadow-sm)] transition-colors hover:bg-[hsl(var(--notfair-hover))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--ring))]"
- style={{ boxShadow: "var(--notfair-shadow-sm)" }}
- >
- <div className="flex items-center justify-between gap-2">
- <span className="font-mono text-[10px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
- {task.display_id.toUpperCase()}
- </span>
- <span className="text-[10px] text-[hsl(var(--notfair-ink-4))]">
- {relativeTime(task.updated_at)}
- </span>
- </div>
- <p className="mt-1.5 line-clamp-2 text-[13px] font-medium text-[hsl(var(--notfair-ink))]">
- {task.title ?? task.brief}
- </p>
- {task.title && (
- <p className="mt-0.5 line-clamp-2 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
- {task.brief}
- </p>
- )}
- <div className="mt-2 flex items-center justify-between gap-2">
- <span className="ns-tag">{assignee}</span>
- </div>
- </Link>
- );
-}
-
-// ── List view ─────────────────────────────────────────────────────────
-
-function ListView({
- projectSlug,
- tasks,
- agentById,
- enabledStatuses,
-}: {
- projectSlug: string;
- tasks: Task[];
- agentById: Map<string, ProjectAgentEntry>;
- enabledStatuses: Set<TaskStatus>;
-}) {
- // In list view we still honor the column-visibility prefs (treating
- // them as "which statuses to include"), but we sort newest-first by
- // updated_at across all of them — no grouping. This is the
- // "everything I care about, by recency" feed.
- const rows = useMemo(
- () =>
- tasks
- .filter((t) => enabledStatuses.has(t.status))
- .slice()
- .sort(
- (a, b) =>
- new Date(b.updated_at).getTime() -
- new Date(a.updated_at).getTime(),
- ),
- [tasks, enabledStatuses],
- );
-
- if (rows.length === 0) {
- return (
- <div className="ns-empty">
- <p className="ns-empty-title">No tasks in the selected statuses.</p>
- <p className="ns-empty-sub">
- Open the Columns menu to include more.
- </p>
- </div>
- );
- }
- return (
- <div
- className="overflow-hidden rounded-[14px] bg-card"
- style={{ boxShadow: "var(--notfair-shadow)" }}
- >
- <div className="grid grid-cols-[6rem_7rem_minmax(0,1fr)_9rem_6rem] gap-3 border-b border-border/60 bg-[hsl(var(--notfair-surface-2))]/40 px-4 py-2.5 text-[10.5px] font-semibold uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">
- <span>ID</span>
- <span>Status</span>
- <span>Description</span>
- <span>Assignee</span>
- <span className="text-right">Updated</span>
- </div>
- <ul className="divide-y divide-border/60">
- {rows.map((t) => (
- <li key={t.id}>
- <Link
- href={projectHref(projectSlug, `/tasks/${t.id}`)}
- className="grid grid-cols-[6rem_7rem_minmax(0,1fr)_9rem_6rem] items-center gap-3 px-4 py-2.5 text-[12.5px] transition-colors hover:bg-[hsl(var(--notfair-hover))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--ring))]"
- >
- <span className="truncate font-mono text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
- {t.display_id.toUpperCase()}
- </span>
- <span className="flex items-center gap-1.5">
- <span
- aria-hidden
- className={cn(
- "size-1.5 rounded-full",
- STATUS_TONE[t.status],
- )}
- />
- <span className="text-[11.5px] text-[hsl(var(--notfair-ink-3))]">
- {STATUS_LABEL[t.status]}
- </span>
- </span>
- <span className="min-w-0">
- <span className="block truncate font-medium text-[hsl(var(--notfair-ink))]">
- {t.title ?? t.brief}
- </span>
- {t.title && (
- <span className="block truncate text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
- {t.brief}
- </span>
- )}
- </span>
- <span className="truncate text-[hsl(var(--notfair-ink-4))]">
- {agentById.get(t.agent_id)?.name ?? t.agent_id}
- </span>
- <span className="truncate text-right text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
- {relativeTime(t.updated_at)}
- </span>
- </Link>
- </li>
- ))}
- </ul>
- </div>
- );
-}
-
-// ── Helpers ───────────────────────────────────────────────────────────
-
-function agentLabel(
- agentById: Map<string, ProjectAgentEntry>,
- agentId: string,
-): string {
- return agentById.get(agentId)?.name ?? agentId;
-}
-
-function countForAgent(
- filtered: Task[],
- all: Task[],
- agentId: string,
-): number {
- // Show the count of *all* tasks for this agent in the dropdown so
- // users see the total they'd see if they picked this agent, not the
- // (potentially zero) count after the current filter is applied.
- void filtered;
- return all.filter((t) => t.agent_id === agentId).length;
-}
-
-function relativeTime(iso: string): string {
- const ms = Date.now() - new Date(iso).getTime();
- if (Number.isNaN(ms)) return "";
- if (ms < 60_000) return "just now";
- if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ago`;
- if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h ago`;
- if (ms < 7 * 86_400_000) return `${Math.floor(ms / 86_400_000)}d ago`;
- return new Date(iso).toLocaleDateString();
-}
diff --git a/notfair-cmo/src/components/working-indicator.test.tsx b/notfair-cmo/src/components/working-indicator.test.tsx
deleted file mode 100644
index 012871df..00000000
--- a/notfair-cmo/src/components/working-indicator.test.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-// @vitest-environment jsdom
-import { describe, expect, it } from "vitest";
-import { render, screen } from "@testing-library/react";
-
-import { WorkingIndicator, type WorkingPhase } from "./working-indicator";
-
-function basePhases(): WorkingPhase[] {
- return [
- { id: "1", label: "list_project_agents", state: "done" },
- { id: "2", label: "summarizeAccountSetup", state: "done" },
- { id: "3", label: "runScript", state: "active" },
- ];
-}
-
-describe("WorkingIndicator", () => {
- it("renders the agent name, headline, and elapsed readout", () => {
- render(
- <WorkingIndicator
- agentDisplayName="CMO"
- headline="Calling runScript"
- subtitle={`{"accountId":"3251706605"}`}
- phases={basePhases()}
- elapsedMs={18_000}
- mood="tool"
- />,
- );
- expect(screen.getByText("CMO")).toBeInTheDocument();
- expect(screen.getByText(/Calling runScript/)).toBeInTheDocument();
- // The elapsed pill formats mm:ss when >= 1s and < 1min.
- expect(screen.getByText(/0:18/)).toBeInTheDocument();
- });
-
- it("renders the trajectory chips (done + active)", () => {
- render(
- <WorkingIndicator
- agentDisplayName="CMO"
- headline="Calling runScript"
- phases={basePhases()}
- elapsedMs={0}
- mood="tool"
- />,
- );
- // Last 3 phases are visible by design (the trajectory cap).
- expect(screen.getByText("list_project_agents")).toBeInTheDocument();
- expect(screen.getByText("summarizeAccountSetup")).toBeInTheDocument();
- // Multiple "runScript" text appearances may exist (chip + headline)
- expect(screen.getAllByText("runScript").length).toBeGreaterThanOrEqual(1);
- });
-
- it("hides the elapsed pill when elapsedMs is null", () => {
- render(
- <WorkingIndicator
- agentDisplayName="CMO"
- headline="Starting"
- phases={[]}
- elapsedMs={null}
- mood="waiting"
- />,
- );
- // 0:00 / Nan etc shouldn't appear; the digital pill is gone entirely.
- expect(screen.queryByText(/^\d+:\d{2}$/)).not.toBeInTheDocument();
- });
-
- it("formats elapsed as mm:ss past 60s", () => {
- render(
- <WorkingIndicator
- agentDisplayName="CMO"
- headline="Calling runScript"
- phases={basePhases()}
- elapsedMs={75_000}
- mood="tool"
- />,
- );
- expect(screen.getByText("1:15")).toBeInTheDocument();
- });
-
- it("uses mood-specific ring color (smoke test via class presence)", () => {
- const { container, rerender } = render(
- <WorkingIndicator
- agentDisplayName="CMO"
- headline="..."
- phases={[]}
- elapsedMs={0}
- mood="waiting"
- />,
- );
- expect(container.querySelector(".ring-sky-500\\/15")).not.toBeNull();
- rerender(
- <WorkingIndicator
- agentDisplayName="CMO"
- headline="..."
- phases={[]}
- elapsedMs={0}
- mood="writing"
- />,
- );
- expect(container.querySelector(".ring-emerald-500\\/15")).not.toBeNull();
- });
-});
diff --git a/notfair-cmo/src/components/working-status.test.ts b/notfair-cmo/src/components/working-status.test.ts
deleted file mode 100644
index a8bce535..00000000
--- a/notfair-cmo/src/components/working-status.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { describe, it, expect } from "vitest";
-
-// The helpers are file-private to live-transcript.tsx so we can't import
-// them directly. Re-implement here to lock the behaviour in via tests —
-// if the logic in live-transcript.tsx drifts, this fails and we update
-// both. Tiny cost; keeps the documented behaviour pinned.
-
-function formatElapsed(ms: number): string {
- if (ms < 1500) return "just now";
- const s = Math.floor(ms / 1000);
- if (s < 60) return `${s}s`;
- const m = Math.floor(s / 60);
- const rem = s % 60;
- if (m < 60) return rem === 0 ? `${m}m` : `${m}m ${rem}s`;
- const h = Math.floor(m / 60);
- return `${h}h ${m % 60}m`;
-}
-
-function formatToolName(name: string): string {
- if (!name) return name;
- for (const sep of ["__", "."]) {
- const idx = name.lastIndexOf(sep);
- if (idx >= 0) {
- const tail = name.slice(idx + sep.length);
- if (tail) return tail;
- }
- }
- return name;
-}
-
-describe("formatElapsed", () => {
- it("uses 'just now' under 1.5s", () => {
- expect(formatElapsed(0)).toBe("just now");
- expect(formatElapsed(900)).toBe("just now");
- expect(formatElapsed(1499)).toBe("just now");
- });
- it("emits seconds between 1.5s and 60s", () => {
- expect(formatElapsed(1500)).toBe("1s");
- expect(formatElapsed(15_000)).toBe("15s");
- expect(formatElapsed(59_999)).toBe("59s");
- });
- it("emits minutes (and remaining seconds) under an hour", () => {
- expect(formatElapsed(60_000)).toBe("1m");
- expect(formatElapsed(75_000)).toBe("1m 15s");
- expect(formatElapsed(125_000)).toBe("2m 5s");
- });
- it("emits hours over an hour", () => {
- expect(formatElapsed(3_600_000)).toBe("1h 0m");
- expect(formatElapsed(3_900_000)).toBe("1h 5m");
- });
-});
-
-describe("formatToolName", () => {
- it("returns the tail after the last dot", () => {
- expect(formatToolName("demo1-notfair-googleads.summarizeAccountSetup")).toBe(
- "summarizeAccountSetup",
- );
- expect(formatToolName("notfair.runScript")).toBe("runScript");
- });
- it("returns the tail after the last double-underscore", () => {
- expect(formatToolName("demo1-notfair-googleads__runScript")).toBe(
- "runScript",
- );
- expect(formatToolName("acme__listKeywords")).toBe("listKeywords");
- });
- it("returns the name untouched when there's no separator", () => {
- expect(formatToolName("exec")).toBe("exec");
- expect(formatToolName("read_file")).toBe("read_file");
- });
- it("handles empty / trailing-separator edge cases", () => {
- expect(formatToolName("")).toBe("");
- expect(formatToolName("trailing.")).toBe("trailing.");
- expect(formatToolName("trailing__")).toBe("trailing__");
- });
-});
diff --git a/notfair-cmo/src/components/workspace-browser-card.test.tsx b/notfair-cmo/src/components/workspace-browser-card.test.tsx
deleted file mode 100644
index 8cbf9fdb..00000000
--- a/notfair-cmo/src/components/workspace-browser-card.test.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-// @vitest-environment jsdom
-import { describe, expect, it, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
-
-import { WorkspaceBrowserCard } from "./workspace-browser-card";
-
-// sonner.toast emits real DOM in jsdom; stub so we can assert on call args.
-vi.mock("sonner", () => ({
- toast: {
- success: vi.fn(),
- error: vi.fn(),
- },
-}));
-
-const originalFetch = globalThis.fetch;
-
-function mockFetch(handler: (url: string, init?: RequestInit) => unknown) {
- globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
- const value = handler(url, init);
- return new Response(JSON.stringify(value), { status: 200, headers: { "content-type": "application/json" } });
- }) as typeof fetch;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- globalThis.fetch = originalFetch;
-});
-
-describe("WorkspaceBrowserCard", () => {
- it("renders 'Not running' state on initial load when no session is active", async () => {
- mockFetch(() => ({
- status: { running: false, cdpPort: 19042, userDataDir: "/tmp/profile" },
- tabs: [],
- }));
-
- render(<WorkspaceBrowserCard projectSlug="acme" />);
-
- await waitFor(() => expect(screen.getByText(/Not running/)).toBeInTheDocument());
- expect(screen.getByRole("button", { name: /^Launch$/ })).toBeInTheDocument();
- expect(screen.getByText(/Profile dir:/)).toBeInTheDocument();
- });
-
- it("shows running state, idle countdown, sign-in buttons, and open tabs when session is up", async () => {
- mockFetch(() => ({
- status: {
- running: true,
- cdpPort: 19042,
- userDataDir: "/tmp/profile",
- uptimeMs: 32_000,
- idleMs: 60_000,
- idleTimeoutMs: 300_000,
- },
- tabs: [
- { id: "greg", url: "https://greg.example/", title: "Greg" },
- { id: "tina", url: "https://tina.example/", title: "Tina" },
- ],
- }));
-
- render(<WorkspaceBrowserCard projectSlug="acme" />);
-
- await waitFor(() => expect(screen.getByText(/Running on port 19042/)).toBeInTheDocument());
- expect(screen.getByText(/32s uptime/)).toBeInTheDocument();
- // 300_000 - 60_000 = 240_000ms → "auto-stops in 240s if idle"
- expect(screen.getByText(/auto-stops in 240s if idle/)).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /Open Google/ })).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /Open Meta/ })).toBeInTheDocument();
- expect(screen.getByText("greg")).toBeInTheDocument();
- expect(screen.getByText("Tina")).toBeInTheDocument();
- });
-
- it("POSTs to /api/browser/launch with headless=false when Launch is clicked", async () => {
- const fetchSpy = vi.fn(async (url: string, init?: RequestInit) => {
- if (url.includes("/status")) {
- return new Response(
- JSON.stringify({
- status: { running: false, cdpPort: 19042, userDataDir: "/tmp/profile" },
- tabs: [],
- }),
- { status: 200 },
- );
- }
- if (url.includes("/launch")) {
- return new Response(JSON.stringify({ status: { running: true } }), { status: 200 });
- }
- return new Response("{}", { status: 200 });
- });
- globalThis.fetch = fetchSpy as typeof fetch;
-
- render(<WorkspaceBrowserCard projectSlug="acme" />);
- await waitFor(() => screen.getByRole("button", { name: /^Launch$/ }));
-
- fireEvent.click(screen.getByRole("button", { name: /^Launch$/ }));
-
- await waitFor(() => {
- const launchCall = fetchSpy.mock.calls.find(([u]) => String(u).includes("/launch"));
- expect(launchCall).toBeDefined();
- const body = JSON.parse((launchCall![1] as RequestInit).body as string);
- expect(body).toEqual({ project_slug: "acme", signin_url: undefined, headless: false });
- });
- });
-
- it("POSTs to /api/browser/shutdown when Stop is clicked", async () => {
- let runningState = true;
- const fetchSpy = vi.fn(async (url: string) => {
- if (url.includes("/status")) {
- return new Response(
- JSON.stringify({
- status: { running: runningState, cdpPort: 19042, userDataDir: "/tmp/profile" },
- tabs: [],
- }),
- { status: 200 },
- );
- }
- if (url.includes("/shutdown")) {
- runningState = false;
- return new Response(JSON.stringify({ ok: true }), { status: 200 });
- }
- return new Response("{}", { status: 200 });
- });
- globalThis.fetch = fetchSpy as typeof fetch;
-
- render(<WorkspaceBrowserCard projectSlug="acme" />);
- await waitFor(() => screen.getByRole("button", { name: /^Stop$/ }));
-
- fireEvent.click(screen.getByRole("button", { name: /^Stop$/ }));
-
- await waitFor(() => {
- const shutdownCall = fetchSpy.mock.calls.find(([u]) => String(u).includes("/shutdown"));
- expect(shutdownCall).toBeDefined();
- });
- });
-
- it("POSTs signin_url when a sign-in target button is clicked", async () => {
- const fetchSpy = vi.fn(async (url: string, _init?: RequestInit) => {
- if (url.includes("/status")) {
- return new Response(
- JSON.stringify({
- status: {
- running: true,
- cdpPort: 19042,
- userDataDir: "/tmp/profile",
- uptimeMs: 1_000,
- },
- tabs: [],
- }),
- { status: 200 },
- );
- }
- return new Response(JSON.stringify({ status: { running: true } }), { status: 200 });
- });
- globalThis.fetch = fetchSpy as typeof fetch;
-
- render(<WorkspaceBrowserCard projectSlug="acme" />);
- await waitFor(() => screen.getByRole("button", { name: /Open Google/ }));
-
- fireEvent.click(screen.getByRole("button", { name: /Open Google/ }));
-
- await waitFor(() => {
- const launchCall = fetchSpy.mock.calls.find(([u]) => String(u).includes("/launch"));
- expect(launchCall).toBeDefined();
- const body = JSON.parse(launchCall![1]!.body as string);
- expect(body.signin_url).toBe("https://accounts.google.com/");
- });
- });
-});
diff --git a/notfair-cmo/src/lib/agent-colors.test.ts b/notfair-cmo/src/lib/agent-colors.test.ts
deleted file mode 100644
index c40bed11..00000000
--- a/notfair-cmo/src/lib/agent-colors.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { colorForAgentSlug } from "./agent-colors";
-
-describe("colorForAgentSlug", () => {
- it("returns the reserved blue palette for cmo", () => {
- const c = colorForAgentSlug("cmo");
- expect(c.dot).toBe("bg-blue-500");
- // Codex theme: chip fills are neutral inset for every agent — hue
- // survives only in dot/label.
- expect(c.chip).toContain("bg-[hsl(var(--notfair-surface-2))]");
- expect(c.label).toContain("text-blue-700");
- });
-
- it("returns the amber palette for google-ads (hyphenated slug)", () => {
- const c = colorForAgentSlug("google-ads");
- expect(c.dot).toBe("bg-amber-500");
- expect(c.chip).toContain("bg-[hsl(var(--notfair-surface-2))]");
- expect(c.label).toContain("text-amber-700");
- });
-
- it("returns the amber palette for google_ads (underscored key)", () => {
- const c = colorForAgentSlug("google_ads");
- expect(c.dot).toBe("bg-amber-500");
- });
-
- it("returns the emerald palette for seo", () => {
- const c = colorForAgentSlug("seo");
- expect(c.dot).toBe("bg-emerald-500");
- expect(c.label).toContain("text-emerald-700");
- });
-
- it("returns the sky palette for x-ads (with or without a name suffix)", () => {
- expect(colorForAgentSlug("x-ads").dot).toBe("bg-sky-500");
- expect(colorForAgentSlug("x-ads-max").dot).toBe("bg-sky-500");
- });
-
- it("returns a non-template color for custom slugs", () => {
- const c = colorForAgentSlug("growth-engineer");
- // Custom slugs must never land on a template dot color (they would clash
- // with the reserved cmo/google_ads/meta_ads/seo/x_ads legend swatches).
- expect(c.dot).not.toBe("bg-blue-500");
- expect(c.dot).not.toBe("bg-amber-500");
- expect(c.dot).not.toBe("bg-pink-500");
- expect(c.dot).not.toBe("bg-emerald-500");
- expect(c.dot).not.toBe("bg-sky-500");
- });
-
- it("maps the same custom slug to the same color across calls", () => {
- const a = colorForAgentSlug("growth-engineer");
- const b = colorForAgentSlug("growth-engineer");
- expect(a).toEqual(b);
- });
-
- it("returns a color from the extras palette for an empty slug", () => {
- const c = colorForAgentSlug("");
- const extraDots = [
- "bg-violet-500",
- "bg-rose-500",
- "bg-cyan-500",
- "bg-fuchsia-500",
- "bg-teal-500",
- "bg-orange-500",
- "bg-indigo-500",
- "bg-lime-500",
- ];
- expect(extraDots).toContain(c.dot);
- });
-
- it("returns chip/dot/label fields for every input", () => {
- for (const slug of ["cmo", "seo", "custom-1", "custom-2", "another"]) {
- const c = colorForAgentSlug(slug);
- expect(typeof c.chip).toBe("string");
- expect(typeof c.dot).toBe("string");
- expect(typeof c.label).toBe("string");
- expect(c.chip.length).toBeGreaterThan(0);
- expect(c.dot.length).toBeGreaterThan(0);
- expect(c.label.length).toBeGreaterThan(0);
- }
- });
-
- it("distributes different custom slugs across more than one extras bucket", () => {
- const dots = new Set<string>();
- for (const slug of [
- "alpha",
- "beta",
- "gamma",
- "delta",
- "epsilon",
- "zeta",
- "eta",
- "theta",
- "iota",
- "kappa",
- "lambda",
- "mu",
- "nu",
- "xi",
- "omicron",
- "pi",
- ]) {
- dots.add(colorForAgentSlug(slug).dot);
- }
- expect(dots.size).toBeGreaterThan(1);
- });
-});
diff --git a/notfair-cmo/src/lib/agent-colors.ts b/notfair-cmo/src/lib/agent-colors.ts
deleted file mode 100644
index 021d7219..00000000
--- a/notfair-cmo/src/lib/agent-colors.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import type { AgentTemplateKey } from "@/server/agent-templates";
-
-/**
- * Per-agent color palette used by the cron calendar so users can scan which
- * agent owns which job at a glance. Deliberately distinct hues that all read
- * well against the zinc neutral background.
- */
-export type AgentColor = {
- /** Tailwind classes: chip background + text color. Codex theme:
- * chips are neutral inset fills for every agent — hue lives in the
- * `dot` / `label` fields only, so ownership stays scannable without
- * colored blocks in the chrome. */
- chip: string;
- /** Solid dot/legend swatch. */
- dot: string;
- /** Label color when only the label is shown. */
- label: string;
-};
-
-const PALETTE: Record<AgentTemplateKey, AgentColor> = {
- cmo: {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-blue-500",
- label: "text-blue-700 dark:text-blue-300",
- },
- google_ads: {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-amber-500",
- label: "text-amber-700 dark:text-amber-300",
- },
- meta_ads: {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-pink-500",
- label: "text-pink-700 dark:text-pink-300",
- },
- seo: {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-emerald-500",
- label: "text-emerald-700 dark:text-emerald-300",
- },
- // Sky, not cyan: cyan-500 lives in EXTRA_PALETTE and a reserved role
- // hue must never collide with a hashed custom-agent swatch.
- x_ads: {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-sky-500",
- label: "text-sky-700 dark:text-sky-300",
- },
-};
-
-/**
- * Extra palette used for custom or cloned agents (anything not in TEMPLATES).
- * Each entry is intentionally vivid — zinc/neutral would read as "disabled"
- * against the rest of the UI. Hue-hashing the slug below keeps the mapping
- * stable across renders without needing a DB.
- */
-const EXTRA_PALETTE: AgentColor[] = [
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-violet-500",
- label: "text-violet-700 dark:text-violet-300",
- },
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-rose-500",
- label: "text-rose-700 dark:text-rose-300",
- },
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-cyan-500",
- label: "text-cyan-700 dark:text-cyan-300",
- },
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-fuchsia-500",
- label: "text-fuchsia-700 dark:text-fuchsia-300",
- },
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-teal-500",
- label: "text-teal-700 dark:text-teal-300",
- },
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-orange-500",
- label: "text-orange-700 dark:text-orange-300",
- },
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-indigo-500",
- label: "text-indigo-700 dark:text-indigo-300",
- },
- {
- chip: "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent",
- dot: "bg-lime-500",
- label: "text-lime-700 dark:text-lime-300",
- },
-];
-
-/** Fast deterministic hash (djb2) so a slug always maps to the same color. */
-function hashSlug(slug: string): number {
- let h = 5381;
- for (let i = 0; i < slug.length; i++) {
- h = ((h << 5) + h + slug.charCodeAt(i)) | 0;
- }
- return Math.abs(h);
-}
-
-/**
- * Color for a template ROLE (cmo, google_ads, seo). Canonical lookup for
- * the sidebar role pill + cron calendar swatches — both should agree on
- * "CMO is blue" regardless of any personal-name suffix in the URL slug.
- * Stable across the lifetime of the project.
- */
-export function colorForRole(role: AgentTemplateKey): AgentColor {
- return PALETTE[role];
-}
-
-/**
- * Resolve a color for an agent slug as it appears in our cron view.
- * Templates (cmo / google-ads / seo, with or without a `-<name>` suffix)
- * get their reserved hue. Anything else gets a stable color from the
- * extras palette via slug hash — never the zinc fallback, which reads
- * as "disabled".
- *
- * Accepts both legacy bare slugs (`cmo`) and the new role-plus-name
- * shape (`cmo-greg`) — the role prefix is matched against the palette
- * before falling through to the hash bucket.
- */
-export function colorForAgentSlug(slug: string): AgentColor {
- // Try a direct lookup first (handles legacy "cmo" / "seo" slugs).
- const direct = PALETTE[slug.replace(/-/g, "_") as AgentTemplateKey];
- if (direct) return direct;
- // New shape: <role>-<name>. Walk the role keys longest-first so
- // "google_ads" matches before "cmo" wouldn't accidentally match
- // "cmo-anything".
- const roleKeys = Object.keys(PALETTE) as AgentTemplateKey[];
- const sorted = roleKeys.slice().sort((a, b) => b.length - a.length);
- for (const role of sorted) {
- const rolePrefix = role.replace(/_/g, "-");
- if (slug === rolePrefix || slug.startsWith(`${rolePrefix}-`)) {
- return PALETTE[role];
- }
- }
- return EXTRA_PALETTE[hashSlug(slug) % EXTRA_PALETTE.length]!;
-}
diff --git a/notfair-cmo/src/lib/project-href.test.ts b/notfair-cmo/src/lib/project-href.test.ts
deleted file mode 100644
index 0d38458e..00000000
--- a/notfair-cmo/src/lib/project-href.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { projectHref, subPathFromPathname } from "./project-href";
-
-describe("projectHref", () => {
- it("returns /:slug for empty path", () => {
- expect(projectHref("acme")).toBe("/acme");
- expect(projectHref("acme", "")).toBe("/acme");
- expect(projectHref("acme", "/")).toBe("/acme");
- });
-
- it("prefixes paths missing a leading slash", () => {
- expect(projectHref("acme", "agents/cmo")).toBe("/acme/agents/cmo");
- });
-
- it("prefixes paths with a leading slash", () => {
- expect(projectHref("acme", "/agents/cmo")).toBe("/acme/agents/cmo");
- });
-
- it("preserves nested segments and query strings verbatim", () => {
- expect(projectHref("acme", "/agents/cmo/chat/abc-123")).toBe(
- "/acme/agents/cmo/chat/abc-123",
- );
- expect(projectHref("acme", "/tasks?status=running")).toBe(
- "/acme/tasks?status=running",
- );
- });
-
- it("rejects an empty slug", () => {
- expect(() => projectHref("", "/agents")).toThrow();
- });
-
- it("works with hyphenated slugs", () => {
- expect(projectHref("my-cool-co", "/connections")).toBe(
- "/my-cool-co/connections",
- );
- });
-});
-
-describe("subPathFromPathname", () => {
- it("returns empty for the project home", () => {
- expect(subPathFromPathname("/acme", "acme")).toBe("");
- });
-
- it("strips the project slug from a nested path", () => {
- expect(subPathFromPathname("/acme/agents/cmo/tasks", "acme")).toBe(
- "/agents/cmo/tasks",
- );
- expect(subPathFromPathname("/acme/crons", "acme")).toBe("/crons");
- });
-
- it("returns empty when pathname is missing or doesn't match", () => {
- expect(subPathFromPathname(null, "acme")).toBe("");
- expect(subPathFromPathname(undefined, "acme")).toBe("");
- expect(subPathFromPathname("/onboarding", "acme")).toBe("");
- expect(subPathFromPathname("/other/agents", "acme")).toBe("");
- });
-
- it("returns empty when slug is missing", () => {
- expect(subPathFromPathname("/acme/agents", null)).toBe("");
- expect(subPathFromPathname("/acme/agents", "")).toBe("");
- });
-
- it("handles hyphenated slugs", () => {
- expect(
- subPathFromPathname("/my-cool-co/agents/cmo", "my-cool-co"),
- ).toBe("/agents/cmo");
- });
-
- it("does not strip when the slug is a partial prefix", () => {
- // "/acmeful/agents" shouldn't match slug "acme"
- expect(subPathFromPathname("/acmeful/agents", "acme")).toBe("");
- });
-
- it("supports round-tripping through projectHref", () => {
- const original = "/acme/agents/cmo/tasks";
- const sub = subPathFromPathname(original, "acme");
- expect(projectHref("zeta", sub)).toBe("/zeta/agents/cmo/tasks");
- });
-});
diff --git a/notfair-cmo/src/lib/slash-commands.test.ts b/notfair-cmo/src/lib/slash-commands.test.ts
deleted file mode 100644
index 0ed8371d..00000000
--- a/notfair-cmo/src/lib/slash-commands.test.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- SLASH_COMMANDS,
- executeLocalSlashCommand,
- filterSlashCommands,
- findCommand,
- parseSlashMessage,
-} from "./slash-commands";
-
-describe("SLASH_COMMANDS catalog", () => {
- it("has unique command keys", () => {
- const keys = SLASH_COMMANDS.map((c) => c.key);
- expect(new Set(keys).size).toBe(keys.length);
- });
-
- it("has unique command names", () => {
- const names = SLASH_COMMANDS.map((c) => c.name);
- expect(new Set(names).size).toBe(names.length);
- });
-
- it("marks every command as executeLocal — no dead OpenClaw passthroughs", () => {
- // The catalog used to carry ~17 OpenClaw gateway directives
- // (/compact, /status, /elevated, …) that were sent to the agent as
- // literal text. notfair-cmo has no gateway; only commands the client
- // itself handles belong here.
- for (const cmd of SLASH_COMMANDS) {
- expect(cmd.executeLocal).toBe(true);
- }
- for (const name of ["clear", "new", "stop", "model", "help"]) {
- expect(findCommand(name)).toBeDefined();
- }
- for (const gone of ["status", "compact", "think", "elevated", "skill", "queue"]) {
- expect(findCommand(gone)).toBeUndefined();
- }
- });
-});
-
-describe("filterSlashCommands", () => {
- it("returns all commands for empty query", () => {
- expect(filterSlashCommands("")).toEqual(SLASH_COMMANDS);
- expect(filterSlashCommands(" ")).toEqual(SLASH_COMMANDS);
- });
-
- it("returns all commands for a bare slash", () => {
- expect(filterSlashCommands("/")).toEqual(SLASH_COMMANDS);
- });
-
- it("prefix-matches with or without leading slash", () => {
- const a = filterSlashCommands("cl");
- const b = filterSlashCommands("/cl");
- expect(a).toEqual(b);
- expect(a.some((c) => c.name === "clear")).toBe(true);
- });
-
- it("is case-insensitive", () => {
- const lower = filterSlashCommands("CL");
- expect(lower.some((c) => c.name === "clear")).toBe(true);
- });
-
- it("falls back to substring match when no prefix hits", () => {
- // "od" does not prefix any command name, but `model` contains it,
- // so the substring fallback should surface it.
- const r = filterSlashCommands("od");
- const names = r.map((c) => c.name);
- expect(names).toContain("model");
- expect(names.every((n) => n.toLowerCase().startsWith("od"))).toBe(false);
- });
-
- it("returns empty list when nothing matches", () => {
- expect(filterSlashCommands("zzzzzz")).toEqual([]);
- });
-
- it("prefers prefix matches over substring matches", () => {
- // "cl" prefix-matches `clear`. It should NOT fall back to substring,
- // and the result must contain only prefix hits.
- const r = filterSlashCommands("cl");
- expect(r.every((c) => c.name.toLowerCase().startsWith("cl"))).toBe(true);
- expect(r.length).toBeGreaterThan(0);
- });
-});
-
-describe("parseSlashMessage", () => {
- it("returns null for plain text", () => {
- expect(parseSlashMessage("hello")).toBeNull();
- expect(parseSlashMessage("")).toBeNull();
- });
-
- it("returns null for whitespace-only", () => {
- expect(parseSlashMessage(" ")).toBeNull();
- });
-
- it("parses a bare slash command", () => {
- expect(parseSlashMessage("/clear")).toEqual({ command: "clear", args: "" });
- });
-
- it("parses a slash command with args", () => {
- expect(parseSlashMessage("/model gpt-5.5 codex")).toEqual({
- command: "model",
- args: "gpt-5.5 codex",
- });
- });
-
- it("trims trailing whitespace from args", () => {
- expect(parseSlashMessage("/model gpt-5 ")).toEqual({
- command: "model",
- args: "gpt-5",
- });
- });
-
- it("trims leading whitespace from the message", () => {
- expect(parseSlashMessage(" /help")).toEqual({ command: "help", args: "" });
- });
-
- it("treats a lone slash as an empty command", () => {
- expect(parseSlashMessage("/")).toEqual({ command: "", args: "" });
- });
-});
-
-describe("findCommand", () => {
- it("finds a known command by name", () => {
- const cmd = findCommand("model");
- expect(cmd).toBeDefined();
- expect(cmd?.key).toBe("model");
- });
-
- it("returns undefined for an unknown command", () => {
- expect(findCommand("nope")).toBeUndefined();
- });
-
- it("is case-sensitive on the canonical name", () => {
- expect(findCommand("CLEAR")).toBeUndefined();
- });
-});
-
-describe("executeLocalSlashCommand", () => {
- it("returns a clear action for /clear", () => {
- expect(executeLocalSlashCommand("clear")).toEqual({ kind: "clear" });
- });
-
- it("returns a new-session action for /new", () => {
- expect(executeLocalSlashCommand("new")).toEqual({ kind: "new-session" });
- });
-
- it("returns a stop action for /stop", () => {
- expect(executeLocalSlashCommand("stop")).toEqual({ kind: "stop" });
- });
-
- it("returns a set-model action for /model, carrying the argument", () => {
- expect(executeLocalSlashCommand("model", "gpt-5.5")).toEqual({
- kind: "set-model",
- value: "gpt-5.5",
- });
- // No argument → empty value; the composer shows current + options.
- expect(executeLocalSlashCommand("model")).toEqual({
- kind: "set-model",
- value: "",
- });
- });
-
- it("returns a help action with rendered markdown content", () => {
- const r = executeLocalSlashCommand("help");
- expect(r?.kind).toBe("help");
- if (r?.kind !== "help") return;
- expect(r.content).toContain("Available commands");
- expect(r.content).toContain("/clear");
- // Commands that declare args render them.
- expect(r.content).toContain("/model <model>");
- });
-
- it("returns null for removed OpenClaw passthrough commands", () => {
- expect(executeLocalSlashCommand("status")).toBeNull();
- expect(executeLocalSlashCommand("compact")).toBeNull();
- });
-
- it("returns null for an unknown command", () => {
- expect(executeLocalSlashCommand("nope")).toBeNull();
- });
-});
diff --git a/notfair-cmo/src/lib/slug.test.ts b/notfair-cmo/src/lib/slug.test.ts
deleted file mode 100644
index 758d2cf4..00000000
--- a/notfair-cmo/src/lib/slug.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { isValidSlug, slugify } from "./slug";
-
-describe("slugify", () => {
- it("returns slug for a normal name", () => {
- const r = slugify("Acme Q4 launch");
- expect(r).toEqual({ ok: true, slug: "acme-q4-launch" });
- });
-
- it("collapses runs of whitespace and hyphens", () => {
- const r = slugify(" Acme -- Q4 ");
- expect(r).toEqual({ ok: true, slug: "acme-q4" });
- });
-
- it("strips non-ascii characters", () => {
- const r = slugify("Café — naïve résumé");
- expect(r).toEqual({ ok: true, slug: "cafe-naive-resume" });
- });
-
- it("rejects empty input", () => {
- expect(slugify("")).toEqual({ ok: false, reason: "input is empty" });
- expect(slugify(" ")).toEqual({ ok: false, reason: "input is empty" });
- });
-
- it("rejects input with no valid characters", () => {
- const r = slugify("✨🔥");
- expect(r).toEqual({ ok: false, reason: "no valid characters" });
- });
-
- it("rejects reserved slugs", () => {
- const r = slugify("CMO");
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.reason).toMatch(/reserved/);
- });
-
- it("caps at maxLen and trims trailing hyphens after the cap", () => {
- const r = slugify("a".repeat(60), 10);
- expect(r).toEqual({ ok: true, slug: "aaaaaaaaaa" });
- });
-
- it("does not leave a trailing hyphen when cap falls mid-word", () => {
- const r = slugify("ab-cd-ef-gh", 5);
- expect(r.ok).toBe(true);
- if (r.ok) expect(r.slug).not.toMatch(/-$/);
- });
-});
-
-describe("isValidSlug", () => {
- it("accepts valid lowercase hyphenated slugs", () => {
- expect(isValidSlug("acme-q4")).toBe(true);
- expect(isValidSlug("acme")).toBe(true);
- expect(isValidSlug("a1b2c3")).toBe(true);
- });
-
- it("rejects uppercase, underscores, leading/trailing hyphens", () => {
- expect(isValidSlug("Acme")).toBe(false);
- expect(isValidSlug("acme_q4")).toBe(false);
- expect(isValidSlug("-acme")).toBe(false);
- expect(isValidSlug("acme-")).toBe(false);
- });
-
- it("rejects reserved slugs", () => {
- expect(isValidSlug("cmo")).toBe(false);
- expect(isValidSlug("api")).toBe(false);
- expect(isValidSlug("openclaw")).toBe(false);
- });
-});
diff --git a/notfair-cmo/src/lib/utils.test.ts b/notfair-cmo/src/lib/utils.test.ts
deleted file mode 100644
index 7ea3f069..00000000
--- a/notfair-cmo/src/lib/utils.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { cn } from "./utils";
-
-describe("cn", () => {
- it("joins simple class strings", () => {
- expect(cn("a", "b")).toBe("a b");
- });
-
- it("returns an empty string for no inputs", () => {
- expect(cn()).toBe("");
- });
-
- it("filters out falsy values", () => {
- expect(cn("a", false, null, undefined, "", "b")).toBe("a b");
- });
-
- it("supports conditional object syntax via clsx", () => {
- expect(cn("a", { b: true, c: false, d: true })).toBe("a b d");
- });
-
- it("supports nested arrays via clsx", () => {
- expect(cn(["a", ["b", "c"]], "d")).toBe("a b c d");
- });
-
- it("dedupes conflicting tailwind utilities via twMerge (last wins)", () => {
- expect(cn("p-2", "p-4")).toBe("p-4");
- expect(cn("text-sm", "text-lg")).toBe("text-lg");
- });
-
- it("keeps non-conflicting tailwind utilities", () => {
- expect(cn("p-2", "text-sm")).toBe("p-2 text-sm");
- });
-
- it("merges variant prefixes correctly", () => {
- // sm:p-2 and p-4 are different variants → both kept.
- expect(cn("sm:p-2", "p-4")).toBe("sm:p-2 p-4");
- // Same variant → last wins.
- expect(cn("sm:p-2", "sm:p-4")).toBe("sm:p-4");
- });
-
- it("handles a mix of conditional + tailwind merge inputs", () => {
- expect(cn("p-2", { "p-4": true }, ["text-sm", { "text-lg": false }]))
- .toBe("p-4 text-sm");
- });
-});
diff --git a/notfair-cmo/src/server/actions/agents.ts b/notfair-cmo/src/server/actions/agents.ts
deleted file mode 100644
index ef852f90..00000000
--- a/notfair-cmo/src/server/actions/agents.ts
+++ /dev/null
@@ -1,351 +0,0 @@
-"use server";
-
-import { existsSync } from "node:fs";
-import { revalidatePath } from "next/cache";
-import { getActiveProject } from "@/server/active-project";
-import {
- disableCron,
- listCronsForProject,
- removeCron,
-} from "@/server/scheduler/display";
-import {
- agentExistsInProject,
- cascadeDeleteAgent,
- cloneAgent,
- type CloneAgentResult,
-} from "@/server/agents/clone";
-import {
- workspaceDirFor,
- provisionAgent,
-} from "@/server/agents/provisioning";
-import {
- readAgentMeta,
- writeAgentMeta,
- listProjectAgents,
- type AgentMeta,
- type ProjectAgentEntry,
-} from "@/server/agent-meta";
-import { listSessionsForAgent } from "@/server/sessions/view";
-import { slugify } from "@/lib/slug";
-import { getProject } from "@/server/db/projects";
-import { DEFAULT_HARNESS_ADAPTER } from "@/server/adapters/registry";
-import type { AgentTemplate } from "@/server/agent-templates";
-
-export type ActionResult<T = void> =
- | { ok: true; data: T }
- | { ok: false; error: string };
-
-export type AgentChoice = {
- agent_id: string;
- display_name: string;
- in_current_project: boolean;
-};
-
-/**
- * Previously listed every agent across the OpenClaw config. With the harness-
- * adapter model there's no global agent registry — agents live per-project in
- * notfair-cmo's data dir. We surface the active project's roster only.
- */
-export async function listOpenClawAgentsAction(): Promise<ActionResult<AgentChoice[]>> {
- const project = await getActiveProject();
- if (!project) return { ok: true, data: [] };
- try {
- const entries = await listProjectAgents(project.slug);
- return {
- ok: true,
- data: entries.map((e) => ({
- agent_id: e.agent_id,
- display_name: e.name,
- in_current_project: true,
- })),
- };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
-export async function listProjectAgentsAction(): Promise<ActionResult<ProjectAgentEntry[]>> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
- try {
- return { ok: true, data: await listProjectAgents(project.slug) };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
-export type CreateAgentInput = { display_name: string };
-
-export async function createAgentAction(
- input: CreateAgentInput,
-): Promise<ActionResult<{ agent_id: string; slug: string }>> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
- const slug = slugify(input.display_name);
- if (!slug.ok) return { ok: false, error: `Invalid name: ${slug.reason}` };
-
- if (agentExistsInProject(project.slug, slug.slug)) {
- return {
- ok: false,
- error: `An agent named "${slug.slug}" already exists in this project.`,
- };
- }
-
- const agentId = `${project.slug}-${slug.slug}`;
- const harness = project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;
-
- try {
- await provisionAgent({
- projectSlug: project.slug,
- agentId,
- displayName: input.display_name.trim(),
- templateKey: "custom",
- identityMd: `# ${input.display_name.trim()}\n\nCustom agent. Edit IDENTITY.md to define this agent's role.\n`,
- harnessAdapter: harness,
- });
- await writeAgentMeta({
- agent_id: agentId,
- project_slug: project.slug,
- slug: slug.slug,
- name: input.display_name.trim(),
- created_at: new Date().toISOString(),
- });
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
- revalidatePath("/", "layout");
- return { ok: true, data: { agent_id: agentId, slug: slug.slug } };
-}
-
-export type CloneAgentActionInput = {
- source_agent_id: string;
- new_display_name: string;
- new_slug?: string;
-};
-
-export async function cloneAgentAction(
- input: CloneAgentActionInput,
-): Promise<ActionResult<CloneAgentResult>> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
-
- const slugSource = (input.new_slug ?? input.new_display_name).trim();
- if (!slugSource) {
- return { ok: false, error: "Please provide a name for the cloned agent." };
- }
- try {
- const result = await cloneAgent({
- source_agent_id: input.source_agent_id,
- project_slug: project.slug,
- new_slug: slugSource,
- display_name: input.new_display_name,
- });
- revalidatePath("/", "layout");
- return { ok: true, data: result };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
-export async function disableCronsAction(
- cronIds: string[],
-): Promise<ActionResult<{ disabled: number; failed: number }>> {
- let disabled = 0;
- let failed = 0;
- for (const id of cronIds) {
- try {
- await disableCron(id);
- disabled++;
- } catch {
- failed++;
- }
- }
- revalidatePath("/", "layout");
- return { ok: true, data: { disabled, failed } };
-}
-
-// --- Relocate ---
-
-export type RelocateAgentInput = {
- old_agent_id: string;
- source_project_slug: string;
- new_project_slug: string;
- new_slug: string;
- new_display_name: string;
- preserve_template_key?: AgentTemplate["key"];
- preserve_source_agent_id?: string;
- preserve_created_at?: string;
-};
-
-export type RelocateAgentResult = {
- new_agent_id: string;
- new_slug: string;
-};
-
-export async function relocateAgent(
- input: RelocateAgentInput,
-): Promise<RelocateAgentResult> {
- const cloneResult = await cloneAgent({
- source_agent_id: input.old_agent_id,
- project_slug: input.new_project_slug,
- new_slug: input.new_slug,
- display_name: input.new_display_name,
- slug_is_canonical: true,
- });
-
- const isTemplateAgent = !!input.preserve_template_key;
- await writeAgentMeta({
- agent_id: cloneResult.new_agent_id,
- project_slug: input.new_project_slug,
- ...(isTemplateAgent ? {} : { slug: cloneResult.new_slug }),
- name: input.new_display_name,
- ...(input.preserve_template_key ? { template_key: input.preserve_template_key } : {}),
- ...(input.preserve_source_agent_id
- ? { source_agent_id: input.preserve_source_agent_id }
- : {}),
- created_at: input.preserve_created_at ?? new Date().toISOString(),
- });
-
- await cascadeDeleteAgent(input.old_agent_id, input.source_project_slug).catch(() => {});
-
- return {
- new_agent_id: cloneResult.new_agent_id,
- new_slug: cloneResult.new_slug,
- };
-}
-
-// --- Rename ---
-
-export type RenameAgentInput = {
- agent_id: string;
- new_display_name: string;
-};
-
-export type RenameAgentData = {
- agent_id: string;
- slug: string;
- display_name: string;
- full_rename: boolean;
-};
-
-export async function renameAgentAction(
- _input: RenameAgentInput,
-): Promise<ActionResult<RenameAgentData>> {
- return {
- ok: false,
- error: "Agents are immutable once created. To use a different name, clone the agent and delete the original.",
- };
-}
-
-// --- Per-agent deletion ---
-
-export type AgentDeletionSummary = {
- agent_id: string;
- display_name: string;
- exists_in_openclaw: boolean;
- threads: Array<{ session_id: string; label: string; last_interaction_at: number }>;
- crons: Array<{ id: string; name: string; disabled: boolean }>;
- source_agent_id?: string;
- template_key?: string;
-};
-
-export async function getAgentDeletionSummaryAction(
- agent_id: string,
-): Promise<ActionResult<AgentDeletionSummary>> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
-
- const meta: AgentMeta | null = readAgentMeta(agent_id);
- const agentDir = workspaceDirFor(agent_id);
- const exists = existsSync(agentDir);
- const sessions = exists ? listSessionsForAgent(project.slug, agent_id) : [];
- const threads = sessions.map((s) => ({
- session_id: s.sessionId,
- label: s.label,
- last_interaction_at: s.lastInteractionAt,
- }));
-
- const crons: Array<{ id: string; name: string; disabled: boolean }> = [];
- try {
- const view = await listCronsForProject(project.slug);
- for (const g of view.groups) {
- for (const c of g.crons) {
- if (c.agent_id !== agent_id) continue;
- crons.push({ id: c.id, name: c.short_name || c.name, disabled: c.disabled });
- }
- }
- } catch {
- // best-effort
- }
-
- return {
- ok: true,
- data: {
- agent_id,
- display_name: meta?.name ?? agent_id,
- // field kept for UI compatibility — true when the workspace exists
- exists_in_openclaw: exists,
- threads,
- crons,
- source_agent_id: meta?.source_agent_id,
- template_key: meta?.template_key,
- },
- };
-}
-
-export type DeleteAgentData = {
- agent_id: string;
- crons_removed: number;
- crons_failed: number;
- openclaw_deleted: boolean;
- meta_removed: boolean;
-};
-
-export type CascadeAgentDeleteOutcome = DeleteAgentData;
-
-export async function deleteAgentCascadeAction(
- agent_id: string,
-): Promise<ActionResult<DeleteAgentData>> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
-
- let cronsRemoved = 0;
- let cronsFailed = 0;
- try {
- const view = await listCronsForProject(project.slug);
- for (const g of view.groups) {
- for (const c of g.crons) {
- if (c.agent_id !== agent_id) continue;
- try {
- await removeCron(c.id);
- cronsRemoved++;
- } catch {
- cronsFailed++;
- }
- }
- }
- } catch {
- // best-effort
- }
-
- try {
- await cascadeDeleteAgent(agent_id, project.slug);
- } catch (err) {
- return {
- ok: false,
- error: `Failed to delete agent: ${err instanceof Error ? err.message : String(err)}`,
- };
- }
-
- revalidatePath("/", "layout");
- return {
- ok: true,
- data: {
- agent_id,
- crons_removed: cronsRemoved,
- crons_failed: cronsFailed,
- openclaw_deleted: true,
- meta_removed: true,
- },
- };
-}
diff --git a/notfair-cmo/src/server/actions/approvals.test.ts b/notfair-cmo/src/server/actions/approvals.test.ts
deleted file mode 100644
index a9a3263b..00000000
--- a/notfair-cmo/src/server/actions/approvals.test.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const revalidatePathMock = vi.fn();
-vi.mock("next/cache", () => ({
- revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),
-}));
-
-const getApprovalMock = vi.fn();
-const resolveApprovalMock = vi.fn();
-const requestApprovalRevisionMock = vi.fn();
-const appendCommentMock = vi.fn();
-const createPolicyMock = vi.fn();
-const deletePolicyMock = vi.fn();
-vi.mock("@/server/db/approvals", () => ({
- getApproval: (...a: unknown[]) => getApprovalMock(...a),
- resolveApproval: (...a: unknown[]) => resolveApprovalMock(...a),
- requestApprovalRevision: (...a: unknown[]) => requestApprovalRevisionMock(...a),
- appendComment: (...a: unknown[]) => appendCommentMock(...a),
- createPolicy: (...a: unknown[]) => createPolicyMock(...a),
- deletePolicy: (...a: unknown[]) => deletePolicyMock(...a),
-}));
-
-const wakeMock = vi.fn();
-vi.mock("@/server/orchestration/approval-wakeup", () => ({
- wakeTaskOnApprovalResolution: (...a: unknown[]) => wakeMock(...a),
-}));
-
-import {
- addApprovalCommentAction,
- approveAction,
- createPolicyAction,
- deletePolicyAction,
- rejectAction,
- requestRevisionAction,
-} from "./approvals";
-
-function makeApproval(overrides: Record<string, unknown> = {}) {
- return {
- id: "ap-1",
- project_slug: "demo",
- agent_id: "demo-cmo",
- task_id: null,
- action_summary: "raise bid",
- action_type: "bid_change",
- cost_estimate_usd: 0,
- reasoning: null,
- payload_json: "{}",
- status: "pending",
- decision_note: null,
- decided_by_kind: null,
- decided_by_id: null,
- created_at: "2026-05-01T00:00:00Z",
- resolved_at: null,
- ...overrides,
- };
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- wakeMock.mockResolvedValue(undefined);
-});
-
-describe("approveAction", () => {
- it("resolves approval, appends a user comment, and triggers wake-up", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
- resolveApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
- const out = await approveAction("ap-1", "looks good");
- expect(out).toEqual({ ok: true });
- expect(resolveApprovalMock).toHaveBeenCalledWith(
- "ap-1",
- "approved",
- expect.objectContaining({
- decision_note: "looks good",
- decided_by_kind: "user",
- }),
- );
- expect(appendCommentMock).toHaveBeenCalledWith(
- expect.objectContaining({
- approval_id: "ap-1",
- author_kind: "user",
- body: "looks good",
- }),
- );
- expect(wakeMock).toHaveBeenCalled();
- expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
- });
-
- it("defaults comment body to 'Approved.' when no note given", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
- resolveApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
- await approveAction("ap-1");
- expect(appendCommentMock).toHaveBeenCalledWith(
- expect.objectContaining({ body: "Approved." }),
- );
- });
-
- it("returns ok:false when the approval is missing", async () => {
- getApprovalMock.mockReturnValue(null);
- const out = await approveAction("missing");
- expect(out).toEqual({ ok: false, error: "Approval not found." });
- expect(resolveApprovalMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when the approval is already resolved", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
- const out = await approveAction("ap-1");
- expect(out).toEqual({ ok: false, error: "Approval is already approved." });
- expect(resolveApprovalMock).not.toHaveBeenCalled();
- });
-});
-
-describe("rejectAction", () => {
- it("resolves approval to rejected with note and triggers wake-up", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
- resolveApprovalMock.mockReturnValue(makeApproval({ status: "rejected" }));
- const out = await rejectAction("ap-1", "too risky");
- expect(out).toEqual({ ok: true });
- expect(resolveApprovalMock).toHaveBeenCalledWith(
- "ap-1",
- "rejected",
- expect.objectContaining({
- decision_note: "too risky",
- decided_by_kind: "user",
- }),
- );
- expect(wakeMock).toHaveBeenCalled();
- });
-
- it("defaults comment body to 'Rejected.' when no note", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
- resolveApprovalMock.mockReturnValue(makeApproval({ status: "rejected" }));
- await rejectAction("ap-1");
- expect(appendCommentMock).toHaveBeenCalledWith(
- expect.objectContaining({ body: "Rejected." }),
- );
- });
-});
-
-describe("requestRevisionAction", () => {
- it("requires a non-empty note", async () => {
- const out = await requestRevisionAction("ap-1", " ");
- expect(out.ok).toBe(false);
- expect(out.error).toMatch(/note is required/);
- expect(requestApprovalRevisionMock).not.toHaveBeenCalled();
- });
-
- it("transitions pending → revision_requested with the note", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "pending" }));
- requestApprovalRevisionMock.mockReturnValue(
- makeApproval({ status: "revision_requested" }),
- );
- const out = await requestRevisionAction("ap-1", "shrink scope");
- expect(out).toEqual({ ok: true });
- expect(requestApprovalRevisionMock).toHaveBeenCalledWith("ap-1", {
- decision_note: "shrink scope",
- decided_by_kind: "user",
- });
- expect(appendCommentMock).toHaveBeenCalledWith(
- expect.objectContaining({ body: "shrink scope" }),
- );
- expect(wakeMock).toHaveBeenCalled();
- });
-
- it("refuses revision on a non-pending row", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
- const out = await requestRevisionAction("ap-1", "x");
- expect(out.ok).toBe(false);
- expect(out.error).toMatch(/pending/);
- });
-});
-
-describe("addApprovalCommentAction", () => {
- it("appends a user comment when the approval exists", async () => {
- getApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));
- const out = await addApprovalCommentAction("ap-1", "fyi");
- expect(out.ok).toBe(true);
- expect(appendCommentMock).toHaveBeenCalledWith(
- expect.objectContaining({
- approval_id: "ap-1",
- author_kind: "user",
- body: "fyi",
- }),
- );
- });
-
- it("rejects empty bodies", async () => {
- const out = await addApprovalCommentAction("ap-1", " ");
- expect(out.ok).toBe(false);
- expect(appendCommentMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when approval is missing", async () => {
- getApprovalMock.mockReturnValue(null);
- const out = await addApprovalCommentAction("ap-1", "hi");
- expect(out.ok).toBe(false);
- });
-});
-
-describe("createPolicyAction + deletePolicyAction", () => {
- it("create returns the policy id when DB returns one", async () => {
- createPolicyMock.mockReturnValue({ id: "pol-1" });
- const out = await createPolicyAction({
- project_slug: "demo",
- action_type: "spend",
- auto_decision: "approve",
- max_cost_usd: 50,
- });
- expect(out).toEqual({ ok: true, policy_id: "pol-1" });
- expect(createPolicyMock).toHaveBeenCalledWith(
- expect.objectContaining({
- project_slug: "demo",
- action_type: "spend",
- max_cost_usd: 50,
- auto_decision: "approve",
- created_by_kind: "user",
- }),
- );
- });
-
- it("create validates inputs", async () => {
- // @ts-expect-error invalid on purpose
- const out = await createPolicyAction({ project_slug: "", action_type: "" });
- expect(out.ok).toBe(false);
- });
-
- it("delete returns ok:true on success and ok:false on missing", async () => {
- deletePolicyMock.mockReturnValueOnce(true);
- expect(await deletePolicyAction("pol-1")).toEqual({ ok: true });
- deletePolicyMock.mockReturnValueOnce(false);
- const out = await deletePolicyAction("missing");
- expect(out.ok).toBe(false);
- });
-});
diff --git a/notfair-cmo/src/server/actions/approvals.ts b/notfair-cmo/src/server/actions/approvals.ts
deleted file mode 100644
index 25d2bd46..00000000
--- a/notfair-cmo/src/server/actions/approvals.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-"use server";
-
-import { revalidatePath } from "next/cache";
-import {
- appendComment,
- createPolicy,
- deletePolicy,
- getApproval,
- requestApprovalRevision,
- resolveApproval,
-} from "@/server/db/approvals";
-import { wakeTaskOnApprovalResolution } from "@/server/orchestration/approval-wakeup";
-import type { ApprovalType } from "@/types";
-
-export type ActionResult = { ok: boolean; error?: string };
-
-/**
- * Centralized "decide and wake" path for human-driven approvals. Resolves
- * the row, posts a comment trail (so the inbox shows the decision), and
- * kicks the task wake-up fire-and-forget so the agent picks up the
- * decision on its next turn.
- */
-async function decideApproval(
- id: string,
- status: "approved" | "rejected",
- options: { decision_note?: string; decided_by_id?: string } = {},
-): Promise<ActionResult> {
- const before = getApproval(id);
- if (!before) return { ok: false, error: "Approval not found." };
- if (before.status !== "pending" && before.status !== "revision_requested") {
- return { ok: false, error: `Approval is already ${before.status}.` };
- }
-
- const after = resolveApproval(id, status, {
- decision_note: options.decision_note ?? null,
- decided_by_kind: "user",
- decided_by_id: options.decided_by_id ?? null,
- });
- if (!after) return { ok: false, error: "Approval row vanished." };
-
- appendComment({
- approval_id: id,
- author_kind: "user",
- author_id: options.decided_by_id ?? null,
- body:
- options.decision_note?.trim() ||
- (status === "approved" ? "Approved." : "Rejected."),
- });
-
- // Fire-and-forget wake-up so the form post returns instantly.
- void wakeTaskOnApprovalResolution(after).catch((err) => {
- console.error("[approve-action] wake-up failed:", err);
- });
-
- revalidatePath("/", "layout");
- return { ok: true };
-}
-
-export async function approveAction(
- id: string,
- decision_note?: string,
-): Promise<ActionResult> {
- return decideApproval(id, "approved", { decision_note });
-}
-
-export async function rejectAction(
- id: string,
- decision_note?: string,
-): Promise<ActionResult> {
- return decideApproval(id, "rejected", { decision_note });
-}
-
-/**
- * Push back on the agent with a comment + revision_requested status. The
- * agent's next turn sees the feedback and is expected to emit a fresh
- * <request_approval> with a refined plan.
- */
-export async function requestRevisionAction(
- id: string,
- decision_note: string,
-): Promise<ActionResult> {
- if (!decision_note.trim()) {
- return { ok: false, error: "A note is required when requesting revision." };
- }
- const before = getApproval(id);
- if (!before) return { ok: false, error: "Approval not found." };
- if (before.status !== "pending") {
- return {
- ok: false,
- error: `Can only request revision on a pending approval (got ${before.status}).`,
- };
- }
- const after = requestApprovalRevision(id, {
- decision_note,
- decided_by_kind: "user",
- });
- if (!after) return { ok: false, error: "Revision request failed." };
-
- appendComment({
- approval_id: id,
- author_kind: "user",
- body: decision_note,
- });
-
- void wakeTaskOnApprovalResolution(after).catch((err) => {
- console.error("[request-revision-action] wake-up failed:", err);
- });
-
- revalidatePath("/", "layout");
- return { ok: true };
-}
-
-/** Free-form comment without changing the approval status. */
-export async function addApprovalCommentAction(
- id: string,
- body: string,
-): Promise<ActionResult> {
- const trimmed = body.trim();
- if (!trimmed) return { ok: false, error: "Comment cannot be empty." };
- const approval = getApproval(id);
- if (!approval) return { ok: false, error: "Approval not found." };
-
- appendComment({
- approval_id: id,
- author_kind: "user",
- body: trimmed,
- });
- revalidatePath("/", "layout");
- return { ok: true };
-}
-
-export type CreatePolicyActionInput = {
- project_slug: string;
- action_type: ApprovalType;
- agent_id?: string | null;
- max_cost_usd?: number | null;
- auto_decision: "approve" | "reject";
- note?: string | null;
-};
-
-export async function createPolicyAction(
- input: CreatePolicyActionInput,
-): Promise<ActionResult & { policy_id?: string }> {
- if (!input.project_slug || !input.action_type) {
- return { ok: false, error: "project_slug and action_type are required." };
- }
- const policy = createPolicy({
- project_slug: input.project_slug,
- action_type: input.action_type,
- agent_id: input.agent_id ?? null,
- max_cost_usd: input.max_cost_usd ?? null,
- auto_decision: input.auto_decision,
- note: input.note ?? null,
- created_by_kind: "user",
- });
- revalidatePath("/", "layout");
- return { ok: true, policy_id: policy.id };
-}
-
-export async function deletePolicyAction(id: string): Promise<ActionResult> {
- const ok = deletePolicy(id);
- if (!ok) return { ok: false, error: "Policy not found." };
- revalidatePath("/", "layout");
- return { ok: true };
-}
diff --git a/notfair-cmo/src/server/actions/cron-runs.ts b/notfair-cmo/src/server/actions/cron-runs.ts
deleted file mode 100644
index da721d55..00000000
--- a/notfair-cmo/src/server/actions/cron-runs.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-"use server";
-
-import { loadCronRuns, tickAtOrBefore, type CronRun, type CronSchedule } from "@/server/scheduler/display";
-
-export type CronRunWithTick = CronRun & {
- /**
- * The scheduled tick (ms epoch) this run belongs to. Computed by walking the
- * cron schedule backwards from `runAtMs` and taking the most recent tick at
- * or before it. Lets the UI match a run to the calendar occurrence the user
- * clicked, regardless of how late the scheduler fired.
- */
- owning_occurrence_at_ms?: number;
-};
-
-export type ScheduleInput = CronSchedule;
-
-export type GetCronRunsResult =
- | { ok: true; runs: CronRunWithTick[] }
- | { ok: false; error: string };
-
-export async function getCronRunsAction(
- cron_id: string,
- schedule: ScheduleInput | null,
- limit = 100,
-): Promise<GetCronRunsResult> {
- try {
- const raw = loadCronRuns(cron_id, limit);
- const enriched: CronRunWithTick[] = raw.map((r) => ({
- ...r,
- owning_occurrence_at_ms: schedule
- ? tickAtOrBefore(schedule, r.run_at_ms)
- : undefined,
- }));
- return { ok: true, runs: enriched };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
diff --git a/notfair-cmo/src/server/actions/crons.ts b/notfair-cmo/src/server/actions/crons.ts
deleted file mode 100644
index 1548dd91..00000000
--- a/notfair-cmo/src/server/actions/crons.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-"use server";
-
-import { revalidatePath } from "next/cache";
-import {
- createCron,
- disableCron,
- enableCron,
- invalidateCronCache,
- removeCron,
-} from "@/server/scheduler/display";
-import { getDb } from "@/server/db/db";
-import { type AgentTemplate } from "@/server/agent-templates";
-import { listProjectAgents } from "@/server/agent-meta";
-import { slugify } from "@/lib/slug";
-import { logAgentAction } from "@/server/db/agent-actions";
-
-export type ScheduleCronInput = {
- project_slug: string;
- specialist: AgentTemplate["key"];
- name: string;
- schedule_kind: "cron";
- schedule_value: string;
- tz?: string;
- brief: string;
-};
-
-export type ScheduleCronResult =
- | { ok: true; cron_id: string; cron_name: string }
- | { ok: false; error: string };
-
-export async function scheduleCronAction(input: ScheduleCronInput): Promise<ScheduleCronResult> {
- const nameSlug = slugify(input.name);
- if (!nameSlug.ok) return { ok: false, error: `Invalid name: ${nameSlug.reason}` };
-
- const briefTrimmed = input.brief.trim();
- if (!briefTrimmed) return { ok: false, error: "Brief is required." };
-
- const scheduleValueTrimmed = input.schedule_value.trim();
- if (!scheduleValueTrimmed) return { ok: false, error: "Schedule is required." };
-
- // Look up the agent's actual id/slug from the project — agent_ids now
- // encode the personal name (e.g. `demo3-cmo-greg`) so we can't
- // synthesize them from the template key alone.
- const projectAgents = await listProjectAgents(input.project_slug);
- const target = projectAgents.find((a) => a.template_key === input.specialist);
- if (!target) {
- return {
- ok: false,
- error: `No '${input.specialist}' agent found in project ${input.project_slug}.`,
- };
- }
- const agent_slug = target.slug;
- const agent_full_id = target.agent_id;
-
- try {
- const result = await createCron({
- project_slug: input.project_slug,
- agent_slug,
- agent_full_id,
- cron_name: nameSlug.slug,
- schedule: { kind: "cron", expr: scheduleValueTrimmed, tz: input.tz },
- message: briefTrimmed,
- });
- logAgentAction({
- project_slug: input.project_slug,
- agent_id: agent_full_id,
- action_type: "cron_created",
- summary: `Scheduled '${nameSlug.slug}' (${input.schedule_kind} ${scheduleValueTrimmed})`,
- payload: { cron_id: result.id, cron_name: result.name, brief: briefTrimmed },
- });
- revalidatePath("/", "layout");
- revalidatePath("/", "layout");
- return { ok: true, cron_id: result.id, cron_name: result.name };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
-export async function pauseCronAction(id: string): Promise<{ ok: boolean; error?: string }> {
- try {
- await disableCron(id);
- revalidatePath("/", "layout");
- return { ok: true };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
-export async function resumeCronAction(id: string): Promise<{ ok: boolean; error?: string }> {
- try {
- await enableCron(id);
- revalidatePath("/", "layout");
- return { ok: true };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
-export async function deleteCronAction(id: string): Promise<{ ok: boolean; error?: string }> {
- try {
- await removeCron(id);
- revalidatePath("/", "layout");
- return { ok: true };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
-export async function updateCronPromptAction(
- id: string,
- message: string,
-): Promise<{ ok: boolean; error?: string }> {
- const trimmed = message.trim();
- if (!trimmed) return { ok: false, error: "Prompt cannot be empty." };
- try {
- getDb()
- .prepare("UPDATE scheduled_jobs SET message = ?, updated_at = ? WHERE id = ?")
- .run(trimmed, new Date().toISOString(), id);
- invalidateCronCache();
- revalidatePath("/", "layout");
- return { ok: true };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
diff --git a/notfair-cmo/src/server/actions/questions.ts b/notfair-cmo/src/server/actions/questions.ts
deleted file mode 100644
index bb135610..00000000
--- a/notfair-cmo/src/server/actions/questions.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-"use server";
-
-import { revalidatePath } from "next/cache";
-import {
- answerQuestion,
- cancelQuestion,
- getQuestion,
- parseQuestionOptions,
-} from "@/server/db/questions";
-import { wakeTaskOnQuestionResolution } from "@/server/orchestration/question-wakeup";
-
-export type QuestionActionResult = { ok: boolean; error?: string };
-
-export type AnswerQuestionInput = {
- /** Zero-based index into the original options[]. Null = no option chosen. */
- option_index?: number | null;
- /** Free-text answer alongside / instead of an option. Null = no comment. */
- text?: string | null;
-};
-
-/**
- * Answer the user's open question. Validates the option index against the
- * stored options[], writes the answer, then fires the wake-up
- * fire-and-forget so the agent picks it up on its next turn.
- */
-export async function answerQuestionAction(
- id: string,
- input: AnswerQuestionInput,
-): Promise<QuestionActionResult> {
- const before = getQuestion(id);
- if (!before) return { ok: false, error: "Question not found." };
- if (before.status !== "pending") {
- return { ok: false, error: `Question is already ${before.status}.` };
- }
-
- const trimmedText = input.text?.trim() || null;
- let optionIndex: number | null = null;
- if (input.option_index != null) {
- const options = parseQuestionOptions(before);
- if (
- !Number.isInteger(input.option_index) ||
- input.option_index < 0 ||
- input.option_index >= options.length
- ) {
- return { ok: false, error: "Selected option is out of range." };
- }
- optionIndex = input.option_index;
- }
-
- if (optionIndex == null && !trimmedText) {
- return {
- ok: false,
- error: "Pick an option or type an answer.",
- };
- }
-
- const after = answerQuestion({
- id,
- answer_option_index: optionIndex,
- answer_text: trimmedText,
- });
- if (!after) return { ok: false, error: "Question row vanished." };
-
- void wakeTaskOnQuestionResolution(after).catch((err) => {
- console.error("[answer-question-action] wake-up failed:", err);
- });
-
- revalidatePath("/", "layout");
- return { ok: true };
-}
-
-/**
- * Dismiss the question without delivering an answer. The task STAYS
- * blocked — the user opted out of resolving here, so the agent is not
- * woken. The agent / user can take the next step manually (cancel the
- * task, re-ask, etc.).
- */
-export async function cancelQuestionAction(
- id: string,
-): Promise<QuestionActionResult> {
- const before = getQuestion(id);
- if (!before) return { ok: false, error: "Question not found." };
- if (before.status !== "pending") {
- return { ok: false, error: `Question is already ${before.status}.` };
- }
- const after = cancelQuestion(id);
- if (!after) return { ok: false, error: "Question row vanished." };
- revalidatePath("/", "layout");
- return { ok: true };
-}
diff --git a/notfair-cmo/src/server/actions/tasks.test.ts b/notfair-cmo/src/server/actions/tasks.test.ts
deleted file mode 100644
index 220dc09a..00000000
--- a/notfair-cmo/src/server/actions/tasks.test.ts
+++ /dev/null
@@ -1,261 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { Project, Task } from "@/types";
-
-const revalidatePathMock = vi.fn();
-vi.mock("next/cache", () => ({
- revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),
-}));
-
-const getActiveProjectMock = vi.fn();
-vi.mock("@/server/active-project", () => ({
- getActiveProject: () => getActiveProjectMock(),
-}));
-
-const claimProposedTaskMock = vi.fn();
-const getTaskMock = vi.fn();
-const listTasksByAgentMock = vi.fn();
-const updateTaskMock = vi.fn();
-vi.mock("@/server/db/tasks", () => ({
- claimProposedTask: (...a: unknown[]) => claimProposedTaskMock(...a),
- getTask: (...a: unknown[]) => getTaskMock(...a),
- listTasksByAgent: (...a: unknown[]) => listTasksByAgentMock(...a),
- updateTask: (...a: unknown[]) => updateTaskMock(...a),
-}));
-
-const runTaskKickoffServerSideMock = vi.fn();
-vi.mock("@/server/orchestration/run-task", () => ({
- runTaskKickoffServerSide: (...a: unknown[]) => runTaskKickoffServerSideMock(...a),
-}));
-
-import { cancelTaskAction, startAllProposedTasksAction } from "./tasks";
-
-function makeProject(overrides: Partial<Project> = {}): Project {
- return {
- id: "p-1",
- slug: "demo",
- display_name: "Demo",
- created_at: "2026-01-01T00:00:00.000Z",
- archived_at: null,
- google_ads_account_id: null,
- website_url: null,
- codebase_path: null,
- ...overrides,
- };
-}
-
-function makeTask(overrides: Partial<Task> = {}): Task {
- return {
- id: "task-1",
- display_id: "demo-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- title: "T",
- brief: "b",
- success_criteria: null,
- deadline_iso: null,
- status: "proposed",
- result_json: null,
- 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,
- };
-}
-
-describe("startAllProposedTasksAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- runTaskKickoffServerSideMock.mockResolvedValue(undefined);
- });
-
- it("returns ok:false when agentId is whitespace-only", async () => {
- const out = await startAllProposedTasksAction(" ");
- expect(out).toEqual({ ok: false, error: "agentId is required" });
- expect(getActiveProjectMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when no active project is set", async () => {
- getActiveProjectMock.mockResolvedValue(null);
- const out = await startAllProposedTasksAction("demo-google-ads");
- expect(out).toEqual({ ok: false, error: "No active project." });
- expect(listTasksByAgentMock).not.toHaveBeenCalled();
- });
-
- it("returns started=0 when the agent has no proposed tasks", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- listTasksByAgentMock.mockReturnValue([]);
- const out = await startAllProposedTasksAction("demo-google-ads");
- expect(out).toEqual({ ok: true, data: { started: 0, task_ids: [] } });
- expect(claimProposedTaskMock).not.toHaveBeenCalled();
- expect(revalidatePathMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when none of the proposed tasks belong to the active project (cookie drift guard)", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject({ slug: "demo" }));
- listTasksByAgentMock.mockReturnValue([
- makeTask({ id: "t-other", project_slug: "other-project" }),
- ]);
- const out = await startAllProposedTasksAction("demo-google-ads");
- expect(out.ok).toBe(false);
- if (out.ok) return;
- expect(out.error).toMatch(/no proposed tasks in the active project/);
- expect(claimProposedTaskMock).not.toHaveBeenCalled();
- });
-
- it("claims every valid task atomically and fires kickoffs in the background", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- const t1 = makeTask({ id: "t1" });
- const t2 = makeTask({ id: "t2" });
- listTasksByAgentMock.mockReturnValue([t1, t2]);
- claimProposedTaskMock.mockImplementation((id: string) => {
- if (id === "t1") return { ...t1, status: "working" };
- if (id === "t2") return { ...t2, status: "working" };
- return null;
- });
-
- const out = await startAllProposedTasksAction("demo-google-ads");
- expect(out.ok).toBe(true);
- if (!out.ok) return;
- expect(out.data.started).toBe(2);
- expect(out.data.task_ids.sort()).toEqual(["t1", "t2"]);
- expect(claimProposedTaskMock).toHaveBeenCalledTimes(2);
-
- // Let fire-and-forget kickoffs schedule.
- await new Promise((r) => setImmediate(r));
- expect(runTaskKickoffServerSideMock).toHaveBeenCalledTimes(2);
- expect(revalidatePathMock).toHaveBeenCalledWith("/agents", "layout");
- expect(revalidatePathMock).toHaveBeenCalledWith("/tasks", "layout");
- });
-
- it("silently skips tasks whose claim fails (race already-running/terminal)", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- const t1 = makeTask({ id: "t1" });
- const t2 = makeTask({ id: "t2" });
- listTasksByAgentMock.mockReturnValue([t1, t2]);
- claimProposedTaskMock.mockImplementation((id: string) => {
- if (id === "t1") return { ...t1, status: "working" };
- return null;
- });
-
- const out = await startAllProposedTasksAction("demo-google-ads");
- expect(out.ok).toBe(true);
- if (!out.ok) return;
- expect(out.data.started).toBe(1);
- expect(out.data.task_ids).toEqual(["t1"]);
-
- await new Promise((r) => setImmediate(r));
- expect(runTaskKickoffServerSideMock).toHaveBeenCalledTimes(1);
- });
-
- it("filters tasks belonging to other projects before claiming", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject({ slug: "demo" }));
- const tMine = makeTask({ id: "t-mine", project_slug: "demo" });
- const tOther = makeTask({ id: "t-other", project_slug: "other" });
- listTasksByAgentMock.mockReturnValue([tMine, tOther]);
- claimProposedTaskMock.mockReturnValue({ ...tMine, status: "working" });
-
- const out = await startAllProposedTasksAction("demo-google-ads");
- expect(out.ok).toBe(true);
- expect(claimProposedTaskMock).toHaveBeenCalledTimes(1);
- expect(claimProposedTaskMock).toHaveBeenCalledWith("t-mine");
- });
-
- it("logs but does not rethrow when a background kickoff rejects", async () => {
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- getActiveProjectMock.mockResolvedValue(makeProject());
- const t = makeTask({ id: "t1" });
- listTasksByAgentMock.mockReturnValue([t]);
- claimProposedTaskMock.mockReturnValue({ ...t, status: "working" });
- runTaskKickoffServerSideMock.mockRejectedValue(new Error("kickoff boom"));
-
- const out = await startAllProposedTasksAction("demo-google-ads");
- expect(out.ok).toBe(true);
-
- // Drain microtasks twice to let the rejection propagate to .catch.
- await new Promise((r) => setImmediate(r));
- await new Promise((r) => setImmediate(r));
- expect(errSpy).toHaveBeenCalledWith(
- expect.stringContaining("[start-all] kickoff failed for t1:"),
- expect.any(Error),
- );
- errSpy.mockRestore();
- });
-
- it("passes the agentId and status='proposed' filter to listTasksByAgent", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- listTasksByAgentMock.mockReturnValue([]);
- await startAllProposedTasksAction("demo-google-ads");
- expect(listTasksByAgentMock).toHaveBeenCalledWith("demo-google-ads", "proposed");
- });
-});
-
-describe("cancelTaskAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("returns ok:false when no active project is set", async () => {
- getActiveProjectMock.mockResolvedValue(null);
- const out = await cancelTaskAction("demo-1");
- expect(out).toEqual({ ok: false, error: "No active project." });
- expect(getTaskMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when the task is not found", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- getTaskMock.mockReturnValue(null);
- const out = await cancelTaskAction("demo-1");
- expect(out).toEqual({ ok: false, error: "Task not found." });
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("returns ok:false when the task belongs to a different project (active-project mismatch)", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject({ slug: "demo" }));
- getTaskMock.mockReturnValue(makeTask({ project_slug: "other" }));
- const out = await cancelTaskAction("other-1");
- expect(out).toEqual({ ok: false, error: "Task isn't in the active project." });
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it.each(["done", "failed", "cancelled"] as const)(
- "returns ok:false when the task is already %s",
- async (status) => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- getTaskMock.mockReturnValue(makeTask({ status }));
- const out = await cancelTaskAction("demo-1");
- expect(out).toEqual({ ok: false, error: `Task is already ${status}.` });
- expect(updateTaskMock).not.toHaveBeenCalled();
- },
- );
-
- it.each(["proposed", "approved", "working"] as const)(
- "cancels the task when it is in non-terminal state %s",
- async (status) => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- getTaskMock.mockReturnValue(makeTask({ id: "task-1", status }));
- updateTaskMock.mockReturnValue(makeTask({ id: "task-1", status: "cancelled" }));
-
- const out = await cancelTaskAction("demo-1");
- expect(out).toEqual({ ok: true });
- expect(updateTaskMock).toHaveBeenCalledWith("task-1", {
- status: "cancelled",
- error_message: "Cancelled by user",
- });
- expect(revalidatePathMock).toHaveBeenCalledWith("/agents", "layout");
- expect(revalidatePathMock).toHaveBeenCalledWith("/tasks", "layout");
- },
- );
-
- it("accepts a display_id and forwards it to getTask", async () => {
- getActiveProjectMock.mockResolvedValue(makeProject());
- getTaskMock.mockReturnValue(makeTask({ id: "uuid-xyz", status: "working" }));
- await cancelTaskAction("demo-7");
- expect(getTaskMock).toHaveBeenCalledWith("demo-7");
- // updateTask is keyed by the row PK, not the display_id input.
- expect(updateTaskMock).toHaveBeenCalledWith("uuid-xyz", expect.any(Object));
- });
-});
diff --git a/notfair-cmo/src/server/actions/tasks.ts b/notfair-cmo/src/server/actions/tasks.ts
deleted file mode 100644
index 4880c31f..00000000
--- a/notfair-cmo/src/server/actions/tasks.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-"use server";
-
-import { revalidatePath } from "next/cache";
-
-import { getActiveProject } from "@/server/active-project";
-import { claimProposedTask, getTask, listTasksByAgent, updateTask } from "@/server/db/tasks";
-import { runTaskKickoffServerSide } from "@/server/orchestration/run-task";
-
-export type StartAllResult =
- | { ok: true; data: { started: number; task_ids: string[] } }
- | { ok: false; error: string };
-
-/**
- * Start all proposed tasks for an agent. Marks each as running, then fires
- * a server-side kickoff per task (fire-and-forget). The kickoffs run the
- * agent against each task in parallel using the shared OpenClaw gateway;
- * the action returns as soon as kickoffs are scheduled so the UI can
- * refresh without blocking on agent completion.
- *
- * Polling: the page is server-rendered, so the caller should run
- * router.refresh() periodically to see status flip from proposed →
- * running → succeeded as each kickoff finishes.
- */
-export async function startAllProposedTasksAction(
- agentId: string,
-): Promise<StartAllResult> {
- if (!agentId.trim()) return { ok: false, error: "agentId is required" };
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
-
- const proposed = listTasksByAgent(agentId, "proposed");
- if (proposed.length === 0) {
- return { ok: true, data: { started: 0, task_ids: [] } };
- }
-
- // Guard: every task we touch must belong to the active project. Defends
- // against the assignee belonging to a project the user no longer has
- // active (cookie drift).
- const validTasks = proposed.filter((t) => t.project_slug === project.slug);
- if (validTasks.length === 0) {
- return {
- ok: false,
- error: `Agent ${agentId} has no proposed tasks in the active project.`,
- };
- }
-
- // Atomic claim per task — conditional UPDATE so a task that raced into
- // running/terminal between the SELECT and now is silently skipped instead
- // of getting its terminal status overwritten with `running`.
- const claimedTasks = validTasks
- .map((t) => claimProposedTask(t.id))
- .filter((t): t is NonNullable<typeof t> => t !== null);
-
- // Fire-and-forget per claimed task. The server stays alive long enough to
- // drain each gateway stream because Node keeps event-loop work running
- // even after the action's response is sent. In production we'd want
- // `unstable_after` for stronger guarantees; V1 dev mode is fine.
- for (const task of claimedTasks) {
- void runTaskKickoffServerSide(task).catch((err) =>
- console.error(`[start-all] kickoff failed for ${task.id}:`, err),
- );
- }
-
- revalidatePath(`/agents`, "layout");
- revalidatePath(`/tasks`, "layout");
- return {
- ok: true,
- data: { started: claimedTasks.length, task_ids: claimedTasks.map((t) => t.id) },
- };
-}
-
-export type CancelTaskResult =
- | { ok: true }
- | { ok: false; error: string };
-
-/**
- * Mark a task as cancelled. The agent run on OpenClaw is fire-and-forget
- * and may still complete in the background; processOrchestrationBlocks
- * guards against overwriting a terminal status, so a late "done" from
- * the agent won't flip cancelled → succeeded. Accepts either the PK
- * UUID or the display_id (`<slug>-<n>`).
- */
-export async function cancelTaskAction(
- idOrDisplayId: string,
-): Promise<CancelTaskResult> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
- const task = getTask(idOrDisplayId);
- if (!task) return { ok: false, error: "Task not found." };
- if (task.project_slug !== project.slug) {
- return { ok: false, error: "Task isn't in the active project." };
- }
- if (
- task.status === "done" ||
- task.status === "failed" ||
- task.status === "cancelled"
- ) {
- return { ok: false, error: `Task is already ${task.status}.` };
- }
- updateTask(task.id, {
- status: "cancelled",
- error_message: "Cancelled by user",
- });
- revalidatePath(`/agents`, "layout");
- revalidatePath(`/tasks`, "layout");
- return { ok: true };
-}
-
-export type SimpleTaskActionResult =
- | { ok: true }
- | { ok: false; error: string };
-
-/**
- * Resume a task that the agent abandoned (turn ended without a
- * submit_task_status call, so we parked it in `blocked`). Flips the
- * task back to `proposed` and re-fires the kickoff so the agent picks
- * up where it left off — its prior transcript stays intact.
- *
- * Safe to call repeatedly: only succeeds when the task is currently
- * `blocked` and not gated on an approval / question / upstream task.
- */
-export async function resumeBlockedTaskAction(
- idOrDisplayId: string,
-): Promise<SimpleTaskActionResult> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
- const task = getTask(idOrDisplayId);
- if (!task) return { ok: false, error: "Task not found." };
- if (task.project_slug !== project.slug) {
- return { ok: false, error: "Task isn't in the active project." };
- }
- if (task.status !== "blocked") {
- return { ok: false, error: `Task isn't blocked (it's ${task.status}).` };
- }
- if (task.blocked_by_task_id) {
- return {
- ok: false,
- error: "Task is blocked on an upstream task; resolve that first.",
- };
- }
- // Flip back to `proposed` and re-kickoff via the same path the
- // initial kickoff used. The kickoff function atomically claims the
- // task so concurrent clicks are safe.
- updateTask(task.id, { status: "proposed", error_message: null });
- const reread = getTask(task.id);
- if (reread) {
- const { startTaskIfProposed } = await import("@/server/orchestration/run-task");
- startTaskIfProposed(reread);
- }
- revalidatePath(`/agents`, "layout");
- revalidatePath(`/tasks`, "layout");
- return { ok: true };
-}
-
-/**
- * Manually mark a task as done. For the abandoned-task case where the
- * agent finished its work but never called submit_task_status — the
- * user is closing it on the agent's behalf.
- */
-export async function markTaskDoneAction(
- idOrDisplayId: string,
-): Promise<SimpleTaskActionResult> {
- const project = await getActiveProject();
- if (!project) return { ok: false, error: "No active project." };
- const task = getTask(idOrDisplayId);
- if (!task) return { ok: false, error: "Task not found." };
- if (task.project_slug !== project.slug) {
- return { ok: false, error: "Task isn't in the active project." };
- }
- if (task.status === "done" || task.status === "failed" || task.status === "cancelled") {
- return { ok: false, error: `Task is already ${task.status}.` };
- }
- updateTask(task.id, {
- status: "done",
- error_message: null,
- });
- revalidatePath(`/agents`, "layout");
- revalidatePath(`/tasks`, "layout");
- return { ok: true };
-}
diff --git a/notfair-cmo/src/server/active-project.test.ts b/notfair-cmo/src/server/active-project.test.ts
deleted file mode 100644
index c7662135..00000000
--- a/notfair-cmo/src/server/active-project.test.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { Project } from "@/types";
-
-// ── Mocks ──────────────────────────────────────────────────────────
-
-const cookieGetMock = vi.fn();
-const cookieSetMock = vi.fn();
-const cookieDeleteMock = vi.fn();
-
-vi.mock("next/headers", () => ({
- cookies: async () => ({
- get: (...args: unknown[]) => cookieGetMock(...args),
- set: (...args: unknown[]) => cookieSetMock(...args),
- delete: (...args: unknown[]) => cookieDeleteMock(...args),
- }),
-}));
-
-const getProjectMock = vi.fn();
-const listProjectsMock = vi.fn();
-vi.mock("./db/projects", () => ({
- getProject: (...args: unknown[]) => getProjectMock(...args),
- listProjects: (...args: unknown[]) => listProjectsMock(...args),
-}));
-
-import {
- clearActiveProject,
- getActiveProject,
- setActiveProject,
-} from "./active-project";
-
-// ── Fixtures ───────────────────────────────────────────────────────
-
-function makeProject(overrides: Partial<Project> = {}): Project {
- return {
- id: "uuid",
- slug: "acme",
- display_name: "Acme",
- created_at: "now",
- archived_at: null,
- google_ads_account_id: null,
- website_url: null,
- codebase_path: null,
- ...overrides,
- };
-}
-
-// ── Tests ──────────────────────────────────────────────────────────
-
-describe("getActiveProject", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("returns the cookie-pinned project when it exists and is not archived", async () => {
- cookieGetMock.mockReturnValueOnce({ value: "acme" });
- const acme = makeProject({ slug: "acme" });
- getProjectMock.mockReturnValueOnce(acme);
-
- const r = await getActiveProject();
- expect(r).toEqual(acme);
- expect(getProjectMock).toHaveBeenCalledWith("acme");
- expect(listProjectsMock).not.toHaveBeenCalled();
- });
-
- it("falls back to first listProjects result when cookie absent", async () => {
- cookieGetMock.mockReturnValueOnce(undefined);
- const first = makeProject({ slug: "first" });
- listProjectsMock.mockReturnValueOnce([first, makeProject({ slug: "other" })]);
-
- const r = await getActiveProject();
- expect(r).toEqual(first);
- expect(getProjectMock).not.toHaveBeenCalled();
- });
-
- it("falls back when cookie present but project no longer exists", async () => {
- cookieGetMock.mockReturnValueOnce({ value: "ghost" });
- getProjectMock.mockReturnValueOnce(null);
- const fallback = makeProject({ slug: "fallback" });
- listProjectsMock.mockReturnValueOnce([fallback]);
-
- const r = await getActiveProject();
- expect(r).toEqual(fallback);
- });
-
- it("falls back when cookie-pinned project is archived", async () => {
- cookieGetMock.mockReturnValueOnce({ value: "old" });
- const archived = makeProject({
- slug: "old",
- archived_at: "2025-01-01T00:00:00Z",
- });
- getProjectMock.mockReturnValueOnce(archived);
- const fallback = makeProject({ slug: "fresh" });
- listProjectsMock.mockReturnValueOnce([fallback]);
-
- const r = await getActiveProject();
- expect(r).toEqual(fallback);
- });
-
- it("returns null when cookie absent and no projects exist", async () => {
- cookieGetMock.mockReturnValueOnce(undefined);
- listProjectsMock.mockReturnValueOnce([]);
-
- const r = await getActiveProject();
- expect(r).toBeNull();
- });
-
- it("returns null when cookie present but no projects exist", async () => {
- cookieGetMock.mockReturnValueOnce({ value: "ghost" });
- getProjectMock.mockReturnValueOnce(null);
- listProjectsMock.mockReturnValueOnce([]);
-
- const r = await getActiveProject();
- expect(r).toBeNull();
- });
-});
-
-describe("setActiveProject", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("writes the cookie with the notfair_active_project name and httpOnly options", async () => {
- await setActiveProject("acme");
- expect(cookieSetMock).toHaveBeenCalledTimes(1);
- const [name, value, opts] = cookieSetMock.mock.calls[0]!;
- expect(name).toBe("notfair_active_project");
- expect(value).toBe("acme");
- expect(opts).toMatchObject({
- httpOnly: true,
- sameSite: "lax",
- path: "/",
- });
- expect(opts.maxAge).toBeGreaterThan(0);
- });
-
- it("persists the maxAge as one year in seconds", async () => {
- await setActiveProject("acme");
- const [, , opts] = cookieSetMock.mock.calls[0]!;
- expect(opts.maxAge).toBe(60 * 60 * 24 * 365);
- });
-
- it("accepts a different slug verbatim", async () => {
- await setActiveProject("acme-q4");
- const [, value] = cookieSetMock.mock.calls[0]!;
- expect(value).toBe("acme-q4");
- });
-});
-
-describe("clearActiveProject", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("deletes the notfair_active_project cookie", async () => {
- await clearActiveProject();
- expect(cookieDeleteMock).toHaveBeenCalledWith("notfair_active_project");
- });
-});
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/mcp.test.ts b/notfair-cmo/src/server/adapters/claude-code-local/mcp.test.ts
deleted file mode 100644
index 366876df..00000000
--- a/notfair-cmo/src/server/adapters/claude-code-local/mcp.test.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-interface FsState {
- files: Map<string, string>;
- dirs: Set<string>;
-}
-const fsState: FsState = { files: new Map(), dirs: new Set() };
-
-vi.mock("node:fs", () => ({
- existsSync: (p: string) => fsState.files.has(p),
-}));
-
-vi.mock("node:fs/promises", () => ({
- mkdir: async (p: string) => {
- fsState.dirs.add(p);
- },
- readFile: async (p: string) => {
- const v = fsState.files.get(p);
- if (v === undefined) throw new Error(`ENOENT: ${p}`);
- return v;
- },
- writeFile: async (p: string, content: string) => {
- fsState.files.set(p, content);
- },
-}));
-
-beforeEach(() => {
- fsState.files.clear();
- fsState.dirs.clear();
-});
-
-afterEach(() => {
- // nothing
-});
-
-import { registerClaudeCodeMcp, unregisterClaudeCodeMcp } from "./mcp";
-import type { McpRegistrationSpec } from "../types";
-
-const WORKSPACE = "/workspace/agent";
-
-function makeHttpSpec(
- overrides: Partial<McpRegistrationSpec> = {},
-): McpRegistrationSpec {
- return {
- serverName: "notfair-orchestration",
- agentId: "acme-cmo-greg",
- projectSlug: "acme",
- transport: {
- type: "http",
- url: "http://127.0.0.1:3326/api/mcp/orchestration",
- headers: { Authorization: "Bearer s3cret" },
- },
- ...overrides,
- };
-}
-
-describe("registerClaudeCodeMcp (http)", () => {
- it("writes .mcp.json with url + headers carrying the bearer", async () => {
- await registerClaudeCodeMcp(WORKSPACE, makeHttpSpec());
- const raw = fsState.files.get("/workspace/agent/.mcp.json");
- expect(raw).toBeDefined();
- const cfg = JSON.parse(raw!);
- expect(cfg.mcpServers["notfair-orchestration"]).toEqual({
- type: "http",
- url: "http://127.0.0.1:3326/api/mcp/orchestration",
- headers: { Authorization: "Bearer s3cret" },
- });
- });
-
- it("re-registering the same server replaces, doesn't duplicate", async () => {
- await registerClaudeCodeMcp(WORKSPACE, makeHttpSpec());
- await registerClaudeCodeMcp(
- WORKSPACE,
- makeHttpSpec({
- transport: {
- type: "http",
- url: "http://127.0.0.1:3326/api/mcp/orchestration",
- headers: { Authorization: "Bearer rotated" },
- },
- }),
- );
- const cfg = JSON.parse(
- fsState.files.get("/workspace/agent/.mcp.json") ?? "{}",
- );
- expect(Object.keys(cfg.mcpServers)).toHaveLength(1);
- expect(cfg.mcpServers["notfair-orchestration"].headers.Authorization).toBe(
- "Bearer rotated",
- );
- });
-
- it("preserves other servers when adding a new one", async () => {
- fsState.files.set(
- "/workspace/agent/.mcp.json",
- JSON.stringify({
- mcpServers: {
- existing: { type: "stdio", command: "node", args: ["x.js"] },
- },
- }),
- );
- await registerClaudeCodeMcp(WORKSPACE, makeHttpSpec());
- const cfg = JSON.parse(
- fsState.files.get("/workspace/agent/.mcp.json") ?? "{}",
- );
- expect(Object.keys(cfg.mcpServers).sort()).toEqual([
- "existing",
- "notfair-orchestration",
- ]);
- });
-});
-
-describe("registerClaudeCodeMcp (stdio)", () => {
- it("emits a stdio server with command, args, env", async () => {
- await registerClaudeCodeMcp(WORKSPACE, {
- serverName: "stdio-thing",
- agentId: "acme-cmo-greg",
- projectSlug: "acme",
- transport: {
- type: "stdio",
- command: "node",
- args: ["server.js"],
- env: { KEY: "v" },
- },
- });
- const cfg = JSON.parse(
- fsState.files.get("/workspace/agent/.mcp.json") ?? "{}",
- );
- expect(cfg.mcpServers["stdio-thing"]).toEqual({
- type: "stdio",
- command: "node",
- args: ["server.js"],
- env: { KEY: "v" },
- });
- });
-});
-
-describe("unregisterClaudeCodeMcp", () => {
- it("drops the named server but leaves others", async () => {
- await registerClaudeCodeMcp(WORKSPACE, makeHttpSpec());
- await registerClaudeCodeMcp(WORKSPACE, {
- serverName: "other",
- agentId: "acme-cmo-greg",
- projectSlug: "acme",
- transport: { type: "stdio", command: "x", args: [] },
- });
- await unregisterClaudeCodeMcp(WORKSPACE, "notfair-orchestration");
- const cfg = JSON.parse(
- fsState.files.get("/workspace/agent/.mcp.json") ?? "{}",
- );
- expect(Object.keys(cfg.mcpServers)).toEqual(["other"]);
- });
-});
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/parse.test.ts b/notfair-cmo/src/server/adapters/claude-code-local/parse.test.ts
deleted file mode 100644
index cc5f3c81..00000000
--- a/notfair-cmo/src/server/adapters/claude-code-local/parse.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { makeClaudeStreamState, parseClaudeLine } from "./parse";
-
-describe("parseClaudeLine", () => {
- it("ignores blank and malformed lines", () => {
- const state = makeClaudeStreamState();
- expect(parseClaudeLine("", state)).toEqual([]);
- expect(parseClaudeLine("not json", state)).toEqual([]);
- expect(state.assistantText).toBe("");
- });
-
- it("forwards a `system` event as a lifecycle", () => {
- const state = makeClaudeStreamState();
- const out = parseClaudeLine(
- JSON.stringify({ type: "system", subtype: "init" }),
- state,
- );
- expect(out).toEqual([{ kind: "lifecycle", phase: "init" }]);
- });
-
- it("emits a session event once when the system message carries a session_id", () => {
- const state = makeClaudeStreamState();
- const first = parseClaudeLine(
- JSON.stringify({
- type: "system",
- subtype: "init",
- session_id: "claude-session-uuid",
- }),
- state,
- );
- expect(first).toEqual([
- { kind: "lifecycle", phase: "init" },
- { kind: "session", harnessSessionId: "claude-session-uuid" },
- ]);
- // Second system event with the same session_id must not re-emit.
- const second = parseClaudeLine(
- JSON.stringify({
- type: "system",
- subtype: "another_hook",
- session_id: "claude-session-uuid",
- }),
- state,
- );
- expect(second).toEqual([{ kind: "lifecycle", phase: "another_hook" }]);
- });
-
- it("emits a delta when an assistant text block arrives", () => {
- const state = makeClaudeStreamState();
- const out = parseClaudeLine(
- JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "text", text: "Hello" }] },
- }),
- state,
- );
- expect(out).toEqual([{ kind: "delta", text: "Hello" }]);
- expect(state.assistantText).toBe("Hello");
- expect(state.emittedTextLen).toBe(5);
- });
-
- it("emits only the new suffix on subsequent assistant blocks", () => {
- const state = makeClaudeStreamState();
- parseClaudeLine(
- JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "text", text: "Hello" }] },
- }),
- state,
- );
- const out = parseClaudeLine(
- JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "text", text: " world" }] },
- }),
- state,
- );
- expect(out).toEqual([{ kind: "delta", text: " world" }]);
- expect(state.assistantText).toBe("Hello world");
- });
-
- it("surfaces a tool_use block as a `tool` start event", () => {
- const state = makeClaudeStreamState();
- const out = parseClaudeLine(
- JSON.stringify({
- type: "assistant",
- message: {
- content: [
- {
- type: "tool_use",
- id: "call_42",
- name: "Bash",
- input: { command: "pnpm test" },
- },
- ],
- },
- }),
- state,
- );
- expect(out).toEqual([
- {
- kind: "tool",
- phase: "start",
- toolCallId: "call_42",
- name: "Bash",
- label: "pnpm test",
- },
- ]);
- });
-
- it("marks state.finalized and emits a final event on result", () => {
- const state = makeClaudeStreamState();
- state.assistantText = "Hi";
- state.emittedTextLen = 2;
- const out = parseClaudeLine(
- JSON.stringify({ type: "result", subtype: "success", result: "Hi" }),
- state,
- );
- expect(out).toEqual([{ kind: "final", text: "Hi" }]);
- expect(state.finalized).toBe(true);
- });
-
- it("emits an error event when the result subtype is an error", () => {
- const state = makeClaudeStreamState();
- const out = parseClaudeLine(
- JSON.stringify({
- type: "result",
- subtype: "error_max_turns",
- error: { message: "too many turns" },
- }),
- state,
- );
- expect(out).toEqual([{ kind: "error", message: "too many turns" }]);
- expect(state.finalized).toBe(true);
- });
-});
diff --git a/notfair-cmo/src/server/adapters/codex-local/mcp.test.ts b/notfair-cmo/src/server/adapters/codex-local/mcp.test.ts
deleted file mode 100644
index 2496cfd7..00000000
--- a/notfair-cmo/src/server/adapters/codex-local/mcp.test.ts
+++ /dev/null
@@ -1,260 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-// ── In-memory fs mock ──────────────────────────────────────────────────
-
-interface FsState {
- files: Map<string, string>;
- dirs: Set<string>;
-}
-const fsState: FsState = { files: new Map(), dirs: new Set() };
-
-vi.mock("node:fs", () => ({
- existsSync: (p: string) => fsState.files.has(p),
-}));
-
-vi.mock("node:fs/promises", () => ({
- mkdir: async (p: string) => {
- fsState.dirs.add(p);
- },
- readFile: async (p: string) => {
- const v = fsState.files.get(p);
- if (v === undefined) throw new Error(`ENOENT: ${p}`);
- return v;
- },
- writeFile: async (p: string, content: string) => {
- fsState.files.set(p, content);
- },
-}));
-
-beforeEach(() => {
- fsState.files.clear();
- fsState.dirs.clear();
- process.env.CODEX_HOME = "/codex";
-});
-
-afterEach(() => {
- delete process.env.CODEX_HOME;
-});
-
-// Imported after the mock so the in-memory fs is the one the module uses.
-import {
- CODEX_BEARER_ENV_VAR,
- pruneOrphanCodexNamespaces,
- registerCodexMcp,
- unregisterCodexMcp,
-} from "./mcp";
-import type { McpRegistrationSpec } from "../types";
-
-function makeHttpSpec(
- overrides: Partial<McpRegistrationSpec> = {},
-): McpRegistrationSpec {
- return {
- serverName: "notfair-orchestration",
- agentId: "acme-cmo-greg",
- projectSlug: "acme",
- transport: {
- type: "http",
- url: "http://127.0.0.1:3326/api/mcp/orchestration",
- headers: { Authorization: "Bearer s3cret" },
- },
- ...overrides,
- };
-}
-
-describe("registerCodexMcp (http)", () => {
- it("emits bearer_token_env_var instead of raw Authorization header", async () => {
- await registerCodexMcp(makeHttpSpec());
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).toContain(
- `[mcp_servers.notfair_acme__notfair_orchestration]`,
- );
- expect(toml).toContain(
- `url = "http://127.0.0.1:3326/api/mcp/orchestration"`,
- );
- expect(toml).toContain(
- `bearer_token_env_var = ${JSON.stringify(CODEX_BEARER_ENV_VAR)}`,
- );
- // Regression: codex 0.132+ marks raw `headers = {Authorization=...}` as
- // Auth: Unsupported and refuses to expose the MCP tools.
- expect(toml).not.toMatch(/headers\s*=\s*\{\s*Authorization/);
- expect(toml).not.toContain("s3cret");
- });
-
- it("preserves non-Authorization headers verbatim", async () => {
- await registerCodexMcp(
- makeHttpSpec({
- transport: {
- type: "http",
- url: "https://example.test/mcp",
- headers: {
- Authorization: "Bearer s3cret",
- "X-Custom": "yes",
- },
- },
- }),
- );
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).toContain(`bearer_token_env_var = ${JSON.stringify(CODEX_BEARER_ENV_VAR)}`);
- expect(toml).toContain(`headers = { X-Custom = "yes" }`);
- });
-
- it("is idempotent on re-registration (single section, no duplicates)", async () => {
- await registerCodexMcp(makeHttpSpec());
- await registerCodexMcp(makeHttpSpec());
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- const matches = toml.match(
- /\[mcp_servers\.notfair_acme__notfair_orchestration\]/g,
- );
- expect(matches?.length).toBe(1);
- });
-
- it("namespaces by project slug so two projects don't collide", async () => {
- await registerCodexMcp(makeHttpSpec({ projectSlug: "acme" }));
- await registerCodexMcp(makeHttpSpec({ projectSlug: "globex" }));
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).toContain(
- `[mcp_servers.notfair_acme__notfair_orchestration]`,
- );
- expect(toml).toContain(
- `[mcp_servers.notfair_globex__notfair_orchestration]`,
- );
- });
-
- it("collapses two agents in the same project into one shared entry", async () => {
- await registerCodexMcp(
- makeHttpSpec({ projectSlug: "acme", agentId: "acme-cmo-greg" }),
- );
- await registerCodexMcp(
- makeHttpSpec({ projectSlug: "acme", agentId: "acme-google-ads-ana" }),
- );
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- const matches = toml.match(
- /\[mcp_servers\.notfair_acme__notfair_orchestration\]/g,
- );
- expect(matches?.length).toBe(1);
- // No per-agent suffixes left in the file from either registration.
- expect(toml).not.toContain("notfair_acme_cmo_greg__");
- expect(toml).not.toContain("notfair_acme_google_ads_ana__");
- });
-});
-
-describe("registerCodexMcp (stdio)", () => {
- it("writes command + args; no bearer env var (stdio uses inline env)", async () => {
- await registerCodexMcp({
- serverName: "stdio-thing",
- agentId: "acme-cmo-greg",
- projectSlug: "acme",
- transport: {
- type: "stdio",
- command: "node",
- args: ["server.js"],
- env: { KEY: "v" },
- },
- });
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).toContain(`command = "node"`);
- expect(toml).toContain(`args = ["server.js"]`);
- expect(toml).toContain(`env = { KEY = "v" }`);
- expect(toml).not.toContain("bearer_token_env_var");
- });
-});
-
-describe("unregisterCodexMcp", () => {
- it("removes only the matching project's section", async () => {
- await registerCodexMcp(makeHttpSpec({ projectSlug: "acme" }));
- await registerCodexMcp(makeHttpSpec({ projectSlug: "globex" }));
- await unregisterCodexMcp("notfair-orchestration", "acme");
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).not.toContain("notfair_acme__");
- expect(toml).toContain("notfair_globex__");
- });
-});
-
-describe("pruneOrphanCodexNamespaces", () => {
- it("strips legacy per-agent sections (prefix is an agent id, not a project slug)", async () => {
- // Hand-write a config that looks like what an upgraded 0.3.x install
- // would have: per-agent prefixes from before per-project namespacing.
- fsState.files.set(
- "/codex/config.toml",
- [
- `[mcp_servers.notfair_acme_cmo_greg__notfair_orchestration]`,
- `url = "http://x"`,
- ``,
- `[mcp_servers.notfair_acme_google_ads_ana__notfair_orchestration]`,
- `url = "http://x"`,
- ``,
- `[mcp_servers.notfair_acme__notfair_orchestration]`,
- `url = "http://x"`,
- ``,
- ].join("\n"),
- );
- const removed = await pruneOrphanCodexNamespaces(new Set(["acme"]));
- expect(removed).toBe(2);
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).toContain("notfair_acme__notfair_orchestration");
- expect(toml).not.toContain("notfair_acme_cmo_greg__");
- expect(toml).not.toContain("notfair_acme_google_ads_ana__");
- });
-
- it("strips sections for deleted projects", async () => {
- fsState.files.set(
- "/codex/config.toml",
- [
- `[mcp_servers.notfair_acme__notfair_orchestration]`,
- `url = "http://x"`,
- ``,
- `[mcp_servers.notfair_oldproject__notfair_orchestration]`,
- `url = "http://x"`,
- ``,
- ].join("\n"),
- );
- const removed = await pruneOrphanCodexNamespaces(new Set(["acme"]));
- expect(removed).toBe(1);
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).toContain("notfair_acme__");
- expect(toml).not.toContain("notfair_oldproject__");
- });
-
- it("leaves user-installed non-notfair servers alone", async () => {
- fsState.files.set(
- "/codex/config.toml",
- [
- `[mcp_servers.user_linear]`,
- `command = "linear-mcp"`,
- ``,
- `[mcp_servers.notfair_dead__notfair_orchestration]`,
- `url = "http://x"`,
- ``,
- ].join("\n"),
- );
- const removed = await pruneOrphanCodexNamespaces(new Set(["acme"]));
- expect(removed).toBe(1);
- const toml = fsState.files.get("/codex/config.toml") ?? "";
- expect(toml).toContain(`[mcp_servers.user_linear]`);
- expect(toml).toContain(`command = "linear-mcp"`);
- expect(toml).not.toContain("notfair_dead__");
- });
-
- it("normalizes dashed slugs to underscored prefixes before comparing", async () => {
- fsState.files.set(
- "/codex/config.toml",
- [
- `[mcp_servers.notfair_acme_co__notfair_orchestration]`,
- `url = "http://x"`,
- ``,
- ].join("\n"),
- );
- // Project slug uses a dash; namespace prefix uses underscore.
- const removed = await pruneOrphanCodexNamespaces(new Set(["acme-co"]));
- expect(removed).toBe(0);
- expect(fsState.files.get("/codex/config.toml")).toContain(
- "notfair_acme_co__",
- );
- });
-
- it("is a no-op when the config file is absent", async () => {
- const removed = await pruneOrphanCodexNamespaces(new Set(["acme"]));
- expect(removed).toBe(0);
- expect(fsState.files.has("/codex/config.toml")).toBe(false);
- });
-});
diff --git a/notfair-cmo/src/server/adapters/codex-local/models.test.ts b/notfair-cmo/src/server/adapters/codex-local/models.test.ts
deleted file mode 100644
index 7a7f466d..00000000
--- a/notfair-cmo/src/server/adapters/codex-local/models.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { mkdtemp, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { describe, expect, it } from "vitest";
-
-import { listCodexModels } from "./models";
-
-async function writeCache(content: unknown): Promise<string> {
- const dir = await mkdtemp(join(tmpdir(), "codex-models-"));
- const file = join(dir, "models_cache.json");
- await writeFile(
- file,
- typeof content === "string" ? content : JSON.stringify(content),
- );
- return file;
-}
-
-describe("listCodexModels", () => {
- it("maps visible models from the provider cache, sorted by priority", async () => {
- const file = await writeCache({
- models: [
- { slug: "gpt-5.4", display_name: "GPT-5.4", visibility: "list", priority: 16 },
- { slug: "gpt-5.5", display_name: "GPT-5.5", visibility: "list", priority: 7 },
- { slug: "codex-auto-review", display_name: "Codex Auto Review", visibility: "hide", priority: 43 },
- { slug: "gpt-5.4-mini", display_name: "GPT-5.4-Mini", visibility: "list", priority: 23 },
- ],
- });
- expect(await listCodexModels(file)).toEqual([
- { value: "gpt-5.5", label: "GPT-5.5" },
- { value: "gpt-5.4", label: "GPT-5.4" },
- { value: "gpt-5.4-mini", label: "GPT-5.4-Mini" },
- ]);
- });
-
- it("falls back to slug when display_name is missing", async () => {
- const file = await writeCache({
- models: [{ slug: "gpt-9", visibility: "list", priority: 1 }],
- });
- expect(await listCodexModels(file)).toEqual([
- { value: "gpt-9", label: "gpt-9" },
- ]);
- });
-
- it("returns the static fallback when the cache file is missing", async () => {
- const models = await listCodexModels("/nonexistent/models_cache.json");
- expect(models.length).toBeGreaterThan(0);
- expect(models[0]!.value).toBe("gpt-5.5");
- });
-
- it("returns the static fallback on malformed JSON or an empty list", async () => {
- expect(await listCodexModels(await writeCache("not-json{{{"))).toEqual(
- await listCodexModels("/nonexistent"),
- );
- expect(await listCodexModels(await writeCache({ models: [] }))).toEqual(
- await listCodexModels("/nonexistent"),
- );
- });
-});
diff --git a/notfair-cmo/src/server/adapters/codex-local/parse.test.ts b/notfair-cmo/src/server/adapters/codex-local/parse.test.ts
deleted file mode 100644
index 010c5bc4..00000000
--- a/notfair-cmo/src/server/adapters/codex-local/parse.test.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { makeCodexStreamState, parseCodexLine } from "./parse";
-
-describe("parseCodexLine", () => {
- it("ignores blank and malformed lines", () => {
- const state = makeCodexStreamState();
- expect(parseCodexLine("", state)).toEqual([]);
- expect(parseCodexLine("not json", state)).toEqual([]);
- });
-
- it("captures the thread id on thread.started and emits a session event", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({ type: "thread.started", thread_id: "abc-123" }),
- state,
- );
- expect(out).toEqual([
- { kind: "lifecycle", phase: "start" },
- { kind: "session", harnessSessionId: "abc-123" },
- ]);
- expect(state.threadId).toBe("abc-123");
- });
-
- it("emits a tool start event on item.started for a command_execution", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "item.started",
- item: {
- type: "command_execution",
- id: "cmd_1",
- command: "ls -la\nsecond line",
- },
- }),
- state,
- );
- // Shell command items get a stable `"shell"` name so the chat UI can
- // route them to the Terminal icon + humanize the intent from the
- // command line. The raw command stays in `label`.
- expect(out).toEqual([
- {
- kind: "tool",
- phase: "start",
- toolCallId: "cmd_1",
- name: "shell",
- label: "ls -la",
- },
- ]);
- });
-
- it("emits a tool start event for an mcp_tool_call item using <server>.<tool> naming", () => {
- // Codex 0.132+ surfaces MCP invocations as their own item type with
- // distinct `server` + `tool` fields. The UI matches tool calls to
- // catalog entries via a `<server>.<tool>` shape, so the parser
- // normalizes to that.
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "item.started",
- item: {
- type: "mcp_tool_call",
- id: "mcp_1",
- server: "notfair_demo__notfair_googleads",
- tool: "listAdAccounts",
- arguments: { query: "active campaigns" },
- },
- }),
- state,
- );
- expect(out).toEqual([
- {
- kind: "tool",
- phase: "start",
- toolCallId: "mcp_1",
- name: "notfair_demo__notfair_googleads.listAdAccounts",
- label: "active campaigns",
- },
- ]);
- });
-
- it("emits a tool result event when an mcp_tool_call completes", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "item.completed",
- item: {
- type: "mcp_tool_call",
- id: "mcp_1",
- server: "notfair_demo__notfair_googleads",
- tool: "listAdAccounts",
- },
- }),
- state,
- );
- expect(out).toEqual([
- {
- kind: "tool",
- phase: "result",
- toolCallId: "mcp_1",
- name: "notfair_demo__notfair_googleads.listAdAccounts",
- },
- ]);
- });
-
- it("keeps the declared name when item.name is provided (real MCP tool call)", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "item.started",
- item: {
- type: "tool_call",
- id: "tc_1",
- name: "notfair_demo__notfair_googleads__listAdAccounts",
- arguments: { query: "active campaigns" },
- },
- }),
- state,
- );
- expect(out).toEqual([
- {
- kind: "tool",
- phase: "start",
- toolCallId: "tc_1",
- name: "notfair_demo__notfair_googleads__listAdAccounts",
- label: "active campaigns",
- },
- ]);
- });
-
- it("emits a delta when an agent_message item completes", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "item.completed",
- item: { type: "agent_message", text: "Sure thing." },
- }),
- state,
- );
- expect(out).toEqual([{ kind: "delta", text: "Sure thing." }]);
- expect(state.assistantText).toBe("Sure thing.");
- });
-
- it("surfaces item-level error items as transient errors (codex 0.144+)", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "item.completed",
- item: { id: "item_3", type: "error", message: "MCP call blew up" },
- }),
- state,
- );
- expect(out).toEqual([
- { kind: "error", message: "MCP call blew up", transient: true },
- ]);
- // Item errors are non-fatal — the turn keeps going.
- expect(state.finalized).toBe(false);
- });
-
- it("drops known advisory error items (skills-budget nudge on every run)", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "item.completed",
- item: {
- id: "item_0",
- type: "error",
- message:
- "Skill descriptions were shortened to fit the 2% skills context budget. Codex can still see every skill, but some descriptions are shorter.",
- },
- }),
- state,
- );
- expect(out).toEqual([]);
- });
-
- it("marks the turn finalized on turn.completed", () => {
- const state = makeCodexStreamState();
- state.assistantText = "Done";
- state.emittedTextLen = 4;
- const out = parseCodexLine(
- JSON.stringify({ type: "turn.completed", usage: {} }),
- state,
- );
- expect(out).toEqual([{ kind: "final", text: "Done" }]);
- expect(state.finalized).toBe(true);
- });
-
- it("emits an error event on turn.failed", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "turn.failed",
- error: { message: "rate limit hit" },
- }),
- state,
- );
- expect(out).toEqual([
- { kind: "error", message: "rate limit hit", transient: false },
- ]);
- expect(state.finalized).toBe(true);
- });
-
- it("tags Codex MCP reconnect chatter as transient and leaves the turn un-finalized", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "turn.failed",
- error: {
- message: "Reconnecting... 2/5 (timeout waiting for child process to exit)",
- },
- }),
- state,
- );
- expect(out).toEqual([
- {
- kind: "error",
- message: "Reconnecting... 2/5 (timeout waiting for child process to exit)",
- transient: true,
- },
- ]);
- // Critically: a transient error must NOT finalize the turn, otherwise
- // execute.ts's close handler suppresses the richer post-exit error.
- expect(state.finalized).toBe(false);
- });
-
- it("tags `type: error` lines that match the reconnect pattern as transient", () => {
- const state = makeCodexStreamState();
- const out = parseCodexLine(
- JSON.stringify({
- type: "error",
- message: "Reconnecting... 1/5",
- }),
- state,
- );
- expect(out).toEqual([
- { kind: "error", message: "Reconnecting... 1/5", transient: true },
- ]);
- });
-});
diff --git a/notfair-cmo/src/server/agent-meta.test.ts b/notfair-cmo/src/server/agent-meta.test.ts
deleted file mode 100644
index 5d754b44..00000000
--- a/notfair-cmo/src/server/agent-meta.test.ts
+++ /dev/null
@@ -1,400 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { AgentMeta } from "./agent-meta";
-
-// ── Mocks ──────────────────────────────────────────────────────────
-
-// In-memory "filesystem" backing both node:fs (sync) and node:fs/promises.
-type FsState = {
- files: Map<string, string>;
- dirs: Set<string>;
- /** When set, readdir throws ENOENT for this root. */
- missingDirs: Set<string>;
-};
-
-const fsState: FsState = {
- files: new Map(),
- dirs: new Set(),
- missingDirs: new Set(),
-};
-
-vi.mock("node:fs", () => ({
- existsSync: (p: string) => fsState.files.has(p),
- readFileSync: (p: string) => {
- const v = fsState.files.get(p);
- if (v === undefined) throw new Error(`ENOENT: ${p}`);
- return v;
- },
-}));
-
-vi.mock("node:fs/promises", () => ({
- mkdir: async (p: string, _opts?: unknown) => {
- fsState.dirs.add(p);
- },
- writeFile: async (p: string, content: string, _enc?: string) => {
- fsState.files.set(p, content);
- },
- readdir: async (p: string) => {
- if (fsState.missingDirs.has(p)) {
- const err = new Error(`ENOENT: ${p}`) as NodeJS.ErrnoException;
- err.code = "ENOENT";
- throw err;
- }
- // Return directory names under p that are direct children.
- const out = new Set<string>();
- const prefix = p.endsWith("/") ? p : `${p}/`;
- for (const file of fsState.files.keys()) {
- if (file.startsWith(prefix)) {
- const rest = file.slice(prefix.length);
- const first = rest.split("/")[0];
- if (first) out.add(first);
- }
- }
- for (const dir of fsState.dirs) {
- if (dir.startsWith(prefix)) {
- const rest = dir.slice(prefix.length);
- const first = rest.split("/")[0];
- if (first) out.add(first);
- }
- }
- return Array.from(out);
- },
-}));
-
-// homedir → deterministic path so tests don't depend on the runner's $HOME.
-vi.mock("node:os", () => ({
- homedir: () => "/home/test",
-}));
-
-// Stub TEMPLATES so we don't depend on real prompt-edit churn. listProjectAgents
-// only uses { key, display_name, description } from each entry + the helpers
-// imported alongside.
-vi.mock("./agent-templates", () => ({
- TEMPLATES: [
- {
- key: "cmo",
- display_name: "CMO",
- default_name: "Greg",
- description: "Chief Marketing Officer.",
- default_onboarding: true,
- },
- {
- key: "google_ads",
- display_name: "Google Ads",
- default_name: "Ana",
- description: "Google Ads specialist.",
- default_onboarding: true,
- },
- {
- key: "seo",
- display_name: "SEO",
- default_name: "Sam",
- description: "SEO specialist.",
- // Opt-in template: not pre-seeded, only appears via meta sidecar.
- default_onboarding: false,
- },
- ],
- agentNameFor: (slug: string, key: string) =>
- `${slug}-${key.replace(/_/g, "-")}`,
- urlSlugForTemplate: (key: string) => key.replace(/_/g, "-"),
- agentUrlSlug: (key: string, n: string) =>
- `${key.replace(/_/g, "-")}-${n
- .toLowerCase()
- .trim()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-+|-+$/g, "")
- .slice(0, 32)}`,
-}));
-
-import {
- listProjectAgents,
- readAgentMeta,
- resolveAgentBySlug,
- workspaceDirFor,
- writeAgentMeta,
-} from "./agent-meta";
-
-// ── Helpers ────────────────────────────────────────────────────────
-
-function resetFs() {
- fsState.files.clear();
- fsState.dirs.clear();
- fsState.missingDirs.clear();
-}
-
-function makeMeta(overrides: Partial<AgentMeta> = {}): AgentMeta {
- return {
- agent_id: "acme-cmo",
- project_slug: "acme",
- slug: "cmo",
- name: "CMO",
- template_key: "cmo",
- created_at: "2026-01-01T00:00:00Z",
- ...overrides,
- };
-}
-
-beforeEach(() => {
- resetFs();
- // Set deterministic data dir so paths are predictable.
- process.env.NOTFAIR_CMO_DATA_DIR = "/data";
-});
-
-// ── Tests ──────────────────────────────────────────────────────────
-
-describe("workspaceDirFor", () => {
- it("returns <DATA_DIR>/agents/<agentId>", () => {
- expect(workspaceDirFor("acme-cmo")).toBe("/data/agents/acme-cmo");
- });
-
- it("falls back to homedir when env unset", () => {
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- expect(workspaceDirFor("acme-cmo")).toBe(
- "/home/test/.notfair-cmo/agents/acme-cmo",
- );
- });
-});
-
-describe("writeAgentMeta + readAgentMeta", () => {
- it("writes JSON to <DATA_DIR>/agents/<agentId>/notfair-meta.json", async () => {
- const meta = makeMeta();
- await writeAgentMeta(meta);
- const written = fsState.files.get("/data/agents/acme-cmo/notfair-meta.json");
- expect(written).toBeDefined();
- expect(JSON.parse(written!)).toEqual(meta);
- });
-
- it("creates the parent directory recursively before writing", async () => {
- await writeAgentMeta(makeMeta());
- expect(fsState.dirs.has("/data/agents/acme-cmo")).toBe(true);
- });
-
- it("readAgentMeta returns the parsed object after a writeAgentMeta", async () => {
- const meta = makeMeta();
- await writeAgentMeta(meta);
- expect(readAgentMeta("acme-cmo")).toEqual(meta);
- });
-
- it("readAgentMeta returns null when the file does not exist", () => {
- expect(readAgentMeta("ghost-agent")).toBeNull();
- });
-
- it("readAgentMeta returns null when the file is malformed JSON", () => {
- fsState.files.set(
- "/data/agents/broken/notfair-meta.json",
- "{ not valid json",
- );
- expect(readAgentMeta("broken")).toBeNull();
- });
-
- it("round-trips an entry with optional source_agent_id (clone case)", async () => {
- const meta = makeMeta({
- agent_id: "acme-supa-clone",
- slug: "supa-clone",
- name: "Supabase Clone",
- source_agent_id: "acme-cmo",
- });
- await writeAgentMeta(meta);
- expect(readAgentMeta("acme-supa-clone")).toEqual(meta);
- });
-});
-
-describe("listProjectAgents", () => {
- it("returns the onboarding-default templates only when agents dir is missing", async () => {
- fsState.missingDirs.add("/data/agents");
- const r = await listProjectAgents("acme");
- // SEO is template_key: 'seo' with default_onboarding: false — it should
- // NOT appear until something explicitly provisions it for the project.
- expect(r).toHaveLength(2);
- expect(r.map((e) => e.agent_id)).toEqual([
- "acme-cmo",
- "acme-google-ads",
- ]);
- expect(r.every((e) => e.is_template_default)).toBe(true);
- });
-
- it("returns onboarding-default templates only when agents dir exists but has no entries for the project", async () => {
- // Empty dir: readdir resolves to [], no entries match.
- const r = await listProjectAgents("acme");
- expect(r.map((e) => e.agent_id)).toEqual([
- "acme-cmo",
- "acme-google-ads",
- ]);
- });
-
- it("includes an opt-in template (e.g. SEO) once a meta sidecar is written for it", async () => {
- await writeAgentMeta(
- makeMeta({
- agent_id: "acme-seo",
- slug: "seo",
- name: "SEO",
- template_key: "seo",
- }),
- );
- const r = await listProjectAgents("acme");
- const seo = r.find((e) => e.agent_id === "acme-seo");
- expect(seo).toBeDefined();
- expect(seo?.template_key).toBe("seo");
- // It now appears as a non-template-default entry (overlay row wins).
- expect(seo?.is_template_default).toBe(false);
- });
-
- it("overlays a meta sidecar so is_template_default flips to false", async () => {
- await writeAgentMeta(makeMeta()); // /data/agents/acme-cmo/notfair-meta.json
- const r = await listProjectAgents("acme");
- const cmo = r.find((e) => e.agent_id === "acme-cmo");
- expect(cmo?.is_template_default).toBe(false);
- expect(cmo?.name).toBe("CMO");
- });
-
- it("includes a cloned/custom agent with its source_agent_id surfaced", async () => {
- await writeAgentMeta(
- makeMeta({
- agent_id: "acme-supa-clone",
- slug: "supa-clone",
- name: "Supa Clone",
- template_key: undefined,
- source_agent_id: "acme-cmo",
- }),
- );
- const r = await listProjectAgents("acme");
- const clone = r.find((e) => e.agent_id === "acme-supa-clone");
- expect(clone).toMatchObject({
- agent_id: "acme-supa-clone",
- slug: "supa-clone",
- name: "Supa Clone",
- source_agent_id: "acme-cmo",
- is_template_default: false,
- });
- });
-
- it("orders templates by declared order, then custom by slug", async () => {
- await writeAgentMeta(
- makeMeta({
- agent_id: "acme-z-tool",
- slug: "z-tool",
- name: "Z Tool",
- template_key: undefined,
- }),
- );
- await writeAgentMeta(
- makeMeta({
- agent_id: "acme-a-tool",
- slug: "a-tool",
- name: "A Tool",
- template_key: undefined,
- }),
- );
- const r = await listProjectAgents("acme");
- // Onboarding-default templates first in declared order (SEO is opt-in
- // and not seeded), then custom alphabetically by slug. Template slugs
- // are computed `<role>-<slugified-name>` from the default_name.
- expect(r.map((e) => e.slug)).toEqual([
- "cmo-greg",
- "google-ads-ana",
- "a-tool",
- "z-tool",
- ]);
- });
-
- it("ignores entries from other projects (different slug prefix)", async () => {
- await writeAgentMeta(
- makeMeta({
- agent_id: "globex-cmo",
- project_slug: "globex",
- slug: "cmo",
- name: "Globex CMO",
- }),
- );
- const r = await listProjectAgents("acme");
- expect(r.find((e) => e.agent_id === "globex-cmo")).toBeUndefined();
- // Still has the onboarding-default templates for acme.
- expect(r.filter((e) => e.is_template_default)).toHaveLength(2);
- });
-
- it("skips entries with a matching prefix but no meta sidecar", async () => {
- // Create a phantom agent dir without a notfair-meta.json — simulates an
- // older workspace dir without the sidecar.
- fsState.dirs.add("/data/agents/acme-orphan");
- const r = await listProjectAgents("acme");
- // Should not include acme-orphan; just the onboarding-default templates.
- expect(r.find((e) => e.agent_id === "acme-orphan")).toBeUndefined();
- expect(r).toHaveLength(2);
- });
-
- it("does NOT leak agents from a project whose slug starts with this slug + '-'", async () => {
- // Regression: project "acme" must not list agents that belong to
- // project "acme-q4". The dir-name prefix `acme-` matches both
- // `acme-cmo-greg` (this project) AND `acme-q4-cmo-greg` (the other);
- // the meta sidecar's project_slug field is what disambiguates.
- await writeAgentMeta(
- makeMeta({
- agent_id: "acme-cmo-greg",
- project_slug: "acme",
- slug: "cmo-greg",
- name: "Greg",
- }),
- );
- await writeAgentMeta(
- makeMeta({
- agent_id: "acme-q4-cmo-greg",
- project_slug: "acme-q4",
- slug: "cmo-greg",
- name: "Greg",
- }),
- );
-
- const acme = await listProjectAgents("acme");
- expect(acme.find((e) => e.agent_id === "acme-q4-cmo-greg")).toBeUndefined();
- expect(acme.find((e) => e.agent_id === "acme-cmo-greg")).toBeDefined();
-
- const q4 = await listProjectAgents("acme-q4");
- expect(q4.find((e) => e.agent_id === "acme-cmo-greg")).toBeUndefined();
- expect(q4.find((e) => e.agent_id === "acme-q4-cmo-greg")).toBeDefined();
- });
-});
-
-describe("resolveAgentBySlug", () => {
- it("resolves a template URL slug (role-name shape) to its agent_id", async () => {
- fsState.missingDirs.add("/data/agents");
- // Template agents are pre-seeded with their default_name → the URL
- // slug is `<role>-<default_name>` for the placeholder entry.
- const r = await resolveAgentBySlug("acme", "google-ads-ana");
- expect(r).toEqual({
- agent_id: "acme-google-ads",
- name: "Ana",
- slug: "google-ads-ana",
- template_key: "google_ads",
- });
- });
-
- it("returns null for the bare role slug (the new shape is role-name)", async () => {
- fsState.missingDirs.add("/data/agents");
- const r = await resolveAgentBySlug("acme", "cmo");
- expect(r).toBeNull();
- });
-
- it("resolves a custom (non-template) agent by its meta slug", async () => {
- await writeAgentMeta(
- makeMeta({
- agent_id: "acme-supa-clone",
- slug: "supa-clone",
- name: "Supa Clone",
- template_key: undefined,
- }),
- );
- const r = await resolveAgentBySlug("acme", "supa-clone");
- expect(r).toEqual({
- agent_id: "acme-supa-clone",
- name: "Supa Clone",
- slug: "supa-clone",
- template_key: undefined,
- });
- });
-
- it("returns null when slug doesn't match any agent in the project", async () => {
- fsState.missingDirs.add("/data/agents");
- const r = await resolveAgentBySlug("acme", "nonexistent");
- expect(r).toBeNull();
- });
-});
diff --git a/notfair-cmo/src/server/agent-meta.ts b/notfair-cmo/src/server/agent-meta.ts
deleted file mode 100644
index 0d4aeb3a..00000000
--- a/notfair-cmo/src/server/agent-meta.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-import { existsSync, readFileSync } from "node:fs";
-import { mkdir, writeFile, readdir } from "node:fs/promises";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import {
- TEMPLATES,
- agentNameFor,
- agentUrlSlug,
- urlSlugForTemplate,
- type AgentTemplateKey,
-} from "./agent-templates";
-
-/**
- * Per-agent meta we own (notfair-cmo) and store next to the agent's workspace
- * directory. OpenClaw doesn't have a place for our UI-facing display name +
- * project linkage, so this sidecar fills the gap without requiring a DB
- * migration. Authored at agent creation/clone time, read by the sidebar.
- */
-
-export type AgentMeta = {
- /** Full OpenClaw agentId, e.g. `acme-cmo` or `acme-supa-clone`. */
- agent_id: string;
- /** Project slug this agent belongs to. */
- project_slug: string;
- /**
- * Personal name the user assigned (e.g. "Greg", "Ana"). IMMUTABLE —
- * set once at agent-create time. The URL slug is computed from this
- * + template_key (see agentUrlSlug); the sidebar shows this as the
- * primary label next to a role pill.
- */
- name: string;
- /**
- * URL slug — stored ONLY for non-template (cloned/custom) agents,
- * where there's no role+name pair to compute from. Template agents
- * always compute their slug from template_key + name and never write
- * this field.
- */
- slug?: string;
- /** If from one of our bootstrap templates, which one. */
- template_key?: AgentTemplateKey;
- /** When cloned, the source agentId. */
- source_agent_id?: string;
- created_at: string;
-};
-
-function notfairDataDir(): string {
- return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
-}
-
-function metaPath(agentId: string): string {
- return join(notfairDataDir(), "agents", agentId, "notfair-meta.json");
-}
-
-export async function writeAgentMeta(meta: AgentMeta): Promise<void> {
- const path = metaPath(meta.agent_id);
- await mkdir(join(path, ".."), { recursive: true });
- await writeFile(path, JSON.stringify(meta, null, 2), "utf8");
-}
-
-export function readAgentMeta(agentId: string): AgentMeta | null {
- const path = metaPath(agentId);
- if (!existsSync(path)) return null;
- try {
- return JSON.parse(readFileSync(path, "utf8")) as AgentMeta;
- } catch {
- return null;
- }
-}
-
-export type ProjectAgentEntry = {
- agent_id: string;
- /**
- * URL slug. For template agents: `<role>-<slugified-name>` computed
- * from template_key + name. For cloned/custom: the stored slug.
- */
- slug: string;
- /** Personal name (e.g. "Greg"). */
- name: string;
- /** Role identifier (template key). Undefined for cloned/custom agents. */
- template_key?: AgentTemplateKey;
- description?: string;
- source_agent_id?: string;
- is_template_default: boolean;
-};
-
-/**
- * List agents for a project. Source of truth:
- * - notfair-meta.json sidecars whose `project_slug` field equals the requested
- * slug. The sidecar — not the workspace dir name — is authoritative, so
- * projects whose slug is a string prefix of another project's slug (e.g.
- * "acme" vs "acme-q4") never cross-leak their rosters.
- * - For each TEMPLATE not yet present on disk, fall back to a synthesized
- * default entry so the user sees the bootstrap agents immediately even
- * before `ensureProjectAgents` runs.
- */
-export async function listProjectAgents(project_slug: string): Promise<ProjectAgentEntry[]> {
- // Two-phase merge:
- // - Template agents are deduplicated by template_key. The agent_id
- // encodes the personal name (e.g. demo-cmo-greg), so the seed and
- // the overlay COULD disagree on the id if the on-disk sidecar still
- // uses an older naming. Keying by template_key prevents that from
- // showing two CMO entries in the sidebar.
- // - Cloned/custom agents (no template_key) key by their agent_id since
- // a project may have many of them.
- const byRole = new Map<string, ProjectAgentEntry>();
- const byAgentId = new Map<string, ProjectAgentEntry>();
-
- // 1) Seed with the templates an onboarded project actually has. Opt-in
- // templates (e.g. SEO until v1.1 lights it up) live in TEMPLATES but
- // are NOT pre-seeded — they only appear when a meta sidecar shows
- // one was actually provisioned.
- for (const t of TEMPLATES) {
- if (!t.default_onboarding) continue;
- const agentId = agentNameFor(project_slug, t.key, t.default_name);
- byRole.set(t.key, {
- agent_id: agentId,
- slug: agentUrlSlug(t.key, t.default_name),
- name: t.default_name,
- description: t.description,
- template_key: t.key,
- is_template_default: true,
- });
- }
-
- // 2) Overlay anything we have meta for (template agents written by
- // ensureProjectAgents, plus cloned/custom agents). Filter by the
- // sidecar's `project_slug` field — NOT the dir name prefix — because
- // a prefix like "acme-" also matches "acme-q4-cmo-greg" which belongs
- // to a different project.
- const agentsRoot = join(notfairDataDir(), "agents");
- let entries: string[] = [];
- try {
- entries = await readdir(agentsRoot);
- } catch {
- // No agents dir yet — keep templates-only view.
- return Array.from(byRole.values());
- }
- // Coarse pre-filter: an agent that belongs to this project MUST have
- // an id starting with `<slug>-`. This cheaply skips clearly-unrelated
- // dirs without reading their sidecar. Project_slug match below is the
- // authoritative check.
- const prefix = `${project_slug}-`;
- for (const entry of entries) {
- if (!entry.startsWith(prefix)) continue;
- const meta = readAgentMeta(entry);
- if (!meta) continue;
- // Hard isolation: only accept agents whose sidecar declares this
- // project as their owner. Catches the "acme" vs "acme-q4" collision.
- if (meta.project_slug !== project_slug) continue;
- const template = meta.template_key
- ? TEMPLATES.find((t) => t.key === meta.template_key)
- : undefined;
- if (template) {
- // Template agent: replace the seed row keyed by role.
- const slug = agentUrlSlug(template.key, meta.name);
- byRole.set(template.key, {
- agent_id: meta.agent_id,
- slug,
- name: meta.name,
- template_key: meta.template_key,
- source_agent_id: meta.source_agent_id,
- is_template_default: false,
- });
- } else {
- // Cloned/custom agent: key by agent_id.
- const slug = meta.slug ?? slugifyForCustom(meta.name);
- byAgentId.set(meta.agent_id, {
- agent_id: meta.agent_id,
- slug,
- name: meta.name,
- template_key: undefined,
- source_agent_id: meta.source_agent_id,
- is_template_default: false,
- });
- }
- }
-
- const result = new Map<string, ProjectAgentEntry>();
- for (const v of byRole.values()) result.set(v.agent_id, v);
- for (const v of byAgentId.values()) result.set(v.agent_id, v);
-
- // Stable order: templates first (in declared order), then custom by slug.
- const templateOrder = new Map(TEMPLATES.map((t, i) => [t.key, i]));
- return Array.from(result.values()).sort((a, b) => {
- const ai = a.template_key ? templateOrder.get(a.template_key) ?? 99 : 99;
- const bi = b.template_key ? templateOrder.get(b.template_key) ?? 99 : 99;
- if (ai !== bi) return ai - bi;
- return a.slug.localeCompare(b.slug);
- });
-}
-
-/** Workspace dir we hand to OpenClaw at creation time. */
-export function workspaceDirFor(agentId: string): string {
- return join(notfairDataDir(), "agents", agentId);
-}
-
-/**
- * Fallback slug generator for cloned/custom agents (no template_key) whose
- * sidecar lacks an explicit `slug` field. Same shape as slugifyName but
- * lives here to avoid the agent-templates dependency for non-template
- * code paths.
- */
-function slugifyForCustom(s: string): string {
- return s
- .toLowerCase()
- .trim()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-+|-+$/g, "")
- .slice(0, 32);
-}
-
-export type ResolvedAgent = {
- agent_id: string;
- /** Personal name (e.g. "Greg"). */
- name: string;
- slug: string;
- template_key?: AgentTemplateKey;
-};
-
-/**
- * Resolve a URL slug to its full agent_id within the current project. Looks
- * up templates first, then any cloned/custom agents via the meta sidecar.
- * Returns null when no project agent matches the slug.
- */
-export async function resolveAgentBySlug(
- project_slug: string,
- url_slug: string,
-): Promise<ResolvedAgent | null> {
- const all = await listProjectAgents(project_slug);
- const hit = all.find((a) => a.slug === url_slug);
- if (!hit) return null;
- return {
- agent_id: hit.agent_id,
- name: hit.name,
- slug: hit.slug,
- template_key: hit.template_key,
- };
-}
diff --git a/notfair-cmo/src/server/agent-templates.test.ts b/notfair-cmo/src/server/agent-templates.test.ts
deleted file mode 100644
index 886d4612..00000000
--- a/notfair-cmo/src/server/agent-templates.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- TEMPLATES,
- templateForKey,
- templateForUrlSlug,
- agentUrlSlug,
- DEFAULT_ONBOARDING_TEMPLATE_KEYS,
- SPECIALIST_TEMPLATE_BY_MCP_KEY,
-} from "./agent-templates";
-
-describe("AgentTemplate catalog", () => {
- it("ships five templates: cmo + google_ads + meta_ads + seo (which owns GSC) + x_ads", () => {
- const keys = TEMPLATES.map((t) => t.key).sort();
- expect(keys).toEqual(["cmo", "google_ads", "meta_ads", "seo", "x_ads"]);
- });
-
- it("only CMO is included in the default onboarding bundle", () => {
- expect(DEFAULT_ONBOARDING_TEMPLATE_KEYS).toEqual(["cmo"]);
- expect(TEMPLATES.filter((t) => t.default_onboarding).map((t) => t.key)).toEqual(
- ["cmo"],
- );
- });
-
- it("the four specialists declare their required MCP catalog key — SEO owns GSC", () => {
- expect(templateForKey("google_ads")?.requires_mcp_key).toBe(
- "notfair-googleads",
- );
- expect(templateForKey("meta_ads")?.requires_mcp_key).toBe(
- "notfair-metaads",
- );
- expect(templateForKey("seo")?.requires_mcp_key).toBe(
- "notfair-googlesearchconsole",
- );
- expect(templateForKey("x_ads")?.requires_mcp_key).toBe("notfair-xads");
- });
-
- it("CMO has no requires_mcp_key — it never blocks", () => {
- expect(templateForKey("cmo")?.requires_mcp_key).toBeUndefined();
- });
-
- it("SPECIALIST_TEMPLATE_BY_MCP_KEY inverts requires_mcp_key — GSC maps to seo", () => {
- expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-googleads"]).toBe(
- "google_ads",
- );
- expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-metaads"]).toBe("meta_ads");
- expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-googlesearchconsole"]).toBe(
- "seo",
- );
- expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-xads"]).toBe("x_ads");
- // Google Analytics deliberately provisions no specialist.
- expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["notfair-googleanalytics"]).toBeUndefined();
- expect(SPECIALIST_TEMPLATE_BY_MCP_KEY["stripe"]).toBeUndefined();
- });
-
- it("templateForUrlSlug resolves the hyphenated URL form", () => {
- expect(templateForUrlSlug("google-ads")?.key).toBe("google_ads");
- expect(templateForUrlSlug("meta-ads")?.key).toBe("meta_ads");
- expect(templateForUrlSlug("seo")?.key).toBe("seo");
- expect(templateForUrlSlug("x-ads")?.key).toBe("x_ads");
- });
-
- it("agentUrlSlug produces stable slugs for the new templates", () => {
- expect(agentUrlSlug("meta_ads", "Mia")).toBe("meta-ads-mia");
- expect(agentUrlSlug("seo", "Sam")).toBe("seo-sam");
- expect(agentUrlSlug("x_ads", "Max")).toBe("x-ads-max");
- });
-});
diff --git a/notfair-cmo/src/server/agent-templates.ts b/notfair-cmo/src/server/agent-templates.ts
deleted file mode 100644
index 80b52d96..00000000
--- a/notfair-cmo/src/server/agent-templates.ts
+++ /dev/null
@@ -1,725 +0,0 @@
-import { stat } from "node:fs/promises";
-import {
- initProgress,
- updateStep,
- type ProgressStep,
-} from "@/server/onboarding/provisioning-progress";
-import { readAgentMeta, writeAgentMeta } from "@/server/agent-meta";
-import { provisionAgent, workspaceDirFor as agentWorkspaceDirFor } from "@/server/agents/provisioning";
-import { getProject } from "@/server/db/projects";
-import { getOrchestrationSkill } from "@/server/skills/orchestration-skill";
-import { readProjectBrief } from "@/server/onboarding/project-brief";
-import { DEFAULT_HARNESS_ADAPTER } from "@/server/adapters/registry";
-import {
- registerBrowserMcpForAgent,
- registerOrchestrationForAgent,
-} from "@/server/mcp-server/registration";
-
-/**
- * Role-specific behavior for the CMO. Concise — the procedural how-to
- * (MCP tool surface, state machine, cron CLI, propose-cron rules) lives
- * once in `getOrchestrationSkill()` and is appended to every agent's
- * IDENTITY.md by writeIdentityFile.
- *
- * Keep this strictly about "who am I + what's my decision-making lens?".
- * Tool listings, schemas, cron syntax → skill file, not here.
- */
-const CMO_ROLE = `## Your role: orchestrator
-
-You think about strategy, decompose work into tasks, and delegate to
-the specialist agents you coordinate. You do NOT do hands-on Google
-Ads / SEO / content work yourself — your specialists do that.
-
-Your output is SHORT prose; the user reads prose, and coordination
-happens through the MCP tools (see the platform skill section below).
-Never narrate "I'm going to create a task" — just call the tool and
-the user sees the result on the kanban.
-
-Shape of a typical turn (chat or scheduled heartbeat):
-
-1. Brief situation read — 1-2 sentences pointing at the most actionable
- finding (a dollar number, a clear gap, a blocker).
-2. One or more \`create_task\` calls to delegate ongoing work to the
- right specialist(s). 1-3 tasks per turn, not 10 — pick what matters.
-3. Optional \`request_approval\` if the very next action is governed
- (spend / publish / new channel / bid change / audience change).
-4. Close any task you yourself were assigned with \`submit_task_status\`.
-
-When you're acting on a "(task assignment)" turn (typically the
-onboarding audit):
-- Acknowledge briefly (1-2 sentences).
-- Do the planning / research work the brief asks for. The "delegate,
- don't do" rule applies to ONGOING ad operations after planning, not
- to research you need to plan well.
-- Report findings inline (markdown, scannable).
-- Delegate the ongoing follow-up via \`create_task\`.
-- Close the audit task with \`submit_task_status\` status=done.
-
-Style:
-- Lead with the point. Be specific. Reference real numbers + channel realities.
-- Don't waffle. Recommendations beat options. The user can push back.
-- Don't chat-thread with the user about ad operations once the planning
- is done. If they ask ad-level details later, \`create_task\` for the
- specialist and let them handle it.
-- Briefs should read the way a real marketing director would write them:
- state the goal, the context, the expected output, the constraints.`;
-
-/**
- * Role-specific behavior for any non-CMO specialist (Google Ads, SEO,
- * future others). Domain-specific tool guidance (notfair-googleads,
- * GSC, etc.) is injected per-template after this block — this constant
- * is the shared "I'm a worker, here's how I behave" identity.
- */
-const SPECIALIST_ROLE = `## Your role: specialist worker
-
-You receive tasks from the CMO via chat messages that begin with
-"(task assignment)" — they carry your project_slug, agent_id, task_id,
-title, brief, and success criteria. Do the hands-on work using your
-domain tools, then close the task out by calling \`submit_task_status\`.
-
-Shape of a "(task assignment)" turn:
-
-1. Acknowledge in 1-2 sentences — what you'll do and roughly how long.
-2. Start working. Use your domain tools to actually do the thing — not
- describe what you'd do.
-3. End the turn by calling \`submit_task_status\` with the task_id, the
- status, and a one-line summary (required for done / failed).
-
-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.
-
-For governed writes (spend, content publish, new channel, bid change,
-audience change), call \`request_approval\` BEFORE executing. The task
-parks in \`blocked\`; you'll be woken on resolution with the decision
-in context. Don't perform the gated action until then.
-
-When a task brief specifies a recurring cadence ("daily 9am check",
-"weekly Monday triage", …), the deliverable INCLUDES the schedule:
-call \`schedule_recurring_work\` with that cadence before closing the
-task. Running the work once and documenting a playbook is NOT done —
-a recurring task without its cron silently never runs again.
-
-Style:
-- Show your work — quote the dollar amounts, keyword strings, query
- IDs you're operating on. The user trusts numbers more than words.
-- One thread of execution per turn. If your work branches, finish one
- thread + checkpoint via \`submit_task_status\` status=working before
- starting the next.`;
-
-export type AgentTemplate = {
- key: "cmo" | "google_ads" | "meta_ads" | "seo" | "x_ads";
- /**
- * Label for the ROLE this template represents (e.g. "CMO", "Google
- * Ads"). Used in the sidebar role pill + anywhere the UI says
- * "what kind of agent is this". Distinct from the agent's PERSONAL
- * name (e.g. "Greg"); the personal name lives on AgentMeta.
- */
- display_name: string;
- /**
- * Suggested personal name pre-filled into the onboarding form when
- * the user provisions this template. Short + memorable so the
- * sidebar reads like a team of named colleagues rather than a roster
- * of job titles. Users can override during onboarding; the choice
- * becomes immutable once the agent is created.
- */
- default_name: string;
- description: string;
- capabilities: string[];
- model: string;
- system_prompt: string;
- /**
- * True when this template is included in the default onboarding bundle
- * (provisioned on project create + always shown in the sidebar even
- * before disk writes finish). False = opt-in: the template exists for
- * future use, but nothing surfaces it until something explicitly
- * provisions a clone of it for a project.
- */
- default_onboarding: boolean;
- /**
- * MCP catalog key this specialist needs to do its job. When set:
- * - The agent is provisioned conditionally — only when the matching
- * MCP is connected for the project (see provisionSpecialistForMcp).
- * - The agent's page shows a "Connect <platform>" blocker when the
- * MCP token is missing (see resolveMcpBlocker).
- * CMO and other tools-less templates leave this undefined.
- */
- requires_mcp_key?: string;
-};
-
-export type AgentTemplateKey = AgentTemplate["key"];
-
-/**
- * Subset of TEMPLATES included in the default onboarding bundle. Single
- * source of truth for "which agents does a freshly-created project get?".
- *
- * Only CMO ships by default now. The four specialists (Google Ads,
- * Meta Ads, SEO, X Ads) are gated on the user connecting the matching
- * MCP — the connect step in onboarding triggers provisioning via
- * provisionSpecialistForMcp as each token lands. Google Search Console
- * isn't its own specialist — connecting GSC provisions the SEO agent,
- * which uses GSC alongside on-page / technical SEO work.
- */
-export const DEFAULT_ONBOARDING_TEMPLATE_KEYS: AgentTemplateKey[] = ["cmo"];
-
-/**
- * Template key → MCP catalog key mapping for the specialists that the
- * onboarding connect step gates provisioning on. Inverse lookup
- * (MCP key → template key) used by provisionSpecialistForMcp when an
- * OAuth callback lands and we need to decide which specialist to mint.
- *
- * Notice GSC maps to `seo` — there's no dedicated GSC agent. The SEO
- * specialist owns search-console work as part of its broader remit
- * (technical SEO, content, ranking analysis). Google Analytics is
- * deliberately absent: its data serves the CMO + existing specialists,
- * so connecting it provisions no agent.
- */
-export const SPECIALIST_TEMPLATE_BY_MCP_KEY: Record<string, AgentTemplateKey> = {
- "notfair-googleads": "google_ads",
- "notfair-metaads": "meta_ads",
- "notfair-googlesearchconsole": "seo",
- "notfair-xads": "x_ads",
-};
-
-export function templateForKey(key: string): AgentTemplate | undefined {
- return TEMPLATES.find((t) => t.key === key || t.key.replace(/_/g, "-") === key);
-}
-
-export function templateForUrlSlug(slug: string): AgentTemplate | undefined {
- // URL slugs use hyphens (google-ads), template keys use underscores (google_ads).
- return TEMPLATES.find(
- (t) => t.key === slug || t.key.replace(/_/g, "-") === slug,
- );
-}
-
-export function urlSlugForTemplate(key: AgentTemplateKey): string {
- return key.replace(/_/g, "-");
-}
-
-export const TEMPLATES: AgentTemplate[] = [
- {
- key: "cmo",
- display_name: "CMO",
- default_name: "Greg",
- description: "Chief Marketing Officer. Owns strategy and orchestrates the specialist agents.",
- capabilities: [
- "Talk through marketing strategy and prioritization",
- "Propose experiments + 30-day plans",
- "Delegate work to specialist agents (Google Ads, Meta Ads, SEO, X Ads)",
- "Schedule recurring jobs via openclaw cron",
- "Coordinate signals across channels",
- ],
- model: "openai-codex/gpt-5.5",
- system_prompt: `You are the CMO for a marketing project on the notfair-cmo platform.
-
-${CMO_ROLE}`,
- default_onboarding: true,
- },
- {
- key: "google_ads",
- display_name: "Google Ads Specialist",
- default_name: "Ana",
- description: "Runs Google Ads campaigns, keywords, bids, budgets, search terms, negatives.",
- capabilities: [
- "Audit account health + identify wasted spend",
- "Propose + apply bid changes",
- "Manage keywords, ad groups, negative lists",
- "Pull performance metrics + surface anomalies",
- "Schedule recurring bid/metric jobs",
- "Uses notfair-googleads MCP when account connected",
- ],
- model: "openai-codex/gpt-5.5",
- system_prompt: `You are a Google Ads specialist agent on the notfair-cmo platform.
-
-${SPECIALIST_ROLE}
-
-## Your domain tools
-
-When the notfair-googleads MCP is connected to this project, use its
-\`runScript\` tool for everything — \`ads.gaql\` for single GAQL queries,
-\`ads.gaqlParallel\` to fan out audits across surfaces in one call. Cast
-a wide net on the first pass; filter in-script for free.
-
-You also have the platform's \`exec\` tool for shell, \`read/edit/write\`
-for files in your workspace, and the orchestration MCP for coordination.`,
- default_onboarding: false,
- requires_mcp_key: "notfair-googleads",
- },
- {
- key: "meta_ads",
- display_name: "Meta Ads Specialist",
- default_name: "Mia",
- description: "Runs Meta Ads (Facebook + Instagram) campaigns, ad sets, creative, audiences.",
- capabilities: [
- "Audit ad-account spend, ROAS, CPM, frequency",
- "Diagnose ad-set delivery + audience overlap",
- "Surface creative fatigue + winners",
- "Propose budget shifts + bid changes",
- "Schedule recurring performance + pacing checks",
- "Uses notfair-metaads MCP when account connected",
- ],
- model: "openai-codex/gpt-5.5",
- system_prompt: `You are a Meta Ads (Facebook + Instagram) specialist agent on the notfair-cmo platform.
-
-${SPECIALIST_ROLE}
-
-## Your domain tools
-
-When the notfair-metaads MCP is connected to this project, use its
-\`runScript\` tool for reads — \`ads.graph\` for single Graph API calls,
-\`ads.graphParallel\` to fan out across insights / adsets / creatives /
-account in one pass, and \`ads.insights\` for the conventional insights
-pull with sensible defaults. Cast a wide net on the first call; filter
-in-script for free.
-
-Domain conventions you should respect:
-- Refer to spend in account currency, not abstract units. Always quote
- numbers (spend, ROAS, CPM, CTR, freq) when reporting findings.
-- Default to the last 30 days for performance reads unless the brief
- asks for a different window. Use date_preset \`last_30d\` for
- consistency.
-- Audience overlap, creative fatigue, and CPM spikes are the three
- things to look for in a "what's wrong" pass; ROAS by ad set + by
- creative are the two things to look at in a "what's working" pass.
-
-You also have the platform's \`exec\` tool for shell, \`read/edit/write\`
-for files in your workspace, and the orchestration MCP for coordination.`,
- default_onboarding: false,
- requires_mcp_key: "notfair-metaads",
- },
- {
- key: "seo",
- display_name: "SEO Specialist",
- default_name: "Sam",
- description:
- "Organic search — Search Console performance, technical SEO, content recommendations.",
- capabilities: [
- "Pull Search Console performance (queries, pages, devices, countries)",
- "Surface query and page movers week-over-week",
- "Identify pages losing impressions or rankings",
- "Diagnose indexing issues + coverage gaps",
- "Audit on-page + technical SEO",
- "Propose content ideas based on keyword movers",
- "Schedule recurring ranking / click summaries",
- "Uses notfair-googlesearchconsole MCP when property connected",
- ],
- model: "openai-codex/gpt-5.5",
- system_prompt: `You are the SEO specialist agent on the notfair-cmo platform.
-
-${SPECIALIST_ROLE}
-
-## Your domain tools
-
-Your primary data source is the **notfair-googlesearchconsole** MCP
-(connected during onboarding). The selected GSC property
-(e.g. \`sc-domain:example.com\` or \`https://example.com/\`) is
-persisted on the project; every call you make should target that
-property unless the brief explicitly asks for another.
-
-Use the MCP to pull organic search performance (impressions, clicks,
-average position) sliced by query, page, country, device, or date.
-Combine that with on-page audits, technical SEO checks, schema
-recommendations, and internal-link analysis when the brief asks for
-broader SEO work.
-
-Domain conventions you should respect:
-- Always quote impressions, clicks, CTR, and average position when
- reporting Search Console findings. The user trusts numbers more than
- adjectives.
-- Default to the last 28 days for performance reads unless the brief
- asks otherwise. That window aligns with Search Console's native
- default and survives one-off Sunday spikes.
-- Lead with **movers**, not absolutes — surface queries and pages that
- moved week-over-week (impressions or position) rather than the static
- top-10 lists the user has already seen.
-- Pages losing impressions + dropping in position are the high-signal
- finding; pages with high impressions but low CTR are the high-leverage
- one. Frame recommendations around which is which.
-
-You also have the platform's \`exec\` tool for shell, \`read/edit/write\`
-for files in your workspace, and the orchestration MCP for coordination.`,
- default_onboarding: false,
- requires_mcp_key: "notfair-googlesearchconsole",
- },
- {
- key: "x_ads",
- display_name: "X Ads Specialist",
- default_name: "Max",
- description:
- "Runs X (Twitter) Ads campaigns, line items, promoted posts, targeting, budgets.",
- capabilities: [
- "Audit campaign + line-item spend, CPM, engagement",
- "Diagnose delivery + targeting issues",
- "Surface creative fatigue + winners on promoted posts",
- "Propose budget shifts + bid changes",
- "Schedule recurring performance + pacing checks",
- "Uses notfair-xads MCP when account connected",
- ],
- model: "openai-codex/gpt-5.5",
- system_prompt: `You are an X Ads (Twitter) specialist agent on the notfair-cmo platform.
-
-${SPECIALIST_ROLE}
-
-## Your domain tools
-
-When the notfair-xads MCP is connected to this project, use its tools
-for everything on the ads account — campaigns, line items (X's ad
-groups), promoted posts, funding instruments, targeting, and analytics.
-Prefer the widest read the surface offers on a first pass (analytics
-across all campaigns / line items), then narrow — one broad read beats
-many small calls.
-
-Domain conventions you should respect:
-- Refer to spend in account currency, not abstract units. Always quote
- numbers (spend, impressions, engagement rate, CPM, CTR) when
- reporting findings.
-- Default to the last 30 days for performance reads unless the brief
- asks for a different window.
-- X's structure is campaign → line item → promoted post. Bids,
- targeting, and placements live on the LINE ITEM — most "why is this
- campaign behaving oddly" questions resolve at line-item level.
-- Creative fatigue shows up fast on X: engagement rate decaying while
- frequency climbs is the first thing to check in a "what's wrong"
- pass; engagement rate + cost-per-engagement by promoted post is the
- "what's working" pass.
-
-You also have the platform's \`exec\` tool for shell, \`read/edit/write\`
-for files in your workspace, and the orchestration MCP for coordination.`,
- default_onboarding: false,
- requires_mcp_key: "notfair-xads",
- },
-];
-
-/**
- * Provision the specialist agent that matches a newly-connected MCP. Called
- * from the OAuth callback right after `setMcpBearer` lands a token. Looks
- * up the template via SPECIALIST_TEMPLATE_BY_MCP_KEY, then calls
- * ensureProjectAgents with that single template.
- *
- * Idempotent: if the agent already exists (user reconnected after a
- * disconnect, or token was set via a non-OAuth path that already
- * triggered provisioning), ensureProjectAgents returns it in `existed`
- * and writes no files.
- *
- * No-op when:
- * - The catalog_key isn't one of the recommended specialists (e.g.
- * Stripe / Supabase MCPs from the "More" tile — those don't get an
- * agent).
- * - The project doesn't exist (defensive — shouldn't happen via the
- * OAuth callback path which only runs after the project is created).
- */
-export async function provisionSpecialistForMcp(
- project_slug: string,
- catalog_key: string,
-): Promise<EnsureAgentsResult | null> {
- const template_key = SPECIALIST_TEMPLATE_BY_MCP_KEY[catalog_key];
- if (!template_key) return null;
- if (!getProject(project_slug)) return null;
- return ensureProjectAgents(project_slug, [template_key]);
-}
-
-export function agentNameFor(
- project_slug: string,
- template_key: AgentTemplate["key"],
- name: string,
-): string {
- // OpenClaw agent name format: <project-slug>-<role>-<slugified-name>
- // (e.g. `acme-cmo-greg`). Encoding the personal name in the backend
- // id keeps the agent_id and URL slug in lockstep: the URL slug is
- // exactly `<role>-<slugified-name>`, the project-prefix dropped.
- return `${project_slug}-${agentUrlSlug(template_key, name)}`;
-}
-
-/**
- * URL slug for a template agent — `<role>-<slugified-name>`. The personal
- * name is the user-chosen "Greg" / "Ana" etc; the role is the template
- * key (cmo, google_ads → google-ads). Examples:
- *
- * role=cmo, name=Greg → "cmo-greg"
- * role=google_ads, name="Ana Q4" → "google-ads-ana-q4"
- *
- * This slug appears in URLs (`/agents/cmo-greg/tasks`) and is what
- * resolveAgentBySlug looks up. It is computed — never stored — so a
- * future rename of an agent's name (currently not allowed) would just
- * flow through here. Because names are immutable post-creation, the
- * slug is effectively immutable too.
- */
-export function agentUrlSlug(
- template_key: AgentTemplate["key"],
- name: string,
-): string {
- const role = template_key.replace(/_/g, "-");
- return `${role}-${slugifyName(name)}`;
-}
-
-/**
- * Lowercase, hyphen-only, no leading/trailing dashes. Trims to a sane
- * length so a misbehaving name input can't blow up the URL.
- */
-export function slugifyName(name: string): string {
- return name
- .toLowerCase()
- .trim()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-+|-+$/g, "")
- .slice(0, 32);
-}
-
-export type EnsureAgentsResult = {
- created: string[];
- existed: string[];
- failed: Array<{ name: string; error: string }>;
-};
-
-/**
- * Idempotently provision OpenClaw agents for a project.
- *
- * Pass `scope` to provision only a subset (per D4: onboarding ships with CMO
- * + Google Ads only; SEO becomes opt-in later). Omit `scope` to provision
- * every template — preserved for back-compat with existing call sites like
- * the reprovision endpoint.
- *
- * `names` is an optional partial map of template_key → user-chosen personal
- * name (e.g. { cmo: "Greg", google_ads: "Ana" }). Names are immutable post-
- * creation — when the meta sidecar already has a `name`, we keep it and
- * IGNORE this argument for that agent. Templates with no entry here fall
- * back to the template's `default_name`.
- *
- * The result includes `failed`: when a subprocess fails for one agent, the
- * loop logs + continues (partial provisioning is recoverable) and the
- * caller can decide whether `failed.length > 0` is fatal for their flow.
- */
-export async function ensureProjectAgents(
- project_slug: string,
- scope?: AgentTemplateKey[],
- names?: Partial<Record<AgentTemplateKey, string>>,
-): Promise<EnsureAgentsResult> {
- const created: string[] = [];
- const existed: string[] = [];
- const failed: Array<{ name: string; error: string }> = [];
-
- const templates = scope
- ? TEMPLATES.filter((t) => scope.includes(t.key))
- : TEMPLATES;
-
- // Publish per-template progress so the onboarding setup screen can
- // render a live "Setting up CMO… / Setting up Google Ads agent…"
- // checklist instead of a single opaque spinner.
- const progressSteps: ProgressStep[] = templates.map<ProgressStep>((t) => ({
- key: t.key,
- // display_name carries the full role label now (e.g. "Google Ads
- // Specialist"), so no suffix kludge.
- label: `Setting up ${t.display_name}`,
- status: "pending",
- }));
- initProgress(project_slug, progressSteps);
-
- // Adapter for this project (chosen at onboarding). All harness-specific
- // workspace writes route through it.
- const project = getProject(project_slug);
- const harnessAdapter = project?.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;
-
- // Project brief is shared across every agent in the project; read once.
- const brief = await readProjectBrief(project_slug).catch(() => null);
- const skill = getOrchestrationSkill();
-
- for (const template of templates) {
- updateStep(project_slug, template.key, { status: "in_progress" });
- const personalName = names?.[template.key] ?? template.default_name;
- const agentId = agentNameFor(project_slug, template.key, personalName);
- const already = await agentExists(agentId);
-
- try {
- const identityMd = renderIdentity({
- template,
- project_slug,
- agent_id: agentId,
- skill,
- brief,
- });
- await provisionAgent({
- projectSlug: project_slug,
- agentId,
- displayName: personalName,
- templateKey: template.key,
- identityMd,
- skillMd: skill,
- projectMd: brief ?? undefined,
- harnessAdapter,
- });
- // Wire notfair-orchestration MCP for this agent so create_task /
- // submit_task_status / request_approval etc. are callable. Best-effort.
- try {
- await registerOrchestrationForAgent(project_slug, agentId);
- } catch (err) {
- console.warn(
- `[provision] orchestration MCP registration failed for ${agentId}:`,
- err,
- );
- }
- // Wire notfair-browser MCP for this agent so browser_open /
- // browser_snapshot / browser_click etc. are callable. Best-effort —
- // an agent without browser access still has all task tooling.
- try {
- await registerBrowserMcpForAgent(project_slug, agentId);
- } catch (err) {
- console.warn(
- `[provision] browser MCP registration failed for ${agentId}:`,
- err,
- );
- }
- // Also wire any external catalog MCPs the project already has tokens
- // for (e.g. Google Ads was connected before this agent was created).
- // Without this, a new agent in an established project sees the
- // orchestration MCP but not the catalog ones the others can see.
- try {
- const { listProjectMcpTokens } = await import("@/server/mcp/tokens");
- const { registerCatalogMcpForAgent } = await import(
- "@/server/mcp-server/registration"
- );
- const tokens = listProjectMcpTokens(project_slug);
- for (const t of tokens) {
- await registerCatalogMcpForAgent(project_slug, t.server_name, agentId);
- }
- } catch (err) {
- console.warn(
- `[provision] catalog MCP registration failed for ${agentId}:`,
- err,
- );
- }
- if (already) {
- const existing = readAgentMeta(agentId);
- const finalName = existing?.name ?? personalName;
- await writeAgentMeta({
- agent_id: agentId,
- project_slug,
- name: finalName,
- template_key: template.key,
- created_at: existing?.created_at ?? new Date().toISOString(),
- });
- existed.push(agentId);
- } else {
- await writeAgentMeta({
- agent_id: agentId,
- project_slug,
- name: personalName,
- template_key: template.key,
- created_at: new Date().toISOString(),
- });
- created.push(agentId);
- }
- updateStep(project_slug, template.key, { status: "done" });
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- console.error(`Failed to provision agent ${agentId}:`, err);
- failed.push({ name: agentId, error: message });
- updateStep(project_slug, template.key, { status: "failed", error: message });
- }
- }
-
- // Adapter-specific MCP registration for the notfair-orchestration server
- // happens in src/server/mcp-server/registration.ts now (called from the
- // onboarding/provision routes). Schema-side scaffolding only here.
-
- return { created, existed, failed };
-}
-
-/**
- * Render the full IDENTITY.md body for an agent. Pure — caller writes it via
- * the adapter so the harness sees the file under whichever name it expects
- * (CLAUDE.md for Claude Code, AGENTS.md for Codex).
- */
-function renderIdentity(input: {
- template: AgentTemplate;
- project_slug: string;
- agent_id: string;
- skill: string;
- brief: string | null;
-}): string {
- const identityBlock = `\n## Your runtime identity\n\nWhen calling notfair-orchestration MCP tools, pass these exact values:\n\n- \`project_slug\`: \`${input.project_slug}\`\n- \`agent_id\`: \`${input.agent_id}\`\n\nDo NOT invent other values. Every orchestration tool call requires both.\n`;
- const projectContextSection = input.brief
- ? `\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${input.brief.trim()}\n`
- : "";
- return `# ${input.template.display_name}
-
-${input.template.description}
-${identityBlock}${projectContextSection}
-${input.template.system_prompt}
-
----
-
-${input.skill}`;
-}
-
-/**
- * Re-render IDENTITY.md / SKILL.md / PROJECT.md for every agent in a project
- * via the project's harness adapter. Called by the `set_project_brief` MCP
- * handler after the canonical PROJECT.md is updated, so specialists pick up
- * the new context without waiting for the next ensureProjectAgents pass.
- */
-export async function syncProjectBriefToAgents(
- project_slug: string,
-): Promise<{ synced: string[]; failed: Array<{ name: string; error: string }> }> {
- const { listProjectAgents } = await import("./agent-meta");
- const synced: string[] = [];
- const failed: Array<{ name: string; error: string }> = [];
-
- const project = getProject(project_slug);
- const harnessAdapter = project?.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;
- const brief = await readProjectBrief(project_slug).catch(() => null);
- const skill = getOrchestrationSkill();
- const entries = await listProjectAgents(project_slug);
-
- for (const entry of entries) {
- if (!entry.template_key) {
- synced.push(entry.agent_id);
- 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 identityMd = renderIdentity({
- template,
- project_slug,
- agent_id: entry.agent_id,
- skill,
- brief,
- });
- await provisionAgent({
- projectSlug: project_slug,
- agentId: entry.agent_id,
- displayName: entry.name,
- templateKey: entry.template_key,
- identityMd,
- skillMd: skill,
- projectMd: brief ?? undefined,
- harnessAdapter,
- });
- synced.push(entry.agent_id);
- } catch (err) {
- failed.push({
- name: entry.agent_id,
- error: err instanceof Error ? err.message : String(err),
- });
- }
- }
-
- return { synced, failed };
-}
-
-/**
- * Check if an agent workspace has been provisioned. Replaces the OpenClaw
- * `agents list` grep — we now own the workspace dir, so a stat suffices.
- */
-export async function agentExists(name: string): Promise<boolean> {
- try {
- const dir = agentWorkspaceDirFor(name);
- const s = await stat(dir);
- return s.isDirectory();
- } catch {
- return false;
- }
-}
diff --git a/notfair-cmo/src/server/agents/skills.ts b/notfair-cmo/src/server/agents/skills.ts
deleted file mode 100644
index ce4f8ee6..00000000
--- a/notfair-cmo/src/server/agents/skills.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { existsSync } from "node:fs";
-import { readFile } from "node:fs/promises";
-import { join } from "node:path";
-import { workspaceDirFor } from "./provisioning";
-
-/**
- * Skill listing — replaces the OpenClaw gateway RPC that backed the per-agent
- * Skills tab. With the harness-adapter model, "skills" are workspace files
- * (SKILL.md, PROJECT.md, IDENTITY.md) that every adapter consumes the same way.
- *
- * For now we expose just the orchestration SKILL.md as the single "skill"
- * every agent has. Future adapters that expose discoverable skills (Claude
- * Code Skills, Codex prompts) can extend this list via adapter introspection.
- */
-export interface SkillEntry {
- key: string;
- name: string;
- description: string;
- enabled: boolean;
- scope: "workspace" | "global";
- source?: string;
-}
-
-export interface SkillStatus {
- skills: SkillEntry[];
-}
-
-export async function getSkillStatus(agent_id: string): Promise<SkillStatus> {
- const skills: SkillEntry[] = [];
- const dir = workspaceDirFor(agent_id);
-
- const skillPath = join(dir, "SKILL.md");
- if (existsSync(skillPath)) {
- let description = "Orchestration skill.";
- try {
- const raw = await readFile(skillPath, "utf8");
- const firstLine = raw.split("\n").find((l) => l.trim().length > 0);
- if (firstLine) description = firstLine.replace(/^#+\s*/, "").slice(0, 200);
- } catch {
- // best-effort
- }
- skills.push({
- key: "notfair-orchestration",
- name: "Orchestration",
- description,
- enabled: true,
- scope: "workspace",
- source: skillPath,
- });
- }
-
- return { skills };
-}
diff --git a/notfair-cmo/src/server/browser/actions.test.ts b/notfair-cmo/src/server/browser/actions.test.ts
deleted file mode 100644
index 2be882cb..00000000
--- a/notfair-cmo/src/server/browser/actions.test.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-import type { Page } from "playwright-core";
-import {
- back,
- click,
- navigate,
- press,
- scroll,
- type as typeAction,
-} from "./actions";
-
-// ── Page fake — only the surface our action layer actually touches ───────
-
-interface LocatorCalls {
- click?: unknown;
- dblclick?: unknown;
- fill?: unknown[];
- press?: unknown[];
-}
-
-function makeLocatorRecorder() {
- const byRef = new Map<string, LocatorCalls>();
- const locator = (selector: string) => {
- const ref = selector.match(/data-notfair-ref="([^"]+)"/)?.[1] ?? "?";
- if (!byRef.has(ref)) byRef.set(ref, { fill: [], press: [] });
- const calls = byRef.get(ref)!;
- return {
- click: vi.fn(async (opts?: unknown) => {
- calls.click = opts;
- }),
- dblclick: vi.fn(async (opts?: unknown) => {
- calls.dblclick = opts;
- }),
- fill: vi.fn(async (text: string, opts?: unknown) => {
- calls.fill!.push({ text, opts });
- }),
- press: vi.fn(async (key: string, opts?: unknown) => {
- calls.press!.push({ key, opts });
- }),
- };
- };
- return { locator, byRef };
-}
-
-function makePage(rec: ReturnType<typeof makeLocatorRecorder>) {
- const keyboardPress = vi.fn(async (_key: string) => {});
- const evaluateCalls: unknown[] = [];
- const page = {
- url: () => "https://example.com",
- title: async () => "Example",
- goto: vi.fn(async (_url: string, _opts?: unknown) => null),
- goBack: vi.fn(async (_opts?: unknown) => null),
- locator: rec.locator,
- keyboard: { press: keyboardPress },
- evaluate: vi.fn(async (_fn: unknown, arg?: unknown) => {
- evaluateCalls.push(arg);
- }),
- } as unknown as Page;
- return { page, keyboardPress, evaluateCalls };
-}
-
-// ── navigate ─────────────────────────────────────────────────────────────
-
-describe("navigate", () => {
- it("calls page.goto with defaults and returns url+title", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- const result = await navigate(page, { url: "https://example.com" });
- expect(page.goto).toHaveBeenCalledWith("https://example.com", {
- waitUntil: "load",
- timeout: 30_000,
- });
- expect(result).toEqual({ url: "https://example.com", title: "Example" });
- });
-
- it("honors caller-supplied waitUntil + timeoutMs", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await navigate(page, {
- url: "https://example.com",
- waitUntil: "networkidle",
- timeoutMs: 5_000,
- });
- expect(page.goto).toHaveBeenCalledWith("https://example.com", {
- waitUntil: "networkidle",
- timeout: 5_000,
- });
- });
-});
-
-// ── click ────────────────────────────────────────────────────────────────
-
-describe("click", () => {
- it("rejects refs that don't match e<number>", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await expect(click(page, { ref: "weird" })).rejects.toThrow(/Invalid ref/);
- });
-
- it("issues a single click by default", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await click(page, { ref: "e3" });
- expect(rec.byRef.get("e3")?.click).toBeDefined();
- expect(rec.byRef.get("e3")?.dblclick).toBeUndefined();
- });
-
- it("issues a double-click when requested", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await click(page, { ref: "e1", doubleClick: true });
- expect(rec.byRef.get("e1")?.dblclick).toBeDefined();
- expect(rec.byRef.get("e1")?.click).toBeUndefined();
- });
-
- it("forwards button and modifiers to Playwright", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await click(page, {
- ref: "e2",
- button: "right",
- modifiers: ["Meta", "Shift"],
- });
- expect(rec.byRef.get("e2")?.click).toMatchObject({
- button: "right",
- modifiers: ["Meta", "Shift"],
- });
- });
-});
-
-// ── type ─────────────────────────────────────────────────────────────────
-
-describe("type", () => {
- it("clears the field then fills with the new text", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await typeAction(page, { ref: "e5", text: "hello world" });
- const fills = rec.byRef.get("e5")?.fill ?? [];
- expect(fills.length).toBe(2);
- expect((fills[0] as { text: string }).text).toBe("");
- expect((fills[1] as { text: string }).text).toBe("hello world");
- });
-
- it("skips the clear when clearFirst is explicitly false", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await typeAction(page, { ref: "e5", text: "append", clearFirst: false });
- const fills = rec.byRef.get("e5")?.fill ?? [];
- expect(fills.length).toBe(1);
- expect((fills[0] as { text: string }).text).toBe("append");
- });
-
- it("presses Enter after typing when submit is true", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await typeAction(page, { ref: "e5", text: "search", submit: true });
- const presses = rec.byRef.get("e5")?.press ?? [];
- expect(presses).toHaveLength(1);
- expect((presses[0] as { key: string }).key).toBe("Enter");
- });
-});
-
-// ── press ────────────────────────────────────────────────────────────────
-
-describe("press", () => {
- it("presses on a locator when ref is supplied", async () => {
- const rec = makeLocatorRecorder();
- const { page, keyboardPress } = makePage(rec);
- await press(page, { ref: "e1", key: "Tab" });
- expect((rec.byRef.get("e1")?.press ?? [])[0]).toMatchObject({ key: "Tab" });
- expect(keyboardPress).not.toHaveBeenCalled();
- });
-
- it("presses at page level when ref is omitted", async () => {
- const rec = makeLocatorRecorder();
- const { page, keyboardPress } = makePage(rec);
- await press(page, { key: "Escape" });
- expect(keyboardPress).toHaveBeenCalledWith("Escape");
- });
-});
-
-// ── scroll ───────────────────────────────────────────────────────────────
-
-describe("scroll", () => {
- it.each([
- ["up", { x: 0, y: -600 }],
- ["down", { x: 0, y: 600 }],
- ["left", { x: -600, y: 0 }],
- ["right", { x: 600, y: 0 }],
- ] as const)("scrolls %s by default amount", async (direction, expected) => {
- const rec = makeLocatorRecorder();
- const { page, evaluateCalls } = makePage(rec);
- await scroll(page, { direction });
- expect(evaluateCalls).toContainEqual(expected);
- });
-
- it("honors a custom amount", async () => {
- const rec = makeLocatorRecorder();
- const { page, evaluateCalls } = makePage(rec);
- await scroll(page, { direction: "down", amount: 1200 });
- expect(evaluateCalls).toContainEqual({ x: 0, y: 1200 });
- });
-});
-
-// ── back ─────────────────────────────────────────────────────────────────
-
-describe("back", () => {
- it("calls page.goBack with load wait", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- await back(page);
- expect(page.goBack).toHaveBeenCalledWith({ waitUntil: "load" });
- });
-
- it("swallows navigation errors (back on first page is normal)", async () => {
- const rec = makeLocatorRecorder();
- const { page } = makePage(rec);
- (page.goBack as ReturnType<typeof vi.fn>).mockRejectedValue(new Error("no history"));
- await expect(back(page)).resolves.toBeUndefined();
- });
-});
diff --git a/notfair-cmo/src/server/browser/browser.e2e.test.ts b/notfair-cmo/src/server/browser/browser.e2e.test.ts
deleted file mode 100644
index 0f361f9c..00000000
--- a/notfair-cmo/src/server/browser/browser.e2e.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * Real-Chrome smoke test.
- *
- * Skipped unless BOTH of the following are true:
- * - findChromeExecutable() finds a Chromium-family binary on the host
- * - NOTFAIR_E2E_BROWSER=1 in the env (gated so day-to-day `pnpm test`
- * stays fast and offline-safe)
- *
- * Confirms the actual wire works end-to-end: Chrome launches, Playwright
- * attaches via CDP, a tab navigates to a data: URL, snapshot extracts
- * interactable elements, click fires the inline handler, type fills the
- * input, scroll moves the viewport, close tears it down.
- *
- * Run locally: `NOTFAIR_E2E_BROWSER=1 pnpm test browser.e2e`
- */
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
-
-import { findChromeExecutable } from "./chrome";
-import { click, navigate, snapshot, scroll, type as typeAction } from "./actions";
-import {
- _sessionsByProject,
- getOrLaunchBrowser,
- stopAllBrowsers,
-} from "./session";
-import { _resetTabRegistries, closeTab, listTabs, openTab } from "./tabs";
-
-const SKIP =
- process.env.NOTFAIR_E2E_BROWSER !== "1" || findChromeExecutable() === null;
-
-const PROJECT_SLUG = "e2e-smoke";
-const TEST_HTML = encodeURIComponent(`
- <!DOCTYPE html>
- <html>
- <head><title>e2e smoke</title></head>
- <body style="height: 3000px">
- <h1 id="heading">hello e2e</h1>
- <button id="b1" onclick="window.__clicked = (window.__clicked||0)+1">click me</button>
- <input id="i1" placeholder="type here" />
- <span id="counter">0</span>
- </body>
- </html>
-`);
-const TEST_URL = `data:text/html,${TEST_HTML}`;
-
-let dataDir: string;
-
-beforeAll(() => {
- if (SKIP) return;
- dataDir = mkdtempSync(join(tmpdir(), "notfair-cmo-e2e-"));
- process.env.NOTFAIR_CMO_DATA_DIR = dataDir;
- // Headless on CI/local runs; this is a smoke test, not a UX test.
- process.env.NOTFAIR_BROWSER_HEADLESS = "1";
-});
-
-afterAll(async () => {
- if (SKIP) return;
- await stopAllBrowsers();
- _resetTabRegistries();
- _sessionsByProject.clear();
- if (dataDir) rmSync(dataDir, { recursive: true, force: true });
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- delete process.env.NOTFAIR_BROWSER_HEADLESS;
-});
-
-describe.skipIf(SKIP)("browser E2E smoke (real Chrome)", () => {
- it(
- "launches Chrome, snapshots a page, clicks + types + scrolls, then closes the tab",
- { timeout: 60_000 },
- async () => {
- const session = await getOrLaunchBrowser(PROJECT_SLUG);
- expect(session.launched.process.exitCode).toBeNull();
-
- const handle = await openTab(PROJECT_SLUG, { label: "smoke", url: TEST_URL });
- expect(handle.id).toBe("smoke");
- expect(handle.url).toContain("data:text/html");
-
- const page = (await import("./tabs")).getTab.bind(null);
- const livePage = await page(PROJECT_SLUG, "smoke");
- expect(livePage).not.toBeNull();
- if (!livePage) throw new Error("unreachable");
-
- // Navigate via the action layer to a fresh page so we exercise it too.
- const navResult = await navigate(livePage, { url: TEST_URL });
- expect(navResult.title).toBe("e2e smoke");
-
- // Snapshot must find the button + input.
- const snap = await snapshot(livePage);
- const button = snap.elements.find((e) => e.name === "click me");
- const input = snap.elements.find((e) => e.role === "input");
- expect(button).toBeDefined();
- expect(input).toBeDefined();
-
- // Click the button — inline handler should bump window.__clicked.
- await click(livePage, { ref: button!.ref });
- const clickedCount = await livePage.evaluate(() => (window as unknown as { __clicked?: number }).__clicked);
- expect(clickedCount).toBe(1);
-
- // Type into the input and verify the value sticks.
- await typeAction(livePage, { ref: input!.ref, text: "hello world" });
- const typedValue = await livePage.evaluate(
- () => (document.querySelector("#i1") as HTMLInputElement).value,
- );
- expect(typedValue).toBe("hello world");
-
- // Scroll and verify scrollY moved.
- await scroll(livePage, { direction: "down", amount: 500 });
- const scrollY = await livePage.evaluate(() => window.scrollY);
- expect(scrollY).toBeGreaterThan(0);
-
- // List tabs sanity.
- const tabs = await listTabs(PROJECT_SLUG);
- expect(tabs.some((t) => t.id === "smoke")).toBe(true);
-
- // Close the tab.
- const closed = await closeTab(PROJECT_SLUG, "smoke");
- expect(closed).toBe(true);
- },
- );
-});
diff --git a/notfair-cmo/src/server/browser/chrome.test.ts b/notfair-cmo/src/server/browser/chrome.test.ts
deleted file mode 100644
index 1da39ec1..00000000
--- a/notfair-cmo/src/server/browser/chrome.test.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- buildChromeLaunchArgs,
- clearChromeSingletonArtifacts,
- findChromeExecutable,
- waitForCdpReady,
-} from "./chrome";
-
-describe("findChromeExecutable", () => {
- it("returns NOTFAIR_CHROME_PATH when set and the file exists", () => {
- const env = { NOTFAIR_CHROME_PATH: "/custom/chrome" };
- const result = findChromeExecutable(env, "darwin", (p) => p === "/custom/chrome");
- expect(result).toBe("/custom/chrome");
- });
-
- it("ignores NOTFAIR_CHROME_PATH when the file does not exist and falls through to defaults", () => {
- const env = { NOTFAIR_CHROME_PATH: "/missing" };
- const result = findChromeExecutable(env, "darwin", (p) =>
- p === "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- );
- expect(result).toBe(
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- );
- });
-
- it("probes macOS Chrome locations on darwin", () => {
- const result = findChromeExecutable(
- {},
- "darwin",
- (p) => p === "/Applications/Chromium.app/Contents/MacOS/Chromium",
- );
- expect(result).toBe("/Applications/Chromium.app/Contents/MacOS/Chromium");
- });
-
- it("probes Linux locations on linux", () => {
- const result = findChromeExecutable({}, "linux", (p) => p === "/usr/bin/chromium");
- expect(result).toBe("/usr/bin/chromium");
- });
-
- it("returns null when nothing matches", () => {
- const result = findChromeExecutable({}, "darwin", () => false);
- expect(result).toBeNull();
- });
-
- it("returns null on unsupported platforms (win32 stub for now)", () => {
- const result = findChromeExecutable({}, "win32", () => true);
- expect(result).toBeNull();
- });
-});
-
-describe("buildChromeLaunchArgs", () => {
- const base = {
- executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- userDataDir: "/tmp/profile",
- cdpPort: 19042,
- };
-
- it("includes the required CDP + user-data-dir flags", () => {
- const args = buildChromeLaunchArgs(base);
- expect(args).toContain("--remote-debugging-port=19042");
- expect(args).toContain("--user-data-dir=/tmp/profile");
- });
-
- it("omits headless flags by default", () => {
- const args = buildChromeLaunchArgs(base);
- expect(args).not.toContain("--headless=new");
- expect(args).not.toContain("--disable-gpu");
- });
-
- it("adds --headless=new and --disable-gpu when headless=true", () => {
- const args = buildChromeLaunchArgs({ ...base, headless: true });
- expect(args).toContain("--headless=new");
- expect(args).toContain("--disable-gpu");
- });
-
- it("adds --disable-dev-shm-usage on linux only", () => {
- expect(buildChromeLaunchArgs({ ...base, platform: "linux" })).toContain(
- "--disable-dev-shm-usage",
- );
- expect(buildChromeLaunchArgs({ ...base, platform: "darwin" })).not.toContain(
- "--disable-dev-shm-usage",
- );
- });
-
- it("appends extraArgs verbatim at the end", () => {
- const args = buildChromeLaunchArgs({
- ...base,
- extraArgs: ["--window-size=1280,800", "--proxy-server=127.0.0.1:8888"],
- });
- expect(args.slice(-2)).toEqual([
- "--window-size=1280,800",
- "--proxy-server=127.0.0.1:8888",
- ]);
- });
-
- it("disables Chrome onboarding + crash bubbles that block agent flows", () => {
- const args = buildChromeLaunchArgs(base);
- expect(args).toContain("--no-first-run");
- expect(args).toContain("--no-default-browser-check");
- expect(args).toContain("--disable-session-crashed-bubble");
- expect(args).toContain("--hide-crash-restore-bubble");
- });
-});
-
-describe("clearChromeSingletonArtifacts", () => {
- let dir: string;
- beforeEach(() => {
- dir = mkdtempSync(path.join(tmpdir(), "notfair-cmo-chrome-test-"));
- });
- afterEach(() => {
- rmSync(dir, { recursive: true, force: true });
- });
-
- it("removes SingletonLock, SingletonSocket, and SingletonCookie", () => {
- for (const f of ["SingletonLock", "SingletonSocket", "SingletonCookie"]) {
- writeFileSync(path.join(dir, f), "");
- }
- clearChromeSingletonArtifacts(dir);
- expect(fs.existsSync(path.join(dir, "SingletonLock"))).toBe(false);
- expect(fs.existsSync(path.join(dir, "SingletonSocket"))).toBe(false);
- expect(fs.existsSync(path.join(dir, "SingletonCookie"))).toBe(false);
- });
-
- it("leaves unrelated files alone", () => {
- writeFileSync(path.join(dir, "SingletonLock"), "");
- writeFileSync(path.join(dir, "Preferences"), "{}");
- clearChromeSingletonArtifacts(dir);
- expect(fs.existsSync(path.join(dir, "Preferences"))).toBe(true);
- });
-
- it("no-ops when the dir or files don't exist", () => {
- expect(() => clearChromeSingletonArtifacts("/nonexistent/path/here")).not.toThrow();
- });
-});
-
-describe("waitForCdpReady", () => {
- const originalFetch = globalThis.fetch;
- afterEach(() => {
- globalThis.fetch = originalFetch;
- vi.useRealTimers();
- });
-
- it("resolves when /json/version returns 200", async () => {
- globalThis.fetch = vi
- .fn()
- .mockResolvedValue(new Response("ok", { status: 200 })) as typeof fetch;
- await expect(
- waitForCdpReady("http://127.0.0.1:19042", 500, 10),
- ).resolves.toBeUndefined();
- });
-
- it("retries on transient errors then succeeds", async () => {
- let attempts = 0;
- globalThis.fetch = vi.fn().mockImplementation(async () => {
- attempts++;
- if (attempts < 3) throw new Error("connection refused");
- return new Response("ok", { status: 200 });
- }) as typeof fetch;
- await expect(
- waitForCdpReady("http://127.0.0.1:19042", 1000, 10),
- ).resolves.toBeUndefined();
- expect(attempts).toBeGreaterThanOrEqual(3);
- });
-
- it("rejects with the last error message when the deadline passes", async () => {
- globalThis.fetch = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")) as typeof fetch;
- await expect(
- waitForCdpReady("http://127.0.0.1:19042", 50, 10),
- ).rejects.toThrow(/did not become ready within 50ms.*ECONNREFUSED/);
- });
-
- it("treats non-200 responses as not-ready", async () => {
- globalThis.fetch = vi
- .fn()
- .mockResolvedValue(new Response("server starting", { status: 503 })) as typeof fetch;
- await expect(
- waitForCdpReady("http://127.0.0.1:19042", 50, 10),
- ).rejects.toThrow(/status 503/);
- });
-});
diff --git a/notfair-cmo/src/server/browser/paths.test.ts b/notfair-cmo/src/server/browser/paths.test.ts
deleted file mode 100644
index 2a14f5b0..00000000
--- a/notfair-cmo/src/server/browser/paths.test.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-
-import {
- CDP_PORT_RANGE_END,
- CDP_PORT_RANGE_START,
- allocateCdpPort,
- isValidProjectSlug,
- notfairDataDir,
- resolveBrowserProfileDir,
- resolveUserDataDir,
-} from "./paths";
-
-describe("isValidProjectSlug", () => {
- it.each([
- "acme",
- "acme-co",
- "a1",
- "0-foo",
- "x".repeat(64),
- ])("accepts %s", (slug) => {
- expect(isValidProjectSlug(slug)).toBe(true);
- });
-
- it.each([
- "",
- "ACME",
- "acme co",
- "acme_co",
- "-acme",
- "x".repeat(65),
- "acme.co",
- ])("rejects %s", (slug) => {
- expect(isValidProjectSlug(slug)).toBe(false);
- });
-});
-
-describe("notfairDataDir", () => {
- let originalEnv: string | undefined;
- beforeEach(() => {
- originalEnv = process.env.NOTFAIR_CMO_DATA_DIR;
- });
- afterEach(() => {
- if (originalEnv === undefined) delete process.env.NOTFAIR_CMO_DATA_DIR;
- else process.env.NOTFAIR_CMO_DATA_DIR = originalEnv;
- });
-
- it("uses env override when set", () => {
- process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
- expect(notfairDataDir()).toBe("/tmp/notfair-cmo-test");
- });
-
- it("falls back to ~/.notfair-cmo when env not set", () => {
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- expect(notfairDataDir()).toBe(join(homedir(), ".notfair-cmo"));
- });
-});
-
-describe("resolveBrowserProfileDir / resolveUserDataDir", () => {
- beforeEach(() => {
- process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
- });
- afterEach(() => {
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- });
-
- it("nests profile dir under projects/<slug>/browser", () => {
- expect(resolveBrowserProfileDir("acme")).toBe(
- "/tmp/notfair-cmo-test/projects/acme/browser",
- );
- });
-
- it("nests user-data dir under the profile dir", () => {
- expect(resolveUserDataDir("acme")).toBe(
- "/tmp/notfair-cmo-test/projects/acme/browser/user-data",
- );
- });
-
- it("throws on invalid slug", () => {
- expect(() => resolveBrowserProfileDir("Invalid Slug")).toThrow(/Invalid project slug/);
- expect(() => resolveUserDataDir("")).toThrow(/Invalid project slug/);
- });
-});
-
-describe("allocateCdpPort", () => {
- it("returns a port in the configured range", () => {
- const port = allocateCdpPort("acme");
- expect(port).toBeGreaterThanOrEqual(CDP_PORT_RANGE_START);
- expect(port).toBeLessThanOrEqual(CDP_PORT_RANGE_END);
- });
-
- it("is deterministic for the same slug", () => {
- expect(allocateCdpPort("acme")).toBe(allocateCdpPort("acme"));
- expect(allocateCdpPort("xyz-123")).toBe(allocateCdpPort("xyz-123"));
- });
-
- it("distributes across the range for different slugs (hash spreads)", () => {
- const seen = new Set<number>();
- for (let i = 0; i < 50; i++) {
- seen.add(allocateCdpPort(`project-${i}`));
- }
- // 50 slugs into a 100-port space. Birthday-paradox expected distinct ≈ 39.
- // We just want to prove the hash isn't degenerate; require >30 to give
- // headroom over the expected value while staying deterministic.
- expect(seen.size).toBeGreaterThan(30);
- });
-
- it("throws on invalid slug", () => {
- expect(() => allocateCdpPort("Invalid")).toThrow(/Invalid project slug/);
- });
-});
diff --git a/notfair-cmo/src/server/browser/session.test.ts b/notfair-cmo/src/server/browser/session.test.ts
deleted file mode 100644
index 56320183..00000000
--- a/notfair-cmo/src/server/browser/session.test.ts
+++ /dev/null
@@ -1,312 +0,0 @@
-import { EventEmitter } from "node:events";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { ChromeLaunchOptions, LaunchedChrome } from "./chrome";
-import type { Browser, BrowserContext } from "playwright-core";
-import {
- _sessionsByProject,
- _stopIdleChecker,
- checkIdleSessions,
- getOrLaunchBrowser,
- getSessionStatus,
- stopAllBrowsers,
- stopBrowser,
-} from "./session";
-
-// ── Fakes ────────────────────────────────────────────────────────────────
-
-class FakeProcess extends EventEmitter {
- exitCode: number | null = null;
- killed = false;
- kill(_signal?: string) {
- if (this.exitCode === null) {
- this.exitCode = 0;
- this.killed = true;
- setImmediate(() => this.emit("exit", 0, null));
- }
- return true;
- }
-}
-
-function makeLaunched(port: number): LaunchedChrome {
- return {
- process: new FakeProcess() as unknown as LaunchedChrome["process"],
- cdpPort: port,
- cdpHttpUrl: `http://127.0.0.1:${port}`,
- userDataDir: `/tmp/notfair-cmo-test/projects/acme/browser/user-data`,
- };
-}
-
-function makeFakeBrowser(): { browser: Browser; context: BrowserContext; closed: () => boolean } {
- let closedFlag = false;
- const context = {
- pages: () => [],
- on: vi.fn(),
- once: vi.fn(),
- newPage: vi.fn(),
- close: vi.fn(async () => {}),
- } as unknown as BrowserContext;
- const browser = {
- contexts: () => [context],
- close: vi.fn(async () => {
- closedFlag = true;
- }),
- } as unknown as Browser;
- return { browser, context, closed: () => closedFlag };
-}
-
-beforeEach(() => {
- process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
- process.env.NOTFAIR_CHROME_PATH = "/usr/bin/fake-chrome";
- _sessionsByProject.clear();
- // Cancel any leftover ticker so cross-test interactions are deterministic.
- // The ticker fires every 30s; test durations are <1s, so we're not racing
- // mid-test, but we still keep the slate clean.
- _stopIdleChecker();
-});
-
-afterEach(async () => {
- await stopAllBrowsers();
- _stopIdleChecker();
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- delete process.env.NOTFAIR_CHROME_PATH;
- delete process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS;
-});
-
-// ── Tests ────────────────────────────────────────────────────────────────
-
-describe("getOrLaunchBrowser", () => {
- it("launches Chrome and attaches Playwright on first call", async () => {
- const launch = vi.fn(async (_opts: ChromeLaunchOptions) => makeLaunched(19042));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- const session = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
-
- expect(launch).toHaveBeenCalledOnce();
- expect(connectOverCDP).toHaveBeenCalledWith("http://127.0.0.1:19042");
- expect(session.projectSlug).toBe("acme");
- expect(session.browser).toBe(fake.browser);
- expect(session.context).toBe(fake.context);
- });
-
- it("reuses the cached session on subsequent calls", async () => {
- const launch = vi.fn(async () => makeLaunched(19042));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- const a = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- const b = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
-
- expect(a).toBe(b);
- expect(launch).toHaveBeenCalledOnce();
- expect(connectOverCDP).toHaveBeenCalledOnce();
- });
-
- it("dedupes concurrent launches with the same slug", async () => {
- let launchCount = 0;
- const launch = vi.fn(async () => {
- launchCount++;
- await new Promise((r) => setTimeout(r, 20));
- return makeLaunched(19042);
- });
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- const [a, b, c] = await Promise.all([
- getOrLaunchBrowser("acme", { launch, connectOverCDP }),
- getOrLaunchBrowser("acme", { launch, connectOverCDP }),
- getOrLaunchBrowser("acme", { launch, connectOverCDP }),
- ]);
-
- expect(launchCount).toBe(1);
- expect(a).toBe(b);
- expect(b).toBe(c);
- });
-
- it("relaunches when the cached session's Chrome process has exited", async () => {
- const launch = vi
- .fn<(opts: ChromeLaunchOptions) => Promise<LaunchedChrome>>()
- .mockImplementationOnce(async () => makeLaunched(19042))
- .mockImplementationOnce(async () => makeLaunched(19043));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- const first = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- // Simulate Chrome dying.
- (first.launched.process as unknown as FakeProcess).kill();
- await new Promise((r) => setImmediate(r));
-
- const second = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- expect(second).not.toBe(first);
- expect(launch).toHaveBeenCalledTimes(2);
- });
-
- it("throws a friendly error when Chrome cannot be found", async () => {
- // Override findChromeExecutable's discovery path by passing an empty
- // executablePath (falsy, so the lookup fallback runs but lands on the
- // null branch — explicit empty string sidesteps the env/file probe).
- const launch = vi.fn();
- const connectOverCDP = vi.fn();
- await expect(
- getOrLaunchBrowser("acme", {
- executablePath: "",
- launch,
- connectOverCDP,
- }),
- ).rejects.toThrow(/Could not find Chrome/);
- expect(launch).not.toHaveBeenCalled();
- });
-
- it("cleans up Chrome when Playwright attach fails", async () => {
- const launched = makeLaunched(19042);
- const launch = vi.fn(async () => launched);
- const connectOverCDP = vi.fn(async () => {
- throw new Error("CDP handshake failed");
- });
-
- await expect(
- getOrLaunchBrowser("acme", { launch, connectOverCDP }),
- ).rejects.toThrow(/Failed to attach Playwright/);
-
- // Process should have been killed during cleanup.
- expect((launched.process as unknown as FakeProcess).killed).toBe(true);
- });
-
- it("rejects connections with no default context", async () => {
- const launched = makeLaunched(19042);
- const launch = vi.fn(async () => launched);
- const browser = {
- contexts: () => [],
- close: vi.fn(async () => {}),
- } as unknown as Browser;
- const connectOverCDP = vi.fn(async () => browser);
-
- await expect(
- getOrLaunchBrowser("acme", { launch, connectOverCDP }),
- ).rejects.toThrow(/no default context/);
- });
-});
-
-describe("stopBrowser", () => {
- it("closes Playwright + Chrome and clears the registry entry", async () => {
- const launched = makeLaunched(19042);
- const launch = vi.fn(async () => launched);
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- expect(_sessionsByProject.has("acme")).toBe(true);
-
- await stopBrowser("acme");
-
- expect(_sessionsByProject.has("acme")).toBe(false);
- expect(fake.closed()).toBe(true);
- expect((launched.process as unknown as FakeProcess).killed).toBe(true);
- });
-
- it("no-ops when the project has no active session", async () => {
- await expect(stopBrowser("missing")).resolves.toBeUndefined();
- });
-});
-
-describe("getSessionStatus", () => {
- it("reports running=false when no session exists", () => {
- const status = getSessionStatus("brand-new");
- expect(status.running).toBe(false);
- expect(status.cdpPort).toBeGreaterThanOrEqual(19000);
- expect(status.cdpPort).toBeLessThanOrEqual(19099);
- expect(status.userDataDir).toContain("brand-new/browser/user-data");
- });
-
- it("reports running=true with uptime once launched", async () => {
- const launch = vi.fn(async () => makeLaunched(19042));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
- await getOrLaunchBrowser("acme", { launch, connectOverCDP });
-
- const status = getSessionStatus("acme");
- expect(status.running).toBe(true);
- expect(status.launchedAt).toBeTypeOf("number");
- expect(status.uptimeMs).toBeGreaterThanOrEqual(0);
- expect(status.idleMs).toBeGreaterThanOrEqual(0);
- expect(status.idleTimeoutMs).toBe(5 * 60 * 1000);
- });
-
- it("reflects NOTFAIR_BROWSER_IDLE_TIMEOUT_MS in idleTimeoutMs", () => {
- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "90000";
- const status = getSessionStatus("brand-new");
- expect(status.idleTimeoutMs).toBe(90_000);
- });
-
- it("falls back to the default when the env value is non-numeric or non-positive", () => {
- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "garbage";
- expect(getSessionStatus("a").idleTimeoutMs).toBe(5 * 60 * 1000);
- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "0";
- expect(getSessionStatus("a").idleTimeoutMs).toBe(5 * 60 * 1000);
- });
-});
-
-// ── Idle auto-shutdown ───────────────────────────────────────────────────
-
-describe("checkIdleSessions", () => {
- it("stops sessions whose lastActivityAt exceeds the timeout", async () => {
- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";
- const launch = vi.fn(async () => makeLaunched(19042));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- const session = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- // Backdate the lastActivityAt to make this session "idle".
- session.lastActivityAt = Date.now() - 5_000;
-
- const stopped = await checkIdleSessions();
- expect(stopped).toEqual(["acme"]);
- expect(_sessionsByProject.has("acme")).toBe(false);
- });
-
- it("leaves recently-active sessions running", async () => {
- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "60000";
- const launch = vi.fn(async () => makeLaunched(19042));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- const stopped = await checkIdleSessions();
- expect(stopped).toEqual([]);
- expect(_sessionsByProject.has("acme")).toBe(true);
- });
-
- it("getOrLaunchBrowser bumps lastActivityAt on cache hit (touches the session)", async () => {
- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";
- const launch = vi.fn(async () => makeLaunched(19042));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- const session = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- session.lastActivityAt = Date.now() - 10_000; // would-be idle
-
- await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- // After the second call, the touch should have moved lastActivityAt forward.
- expect(Date.now() - session.lastActivityAt).toBeLessThan(500);
-
- // Idle check now leaves it alone.
- const stopped = await checkIdleSessions();
- expect(stopped).toEqual([]);
- });
-
- it("can shut down multiple idle projects in one tick", async () => {
- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";
- const launch = vi.fn(async () => makeLaunched(19042));
- const fake = makeFakeBrowser();
- const connectOverCDP = vi.fn(async () => fake.browser);
-
- const a = await getOrLaunchBrowser("acme", { launch, connectOverCDP });
- const b = await getOrLaunchBrowser("beta", { launch, connectOverCDP });
- a.lastActivityAt = Date.now() - 5_000;
- b.lastActivityAt = Date.now() - 5_000;
-
- const stopped = await checkIdleSessions();
- expect(stopped.sort()).toEqual(["acme", "beta"]);
- });
-});
diff --git a/notfair-cmo/src/server/browser/tabs.test.ts b/notfair-cmo/src/server/browser/tabs.test.ts
deleted file mode 100644
index 81476856..00000000
--- a/notfair-cmo/src/server/browser/tabs.test.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-import { EventEmitter } from "node:events";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { Browser, BrowserContext, Page } from "playwright-core";
-import type { ChromeLaunchOptions, LaunchedChrome } from "./chrome";
-import {
- _sessionsByProject,
- getOrLaunchBrowser,
- stopAllBrowsers,
-} from "./session";
-import { _resetTabRegistries, assertValidLabel, closeTab, getTab, listTabs, openTab } from "./tabs";
-
-// ── Page / Context / Browser fakes ───────────────────────────────────────
-
-class FakePage extends EventEmitter {
- private _url = "about:blank";
- private _title = "";
- private _closed = false;
-
- url() { return this._url; }
- async title() { return this._title; }
- isClosed() { return this._closed; }
- async goto(url: string) { this._url = url; this._title = `title:${url}`; }
- async close() {
- if (this._closed) return;
- this._closed = true;
- this.emit("close");
- }
- setTitle(t: string) { this._title = t; }
-}
-
-class FakeContext extends EventEmitter {
- private _pages: FakePage[] = [];
- pages() { return [...this._pages] as unknown as Page[]; }
- async newPage(): Promise<Page> {
- const page = new FakePage();
- this._pages.push(page);
- page.once("close", () => {
- this._pages = this._pages.filter((p) => p !== page);
- });
- this.emit("page", page);
- return page as unknown as Page;
- }
- async close() {
- this.emit("close");
- }
-}
-
-class FakeProcess extends EventEmitter {
- exitCode: number | null = null;
- killed = false;
- kill() {
- if (this.exitCode === null) {
- this.exitCode = 0;
- this.killed = true;
- setImmediate(() => this.emit("exit", 0, null));
- }
- return true;
- }
-}
-
-function makeFakeBrowserAndLaunch() {
- const context = new FakeContext();
- const browser = {
- contexts: () => [context as unknown as BrowserContext],
- close: vi.fn(async () => {}),
- } as unknown as Browser;
- const launched: LaunchedChrome = {
- process: new FakeProcess() as unknown as LaunchedChrome["process"],
- cdpPort: 19042,
- cdpHttpUrl: "http://127.0.0.1:19042",
- userDataDir: "/tmp/notfair-cmo-test/projects/acme/browser/user-data",
- };
- return {
- launched,
- browser,
- context,
- launch: vi.fn(async (_o: ChromeLaunchOptions) => launched),
- connectOverCDP: vi.fn(async () => browser),
- };
-}
-
-beforeEach(async () => {
- process.env.NOTFAIR_CMO_DATA_DIR = "/tmp/notfair-cmo-test";
- process.env.NOTFAIR_CHROME_PATH = "/usr/bin/fake-chrome";
- _sessionsByProject.clear();
- _resetTabRegistries();
-});
-
-afterEach(async () => {
- await stopAllBrowsers();
- _resetTabRegistries();
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- delete process.env.NOTFAIR_CHROME_PATH;
-});
-
-// ── Tests ────────────────────────────────────────────────────────────────
-
-describe("assertValidLabel", () => {
- it.each(["greg", "tina_googleads", "agent-1", "a"])("accepts %s", (l) => {
- expect(() => assertValidLabel(l)).not.toThrow();
- });
- it.each(["", "-greg", "greg page", "greg.cmo", "x".repeat(65)])("rejects %s", (l) => {
- expect(() => assertValidLabel(l)).toThrow(/Invalid tab label/);
- });
-});
-
-describe("openTab", () => {
- it("opens a new tab with a caller-supplied label", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
-
- const handle = await openTab("acme", { label: "greg", url: "https://example.com" });
-
- expect(handle.id).toBe("greg");
- expect(handle.label).toBe("greg");
- expect(handle.url).toBe("https://example.com");
- });
-
- it("auto-generates t1/t2/... when label is omitted", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
-
- const a = await openTab("acme");
- const b = await openTab("acme");
- expect(a.id).toMatch(/^t\d+$/);
- expect(b.id).toMatch(/^t\d+$/);
- expect(a.id).not.toBe(b.id);
- });
-
- it("reuses an existing labeled tab instead of opening a duplicate", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
-
- const first = await openTab("acme", { label: "greg", url: "https://example.com" });
- const second = await openTab("acme", { label: "greg", url: "https://other.com" });
-
- expect(second.id).toBe(first.id);
- expect(second.url).toBe("https://other.com");
- // Only one page should exist on the context.
- const tabs = await listTabs("acme");
- expect(tabs).toHaveLength(1);
- });
-
- it("rejects invalid labels", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
-
- await expect(openTab("acme", { label: "bad label" })).rejects.toThrow(/Invalid tab label/);
- });
-});
-
-describe("getTab + listTabs + closeTab", () => {
- it("getTab resolves by id and returns null for unknown refs", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
-
- const opened = await openTab("acme", { label: "greg" });
- const page = await getTab("acme", opened.id);
- expect(page).not.toBeNull();
- expect(await getTab("acme", "nope")).toBeNull();
- });
-
- it("listTabs includes all open tabs with current URL + title", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
-
- await openTab("acme", { label: "greg", url: "https://greg.example/" });
- await openTab("acme", { label: "tina", url: "https://tina.example/" });
-
- const tabs = await listTabs("acme");
- expect(tabs.map((t) => t.id).sort()).toEqual(["greg", "tina"]);
- expect(tabs.find((t) => t.id === "greg")?.url).toBe("https://greg.example/");
- expect(tabs.find((t) => t.id === "tina")?.title).toBe("title:https://tina.example/");
- });
-
- it("closeTab closes the page and removes it from the registry", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
- await openTab("acme", { label: "greg" });
-
- const ok = await closeTab("acme", "greg");
- expect(ok).toBe(true);
-
- const tabs = await listTabs("acme");
- expect(tabs.find((t) => t.id === "greg")).toBeUndefined();
- expect(await getTab("acme", "greg")).toBeNull();
- });
-
- it("closeTab returns false for an unknown ref", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
- expect(await closeTab("acme", "missing")).toBe(false);
- });
-
- it("adopts pages opened on the context outside of openTab (e.g. oauth redirects)", async () => {
- const env = makeFakeBrowserAndLaunch();
- await getOrLaunchBrowser("acme", env);
-
- // Simulate Chrome opening a tab itself (e.g. _blank link, oauth popup).
- await env.context.newPage();
-
- const tabs = await listTabs("acme");
- expect(tabs).toHaveLength(1);
- expect(tabs[0]!.id).toMatch(/^t\d+$/);
- });
-});
diff --git a/notfair-cmo/src/server/db/agent-actions.test.ts b/notfair-cmo/src/server/db/agent-actions.test.ts
deleted file mode 100644
index c5337ed4..00000000
--- a/notfair-cmo/src/server/db/agent-actions.test.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import { listAgentActions, logAgentAction } from "./agent-actions";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) {
- db.exec(migration.sql);
- }
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("logAgentAction", () => {
- it("persists a minimal action with sensible defaults", () => {
- seedProject();
- const before = Date.now();
- const action = logAgentAction({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_type: "audit",
- summary: "ran nightly audit",
- });
- const after = Date.now();
-
- expect(action.id).toMatch(/[0-9a-f-]{36}/);
- expect(action.project_slug).toBe("acme");
- expect(action.agent_id).toBe("acme-google-ads");
- expect(action.action_type).toBe("audit");
- expect(action.summary).toBe("ran nightly audit");
- expect(action.task_id).toBeNull();
- expect(action.reasoning).toBeNull();
- expect(action.payload_json).toBeNull();
- const t = Date.parse(action.occurred_at);
- expect(t).toBeGreaterThanOrEqual(before);
- expect(t).toBeLessThanOrEqual(after);
-
- // Round-trip via the DB to confirm the insert actually landed.
- const row = testDb
- .prepare("SELECT * FROM agent_actions WHERE id = ?")
- .get(action.id) as Record<string, unknown>;
- expect(row).toMatchObject({
- id: action.id,
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_type: "audit",
- summary: "ran nightly audit",
- task_id: null,
- reasoning: null,
- payload_json: null,
- });
- });
-
- it("stores reasoning, task_id, and JSON-encoded payload when provided", () => {
- seedProject();
- const payload = { keyword: "shoes", bid_usd: 1.25, nested: { tag: "x" } };
- const action = logAgentAction({
- project_slug: "acme",
- agent_id: "acme-cmo",
- action_type: "bid_change",
- summary: "raised bid",
- reasoning: "below target ROAS",
- task_id: "task-123",
- payload,
- });
- expect(action.reasoning).toBe("below target ROAS");
- expect(action.task_id).toBe("task-123");
- expect(action.payload_json).toBe(JSON.stringify(payload));
- expect(JSON.parse(action.payload_json!)).toEqual(payload);
- });
-
- it("treats null reasoning / null task_id distinctly from undefined", () => {
- seedProject();
- const action = logAgentAction({
- project_slug: "acme",
- agent_id: "acme-cmo",
- action_type: "x",
- summary: "y",
- reasoning: null,
- task_id: null,
- });
- expect(action.reasoning).toBeNull();
- expect(action.task_id).toBeNull();
- });
-
- it("serializes payload === null as the JSON string 'null' (distinct from omitted)", () => {
- seedProject();
- // input.payload === null → not undefined → JSON.stringify(null) === "null"
- const action = logAgentAction({
- project_slug: "acme",
- agent_id: "acme-cmo",
- action_type: "x",
- summary: "y",
- payload: null,
- });
- expect(action.payload_json).toBe("null");
- });
-
- it("throws when project_slug FK is violated", () => {
- // No project seeded — insert should trip the FK.
- expect(() =>
- logAgentAction({
- project_slug: "missing",
- agent_id: "x",
- action_type: "y",
- summary: "z",
- }),
- ).toThrow(/FOREIGN KEY/i);
- });
-});
-
-describe("listAgentActions", () => {
- it("returns rows ordered by occurred_at DESC (newest first)", () => {
- seedProject();
- testDb
- .prepare(
- `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run("a1", "acme", "x", "t", "first", "2026-01-01T00:00:00.000Z");
- testDb
- .prepare(
- `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run("a2", "acme", "x", "t", "second", "2026-01-02T00:00:00.000Z");
- testDb
- .prepare(
- `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run("a3", "acme", "x", "t", "third", "2026-01-03T00:00:00.000Z");
- const rows = listAgentActions("acme");
- expect(rows.map((r) => r.summary)).toEqual(["third", "second", "first"]);
- });
-
- it("filters by project_slug", () => {
- seedProject("acme");
- seedProject("other");
- logAgentAction({
- project_slug: "acme",
- agent_id: "x",
- action_type: "t",
- summary: "for acme",
- });
- logAgentAction({
- project_slug: "other",
- agent_id: "x",
- action_type: "t",
- summary: "for other",
- });
- const rows = listAgentActions("acme");
- expect(rows).toHaveLength(1);
- expect(rows[0]!.summary).toBe("for acme");
- });
-
- it("honors the limit parameter", () => {
- seedProject();
- for (let i = 0; i < 5; i++) {
- testDb
- .prepare(
- `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run(`a${i}`, "acme", "x", "t", `s${i}`, `2026-01-0${i + 1}T00:00:00.000Z`);
- }
- expect(listAgentActions("acme", 3)).toHaveLength(3);
- expect(listAgentActions("acme", 100)).toHaveLength(5);
- });
-
- it("defaults to limit=50", () => {
- seedProject();
- const insert = testDb.prepare(
- `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- );
- for (let i = 0; i < 60; i++) {
- // pad the timestamp so they sort cleanly
- const ts = `2026-01-01T00:${String(i).padStart(2, "0")}:00.000Z`;
- insert.run(`a${i}`, "acme", "x", "t", `s${i}`, ts);
- }
- expect(listAgentActions("acme")).toHaveLength(50);
- });
-
- it("returns empty array when project has no actions", () => {
- seedProject();
- expect(listAgentActions("acme")).toEqual([]);
- });
-
- it("returns empty array for unknown project slug", () => {
- expect(listAgentActions("does-not-exist")).toEqual([]);
- });
-});
diff --git a/notfair-cmo/src/server/db/agent-actions.ts b/notfair-cmo/src/server/db/agent-actions.ts
deleted file mode 100644
index 65e09f43..00000000
--- a/notfair-cmo/src/server/db/agent-actions.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { getDb } from "./db";
-
-export type AgentAction = {
- id: string;
- project_slug: string;
- agent_id: string;
- task_id: string | null;
- action_type: string;
- summary: string;
- reasoning: string | null;
- payload_json: string | null;
- occurred_at: string;
-};
-
-export type LogActionInput = {
- project_slug: string;
- agent_id: string;
- action_type: string;
- summary: string;
- reasoning?: string | null;
- task_id?: string | null;
- payload?: unknown;
-};
-
-export function logAgentAction(input: LogActionInput): AgentAction {
- const db = getDb();
- const action: AgentAction = {
- id: randomUUID(),
- project_slug: input.project_slug,
- agent_id: input.agent_id,
- task_id: input.task_id ?? null,
- action_type: input.action_type,
- summary: input.summary,
- reasoning: input.reasoning ?? null,
- payload_json: input.payload === undefined ? null : JSON.stringify(input.payload),
- occurred_at: new Date().toISOString(),
- };
- db.prepare(
- `INSERT INTO agent_actions (id, project_slug, agent_id, task_id, action_type, summary, reasoning, payload_json, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- ).run(
- action.id,
- action.project_slug,
- action.agent_id,
- action.task_id,
- action.action_type,
- action.summary,
- action.reasoning,
- action.payload_json,
- action.occurred_at,
- );
- return action;
-}
-
-export function listAgentActions(project_slug: string, limit = 50): AgentAction[] {
- const db = getDb();
- return db
- .prepare("SELECT * FROM agent_actions WHERE project_slug = ? ORDER BY occurred_at DESC LIMIT ?")
- .all(project_slug, limit) as AgentAction[];
-}
diff --git a/notfair-cmo/src/server/db/approvals.test.ts b/notfair-cmo/src/server/db/approvals.test.ts
deleted file mode 100644
index 2b02253e..00000000
--- a/notfair-cmo/src/server/db/approvals.test.ts
+++ /dev/null
@@ -1,778 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import {
- actionableApprovalCount,
- appendComment,
- createApproval,
- createPolicy,
- deletePolicy,
- findMatchingPolicy,
- getApproval,
- listActionableApprovals,
- listComments,
- listPendingApprovals,
- listPolicies,
- listResolvedApprovals,
- pendingApprovalCount,
- requestApprovalRevision,
- resolveApproval,
-} from "./approvals";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) {
- db.exec(migration.sql);
- }
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("createApproval", () => {
- it("persists a pending approval with a generated id and serialized payload", () => {
- seedProject();
- const payload = { campaign_id: "123", new_bid: 2.5 };
- const approval = createApproval({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_summary: "raise bid on shoes",
- action_type: "bid_change",
- cost_estimate_usd: 10,
- reasoning: "below target ROAS",
- payload,
- });
-
- expect(approval.id).toMatch(/[0-9a-f-]{36}/);
- expect(approval.status).toBe("pending");
- expect(approval.resolved_at).toBeNull();
- expect(approval.payload_json).toBe(JSON.stringify(payload));
- expect(approval.reasoning).toBe("below target ROAS");
- expect(approval.cost_estimate_usd).toBe(10);
- expect(approval.action_type).toBe("bid_change");
-
- // Round-trip via DB
- const row = testDb
- .prepare("SELECT * FROM approvals WHERE id = ?")
- .get(approval.id) as Record<string, unknown>;
- expect(row.status).toBe("pending");
- expect(row.resolved_at).toBeNull();
- });
-
- it("defaults reasoning to null when omitted", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-cmo",
- action_summary: "x",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- expect(a.reasoning).toBeNull();
- });
-
- it("serializes an undefined payload as {}", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-cmo",
- action_summary: "x",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: undefined,
- });
- expect(a.payload_json).toBe("{}");
- });
-
- it("serializes a null payload as {} (?? operator coerces null too)", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-cmo",
- action_summary: "x",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: null,
- });
- // Behaviorally: `?? {}` replaces null with {}, then JSON.stringify({}) === "{}".
- expect(a.payload_json).toBe("{}");
- });
-
- it("throws on invalid action_type (CHECK constraint)", () => {
- seedProject();
- expect(() =>
- createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "y",
- // @ts-expect-error invalid on purpose
- action_type: "invalid_type",
- cost_estimate_usd: 0,
- payload: {},
- }),
- ).toThrow(/CHECK/i);
- });
-
- it("throws on missing project FK", () => {
- expect(() =>
- createApproval({
- project_slug: "no-such-project",
- agent_id: "x",
- action_summary: "y",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- }),
- ).toThrow(/FOREIGN KEY/i);
- });
-});
-
-describe("listPendingApprovals", () => {
- it("returns only pending approvals for the given project", () => {
- seedProject("acme");
- seedProject("other");
- const a1 = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "pending1",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "pending2",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- // Resolve one so it's filtered out.
- resolveApproval(a1.id, "approved");
- createApproval({
- project_slug: "other",
- agent_id: "x",
- action_summary: "from other project",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
-
- const rows = listPendingApprovals("acme");
- expect(rows.map((r) => r.action_summary)).toEqual(["pending2"]);
- expect(rows.every((r) => r.status === "pending")).toBe(true);
- });
-
- it("orders by created_at DESC", () => {
- seedProject();
- testDb
- .prepare(
- `INSERT INTO approvals
- (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)`,
- )
- .run("a1", "acme", "x", "old", "other", 0, "{}", "2026-01-01T00:00:00.000Z");
- testDb
- .prepare(
- `INSERT INTO approvals
- (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)`,
- )
- .run("a2", "acme", "x", "newer", "other", 0, "{}", "2026-01-02T00:00:00.000Z");
- expect(listPendingApprovals("acme").map((r) => r.action_summary)).toEqual([
- "newer",
- "old",
- ]);
- });
-
- it("returns empty array when project has no pending approvals", () => {
- seedProject();
- expect(listPendingApprovals("acme")).toEqual([]);
- });
-});
-
-describe("pendingApprovalCount", () => {
- it("returns 0 when there are no approvals", () => {
- seedProject();
- expect(pendingApprovalCount("acme")).toBe(0);
- });
-
- it("counts only pending approvals", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p1",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p2",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p3",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- expect(pendingApprovalCount("acme")).toBe(3);
- resolveApproval(a.id, "approved");
- expect(pendingApprovalCount("acme")).toBe(2);
- });
-
- it("isolates count by project", () => {
- seedProject("a");
- seedProject("b");
- createApproval({
- project_slug: "a",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- expect(pendingApprovalCount("a")).toBe(1);
- expect(pendingApprovalCount("b")).toBe(0);
- });
-});
-
-describe("resolveApproval", () => {
- it("flips pending → approved and stamps resolved_at", async () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const out = resolveApproval(a.id, "approved");
- expect(out).not.toBeNull();
- expect(out!.status).toBe("approved");
- expect(out!.resolved_at).not.toBeNull();
- expect(Date.parse(out!.resolved_at!)).toBeGreaterThan(0);
- });
-
- it("flips pending → rejected", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const out = resolveApproval(a.id, "rejected");
- expect(out!.status).toBe("rejected");
- });
-
- it("flips pending → expired", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const out = resolveApproval(a.id, "expired");
- expect(out!.status).toBe("expired");
- });
-
- it("is a no-op when the approval is not pending (returns current row)", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const first = resolveApproval(a.id, "approved")!;
- const second = resolveApproval(a.id, "rejected")!;
- // Still approved — the WHERE status='pending' clause prevents re-resolution.
- expect(second.status).toBe("approved");
- expect(second.resolved_at).toBe(first.resolved_at);
- });
-
- it("returns null when the approval id doesn't exist", () => {
- expect(resolveApproval("missing-id", "approved")).toBeNull();
- });
-
- it("persists decision_note + decided_by_kind + decided_by_id on resolve", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const out = resolveApproval(a.id, "approved", {
- decision_note: "Looks good",
- decided_by_kind: "user",
- decided_by_id: "[email protected]",
- });
- expect(out!.decision_note).toBe("Looks good");
- expect(out!.decided_by_kind).toBe("user");
- expect(out!.decided_by_id).toBe("[email protected]");
- });
-});
-
-describe("createApproval + policies", () => {
- it("creates a pending row by default with task_id null and no decision metadata", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_summary: "raise bid",
- action_type: "bid_change",
- cost_estimate_usd: 5,
- payload: {},
- });
- expect(a.task_id).toBeNull();
- expect(a.status).toBe("pending");
- expect(a.decided_by_kind).toBeNull();
- expect(a.decided_by_id).toBeNull();
- expect(a.decision_note).toBeNull();
- });
-
- it("auto-approves when a matching policy exists", () => {
- seedProject();
- const policy = createPolicy({
- project_slug: "acme",
- action_type: "bid_change",
- agent_id: null,
- max_cost_usd: null,
- auto_decision: "approve",
- note: "trusted",
- created_by_kind: "user",
- });
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_summary: "raise bid",
- action_type: "bid_change",
- cost_estimate_usd: 50,
- payload: {},
- });
- expect(a.status).toBe("approved");
- expect(a.decided_by_kind).toBe("policy");
- expect(a.decided_by_id).toBe(policy.id);
- expect(a.resolved_at).not.toBeNull();
-
- // System comment recorded so the thread shows the trail.
- const comments = listComments(a.id);
- expect(comments).toHaveLength(1);
- expect(comments[0]!.author_kind).toBe("system");
- expect(comments[0]!.body).toContain("Auto-approved");
- });
-
- it("does NOT auto-approve when cost exceeds max_cost_usd", () => {
- seedProject();
- createPolicy({
- project_slug: "acme",
- action_type: "bid_change",
- agent_id: null,
- max_cost_usd: 10,
- auto_decision: "approve",
- created_by_kind: "user",
- });
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_summary: "expensive bid raise",
- action_type: "bid_change",
- cost_estimate_usd: 50,
- payload: {},
- });
- expect(a.status).toBe("pending");
- expect(a.decided_by_kind).toBeNull();
- });
-
- it("auto-rejects when a matching reject policy exists", () => {
- seedProject();
- createPolicy({
- project_slug: "acme",
- action_type: "content_publishing",
- agent_id: null,
- max_cost_usd: null,
- auto_decision: "reject",
- note: "human approval required for content",
- created_by_kind: "user",
- });
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-seo",
- action_summary: "publish landing page",
- action_type: "content_publishing",
- cost_estimate_usd: 0,
- payload: {},
- });
- expect(a.status).toBe("rejected");
- expect(a.decided_by_kind).toBe("policy");
- });
-
- it("ignores policies from another project", () => {
- seedProject("acme");
- seedProject("other");
- createPolicy({
- project_slug: "other",
- action_type: "bid_change",
- agent_id: null,
- max_cost_usd: null,
- auto_decision: "approve",
- created_by_kind: "user",
- });
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_summary: "bid",
- action_type: "bid_change",
- cost_estimate_usd: 1,
- payload: {},
- });
- expect(a.status).toBe("pending");
- });
-
- it("prefers an agent-scoped policy over a wildcard policy", () => {
- seedProject();
- createPolicy({
- project_slug: "acme",
- action_type: "bid_change",
- agent_id: null,
- max_cost_usd: null,
- auto_decision: "approve",
- note: "wildcard",
- created_by_kind: "user",
- });
- const scoped = createPolicy({
- project_slug: "acme",
- action_type: "bid_change",
- agent_id: "acme-google-ads",
- max_cost_usd: null,
- auto_decision: "reject",
- note: "specific reject",
- created_by_kind: "user",
- });
- // Specific reject must win for this agent.
- const a = createApproval({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- action_summary: "bid",
- action_type: "bid_change",
- cost_estimate_usd: 1,
- payload: {},
- });
- expect(a.status).toBe("rejected");
- expect(a.decided_by_id).toBe(scoped.id);
- });
-
- it("persists task_id when provided", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- task_id: "task-uuid-123",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- expect(a.task_id).toBe("task-uuid-123");
- });
-});
-
-describe("requestApprovalRevision", () => {
- it("flips pending → revision_requested with a note", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const out = requestApprovalRevision(a.id, {
- decision_note: "narrow the audience first",
- decided_by_kind: "user",
- });
- expect(out!.status).toBe("revision_requested");
- expect(out!.decision_note).toBe("narrow the audience first");
- expect(out!.resolved_at).toBeNull(); // not terminal yet
- });
-
- it("no-ops on a non-pending row", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- resolveApproval(a.id, "approved");
- const out = requestApprovalRevision(a.id, {
- decision_note: "second thoughts",
- decided_by_kind: "user",
- });
- // Status is still approved — revision can't undo a terminal decision.
- expect(out!.status).toBe("approved");
- });
-
- it("approved/rejected work after revision_requested transition (pending+revision_requested both resolvable)", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- requestApprovalRevision(a.id, {
- decision_note: "smaller scope",
- decided_by_kind: "user",
- });
- const out = resolveApproval(a.id, "approved");
- expect(out!.status).toBe("approved");
- });
-});
-
-describe("listActionableApprovals + listResolvedApprovals + actionableApprovalCount", () => {
- it("actionable includes pending and revision_requested but not terminal", () => {
- seedProject();
- const pending = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "pending",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const revising = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "revising",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- requestApprovalRevision(revising.id, {
- decision_note: "x",
- decided_by_kind: "user",
- });
- const approved = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "approved",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- resolveApproval(approved.id, "approved");
-
- const ids = listActionableApprovals("acme")
- .map((a) => a.id)
- .sort();
- expect(ids).toEqual([pending.id, revising.id].sort());
- expect(actionableApprovalCount("acme")).toBe(2);
- });
-
- it("resolved lists approved/rejected/expired, excluding pending+revision_requested", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p1",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const b = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p2",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- resolveApproval(a.id, "approved");
- resolveApproval(b.id, "rejected");
-
- const resolved = listResolvedApprovals("acme");
- const statuses = new Set(resolved.map((r) => r.status));
- expect(statuses).toEqual(new Set(["approved", "rejected"]));
- });
-});
-
-describe("appendComment + listComments", () => {
- it("round-trips a comment with author metadata", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- appendComment({
- approval_id: a.id,
- author_kind: "user",
- author_id: "alice",
- body: "let's push back here",
- });
- const c = listComments(a.id);
- expect(c).toHaveLength(1);
- expect(c[0]!.author_kind).toBe("user");
- expect(c[0]!.author_id).toBe("alice");
- expect(c[0]!.body).toBe("let's push back here");
- });
-
- it("orders comments by created_at ASC (chat-like)", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- appendComment({ approval_id: a.id, author_kind: "user", body: "first" });
- appendComment({ approval_id: a.id, author_kind: "agent", author_id: "bot", body: "second" });
- appendComment({ approval_id: a.id, author_kind: "system", body: "third" });
- const ordered = listComments(a.id).map((c) => c.body);
- expect(ordered).toEqual(["first", "second", "third"]);
- });
-
- it("comments cascade-delete with the parent approval", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- appendComment({ approval_id: a.id, author_kind: "user", body: "hi" });
- testDb.prepare("DELETE FROM approvals WHERE id = ?").run(a.id);
- expect(listComments(a.id)).toEqual([]);
- });
-});
-
-describe("policies CRUD + findMatchingPolicy", () => {
- it("creates + lists + deletes a policy", () => {
- seedProject();
- const p = createPolicy({
- project_slug: "acme",
- action_type: "spend",
- agent_id: null,
- max_cost_usd: 100,
- auto_decision: "approve",
- note: "anything under $100",
- created_by_kind: "user",
- });
- expect(listPolicies("acme")).toHaveLength(1);
- expect(listPolicies("acme")[0]!.id).toBe(p.id);
- expect(deletePolicy(p.id)).toBe(true);
- expect(listPolicies("acme")).toHaveLength(0);
- expect(deletePolicy("missing")).toBe(false);
- });
-
- it("findMatchingPolicy respects cost cap (≤ semantics)", () => {
- seedProject();
- createPolicy({
- project_slug: "acme",
- action_type: "spend",
- agent_id: null,
- max_cost_usd: 100,
- auto_decision: "approve",
- created_by_kind: "user",
- });
- // 100 is OK (≤ cap), 101 is not.
- expect(findMatchingPolicy("acme", "spend", "x", 100)).not.toBeNull();
- expect(findMatchingPolicy("acme", "spend", "x", 99.99)).not.toBeNull();
- expect(findMatchingPolicy("acme", "spend", "x", 100.01)).toBeNull();
- });
-
- it("findMatchingPolicy returns null when project, type, or agent mismatch", () => {
- seedProject("acme");
- seedProject("other");
- createPolicy({
- project_slug: "acme",
- action_type: "spend",
- agent_id: "agent-1",
- max_cost_usd: null,
- auto_decision: "approve",
- created_by_kind: "user",
- });
- expect(findMatchingPolicy("other", "spend", "agent-1", 0)).toBeNull();
- expect(findMatchingPolicy("acme", "bid_change", "agent-1", 0)).toBeNull();
- expect(findMatchingPolicy("acme", "spend", "agent-2", 0)).toBeNull();
- });
-});
-
-describe("getApproval", () => {
- it("returns the row by id", () => {
- seedProject();
- const a = createApproval({
- project_slug: "acme",
- agent_id: "x",
- action_summary: "p",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- expect(getApproval(a.id)?.id).toBe(a.id);
- });
- it("returns null for unknown id", () => {
- expect(getApproval("nope")).toBeNull();
- });
-});
diff --git a/notfair-cmo/src/server/db/approvals.ts b/notfair-cmo/src/server/db/approvals.ts
deleted file mode 100644
index a695a418..00000000
--- a/notfair-cmo/src/server/db/approvals.ts
+++ /dev/null
@@ -1,372 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { getDb } from "./db";
-import type {
- Approval,
- ApprovalComment,
- ApprovalCommentAuthorKind,
- ApprovalDecidedByKind,
- ApprovalPolicy,
- ApprovalStatus,
- ApprovalType,
-} from "@/types";
-
-export type CreateApprovalInput = {
- project_slug: string;
- agent_id: string;
- task_id?: string | null;
- action_summary: string;
- action_type: ApprovalType;
- cost_estimate_usd: number;
- reasoning?: string | null;
- payload: unknown;
-};
-
-/**
- * Returns the inserted approval row. When a matching auto-approve/reject
- * policy fired, the row comes back already in its terminal state with
- * `decided_by_kind = 'policy'` and `decided_by_id = policy.id` — callers
- * that need to fire wake-up logic can detect that without an extra read.
- */
-export function createApproval(input: CreateApprovalInput): Approval {
- const db = getDb();
- const id = randomUUID();
- const createdAt = new Date().toISOString();
-
- // Consult the "always allow / always reject" policies BEFORE writing a
- // pending row. If a policy matches, write the row in its terminal state
- // straight away so the agent can be woken in the same tick. Mirrors
- // paperclip's intent of decoupling the decision from human latency.
- const policy = findMatchingPolicy(
- input.project_slug,
- input.action_type,
- input.agent_id,
- input.cost_estimate_usd,
- );
-
- const initialStatus: ApprovalStatus = policy
- ? policy.auto_decision === "approve"
- ? "approved"
- : "rejected"
- : "pending";
-
- db.prepare(
- `INSERT INTO approvals
- (id, project_slug, agent_id, task_id, action_summary, action_type,
- cost_estimate_usd, reasoning, payload_json, status,
- decision_note, decided_by_kind, decided_by_id,
- created_at, resolved_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- ).run(
- id,
- input.project_slug,
- input.agent_id,
- input.task_id ?? null,
- input.action_summary,
- input.action_type,
- input.cost_estimate_usd,
- input.reasoning ?? null,
- JSON.stringify(input.payload ?? {}),
- initialStatus,
- policy ? (policy.note ?? "Auto-decided by policy.") : null,
- policy ? "policy" : null,
- policy ? policy.id : null,
- createdAt,
- policy ? createdAt : null,
- );
-
- // If a policy auto-resolved, append a system comment so the thread shows
- // a clear trail of "why was this approved without me clicking anything?".
- if (policy) {
- appendComment({
- approval_id: id,
- author_kind: "system",
- author_id: policy.id,
- body: `Auto-${policy.auto_decision === "approve" ? "approved" : "rejected"} by policy: ${policy.note ?? "(no note)"}`,
- });
- }
-
- const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id) as Approval;
- return row;
-}
-
-/** Pending OR revision_requested — anything still needing human attention. */
-export function listActionableApprovals(project_slug: string): Approval[] {
- const db = getDb();
- return db
- .prepare(
- `SELECT * FROM approvals
- WHERE project_slug = ?
- AND status IN ('pending','revision_requested')
- ORDER BY created_at DESC`,
- )
- .all(project_slug) as Approval[];
-}
-
-/** Back-compat: caller wanted only strictly-pending rows. */
-export function listPendingApprovals(project_slug: string): Approval[] {
- const db = getDb();
- return db
- .prepare(
- "SELECT * FROM approvals WHERE project_slug = ? AND status = 'pending' ORDER BY created_at DESC",
- )
- .all(project_slug) as Approval[];
-}
-
-/** Resolved approvals (approved | rejected | expired) — for the history tab. */
-export function listResolvedApprovals(project_slug: string, limit = 50): Approval[] {
- const db = getDb();
- return db
- .prepare(
- `SELECT * FROM approvals
- WHERE project_slug = ?
- AND status IN ('approved','rejected','expired')
- ORDER BY resolved_at DESC NULLS LAST, created_at DESC
- LIMIT ?`,
- )
- .all(project_slug, limit) as Approval[];
-}
-
-export function listApprovalsForTask(task_id: string): Approval[] {
- const db = getDb();
- return db
- .prepare("SELECT * FROM approvals WHERE task_id = ? ORDER BY created_at DESC")
- .all(task_id) as Approval[];
-}
-
-export function getApproval(id: string): Approval | null {
- const db = getDb();
- const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id);
- return (row as Approval) ?? null;
-}
-
-/** Count of actionable (pending + revision_requested) approvals — sidebar badge. */
-export function actionableApprovalCount(project_slug: string): number {
- const db = getDb();
- const row = db
- .prepare(
- `SELECT COUNT(*) AS n FROM approvals
- WHERE project_slug = ? AND status IN ('pending','revision_requested')`,
- )
- .get(project_slug) as { n: number };
- return row.n;
-}
-
-/** Back-compat shim: pendingApprovalCount counts strict 'pending'. The sidebar
- * badge has been switched to actionableApprovalCount so this is unused inside
- * the repo but exported so external callers (tests, scripts) keep working. */
-export function pendingApprovalCount(project_slug: string): number {
- const db = getDb();
- const row = db
- .prepare("SELECT COUNT(*) AS n FROM approvals WHERE project_slug = ? AND status = 'pending'")
- .get(project_slug) as { n: number };
- return row.n;
-}
-
-export type ResolveApprovalOptions = {
- decision_note?: string | null;
- decided_by_kind?: ApprovalDecidedByKind;
- decided_by_id?: string | null;
-};
-
-/**
- * Conditional update: only flips a row that's still actionable (pending or
- * revision_requested). The WHERE clause prevents a stale caller from
- * re-resolving an already-terminal approval. Returns the post-update row
- * (which may be unchanged if the transition didn't apply) or null when the
- * id is missing.
- *
- * Wakeup logic should NOT live here — call `decideApproval()` in the
- * actions layer if you want the post-resolution task wake-up.
- */
-export function resolveApproval(
- id: string,
- status: Exclude<ApprovalStatus, "pending" | "revision_requested">,
- options: ResolveApprovalOptions = {},
-): Approval | null {
- const db = getDb();
- const now = new Date().toISOString();
- db.prepare(
- `UPDATE approvals
- SET status = ?,
- resolved_at = ?,
- decision_note = COALESCE(?, decision_note),
- decided_by_kind = COALESCE(?, decided_by_kind),
- decided_by_id = COALESCE(?, decided_by_id)
- WHERE id = ?
- AND status IN ('pending','revision_requested')`,
- ).run(
- status,
- now,
- options.decision_note ?? null,
- options.decided_by_kind ?? null,
- options.decided_by_id ?? null,
- id,
- );
- const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id);
- return (row as Approval) ?? null;
-}
-
-/**
- * Push back on the agent: flip pending → revision_requested with a note.
- * The agent's next turn sees the note + can resubmit a new <request_approval>.
- * From revision_requested the only forward transitions are approved/rejected.
- */
-export function requestApprovalRevision(
- id: string,
- options: ResolveApprovalOptions & { decision_note: string },
-): Approval | null {
- const db = getDb();
- db.prepare(
- `UPDATE approvals
- SET status = 'revision_requested',
- decision_note = ?,
- decided_by_kind = COALESCE(?, decided_by_kind),
- decided_by_id = COALESCE(?, decided_by_id)
- WHERE id = ?
- AND status = 'pending'`,
- ).run(
- options.decision_note,
- options.decided_by_kind ?? null,
- options.decided_by_id ?? null,
- id,
- );
- const row = db.prepare("SELECT * FROM approvals WHERE id = ?").get(id);
- return (row as Approval) ?? null;
-}
-
-// ── Comments ────────────────────────────────────────────────────────
-
-export type AppendCommentInput = {
- approval_id: string;
- author_kind: ApprovalCommentAuthorKind;
- author_id?: string | null;
- body: string;
-};
-
-export function appendComment(input: AppendCommentInput): ApprovalComment {
- const db = getDb();
- const comment: ApprovalComment = {
- id: randomUUID(),
- approval_id: input.approval_id,
- author_kind: input.author_kind,
- author_id: input.author_id ?? null,
- body: input.body,
- created_at: new Date().toISOString(),
- };
- db.prepare(
- `INSERT INTO approval_comments (id, approval_id, author_kind, author_id, body, created_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- ).run(
- comment.id,
- comment.approval_id,
- comment.author_kind,
- comment.author_id,
- comment.body,
- comment.created_at,
- );
- return comment;
-}
-
-export function listComments(approval_id: string): ApprovalComment[] {
- const db = getDb();
- return db
- .prepare(
- "SELECT * FROM approval_comments WHERE approval_id = ? ORDER BY created_at ASC",
- )
- .all(approval_id) as ApprovalComment[];
-}
-
-// ── Policies ────────────────────────────────────────────────────────
-
-export type CreatePolicyInput = {
- project_slug: string;
- action_type: ApprovalType;
- agent_id?: string | null;
- max_cost_usd?: number | null;
- auto_decision: "approve" | "reject";
- note?: string | null;
- created_by_kind: "user" | "agent";
- created_by_id?: string | null;
-};
-
-export function createPolicy(input: CreatePolicyInput): ApprovalPolicy {
- const db = getDb();
- const policy: ApprovalPolicy = {
- id: randomUUID(),
- project_slug: input.project_slug,
- action_type: input.action_type,
- agent_id: input.agent_id ?? null,
- max_cost_usd: input.max_cost_usd ?? null,
- auto_decision: input.auto_decision,
- note: input.note ?? null,
- created_at: new Date().toISOString(),
- created_by_kind: input.created_by_kind,
- created_by_id: input.created_by_id ?? null,
- };
- db.prepare(
- `INSERT INTO approval_policies
- (id, project_slug, action_type, agent_id, max_cost_usd, auto_decision, note, created_at, created_by_kind, created_by_id)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- ).run(
- policy.id,
- policy.project_slug,
- policy.action_type,
- policy.agent_id,
- policy.max_cost_usd,
- policy.auto_decision,
- policy.note,
- policy.created_at,
- policy.created_by_kind,
- policy.created_by_id,
- );
- return policy;
-}
-
-export function listPolicies(project_slug: string): ApprovalPolicy[] {
- const db = getDb();
- return db
- .prepare(
- "SELECT * FROM approval_policies WHERE project_slug = ? ORDER BY created_at DESC",
- )
- .all(project_slug) as ApprovalPolicy[];
-}
-
-export function deletePolicy(id: string): boolean {
- const db = getDb();
- const info = db.prepare("DELETE FROM approval_policies WHERE id = ?").run(id);
- return info.changes > 0;
-}
-
-/**
- * Find the first policy that matches a candidate approval. Matching rules:
- * - same project_slug
- * - same action_type
- * - agent_id matches (NULL agent_id in policy = any agent)
- * - cost ≤ max_cost_usd (NULL max_cost_usd = no cap)
- *
- * Most-specific wins: agent-scoped policies are preferred over wildcard;
- * cost-capped policies preferred over uncapped (tighter cap first).
- */
-export function findMatchingPolicy(
- project_slug: string,
- action_type: ApprovalType,
- agent_id: string,
- cost_estimate_usd: number,
-): ApprovalPolicy | null {
- const db = getDb();
- const rows = db
- .prepare(
- `SELECT * FROM approval_policies
- WHERE project_slug = ?
- AND action_type = ?
- AND (agent_id IS NULL OR agent_id = ?)
- AND (max_cost_usd IS NULL OR max_cost_usd >= ?)
- ORDER BY
- CASE WHEN agent_id IS NULL THEN 1 ELSE 0 END,
- CASE WHEN max_cost_usd IS NULL THEN 1 ELSE 0 END,
- max_cost_usd ASC NULLS LAST,
- created_at DESC`,
- )
- .all(project_slug, action_type, agent_id, cost_estimate_usd) as ApprovalPolicy[];
- return rows[0] ?? null;
-}
diff --git a/notfair-cmo/src/server/db/attention.test.ts b/notfair-cmo/src/server/db/attention.test.ts
deleted file mode 100644
index efec92fb..00000000
--- a/notfair-cmo/src/server/db/attention.test.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import { attentionByAgent, attentionByTaskForAgent } from "./attention";
-import { createQuestion, answerQuestion } from "./questions";
-
-function applyMigrations(db: Database.Database): void {
- for (const m of MIGRATIONS) db.exec(m.sql);
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-/** questions.task_id carries a FK to tasks(id) — seed a real row. */
-function seedTask(id: string, agent_id = "acme-cmo-greg"): void {
- testDb
- .prepare(
- `INSERT INTO tasks (id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES (?, 'acme', ?, 'brief', 'blocked', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`,
- )
- .run(id, agent_id);
-}
-
-function insertApproval(input: {
- id: string;
- agent_id: string;
- task_id?: string | null;
- status?: string;
- created_at?: string;
-}): void {
- testDb
- .prepare(
- `INSERT INTO approvals
- (id, project_slug, agent_id, task_id, action_summary, action_type,
- cost_estimate_usd, payload_json, status, created_at)
- VALUES (?, 'acme', ?, ?, 'Raise budget', 'spend', 10, '{}', ?, ?)`,
- )
- .run(
- input.id,
- input.agent_id,
- input.task_id ?? null,
- input.status ?? "pending",
- input.created_at ?? "2026-01-02T00:00:00.000Z",
- );
-}
-
-beforeEach(() => {
- testDb = createDb();
- seedProject();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("attentionByAgent", () => {
- it("returns an empty map when nothing waits on the user", () => {
- expect(attentionByAgent("acme")).toEqual({});
- });
-
- it("counts pending questions and actionable approvals per agent", () => {
- seedTask("t-1");
- createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- task_id: "t-1",
- prompt: "What does Demo1 sell?",
- options: [],
- });
- insertApproval({ id: "a-1", agent_id: "acme-cmo-greg", task_id: "t-1" });
- insertApproval({
- id: "a-2",
- agent_id: "acme-google-ads-ana",
- task_id: "t-9",
- status: "revision_requested",
- });
-
- const out = attentionByAgent("acme");
- expect(out["acme-cmo-greg"]?.count).toBe(2);
- expect(out["acme-google-ads-ana"]?.count).toBe(1);
- expect(out["acme-google-ads-ana"]?.task_id).toBe("t-9");
- });
-
- it("deep-links to the OLDEST task-anchored item", () => {
- insertApproval({
- id: "a-new",
- agent_id: "acme-cmo-greg",
- task_id: "t-new",
- created_at: "2026-01-05T00:00:00.000Z",
- });
- insertApproval({
- id: "a-old",
- agent_id: "acme-cmo-greg",
- task_id: "t-old",
- created_at: "2026-01-03T00:00:00.000Z",
- });
-
- expect(attentionByAgent("acme")["acme-cmo-greg"]?.task_id).toBe("t-old");
- });
-
- it("falls back past unanchored items to the first task-anchored one", () => {
- seedTask("t-2");
- createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- task_id: null,
- prompt: "Free-standing question",
- options: [],
- });
- insertApproval({
- id: "a-1",
- agent_id: "acme-cmo-greg",
- task_id: "t-2",
- created_at: "2099-01-01T00:00:00.000Z",
- });
-
- const entry = attentionByAgent("acme")["acme-cmo-greg"];
- expect(entry?.count).toBe(2);
- expect(entry?.task_id).toBe("t-2");
- });
-
- it("excludes resolved questions and decided approvals", () => {
- seedTask("t-1");
- const q = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- task_id: "t-1",
- prompt: "Answered already",
- options: ["Yes"],
- });
- answerQuestion({ id: q.id, answer_option_index: 0, answer_text: null });
- insertApproval({
- id: "a-done",
- agent_id: "acme-cmo-greg",
- task_id: "t-1",
- status: "approved",
- });
-
- expect(attentionByAgent("acme")).toEqual({});
- });
-
- it("attentionByTaskForAgent maps task ids to their pending-item counts", () => {
- seedTask("t-1");
- seedTask("t-2");
- createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- task_id: "t-1",
- prompt: "One",
- options: [],
- });
- insertApproval({ id: "a-1", agent_id: "acme-cmo-greg", task_id: "t-1" });
- insertApproval({ id: "a-2", agent_id: "acme-cmo-greg", task_id: "t-2" });
- // Unanchored + other-agent rows don't leak in.
- createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- task_id: null,
- prompt: "Free-standing",
- options: [],
- });
- insertApproval({ id: "a-3", agent_id: "acme-google-ads-ana", task_id: "t-9" });
-
- expect(attentionByTaskForAgent("acme", "acme-cmo-greg")).toEqual({
- "t-1": 2,
- "t-2": 1,
- });
- });
-
- it("scopes to the requested project", () => {
- seedProject("other");
- testDb
- .prepare(
- `INSERT INTO questions
- (id, project_slug, agent_id, task_id, prompt, options_json,
- status, answer_option_index, answer_text, resolved_by_kind,
- created_at, resolved_at)
- VALUES ('q-x', 'other', 'other-cmo', NULL, 'p', '[]',
- 'pending', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', NULL)`,
- )
- .run();
-
- expect(attentionByAgent("acme")).toEqual({});
- expect(attentionByAgent("other")["other-cmo"]?.count).toBe(1);
- });
-});
diff --git a/notfair-cmo/src/server/db/attention.ts b/notfair-cmo/src/server/db/attention.ts
deleted file mode 100644
index 2dd6f001..00000000
--- a/notfair-cmo/src/server/db/attention.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { getDb } from "./db";
-
-/**
- * "Needs you" signal for the sidebar — the Slack-unread-badge model.
- * An agent demands attention when it has a pending question
- * (`ask_user_question`) or an actionable approval (`request_approval`)
- * waiting on the user. Both park the task in `blocked`, where it is
- * invisible unless the user happens to open that agent's Tasks tab —
- * this module powers the red badge that makes it visible everywhere.
- */
-export type AgentAttention = {
- /** Pending questions + actionable approvals waiting on the user. */
- count: number;
- /**
- * Task id of the OLDEST waiting item that is anchored to a task — the
- * deep-link target so clicking the badge lands directly in the
- * decision space (`/agents/<slug>/tasks?task=<id>`). Null when no
- * waiting item names a task (free-standing questions).
- */
- task_id: string | null;
-};
-
-/**
- * Per-task variant for the task rail: task_id → count of pending
- * questions + actionable approvals on that task. Rows without a task
- * anchor are skipped — the rail can only badge rows it renders.
- */
-export function attentionByTaskForAgent(
- project_slug: string,
- agent_id: string,
-): Record<string, number> {
- const db = getDb();
- const rows = db
- .prepare(
- `SELECT task_id FROM questions
- WHERE project_slug = ? AND agent_id = ? AND status = 'pending'
- AND task_id IS NOT NULL
- UNION ALL
- SELECT task_id FROM approvals
- WHERE project_slug = ? AND agent_id = ? AND status IN ('pending','revision_requested')
- AND task_id IS NOT NULL`,
- )
- .all(project_slug, agent_id, project_slug, agent_id) as Array<{
- task_id: string;
- }>;
-
- const out: Record<string, number> = {};
- for (const r of rows) out[r.task_id] = (out[r.task_id] ?? 0) + 1;
- return out;
-}
-
-export function attentionByAgent(
- project_slug: string,
-): Record<string, AgentAttention> {
- const db = getDb();
- const rows = db
- .prepare(
- `SELECT agent_id, task_id, created_at FROM questions
- WHERE project_slug = ? AND status = 'pending'
- UNION ALL
- SELECT agent_id, task_id, created_at FROM approvals
- WHERE project_slug = ? AND status IN ('pending','revision_requested')
- ORDER BY created_at ASC`,
- )
- .all(project_slug, project_slug) as Array<{
- agent_id: string;
- task_id: string | null;
- created_at: string;
- }>;
-
- const out: Record<string, AgentAttention> = {};
- for (const r of rows) {
- const entry = (out[r.agent_id] ??= { count: 0, task_id: null });
- entry.count += 1;
- // Rows arrive oldest-first, so the first anchored one wins — answer
- // the item the agent has been waiting on longest.
- if (entry.task_id === null && r.task_id) entry.task_id = r.task_id;
- }
- return out;
-}
diff --git a/notfair-cmo/src/server/db/cost.test.ts b/notfair-cmo/src/server/db/cost.test.ts
deleted file mode 100644
index a6150b2d..00000000
--- a/notfair-cmo/src/server/db/cost.test.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import { costToday, recordCost } from "./cost";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) {
- db.exec(migration.sql);
- }
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("recordCost", () => {
- it("inserts a cost event and returns the row", () => {
- seedProject();
- const event = recordCost({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- source: "llm",
- amount_usd: 0.42,
- ref: "openai:gpt-4o:msg-1",
- });
- expect(event.id).toMatch(/[0-9a-f-]{36}/);
- expect(event.project_slug).toBe("acme");
- expect(event.agent_id).toBe("acme-google-ads");
- expect(event.source).toBe("llm");
- expect(event.amount_usd).toBe(0.42);
- expect(event.ref).toBe("openai:gpt-4o:msg-1");
- expect(Date.parse(event.occurred_at)).toBeGreaterThan(0);
-
- const row = testDb
- .prepare("SELECT * FROM cost_events WHERE id = ?")
- .get(event.id);
- expect(row).toMatchObject({ project_slug: "acme", source: "llm" });
- });
-
- it("defaults agent_id and ref to null when omitted", () => {
- seedProject();
- const event = recordCost({
- project_slug: "acme",
- source: "google_ads",
- amount_usd: 1.0,
- });
- expect(event.agent_id).toBeNull();
- expect(event.ref).toBeNull();
- });
-
- it("explicit null agent_id / null ref also persist as null", () => {
- seedProject();
- const event = recordCost({
- project_slug: "acme",
- agent_id: null,
- source: "gsc",
- amount_usd: 0,
- ref: null,
- });
- expect(event.agent_id).toBeNull();
- expect(event.ref).toBeNull();
- });
-
- it("honors an explicit occurred_at timestamp", () => {
- seedProject();
- const event = recordCost({
- project_slug: "acme",
- source: "other",
- amount_usd: 0.01,
- occurred_at: "2020-06-01T12:34:56.000Z",
- });
- expect(event.occurred_at).toBe("2020-06-01T12:34:56.000Z");
- });
-
- it("rejects invalid source via CHECK constraint", () => {
- seedProject();
- expect(() =>
- recordCost({
- project_slug: "acme",
- // @ts-expect-error invalid on purpose
- source: "bogus",
- amount_usd: 0,
- }),
- ).toThrow(/CHECK/i);
- });
-
- it("trips FK constraint when project_slug is missing", () => {
- expect(() =>
- recordCost({
- project_slug: "no-such",
- source: "llm",
- amount_usd: 0.01,
- }),
- ).toThrow(/FOREIGN KEY/i);
- });
-});
-
-describe("costToday", () => {
- it("returns zeros when there are no cost events", () => {
- seedProject();
- expect(costToday("acme")).toEqual({
- total_usd: 0,
- by_source: { llm: 0, google_ads: 0, gsc: 0, other: 0 },
- });
- });
-
- it("groups today's spend by source and sums total", () => {
- seedProject();
- // Use 'now' as the occurred_at so the >= startOfDay filter passes regardless of TZ.
- const now = new Date().toISOString();
- recordCost({ project_slug: "acme", source: "llm", amount_usd: 0.10, occurred_at: now });
- recordCost({ project_slug: "acme", source: "llm", amount_usd: 0.20, occurred_at: now });
- recordCost({ project_slug: "acme", source: "google_ads", amount_usd: 5.0, occurred_at: now });
- recordCost({ project_slug: "acme", source: "gsc", amount_usd: 1.5, occurred_at: now });
- recordCost({ project_slug: "acme", source: "other", amount_usd: 0.05, occurred_at: now });
- const out = costToday("acme");
- expect(out.by_source.llm).toBeCloseTo(0.3, 6);
- expect(out.by_source.google_ads).toBe(5.0);
- expect(out.by_source.gsc).toBe(1.5);
- expect(out.by_source.other).toBe(0.05);
- expect(out.total_usd).toBeCloseTo(0.3 + 5.0 + 1.5 + 0.05, 6);
- });
-
- it("excludes events from yesterday", () => {
- seedProject();
- const yesterday = new Date();
- yesterday.setDate(yesterday.getDate() - 1);
- // Pin yesterday to early morning UTC so we are definitely before today's
- // 00:00 local even for tests run shortly after midnight in any TZ.
- yesterday.setHours(0, 5, 0, 0);
- yesterday.setDate(yesterday.getDate() - 1); // 2 days back for safety
- recordCost({
- project_slug: "acme",
- source: "llm",
- amount_usd: 99,
- occurred_at: yesterday.toISOString(),
- });
- expect(costToday("acme").total_usd).toBe(0);
- });
-
- it("isolates spend by project", () => {
- seedProject("a");
- seedProject("b");
- const now = new Date().toISOString();
- recordCost({ project_slug: "a", source: "llm", amount_usd: 1, occurred_at: now });
- recordCost({ project_slug: "b", source: "llm", amount_usd: 10, occurred_at: now });
- expect(costToday("a").total_usd).toBe(1);
- expect(costToday("b").total_usd).toBe(10);
- });
-
- it("returns the zero shape (does not mutate the shared ZERO_BY_SOURCE)", () => {
- seedProject();
- const first = costToday("acme");
- const now = new Date().toISOString();
- recordCost({ project_slug: "acme", source: "llm", amount_usd: 42, occurred_at: now });
- const second = costToday("acme");
- expect(first.by_source.llm).toBe(0); // first snapshot wasn't mutated
- expect(second.by_source.llm).toBe(42);
- });
-});
diff --git a/notfair-cmo/src/server/db/cost.ts b/notfair-cmo/src/server/db/cost.ts
deleted file mode 100644
index f3ccfb91..00000000
--- a/notfair-cmo/src/server/db/cost.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { getDb } from "./db";
-import type { CostEvent, CostEventSource } from "@/types";
-
-export type RecordCostInput = {
- project_slug: string;
- agent_id?: string | null;
- source: CostEventSource;
- amount_usd: number;
- ref?: string | null;
- occurred_at?: string;
-};
-
-export function recordCost(input: RecordCostInput): CostEvent {
- const db = getDb();
- const event: CostEvent = {
- id: randomUUID(),
- project_slug: input.project_slug,
- agent_id: input.agent_id ?? null,
- source: input.source,
- amount_usd: input.amount_usd,
- ref: input.ref ?? null,
- occurred_at: input.occurred_at ?? new Date().toISOString(),
- };
- db.prepare(
- "INSERT INTO cost_events (id, project_slug, agent_id, source, amount_usd, ref, occurred_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
- ).run(
- event.id,
- event.project_slug,
- event.agent_id,
- event.source,
- event.amount_usd,
- event.ref,
- event.occurred_at,
- );
- return event;
-}
-
-export type CostSummary = {
- total_usd: number;
- by_source: Record<CostEventSource, number>;
-};
-
-const ZERO_BY_SOURCE: Record<CostEventSource, number> = {
- llm: 0,
- google_ads: 0,
- gsc: 0,
- other: 0,
-};
-
-export function costToday(project_slug: string): CostSummary {
- const db = getDb();
- const startOfDay = new Date();
- startOfDay.setHours(0, 0, 0, 0);
- const since = startOfDay.toISOString();
- const rows = db
- .prepare(
- "SELECT source, COALESCE(SUM(amount_usd), 0) AS total FROM cost_events WHERE project_slug = ? AND occurred_at >= ? GROUP BY source",
- )
- .all(project_slug, since) as { source: CostEventSource; total: number }[];
-
- const by_source = { ...ZERO_BY_SOURCE };
- let total_usd = 0;
- for (const row of rows) {
- by_source[row.source] = row.total;
- total_usd += row.total;
- }
- return { total_usd, by_source };
-}
diff --git a/notfair-cmo/src/server/db/db.test.ts b/notfair-cmo/src/server/db/db.test.ts
deleted file mode 100644
index 0424f128..00000000
--- a/notfair-cmo/src/server/db/db.test.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import { existsSync, mkdtempSync, rmSync, statSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-// Each test re-imports the module after tweaking env so the module-scoped
-// DEFAULT_DATA_DIR / DB_PATH constants pick up our tmpdir override. The
-// connection is cached at module level — vi.resetModules() between tests
-// ensures we get a fresh `cached: null` every time.
-type DbModule = typeof import("./db");
-
-async function loadDb(): Promise<DbModule> {
- return (await import("./db")) as DbModule;
-}
-
-let tmpDir: string;
-const ORIGINAL_ENV = process.env.NOTFAIR_CMO_DATA_DIR;
-
-beforeEach(() => {
- vi.resetModules();
- tmpDir = mkdtempSync(join(tmpdir(), "notfair-cmo-db-test-"));
- process.env.NOTFAIR_CMO_DATA_DIR = tmpDir;
-});
-
-afterEach(() => {
- // Restore env so other tests don't pick up our tmpdir.
- if (ORIGINAL_ENV === undefined) {
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- } else {
- process.env.NOTFAIR_CMO_DATA_DIR = ORIGINAL_ENV;
- }
- if (tmpDir && existsSync(tmpDir)) {
- rmSync(tmpDir, { recursive: true, force: true });
- }
-});
-
-describe("getDbPath", () => {
- it("returns the path inside NOTFAIR_CMO_DATA_DIR", async () => {
- const { getDbPath } = await loadDb();
- expect(getDbPath()).toBe(join(tmpDir, "db.sqlite"));
- });
-
- it("falls back to ~/.notfair-cmo when env var is unset", async () => {
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- vi.resetModules();
- const fakeHome = mkdtempSync(join(tmpdir(), "notfair-cmo-fake-home-"));
- try {
- vi.doMock("node:os", async () => {
- const actual = await vi.importActual<typeof import("node:os")>("node:os");
- return { ...actual, homedir: () => fakeHome };
- });
- const { getDbPath } = await loadDb();
- expect(getDbPath()).toBe(join(fakeHome, ".notfair-cmo", "db.sqlite"));
- } finally {
- vi.doUnmock("node:os");
- rmSync(fakeHome, { recursive: true, force: true });
- }
- });
-});
-
-describe("getDb", () => {
- it("creates the data dir if it doesn't exist", async () => {
- const nested = join(tmpDir, "nested", "deeper");
- process.env.NOTFAIR_CMO_DATA_DIR = nested;
- vi.resetModules();
- const { getDb } = await loadDb();
- const db = getDb();
- try {
- expect(existsSync(nested)).toBe(true);
- } finally {
- db.close();
- }
- });
-
- it("creates the data dir with mode 0o700", async () => {
- const nested = join(tmpDir, "secure");
- process.env.NOTFAIR_CMO_DATA_DIR = nested;
- vi.resetModules();
- const { getDb } = await loadDb();
- const db = getDb();
- try {
- const stat = statSync(nested);
- // On POSIX systems we expect 0o700. Skip on Windows-y environments.
- if (process.platform !== "win32") {
- // Mask with 0o777 to strip the file-type bits.
- expect(stat.mode & 0o777).toBe(0o700);
- }
- } finally {
- db.close();
- }
- });
-
- it("opens the SQLite file at the expected path", async () => {
- const { getDb, getDbPath } = await loadDb();
- const db = getDb();
- try {
- expect(existsSync(getDbPath())).toBe(true);
- } finally {
- db.close();
- }
- });
-
- it("returns a cached instance on subsequent calls", async () => {
- const { getDb } = await loadDb();
- const a = getDb();
- const b = getDb();
- try {
- expect(a).toBe(b);
- } finally {
- a.close();
- }
- });
-
- it("enables foreign_keys pragma", async () => {
- const { getDb } = await loadDb();
- const db = getDb();
- try {
- const row = db.pragma("foreign_keys", { simple: true });
- expect(row).toBe(1);
- } finally {
- db.close();
- }
- });
-
- it("sets WAL journal mode", async () => {
- const { getDb } = await loadDb();
- const db = getDb();
- try {
- const mode = db.pragma("journal_mode", { simple: true });
- expect(String(mode).toLowerCase()).toBe("wal");
- } finally {
- db.close();
- }
- });
-
- it("sets busy_timeout to 5000", async () => {
- const { getDb } = await loadDb();
- const db = getDb();
- try {
- const ms = db.pragma("busy_timeout", { simple: true });
- expect(ms).toBe(5000);
- } finally {
- db.close();
- }
- });
-
- it("applies migrations on first open", async () => {
- const { getDb } = await loadDb();
- const db = getDb();
- try {
- // Every migration from MIGRATIONS should be recorded.
- const { MIGRATIONS } = await import("./migrations");
- const applied = db
- .prepare("SELECT name FROM _migrations ORDER BY name")
- .all() as { name: string }[];
- expect(applied.map((r) => r.name).sort()).toEqual(
- MIGRATIONS.map((m) => m.name).sort(),
- );
-
- // Spot-check that the schema is real (table from 001_init).
- const tables = db
- .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'projects'")
- .all();
- expect(tables).toHaveLength(1);
- } finally {
- db.close();
- }
- });
-
- it("does not re-apply migrations on a second open", async () => {
- {
- const { getDb } = await loadDb();
- const db = getDb();
- db.close();
- }
-
- // Reset module so cached=null but the file at NOTFAIR_CMO_DATA_DIR remains.
- vi.resetModules();
- const { getDb } = await loadDb();
- const db = getDb();
- try {
- const { MIGRATIONS } = await import("./migrations");
- const rows = db
- .prepare("SELECT COUNT(*) AS n FROM _migrations")
- .get() as { n: number };
- // Should NOT have duplicated.
- expect(rows.n).toBe(MIGRATIONS.length);
- } finally {
- db.close();
- }
- });
-});
diff --git a/notfair-cmo/src/server/db/db.ts b/notfair-cmo/src/server/db/db.ts
deleted file mode 100644
index 8cd2e78f..00000000
--- a/notfair-cmo/src/server/db/db.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { existsSync, mkdirSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import Database from "better-sqlite3";
-import { MIGRATIONS } from "./migrations";
-
-const DEFAULT_DATA_DIR = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
-const DB_PATH = join(DEFAULT_DATA_DIR, "db.sqlite");
-
-let cached: Database.Database | null = null;
-
-export function getDb(): Database.Database {
- if (cached) return cached;
-
- if (!existsSync(DEFAULT_DATA_DIR)) {
- mkdirSync(DEFAULT_DATA_DIR, { recursive: true, mode: 0o700 });
- }
-
- const db = new Database(DB_PATH);
- db.pragma("journal_mode = WAL");
- db.pragma("foreign_keys = ON");
- db.pragma("busy_timeout = 5000");
-
- applyMigrations(db);
-
- cached = db;
- return db;
-}
-
-export function getDbPath(): string {
- return DB_PATH;
-}
-
-function applyMigrations(db: Database.Database): void {
- db.exec(`
- CREATE TABLE IF NOT EXISTS _migrations (
- name TEXT PRIMARY KEY,
- applied_at TEXT NOT NULL
- );
- `);
-
- const applied = new Set(
- (db.prepare("SELECT name FROM _migrations").all() as { name: string }[]).map(
- (row) => row.name,
- ),
- );
-
- for (const migration of MIGRATIONS) {
- if (applied.has(migration.name)) continue;
- const tx = db.transaction(() => {
- db.exec(migration.sql);
- db.prepare("INSERT INTO _migrations (name, applied_at) VALUES (?, ?)").run(
- migration.name,
- new Date().toISOString(),
- );
- });
- tx();
- }
-}
diff --git a/notfair-cmo/src/server/db/migrations.ts b/notfair-cmo/src/server/db/migrations.ts
deleted file mode 100644
index 3439ce71..00000000
--- a/notfair-cmo/src/server/db/migrations.ts
+++ /dev/null
@@ -1,585 +0,0 @@
-// Embedded migration manifest. The canonical SQL lives in migrations/*.sql for
-// readability and editor tooling; this file is a small generated mirror so the
-// production build doesn't need filesystem access to apply migrations.
-//
-// To add a migration:
-// 1. Write src/server/db/migrations/00N_<name>.sql
-// 2. Append an entry below with the SAME contents (order = apply order)
-// 3. CI lint (TODO) keeps the two in sync
-
-export type Migration = {
- name: string;
- sql: string;
-};
-
-export const MIGRATIONS: Migration[] = [
- {
- name: "001_init.sql",
- sql: `
--- notfair-cmo SQLite schema, migration 001.
--- Forward-only; do not edit after release. New changes go in a new numbered migration.
-
-CREATE TABLE IF NOT EXISTS projects (
- id TEXT PRIMARY KEY,
- slug TEXT NOT NULL UNIQUE,
- display_name TEXT NOT NULL,
- created_at TEXT NOT NULL,
- archived_at TEXT
-);
-
--- Task lifecycle:
--- proposed -> approved -> running -> (succeeded | failed | cancelled)
-CREATE TABLE IF NOT EXISTS tasks (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- brief TEXT NOT NULL,
- success_criteria TEXT,
- deadline_iso TEXT,
- status TEXT NOT NULL CHECK (status IN ('proposed','approved','running','succeeded','failed','cancelled')),
- result_json TEXT,
- error_message TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
-);
-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 TABLE IF NOT EXISTS approvals (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- action_summary TEXT NOT NULL,
- action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
- cost_estimate_usd REAL NOT NULL DEFAULT 0,
- reasoning TEXT,
- payload_json TEXT NOT NULL,
- status TEXT NOT NULL CHECK (status IN ('pending','approved','rejected','expired')),
- created_at TEXT NOT NULL,
- resolved_at TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_approvals_pending ON approvals(project_slug, status) WHERE status = 'pending';
-
-CREATE TABLE IF NOT EXISTS cost_events (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT,
- source TEXT NOT NULL CHECK (source IN ('llm','google_ads','gsc','other')),
- amount_usd REAL NOT NULL,
- ref TEXT,
- occurred_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_cost_events_project_time ON cost_events(project_slug, occurred_at);
-
-CREATE TABLE IF NOT EXISTS oauth_tokens (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- provider TEXT NOT NULL CHECK (provider IN ('google_ads','gsc')),
- account_label TEXT NOT NULL,
- access_token_enc TEXT NOT NULL,
- refresh_token_enc TEXT NOT NULL,
- expires_at TEXT NOT NULL,
- scope TEXT NOT NULL,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- UNIQUE(project_slug, provider, account_label)
-);
-
-CREATE TABLE IF NOT EXISTS guardrails (
- project_slug TEXT PRIMARY KEY REFERENCES projects(slug),
- config_json TEXT NOT NULL,
- updated_at TEXT NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS agent_actions (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- task_id TEXT,
- action_type TEXT NOT NULL,
- summary TEXT NOT NULL,
- reasoning TEXT,
- payload_json TEXT,
- occurred_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_agent_actions_project_time ON agent_actions(project_slug, occurred_at);
-
-CREATE TABLE IF NOT EXISTS sequence_runs (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- sequence_kind TEXT NOT NULL,
- cursor TEXT NOT NULL,
- status TEXT NOT NULL CHECK (status IN ('pending','running','succeeded','failed','cancelled')),
- payload_json TEXT,
- last_tick_at TEXT,
- next_tick_at TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
-);
-`,
- },
- {
- name: "002_google_ads_account.sql",
- sql: `
--- Per-project Google Ads account selection. Bearers from notfair.co's MCP
--- can grant access to multiple customer accounts; onboarding asks the user
--- to pick one and persists it here so the audit + later automation always
--- target the right account.
-ALTER TABLE projects ADD COLUMN google_ads_account_id TEXT;
-`,
- },
- {
- name: "003_tasks_orchestration.sql",
- sql: `
--- Tasks gain three columns to power the autonomous CMO orchestrator:
---
--- title — short label distinct from the long brief, shown
--- on /tasks cards + task detail header.
--- thread_id — the OpenClaw chat session id this task's
--- per-task thread runs under. The assignee picks
--- up the task in this thread (TASK_BRIEF.md
--- kickoff). Null until the user (or the CMO
--- autonomously) opens the detail page; populated
--- once and immutable.
--- assigner_agent_id — who created this task. CMO assigns to specialists;
--- in v1.1 specialists can create sub-tasks and
--- this lets us walk the chain back to the planner.
-ALTER TABLE tasks ADD COLUMN title TEXT;
-ALTER TABLE tasks ADD COLUMN thread_id TEXT;
-ALTER TABLE tasks ADD COLUMN assigner_agent_id TEXT;
-`,
- },
- {
- name: "004_task_display_id.sql",
- sql: `
--- Human-readable per-project task IDs (e.g. demo7-3) shown in the UI and
--- used in URLs. PK stays as the UUID for FK integrity / agent protocol;
--- display_id is the surface that humans + URLs see.
---
--- Backfill assigns sequential numbers in created_at order per project,
--- so existing demos get pretty IDs without manual cleanup.
-ALTER TABLE tasks ADD COLUMN display_id TEXT;
-
-WITH numbered AS (
- SELECT
- id,
- project_slug || '-' || ROW_NUMBER() OVER (
- PARTITION BY project_slug ORDER BY created_at
- ) AS dn
- FROM tasks
-)
-UPDATE tasks
-SET display_id = numbered.dn
-FROM numbered
-WHERE tasks.id = numbered.id;
-
-CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
-`,
- },
- {
- name: "005_drop_guardrails.sql",
- sql: `
--- Remove the guardrails autonomy feature. The Settings page no longer
--- exposes per-project autonomy knobs and no runtime code reads/writes
--- this table, so drop it to keep the schema honest.
-DROP TABLE IF EXISTS guardrails;
-`,
- },
- {
- name: "006_approvals_v2.sql",
- sql: `
--- Approval system v2: blocked task state, comments, auto-policies, decision tracking.
---
--- Changes:
--- 1. tasks.status CHECK gains 'blocked' (task is waiting on an approval).
--- SQLite can't ALTER CHECK in place, so recreate the table.
--- 2. approvals gains task_id, decision_note, decided_by_kind, decided_by_id;
--- status CHECK gains 'revision_requested' (paperclip-style push-back loop).
--- 3. New approval_comments table — discussion thread per approval.
--- 4. New approval_policies table — "always allow" / "always reject" rules
--- consulted before pending rows are created.
-
-CREATE TABLE tasks_new (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- brief TEXT NOT NULL,
- success_criteria TEXT,
- deadline_iso TEXT,
- status TEXT NOT NULL CHECK (status IN ('proposed','approved','running','blocked','succeeded','failed','cancelled')),
- result_json TEXT,
- error_message TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- title TEXT,
- thread_id TEXT,
- assigner_agent_id TEXT,
- display_id TEXT
-);
-INSERT INTO tasks_new (id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id)
-SELECT id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id
-FROM tasks;
-DROP TABLE tasks;
-ALTER TABLE tasks_new RENAME TO tasks;
-CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
-CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
-
-CREATE TABLE approvals_new (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- task_id TEXT,
- action_summary TEXT NOT NULL,
- action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
- cost_estimate_usd REAL NOT NULL DEFAULT 0,
- reasoning TEXT,
- payload_json TEXT NOT NULL,
- status TEXT NOT NULL CHECK (status IN ('pending','revision_requested','approved','rejected','expired')),
- decision_note TEXT,
- decided_by_kind TEXT CHECK (decided_by_kind IN ('user','agent','policy')),
- decided_by_id TEXT,
- created_at TEXT NOT NULL,
- resolved_at TEXT
-);
-INSERT INTO approvals_new (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at)
-SELECT id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at
-FROM approvals;
-DROP TABLE approvals;
-ALTER TABLE approvals_new RENAME TO approvals;
-CREATE INDEX IF NOT EXISTS idx_approvals_actionable ON approvals(project_slug, status) WHERE status IN ('pending','revision_requested');
-CREATE INDEX IF NOT EXISTS idx_approvals_task ON approvals(task_id) WHERE task_id IS NOT NULL;
-
-CREATE TABLE IF NOT EXISTS approval_comments (
- id TEXT PRIMARY KEY,
- approval_id TEXT NOT NULL REFERENCES approvals(id) ON DELETE CASCADE,
- author_kind TEXT NOT NULL CHECK (author_kind IN ('user','agent','system')),
- author_id TEXT,
- body TEXT NOT NULL,
- created_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_approval_comments_approval ON approval_comments(approval_id, created_at);
-
-CREATE TABLE IF NOT EXISTS approval_policies (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
- agent_id TEXT,
- max_cost_usd REAL,
- auto_decision TEXT NOT NULL CHECK (auto_decision IN ('approve','reject')),
- note TEXT,
- created_at TEXT NOT NULL,
- created_by_kind TEXT NOT NULL CHECK (created_by_kind IN ('user','agent')),
- created_by_id TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_approval_policies_project ON approval_policies(project_slug, action_type);
-`,
- },
- {
- name: "007_unify_task_status_vocab.sql",
- sql: `
--- Unify TaskStatus on the agent-facing verb form: running→working,
--- succeeded→done. SQLite can't ALTER CHECK in place — recreate the table
--- and transform existing rows via CASE. See 007_unify_task_status_vocab.sql
--- for the rationale.
-
-CREATE TABLE tasks_new (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- brief TEXT NOT NULL,
- success_criteria TEXT,
- deadline_iso TEXT,
- status TEXT NOT NULL CHECK (status IN ('proposed','approved','working','blocked','done','failed','cancelled')),
- result_json TEXT,
- error_message TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- title TEXT,
- thread_id TEXT,
- assigner_agent_id TEXT,
- display_id TEXT
-);
-
-INSERT INTO tasks_new (
- id, project_slug, agent_id, brief, success_criteria, deadline_iso,
- status, result_json, error_message, created_at, updated_at, title,
- thread_id, assigner_agent_id, display_id
-)
-SELECT
- id, project_slug, agent_id, brief, success_criteria, deadline_iso,
- CASE status
- WHEN 'running' THEN 'working'
- WHEN 'succeeded' THEN 'done'
- ELSE status
- END AS status,
- result_json, error_message, created_at, updated_at, title,
- thread_id, assigner_agent_id, display_id
-FROM tasks;
-
-DROP TABLE tasks;
-ALTER TABLE tasks_new RENAME TO tasks;
-CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
-CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
-`,
- },
- {
- 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;
-`,
- },
- {
- name: "009_questions.sql",
- sql: `
--- Migration 009: questions table for ask_user_question.
---
--- Agents call the ask_user_question MCP tool to surface a structured
--- question to the user (with optional multiple-choice options). Previously
--- this only logged an action; now it persists a row, blocks the gating
--- task, and the UI renders a QuestionCard alongside ApprovalCard. The
--- user picks an option or types free-text; the wake-up streams the
--- resolution back to the agent.
---
--- Modeled like approvals: one row per question, pending → answered |
--- cancelled (terminal). No comments table — single-shot Q&A; if the
--- agent needs more, it asks again.
-
-CREATE TABLE IF NOT EXISTS questions (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
- prompt TEXT NOT NULL,
- options_json TEXT NOT NULL DEFAULT '[]',
- status TEXT NOT NULL CHECK (status IN ('pending','answered','cancelled')),
- answer_option_index INTEGER,
- answer_text TEXT,
- resolved_by_kind TEXT CHECK (resolved_by_kind IN ('user','system')),
- created_at TEXT NOT NULL,
- resolved_at TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_questions_pending ON questions(project_slug, status) WHERE status = 'pending';
-CREATE INDEX IF NOT EXISTS idx_questions_task ON questions(task_id) WHERE task_id IS NOT NULL;
-`,
- },
- {
- name: "010_harness_adapter.sql",
- sql: `
--- Migration 010: pivot off OpenClaw to harness adapters.
---
--- 1. \`projects.harness_adapter\` — which adapter (claude-code-local |
--- codex-local) runs this project's agents. Onboarding sets it; per-
--- project so different teams can pick different tools.
---
--- 2. \`mcp_tokens\` — per-project OAuth tokens for MCP servers
--- (notfair-googleads, etc.). Replaces the OpenClaw config-file storage
--- so we don't depend on the openclaw binary for token persistence.
---
--- 3. \`scheduled_jobs\` — native cron schedule rows. Replaces openclaw
--- cron CLI. A node-cron loop in the next process ticks these on their
--- cron_expr and dispatches a synthetic chat turn through the harness.
---
--- 4. \`sessions\` + \`transcript_events\` — native chat thread + event log.
--- Replaces OpenClaw's session-key namespace and JSONL transcript files.
--- One row per (agent, label) thread; transcript_events stores the
--- delta/tool/lifecycle events emitted by the adapter so the UI can
--- replay on re-attach.
-
-ALTER TABLE projects ADD COLUMN harness_adapter TEXT NOT NULL DEFAULT 'claude-code-local';
-
-CREATE TABLE IF NOT EXISTS mcp_tokens (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- server_name TEXT NOT NULL,
- account_label TEXT NOT NULL DEFAULT '',
- access_token_enc TEXT NOT NULL,
- refresh_token_enc TEXT,
- expires_at TEXT,
- scope TEXT,
- metadata_json TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- UNIQUE(project_slug, server_name, account_label)
-);
-CREATE INDEX IF NOT EXISTS idx_mcp_tokens_project ON mcp_tokens(project_slug);
-
-CREATE TABLE IF NOT EXISTS scheduled_jobs (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- name TEXT NOT NULL,
- cron_expr TEXT NOT NULL,
- message TEXT NOT NULL,
- enabled INTEGER NOT NULL DEFAULT 1,
- last_run_at TEXT,
- next_run_at TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- UNIQUE(project_slug, agent_id, name)
-);
-CREATE INDEX IF NOT EXISTS idx_scheduled_jobs_next ON scheduled_jobs(enabled, next_run_at);
-
-CREATE TABLE IF NOT EXISTS sessions (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- label TEXT NOT NULL,
- harness_adapter TEXT NOT NULL,
- harness_session_id TEXT,
- task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- UNIQUE(project_slug, agent_id, label)
-);
-CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(project_slug, agent_id);
-CREATE INDEX IF NOT EXISTS idx_sessions_task ON sessions(task_id) WHERE task_id IS NOT NULL;
-
-CREATE TABLE IF NOT EXISTS transcript_events (
- id TEXT PRIMARY KEY,
- session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
- seq INTEGER NOT NULL,
- kind TEXT NOT NULL CHECK (kind IN ('user','delta','tool','lifecycle','final','error')),
- payload_json TEXT NOT NULL,
- created_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_transcript_events_session ON transcript_events(session_id, seq);
-
-CREATE TABLE IF NOT EXISTS scheduled_job_runs (
- id TEXT PRIMARY KEY,
- scheduled_job_id TEXT NOT NULL REFERENCES scheduled_jobs(id) ON DELETE CASCADE,
- started_at TEXT NOT NULL,
- finished_at TEXT,
- status TEXT NOT NULL CHECK (status IN ('running','done','failed')),
- error_message TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_scheduled_job_runs_job ON scheduled_job_runs(scheduled_job_id, started_at);
-`,
- },
- {
- name: "011_user_mcp_servers.sql",
- sql: `
--- Migration 011: user-added MCP servers.
---
--- The Connections page used to render a hardcoded preset catalog
--- (notfair-googleads). Users now register arbitrary OAuth-2.0 MCP servers
--- (Stripe, Vercel, Supabase, etc.) from the UI. Each row is project-scoped
--- and joined alongside the preset list in \`getMcpCatalog\`.
---
--- The \`key\` column carries the same identifier that mcp_tokens.server_name
--- uses, so the OAuth callback + token storage + adapter registration paths
--- work without changes.
-
-CREATE TABLE IF NOT EXISTS user_mcp_servers (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- key TEXT NOT NULL,
- display_name TEXT NOT NULL,
- description TEXT NOT NULL DEFAULT '',
- resource_url TEXT NOT NULL,
- discovery_url TEXT NOT NULL,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- UNIQUE(project_slug, key)
-);
-CREATE INDEX IF NOT EXISTS idx_user_mcp_servers_project ON user_mcp_servers(project_slug);
-`,
- },
- {
- name: "012_hidden_mcp_presets.sql",
- sql: `
--- Migration 012: per-project hide-list for preset MCP catalog entries.
---
--- Users can now "remove" a preset connector (NotFair Google Ads, etc.)
--- from a project's Connections page. Since the preset list is hardcoded
--- in source, removal stores the key in this column and getMcpCatalog
--- filters it out. Re-adding from "Browse connectors" deletes the key
--- here, so the preset reappears.
-
-ALTER TABLE projects
- ADD COLUMN hidden_mcp_preset_keys_json TEXT NOT NULL DEFAULT '[]';
-`,
- },
- {
- name: "013_mcp_token_oauth_client.sql",
- sql: `
--- Migration 013: persist OAuth client + token endpoint on mcp_tokens.
---
--- Refresh-token rotation needs three things at runtime: the token endpoint
--- URL, the dynamically-registered client_id, and (where the server requires
--- it) the client_secret. We have all three in mcp_oauth_pending during the
--- authorize flow but used to throw them away after the callback finished.
--- Persisting them here lets the refresh helper exchange a refresh_token for
--- a fresh access_token without bouncing the user back through consent.
---
--- All three columns are nullable. Pre-existing rows (created before this
--- migration) have no refresh_token captured either, so they fall through to
--- the "reconnect to fix" path on next 401 — exactly the behavior they had
--- before. New rows written by the patched callback will populate them.
-
-ALTER TABLE mcp_tokens ADD COLUMN token_endpoint TEXT;
-ALTER TABLE mcp_tokens ADD COLUMN client_id TEXT;
-ALTER TABLE mcp_tokens ADD COLUMN client_secret TEXT;
-`,
- },
- {
- name: "014_scheduled_job_run_summary.sql",
- sql: `
--- Migration 014: capture a short summary on every cron run so the calendar
--- detail dialog can show what actually happened. dispatchJob accumulates the
--- adapter's final/delta text and writes it on finishJobRun.
-
-ALTER TABLE scheduled_job_runs ADD COLUMN summary TEXT;
-`,
- },
- {
- name: "015_meta_ads_and_gsc_accounts.sql",
- sql: `
--- Per-project Meta Ads and Google Search Console account/property
--- selection — same pattern as google_ads_account_id (migration 002).
--- The notfair-metaads bearer can cover multiple ad accounts; the
--- notfair-googlesearchconsole bearer can cover multiple verified
--- properties. Onboarding asks the user to pick one of each (when the
--- token has >1) so the specialist agents always target the right
--- entity. Null until picked.
-
-ALTER TABLE projects ADD COLUMN meta_ads_account_id TEXT;
-ALTER TABLE projects ADD COLUMN gsc_property_id TEXT;
-`,
- },
- {
- name: "016_session_title_pin.sql",
- sql: `
--- Chat-thread management for the thread rail: user-set display titles
--- (rename), and pinning. \`title\` overrides the derived first-message
--- preview when set; \`pinned_at\` doubles as the pin flag and the
--- pin-order tiebreaker (most recently pinned first). Delete needs no
--- schema: transcript_events already cascades on session delete.
-
-ALTER TABLE sessions ADD COLUMN title TEXT;
-ALTER TABLE sessions ADD COLUMN pinned_at TEXT;
-`,
- },
-];
diff --git a/notfair-cmo/src/server/db/migrations/001_init.sql b/notfair-cmo/src/server/db/migrations/001_init.sql
deleted file mode 100644
index bdf8671f..00000000
--- a/notfair-cmo/src/server/db/migrations/001_init.sql
+++ /dev/null
@@ -1,105 +0,0 @@
--- notfair-cmo SQLite schema, migration 001.
--- Forward-only; do not edit after release. New changes go in a new numbered migration.
-
-CREATE TABLE IF NOT EXISTS projects (
- id TEXT PRIMARY KEY,
- slug TEXT NOT NULL UNIQUE,
- display_name TEXT NOT NULL,
- created_at TEXT NOT NULL,
- archived_at TEXT
-);
-
--- Task lifecycle:
--- proposed → approved → running → (succeeded | failed | cancelled)
--- See src/types/index.ts for the ASCII state diagram.
-CREATE TABLE IF NOT EXISTS tasks (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- brief TEXT NOT NULL,
- success_criteria TEXT,
- deadline_iso TEXT,
- status TEXT NOT NULL CHECK (status IN ('proposed','approved','running','succeeded','failed','cancelled')),
- result_json TEXT,
- error_message TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
-);
-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 TABLE IF NOT EXISTS approvals (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- action_summary TEXT NOT NULL,
- action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
- cost_estimate_usd REAL NOT NULL DEFAULT 0,
- reasoning TEXT,
- payload_json TEXT NOT NULL,
- status TEXT NOT NULL CHECK (status IN ('pending','approved','rejected','expired')),
- created_at TEXT NOT NULL,
- resolved_at TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_approvals_pending ON approvals(project_slug, status) WHERE status = 'pending';
-
-CREATE TABLE IF NOT EXISTS cost_events (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT,
- source TEXT NOT NULL CHECK (source IN ('llm','google_ads','gsc','other')),
- amount_usd REAL NOT NULL,
- ref TEXT,
- occurred_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_cost_events_project_time ON cost_events(project_slug, occurred_at);
-
-CREATE TABLE IF NOT EXISTS oauth_tokens (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- provider TEXT NOT NULL CHECK (provider IN ('google_ads','gsc')),
- account_label TEXT NOT NULL,
- access_token_enc TEXT NOT NULL,
- refresh_token_enc TEXT NOT NULL,
- expires_at TEXT NOT NULL,
- scope TEXT NOT NULL,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- UNIQUE(project_slug, provider, account_label)
-);
-
-CREATE TABLE IF NOT EXISTS guardrails (
- project_slug TEXT PRIMARY KEY REFERENCES projects(slug),
- config_json TEXT NOT NULL,
- updated_at TEXT NOT NULL
-);
-
--- Append-only audit log of every autonomous action.
--- Powers the "Why?" command and post-hoc cost/decision review.
-CREATE TABLE IF NOT EXISTS agent_actions (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- task_id TEXT,
- action_type TEXT NOT NULL,
- summary TEXT NOT NULL,
- reasoning TEXT,
- payload_json TEXT,
- occurred_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_agent_actions_project_time ON agent_actions(project_slug, occurred_at);
-
--- Cursor for long-running multi-tick agent work (e.g., cold email sequences).
-CREATE TABLE IF NOT EXISTS sequence_runs (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- sequence_kind TEXT NOT NULL,
- cursor TEXT NOT NULL,
- status TEXT NOT NULL CHECK (status IN ('pending','running','succeeded','failed','cancelled')),
- payload_json TEXT,
- last_tick_at TEXT,
- next_tick_at TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
-);
diff --git a/notfair-cmo/src/server/db/migrations/002_google_ads_account.sql b/notfair-cmo/src/server/db/migrations/002_google_ads_account.sql
deleted file mode 100644
index 928537d2..00000000
--- a/notfair-cmo/src/server/db/migrations/002_google_ads_account.sql
+++ /dev/null
@@ -1,5 +0,0 @@
--- Per-project Google Ads account selection. A bearer from notfair.co's MCP
--- can grant access to multiple customer accounts; the onboarding flow asks
--- the user to pick one and persists it here so the audit + later automation
--- always target the right account.
-ALTER TABLE projects ADD COLUMN google_ads_account_id TEXT;
diff --git a/notfair-cmo/src/server/db/migrations/003_tasks_orchestration.sql b/notfair-cmo/src/server/db/migrations/003_tasks_orchestration.sql
deleted file mode 100644
index 8f3fa464..00000000
--- a/notfair-cmo/src/server/db/migrations/003_tasks_orchestration.sql
+++ /dev/null
@@ -1,16 +0,0 @@
--- Tasks gain three columns to power the autonomous CMO orchestrator:
---
--- title — short label distinct from the long brief, shown
--- on /tasks cards + task detail header.
--- thread_id — the OpenClaw chat session id this task's
--- per-task thread runs under. The assignee picks
--- up the task in this thread (TASK_BRIEF.md
--- kickoff). Null until the user (or the CMO
--- autonomously) opens the detail page; populated
--- once and immutable.
--- assigner_agent_id — who created this task. CMO assigns to specialists;
--- in v1.1 specialists can create sub-tasks and
--- this lets us walk the chain back to the planner.
-ALTER TABLE tasks ADD COLUMN title TEXT;
-ALTER TABLE tasks ADD COLUMN thread_id TEXT;
-ALTER TABLE tasks ADD COLUMN assigner_agent_id TEXT;
diff --git a/notfair-cmo/src/server/db/migrations/004_task_display_id.sql b/notfair-cmo/src/server/db/migrations/004_task_display_id.sql
deleted file mode 100644
index 0030dac5..00000000
--- a/notfair-cmo/src/server/db/migrations/004_task_display_id.sql
+++ /dev/null
@@ -1,22 +0,0 @@
--- Human-readable per-project task IDs (e.g. demo7-3) shown in the UI and
--- used in URLs. PK stays as the UUID for FK integrity / agent protocol;
--- display_id is the surface that humans + URLs see.
---
--- Backfill assigns sequential numbers in created_at order per project,
--- so existing demos get pretty IDs without manual cleanup.
-ALTER TABLE tasks ADD COLUMN display_id TEXT;
-
-WITH numbered AS (
- SELECT
- id,
- project_slug || '-' || ROW_NUMBER() OVER (
- PARTITION BY project_slug ORDER BY created_at
- ) AS dn
- FROM tasks
-)
-UPDATE tasks
-SET display_id = numbered.dn
-FROM numbered
-WHERE tasks.id = numbered.id;
-
-CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
diff --git a/notfair-cmo/src/server/db/migrations/005_drop_guardrails.sql b/notfair-cmo/src/server/db/migrations/005_drop_guardrails.sql
deleted file mode 100644
index e7e30a24..00000000
--- a/notfair-cmo/src/server/db/migrations/005_drop_guardrails.sql
+++ /dev/null
@@ -1,4 +0,0 @@
--- Remove the guardrails autonomy feature. The Settings page no longer
--- exposes per-project autonomy knobs and no runtime code reads/writes
--- this table, so drop it to keep the schema honest.
-DROP TABLE IF EXISTS guardrails;
diff --git a/notfair-cmo/src/server/db/migrations/006_approvals_v2.sql b/notfair-cmo/src/server/db/migrations/006_approvals_v2.sql
deleted file mode 100644
index 9e9d5475..00000000
--- a/notfair-cmo/src/server/db/migrations/006_approvals_v2.sql
+++ /dev/null
@@ -1,94 +0,0 @@
--- Approval system v2: blocked task state, comments, auto-policies, decision tracking.
---
--- Changes:
--- 1. tasks.status CHECK gains 'blocked' (task is waiting on an approval).
--- SQLite can't ALTER CHECK in place, so recreate the table.
--- 2. approvals gains task_id, decision_note, decided_by_kind, decided_by_id;
--- status CHECK gains 'revision_requested' (paperclip-style push-back loop).
--- 3. New approval_comments table — discussion thread per approval.
--- 4. New approval_policies table — "always allow" / "always reject" rules
--- consulted before pending rows are created.
-
--- ── tasks: add 'blocked' to status CHECK ──────────────────────────────
-CREATE TABLE tasks_new (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- brief TEXT NOT NULL,
- success_criteria TEXT,
- deadline_iso TEXT,
- status TEXT NOT NULL CHECK (status IN ('proposed','approved','running','blocked','succeeded','failed','cancelled')),
- result_json TEXT,
- error_message TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- title TEXT,
- thread_id TEXT,
- assigner_agent_id TEXT,
- display_id TEXT
-);
-INSERT INTO tasks_new (id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id)
-SELECT id, project_slug, agent_id, brief, success_criteria, deadline_iso, status, result_json, error_message, created_at, updated_at, title, thread_id, assigner_agent_id, display_id
-FROM tasks;
-DROP TABLE tasks;
-ALTER TABLE tasks_new RENAME TO tasks;
-CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
-CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
-
--- ── approvals: task_id, decision_note, decided_by_*, 'revision_requested' status ──
-CREATE TABLE approvals_new (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- task_id TEXT,
- action_summary TEXT NOT NULL,
- action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
- cost_estimate_usd REAL NOT NULL DEFAULT 0,
- reasoning TEXT,
- payload_json TEXT NOT NULL,
- status TEXT NOT NULL CHECK (status IN ('pending','revision_requested','approved','rejected','expired')),
- decision_note TEXT,
- decided_by_kind TEXT CHECK (decided_by_kind IN ('user','agent','policy')),
- decided_by_id TEXT,
- created_at TEXT NOT NULL,
- resolved_at TEXT
-);
-INSERT INTO approvals_new (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at)
-SELECT id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, reasoning, payload_json, status, created_at, resolved_at
-FROM approvals;
-DROP TABLE approvals;
-ALTER TABLE approvals_new RENAME TO approvals;
--- Partial index: rows that still need attention (pending OR revision_requested).
-CREATE INDEX IF NOT EXISTS idx_approvals_actionable ON approvals(project_slug, status) WHERE status IN ('pending','revision_requested');
-CREATE INDEX IF NOT EXISTS idx_approvals_task ON approvals(task_id) WHERE task_id IS NOT NULL;
-
--- ── approval_comments: discussion thread per approval ─────────────────
--- Author kinds: 'user' = human, 'agent' = the requesting/deciding agent,
--- 'system' = automated notes (e.g., "auto-approved by policy <id>").
-CREATE TABLE IF NOT EXISTS approval_comments (
- id TEXT PRIMARY KEY,
- approval_id TEXT NOT NULL REFERENCES approvals(id) ON DELETE CASCADE,
- author_kind TEXT NOT NULL CHECK (author_kind IN ('user','agent','system')),
- author_id TEXT,
- body TEXT NOT NULL,
- created_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_approval_comments_approval ON approval_comments(approval_id, created_at);
-
--- ── approval_policies: auto-decide rules consulted before pending row is created ──
--- agent_id IS NULL means "any agent". max_cost_usd IS NULL means "no cost cap".
--- auto_decision='approve' auto-approves matching requests; ='reject' blocks them.
-CREATE TABLE IF NOT EXISTS approval_policies (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- action_type TEXT NOT NULL CHECK (action_type IN ('spend','content_publishing','new_channel','bid_change','audience_change','other')),
- agent_id TEXT,
- max_cost_usd REAL,
- auto_decision TEXT NOT NULL CHECK (auto_decision IN ('approve','reject')),
- note TEXT,
- created_at TEXT NOT NULL,
- created_by_kind TEXT NOT NULL CHECK (created_by_kind IN ('user','agent')),
- created_by_id TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_approval_policies_project ON approval_policies(project_slug, action_type);
diff --git a/notfair-cmo/src/server/db/migrations/007_unify_task_status_vocab.sql b/notfair-cmo/src/server/db/migrations/007_unify_task_status_vocab.sql
deleted file mode 100644
index 68ce08a2..00000000
--- a/notfair-cmo/src/server/db/migrations/007_unify_task_status_vocab.sql
+++ /dev/null
@@ -1,55 +0,0 @@
--- Unify TaskStatus vocabulary on the agent-facing verb form.
---
--- Before: tasks.status ∈ proposed | approved | running | blocked | succeeded | failed | cancelled
--- After: tasks.status ∈ proposed | approved | working | blocked | done | failed | cancelled
---
--- Rationale: the `submit_task_status` MCP tool always accepted the verb
--- enum (working/done/blocked/failed), then the handler mapped it to the
--- DB's noun enum (running/succeeded). The mapping created a visible
--- inconsistency between what the agent calls + what the UI shows on
--- /tasks ("Succeeded" / "Running"), and what the `list_task_statuses`
--- discovery tool returned. One vocabulary everywhere = no mapping layer,
--- no drift surface.
---
--- SQLite can't ALTER CHECK constraints in place — recreate the table.
--- Existing rows are transformed via CASE during the INSERT...SELECT.
-
-CREATE TABLE tasks_new (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- brief TEXT NOT NULL,
- success_criteria TEXT,
- deadline_iso TEXT,
- status TEXT NOT NULL CHECK (status IN ('proposed','approved','working','blocked','done','failed','cancelled')),
- result_json TEXT,
- error_message TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- title TEXT,
- thread_id TEXT,
- assigner_agent_id TEXT,
- display_id TEXT
-);
-
-INSERT INTO tasks_new (
- id, project_slug, agent_id, brief, success_criteria, deadline_iso,
- status, result_json, error_message, created_at, updated_at, title,
- thread_id, assigner_agent_id, display_id
-)
-SELECT
- id, project_slug, agent_id, brief, success_criteria, deadline_iso,
- CASE status
- WHEN 'running' THEN 'working'
- WHEN 'succeeded' THEN 'done'
- ELSE status
- END AS status,
- result_json, error_message, created_at, updated_at, title,
- thread_id, assigner_agent_id, display_id
-FROM tasks;
-
-DROP TABLE tasks;
-ALTER TABLE tasks_new RENAME TO tasks;
-CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_slug);
-CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(project_slug, status);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_display_id ON tasks(display_id);
diff --git a/notfair-cmo/src/server/db/migrations/008_project_brief_and_task_blocks.sql b/notfair-cmo/src/server/db/migrations/008_project_brief_and_task_blocks.sql
deleted file mode 100644
index 2830aef9..00000000
--- a/notfair-cmo/src/server/db/migrations/008_project_brief_and_task_blocks.sql
+++ /dev/null
@@ -1,21 +0,0 @@
--- 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/notfair-cmo/src/server/db/migrations/009_questions.sql b/notfair-cmo/src/server/db/migrations/009_questions.sql
deleted file mode 100644
index 05c0871a..00000000
--- a/notfair-cmo/src/server/db/migrations/009_questions.sql
+++ /dev/null
@@ -1,29 +0,0 @@
--- Migration 009: questions table for ask_user_question.
---
--- Agents call the ask_user_question MCP tool to surface a structured
--- question to the user (with optional multiple-choice options). Previously
--- this only logged an action; now it persists a row, blocks the gating
--- task, and the UI renders a QuestionCard alongside ApprovalCard. The
--- user picks an option or types free-text; the wake-up streams the
--- resolution back to the agent.
---
--- Modeled like approvals: one row per question, pending → answered |
--- cancelled (terminal). No comments table — single-shot Q&A; if the
--- agent needs more, it asks again.
-
-CREATE TABLE IF NOT EXISTS questions (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- agent_id TEXT NOT NULL,
- task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
- prompt TEXT NOT NULL,
- options_json TEXT NOT NULL DEFAULT '[]',
- status TEXT NOT NULL CHECK (status IN ('pending','answered','cancelled')),
- answer_option_index INTEGER,
- answer_text TEXT,
- resolved_by_kind TEXT CHECK (resolved_by_kind IN ('user','system')),
- created_at TEXT NOT NULL,
- resolved_at TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_questions_pending ON questions(project_slug, status) WHERE status = 'pending';
-CREATE INDEX IF NOT EXISTS idx_questions_task ON questions(task_id) WHERE task_id IS NOT NULL;
diff --git a/notfair-cmo/src/server/db/migrations/011_user_mcp_servers.sql b/notfair-cmo/src/server/db/migrations/011_user_mcp_servers.sql
deleted file mode 100644
index 8e06b2d7..00000000
--- a/notfair-cmo/src/server/db/migrations/011_user_mcp_servers.sql
+++ /dev/null
@@ -1,24 +0,0 @@
--- Migration 011: user-added MCP servers.
---
--- The Connections page used to render a hardcoded preset catalog
--- (notfair-googleads). Users now register arbitrary OAuth-2.0 MCP servers
--- (Stripe, Vercel, Supabase, etc.) from the UI. Each row is project-scoped
--- and joined alongside the preset list in `getMcpCatalog`.
---
--- The `key` column carries the same identifier that mcp_tokens.server_name
--- uses, so the OAuth callback + token storage + adapter registration paths
--- work without changes.
-
-CREATE TABLE IF NOT EXISTS user_mcp_servers (
- id TEXT PRIMARY KEY,
- project_slug TEXT NOT NULL REFERENCES projects(slug),
- key TEXT NOT NULL,
- display_name TEXT NOT NULL,
- description TEXT NOT NULL DEFAULT '',
- resource_url TEXT NOT NULL,
- discovery_url TEXT NOT NULL,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- UNIQUE(project_slug, key)
-);
-CREATE INDEX IF NOT EXISTS idx_user_mcp_servers_project ON user_mcp_servers(project_slug);
diff --git a/notfair-cmo/src/server/db/migrations/012_hidden_mcp_presets.sql b/notfair-cmo/src/server/db/migrations/012_hidden_mcp_presets.sql
deleted file mode 100644
index 078e0468..00000000
--- a/notfair-cmo/src/server/db/migrations/012_hidden_mcp_presets.sql
+++ /dev/null
@@ -1,13 +0,0 @@
--- Migration 012: per-project hide-list for preset MCP catalog entries.
---
--- Users can now "remove" a preset connector (NotFair Google Ads, etc.)
--- from a project's Connections page. Since the preset list is hardcoded
--- in source, removal stores the key in this column and getMcpCatalog
--- filters it out. Re-adding from "Browse connectors" deletes the key
--- here, so the preset reappears.
---
--- JSON-encoded string array, NOT NULL, defaulting to '[]' so existing
--- rows behave like "no presets hidden".
-
-ALTER TABLE projects
- ADD COLUMN hidden_mcp_preset_keys_json TEXT NOT NULL DEFAULT '[]';
diff --git a/notfair-cmo/src/server/db/migrations/013_mcp_token_oauth_client.sql b/notfair-cmo/src/server/db/migrations/013_mcp_token_oauth_client.sql
deleted file mode 100644
index 4c460744..00000000
--- a/notfair-cmo/src/server/db/migrations/013_mcp_token_oauth_client.sql
+++ /dev/null
@@ -1,17 +0,0 @@
--- Migration 013: persist OAuth client + token endpoint on mcp_tokens.
---
--- Refresh-token rotation needs three things at runtime: the token endpoint
--- URL, the dynamically-registered client_id, and (where the server requires
--- it) the client_secret. We have all three in mcp_oauth_pending during the
--- authorize flow but used to throw them away after the callback finished.
--- Persisting them here lets the refresh helper exchange a refresh_token for
--- a fresh access_token without bouncing the user back through consent.
---
--- All three columns are nullable. Pre-existing rows (created before this
--- migration) have no refresh_token captured either, so they fall through to
--- the "reconnect to fix" path on next 401 — exactly the behavior they had
--- before. New rows written by the patched callback will populate them.
-
-ALTER TABLE mcp_tokens ADD COLUMN token_endpoint TEXT;
-ALTER TABLE mcp_tokens ADD COLUMN client_id TEXT;
-ALTER TABLE mcp_tokens ADD COLUMN client_secret TEXT;
diff --git a/notfair-cmo/src/server/db/migrations/014_scheduled_job_run_summary.sql b/notfair-cmo/src/server/db/migrations/014_scheduled_job_run_summary.sql
deleted file mode 100644
index dbaa8ed6..00000000
--- a/notfair-cmo/src/server/db/migrations/014_scheduled_job_run_summary.sql
+++ /dev/null
@@ -1,5 +0,0 @@
--- Migration 014: capture a short summary on every cron run so the calendar
--- detail dialog can show what actually happened. dispatchJob accumulates the
--- adapter's final/delta text and writes it on finishJobRun.
-
-ALTER TABLE scheduled_job_runs ADD COLUMN summary TEXT;
diff --git a/notfair-cmo/src/server/db/migrations/015_meta_ads_and_gsc_accounts.sql b/notfair-cmo/src/server/db/migrations/015_meta_ads_and_gsc_accounts.sql
deleted file mode 100644
index 2d438d7b..00000000
--- a/notfair-cmo/src/server/db/migrations/015_meta_ads_and_gsc_accounts.sql
+++ /dev/null
@@ -1,10 +0,0 @@
--- Per-project Meta Ads and Google Search Console account/property
--- selection — same pattern as google_ads_account_id (migration 002).
--- The notfair-metaads bearer can cover multiple ad accounts; the
--- notfair-googlesearchconsole bearer can cover multiple verified
--- properties. Onboarding asks the user to pick one of each (when the
--- token has >1) so the specialist agents always target the right
--- entity. Null until picked.
-
-ALTER TABLE projects ADD COLUMN meta_ads_account_id TEXT;
-ALTER TABLE projects ADD COLUMN gsc_property_id TEXT;
diff --git a/notfair-cmo/src/server/db/migrations/016_session_title_pin.sql b/notfair-cmo/src/server/db/migrations/016_session_title_pin.sql
deleted file mode 100644
index 5a8d0e24..00000000
--- a/notfair-cmo/src/server/db/migrations/016_session_title_pin.sql
+++ /dev/null
@@ -1,8 +0,0 @@
--- Chat-thread management for the thread rail: user-set display titles
--- (rename), and pinning. `title` overrides the derived first-message
--- preview when set; `pinned_at` doubles as the pin flag and the
--- pin-order tiebreaker (most recently pinned first). Delete needs no
--- schema: transcript_events already cascades on session delete.
-
-ALTER TABLE sessions ADD COLUMN title TEXT;
-ALTER TABLE sessions ADD COLUMN pinned_at TEXT;
diff --git a/notfair-cmo/src/server/db/oauth.test.ts b/notfair-cmo/src/server/db/oauth.test.ts
deleted file mode 100644
index 61cb671d..00000000
--- a/notfair-cmo/src/server/db/oauth.test.ts
+++ /dev/null
@@ -1,315 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-// Stub the cipher so the tests don't require a working OS keychain. The
-// "encrypted" representation is just a length-prefixed marker that we can
-// round-trip deterministically.
-vi.mock("@/server/secrets/cipher", () => ({
- encrypt: async (plaintext: string) => `enc:${plaintext}`,
- decrypt: async (blob: string) => blob.replace(/^enc:/, ""),
-}));
-
-import {
- decryptToken,
- getOAuthTokenRecord,
- listOAuthTokens,
- storeOAuthToken,
-} from "./oauth";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) {
- db.exec(migration.sql);
- }
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("storeOAuthToken", () => {
- it("encrypts and persists a new token row", async () => {
- seedProject();
- const out = await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "access-1",
- refresh_token: "refresh-1",
- expires_at: "2027-01-01T00:00:00.000Z",
- scope: "https://www.googleapis.com/auth/adwords",
- });
- expect(out.id).toMatch(/[0-9a-f-]{36}/);
- expect(out.project_slug).toBe("acme");
- expect(out.provider).toBe("google_ads");
- expect(out.account_label).toBe("main");
- expect(out.access_token_enc).toBe("enc:access-1");
- expect(out.refresh_token_enc).toBe("enc:refresh-1");
- expect(out.expires_at).toBe("2027-01-01T00:00:00.000Z");
- expect(out.scope).toBe("https://www.googleapis.com/auth/adwords");
-
- // Round-trip via DB.
- const row = testDb
- .prepare(
- "SELECT * FROM oauth_tokens WHERE project_slug=? AND provider=? AND account_label=?",
- )
- .get("acme", "google_ads", "main");
- expect(row).toMatchObject({ access_token_enc: "enc:access-1" });
- });
-
- it("upserts on (project_slug, provider, account_label) conflict", async () => {
- seedProject();
- const a = await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "a1",
- refresh_token: "r1",
- expires_at: "2027-01-01T00:00:00.000Z",
- scope: "scope",
- });
- // Force a different time so we can verify updated_at advanced.
- await new Promise((r) => setTimeout(r, 5));
- const b = await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "a2",
- refresh_token: "r2",
- expires_at: "2028-01-01T00:00:00.000Z",
- scope: "scope2",
- });
-
- // ON CONFLICT keeps the original primary key id (excluded.id is not set).
- expect(b.id).toBe(a.id);
- expect(b.access_token_enc).toBe("enc:a2");
- expect(b.refresh_token_enc).toBe("enc:r2");
- expect(b.expires_at).toBe("2028-01-01T00:00:00.000Z");
- expect(b.scope).toBe("scope2");
- // created_at unchanged; updated_at advanced.
- expect(b.created_at).toBe(a.created_at);
- expect(Date.parse(b.updated_at)).toBeGreaterThanOrEqual(Date.parse(a.updated_at));
-
- const count = testDb
- .prepare("SELECT COUNT(*) AS n FROM oauth_tokens")
- .get() as { n: number };
- expect(count.n).toBe(1);
- });
-
- it("allows multiple account_labels per (project, provider)", async () => {
- seedProject();
- await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "secondary",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- expect(listOAuthTokens("acme")).toHaveLength(2);
- });
-
- it("throws on invalid provider via CHECK constraint", async () => {
- seedProject();
- await expect(
- storeOAuthToken({
- project_slug: "acme",
- // @ts-expect-error invalid on purpose
- provider: "twitter",
- account_label: "main",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- }),
- ).rejects.toThrow(/CHECK/i);
- });
-
- it("trips FK on missing project", async () => {
- await expect(
- storeOAuthToken({
- project_slug: "no-such",
- provider: "gsc",
- account_label: "main",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- }),
- ).rejects.toThrow(/FOREIGN KEY/i);
- });
-});
-
-describe("listOAuthTokens", () => {
- it("orders by provider, account_label and isolates by project", async () => {
- seedProject("a");
- seedProject("b");
- await storeOAuthToken({
- project_slug: "a",
- provider: "gsc",
- account_label: "z",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- await storeOAuthToken({
- project_slug: "a",
- provider: "google_ads",
- account_label: "z",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- await storeOAuthToken({
- project_slug: "a",
- provider: "google_ads",
- account_label: "a",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- await storeOAuthToken({
- project_slug: "b",
- provider: "google_ads",
- account_label: "main",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
-
- const rows = listOAuthTokens("a");
- expect(rows.map((r) => `${r.provider}:${r.account_label}`)).toEqual([
- "google_ads:a",
- "google_ads:z",
- "gsc:z",
- ]);
- });
-
- it("returns empty array for projects with no tokens", () => {
- seedProject();
- expect(listOAuthTokens("acme")).toEqual([]);
- });
-});
-
-describe("getOAuthTokenRecord", () => {
- it("returns the matching row when account_label is provided", async () => {
- seedProject();
- await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- const row = getOAuthTokenRecord("acme", "google_ads", "main");
- expect(row).not.toBeNull();
- expect(row!.account_label).toBe("main");
- });
-
- it("returns null when account_label is provided but doesn't match", async () => {
- seedProject();
- await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- expect(getOAuthTokenRecord("acme", "google_ads", "missing")).toBeNull();
- });
-
- it("falls back to LIMIT 1 when account_label is omitted", async () => {
- seedProject();
- await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "secondary",
- access_token: "a",
- refresh_token: "r",
- expires_at: "x",
- scope: "s",
- });
- const row = getOAuthTokenRecord("acme", "google_ads");
- expect(row).not.toBeNull();
- expect(["main", "secondary"]).toContain(row!.account_label);
- });
-
- it("returns null when no rows match (no account_label)", () => {
- seedProject();
- expect(getOAuthTokenRecord("acme", "google_ads")).toBeNull();
- });
-});
-
-describe("decryptToken", () => {
- it("decrypts both access and refresh tokens", async () => {
- seedProject();
- const stored = await storeOAuthToken({
- project_slug: "acme",
- provider: "google_ads",
- account_label: "main",
- access_token: "the-access",
- refresh_token: "the-refresh",
- expires_at: "x",
- scope: "s",
- });
- const decoded = await decryptToken(stored);
- expect(decoded).toEqual({
- access_token: "the-access",
- refresh_token: "the-refresh",
- });
- });
-});
diff --git a/notfair-cmo/src/server/db/oauth.ts b/notfair-cmo/src/server/db/oauth.ts
deleted file mode 100644
index 212f3589..00000000
--- a/notfair-cmo/src/server/db/oauth.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { getDb } from "./db";
-import { encrypt, decrypt } from "@/server/secrets/cipher";
-import type { OAuthProvider, OAuthToken } from "@/types";
-
-export type StoreTokenInput = {
- project_slug: string;
- provider: OAuthProvider;
- account_label: string;
- access_token: string;
- refresh_token: string;
- expires_at: string;
- scope: string;
-};
-
-export async function storeOAuthToken(input: StoreTokenInput): Promise<OAuthToken> {
- const db = getDb();
- const now = new Date().toISOString();
- const id = randomUUID();
- const access_token_enc = await encrypt(input.access_token);
- const refresh_token_enc = await encrypt(input.refresh_token);
-
- db.prepare(
- `INSERT INTO oauth_tokens
- (id, project_slug, provider, account_label, access_token_enc, refresh_token_enc, expires_at, scope, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(project_slug, provider, account_label) DO UPDATE SET
- access_token_enc = excluded.access_token_enc,
- refresh_token_enc = excluded.refresh_token_enc,
- expires_at = excluded.expires_at,
- scope = excluded.scope,
- updated_at = excluded.updated_at`,
- ).run(
- id,
- input.project_slug,
- input.provider,
- input.account_label,
- access_token_enc,
- refresh_token_enc,
- input.expires_at,
- input.scope,
- now,
- now,
- );
-
- return getOAuthTokenRecord(input.project_slug, input.provider, input.account_label)!;
-}
-
-export function listOAuthTokens(project_slug: string): OAuthToken[] {
- const db = getDb();
- return db
- .prepare("SELECT * FROM oauth_tokens WHERE project_slug = ? ORDER BY provider, account_label")
- .all(project_slug) as OAuthToken[];
-}
-
-export function getOAuthTokenRecord(
- project_slug: string,
- provider: OAuthProvider,
- account_label?: string,
-): OAuthToken | null {
- const db = getDb();
- if (account_label) {
- const row = db
- .prepare("SELECT * FROM oauth_tokens WHERE project_slug = ? AND provider = ? AND account_label = ?")
- .get(project_slug, provider, account_label);
- return (row as OAuthToken) ?? null;
- }
- const row = db
- .prepare("SELECT * FROM oauth_tokens WHERE project_slug = ? AND provider = ? LIMIT 1")
- .get(project_slug, provider);
- return (row as OAuthToken) ?? null;
-}
-
-export async function decryptToken(record: OAuthToken): Promise<{ access_token: string; refresh_token: string }> {
- const [access_token, refresh_token] = await Promise.all([
- decrypt(record.access_token_enc),
- decrypt(record.refresh_token_enc),
- ]);
- return { access_token, refresh_token };
-}
diff --git a/notfair-cmo/src/server/db/projects.test.ts b/notfair-cmo/src/server/db/projects.test.ts
deleted file mode 100644
index cfc4db80..00000000
--- a/notfair-cmo/src/server/db/projects.test.ts
+++ /dev/null
@@ -1,544 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-// Use a real in-memory better-sqlite3 instance so SQLite's FK constraint
-// actually engages — mocking the DB would defeat the point (the bug was a
-// real FK violation our code wasn't catching).
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import {
- archiveProject,
- changeProjectSlug,
- createProject,
- deleteProjectRow,
- getProject,
- listProjects,
- renameProject,
- setProjectGoogleAdsAccount,
- unarchiveProject,
-} from "./projects";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) {
- db.exec(migration.sql);
- }
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("createProject", () => {
- it("creates a new project from display_name and returns the row", () => {
- const result = createProject({ display_name: "Acme Inc." });
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- expect(result.project.slug).toBe("acme-inc");
- expect(result.project.display_name).toBe("Acme Inc.");
- expect(result.project.archived_at).toBeNull();
- expect(result.project.google_ads_account_id).toBeNull();
- expect(result.project.id).toMatch(/[0-9a-f-]{36}/);
- expect(Date.parse(result.project.created_at)).toBeGreaterThan(0);
-
- // Round-trip via DB.
- const row = testDb
- .prepare("SELECT * FROM projects WHERE slug = ?")
- .get("acme-inc");
- expect(row).toMatchObject({ slug: "acme-inc", display_name: "Acme Inc." });
- });
-
- it("respects an explicit slug override", () => {
- const result = createProject({
- display_name: "Long Pretty Name",
- slug: "shortie",
- });
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- expect(result.project.slug).toBe("shortie");
- expect(result.project.display_name).toBe("Long Pretty Name");
- });
-
- it("trims display_name", () => {
- const result = createProject({ display_name: " Acme " });
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- expect(result.project.display_name).toBe("Acme");
- });
-
- it("returns { ok: false } when slugify fails (empty input)", () => {
- const result = createProject({ display_name: "" });
- expect(result.ok).toBe(false);
- if (result.ok) return;
- expect(result.reason).toMatch(/empty/i);
- });
-
- it("returns { ok: false } when slug is reserved", () => {
- const result = createProject({ display_name: "api" });
- expect(result.ok).toBe(false);
- if (result.ok) return;
- expect(result.reason).toMatch(/reserved/i);
- });
-
- it("returns { ok: false } when slug already exists", () => {
- const first = createProject({ display_name: "Acme" });
- expect(first.ok).toBe(true);
- const dup = createProject({ display_name: "Acme" });
- expect(dup.ok).toBe(false);
- if (dup.ok) return;
- expect(dup.reason).toMatch(/already exists/i);
- });
-});
-
-describe("listProjects", () => {
- it("returns empty array when no projects exist", () => {
- expect(listProjects()).toEqual([]);
- });
-
- it("orders by created_at DESC", () => {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p1", "old", "Old", "2026-01-01T00:00:00.000Z");
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p2", "new", "New", "2026-02-01T00:00:00.000Z");
- const rows = listProjects();
- expect(rows.map((r) => r.slug)).toEqual(["new", "old"]);
- });
-
- it("filters archived by default", () => {
- createProject({ display_name: "Live" });
- const archived = createProject({ display_name: "Dead" });
- expect(archived.ok).toBe(true);
- if (!archived.ok) return;
- archiveProject(archived.project.slug);
-
- const rows = listProjects();
- expect(rows.map((r) => r.slug)).toEqual(["live"]);
- });
-
- it("includes archived when includeArchived: true", () => {
- createProject({ display_name: "Live" });
- const archived = createProject({ display_name: "Dead" });
- expect(archived.ok).toBe(true);
- if (!archived.ok) return;
- archiveProject(archived.project.slug);
-
- const rows = listProjects({ includeArchived: true });
- expect(rows.map((r) => r.slug).sort()).toEqual(["dead", "live"]);
- });
-});
-
-describe("getProject", () => {
- it("returns the project when found", () => {
- createProject({ display_name: "Acme" });
- const out = getProject("acme");
- expect(out).not.toBeNull();
- expect(out!.slug).toBe("acme");
- });
-
- it("returns null when no project matches", () => {
- expect(getProject("nope")).toBeNull();
- });
-});
-
-describe("setProjectGoogleAdsAccount", () => {
- it("persists the customer id and returns the updated row", () => {
- createProject({ display_name: "Acme" });
- const out = setProjectGoogleAdsAccount("acme", "123-456-7890");
- expect(out).not.toBeNull();
- expect(out!.google_ads_account_id).toBe("123-456-7890");
- });
-
- it("can clear the customer id by passing null", () => {
- createProject({ display_name: "Acme" });
- setProjectGoogleAdsAccount("acme", "123");
- const cleared = setProjectGoogleAdsAccount("acme", null);
- expect(cleared!.google_ads_account_id).toBeNull();
- });
-
- it("is idempotent (re-set same value)", () => {
- createProject({ display_name: "Acme" });
- setProjectGoogleAdsAccount("acme", "abc");
- const again = setProjectGoogleAdsAccount("acme", "abc");
- expect(again!.google_ads_account_id).toBe("abc");
- });
-
- it("returns null when project doesn't exist", () => {
- expect(setProjectGoogleAdsAccount("nope", "x")).toBeNull();
- });
-});
-
-describe("renameProject", () => {
- it("changes display_name and returns the updated row", () => {
- createProject({ display_name: "Acme" });
- const out = renameProject("acme", "Acme Corp");
- expect(out!.display_name).toBe("Acme Corp");
- // Slug must NOT change here — renameProject only edits the label.
- expect(out!.slug).toBe("acme");
- });
-
- it("trims the new display_name", () => {
- createProject({ display_name: "Acme" });
- const out = renameProject("acme", " Trimmed ");
- expect(out!.display_name).toBe("Trimmed");
- });
-
- it("returns null when display_name is empty after trimming", () => {
- createProject({ display_name: "Acme" });
- expect(renameProject("acme", " ")).toBeNull();
- expect(getProject("acme")!.display_name).toBe("Acme");
- });
-
- it("returns null when project doesn't exist (no row, no update)", () => {
- // No row in projects — UPDATE affects 0 rows; getProject returns null.
- expect(renameProject("nope", "X")).toBeNull();
- });
-});
-
-describe("changeProjectSlug", () => {
- it("renames slug and migrates child rows", () => {
- createProject({ display_name: "Old" });
- // Seed a row in each child table so we can verify the migration touches them all.
- testDb
- .prepare(
- `INSERT INTO tasks (id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("t1", "old", "old-cmo", "b", "proposed", "now", "now");
- testDb
- .prepare(
- `INSERT INTO approvals
- (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("ap1", "old", "old-cmo", "s", "other", 0, "{}", "pending", "now");
- testDb
- .prepare(
- `INSERT INTO cost_events (id, project_slug, agent_id, source, amount_usd, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run("c1", "old", null, "llm", 0.01, "now");
- testDb
- .prepare(
- `INSERT INTO oauth_tokens
- (id, project_slug, provider, account_label, access_token_enc, refresh_token_enc, expires_at, scope, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("o1", "old", "google_ads", "main", "x", "y", "later", "s", "now", "now");
- testDb
- .prepare(
- `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run("a1", "old", "x", "t", "s", "now");
- testDb
- .prepare(
- `INSERT INTO sequence_runs
- (id, project_slug, agent_id, sequence_kind, cursor, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("s1", "old", "x", "k", "0", "pending", "now", "now");
-
- const out = changeProjectSlug("old", "renamed");
- expect(out).not.toBeNull();
- expect(out!.slug).toBe("renamed");
-
- // Every child table's row should now live under the new slug.
- for (const table of [
- "tasks",
- "approvals",
- "cost_events",
- "oauth_tokens",
- "agent_actions",
- "sequence_runs",
- ]) {
- const row = testDb
- .prepare(`SELECT project_slug FROM ${table} LIMIT 1`)
- .get() as { project_slug: string };
- expect(row.project_slug, table).toBe("renamed");
- }
- expect(getProject("old")).toBeNull();
- });
-
- it("also updates display_name when provided", () => {
- createProject({ display_name: "Old" });
- const out = changeProjectSlug("old", "new", "New Display");
- expect(out!.slug).toBe("new");
- expect(out!.display_name).toBe("New Display");
- });
-
- it("trims new display_name", () => {
- createProject({ display_name: "Old" });
- const out = changeProjectSlug("old", "new", " Padded ");
- expect(out!.display_name).toBe("Padded");
- });
-
- it("when old === new and display_name is provided, updates only display_name", () => {
- createProject({ display_name: "Acme" });
- const out = changeProjectSlug("acme", "acme", "Renamed");
- expect(out!.slug).toBe("acme");
- expect(out!.display_name).toBe("Renamed");
- });
-
- it("when old === new and no display_name, returns the current row (no-op)", () => {
- createProject({ display_name: "Acme" });
- const out = changeProjectSlug("acme", "acme");
- expect(out!.slug).toBe("acme");
- expect(out!.display_name).toBe("Acme");
- });
-
- it("returns null when the source slug doesn't exist", () => {
- expect(changeProjectSlug("missing", "new")).toBeNull();
- });
-
- it("throws when the destination slug already exists", () => {
- createProject({ display_name: "A" });
- createProject({ display_name: "B" });
- expect(() => changeProjectSlug("a", "b")).toThrow(/already exists/i);
- });
-
- it("restores foreign_keys = ON after the rename (even on failure)", () => {
- createProject({ display_name: "A" });
- // Pre-condition.
- expect(testDb.pragma("foreign_keys", { simple: true })).toBe(1);
- changeProjectSlug("a", "renamed");
- expect(testDb.pragma("foreign_keys", { simple: true })).toBe(1);
- });
-
- it("BUG: does not actually restore prior FK state (always leaves FK = ON)", () => {
- // Documenting current behavior. The implementation captures
- // const fkWasOn = db.pragma("foreign_keys = OFF", { simple: true });
- // expecting fkWasOn to be the previous value, but better-sqlite3's pragma
- // returns undefined for SET-style PRAGMAs. So the ternary always falls
- // through to "ON" regardless of prior state. Not a regression for our
- // single-user CLI (which always runs with FK=ON) but worth flagging.
- createProject({ display_name: "Acme" });
- testDb.pragma("foreign_keys = OFF");
- changeProjectSlug("acme", "new");
- // After the rename, FK ends up ON even though we started with FK=OFF.
- expect(testDb.pragma("foreign_keys", { simple: true })).toBe(1);
- });
-});
-
-describe("archiveProject", () => {
- it("sets archived_at and returns the row", () => {
- createProject({ display_name: "Acme" });
- const out = archiveProject("acme");
- expect(out!.archived_at).not.toBeNull();
- expect(Date.parse(out!.archived_at!)).toBeGreaterThan(0);
- });
-
- it("is a no-op when already archived (preserves first archived_at)", async () => {
- createProject({ display_name: "Acme" });
- const first = archiveProject("acme")!;
- await new Promise((r) => setTimeout(r, 5));
- const second = archiveProject("acme")!;
- expect(second.archived_at).toBe(first.archived_at);
- });
-
- it("returns null when project doesn't exist", () => {
- expect(archiveProject("nope")).toBeNull();
- });
-});
-
-describe("unarchiveProject", () => {
- it("clears archived_at and returns the row", () => {
- createProject({ display_name: "Acme" });
- archiveProject("acme");
- expect(getProject("acme")!.archived_at).not.toBeNull();
- const out = unarchiveProject("acme");
- expect(out!.archived_at).toBeNull();
- });
-
- it("is a no-op when project is not archived", () => {
- createProject({ display_name: "Acme" });
- const out = unarchiveProject("acme");
- expect(out!.archived_at).toBeNull();
- });
-
- it("returns null when project doesn't exist", () => {
- expect(unarchiveProject("nope")).toBeNull();
- });
-});
-
-describe("deleteProjectRow", () => {
- it("cleans the project row when no child rows exist", () => {
- const result = createProject({ display_name: "Acme" });
- expect(result.ok).toBe(true);
- expect(() => deleteProjectRow("acme")).not.toThrow();
- expect(testDb.prepare("SELECT 1 FROM projects WHERE slug = ?").get("acme")).toBeUndefined();
- });
-
- it("is a no-op when project doesn't exist", () => {
- expect(() => deleteProjectRow("missing")).not.toThrow();
- });
-
- describe("regression: FOREIGN KEY constraint failure on delete", () => {
- // The bug: deleteProjectRow's childTables list was stale — it deleted
- // from approvals/agent_actions/cost_snapshots/connections (the last
- // two don't even exist in our migrations), missing tasks, cost_events,
- // oauth_tokens, sequence_runs. With orchestration adding task rows
- // aggressively, deletes started tripping the FK constraint.
- // This block populates every FK-bearing table and asserts the delete
- // succeeds + nothing is left behind.
-
- it("cleans tasks rows (the table that exposed the bug)", () => {
- createProject({ display_name: "Acme" });
- testDb
- .prepare(
- `INSERT INTO tasks
- (id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES ('t1', 'acme', 'acme-google-ads', 'do x', 'proposed', 'now', 'now')`,
- )
- .run();
-
- expect(() => deleteProjectRow("acme")).not.toThrow();
- expect(testDb.prepare("SELECT 1 FROM tasks WHERE project_slug = ?").get("acme")).toBeUndefined();
- expect(testDb.prepare("SELECT 1 FROM projects WHERE slug = ?").get("acme")).toBeUndefined();
- });
-
- it("cleans every FK-bearing child table without tripping FK", () => {
- createProject({ display_name: "Acme" });
-
- // One row per FK-bearing table from the migrations. If any new
- // migration adds a project_slug FK and forgets to update
- // deleteProjectRow's list, this test fails immediately.
- testDb
- .prepare(
- `INSERT INTO tasks
- (id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("t1", "acme", "acme-google-ads", "do x", "proposed", "now", "now");
- testDb
- .prepare(
- `INSERT INTO approvals
- (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("ap1", "acme", "acme-google-ads", "raise bid", "bid_change", 0, "{}", "pending", "now");
- testDb
- .prepare(
- `INSERT INTO cost_events
- (id, project_slug, agent_id, source, amount_usd, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run("c1", "acme", "acme-google-ads", "llm", 0.01, "now");
- testDb
- .prepare(
- `INSERT INTO oauth_tokens
- (id, project_slug, provider, account_label, access_token_enc, refresh_token_enc, expires_at, scope, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("o1", "acme", "google_ads", "acme", "x", "y", "later", "scope", "now", "now");
- testDb
- .prepare(
- `INSERT INTO agent_actions
- (id, project_slug, agent_id, action_type, summary, occurred_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- )
- .run("a1", "acme", "system", "project_created", "x", "now");
- testDb
- .prepare(
- `INSERT INTO sequence_runs
- (id, project_slug, agent_id, sequence_kind, cursor, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("s1", "acme", "acme-cmo", "k", "0", "pending", "now", "now");
- testDb
- .prepare(
- `INSERT INTO questions
- (id, project_slug, agent_id, prompt, options_json, status, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("q1", "acme", "acme-cmo", "ok?", "[]", "pending", "now");
- testDb
- .prepare(
- `INSERT INTO mcp_tokens
- (id, project_slug, server_name, account_label, access_token_enc, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("m1", "acme", "notfair-googleads", "", "tok", "now", "now");
- testDb
- .prepare(
- `INSERT INTO scheduled_jobs
- (id, project_slug, agent_id, name, cron_expr, message, enabled, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("j1", "acme", "acme-google-ads", "daily", "0 9 * * *", "go", 1, "now", "now");
- testDb
- .prepare(
- `INSERT INTO sessions
- (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("se1", "acme", "acme-google-ads", "main", "claude-code-local", "now", "now");
-
- // Pre-condition: every child table has a row keyed to acme.
- for (const table of [
- "tasks",
- "approvals",
- "cost_events",
- "oauth_tokens",
- "agent_actions",
- "sequence_runs",
- "questions",
- "mcp_tokens",
- "scheduled_jobs",
- "sessions",
- ]) {
- expect(
- testDb.prepare(`SELECT 1 FROM ${table} WHERE project_slug = ?`).get("acme"),
- `${table} should have a pre-existing row`,
- ).toBeTruthy();
- }
-
- // The actual fix: delete should NOT throw FOREIGN KEY constraint failed.
- expect(() => deleteProjectRow("acme")).not.toThrow();
-
- // Post-condition: project + every child row gone.
- expect(
- testDb.prepare("SELECT 1 FROM projects WHERE slug = ?").get("acme"),
- ).toBeUndefined();
- for (const table of [
- "tasks",
- "approvals",
- "cost_events",
- "oauth_tokens",
- "agent_actions",
- "sequence_runs",
- "questions",
- "mcp_tokens",
- "scheduled_jobs",
- "sessions",
- ]) {
- expect(
- testDb.prepare(`SELECT 1 FROM ${table} WHERE project_slug = ?`).get("acme"),
- `${table} should have no rows after delete`,
- ).toBeUndefined();
- }
- });
- });
-});
diff --git a/notfair-cmo/src/server/db/questions.test.ts b/notfair-cmo/src/server/db/questions.test.ts
deleted file mode 100644
index 7ec37c43..00000000
--- a/notfair-cmo/src/server/db/questions.test.ts
+++ /dev/null
@@ -1,240 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import {
- answerQuestion,
- cancelQuestion,
- createQuestion,
- getQuestion,
- listOpenQuestionsForProject,
- listOpenQuestionsForTask,
- listQuestionsForTask,
- parseQuestionOptions,
-} from "./questions";
-
-function applyMigrations(db: Database.Database): void {
- for (const m of MIGRATIONS) db.exec(m.sql);
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-function seedTask(id = "t-1", project_slug = "acme"): string {
- testDb
- .prepare(
- `INSERT INTO tasks
- (id, project_slug, agent_id, brief, status, created_at, updated_at, display_id)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run(
- id,
- project_slug,
- `${project_slug}-cmo`,
- "do the thing",
- "working",
- "2026-01-01T00:00:00.000Z",
- "2026-01-01T00:00:00.000Z",
- // display_id is globally unique — derive from the task id so multiple
- // seedTask() calls in one test don't collide.
- `${project_slug}-${id}`,
- );
- return id;
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("createQuestion", () => {
- it("persists a pending question with options serialized as JSON", () => {
- seedProject();
- const taskId = seedTask();
- const q = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- task_id: taskId,
- prompt: "Which channel should we test first?",
- options: ["Google Ads", "Meta", "TikTok"],
- });
- expect(q.id).toMatch(/[0-9a-f-]{36}/);
- expect(q.status).toBe("pending");
- expect(q.resolved_at).toBeNull();
- expect(q.answer_option_index).toBeNull();
- expect(q.answer_text).toBeNull();
- expect(parseQuestionOptions(q)).toEqual(["Google Ads", "Meta", "TikTok"]);
- });
-
- it("stores an empty options array when none are supplied", () => {
- seedProject();
- const q = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- prompt: "Free text only",
- options: [],
- });
- expect(parseQuestionOptions(q)).toEqual([]);
- });
-});
-
-describe("listOpenQuestionsForTask / listOpenQuestionsForProject", () => {
- it("filters by status=pending and the right scope", () => {
- seedProject();
- const taskA = seedTask("t-a");
- const taskB = seedTask("t-b");
- const open = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- task_id: taskA,
- prompt: "Open on A",
- options: [],
- });
- const other = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- task_id: taskB,
- prompt: "Open on B",
- options: [],
- });
- const cancelled = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- task_id: taskA,
- prompt: "Will be cancelled",
- options: [],
- });
- cancelQuestion(cancelled.id);
-
- const openOnA = listOpenQuestionsForTask(taskA);
- expect(openOnA.map((q) => q.id)).toEqual([open.id]);
-
- const allProject = listOpenQuestionsForProject("acme");
- expect(allProject.map((q) => q.id).sort()).toEqual(
- [open.id, other.id].sort(),
- );
- });
-});
-
-describe("listQuestionsForTask", () => {
- it("returns every question on the task regardless of status, newest first", () => {
- seedProject();
- const taskId = seedTask();
- const first = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- task_id: taskId,
- prompt: "First",
- options: [],
- });
- const second = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- task_id: taskId,
- prompt: "Second",
- options: [],
- });
- cancelQuestion(first.id);
-
- const rows = listQuestionsForTask(taskId);
- expect(rows.map((q) => q.id)).toEqual([second.id, first.id]);
- });
-});
-
-describe("answerQuestion", () => {
- it("marks the row answered with option_index and text, sets resolved_at", () => {
- seedProject();
- const taskId = seedTask();
- const q = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- task_id: taskId,
- prompt: "Pick one",
- options: ["A", "B"],
- });
- const after = answerQuestion({
- id: q.id,
- answer_option_index: 1,
- answer_text: "B with caveats",
- });
- expect(after).not.toBeNull();
- expect(after?.status).toBe("answered");
- expect(after?.answer_option_index).toBe(1);
- expect(after?.answer_text).toBe("B with caveats");
- expect(after?.resolved_by_kind).toBe("user");
- expect(after?.resolved_at).toBeTruthy();
- });
-
- it("is a no-op when the row is already terminal (returns null)", () => {
- seedProject();
- const q = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- prompt: "Already cancelled",
- options: [],
- });
- cancelQuestion(q.id);
- const result = answerQuestion({
- id: q.id,
- answer_option_index: null,
- answer_text: "too late",
- });
- expect(result).toBeNull();
- const fresh = getQuestion(q.id);
- expect(fresh?.status).toBe("cancelled");
- });
-});
-
-describe("cancelQuestion", () => {
- it("marks pending → cancelled and is idempotent (second call returns null)", () => {
- seedProject();
- const q = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- prompt: "Cancel me",
- options: [],
- });
- const first = cancelQuestion(q.id);
- expect(first?.status).toBe("cancelled");
- const again = cancelQuestion(q.id);
- expect(again).toBeNull();
- });
-});
-
-describe("parseQuestionOptions", () => {
- it("returns [] for malformed JSON or non-string entries", () => {
- seedProject();
- const q = createQuestion({
- project_slug: "acme",
- agent_id: "acme-cmo",
- prompt: "fine",
- options: ["x"],
- });
- expect(parseQuestionOptions(q)).toEqual(["x"]);
- expect(parseQuestionOptions({ ...q, options_json: "not json" })).toEqual([]);
- expect(parseQuestionOptions({ ...q, options_json: "[1, 2]" })).toEqual([]);
- });
-});
diff --git a/notfair-cmo/src/server/db/questions.ts b/notfair-cmo/src/server/db/questions.ts
deleted file mode 100644
index eb13f0df..00000000
--- a/notfair-cmo/src/server/db/questions.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { getDb } from "./db";
-import type { Question, QuestionStatus } from "@/types";
-
-export type CreateQuestionInput = {
- project_slug: string;
- agent_id: string;
- task_id?: string | null;
- prompt: string;
- /** Multiple-choice hints rendered as buttons. Empty array = free-text only. */
- options: string[];
-};
-
-export function createQuestion(input: CreateQuestionInput): Question {
- const db = getDb();
- const id = randomUUID();
- const createdAt = new Date().toISOString();
- db.prepare(
- `INSERT INTO questions
- (id, project_slug, agent_id, task_id, prompt, options_json,
- status, answer_option_index, answer_text, resolved_by_kind,
- created_at, resolved_at)
- VALUES (?, ?, ?, ?, ?, ?, 'pending', NULL, NULL, NULL, ?, NULL)`,
- ).run(
- id,
- input.project_slug,
- input.agent_id,
- input.task_id ?? null,
- input.prompt,
- JSON.stringify(input.options ?? []),
- createdAt,
- );
- return getQuestion(id)!;
-}
-
-export function getQuestion(id: string): Question | null {
- const db = getDb();
- const row = db
- .prepare("SELECT * FROM questions WHERE id = ?")
- .get(id) as Question | undefined;
- return row ?? null;
-}
-
-/** Open (pending) questions on a given task, oldest first. Usually 0 or 1. */
-export function listOpenQuestionsForTask(task_id: string): Question[] {
- const db = getDb();
- return db
- .prepare(
- `SELECT * FROM questions
- WHERE task_id = ? AND status = 'pending'
- ORDER BY created_at ASC`,
- )
- .all(task_id) as Question[];
-}
-
-/** Every question (any status) anchored to a task, newest first. Audit trail.
- * `rowid DESC` tiebreaker keeps ordering deterministic when two rows share
- * a millisecond-resolution `created_at`: SQLite assigns rowid sequentially
- * per insert, so this falls back to insertion order. */
-export function listQuestionsForTask(task_id: string): Question[] {
- const db = getDb();
- return db
- .prepare(
- `SELECT * FROM questions
- WHERE task_id = ?
- ORDER BY created_at DESC, rowid DESC`,
- )
- .all(task_id) as Question[];
-}
-
-/** Project-wide open questions. Used by the future approvals/inbox tab. */
-export function listOpenQuestionsForProject(project_slug: string): Question[] {
- const db = getDb();
- return db
- .prepare(
- `SELECT * FROM questions
- WHERE project_slug = ? AND status = 'pending'
- ORDER BY created_at DESC`,
- )
- .all(project_slug) as Question[];
-}
-
-export type AnswerQuestionInput = {
- id: string;
- /** Zero-based index into the original options[] when the user clicked
- * an option. Null when the user only typed free-text. */
- answer_option_index?: number | null;
- /** Free-text answer typed by the user. Null when the user only clicked
- * an option. */
- answer_text?: string | null;
-};
-
-/**
- * Conditional UPDATE keyed on status='pending' — returns the post-update
- * row, or null if the question wasn't pending (already answered /
- * cancelled / unknown id). Callers use null to detect race-loss and bail
- * silently.
- */
-export function answerQuestion(input: AnswerQuestionInput): Question | null {
- const db = getDb();
- const resolvedAt = new Date().toISOString();
- const res = db
- .prepare(
- `UPDATE questions
- SET status = 'answered',
- answer_option_index = ?,
- answer_text = ?,
- resolved_by_kind = 'user',
- resolved_at = ?
- WHERE id = ? AND status = 'pending'`,
- )
- .run(
- input.answer_option_index ?? null,
- input.answer_text ?? null,
- resolvedAt,
- input.id,
- );
- if (res.changes === 0) return null;
- return getQuestion(input.id);
-}
-
-export function cancelQuestion(id: string): Question | null {
- const db = getDb();
- const resolvedAt = new Date().toISOString();
- const res = db
- .prepare(
- `UPDATE questions
- SET status = 'cancelled',
- resolved_by_kind = 'user',
- resolved_at = ?
- WHERE id = ? AND status = 'pending'`,
- )
- .run(resolvedAt, id);
- if (res.changes === 0) return null;
- return getQuestion(id);
-}
-
-/** Convenience: parse options_json into a string[] for the UI/handler. */
-export function parseQuestionOptions(q: Question): string[] {
- try {
- const parsed = JSON.parse(q.options_json);
- if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) {
- return parsed;
- }
- } catch {
- // fall through
- }
- return [];
-}
-
-/** Map a question.status string to a human label for badges. */
-export function statusLabel(status: QuestionStatus): string {
- switch (status) {
- case "pending":
- return "Pending";
- case "answered":
- return "Answered";
- case "cancelled":
- return "Cancelled";
- }
-}
diff --git a/notfair-cmo/src/server/db/tasks.test.ts b/notfair-cmo/src/server/db/tasks.test.ts
deleted file mode 100644
index 00bb251d..00000000
--- a/notfair-cmo/src/server/db/tasks.test.ts
+++ /dev/null
@@ -1,594 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import {
- claimProposedTask,
- clearBlockerAndPromote,
- createTask,
- getTask,
- inFlightCountsByAgent,
- listTasks,
- listTasksBlockedBy,
- listTasksByAgent,
- markTaskBlocked,
- setTaskThreadIfMissing,
- unblockTask,
- updateTask,
-} from "./tasks";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) {
- db.exec(migration.sql);
- }
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- applyMigrations(db);
- return db;
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("createTask", () => {
- it("creates a proposed task with sensible defaults", () => {
- seedProject();
- const t = createTask({
- project_slug: "acme",
- agent_id: "acme-cmo",
- brief: "do the thing",
- });
- expect(t.id).toMatch(/[0-9a-f-]{36}/);
- expect(t.display_id).toBe("acme-1");
- expect(t.status).toBe("proposed");
- expect(t.title).toBeNull();
- expect(t.success_criteria).toBeNull();
- expect(t.deadline_iso).toBeNull();
- expect(t.thread_id).toBeNull();
- expect(t.assigner_agent_id).toBeNull();
- expect(t.result_json).toBeNull();
- expect(t.error_message).toBeNull();
- expect(Date.parse(t.created_at)).toBeGreaterThan(0);
- expect(t.updated_at).toBe(t.created_at);
- });
-
- it("stores optional fields when provided", () => {
- seedProject();
- const t = createTask({
- project_slug: "acme",
- agent_id: "acme-google-ads",
- title: "Raise bid",
- brief: "Raise bid to $2.50 on shoes",
- success_criteria: "CPA stays < $30",
- deadline_iso: "2026-12-31T23:59:59.000Z",
- assigner_agent_id: "acme-cmo",
- status: "approved",
- });
- expect(t.title).toBe("Raise bid");
- expect(t.success_criteria).toBe("CPA stays < $30");
- expect(t.deadline_iso).toBe("2026-12-31T23:59:59.000Z");
- expect(t.assigner_agent_id).toBe("acme-cmo");
- expect(t.status).toBe("approved");
- });
-
- it("allocates monotonically increasing display_ids per project", () => {
- seedProject("acme");
- seedProject("other");
- const a1 = createTask({ project_slug: "acme", agent_id: "x", brief: "1" });
- const a2 = createTask({ project_slug: "acme", agent_id: "x", brief: "2" });
- const a3 = createTask({ project_slug: "acme", agent_id: "x", brief: "3" });
- const o1 = createTask({ project_slug: "other", agent_id: "x", brief: "1" });
- const o2 = createTask({ project_slug: "other", agent_id: "x", brief: "2" });
- expect(a1.display_id).toBe("acme-1");
- expect(a2.display_id).toBe("acme-2");
- expect(a3.display_id).toBe("acme-3");
- expect(o1.display_id).toBe("other-1");
- expect(o2.display_id).toBe("other-2");
- });
-
- it("display_id allocator picks up after manually inserted high N", () => {
- seedProject();
- // Insert a row with display_id "acme-7" so the next createTask picks acme-8.
- testDb
- .prepare(
- `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("u1", "acme-7", "acme", "x", "b", "proposed", "now", "now");
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "next" });
- expect(t.display_id).toBe("acme-8");
- });
-
- it("display_id is unique (UNIQUE INDEX from migration 004)", () => {
- seedProject();
- createTask({ project_slug: "acme", agent_id: "x", brief: "a" });
- // Manually attempting to insert another acme-1 must fail at the DB layer.
- expect(() =>
- testDb
- .prepare(
- `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("dupe", "acme-1", "acme", "x", "b", "proposed", "now", "now"),
- ).toThrow(/UNIQUE/i);
- });
-
- it("trips FK on missing project", () => {
- expect(() =>
- createTask({ project_slug: "no-such", agent_id: "x", brief: "b" }),
- ).toThrow(/FOREIGN KEY/i);
- });
-
- it("rejects invalid status via CHECK constraint", () => {
- seedProject();
- expect(() =>
- createTask({
- project_slug: "acme",
- agent_id: "x",
- brief: "b",
- // @ts-expect-error invalid on purpose
- status: "bogus",
- }),
- ).toThrow(/CHECK/i);
- });
-});
-
-describe("getTask", () => {
- it("finds a task by UUID", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- const out = getTask(t.id);
- expect(out).not.toBeNull();
- expect(out!.id).toBe(t.id);
- });
-
- it("finds a task by display_id", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- const out = getTask(t.display_id);
- expect(out).not.toBeNull();
- expect(out!.id).toBe(t.id);
- });
-
- it("returns null when neither match", () => {
- expect(getTask("not-there")).toBeNull();
- });
-});
-
-describe("listTasks", () => {
- it("returns all tasks for project ordered by created_at DESC", () => {
- seedProject();
- testDb
- .prepare(
- `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("t1", "acme-1", "acme", "x", "first", "proposed", "2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
- testDb
- .prepare(
- `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run("t2", "acme-2", "acme", "x", "second", "working", "2026-01-02T00:00:00.000Z", "2026-01-02T00:00:00.000Z");
-
- const rows = listTasks("acme");
- expect(rows.map((r) => r.brief)).toEqual(["second", "first"]);
- });
-
- it("filters by status when provided", () => {
- seedProject();
- createTask({ project_slug: "acme", agent_id: "x", brief: "p" });
- createTask({ project_slug: "acme", agent_id: "x", brief: "r", status: "working" });
- expect(listTasks("acme", "proposed")).toHaveLength(1);
- expect(listTasks("acme", "working")).toHaveLength(1);
- expect(listTasks("acme", "done")).toHaveLength(0);
- });
-
- it("isolates by project", () => {
- seedProject("a");
- seedProject("b");
- createTask({ project_slug: "a", agent_id: "x", brief: "1" });
- createTask({ project_slug: "b", agent_id: "x", brief: "1" });
- expect(listTasks("a")).toHaveLength(1);
- expect(listTasks("b")).toHaveLength(1);
- });
-});
-
-describe("listTasksByAgent", () => {
- it("returns tasks for the agent across projects", () => {
- seedProject("a");
- seedProject("b");
- createTask({ project_slug: "a", agent_id: "specialist", brief: "1" });
- createTask({ project_slug: "b", agent_id: "specialist", brief: "2" });
- createTask({ project_slug: "a", agent_id: "other-agent", brief: "x" });
- expect(listTasksByAgent("specialist")).toHaveLength(2);
- expect(listTasksByAgent("other-agent")).toHaveLength(1);
- });
-
- it("filters by status", () => {
- seedProject();
- createTask({ project_slug: "acme", agent_id: "a1", brief: "p" });
- createTask({
- project_slug: "acme",
- agent_id: "a1",
- brief: "r",
- status: "working",
- });
- expect(listTasksByAgent("a1", "working")).toHaveLength(1);
- expect(listTasksByAgent("a1", "proposed")).toHaveLength(1);
- });
-
- it("returns empty array when no tasks assigned", () => {
- expect(listTasksByAgent("nobody")).toEqual([]);
- });
-});
-
-describe("inFlightCountsByAgent", () => {
- it("counts only proposed/approved/running per agent", () => {
- seedProject();
- createTask({ project_slug: "acme", agent_id: "ads", brief: "1" }); // proposed
- createTask({
- project_slug: "acme",
- agent_id: "ads",
- brief: "2",
- status: "approved",
- });
- createTask({
- project_slug: "acme",
- agent_id: "ads",
- brief: "3",
- status: "working",
- });
- createTask({
- project_slug: "acme",
- agent_id: "ads",
- brief: "4",
- status: "done",
- });
- createTask({
- project_slug: "acme",
- agent_id: "seo",
- brief: "1",
- status: "working",
- });
- createTask({
- project_slug: "acme",
- agent_id: "seo",
- brief: "2",
- status: "failed",
- });
- createTask({
- project_slug: "acme",
- agent_id: "seo",
- brief: "3",
- status: "cancelled",
- });
-
- const map = inFlightCountsByAgent("acme");
- expect(map.get("ads")).toBe(3);
- expect(map.get("seo")).toBe(1);
- });
-
- it("returns an empty map when no in-flight tasks exist", () => {
- seedProject();
- createTask({ project_slug: "acme", agent_id: "x", brief: "1", status: "done" });
- const map = inFlightCountsByAgent("acme");
- expect(map.size).toBe(0);
- });
-
- it("isolates by project", () => {
- seedProject("a");
- seedProject("b");
- createTask({ project_slug: "a", agent_id: "ads", brief: "1" });
- createTask({ project_slug: "b", agent_id: "ads", brief: "1" });
- expect(inFlightCountsByAgent("a").get("ads")).toBe(1);
- expect(inFlightCountsByAgent("b").get("ads")).toBe(1);
- });
-});
-
-describe("setTaskThreadIfMissing", () => {
- it("sets thread_id when null and bumps updated_at", async () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- // sleep so updated_at can advance
- await new Promise((r) => setTimeout(r, 5));
- const out = setTaskThreadIfMissing(t.id, "thread-1");
- expect(out).not.toBeNull();
- expect(out!.thread_id).toBe("thread-1");
- expect(Date.parse(out!.updated_at)).toBeGreaterThanOrEqual(
- Date.parse(t.updated_at),
- );
- });
-
- it("is a no-op when thread_id is already set (returns current row)", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- setTaskThreadIfMissing(t.id, "first");
- const after = setTaskThreadIfMissing(t.id, "second");
- expect(after!.thread_id).toBe("first");
- });
-
- it("returns null when the task doesn't exist", () => {
- expect(setTaskThreadIfMissing("nope", "t")).toBeNull();
- });
-
- it("works via display_id (getTask accepts either)", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- // Pass display_id; setTaskThreadIfMissing -> getTask first resolves the
- // current row, but the UPDATE itself uses the PK from the input which is
- // the display_id here. The function signature says "id" — confirm what
- // actually happens. The UPDATE uses WHERE id = ?, and display_id won't
- // match the PK, so no row gets updated. The function returns the row
- // unchanged (getTask resolves display_id).
- const out = setTaskThreadIfMissing(t.display_id, "ignored");
- // Documenting current behavior: the lookup succeeds, the UPDATE filter
- // misses, and we return getTask(display_id) which still has null thread_id.
- expect(out).not.toBeNull();
- expect(out!.thread_id).toBeNull();
- });
-});
-
-describe("updateTask", () => {
- it("updates status, result, error_message and bumps updated_at", async () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- await new Promise((r) => setTimeout(r, 5));
- const out = updateTask(t.id, {
- status: "done",
- result: { hello: "world" },
- error_message: null,
- });
- expect(out).not.toBeNull();
- expect(out!.status).toBe("done");
- expect(out!.result_json).toBe(JSON.stringify({ hello: "world" }));
- expect(out!.error_message).toBeNull();
- expect(Date.parse(out!.updated_at)).toBeGreaterThanOrEqual(
- Date.parse(t.updated_at),
- );
- });
-
- it("keeps existing values when fields are omitted (status defaults to current)", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- updateTask(t.id, { result: { a: 1 } });
- const fetched = getTask(t.id);
- expect(fetched!.status).toBe("proposed"); // unchanged
- expect(fetched!.result_json).toBe(JSON.stringify({ a: 1 }));
- });
-
- it("explicit null error_message clears error", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- updateTask(t.id, { error_message: "boom" });
- expect(getTask(t.id)!.error_message).toBe("boom");
- updateTask(t.id, { error_message: null });
- expect(getTask(t.id)!.error_message).toBeNull();
- });
-
- it("returns null when task doesn't exist", () => {
- expect(updateTask("missing", { status: "working" })).toBeNull();
- });
-
- it("rejects invalid status via CHECK constraint", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- expect(() =>
- // @ts-expect-error invalid on purpose
- updateTask(t.id, { status: "bogus" }),
- ).toThrow(/CHECK/i);
- });
-});
-
-describe("claimProposedTask", () => {
- it("flips proposed → running and returns the post-flip row", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- const out = claimProposedTask(t.id);
- expect(out).not.toBeNull();
- expect(out!.status).toBe("working");
- });
-
- it("returns null when the task is already past proposed", () => {
- seedProject();
- const t = createTask({
- project_slug: "acme",
- agent_id: "x",
- brief: "b",
- status: "working",
- });
- expect(claimProposedTask(t.id)).toBeNull();
- });
-
- it("returns null when the task is terminal (succeeded)", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- updateTask(t.id, { status: "done" });
- expect(claimProposedTask(t.id)).toBeNull();
- expect(getTask(t.id)!.status).toBe("done"); // not regressed
- });
-
- it("returns null when the task doesn't exist", () => {
- expect(claimProposedTask("missing")).toBeNull();
- });
-
- it("is single-shot: a second call after a successful claim returns null", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- expect(claimProposedTask(t.id)!.status).toBe("working");
- expect(claimProposedTask(t.id)).toBeNull();
- });
-});
-
-describe("markTaskBlocked + unblockTask", () => {
- it("flips a running task to blocked, then unblockTask flips it back to running", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- claimProposedTask(t.id); // proposed → running
- const blocked = markTaskBlocked(t.id);
- expect(blocked?.status).toBe("blocked");
- const unblocked = unblockTask(t.id);
- expect(unblocked?.status).toBe("working");
- });
-
- it("markTaskBlocked accepts proposed + approved as source states", () => {
- seedProject();
- const a = createTask({ project_slug: "acme", agent_id: "x", brief: "a" });
- // proposed → blocked
- expect(markTaskBlocked(a.id)?.status).toBe("blocked");
-
- const b = createTask({
- project_slug: "acme",
- agent_id: "x",
- brief: "b",
- status: "approved",
- });
- expect(markTaskBlocked(b.id)?.status).toBe("blocked");
- });
-
- it("markTaskBlocked does NOT regress a terminal task", () => {
- seedProject();
- const t = createTask({
- project_slug: "acme",
- agent_id: "x",
- brief: "b",
- status: "done",
- });
- const after = markTaskBlocked(t.id);
- expect(after?.status).toBe("done");
- });
-
- it("unblockTask is a no-op when the task isn't blocked", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });
- claimProposedTask(t.id);
- const after = unblockTask(t.id);
- expect(after?.status).toBe("working"); // unchanged
- });
-
- it("inFlightCountsByAgent counts blocked tasks too", () => {
- seedProject();
- const t = createTask({ project_slug: "acme", agent_id: "agent-1", brief: "b" });
- markTaskBlocked(t.id);
- expect(inFlightCountsByAgent("acme").get("agent-1")).toBe(1);
- });
-});
-
-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/notfair-cmo/src/server/db/tasks.ts b/notfair-cmo/src/server/db/tasks.ts
deleted file mode 100644
index 5a07e109..00000000
--- a/notfair-cmo/src/server/db/tasks.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { getDb } from "./db";
-import type { Task, TaskStatus } from "@/types";
-
-export type CreateTaskInput = {
- project_slug: string;
- /** Assignee — the agent expected to do the work. */
- agent_id: string;
- /** Short label for the kanban card. Optional but recommended. */
- title?: string | null;
- brief: string;
- success_criteria?: string | null;
- deadline_iso?: string | null;
- status?: TaskStatus;
- /** Agent that created this task. CMO is the typical originator. */
- assigner_agent_id?: string | null;
- /**
- * 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;
-};
-
-/**
- * Allocate the next display_id for a project — `<slug>-<n>` where n is one
- * past the current MAX. better-sqlite3 is synchronous so two creates in
- * one process can't race; cross-process collisions don't apply (single-user
- * local CLI) and the UNIQUE index would catch them if they ever did.
- */
-function nextDisplayId(project_slug: string): string {
- const db = getDb();
- // substr starts at length(slug) + 2 to skip past "slug-".
- const row = db
- .prepare(
- `SELECT COALESCE(MAX(CAST(substr(display_id, ?) AS INTEGER)), 0) AS max_n
- FROM tasks
- WHERE project_slug = ? AND display_id LIKE ?`,
- )
- .get(project_slug.length + 2, project_slug, `${project_slug}-%`) as
- | { max_n: number }
- | undefined;
- const n = (row?.max_n ?? 0) + 1;
- return `${project_slug}-${n}`;
-}
-
-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),
- project_slug: input.project_slug,
- agent_id: input.agent_id,
- title: input.title ?? null,
- brief: input.brief,
- success_criteria: input.success_criteria ?? null,
- deadline_iso: input.deadline_iso ?? null,
- status: 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, blocked_by_task_id, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?, ?, ?)`,
- ).run(
- task.id,
- task.display_id,
- task.project_slug,
- task.agent_id,
- task.title,
- task.brief,
- task.success_criteria,
- 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
- * remains stable forever after so the per-task chat history persists.
- * No-op when the task already has a thread_id assigned.
- */
-export function setTaskThreadIfMissing(
- id: string,
- thread_id: string,
-): Task | null {
- const db = getDb();
- const current = getTask(id);
- if (!current) return null;
- if (current.thread_id) return current;
- db.prepare(
- "UPDATE tasks SET thread_id = ?, updated_at = ? WHERE id = ? AND thread_id IS NULL",
- ).run(thread_id, new Date().toISOString(), id);
- return getTask(id);
-}
-
-/**
- * Look up a task by either the PK UUID or the human-readable display_id
- * (`<slug>-<n>`). URLs prefer display_id; internal callers may pass
- * either. Returns null when neither matches.
- */
-export function getTask(idOrDisplayId: string): Task | null {
- const db = getDb();
- const row = db
- .prepare("SELECT * FROM tasks WHERE id = ? OR display_id = ?")
- .get(idOrDisplayId, idOrDisplayId);
- return (row as Task) ?? null;
-}
-
-export function listTasks(project_slug: string, status?: TaskStatus): Task[] {
- const db = getDb();
- if (status) {
- return db
- .prepare("SELECT * FROM tasks WHERE project_slug = ? AND status = ? ORDER BY created_at DESC")
- .all(project_slug, status) as Task[];
- }
- return db
- .prepare("SELECT * FROM tasks WHERE project_slug = ? ORDER BY created_at DESC")
- .all(project_slug) as Task[];
-}
-
-/**
- * Per-agent task list — what's on this agent's plate. Used by the
- * /agents/[agent]/tasks page so the assignee can see its queue without
- * filtering the project-wide kanban manually.
- */
-export function listTasksByAgent(agent_id: string, status?: TaskStatus): Task[] {
- const db = getDb();
- if (status) {
- return db
- .prepare("SELECT * FROM tasks WHERE agent_id = ? AND status = ? ORDER BY created_at DESC")
- .all(agent_id, status) as Task[];
- }
- return db
- .prepare("SELECT * FROM tasks WHERE agent_id = ? ORDER BY created_at DESC")
- .all(agent_id) as Task[];
-}
-
-/**
- * Map of `agent_id → in-flight task count` for a single project. Drives the
- * sidebar's per-agent live-task badge. "In flight" means proposed (kickoff
- * pending), approved, working, or blocked. Terminal states (done/failed/cancelled)
- * never count.
- */
-export function inFlightCountsByAgent(
- project_slug: string,
-): Map<string, number> {
- const db = getDb();
- const rows = db
- .prepare(
- `SELECT agent_id, COUNT(*) as count
- FROM tasks
- WHERE project_slug = ? AND status IN ('proposed', 'approved', 'working', 'blocked')
- GROUP BY agent_id`,
- )
- .all(project_slug) as Array<{ agent_id: string; count: number }>;
- const map = new Map<string, number>();
- for (const r of rows) map.set(r.agent_id, r.count);
- return map;
-}
-
-export type UpdateTaskInput = {
- status?: TaskStatus;
- result?: unknown;
- error_message?: string | null;
-};
-
-export function updateTask(id: string, update: UpdateTaskInput): Task | null {
- const db = getDb();
- const now = new Date().toISOString();
- const current = getTask(id);
- if (!current) return null;
-
- const result_json = update.result !== undefined ? JSON.stringify(update.result) : current.result_json;
- const error_message = update.error_message !== undefined ? update.error_message : current.error_message;
- const status = update.status ?? current.status;
-
- db.prepare(
- "UPDATE tasks SET status = ?, result_json = ?, error_message = ?, updated_at = ? WHERE id = ?",
- ).run(status, result_json, error_message, now, id);
-
- return getTask(id);
-}
-
-/**
- * Atomically flip a task from `proposed` to `working` and return the post-flip
- * row, or null when no claim happened (already started, already terminal, row
- * missing). The conditional WHERE clause is the whole point — callers
- * (kickoff entry points, "Start all" batch) can never accidentally regress a
- * `done`/`failed`/`cancelled` row back to `working` by passing in a
- * stale in-memory task snapshot. better-sqlite3 is synchronous, so the
- * read-back here cannot race with a concurrent writer in this process.
- */
-export function claimProposedTask(id: string): Task | null {
- const db = getDb();
- const now = new Date().toISOString();
- const info = db
- .prepare(
- "UPDATE tasks SET status = 'working', updated_at = ? WHERE id = ? AND status = 'proposed'",
- )
- .run(now, id);
- if (info.changes === 0) return null;
- return getTask(id);
-}
-
-/**
- * Flip a working task to `blocked` (waiting on an approval). Only transitions
- * from `working` or `proposed` so we don't undo a terminal state. Returns
- * the post-flip row, or the current row when the transition didn't apply.
- */
-export function markTaskBlocked(id: string): Task | null {
- const db = getDb();
- const now = new Date().toISOString();
- db.prepare(
- "UPDATE tasks SET status = 'blocked', updated_at = ? WHERE id = ? AND status IN ('working','proposed','approved')",
- ).run(now, id);
- return getTask(id);
-}
-
-/**
- * Flip a blocked task back to working once its approval resolves. No-op when
- * the task isn't blocked (e.g., already terminal because the user cancelled).
- */
-export function unblockTask(id: string): Task | null {
- const db = getDb();
- const now = new Date().toISOString();
- db.prepare(
- "UPDATE tasks SET status = 'working', updated_at = ? WHERE id = ? AND status = 'blocked'",
- ).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/notfair-cmo/src/server/db/user-mcp-servers.test.ts b/notfair-cmo/src/server/db/user-mcp-servers.test.ts
deleted file mode 100644
index 303eee3a..00000000
--- a/notfair-cmo/src/server/db/user-mcp-servers.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import {
- insertUserMcpServer,
- findUserMcpServer,
- listUserMcpServers,
- deleteUserMcpServer,
-} from "./user-mcp-servers";
-import { createProject } from "./projects";
-
-function makeProject(display_name: string) {
- const r = createProject({ display_name });
- if (!r.ok) throw new Error(`createProject failed: ${r.reason}`);
- return r.project;
-}
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- for (const m of MIGRATIONS) db.exec(m.sql);
- return db;
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("user_mcp_servers CRUD", () => {
- it("insertUserMcpServer + findUserMcpServer round-trips a row", () => {
- const project = makeProject("Acme Co");
- const row = insertUserMcpServer({
- project_slug: project.slug,
- key: "stripe",
- display_name: "Stripe",
- description: "Payments",
- resource_url: "https://mcp.stripe.com/",
- discovery_url:
- "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- });
- expect(row.id).toBeTruthy();
- expect(row.created_at).toBe(row.updated_at);
-
- const hit = findUserMcpServer(project.slug, "stripe");
- expect(hit?.display_name).toBe("Stripe");
- expect(hit?.resource_url).toBe("https://mcp.stripe.com/");
- });
-
- it("findUserMcpServer returns null for unknown rows", () => {
- const project = makeProject("Acme Co");
- expect(findUserMcpServer(project.slug, "nope")).toBeNull();
- });
-
- it("listUserMcpServers filters by project", () => {
- const a = makeProject("Acme A");
- const b = makeProject("Acme B");
- insertUserMcpServer({
- project_slug: a.slug,
- key: "stripe",
- display_name: "Stripe",
- resource_url: "https://mcp.stripe.com/",
- discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- });
- insertUserMcpServer({
- project_slug: b.slug,
- key: "vercel",
- display_name: "Vercel",
- resource_url: "https://mcp.vercel.com/",
- discovery_url: "https://mcp.vercel.com/.well-known/oauth-protected-resource",
- });
- expect(listUserMcpServers(a.slug)).toHaveLength(1);
- expect(listUserMcpServers(b.slug)).toHaveLength(1);
- expect(listUserMcpServers(a.slug)[0]?.key).toBe("stripe");
- });
-
- it("(project_slug, key) is unique", () => {
- const project = makeProject("Acme Co");
- insertUserMcpServer({
- project_slug: project.slug,
- key: "stripe",
- display_name: "Stripe",
- resource_url: "https://mcp.stripe.com/",
- discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- });
- expect(() =>
- insertUserMcpServer({
- project_slug: project.slug,
- key: "stripe",
- display_name: "Stripe v2",
- resource_url: "https://mcp.stripe.com/v2",
- discovery_url:
- "https://mcp.stripe.com/.well-known/oauth-protected-resource/v2",
- }),
- ).toThrow(/UNIQUE constraint/);
- });
-
- it("deleteUserMcpServer removes the row", () => {
- const project = makeProject("Acme Co");
- insertUserMcpServer({
- project_slug: project.slug,
- key: "stripe",
- display_name: "Stripe",
- resource_url: "https://mcp.stripe.com/",
- discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- });
- deleteUserMcpServer(project.slug, "stripe");
- expect(findUserMcpServer(project.slug, "stripe")).toBeNull();
- });
-
- it("FK rejects an insert against an unknown project", () => {
- expect(() =>
- insertUserMcpServer({
- project_slug: "ghost",
- key: "stripe",
- display_name: "Stripe",
- resource_url: "https://mcp.stripe.com/",
- discovery_url:
- "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- }),
- ).toThrow(/FOREIGN KEY/);
- });
-});
diff --git a/notfair-cmo/src/server/fs/pick-folder.test.ts b/notfair-cmo/src/server/fs/pick-folder.test.ts
deleted file mode 100644
index 4e1cf516..00000000
--- a/notfair-cmo/src/server/fs/pick-folder.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-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/notfair-cmo/src/server/live-events/emitter.test.ts b/notfair-cmo/src/server/live-events/emitter.test.ts
deleted file mode 100644
index 7fb10d02..00000000
--- a/notfair-cmo/src/server/live-events/emitter.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import {
- publishSessionEvent,
- subscribeSessionEvents,
-} from "./emitter";
-import type { TranscriptEvent } from "@/server/sessions";
-
-function makeEvent(overrides: Partial<TranscriptEvent> = {}): TranscriptEvent {
- return {
- id: "row-1",
- session_id: "s1",
- seq: 1,
- kind: "delta",
- payload_json: JSON.stringify({ text: "hi" }),
- created_at: "2026-05-31T00:00:00.000Z",
- ...overrides,
- };
-}
-
-describe("session event pub/sub", () => {
- const cleanups: Array<() => void> = [];
-
- afterEach(() => {
- while (cleanups.length > 0) cleanups.pop()!();
- });
-
- it("delivers a published event to a session's subscriber", () => {
- const listener = vi.fn();
- cleanups.push(subscribeSessionEvents("s1", listener));
- publishSessionEvent("s1", makeEvent());
- expect(listener).toHaveBeenCalledTimes(1);
- expect(listener.mock.calls[0][0].kind).toBe("delta");
- });
-
- it("does not deliver events from other sessions", () => {
- const listener = vi.fn();
- cleanups.push(subscribeSessionEvents("s1", listener));
- publishSessionEvent("s2", makeEvent({ session_id: "s2" }));
- expect(listener).not.toHaveBeenCalled();
- });
-
- it("stops delivering after unsubscribe", () => {
- const listener = vi.fn();
- const off = subscribeSessionEvents("s1", listener);
- off();
- publishSessionEvent("s1", makeEvent());
- expect(listener).not.toHaveBeenCalled();
- });
-
- it("fans out to every active subscriber for the same session", () => {
- const tabA = vi.fn();
- const tabB = vi.fn();
- cleanups.push(subscribeSessionEvents("s1", tabA));
- cleanups.push(subscribeSessionEvents("s1", tabB));
- publishSessionEvent("s1", makeEvent());
- expect(tabA).toHaveBeenCalledTimes(1);
- expect(tabB).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/notfair-cmo/src/server/mcp-catalog.test.ts b/notfair-cmo/src/server/mcp-catalog.test.ts
deleted file mode 100644
index ded80fe1..00000000
--- a/notfair-cmo/src/server/mcp-catalog.test.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "./db/migrations";
-
-let testDb: Database.Database;
-
-vi.mock("./db/db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import {
- MCP_CATALOG_PRESETS,
- getMcpCatalog,
- getMcpPresets,
- isPresetKey,
- mcpSpecByKey,
-} from "./mcp-catalog";
-import { createProject } from "./db/projects";
-import { insertUserMcpServer } from "./db/user-mcp-servers";
-
-function createDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- for (const m of MIGRATIONS) db.exec(m.sql);
- return db;
-}
-
-function makeProject(display_name: string) {
- const r = createProject({ display_name });
- if (!r.ok) throw new Error(`createProject failed: ${r.reason}`);
- return r.project;
-}
-
-beforeEach(() => {
- testDb = createDb();
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("MCP_CATALOG_PRESETS", () => {
- it("contains at least one preset", () => {
- expect(MCP_CATALOG_PRESETS.length).toBeGreaterThan(0);
- });
-
- it("includes the notfair-googleads preset with all required fields", () => {
- const ga = MCP_CATALOG_PRESETS.find((m) => m.key === "notfair-googleads");
- expect(ga).toBeDefined();
- expect(ga).toMatchObject({
- key: "notfair-googleads",
- display_name: expect.any(String),
- description: expect.any(String),
- resource_url: expect.stringMatching(/^https:\/\//),
- discovery_url: expect.stringMatching(/^https:\/\//),
- source: "preset",
- });
- });
-
- it("every preset is tagged source: 'preset' with required fields", () => {
- for (const spec of MCP_CATALOG_PRESETS) {
- expect(spec.source).toBe("preset");
- expect(spec.key).toMatch(/^[a-z0-9][a-z0-9-]*$/);
- expect(spec.resource_url).toMatch(/^https?:\/\//);
- expect(spec.discovery_url).toMatch(/^https?:\/\//);
- }
- });
-
- it("every preset key is unique", () => {
- const keys = MCP_CATALOG_PRESETS.map((m) => m.key);
- expect(new Set(keys).size).toBe(keys.length);
- });
-
- it("ships the five NotFair platform presets", () => {
- expect(MCP_CATALOG_PRESETS.map((m) => m.key)).toEqual([
- "notfair-googleads",
- "notfair-metaads",
- "notfair-googlesearchconsole",
- "notfair-googleanalytics",
- "notfair-xads",
- ]);
- });
-});
-
-describe("isPresetKey", () => {
- it("returns true for preset keys", () => {
- expect(isPresetKey("notfair-googleads")).toBe(true);
- });
-
- it("returns false for unknown keys", () => {
- expect(isPresetKey("stripe")).toBe(false);
- expect(isPresetKey("")).toBe(false);
- });
-});
-
-describe("getMcpCatalog", () => {
- it("returns presets when the project has no user rows", () => {
- const project = makeProject("Acme Co");
- const catalog = getMcpCatalog(project.slug);
- expect(catalog).toHaveLength(MCP_CATALOG_PRESETS.length);
- expect(catalog.every((s) => s.source === "preset")).toBe(true);
- });
-
- it("appends user-added rows tagged source: 'user' after presets", () => {
- const project = makeProject("Acme Co");
- insertUserMcpServer({
- project_slug: project.slug,
- key: "stripe",
- display_name: "Stripe",
- description: "Payments",
- resource_url: "https://mcp.stripe.com/",
- discovery_url:
- "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- });
- const catalog = getMcpCatalog(project.slug);
- expect(catalog).toHaveLength(MCP_CATALOG_PRESETS.length + 1);
- const stripe = catalog.find((s) => s.key === "stripe");
- expect(stripe?.source).toBe("user");
- expect(catalog[catalog.length - 1]?.key).toBe("stripe");
- });
-
- it("does not leak user rows from one project to another", () => {
- const a = makeProject("Acme A");
- const b = makeProject("Acme B");
- insertUserMcpServer({
- project_slug: a.slug,
- key: "stripe",
- display_name: "Stripe",
- resource_url: "https://mcp.stripe.com/",
- discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- });
- expect(getMcpCatalog(a.slug).map((s) => s.key)).toContain("stripe");
- expect(getMcpCatalog(b.slug).map((s) => s.key)).not.toContain("stripe");
- });
-
- it("filters out user rows that collide with a preset key", () => {
- const project = makeProject("Acme Co");
- insertUserMcpServer({
- project_slug: project.slug,
- key: "notfair-googleads",
- display_name: "Bogus shadow",
- resource_url: "https://evil.example/",
- discovery_url:
- "https://evil.example/.well-known/oauth-protected-resource",
- });
- const ga = getMcpCatalog(project.slug).filter(
- (s) => s.key === "notfair-googleads",
- );
- expect(ga).toHaveLength(1);
- expect(ga[0]?.source).toBe("preset");
- });
-});
-
-describe("mcpSpecByKey", () => {
- it("returns the preset when key matches", () => {
- const project = makeProject("Acme Co");
- const spec = mcpSpecByKey(project.slug, "notfair-googleads");
- expect(spec?.key).toBe("notfair-googleads");
- expect(spec?.source).toBe("preset");
- });
-
- it("returns a user-added spec when key matches", () => {
- const project = makeProject("Acme Co");
- insertUserMcpServer({
- project_slug: project.slug,
- key: "stripe",
- display_name: "Stripe",
- resource_url: "https://mcp.stripe.com/",
- discovery_url: "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- });
- const spec = mcpSpecByKey(project.slug, "stripe");
- expect(spec?.source).toBe("user");
- expect(spec?.display_name).toBe("Stripe");
- });
-
- it("returns undefined for unknown / empty keys", () => {
- const project = makeProject("Acme Co");
- expect(mcpSpecByKey(project.slug, "does-not-exist")).toBeUndefined();
- expect(mcpSpecByKey(project.slug, "")).toBeUndefined();
- });
-
- it("is case-sensitive", () => {
- const project = makeProject("Acme Co");
- expect(mcpSpecByKey(project.slug, "NOTFAIR-GOOGLEADS")).toBeUndefined();
- });
-});
-
-describe("getMcpPresets", () => {
- it("returns the preset list", () => {
- expect(getMcpPresets()).toEqual(MCP_CATALOG_PRESETS);
- });
-});
diff --git a/notfair-cmo/src/server/mcp-pending.test.ts b/notfair-cmo/src/server/mcp-pending.test.ts
deleted file mode 100644
index 59694b1c..00000000
--- a/notfair-cmo/src/server/mcp-pending.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- consumePending,
- setPending,
- type PendingMcpFlow,
-} from "./mcp-pending";
-
-function makeFlow(overrides: Partial<PendingMcpFlow> = {}): PendingMcpFlow {
- return {
- catalog_key: "notfair-googleads",
- stored_key: "acme-notfair-googleads",
- display_name: "NotFair Google Ads",
- resource_url: "https://notfair.co/api/mcp/google_ads",
- issuer: "https://issuer.example",
- token_endpoint: "https://issuer.example/token",
- client_id: "client-abc",
- client_secret: "secret-xyz",
- code_verifier: "verifier-123",
- redirect_uri: "http://localhost:3326/callback",
- project_slug: "acme",
- return_to: "/chat",
- created_at: Date.now(),
- ...overrides,
- };
-}
-
-// Each test starts from a clean store — drain any leftovers from prior tests
-// (the store hangs off globalThis, so state survives across files).
-function drain() {
- // setPending+consumePending is the only public surface; we use a unique
- // sentinel state and then drain by reading globalThis directly to flush.
- type Slot = { store?: Map<string, unknown> };
- const slot = globalThis as unknown as Slot;
- slot.store?.clear();
-}
-
-describe("setPending / consumePending", () => {
- beforeEach(() => {
- drain();
- vi.useRealTimers();
- });
-
- afterEach(() => {
- drain();
- });
-
- it("stores a flow and returns it once on consume", () => {
- const flow = makeFlow();
- setPending("state-1", flow);
- expect(consumePending("state-1")).toEqual(flow);
- });
-
- it("a second consume returns null (pop semantics, not peek)", () => {
- setPending("state-2", makeFlow());
- consumePending("state-2");
- expect(consumePending("state-2")).toBeNull();
- });
-
- it("returns null for an unknown state", () => {
- expect(consumePending("never-set")).toBeNull();
- });
-
- it("isolates two different state keys", () => {
- const f1 = makeFlow({ project_slug: "acme" });
- const f2 = makeFlow({ project_slug: "globex" });
- setPending("s1", f1);
- setPending("s2", f2);
- expect(consumePending("s1")).toEqual(f1);
- expect(consumePending("s2")).toEqual(f2);
- });
-
- it("overwrites an existing flow when the same state is set twice", () => {
- setPending("dup", makeFlow({ project_slug: "first" }));
- setPending("dup", makeFlow({ project_slug: "second" }));
- const r = consumePending("dup");
- expect(r?.project_slug).toBe("second");
- });
-
- it("supports a flow without optional client_secret + return_to", () => {
- const minimal: PendingMcpFlow = {
- catalog_key: "notfair-googleads",
- stored_key: "acme-notfair-googleads",
- display_name: "NotFair Google Ads",
- resource_url: "https://notfair.co/api/mcp/google_ads",
- issuer: "https://issuer.example",
- token_endpoint: "https://issuer.example/token",
- client_id: "public-client",
- code_verifier: "v",
- redirect_uri: "http://localhost:3326/cb",
- project_slug: "acme",
- created_at: Date.now(),
- };
- setPending("public", minimal);
- expect(consumePending("public")).toEqual(minimal);
- });
-});
-
-describe("TTL eviction", () => {
- beforeEach(() => {
- drain();
- });
-
- afterEach(() => {
- drain();
- });
-
- it("evicts entries older than the 10-minute TTL on setPending", () => {
- // Flow created 11 minutes ago — older than TTL.
- const oldFlow = makeFlow({ created_at: Date.now() - 11 * 60 * 1000 });
- setPending("stale", oldFlow);
- // Touch via a fresh set call — eviction runs at the top of setPending too.
- setPending("fresh", makeFlow());
- expect(consumePending("stale")).toBeNull();
- expect(consumePending("fresh")).not.toBeNull();
- });
-
- it("evicts entries older than the 10-minute TTL on consumePending", () => {
- const stale = makeFlow({ created_at: Date.now() - 11 * 60 * 1000 });
- setPending("evict-me", stale);
- // consume itself should evict before the lookup.
- expect(consumePending("evict-me")).toBeNull();
- });
-
- it("keeps entries newer than TTL — exactly-9-minute-old flow survives", () => {
- const recent = makeFlow({ created_at: Date.now() - 9 * 60 * 1000 });
- setPending("recent", recent);
- expect(consumePending("recent")).toEqual(recent);
- });
-});
diff --git a/notfair-cmo/src/server/mcp-server/browser-tools.test.ts b/notfair-cmo/src/server/mcp-server/browser-tools.test.ts
deleted file mode 100644
index 7f90ba54..00000000
--- a/notfair-cmo/src/server/mcp-server/browser-tools.test.ts
+++ /dev/null
@@ -1,390 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-// We mock the browser modules wholesale — these tests verify schema
-// parsing, error envelopes, and that the right action functions get
-// invoked with the right arguments. Real Page / Browser behavior is
-// covered by actions.test.ts and the E2E smoke test.
-
-vi.mock("@/server/browser/session", () => ({
- getOrLaunchBrowser: vi.fn(async () => ({ projectSlug: "acme" })),
- getSessionStatus: vi.fn(() => ({
- projectSlug: "acme",
- running: true,
- cdpPort: 19042,
- userDataDir: "/tmp/profile",
- launchedAt: 1_000,
- uptimeMs: 5_000,
- })),
-}));
-
-vi.mock("@/server/browser/tabs", () => ({
- openTab: vi.fn(async (_slug: string, opts: { label?: string; url?: string }) => ({
- id: opts.label ?? "t1",
- label: opts.label ?? "t1",
- url: opts.url ?? "about:blank",
- title: "",
- })),
- listTabs: vi.fn(async () => [
- { id: "greg", label: "greg", url: "https://example.com", title: "Example" },
- ]),
- closeTab: vi.fn(async (_slug: string, ref: string) => ref === "greg"),
- getTab: vi.fn(async (_slug: string, ref: string) =>
- ref === "greg" ? ({ __fakePage: true } as unknown as null) : null,
- ),
-}));
-
-vi.mock("@/server/browser/actions", () => ({
- navigate: vi.fn(async () => ({ url: "https://example.com", title: "Example" })),
- snapshot: vi.fn(async () => ({
- url: "https://example.com",
- title: "Example",
- elements: [
- { ref: "e1", role: "button", name: "Sign in" },
- { ref: "e2", role: "input", name: "Email", value: "" },
- ],
- text: "Sign in to your account",
- })),
- click: vi.fn(async () => {}),
- type: vi.fn(async () => {}),
- press: vi.fn(async () => {}),
- scroll: vi.fn(async () => {}),
- back: vi.fn(async () => {}),
-}));
-
-import { BROWSER_TOOLS } from "./browser-tools";
-import * as session from "@/server/browser/session";
-import * as tabs from "@/server/browser/tabs";
-import * as actions from "@/server/browser/actions";
-
-function tool(name: string) {
- const found = BROWSER_TOOLS.find((t) => t.name === name);
- if (!found) throw new Error(`No tool named ${name}`);
- return found;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- vi.clearAllMocks();
-});
-
-// ── Registry shape ─────────────────────────────────────────────────────
-
-describe("BROWSER_TOOLS registry", () => {
- it("exposes exactly the 11 expected tools (no shutdown — that's intentionally user-only)", () => {
- expect(BROWSER_TOOLS.map((t) => t.name).sort()).toEqual(
- [
- "browser_back",
- "browser_click",
- "browser_close",
- "browser_navigate",
- "browser_open",
- "browser_press",
- "browser_scroll",
- "browser_snapshot",
- "browser_status",
- "browser_tabs",
- "browser_type",
- ].sort(),
- );
- });
-
- it("does NOT expose browser_shutdown to agents (multi-agent safety: any agent calling it would kill Chrome for the others)", () => {
- const names = BROWSER_TOOLS.map((t) => t.name);
- expect(names).not.toContain("browser_shutdown");
- });
-
- it("each tool ships a non-empty description and a zod inputSchema", () => {
- for (const t of BROWSER_TOOLS) {
- expect(t.description.length).toBeGreaterThan(20);
- expect(typeof t.inputSchema.safeParse).toBe("function");
- }
- });
-
- it("browser_open description does tool routing (claims the 'launch browser' intent and warns off competitors)", () => {
- // Regression guard: real failure observed where the bundled
- // OpenAI browser-use plugin / `open -a "Google Chrome"` shell won
- // the intent. Descriptions are the first thing the model reads
- // when picking a tool, so they have to fight for it explicitly.
- const open = BROWSER_TOOLS.find((t) => t.name === "browser_open");
- expect(open).toBeDefined();
- expect(open!.description).toMatch(/launch the browser|open a page/i);
- expect(open!.description).toMatch(/browser-use|open -a|AppleScript/i);
- expect(open!.description).toMatch(/persistent profile|workspace browser/i);
- });
-
- it("every navigation/discovery tool description mentions the workspace profile so agents don't pick a different browser", () => {
- const guarded = ["browser_status", "browser_tabs", "browser_open", "browser_navigate"];
- for (const name of guarded) {
- const t = BROWSER_TOOLS.find((x) => x.name === name)!;
- expect(t.description).toMatch(/workspace browser|notfair-cmo workspace/i);
- }
- });
-
- it("interaction tool descriptions teach stale-ref recovery", () => {
- const snapshot = BROWSER_TOOLS.find((t) => t.name === "browser_snapshot")!;
- expect(snapshot.description).toMatch(/[Ss]tale/);
- expect(snapshot.description).toMatch(/snapshot again/i);
- });
-});
-
-// ── browser_status ─────────────────────────────────────────────────────
-
-describe("browser_status", () => {
- it("returns running status from getSessionStatus", async () => {
- const result = await tool("browser_status").handler({ project_slug: "acme" }, {});
- expect(result.ok).toBe(true);
- if (result.ok) {
- const payload = JSON.parse(result.content[0]!.text);
- expect(payload.running).toBe(true);
- expect(payload.cdpPort).toBe(19042);
- }
- expect(session.getSessionStatus).toHaveBeenCalledWith("acme");
- });
-
- it("rejects missing project_slug", async () => {
- const result = await tool("browser_status").handler({}, {});
- expect(result.ok).toBe(false);
- });
-});
-
-// ── browser_tabs ───────────────────────────────────────────────────────
-
-describe("browser_tabs", () => {
- it("returns the tab list from listTabs", async () => {
- const result = await tool("browser_tabs").handler({ project_slug: "acme" }, {});
- expect(result.ok).toBe(true);
- if (result.ok) {
- const payload = JSON.parse(result.content[0]!.text);
- expect(payload).toHaveLength(1);
- expect(payload[0].id).toBe("greg");
- }
- expect(tabs.listTabs).toHaveBeenCalledWith("acme");
- });
-});
-
-// ── browser_open ───────────────────────────────────────────────────────
-
-describe("browser_open", () => {
- it("launches the session and forwards label + url", async () => {
- const result = await tool("browser_open").handler(
- { project_slug: "acme", label: "greg", url: "https://example.com" },
- {},
- );
- expect(result.ok).toBe(true);
- expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("acme");
- expect(tabs.openTab).toHaveBeenCalledWith("acme", {
- label: "greg",
- url: "https://example.com",
- });
- });
-
- it("rejects invalid url", async () => {
- const result = await tool("browser_open").handler(
- { project_slug: "acme", url: "not a url" },
- {},
- );
- expect(result.ok).toBe(false);
- });
-
- it("rejects invalid label format", async () => {
- const result = await tool("browser_open").handler(
- { project_slug: "acme", label: "bad label", url: "https://example.com" },
- {},
- );
- expect(result.ok).toBe(false);
- });
-});
-
-// ── browser_close ──────────────────────────────────────────────────────
-
-describe("browser_close", () => {
- it("reports success when closeTab returns true", async () => {
- const result = await tool("browser_close").handler(
- { project_slug: "acme", target_id: "greg" },
- {},
- );
- expect(result.ok).toBe(true);
- if (result.ok) {
- expect(result.content[0]!.text).toMatch(/Closed tab/);
- }
- });
-
- it("reports no-op when closeTab returns false", async () => {
- const result = await tool("browser_close").handler(
- { project_slug: "acme", target_id: "missing" },
- {},
- );
- expect(result.ok).toBe(true);
- if (result.ok) {
- expect(result.content[0]!.text).toMatch(/No tab/);
- }
- });
-});
-
-// ── browser_navigate ───────────────────────────────────────────────────
-
-describe("browser_navigate", () => {
- it("invokes actions.navigate on the resolved tab", async () => {
- const result = await tool("browser_navigate").handler(
- { project_slug: "acme", target_id: "greg", url: "https://example.com" },
- {},
- );
- expect(result.ok).toBe(true);
- expect(actions.navigate).toHaveBeenCalledOnce();
- expect((actions.navigate as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
- url: "https://example.com",
- });
- });
-
- it("returns a clear error when the tab handle is unknown", async () => {
- const result = await tool("browser_navigate").handler(
- { project_slug: "acme", target_id: "ghost", url: "https://example.com" },
- {},
- );
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.error).toMatch(/No tab "ghost"/);
- });
-});
-
-// ── browser_snapshot ───────────────────────────────────────────────────
-
-describe("browser_snapshot", () => {
- it("returns the snapshot payload as JSON", async () => {
- const result = await tool("browser_snapshot").handler(
- { project_slug: "acme", target_id: "greg" },
- {},
- );
- expect(result.ok).toBe(true);
- if (result.ok) {
- const payload = JSON.parse(result.content[0]!.text);
- expect(payload.elements).toHaveLength(2);
- expect(payload.elements[0].ref).toBe("e1");
- }
- });
-
- it("respects max_elements truncation", async () => {
- const result = await tool("browser_snapshot").handler(
- { project_slug: "acme", target_id: "greg", max_elements: 1 },
- {},
- );
- expect(result.ok).toBe(true);
- if (result.ok) {
- const payload = JSON.parse(result.content[0]!.text);
- expect(payload.elements).toHaveLength(1);
- }
- });
-});
-
-// ── browser_click ──────────────────────────────────────────────────────
-
-describe("browser_click", () => {
- it("forwards ref + button + modifiers to actions.click", async () => {
- const result = await tool("browser_click").handler(
- {
- project_slug: "acme",
- target_id: "greg",
- ref: "e2",
- button: "right",
- modifiers: ["Meta"],
- double_click: true,
- },
- {},
- );
- expect(result.ok).toBe(true);
- expect((actions.click as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
- ref: "e2",
- button: "right",
- modifiers: ["Meta"],
- doubleClick: true,
- });
- });
-
- it("rejects refs that don't match e<number>", async () => {
- const result = await tool("browser_click").handler(
- { project_slug: "acme", target_id: "greg", ref: "weird" },
- {},
- );
- expect(result.ok).toBe(false);
- });
-});
-
-// ── browser_type ───────────────────────────────────────────────────────
-
-describe("browser_type", () => {
- it("forwards text + submit + clear_first", async () => {
- const result = await tool("browser_type").handler(
- {
- project_slug: "acme",
- target_id: "greg",
- ref: "e2",
- text: "hello",
- submit: true,
- clear_first: false,
- },
- {},
- );
- expect(result.ok).toBe(true);
- expect((actions.type as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
- ref: "e2",
- text: "hello",
- submit: true,
- clearFirst: false,
- });
- });
-});
-
-// ── browser_press ──────────────────────────────────────────────────────
-
-describe("browser_press", () => {
- it("forwards key + optional ref", async () => {
- const result = await tool("browser_press").handler(
- { project_slug: "acme", target_id: "greg", key: "Tab", ref: "e1" },
- {},
- );
- expect(result.ok).toBe(true);
- expect((actions.press as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
- key: "Tab",
- ref: "e1",
- });
- });
-});
-
-// ── browser_scroll ─────────────────────────────────────────────────────
-
-describe("browser_scroll", () => {
- it("forwards direction + amount", async () => {
- const result = await tool("browser_scroll").handler(
- { project_slug: "acme", target_id: "greg", direction: "down", amount: 1000 },
- {},
- );
- expect(result.ok).toBe(true);
- expect((actions.scroll as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toMatchObject({
- direction: "down",
- amount: 1000,
- });
- });
-
- it("rejects invalid direction", async () => {
- const result = await tool("browser_scroll").handler(
- { project_slug: "acme", target_id: "greg", direction: "diagonal" },
- {},
- );
- expect(result.ok).toBe(false);
- });
-});
-
-// ── browser_back ───────────────────────────────────────────────────────
-
-describe("browser_back", () => {
- it("invokes actions.back", async () => {
- const result = await tool("browser_back").handler(
- { project_slug: "acme", target_id: "greg" },
- {},
- );
- expect(result.ok).toBe(true);
- expect(actions.back).toHaveBeenCalledOnce();
- });
-});
diff --git a/notfair-cmo/src/server/mcp-server/jsonrpc.browser.test.ts b/notfair-cmo/src/server/mcp-server/jsonrpc.browser.test.ts
deleted file mode 100644
index ee96f07f..00000000
--- a/notfair-cmo/src/server/mcp-server/jsonrpc.browser.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-// The browser MCP server hits the live browser/session modules, so mock
-// them out — these tests only verify wiring (right server name, right
-// tools, isolation from orchestration).
-vi.mock("@/server/browser/session", () => ({
- getOrLaunchBrowser: vi.fn(async () => ({ projectSlug: "acme" })),
- getSessionStatus: vi.fn(() => ({
- projectSlug: "acme",
- running: false,
- cdpPort: 19042,
- userDataDir: "/tmp/profile",
- idleTimeoutMs: 300_000,
- })),
-}));
-
-vi.mock("@/server/browser/tabs", () => ({
- openTab: vi.fn(async () => ({ id: "t1", label: "t1", url: "about:blank", title: "" })),
- listTabs: vi.fn(async () => []),
- closeTab: vi.fn(async () => false),
- getTab: vi.fn(async () => null),
-}));
-
-vi.mock("@/server/browser/actions", () => ({
- navigate: vi.fn(),
- snapshot: vi.fn(),
- click: vi.fn(),
- type: vi.fn(),
- press: vi.fn(),
- scroll: vi.fn(),
- back: vi.fn(),
-}));
-
-import { BROWSER_TOOLS } from "./browser-tools";
-import { handleJsonRpc } from "./jsonrpc";
-import { TOOLS as ORCHESTRATION_TOOLS } from "./tools";
-
-const BROWSER_SERVER = {
- name: "notfair-browser",
- version: "0.1.0",
- tools: BROWSER_TOOLS,
-};
-
-beforeEach(() => vi.clearAllMocks());
-afterEach(() => vi.clearAllMocks());
-
-describe("notfair-browser MCP server", () => {
- it("identifies itself as notfair-browser on initialize", async () => {
- const r = await handleJsonRpc(
- { jsonrpc: "2.0", id: 1, method: "initialize" },
- BROWSER_SERVER,
- );
- const result = (r as { result: { serverInfo: { name: string } } }).result;
- expect(result.serverInfo.name).toBe("notfair-browser");
- });
-
- it("tools/list returns only browser_* tools", async () => {
- const r = await handleJsonRpc(
- { jsonrpc: "2.0", id: 1, method: "tools/list" },
- BROWSER_SERVER,
- );
- const tools = (r as { result: { tools: Array<{ name: string }> } }).result.tools;
- const names = tools.map((t) => t.name).sort();
- expect(names.length).toBeGreaterThan(0);
- expect(names.every((n) => n.startsWith("browser_"))).toBe(true);
- });
-
- it("orchestration registry does NOT contain browser_* tools (the split is real)", () => {
- const orchestrationNames = ORCHESTRATION_TOOLS.map((t) => t.name);
- expect(orchestrationNames.some((n) => n.startsWith("browser_"))).toBe(false);
- });
-
- it("browser registry does NOT contain orchestration tools (isolated surfaces)", () => {
- const browserNames = BROWSER_TOOLS.map((t) => t.name);
- expect(browserNames).not.toContain("submit_task_status");
- expect(browserNames).not.toContain("create_task");
- expect(browserNames).not.toContain("request_approval");
- });
-
- it("tools/call rejects orchestration tool names on the browser server", async () => {
- const r = await handleJsonRpc(
- {
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: { name: "submit_task_status", arguments: {} },
- },
- BROWSER_SERVER,
- );
- const err = (r as { error?: { code: number; message: string } }).error;
- expect(err?.code).toBe(-32601);
- expect(err?.message).toMatch(/Unknown tool/);
- });
-
- it("tools/call accepts a browser_* tool name", async () => {
- const r = await handleJsonRpc(
- {
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: { name: "browser_status", arguments: { project_slug: "acme" } },
- },
- BROWSER_SERVER,
- );
- const result = (r as { result: { isError?: boolean } }).result;
- expect(result.isError).toBe(false);
- });
-});
diff --git a/notfair-cmo/src/server/mcp-server/jsonrpc.test.ts b/notfair-cmo/src/server/mcp-server/jsonrpc.test.ts
deleted file mode 100644
index 0c878c0a..00000000
--- a/notfair-cmo/src/server/mcp-server/jsonrpc.test.ts
+++ /dev/null
@@ -1,352 +0,0 @@
-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();
-vi.mock("@/server/db/agent-actions", () => ({
- logAgentAction: (...a: unknown[]) => logAgentActionMock(...a),
-}));
-
-import { handleJsonRpc, type JsonRpcRequest } from "./jsonrpc";
-import { TOOLS } from "./tools";
-
-const ORCHESTRATION_SERVER = {
- name: "notfair-orchestration",
- version: "0.2.0",
- tools: TOOLS,
-};
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-function call(req: JsonRpcRequest) {
- return handleJsonRpc(req, ORCHESTRATION_SERVER);
-}
-
-describe("handleJsonRpc — initialize", () => {
- it("returns protocolVersion + serverInfo + tools capability", async () => {
- const r = await call({ jsonrpc: "2.0", id: 1, method: "initialize" });
- expect(r).not.toBeNull();
- if (!r || "error" in r) throw new Error("expected ok result");
- const result = r.result as {
- protocolVersion: string;
- serverInfo: { name: string };
- capabilities: { tools: object };
- };
- expect(result.protocolVersion).toMatch(/^\d{4}-\d{2}-\d{2}$/);
- expect(result.serverInfo.name).toBe("notfair-orchestration");
- expect(result.capabilities.tools).toEqual({});
- });
-
- it("notifications (id null) return null with no response body", async () => {
- const r = await call({
- jsonrpc: "2.0",
- id: null,
- method: "notifications/initialized",
- });
- expect(r).toBeNull();
- });
-});
-
-describe("handleJsonRpc — tools/list", () => {
- it("includes submit_task_status with the right enum + required fields", async () => {
- const r = await call({ jsonrpc: "2.0", id: 1, method: "tools/list" });
- if (!r || "error" in r) throw new Error("expected ok result");
- const { tools } = r.result as {
- tools: Array<{
- name: string;
- description: string;
- inputSchema: {
- properties: Record<string, { type: string; enum?: string[] }>;
- required: string[];
- };
- }>;
- };
- const submit = tools.find((t) => t.name === "submit_task_status")!;
- expect(submit).toBeDefined();
- expect(submit.inputSchema.properties.task_id.type).toBe("string");
- expect(submit.inputSchema.properties.status.enum).toEqual([
- "working",
- "done",
- "blocked",
- "failed",
- ]);
- // summary is optional → not in required
- expect(submit.inputSchema.required).toEqual(
- expect.arrayContaining(["task_id", "status"]),
- );
- expect(submit.inputSchema.required).not.toContain("summary");
- });
-});
-
-describe("handleJsonRpc — tools/call submit_task_status", () => {
- it("rejects an invalid status value with isError content (no JSON-RPC error)", async () => {
- const r = await call({
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: {
- name: "submit_task_status",
- arguments: {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- task_id: "t1",
- status: "closed",
- },
- },
- });
- if (!r || "error" in r) throw new Error("expected ok envelope");
- const result = r.result as {
- isError: boolean;
- content: Array<{ type: string; text: string }>;
- };
- expect(result.isError).toBe(true);
- expect(result.content[0]!.text).toMatch(/Invalid arguments/);
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("updates the task and logs an action on valid `done` status", async () => {
- getTaskMock.mockReturnValue({
- id: "t-uuid",
- display_id: "demo-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- status: "working",
- });
- const r = await call({
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: {
- name: "submit_task_status",
- arguments: {
- project_slug: "demo",
- agent_id: "demo-google-ads",
- task_id: "demo-1",
- status: "done",
- summary: "shipped the change",
- },
- },
- });
- if (!r || "error" in r) throw new Error("expected ok envelope");
- const result = r.result as { isError: boolean };
- expect(result.isError).toBe(false);
- expect(updateTaskMock).toHaveBeenCalledWith(
- "t-uuid",
- expect.objectContaining({
- status: "done",
- result: { summary: "shipped the change" },
- }),
- );
- expect(logAgentActionMock).toHaveBeenCalledWith(
- expect.objectContaining({
- action_type: "task_done",
- task_id: "t-uuid",
- }),
- );
- });
-
- it("maps status=blocked to TaskStatus blocked (not running)", async () => {
- getTaskMock.mockReturnValue({
- id: "t1",
- display_id: "x-1",
- project_slug: "x",
- agent_id: "x-agent",
- status: "working",
- });
- await call({
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: {
- name: "submit_task_status",
- arguments: {
- project_slug: "x",
- agent_id: "x-agent",
- task_id: "t1",
- status: "blocked",
- },
- },
- });
- expect(updateTaskMock).toHaveBeenCalledWith(
- "t1",
- expect.objectContaining({ status: "blocked" }),
- );
- });
-
- it("maps status=failed and stores summary in error_message", async () => {
- getTaskMock.mockReturnValue({
- id: "t1",
- display_id: "x-1",
- project_slug: "x",
- agent_id: "x-agent",
- status: "working",
- });
- await call({
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: {
- name: "submit_task_status",
- arguments: {
- project_slug: "x",
- agent_id: "x-agent",
- task_id: "t1",
- status: "failed",
- summary: "MCP returned 401",
- },
- },
- });
- expect(updateTaskMock).toHaveBeenCalledWith(
- "t1",
- expect.objectContaining({
- status: "failed",
- error_message: "MCP returned 401",
- }),
- );
- });
-
- it("returns isError when task_id is unknown", async () => {
- getTaskMock.mockReturnValue(null);
- const r = await call({
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: {
- name: "submit_task_status",
- arguments: {
- project_slug: "x",
- agent_id: "x-agent",
- task_id: "missing",
- status: "done",
- summary: "x",
- },
- },
- });
- if (!r || "error" in r) throw new Error("expected ok envelope");
- const result = r.result as { isError: boolean; content: { text: string }[] };
- expect(result.isError).toBe(true);
- expect(result.content[0]!.text).toMatch(/Unknown task_id/);
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("returns isError when project_slug doesn't match the task's (cross-project guard)", async () => {
- getTaskMock.mockReturnValue({
- id: "t1",
- display_id: "x-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- status: "working",
- });
- const r = await call({
- jsonrpc: "2.0",
- id: 99,
- method: "tools/call",
- params: {
- name: "submit_task_status",
- arguments: {
- project_slug: "evil-other",
- agent_id: "demo-google-ads",
- task_id: "t1",
- status: "done",
- summary: "x",
- },
- },
- });
- if (!r || "error" in r) throw new Error("expected ok envelope");
- const result = r.result as { isError: boolean; content: { text: string }[] };
- expect(result.isError).toBe(true);
- expect(result.content[0]!.text).toMatch(/Cross-project/);
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("refuses updates to terminal tasks with an instructive error", async () => {
- getTaskMock.mockReturnValue({
- id: "t1",
- display_id: "x-1",
- project_slug: "x",
- agent_id: "x-agent",
- status: "done",
- });
- const r = await call({
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: {
- name: "submit_task_status",
- arguments: {
- project_slug: "x",
- agent_id: "x-agent",
- task_id: "t1",
- status: "done",
- },
- },
- });
- if (!r || "error" in r) throw new Error("expected ok envelope");
- const result = r.result as {
- isError: boolean;
- content: Array<{ text: string }>;
- };
- // Used to be a silent ok:true no-op — the agent would "restart" a
- // cancelled task and narrate success the DB never recorded. Now the
- // tool result is an error that names the terminal status and points
- // the agent at create_task.
- expect(result.isError).toBe(true);
- expect(result.content[0]!.text).toContain("done");
- expect(result.content[0]!.text).toContain("create_task");
- // Terminal status is preserved — no DB write happens.
- expect(updateTaskMock).not.toHaveBeenCalled();
- });
-
- it("returns Method-not-found for unknown tools", async () => {
- const r = await call({
- jsonrpc: "2.0",
- id: 1,
- method: "tools/call",
- params: { name: "wat", arguments: {} },
- });
- if (!r || "error" in r) {
- expect(r?.error?.code).toBe(-32601);
- return;
- }
- throw new Error("expected error envelope");
- });
-
- it("returns Method-not-found for unknown methods", async () => {
- const r = await call({
- jsonrpc: "2.0",
- id: 1,
- method: "wat/nope",
- });
- if (!r || "error" in r) {
- expect(r?.error?.code).toBe(-32601);
- return;
- }
- throw new Error("expected error envelope");
- });
-});
diff --git a/notfair-cmo/src/server/mcp-server/schedule-tool.test.ts b/notfair-cmo/src/server/mcp-server/schedule-tool.test.ts
deleted file mode 100644
index 35f321d8..00000000
--- a/notfair-cmo/src/server/mcp-server/schedule-tool.test.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { randomUUID } from "node:crypto";
-
-let dataDir: string;
-beforeEach(() => {
- dataDir = mkdtempSync(join(tmpdir(), "notfair-schedule-tool-"));
- process.env.NOTFAIR_CMO_DATA_DIR = dataDir;
- // Force a fresh DB connection for each test so projects.slug uniqueness
- // doesn't carry across.
- vi.resetModules();
-});
-
-afterEach(() => {
- rmSync(dataDir, { recursive: true, force: true });
- delete process.env.NOTFAIR_CMO_DATA_DIR;
-});
-
-async function seedProjectAndAgent(slug: string, agentId: string) {
- const { getDb } = await import("@/server/db/db");
- const db = getDb();
- db.prepare(
- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'claude-code-local')",
- ).run(randomUUID(), slug, slug, new Date().toISOString());
-
- // listProjectAgents reads from notfair-meta.json sidecars; the simplest
- // way to make it return the agent is to write the sidecar.
- const { writeAgentMeta } = await import("@/server/agent-meta");
- await writeAgentMeta({
- agent_id: agentId,
- project_slug: slug,
- name: "Ana",
- template_key: "google_ads",
- created_at: new Date().toISOString(),
- });
-}
-
-describe("schedule_recurring_work MCP tool", () => {
- it("creates a scheduled_jobs row visible in the cron view", async () => {
- await seedProjectAndAgent("demo1", "demo1-google-ads-ana");
- const { findTool } = await import("./tools");
- const tool = findTool("schedule_recurring_work");
- expect(tool).toBeDefined();
-
- const result = await tool!.handler({
- project_slug: "demo1",
- agent_id: "demo1-google-ads-ana",
- name: "daily-anomaly-check",
- cron_expr: "0 16 * * *",
- message: "Run the daily anomaly check and report any spikes.",
- });
- expect(result.ok).toBe(true);
- if (!result.ok) return;
-
- // Verify a row landed in scheduled_jobs.
- const { listProjectScheduledJobs } = await import("@/server/scheduler");
- const jobs = listProjectScheduledJobs("demo1");
- expect(jobs).toHaveLength(1);
- expect(jobs[0]).toMatchObject({
- project_slug: "demo1",
- agent_id: "demo1-google-ads-ana",
- name: "daily-anomaly-check",
- cron_expr: "0 16 * * *",
- enabled: 1,
- });
- expect(jobs[0].next_run_at).toBeTruthy();
- });
-
- it("rejects invalid cron expressions", async () => {
- await seedProjectAndAgent("demo1", "demo1-google-ads-ana");
- const { findTool } = await import("./tools");
- const tool = findTool("schedule_recurring_work")!;
- const result = await tool.handler({
- project_slug: "demo1",
- agent_id: "demo1-google-ads-ana",
- name: "bad",
- cron_expr: "not a cron",
- message: "...",
- });
- expect(result.ok).toBe(false);
- if (!result.ok) {
- expect(result.error).toMatch(/Invalid cron_expr/);
- }
- });
-
- it("rejects an agent that doesn't belong to the project", async () => {
- await seedProjectAndAgent("demo1", "demo1-google-ads-ana");
- const { findTool } = await import("./tools");
- const tool = findTool("schedule_recurring_work")!;
- const result = await tool.handler({
- project_slug: "demo1",
- agent_id: "other-project-agent",
- name: "x",
- cron_expr: "0 9 * * *",
- message: "x",
- });
- expect(result.ok).toBe(false);
- if (!result.ok) {
- expect(result.error).toMatch(/not part of project/);
- }
- });
-
- it("rejects bad name shapes (must be kebab-case lowercase)", async () => {
- await seedProjectAndAgent("demo1", "demo1-google-ads-ana");
- const { findTool } = await import("./tools");
- const tool = findTool("schedule_recurring_work")!;
- const result = await tool.handler({
- project_slug: "demo1",
- agent_id: "demo1-google-ads-ana",
- name: "Bad Name With Spaces",
- cron_expr: "0 9 * * *",
- message: "x",
- });
- expect(result.ok).toBe(false);
- });
-
- it("rejects duplicate (project, agent, name)", async () => {
- await seedProjectAndAgent("demo1", "demo1-google-ads-ana");
- const { findTool } = await import("./tools");
- const tool = findTool("schedule_recurring_work")!;
- const args = {
- project_slug: "demo1",
- agent_id: "demo1-google-ads-ana",
- name: "weekly-review",
- cron_expr: "0 16 * * 1",
- message: "Run the review.",
- };
- const first = await tool.handler(args);
- expect(first.ok).toBe(true);
- const second = await tool.handler(args);
- expect(second.ok).toBe(false);
- if (!second.ok) {
- expect(second.error).toMatch(/already exists/);
- }
- });
-});
diff --git a/notfair-cmo/src/server/mcp-server/secret.test.ts b/notfair-cmo/src/server/mcp-server/secret.test.ts
deleted file mode 100644
index d84fddaf..00000000
--- a/notfair-cmo/src/server/mcp-server/secret.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { mkdtempSync, rmSync, existsSync, statSync, readFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-type SecretModule = typeof import("./secret");
-
-async function loadSecret(): Promise<SecretModule> {
- return (await import("./secret")) as SecretModule;
-}
-
-let tmpDir: string;
-
-beforeEach(() => {
- vi.resetModules();
- tmpDir = mkdtempSync(join(tmpdir(), "notfair-cmo-secret-"));
- process.env.NOTFAIR_CMO_DATA_DIR = tmpDir;
-});
-
-afterEach(() => {
- delete process.env.NOTFAIR_CMO_DATA_DIR;
- if (tmpDir && existsSync(tmpDir)) rmSync(tmpDir, { recursive: true, force: true });
-});
-
-describe("getOrCreateMcpServerSecret", () => {
- it("mints + persists a 64-char hex secret on first call", async () => {
- const { getOrCreateMcpServerSecret, getMcpServerSecretPath } = await loadSecret();
- const s = getOrCreateMcpServerSecret();
- expect(s).toMatch(/^[0-9a-f]{64}$/);
- expect(existsSync(getMcpServerSecretPath())).toBe(true);
- const onDisk = readFileSync(getMcpServerSecretPath(), "utf8").trim();
- expect(onDisk).toBe(s);
- });
-
- it("returns the same secret on subsequent calls (in-process and after reload)", async () => {
- const { getOrCreateMcpServerSecret } = await loadSecret();
- const first = getOrCreateMcpServerSecret();
- const second = getOrCreateMcpServerSecret();
- expect(second).toBe(first);
- // Simulate process restart by re-importing.
- vi.resetModules();
- const reloaded = await loadSecret();
- expect(reloaded.getOrCreateMcpServerSecret()).toBe(first);
- });
-
- it("writes the secret file with 0600 perms (POSIX only)", async () => {
- if (process.platform === "win32") return;
- const { getOrCreateMcpServerSecret, getMcpServerSecretPath } = await loadSecret();
- getOrCreateMcpServerSecret();
- const mode = statSync(getMcpServerSecretPath()).mode & 0o777;
- expect(mode).toBe(0o600);
- });
-});
-
-describe("verifyMcpServerSecret", () => {
- it("returns true for the stored secret", async () => {
- const { getOrCreateMcpServerSecret, verifyMcpServerSecret } = await loadSecret();
- const s = getOrCreateMcpServerSecret();
- expect(verifyMcpServerSecret(s)).toBe(true);
- });
-
- it("returns false for a wrong-but-same-length value", async () => {
- const { getOrCreateMcpServerSecret, verifyMcpServerSecret } = await loadSecret();
- const s = getOrCreateMcpServerSecret();
- const wrong = "0".repeat(s.length);
- expect(verifyMcpServerSecret(wrong)).toBe(false);
- });
-
- it("returns false for mismatched length (avoids timingSafeEqual throw)", async () => {
- const { verifyMcpServerSecret } = await loadSecret();
- expect(verifyMcpServerSecret("short")).toBe(false);
- });
-
- it("returns false for null/undefined/empty", async () => {
- const { verifyMcpServerSecret } = await loadSecret();
- expect(verifyMcpServerSecret(null)).toBe(false);
- expect(verifyMcpServerSecret(undefined)).toBe(false);
- expect(verifyMcpServerSecret("")).toBe(false);
- });
-});
diff --git a/notfair-cmo/src/server/mcp-server/tools.ts b/notfair-cmo/src/server/mcp-server/tools.ts
deleted file mode 100644
index 61876ed5..00000000
--- a/notfair-cmo/src/server/mcp-server/tools.ts
+++ /dev/null
@@ -1,920 +0,0 @@
-import { z } from "zod";
-
-import {
- APPROVAL_ACTION_TYPE_VALUES,
- handleAddTaskComment,
- handleAskUser,
- handleCancelTask,
- handleCreateTask,
- handleGetApproval,
- handleGetProject,
- handleGetTask,
- handleListApprovalActionTypes,
- handleListApprovalsForTask,
- handleListMyApprovals,
- handleListMyTasks,
- handleListPendingApprovals,
- handleListProjectAgents,
- handleListTaskComments,
- handleListTaskStatuses,
- handleListTasks,
- handleRequestApproval,
- handleSetProjectBrief,
- handleTaskStatus,
- handleUpdateTask,
- TASK_STATUS_VALUES,
-} from "@/server/orchestration/handlers";
-import type { TaskStatus } from "@/types";
-
-/**
- * Tool definitions exposed by notfair-cmo's MCP server to OpenClaw-side
- * agents. The MCP server is **globally installed** (one OpenClaw row,
- * shared across every project), so every tool takes a required
- * `project_slug` argument the caller MUST fill in. We never derive
- * project from the bearer because every project's agents use the same
- * bearer — that's the whole point of "globally shared." The agent learns
- * its `project_slug` + `agent_id` from its IDENTITY.md prompt header and
- * from the task kickoff message.
- *
- * Schema enforcement (zod) prevents the kind of drift that stranded
- * `superpublic-test-1`: an agent emitting `status: closed` instead of a
- * valid enum. The provider rejects invalid values before the model emits
- * them; we double-check server-side so a misbehaving runtime can't slip
- * past.
- */
-
-// ── Shared scaffolding ─────────────────────────────────────────────────
-
-export type ToolHandlerContext = {
- /** Reserved for future per-agent bearer scoping. Unused today. */
- agentId?: string;
-};
-
-export type ToolResult =
- | { ok: true; content: { type: "text"; text: string }[] }
- | { ok: false; error: string };
-
-export type ToolDefinition = {
- name: string;
- description: string;
- inputSchema: z.ZodObject<z.ZodRawShape>;
- handler: (input: unknown, ctx: ToolHandlerContext) => Promise<ToolResult>;
-};
-
-function invalid(err: z.ZodError): ToolResult {
- return {
- ok: false,
- error: `Invalid arguments: ${err.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`,
- };
-}
-
-function txt(text: string): ToolResult {
- return { ok: true, content: [{ type: "text", text }] };
-}
-
-// ── Tool: submit_task_status ───────────────────────────────────────────
-
-const submitTaskStatusInput = z.object({
- project_slug: z
- .string()
- .min(1)
- .describe(
- "The project this task belongs to. From your IDENTITY.md prompt header / kickoff message.",
- ),
- agent_id: z
- .string()
- .min(1)
- .describe(
- "Your agent_id (e.g. `superpublic-google-ads`). From IDENTITY.md. Used to enforce 'only the assignee can update'.",
- ),
- task_id: z
- .string()
- .min(1)
- .describe("UUID or display_id of the task you were assigned."),
- status: z
- .enum(TASK_STATUS_VALUES)
- .describe(
- "working = still progressing, done = task complete, blocked = waiting on user/CMO/approval, failed = couldn't complete.",
- ),
- summary: z
- .string()
- .optional()
- .describe(
- "One-paragraph progress note. Required when status is 'done' or 'failed'.",
- ),
-});
-
-async function handleSubmitTaskStatus(input: unknown): Promise<ToolResult> {
- const parsed = submitTaskStatusInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, task_id, status, summary } = parsed.data;
- const r = handleTaskStatus(
- { task_id, status, summary },
- { project_slug, agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(`task ${r.data.task_id} updated to ${r.data.status}.`);
-}
-
-// ── Tool: create_task ──────────────────────────────────────────────────
-
-const createTaskInput = z.object({
- project_slug: z
- .string()
- .min(1)
- .describe("The project you are operating in. From your IDENTITY.md."),
- assigner_agent_id: z
- .string()
- .min(1)
- .describe(
- "Your own agent_id — the one creating the task (e.g. `demo-cmo`). From IDENTITY.md.",
- ),
- assignee: z
- .string()
- .min(1)
- .describe(
- "Template key of the assignee (e.g. `google_ads`, `seo`). Must be a specialist provisioned in this project; CMO can't assign to itself.",
- ),
- title: z
- .string()
- .min(1)
- .describe("Short label shown on task cards."),
- brief: z
- .string()
- .min(1)
- .describe(
- "Full request body. PRD-style description with context, target outcome, constraints.",
- ),
- success_criteria: z
- .string()
- .optional()
- .describe("Measurable definition of done."),
-});
-
-async function handleCreateTaskTool(input: unknown): Promise<ToolResult> {
- const parsed = createTaskInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, assigner_agent_id, assignee, title, brief, success_criteria } = parsed.data;
- const r = await handleCreateTask(
- { assignee, title, brief, success_criteria },
- { project_slug, agent_id: assigner_agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(
- `task ${r.data.display_id} ("${r.data.title}") created for ${r.data.agent_id}. Status: ${r.data.status}.`,
- );
-}
-
-// ── Tool: request_approval ─────────────────────────────────────────────
-
-const requestApprovalInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- agent_id: z.string().min(1).describe("Your own agent_id."),
- task_id: z
- .string()
- .optional()
- .describe(
- "Task this approval is gating, if any. Setting this parks the task in `blocked` until resolved.",
- ),
- action_summary: z
- .string()
- .min(1)
- .describe("One-line description of what you want to do."),
- action_type: z
- .enum(APPROVAL_ACTION_TYPE_VALUES)
- .describe(
- "Category of the action. Used by auto-approval policies and to label the inbox card.",
- ),
- cost_estimate_usd: z
- .number()
- .optional()
- .describe(
- "Estimated monthly cost in USD. Required for spend / bid_change / new_channel.",
- ),
- reasoning: z
- .string()
- .optional()
- .describe(
- "Why you want to do this. Shown in the approval card; the more concrete the better.",
- ),
-});
-
-async function handleRequestApprovalTool(input: unknown): Promise<ToolResult> {
- const parsed = requestApprovalInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, task_id, action_summary, action_type, cost_estimate_usd, reasoning } = parsed.data;
- const r = await handleRequestApproval(
- { task_id, action_summary, action_type, cost_estimate_usd, reasoning },
- { project_slug, agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- const suffix = r.data.auto_resolved
- ? ` (auto-${r.data.status} by policy)`
- : "";
- return txt(
- `approval ${r.data.approval_id} created${suffix}. status=${r.data.status}.`,
- );
-}
-
-// ── Tool: add_task_comment ─────────────────────────────────────────────
-
-const addTaskCommentInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- agent_id: z.string().min(1).describe("Your own agent_id."),
- task_id: z.string().min(1).describe("Task you're commenting on."),
- body: z.string().min(1).describe("Comment text. Visible in /activity."),
-});
-
-async function handleAddTaskCommentTool(input: unknown): Promise<ToolResult> {
- const parsed = addTaskCommentInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, task_id, body } = parsed.data;
- const r = handleAddTaskComment(
- { task_id, body },
- { project_slug, agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(`comment added to task ${r.data.task_id}.`);
-}
-
-// ── Tool: ask_user_question ────────────────────────────────────────────
-
-const askUserInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- agent_id: z.string().min(1).describe("Your own agent_id."),
- question: z.string().min(1).describe("The question to surface to the user."),
- task_id: z
- .string()
- .optional()
- .describe("Optional — anchor the question to a task."),
- options: z
- .string()
- .optional()
- .describe("Optional comma-separated multiple-choice hints (rendered as buttons)."),
-});
-
-async function handleAskUserTool(input: unknown): Promise<ToolResult> {
- const parsed = askUserInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, question, task_id, options } = parsed.data;
- const r = handleAskUser(
- { question, task_id, options },
- { project_slug, agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- // The task is now parked in `blocked`; the agent should end its turn
- // and wait for the user's answer to be delivered via a [SYSTEM] wake-up
- // turn. Surface the question_id so the agent can correlate.
- const taskClause = r.data.task_id
- ? ` on task ${r.data.task_id}. The task is now blocked until the user answers; end your turn.`
- : ".";
- return txt(
- `question ${r.data.question_id} recorded${taskClause}`,
- );
-}
-
-// ── Tool: get_task ─────────────────────────────────────────────────────
-
-const getTaskInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- task_id: z.string().min(1).describe("UUID or display_id."),
-});
-
-async function handleGetTaskTool(input: unknown): Promise<ToolResult> {
- const parsed = getTaskInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleGetTask(
- { task_id: parsed.data.task_id },
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify(r.data));
-}
-
-// ── Tool: list_my_tasks ────────────────────────────────────────────────
-
-const TASK_STATUS_FILTER_VALUES = [
- "proposed",
- "approved",
- "working",
- "blocked",
- "done",
- "failed",
- "cancelled",
- "in_flight",
- "all",
-] as const;
-
-const listMyTasksInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- agent_id: z.string().min(1).describe("Your own agent_id."),
- status: z
- .enum(TASK_STATUS_FILTER_VALUES)
- .optional()
- .describe(
- "Filter by status. 'in_flight' (default) = proposed|approved|running|blocked; 'all' = no filter.",
- ),
-});
-
-async function handleListMyTasksTool(input: unknown): Promise<ToolResult> {
- const parsed = listMyTasksInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, status } = parsed.data;
- const filter = status as
- | TaskStatus
- | "in_flight"
- | "all"
- | undefined;
- const r = handleListMyTasks(
- { status: filter },
- { project_slug, agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ tasks: r.data, count: r.data.length }));
-}
-
-// ── Tool: list_tasks (project-wide) ────────────────────────────────────
-
-const listTasksInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- status: z
- .enum([
- "proposed",
- "approved",
- "working",
- "blocked",
- "done",
- "failed",
- "cancelled",
- ])
- .optional()
- .describe("Optional status filter."),
-});
-
-async function handleListTasksTool(input: unknown): Promise<ToolResult> {
- const parsed = listTasksInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleListTasks(
- { status: parsed.data.status as TaskStatus | undefined },
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ tasks: r.data, count: r.data.length }));
-}
-
-// ── Tool: update_task ──────────────────────────────────────────────────
-
-const updateTaskInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- agent_id: z.string().min(1).describe("Your own agent_id."),
- task_id: z.string().min(1).describe("UUID or display_id of the task to update."),
- title: z.string().optional().describe("New title."),
- brief: z.string().optional().describe("New brief / description."),
- success_criteria: z.string().optional().describe("New success criteria."),
-});
-
-async function handleUpdateTaskTool(input: unknown): Promise<ToolResult> {
- const parsed = updateTaskInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, task_id, title, brief, success_criteria } = parsed.data;
- const r = handleUpdateTask(
- { task_id, title, brief, success_criteria },
- { project_slug, agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(`task ${r.data.display_id} updated.`);
-}
-
-// ── Tool: cancel_task ──────────────────────────────────────────────────
-
-const cancelTaskInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- agent_id: z.string().min(1).describe("Your own agent_id."),
- task_id: z.string().min(1).describe("UUID or display_id of the task to cancel."),
- reason: z
- .string()
- .optional()
- .describe("Why you're cancelling. Stored on the task's error_message."),
-});
-
-async function handleCancelTaskTool(input: unknown): Promise<ToolResult> {
- const parsed = cancelTaskInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, task_id, reason } = parsed.data;
- const r = handleCancelTask(
- { task_id, reason },
- { project_slug, agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(`task ${r.data.display_id} cancelled.`);
-}
-
-// ── Tool: get_project ──────────────────────────────────────────────────
-
-const getProjectInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
-});
-
-async function handleGetProjectTool(input: unknown): Promise<ToolResult> {
- const parsed = getProjectInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleGetProject(
- {},
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify(r.data));
-}
-
-// ── Tool: list_project_agents ──────────────────────────────────────────
-
-const listProjectAgentsInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
-});
-
-async function handleListProjectAgentsTool(input: unknown): Promise<ToolResult> {
- const parsed = listProjectAgentsInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = await handleListProjectAgents(
- {},
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ agents: r.data, count: r.data.length }));
-}
-
-// ── Tool: list_task_comments ───────────────────────────────────────────
-
-const listTaskCommentsInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- task_id: z.string().min(1).describe("Task whose comment thread you want."),
- limit: z.number().optional().describe("Max comments to return (default 50)."),
-});
-
-async function handleListTaskCommentsTool(input: unknown): Promise<ToolResult> {
- const parsed = listTaskCommentsInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleListTaskComments(
- { task_id: parsed.data.task_id, limit: parsed.data.limit },
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ comments: r.data, count: r.data.length }));
-}
-
-// ── Tool: get_approval ─────────────────────────────────────────────────
-
-const getApprovalInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- approval_id: z.string().min(1).describe("Approval UUID."),
-});
-
-async function handleGetApprovalTool(input: unknown): Promise<ToolResult> {
- const parsed = getApprovalInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleGetApproval(
- { approval_id: parsed.data.approval_id },
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify(r.data));
-}
-
-// ── Tool: list_my_approvals ────────────────────────────────────────────
-
-const listMyApprovalsInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- agent_id: z.string().min(1).describe("Your own agent_id."),
-});
-
-async function handleListMyApprovalsTool(input: unknown): Promise<ToolResult> {
- const parsed = listMyApprovalsInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleListMyApprovals(
- {},
- { project_slug: parsed.data.project_slug, agent_id: parsed.data.agent_id },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ approvals: r.data, count: r.data.length }));
-}
-
-// ── Tool: list_pending_approvals ───────────────────────────────────────
-
-const listPendingApprovalsInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
-});
-
-async function handleListPendingApprovalsTool(input: unknown): Promise<ToolResult> {
- const parsed = listPendingApprovalsInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleListPendingApprovals(
- {},
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ approvals: r.data, count: r.data.length }));
-}
-
-// ── Tool: list_approvals_for_task ──────────────────────────────────────
-
-const listApprovalsForTaskInput = z.object({
- project_slug: z.string().min(1).describe("From IDENTITY.md."),
- task_id: z.string().min(1).describe("Task whose approvals you want."),
-});
-
-async function handleListApprovalsForTaskTool(
- input: unknown,
-): Promise<ToolResult> {
- const parsed = listApprovalsForTaskInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleListApprovalsForTask(
- { task_id: parsed.data.task_id },
- { project_slug: parsed.data.project_slug, agent_id: "" },
- );
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ approvals: r.data, count: r.data.length }));
-}
-
-// ── Tool: list_task_statuses (enum discovery) ──────────────────────────
-// No project_slug — this is a static enum, not project-scoped state. Agents
-// query it once to learn the workflow.
-
-const listTaskStatusesInput = z.object({});
-
-async function handleListTaskStatusesTool(input: unknown): Promise<ToolResult> {
- const parsed = listTaskStatusesInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleListTaskStatuses();
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ statuses: r.data }));
-}
-
-// ── Tool: list_approval_action_types ───────────────────────────────────
-
-const listApprovalActionTypesInput = z.object({});
-
-async function handleListApprovalActionTypesTool(
- input: unknown,
-): Promise<ToolResult> {
- const parsed = listApprovalActionTypesInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const r = handleListApprovalActionTypes();
- if (!r.ok) return { ok: false, error: r.error };
- return txt(JSON.stringify({ action_types: r.data }));
-}
-
-// ── 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.`);
-}
-
-// ── Tool: schedule_recurring_work ─────────────────────────────────────
-
-const scheduleRecurringWorkInput = z.object({
- project_slug: z
- .string()
- .min(1)
- .describe("Your project_slug from IDENTITY.md."),
- agent_id: z
- .string()
- .min(1)
- .describe(
- "Your agent_id (e.g. `demo1-google-ads-ana`). The cron will fire as a task assignment to this agent.",
- ),
- name: z
- .string()
- .min(1)
- .max(64)
- .regex(/^[a-z0-9][a-z0-9-]*$/, "must be kebab-case lowercase")
- .describe(
- "Short kebab-case identifier for this scheduled job. Should describe the work, not the schedule. Good: `daily-bid-opt`, `weekly-quality-score`. Bad: `9am-cron`.",
- ),
- cron_expr: z
- .string()
- .min(1)
- .describe(
- "Standard 5-field cron expression (minute hour day month day-of-week). Example: `0 9 * * 1` = 9am every Monday. Interpreted as UTC; embed timezone offset in the hour field if needed.",
- ),
- message: z
- .string()
- .min(1)
- .describe(
- "The prompt the scheduled job will send to the agent on each tick. Treat it as instructions to your future self — be specific about what to do and what to report.",
- ),
-});
-
-async function handleScheduleRecurringWorkTool(
- input: unknown,
-): Promise<ToolResult> {
- const parsed = scheduleRecurringWorkInput.safeParse(input);
- if (!parsed.success) return invalid(parsed.error);
- const { project_slug, agent_id, name, cron_expr, message } = parsed.data;
-
- // Verify the calling agent belongs to the project they're scoping.
- const project = await import("@/server/db/projects").then((m) =>
- m.getProject(project_slug),
- );
- if (!project) return { ok: false, error: `Unknown project '${project_slug}'.` };
- const { listProjectAgents } = await import("@/server/agent-meta");
- const projectAgents = await listProjectAgents(project_slug);
- if (!projectAgents.some((a) => a.agent_id === agent_id)) {
- return {
- ok: false,
- error: `Agent '${agent_id}' is not part of project '${project_slug}'.`,
- };
- }
-
- // Validate the cron expression by trying to parse it.
- try {
- const { CronExpressionParser } = await import("cron-parser");
- CronExpressionParser.parse(cron_expr, { tz: "UTC" });
- } catch (err) {
- return {
- ok: false,
- error: `Invalid cron_expr: ${err instanceof Error ? err.message : String(err)}`,
- };
- }
-
- try {
- const { createScheduledJob } = await import("@/server/scheduler");
- const job = createScheduledJob({
- project_slug,
- agent_id,
- name,
- cron_expr,
- message,
- enabled: true,
- });
- return txt(
- JSON.stringify({
- id: job.id,
- name: job.name,
- cron_expr: job.cron_expr,
- next_run_at: job.next_run_at,
- }),
- );
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg.includes("UNIQUE constraint")) {
- return {
- ok: false,
- error: `A scheduled job named '${name}' already exists for this agent. Pick a different name or list existing jobs first.`,
- };
- }
- return { ok: false, error: msg };
- }
-}
-
-// ── Registry ───────────────────────────────────────────────────────────
-
-export const TOOLS: ToolDefinition[] = [
- {
- name: "submit_task_status",
- description:
- "Report progress on the task you were assigned. Call at the END of any turn that finishes work, blocks, or fails. Replaces the legacy `<task_status>` text block — same semantics, strict enum.",
- inputSchema: submitTaskStatusInput,
- handler: handleSubmitTaskStatus,
- },
- {
- name: "create_task",
- description:
- "Spawn a new task and assign it to a specialist. CMO uses this to delegate; specialists can use it to chain follow-up work. The task auto-starts (proposed → running) so the assignee picks it up immediately.",
- inputSchema: createTaskInput,
- handler: handleCreateTaskTool,
- },
- {
- name: "request_approval",
- description:
- "Ask the user (or an auto-approve policy) to sign off on a governed action before you execute it. Required before any spend change, content publish, new channel, bid change, or audience change. Setting `task_id` parks the task in `blocked` until the user (or policy) resolves it; on approve the agent receives a wake-up message to proceed.",
- inputSchema: requestApprovalInput,
- handler: handleRequestApprovalTool,
- },
- {
- name: "add_task_comment",
- description:
- "Leave a note on a task — for the CMO to see, or to record your reasoning. Visible in /activity. Use this for cross-agent communication that doesn't need user attention.",
- inputSchema: addTaskCommentInput,
- handler: handleAddTaskCommentTool,
- },
- {
- name: "ask_user_question",
- description:
- "Surface a question to the user (not the CMO). Use sparingly — only when the answer can't come from the CMO, your tools, or the brief. Provide `options` for multiple-choice.",
- inputSchema: askUserInput,
- handler: handleAskUserTool,
- },
- {
- name: "get_task",
- description:
- "Fetch a task by id (UUID or display_id). Use this to re-anchor when your context window rotates and you've lost the brief, or to check the latest state of a task you previously touched.",
- inputSchema: getTaskInput,
- handler: handleGetTaskTool,
- },
- {
- name: "list_my_tasks",
- description:
- "List tasks assigned to YOU (filtered to your project). Default returns in-flight tasks (proposed | approved | running | blocked). Use this to see what's on your plate.",
- inputSchema: listMyTasksInput,
- handler: handleListMyTasksTool,
- },
- {
- name: "list_tasks",
- description:
- "List ALL tasks in the project — across every agent. Optional status filter. Use this to understand cross-agent activity or, as the CMO, to plan.",
- inputSchema: listTasksInput,
- handler: handleListTasksTool,
- },
- {
- name: "update_task",
- description:
- "Edit a task's title, brief, or success criteria. Used by the CMO to clarify a delegation after the fact. Doesn't change task status — use submit_task_status / cancel_task for that.",
- inputSchema: updateTaskInput,
- handler: handleUpdateTaskTool,
- },
- {
- name: "cancel_task",
- description:
- "Mark a task `cancelled`. Use when the work is no longer relevant or has been superseded. Optional `reason` is stored on error_message.",
- inputSchema: cancelTaskInput,
- handler: handleCancelTaskTool,
- },
- {
- name: "get_project",
- description:
- "Fetch the current project's metadata (display name, Google Ads account id, etc.). Useful when you need project-level context for an answer.",
- inputSchema: getProjectInput,
- handler: handleGetProjectTool,
- },
- {
- name: "list_project_agents",
- description:
- "List the agents available in this project (CMO + specialists + any custom clones). Use this to discover valid `assignee` template_keys for create_task.",
- inputSchema: listProjectAgentsInput,
- handler: handleListProjectAgentsTool,
- },
- {
- name: "list_task_comments",
- description:
- "Fetch the comment thread on a task (added via add_task_comment / <add_comment>). Use to catch up on cross-agent conversation when you re-engage with a task.",
- inputSchema: listTaskCommentsInput,
- handler: handleListTaskCommentsTool,
- },
- {
- name: "get_approval",
- description:
- "Fetch an approval row by id. Use when an earlier wake-up message gave you an approval_id and you need the latest state (decision_note, decided_by, etc.).",
- inputSchema: getApprovalInput,
- handler: handleGetApprovalTool,
- },
- {
- name: "list_my_approvals",
- description:
- "List approvals YOU requested (pending and revision_requested). Use to check whether any of your prior asks are still parked.",
- inputSchema: listMyApprovalsInput,
- handler: handleListMyApprovalsTool,
- },
- {
- name: "list_pending_approvals",
- description:
- "List every actionable approval in the project (pending + revision_requested), across all agents. Useful for the CMO to triage.",
- inputSchema: listPendingApprovalsInput,
- handler: handleListPendingApprovalsTool,
- },
- {
- name: "list_approvals_for_task",
- description:
- "List every approval ever requested on a specific task — history of governed actions for that task.",
- inputSchema: listApprovalsForTaskInput,
- handler: handleListApprovalsForTaskTool,
- },
- {
- name: "list_task_statuses",
- description:
- "Discover the task workflow state machine: every status value, what it means, whether it's terminal, and what transitions are allowed FROM it. Call once when you're unsure which status to use.",
- inputSchema: listTaskStatusesInput,
- handler: handleListTaskStatusesTool,
- },
- {
- name: "list_approval_action_types",
- description:
- "Discover valid `action_type` values for request_approval, with descriptions and which require a cost estimate. Call once if you're unsure which type fits your action.",
- inputSchema: listApprovalActionTypesInput,
- handler: handleListApprovalActionTypesTool,
- },
- {
- 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,
- },
- {
- name: "schedule_recurring_work",
- description:
- "Create a scheduled job that fires a synthetic task assignment to an agent on a cron schedule. Persists to notfair-cmo's SQLite scheduled_jobs table; visible in the Crons tab. Use this when the user asks for 'every day', 'every Monday', 'every hour' work. Replaces the legacy `openclaw cron add` CLI.",
- inputSchema: scheduleRecurringWorkInput,
- handler: handleScheduleRecurringWorkTool,
- },
-];
-
-// Browser MCP tools live in their own server (notfair-browser) so the
-// orchestration surface stays focused. See ./browser-tools.ts and the
-// /api/mcp/browser route.
-
-export function describeTool(tool: ToolDefinition): {
- name: string;
- description: string;
- inputSchema: Record<string, unknown>;
-} {
- return {
- name: tool.name,
- description: tool.description,
- inputSchema: zodObjectToJsonSchema(tool.inputSchema),
- };
-}
-
-export function findTool(name: string): ToolDefinition | undefined {
- return TOOLS.find((t) => t.name === name);
-}
-
-/**
- * Minimal zod → JSON-Schema converter for the shapes we actually use:
- * z.object with z.string / z.number / z.string().optional / z.enum / .describe.
- * Anything richer falls back to {type:"string"} — the handler's safeParse
- * catches real violations either way.
- */
-function zodObjectToJsonSchema(
- schema: z.ZodObject<z.ZodRawShape>,
-): Record<string, unknown> {
- const shape = schema.shape;
- const properties: Record<string, unknown> = {};
- const required: string[] = [];
- for (const [key, value] of Object.entries(shape)) {
- const node = leafSchema(value as z.ZodTypeAny);
- properties[key] = node.schema;
- if (!node.optional) required.push(key);
- }
- return {
- type: "object",
- properties,
- required,
- additionalProperties: false,
- };
-}
-
-function leafSchema(
- schema: z.ZodTypeAny,
-): { schema: Record<string, unknown>; optional: boolean } {
- let optional = false;
- let inner: z.ZodTypeAny = schema;
- if (inner instanceof z.ZodOptional) {
- optional = true;
- inner = inner._def.innerType as z.ZodTypeAny;
- }
- const description = (schema as { description?: string }).description;
- const out: Record<string, unknown> = {};
- if (inner instanceof z.ZodString) {
- out.type = "string";
- } else if (inner instanceof z.ZodEnum) {
- out.type = "string";
- out.enum = (inner._def as { values: string[] }).values;
- } else if (inner instanceof z.ZodNumber) {
- out.type = "number";
- } else if (inner instanceof z.ZodBoolean) {
- out.type = "boolean";
- } else {
- out.type = "string";
- }
- if (description) out.description = description;
- return { schema: out, optional };
-}
diff --git a/notfair-cmo/src/server/mcp/discovery-url.test.ts b/notfair-cmo/src/server/mcp/discovery-url.test.ts
deleted file mode 100644
index 25de40b7..00000000
--- a/notfair-cmo/src/server/mcp/discovery-url.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { deriveDiscoveryUrl } from "./discovery-url";
-
-describe("deriveDiscoveryUrl", () => {
- it("inserts the well-known suffix between origin and path", () => {
- expect(deriveDiscoveryUrl("https://notfair.co/api/mcp/google_ads")).toBe(
- "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",
- );
- });
-
- it("handles path-less origins (trailing /)", () => {
- expect(deriveDiscoveryUrl("https://mcp.stripe.com/")).toBe(
- "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- );
- });
-
- it("handles bare origins (no path)", () => {
- expect(deriveDiscoveryUrl("https://mcp.stripe.com")).toBe(
- "https://mcp.stripe.com/.well-known/oauth-protected-resource",
- );
- });
-
- it("strips trailing slashes from the resource path", () => {
- expect(deriveDiscoveryUrl("https://example.com/api/v1/")).toBe(
- "https://example.com/.well-known/oauth-protected-resource/api/v1",
- );
- });
-
- it("strips multiple trailing slashes", () => {
- expect(deriveDiscoveryUrl("https://example.com/api///")).toBe(
- "https://example.com/.well-known/oauth-protected-resource/api",
- );
- });
-
- it("preserves non-default ports", () => {
- expect(deriveDiscoveryUrl("https://example.com:8443/mcp")).toBe(
- "https://example.com:8443/.well-known/oauth-protected-resource/mcp",
- );
- });
-
- it("accepts http origins (for local dev)", () => {
- expect(deriveDiscoveryUrl("http://localhost:3326/api/mcp")).toBe(
- "http://localhost:3326/.well-known/oauth-protected-resource/api/mcp",
- );
- });
-
- it("returns null for malformed URLs", () => {
- expect(deriveDiscoveryUrl("")).toBeNull();
- expect(deriveDiscoveryUrl("not a url")).toBeNull();
- expect(deriveDiscoveryUrl("/api/mcp")).toBeNull();
- });
-
- it("rejects non-http(s) schemes", () => {
- expect(deriveDiscoveryUrl("ftp://example.com/mcp")).toBeNull();
- expect(deriveDiscoveryUrl("file:///tmp/mcp")).toBeNull();
- expect(deriveDiscoveryUrl("javascript:alert(1)")).toBeNull();
- });
-});
diff --git a/notfair-cmo/src/server/mcp/probe-cache.test.ts b/notfair-cmo/src/server/mcp/probe-cache.test.ts
deleted file mode 100644
index d738caa7..00000000
--- a/notfair-cmo/src/server/mcp/probe-cache.test.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- _clearProbeCacheForTests,
- getCachedProbe,
- invalidateProbe,
- setCachedProbe,
-} from "./probe-cache";
-import type { McpRuntimeStatus } from "./state";
-
-const connected: McpRuntimeStatus = {
- state: "connected",
- url: "https://example.com/mcp",
- tools_count: null,
- last_checked_at: "2026-06-01T00:00:00.000Z",
-};
-
-const unreachable: McpRuntimeStatus = {
- state: "unreachable",
- url: "https://example.com/mcp",
- error: "HTTP 500",
- last_checked_at: "2026-06-01T00:00:00.000Z",
-};
-
-const staleToken: McpRuntimeStatus = {
- state: "stale_token",
- url: "https://example.com/mcp",
- http_status: 401,
- last_checked_at: "2026-06-01T00:00:00.000Z",
-};
-
-beforeEach(() => {
- _clearProbeCacheForTests();
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-06-01T00:00:00.000Z"));
-});
-
-afterEach(() => {
- vi.useRealTimers();
- _clearProbeCacheForTests();
-});
-
-describe("probe-cache: TTL by state", () => {
- it("caches connected results for 60 seconds", () => {
- setCachedProbe("acme", "stripe", connected);
- expect(getCachedProbe("acme", "stripe")).toEqual(connected);
-
- vi.advanceTimersByTime(59_999);
- expect(getCachedProbe("acme", "stripe")).toEqual(connected);
-
- vi.advanceTimersByTime(2);
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-
- it("caches unreachable results for 10 seconds", () => {
- setCachedProbe("acme", "stripe", unreachable);
- expect(getCachedProbe("acme", "stripe")).toEqual(unreachable);
-
- vi.advanceTimersByTime(9_999);
- expect(getCachedProbe("acme", "stripe")).toEqual(unreachable);
-
- vi.advanceTimersByTime(2);
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-
- it("does not cache stale_token (immediate feedback after reconnect)", () => {
- setCachedProbe("acme", "stripe", staleToken);
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-
- it("does not cache not_configured", () => {
- setCachedProbe("acme", "stripe", { state: "not_configured" });
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-
- it("does not cache configured_no_token", () => {
- setCachedProbe("acme", "stripe", {
- state: "configured_no_token",
- url: "https://example.com/mcp",
- });
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-});
-
-describe("probe-cache: keying", () => {
- it("scopes entries by (project_slug, catalog_key)", () => {
- setCachedProbe("acme", "stripe", connected);
- expect(getCachedProbe("acme", "stripe")).toEqual(connected);
- expect(getCachedProbe("acme", "supabase")).toBeNull();
- expect(getCachedProbe("other-project", "stripe")).toBeNull();
- });
-});
-
-describe("probe-cache: replacement and invalidation", () => {
- it("clears a previously-cached connected entry when overwritten with a non-cacheable state", () => {
- setCachedProbe("acme", "stripe", connected);
- expect(getCachedProbe("acme", "stripe")).not.toBeNull();
-
- setCachedProbe("acme", "stripe", staleToken);
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-
- it("invalidateProbe drops the cached entry", () => {
- setCachedProbe("acme", "stripe", connected);
- invalidateProbe("acme", "stripe");
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-
- it("invalidateProbe on a missing entry is a no-op (no throw)", () => {
- expect(() => invalidateProbe("acme", "ghost")).not.toThrow();
- });
-
- it("overwriting a connected entry resets its TTL window", () => {
- setCachedProbe("acme", "stripe", connected);
- vi.advanceTimersByTime(50_000);
- // Refresh — the second write resets the 60s window.
- setCachedProbe("acme", "stripe", connected);
- vi.advanceTimersByTime(50_000);
- // 100s since the first write; 50s since the refresh — still valid.
- expect(getCachedProbe("acme", "stripe")).toEqual(connected);
- });
-});
-
-describe("probe-cache: read-time eviction", () => {
- it("removes expired entries on read so the next setCachedProbe starts clean", () => {
- setCachedProbe("acme", "stripe", connected);
- vi.advanceTimersByTime(120_000);
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- // After eviction, a write with a non-cacheable state is still a clear-no-op.
- setCachedProbe("acme", "stripe", staleToken);
- expect(getCachedProbe("acme", "stripe")).toBeNull();
- });
-});
diff --git a/notfair-cmo/src/server/mcp/refresh.test.ts b/notfair-cmo/src/server/mcp/refresh.test.ts
deleted file mode 100644
index 93077377..00000000
--- a/notfair-cmo/src/server/mcp/refresh.test.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "@/server/db/migrations";
-
-let testDb: Database.Database;
-
-vi.mock("@/server/db/db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import { refreshMcpToken, isExpiringSoon } from "./refresh";
-import { findMcpToken, upsertMcpToken, type McpToken } from "./tokens";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) db.exec(migration.sql);
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-function makeToken(overrides: Partial<McpToken> = {}): McpToken {
- seedProject();
- const row = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: overrides.access_token_enc ?? "old-at",
- refresh_token: overrides.refresh_token_enc ?? "rt-1",
- expires_at: overrides.expires_at ?? "2026-01-01T00:00:00.000Z",
- token_endpoint: overrides.token_endpoint ?? "https://auth.example.com/token",
- client_id: overrides.client_id ?? "client-abc",
- client_secret: overrides.client_secret ?? "shh",
- });
- return row;
-}
-
-beforeEach(() => {
- testDb = new Database(":memory:");
- testDb.pragma("foreign_keys = ON");
- applyMigrations(testDb);
-});
-
-afterEach(() => {
- testDb.close();
- vi.restoreAllMocks();
-});
-
-describe("refreshMcpToken", () => {
- it("exchanges refresh_token for a fresh access_token and persists it", async () => {
- const token = makeToken();
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({ access_token: "new-at", expires_in: 3600 }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- ),
- );
-
- const refreshed = await refreshMcpToken(token);
- expect(refreshed).not.toBeNull();
- expect(refreshed!.access_token_enc).toBe("new-at");
- expect(refreshed!.refresh_token_enc).toBe("rt-1");
- expect(Date.parse(refreshed!.expires_at!)).toBeGreaterThan(Date.now() + 3500 * 1000);
-
- const stored = findMcpToken("acme", "stripe");
- expect(stored!.access_token_enc).toBe("new-at");
- });
-
- it("rotates the refresh_token when the provider returns a new one", async () => {
- const token = makeToken();
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- access_token: "new-at",
- refresh_token: "rt-2",
- expires_in: 3600,
- }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- ),
- );
-
- const refreshed = await refreshMcpToken(token);
- expect(refreshed!.refresh_token_enc).toBe("rt-2");
- });
-
- it("returns null when the row has no refresh_token (legacy)", async () => {
- seedProject();
- const legacy = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "old-at",
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- });
- const fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
-
- expect(await refreshMcpToken(legacy)).toBeNull();
- expect(fetchSpy).not.toHaveBeenCalled();
- });
-
- it("returns null when the row has no token_endpoint (legacy)", async () => {
- seedProject();
- const legacy = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "old-at",
- refresh_token: "rt-1",
- client_id: "client-abc",
- });
- const fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
-
- expect(await refreshMcpToken(legacy)).toBeNull();
- expect(fetchSpy).not.toHaveBeenCalled();
- });
-
- it("returns null on 4xx (revoked refresh token) without trashing the row", async () => {
- const token = makeToken();
- vi.stubGlobal(
- "fetch",
- vi
- .fn()
- .mockResolvedValue(new Response("invalid_grant", { status: 400 })),
- );
-
- expect(await refreshMcpToken(token)).toBeNull();
- const stored = findMcpToken("acme", "stripe");
- expect(stored!.access_token_enc).toBe("old-at");
- expect(stored!.refresh_token_enc).toBe("rt-1");
- });
-
- it("returns null on network error", async () => {
- const token = makeToken();
- vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED")));
- expect(await refreshMcpToken(token)).toBeNull();
- });
-
- it("omits client_secret when not stored (public client)", async () => {
- seedProject();
- const publicClient = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "old-at",
- refresh_token: "rt-1",
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- // no client_secret
- });
- const fetchSpy = vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({ access_token: "new-at", expires_in: 3600 }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- );
- vi.stubGlobal("fetch", fetchSpy);
-
- await refreshMcpToken(publicClient);
- const call = fetchSpy.mock.calls[0];
- const body = call[1].body as string;
- expect(body).toContain("grant_type=refresh_token");
- expect(body).toContain("client_id=client-abc");
- expect(body).not.toContain("client_secret");
- });
-});
-
-describe("isExpiringSoon", () => {
- function row(expires_at: string | null): McpToken {
- return {
- id: "x",
- project_slug: "acme",
- server_name: "stripe",
- account_label: "",
- access_token_enc: "at",
- refresh_token_enc: null,
- expires_at,
- scope: null,
- metadata_json: null,
- token_endpoint: null,
- client_id: null,
- client_secret: null,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- };
- }
-
- it("returns true when expires_at is in the past", () => {
- expect(isExpiringSoon(row("2020-01-01T00:00:00.000Z"))).toBe(true);
- });
-
- it("returns true when expires_at is within the skew window", () => {
- const soon = new Date(Date.now() + 30_000).toISOString();
- expect(isExpiringSoon(row(soon))).toBe(true);
- });
-
- it("returns false when expires_at is comfortably in the future", () => {
- const later = new Date(Date.now() + 10 * 60_000).toISOString();
- expect(isExpiringSoon(row(later))).toBe(false);
- });
-
- it("returns false when expires_at is null (unknown)", () => {
- expect(isExpiringSoon(row(null))).toBe(false);
- });
-
- it("respects a custom skew", () => {
- const inTwoMin = new Date(Date.now() + 2 * 60_000).toISOString();
- expect(isExpiringSoon(row(inTwoMin), 30_000)).toBe(false);
- expect(isExpiringSoon(row(inTwoMin), 5 * 60_000)).toBe(true);
- });
-});
diff --git a/notfair-cmo/src/server/mcp/rpc.test.ts b/notfair-cmo/src/server/mcp/rpc.test.ts
deleted file mode 100644
index 5fef8f51..00000000
--- a/notfair-cmo/src/server/mcp/rpc.test.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "@/server/db/migrations";
-
-let testDb: Database.Database;
-
-vi.mock("@/server/db/db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import { mcpRpcAutoRefresh } from "./rpc";
-import { findMcpToken, upsertMcpToken } from "./tokens";
-
-const PRESET_KEY = "notfair-googleads";
-const PRESET_URL = "https://notfair.co/api/mcp/google_ads";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) db.exec(migration.sql);
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-function rpcOk(body: unknown): Response {
- return new Response(JSON.stringify({ jsonrpc: "2.0", id: 1, result: body }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
-}
-
-function http401(): Response {
- return new Response("unauthorized", { status: 401 });
-}
-
-beforeEach(() => {
- testDb = new Database(":memory:");
- testDb.pragma("foreign_keys = ON");
- applyMigrations(testDb);
- seedProject();
-});
-
-afterEach(() => {
- testDb.close();
- vi.restoreAllMocks();
-});
-
-describe("mcpRpcAutoRefresh", () => {
- it("returns 401 when no token row exists", async () => {
- const fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
- const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");
- expect(r.ok).toBe(false);
- if (!r.ok && r.kind === "http_error") {
- expect(r.status).toBe(401);
- }
- expect(fetchSpy).not.toHaveBeenCalled();
- });
-
- it("returns 404 when the catalog key is unknown", async () => {
- upsertMcpToken({
- project_slug: "acme",
- server_name: "ghost",
- access_token: "at",
- });
- const r = await mcpRpcAutoRefresh("acme", "ghost", "initialize");
- expect(r.ok).toBe(false);
- if (!r.ok && r.kind === "http_error") expect(r.status).toBe(404);
- });
-
- it("calls mcpRpc with the stored access token (happy path)", async () => {
- upsertMcpToken({
- project_slug: "acme",
- server_name: PRESET_KEY,
- access_token: "at-1",
- expires_at: new Date(Date.now() + 60 * 60_000).toISOString(),
- });
- const fetchSpy = vi.fn().mockResolvedValue(rpcOk({ ok: true }));
- vi.stubGlobal("fetch", fetchSpy);
-
- const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");
- expect(r.ok).toBe(true);
- expect(fetchSpy).toHaveBeenCalledTimes(1);
- const headers = fetchSpy.mock.calls[0][1].headers;
- expect(headers.Authorization).toBe("Bearer at-1");
- });
-
- it("refreshes proactively when expires_at is within the skew window", async () => {
- upsertMcpToken({
- project_slug: "acme",
- server_name: PRESET_KEY,
- access_token: "stale-at",
- refresh_token: "rt-1",
- expires_at: new Date(Date.now() + 10_000).toISOString(), // 10s away
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- client_secret: "shh",
- });
-
- const fetchSpy = vi
- .fn()
- // 1st call: refresh
- .mockResolvedValueOnce(
- new Response(
- JSON.stringify({ access_token: "fresh-at", expires_in: 3600 }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- )
- // 2nd call: actual RPC against the MCP resource
- .mockResolvedValueOnce(rpcOk({ ok: true }));
- vi.stubGlobal("fetch", fetchSpy);
-
- const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");
- expect(r.ok).toBe(true);
- expect(fetchSpy).toHaveBeenCalledTimes(2);
- expect(fetchSpy.mock.calls[0][0]).toBe("https://auth.example.com/token");
- expect(fetchSpy.mock.calls[1][0]).toBe(PRESET_URL);
- expect(fetchSpy.mock.calls[1][1].headers.Authorization).toBe("Bearer fresh-at");
- expect(findMcpToken("acme", PRESET_KEY)!.access_token_enc).toBe("fresh-at");
- });
-
- it("refreshes reactively on 401 and retries once", async () => {
- upsertMcpToken({
- project_slug: "acme",
- server_name: PRESET_KEY,
- access_token: "stale-at",
- refresh_token: "rt-1",
- expires_at: new Date(Date.now() + 60 * 60_000).toISOString(), // not soon
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- });
- // Backdate updated_at so the reactive guard ("just refreshed") doesn't
- // suppress the retry.
- testDb
- .prepare("UPDATE mcp_tokens SET updated_at = ? WHERE project_slug = ?")
- .run(new Date(Date.now() - 60_000).toISOString(), "acme");
-
- const fetchSpy = vi
- .fn()
- .mockResolvedValueOnce(http401()) // first RPC: 401
- .mockResolvedValueOnce(
- new Response(
- JSON.stringify({ access_token: "fresh-at", expires_in: 3600 }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- )
- .mockResolvedValueOnce(rpcOk({ ok: true }));
- vi.stubGlobal("fetch", fetchSpy);
-
- const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");
- expect(r.ok).toBe(true);
- expect(fetchSpy).toHaveBeenCalledTimes(3);
- expect(fetchSpy.mock.calls[2][1].headers.Authorization).toBe("Bearer fresh-at");
- });
-
- it("does not loop refresh when the fresh token also 401s", async () => {
- upsertMcpToken({
- project_slug: "acme",
- server_name: PRESET_KEY,
- access_token: "stale-at",
- refresh_token: "rt-1",
- expires_at: new Date(Date.now() + 5_000).toISOString(), // triggers proactive refresh
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- });
-
- const fetchSpy = vi
- .fn()
- // proactive refresh
- .mockResolvedValueOnce(
- new Response(
- JSON.stringify({ access_token: "fresh-but-still-bad", expires_in: 3600 }),
- { status: 200, headers: { "Content-Type": "application/json" } },
- ),
- )
- // RPC still 401s (e.g. server invalidated the session)
- .mockResolvedValueOnce(http401());
- vi.stubGlobal("fetch", fetchSpy);
-
- const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");
- expect(r.ok).toBe(false);
- if (!r.ok && r.kind === "http_error") expect(r.status).toBe(401);
- expect(fetchSpy).toHaveBeenCalledTimes(2); // no third call
- });
-
- it("returns the original 401 when no refresh_token is stored (legacy row)", async () => {
- upsertMcpToken({
- project_slug: "acme",
- server_name: PRESET_KEY,
- access_token: "stale-at",
- // no refresh_token, no token_endpoint, no client_id
- });
- const fetchSpy = vi.fn().mockResolvedValueOnce(http401());
- vi.stubGlobal("fetch", fetchSpy);
-
- const r = await mcpRpcAutoRefresh("acme", PRESET_KEY, "initialize");
- expect(r.ok).toBe(false);
- if (!r.ok && r.kind === "http_error") expect(r.status).toBe(401);
- expect(fetchSpy).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/notfair-cmo/src/server/mcp/tokens.test.ts b/notfair-cmo/src/server/mcp/tokens.test.ts
deleted file mode 100644
index ee47e00d..00000000
--- a/notfair-cmo/src/server/mcp/tokens.test.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "@/server/db/migrations";
-
-let testDb: Database.Database;
-
-vi.mock("@/server/db/db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-import {
- findMcpToken,
- updateMcpTokenSecrets,
- upsertMcpToken,
-} from "./tokens";
-
-function applyMigrations(db: Database.Database): void {
- for (const migration of MIGRATIONS) db.exec(migration.sql);
-}
-
-function seedProject(slug = "acme"): void {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
-}
-
-beforeEach(() => {
- testDb = new Database(":memory:");
- testDb.pragma("foreign_keys = ON");
- applyMigrations(testDb);
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("upsertMcpToken (OAuth client fields)", () => {
- it("persists token_endpoint, client_id, client_secret, and refresh_token", () => {
- seedProject();
- const row = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "at-1",
- refresh_token: "rt-1",
- expires_at: "2027-01-01T00:00:00.000Z",
- scope: "read_write",
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- client_secret: "shh",
- });
- expect(row.refresh_token_enc).toBe("rt-1");
- expect(row.expires_at).toBe("2027-01-01T00:00:00.000Z");
- expect(row.scope).toBe("read_write");
- expect(row.token_endpoint).toBe("https://auth.example.com/token");
- expect(row.client_id).toBe("client-abc");
- expect(row.client_secret).toBe("shh");
- });
-
- it("leaves OAuth client fields null when omitted (legacy callers)", () => {
- seedProject();
- const row = upsertMcpToken({
- project_slug: "acme",
- server_name: "legacy",
- access_token: "at",
- });
- expect(row.refresh_token_enc).toBeNull();
- expect(row.token_endpoint).toBeNull();
- expect(row.client_id).toBeNull();
- expect(row.client_secret).toBeNull();
- });
-
- it("overwrites OAuth client fields on update (re-auth case)", () => {
- seedProject();
- upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "old",
- client_id: "old-client",
- });
- const after = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "new",
- refresh_token: "new-rt",
- client_id: "new-client",
- client_secret: "new-secret",
- token_endpoint: "https://auth.example.com/token",
- });
- expect(after.access_token_enc).toBe("new");
- expect(after.refresh_token_enc).toBe("new-rt");
- expect(after.client_id).toBe("new-client");
- expect(after.client_secret).toBe("new-secret");
- expect(after.token_endpoint).toBe("https://auth.example.com/token");
- });
-});
-
-describe("updateMcpTokenSecrets", () => {
- it("rotates access_token + expires_at without touching client fields", () => {
- seedProject();
- const row = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "at-1",
- refresh_token: "rt-1",
- expires_at: "2027-01-01T00:00:00.000Z",
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- client_secret: "shh",
- });
- const updated = updateMcpTokenSecrets(row.id, {
- access_token: "at-2",
- expires_at: "2028-01-01T00:00:00.000Z",
- });
- expect(updated).not.toBeNull();
- expect(updated!.access_token_enc).toBe("at-2");
- expect(updated!.expires_at).toBe("2028-01-01T00:00:00.000Z");
- expect(updated!.refresh_token_enc).toBe("rt-1");
- expect(updated!.token_endpoint).toBe("https://auth.example.com/token");
- expect(updated!.client_id).toBe("client-abc");
- expect(updated!.client_secret).toBe("shh");
- });
-
- it("rotates refresh_token when provider issues a new one", () => {
- seedProject();
- const row = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "at-1",
- refresh_token: "rt-1",
- });
- const updated = updateMcpTokenSecrets(row.id, {
- access_token: "at-2",
- refresh_token: "rt-2",
- });
- expect(updated!.refresh_token_enc).toBe("rt-2");
- });
-
- it("keeps existing refresh_token when patch omits it (RFC 6749 §6)", () => {
- seedProject();
- const row = upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "at-1",
- refresh_token: "rt-1",
- });
- const updated = updateMcpTokenSecrets(row.id, { access_token: "at-2" });
- expect(updated!.refresh_token_enc).toBe("rt-1");
- });
-
- it("returns null when row no longer exists", () => {
- expect(
- updateMcpTokenSecrets("nope-uuid", { access_token: "x" }),
- ).toBeNull();
- });
-});
-
-describe("findMcpToken (after migration 013)", () => {
- it("reads the new fields back via findMcpToken", () => {
- seedProject();
- upsertMcpToken({
- project_slug: "acme",
- server_name: "stripe",
- access_token: "at",
- refresh_token: "rt",
- token_endpoint: "https://auth.example.com/token",
- client_id: "client-abc",
- });
- const found = findMcpToken("acme", "stripe");
- expect(found).not.toBeNull();
- expect(found!.token_endpoint).toBe("https://auth.example.com/token");
- expect(found!.client_id).toBe("client-abc");
- expect(found!.refresh_token_enc).toBe("rt");
- });
-});
diff --git a/notfair-cmo/src/server/onboarding/accounts.test.ts b/notfair-cmo/src/server/onboarding/accounts.test.ts
deleted file mode 100644
index f00ffbd8..00000000
--- a/notfair-cmo/src/server/onboarding/accounts.test.ts
+++ /dev/null
@@ -1,580 +0,0 @@
-import { afterEach, 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),
- // The action wraps `mcpRpc` in an auto-refresh helper that resolves the
- // token from the DB; tests don't exercise refresh, so we route the
- // wrapper to the same underlying mock for simplicity.
- mcpRpcAutoRefresh: (...args: unknown[]) => mcpRpcMock(...args),
-}));
-
-const getProjectMock = vi.fn();
-const setProjectGoogleAdsAccountMock = vi.fn();
-const setProjectMetaAdsAccountMock = vi.fn();
-const setProjectGscPropertyMock = vi.fn();
-vi.mock("@/server/db/projects", () => ({
- getProject: (...args: unknown[]) => getProjectMock(...args),
- setProjectGoogleAdsAccount: (...args: unknown[]) =>
- setProjectGoogleAdsAccountMock(...args),
- setProjectMetaAdsAccount: (...args: unknown[]) =>
- setProjectMetaAdsAccountMock(...args),
- setProjectGscProperty: (...args: unknown[]) =>
- setProjectGscPropertyMock(...args),
-}));
-
-vi.mock("next/cache", () => ({
- revalidatePath: vi.fn(),
-}));
-
-// getOnboardingTaskForSkipAction awaits provisioning + reads the token
-// table to decide whether to mint the audit task.
-vi.mock("./provisioning-state", () => ({
- awaitProvisioning: async () => ({ kind: "done" }),
-}));
-const listTokensMock = vi.fn<(slug: string) => Array<{ server_name: string }>>(
- () => [],
-);
-vi.mock("@/server/mcp/tokens", () => ({
- listProjectMcpTokens: (slug: string) => listTokensMock(slug),
-}));
-
-// 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<(slug: string) => 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-greg",
- 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: (slug: string) => listTasksMock(slug),
-}));
-vi.mock("@/server/agent-templates", () => ({
- agentNameFor: (slug: string, key: string, name: string) =>
- `${slug}-${key.replace(/_/g, "-")}-${name
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")}`,
- agentUrlSlug: (key: string, name: string) =>
- `${key.replace(/_/g, "-")}-${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`,
- TEMPLATES: [
- { key: "cmo", default_name: "Greg" },
- { key: "google_ads", default_name: "Ana" },
- { key: "seo", default_name: "Sam" },
- ],
-}));
-
-// setOnboardingAccountAction resolves the CMO via listProjectAgents now —
-// agent_ids encode the personal name, so it can't be synthesized.
-vi.mock("@/server/agent-meta", () => ({
- readAgentMeta: () => null,
- listProjectAgents: async () => [
- {
- agent_id: "acme-cmo-greg",
- slug: "cmo-greg",
- name: "Greg",
- template_key: "cmo",
- is_template_default: true,
- },
- ],
-}));
-
-import {
- getOnboardingTaskForSkipAction,
- listGoogleAdsAccounts,
- setOnboardingAccountAction,
- listMetaAdsAccounts,
- setOnboardingMetaAdsAccountAction,
- listGscProperties,
- setOnboardingGscPropertyAction,
-} from "./accounts";
-
-// ── Fixtures ───────────────────────────────────────────────────────
-
-const ACCOUNTS_PAYLOAD = {
- accounts: [
- { id: "7384288909", name: "IOW" },
- { id: "7521406707", name: "PawsVIP" },
- { id: "1301265570", name: "InOtherWord.ai" },
- { id: "7073485715", name: "BulkGPT.ai" },
- { id: "3251706605", name: "NotFair" },
- ],
- defaultAccountId: "3251706605",
- totalAccounts: 5,
-};
-
-function toolCallResult(payload: unknown): {
- ok: true;
- result: { content: Array<{ type: string; text: string }>; isError: boolean };
-} {
- return {
- ok: true,
- result: {
- content: [{ type: "text", text: JSON.stringify(payload) }],
- isError: false,
- },
- };
-}
-
-// ── Tests ──────────────────────────────────────────────────────────
-
-describe("listGoogleAdsAccounts", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getMcpConfigMock.mockReturnValue({
- url: "https://notfair.co/api/mcp/google_ads",
- token: "tok",
- });
- });
-
- it("returns accounts + default_account_id on the real Demo2 shape", async () => {
- mcpRpcMock.mockResolvedValueOnce(toolCallResult(ACCOUNTS_PAYLOAD));
- const r = await listGoogleAdsAccounts("acme");
- expect(r.ok).toBe(true);
- if (r.ok) {
- expect(r.accounts).toHaveLength(5);
- expect(r.accounts[0]).toEqual({ id: "7384288909", name: "IOW" });
- expect(r.default_account_id).toBe("3251706605");
- }
- });
-
- it("falls back to id when name is empty", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult({ accounts: [{ id: "123" }], defaultAccountId: null }),
- );
- const r = await listGoogleAdsAccounts("acme");
- expect(r.ok).toBe(true);
- if (r.ok) {
- expect(r.accounts[0]).toEqual({ id: "123", name: "123" });
- }
- });
-
- it("returns mcp_not_configured when getMcpConfig returns null", async () => {
- getMcpConfigMock.mockReturnValueOnce(null);
- const r = await listGoogleAdsAccounts("acme");
- expect(r).toMatchObject({ ok: false, kind: "mcp_not_configured" });
- expect(mcpRpcMock).not.toHaveBeenCalled();
- });
-
- it("returns rpc error when mcpRpc fails", async () => {
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "http_error",
- status: 401,
- });
- const r = await listGoogleAdsAccounts("acme");
- expect(r).toMatchObject({ ok: false, kind: "rpc" });
- });
-
- it("returns shape error when payload is missing accounts array", async () => {
- mcpRpcMock.mockResolvedValueOnce(toolCallResult({ totalAccounts: 0 }));
- const r = await listGoogleAdsAccounts("acme");
- expect(r).toMatchObject({ ok: false, kind: "shape" });
- });
-
- it("returns shape error when JSON is malformed", async () => {
- mcpRpcMock.mockResolvedValueOnce({
- ok: true,
- result: {
- content: [{ type: "text", text: "not json" }],
- isError: false,
- },
- });
- const r = await listGoogleAdsAccounts("acme");
- expect(r).toMatchObject({ ok: false, kind: "shape" });
- });
-});
-
-describe("setOnboardingAccountAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getMcpConfigMock.mockReturnValue({
- url: "https://notfair.co/api/mcp/google_ads",
- token: "tok",
- });
- getProjectMock.mockReturnValue({
- id: "uuid",
- slug: "acme",
- display_name: "Acme",
- created_at: "now",
- archived_at: null,
- google_ads_account_id: null,
- });
- setProjectGoogleAdsAccountMock.mockReturnValue({
- id: "uuid",
- slug: "acme",
- display_name: "Acme",
- created_at: "now",
- archived_at: null,
- google_ads_account_id: "3251706605",
- });
- mcpRpcMock.mockResolvedValue(toolCallResult(ACCOUNTS_PAYLOAD));
- });
-
- it("persists the selection when account is in the bearer's list", async () => {
- const r = await setOnboardingAccountAction("acme", "3251706605");
- expect(r.ok).toBe(true);
- expect(setProjectGoogleAdsAccountMock).toHaveBeenCalledWith(
- "acme",
- "3251706605",
- );
- });
-
- 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-greg",
- 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-greg",
- title: "Audit the account and propose a starter playbook",
- status: "working",
- },
- ]);
- 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);
- if (!r.ok) expect(r.error).toMatch(/isn't in this bearer/i);
- expect(setProjectGoogleAdsAccountMock).not.toHaveBeenCalled();
- });
-
- it("rejects when project doesn't exist", async () => {
- getProjectMock.mockReturnValueOnce(null);
- const r = await setOnboardingAccountAction("missing", "3251706605");
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.error).toMatch(/not found/i);
- expect(mcpRpcMock).not.toHaveBeenCalled();
- });
-
- it("rejects on empty slug or account id", async () => {
- const r1 = await setOnboardingAccountAction("", "3251706605");
- expect(r1.ok).toBe(false);
- const r2 = await setOnboardingAccountAction("acme", "");
- expect(r2.ok).toBe(false);
- });
-
- it("surfaces MCP errors when listing accounts fails during validation", async () => {
- mcpRpcMock.mockResolvedValueOnce({
- ok: false,
- kind: "http_error",
- status: 500,
- });
- const r = await setOnboardingAccountAction("acme", "3251706605");
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.error).toMatch(/couldn't verify/i);
- expect(setProjectGoogleAdsAccountMock).not.toHaveBeenCalled();
- });
-});
-
-// ── Meta Ads ───────────────────────────────────────────────────────
-
-describe("listMetaAdsAccounts", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getMcpConfigMock.mockReturnValue({
- url: "https://notfair.co/api/mcp/meta_ads",
- token: "tok",
- });
- });
-
- it("parses the Meta Graph `data` array shape (id + name)", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult({
- data: [
- { id: "act_111", name: "Brand A" },
- { id: "act_222", name: "Brand B" },
- ],
- }),
- );
- const r = await listMetaAdsAccounts("acme");
- expect(r.ok).toBe(true);
- if (r.ok) {
- expect(r.accounts).toEqual([
- { id: "act_111", name: "Brand A" },
- { id: "act_222", name: "Brand B" },
- ]);
- expect(r.default_account_id).toBeNull();
- }
- });
-
- it("returns shape error when neither `data` nor `accounts` is present", async () => {
- mcpRpcMock.mockResolvedValueOnce(toolCallResult({ foo: "bar" }));
- const r = await listMetaAdsAccounts("acme");
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.kind).toBe("shape");
- });
-
- it("returns mcp_not_configured when no token row exists for the project", async () => {
- getMcpConfigMock.mockReturnValueOnce(null);
- const r = await listMetaAdsAccounts("acme");
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.kind).toBe("mcp_not_configured");
- });
-});
-
-describe("setOnboardingMetaAdsAccountAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getProjectMock.mockReturnValue({
- id: "p-1",
- slug: "acme",
- display_name: "Acme",
- });
- getMcpConfigMock.mockReturnValue({
- url: "https://notfair.co/api/mcp/meta_ads",
- token: "tok",
- });
- });
-
- it("persists the chosen ad-account when it's in the bearer's list", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult({
- data: [
- { id: "act_111", name: "Brand A" },
- { id: "act_222", name: "Brand B" },
- ],
- }),
- );
- setProjectMetaAdsAccountMock.mockReturnValue({
- slug: "acme",
- meta_ads_account_id: "act_222",
- });
- const r = await setOnboardingMetaAdsAccountAction("acme", "act_222");
- expect(r.ok).toBe(true);
- expect(setProjectMetaAdsAccountMock).toHaveBeenCalledWith("acme", "act_222");
- });
-
- it("rejects when the account isn't in the bearer's list (tamper defense)", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult({ data: [{ id: "act_111", name: "Brand A" }] }),
- );
- const r = await setOnboardingMetaAdsAccountAction("acme", "act_evil");
- expect(r.ok).toBe(false);
- expect(setProjectMetaAdsAccountMock).not.toHaveBeenCalled();
- });
-});
-
-// ── GSC ────────────────────────────────────────────────────────────
-
-describe("listGscProperties", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getMcpConfigMock.mockReturnValue({
- url: "https://notfair.co/api/mcp/google_search_console",
- token: "tok",
- });
- });
-
- it("parses the bare-array shape the actual notfair MCP returns", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult([
- { siteUrl: "sc-domain:notfair.co", permissionLevel: "siteFullUser" },
- { siteUrl: "https://example.com/", permissionLevel: "siteOwner" },
- ]),
- );
- const r = await listGscProperties("acme");
- expect(r.ok).toBe(true);
- if (r.ok) {
- expect(r.properties.map((p) => p.id)).toEqual([
- "sc-domain:notfair.co",
- "https://example.com/",
- ]);
- expect(r.properties[0]!.name).toBe("notfair.co");
- expect(r.properties[1]!.name).toBe("example.com");
- expect(r.properties[0]!.permission).toBe("siteFullUser");
- }
- });
-
- it("parses the Search Console `siteEntry` shape", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult({
- siteEntry: [
- {
- siteUrl: "https://notfair.co/",
- permissionLevel: "siteOwner",
- },
- { siteUrl: "sc-domain:notfair.co", permissionLevel: "siteFullUser" },
- ],
- }),
- );
- const r = await listGscProperties("acme");
- expect(r.ok).toBe(true);
- if (r.ok) {
- expect(r.properties.map((p) => p.id)).toEqual([
- "https://notfair.co/",
- "sc-domain:notfair.co",
- ]);
- // prettyGscName strips scheme + sc-domain prefix.
- expect(r.properties[0]!.name).toBe("notfair.co");
- expect(r.properties[1]!.name).toBe("notfair.co");
- expect(r.properties[0]!.permission).toBe("siteOwner");
- }
- });
-
- it("returns shape error when neither siteEntry nor sites is present", async () => {
- mcpRpcMock.mockResolvedValueOnce(toolCallResult({ foo: "bar" }));
- const r = await listGscProperties("acme");
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.kind).toBe("shape");
- });
-});
-
-describe("setOnboardingGscPropertyAction", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getProjectMock.mockReturnValue({
- id: "p-1",
- slug: "acme",
- display_name: "Acme",
- });
- getMcpConfigMock.mockReturnValue({
- url: "https://notfair.co/api/mcp/google_search_console",
- token: "tok",
- });
- });
-
- it("persists the chosen property when it's in the bearer's list", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult({
- siteEntry: [{ siteUrl: "sc-domain:notfair.co", permissionLevel: "siteOwner" }],
- }),
- );
- setProjectGscPropertyMock.mockReturnValue({
- slug: "acme",
- gsc_property_id: "sc-domain:notfair.co",
- });
- const r = await setOnboardingGscPropertyAction("acme", "sc-domain:notfair.co");
- expect(r.ok).toBe(true);
- expect(setProjectGscPropertyMock).toHaveBeenCalledWith(
- "acme",
- "sc-domain:notfair.co",
- );
- });
-
- it("rejects when the property isn't in the bearer's list", async () => {
- mcpRpcMock.mockResolvedValueOnce(
- toolCallResult({
- siteEntry: [{ siteUrl: "https://other.example/", permissionLevel: "siteUser" }],
- }),
- );
- const r = await setOnboardingGscPropertyAction("acme", "sc-domain:evil.com");
- expect(r.ok).toBe(false);
- expect(setProjectGscPropertyMock).not.toHaveBeenCalled();
- });
-});
-
-afterEach(() => {
- vi.clearAllMocks();
-});
-
-describe("getOnboardingTaskForSkipAction", () => {
- const ONBOARDING_TASK = {
- id: "onboarding-uuid",
- display_id: "acme-0",
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- title: "Learn the project and write PROJECT.md",
- status: "done",
- };
-
- beforeEach(() => {
- getProjectMock.mockReturnValue({
- id: "p1",
- slug: "acme",
- display_name: "Acme",
- archived_at: null,
- google_ads_account_id: null,
- website_url: null,
- codebase_path: null,
- harness_adapter: "codex-local",
- });
- listTasksMock.mockReturnValue([ONBOARDING_TASK]);
- listTokensMock.mockReturnValue([]);
- createTaskMock.mockClear();
- });
-
- it("mints the audit for an X-Ads-only connect (no account picker on that path)", async () => {
- listTokensMock.mockReturnValue([{ server_name: "notfair-xads" }]);
- const r = await getOnboardingTaskForSkipAction("acme");
- expect(r.ok).toBe(true);
- expect(createTaskMock).toHaveBeenCalledWith(
- expect.objectContaining({
- agent_id: "acme-cmo-greg",
- title: expect.stringContaining("Audit the connected ad platforms"),
- }),
- );
- // Onboarding task is terminal → the freshly minted audit is surfaced.
- if (r.ok) expect(r.task_display_id).toBe("acme-1");
- });
-
- it("creates no audit on a true skip (nothing connected)", async () => {
- const r = await getOnboardingTaskForSkipAction("acme");
- expect(r.ok).toBe(true);
- expect(createTaskMock).not.toHaveBeenCalled();
- if (r.ok) expect(r.task_display_id).toBe("acme-0");
- });
-
- it("does not double-create when an audit already exists", async () => {
- listTokensMock.mockReturnValue([{ server_name: "notfair-googleads" }]);
- listTasksMock.mockReturnValue([
- ONBOARDING_TASK,
- {
- id: "audit-uuid",
- display_id: "acme-9",
- project_slug: "acme",
- agent_id: "acme-cmo-greg",
- title: "Audit the connected ad platforms and propose a starter playbook",
- status: "proposed",
- },
- ]);
- const r = await getOnboardingTaskForSkipAction("acme");
- expect(r.ok).toBe(true);
- expect(createTaskMock).not.toHaveBeenCalled();
- if (r.ok) expect(r.task_display_id).toBe("acme-9");
- });
-});
diff --git a/notfair-cmo/src/server/onboarding/agent-mcp-blocker.test.ts b/notfair-cmo/src/server/onboarding/agent-mcp-blocker.test.ts
deleted file mode 100644
index 5c74ee39..00000000
--- a/notfair-cmo/src/server/onboarding/agent-mcp-blocker.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-
-const findMcpTokenMock = vi.fn();
-vi.mock("@/server/mcp/tokens", () => ({
- findMcpToken: (...args: unknown[]) => findMcpTokenMock(...args),
-}));
-
-const getMcpCatalogMock = vi.fn(() => [
- {
- key: "notfair-googleads",
- display_name: "NotFair Google Ads",
- description: "",
- resource_url: "https://notfair.co/api/mcp/google_ads",
- discovery_url: "",
- source: "preset" as const,
- },
- {
- key: "notfair-metaads",
- display_name: "NotFair Meta Ads",
- description: "",
- resource_url: "https://notfair.co/api/mcp/meta_ads",
- discovery_url: "",
- source: "preset" as const,
- },
-]);
-vi.mock("@/server/mcp-catalog", () => ({
- getMcpCatalog: (...args: unknown[]) => getMcpCatalogMock(...args),
-}));
-
-import { resolveAgentMcpBlocker } from "./agent-mcp-blocker";
-
-beforeEach(() => {
- findMcpTokenMock.mockReset();
-});
-
-describe("resolveAgentMcpBlocker", () => {
- it("returns null when template_key is undefined (cloned/custom agent)", () => {
- expect(resolveAgentMcpBlocker("acme", undefined)).toBeNull();
- expect(findMcpTokenMock).not.toHaveBeenCalled();
- });
-
- it("returns null for CMO — no requires_mcp_key on the template", () => {
- expect(resolveAgentMcpBlocker("acme", "cmo")).toBeNull();
- expect(findMcpTokenMock).not.toHaveBeenCalled();
- });
-
- it("returns a blocker when Google Ads agent's MCP isn't connected", () => {
- findMcpTokenMock.mockReturnValue(null);
- const result = resolveAgentMcpBlocker("acme", "google_ads");
- expect(result).toEqual({
- mcp_key: "notfair-googleads",
- mcp_display_name: "NotFair Google Ads",
- agent_display_name: "Google Ads Specialist",
- });
- expect(findMcpTokenMock).toHaveBeenCalledWith("acme", "notfair-googleads");
- });
-
- it("returns a blocker for Meta Ads when the MCP isn't connected", () => {
- findMcpTokenMock.mockReturnValue(null);
- const result = resolveAgentMcpBlocker("acme", "meta_ads");
- expect(result).toEqual({
- mcp_key: "notfair-metaads",
- mcp_display_name: "NotFair Meta Ads",
- agent_display_name: "Meta Ads Specialist",
- });
- });
-
- it("returns null when the required MCP is connected (token row exists)", () => {
- findMcpTokenMock.mockReturnValue({
- id: "tok-1",
- project_slug: "acme",
- server_name: "notfair-googleads",
- access_token_enc: "secret",
- });
- expect(resolveAgentMcpBlocker("acme", "google_ads")).toBeNull();
- });
-
- it("falls back to the template display_name when the catalog has no matching entry", () => {
- getMcpCatalogMock.mockReturnValueOnce([]); // empty catalog this call
- findMcpTokenMock.mockReturnValue(null);
- const result = resolveAgentMcpBlocker("acme", "google_ads");
- expect(result?.mcp_display_name).toBe("Google Ads Specialist");
- });
-});
diff --git a/notfair-cmo/src/server/onboarding/agent-mcp-blocker.ts b/notfair-cmo/src/server/onboarding/agent-mcp-blocker.ts
deleted file mode 100644
index 08faead9..00000000
--- a/notfair-cmo/src/server/onboarding/agent-mcp-blocker.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { templateForKey } from "@/server/agent-templates";
-import { findMcpToken } from "@/server/mcp/tokens";
-import { getMcpCatalog } from "@/server/mcp-catalog";
-import type { AgentTemplateKey } from "@/server/agent-templates";
-
-/**
- * Pure predicate the agent layout calls to decide whether to render the
- * "Connect <Platform> MCP" blocker instead of the agent's chat/tasks UI.
- *
- * Returns null when the agent can proceed (CMO and other tools-less
- * templates, or specialists whose required MCP is connected). Returns a
- * BlockerInfo when the agent's template declares a `requires_mcp_key`
- * and that token row is missing from `mcp_tokens` for the project.
- *
- * Separate from rendering so the predicate is tractable to unit-test
- * without spinning up React.
- */
-
-export type AgentMcpBlocker = {
- /** Catalog key the user needs to connect (e.g. "notfair-googleads"). */
- mcp_key: string;
- /** Display name shown in the blocker copy ("Google Ads"). */
- mcp_display_name: string;
- /** Agent display label for the secondary line ("the Meta Ads agent"). */
- agent_display_name: string;
-};
-
-export function resolveAgentMcpBlocker(
- project_slug: string,
- template_key: AgentTemplateKey | undefined,
-): AgentMcpBlocker | null {
- if (!template_key) return null;
- const template = templateForKey(template_key);
- if (!template?.requires_mcp_key) return null;
-
- const token = findMcpToken(project_slug, template.requires_mcp_key);
- if (token) return null;
-
- // Pull the display name from the catalog so the blocker calls the
- // connector by the same label the Connections page uses (the catalog
- // is the source of truth — templates only carry the catalog *key*).
- const catalog = getMcpCatalog(project_slug);
- const entry = catalog.find((c) => c.key === template.requires_mcp_key);
- return {
- mcp_key: template.requires_mcp_key,
- mcp_display_name: entry?.display_name ?? template.display_name,
- agent_display_name: template.display_name,
- };
-}
diff --git a/notfair-cmo/src/server/onboarding/cmo-task-brief.ts b/notfair-cmo/src/server/onboarding/cmo-task-brief.ts
deleted file mode 100644
index 53e97007..00000000
--- a/notfair-cmo/src/server/onboarding/cmo-task-brief.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-/**
- * 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.",
- "",
- "Do NOT write anything about which ad platforms / accounts are",
- "connected — this task runs while the user is still connecting them,",
- "so any claim you make goes stale immediately. The platform injects",
- "live connection facts into every task assignment; PROJECT.md is for",
- "the business, not the plumbing.",
- "",
- "## 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 the
- * audit IS a task, and it covers EVERY connected ads platform (Google,
- * Meta, X) — the kickoff message's platform-connections facts block tells
- * the CMO which ones are live. The CMO runs the probes itself via each
- * platform's MCP, writes findings inline, and delegates ongoing work via
- * the notfair-orchestration MCP tools (the same surface the CMO uses for
- * every other planning turn — see agent-templates.ts for the full teaching).
- *
- * Keeping this server-side so the wording stays in lockstep with the CMO
- * system prompt; templated rather than free-form so each new project
- * 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)";
-
- const title = "Audit the connected ad platforms 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 EVERY",
- "connected ads platform — the \"Platform connections\" list in this",
- "assignment is ground truth: audit each ads platform it shows as",
- "connected, skip the rest. Present findings per platform, then",
- "delegate ongoing work to each platform's specialist.",
- "",
- "## 1. Probe each connected platform",
- "",
- "**Google Ads** — use the notfair-googleads MCP `runScript` tool",
- "(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",
- "",
- "**Meta Ads** — use the notfair-metaads MCP `runScript` tool",
- "(`ads.graphParallel`): campaign / ad set / ad listings with 30-day",
- "insights (spend, ROAS, CPM, CTR, frequency); flag learning-limited",
- "ad sets, creative fatigue (rising frequency + falling CTR), and",
- "audience overlap.",
- "",
- "**X Ads** — use the notfair-xads MCP tools: campaigns + line items",
- "with 30-day spend / impressions / engagement, promoted posts, and",
- "funding instruments; flag zero-spend or fully-paused accounts.",
- "",
- "## 2. Classify each platform's archetype",
- "",
- "One per audited platform:",
- "- empty — no enabled/serving campaigns",
- "- no_tracking — campaigns but no conversion tracking",
- "- low_volume — too little traffic/spend to optimize (< ~50 clicks or",
- " < ~$200 / month)",
- "- active — meaningful data to optimize on",
- "",
- "## 3. Report findings to the user (in this reply)",
- "",
- "Markdown, scannable, one section per audited platform (skip findings",
- "that don't exist, don't pad):",
- "- **Snapshot** — 1-2 sentences naming the archetype + spend",
- "- **Wasted spend** — top gaps with $ amounts (search terms on Google;",
- " fatigued creatives / overlapping audiences on Meta; dead line items on X)",
- "- **Quality issues** — low QS keywords, learning-limited ad sets, etc.",
- "- **Budget pacing** — campaigns hitting cap",
- "- **Next steps** — up to 3 concrete actions per platform, tailored to",
- " its 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, delegate it to",
- "THAT platform's specialist (google_ads / meta_ads / x_ads — use",
- "`list_project_agents` to get exact agent ids). Phrase each delegated",
- "brief as \"SET UP a recurring <cadence> ...\" with the cadence explicit",
- "(\"set up a daily 9am Pacific anomaly check on enabled campaigns\",",
- "\"set up a weekly Monday search-term review\") — the specialist",
- "schedules its own cron, and the cron IS the deliverable; a brief that",
- "reads like a one-off gets run once and never again.",
- "",
- "ONLY IF you actually delegated tasks, close with a one-line tail",
- "naming which specialists got work (\"Handed these to your Google Ads",
- 'and X Ads specialists — open their Tasks tabs to follow along.").',
- "When you skipped delegation for a platform (e.g. empty account), say",
- "what would unlock it instead — don't claim a handoff that didn't happen.",
- ].join("\n");
-
- const success_criteria = [
- "Findings reported per connected ads platform as inline markdown;",
- "ongoing work delegated to each platform's specialist (skip a",
- "platform's delegation when its archetype = empty); this audit task",
- "marked done.",
- ].join(" ");
-
- return { title, brief, success_criteria };
-}
diff --git a/notfair-cmo/src/server/onboarding/project-brief.test.ts b/notfair-cmo/src/server/onboarding/project-brief.test.ts
deleted file mode 100644
index 2bbd9c86..00000000
--- a/notfair-cmo/src/server/onboarding/project-brief.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { mkdtempSync } from "node:fs";
-import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
-
-const tmpRoot = mkdtempSync(join(tmpdir(), "notfair-cmo-pb-"));
-process.env.NOTFAIR_CMO_DATA_DIR = tmpRoot;
-
-import {
- deleteProjectBriefDir,
- projectBriefDir,
- projectBriefPath,
- readProjectBrief,
- renameProjectBriefDir,
- writeProjectBrief,
-} from "./project-brief";
-
-describe("project-brief paths + writeProjectBrief + readProjectBrief", () => {
- it("writes + reads back at the canonical path", async () => {
- await writeProjectBrief("alpha", "# Alpha\n\nbody");
- const got = await readProjectBrief("alpha");
- expect(got).toBe("# Alpha\n\nbody");
- const on_disk = await readFile(projectBriefPath("alpha"), "utf8");
- expect(on_disk).toBe("# Alpha\n\nbody");
- });
-
- it("readProjectBrief returns null when missing", async () => {
- expect(await readProjectBrief("never-written")).toBeNull();
- });
-});
-
-describe("deleteProjectBriefDir", () => {
- it("removes the canonical dir + its file", async () => {
- await writeProjectBrief("doomed", "to be deleted");
- await deleteProjectBriefDir("doomed");
- expect(await readProjectBrief("doomed")).toBeNull();
- await expect(stat(projectBriefDir("doomed"))).rejects.toMatchObject({
- code: "ENOENT",
- });
- });
-
- it("is a no-op when the dir doesn't exist", async () => {
- await expect(
- deleteProjectBriefDir("nothing-here-either"),
- ).resolves.toBeUndefined();
- });
-});
-
-describe("renameProjectBriefDir", () => {
- it("moves the dir to the new slug", async () => {
- await writeProjectBrief("from-slug", "original body");
- await renameProjectBriefDir("from-slug", "to-slug");
- expect(await readProjectBrief("from-slug")).toBeNull();
- expect(await readProjectBrief("to-slug")).toBe("original body");
- });
-
- it("is a no-op when old == new", async () => {
- await writeProjectBrief("same-same", "body");
- await renameProjectBriefDir("same-same", "same-same");
- expect(await readProjectBrief("same-same")).toBe("body");
- });
-
- it("is a no-op when the source dir doesn't exist", async () => {
- await expect(
- renameProjectBriefDir("nonexistent-source", "any-dest"),
- ).resolves.toBeUndefined();
- expect(await readProjectBrief("any-dest")).toBeNull();
- });
-
- it("rejects when the destination already exists (slug collision)", async () => {
- // Both dirs exist — rename would clobber the destination silently
- // on POSIX, which is the kind of bug we want to surface upstream.
- await mkdir(projectBriefDir("clobber-src"), { recursive: true });
- await writeFile(
- projectBriefPath("clobber-src"),
- "from",
- "utf8",
- );
- await mkdir(projectBriefDir("clobber-dst"), { recursive: true });
- await writeFile(
- projectBriefPath("clobber-dst"),
- "to",
- "utf8",
- );
- // Node's rename() on POSIX *does* overwrite an empty dir, so this
- // catches the more dangerous "dest has content" case where rename
- // would fail with ENOTEMPTY. The point is the caller learns about
- // it instead of silently losing data.
- await expect(
- renameProjectBriefDir("clobber-src", "clobber-dst"),
- ).rejects.toMatchObject({ code: expect.stringMatching(/ENOTEMPTY|EEXIST/) });
- });
-});
-
-afterAll(async () => {
- void tmpRoot; // keep tmpdir alive across tests; vitest will tear down the process
-});
-beforeAll(() => {
- // no-op; the env was set at import time so the module captured the dir
-});
diff --git a/notfair-cmo/src/server/onboarding/provisioning-progress.ts b/notfair-cmo/src/server/onboarding/provisioning-progress.ts
deleted file mode 100644
index 00417841..00000000
--- a/notfair-cmo/src/server/onboarding/provisioning-progress.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Per-slug in-memory provisioning progress, published by
- * `ensureProjectAgents` and consumed by the onboarding "Setting up your
- * agents…" screen. Each step (CMO, Google Ads, gateway registration)
- * transitions pending → in_progress → done so the UI can render a live
- * checklist instead of a single opaque spinner.
- *
- * Pattern matches `provisioning-state.ts`: globalThis-pinned Map that
- * survives Next.js dev hot-reload. Single-process invariant holds
- * because the CLI launches one Next.js server per user.
- */
-
-export type ProgressStatus = "pending" | "in_progress" | "done" | "failed";
-
-export type ProgressStep = {
- /** Stable key — `cmo`, `google_ads`, `seo`, `gateway`. */
- key: string;
- /** Human label rendered as the row text. */
- label: string;
- status: ProgressStatus;
- error?: string;
-};
-
-export type ProvisioningProgress = {
- slug: string;
- steps: ProgressStep[];
- /** Overall verdict — `running` until every step is terminal. */
- overall: "running" | "done" | "failed";
-};
-
-const GLOBAL_KEY = "__notfair_cmo_provisioning_progress__";
-type GlobalSlot = { store?: Map<string, ProgressStep[]> };
-const slot = globalThis as unknown as Record<string, GlobalSlot>;
-const STORE: Map<string, ProgressStep[]> =
- (slot[GLOBAL_KEY] ??= {}).store ??
- ((slot[GLOBAL_KEY] as GlobalSlot).store = new Map());
-
-export function initProgress(slug: string, steps: ProgressStep[]): void {
- STORE.set(
- slug,
- steps.map((s) => ({ ...s })),
- );
-}
-
-export function updateStep(
- slug: string,
- key: string,
- patch: Partial<Pick<ProgressStep, "status" | "error">>,
-): void {
- const steps = STORE.get(slug);
- if (!steps) return;
- const idx = steps.findIndex((s) => s.key === key);
- if (idx < 0) return;
- steps[idx] = { ...steps[idx]!, ...patch };
-}
-
-export function getProgress(slug: string): ProvisioningProgress | null {
- const steps = STORE.get(slug);
- if (!steps) return null;
- const overall = steps.some((s) => s.status === "failed")
- ? "failed"
- : steps.every((s) => s.status === "done")
- ? "done"
- : "running";
- return { slug, steps: steps.map((s) => ({ ...s })), overall };
-}
-
-export function clearProgress(slug: string): void {
- STORE.delete(slug);
-}
-
-/** Test helper: drain the global Map. */
-export function __resetProgressForTesting(): void {
- STORE.clear();
-}
diff --git a/notfair-cmo/src/server/onboarding/provisioning-state.test.ts b/notfair-cmo/src/server/onboarding/provisioning-state.test.ts
deleted file mode 100644
index 4eb52fcc..00000000
--- a/notfair-cmo/src/server/onboarding/provisioning-state.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-const agentExistsMock = vi.fn<(name: string) => Promise<boolean>>();
-vi.mock("@/server/agent-templates", () => ({
- agentExists: (name: string) => agentExistsMock(name),
-}));
-
-import {
- __resetProvisioningForTesting,
- awaitProvisioning,
- clearProvisioning,
- startProvisioning,
- type ProvisionResult,
-} from "./provisioning-state";
-
-const okResult: ProvisionResult = {
- created: ["acme-cmo", "acme-google-ads"],
- existed: [],
- failed: [],
-};
-
-describe("provisioning-state", () => {
- beforeEach(() => {
- __resetProvisioningForTesting();
- agentExistsMock.mockReset();
- });
-
- afterEach(() => {
- __resetProvisioningForTesting();
- });
-
- describe("happy path (Promise present)", () => {
- it("resolves to ready with the provisioning result", async () => {
- const promise = Promise.resolve(okResult);
- startProvisioning("acme", promise);
- const r = await awaitProvisioning("acme", 5_000);
- expect(r).toEqual({ kind: "ready", via_fallback: false, result: okResult });
- });
-
- it("consumes the map entry after resolution", async () => {
- startProvisioning("acme", Promise.resolve(okResult));
- await awaitProvisioning("acme", 5_000);
- // Second call should hit the cold-start path now.
- agentExistsMock.mockResolvedValue(true);
- const r2 = await awaitProvisioning("acme", 5_000);
- expect(r2).toEqual({ kind: "ready", via_fallback: true });
- });
- });
-
- describe("timeout", () => {
- it("returns timeout when Promise doesn't resolve in time", async () => {
- const slowPromise = new Promise<ProvisionResult>((resolve) =>
- setTimeout(() => resolve(okResult), 200),
- );
- startProvisioning("acme", slowPromise);
- const r = await awaitProvisioning("acme", 50);
- expect(r).toEqual({ kind: "timeout" });
- });
- });
-
- describe("Promise rejection", () => {
- it("returns timeout when the provisioning Promise rejects", async () => {
- const rejected = Promise.reject(new Error("openclaw blew up"));
- // Pre-catch to avoid Node's unhandled-rejection warning in the test runner.
- rejected.catch(() => {});
- startProvisioning("acme", rejected);
- const r = await awaitProvisioning("acme", 5_000);
- expect(r).toEqual({ kind: "timeout" });
- });
- });
-
- describe("clearProvisioning (called from deleteProjectAction)", () => {
- it("drops an in-flight Promise so a re-created slug starts fresh", async () => {
- const slowPromise = new Promise<ProvisionResult>((resolve) =>
- setTimeout(() => resolve(okResult), 1_000),
- );
- startProvisioning("acme", slowPromise);
- clearProvisioning("acme");
- // After clear, the Map is empty for this slug → next awaitProvisioning
- // hits the cold-start fallback path.
- agentExistsMock.mockResolvedValue(false);
- const r = await awaitProvisioning("acme", 5_000);
- expect(r).toEqual({ kind: "no-agents", via_fallback: true });
- });
-
- it("is a no-op when slug isn't in the Map (deleteProjectAction can call defensively)", () => {
- expect(() => clearProvisioning("never-seen")).not.toThrow();
- });
- });
-
- describe("cold-start fallback (Map empty)", () => {
- it("returns ready when both expected agents exist on disk", async () => {
- agentExistsMock.mockImplementation(async (name) =>
- name === "acme-cmo" || name === "acme-google-ads",
- );
- const r = await awaitProvisioning("acme", 5_000);
- expect(r).toEqual({ kind: "ready", via_fallback: true });
- expect(agentExistsMock).toHaveBeenCalledWith("acme-cmo");
- expect(agentExistsMock).toHaveBeenCalledWith("acme-google-ads");
- });
-
- it("returns no-agents when neither agent exists", async () => {
- agentExistsMock.mockResolvedValue(false);
- const r = await awaitProvisioning("acme", 5_000);
- expect(r).toEqual({ kind: "no-agents", via_fallback: true });
- });
-
- it("returns no-agents when only one of the expected agents exists", async () => {
- agentExistsMock.mockImplementation(async (name) => name === "acme-cmo");
- const r = await awaitProvisioning("acme", 5_000);
- expect(r).toEqual({ kind: "no-agents", via_fallback: true });
- });
- });
-});
diff --git a/notfair-cmo/src/server/onboarding/provisioning-state.ts b/notfair-cmo/src/server/onboarding/provisioning-state.ts
deleted file mode 100644
index 63e881ca..00000000
--- a/notfair-cmo/src/server/onboarding/provisioning-state.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { agentExists } from "@/server/agent-templates";
-
-/**
- * In-process map tracking async OpenClaw agent provisioning per project.
- *
- * Why this exists: per D6, `createProjectAction` fires `ensureProjectAgents`
- * without awaiting it so the form returns immediately and the user can begin
- * the OAuth redirect. The audit SSE route (a separate request, after OAuth)
- * still needs to wait until provisioning completes before calling MCP — per
- * D13 with an 8s ceiling. The Promise from the form action's request scope
- * is gone by the time the audit route runs; we stash it here so the audit
- * route can `await` it.
- *
- * Pattern mirrors `server/mcp-pending.ts`: globalThis-pinned map that
- * survives Next.js dev hot-reload. Single-process invariant holds because
- * the CLI launches one Next.js server per user.
- *
- * Cold-start fallback: if the process restarted between form submit and
- * audit start (user closed the tab and returned hours later), the Map is
- * empty. `awaitProvisioning` falls back to a fast filesystem-level check via
- * `agentExists` so the audit can still proceed.
- */
-
-export type ProvisionResult = {
- created: string[];
- existed: string[];
- failed: Array<{ name: string; error: string }>;
-};
-
-export type AwaitResult =
- | { kind: "ready"; via_fallback: boolean; result?: ProvisionResult }
- | { kind: "timeout" }
- | { kind: "no-agents"; via_fallback: true };
-
-const GLOBAL_KEY = "__notfair_cmo_provisioning__";
-type GlobalSlot = { store?: Map<string, Promise<ProvisionResult>> };
-const slot = globalThis as unknown as Record<string, GlobalSlot>;
-const STORE: Map<string, Promise<ProvisionResult>> =
- (slot[GLOBAL_KEY] ??= {}).store ??
- ((slot[GLOBAL_KEY] as GlobalSlot).store = new Map());
-
-/**
- * Register a provisioning Promise for a project slug. The Promise is held
- * until consumed by `awaitProvisioning`; subsequent calls for the same slug
- * after consumption see no entry and fall through to the agentExists
- * fast-check.
- */
-export function startProvisioning(
- slug: string,
- promise: Promise<ProvisionResult>,
-): void {
- STORE.set(slug, promise);
-}
-
-/**
- * Wait for provisioning to complete (Promise resolution) or fall back to
- * checking agentExists if no Promise is registered (cold-start path).
- * Returns:
- * - `ready` with the result when the Promise resolves before the timeout
- * - `ready` via_fallback when the Map was empty but both expected agents
- * are present on disk (process restart, work is done)
- * - `no-agents` when the Map was empty AND agents are NOT present (cold
- * start before any provisioning ever happened — caller should error)
- * - `timeout` when the Promise didn't resolve within timeoutMs
- */
-export async function awaitProvisioning(
- slug: string,
- timeoutMs: number,
-): Promise<AwaitResult> {
- const existing = STORE.get(slug);
-
- if (existing) {
- try {
- const result = await Promise.race([
- existing.then((r) => ({ kind: "ready" as const, result: r })),
- new Promise<{ kind: "timeout" }>((resolve) =>
- setTimeout(() => resolve({ kind: "timeout" }), timeoutMs),
- ),
- ]);
- if (result.kind === "ready") {
- STORE.delete(slug);
- return { kind: "ready", via_fallback: false, result: result.result };
- }
- return { kind: "timeout" };
- } catch {
- // Promise rejected. Treat as "not ready" — caller can decide to retry.
- STORE.delete(slug);
- return { kind: "timeout" };
- }
- }
-
- // Cold-start path: check whether the expected agents exist on disk.
- const cmoId = `${slug}-cmo`;
- const googleAdsId = `${slug}-google-ads`;
- const [hasCmo, hasGoogleAds] = await Promise.all([
- agentExists(cmoId),
- agentExists(googleAdsId),
- ]);
- if (hasCmo && hasGoogleAds) {
- return { kind: "ready", via_fallback: true };
- }
- return { kind: "no-agents", via_fallback: true };
-}
-
-/**
- * Drop any in-flight or stale provisioning Promise for a slug. Called by
- * deleteProjectAction so a deleted project doesn't leak its Promise entry
- * in the global Map (and so re-creating a project with the same slug
- * later starts from a clean state).
- */
-export function clearProvisioning(slug: string): void {
- STORE.delete(slug);
-}
-
-/** Test helper: drain the global Map. Never call in production code. */
-export function __resetProvisioningForTesting(): void {
- STORE.clear();
-}
diff --git a/notfair-cmo/src/server/orchestration/approval-wakeup.ts b/notfair-cmo/src/server/orchestration/approval-wakeup.ts
deleted file mode 100644
index cfa03c72..00000000
--- a/notfair-cmo/src/server/orchestration/approval-wakeup.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { getProject } from "@/server/db/projects";
-import { requireAdapter } from "@/server/adapters/registry";
-import { workspaceDirFor } from "@/server/agents/provisioning";
-import {
- appendTranscriptEvent,
- getOrCreateSession,
- touchSession,
-} from "@/server/sessions";
-import { appendComment, listComments } from "@/server/db/approvals";
-import { getTask, setTaskThreadIfMissing, unblockTask } from "@/server/db/tasks";
-import type { Approval } from "@/types";
-
-import { generateTaskThreadId } from "./task-kickoff";
-
-/**
- * After an approval is resolved (approve / reject / revision_requested),
- * deliver a system message into the task thread so the agent can pick up
- * the decision on its next turn. Mirrors paperclip's heartbeat.wakeup()
- * pattern: the agent doesn't poll — we push a turn with the decision in
- * its context, and side effects (next submit_task_status, follow-up
- * request_approval, etc.) happen via MCP tool calls during the turn.
- *
- * - approved/rejected → task unblocks, agent receives a green/red light.
- * - revision_requested → task stays `blocked`, agent receives the revision
- * note and is expected to call request_approval again with the revised
- * plan.
- *
- * No-op when the approval isn't linked to a task. Free-standing
- * approvals (without task_id) surface only in the inbox.
- */
-export async function wakeTaskOnApprovalResolution(approval: Approval): Promise<void> {
- if (!approval.task_id) return;
- const task = getTask(approval.task_id);
- if (!task) return;
- // Don't restart agents on terminal tasks — the user may have cancelled
- // while the approval was outstanding.
- if (
- task.status === "done" ||
- task.status === "failed" ||
- task.status === "cancelled"
- ) {
- return;
- }
-
- // Approved/rejected both unblock the task. Revision keeps it blocked so
- // the UI continues to show "Waiting on approval" while the agent reworks.
- if (approval.status === "approved" || approval.status === "rejected") {
- unblockTask(task.id);
- }
-
- // Lazy thread mint — usually already set by an earlier kickoff, but a
- // free-floating approval (no prior message yet) won't have one.
- let threadId = task.thread_id;
- if (!threadId) {
- const minted = setTaskThreadIfMissing(task.id, generateTaskThreadId());
- if (minted?.thread_id) threadId = minted.thread_id;
- }
- if (!threadId) {
- console.error(`[approval-wakeup] no thread_id for task ${task.id}`);
- return;
- }
-
- const project = getProject(task.project_slug);
- if (!project) {
- console.error(`[approval-wakeup] project '${task.project_slug}' not found`);
- return;
- }
- const adapter = requireAdapter(project.harness_adapter);
- const session = getOrCreateSession({
- project_slug: project.slug,
- agent_id: task.agent_id,
- label: threadId,
- harness_adapter: project.harness_adapter,
- task_id: task.id,
- });
-
- const message = buildWakeupMessage(approval);
- appendComment({
- approval_id: approval.id,
- author_kind: "system",
- body: `Delivered to ${task.agent_id} on thread ${threadId}.`,
- });
- appendTranscriptEvent(session.id, "user", { text: message, source: "approval-wakeup" });
-
- try {
- for await (const evt of adapter.execute({
- projectSlug: project.slug,
- agentId: task.agent_id,
- workspaceDir: workspaceDirFor(task.agent_id),
- message,
- threadId: session.id,
- harnessSessionId: session.harness_session_id,
- })) {
- if (evt.kind === "session") {
- touchSession(session.id, evt.harnessSessionId);
- continue;
- }
- appendTranscriptEvent(session.id, evt.kind, evt);
- if (evt.kind === "error") throw new Error(evt.message);
- }
- touchSession(session.id);
- } catch (err) {
- console.error(`[approval-wakeup] adapter stream failed for task ${task.id}:`, err);
- }
-}
-
-function buildWakeupMessage(approval: Approval): string {
- const decidedBy =
- approval.decided_by_kind === "user"
- ? "the user"
- : approval.decided_by_kind === "agent"
- ? `another agent (${approval.decided_by_id ?? "unknown"})`
- : approval.decided_by_kind === "policy"
- ? "an auto-approval policy"
- : "an unknown party";
-
- const note = approval.decision_note?.trim();
-
- switch (approval.status) {
- case "approved":
- return [
- `[SYSTEM] Approval #${approval.id.slice(0, 8)} has been APPROVED by ${decidedBy}.`,
- `Action: ${approval.action_summary}`,
- note ? `Note: ${note}` : null,
- "",
- "You may now proceed with the action. When you're finished, call the `submit_task_status` MCP tool with status `done` (or `working` if you're posting an interim update). Do NOT invent new status values.",
- ]
- .filter(Boolean)
- .join("\n");
- case "rejected":
- return [
- `[SYSTEM] Approval #${approval.id.slice(0, 8)} has been REJECTED by ${decidedBy}.`,
- `Action: ${approval.action_summary}`,
- note ? `Reason: ${note}` : null,
- "",
- "Do NOT perform the rejected action. Decide whether to propose an alternative or stop here. Either way, call the `submit_task_status` MCP tool — use status `done` if you have nothing further to do, or `working` if you're proposing an alternative. The valid statuses are exactly: working, done, blocked, failed.",
- ]
- .filter(Boolean)
- .join("\n");
- case "revision_requested":
- return [
- `[SYSTEM] Approval #${approval.id.slice(0, 8)} needs revision per ${decidedBy}.`,
- `Action: ${approval.action_summary}`,
- note ? `Feedback: ${note}` : "Feedback: (no note left — re-read the request and propose a refined version)",
- "",
- "Re-evaluate the request given the feedback, then call the notfair-orchestration `request_approval` MCP tool again with the revised plan. Keep status `working` via `submit_task_status` in the meantime. Do NOT emit pseudo-XML blocks.",
- ]
- .filter(Boolean)
- .join("\n");
- default:
- return `[SYSTEM] Approval #${approval.id.slice(0, 8)} resolved (${approval.status}). Continue.`;
- }
-}
-
-/** Re-export for tests / future code that wants the inbox thread. */
-export { listComments };
diff --git a/notfair-cmo/src/server/orchestration/handlers.test.ts b/notfair-cmo/src/server/orchestration/handlers.test.ts
deleted file mode 100644
index af26eee1..00000000
--- a/notfair-cmo/src/server/orchestration/handlers.test.ts
+++ /dev/null
@@ -1,730 +0,0 @@
-import Database from "better-sqlite3";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { MIGRATIONS } from "@/server/db/migrations";
-
-let testDb: Database.Database;
-
-vi.mock("@/server/db/db", () => ({
- getDb: () => testDb,
- getDbPath: () => ":memory:",
-}));
-
-vi.mock("@/server/agent-meta", () => ({
- listProjectAgents: vi.fn(async (slug: string) => [
- {
- agent_id: `${slug}-cmo`,
- slug: "cmo",
- display_name: "CMO",
- description: "Chief Marketing Officer.",
- template_key: "cmo",
- is_template_default: true,
- },
- {
- agent_id: `${slug}-google-ads`,
- slug: "google-ads",
- display_name: "Google Ads",
- description: "Google Ads specialist.",
- template_key: "google_ads",
- is_template_default: true,
- },
- ]),
-}));
-
-// Most handler tests don't need run-task; mock it so the dynamic import in
-// handleCreateTask doesn't reach OpenClaw.
-vi.mock("./run-task", () => ({
- startTaskIfProposed: (task: { id: string; status: string }) => ({
- ...task,
- status: "working",
- }),
-}));
-
-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) =>
- `${slug}-${key.replace(/_/g, "-")}`,
- templateForKey: (k: string) =>
- k === "google_ads"
- ? { key: "google_ads", display_name: "Google Ads" }
- : k === "cmo"
- ? { key: "cmo", display_name: "CMO" }
- : undefined,
- 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,
- handleGetProject,
- handleGetTask,
- handleListApprovalActionTypes,
- handleListMyApprovals,
- handleListMyTasks,
- handleListPendingApprovals,
- handleListProjectAgents,
- handleListTaskComments,
- handleListTaskStatuses,
- handleListTasks,
- handleUpdateTask,
-} from "./handlers";
-import { createTask } from "@/server/db/tasks";
-import { createApproval } from "@/server/db/approvals";
-import { logAgentAction } from "@/server/db/agent-actions";
-
-function createTestDb(): Database.Database {
- const db = new Database(":memory:");
- db.pragma("foreign_keys = ON");
- for (const m of MIGRATIONS) db.exec(m.sql);
- return db;
-}
-
-function seedProject(slug: string) {
- testDb
- .prepare(
- "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
- )
- .run(`p-${slug}`, slug, slug, "2026-05-20T00:00:00Z");
-}
-
-beforeEach(() => {
- testDb = createTestDb();
- seedProject("demo");
- seedProject("other");
-});
-
-afterEach(() => {
- testDb.close();
-});
-
-describe("handleGetTask", () => {
- it("returns the task when project_slug matches", () => {
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- brief: "do x",
- title: "T1",
- });
- const r = handleGetTask(
- { task_id: t.id },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok && r.data.id).toBe(t.id);
- });
-
- it("rejects cross-project reads", () => {
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- brief: "do x",
- });
- const r = handleGetTask(
- { task_id: t.id },
- { project_slug: "other", agent_id: "other-google-ads" },
- );
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.error).toMatch(/Cross-project/);
- });
-
- it("returns ok:false for unknown task_id", () => {
- const r = handleGetTask(
- { task_id: "nope" },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok).toBe(false);
- });
-});
-
-describe("handleTaskStatus — cannot-close-with-pending-approval invariant", () => {
- it("refuses status='done' when the task has a pending approval", async () => {
- const { handleTaskStatus } = await import("./handlers");
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- brief: "x",
- });
- testDb.prepare("UPDATE tasks SET status='blocked' WHERE id = ?").run(t.id);
- createApproval({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- task_id: t.id,
- action_summary: "Pause keyword",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const r = handleTaskStatus(
- { task_id: t.id, status: "done" },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.error).toMatch(/unresolved approval/i);
- // Task should NOT have been flipped to succeeded.
- const after = testDb
- .prepare("SELECT status FROM tasks WHERE id = ?")
- .get(t.id) as { status: string };
- expect(after.status).toBe("blocked");
- });
-
- it("allows status='failed' even with pending approvals (bail-out hatch)", async () => {
- const { handleTaskStatus } = await import("./handlers");
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- brief: "x",
- });
- testDb.prepare("UPDATE tasks SET status='blocked' WHERE id = ?").run(t.id);
- createApproval({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- task_id: t.id,
- action_summary: "x",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const r = handleTaskStatus(
- { task_id: t.id, status: "failed", summary: "user is unreachable" },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok).toBe(true);
- if (r.ok) expect(r.data.status).toBe("failed");
- });
-
- it("allows status='done' once the approval is resolved", async () => {
- const { handleTaskStatus } = await import("./handlers");
- const { resolveApproval } = await import("@/server/db/approvals");
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- brief: "x",
- });
- testDb.prepare("UPDATE tasks SET status='blocked' WHERE id = ?").run(t.id);
- const a = createApproval({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- task_id: t.id,
- action_summary: "x",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- resolveApproval(a.id, "approved");
- const r = handleTaskStatus(
- { task_id: t.id, status: "done", summary: "shipped" },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok && r.data.status).toBe("done");
- });
-
- it("refuses updates to terminal tasks with an instructive error (no silent no-op)", async () => {
- const { handleTaskStatus } = await import("./handlers");
- for (const terminal of ["cancelled", "failed", "done"] as const) {
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- brief: "x",
- });
- testDb.prepare("UPDATE tasks SET status=? WHERE id = ?").run(terminal, t.id);
- const r = handleTaskStatus(
- { task_id: t.id, status: "working" },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- // The old behavior returned ok:true here — the agent "restarted" a
- // cancelled task, saw success, and narrated progress the DB never
- // recorded. The error must name the terminal status and point the
- // agent at create_task instead.
- expect(r.ok).toBe(false);
- if (!r.ok) {
- expect(r.error).toContain(terminal);
- expect(r.error).toContain("create_task");
- }
- const after = testDb
- .prepare("SELECT status FROM tasks WHERE id = ?")
- .get(t.id) as { status: string };
- expect(after.status).toBe(terminal);
- }
- });
-});
-
-describe("handleListMyTasks", () => {
- it("returns only in-flight tasks by default, filtered to this project + agent", () => {
- createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a", title: "A" });
- const t2 = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "b", title: "B" });
- testDb.prepare("UPDATE tasks SET status='done' WHERE id = ?").run(t2.id);
- createTask({ project_slug: "demo", agent_id: "demo-seo", brief: "not mine" });
- createTask({ project_slug: "other", agent_id: "other-google-ads", brief: "other proj" });
-
- const r = handleListMyTasks(
- {},
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.map((t) => t.title).sort()).toEqual(["A"]);
- });
-
- it("status='all' returns terminal + in-flight", () => {
- createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a", title: "A" });
- const t2 = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "b", title: "B" });
- testDb.prepare("UPDATE tasks SET status='done' WHERE id = ?").run(t2.id);
-
- const r = handleListMyTasks(
- { status: "all" },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok && r.data.length).toBe(2);
- });
-
- it("status='done' narrows", () => {
- const t1 = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a" });
- testDb.prepare("UPDATE tasks SET status='done' WHERE id = ?").run(t1.id);
- createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "b" });
-
- const r = handleListMyTasks(
- { status: "done" },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(r.ok && r.data.length).toBe(1);
- });
-});
-
-describe("handleListTasks", () => {
- it("returns all project tasks regardless of agent", () => {
- createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "a" });
- createTask({ project_slug: "demo", agent_id: "demo-seo", brief: "b" });
- createTask({ project_slug: "other", agent_id: "other-seo", brief: "c" });
- const r = handleListTasks(
- {},
- { project_slug: "demo", agent_id: "" },
- );
- expect(r.ok && r.data.length).toBe(2);
- });
-});
-
-describe("handleUpdateTask", () => {
- it("patches the requested fields and logs an action", () => {
- const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "old", title: "Old" });
- const r = handleUpdateTask(
- { task_id: t.id, title: "New", brief: "fresh" },
- { project_slug: "demo", agent_id: "demo-cmo" },
- );
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.title).toBe("New");
- expect(r.data.brief).toBe("fresh");
- const log = testDb
- .prepare("SELECT action_type FROM agent_actions WHERE task_id = ?")
- .all(t.id) as Array<{ action_type: string }>;
- expect(log.some((l) => l.action_type === "task_updated")).toBe(true);
- });
-
- it("rejects updates with no fields", () => {
- const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
- const r = handleUpdateTask(
- { task_id: t.id },
- { project_slug: "demo", agent_id: "demo-cmo" },
- );
- expect(r.ok).toBe(false);
- });
-
- it("rejects cross-project updates", () => {
- const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
- const r = handleUpdateTask(
- { task_id: t.id, title: "z" },
- { project_slug: "other", agent_id: "other-cmo" },
- );
- expect(r.ok).toBe(false);
- });
-});
-
-describe("handleCancelTask", () => {
- it("flips a running task to cancelled with reason", () => {
- const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
- testDb.prepare("UPDATE tasks SET status='working' WHERE id = ?").run(t.id);
- const r = handleCancelTask(
- { task_id: t.id, reason: "no longer needed" },
- { project_slug: "demo", agent_id: "demo-cmo" },
- );
- expect(r.ok && r.data.status).toBe("cancelled");
- expect(r.ok && r.data.error_message).toBe("no longer needed");
- });
-
- it("is a no-op on already-terminal tasks", () => {
- const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
- testDb.prepare("UPDATE tasks SET status='done' WHERE id = ?").run(t.id);
- const r = handleCancelTask(
- { task_id: t.id },
- { project_slug: "demo", agent_id: "demo-cmo" },
- );
- expect(r.ok && r.data.status).toBe("done");
- });
-});
-
-describe("handleGetProject + handleListProjectAgents", () => {
- it("returns the project metadata for the caller's project", () => {
- const r = handleGetProject({}, { project_slug: "demo", agent_id: "" });
- expect(r.ok && r.data.slug).toBe("demo");
- });
-
- it("listProjectAgents returns the seeded mock", async () => {
- const r = await handleListProjectAgents({}, { project_slug: "demo", agent_id: "" });
- expect(r.ok && r.data.map((a) => a.slug)).toEqual(["cmo", "google-ads"]);
- });
-});
-
-describe("handleListTaskComments", () => {
- it("returns task_comment rows scoped to the task", () => {
- const t = createTask({ project_slug: "demo", agent_id: "demo-google-ads", brief: "x" });
- logAgentAction({
- project_slug: "demo",
- agent_id: "demo-cmo",
- task_id: t.id,
- action_type: "task_comment",
- summary: "first",
- });
- logAgentAction({
- project_slug: "demo",
- agent_id: "demo-cmo",
- task_id: t.id,
- action_type: "task_done", // not a comment
- summary: "should be filtered",
- });
- const r = handleListTaskComments(
- { task_id: t.id },
- { project_slug: "demo", agent_id: "demo-cmo" },
- );
- expect(r.ok && r.data.map((c) => c.summary)).toEqual(["first"]);
- });
-});
-
-describe("handleGetApproval + handleListMyApprovals + handleListPendingApprovals", () => {
- it("returns the approval and filters by agent for list_my_approvals", () => {
- const a1 = createApproval({
- project_slug: "demo",
- agent_id: "demo-google-ads",
- action_summary: "raise bid",
- action_type: "bid_change",
- cost_estimate_usd: 10,
- payload: {},
- });
- createApproval({
- project_slug: "demo",
- agent_id: "demo-seo",
- action_summary: "publish",
- action_type: "content_publishing",
- cost_estimate_usd: 0,
- payload: {},
- });
-
- const got = handleGetApproval(
- { approval_id: a1.id },
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(got.ok && got.data.id).toBe(a1.id);
-
- const mine = handleListMyApprovals(
- {},
- { project_slug: "demo", agent_id: "demo-google-ads" },
- );
- expect(mine.ok && mine.data.length).toBe(1);
- expect(mine.ok && mine.data[0]!.agent_id).toBe("demo-google-ads");
-
- const pending = handleListPendingApprovals(
- {},
- { project_slug: "demo", agent_id: "" },
- );
- expect(pending.ok && pending.data.length).toBe(2);
- });
-
- it("rejects cross-project get_approval", () => {
- const a = createApproval({
- project_slug: "demo",
- agent_id: "demo-cmo",
- action_summary: "x",
- action_type: "other",
- cost_estimate_usd: 0,
- payload: {},
- });
- const r = handleGetApproval(
- { approval_id: a.id },
- { project_slug: "other", agent_id: "" },
- );
- expect(r.ok).toBe(false);
- });
-});
-
-describe("enum discovery handlers", () => {
- it("list_task_statuses returns 7 entries with transitions", () => {
- const r = handleListTaskStatuses();
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.map((s) => s.value).sort()).toEqual(
- ["approved", "blocked", "cancelled", "failed", "proposed", "working", "done"].sort(),
- );
- const succeeded = r.data.find((s) => s.value === "done")!;
- expect(succeeded.terminal).toBe(true);
- expect(succeeded.next).toEqual([]);
- const running = r.data.find((s) => s.value === "working")!;
- expect(running.terminal).toBe(false);
- expect(running.next).toContain("blocked");
- expect(running.next).toContain("done");
- });
-
- it("list_approval_action_types marks cost-required types", () => {
- const r = handleListApprovalActionTypes();
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- const spend = r.data.find((a) => a.value === "spend")!;
- expect(spend.cost_estimate_required).toBe(true);
- const content = r.data.find((a) => a.value === "content_publishing")!;
- expect(content.cost_estimate_required).toBe(false);
- });
-});
-
-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
- });
-});
-
-describe("handleAskUser — ask_user_question", () => {
- it("persists a Question row with parsed options and parks the task in blocked", async () => {
- const { handleAskUser } = await import("./handlers");
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-cmo",
- brief: "x",
- });
- const r = handleAskUser(
- {
- question: "Which channel first?",
- task_id: t.id,
- options: " Google Ads , Meta ,, TikTok ",
- },
- { project_slug: "demo", agent_id: "demo-cmo" },
- );
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.question_id).toMatch(/[0-9a-f-]{36}/);
- expect(r.data.options).toEqual(["Google Ads", "Meta", "TikTok"]);
-
- // Row persisted with status='pending' and options serialized.
- const row = testDb
- .prepare("SELECT status, options_json, task_id FROM questions WHERE id = ?")
- .get(r.data.question_id) as {
- status: string;
- options_json: string;
- task_id: string | null;
- };
- expect(row.status).toBe("pending");
- expect(row.task_id).toBe(t.id);
- expect(JSON.parse(row.options_json)).toEqual([
- "Google Ads",
- "Meta",
- "TikTok",
- ]);
-
- // Task transitioned to blocked.
- const taskAfter = testDb
- .prepare("SELECT status FROM tasks WHERE id = ?")
- .get(t.id) as { status: string };
- expect(taskAfter.status).toBe("blocked");
- });
-
- it("does not block when there's no task_id (free-standing question)", async () => {
- const { handleAskUser } = await import("./handlers");
- const r = handleAskUser(
- { question: "What's your timezone?" },
- { project_slug: "demo", agent_id: "demo-cmo" },
- );
- expect(r.ok).toBe(true);
- if (!r.ok) return;
- expect(r.data.task_id).toBeNull();
- const row = testDb
- .prepare("SELECT task_id FROM questions WHERE id = ?")
- .get(r.data.question_id) as { task_id: string | null };
- expect(row.task_id).toBeNull();
- });
-
- it("rejects cross-project task references", async () => {
- const { handleAskUser } = await import("./handlers");
- const t = createTask({
- project_slug: "demo",
- agent_id: "demo-cmo",
- brief: "x",
- });
- const r = handleAskUser(
- { question: "?", task_id: t.id },
- { project_slug: "other", agent_id: "other-cmo" },
- );
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.error).toMatch(/Cross-project/);
- });
-});
diff --git a/notfair-cmo/src/server/orchestration/handlers.ts b/notfair-cmo/src/server/orchestration/handlers.ts
deleted file mode 100644
index 04220f2d..00000000
--- a/notfair-cmo/src/server/orchestration/handlers.ts
+++ /dev/null
@@ -1,847 +0,0 @@
-import {
- agentExists,
- templateForKey,
- type AgentTemplateKey,
-} from "@/server/agent-templates";
-import { listProjectAgents } from "@/server/agent-meta";
-import { listAgentActions, logAgentAction } from "@/server/db/agent-actions";
-import {
- createApproval,
- getApproval,
- listActionableApprovals,
- listApprovalsForTask,
-} from "@/server/db/approvals";
-import { createQuestion } from "@/server/db/questions";
-import { getDb } from "@/server/db/db";
-import { getProject } from "@/server/db/projects";
-import {
- clearBlockerAndPromote,
- createTask,
- getTask,
- listTasks,
- listTasksBlockedBy,
- listTasksByAgent,
- markTaskBlocked,
- unblockTask,
- updateTask,
-} from "@/server/db/tasks";
-import type {
- AgentAction,
-} from "@/server/db/agent-actions";
-import type {
- Approval,
- Project,
- Task,
- TaskStatus,
-} from "@/types";
-
-/**
- * Shared orchestration handlers. Both the legacy text-block parser
- * (`process-blocks.ts`) and the MCP server tools (`mcp-server/tools.ts`)
- * dispatch through these so the two entry points stay in sync — same
- * validation, same logging, same side effects.
- *
- * Inputs are already-parsed/validated payloads (schema enforcement happens
- * upstream — regex in the block parser, zod in the MCP layer). Context
- * carries the caller's identity which the handler uses for authorization
- * checks (cross-project rejection, assignee-only updates).
- *
- * Return shape is the `HandlerResult` discriminated union so callers can
- * surface failures consistently — the MCP layer maps `ok: false` to the
- * tool-call `isError: true` envelope; the block parser maps it to an
- * `outcome.errors[]` entry.
- */
-
-export type HandlerContext = {
- /** Project the caller is operating in. */
- project_slug: string;
- /** Caller's agent_id (the one making the change). */
- agent_id: string;
-};
-
-export type HandlerResult<T> =
- | { ok: true; data: T }
- | { ok: false; error: string };
-
-const TASK_STATUS_ENUM = ["working", "done", "blocked", "failed"] as const;
-export type TaskStatusValue = (typeof TASK_STATUS_ENUM)[number];
-
-const APPROVAL_ACTION_TYPES = [
- "spend",
- "content_publishing",
- "new_channel",
- "bid_change",
- "audience_change",
- "other",
-] as const;
-export type ApprovalActionType = (typeof APPROVAL_ACTION_TYPES)[number];
-
-export {
- TASK_STATUS_ENUM as TASK_STATUS_VALUES,
- APPROVAL_ACTION_TYPES as APPROVAL_ACTION_TYPE_VALUES,
-};
-
-// ── create_task ────────────────────────────────────────────────────────
-
-export type CreateTaskInput = {
- title: string;
- /** Template key (e.g. `google_ads`). Normalized through templateForKey. */
- assignee: string;
- brief: string;
- success_criteria?: string;
-};
-
-export async function handleCreateTask(
- input: CreateTaskInput,
- ctx: HandlerContext,
-): Promise<HandlerResult<Task>> {
- const template = templateForKey(input.assignee);
- if (!template) {
- return { ok: false, error: `Unknown assignee template '${input.assignee}'` };
- }
- if (template.key === "cmo") {
- return { ok: false, error: "CMO cannot assign tasks to itself — pick a specialist" };
- }
-
- // Look up the assignee by template_key — agent_ids encode the
- // personal name (e.g. `acme-google-ads-ana`), so we can't synthesize
- // one from the role alone.
- const assigneeEntry = (await listProjectAgents(ctx.project_slug)).find(
- (a) => a.template_key === template.key,
- );
- if (!assigneeEntry || !(await agentExists(assigneeEntry.agent_id))) {
- return {
- ok: false,
- error: `Assignee agent for role '${template.key}' is not provisioned for this project`,
- };
- }
- const assigneeAgentId = assigneeEntry.agent_id;
-
- const task = createTask({
- project_slug: ctx.project_slug,
- agent_id: assigneeAgentId,
- title: input.title,
- brief: input.brief,
- success_criteria: input.success_criteria ?? null,
- assigner_agent_id: ctx.agent_id,
- status: "proposed",
- });
-
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- action_type: "task_created",
- summary: `Created task '${task.title}' for ${template.display_name}.`,
- payload: { task_id: task.id, assignee: assigneeAgentId },
- });
-
- // Auto-start the delegated task. Lazy import keeps the orchestration →
- // run-task → gateway chain out of modules that just want createTask.
- const { startTaskIfProposed } = await import("./run-task");
- const started = startTaskIfProposed(task);
- return { ok: true, data: started };
-}
-
-// ── submit_task_status ──────────────────────────────────────────────────
-
-export type TaskStatusInput = {
- task_id: string;
- status: TaskStatusValue;
- summary?: string;
-};
-
-/** Used by the MCP submit_task_status handler; the text-block path is in
- * process-blocks.ts and shares this logic. */
-export function handleTaskStatus(
- input: TaskStatusInput,
- ctx: HandlerContext | null,
-): HandlerResult<{ task_id: string; status: TaskStatus }> {
- const task = getTask(input.task_id);
- if (!task) {
- return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- }
- // For MCP calls ctx is null (we trust the bearer; status updates are
- // intrinsically agent-scoped via task.agent_id). The block-parser path
- // passes ctx so it can enforce cross-project / wrong-assignee rules.
- if (ctx) {
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project task update rejected: task '${input.task_id}' belongs to '${task.project_slug}' but emitter is in '${ctx.project_slug}'`,
- };
- }
- if (task.agent_id !== ctx.agent_id) {
- return {
- ok: false,
- error: `Only the assignee (${task.agent_id}) can update task '${input.task_id}'; got update from '${ctx.agent_id}'`,
- };
- }
- }
- if (
- task.status === "cancelled" ||
- task.status === "failed" ||
- task.status === "done"
- ) {
- // Terminal statuses never change. This used to return ok:true (a
- // silent no-op so a late status flush after a mid-run user-cancel
- // wouldn't error the turn) — but that lied to the agent: it would
- // "restart" a cancelled task, get success back, and narrate progress
- // the DB never recorded. Refuse loudly and say what to do instead.
- return {
- ok: false,
- error:
- `Task ${task.display_id} is '${task.status}' — a terminal status that cannot change. ` +
- `Do NOT claim this task was restarted or updated. If the work should be redone, ` +
- `create a NEW task via create_task and tell the user that's what you did.`,
- };
- }
-
- // Closing a task that's gated on an unresolved approval is almost always
- // a mistake — the agent thinks "I queued the approval, my work is done"
- // and prematurely marks the task done, orphaning the approval in the
- // inbox. Refuse the transition and tell the agent what's blocking it.
- // The exception is `failed`, which we DO allow even with pending
- // approvals (an agent should be able to bail out of a stuck flow).
- if (input.status === "done") {
- const pendingApprovals = listApprovalsForTask(task.id).filter(
- (a) => a.status === "pending" || a.status === "revision_requested",
- );
- if (pendingApprovals.length > 0) {
- const ids = pendingApprovals.map((a) => a.id.slice(0, 8)).join(", ");
- return {
- ok: false,
- error: `Cannot close task ${task.display_id} — ${pendingApprovals.length} unresolved approval(s) still pending: ${ids}. Stay in 'blocked' until the user resolves them; the platform will wake you up on resolution with the decision in context.`,
- };
- }
- }
-
- // No mapping layer anymore: the agent-facing enum (working/done/blocked/
- // failed) IS the DB enum. Migration 007 unified the vocabularies.
- const newStatus: TaskStatus = input.status;
-
- updateTask(task.id, {
- status: newStatus,
- result: input.summary ? { summary: input.summary } : undefined,
- error_message:
- input.status === "failed"
- ? (input.summary ?? "agent reported failure")
- : null,
- });
-
- logAgentAction({
- project_slug: task.project_slug,
- agent_id: task.agent_id,
- task_id: task.id,
- action_type: `task_${input.status}`,
- summary: input.summary ?? `Task ${input.status}.`,
- payload: { task_id: task.id, status: newStatus, via: ctx ? "block" : "mcp" },
- });
-
- // 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") {
- // Promote dependents from `blocked → proposed` and auto-fire each
- // kickoff so the audit runs in the background even when the user is
- // on another page. Visibility comes from the SHADOW TRANSCRIPT that
- // runTaskKickoffServerSide writes — readTranscriptTail merges it
- // with OpenClaw's buffered JSONL so polling sees events live.
- 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 = {
- task_id: string;
- body: string;
-};
-
-export function handleAddTaskComment(
- input: AddCommentInput,
- ctx: HandlerContext,
-): HandlerResult<{ task_id: string }> {
- const task = getTask(input.task_id);
- if (!task) {
- return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- }
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project comment rejected on task '${input.task_id}'`,
- };
- }
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- task_id: task.id,
- action_type: "task_comment",
- summary: input.body,
- payload: { task_id: task.id },
- });
- return { ok: true, data: { task_id: task.id } };
-}
-
-// ── ask_user_question ──────────────────────────────────────────────────
-
-export type AskUserInput = {
- question: string;
- task_id?: string;
- /** Comma-separated multi-choice hints rendered as buttons in the UI. */
- options?: string;
-};
-
-export function handleAskUser(
- input: AskUserInput,
- ctx: HandlerContext,
-): HandlerResult<{
- question_id: string;
- question: string;
- task_id: string | null;
- options: string[];
-}> {
- let resolvedTaskId: string | null = null;
- if (input.task_id) {
- const task = getTask(input.task_id);
- if (!task) {
- return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- }
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project ask_user rejected on task '${input.task_id}'`,
- };
- }
- resolvedTaskId = task.id;
- }
-
- // Parse comma-separated options into a clean string[] — the tool input
- // is a comma-separated string for ergonomics in the agent template, but
- // the DB and UI use a structured array. Drop empties/whitespace so the
- // UI never renders an empty button.
- const options = (input.options ?? "")
- .split(",")
- .map((s) => s.trim())
- .filter((s) => s.length > 0);
-
- const question = createQuestion({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- task_id: resolvedTaskId,
- prompt: input.question,
- options,
- });
-
- // Park the task in `blocked` so the workspace renders the QuestionCard
- // and the agent doesn't keep running while waiting on a human answer.
- // Mirrors request_approval's blocking behavior.
- if (resolvedTaskId) {
- markTaskBlocked(resolvedTaskId);
- }
-
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- task_id: resolvedTaskId,
- action_type: "ask_user",
- summary: input.question,
- payload: {
- task_id: resolvedTaskId,
- options,
- question_id: question.id,
- },
- });
- return {
- ok: true,
- data: {
- question_id: question.id,
- question: input.question,
- task_id: resolvedTaskId,
- options,
- },
- };
-}
-
-// ── request_approval ────────────────────────────────────────────────────
-
-export type RequestApprovalInput = {
- action_summary: string;
- action_type: ApprovalActionType;
- task_id?: string;
- cost_estimate_usd?: number;
- reasoning?: string;
-};
-
-export async function handleRequestApproval(
- input: RequestApprovalInput,
- ctx: HandlerContext,
-): Promise<HandlerResult<{
- approval_id: string;
- action_type: ApprovalActionType;
- status: string;
- auto_resolved: boolean;
-}>> {
- let resolvedTaskId: string | null = null;
- if (input.task_id) {
- const task = getTask(input.task_id);
- if (!task) {
- return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- }
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project approval rejected on task '${input.task_id}'`,
- };
- }
- resolvedTaskId = task.id;
- }
-
- const approval = createApproval({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- task_id: resolvedTaskId,
- action_summary: input.action_summary,
- action_type: input.action_type,
- cost_estimate_usd: input.cost_estimate_usd ?? 0,
- reasoning: input.reasoning ?? null,
- payload: { task_id: resolvedTaskId },
- });
-
- const autoResolved = approval.decided_by_kind === "policy";
-
- if (resolvedTaskId) {
- if (autoResolved) {
- unblockTask(resolvedTaskId);
- } else {
- markTaskBlocked(resolvedTaskId);
- }
- }
-
- if (autoResolved) {
- void (async () => {
- try {
- const { wakeTaskOnApprovalResolution } = await import("./approval-wakeup");
- await wakeTaskOnApprovalResolution(approval);
- } catch (err) {
- console.error("[request-approval] auto-resolve wake-up failed:", err);
- }
- })();
- }
-
- return {
- ok: true,
- data: {
- approval_id: approval.id,
- action_type: input.action_type,
- status: approval.status,
- auto_resolved: autoResolved,
- },
- };
-}
-
-// ── Read handlers (paperclip-aligned context surface) ──────────────────
-//
-// These let agents ask "what's my task?", "what's pending?", "who can I
-// delegate to?" instead of relying solely on the one-shot kickoff message.
-// Without them, an agent whose context window rotates loses task anchoring.
-
-export function handleGetTask(
- input: { task_id: string },
- ctx: HandlerContext,
-): HandlerResult<Task> {
- const task = getTask(input.task_id);
- if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project read rejected: task '${input.task_id}' belongs to '${task.project_slug}'`,
- };
- }
- return { ok: true, data: task };
-}
-
-export function handleListMyTasks(
- input: { status?: TaskStatus | "in_flight" | "all" },
- ctx: HandlerContext,
-): HandlerResult<Task[]> {
- // "in_flight" = anything not terminal; the common case for an agent asking
- // "what's on my plate?". "all" disables the filter; a specific TaskStatus
- // narrows to that state.
- const status = input.status ?? "in_flight";
- let all: Task[];
- if (status === "in_flight" || status === "all") {
- all = listTasksByAgent(ctx.agent_id);
- } else {
- all = listTasksByAgent(ctx.agent_id, status);
- }
- if (status === "in_flight") {
- const inFlight = new Set<TaskStatus>([
- "proposed",
- "approved",
- "working",
- "blocked",
- ]);
- all = all.filter((t) => inFlight.has(t.status));
- }
- const projectScoped = all.filter((t) => t.project_slug === ctx.project_slug);
- return { ok: true, data: projectScoped };
-}
-
-export function handleListTasks(
- input: { status?: TaskStatus },
- ctx: HandlerContext,
-): HandlerResult<Task[]> {
- const rows = listTasks(ctx.project_slug, input.status);
- return { ok: true, data: rows };
-}
-
-// ── update_task ────────────────────────────────────────────────────────
-
-export type UpdateTaskInput = {
- task_id: string;
- title?: string;
- brief?: string;
- success_criteria?: string;
-};
-
-export function handleUpdateTask(
- input: UpdateTaskInput,
- ctx: HandlerContext,
-): HandlerResult<Task> {
- const task = getTask(input.task_id);
- if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project update rejected on task '${input.task_id}'`,
- };
- }
- if (
- input.title === undefined &&
- input.brief === undefined &&
- input.success_criteria === undefined
- ) {
- return { ok: false, error: "At least one field (title/brief/success_criteria) must be provided." };
- }
- // Patch via raw SQL inline so we don't widen the public updateTask
- // surface (which only supports status/result/error_message) for this
- // one tool. better-sqlite3 is synchronous so the read-after-write is
- // race-free in this process.
- const db = getDb();
- const now = new Date().toISOString();
- const sets: string[] = ["updated_at = ?"];
- const args: unknown[] = [now];
- if (input.title !== undefined) {
- sets.push("title = ?");
- args.push(input.title);
- }
- if (input.brief !== undefined) {
- sets.push("brief = ?");
- args.push(input.brief);
- }
- if (input.success_criteria !== undefined) {
- sets.push("success_criteria = ?");
- args.push(input.success_criteria);
- }
- args.push(task.id);
- db.prepare(`UPDATE tasks SET ${sets.join(", ")} WHERE id = ?`).run(...args);
- const after = getTask(task.id);
- if (!after) return { ok: false, error: "Task vanished after update." };
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- task_id: task.id,
- action_type: "task_updated",
- summary: "Task fields updated.",
- payload: {
- task_id: task.id,
- fields: Object.fromEntries(
- Object.entries(input).filter(([k, v]) => k !== "task_id" && v !== undefined),
- ),
- },
- });
- return { ok: true, data: after };
-}
-
-// ── cancel_task ────────────────────────────────────────────────────────
-
-export function handleCancelTask(
- input: { task_id: string; reason?: string },
- ctx: HandlerContext,
-): HandlerResult<Task> {
- const task = getTask(input.task_id);
- if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project cancel rejected on task '${input.task_id}'`,
- };
- }
- if (
- task.status === "done" ||
- task.status === "failed" ||
- task.status === "cancelled"
- ) {
- return { ok: true, data: task }; // already terminal — no-op
- }
- updateTask(task.id, {
- status: "cancelled",
- error_message: input.reason ?? null,
- });
- logAgentAction({
- project_slug: ctx.project_slug,
- agent_id: ctx.agent_id,
- task_id: task.id,
- action_type: "task_cancelled",
- summary: input.reason ?? "Task cancelled.",
- payload: { task_id: task.id, reason: input.reason ?? null },
- });
- const after = getTask(task.id);
- if (!after) return { ok: false, error: "Task vanished after cancel." };
- return { ok: true, data: after };
-}
-
-// ── project + agents context ───────────────────────────────────────────
-
-export function handleGetProject(
- _input: Record<string, never>,
- ctx: HandlerContext,
-): HandlerResult<Project> {
- const project = getProject(ctx.project_slug);
- if (!project) return { ok: false, error: `Unknown project '${ctx.project_slug}'` };
- return { ok: true, data: project };
-}
-
-export type ProjectAgentSummary = {
- agent_id: string;
- slug: string;
- display_name: string;
- description: string;
- template_key: string | null;
- is_template_default: boolean;
-};
-
-export async function handleListProjectAgents(
- _input: Record<string, never>,
- ctx: HandlerContext,
-): Promise<HandlerResult<ProjectAgentSummary[]>> {
- const entries = await listProjectAgents(ctx.project_slug);
- return {
- ok: true,
- data: entries.map((e) => ({
- agent_id: e.agent_id,
- slug: e.slug,
- display_name: e.name,
- description: e.description ?? "",
- template_key: e.template_key ?? null,
- is_template_default: Boolean(e.is_template_default),
- })),
- };
-}
-
-// ── activity / comments ────────────────────────────────────────────────
-
-export function handleListTaskComments(
- input: { task_id: string; limit?: number },
- ctx: HandlerContext,
-): HandlerResult<AgentAction[]> {
- const task = getTask(input.task_id);
- if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project read rejected on task '${input.task_id}'`,
- };
- }
- // Comments are stored on the agent_actions log keyed by task_id and
- // action_type. Filter both client-side; a dedicated table is in scope
- // for v1.1 (paperclip parity — see comments in process-blocks.ts).
- const limit = input.limit ?? 50;
- const rows = listAgentActions(ctx.project_slug, 500).filter(
- (a) => a.task_id === task.id && a.action_type === "task_comment",
- );
- return { ok: true, data: rows.slice(0, limit) };
-}
-
-// ── approvals ─────────────────────────────────────────────────────────
-
-export function handleGetApproval(
- input: { approval_id: string },
- ctx: HandlerContext,
-): HandlerResult<Approval> {
- const approval = getApproval(input.approval_id);
- if (!approval) {
- return { ok: false, error: `Unknown approval_id '${input.approval_id}'` };
- }
- if (approval.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project read rejected on approval '${input.approval_id}'`,
- };
- }
- return { ok: true, data: approval };
-}
-
-export function handleListMyApprovals(
- _input: Record<string, never>,
- ctx: HandlerContext,
-): HandlerResult<Approval[]> {
- // Approvals requested by this agent across all states. Caller filters
- // status client-side if needed.
- const rows = listActionableApprovals(ctx.project_slug).filter(
- (a) => a.agent_id === ctx.agent_id,
- );
- return { ok: true, data: rows };
-}
-
-export function handleListPendingApprovals(
- _input: Record<string, never>,
- ctx: HandlerContext,
-): HandlerResult<Approval[]> {
- return { ok: true, data: listActionableApprovals(ctx.project_slug) };
-}
-
-export function handleListApprovalsForTask(
- input: { task_id: string },
- ctx: HandlerContext,
-): HandlerResult<Approval[]> {
- const task = getTask(input.task_id);
- if (!task) return { ok: false, error: `Unknown task_id '${input.task_id}'` };
- if (task.project_slug !== ctx.project_slug) {
- return {
- ok: false,
- error: `Cross-project read rejected on task '${input.task_id}'`,
- };
- }
- return { ok: true, data: listApprovalsForTask(task.id) };
-}
-
-// ── enum discovery ─────────────────────────────────────────────────────
-
-export type TaskStatusInfo = {
- value: TaskStatus;
- description: string;
- terminal: boolean;
- /** Statuses you can transition INTO from this one. Empty for terminal. */
- next: TaskStatus[];
-};
-
-const TASK_STATUS_INFO: TaskStatusInfo[] = [
- { value: "proposed", description: "Task created, awaiting kickoff or user approval.", terminal: false, next: ["approved", "working", "cancelled"] },
- { value: "approved", description: "User approved a guarded task; ready for the assignee to pick up.", terminal: false, next: ["working", "cancelled"] },
- { value: "working", description: "Assignee is actively working.", terminal: false, next: ["blocked", "done", "failed", "cancelled"] },
- { value: "blocked", description: "Waiting on a user decision, an approval, or a missing input.", terminal: false, next: ["working", "done", "failed", "cancelled"] },
- { value: "done", description: "Task complete (terminal).", terminal: true, next: [] },
- { value: "failed", description: "Task could not complete (terminal). error_message has the reason.", terminal: true, next: [] },
- { value: "cancelled", description: "User or CMO cancelled before completion (terminal).", terminal: true, next: [] },
-];
-
-export function handleListTaskStatuses(): HandlerResult<TaskStatusInfo[]> {
- return { ok: true, data: TASK_STATUS_INFO };
-}
-
-const APPROVAL_ACTION_TYPE_INFO: Array<{
- value: ApprovalActionType;
- description: string;
- cost_estimate_required: boolean;
-}> = [
- { value: "spend", description: "Increase or shift advertising spend.", cost_estimate_required: true },
- { value: "content_publishing", description: "Publish public-facing content (landing page, blog post, ad copy).", cost_estimate_required: false },
- { value: "new_channel", description: "Launch a new marketing channel (new ad platform, new geo, etc.).", cost_estimate_required: true },
- { value: "bid_change", description: "Modify keyword bids or bidding strategy.", cost_estimate_required: true },
- { value: "audience_change", description: "Change campaign targeting / audience.", cost_estimate_required: false },
- { value: "other", description: "Any other governed action not covered above.", cost_estimate_required: false },
-];
-
-export function handleListApprovalActionTypes(): HandlerResult<typeof APPROVAL_ACTION_TYPE_INFO> {
- return { ok: true, data: APPROVAL_ACTION_TYPE_INFO };
-}
diff --git a/notfair-cmo/src/server/orchestration/question-wakeup.ts b/notfair-cmo/src/server/orchestration/question-wakeup.ts
deleted file mode 100644
index 9a05b201..00000000
--- a/notfair-cmo/src/server/orchestration/question-wakeup.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { getProject } from "@/server/db/projects";
-import { requireAdapter } from "@/server/adapters/registry";
-import { workspaceDirFor } from "@/server/agents/provisioning";
-import {
- appendTranscriptEvent,
- getOrCreateSession,
- touchSession,
-} from "@/server/sessions";
-import { parseQuestionOptions } from "@/server/db/questions";
-import { getTask, setTaskThreadIfMissing, unblockTask } from "@/server/db/tasks";
-import type { Question } from "@/types";
-
-import { generateTaskThreadId } from "./task-kickoff";
-
-/**
- * After the user answers (or cancels) a question raised by ask_user_question,
- * deliver a [SYSTEM] turn into the task's chat thread so the agent picks up
- * the resolution on its next turn. Mirrors approval-wakeup.ts.
- *
- * - answered → task unblocks, agent receives the question + chosen option +
- * any free-text comment.
- * - cancelled → task STAYS blocked (the user dismissed without resolving).
- * The agent is not woken; the question simply disappears from the
- * workspace and the task remains parked until the agent / user takes
- * the next step.
- *
- * No-op when the question isn't anchored to a task — free-standing asks
- * surface only in the project inbox and never park anything.
- */
-export async function wakeTaskOnQuestionResolution(question: Question): Promise<void> {
- if (!question.task_id) return;
- if (question.status === "cancelled") return;
- if (question.status !== "answered") return;
-
- const task = getTask(question.task_id);
- if (!task) return;
- if (
- task.status === "done" ||
- task.status === "failed" ||
- task.status === "cancelled"
- ) {
- return;
- }
-
- unblockTask(task.id);
-
- // Lazy thread mint so a free-floating ask (no prior message) still has
- // somewhere to deliver the [SYSTEM] turn.
- let threadId = task.thread_id;
- if (!threadId) {
- const minted = setTaskThreadIfMissing(task.id, generateTaskThreadId());
- if (minted?.thread_id) threadId = minted.thread_id;
- }
- if (!threadId) {
- console.error(`[question-wakeup] no thread_id for task ${task.id}`);
- return;
- }
-
- const project = getProject(task.project_slug);
- if (!project) {
- console.error(`[question-wakeup] project '${task.project_slug}' not found`);
- return;
- }
- const adapter = requireAdapter(project.harness_adapter);
- const session = getOrCreateSession({
- project_slug: project.slug,
- agent_id: task.agent_id,
- label: threadId,
- harness_adapter: project.harness_adapter,
- task_id: task.id,
- });
-
- const message = buildAnswerMessage(question);
- appendTranscriptEvent(session.id, "user", { text: message, source: "question-wakeup" });
-
- try {
- for await (const evt of adapter.execute({
- projectSlug: project.slug,
- agentId: task.agent_id,
- workspaceDir: workspaceDirFor(task.agent_id),
- message,
- threadId: session.id,
- harnessSessionId: session.harness_session_id,
- })) {
- if (evt.kind === "session") {
- touchSession(session.id, evt.harnessSessionId);
- continue;
- }
- appendTranscriptEvent(session.id, evt.kind, evt);
- if (evt.kind === "error") throw new Error(evt.message);
- }
- touchSession(session.id);
- } catch (err) {
- console.error(
- `[question-wakeup] adapter stream failed for task ${task.id}:`,
- err,
- );
- }
-}
-
-function buildAnswerMessage(question: Question): string {
- const options = parseQuestionOptions(question);
- const chosen =
- question.answer_option_index != null
- ? (options[question.answer_option_index] ?? null)
- : null;
- const note = question.answer_text?.trim() || null;
-
- // Compose a single "Answer: …" line that's unambiguous no matter how
- // the user replied: option only, free-text only, or both.
- let answerLine: string;
- if (chosen && note) {
- answerLine = `Answer: ${chosen} — ${note}`;
- } else if (chosen) {
- answerLine = `Answer: ${chosen}`;
- } else if (note) {
- answerLine = `Answer: ${note}`;
- } else {
- answerLine = "Answer: (the user submitted an empty response — re-ask if needed)";
- }
-
- return [
- `[SYSTEM] The user answered question #${question.id.slice(0, 8)}.`,
- `Question: ${question.prompt}`,
- answerLine,
- "",
- "The task has been unblocked. Continue your work using this answer. End your turn with `submit_task_status` (working / done / failed / blocked) when appropriate.",
- ].join("\n");
-}
diff --git a/notfair-cmo/src/server/orchestration/run-task.ts b/notfair-cmo/src/server/orchestration/run-task.ts
deleted file mode 100644
index 43fdb995..00000000
--- a/notfair-cmo/src/server/orchestration/run-task.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { claimProposedTask, setTaskThreadIfMissing, updateTask } from "@/server/db/tasks";
-import { getProject } from "@/server/db/projects";
-import { requireAdapter } from "@/server/adapters/registry";
-import { workspaceDirFor } from "@/server/agents/provisioning";
-import {
- getOrCreateSession,
- appendTranscriptEvent,
- touchSession,
-} from "@/server/sessions";
-import type { Task } from "@/types";
-
-import {
- buildTaskKickoffMessage,
- getProjectPlatformFacts,
- generateTaskThreadId,
-} from "./task-kickoff";
-
-/**
- * Idempotent "claim and kickoff" — atomically flips a proposed task to
- * working and fires the server-side kickoff. No-op when the row is already
- * running, terminal, or missing.
- */
-export function startTaskIfProposed(task: Task): Task {
- const claimed = claimProposedTask(task.id);
- if (!claimed) return task;
- void runTaskKickoffServerSide(claimed).catch((err) => {
- console.error("[start-task] kickoff failed:", err);
- });
- return claimed;
-}
-
-/**
- * Server-side kickoff for a task. Dispatches the kickoff message through the
- * project's harness adapter and persists every emitted event to
- * `transcript_events`. The browser tails the same row range over SSE for
- * live render.
- */
-export async function runTaskKickoffServerSide(task: Task): Promise<void> {
- let finalTask = task;
- if (!finalTask.thread_id) {
- const updated = setTaskThreadIfMissing(task.id, generateTaskThreadId());
- if (updated) finalTask = updated;
- if (!finalTask.thread_id) {
- throw new Error(`Failed to assign thread_id for task ${task.id}`);
- }
- }
-
- const project = getProject(finalTask.project_slug);
- if (!project) {
- updateTask(finalTask.id, {
- status: "failed",
- error_message: `Project '${finalTask.project_slug}' not found.`,
- });
- return;
- }
- const adapter = requireAdapter(project.harness_adapter);
-
- const session = getOrCreateSession({
- project_slug: project.slug,
- agent_id: finalTask.agent_id,
- label: finalTask.thread_id,
- harness_adapter: project.harness_adapter,
- task_id: finalTask.id,
- });
-
- const kickoffMessage = buildTaskKickoffMessage(
- finalTask,
- getProjectPlatformFacts(finalTask.project_slug),
- );
- appendTranscriptEvent(session.id, "user", { text: kickoffMessage, source: "kickoff" });
-
- console.log(
- `[run-task] kickoff start task=${finalTask.id} agent=${finalTask.agent_id} thread=${finalTask.thread_id}`,
- );
-
- try {
- for await (const evt of adapter.execute({
- projectSlug: project.slug,
- agentId: finalTask.agent_id,
- workspaceDir: workspaceDirFor(finalTask.agent_id),
- message: kickoffMessage,
- threadId: session.id,
- harnessSessionId: session.harness_session_id,
- })) {
- if (evt.kind === "session") {
- touchSession(session.id, evt.harnessSessionId);
- continue;
- }
- appendTranscriptEvent(session.id, evt.kind, evt);
- if (evt.kind === "error") {
- throw new Error(evt.message);
- }
- }
- touchSession(session.id);
- console.log(`[run-task] kickoff stream done task=${finalTask.id}`);
-
- // The harness turn ended cleanly. If the agent didn't call
- // submit_task_status the task is stuck in `working` and the UI
- // shows a wrong "Wrapping up" spinner forever. Detect that, flip
- // the task to `blocked` with a clear reason so the user can decide
- // whether to retry, take over, or mark done. Best-effort: a stale
- // read is harmless because the orchestration tool path also writes
- // the task status, and our update is gated on status === "working".
- const current = updateTask(finalTask.id, {});
- if (current && current.status === "working") {
- console.warn(
- `[run-task] turn ended but agent did not call submit_task_status (task=${finalTask.id}); marking blocked`,
- );
- updateTask(finalTask.id, {
- status: "blocked",
- error_message:
- "Agent finished its turn without calling submit_task_status. The task is parked — send a follow-up message or mark it done manually.",
- });
- appendTranscriptEvent(session.id, "error", {
- kind: "error",
- message:
- "Turn ended without submit_task_status. Task moved to blocked — open Approvals or send a follow-up message to resume.",
- });
- }
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- console.error(
- `[run-task] kickoff failed task=${finalTask.id} agent=${finalTask.agent_id}: ${message}`,
- );
- updateTask(finalTask.id, {
- status: "failed",
- error_message: message,
- });
- }
-}
diff --git a/notfair-cmo/src/server/orchestration/task-kickoff.test.ts b/notfair-cmo/src/server/orchestration/task-kickoff.test.ts
deleted file mode 100644
index 48cb5e3e..00000000
--- a/notfair-cmo/src/server/orchestration/task-kickoff.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import type { Task } from "@/types";
-
-import {
- buildTaskKickoffMessage,
- formatPlatformFacts,
- type ProjectPlatformFacts,
-} from "./task-kickoff";
-
-function makeTask(overrides: Partial<Task> = {}): Task {
- return {
- id: "task-123",
- display_id: "demo-1",
- project_slug: "demo",
- agent_id: "demo-google-ads",
- title: "Install conversion tracking",
- brief: "Add the Google Ads conversion tag to /thanks.",
- success_criteria: "Tag fires on /thanks and a test conv lands in Google Ads.",
- deadline_iso: null,
- status: "working",
- result_json: null,
- 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,
- };
-}
-
-describe("buildTaskKickoffMessage", () => {
- it("opens with the (task assignment) header so the agent recognizes the system-injected turn", () => {
- const msg = buildTaskKickoffMessage(makeTask());
- expect(msg.startsWith("(task assignment)")).toBe(true);
- });
-
- it("includes the canonical task fields in a stable order", () => {
- const msg = buildTaskKickoffMessage(makeTask());
- // Each piece appears, and the brief comes before success criteria.
- expect(msg).toContain("task_id: task-123");
- expect(msg).toContain("project_slug: demo");
- expect(msg).toContain("agent_id: demo-google-ads");
- expect(msg).toContain("Title: Install conversion tracking");
- expect(msg).toContain("Brief:");
- expect(msg).toContain("Add the Google Ads conversion tag to /thanks.");
- expect(msg).toContain("Success criteria:");
- expect(msg).toContain(
- "Tag fires on /thanks and a test conv lands in Google Ads.",
- );
- expect(msg.indexOf("Brief:")).toBeLessThan(msg.indexOf("Success criteria:"));
- });
-
- it("falls back to '(untitled)' when title is null", () => {
- const msg = buildTaskKickoffMessage(makeTask({ title: null }));
- expect(msg).toContain("Title: (untitled)");
- });
-
- it("omits the Success criteria section entirely when success_criteria is null", () => {
- const msg = buildTaskKickoffMessage(
- makeTask({ success_criteria: null }),
- );
- expect(msg).not.toContain("Success criteria:");
- // Still has the trailing instructions block.
- expect(msg).toContain("Acknowledge this task");
- });
-
- it("tells the agent to actually use its tools, not just describe, and to close out when done", () => {
- const msg = buildTaskKickoffMessage(makeTask());
- expect(msg).toContain("Use your domain tools");
- expect(msg).toContain("don't just describe what you'd do");
- expect(msg).toMatch(/close the task out/i);
- });
-
- it("does NOT re-teach the MCP tool surface — that's the system prompt's job", () => {
- const msg = buildTaskKickoffMessage(makeTask());
- // Schema-shaped lines like `status: "done"` belong in the system prompt;
- // every brief shouldn't duplicate them. Same for the pseudo-XML rule.
- expect(msg).not.toMatch(/status:\s*"done"/);
- expect(msg).not.toMatch(/do NOT emit/i);
- expect(msg).not.toContain("not parsed");
- });
-
- it("returns a multi-line string (joined with \\n, not \\r\\n)", () => {
- const msg = buildTaskKickoffMessage(makeTask());
- expect(msg).not.toContain("\r");
- expect(msg.split("\n").length).toBeGreaterThan(6);
- });
-
- it("preserves multi-line brief content verbatim", () => {
- const brief = "Step 1: import GA4.\nStep 2: map conv to lead.\nStep 3: verify.";
- const msg = buildTaskKickoffMessage(makeTask({ brief }));
- expect(msg).toContain(brief);
- });
-});
-
-describe("platform facts block", () => {
- const facts: ProjectPlatformFacts = {
- website_url: "https://example.com",
- codebase_path: null,
- connected: [
- { label: "Google Ads", detail: "account 7384288909" },
- { label: "X Ads", detail: null },
- ],
- notConnected: ["Meta Ads", "Google Search Console", "Google Analytics"],
- };
-
- it("renders connected platforms with details and NOT-connected ones explicitly", () => {
- const lines = formatPlatformFacts(facts).join("\n");
- expect(lines).toContain("ground truth from the platform database");
- expect(lines).toContain("- Google Ads: connected — account 7384288909");
- expect(lines).toContain("- X Ads: connected");
- expect(lines).toContain("- Meta Ads: NOT connected");
- expect(lines).toContain("- Website: https://example.com");
- expect(lines).not.toContain("Local codebase");
- });
-
- it("kickoff message embeds the facts block between brief and success criteria", () => {
- const msg = buildTaskKickoffMessage(makeTask(), facts);
- expect(msg).toContain("- Google Ads: connected — account 7384288909");
- expect(msg.indexOf("Brief:")).toBeLessThan(msg.indexOf("Google Ads: connected"));
- expect(msg.indexOf("Google Ads: connected")).toBeLessThan(
- msg.indexOf("Success criteria:"),
- );
- });
-
- it("kickoff message omits the block when facts are null/undefined", () => {
- expect(buildTaskKickoffMessage(makeTask(), null)).not.toContain(
- "Platform connections",
- );
- expect(buildTaskKickoffMessage(makeTask())).not.toContain(
- "Platform connections",
- );
- });
-});
diff --git a/notfair-cmo/src/server/orchestration/task-kickoff.ts b/notfair-cmo/src/server/orchestration/task-kickoff.ts
deleted file mode 100644
index 321ec256..00000000
--- a/notfair-cmo/src/server/orchestration/task-kickoff.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import { randomUUID } from "node:crypto";
-
-import { getProject } from "@/server/db/projects";
-import { listProjectMcpTokens } from "@/server/mcp/tokens";
-import type { Task } from "@/types";
-
-/**
- * Generate a UUID for a per-task chat thread. Stable per-call; callers
- * persist it via setTaskThreadIfMissing once they decide to materialize
- * the thread (typically on the first /tasks/[id] page visit, or when
- * approval-wakeup needs to push a system message into a task that's
- * never been opened in the UI).
- */
-export function generateTaskThreadId(): string {
- return randomUUID();
-}
-
-/**
- * Deterministic snapshot of what's ACTUALLY connected for a project,
- * read from the platform DB at kickoff time. Injected into the kickoff
- * message so the agent never has to derive it — a real onboarding run
- * had the CMO write "no ad account attached" into PROJECT.md even
- * though get_project returned the picked account id.
- */
-export interface ProjectPlatformFacts {
- website_url: string | null;
- codebase_path: string | null;
- /** Connected platforms, with the selected account/property when picked. */
- connected: Array<{ label: string; detail: string | null }>;
- /** Recommended platforms with no token — the agent must not assume them. */
- notConnected: string[];
-}
-
-const RECOMMENDED_PLATFORMS: Array<{
- key: string;
- label: string;
- detail?: (p: {
- google_ads_account_id: string | null;
- meta_ads_account_id: string | null;
- gsc_property_id: string | null;
- }) => string | null;
-}> = [
- {
- key: "notfair-googleads",
- label: "Google Ads",
- detail: (p) =>
- p.google_ads_account_id
- ? `account ${p.google_ads_account_id}`
- : "no account picked yet",
- },
- {
- key: "notfair-metaads",
- label: "Meta Ads",
- detail: (p) =>
- p.meta_ads_account_id
- ? `ad account ${p.meta_ads_account_id}`
- : "no ad account picked yet",
- },
- {
- key: "notfair-googlesearchconsole",
- label: "Google Search Console",
- detail: (p) =>
- p.gsc_property_id ? `property ${p.gsc_property_id}` : "no property picked yet",
- },
- { key: "notfair-googleanalytics", label: "Google Analytics" },
- { key: "notfair-xads", label: "X Ads" },
-];
-
-/** Never throws — a facts block is an enhancement, not a gate. */
-export function getProjectPlatformFacts(
- project_slug: string,
-): ProjectPlatformFacts | null {
- try {
- const project = getProject(project_slug);
- if (!project) return null;
- const tokens = new Set(
- listProjectMcpTokens(project_slug).map((t) => t.server_name),
- );
-
- const connected: Array<{ label: string; detail: string | null }> = [];
- const notConnected: string[] = [];
- for (const platform of RECOMMENDED_PLATFORMS) {
- if (tokens.has(platform.key)) {
- connected.push({
- label: platform.label,
- detail: platform.detail?.(project) ?? null,
- });
- tokens.delete(platform.key);
- } else {
- notConnected.push(platform.label);
- }
- }
- // Extras connected via "More tools" (stripe, posthog, custom URLs…).
- for (const key of tokens) {
- connected.push({ label: key, detail: null });
- }
-
- return {
- website_url: project.website_url,
- codebase_path: project.codebase_path,
- connected,
- notConnected,
- };
- } catch {
- return null;
- }
-}
-
-/** Pure formatter — separated so tests don't need a DB. */
-export function formatPlatformFacts(facts: ProjectPlatformFacts): string[] {
- const lines: string[] = [
- "Platform connections (ground truth from the platform database — trust",
- "this over inference). Point-in-time for THIS task only: more platforms",
- "may connect later, so never copy this list into PROJECT.md or other",
- "durable docs:",
- ];
- for (const c of facts.connected) {
- lines.push(`- ${c.label}: connected${c.detail ? ` — ${c.detail}` : ""}`);
- }
- for (const label of facts.notConnected) {
- lines.push(`- ${label}: NOT connected`);
- }
- if (facts.website_url) lines.push(`- Website: ${facts.website_url}`);
- if (facts.codebase_path) lines.push(`- Local codebase: ${facts.codebase_path}`);
- return lines;
-}
-
-/**
- * Build the hidden kickoff message the assignee receives on first open of
- * a task's per-task chat thread. Carries the brief + operating
- * instructions — the agent has everything it needs to acknowledge and
- * start working without the user typing anything.
- *
- * `facts` (from getProjectPlatformFacts, fetched by the caller at kickoff
- * time) grounds the turn in what's actually connected. Passed in rather
- * than fetched here so the formatter stays pure and testable.
- *
- * Kept server-side (in orchestration/) because the format mirrors what
- * the agent's system prompt expects; changing one without the other
- * desyncs the contract.
- */
-export function buildTaskKickoffMessage(
- task: Task,
- facts?: ProjectPlatformFacts | null,
-): string {
- const lines: string[] = [
- "(task assignment)",
- "",
- `project_slug: ${task.project_slug}`,
- `agent_id: ${task.agent_id}`,
- `task_id: ${task.id}`,
- `Title: ${task.title ?? "(untitled)"}`,
- "",
- "Brief:",
- task.brief,
- "",
- ];
- if (facts) {
- lines.push(...formatPlatformFacts(facts), "");
- }
- if (task.success_criteria) {
- lines.push("Success criteria:", task.success_criteria, "");
- }
- lines.push(
- "Acknowledge this task in 1-2 sentences (what you'll do + roughly how",
- "long), then start working. Use your domain tools to actually do the",
- "thing — don't just describe what you'd do. Close the task out when",
- "you're done.",
- );
- return lines.join("\n");
-}
diff --git a/notfair-cmo/src/server/scheduler/display.ts b/notfair-cmo/src/server/scheduler/display.ts
deleted file mode 100644
index 86451061..00000000
--- a/notfair-cmo/src/server/scheduler/display.ts
+++ /dev/null
@@ -1,347 +0,0 @@
-import { cache } from "react";
-import { CronExpressionParser } from "cron-parser";
-import { getDb } from "@/server/db/db";
-import {
- createScheduledJob,
- deleteScheduledJob,
- listJobRuns,
- setJobEnabled,
- type CreateScheduledJobInput,
- type ScheduledJob,
-} from "./index";
-
-/**
- * UI-facing view of a scheduled job.
- *
- * Shape preserved from the previous OpenClaw-backed `DisplayCron` so pages
- * and components keep rendering without refactoring. `agent_slug` is the
- * project-prefix-stripped agent id used for color lookup; `schedule_raw`
- * mirrors OpenClaw's tagged union so calendar code still works.
- */
-export type CronSchedule = { kind: "cron"; expr: string; tz?: string };
-
-export interface DisplayCron {
- id: string;
- name: string;
- short_name: string;
- agent_id: string;
- agent_slug: string;
- schedule_raw: CronSchedule | undefined;
- schedule_text: string;
- next_run_text: string;
- last_run_text: string;
- status_text: string;
- disabled: boolean;
- message?: string;
- description?: string;
- last_run_at_ms?: number;
- last_status?: string;
- last_error?: string;
- next_run_at_ms?: number;
- created_at_ms?: number;
-}
-
-export interface CronGroup {
- agent: string;
- crons: DisplayCron[];
-}
-
-export interface ProjectCronView {
- project_slug: string;
- groups: CronGroup[];
-}
-
-const NAME_SEPARATOR = "/";
-
-function shortenAgentId(agentId: string, project_slug: string): string {
- const prefix = `${project_slug}-`;
- return agentId.startsWith(prefix) ? agentId.slice(prefix.length) : agentId;
-}
-
-function isoMs(iso: string | null): number | undefined {
- if (!iso) return undefined;
- const t = Date.parse(iso);
- return Number.isFinite(t) ? t : undefined;
-}
-
-function formatSchedule(expr: string): string {
- return expr;
-}
-
-function formatRelativeMs(ms: number | undefined): string {
- if (!ms) return "—";
- const delta = ms - Date.now();
- const abs = Math.abs(delta);
- const seconds = Math.round(abs / 1000);
- if (seconds < 60) return delta > 0 ? `in ${seconds}s` : `${seconds}s ago`;
- const minutes = Math.round(seconds / 60);
- if (minutes < 60) return delta > 0 ? `in ${minutes}m` : `${minutes}m ago`;
- const hours = Math.round(minutes / 60);
- if (hours < 24) return delta > 0 ? `in ${hours}h` : `${hours}h ago`;
- const days = Math.round(hours / 24);
- return delta > 0 ? `in ${days}d` : `${days}d ago`;
-}
-
-function normalizeRunStatus(s: string | undefined): string | undefined {
- if (!s) return undefined;
- if (s === "done") return "ok";
- if (s === "failed") return "error";
- return s;
-}
-
-function jobToDisplay(job: ScheduledJob, project_slug: string): DisplayCron {
- // Most recent run gives us the last_status / last_error fields the UI surfaces.
- const recent = listJobRuns(job.id, 1)[0];
- const lastStatus = normalizeRunStatus(recent?.status);
- const lastError = recent?.error_message ?? undefined;
- const lastRunMs = isoMs(job.last_run_at) ?? (recent ? Date.parse(recent.started_at) : undefined);
- const nextRunMs = isoMs(job.next_run_at);
- const disabled = job.enabled === 0;
- const shortAgent = shortenAgentId(job.agent_id, project_slug);
- return {
- id: job.id,
- name: `${project_slug}${NAME_SEPARATOR}${shortAgent}${NAME_SEPARATOR}${job.name}`,
- short_name: job.name,
- agent_id: job.agent_id,
- agent_slug: shortAgent,
- schedule_raw: { kind: "cron", expr: job.cron_expr },
- schedule_text: formatSchedule(job.cron_expr),
- next_run_text: formatRelativeMs(nextRunMs),
- last_run_text: formatRelativeMs(lastRunMs),
- status_text: disabled ? "disabled" : lastStatus ?? "idle",
- disabled,
- message: job.message,
- last_run_at_ms: lastRunMs,
- last_status: lastStatus ?? undefined,
- last_error: lastError,
- next_run_at_ms: nextRunMs,
- created_at_ms: isoMs(job.created_at),
- };
-}
-
-export const listCronsForProject = cache(
- async (project_slug: string): Promise<ProjectCronView> => {
- const rows = getDb()
- .prepare(
- "SELECT * FROM scheduled_jobs WHERE project_slug = ? ORDER BY created_at DESC",
- )
- .all(project_slug) as ScheduledJob[];
- const byAgent = new Map<string, DisplayCron[]>();
- for (const job of rows) {
- const display = jobToDisplay(job, project_slug);
- const list = byAgent.get(display.agent_slug) ?? [];
- list.push(display);
- byAgent.set(display.agent_slug, list);
- }
- const groups: CronGroup[] = Array.from(byAgent.entries())
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([agent, crons]) => ({ agent, crons }));
- return { project_slug, groups };
- },
-);
-
-/** Per-run history view, preserved from the OpenClaw-backed `CronRun` shape. */
-export interface CronRun {
- run_at_ms: number;
- finished_at_ms: number;
- status: string;
- summary: string;
- error?: string;
- duration_ms?: number;
- session_id?: string;
- model?: string;
- provider?: string;
- usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number };
-}
-
-export function loadCronRuns(cron_id: string, limit = 100): CronRun[] {
- const runs = listJobRuns(cron_id, limit);
- return runs.map((r) => {
- const startedMs = Date.parse(r.started_at);
- const finishedMs = r.finished_at ? Date.parse(r.finished_at) : startedMs;
- return {
- run_at_ms: startedMs,
- finished_at_ms: finishedMs,
- status: normalizeRunStatus(r.status) ?? r.status,
- summary: r.summary ?? "",
- error: r.error_message ?? undefined,
- duration_ms: Number.isFinite(finishedMs - startedMs) ? finishedMs - startedMs : undefined,
- };
- });
-}
-
-/**
- * Find the most recent scheduled tick at or before `at` for a given cron.
- * Used to attribute a run back to its calendar occurrence.
- */
-export function tickAtOrBefore(
- schedule: CronSchedule | undefined,
- at: number,
- lookbackMs = 14 * 24 * 60 * 60 * 1000,
-): number | undefined {
- if (!schedule || schedule.kind !== "cron") return undefined;
- const from = at - lookbackMs;
- try {
- const it = CronExpressionParser.parse(schedule.expr, {
- currentDate: new Date(from),
- endDate: new Date(at + 1),
- tz: schedule.tz ?? "UTC",
- });
- let last: number | undefined;
- for (let i = 0; i < 10_000; i++) {
- try {
- const t = it.next().toDate().getTime();
- if (t > at) break;
- last = t;
- } catch {
- break;
- }
- }
- return last;
- } catch {
- return undefined;
- }
-}
-
-export interface CronOccurrence {
- at: number;
- cron_id: string;
- cron_name: string;
- short_name: string;
- agent_id: string;
- agent_slug: string;
- schedule_text: string;
- run_status?: string;
-}
-
-/** Expand one cron's schedule into occurrences inside [from, until]. */
-export function expandSchedule(
- cron_id: string,
- schedule: CronSchedule | undefined,
- range: { from: number; until: number },
- meta: { name: string; short_name: string; agent_id: string; agent_slug: string; schedule_text: string },
- maxPerCron = 60,
-): CronOccurrence[] {
- if (!schedule || schedule.kind !== "cron") return [];
- const { from, until } = range;
- const out: CronOccurrence[] = [];
- try {
- const it = CronExpressionParser.parse(schedule.expr, {
- currentDate: new Date(from),
- endDate: new Date(until),
- tz: schedule.tz ?? "UTC",
- });
- while (out.length < maxPerCron) {
- try {
- const next = it.next();
- out.push({
- at: next.toDate().getTime(),
- cron_id,
- cron_name: meta.name,
- short_name: meta.short_name,
- agent_id: meta.agent_id,
- agent_slug: meta.agent_slug,
- schedule_text: meta.schedule_text,
- });
- } catch {
- break;
- }
- }
- } catch {
- return [];
- }
- return out;
-}
-
-/** Attach run status to occurrences by mapping each completed run back to its tick. */
-export function annotateOccurrencesWithRunStatus(
- occurrences: CronOccurrence[],
- schedulesByCronId: Map<string, CronSchedule | undefined>,
-): CronOccurrence[] {
- const byCron = new Map<string, CronOccurrence[]>();
- for (const occ of occurrences) {
- const arr = byCron.get(occ.cron_id) ?? [];
- arr.push(occ);
- byCron.set(occ.cron_id, arr);
- }
- for (const [cronId, occs] of byCron) {
- const schedule = schedulesByCronId.get(cronId);
- if (!schedule) continue;
- const runs = loadCronRuns(cronId, 200);
- const statusByTick = new Map<number, string>();
- for (const run of runs) {
- const tick = tickAtOrBefore(schedule, run.run_at_ms);
- if (tick != null && !statusByTick.has(tick)) {
- statusByTick.set(tick, run.status);
- }
- }
- for (const o of occs) {
- const s = statusByTick.get(o.at);
- if (s) o.run_status = s;
- }
- }
- return occurrences;
-}
-
-/** Compatibility no-op — the new scheduler has no subprocess cache to invalidate. */
-export function invalidateCronCache(): void {}
-
-export async function disableCron(id: string): Promise<void> {
- setJobEnabled(id, false);
-}
-
-export async function enableCron(id: string): Promise<void> {
- setJobEnabled(id, true);
-}
-
-export async function removeCron(id: string): Promise<void> {
- deleteScheduledJob(id);
-}
-
-export interface CreateCronInput {
- project_slug: string;
- agent_slug: string;
- agent_full_id: string;
- cron_name: string;
- schedule: { kind: "cron"; expr: string; tz?: string };
- message: string;
- description?: string;
-}
-
-export interface CreateCronResult {
- id: string;
- name: string;
-}
-
-export async function createCron(input: CreateCronInput): Promise<CreateCronResult> {
- const jobInput: CreateScheduledJobInput = {
- project_slug: input.project_slug,
- agent_id: input.agent_full_id,
- name: input.cron_name,
- cron_expr: input.schedule.expr,
- message: input.message,
- enabled: true,
- };
- const job = createScheduledJob(jobInput);
- return {
- id: job.id,
- name: `${input.project_slug}/${input.agent_slug}/${input.cron_name}`,
- };
-}
-
-/** Bucket occurrences into day-aligned arrays starting at `startOfFirstDay`. */
-export function groupOccurrencesByDay(
- occurrences: CronOccurrence[],
- startOfFirstDay: number,
- numDays: number,
-): CronOccurrence[][] {
- const days: CronOccurrence[][] = Array.from({ length: numDays }, () => []);
- const dayMs = 24 * 60 * 60 * 1000;
- for (const o of occurrences) {
- const dayIndex = Math.floor((o.at - startOfFirstDay) / dayMs);
- if (dayIndex < 0 || dayIndex >= numDays) continue;
- days[dayIndex]!.push(o);
- }
- for (const day of days) day.sort((a, b) => a.at - b.at);
- return days;
-}
diff --git a/notfair-cmo/src/server/scheduler/index.ts b/notfair-cmo/src/server/scheduler/index.ts
deleted file mode 100644
index 23ac32ac..00000000
--- a/notfair-cmo/src/server/scheduler/index.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { CronExpressionParser } from "cron-parser";
-import { getDb } from "@/server/db/db";
-
-/**
- * Native cron scheduler for notfair-cmo.
- *
- * Schedules live in SQLite (`scheduled_jobs`). A single setInterval in the
- * Next.js process polls every minute, finds jobs whose next_run_at is due,
- * and dispatches them through the project's harness adapter.
- *
- * Replaces OpenClaw's cron CLI. notfair-cmo now owns the schedule registry,
- * the tick loop, and the run history.
- */
-export interface ScheduledJob {
- id: string;
- project_slug: string;
- agent_id: string;
- name: string;
- cron_expr: string;
- message: string;
- enabled: 0 | 1;
- last_run_at: string | null;
- next_run_at: string | null;
- created_at: string;
- updated_at: string;
-}
-
-export interface CreateScheduledJobInput {
- project_slug: string;
- agent_id: string;
- name: string;
- cron_expr: string;
- message: string;
- enabled?: boolean;
-}
-
-function computeNextRun(cron_expr: string, from = new Date()): string | null {
- try {
- const it = CronExpressionParser.parse(cron_expr, { currentDate: from, tz: "UTC" });
- return it.next().toISOString();
- } catch {
- return null;
- }
-}
-
-export function createScheduledJob(input: CreateScheduledJobInput): ScheduledJob {
- const db = getDb();
- const now = new Date().toISOString();
- const next_run_at = input.enabled === false ? null : computeNextRun(input.cron_expr);
- const job: ScheduledJob = {
- id: randomUUID(),
- project_slug: input.project_slug,
- agent_id: input.agent_id,
- name: input.name,
- cron_expr: input.cron_expr,
- message: input.message,
- enabled: input.enabled === false ? 0 : 1,
- last_run_at: null,
- next_run_at,
- created_at: now,
- updated_at: now,
- };
- db.prepare(
- "INSERT INTO scheduled_jobs (id, project_slug, agent_id, name, cron_expr, message, enabled, last_run_at, next_run_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)",
- ).run(
- job.id,
- job.project_slug,
- job.agent_id,
- job.name,
- job.cron_expr,
- job.message,
- job.enabled,
- job.next_run_at,
- job.created_at,
- job.updated_at,
- );
- return job;
-}
-
-export function getScheduledJob(id: string): ScheduledJob | null {
- return (
- (getDb()
- .prepare("SELECT * FROM scheduled_jobs WHERE id = ?")
- .get(id) as ScheduledJob | undefined) ?? null
- );
-}
-
-export function listProjectScheduledJobs(project_slug: string): ScheduledJob[] {
- return getDb()
- .prepare("SELECT * FROM scheduled_jobs WHERE project_slug = ? ORDER BY created_at DESC")
- .all(project_slug) as ScheduledJob[];
-}
-
-export function listAgentScheduledJobs(project_slug: string, agent_id: string): ScheduledJob[] {
- return getDb()
- .prepare(
- "SELECT * FROM scheduled_jobs WHERE project_slug = ? AND agent_id = ? ORDER BY created_at DESC",
- )
- .all(project_slug, agent_id) as ScheduledJob[];
-}
-
-export function setJobEnabled(id: string, enabled: boolean): void {
- const job = getScheduledJob(id);
- if (!job) return;
- const next = enabled ? computeNextRun(job.cron_expr) : null;
- getDb()
- .prepare(
- "UPDATE scheduled_jobs SET enabled = ?, next_run_at = ?, updated_at = ? WHERE id = ?",
- )
- .run(enabled ? 1 : 0, next, new Date().toISOString(), id);
-}
-
-export function deleteScheduledJob(id: string): void {
- getDb().prepare("DELETE FROM scheduled_jobs WHERE id = ?").run(id);
-}
-
-export function dueJobs(now = new Date()): ScheduledJob[] {
- return getDb()
- .prepare(
- "SELECT * FROM scheduled_jobs WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ? ORDER BY next_run_at ASC",
- )
- .all(now.toISOString()) as ScheduledJob[];
-}
-
-export function markJobRun(id: string, ran_at = new Date()): void {
- const job = getScheduledJob(id);
- if (!job) return;
- const next = computeNextRun(job.cron_expr, ran_at);
- getDb()
- .prepare(
- "UPDATE scheduled_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE id = ?",
- )
- .run(ran_at.toISOString(), next, new Date().toISOString(), id);
-}
-
-export interface ScheduledJobRun {
- id: string;
- scheduled_job_id: string;
- started_at: string;
- finished_at: string | null;
- status: "running" | "done" | "failed";
- error_message: string | null;
- summary: string | null;
-}
-
-export function startJobRun(scheduled_job_id: string): string {
- const id = randomUUID();
- getDb()
- .prepare(
- "INSERT INTO scheduled_job_runs (id, scheduled_job_id, started_at, finished_at, status, error_message, summary) VALUES (?, ?, ?, NULL, 'running', NULL, NULL)",
- )
- .run(id, scheduled_job_id, new Date().toISOString());
- return id;
-}
-
-export function finishJobRun(
- run_id: string,
- status: "done" | "failed",
- error_message: string | null = null,
- summary: string | null = null,
-): void {
- getDb()
- .prepare(
- "UPDATE scheduled_job_runs SET finished_at = ?, status = ?, error_message = ?, summary = ? WHERE id = ?",
- )
- .run(new Date().toISOString(), status, error_message, summary, run_id);
-}
-
-export function listJobRuns(scheduled_job_id: string, limit = 50): ScheduledJobRun[] {
- return getDb()
- .prepare(
- "SELECT * FROM scheduled_job_runs WHERE scheduled_job_id = ? ORDER BY started_at DESC LIMIT ?",
- )
- .all(scheduled_job_id, limit) as ScheduledJobRun[];
-}
diff --git a/notfair-cmo/src/server/scheduler/tick.ts b/notfair-cmo/src/server/scheduler/tick.ts
deleted file mode 100644
index b49e67fa..00000000
--- a/notfair-cmo/src/server/scheduler/tick.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import { getProject } from "@/server/db/projects";
-import { requireAdapter } from "@/server/adapters/registry";
-import { getOrCreateSession, appendTranscriptEvent, touchSession } from "@/server/sessions";
-import {
- dueJobs,
- markJobRun,
- startJobRun,
- finishJobRun,
- type ScheduledJob,
-} from "./index";
-import { homedir } from "node:os";
-import { join } from "node:path";
-
-/**
- * Scheduler tick loop.
- *
- * Started once on first import via `ensureSchedulerRunning()`. The Next.js
- * dev server can reload modules, so the loop guards against multiple
- * concurrent intervals with a module-scoped flag — there's only ever one
- * tick at a time per process.
- */
-let started = false;
-let timer: NodeJS.Timeout | null = null;
-const TICK_INTERVAL_MS = 30_000;
-
-export function ensureSchedulerRunning(): void {
- if (started) return;
- started = true;
- timer = setInterval(() => {
- runTickSafe().catch((err) => console.error("[scheduler] tick failed:", err));
- }, TICK_INTERVAL_MS);
- // First tick on the next event-loop turn so callers can return immediately.
- setImmediate(() => runTickSafe().catch(() => undefined));
-}
-
-export function stopScheduler(): void {
- if (timer) clearInterval(timer);
- timer = null;
- started = false;
-}
-
-async function runTickSafe(): Promise<void> {
- const jobs = dueJobs();
- for (const job of jobs) {
- // Mark next run forward IMMEDIATELY so concurrent ticks (process reloads,
- // etc.) don't double-fire the same job.
- markJobRun(job.id);
- const runId = startJobRun(job.id);
- try {
- const summary = await dispatchJob(job);
- finishJobRun(runId, "done", null, summary);
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- console.error(`[scheduler] job ${job.id} failed:`, err);
- finishJobRun(runId, "failed", message);
- }
- }
-}
-
-function workspaceDirFor(agentId: string): string {
- const dataDir = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
- return join(dataDir, "agents", agentId);
-}
-
-async function dispatchJob(job: ScheduledJob): Promise<string | null> {
- const project = getProject(job.project_slug);
- if (!project) {
- throw new Error(`project not found: ${job.project_slug}`);
- }
- const adapter = requireAdapter(project.harness_adapter);
- const session = getOrCreateSession({
- project_slug: project.slug,
- agent_id: job.agent_id,
- label: `cron:${job.name}`,
- harness_adapter: project.harness_adapter,
- });
- appendTranscriptEvent(session.id, "user", { text: job.message, source: "cron" });
-
- // Prefer the adapter's explicit `final` event for the summary; fall back to
- // concatenated `delta` chunks if the adapter only streams text. Truncate so
- // we never bloat the DB with a multi-MB run row.
- let finalText: string | null = null;
- let deltaBuffer = "";
- const MAX_SUMMARY = 4000;
- const errors: { message: string; transient: boolean }[] = [];
-
- for await (const evt of adapter.execute({
- projectSlug: project.slug,
- agentId: job.agent_id,
- workspaceDir: workspaceDirFor(job.agent_id),
- message: job.message,
- threadId: session.id,
- harnessSessionId: session.harness_session_id,
- })) {
- if (evt.kind === "session") {
- touchSession(session.id, evt.harnessSessionId);
- continue;
- }
- appendTranscriptEvent(session.id, evt.kind, evt);
- if (evt.kind === "final") {
- finalText = evt.text;
- } else if (evt.kind === "delta" && deltaBuffer.length < MAX_SUMMARY) {
- deltaBuffer += evt.text;
- } else if (evt.kind === "error") {
- // Buffer rather than throw. Adapters (notably codex-local) can emit
- // several error events during a single retry burst — the last one is
- // usually the richest (exit code + stderr tail from execute.ts's
- // close handler). Throwing on the first event surfaced opaque retry
- // chatter like "Reconnecting... 2/5 (...)" and discarded the
- // actionable post-exit message that arrived a few hundred ms later.
- errors.push({ message: evt.message, transient: evt.transient ?? false });
- }
- }
- touchSession(session.id);
-
- // No `final` and we have errors → the turn failed. Prefer the most recent
- // non-transient error (the terminal exit-code message). Fall back to the
- // last entry when everything was tagged transient (we ran out of richer
- // signal; the retry chatter is all we have).
- if (finalText === null && errors.length > 0) {
- const terminal = [...errors].reverse().find((e) => !e.transient);
- throw new Error((terminal ?? errors[errors.length - 1]!).message);
- }
-
- const raw = (finalText ?? deltaBuffer).trim();
- if (!raw) return null;
- return raw.length > MAX_SUMMARY ? `${raw.slice(0, MAX_SUMMARY)}…` : raw;
-}
diff --git a/notfair-cmo/src/server/secrets/cipher.test.ts b/notfair-cmo/src/server/secrets/cipher.test.ts
deleted file mode 100644
index 6dbdb8a0..00000000
--- a/notfair-cmo/src/server/secrets/cipher.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const KEY_A = Buffer.alloc(32, 0xab);
-const KEY_B = Buffer.alloc(32, 0xcd);
-
-const getMasterKeyMock = vi.fn();
-
-vi.mock("./master-key", () => ({
- getMasterKey: () => getMasterKeyMock(),
-}));
-
-import { decrypt, encrypt } from "./cipher";
-
-describe("cipher", () => {
- beforeEach(() => {
- getMasterKeyMock.mockReset();
- getMasterKeyMock.mockResolvedValue(KEY_A);
- });
-
- describe("encrypt", () => {
- it("returns a base64 string distinct from plaintext", async () => {
- const out = await encrypt("hello world");
- expect(typeof out).toBe("string");
- expect(out).not.toContain("hello world");
- const buf = Buffer.from(out, "base64");
- // 12-byte IV + ciphertext("hello world" = 11 bytes) + 16-byte tag
- expect(buf.length).toBe(12 + 11 + 16);
- });
-
- it("produces different output for the same plaintext on each call (random IV)", async () => {
- const a = await encrypt("same input");
- const b = await encrypt("same input");
- expect(a).not.toBe(b);
- });
-
- it("handles empty string plaintext", async () => {
- const out = await encrypt("");
- const buf = Buffer.from(out, "base64");
- expect(buf.length).toBe(12 + 0 + 16);
- const round = await decrypt(out);
- expect(round).toBe("");
- });
-
- it("handles unicode plaintext", async () => {
- const text = "héllo 世界 🚀";
- const out = await encrypt(text);
- const round = await decrypt(out);
- expect(round).toBe(text);
- });
- });
-
- describe("decrypt — round trip", () => {
- it("round-trips plaintext through encrypt → decrypt", async () => {
- const text = "the quick brown fox jumps over the lazy dog";
- const blob = await encrypt(text);
- const round = await decrypt(blob);
- expect(round).toBe(text);
- });
-
- it("round-trips longer plaintext", async () => {
- const text = "x".repeat(10_000);
- const blob = await encrypt(text);
- const round = await decrypt(blob);
- expect(round).toBe(text);
- });
- });
-
- describe("decrypt — failure modes", () => {
- it("throws on a blob shorter than IV + tag", async () => {
- const tooShort = Buffer.alloc(12 + 16 - 1).toString("base64");
- await expect(decrypt(tooShort)).rejects.toThrow(/malformed/);
- });
-
- it("throws on an empty blob", async () => {
- await expect(decrypt("")).rejects.toThrow(/malformed/);
- });
-
- it("throws when decrypting with the wrong key", async () => {
- const blob = await encrypt("secret payload");
- getMasterKeyMock.mockResolvedValue(KEY_B);
- await expect(decrypt(blob)).rejects.toThrow();
- });
-
- it("throws when the auth tag has been tampered with", async () => {
- const blob = await encrypt("secret payload");
- const buf = Buffer.from(blob, "base64");
- // Flip a bit in the tag (last 16 bytes).
- buf[buf.length - 1] = buf[buf.length - 1]! ^ 0x01;
- const tampered = buf.toString("base64");
- await expect(decrypt(tampered)).rejects.toThrow();
- });
-
- it("throws when the ciphertext has been tampered with", async () => {
- const blob = await encrypt("secret payload");
- const buf = Buffer.from(blob, "base64");
- // Flip a bit somewhere in the ciphertext region (after IV, before tag).
- const idx = 12 + 2;
- buf[idx] = buf[idx]! ^ 0x01;
- const tampered = buf.toString("base64");
- await expect(decrypt(tampered)).rejects.toThrow();
- });
-
- it("throws when the IV has been tampered with", async () => {
- const blob = await encrypt("secret payload");
- const buf = Buffer.from(blob, "base64");
- buf[0] = buf[0]! ^ 0x01;
- const tampered = buf.toString("base64");
- await expect(decrypt(tampered)).rejects.toThrow();
- });
- });
-});
diff --git a/notfair-cmo/src/server/secrets/master-key.test.ts b/notfair-cmo/src/server/secrets/master-key.test.ts
deleted file mode 100644
index 32a534f6..00000000
--- a/notfair-cmo/src/server/secrets/master-key.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-async function loadFreshMasterKey() {
- vi.resetModules();
- return await import("./master-key");
-}
-
-describe("getMasterKey", () => {
- beforeEach(() => {
- vi.resetModules();
- });
-
- afterEach(() => {
- vi.doUnmock("keytar");
- });
-
- it("returns existing key from keychain as a 32-byte Buffer", async () => {
- const existing = Buffer.alloc(32, 7).toString("base64");
- const getPassword = vi.fn().mockResolvedValueOnce(existing);
- const setPassword = vi.fn();
- vi.doMock("keytar", () => ({
- default: { getPassword, setPassword },
- getPassword,
- setPassword,
- }));
-
- const mod = await loadFreshMasterKey();
- const key = await mod.getMasterKey();
-
- expect(Buffer.isBuffer(key)).toBe(true);
- expect(key.length).toBe(32);
- expect(key.equals(Buffer.alloc(32, 7))).toBe(true);
- expect(getPassword).toHaveBeenCalledWith("notfair-cmo", "master-key");
- expect(setPassword).not.toHaveBeenCalled();
- });
-
- it("generates and persists a fresh 32-byte key when none stored", async () => {
- const getPassword = vi.fn().mockResolvedValueOnce(null);
- const setPassword = vi.fn().mockResolvedValueOnce(undefined);
- vi.doMock("keytar", () => ({
- default: { getPassword, setPassword },
- getPassword,
- setPassword,
- }));
-
- const mod = await loadFreshMasterKey();
- const key = await mod.getMasterKey();
-
- expect(key.length).toBe(32);
- expect(setPassword).toHaveBeenCalledTimes(1);
- const [service, account, stored] = setPassword.mock.calls[0]!;
- expect(service).toBe("notfair-cmo");
- expect(account).toBe("master-key");
- expect(typeof stored).toBe("string");
- const decoded = Buffer.from(stored as string, "base64");
- expect(decoded.length).toBe(32);
- expect(key.equals(decoded)).toBe(true);
- });
-
- it("caches the key across calls — only reads keychain once", async () => {
- const getPassword = vi
- .fn()
- .mockResolvedValueOnce(Buffer.alloc(32, 1).toString("base64"));
- const setPassword = vi.fn();
- vi.doMock("keytar", () => ({
- default: { getPassword, setPassword },
- getPassword,
- setPassword,
- }));
-
- const mod = await loadFreshMasterKey();
- const k1 = await mod.getMasterKey();
- const k2 = await mod.getMasterKey();
-
- expect(k1).toBe(k2);
- expect(getPassword).toHaveBeenCalledTimes(1);
- });
-
- it("throws when keytar import fails", async () => {
- vi.doMock("keytar", () => {
- throw new Error("module not installed");
- });
-
- const mod = await loadFreshMasterKey();
- await expect(mod.getMasterKey()).rejects.toThrow(
- /OS keychain \(keytar\) not available/,
- );
- });
-
- it("throws a follow-up error on subsequent calls after load failure", async () => {
- vi.doMock("keytar", () => {
- throw new Error("module not installed");
- });
-
- const mod = await loadFreshMasterKey();
- await expect(mod.getMasterKey()).rejects.toThrow(
- /OS keychain \(keytar\) not available/,
- );
- await expect(mod.getMasterKey()).rejects.toThrow(
- /Master key unavailable \(keytar not loadable\)/,
- );
- });
-
- it("uses the default export when keytar exposes one", async () => {
- const getPassword = vi
- .fn()
- .mockResolvedValueOnce(Buffer.alloc(32, 9).toString("base64"));
- const setPassword = vi.fn();
- vi.doMock("keytar", () => ({
- default: { getPassword, setPassword },
- }));
-
- const mod = await loadFreshMasterKey();
- const key = await mod.getMasterKey();
- expect(key.equals(Buffer.alloc(32, 9))).toBe(true);
- expect(getPassword).toHaveBeenCalledWith("notfair-cmo", "master-key");
- });
-
- it("falls back to namespace export when default is null", async () => {
- const getPassword = vi
- .fn()
- .mockResolvedValueOnce(Buffer.alloc(32, 3).toString("base64"));
- const setPassword = vi.fn();
- vi.doMock("keytar", () => ({
- default: null,
- getPassword,
- setPassword,
- }));
-
- const mod = await loadFreshMasterKey();
- const key = await mod.getMasterKey();
- expect(key.equals(Buffer.alloc(32, 3))).toBe(true);
- expect(getPassword).toHaveBeenCalledWith("notfair-cmo", "master-key");
- });
-});
diff --git a/notfair-cmo/src/server/skills/orchestration-skill.test.ts b/notfair-cmo/src/server/skills/orchestration-skill.test.ts
deleted file mode 100644
index 214faa6a..00000000
--- a/notfair-cmo/src/server/skills/orchestration-skill.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- getOrchestrationSkill,
- ORCHESTRATION_SKILL,
-} from "./orchestration-skill";
-
-describe("ORCHESTRATION_SKILL", () => {
- it("getOrchestrationSkill() returns the exported constant verbatim (pure)", () => {
- expect(getOrchestrationSkill()).toBe(ORCHESTRATION_SKILL);
- });
-
- it("calling getOrchestrationSkill() multiple times returns the same string (cacheable / pure)", () => {
- expect(getOrchestrationSkill()).toBe(getOrchestrationSkill());
- });
-
- it("teaches the MCP tool surface (writing tools)", () => {
- const s = getOrchestrationSkill();
- for (const tool of [
- "create_task",
- "submit_task_status",
- "request_approval",
- "add_task_comment",
- "ask_user_question",
- "update_task",
- "cancel_task",
- ]) {
- expect(s).toContain(tool);
- }
- });
-
- it("teaches the read / context-reanchor tools", () => {
- const s = getOrchestrationSkill();
- for (const tool of [
- "get_task",
- "list_my_tasks",
- "list_tasks",
- "get_project",
- "list_task_comments",
- "get_approval",
- "list_my_approvals",
- "list_pending_approvals",
- "list_approvals_for_task",
- ]) {
- expect(s).toContain(tool);
- }
- });
-
- it("teaches the enum-discovery tools so agents don't guess", () => {
- const s = getOrchestrationSkill();
- expect(s).toContain("list_task_statuses");
- expect(s).toContain("list_approval_action_types");
- expect(s).toContain("list_project_agents");
- });
-
- it("forbids pseudo-XML pseudo-blocks (the rule that fixed the closed/done drift bug)", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/NEVER through pseudo-XML/);
- expect(s).toContain("`<create_task>`");
- expect(s).toContain("`<task_status>`");
- });
-
- it("documents the cannot-close-with-pending-approval invariant", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/can NOT close a task.*pending approval/i);
- });
-
- it("teaches the schedule_recurring_work MCP tool, not the dead openclaw CLI", () => {
- const s = getOrchestrationSkill();
- expect(s).toContain("schedule_recurring_work");
- expect(s).toContain("cron_expr");
- expect(s).toContain("project_slug");
- expect(s).toContain("agent_id");
- // Regression: previous skill told agents to shell out to a CLI that
- // doesn't exist anymore. That made agents hallucinate cron creation
- // success without ever persisting a row to scheduled_jobs.
- expect(s).not.toContain("openclaw cron add");
- });
-
- it("documents propose-then-call flow for recurring schedules after one-time approvals", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/propose ONE schedule per turn/);
- // The pseudo-XML <propose_cron> sentinel block was removed when the
- // dead openclaw CLI was retired; agents now propose in prose and
- // call schedule_recurring_work on confirmation.
- expect(s).not.toContain("<propose_cron>");
- });
-
- it("points agents at the standalone notfair-browser MCP (not the orchestration MCP)", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/notfair-browser MCP/);
- expect(s).not.toMatch(/notfair-orchestration MCP exposes .*browser_/);
- });
-
- it("teaches the workspace browser tool inventory", () => {
- const s = getOrchestrationSkill();
- for (const tool of [
- "browser_status",
- "browser_tabs",
- "browser_open",
- "browser_close",
- "browser_navigate",
- "browser_snapshot",
- "browser_click",
- "browser_type",
- "browser_press",
- "browser_scroll",
- "browser_back",
- ]) {
- expect(s).toContain(tool);
- }
- });
-
- it("tells agents they CANNOT stop the workspace browser (multi-agent safety)", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/cannot stop/i);
- expect(s).not.toContain("browser_shutdown");
- });
-
- it("teaches the snapshot → act → snapshot discipline (stale refs are the #1 browser bug)", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/snapshot AGAIN/i);
- expect(s).toMatch(/[Ss]tale refs/);
- });
-
- it("teaches agents to use agent_id as their browser tab label", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/label.*agent_id/i);
- });
-
- it("teaches agents to report login/captcha/2FA as blockers via submit_task_status", () => {
- const s = getOrchestrationSkill();
- expect(s).toMatch(/captcha|2FA|login wall/i);
- expect(s).toMatch(/submit_task_status.*blocked/);
- });
-
- it("explicitly tells agents NOT to use bundled browser-use plugins or `open -a` shell commands", () => {
- // Regression guard: real failure observed where Greg launched
- // OpenAI's bundled `browser-use` plugin instead of browser_open,
- // then fell back to `open -a "Google Chrome"` (wrong profile).
- const s = getOrchestrationSkill();
- expect(s).toMatch(/browser-use/i);
- expect(s).toMatch(/open -a/);
- expect(s).toMatch(/different Chrome|wrong profile|won't persist/i);
- });
-
- it("includes a 'Your role:' section selector so role-specific content sits ABOVE", () => {
- // The skill should sound like a how-to manual, NOT contain role
- // declarations like "You are the CMO" / "You are a worker" — those
- // live in CMO_ROLE / SPECIALIST_ROLE, not here.
- const s = getOrchestrationSkill();
- expect(s).not.toMatch(/^You are the CMO/m);
- expect(s).not.toMatch(/^You are a specialist worker/m);
- });
-});
diff --git a/notfair-cmo/src/server/skills/orchestration-skill.ts b/notfair-cmo/src/server/skills/orchestration-skill.ts
deleted file mode 100644
index 38f4396d..00000000
--- a/notfair-cmo/src/server/skills/orchestration-skill.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-/**
- * Shared, role-agnostic procedural knowledge appended to every agent's
- * IDENTITY.md. Paperclip-style: one skill file every agent loads, with
- * role-specific behavior + style living separately in the per-agent
- * IDENTITY block above it.
- *
- * Edits here propagate to every provisioned agent on the next provision
- * (which is idempotent and runs on every project re-provision call).
- *
- * What belongs HERE:
- * - The notfair-orchestration MCP tool surface (names, when to call)
- * - The task state machine + no-pseudo-XML rule
- * - Cron scheduling CLI shape
- * - "Propose recurring cron after one-time approval" behavior
- *
- * What does NOT belong here (lives in each role's template):
- * - "You are the CMO" / "You are a worker" identity
- * - Role-specific tool guidance (notfair-googleads, GSC, etc.)
- * - Style guides
- */
-export const ORCHESTRATION_SKILL = `## Platform skill: notfair-cmo orchestration
-
-This section is identical for every agent on the platform. Your role-
-specific behavior is above this divider; the procedural how-to is below.
-
-### Coordinate through the notfair-orchestration MCP server
-
-Tasks, approvals, comments, questions, and project context are all
-managed through tool calls — NEVER through pseudo-XML in your prose.
-Do not emit \`<create_task>\`, \`<task_status>\`, \`<add_comment>\`,
-\`<ask_user>\`, or \`<request_approval>\`. The platform does not parse them.
-
-Every notfair-orchestration tool requires \`project_slug\`; most also
-require \`agent_id\` (or \`assigner_agent_id\`). Take both from the "Your
-runtime identity" section at the top of this file. Never guess.
-
-When you're unsure of an enum (status, action_type, assignee template),
-call the discovery tool first instead of guessing:
-- \`list_task_statuses\` — workflow state machine + allowed transitions
-- \`list_approval_action_types\` — approval categories + cost-required hints
-- \`list_project_agents\` — agents you can delegate to
-
-### Writing tools (what you can change)
-
-- \`create_task\` — spawn a task and auto-start it. Use to delegate work
- to a specialist. Title is the kanban label; brief is a PRD.
-- \`submit_task_status\` — report progress on YOUR assigned task. Status
- enum (strict): \`working\` | \`done\` | \`blocked\` | \`failed\`. Summary
- required for done / failed. Call multiple times across turns is fine.
-- \`request_approval\` — ask the user (or auto-approval policy) before a
- governed write. Required for spend / content publish / new channel /
- bid change / audience change. Setting \`task_id\` parks the task in
- \`blocked\` until resolved; the platform wakes you with the decision.
-- \`add_task_comment\` — talk to the CMO (or future-you) on a specific
- task. Cross-agent comms log, visible in /activity.
-- \`ask_user_question\` — surface a structured question to the human, with
- optional comma-separated \`options\` rendered as buttons. Setting
- \`task_id\` parks the task in \`blocked\` until the user answers; the
- platform wakes you with the answer on the task thread. Use sparingly;
- prefer asking the CMO or your own tools first. End your turn after
- calling — don't keep working on a blocked task.
-- \`update_task\` — edit title / brief / success criteria on a task you
- created. 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)
-
-When your context window rotates and you've lost the brief, use these to
-recover instead of asking the user:
-- \`get_task\` — fetch a task by id or display_id
-- \`list_my_tasks\` — what's currently on your plate (default: in-flight)
-- \`list_tasks\` — project-wide kanban view
-- \`get_project\` — current project metadata
-- \`list_task_comments\` — comment history on a task
-- \`get_approval\`, \`list_my_approvals\`, \`list_pending_approvals\`,
- \`list_approvals_for_task\` — approval state lookups
-
-### Invariants the platform enforces
-
-- You can NOT close a task (\`done\`) while it has a pending approval —
- the call will fail with a clear error. Either wait for resolution (the
- platform wakes you) or call \`submit_task_status\` with \`failed\`.
-- Cross-project tool calls are rejected. Use the project_slug from your
- runtime identity, not another project's.
-- Terminal statuses (succeeded / failed / cancelled) are not re-writable.
- Once a task is closed, status calls become no-ops.
-
-## Workspace browser tools
-
-The workspace has a single shared Chrome instance with persistent cookies.
-The user has signed in there during onboarding — so login state for Google,
-Meta, Search Console, etc. is already available to you. Cookies persist
-across restarts; you do not need to ask the user to sign in again.
-
-### CRITICAL: which "browser" tool to use
-
-The notfair-browser MCP exposes \`browser_open\`, \`browser_snapshot\`,
-\`browser_click\`, etc. **These are the ONLY tools that touch the workspace
-browser.** When the user says "launch the browser", "open a page", "go to
-<URL>", "snapshot the page", or anything in that family, the answer is
-ALWAYS one of the \`browser_*\` MCP tools below.
-
-Do **not**:
-- Use any bundled or third-party "browser-use" plugin your host runtime
- might ship (e.g. OpenAI's bundled \`browser-use\` plugin in Codex CLI).
- Those open a different Chrome with a different profile — your work
- won't persist for other agents in this project.
-- Shell out to \`open -a "Google Chrome"\`, \`open <url>\`, AppleScript
- \`tell application "Google Chrome"\`, \`xdg-open\`, \`start chrome\`,
- or similar. Same problem: wrong profile, no shared cookies.
-- "Initialize" or "launch" the browser as a separate step. \`browser_open\`
- starts the workspace Chrome on its first call automatically.
-
-If you're unsure whether the workspace browser is running, call
-\`browser_status\` first — it's cheap and tells you everything.
-
-### One labeled tab per agent
-
-Every agent shares the same Chrome, so coordinate via tab labels.
-**Always pass \`label\` equal to your \`agent_id\` when calling
-\`browser_open\`.** That reserves a stable tab for your work and prevents
-you (or a retry) from racing other agents.
-
-\`\`\`
-browser_open({ project_slug, label: "<your agent_id>", url: "..." })
-\`\`\`
-
-If a labeled tab already exists, \`browser_open\` reuses it (navigates
-that tab instead of duplicating). Subsequent calls target it as
-\`target_id: "<your agent_id>"\`.
-
-Before opening, call \`browser_tabs\` if you suspect a prior turn left
-state you can reuse — it lists every tab in the workspace with handle,
-URL, and title.
-
-### Snapshot → act → snapshot
-
-Refs in a snapshot (\`e1\`, \`e2\`, ...) are valid ONLY until the DOM
-changes. Discipline:
-
-1. \`browser_snapshot\` to learn what's on the page (returns elements
- with stable refs + a text excerpt).
-2. \`browser_click\`/\`browser_type\`/\`browser_press\` using a ref from
- that snapshot.
-3. After any navigation, form submit, or modal change, snapshot AGAIN
- before the next action. Stale refs fail loudly — recover with a
- fresh snapshot, never a blind retry.
-
-\`browser_navigate\` triggers a navigation; \`browser_scroll\` does not
-invalidate refs but may reveal new ones (re-snapshot if you need them).
-
-### Reporting blockers honestly
-
-If the page surfaces a login wall, captcha, 2FA prompt, permission
-dialog, or any state that needs the human, STOP. Do not loop. Use
-\`submit_task_status\` with \`status: "blocked"\` and a summary that
-quotes the exact UI ("Google asks for SMS verification on
-+1•••••5309"). Do not claim "not logged in" just because the current
-page shows an onboarding splash — snapshot first and read the visible
-UI.
-
-Do not try to bypass interstitials by reloading or clicking around. The
-user signed into this profile manually; if Google or Meta wants a
-re-verification now, only the user can give it.
-
-### Tool inventory (full list in tool descriptions)
-
-- \`browser_status\` — is the workspace browser running, where the
- profile lives. Cheap; safe to call first.
-- \`browser_tabs\` — list every tab with handle, URL, title.
-- \`browser_open\` — open / reuse a tab. ALWAYS pass \`label\`.
-- \`browser_close\` — close a tab by handle.
-- \`browser_navigate\` — point an existing tab at a new URL.
-- \`browser_snapshot\` — get refs + text. Snapshot before every action.
-- \`browser_click\` — click ref. Supports right/middle/double + modifiers.
-- \`browser_type\` — type into ref. \`submit: true\` presses Enter after.
-- \`browser_press\` — single key / chord (Tab, Escape, Control+a, ...).
-- \`browser_scroll\` — viewport scroll up/down/left/right.
-- \`browser_back\` — history back.
-
-You CANNOT stop the workspace browser. Browser lifecycle belongs to the
-user (Settings → Workspace browser → Stop). This is deliberate: every
-agent in this workspace shares one Chrome, so stopping it would interrupt
-your teammates mid-task.
-
-## Scheduling recurring work
-
-When the user asks for "every day", "every Monday", "every hour", etc.,
-call the \`schedule_recurring_work\` MCP tool. Do NOT shell out — there
-is no \`openclaw cron\` CLI. The SQLite-backed scheduler is the only
-path now and it's exposed only via this tool.
-
-Inputs:
-- \`project_slug\` — from your runtime identity above.
-- \`agent_id\` — full id (e.g. \`demo1-google-ads-ana\`) of the agent
- who should receive the scheduled task assignment. Usually yourself.
-- \`name\` — short kebab-case identifier of the WORK (not the schedule).
- Good: \`daily-bid-opt\`, \`weekly-quality-score\`. Bad: \`9am-cron\`,
- \`every-monday\`.
-- \`cron_expr\` — standard 5-field cron expression in UTC. Embed the
- user's desired hour as UTC: 9am Pacific (UTC-7 in summer) is
- \`0 16 * * *\`; 9am Pacific in winter (UTC-8) is \`0 17 * * *\`.
-- \`message\` — the prompt the schedule will send to the agent on each
- tick. Write it as instructions to your future self: be specific about
- what to do and what to report.
-
-After the tool returns, you'll get \`{ id, name, cron_expr, next_run_at }\`.
-Mention the created id in your reply so the user can correlate with the
-Crons tab.
-
-Common patterns:
-- Daily morning: \`0 16 * * *\` (9am PT summer)
-- Weekly Monday: \`0 16 * * 1\`
-- Hourly: \`0 * * * *\`
-
-## Propose recurring crons after approved one-time actions
-
-When the user just approved a one-time action that produces a one-time
-outcome (e.g., pausing wasted-spend keywords), your next response should
-propose a recurring schedule to catch the same kind of issue in the
-future. Describe the proposed schedule in prose plus the exact tool
-call you would make, then wait for the user's go-ahead:
-
-> "I'd suggest scheduling this weekly — every Monday at 9am Pacific.
-> If you want, I'll set it up:
-> - name: weekly-wasted-spend-sweep
-> - cron_expr: 0 16 * * 1
-> - message: 'Re-run the wasted-spend audit and pause any keyword with
-> > $50 spend and 0 conversions in the past 7 days. Report counts.'"
-
-Rules:
-- Only propose ONE schedule per turn. Quality over quantity.
-- Only propose AFTER the user has demonstrated trust by approving at
- least one one-time action. Do not propose on a cold chat.
-- When the user replies "yes" / "do it", THEN call
- \`schedule_recurring_work\` with the exact fields above.
-`;
-
-/** Public reader used by writeIdentityFile + tests. Pure for snapshot-style
- * assertions; never mutates state. */
-export function getOrchestrationSkill(): string {
- return ORCHESTRATION_SKILL;
-}
diff --git a/notfair-cmo/src/server/version.test.ts b/notfair-cmo/src/server/version.test.ts
deleted file mode 100644
index cf131596..00000000
--- a/notfair-cmo/src/server/version.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- _resetLatestCache,
- getCurrentVersion,
- getLatestVersion,
- getVersionStatus,
- isSemverGreater,
-} from "./version";
-
-const originalFetch = globalThis.fetch;
-
-beforeEach(() => {
- _resetLatestCache();
-});
-
-afterEach(() => {
- _resetLatestCache();
- globalThis.fetch = originalFetch;
-});
-
-describe("getCurrentVersion", () => {
- it("returns a non-empty semver string from package.json", () => {
- const v = getCurrentVersion();
- expect(v).toMatch(/^\d+\.\d+\.\d+/);
- });
-});
-
-describe("isSemverGreater", () => {
- it.each([
- ["1.0.0", "0.9.9", true],
- ["1.1.0", "1.0.9", true],
- ["0.0.2", "0.0.1", true],
- ["0.0.1", "0.0.1", false],
- ["0.0.1", "0.0.2", false],
- ["1.0.0", "1.0.0", false],
- ["2.0.0", "10.0.0", false],
- ["10.0.0", "9.99.99", true],
- ])("isSemverGreater(%s, %s) === %s", (a, b, expected) => {
- expect(isSemverGreater(a, b)).toBe(expected);
- });
-
- it("ignores pre-release / build suffixes (compares numeric core only)", () => {
- expect(isSemverGreater("1.0.0", "1.0.0-rc.1")).toBe(false);
- expect(isSemverGreater("1.0.1-rc.1", "1.0.0")).toBe(true);
- });
-});
-
-describe("getLatestVersion", () => {
- it("returns the npm registry version on success", async () => {
- globalThis.fetch = vi.fn(async () =>
- new Response(JSON.stringify({ version: "9.9.9" }), { status: 200 }),
- ) as typeof fetch;
- const v = await getLatestVersion();
- expect(v).toBe("9.9.9");
- });
-
- it("caches within the TTL window", async () => {
- const spy = vi.fn(async () =>
- new Response(JSON.stringify({ version: "1.2.3" }), { status: 200 }),
- );
- globalThis.fetch = spy as typeof fetch;
- await getLatestVersion();
- await getLatestVersion();
- await getLatestVersion();
- expect(spy).toHaveBeenCalledTimes(1);
- });
-
- it("re-fetches after force=true", async () => {
- const spy = vi.fn(async () =>
- new Response(JSON.stringify({ version: "1.2.3" }), { status: 200 }),
- );
- globalThis.fetch = spy as typeof fetch;
- await getLatestVersion();
- await getLatestVersion(true);
- expect(spy).toHaveBeenCalledTimes(2);
- });
-
- it("returns null on registry errors instead of throwing", async () => {
- globalThis.fetch = vi.fn(async () =>
- new Response("server is on fire", { status: 503 }),
- ) as typeof fetch;
- expect(await getLatestVersion()).toBeNull();
- });
-
- it("returns null when fetch rejects (offline)", async () => {
- globalThis.fetch = vi.fn(async () => {
- throw new Error("ECONNREFUSED");
- }) as typeof fetch;
- expect(await getLatestVersion()).toBeNull();
- });
-
- it("returns null when the response is not JSON or lacks version", async () => {
- globalThis.fetch = vi.fn(async () =>
- new Response(JSON.stringify({ name: "notfair-cmo" }), { status: 200 }),
- ) as typeof fetch;
- expect(await getLatestVersion()).toBeNull();
- });
-});
-
-describe("getVersionStatus", () => {
- it("flags has_update=true when registry reports a newer version", async () => {
- const current = getCurrentVersion();
- const bumped = bumpPatch(current);
- globalThis.fetch = vi.fn(async () =>
- new Response(JSON.stringify({ version: bumped }), { status: 200 }),
- ) as typeof fetch;
- const status = await getVersionStatus();
- expect(status.current).toBe(current);
- expect(status.latest).toBe(bumped);
- expect(status.has_update).toBe(true);
- });
-
- it("flags has_update=false when current is the latest", async () => {
- const current = getCurrentVersion();
- globalThis.fetch = vi.fn(async () =>
- new Response(JSON.stringify({ version: current }), { status: 200 }),
- ) as typeof fetch;
- const status = await getVersionStatus();
- expect(status.has_update).toBe(false);
- });
-
- it("flags has_update=false (not unknown) when registry is unreachable", async () => {
- globalThis.fetch = vi.fn(async () => {
- throw new Error("network down");
- }) as typeof fetch;
- const status = await getVersionStatus();
- expect(status.latest).toBeNull();
- expect(status.has_update).toBe(false);
- });
-});
-
-function bumpPatch(v: string): string {
- const [maj, min, patch] = v.split(".").map((n) => parseInt(n, 10));
- return `${maj}.${min}.${(patch ?? 0) + 1}`;
-}
diff --git a/notfair-cmo/src/types/index.ts b/notfair-cmo/src/types/index.ts
deleted file mode 100644
index b3311b2d..00000000
--- a/notfair-cmo/src/types/index.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-// Shared types. Imported by both server (Next.js API + MCP) and client (React).
-
-export type Project = {
- id: string;
- slug: string;
- display_name: string;
- created_at: string;
- archived_at: string | null;
- /**
- * Selected Google Ads customer ID for this project. Bearers from
- * notfair.co/api/mcp/google_ads can grant access to multiple customer
- * accounts; the onboarding flow asks the user to pick one and persists
- * it here so the audit + later automation target the right account.
- * Null until the user picks (or until /onboarding gets re-run).
- */
- google_ads_account_id: string | null;
- /**
- * Selected Meta Ads ad-account id (e.g. "act_123456"). Same pattern as
- * google_ads_account_id: the notfair-metaads bearer may grant access
- * to multiple ad accounts, and onboarding asks the user to pick the
- * one this project should target. Null until picked.
- */
- meta_ads_account_id: string | null;
- /**
- * Selected Google Search Console property id (e.g. "sc-domain:example.com"
- * or "https://example.com/"). Same idea as the ad-account fields: the
- * notfair-googlesearchconsole bearer may cover multiple verified
- * properties, and we persist the chosen one. Null until picked.
- */
- gsc_property_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;
- /**
- * Which harness adapter runs this project's agents. Picked at
- * onboarding. "codex-local" is the recommended default; "claude-code-local"
- * runs through Anthropic's Claude Code CLI instead.
- */
- harness_adapter: "claude-code-local" | "codex-local";
-};
-
-export type TaskStatus =
- | "proposed"
- | "approved"
- | "working"
- | "blocked"
- | "done"
- | "failed"
- | "cancelled";
-
-// ┌──────────┐ user approves ┌──────────┐ agent picks up ┌─────────┐
-// │ proposed │ ─────────────────────────────▶│ approved │ ────────────────▶│ running │◀─┐
-// └──────────┘ needs_approval └──────────┘ └────┬────┘ │
-// │ ▲ │ │
-// │ └── user approves from inbox ──────────────────────────────┐ │ │
-// │ │ ▼ │
-// │ ┌───────────────┐ │
-// │ │ blocked │────────┘
-// │ └───────────────┘ approval resolved
-// │ │
-// │ ▼
-// │ ┌───────────────┐
-// └─ user/CMO cancels ───────────────────────────────────▶│ cancelled / failed / succeeded │
-// └───────────────┘
-export type Task = {
- id: string;
- /**
- * Human-readable per-project ID like "demo7-3". Used in URLs and UI
- * surfaces. PK stays as `id` (UUID) for FK integrity; display_id is
- * the surface humans see. Backfilled for pre-004 tasks; always set
- * for new tasks.
- */
- display_id: string;
- project_slug: string;
- /** Assignee — the agent expected to do the work. */
- agent_id: string;
- /** Short label shown on task cards (e.g., "Set up daily anomaly check"). */
- title: string | null;
- /** Full request body. Often a PRD-style description from the CMO. */
- brief: string;
- success_criteria: string | null;
- deadline_iso: string | null;
- status: TaskStatus;
- result_json: string | null;
- error_message: string | null;
- /**
- * OpenClaw chat session id where the assignee picks up this task. Null
- * until first opened; populated on first /tasks/[id] visit + remains
- * stable forever after.
- */
- thread_id: string | null;
- /**
- * Agent that created this task. For CMO-originated tasks this is the
- * CMO agent id; in v1.1 specialists creating sub-tasks fill in their
- * own id so the chain back to the planner is walkable.
- */
- assigner_agent_id: string | null;
- /**
- * 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;
-};
-
-export type ApprovalStatus =
- | "pending"
- | "revision_requested"
- | "approved"
- | "rejected"
- | "expired";
-
-export type ApprovalType =
- | "spend"
- | "content_publishing"
- | "new_channel"
- | "bid_change"
- | "audience_change"
- | "other";
-
-/** Who made the decision on an approval. 'policy' = auto-decided by a rule. */
-export type ApprovalDecidedByKind = "user" | "agent" | "policy";
-
-/** Author of a comment on an approval thread. 'system' = automated note. */
-export type ApprovalCommentAuthorKind = "user" | "agent" | "system";
-
-export type Approval = {
- id: string;
- project_slug: string;
- agent_id: string;
- /** Task this approval is gating, if any. Filled when the agent emits
- * <request_approval> inside a task context; null for free-standing asks. */
- task_id: string | null;
- action_summary: string;
- action_type: ApprovalType;
- cost_estimate_usd: number;
- reasoning: string | null;
- payload_json: string;
- status: ApprovalStatus;
- /** Free-text reason the decider attached on resolve/revision_requested. */
- decision_note: string | null;
- decided_by_kind: ApprovalDecidedByKind | null;
- decided_by_id: string | null;
- created_at: string;
- resolved_at: string | null;
-};
-
-/** Open question raised by an agent via the `ask_user_question` MCP tool.
- * Modeled like Approval — a pending row blocks the task; the user answers
- * (option or free-text) or cancels; the wake-up streams the resolution
- * back to the agent as a [SYSTEM] message on the task thread. */
-export type QuestionStatus = "pending" | "answered" | "cancelled";
-
-export type Question = {
- id: string;
- project_slug: string;
- agent_id: string;
- /** Task this question is anchored to. Null for free-standing asks. */
- task_id: string | null;
- prompt: string;
- /** Optional multiple-choice hints rendered as buttons in the UI. JSON
- * array of strings. Empty array when the agent didn't supply choices. */
- options_json: string;
- status: QuestionStatus;
- /** Zero-based index into options_json[] when the user picked an option.
- * Null when the user only typed free-text or cancelled. */
- answer_option_index: number | null;
- /** Free-text answer the user typed alongside / instead of an option.
- * Null when the user only clicked an option or cancelled. */
- answer_text: string | null;
- /** Who resolved the question — user (typical) vs system (future timeout). */
- resolved_by_kind: "user" | "system" | null;
- created_at: string;
- resolved_at: string | null;
-};
-
-export type ApprovalComment = {
- id: string;
- approval_id: string;
- author_kind: ApprovalCommentAuthorKind;
- author_id: string | null;
- body: string;
- created_at: string;
-};
-
-/** "Always allow / reject" rule consulted before a pending approval is created.
- * Matches by (project_slug, action_type) + optional agent_id + optional cost cap. */
-export type ApprovalPolicy = {
- id: string;
- project_slug: string;
- action_type: ApprovalType;
- /** Restrict to a single agent. Null = applies to any agent in the project. */
- agent_id: string | null;
- /** Maximum cost the policy auto-decides for. Null = no cap. */
- max_cost_usd: number | null;
- auto_decision: "approve" | "reject";
- note: string | null;
- created_at: string;
- created_by_kind: "user" | "agent";
- created_by_id: string | null;
-};
-
-export type CostEventSource = "llm" | "google_ads" | "gsc" | "other";
-
-export type CostEvent = {
- id: string;
- project_slug: string;
- agent_id: string | null;
- source: CostEventSource;
- amount_usd: number;
- ref: string | null;
- occurred_at: string;
-};
-
-export type OAuthProvider = "google_ads" | "gsc";
-
-export type OAuthToken = {
- id: string;
- project_slug: string;
- provider: OAuthProvider;
- account_label: string;
- access_token_enc: string;
- refresh_token_enc: string;
- expires_at: string;
- scope: string;
- created_at: string;
- updated_at: string;
-};
-
-export type ToolErrorEnvelope = {
- ok: false;
- error_code: string;
- message: string;
- retryable: boolean;
- user_message: string;
-};
-
-export type ToolSuccessEnvelope<T> = {
- ok: true;
- data: T;
-};
-
-export type ToolResult<T> = ToolSuccessEnvelope<T> | ToolErrorEnvelope;
diff --git a/notfair-cmo/tests/evals/README.md b/notfair-cmo/tests/evals/README.md
deleted file mode 100644
index 7cf79b97..00000000
--- a/notfair-cmo/tests/evals/README.md
+++ /dev/null
@@ -1,38 +0,0 @@
-# Evals
-
-Golden-case prompt evaluations for prompts that matter. Per the V1 ship gate in PLAN.md ("eval harness, light"), these are critical for surfaces where a silent prompt regression would degrade product behavior without any test failing.
-
-## Running
-
-```bash
-pnpm eval
-```
-
-Requires `OPENAI_API_KEY` in env (or `~/.gstack/openai.json`). If absent, eval suites skip automatically — they never fail-by-not-running. The default `pnpm test` does NOT run evals; they live under `tests/evals/` and use `*.eval.ts` instead of `*.test.ts`.
-
-## What's covered
-
-| Eval file | What it checks | Decision |
-|---|---|---|
-| `cmo-first-turn.eval.ts` | When the CMO opens a chat session with `FIRST_TURN.md` present in its workspace, the first reply must reference a specific audit finding by name + dollar figure. With an empty-account `FIRST_TURN.md`, the reply must offer launch help. With no `FIRST_TURN.md`, the reply must NOT fabricate audit findings. | D15 + D19 |
-
-## How the eval works
-
-The CMO's production system prompt (from `src/server/agent-templates.ts`) is used unchanged. For each golden case:
-
-1. The case JSON specifies whether `FIRST_TURN.md` is present + its content.
-2. The eval simulates the workspace by prepending the file content to the system prompt with a clear marker. (In production the agent reads it via `exec cat FIRST_TURN.md`; the eval approximates by injecting the read result.)
-3. The LLM is called with the system prompt and a minimal opening user message ("Hi") to elicit the first assistant turn.
-4. The reply is checked against `must_contain_any_of` (regex/string match — permissive enough to absorb wording variation) and `must_not_contain` (strict — used to catch fabrication when no audit context is present).
-
-If a case fails, the eval prints the full reply for inspection. Iterate on the system prompt in `agent-templates.ts` until the case passes again.
-
-## When to add a new eval case
-
-- A new product surface introduces a prompt that, if regressed, would silently degrade behavior.
-- A bug report turns out to be a prompt-following failure — capture it as a golden case so the regression doesn't recur.
-
-## Caveats
-
-- Evals are inherently non-deterministic. Use generous `must_contain_any_of` (alternatives are forgiving) and strict `must_not_contain` (only block clear violations).
-- Cost: each case is ~1 LLM call. The full suite at V1 is ~3 calls = single-digit cents per run.
diff --git a/notfair-cmo/tests/evals/cases/empty-account.json b/notfair-cmo/tests/evals/cases/empty-account.json
deleted file mode 100644
index 58621b7c..00000000
--- a/notfair-cmo/tests/evals/cases/empty-account.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "name": "empty-account",
- "description": "Audit found no campaigns/spend; CMO first reply must offer launch help via the hybrid roadmap.",
- "first_turn_md": "# First-turn context for the CMO\n\nYou have just connected the user's Google Ads account and run a baseline audit.\nThis is a one-shot context: on your FIRST chat turn after the user opens this\nproject's CMO chat, weave the highlights into your greeting, then move this\nfile to MEMORY/last-first-turn-<YYYY-MM-DD>.md so you don't repeat it.\n\n## Audit metadata\n- Project: acme\n- Audit run at: 2026-05-19T14:00:00Z\n- Account state: empty\n- Findings count: 0\n\n## Top suggestion (new account — empty audit)\n- Set a daily budget for your first campaign — most B2B starts at $50-100/day to gather signal.\n\n## Other roadmap items\n- Decide your first goal: leads vs traffic vs brand. I can help you pick.\n- Talk it through with me — 30 minutes and you'll have a campaign brief.\n\n## Suggested opener\nGreet the user by acknowledging they're just getting started with Google Ads.\nReference the budget recommendation by name. End with an open question that\ninvites them to talk through their first campaign. Keep it under 3 sentences.\n",
- "user_first_message": "Hi",
- "expected_assistant_first_reply": {
- "must_contain_any_of": ["daily budget", "first campaign", "\\$50", "\\$100", "getting started", "leads vs"],
- "must_not_contain": ["\\$42", "Brand-US", "wasted spend", "wasted-spend"]
- }
-}
diff --git a/notfair-cmo/tests/evals/cases/no-context.json b/notfair-cmo/tests/evals/cases/no-context.json
deleted file mode 100644
index b7492e97..00000000
--- a/notfair-cmo/tests/evals/cases/no-context.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "name": "no-context",
- "description": "No FIRST_TURN.md present; CMO must NOT fabricate audit findings.",
- "first_turn_md": null,
- "user_first_message": "Hi",
- "expected_assistant_first_reply": {
- "must_contain_any_of": [],
- "must_not_contain": [
- "Brand-US",
- "\\$42",
- "\\$1,260",
- "WASTED_SPEND",
- "wasted spend",
- "wasted-spend",
- "burning \\$",
- "zero-conv",
- "0 conversions in",
- "LOW_QS",
- "Quality Score 5",
- "8 converting search terms"
- ]
- }
-}
diff --git a/notfair-cmo/tests/evals/cases/normal-account.json b/notfair-cmo/tests/evals/cases/normal-account.json
deleted file mode 100644
index a1481d6c..00000000
--- a/notfair-cmo/tests/evals/cases/normal-account.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "name": "normal-account",
- "description": "Audit found a wasted-spend top finding; CMO first reply must reference it concretely.",
- "first_turn_md": "# First-turn context for the CMO\n\nYou have just connected the user's Google Ads account and run a baseline audit.\nThis is a one-shot context: on your FIRST chat turn after the user opens this\nproject's CMO chat, weave the highlights into your greeting, then move this\nfile to MEMORY/last-first-turn-<YYYY-MM-DD>.md so you don't repeat it.\n\n## Audit metadata\n- Project: acme\n- Audit run at: 2026-05-19T14:00:00Z\n- Account state: normal\n- Findings count: 3\n\n## Top finding\n- Category: WASTED_SPEND\n- Headline: Brand-US is burning $42/day on 4 zero-conv keywords\n- Evidence: Last 30 days · 1,200 clicks · $1,260 spent · 0 conv\n- Suggested action: Pause those 4 keywords; expected savings $1,260/mo\n\n## Other findings\n- LOW_QS — 3 keywords below Quality Score 5\n- SEARCH_TERM_GAP — 8 converting search terms not in your keyword list\n\n## Suggested opener\nGreet the user by referencing the top finding by name with the dollar figure.\nMake it personal and specific. End with an open question that invites them to\neither fix the top finding now or talk through the broader audit. Keep it under\n3 sentences.\n",
- "user_first_message": "Hi",
- "expected_assistant_first_reply": {
- "must_contain_any_of": ["Brand-US", "\\$42", "\\$1,260", "wasted spend", "wasted-spend"],
- "must_not_contain": []
- }
-}
diff --git a/notfair-cmo/tests/evals/cmo-first-turn.eval.ts b/notfair-cmo/tests/evals/cmo-first-turn.eval.ts
deleted file mode 100644
index 804c27fb..00000000
--- a/notfair-cmo/tests/evals/cmo-first-turn.eval.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { readFileSync, readdirSync } from "node:fs";
-import { join } from "node:path";
-import { describe, expect, it } from "vitest";
-import { generateText } from "ai";
-import { openai } from "@ai-sdk/openai";
-
-import { TEMPLATES } from "@/server/agent-templates";
-
-/**
- * Goldens for D15: CMO first-turn greeting MUST honor FIRST_TURN.md when
- * present and MUST NOT fabricate audit findings when absent.
- *
- * Each case JSON specifies whether FIRST_TURN.md exists + its content. The
- * production system prompt (from agent-templates.ts) is used unchanged. The
- * eval injects file content via a system-prompt suffix that simulates the
- * agent reading its workspace at session start. The LLM is called with the
- * minimal user "Hi" to elicit the first assistant turn.
- *
- * Skips entirely when OPENAI_API_KEY is absent — the user explicitly
- * declined live evals during the design review (D24). Run with `pnpm eval`
- * to opt in.
- */
-
-type EvalCase = {
- name: string;
- description: string;
- first_turn_md: string | null;
- user_first_message: string;
- expected_assistant_first_reply: {
- must_contain_any_of: string[];
- must_not_contain: string[];
- };
-};
-
-const HAS_KEY = Boolean(process.env.OPENAI_API_KEY);
-const CASES_DIR = join(__dirname, "cases");
-const cases: EvalCase[] = readdirSync(CASES_DIR)
- .filter((f) => f.endsWith(".json"))
- .map((f) => JSON.parse(readFileSync(join(CASES_DIR, f), "utf8")) as EvalCase);
-
-function cmoSystemPrompt(): string {
- const cmo = TEMPLATES.find((t) => t.key === "cmo");
- if (!cmo) throw new Error("CMO template not found in agent-templates.ts");
- return cmo.system_prompt;
-}
-
-function buildSystemMessage(c: EvalCase): string {
- const base = cmoSystemPrompt();
- if (!c.first_turn_md) {
- return `${base}
-
-[Workspace check]
-FIRST_TURN.md does not exist in your workspace.`;
- }
- return `${base}
-
-[Workspace check]
-FIRST_TURN.md IS present in your workspace. Its contents:
-
-=== FIRST_TURN.md ===
-${c.first_turn_md}
-=== END FIRST_TURN.md ===
-
-Per your instructions, weave the file's content into your opening greeting
-now. Treat this as your FIRST chat turn.`;
-}
-
-describe.skipIf(!HAS_KEY)("CMO first-turn (eval, D15)", () => {
- for (const c of cases) {
- it(
- `${c.name} — ${c.description}`,
- async () => {
- const { text } = await generateText({
- model: openai("gpt-4o-mini"),
- system: buildSystemMessage(c),
- prompt: c.user_first_message,
- maxRetries: 1,
- });
-
- const lower = text.toLowerCase();
-
- if (c.expected_assistant_first_reply.must_contain_any_of.length > 0) {
- const matched = c.expected_assistant_first_reply.must_contain_any_of.some(
- (pattern) => new RegExp(pattern, "i").test(text),
- );
- expect(
- matched,
- `\nCMO reply did not reference any of the expected anchors.\nExpected one of: ${c.expected_assistant_first_reply.must_contain_any_of.join(", ")}\nGot:\n${text}\n`,
- ).toBe(true);
- }
-
- for (const forbidden of c.expected_assistant_first_reply.must_not_contain) {
- const re = new RegExp(forbidden, "i");
- expect(
- re.test(text),
- `\nCMO reply contained forbidden phrase \"${forbidden}\".\nGot:\n${text}\n`,
- ).toBe(false);
- }
-
- void lower;
- },
- // Allow up to 30s per case (LLM call latency).
- 30_000,
- );
- }
-});
-
-if (!HAS_KEY) {
- // Surface a non-test diagnostic so the user knows evals were skipped (and why).
- // Vitest prints stdout when --reporter=verbose; in default reporter it's hidden.
- console.log(
- "[evals] OPENAI_API_KEY not set — CMO first-turn evals skipped. Run `pnpm eval` with the key in env to opt in.",
- );
-}
diff --git a/notfair-cmo/vitest.config.ts b/notfair-cmo/vitest.config.ts
deleted file mode 100644
index 647d7637..00000000
--- a/notfair-cmo/vitest.config.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { defineConfig } from "vitest/config";
-import react from "@vitejs/plugin-react";
-import { fileURLToPath } from "node:url";
-import { dirname, resolve } from "node:path";
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-export default defineConfig({
- plugins: [react()],
- resolve: {
- alias: {
- "@": resolve(__dirname, "src"),
- },
- },
- test: {
- // Default environment is `node`. Component / page tests that need a DOM
- // must add `// @vitest-environment jsdom` at the top of the file (vitest 4
- // removed `environmentMatchGlobs` in favor of per-file comments).
- environment: "node",
- globals: false,
- include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
- setupFiles: ["./vitest.setup.ts"],
- coverage: {
- provider: "v8",
- reporter: ["text-summary", "text", "json-summary"],
- include: ["src/**/*.{ts,tsx}"],
- exclude: [
- "src/**/*.test.{ts,tsx}",
- "src/types/**",
- // Server-component pages: data-fetch + render. Better covered by E2E.
- "src/app/**/page.tsx",
- "src/app/**/layout.tsx",
- // shadcn UI primitives: thin wrappers around radix-ui. Testing them
- // tests radix-ui, not our code.
- "src/components/ui/**",
- // Prompt-template strings — covered by the eval harness, not unit tests.
- "src/server/agent-templates.ts",
- // Trivial DOM-resize hook — low value to unit-test in isolation.
- "src/hooks/use-mobile.ts",
- ],
- },
- },
-});
diff --git a/notfair-cmo/vitest.evals.config.ts b/notfair-cmo/vitest.evals.config.ts
deleted file mode 100644
index b685df77..00000000
--- a/notfair-cmo/vitest.evals.config.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { defineConfig } from "vitest/config";
-import { fileURLToPath } from "node:url";
-import { dirname, resolve } from "node:path";
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-/**
- * Separate config for prompt evals. Lives under tests/evals/*.eval.ts so the
- * default `pnpm test` (which globs src/**\/*.test.ts) doesn't trigger them.
- * Run via `pnpm eval`. Skips entirely when OPENAI_API_KEY is absent — the
- * user opted out of live evals during the design review (D24).
- */
-export default defineConfig({
- resolve: {
- alias: {
- "@": resolve(__dirname, "src"),
- },
- },
- test: {
- environment: "node",
- globals: false,
- include: ["tests/evals/**/*.eval.ts"],
- testTimeout: 60_000,
- },
-});
diff --git a/notfair-cmo/vitest.setup.ts b/notfair-cmo/vitest.setup.ts
deleted file mode 100644
index c5dee9b0..00000000
--- a/notfair-cmo/vitest.setup.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import "@testing-library/jest-dom/vitest";
-import { afterEach } from "vitest";
-import { cleanup } from "@testing-library/react";
-
-// vitest 4 disabled globals by default; React Testing Library's auto-cleanup
-// hook (which relies on globals like `afterEach`) no longer fires, so two
-// tests in the same file end up sharing the same DOM. Run cleanup explicitly.
-afterEach(() => {
- cleanup();
-});
diff --git a/notfair-cmo/.claude/scheduled_tasks.lock b/notfair/.claude/scheduled_tasks.lock
similarity index 100%
rename from notfair-cmo/.claude/scheduled_tasks.lock
rename to notfair/.claude/scheduled_tasks.lock
diff --git a/notfair-cmo/.github/workflows/ci.yml b/notfair/.github/workflows/ci.yml
similarity index 100%
rename from notfair-cmo/.github/workflows/ci.yml
rename to notfair/.github/workflows/ci.yml
diff --git a/notfair-cmo/.github/workflows/release.yml b/notfair/.github/workflows/release.yml
similarity index 100%
rename from notfair-cmo/.github/workflows/release.yml
rename to notfair/.github/workflows/release.yml
diff --git a/notfair-cmo/.gitignore b/notfair/.gitignore
similarity index 94%
rename from notfair-cmo/.gitignore
rename to notfair/.gitignore
index 43da16dd..5870f452 100644
--- a/notfair-cmo/.gitignore
+++ b/notfair/.gitignore
@@ -19,7 +19,7 @@ coverage/
.zed/
# Local data dir if symlinked into repo for dev
-.notfair-cmo-dev/
+.notfair-dev/
# npm pack artifacts (release.yml builds these in CI; not for git)
*.tgz
diff --git a/notfair/ARCHITECTURE.md b/notfair/ARCHITECTURE.md
new file mode 100644
index 00000000..ce1f7378
--- /dev/null
+++ b/notfair/ARCHITECTURE.md
@@ -0,0 +1,118 @@
+# Architecture
+
+> Single-user local app. No auth, no multi-tenancy, no hosted backend.
+> One idea: **agent = goal**, and a disciplined loop moves the number.
+
+## The model
+
+```
+project ──▶ agents (user mints as many as they have goals)
+ │ 1:1
+ ▼
+ goal ──▶ metric (executable MCP query, server-verified)
+ │
+ ▼ heartbeat (cron cadence)
+ tick: measure → review past moves → ≤1 new move → diary row
+```
+
+- **Goal lifecycle**: `intake → proposed → active ⇄ paused → achieved | failed | killed`.
+ Defined conversationally in the agent's chat via MCP tools:
+ `define_goal` (record the ambition) → `propose_goal_metric` (agent authors +
+ tests a query; the platform re-runs it server-side and stores the baseline)
+ → `activate_goal` (only after the user explicitly confirms the target).
+- **Measurement discipline**: every mutation is logged *before* execution
+ (`log_goal_action`) with a falsifiable expected effect and an observation
+ window (`review_after`); its resources are untouchable until the window
+ closes, and expired actions must be scored (`review_goal_action`) before
+ any new move. The platform measures the metric mechanically each tick —
+ the agent never self-reports the number it is judged on.
+- **Autonomy**: no approvals. Controls are the spend envelope on the goal,
+ the observation-window gate, and the user's pause/close buttons. Every
+ move is on the record (actions log + tick diary + full transcripts).
+- **Context**: shared workspace context (`PROJECT.md`, synced into every
+ agent identity, writable via `set_shared_context`) + per-agent memory
+ (the `goal_learnings` ledger + the agent's own workspace files). All
+ connected MCPs are registered to every agent.
+
+## Process layout
+
+```
+USER'S MACHINE
+┌────────────────────────────────────────────────────────────────────┐
+│ NotFair (Next.js, `npx notfair` → localhost:3327) │
+│ │
+│ UI: goals index (project root) · per-agent goal dashboard + chat │
+│ + files/skills/cron/settings tabs · crons · connections │
+│ │
+│ Runtime services (SQLite + Node, no external daemon): │
+│ · goals/actions/snapshots/learnings/ticks tables │
+│ · 30s scheduler interval → due goal ticks + cron jobs │
+│ · sessions + transcript_events (chat + tick transcripts) │
+│ · MCP token vault (AES-256-GCM, OS-keychain master key) │
+│ · MCP servers served as Next routes: │
+│ /api/mcp/orchestration (goal tools, shared context, cron) │
+│ /api/mcp/browser (shared workspace Chrome) │
+│ │
+│ Harness adapters spawn a turn as a subprocess: │
+│ claude-code-local (claude CLI) · codex-local (codex CLI) │
+│ per-agent workspace at ~/.notfair/agents/<id>/ with IDENTITY.md │
+│ mirrored to the harness's native files │
+└────────────────────────────────────────────────────────────────────┘
+```
+
+## A tick, end to end
+
+1. `src/server/scheduler/tick.ts` (30s interval, started from
+ `src/instrumentation.ts`) calls `runDueGoalTicks()`.
+2. `src/server/goals/tick.ts` claims the tick (advances `next_tick_at`
+ first — double-fire guard), executes the goal's stored metric query
+ against the catalog MCP via `src/server/mcp/rpc.ts` (token refresh +
+ SSE/JSON parsing handled there), and snapshots the value.
+3. `buildTickMessage` composes the brief purely from DB state: fresh
+ metric, stop-condition flags, actions due for review vs. still gated,
+ recent learnings, last tick summary. The agent's context window is
+ disposable; the DB is the loop's memory.
+4. One adapter turn runs on a `tick-<n>` session; every event persists to
+ `transcript_events`; the result lands as a `goal_ticks` diary row the
+ dashboard renders (and links to the full transcript).
+
+Chat turns hit the same agent through `/api/chat` — same identity, same
+rules; anything decided in chat that future ticks must know is written to
+the learnings ledger by the agent.
+
+## Distribution
+
+- npm package (`notfair` bin); Next.js standalone build started by
+ `bin/cli.mjs`. Runtime requires Node 20+ and at least one harness CLI
+ (`claude` or `codex`) installed + authenticated.
+- Data at `~/.notfair/` (override `NOTFAIR_DATA_DIR`): `db.sqlite`,
+ `agents/<id>/`, `projects/<slug>/PROJECT.md`, `mcp-server-secret`.
+
+## Module map (orientation, not exhaustive)
+
+```
+src/server/goals/ the loop: identity.ts (prompt), tick.ts (runner),
+ metric.ts (server-side MCP measurement),
+ handlers.ts (MCP tool handlers), provision.ts
+src/server/db/goals.ts goal state machine + actions/snapshots/learnings/ticks
+src/server/mcp-server/ orchestration + browser MCP servers (Next routes)
+src/server/adapters/ HarnessAdapter contract + claude/codex implementations
+src/server/scheduler/ scheduled_jobs + the shared 30s interval
+src/server/mcp/ catalog MCP tokens, OAuth refresh, JSON-RPC client
+src/app/(app)/[project]/ goals index (root), agents/[agent]/ (dashboard,
+ chat, files, skills, cron, settings), crons,
+ connections, settings
+```
+
+## Why this shape
+
+- **Loop state lives in SQLite, not context windows.** Contexts rotate;
+ `get_goal` re-anchors an agent from the DB in one call.
+- **The metric is executable, not descriptive.** Storing the exact tool
+ call lets the platform measure before the agent wakes and verify
+ metrics at intake — trust comes from reproducibility.
+- **No org chart.** There is exactly one kind of agent. Coordination
+ across agents happens through the shared workspace context, not
+ through delegation machinery.
+- **Don't rebuild the wheels.** Harness CLIs bring the LLM runtime and
+ login; NotFair adds the loop, the bookkeeping, and the UI.
diff --git a/notfair-cmo/CHANGELOG.md b/notfair/CHANGELOG.md
similarity index 81%
rename from notfair-cmo/CHANGELOG.md
rename to notfair/CHANGELOG.md
index 4f72c32c..ed557bc2 100644
--- a/notfair-cmo/CHANGELOG.md
+++ b/notfair/CHANGELOG.md
@@ -1,4 +1,28 @@
-# notfair-cmo
+# NotFair
+
+## 0.9.0 — 2026-07-10
+
+**Renamed: notfair-cmo is now just NotFair — and the CMO is gone.** The product pivoted from "a CMO delegating to platform specialists" to **agent = goal**: you mint an agent per goal, define the goal by chatting with it, and it runs a disciplined improvement loop until the number says done. npm package `notfair-cmo` → `notfair` (bin: `notfair`), data dir `~/.notfair-cmo` → `~/.notfair` (auto-migrated on first start, merging safely with any plugin config already there), env vars `NOTFAIR_CMO_*` → `NOTFAIR_*`.
+
+**Conversational goal intake with server-verified metrics.** A fresh agent's goal is empty; the chat defines it: the agent records the ambition (`define_goal`), explores your connected platforms, authors + tests ONE query that returns a single number, and submits it (`propose_goal_metric`) — the platform re-runs the exact call server-side and only a reproducible number, with its measured baseline, moves the goal forward. The loop starts only after you explicitly confirm the target in chat (`activate_goal` rejects targets on the wrong side of the baseline).
+
+**Heartbeat ticks with measurement discipline.** On your cadence, the platform measures the metric mechanically — agents never self-report the number they're judged on — and wakes the agent with a tick brief: current reading, actions due for review vs. still gated, memory, stop-condition flags. Mutations must be logged before execution with a falsifiable expected effect and an observation window that gates their resources until review; expired actions must be scored against their predictions before any new move; "achieved" is rejected by the server unless the measured metric meets the target. One mutation per tick, hard stop.
+
+**Everything legacy is deleted, not deprecated.** The CMO and platform-specialist agents, the task board/kanban, the approvals inbox + policies, the questions system, the activity log, and the delegation machinery are all gone — UI, MCP tools, server modules, and tests. Agents run autonomously inside a spend envelope; your controls are the envelope, the observation-window gate, and pause/close. The MCP surface is now 12 tools: the goal lifecycle + loop bookkeeping, `get_project`, `set_shared_context`, and `schedule_recurring_work`.
+
+**Shared context + private memory.** `PROJECT.md` is the workspace brief every agent carries in its identity (any agent updates it via `set_shared_context`, which re-renders all agent identities); each agent keeps its own learnings ledger (`log_learning` / `search_learnings`) and workspace files. All connected MCPs register to every agent automatically.
+
+**New surfaces.** The project root is the goals index (one row per agent: status, statement, live metric); each agent's page is its goal dashboard — sparkline vs. target, tick diary linking to full transcripts, open actions with review dates, memory — with Chat/Files/Skills/Cron/Settings tabs. Onboarding is two steps (name workspace → connect sources) and drops you at the goals index. Sidebar: Goals + Crons/Connections/Settings.
+
+**Goals are the only identity.** No agent personas: the sidebar and every page label goals by an agent-written `short_label` ("Wasted X spend → $0"); the machinery behind a goal is "this goal's agent", full stop. Routes live under `/goals/…`, creation is statement-first (type the ambition, land inside the already-streaming kickoff thread), and platform-generated briefs render as compact system lines, not fake user bubbles.
+
+**Consent + control are platform-enforced.** The agent can propose everything but start nothing: `propose_target` records the plan, the user's START click begins the loop and fires the first tick immediately. Live goals are amendable in chat (`amend_goal`); per-action spend is logged and totaled against the envelope in every tick brief; other agents' observation-gated resources appear in each brief; idle-gated loops sleep until the earliest review date. Two goal modes: **achieve** (complete at target) and **maintain** (hold the number forever — target met is the steady state, and the loop never self-closes).
+
+**Progress you can see.** Each goal's rail carries a time-true progress chart: the metric line with target/baseline references, every agent mutation as a hoverable marker (predicted vs. observed effect), observation windows shaded, deadline flagged, crosshair tooltips. New `backfill_metric_history` tool lets the agent reconstruct ~30 days of per-day history at setup (platform-verified like the metric), so the chart has context from day one. Maintain goals lead with a streak — "held at target for N days" — plus a per-check strip (held / intervened / drifted); the workspace index gains mini sparklines and 7-day deltas per goal. (Migration 022.)
+
+**One screen per goal, one scheduler.** The goal page unifies chat + status rail (metric, sparkline, checks with full logs, open actions, memory) — the Goal/Chat/Files/Settings tabs, chat-thread management, and the entire Crons surface (page, tool, engine) are gone. The heartbeat is the only recurring thing in the product, and the nav is: your goals, Connections, Settings.
+
+Schema: migrations 017–021 (goal tables; one live goal per agent; per-action spend; short labels; goal mode). Eval suite `goal-tick.eval.ts` locks the loop's three invariants (stop at target, review first, respect the gate).
## 0.8.0 — 2026-07-07
@@ -14,9 +38,9 @@
## 0.7.1 — 2026-06-06
-**Sidebar shows the installed version + a one-click Upgrade button.** The sidebar footer now always displays `notfair-cmo v<x.y.z>`. When the npm registry has a newer release, an `v<x.y.z> available` button appears next to it — click runs `npm i -g notfair-cmo@latest` via a new `/api/upgrade` endpoint and surfaces "Restart to apply" on success. Latest-version lookup is cached 1 hour in-process so the sidebar polling doesn't pound `registry.npmjs.org`.
+**Sidebar shows the installed version + a one-click Upgrade button.** The sidebar footer now always displays `NotFair v<x.y.z>`. When the npm registry has a newer release, an `v<x.y.z> available` button appears next to it — click runs `npm i -g notfair@latest` via a new `/api/upgrade` endpoint and surfaces "Restart to apply" on success. Latest-version lookup is cached 1 hour in-process so the sidebar polling doesn't pound `registry.npmjs.org`.
-When `npm` isn't discoverable on the user's PATH (rare but real on minimal shells), `/api/upgrade` returns the command string instead and the client copies `npm i -g notfair-cmo@latest` to the clipboard so the user can run it themselves.
+When `npm` isn't discoverable on the user's PATH (rare but real on minimal shells), `/api/upgrade` returns the command string instead and the client copies `npm i -g notfair@latest` to the clipboard so the user can run it themselves.
## 0.7.0 — 2026-06-06
@@ -34,7 +58,7 @@ E2E verified: fresh Codex chat turn — Greg (CMO) asked to open https://example
## 0.6.0 — 2026-06-05
-**Workspace browser tool — agents can drive real Chrome.** One managed Chrome instance per workspace at `~/.notfair-cmo/projects/<slug>/browser/user-data/`, shared by every agent in that project via labeled tabs. The user signs into Google / Meta / Search Console once (Settings → Workspace browser → Launch + Open <service>), cookies persist in the workspace profile, and every agent inherits the session on subsequent runs.
+**Workspace browser tool — agents can drive real Chrome.** One managed Chrome instance per workspace at `~/.notfair/projects/<slug>/browser/user-data/`, shared by every agent in that project via labeled tabs. The user signs into Google / Meta / Search Console once (Settings → Workspace browser → Launch + Open <service>), cookies persist in the workspace profile, and every agent inherits the session on subsequent runs.
The agent surface is 11 small typed MCP tools — `browser_status`, `browser_tabs`, `browser_open`, `browser_close`, `browser_navigate`, `browser_snapshot`, `browser_click`, `browser_type`, `browser_press`, `browser_scroll`, `browser_back` — matching the granularity of the rest of the `notfair-orchestration` MCP. `browser_shutdown` is intentionally NOT exposed to agents: with multiple agents sharing one workspace Chrome, any agent calling shutdown would kill the browser mid-task for the others. Browser lifecycle is user-owned (Settings → Stop) and process-exit-owned.
@@ -44,7 +68,7 @@ Agents are taught the snapshot-before-act discipline and the `label=<agent_id>`
**Settings → Workspace browser card.** Live status (running / not running, port, uptime, idle countdown), Launch / Stop, sign-in shortcuts for Google / Meta / Search Console, and a list of open tabs. Verified end-to-end in dev: launching from Settings spawns Chrome with the workspace `--user-data-dir`, status flips to running, Stop tears it down cleanly.
-Under the hood: Chrome lifecycle (binary discovery, `SingletonLock` cleanup, deterministic CDP port allocation in 19000-19099) borrowed from openclaw; Playwright (CDP-attach mode, via `playwright-core`) for the actual page driving. No bundled browser — uses system Chrome. SSRF/loopback hardening from openclaw was intentionally NOT ported: notfair-cmo is single-user localhost-only, and the MCP server already requires bearer auth.
+Under the hood: Chrome lifecycle (binary discovery, `SingletonLock` cleanup, deterministic CDP port allocation in 19000-19099) borrowed from openclaw; Playwright (CDP-attach mode, via `playwright-core`) for the actual page driving. No bundled browser — uses system Chrome. SSRF/loopback hardening from openclaw was intentionally NOT ported: NotFair is single-user localhost-only, and the MCP server already requires bearer auth.
## 0.5.0 — 2026-06-03
@@ -195,7 +219,7 @@ End-to-end wiring + reliability pass on top of the 0.2.0 harness-agnostic rewrit
### Internal
-- `notfair-cmo doctor` drops the OpenClaw / gateway / LLM-config probes; now checks Claude Code + Codex per adapter, requires at least one.
+- `NotFair doctor` drops the OpenClaw / gateway / LLM-config probes; now checks Claude Code + Codex per adapter, requires at least one.
- `agents/files.ts` simplified — fs reader returns every workspace file in one pass.
- 870 tests, 73 test files. Adapter parsers, MCP config writers (Claude Code + Codex), pub/sub emitter, scheduler tool, project delete cascade, sidebar live-counts context, abandoned-task UI flows all covered.
@@ -207,7 +231,7 @@ No DB migration required (the schema landed in 0.2.0). The OAuth callback now au
### Harness-agnostic rewrite
-notfair-cmo is no longer coupled to OpenClaw. Agents run through pluggable
+NotFair is no longer coupled to OpenClaw. Agents run through pluggable
harness adapters — Claude Code (default) and Codex ship as the first two
supported options, and the architecture is open for more.
@@ -259,7 +283,7 @@ supported options, and the architecture is open for more.
**bin/cli.mjs**
-- `notfair-cmo doctor` checks Claude Code and Codex separately, requires at
+- `NotFair doctor` checks Claude Code and Codex separately, requires at
least one of them on PATH, and drops every former `openclaw --version` /
gateway / LLM-config probe.
diff --git a/notfair/CLAUDE.md b/notfair/CLAUDE.md
new file mode 100644
index 00000000..65c9e818
--- /dev/null
+++ b/notfair/CLAUDE.md
@@ -0,0 +1,86 @@
+# CLAUDE.md
+
+Project conventions and notes for AI assistants working on NotFair.
+
+## What NotFair is
+
+A local, single-user, goal-driven agent runner. The user states a goal; NotFair
+provisions an anonymous agent for it (agent = goal, 1:1), the agent defines a
+platform-verifiable metric + target in chat, the user clicks START, and a
+heartbeat loop ("checks") measures the metric and lets the agent act — with
+observation windows, a spend envelope, and per-goal memory as the controls.
+No approvals, no tasks, no orchestration layer: goals are the only unit.
+
+## Verification (no test suite by design)
+
+This repo intentionally carries no unit tests, migrations, or legacy/compat
+code. Verification is:
+
+1. `pnpm typecheck` — must be clean.
+2. `pnpm build` — must be clean.
+3. Live smoke: `pnpm dev` (port 3326), then walk the affected flow in the
+ browser (goal index → goal page → chat / START / checks).
+
+Prompt-affecting changes (`src/server/goals/identity.ts`, tick briefs in
+`src/server/goals/tick.ts`, tool descriptions in
+`src/server/mcp-server/tools.ts`) must be validated by running a real goal
+loop end-to-end and reading the agent's actual behavior in the transcript.
+
+## Project structure conventions
+
+- **Database**: SQLite via `better-sqlite3` at `~/.notfair/db.sqlite`
+ (overridable via `NOTFAIR_DATA_DIR`). The entire schema lives in
+ `src/server/db/schema.ts` and is applied idempotently on boot — there is
+ no migration system. Schema changes edit that file; dev databases are
+ recreated, not migrated.
+- **Agent state**: agent workspaces live at `~/.notfair/agents/<agent-id>/`.
+ NotFair owns the workspace; the chosen harness adapter writes whatever
+ files it expects (CLAUDE.md for Claude Code, AGENTS.md for Codex, plus the
+ shared IDENTITY.md / SKILL.md / PROJECT.md NotFair writes).
+- **Sessions / transcripts**: stored in SQLite (`sessions`,
+ `transcript_events`). The chat route persists every adapter event; the UI
+ replays them on attach. Tick sessions are labeled `tick-<n>`; the intake
+ chat is `main`.
+- **Goals**: agent = goal. `goals` + `goal_actions` + `goal_metric_snapshots`
+ + `goal_learnings` + `goal_ticks` tables; db module `src/server/db/goals.ts`;
+ loop runtime under `src/server/goals/` (intake, tick, metric, provision,
+ identity). The 30s scheduler in `src/server/scheduler/tick.ts` sweeps
+ `goals.next_tick_at`.
+- **MCP**: NotFair exposes two internal MCP servers as Next routes —
+ `notfair-goals` (`/api/mcp/goals`, the goal tools) and `notfair-browser`
+ (`/api/mcp/browser`). External catalog tokens are project-scoped in
+ `mcp_tokens`; every agent in a project gets every connected server.
+- **Memory**: shared workspace context is `~/.notfair/projects/<slug>/PROJECT.md`
+ (synced into every agent identity; written via the `set_shared_context`
+ tool). Per-agent memory is the `goal_learnings` ledger + the agent's own
+ workspace files.
+
+## Architectural tenets
+
+- **Harness-agnostic.** NotFair runs on top of any local AI coding agent that
+ conforms to the `HarnessAdapter` contract under `src/server/adapters/`.
+ Today: Claude Code (`claude-code-local`) and Codex (`codex-local`).
+- **NotFair owns the runtime services.** Goal scheduling, MCP token storage,
+ agent provisioning, session/transcript persistence — all in SQLite + Node.
+ Adapters only handle: (1) spawning the harness to stream a turn, (2) writing
+ harness-specific workspace config, (3) registering MCP servers for the
+ harness to find.
+- **Single-user local CLI.** A local Next.js process launched via the
+ `notfair` bin. No multi-tenant code paths, no auth, no multi-process state
+ coordination.
+- **No legacy code.** No migration shims, no backward-compat branches, no
+ dead flags. When a concept is removed, every trace of it goes — code,
+ schema, comments, and on-disk state.
+- **Don't rebuild the wheels.** Before proposing any new abstraction,
+ identify whether an existing tool already solves the sub-problem. Prefer
+ thin glue layers over custom infrastructure.
+
+## Commit style
+
+Conventional commits with type-scope-description: `feat(goals): backfill
+metric history at intake`, `fix(tick): clamp smart sleep to deadline`.
+
+Co-author trailer when AI-assisted:
+```
+Co-Authored-By: Claude Fable 5 <[email protected]>
+```
diff --git a/notfair-cmo/CONTRIBUTING.md b/notfair/CONTRIBUTING.md
similarity index 91%
rename from notfair-cmo/CONTRIBUTING.md
rename to notfair/CONTRIBUTING.md
index 7aad0091..a494ded3 100644
--- a/notfair-cmo/CONTRIBUTING.md
+++ b/notfair/CONTRIBUTING.md
@@ -1,12 +1,12 @@
# Contributing
-Thanks for poking around! notfair-cmo is small, opinionated, and willing to grow.
+Thanks for poking around! NotFair is small, opinionated, and willing to grow.
## Dev setup
```bash
-git clone https://github.com/notfair-co/notfair-cmo.git
-cd notfair-cmo
+git clone https://github.com/notfair-co/notfair.git
+cd NotFair
pnpm install
```
@@ -23,7 +23,7 @@ Quickest way to verify the host machine is set up is the doctor, which the
shipped CLI exposes and which you can run against the dev source too:
```bash
-pnpm cli doctor # same checks the published `notfair-cmo doctor` runs
+pnpm cli doctor # same checks the published `NotFair doctor` runs
```
## Dev loop
@@ -37,21 +37,21 @@ pnpm cli # tsx bin/cli.ts in dev (the published CLI is bin/cli.mjs)
```
`pnpm dev` is the day-to-day. The dev server points at the same
-`~/.notfair-cmo/db.sqlite` as a globally installed `notfair-cmo` does, so if
+`~/.notfair/db.sqlite` as a globally installed `notfair` does, so if
you also run the published CLI on this machine, point one of them at a
different data dir to avoid stomping each other's state:
```bash
-NOTFAIR_CMO_DATA_DIR=$PWD/.notfair-cmo-dev pnpm dev
+NOTFAIR_DATA_DIR=$PWD/.notfair-dev pnpm dev
```
-`.notfair-cmo-dev/` is already gitignored.
+`.notfair-dev/` is already gitignored.
To reset local state for a clean run, stop any running server and:
```bash
-rm ~/.notfair-cmo/db.sqlite # blow away product state
-rm -rf ~/.notfair-cmo/agents/ # blow away agent workspaces
+rm ~/.notfair/db.sqlite # blow away product state
+rm -rf ~/.notfair/agents/ # blow away agent workspaces
openclaw agents rm <agent-name> # remove any orphaned agents
```
diff --git a/notfair-cmo/DESIGN.md b/notfair/DESIGN.md
similarity index 96%
rename from notfair-cmo/DESIGN.md
rename to notfair/DESIGN.md
index 0a9f040c..f1a76035 100644
--- a/notfair-cmo/DESIGN.md
+++ b/notfair/DESIGN.md
@@ -1,4 +1,4 @@
-# notfair-cmo Design System
+# NotFair Design System
**Direction.** Codex-flavored product UI: monochrome chrome, dark-first with a full light mode, depth from **elevation** (surface steps + soft shadows) instead of border lines, monospace for machine-flavored metadata. Color is reserved for **semantics** — green means live/connected, amber means attention, red means error. Primary actions are inverted monochrome (white-on-dark / black-on-light), the OpenAI/Codex signature.
@@ -8,7 +8,7 @@ If a design choice would feel at home in the OpenAI Codex app or ChatGPT's produ
## Brand
-The mark lives at `notfair-cmo/public/notfair-mark.svg` (green "!" + ink "F") with a dark-mode variant at `public/notfair-mark-dark.svg` (the F flips to light ink). Swap them with `dark:hidden` / `hidden dark:block` — never render the light mark on a dark surface.
+The mark lives at `notfair/public/notfair-mark.svg` (green "!" + ink "F") with a dark-mode variant at `public/notfair-mark-dark.svg` (the F flips to light ink). Swap them with `dark:hidden` / `hidden dark:block` — never render the light mark on a dark surface.
The green `#4CAF6E` lifted from the mark is `--notfair-accent`. It is **status-only**: connected dots, live indicators, "ok" run outcomes, completed wizard pips, the recommended chip. It is never a CTA fill, never a link color, never chrome.
diff --git a/notfair-cmo/LICENSE b/notfair/LICENSE
similarity index 95%
rename from notfair-cmo/LICENSE
rename to notfair/LICENSE
index 6ab18489..26abff99 100644
--- a/notfair-cmo/LICENSE
+++ b/notfair/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2026 notfair-cmo contributors
+Copyright (c) 2026 NotFair contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/notfair-cmo/PLAN.md b/notfair/PLAN.md
similarity index 96%
rename from notfair-cmo/PLAN.md
rename to notfair/PLAN.md
index 2ddb05b1..ef7a4be9 100644
--- a/notfair-cmo/PLAN.md
+++ b/notfair/PLAN.md
@@ -2,11 +2,11 @@
status: ACTIVE
---
-# CEO Plan: notfair CMO — AI Marketing OS
+# CEO Plan: NotFair (né notfair CMO) — AI Marketing OS
Generated by /plan-ceo-review on 2026-05-17
Mode: SCOPE EXPANSION | Approach: B (CMO-first Marketing OS)
-Repo: notfari-workspace/notfair-cmo (greenfield)
+Repo: notfair-workspace/notfair (greenfield)
---
@@ -18,7 +18,7 @@ Repo: notfari-workspace/notfair-cmo (greenfield)
## PIVOT (Revision 5, 2026-05-17): open-source local CLI tool
-**Major scope adjustment.** notfair CMO is now an **open-source local app** distributed as an npm package. User runs `npx notfair-cmo` in their terminal; it launches a local Next.js server on `localhost:3000` and opens their browser. Single-user, single-machine, no SaaS hosting, no auth, no multi-tenancy. **OpenClaw is assumed installed + running locally on the user's machine** (we verified its capabilities via live spike — see [[openclaw-capabilities]]).
+**Major scope adjustment.** notfair CMO is now an **open-source local app** distributed as an npm package. User runs `npx notfair` in their terminal; it launches a local Next.js server on `localhost:3000` and opens their browser. Single-user, single-machine, no SaaS hosting, no auth, no multi-tenancy. **OpenClaw is assumed installed + running locally on the user's machine** (we verified its capabilities via live spike — see [[openclaw-capabilities]]).
This pivot eliminates significant infrastructure (multi-tenant auth, RLS, envelope encryption per tenant, hosted Postgres, Vercel deployment, AI Gateway tenancy tagging) AND leverages OpenClaw native capabilities we were about to rebuild (memory, cron, agent isolation, MCP tool exposure, WebSocket gateway). Net effect: V1 effort drops from ~3-4 weeks CC to ~1-2 weeks CC.
@@ -57,9 +57,9 @@ The user sets direction at 9am, reviews outcomes at 5pm. Overnight, agents ran e
## Approach: B-local — CMO-first Marketing OS (open-source local)
Substrate:
-- **Distribution:** npm package; user runs `npx notfair-cmo` → spawns local Next.js server + opens browser
+- **Distribution:** npm package; user runs `npx notfair` → spawns local Next.js server + opens browser
- **Frontend:** Next.js App Router (standalone build, runs locally — no Vercel)
-- **Local DB:** SQLite (better-sqlite3) at `~/.notfair-cmo/db.sqlite` for our own state (tasks, approvals, cost events, oauth tokens, project metadata)
+- **Local DB:** SQLite (better-sqlite3) at `~/.notfair/db.sqlite` for our own state (tasks, approvals, cost events, oauth tokens, project metadata)
- **AI orchestration:** AI SDK v6 with user's own LLM API key (OpenAI/Anthropic/Google — they supply); no AI Gateway tenancy needed
- **Agent runtime:** **OpenClaw** (assumed installed + running on user's machine). We invoke via subprocess (`openclaw ... --json`) and connect to its WebSocket Gateway on loopback.
- **Agent memory:** **OpenClaw memory subsystem** (built-in: index, search, REM reflection, promotion to MEMORY.md). We don't run pgvector.
@@ -104,8 +104,8 @@ We do NOT own:
## Accepted scope (V1) — post-pivot
### CLI + launcher
-1. **`notfair-cmo` CLI** — npm package; `npx notfair-cmo` or `pnpm dlx notfair-cmo` starts local Next.js server, opens browser at `http://localhost:<port>`. Subcommands: `start` (default), `stop`, `doctor` (checks OpenClaw is running), `version`.
-2. **Local data dir** at `~/.notfair-cmo/` (SQLite + logs + cached scrape data). Override via `--data-dir`.
+1. **`notfair` CLI** — npm package; `npx notfair` or `pnpm dlx notfair` starts local Next.js server, opens browser at `http://localhost:<port>`. Subcommands: `start` (default), `stop`, `doctor` (checks OpenClaw is running), `version`.
+2. **Local data dir** at `~/.notfair/` (SQLite + logs + cached scrape data). Override via `--data-dir`.
3. **Doctor command** — verifies OpenClaw is installed + running (`openclaw health`), LLM API key set, port available; surfaces clear fix-instructions for any failure.
### Core product (UI)
@@ -485,7 +485,7 @@ Per the guiding tenet, every custom thing must be justified. Updated after live
| **MCP server exposing our tools** | ✅ JUSTIFIED CUSTOM | `approve_action`, `record_cost`, `log_action`, `query_project_state` etc. are notfair-CMO-specific; how OpenClaw agents reach our state |
| **OAuth flows + token storage** | ✅ JUSTIFIED CUSTOM | Localhost callback flow + OS-keychain-encrypted SQLite storage. OpenClaw doesn't manage external API OAuth tokens for our purpose |
| **Project concept (name-prefix grouping)** | ✅ JUSTIFIED CUSTOM | OpenClaw is flat-namespaced; project = our UX concept layered on top via consistent agent/cron name prefixes |
-| **CLI launcher (`npx notfair-cmo`)** | ✅ JUSTIFIED CUSTOM | Distribution; no off-the-shelf option fits |
+| **CLI launcher (`npx notfair`)** | ✅ JUSTIFIED CUSTOM | Distribution; no off-the-shelf option fits |
---
@@ -493,7 +493,7 @@ Per the guiding tenet, every custom thing must be justified. Updated after live
### Our MCP server: tools exposed to OpenClaw agents
-Our Next.js runs an MCP server (stdio when the agent invokes via OpenClaw runtime, or HTTP-over-loopback for the gateway-mode setup). Registered with OpenClaw via `openclaw mcp set notfair-cmo '{ ... }'`. Every project's CMO + specialist agents are configured to load this MCP.
+Our Next.js runs an MCP server (stdio when the agent invokes via OpenClaw runtime, or HTTP-over-loopback for the gateway-mode setup). Registered with OpenClaw via `openclaw mcp set NotFair '{ ... }'`. Every project's CMO + specialist agents are configured to load this MCP.
Tools:
- `assign_task(project_slug, specialist_agent_id, brief, success_criteria, deadline_iso)` → `{task_id}`. Creates row in our SQLite `tasks` table. Returns task_id. Specialist picks up the brief by querying task status at next turn or via cron trigger.
@@ -602,15 +602,15 @@ Tasks live in our SQLite `tasks` table. OpenClaw agents reference them by task_i
1. **CMO loop: OpenClaw agent per project.** `openclaw agents add <project-slug>-cmo` with our MCP server attached. CMO calls our tools via MCP (zero HTTP roundtrips — stdio). Specialist agents same pattern: `<project-slug>-google-ads`, `<project-slug>-seo`.
2. **No auth.** Local loopback only. OpenClaw gateway started with `--auth none --bind loopback`. Our Next.js binds to 127.0.0.1 only. No Clerk. Settings page is single-user; no roles, no permissions.
-3. **Storage: SQLite via better-sqlite3.** Single file at `~/.notfair-cmo/db.sqlite`. Tables: `projects`, `tasks`, `approvals`, `cost_events`, `oauth_tokens`, `guardrails`, `agent_actions`. No pgvector — memory is OpenClaw's job.
+3. **Storage: SQLite via better-sqlite3.** Single file at `~/.notfair/db.sqlite`. Tables: `projects`, `tasks`, `approvals`, `cost_events`, `oauth_tokens`, `guardrails`, `agent_actions`. No pgvector — memory is OpenClaw's job.
4. **Long-running work: OpenClaw cron + cursor in our SQLite.** Cold email sequences = a cron that runs the agent every N minutes; agent reads `cursor` from our `sequence_runs` table, processes next chunk, updates cursor, exits. Same pattern as before but now OpenClaw is running, not Vercel — no 300s timeout pressure (OpenClaw can run longer turns), but pattern is unchanged for resilience.
5. **Inter-process integration: subprocess + MCP.** Three integration surfaces with OpenClaw:
- **CLI subprocess** for management ops (`agents add`, `cron add/list/edit/rm`, `memory search/index`): spawn `openclaw <cmd> --json`, parse stdout. Wrapped in `apps/web/lib/openclaw/cli.ts`.
- **WebSocket Gateway** for agent invocation with streaming (`openclaw gateway` running; we connect via `ws://localhost:<port>`). Wrapped in `apps/web/lib/openclaw/gateway.ts`.
- - **MCP server** (we run) exposing our tools to OpenClaw agents. Registered once at install via `openclaw mcp set notfair-cmo '{...}'`. Implementation in `apps/web/lib/mcp-server/`.
+ - **MCP server** (we run) exposing our tools to OpenClaw agents. Registered once at install via `openclaw mcp set NotFair '{...}'`. Implementation in `apps/web/lib/mcp-server/`.
6. **OAuth: localhost callback + OS-keychain master key.** Localhost redirect (Google Ads + GSC accept this for desktop apps). Master key generated on first launch + stored in OS keychain via `keytar`. OAuth tokens AES-256-GCM encrypted with this key, stored in SQLite. Refresh handled by a single function called before any agent action; no cron needed.
7. **Real-time UI: SSE from our Next.js to browser, gateway WebSocket from Next.js to OpenClaw.** Chat uses AI SDK streaming through our Next.js (which proxies to gateway WS). Task board / approvals / cron tab updates via SSE that listens to a local pub/sub (Node `EventEmitter` is sufficient — single-process).
-8. **Distribution: npm package + standalone Next.js build.** `notfair-cmo` package exports a CLI bin. CLI uses `next start` against a pre-built `.next/standalone` directory. Targets Node 20+. No native deps beyond `better-sqlite3` and `keytar` (both have prebuilds for major platforms).
+8. **Distribution: npm package + standalone Next.js build.** `notfair` package exports a CLI bin. CLI uses `next start` against a pre-built `.next/standalone` directory. Targets Node 20+. No native deps beyond `better-sqlite3` and `keytar` (both have prebuilds for major platforms).
9. **No monorepo.** Single-package npm project. TypeScript types live in `src/types/` and are imported via relative paths. (Monorepo was needed when CMO ran in OpenClaw with separate tool definitions; now everything is in our Next.js codebase or in OpenClaw config.)
10. **Project = name-prefix grouping.** Project slug is the prefix on OpenClaw agent names and cron names. Project metadata (display name, slug, created_at, archived_at) lives in our SQLite. Archive = mark archived + disable all matching crons + optionally remove agents.
@@ -699,8 +699,8 @@ V1 ship gate: all E2E + EVAL paths green
| Codepath | Failure | Test | Handling | User sees |
|---|---|---|---|---|
-| CLI launch | OpenClaw not installed/running | doctor cmd | `notfair-cmo doctor` runs at startup; surfaces clear install instructions if missing | Terminal output: "OpenClaw not running. Start it with `openclaw gateway` then retry." |
-| CLI launch | Port already in use | Unit | Try N+1 up to 5 times; surface chosen port | "notfair-cmo running on http://localhost:3247 (3000 was busy)" |
+| CLI launch | OpenClaw not installed/running | doctor cmd | `NotFair doctor` runs at startup; surfaces clear install instructions if missing | Terminal output: "OpenClaw not running. Start it with `openclaw gateway` then retry." |
+| CLI launch | Port already in use | Unit | Try N+1 up to 5 times; surface chosen port | "NotFair running on http://localhost:3247 (3000 was busy)" |
| CMO turn | OpenClaw subprocess fails | Integration | Catch, retry once with backoff; surface error to UI | "Couldn't reach agent. Try `openclaw doctor` in another terminal." |
| MCP tool call | Tool throws unexpectedly | Unit | `defineMcpTool` wraps in try/catch, returns standard error envelope | Agent sees structured error, retries or surfaces to user |
| `approve_action` | Race: two agents check cap simultaneously | Unit | SQLite transaction with `BEGIN IMMEDIATE` around check+record | Second action sees updated state, halts correctly |
@@ -758,7 +758,7 @@ Live spike against the running OpenClaw v2026.5.7 install on user's machine. All
## Success criteria (V1 ship readiness)
-- `npx notfair-cmo` works on fresh macOS + Linux + WSL machine where OpenClaw is installed
+- `npx notfair` works on fresh macOS + Linux + WSL machine where OpenClaw is installed
- Solo founder can complete onboarding (URL → first plan) in <5 minutes
- CMO can launch and monitor a Google Ads campaign within guardrails (using user's connected Google Ads account)
- CMO can launch SEO work (audit, content recommendations) and surface signals consumed by Google Ads agent on next turn
@@ -777,7 +777,7 @@ Live spike against the running OpenClaw v2026.5.7 install on user's machine. All
| Risk | Likelihood | Impact | Mitigation |
|------|-----------|--------|-----------|
-| Users don't have OpenClaw installed | High | High | `doctor` command surfaces install instructions; README leads with OpenClaw prereq; consider bundling OpenClaw install script as part of `notfair-cmo install` |
+| Users don't have OpenClaw installed | High | High | `doctor` command surfaces install instructions; README leads with OpenClaw prereq; consider bundling OpenClaw install script as part of `NotFair install` |
| OpenClaw version drift breaks our subprocess wrapper | Med | High | Test against multiple OpenClaw versions in CI; record min-supported version; fail fast with clear error |
| Google Ads OAuth complexity (localhost callback edge cases) | Med | Med | Use Google's standard desktop-app OAuth flow; document well; provide troubleshooting in doctor |
| User runs out of disk for SQLite/memory growth | Low | Med | Default cap on memory entries per agent; quarterly cleanup cron; doctor shows db size |
@@ -792,7 +792,7 @@ Live spike against the running OpenClaw v2026.5.7 install on user's machine. All
## Recommended next steps (post-pivot)
-1. **Scaffold the project** — `pnpm create next-app notfair-cmo`, set up directory structure (`src/server/`, `src/app/`, `src/types/`, `bin/`), install deps (`ai`, `@ai-sdk/openai`, `@ai-sdk/anthropic`, `better-sqlite3`, `keytar`, `zod`, `commander`, shadcn-cli), set up `package.json` with `bin` entry.
+1. **Scaffold the project** — `pnpm create next-app NotFair`, set up directory structure (`src/server/`, `src/app/`, `src/types/`, `bin/`), install deps (`ai`, `@ai-sdk/openai`, `@ai-sdk/anthropic`, `better-sqlite3`, `keytar`, `zod`, `commander`, shadcn-cli), set up `package.json` with `bin` entry.
2. **Doctor command** — `bin/cli.ts doctor` that verifies OpenClaw is installed + running + accessible. Build first; surfaces what's missing for users.
3. **OpenClaw CLI wrapper** — `src/server/openclaw/cli.ts` with `openclaw(args)` function. Cover the operations we need (agents add/list, cron add/list/disable, memory search, mcp set).
4. **SQLite schema + migrations** — `src/server/db/migrations/001_init.sql` with `projects`, `tasks`, `approvals`, `cost_events`, `oauth_tokens`, `guardrails`, `agent_actions`, `sequence_runs`.
diff --git a/notfair/README.md b/notfair/README.md
new file mode 100644
index 00000000..1c16d22b
--- /dev/null
+++ b/notfair/README.md
@@ -0,0 +1,105 @@
+# NotFair
+
+> Goal-driven, loop-powered marketing on your machine, on top of Claude Code or Codex. State an ambition — "cut CAC to $30", "keep wasted spend at $0" — and a dedicated agent turns it into a measured metric and runs a disciplined loop against it. Goals are the only thing you name, see, and manage; the agents behind them are invisible plumbing.
+
+Open source. Runs entirely on your machine. Bring your own LLM credentials (via the harness CLI you already authenticate to) and your own ad-platform OAuth.
+
+## What it gives you
+
+- **Goals are the identity.** Type the ambition, and you land in a chat where the goal's agent is already working: it sharpens the ask, labels the goal ("Wasted X spend → $0"), authors + tests a metric query against your connected platforms, and the platform *re-runs the query server-side* — only a reproducible number with a measured baseline goes on the books. You agree the target in chat; the loop starts only when you press **START** (and the first tick runs immediately). Two modes: **achieve** (reach the number, done) and **maintain** (hold it there forever — a watchdog).
+- **The tick loop.** On the cadence you agree, the platform measures the metric mechanically (the agent never self-reports the number it's judged on) and wakes the agent: it scores past moves against their predicted effects, then makes at most **one** new move — every mutation logged with a falsifiable expected effect and an observation window that gates its resources until review. The agent's page is the diary: sparkline vs. target, tick-by-tick log, open actions, accumulated memory.
+- **Fully autonomous, visibly so.** No approval inbox — agents act inside a spend envelope you set, with the observation-window discipline and your pause button as the controls, and every move on the record.
+- **Shared context + private memory.** `PROJECT.md` is the workspace brief every agent carries (any agent can update it via `set_shared_context`); each agent also keeps its own learnings ledger and workspace files. All connected MCPs are shared by every agent.
+- **One screen per goal.** The conversation and the loop's state live together: chat on the left (where the goal is defined and steered), a status rail on the right — the progress chart, the plan, every check with its full log, open actions with review dates, and the agent's memory. No tabs, no thread management, nothing else to learn.
+- **Progress you can see.** A time-true chart with the target line, every agent action as a marker on the moment it happened (hover: what it did, what it predicted, what actually happened), observation windows shaded, and history backfilled at setup from the platform's own date-segmented stats — context from day one. Maintain goals get a streak ("held at target for 12 days") with a per-check strip; the workspace index shows a mini sparkline + 7-day delta per goal.
+- **Project-scoped MCP connections** — one-click PKCE OAuth to bring third-party tools (Google Ads via NotFair's hosted MCP) into the agents' toolbox. Tokens stored in SQLite, never in env vars, and wired into the chosen harness automatically.
+
+## Pick your harness
+
+At onboarding you pick which local AI coding agent runs the work:
+
+| Harness | Status | Notes |
+|---|---|---|
+| **Claude Code** | Recommended | Uses your existing `claude` login. Per-agent `.mcp.json` for isolation. |
+| **Codex** | Supported | Uses your existing `codex` login. Per-server env-var bearers. Requires `--dangerously-bypass-approvals-and-sandbox` (set by the adapter) so tool calls and loopback reach your local orchestration MCP. |
+
+Different projects can run on different harnesses; the choice persists on the project row.
+
+## Prerequisites
+
+- **Node 20+** (Node 24 recommended for native-module prebuilds).
+- **At least one harness installed and authenticated**:
+ - [Claude Code](https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview), or
+ - [Codex CLI](https://github.com/openai/codex)
+
+Run `NotFair doctor` to verify Node, both harnesses, data dir, and port.
+
+## Install + run
+
+```bash
+# One-shot, no install:
+npx notfair@latest doctor # verify env
+npx notfair@latest # launch UI on http://127.0.0.1:3327
+
+# Or install globally:
+npm install -g notfair
+NotFair
+```
+
+The UI opens in your browser. Sidebar is project-scoped; create one to start.
+
+## CLI
+
+```
+NotFair Launch local server + open UI (default)
+NotFair start Same as above
+NotFair doctor Run preflight checks (see below)
+NotFair --version
+NotFair --help
+```
+
+Options on `start`: `--port <n>` (default 3327), `--no-open`, `--data-dir <path>`.
+Options on `doctor`: `--port <n>`, `--data-dir <path>`.
+
+`doctor` runs five checks: Node ≥ 20 (24 recommended), Claude Code on PATH, Codex on PATH, at least one harness ready, data dir writable, and the preferred port free. Exits 0 if every check is passing, 1 otherwise, with a `Fix:` line under each failure naming the exact command to run.
+
+## What happens when you create a goal
+
+1. You name an agent on the workspace page — a goal row (status `intake`) and the agent's workspace at `~/.notfair/agents/<slug>-goal-<name>/` are created together, with an `IDENTITY.md` carrying the goal spec + the loop protocol, mirrored into the harness's native config (`CLAUDE.md` / `AGENTS.md`, `.mcp.json` for Claude Code, sections in `~/.codex/config.toml` for Codex). Every connected MCP is wired in.
+2. You chat: the agent records the ambition (`define_goal`), authors + tests a metric query, submits it (`propose_goal_metric` — the platform re-runs it server-side and stores the measured baseline), and, once you explicitly confirm the target, starts the loop (`activate_goal`).
+3. The heartbeat rides a `setInterval` in the Next.js process polling every 30 s; due goals get a tick — metric measured, brief composed from the DB, one adapter turn, diary row written.
+
+## Scheduling recurring work
+
+Beyond goal heartbeats, agents can call the `schedule_recurring_work` MCP tool for auxiliary cron jobs, and you can schedule manually via the **+ New cron** button on the Crons tab. Same 30 s tick loop, same per-project harness dispatch.
+
+## Connecting MCP servers (for live ad-platform data)
+
+The Connections page lists the MCP servers in our catalog (NotFair Google Ads, Meta Ads, Google Search Console, Google Analytics, X Ads — plus browseable extras like Stripe and Supabase, or any custom MCP URL). Click **Connect** to start a one-click PKCE OAuth flow — no environment variables to set, no Google Cloud project of your own to register.
+
+The token is persisted into `mcp_tokens` (SQLite) and the catalog MCP is automatically registered with every agent in the project via the chosen harness's config. New agents provisioned later get the same wiring.
+
+OAuth refresh tokens are AES-256-GCM encrypted with a master key stored in your OS keychain (via `keytar`) and persisted to your local SQLite.
+
+## Live transcript
+
+Chat events (deltas, tool calls, lifecycle) are persisted to `transcript_events` and **also** pushed through an in-process `EventEmitter` keyed by session id. Open tabs subscribe via SSE; new events land in milliseconds. Re-attach to a streaming thread (open the URL in a second tab while the agent is mid-turn) is race-free: the server backfills from cursor=0 before attaching the live subscription, with dedup-by-seq.
+
+## Data location
+
+- App state: `~/.notfair/db.sqlite` (override with `--data-dir` or `NOTFAIR_DATA_DIR`)
+- Agent workspaces: `~/.notfair/agents/<agent-id>/`
+- Harness configs: `~/.claude/` for Claude Code; `~/.codex/config.toml` for Codex (managed by the respective CLI)
+- Orchestration MCP secret: `~/.notfair/mcp-server-secret` (0600 perms)
+
+## What V1 is and isn't
+
+**Is:** the goal loop — conversational goal intake with server-verified metrics, heartbeat ticks with measurement discipline, per-agent memory, shared workspace context — plus per-agent chat, a native cron scheduler, and an MCP connection hub. Runs on Claude Code or Codex, no proprietary agent runtime.
+
+**Isn't (yet):** cross-goal coordination (resource leases between agents touching the same campaigns), per-LLM-call cost tracking, or a hosted mode. Those land as the loop earns trust in the field.
+
+See `ARCHITECTURE.md` for the design and `CONTRIBUTING.md` for development setup.
+
+## License
+
+MIT — see LICENSE.
diff --git a/notfair-cmo/bin/cli.mjs b/notfair/bin/cli.mjs
similarity index 93%
rename from notfair-cmo/bin/cli.mjs
rename to notfair/bin/cli.mjs
index fdb5f58b..feff0013 100755
--- a/notfair-cmo/bin/cli.mjs
+++ b/notfair/bin/cli.mjs
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-// notfair-cmo CLI entry point.
+// NotFair CLI entry point.
// Compiled-free: stays as plain ESM JS so it works straight from npm without a build step
// for the CLI surface. The Next.js app itself is built and shipped under .next/standalone.
@@ -21,11 +21,11 @@ import open from "open";
const __dirname = dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = dirname(__dirname);
-const DATA_DIR = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+const DATA_DIR = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
const program = new Command();
program
- .name("notfair-cmo")
+ .name("notfair")
.description("Local AI marketing CMO portal. Orchestrates OpenClaw marketing agents.")
.version(readPackageVersion());
@@ -63,11 +63,11 @@ program
...process.env,
PORT: String(port),
HOSTNAME: "127.0.0.1",
- NOTFAIR_CMO_DATA_DIR: opts.dataDir,
+ NOTFAIR_DATA_DIR: opts.dataDir,
},
});
- console.log(`notfair-cmo running on ${url}`);
+ console.log(`NotFair running on ${url}`);
if (opts.open !== false) {
setTimeout(() => {
@@ -86,7 +86,7 @@ program
program
.command("doctor")
- .description("Verify this machine is ready to run notfair-cmo.")
+ .description("Verify this machine is ready to run NotFair.")
.option("--data-dir <dir>", "Override data directory", DATA_DIR)
.option("-p, --port <port>", "Preferred port for the server", "3327")
.action(async (opts) => {
@@ -95,7 +95,7 @@ program
const node = checkNodeVersion();
results.push(node);
- // Probe each supported harness adapter. notfair-cmo can run on any of
+ // Probe each supported harness adapter. NotFair can run on any of
// them, so doctor lists status for all; at least one needs to be ok.
const claude = node.ok
? await checkHarnessInstalled("Claude Code", "claude")
@@ -134,10 +134,10 @@ program
program
.command("stop")
- .description("Stop any running notfair-cmo instances on this machine.")
+ .description("Stop any running NotFair instances on this machine.")
.action(() => {
console.log("Stop is not implemented yet. Use Ctrl+C in the running terminal,");
- console.log("or kill the node process bound to your notfair-cmo port.");
+ console.log("or kill the node process bound to your NotFair port.");
process.exit(1);
});
@@ -297,8 +297,8 @@ async function checkHarnessInstalled(label, binary) {
}
function checkDataDir(dir) {
- const overrideEnv = process.env.NOTFAIR_CMO_DATA_DIR;
- const source = overrideEnv ? "NOTFAIR_CMO_DATA_DIR" : dir === DATA_DIR ? "default" : "--data-dir";
+ const overrideEnv = process.env.NOTFAIR_DATA_DIR;
+ const source = overrideEnv ? "NOTFAIR_DATA_DIR" : dir === DATA_DIR ? "default" : "--data-dir";
try {
ensureDataDir(dir);
const probe = join(dir, ".doctor-write-probe");
@@ -310,7 +310,7 @@ function checkDataDir(dir) {
return fail(
"Data dir writable",
`${dir}: ${message}`,
- "Pass --data-dir <path> or set NOTFAIR_CMO_DATA_DIR to a writable directory",
+ "Pass --data-dir <path> or set NOTFAIR_DATA_DIR to a writable directory",
);
}
}
@@ -366,7 +366,7 @@ function printResults(results) {
const failed = results.filter((r) => r.status === "fail").length;
const skipped = results.filter((r) => r.status === "skip").length;
if (failed === 0 && skipped === 0) {
- console.log(color("green", "All checks passed. You're ready to run notfair-cmo."));
+ console.log(color("green", "All checks passed. You're ready to run NotFair."));
} else if (failed === 0) {
console.log(
color("yellow", `Passed, with ${skipped} check${skipped === 1 ? "" : "s"} skipped.`),
diff --git a/notfair-cmo/components.json b/notfair/components.json
similarity index 100%
rename from notfair-cmo/components.json
rename to notfair/components.json
diff --git a/notfair-cmo/next-env.d.ts b/notfair/next-env.d.ts
similarity index 84%
rename from notfair-cmo/next-env.d.ts
rename to notfair/next-env.d.ts
index c4b7818f..9edff1c7 100644
--- a/notfair-cmo/next-env.d.ts
+++ b/notfair/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/dev/types/routes.d.ts";
+import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/notfair-cmo/next.config.ts b/notfair/next.config.ts
similarity index 100%
rename from notfair-cmo/next.config.ts
rename to notfair/next.config.ts
diff --git a/notfair-cmo/package.json b/notfair/package.json
similarity index 75%
rename from notfair-cmo/package.json
rename to notfair/package.json
index 42e7f753..d393f2ef 100644
--- a/notfair-cmo/package.json
+++ b/notfair/package.json
@@ -1,10 +1,10 @@
{
- "name": "notfair-cmo",
- "version": "0.8.0",
+ "name": "notfair",
+ "version": "0.9.0",
"description": "Open-source AI marketing CMO portal. Run locally; orchestrates marketing agents (Google Ads, SEO, and more) on top of Claude Code, Codex, or other local AI coding agents.",
"license": "MIT",
"bin": {
- "notfair-cmo": "bin/cli.mjs"
+ "notfair": "bin/cli.mjs"
},
"files": [
"bin/",
@@ -17,23 +17,14 @@
"build": "next build && node scripts/copy-standalone-assets.mjs",
"start": "next start",
"cli": "tsx bin/cli.ts",
- "typecheck": "tsc --noEmit",
- "lint": "next lint",
- "test": "vitest run",
- "test:watch": "vitest",
- "test:ui": "vitest --ui",
- "test:coverage": "vitest run --coverage",
- "eval": "vitest run --config vitest.evals.config.ts"
+ "typecheck": "tsc --noEmit"
},
"dependencies": {
- "@ai-sdk/anthropic": "^1.0.0",
- "@ai-sdk/openai": "^1.0.0",
"@next/env": "16.2.6",
"@radix-ui/react-dialog": "^1.1.0",
"@radix-ui/react-dropdown-menu": "^2.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@swc/helpers": "^0.5.21",
- "ai": "^4.0.0",
"better-sqlite3": "^12.10.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
@@ -57,24 +48,18 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4.0.0",
- "@testing-library/jest-dom": "^6.9.1",
- "@testing-library/react": "^16.3.2",
"@types/better-sqlite3": "^7.6.0",
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@types/ws": "^8.18.1",
"@vitejs/plugin-react": "^6.0.2",
- "@vitest/coverage-v8": "^4.1.7",
- "@vitest/ui": "^4.1.6",
"eslint": "^9.0.0",
"eslint-config-next": "^16.2.6",
- "jsdom": "^29.1.1",
"postcss": "^8.4.0",
"tailwindcss": "^4.0.0",
"tsx": "^4.19.0",
- "typescript": "^5.6.0",
- "vitest": "^4.1.6"
+ "typescript": "^5.6.0"
},
"engines": {
"node": ">=20"
diff --git a/notfair-cmo/pnpm-lock.yaml b/notfair/pnpm-lock.yaml
similarity index 88%
rename from notfair-cmo/pnpm-lock.yaml
rename to notfair/pnpm-lock.yaml
index aab638f4..bd9ba264 100644
--- a/notfair-cmo/pnpm-lock.yaml
+++ b/notfair/pnpm-lock.yaml
@@ -8,12 +8,6 @@ importers:
.:
dependencies:
- '@ai-sdk/anthropic':
- specifier: ^1.0.0
- version: 1.2.12([email protected])
- '@ai-sdk/openai':
- specifier: ^1.0.0
- version: 1.3.24([email protected])
'@next/env':
specifier: 16.2.6
version: 16.2.6
@@ -29,9 +23,6 @@ importers:
'@swc/helpers':
specifier: ^0.5.21
version: 0.5.21
- ai:
- specifier: ^4.0.0
better-sqlite3:
specifier: ^12.10.0
version: 12.10.0
@@ -96,12 +87,6 @@ importers:
'@tailwindcss/postcss':
specifier: ^4.0.0
version: 4.3.0
- '@testing-library/jest-dom':
- specifier: ^6.9.1
- version: 6.9.1
- '@testing-library/react':
- specifier: ^16.3.2
'@types/better-sqlite3':
specifier: ^7.6.0
version: 7.6.13
@@ -120,21 +105,12 @@ importers:
'@vitejs/plugin-react':
specifier: ^6.0.2
- '@vitest/coverage-v8':
- specifier: ^4.1.7
- version: 4.1.7([email protected])
- '@vitest/ui':
- specifier: ^4.1.6
- version: 4.1.6([email protected])
eslint:
specifier: ^9.0.0
version: 9.39.4([email protected])
eslint-config-next:
specifier: ^16.2.6
- jsdom:
- specifier: ^29.1.1
- version: 29.1.1
postcss:
specifier: ^8.4.0
version: 8.5.14
@@ -147,72 +123,13 @@ importers:
typescript:
specifier: ^5.6.0
version: 5.9.3
- vitest:
- specifier: ^4.1.6
packages:
- '@adobe/[email protected]':
- resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-YSzjlko7JvuiyQFmI9RN1tNZdEiZxc+6xld/0tq/VkJaHpEzGAb1yiNxxvmYVcjvfu/PcvCxAAYXmTYQQ63IHQ==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.0.0
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-GYXnGJTHRTZc4gJMSmFRgEQudjqd4PUN0ZjQhPwOAYH1yOAvQoG/Ikqs+HyISRbLPCrhbZnPKCNHuRU4OfpW0Q==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.0.0
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.23.8
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}
- engines: {node: '>=18'}
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-jK1IZZ22evPZoQW3vlkZ7wvjYGYF+tRBKXtrcolduIkQ/m/sOAVcVeVDUDvh1T91xCnWCdUGCPZg2avZ90mv3g==}
- engines: {node: '>=18'}
- peerDependencies:
- react: ^18 || ^19 || ^19.0.0-rc
- zod: ^3.23.8
- peerDependenciesMeta:
- zod:
- optional: true
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.23.8
-
resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}
engines: {node: '>=10'}
- '@asamuzakjp/[email protected]':
- resolution: {integrity: sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==}
- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
-
- '@asamuzakjp/[email protected]':
- resolution: {integrity: sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==}
- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
-
- '@asamuzakjp/[email protected]':
- resolution: {integrity: sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==}
- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
-
- '@asamuzakjp/[email protected]':
- resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==}
-
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
engines: {node: '>=6.9.0'}
@@ -268,10 +185,6 @@ packages:
engines: {node: '>=6.0.0'}
hasBin: true
- '@babel/[email protected]':
- resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}
- engines: {node: '>=6.9.0'}
-
resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==}
engines: {node: '>=6.9.0'}
@@ -284,50 +197,6 @@ packages:
resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
engines: {node: '>=6.9.0'}
- resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
- engines: {node: '>=18'}
-
- '@bramus/[email protected]':
- resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}
- hasBin: true
-
- '@csstools/[email protected]':
- resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==}
- engines: {node: '>=20.19.0'}
-
- '@csstools/[email protected]':
- resolution: {integrity: sha512-DtdHlgXh5ZkA43cwBcAm+huzgJiwx3ZTWVjBs94kwz2xKqSimDA3lBgCjphYgwgVUMWatSM0pDd8TILB1yrVVg==}
- engines: {node: '>=20.19.0'}
- peerDependencies:
- '@csstools/css-parser-algorithms': ^4.0.0
- '@csstools/css-tokenizer': ^4.0.0
-
- '@csstools/[email protected]':
- resolution: {integrity: sha512-eZ5XOtyhK+mggRafYUWzA0tvaYOFgdY8AkgQiCJF9qNAePnUo/zmsqqYubBBb3sQ8uNUaSKTY9s9klfRaAXL0g==}
- engines: {node: '>=20.19.0'}
- peerDependencies:
- '@csstools/css-parser-algorithms': ^4.0.0
- '@csstools/css-tokenizer': ^4.0.0
-
- '@csstools/[email protected]':
- resolution: {integrity: sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==}
- engines: {node: '>=20.19.0'}
- peerDependencies:
- '@csstools/css-tokenizer': ^4.0.0
-
- '@csstools/[email protected]':
- resolution: {integrity: sha512-wgsqt92b7C7tQhIdPNxj0n9zuUbQlvAuI1exyzeNrOKOi62SD7ren8zqszmpVREjAOqg8cD2FqYhQfAuKjk4sw==}
- peerDependencies:
- css-tree: ^3.2.1
- peerDependenciesMeta:
- css-tree:
- optional: true
-
- '@csstools/[email protected]':
- resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==}
- engines: {node: '>=20.19.0'}
-
'@emnapi/[email protected]':
resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}
@@ -531,15 +400,6 @@ packages:
resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
- '@exodus/[email protected]':
- resolution: {integrity: sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==}
- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
- peerDependencies:
- '@noble/hashes': ^1.8.0 || ^2.0.0
- peerDependenciesMeta:
- '@noble/hashes':
- optional: true
-
'@floating-ui/[email protected]':
resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}
@@ -834,9 +694,6 @@ packages:
'@oxc-project/[email protected]':
resolution: {integrity: sha512-ibD2usx9JRu7f5pu2tMKMI4cpA4NgXJQoYRP4pQ7Pxmn1l6k/53qWtQWZayhYy3X4QZkt90Ot+mJEaeXouio6Q==}
- '@polka/[email protected]':
- resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
-
'@radix-ui/[email protected]':
resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==}
@@ -1637,9 +1494,6 @@ packages:
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
- '@standard-schema/[email protected]':
- resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
-
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
@@ -1738,50 +1592,15 @@ packages:
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-Jm05Tjx+9yCLGv5qw1c+84Psds8MnyrEQYCB+FFk2lgGiUjlRqdxke4mVTuYrj2xnVZqKim2Apr5ySuQRYAw/w==}
- '@testing-library/[email protected]':
- resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
- engines: {node: '>=18'}
-
- '@testing-library/[email protected]':
- resolution: {integrity: sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==}
- engines: {node: '>=14', npm: '>=6', yarn: '>=1'}
-
- '@testing-library/[email protected]':
- resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}
- engines: {node: '>=18'}
- peerDependencies:
- '@testing-library/dom': ^10.0.0
- '@types/react': ^18.0.0 || ^19.0.0
- '@types/react-dom': ^18.0.0 || ^19.0.0
- react: ^18.0.0 || ^19.0.0
- react-dom: ^18.0.0 || ^19.0.0
- peerDependenciesMeta:
- '@types/react':
- optional: true
- '@types/react-dom':
- optional: true
-
resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
- '@types/[email protected]':
- resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}
-
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
- '@types/[email protected]':
- resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
-
resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
-
- '@types/[email protected]':
- resolution: {integrity: sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==}
-
resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
@@ -2001,55 +1820,6 @@ packages:
babel-plugin-react-compiler:
optional: true
- '@vitest/[email protected]':
- resolution: {integrity: sha512-qsYPeXc5Q9dFLd1i8Ap+Bx8sQgcp+rFVQo4R0dDsWNBzl26ldVF1qOO+RL24K7FDrR6pA+50XedRLSoSG24bVQ==}
- peerDependencies:
- '@vitest/browser': 4.1.7
- vitest: 4.1.7
- peerDependenciesMeta:
- '@vitest/browser':
- optional: true
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-7EHDquPthALSV0jhhjgEW8FXaviMx7rSqu8W6oqCoAuOhKov814P99QDV1pxMA3QPv21YudvJngIhjrNI4opLg==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-MCFc63czMjEInOlcY2cpQCvCN+KgbAn+60xu9cMgP4sKaLC5JNAKw7JH8QdAnoAC88hW1IiSNZ+GgVXlN1UcMQ==}
- peerDependencies:
- msw: ^2.4.9
- vite: ^6.0.0 || ^7.0.0 || ^8.0.0
- peerDependenciesMeta:
- msw:
- optional: true
- vite:
- optional: true
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-h5SxD/IzNhZYnrSZRsUZQIC+vD0GY8cUvq0iwsmkFKixRCKLLWqCXa/FIQ4S1R+sI+PGoojkHsdNrbZiM9Qpgw==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-umgCarTOYQWIaDMvGDRZij+6b9oVeLIyJzfN+AS88e0ZOU3QTgNNSTtjQOpcvWr3np1N0j4WgZj+sb3oYBDscw==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-nOPCmn2+yD0ZNmKdsXGv/UxMMWbMuKeD6GyYncNwdkYDxpQvrPSKYj2rWuDjC2Y4b6w6hjip5dBKFzEUuZe3vA==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-YhsdE6xAVfTDmzjxL2ZDUvjj+ZsgyOKe+TdQzqkD72wIOmHka8NuGQ6NpTNZv9D2Z63fbwWKJPeVpEw4EQgYxw==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-JFKxMx6udhwKh/Ldo270e17QX710vgunMkuPAvXjHSvC6oqLWAHhVhjg/I71q0u0CBSErIODV1Kjv0FQNSWjdg==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-wiu5em68DfGv/2HFvI1Njr7JI2CHcBlQvereSzVG8my53PRxjTNOCsD9VOkRKrsJBDHmyuXvosxWZw7T91a2mw==}
- peerDependencies:
- vitest: 4.1.6
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-FxIY+U81R3LGKCxaHHFRQ5+g6/iRgGLmeHWdp2Amj4ljQRrEIWHmZyDfDYBRZlpyqA7qKxtS9DD1dhk8RnRIVQ==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-T532WBu791cBxJlCl6SO+J14l81DQx6uQHm1bQbmCDY7nqlEIgkza/UFnSBNaUtSf41unldDFjdOBYEQC4b5Hw==}
-
resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
peerDependencies:
@@ -2060,31 +1830,13 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
- resolution: {integrity: sha512-dIE2bfNpqHN3r6IINp9znguYdhIOheKW2LDigAMrgt/upT3B8eBGPSCblENvaZGoq+hxaN9fSMzjWpbqloP+7Q==}
- engines: {node: '>=18'}
- peerDependencies:
- react: ^18 || ^19 || ^19.0.0-rc
- zod: ^3.23.8
- peerDependenciesMeta:
- react:
- optional: true
-
resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==}
- resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
@@ -2092,9 +1844,6 @@ packages:
resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
-
resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
engines: {node: '>= 0.4'}
@@ -2131,16 +1880,9 @@ packages:
resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==}
- resolution: {integrity: sha512-1fSfIwuDICFA4LKkCzRPO7F0hzFf0B7+Xqrl27ynQaa+Rh0e1Es0v6kWHPott3lU10AyAr7oKHa65OppjLn3Rg==}
-
resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}
engines: {node: '>= 0.4'}
@@ -2179,9 +1921,6 @@ packages:
resolution: {integrity: sha512-CyzaZRQKyHkB2ZInfTTl2nvT33EbDpjkLEbE8/Zck3Ll6O0qqvuGdrJ45HgtH+HykRg88ITY3AdreBGN70aBSQ==}
engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x}
- resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==}
-
resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}
@@ -2233,18 +1972,10 @@ packages:
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
- resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==}
- engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}
-
resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}
@@ -2298,23 +2029,12 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
- resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
- engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
-
- resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
-
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}
- resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==}
- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
-
resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==}
engines: {node: '>= 0.4'}
@@ -2344,9 +2064,6 @@ packages:
supports-color:
optional: true
- resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}
-
resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==}
@@ -2395,19 +2112,10 @@ packages:
resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
- resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==}
-
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
-
- resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
-
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
@@ -2425,10 +2133,6 @@ packages:
resolution: {integrity: sha512-QyL119InA+XXEkNLNTPCXPugSvOfhwv0JOlGNzvxs0hZaiHLNvXSpudUWsOlsXGWJh8G6ckCScEkVHfX3kw/2Q==}
engines: {node: '>=10.13.0'}
- resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==}
- engines: {node: '>=20.19.0'}
-
resolution: {integrity: sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==}
engines: {node: '>= 0.4'}
@@ -2445,9 +2149,6 @@ packages:
resolution: {integrity: sha512-HVLACW1TppGYjJ8H6/jqH/pqOtKRw6wMlrB23xfExmFWxFquAIWCmwoLsOyN96K4a5KbmOf5At9ZUO3GZbetAw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==}
-
resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
engines: {node: '>= 0.4'}
@@ -2600,9 +2301,6 @@ packages:
resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}
- resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
-
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
engines: {node: '>=0.10.0'}
@@ -2611,10 +2309,6 @@ packages:
resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
- engines: {node: '>=12.0.0'}
-
resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}
@@ -2643,9 +2337,6 @@ packages:
picomatch:
optional: true
- resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
-
resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==}
engines: {node: '>=16.0.0'}
@@ -2786,13 +2477,6 @@ packages:
resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==}
- resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}
- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
-
- resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
-
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
@@ -2815,10 +2499,6 @@ packages:
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
- resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
@@ -2925,9 +2605,6 @@ packages:
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
-
resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==}
engines: {node: '>= 0.4'}
@@ -2974,18 +2651,6 @@ packages:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
- resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
- engines: {node: '>=10'}
-
- resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}
engines: {node: '>= 0.4'}
@@ -2994,9 +2659,6 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
- resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
-
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -3004,15 +2666,6 @@ packages:
resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
hasBin: true
- resolution: {integrity: sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==}
- engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0}
- peerDependencies:
- canvas: ^3.0.0
- peerDependenciesMeta:
- canvas:
- optional: true
-
resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}
engines: {node: '>=6'}
@@ -3024,9 +2677,6 @@ packages:
resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==}
- resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==}
-
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
@@ -3039,11 +2689,6 @@ packages:
engines: {node: '>=6'}
hasBin: true
- resolution: {integrity: sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==}
- engines: {node: ^18.0.0 || >=20.0.0}
- hasBin: true
-
resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}
engines: {node: '>=4.0'}
@@ -3153,10 +2798,6 @@ packages:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
- resolution: {integrity: sha512-W+R+kFL4HgVxONq2bhXPi3bGpzGe/yEhVOp233qw9wCRtgncJ15P3bC+e4zZMu4Cq7d+WAJjXGW0uUkifhcatA==}
- engines: {node: 20 || >=22}
-
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
@@ -3169,20 +2810,9 @@ packages:
resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
- hasBin: true
-
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
- resolution: {integrity: sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==}
-
- resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
@@ -3235,9 +2865,6 @@ packages:
resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}
- resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}
-
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
engines: {node: '>= 8'}
@@ -3334,10 +2961,6 @@ packages:
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
- engines: {node: '>=4'}
-
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@@ -3351,10 +2974,6 @@ packages:
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
- resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -3447,9 +3066,6 @@ packages:
resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}
-
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
@@ -3480,9 +3096,6 @@ packages:
resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==}
- resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==}
-
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'}
@@ -3494,9 +3107,6 @@ packages:
resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
- resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
-
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -3535,10 +3145,6 @@ packages:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
- resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
- engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
-
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
@@ -3580,9 +3186,6 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
- resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
-
resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
peerDependencies:
@@ -3627,10 +3230,6 @@ packages:
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
engines: {node: '>= 6'}
- resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
@@ -3651,10 +3250,6 @@ packages:
resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
- resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
- engines: {node: '>=0.10.0'}
-
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
engines: {node: '>=4'}
@@ -3698,16 +3293,9 @@ packages:
resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
- engines: {node: '>=v12.22.7'}
-
resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
- resolution: {integrity: sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==}
-
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
@@ -3757,19 +3345,12 @@ packages:
resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
-
resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}
resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}
- resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==}
peerDependencies:
@@ -3786,12 +3367,6 @@ packages:
resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==}
- resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
-
- resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}
-
resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==}
engines: {node: '>= 0.4'}
@@ -3829,10 +3404,6 @@ packages:
resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==}
engines: {node: '>=4'}
- resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}
engines: {node: '>=0.10.0'}
@@ -3868,14 +3439,6 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-2CC6CiKQtEwaEeNiqWTAw9PGykW8SR5zZX8MZk6TeAvEAnVS7Visz8WzphqgtQ8v2xz/4Q5K+j+SeMaKXeeQIA==}
- peerDependencies:
- react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
-
- resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
-
resolution: {integrity: sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==}
@@ -3893,48 +3456,14 @@ packages:
resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==}
- engines: {node: '>=18'}
-
- resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
-
- resolution: {integrity: sha512-dAqSqE/RabpBKI8+h26GfLq6Vb3JVXs30XYQjdMjaj/c2tS8IYYMbIzP599KtRj7c57/wYApb3QjgRgXmrCukA==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
engines: {node: '>=12.0.0'}
- resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
- engines: {node: '>=14.0.0'}
-
- resolution: {integrity: sha512-uiHN8PIB1VmWyS98eZYja4xzlYqeFZVjb4OuYlJQnZAuJhMw4PbKQOKgHKhBdJR3FE/t5mUQ1Kd80++B+qhD1Q==}
-
- resolution: {integrity: sha512-ELrFxuqsDdHUwoh0XxDbxuLD3Wnz49Z57IFvTtvWy1hJdcMZjXLIuonjilCiWHlT2GbE4Wlv1wKVTzDFnXH1aw==}
- hasBin: true
-
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
engines: {node: '>=8.0'}
- resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}
- engines: {node: '>=6'}
-
- resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==}
- engines: {node: '>=16'}
-
- resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==}
- engines: {node: '>=20'}
-
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
@@ -4000,10 +3529,6 @@ packages:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
- resolution: {integrity: sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==}
- engines: {node: '>=20.18.1'}
-
resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
@@ -4111,63 +3636,6 @@ packages:
yaml:
optional: true
- resolution: {integrity: sha512-6lvjbS3p9b4CrdCmguzbh2/4uoXhGE2q71R4OX5sqF9R1bo9Xd6fGrMAfvp5wnCzlBnFVdCOp6onuTQVbo8iUQ==}
- engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
- hasBin: true
- peerDependencies:
- '@edge-runtime/vm': '*'
- '@opentelemetry/api': ^1.9.0
- '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
- '@vitest/browser-playwright': 4.1.6
- '@vitest/browser-preview': 4.1.6
- '@vitest/browser-webdriverio': 4.1.6
- '@vitest/coverage-istanbul': 4.1.6
- '@vitest/coverage-v8': 4.1.6
- '@vitest/ui': 4.1.6
- happy-dom: '*'
- jsdom: '*'
- vite: ^6.0.0 || ^7.0.0 || ^8.0.0
- peerDependenciesMeta:
- '@edge-runtime/vm':
- optional: true
- '@opentelemetry/api':
- optional: true
- '@types/node':
- optional: true
- '@vitest/browser-playwright':
- optional: true
- '@vitest/browser-preview':
- optional: true
- '@vitest/browser-webdriverio':
- optional: true
- '@vitest/coverage-istanbul':
- optional: true
- '@vitest/coverage-v8':
- optional: true
- '@vitest/ui':
- optional: true
- happy-dom:
- optional: true
- jsdom:
- optional: true
-
- resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
- engines: {node: '>=18'}
-
- resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}
- engines: {node: '>=20'}
-
- resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}
- engines: {node: '>=20'}
-
- resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==}
- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
-
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
engines: {node: '>= 0.4'}
@@ -4189,11 +3657,6 @@ packages:
engines: {node: '>= 8'}
hasBin: true
- resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
- engines: {node: '>=8'}
- hasBin: true
-
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
@@ -4217,13 +3680,6 @@ packages:
resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
- engines: {node: '>=18'}
-
- resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
-
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
@@ -4231,11 +3687,6 @@ packages:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}
- peerDependencies:
- zod: ^3.25.28 || ^4
-
resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==}
engines: {node: '>=18.0.0'}
@@ -4250,70 +3701,8 @@ packages:
snapshots:
- '@adobe/[email protected]': {}
-
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- zod: 3.25.76
-
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- zod: 3.25.76
-
- dependencies:
- '@ai-sdk/provider': 1.1.3
- nanoid: 3.3.12
- secure-json-parse: 2.7.0
- zod: 3.25.76
-
- '@ai-sdk/[email protected]':
- dependencies:
- json-schema: 0.4.0
-
- dependencies:
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- '@ai-sdk/ui-utils': 1.2.11([email protected])
- react: 19.2.6
- swr: 2.4.1([email protected])
- throttleit: 2.1.0
- optionalDependencies:
- zod: 3.25.76
-
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- zod: 3.25.76
- zod-to-json-schema: 3.25.2([email protected])
-
'@alloc/[email protected]': {}
- '@asamuzakjp/[email protected]':
- dependencies:
- '@asamuzakjp/generational-cache': 1.0.1
- '@csstools/css-calc': 3.2.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
- '@csstools/css-color-parser': 4.1.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
- '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
- '@csstools/css-tokenizer': 4.0.0
-
- '@asamuzakjp/[email protected]':
- dependencies:
- '@asamuzakjp/generational-cache': 1.0.1
- '@asamuzakjp/nwsapi': 2.3.9
- bidi-js: 1.0.3
- css-tree: 3.2.1
- is-potential-custom-element-name: 1.0.1
-
- '@asamuzakjp/[email protected]': {}
-
- '@asamuzakjp/[email protected]': {}
-
dependencies:
'@babel/helper-validator-identifier': 7.28.5
@@ -4391,8 +3780,6 @@ snapshots:
dependencies:
'@babel/types': 7.29.0
- '@babel/[email protected]': {}
-
dependencies:
'@babel/code-frame': 7.29.0
@@ -4416,36 +3803,6 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
- '@bcoe/[email protected]': {}
-
- '@bramus/[email protected]':
- dependencies:
- css-tree: 3.2.1
-
- '@csstools/[email protected]': {}
-
- '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
- dependencies:
- '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
- '@csstools/css-tokenizer': 4.0.0
-
- '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
- dependencies:
- '@csstools/color-helpers': 6.0.2
- '@csstools/css-calc': 3.2.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
- '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
- '@csstools/css-tokenizer': 4.0.0
-
- '@csstools/[email protected](@csstools/[email protected])':
- dependencies:
- '@csstools/css-tokenizer': 4.0.0
-
- optionalDependencies:
- css-tree: 3.2.1
-
- '@csstools/[email protected]': {}
-
'@emnapi/[email protected]':
dependencies:
'@emnapi/wasi-threads': 1.2.1
@@ -4586,8 +3943,6 @@ snapshots:
'@eslint/core': 0.17.0
levn: 0.4.1
- '@exodus/[email protected]': {}
-
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.11
@@ -4795,12 +4150,11 @@ snapshots:
'@nolyfill/[email protected]': {}
- '@opentelemetry/[email protected]': {}
+ '@opentelemetry/[email protected]':
+ optional: true
'@oxc-project/[email protected]': {}
- '@polka/[email protected]': {}
-
'@radix-ui/[email protected]': {}
'@radix-ui/[email protected]': {}
@@ -5608,8 +4962,6 @@ snapshots:
'@rtsao/[email protected]': {}
- '@standard-schema/[email protected]': {}
-
dependencies:
tslib: 2.8.1
@@ -5687,60 +5039,19 @@ snapshots:
postcss: 8.5.14
tailwindcss: 4.3.0
- '@testing-library/[email protected]':
- dependencies:
- '@babel/code-frame': 7.29.0
- '@babel/runtime': 7.29.2
- '@types/aria-query': 5.0.4
- aria-query: 5.3.0
- dom-accessibility-api: 0.5.16
- lz-string: 1.5.0
- picocolors: 1.1.1
- pretty-format: 27.5.1
-
- '@testing-library/[email protected]':
- dependencies:
- '@adobe/css-tools': 4.4.4
- aria-query: 5.3.2
- css.escape: 1.5.1
- dom-accessibility-api: 0.6.3
- picocolors: 1.1.1
- redent: 3.0.0
-
- dependencies:
- '@babel/runtime': 7.29.2
- '@testing-library/dom': 10.4.1
- react: 19.2.6
- react-dom: 19.2.6([email protected])
- optionalDependencies:
- '@types/react': 19.2.14
- '@types/react-dom': 19.2.3(@types/[email protected])
-
dependencies:
tslib: 2.8.1
optional: true
- '@types/[email protected]': {}
-
dependencies:
'@types/node': 22.19.19
- '@types/[email protected]':
- dependencies:
- '@types/deep-eql': 4.0.2
- assertion-error: 2.0.1
-
dependencies:
'@types/ms': 2.1.0
- '@types/[email protected]': {}
-
- '@types/[email protected]': {}
-
dependencies:
'@types/estree': 1.0.9
@@ -5938,100 +5249,12 @@ snapshots:
'@rolldown/pluginutils': 1.0.1
- dependencies:
- '@bcoe/v8-coverage': 1.0.2
- '@vitest/utils': 4.1.7
- ast-v8-to-istanbul: 1.0.0
- istanbul-lib-coverage: 3.2.2
- istanbul-lib-report: 3.0.1
- istanbul-reports: 3.2.0
- magicast: 0.5.3
- obug: 2.1.1
- std-env: 4.1.0
- tinyrainbow: 3.1.0
-
- '@vitest/[email protected]':
- dependencies:
- '@standard-schema/spec': 1.1.0
- '@types/chai': 5.2.3
- '@vitest/spy': 4.1.6
- '@vitest/utils': 4.1.6
- chai: 6.2.2
- tinyrainbow: 3.1.0
-
- dependencies:
- '@vitest/spy': 4.1.6
- estree-walker: 3.0.3
- magic-string: 0.30.21
- optionalDependencies:
-
- '@vitest/[email protected]':
- dependencies:
- tinyrainbow: 3.1.0
-
- '@vitest/[email protected]':
- dependencies:
- tinyrainbow: 3.1.0
-
- '@vitest/[email protected]':
- dependencies:
- '@vitest/utils': 4.1.6
- pathe: 2.0.3
-
- '@vitest/[email protected]':
- dependencies:
- '@vitest/pretty-format': 4.1.6
- '@vitest/utils': 4.1.6
- magic-string: 0.30.21
- pathe: 2.0.3
-
- '@vitest/[email protected]': {}
-
- dependencies:
- '@vitest/utils': 4.1.6
- fflate: 0.8.3
- flatted: 3.4.2
- pathe: 2.0.3
- sirv: 3.0.2
- tinyglobby: 0.2.16
- tinyrainbow: 3.1.0
-
- '@vitest/[email protected]':
- dependencies:
- '@vitest/pretty-format': 4.1.6
- convert-source-map: 2.0.0
- tinyrainbow: 3.1.0
-
- '@vitest/[email protected]':
- dependencies:
- '@vitest/pretty-format': 4.1.7
- convert-source-map: 2.0.0
- tinyrainbow: 3.1.0
-
dependencies:
acorn: 8.16.0
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- '@ai-sdk/react': 1.2.12([email protected])([email protected])
- '@ai-sdk/ui-utils': 1.2.11([email protected])
- '@opentelemetry/api': 1.9.0
- jsondiffpatch: 0.6.0
- zod: 3.25.76
- optionalDependencies:
- react: 19.2.6
-
dependencies:
fast-deep-equal: 3.1.3
@@ -6039,24 +5262,16 @@ snapshots:
json-schema-traverse: 0.4.1
uri-js: 4.4.1
-
dependencies:
color-convert: 2.0.1
-
dependencies:
tslib: 2.8.1
- dependencies:
- dequal: 2.0.3
-
@@ -6126,16 +5341,8 @@ snapshots:
get-intrinsic: 1.3.0
is-array-buffer: 3.0.5
-
- dependencies:
- '@jridgewell/trace-mapping': 0.3.31
- estree-walker: 3.0.3
- js-tokens: 10.0.0
-
@@ -6161,10 +5368,6 @@ snapshots:
bindings: 1.5.0
prebuild-install: 7.1.3
- dependencies:
- require-from-string: 2.0.2
-
dependencies:
file-uri-to-path: 1.0.0
@@ -6228,15 +5431,11 @@ snapshots:
-
dependencies:
ansi-styles: 4.3.0
supports-color: 7.2.0
-
@@ -6279,24 +5478,10 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
- dependencies:
- mdn-data: 2.27.1
- source-map-js: 1.2.1
-
-
- dependencies:
- whatwg-mimetype: 5.0.0
- whatwg-url: 16.0.1
- transitivePeerDependencies:
- - '@noble/hashes'
-
dependencies:
call-bound: 1.0.4
@@ -6323,8 +5508,6 @@ snapshots:
dependencies:
ms: 2.1.3
-
dependencies:
character-entities: 2.0.2
@@ -6368,16 +5551,10 @@ snapshots:
dependencies:
dequal: 2.0.3
-
dependencies:
esutils: 2.0.3
-
-
dependencies:
call-bind-apply-helpers: 1.0.2
@@ -6397,8 +5574,6 @@ snapshots:
graceful-fs: 4.2.11
tapable: 2.3.3
-
dependencies:
array-buffer-byte-length: 1.0.2
@@ -6479,8 +5654,6 @@ snapshots:
iterator.prototype: 1.1.5
math-intrinsics: 1.1.0
-
dependencies:
es-errors: 1.3.0
@@ -6742,16 +5915,10 @@ snapshots:
- dependencies:
- '@types/estree': 1.0.9
-
-
@@ -6776,8 +5943,6 @@ snapshots:
optionalDependencies:
picomatch: 4.0.4
-
dependencies:
flat-cache: 4.0.1
@@ -6931,14 +6096,6 @@ snapshots:
dependencies:
hermes-estree: 0.25.1
- dependencies:
- '@exodus/bytes': 1.15.0
- transitivePeerDependencies:
- - '@noble/hashes'
-
-
@@ -6954,8 +6111,6 @@ snapshots:
-
@@ -7060,8 +6215,6 @@ snapshots:
-
dependencies:
call-bound: 1.0.4
@@ -7109,19 +6262,6 @@ snapshots:
-
- dependencies:
- istanbul-lib-coverage: 3.2.2
- make-dir: 4.0.0
- supports-color: 7.2.0
-
- dependencies:
- html-escaper: 2.0.2
- istanbul-lib-report: 3.0.1
-
dependencies:
define-data-property: 1.1.4
@@ -7133,48 +6273,18 @@ snapshots:
-
dependencies:
argparse: 2.0.1
- dependencies:
- '@asamuzakjp/css-color': 5.1.11
- '@asamuzakjp/dom-selector': 7.1.1
- '@bramus/specificity': 2.4.2
- '@csstools/css-syntax-patches-for-csstree': 1.1.4([email protected])
- '@exodus/bytes': 1.15.0
- css-tree: 3.2.1
- data-urls: 7.0.0
- decimal.js: 10.6.0
- html-encoding-sniffer: 6.0.0
- is-potential-custom-element-name: 1.0.1
- lru-cache: 11.4.0
- parse5: 8.0.1
- saxes: 6.0.0
- symbol-tree: 3.2.4
- tough-cookie: 6.0.1
- undici: 7.25.0
- w3c-xmlserializer: 5.0.0
- webidl-conversions: 8.0.1
- whatwg-mimetype: 5.0.0
- whatwg-url: 16.0.1
- xml-name-validator: 5.0.0
- transitivePeerDependencies:
- - '@noble/hashes'
-
-
@@ -7183,12 +6293,6 @@ snapshots:
- dependencies:
- '@types/diff-match-patch': 1.0.36
- chalk: 5.6.2
- diff-match-patch: 1.0.5
-
dependencies:
array-includes: 3.1.9
@@ -7277,8 +6381,6 @@ snapshots:
dependencies:
js-tokens: 4.0.0
-
dependencies:
yallist: 3.1.1
@@ -7289,22 +6391,10 @@ snapshots:
-
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
- dependencies:
- '@babel/parser': 7.29.3
- '@babel/types': 7.29.0
- source-map-js: 1.2.1
-
- dependencies:
- semver: 7.8.0
-
@@ -7462,8 +6552,6 @@ snapshots:
dependencies:
'@types/mdast': 4.0.4
-
@@ -7664,8 +6752,6 @@ snapshots:
-
dependencies:
brace-expansion: 5.0.6
@@ -7678,8 +6764,6 @@ snapshots:
-
@@ -7777,8 +6861,6 @@ snapshots:
define-properties: 1.2.1
es-object-atoms: 1.1.1
-
dependencies:
wrappy: 1.0.2
@@ -7827,18 +6909,12 @@ snapshots:
is-decimal: 2.0.1
is-hexadecimal: 2.0.1
- dependencies:
- entities: 8.0.0
-
-
@@ -7878,12 +6954,6 @@ snapshots:
- dependencies:
- ansi-regex: 5.0.1
- ansi-styles: 5.2.0
- react-is: 17.0.2
-
dependencies:
loose-envify: 1.4.0
@@ -7978,8 +7048,6 @@ snapshots:
-
dependencies:
'@types/hast': 3.0.4
@@ -8033,11 +7101,6 @@ snapshots:
string_decoder: 1.3.0
util-deprecate: 1.0.2
- dependencies:
- indent-string: 4.0.0
- strip-indent: 3.0.0
-
dependencies:
call-bind: 1.0.9
@@ -8092,8 +7155,6 @@ snapshots:
mdast-util-to-markdown: 2.1.2
unified: 11.0.5
-
@@ -8157,14 +7218,8 @@ snapshots:
es-errors: 1.3.0
is-regex: 1.2.1
- dependencies:
- xmlchars: 2.2.0
-
-
@@ -8257,8 +7312,6 @@ snapshots:
side-channel-map: 1.0.1
side-channel-weakmap: 1.0.2
-
@@ -8267,12 +7320,6 @@ snapshots:
once: 1.4.0
simple-concat: 1.0.1
- dependencies:
- '@polka/url': 1.0.0-next.29
- mrmime: 2.0.1
- totalist: 3.0.1
-
dependencies:
react: 19.2.6
@@ -8284,10 +7331,6 @@ snapshots:
-
-
dependencies:
es-errors: 1.3.0
@@ -8354,10 +7397,6 @@ snapshots:
- dependencies:
- min-indent: 1.0.1
-
@@ -8383,14 +7422,6 @@ snapshots:
- dependencies:
- dequal: 2.0.3
- react: 19.2.6
- use-sync-external-store: 1.6.0([email protected])
-
-
@@ -8412,39 +7443,15 @@ snapshots:
inherits: 2.0.4
readable-stream: 3.6.2
-
-
-
dependencies:
fdir: 6.5.0([email protected])
picomatch: 4.0.4
-
-
- dependencies:
- tldts-core: 7.0.30
-
dependencies:
is-number: 7.0.0
-
- dependencies:
- tldts: 7.0.30
-
- dependencies:
- punycode: 2.3.1
-
@@ -8531,8 +7538,6 @@ snapshots:
-
dependencies:
'@types/unist': 3.0.3
@@ -8645,53 +7650,6 @@ snapshots:
jiti: 2.7.0
tsx: 4.22.1
- dependencies:
- '@vitest/expect': 4.1.6
- '@vitest/pretty-format': 4.1.6
- '@vitest/runner': 4.1.6
- '@vitest/snapshot': 4.1.6
- '@vitest/spy': 4.1.6
- '@vitest/utils': 4.1.6
- es-module-lexer: 2.1.0
- expect-type: 1.3.0
- magic-string: 0.30.21
- obug: 2.1.1
- pathe: 2.0.3
- picomatch: 4.0.4
- std-env: 4.1.0
- tinybench: 2.9.0
- tinyexec: 1.1.2
- tinyglobby: 0.2.16
- tinyrainbow: 3.1.0
- why-is-node-running: 2.3.0
- optionalDependencies:
- '@opentelemetry/api': 1.9.0
- '@types/node': 22.19.19
- '@vitest/coverage-v8': 4.1.7([email protected])
- '@vitest/ui': 4.1.6([email protected])
- jsdom: 29.1.1
- transitivePeerDependencies:
- - msw
-
- dependencies:
- xml-name-validator: 5.0.0
-
-
-
- dependencies:
- '@exodus/bytes': 1.15.0
- tr46: 6.0.0
- webidl-conversions: 8.0.1
- transitivePeerDependencies:
- - '@noble/hashes'
-
dependencies:
is-bigint: 1.1.0
@@ -8737,11 +7695,6 @@ snapshots:
dependencies:
isexe: 2.0.0
- dependencies:
- siginfo: 2.0.0
- stackback: 0.0.2
-
@@ -8752,18 +7705,10 @@ snapshots:
dependencies:
is-wsl: 3.1.1
-
-
- dependencies:
- zod: 3.25.76
-
dependencies:
zod: 3.25.76
diff --git a/notfair-cmo/postcss.config.mjs b/notfair/postcss.config.mjs
similarity index 100%
rename from notfair-cmo/postcss.config.mjs
rename to notfair/postcss.config.mjs
diff --git a/notfair-cmo/public/mcp-logos/google-ads-icon.svg b/notfair/public/mcp-logos/google-ads-icon.svg
similarity index 100%
rename from notfair-cmo/public/mcp-logos/google-ads-icon.svg
rename to notfair/public/mcp-logos/google-ads-icon.svg
diff --git a/notfair-cmo/public/mcp-logos/google-analytics-icon.svg b/notfair/public/mcp-logos/google-analytics-icon.svg
similarity index 100%
rename from notfair-cmo/public/mcp-logos/google-analytics-icon.svg
rename to notfair/public/mcp-logos/google-analytics-icon.svg
diff --git a/notfair-cmo/public/mcp-logos/meta-icon.svg b/notfair/public/mcp-logos/meta-icon.svg
similarity index 100%
rename from notfair-cmo/public/mcp-logos/meta-icon.svg
rename to notfair/public/mcp-logos/meta-icon.svg
diff --git a/notfair-cmo/public/mcp-logos/search-console-icon.svg b/notfair/public/mcp-logos/search-console-icon.svg
similarity index 100%
rename from notfair-cmo/public/mcp-logos/search-console-icon.svg
rename to notfair/public/mcp-logos/search-console-icon.svg
diff --git a/notfair-cmo/public/mcp-logos/x-ads-icon.svg b/notfair/public/mcp-logos/x-ads-icon.svg
similarity index 100%
rename from notfair-cmo/public/mcp-logos/x-ads-icon.svg
rename to notfair/public/mcp-logos/x-ads-icon.svg
diff --git a/notfair-cmo/public/notfair-mark-dark.svg b/notfair/public/notfair-mark-dark.svg
similarity index 100%
rename from notfair-cmo/public/notfair-mark-dark.svg
rename to notfair/public/notfair-mark-dark.svg
diff --git a/notfair-cmo/public/notfair-mark.svg b/notfair/public/notfair-mark.svg
similarity index 100%
rename from notfair-cmo/public/notfair-mark.svg
rename to notfair/public/notfair-mark.svg
diff --git a/notfair-cmo/scripts/copy-standalone-assets.mjs b/notfair/scripts/copy-standalone-assets.mjs
similarity index 100%
rename from notfair-cmo/scripts/copy-standalone-assets.mjs
rename to notfair/scripts/copy-standalone-assets.mjs
diff --git a/notfair/scripts/e2e-provision.ts b/notfair/scripts/e2e-provision.ts
new file mode 100644
index 00000000..f539e2d2
--- /dev/null
+++ b/notfair/scripts/e2e-provision.ts
@@ -0,0 +1,32 @@
+import { createProject, getProject } from "../src/server/db/projects";
+import { createGoal } from "../src/server/db/goals";
+import { goalAgentIdFor, provisionGoalAgent } from "../src/server/goals/provision";
+
+/**
+ * Dev helper: provision a test project with one goal agent so the UI has
+ * something to render without walking through onboarding. Agent = goal —
+ * the goal starts in `intake` and gets defined in the agent's chat.
+ *
+ * pnpm tsx scripts/e2e-provision.ts
+ */
+async function main() {
+ const slug = "e2e-test-brand";
+ if (!getProject(slug)) {
+ const r = createProject({ display_name: "E2E Test Brand" });
+ if (!r.ok) throw new Error(r.reason);
+ console.log("project created:", r.project.slug);
+ }
+ const agent_id = goalAgentIdFor(slug, 1);
+ const goal = createGoal({
+ project_slug: slug,
+ agent_id,
+ statement: "Keep test wasted spend at $0",
+ });
+ await provisionGoalAgent({ goal, urlSlug: "goal-1" });
+ console.log("goal agent provisioned:", agent_id, "goal:", goal.id);
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/notfair-cmo/scripts/force-refresh-mcp-tokens.ts b/notfair/scripts/force-refresh-mcp-tokens.ts
similarity index 100%
rename from notfair-cmo/scripts/force-refresh-mcp-tokens.ts
rename to notfair/scripts/force-refresh-mcp-tokens.ts
diff --git a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx b/notfair/src/app/(app)/[project]/connections/page.tsx
similarity index 82%
rename from notfair-cmo/src/app/(app)/[project]/connections/page.tsx
rename to notfair/src/app/(app)/[project]/connections/page.tsx
index e0eea223..decc6abe 100644
--- a/notfair-cmo/src/app/(app)/[project]/connections/page.tsx
+++ b/notfair/src/app/(app)/[project]/connections/page.tsx
@@ -8,8 +8,9 @@ import { BuiltinMcpCard } from "@/components/builtin-mcp-card";
import { McpFlashBanner } from "@/components/mcp-flash-banner";
import { AddMcpServerMenu } from "@/components/add-mcp-server-card";
import { normalizeResourceUrl } from "@/server/mcp/discovery-url";
+import { projectHref } from "@/lib/project-href";
-type Search = { mcp_connected?: string; mcp_error?: string };
+type Search = { mcp_connected?: string; mcp_error?: string; mcp_analyzing?: string };
export default async function ConnectionsPage({
searchParams,
@@ -20,7 +21,7 @@ export default async function ConnectionsPage({
}) {
const { project: slug } = await params;
const project = getProject(slug);
- const { mcp_connected, mcp_error } = await searchParams;
+ const { mcp_connected, mcp_error, mcp_analyzing } = await searchParams;
if (!project || project.archived_at) notFound();
const catalog = getMcpCatalog(project.slug);
@@ -56,17 +57,22 @@ export default async function ConnectionsPage({
</div>
</header>
- <McpFlashBanner connected={mcp_connected} error={mcp_error} />
+ <McpFlashBanner
+ connected={mcp_connected}
+ error={mcp_error}
+ analyzing={mcp_analyzing === "1"}
+ goalsHref={projectHref(project.slug, "")}
+ />
<section>
<h2 className="ns-h2">
<span>Built-in</span>
- <span className="ns-h2-meta">Ships with notfair-cmo</span>
+ <span className="ns-h2-meta">Ships with NotFair</span>
</h2>
<div className="ns-group">
<BuiltinMcpCard
- name="Orchestration"
- description="Built-in tools your agents use to coordinate: assign tasks, request approvals, write PROJECT.md, comment, and report status."
+ name="Goals"
+ description="Built-in tools each goal agent runs its loop with: read the goal, verify metrics, log actions and learnings, and keep the shared context current."
tools={builtinTools}
/>
</div>
diff --git a/notfair/src/app/(app)/[project]/context/page.tsx b/notfair/src/app/(app)/[project]/context/page.tsx
new file mode 100644
index 00000000..4ac4f742
--- /dev/null
+++ b/notfair/src/app/(app)/[project]/context/page.tsx
@@ -0,0 +1,49 @@
+import { notFound } from "next/navigation";
+import { getProject } from "@/server/db/projects";
+import { readProjectBrief, projectBriefPath } from "@/server/onboarding/project-brief";
+import { listProjectAgents } from "@/server/agent-meta";
+import { SharedContextEditor } from "@/components/shared-context-editor";
+
+export const dynamic = "force-dynamic";
+
+/**
+ * The shared workspace context (PROJECT.md): one brief every goal agent
+ * inherits. Agents keep it current via `set_shared_context`; this page is
+ * the user's direct line to the same document.
+ */
+export default async function SharedContextPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
+
+ const brief = await readProjectBrief(slug);
+ const agents = await listProjectAgents(slug);
+
+ return (
+ <div className="ns-app-narrow">
+ <header className="ns-page-head">
+ <div className="ns-page-head-stack">
+ <h1 className="ns-page-title">Shared context</h1>
+ <p className="ns-page-sub">
+ What every goal agent knows about {project.display_name} — who you
+ are, what you sell, what matters. Shared with{" "}
+ {agents.length === 0
+ ? "every future goal agent"
+ : `all ${agents.length} goal agent${agents.length === 1 ? "" : "s"}`}
+ ; agents update it too when they learn something workspace-wide.
+ </p>
+ </div>
+ </header>
+
+ <SharedContextEditor projectSlug={slug} initialContent={brief ?? ""} />
+
+ <p className="mt-4 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ Stored at <span className="font-mono">{projectBriefPath(slug)}</span>
+ </p>
+ </div>
+ );
+}
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx
new file mode 100644
index 00000000..8b6ef9a6
--- /dev/null
+++ b/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx
@@ -0,0 +1,77 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { ArrowLeft } from "lucide-react";
+import { getProject } from "@/server/db/projects";
+import { resolveAgentBySlug } from "@/server/agent-meta";
+import { getGoalForAgent, getLatestGoalForAgent } from "@/server/db/goals";
+import { listSessionsForAgent } from "@/server/sessions/view";
+import { readTranscriptTail } from "@/server/sessions/transcript-tail";
+import { getMcpCatalog } from "@/server/mcp-catalog";
+import { projectHref } from "@/lib/project-href";
+import { goalLabel } from "@/lib/goal-label";
+import { LiveTranscript } from "@/components/live-transcript";
+
+export const dynamic = "force-dynamic";
+
+/**
+ * Read-only transcript of one loop check (tick). Reached from the goal
+ * screen's Checks list; the composer is disabled — steering happens in
+ * the goal's own conversation, not inside a check's log.
+ */
+export default async function CheckTranscriptPage({
+ params,
+}: {
+ params: Promise<{ agent: string; thread: string; project: string }>;
+}) {
+ const { agent: agentSlug, thread: threadId, project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(slug, agentSlug);
+ if (!resolved) notFound();
+ const goal =
+ getGoalForAgent(resolved.agent_id) ?? getLatestGoalForAgent(resolved.agent_id);
+
+ const sessions = listSessionsForAgent(slug, resolved.agent_id);
+ const existing = sessions.find((s) => s.sessionId === threadId);
+ const { events: initialEvents, cursor: initialCursor } = readTranscriptTail(
+ slug,
+ resolved.agent_id,
+ threadId,
+ 0,
+ );
+ const mcpCatalog = getMcpCatalog(slug).map((m) => ({
+ key: m.key,
+ display_name: m.display_name,
+ resource_url: m.resource_url,
+ }));
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <header className="flex items-center gap-3 px-5 py-2.5">
+ <Link
+ href={projectHref(slug, `/goals/${agentSlug}`)}
+ className="ns-btn ns-btn-outline ns-btn-sm shrink-0"
+ >
+ <ArrowLeft className="size-3.5" />
+ Back to goal
+ </Link>
+ <h1 className="m-0 min-w-0 truncate text-[14px] font-semibold">
+ {goal ? goalLabel(goal) : resolved.name} — check log
+ </h1>
+ </header>
+ <div className="min-h-0 flex-1">
+ <LiveTranscript
+ key={threadId}
+ projectSlug={slug}
+ agentSlug={agentSlug}
+ agentDisplayName={goal ? goalLabel(goal) : resolved.name}
+ threadId={threadId}
+ initialEvents={initialEvents}
+ initialCursor={initialCursor}
+ composerDisabled
+ mcpCatalog={mcpCatalog}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/layout.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/layout.tsx
new file mode 100644
index 00000000..d8c55a6d
--- /dev/null
+++ b/notfair/src/app/(app)/[project]/goals/[agent]/layout.tsx
@@ -0,0 +1,22 @@
+import { notFound } from "next/navigation";
+import { getProject } from "@/server/db/projects";
+import { resolveAgentBySlug } from "@/server/agent-meta";
+
+type Params = { agent: string; project: string };
+
+export default async function GoalLayout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<Params>;
+}) {
+ const { agent: agentSlug, project: projectSlug } = await params;
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!resolved) notFound();
+
+ // One screen per goal — no tabs. Children own the full viewport region.
+ return <div className="absolute inset-0 flex flex-col">{children}</div>;
+}
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
new file mode 100644
index 00000000..63459d29
--- /dev/null
+++ b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
@@ -0,0 +1,458 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { getProject } from "@/server/db/projects";
+import { resolveAgentBySlug } from "@/server/agent-meta";
+import {
+ getGoalForAgent,
+ getLatestGoalForAgent,
+ listGatedActions,
+ listGoalActions,
+ loggedSpendTotal,
+ listActionsDueForReview,
+ listGoalLearnings,
+ listGoalTicks,
+ listMetricSnapshots,
+ isTargetMet,
+ type Goal,
+ type GoalTick,
+} from "@/server/db/goals";
+import {
+ listSessionsForAgent,
+ pickLatestChatSession,
+} from "@/server/sessions/view";
+import { readTranscriptTail } from "@/server/sessions/transcript-tail";
+import { getMcpCatalog } from "@/server/mcp-catalog";
+import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/registry";
+import { projectHref } from "@/lib/project-href";
+import { goalLabel } from "@/lib/goal-label";
+import { formatMetric } from "@/lib/format-metric";
+import { GoalMemoryDialog } from "@/components/goal-memory-dialog";
+import { Markdown } from "@/components/markdown";
+import { GoalContextDialog } from "@/components/goal-context-dialog";
+import { cadenceLabel } from "@/lib/goal-cadence";
+import { cn } from "@/lib/utils";
+import { LiveTranscript } from "@/components/live-transcript";
+import { GoalControls } from "@/components/goal-controls";
+import { GoalStartButton } from "@/components/goal-start-button";
+import { GoalAutoRefresh } from "@/components/goal-auto-refresh";
+import { GoalProgressChart } from "@/components/goal-progress-chart";
+import { GoalChecksStrip } from "@/components/goal-checks-strip";
+import { buildCheckSquares, currentStreak } from "@/lib/goal-streak";
+
+export const dynamic = "force-dynamic";
+
+function timeAgo(iso: string) {
+ const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
+ if (seconds < 60) return `${Math.floor(seconds)}s ago`;
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+function fmtDate(iso: string | null): string {
+ return iso ? iso.slice(0, 10) : "—";
+}
+
+
+
+const STATUS_CHIP: Record<Goal["status"], string> = {
+ intake: "setting up",
+ proposed: "ready to start",
+ active: "running",
+ paused: "paused",
+ achieved: "achieved",
+ failed: "failed",
+ killed: "closed",
+};
+
+/**
+ * THE goal screen — everything about one goal on a single page. Chat is
+ * the primary surface (goals are defined and steered in conversation);
+ * the right rail is the loop's state: plan/START, metric + sparkline,
+ * tick diary, open actions, memory. No tabs, no thread management — one
+ * goal, one conversation, one screen.
+ */
+export default async function GoalPage({
+ params,
+}: {
+ params: Promise<{ agent: string; project: string }>;
+}) {
+ const { agent: agentSlug, project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(slug, agentSlug);
+ if (!resolved) notFound();
+
+ const goal =
+ getGoalForAgent(resolved.agent_id) ?? getLatestGoalForAgent(resolved.agent_id);
+ if (!goal) notFound();
+
+ // One conversation per goal: the newest chat-origin session (the intake
+ // kickoff creates it), or "main" for a fresh fallback.
+ const sessions = listSessionsForAgent(slug, resolved.agent_id);
+ const threadId = pickLatestChatSession(sessions)?.sessionId ?? "main";
+ const existing = sessions.find((s) => s.sessionId === threadId);
+ const { events: initialEvents, cursor: initialCursor } = readTranscriptTail(
+ slug,
+ resolved.agent_id,
+ threadId,
+ 0,
+ );
+ const modelOptions = await requireAdapter(
+ project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,
+ ).listModels();
+ const mcpCatalog = getMcpCatalog(slug).map((m) => ({
+ key: m.key,
+ display_name: m.display_name,
+ resource_url: m.resource_url,
+ }));
+
+ const live = goal.status === "intake" || goal.status === "proposed" || goal.status === "active" || goal.status === "paused";
+ const learnings = listGoalLearnings(goal.id, 100);
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {(goal.status === "intake" || goal.status === "active") && (
+ <GoalAutoRefresh intervalMs={8000} />
+ )}
+
+ {/* Header: the goal is the title. */}
+ <header className="flex items-center gap-3 px-5 py-2.5">
+ <span className="ns-tag-mono shrink-0">{STATUS_CHIP[goal.status]}</span>
+ <h1 className="m-0 min-w-0 truncate text-[14px] font-semibold">
+ {goalLabel(goal)}
+ </h1>
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ <GoalContextDialog
+ projectSlug={slug}
+ agentId={resolved.agent_id}
+ threadId={threadId}
+ models={modelOptions.map((m) => ({
+ value: m.value,
+ label: m.label,
+ context_window: m.context_window,
+ }))}
+ />
+ <GoalMemoryDialog
+ entries={learnings.map((l) => ({
+ id: l.id,
+ body: l.body,
+ confidence: l.confidence,
+ created_at: l.created_at,
+ }))}
+ />
+ {live && (
+ <GoalControls
+ goalId={goal.id}
+ status={goal.status as "intake" | "proposed" | "active" | "paused"}
+ />
+ )}
+ </div>
+ </header>
+
+ <div className="flex min-h-0 flex-1">
+ {/* Chat — the primary surface. */}
+ <section className="flex min-w-0 flex-1 flex-col">
+ <LiveTranscript
+ key={threadId}
+ projectSlug={slug}
+ agentSlug={agentSlug}
+ agentDisplayName={goalLabel(goal)}
+ threadId={threadId}
+ initialEvents={initialEvents}
+ initialCursor={initialCursor}
+ mcpCatalog={mcpCatalog}
+ modelOptions={modelOptions}
+ />
+ </section>
+
+ {/* Status rail — the loop's state at a glance. */}
+ <aside className="w-[380px] shrink-0 overflow-y-auto bg-[hsl(var(--notfair-surface-2)/0.4)] px-4 py-4">
+ <GoalRail slug={slug} agentSlug={agentSlug} goal={goal} />
+ </aside>
+ </div>
+ </div>
+ );
+}
+
+function GoalRail({
+ slug,
+ agentSlug,
+ goal,
+}: {
+ slug: string;
+ agentSlug: string;
+ goal: Goal;
+}) {
+ const snapshots = listMetricSnapshots(goal.id, 400);
+ const ticks = listGoalTicks(goal.id, 60);
+ const dueActions = listActionsDueForReview(goal.id);
+ const gatedActions = listGatedActions(goal.id);
+ const allActions = listGoalActions(goal.id, 100);
+ const targetMet = isTargetMet(goal);
+ const tickRunning = ticks.some((t) => t.status === "running");
+
+ // Chart data — plain-JSON props for the client component.
+ const chartPoints = snapshots.map((sn) => ({
+ t: Date.parse(sn.created_at),
+ v: sn.value,
+ source: sn.source,
+ }));
+ const chartActions = allActions
+ .filter((a) => a.kind === "mutation")
+ .map((a) => ({
+ t: Date.parse(a.created_at),
+ kind: a.kind,
+ label: a.description,
+ expected: a.expected_effect,
+ observed: a.observed_outcome,
+ reviewUntil:
+ a.status === "open" && a.review_after ? Date.parse(a.review_after) : null,
+ }));
+ const chartFailures = ticks
+ .filter((t) => t.metric_error || t.status === "failed")
+ .map((t) => ({
+ t: Date.parse(t.started_at),
+ error: t.metric_error ?? t.summary ?? "check failed",
+ }));
+ const mutationTicks = new Set(
+ allActions.filter((a) => a.kind === "mutation").map((a) => a.tick_number),
+ );
+ const squares = buildCheckSquares(
+ ticks
+ .filter((t) => t.status !== "running" && t.trigger_kind !== "intake")
+ .map((t) => ({
+ tick_number: t.tick_number,
+ started_at: t.started_at,
+ metric_value: t.metric_value,
+ status: t.status,
+ acted: mutationTicks.has(t.tick_number),
+ })),
+ goal.target_value,
+ goal.metric_direction,
+ );
+ const streak = currentStreak(squares);
+
+ return (
+ <div className="flex flex-col gap-5">
+ {/* Statement */}
+ <p className="m-0 text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-3))]">
+ “{goal.statement}”
+ </p>
+
+ {/* Lifecycle-specific card */}
+ {goal.status === "intake" && (
+ <RailCard>
+ <p className="m-0 text-[12.5px] leading-relaxed">
+ The agent is working out how to <b>measure</b> this — watch the
+ chat. It will verify a metric, show you the baseline, and propose
+ a plan. Nothing touches your account yet.
+ </p>
+ </RailCard>
+ )}
+
+ {goal.status === "proposed" && (
+ <RailCard>
+ {goal.target_value !== null ? (
+ <>
+ <p className="m-0 mb-3 text-[12.5px] leading-relaxed">
+ Baseline <b className="tabular-nums">{formatMetric(goal.baseline_value)}</b>,
+ verified against{" "}
+ <span className="font-mono text-[11px]">{goal.metric_source_key}</span>.
+ The plan is agreed — the loop starts when you press START, and
+ the first check runs immediately.
+ </p>
+ <dl className="mb-3 grid grid-cols-2 gap-2 text-[12px]">
+ <RailStat k="Target" v={`${formatMetric(goal.target_value)}${goal.mode === "maintain" ? " (hold)" : ""}`} />
+ <RailStat k="Heartbeat" v={cadenceLabel(goal.cadence_cron)} />
+ <RailStat k="Deadline" v={goal.deadline ? fmtDate(goal.deadline) : "none"} />
+ <RailStat
+ k="Spend cap"
+ v={goal.spend_envelope_usd !== null ? `$${goal.spend_envelope_usd}` : "none"}
+ />
+ </dl>
+ <GoalStartButton goalId={goal.id} />
+ </>
+ ) : (
+ <p className="m-0 text-[12.5px] leading-relaxed">
+ Metric verified — baseline{" "}
+ <b className="tabular-nums">{formatMetric(goal.baseline_value)}</b>. Agree the
+ target in chat and the START button appears here.
+ </p>
+ )}
+ </RailCard>
+ )}
+
+ {(goal.status === "active" ||
+ goal.status === "paused" ||
+ goal.status === "achieved" ||
+ goal.status === "failed" ||
+ goal.status === "killed") && (
+ <>
+ <RailCard>
+ <div className="mb-1 flex items-baseline justify-between">
+ <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">
+ {goal.metric_name ?? "Metric"}
+ </span>
+ {targetMet && (
+ <span className="ns-tag">
+ {goal.mode === "maintain" ? "holding" : "target met"}
+ </span>
+ )}
+ {tickRunning && <span className="ns-tag">checking…</span>}
+ </div>
+ <div className="flex items-baseline gap-3">
+ <span className="text-2xl font-semibold tabular-nums">
+ {formatMetric(goal.current_value)}
+ </span>
+ <span className="text-[11.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ target {formatMetric(goal.target_value)}
+ {goal.mode === "maintain" ? " (hold)" : ""} · baseline {formatMetric(goal.baseline_value)}
+ </span>
+ </div>
+ {goal.mode === "maintain" && (
+ <div className="mt-3">
+ <GoalChecksStrip squares={squares} streak={streak} />
+ </div>
+ )}
+ <div className="mt-3">
+ <GoalProgressChart
+ points={chartPoints}
+ actions={chartActions}
+ failures={chartFailures}
+ target={goal.target_value}
+ baseline={goal.baseline_value}
+ deadline={goal.deadline ? Date.parse(goal.deadline) : null}
+ />
+ </div>
+ <p className="mt-1.5 mb-0 text-[11px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">
+ {cadenceLabel(goal.cadence_cron)} · next check{" "}
+ {goal.status === "active" ? fmtDate(goal.next_tick_at) : "—"} ·{" "}
+ {goal.tick_count} check{goal.tick_count === 1 ? "" : "s"} so far
+ {goal.spend_envelope_usd !== null &&
+ ` · spent $${loggedSpendTotal(goal.id)} of $${goal.spend_envelope_usd}`}
+ </p>
+ {goal.status_reason &&
+ (goal.status === "achieved" || goal.status === "failed" || goal.status === "killed") && (
+ <Markdown className="mt-2 text-[12px] leading-relaxed text-[hsl(var(--notfair-ink-3))] [&_p]:m-0">
+ {goal.status_reason}
+ </Markdown>
+ )}
+ </RailCard>
+
+ {(dueActions.length > 0 || gatedActions.length > 0) && (
+ <div>
+ <RailHeading>Open actions</RailHeading>
+ <ul className="m-0 flex list-none flex-col gap-2 p-0">
+ {dueActions.map((a) => (
+ <li key={a.id} className="text-[12px] leading-snug">
+ <span className="ns-tag">review due</span>{" "}
+ <Markdown className="inline text-[12px] text-[hsl(var(--notfair-ink-3))] [&_p]:m-0 [&_p]:inline">
+ {a.description}
+ </Markdown>
+ </li>
+ ))}
+ {gatedActions.map((a) => (
+ <li key={a.id} className="text-[12px] leading-snug">
+ <span className="ns-tag-mono">observing → {fmtDate(a.review_after)}</span>{" "}
+ <Markdown className="inline text-[12px] text-[hsl(var(--notfair-ink-3))] [&_p]:m-0 [&_p]:inline">
+ {a.description}
+ </Markdown>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ <div>
+ <RailHeading>Checks</RailHeading>
+ {ticks.length === 0 ? (
+ <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
+ None yet — the first runs at {fmtDate(goal.next_tick_at)}.
+ </p>
+ ) : (
+ <ul className="m-0 flex list-none flex-col gap-2.5 p-0">
+ {ticks.map((t) => (
+ <TickItem key={t.id} slug={slug} agentSlug={agentSlug} goal={goal} tick={t} />
+ ))}
+ </ul>
+ )}
+ </div>
+
+ </>
+ )}
+ </div>
+ );
+}
+
+function TickItem({
+ slug,
+ agentSlug,
+ goal,
+ tick,
+}: {
+ slug: string;
+ agentSlug: string;
+ goal: Goal;
+ tick: GoalTick;
+}) {
+ const threadLabel = tick.trigger_kind === "intake" ? "main" : `tick-${tick.tick_number}`;
+ return (
+ <li className="text-[12px] leading-snug">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="font-medium">
+ Check {tick.tick_number}
+ {tick.metric_value !== null && (
+ <span className={cn("ml-1.5 tabular-nums font-normal text-[hsl(var(--notfair-ink-3))]")}>
+ → {formatMetric(tick.metric_value)}
+ </span>
+ )}
+ </span>
+ <span className="shrink-0 text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {timeAgo(tick.started_at)}
+ </span>
+ </div>
+ {tick.metric_error && (
+ <p className="m-0 text-[11.5px] text-[hsl(0_72%_51%)]">{tick.metric_error}</p>
+ )}
+ <div className="line-clamp-2 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ <Markdown className="text-[11.5px] text-[hsl(var(--notfair-ink-4))] [&_p]:m-0 [&_p]:inline [&_p+p]:before:content-['_']">
+ {tick.status === "running"
+ ? "running…"
+ : tick.status === "failed"
+ ? `failed: ${tick.summary ?? "(no detail)"}`
+ : tick.summary ?? "(no summary)"}
+ </Markdown>
+ </div>
+ {tick.session_id && tick.status !== "running" && (
+ <Link
+ href={projectHref(slug, `/goals/${agentSlug}/checks/${threadLabel}`)}
+ className="ns-link text-[10.5px]"
+ >
+ details ›
+ </Link>
+ )}
+ </li>
+ );
+}
+
+function RailCard({ children }: { children: React.ReactNode }) {
+ return <div className="ns-card p-3.5">{children}</div>;
+}
+
+function RailHeading({ children }: { children: React.ReactNode }) {
+ return (
+ <p className="mb-2 mt-0 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-[hsl(var(--notfair-ink-4))]">
+ {children}
+ </p>
+ );
+}
+
+function RailStat({ k, v }: { k: string; v: string }) {
+ return (
+ <div>
+ <dt className="text-[hsl(var(--notfair-ink-4))]">{k}</dt>
+ <dd className="m-0 font-medium tabular-nums">{v}</dd>
+ </div>
+ );
+}
diff --git a/notfair-cmo/src/app/(app)/[project]/layout.tsx b/notfair/src/app/(app)/[project]/layout.tsx
similarity index 100%
rename from notfair-cmo/src/app/(app)/[project]/layout.tsx
rename to notfair/src/app/(app)/[project]/layout.tsx
diff --git a/notfair/src/app/(app)/[project]/page.tsx b/notfair/src/app/(app)/[project]/page.tsx
new file mode 100644
index 00000000..d71672a8
--- /dev/null
+++ b/notfair/src/app/(app)/[project]/page.tsx
@@ -0,0 +1,236 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { MessageSquare } from "lucide-react";
+import { getProject } from "@/server/db/projects";
+import { listProjectAgents } from "@/server/agent-meta";
+import {
+ getGoalForAgent,
+ getLatestGoalForAgent,
+ listMetricSnapshots,
+ type Goal,
+} from "@/server/db/goals";
+import { listProjectMcpTokens } from "@/server/mcp/tokens";
+import { listOpenSuggestions } from "@/server/db/suggestions";
+import {
+ listSuggestionRuns,
+ maybeAutoGenerate,
+} from "@/server/suggestions/engine";
+import { projectHref } from "@/lib/project-href";
+import { colorForAgentSlug } from "@/lib/agent-colors";
+import { cn } from "@/lib/utils";
+import { NewGoalForm } from "@/components/new-goal-form";
+import { goalLabel } from "@/lib/goal-label";
+import { formatMetric } from "@/lib/format-metric";
+import { GoalSparkline } from "@/components/goal-sparkline";
+import {
+ GoalSuggestionCard,
+ RetryAnalysisButton,
+} from "@/components/goal-suggestions";
+import { GoalAutoRefresh } from "@/components/goal-auto-refresh";
+
+export const dynamic = "force-dynamic";
+
+const STATUS_LABEL: Record<Goal["status"], string> = {
+ intake: "defining the goal",
+ proposed: "awaiting your target",
+ active: "loop running",
+ paused: "paused",
+ achieved: "achieved",
+ failed: "failed",
+ killed: "closed",
+};
+
+/**
+ * Project root = the goals index. Agent = goal: each row is an agent and
+ * the goal it owns. Minting a new agent is the only creation flow — the
+ * goal itself gets defined in that agent's chat.
+ */
+export default async function ProjectGoalsPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
+
+ const agents = await listProjectAgents(slug);
+ const rows = agents.map((a) => {
+ const goal = getGoalForAgent(a.agent_id) ?? getLatestGoalForAgent(a.agent_id);
+ const snapshots = goal ? listMetricSnapshots(goal.id, 120) : [];
+ // 7-day delta: latest vs the closest snapshot at least 7 days old
+ // (else the earliest we have).
+ let delta: number | null = null;
+ if (goal && snapshots.length >= 2) {
+ const latest = snapshots[snapshots.length - 1]!;
+ const cutoff = Date.parse(latest.created_at) - 7 * 86_400_000;
+ const past =
+ [...snapshots].reverse().find((sn) => Date.parse(sn.created_at) <= cutoff) ??
+ snapshots[0]!;
+ delta = latest.value - past.value;
+ }
+ return { agent: a, goal, snapshots, delta };
+ });
+ const connectedCount = listProjectMcpTokens(slug).length;
+
+ // Account analysis → suggested goals. First index visit after a connect
+ // (or after a restart dropped a run) kicks the audit in the background;
+ // the page then live-refreshes until the cards land.
+ maybeAutoGenerate(slug);
+ const suggestions = listOpenSuggestions(slug);
+ const suggestionRuns = listSuggestionRuns(slug);
+ const analyzing = suggestionRuns.filter((r) => r.status === "running");
+ const failedRuns = suggestionRuns.filter((r) => r.status === "failed");
+
+ return (
+ <div className="ns-app-wide">
+ <header className="ns-page-head">
+ <div className="ns-page-head-stack">
+ <h1 className="ns-page-title">{project.display_name}</h1>
+ <p className="ns-page-sub">
+ State a goal. It gets measured, you press START, the loop runs.
+ </p>
+ </div>
+ </header>
+
+ <div className="mb-6">
+ <NewGoalForm projectSlug={slug} />
+ </div>
+
+ {connectedCount === 0 && (
+ <Link
+ href={projectHref(slug, "/connections")}
+ className="mb-6 block rounded-[14px] bg-[hsl(var(--notfair-accent)/0.08)] px-4 py-3 text-[13px]"
+ >
+ No data sources connected yet — connect Google Ads, Meta Ads, or Search
+ Console so your agents can measure anything. Connect →
+ </Link>
+ )}
+
+ {(analyzing.length > 0 || suggestions.length > 0 || failedRuns.length > 0) && (
+ <section className="mb-6">
+ <h2 className="m-0 mb-2 text-[12px] font-medium uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">
+ Suggested from your account
+ </h2>
+ <div className="flex flex-col gap-3">
+ {analyzing.map((run) => (
+ <div
+ key={run.source_key}
+ className="ns-card flex items-center gap-2.5 p-4 text-[13px] text-[hsl(var(--notfair-ink-3))]"
+ >
+ <span
+ className="size-2 animate-pulse rounded-full bg-[hsl(var(--notfair-accent))]"
+ aria-hidden
+ />
+ Analyzing your {run.label} account for goal ideas…
+ </div>
+ ))}
+ {suggestions.map((s) => (
+ <GoalSuggestionCard key={s.id} suggestion={s} projectSlug={slug} />
+ ))}
+ {failedRuns.map((run) => (
+ <div
+ key={run.source_key}
+ className="ns-card flex items-center justify-between gap-3 p-4 text-[12.5px] text-[hsl(var(--notfair-ink-3))]"
+ >
+ <span>
+ Couldn&rsquo;t analyze your {run.label} account
+ {run.error ? ` — ${run.error}` : "."}
+ </span>
+ <RetryAnalysisButton projectSlug={slug} />
+ </div>
+ ))}
+ </div>
+ {analyzing.length > 0 && <GoalAutoRefresh intervalMs={2500} />}
+ </section>
+ )}
+
+ {rows.length === 0 ? (
+ <div className="ns-empty">
+ <p className="ns-empty-title">No goals yet.</p>
+ <p className="ns-empty-sub">
+ State an ambition above and an agent takes it from there.
+ </p>
+ </div>
+ ) : (
+ <ol className="ns-group">
+ {rows.map(({ agent, goal, snapshots, delta }) => {
+ const color = colorForAgentSlug(agent.slug);
+ const deltaGood =
+ goal && delta !== null
+ ? goal.metric_direction === "decrease"
+ ? delta <= 0
+ : delta >= 0
+ : null;
+ return (
+ <li key={agent.agent_id}>
+ <Link
+ href={projectHref(slug, `/goals/${agent.slug}`)}
+ className="ns-row-button"
+ >
+ <span className="ns-glyph" aria-hidden>
+ <span className={cn("size-2.5 rounded-full", color.dot)} />
+ </span>
+ <span className="ns-row-body">
+ <span className="ns-row-title-row">
+ <span className="ns-row-title">{goal ? goalLabel(goal) : agent.name}</span>
+ {goal && <span className="ns-tag">{STATUS_LABEL[goal.status]}</span>}
+ </span>
+ <span className="ns-row-desc block">
+ {goal?.statement?.trim()
+ ? goal.statement
+ : "Getting started — the agent is working on it."}
+ </span>
+ {goal?.status === "active" &&
+ goal.current_value !== null &&
+ goal.target_value !== null && (
+ <span className="ns-row-desc block tabular-nums">
+ {goal.metric_name}: {formatMetric(goal.current_value)} → target {formatMetric(goal.target_value)}
+ </span>
+ )}
+ </span>
+ <span className="ns-row-meta items-center gap-3">
+ {goal && snapshots.length >= 2 && (
+ <span className="hidden w-28 sm:block" aria-hidden>
+ <GoalSparkline
+ values={snapshots.map((sn) => sn.value)}
+ target={goal.target_value}
+ direction={goal.metric_direction}
+ width={112}
+ height={28}
+ />
+ </span>
+ )}
+ {delta !== null && (
+ <span
+ className={
+ "text-[11.5px] tabular-nums " +
+ (deltaGood
+ ? "text-[hsl(var(--notfair-accent))]"
+ : "text-[hsl(0_60%_55%)]")
+ }
+ title="Change over the last 7 days"
+ >
+ {delta > 0 ? "▲" : delta < 0 ? "▼" : "—"}{" "}
+ {Math.abs(delta) >= 1000
+ ? `${(Math.abs(delta) / 1000).toFixed(1)}k`
+ : Number.isInteger(delta)
+ ? Math.abs(delta)
+ : Math.abs(delta).toFixed(2)}{" "}
+ /7d
+ </span>
+ )}
+ <MessageSquare className="size-4 text-[hsl(var(--notfair-ink-4))]" />
+ <span className="chev" aria-hidden>
+ ›
+ </span>
+ </span>
+ </Link>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ </div>
+ );
+}
diff --git a/notfair-cmo/src/app/(app)/[project]/settings/page.tsx b/notfair/src/app/(app)/[project]/settings/page.tsx
similarity index 100%
rename from notfair-cmo/src/app/(app)/[project]/settings/page.tsx
rename to notfair/src/app/(app)/[project]/settings/page.tsx
diff --git a/notfair/src/app/(app)/layout.tsx b/notfair/src/app/(app)/layout.tsx
new file mode 100644
index 00000000..639bc83b
--- /dev/null
+++ b/notfair/src/app/(app)/layout.tsx
@@ -0,0 +1,27 @@
+import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
+import { AppSidebar } from "@/components/app-sidebar";
+import { ClientMountGate } from "@/components/client-mount-gate";
+
+export default async function AppLayout({ children }: { children: React.ReactNode }) {
+ return (
+ <ClientMountGate
+ fallback={
+ <div className="min-h-screen bg-background" suppressHydrationWarning>
+ {/* Empty shell during hydration — children mount client-side */}
+ </div>
+ }
+ >
+ <SidebarProvider>
+ <AppSidebar />
+ <SidebarInset>
+ <a href="#main-content" className="sr-only focus:not-sr-only">
+ Skip to content
+ </a>
+ <main id="main-content" className="relative flex-1">
+ {children}
+ </main>
+ </SidebarInset>
+ </SidebarProvider>
+ </ClientMountGate>
+ );
+}
diff --git a/notfair-cmo/src/app/(app)/page.tsx b/notfair/src/app/(app)/page.tsx
similarity index 100%
rename from notfair-cmo/src/app/(app)/page.tsx
rename to notfair/src/app/(app)/page.tsx
diff --git a/notfair-cmo/src/app/(app)/projects/new/page.tsx b/notfair/src/app/(app)/projects/new/page.tsx
similarity index 100%
rename from notfair-cmo/src/app/(app)/projects/new/page.tsx
rename to notfair/src/app/(app)/projects/new/page.tsx
diff --git a/notfair-cmo/src/app/(app)/projects/page.tsx b/notfair/src/app/(app)/projects/page.tsx
similarity index 100%
rename from notfair-cmo/src/app/(app)/projects/page.tsx
rename to notfair/src/app/(app)/projects/page.tsx
diff --git a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/live/route.ts b/notfair/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
similarity index 97%
rename from notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
rename to notfair/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
index 82bfe6e2..2942860e 100644
--- a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
+++ b/notfair/src/app/api/agents/[agent]/threads/[thread]/live/route.ts
@@ -54,7 +54,7 @@ export async function GET(
const cursorParam = url.searchParams.get("cursor");
const startCursor = cursorParam ? Math.max(0, Number(cursorParam)) : 0;
- // Resolve the underlying notfair-cmo session row so we can subscribe on
+ // Resolve the underlying NotFair session row so we can subscribe on
// its id (the EventEmitter key). A pending thread that hasn't received
// any turn yet has no row — we still hold the SSE open and rely on the
// subscribe-on-create branch below (the first turn creates the row and
@@ -138,14 +138,14 @@ export async function GET(
function backfill(): void {
if (closed) return;
- const { events, byteOffset } = readTranscriptTail(
+ const { events, cursor } = readTranscriptTail(
projectRow!.slug,
agentFullId,
threadId,
lastSeqEmitted,
);
if (events.length > 0) {
- lastSeqEmitted = byteOffset;
+ lastSeqEmitted = cursor;
send("transcript", { events });
}
// Drain anything that arrived while we were reading the DB.
diff --git a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts b/notfair/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
similarity index 85%
rename from notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
rename to notfair/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
index f4293e2e..fe8c308a 100644
--- a/notfair-cmo/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
+++ b/notfair/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts
@@ -42,19 +42,15 @@ export async function GET(
}
const offsetParam = url.searchParams.get("offset");
- const byteOffset = offsetParam ? Number(offsetParam) : 0;
- const validOffset = Number.isFinite(byteOffset) && byteOffset >= 0 ? byteOffset : 0;
+ const cursor = offsetParam ? Number(offsetParam) : 0;
+ const validOffset = Number.isFinite(cursor) && cursor >= 0 ? cursor : 0;
- const { events, byteOffset: newOffset, fileSize } = readTranscriptTail(
+ const { events, cursor: newCursor } = readTranscriptTail(
project.slug,
resolved.agent_id,
threadId,
validOffset,
);
- return NextResponse.json({
- events,
- byteOffset: newOffset,
- file_size: fileSize,
- });
+ return NextResponse.json({ events, cursor: newCursor });
}
diff --git a/notfair-cmo/src/app/api/browser/launch/route.ts b/notfair/src/app/api/browser/launch/route.ts
similarity index 100%
rename from notfair-cmo/src/app/api/browser/launch/route.ts
rename to notfair/src/app/api/browser/launch/route.ts
diff --git a/notfair-cmo/src/app/api/browser/shutdown/route.ts b/notfair/src/app/api/browser/shutdown/route.ts
similarity index 100%
rename from notfair-cmo/src/app/api/browser/shutdown/route.ts
rename to notfair/src/app/api/browser/shutdown/route.ts
diff --git a/notfair-cmo/src/app/api/browser/status/route.ts b/notfair/src/app/api/browser/status/route.ts
similarity index 100%
rename from notfair-cmo/src/app/api/browser/status/route.ts
rename to notfair/src/app/api/browser/status/route.ts
diff --git a/notfair-cmo/src/app/api/chat/route.ts b/notfair/src/app/api/chat/route.ts
similarity index 67%
rename from notfair-cmo/src/app/api/chat/route.ts
rename to notfair/src/app/api/chat/route.ts
index e9ccbe45..368f5322 100644
--- a/notfair-cmo/src/app/api/chat/route.ts
+++ b/notfair/src/app/api/chat/route.ts
@@ -9,7 +9,6 @@ import {
appendTranscriptEvent,
touchSession,
} from "@/server/sessions";
-import { claimProposedTask, getTask, updateTask } from "@/server/db/tasks";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -22,20 +21,9 @@ type ChatPostBody = {
/**
* Thread label — stable identifier for the chat thread. The route maps
* (project, agent, label) → a sessions row; if none exists it's created.
- * Clients pass the URL thread UUID here (or via `sessionId` for
- * backward-compat with the live-transcript composer). Defaults to "main"
- * only when the caller supplies neither field.
+ * Defaults to "main" when omitted.
*/
thread?: string;
- sessionId?: string;
- /** Legacy from the OpenClaw composer; ignored, kept for body schema compat. */
- sessionKey?: string;
- /**
- * When set, this turn is a task kickoff: atomically claim the task
- * (proposed → working) before forwarding. Concurrent kickoffs / reloads
- * mid-run are rejected with 409.
- */
- task_id?: string;
/**
* Per-turn model override from the composer's model selector. Must be
* one of HARNESS_MODEL_OPTIONS for the project's adapter — anything
@@ -63,7 +51,10 @@ export async function POST(request: Request) {
);
}
- const requestedSlug = (body.agent ?? "cmo").trim();
+ const requestedSlug = (body.agent ?? "").trim();
+ if (!requestedSlug) {
+ return NextResponse.json({ error: "agent is required" }, { status: 400 });
+ }
const resolved = await resolveAgentBySlug(project.slug, requestedSlug);
if (!resolved) {
return NextResponse.json(
@@ -86,37 +77,13 @@ export async function POST(request: Request) {
}
}
- const taskId = body.task_id?.trim();
- if (taskId) {
- const existing = getTask(taskId);
- if (!existing) {
- return NextResponse.json({ error: `Unknown task_id '${taskId}'` }, { status: 404 });
- }
- if (existing.agent_id !== resolved.agent_id) {
- return NextResponse.json(
- {
- error: `Task ${existing.display_id} belongs to ${existing.agent_id}, not ${resolved.agent_id}`,
- },
- { status: 400 },
- );
- }
- const claimed = claimProposedTask(existing.id);
- if (!claimed) {
- return NextResponse.json(
- { error: "task already claimed", status: existing.status, task_id: existing.id },
- { status: 409 },
- );
- }
- }
-
const label =
- body.thread?.trim() || body.sessionId?.trim() || "main";
+ body.thread?.trim() || "main";
const session = getOrCreateSession({
project_slug: project.slug,
agent_id: resolved.agent_id,
label,
harness_adapter: project.harness_adapter,
- task_id: taskId ?? null,
});
appendTranscriptEvent(session.id, "user", { text: body.message });
@@ -148,7 +115,6 @@ export async function POST(request: Request) {
session_id: session.id,
harness_adapter: project.harness_adapter,
message_chars: body.message.length,
- is_kickoff: Boolean(taskId),
});
for await (const evt of adapter.execute({
@@ -187,41 +153,15 @@ export async function POST(request: Request) {
send("lifecycle", { phase: evt.phase });
} else if (evt.kind === "error") {
send("error", { message: evt.message });
- if (taskId) {
- updateTask(taskId, { status: "failed", error_message: evt.message });
- }
}
}
touchSession(session.id);
- // Detect abandoned task kickoffs / follow-ups: the harness turn
- // ended cleanly but the agent didn't call submit_task_status, so
- // the task is still in `working` and would otherwise stay
- // stuck forever. Flip to `blocked` with a clear reason so the
- // UI can recover and the user can choose what to do.
- if (taskId) {
- const current = getTask(taskId);
- if (current && current.status === "working") {
- updateTask(taskId, {
- status: "blocked",
- error_message:
- "Agent finished its turn without calling submit_task_status. The task is parked — send a follow-up message or mark it done manually.",
- });
- send("error", {
- message:
- "Turn ended without submit_task_status. Task moved to blocked.",
- });
- }
- }
-
send("done", {});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
send("error", { message });
- if (taskId) {
- updateTask(taskId, { status: "failed", error_message: message });
- }
} finally {
try {
controller.close();
diff --git a/notfair-cmo/src/app/api/fs/pick-folder/route.ts b/notfair/src/app/api/fs/pick-folder/route.ts
similarity index 100%
rename from notfair-cmo/src/app/api/fs/pick-folder/route.ts
rename to notfair/src/app/api/fs/pick-folder/route.ts
diff --git a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts b/notfair/src/app/api/mcp-oauth/callback/route.ts
similarity index 89%
rename from notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
rename to notfair/src/app/api/mcp-oauth/callback/route.ts
index e961ff33..3dc30be2 100644
--- a/notfair-cmo/src/app/api/mcp-oauth/callback/route.ts
+++ b/notfair/src/app/api/mcp-oauth/callback/route.ts
@@ -9,7 +9,7 @@ export const runtime = "nodejs";
* OAuth 2.0 redirect URI for the one-click MCP connect flow. The browser
* lands here after the user authorizes upstream. We look up the pending
* flow by `state`, exchange the code for an access token, write the
- * MCP config via `openclaw mcp set`, and bounce the user back to the
+ * harness MCP config, and bounce the user back to the
* agent's MCP tab.
*
* On failure we still redirect (so the browser doesn't end up on a raw
@@ -147,22 +147,6 @@ export async function GET(request: Request) {
return NextResponse.redirect(back);
}
- // Token is stored — now provision the specialist agent that matches
- // this MCP (when it's one of the recommended trio: notfair-googleads,
- // notfair-metaads, notfair-googlesearchconsole). The agent must exist
- // BEFORE we register the MCP for it: registerCatalogMcpForProject
- // iterates the project's agents and writes one MCP entry per agent,
- // so a fresh specialist needs to be on disk first or it gets skipped.
- // No-op for non-specialist MCPs (Stripe, Supabase, …).
- try {
- const { provisionSpecialistForMcp } = await import(
- "@/server/agent-templates"
- );
- await provisionSpecialistForMcp(pending.project_slug, pending.catalog_key);
- } catch (err) {
- console.error("[mcp-oauth] provisionSpecialistForMcp threw:", err);
- }
-
// Wire the new token into every agent's harness config so running
// agents actually see the MCP tool surface. Without this step the
// Connections page reads "Connected" (because the probe finds the
@@ -187,8 +171,23 @@ export async function GET(request: Request) {
console.error("[mcp-oauth] registerCatalogMcpForProject threw:", err);
}
+ // Kick off account analysis for platforms we can propose goals from.
+ // Fire-and-forget: the goals index shows the run's progress and the
+ // resulting suggestion cards.
+ try {
+ const { generateSuggestionsForSource, suggestionSourceLabel } = await import(
+ "@/server/suggestions/engine"
+ );
+ if (suggestionSourceLabel(pending.catalog_key)) {
+ void generateSuggestionsForSource(pending.project_slug, pending.catalog_key);
+ back.searchParams.set("mcp_analyzing", "1");
+ }
+ } catch (err) {
+ console.error("[mcp-oauth] suggestion generation kickoff failed:", err);
+ }
+
// Flash banner uses the catalog name (what the user recognizes), not the
- // project-prefixed openclaw key.
+ // project-prefixed server key.
back.searchParams.set("mcp_connected", pending.display_name);
return NextResponse.redirect(back);
}
diff --git a/notfair-cmo/src/app/api/mcp/browser/route.ts b/notfair/src/app/api/mcp/browser/route.ts
similarity index 91%
rename from notfair-cmo/src/app/api/mcp/browser/route.ts
rename to notfair/src/app/api/mcp/browser/route.ts
index 2a9505dc..407daea2 100644
--- a/notfair-cmo/src/app/api/mcp/browser/route.ts
+++ b/notfair/src/app/api/mcp/browser/route.ts
@@ -10,12 +10,12 @@ export const runtime = "nodejs";
/**
* Standalone MCP server for the workspace browser tools.
*
- * Split out from notfair-orchestration so the orchestration surface stays
+ * Split out from notfair-goals so the goal-tool surface stays
* focused on task/approval/project tools, and so users can think about
* "the browser MCP" as its own thing in the Connections / Codex MCP list.
*
* Same transport (streamable-http, JSON-only) and same shared bearer as
- * the orchestration MCP — single-user CLI on loopback so we don't need
+ * the goals MCP — single-user CLI on loopback so we don't need
* per-MCP secrets.
*/
@@ -91,6 +91,6 @@ export async function GET(): Promise<Response> {
return NextResponse.json({
name: SERVER_INFO.name,
transport: "streamable-http",
- note: "POST JSON-RPC with Bearer auth. See ~/.notfair-cmo/mcp-server-secret.",
+ note: "POST JSON-RPC with Bearer auth. See ~/.notfair/mcp-server-secret.",
});
}
diff --git a/notfair-cmo/src/app/api/mcp/orchestration/route.ts b/notfair/src/app/api/mcp/goals/route.ts
similarity index 87%
rename from notfair-cmo/src/app/api/mcp/orchestration/route.ts
rename to notfair/src/app/api/mcp/goals/route.ts
index 301feb22..8443a62b 100644
--- a/notfair-cmo/src/app/api/mcp/orchestration/route.ts
+++ b/notfair/src/app/api/mcp/goals/route.ts
@@ -5,7 +5,7 @@ import { verifyMcpServerSecret } from "@/server/mcp-server/secret";
import { TOOLS } from "@/server/mcp-server/tools";
const SERVER_INFO = {
- name: "notfair-orchestration",
+ name: "notfair-goals",
version: "0.2.0",
tools: TOOLS,
};
@@ -14,15 +14,15 @@ export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
- * MCP server endpoint for OpenClaw-side specialist agents.
+ * MCP server endpoint for goal agents (the notfair-goals server).
*
* Transport: streamable-http with single-shot JSON responses (no SSE; the
- * orchestration tools are short-lived and don't stream). OpenClaw accepts
+ * goal tools are short-lived and don't stream). Clients accept
* either; plain JSON keeps the code small.
*
- * Auth: shared secret in ~/.notfair-cmo/mcp-server-secret. Loopback-only +
+ * Auth: shared secret in ~/.notfair/mcp-server-secret. Loopback-only +
* single-user CLI, so a shared bearer is sufficient. Agents pick up the
- * secret via the per-project `openclaw mcp set` registration step.
+ * secret written at agent-provision time.
*/
function unauthorized(): Response {
@@ -99,6 +99,6 @@ export async function GET(): Promise<Response> {
return NextResponse.json({
name: SERVER_INFO.name,
transport: "streamable-http",
- note: "POST JSON-RPC with Bearer auth. See ~/.notfair-cmo/mcp-server-secret.",
+ note: "POST JSON-RPC with Bearer auth. See ~/.notfair/mcp-server-secret.",
});
}
diff --git a/notfair-cmo/src/app/api/upgrade/route.ts b/notfair/src/app/api/upgrade/route.ts
similarity index 81%
rename from notfair-cmo/src/app/api/upgrade/route.ts
rename to notfair/src/app/api/upgrade/route.ts
index 7143c204..d15fec22 100644
--- a/notfair-cmo/src/app/api/upgrade/route.ts
+++ b/notfair/src/app/api/upgrade/route.ts
@@ -12,12 +12,12 @@ const TAIL_BYTES = 4_000;
/**
* POST /api/upgrade
*
- * Runs `npm i -g notfair-cmo@latest` from the user's shell environment.
- * The currently-running notfair-cmo process keeps the old code loaded in
- * memory (Node module cache), so the user must restart `notfair-cmo` to
+ * Runs `npm i -g notfair@latest` from the user's shell environment.
+ * The currently-running NotFair process keeps the old code loaded in
+ * memory (Node module cache), so the user must restart `notfair` to
* pick up the upgraded binary. The response message says so.
*
- * If npm isn't on PATH (e.g. the user runs notfair-cmo from a node_modules
+ * If npm isn't on PATH (e.g. the user runs NotFair from a node_modules
* shim that doesn't expose npm globally), we surface the spawn error so
* the client can show the copyable command instead.
*/
@@ -26,7 +26,7 @@ export async function POST() {
// PATH (Homebrew Node etc.). `-l` ensures their shell profile is read.
return new Promise<Response>((resolve) => {
const startedAt = Date.now();
- const child = spawn("npm", ["i", "-g", "notfair-cmo@latest"], {
+ const child = spawn("npm", ["i", "-g", "notfair@latest"], {
stdio: ["ignore", "pipe", "pipe"],
env: process.env,
});
@@ -60,8 +60,8 @@ export async function POST() {
ok: false,
error: err.message,
hint:
- "Could not run `npm` from the notfair-cmo process. Run `npm i -g notfair-cmo@latest` in your terminal instead.",
- command: "npm i -g notfair-cmo@latest",
+ "Could not run `npm` from the NotFair process. Run `npm i -g notfair@latest` in your terminal instead.",
+ command: "npm i -g notfair@latest",
},
{ status: 500 },
),
@@ -83,7 +83,7 @@ export async function POST() {
installed_version: latest ?? null,
running_version: getCurrentVersion(),
note:
- "Upgraded. Restart notfair-cmo to load the new version (`notfair-cmo` in your terminal).",
+ "Upgraded. Restart NotFair to load the new version (`notfair` in your terminal).",
elapsed_ms,
stdout_tail: stdout.slice(-1000),
}),
@@ -97,7 +97,7 @@ export async function POST() {
elapsed_ms,
stdout_tail: stdout.slice(-1000),
stderr_tail: stderr.slice(-1000),
- command: "npm i -g notfair-cmo@latest",
+ command: "npm i -g notfair@latest",
},
{ status: 500 },
),
diff --git a/notfair-cmo/src/app/api/version/route.ts b/notfair/src/app/api/version/route.ts
similarity index 86%
rename from notfair-cmo/src/app/api/version/route.ts
rename to notfair/src/app/api/version/route.ts
index c7387ad1..9703ec28 100644
--- a/notfair-cmo/src/app/api/version/route.ts
+++ b/notfair/src/app/api/version/route.ts
@@ -8,7 +8,7 @@ export const runtime = "nodejs";
/**
* GET /api/version
*
- * Returns the installed notfair-cmo version + the latest version on npm
+ * Returns the installed NotFair version + the latest version on npm
* + whether an update is available. The sidebar polls this once on mount;
* the latest-version lookup is cached for 1 hour in-process so this is
* cheap to call.
diff --git a/notfair-cmo/src/app/globals.css b/notfair/src/app/globals.css
similarity index 99%
rename from notfair-cmo/src/app/globals.css
rename to notfair/src/app/globals.css
index ad4368db..6c2f7b77 100644
--- a/notfair-cmo/src/app/globals.css
+++ b/notfair/src/app/globals.css
@@ -4,7 +4,7 @@
@layer base {
:root {
- /* ── notfair-cmo design system (see DESIGN.md) ───────────────────
+ /* ── NotFair design system (see DESIGN.md) ───────────────────
Codex-flavored monochrome chrome, dark-first with a light mode.
Depth comes from elevation (surface steps + soft shadows), not
border lines. Color is reserved for semantics: green = live/
@@ -234,7 +234,7 @@
}
/* ────────────────────────────────────────────────────────────────────
- notfair-cmo design-system component classes.
+ NotFair design-system component classes.
These are the named building blocks called out in DESIGN.md so
onboarding (and later, every other surface) can compose them
diff --git a/notfair-cmo/src/app/layout.tsx b/notfair/src/app/layout.tsx
similarity index 78%
rename from notfair-cmo/src/app/layout.tsx
rename to notfair/src/app/layout.tsx
index d688c9fa..737869cc 100644
--- a/notfair-cmo/src/app/layout.tsx
+++ b/notfair/src/app/layout.tsx
@@ -5,8 +5,8 @@ import { ThemeProvider } from "@/components/theme-provider";
import "./globals.css";
export const metadata: Metadata = {
- title: "notfair CMO",
- description: "Your local AI marketing team.",
+ title: "NotFair",
+ description: "Goal-driven, loop-powered marketing agents on your machine.",
};
export default function RootLayout({
@@ -19,7 +19,7 @@ export default function RootLayout({
<body className="min-h-screen bg-background text-foreground antialiased">
<ThemeProvider>
<TooltipProvider delayDuration={200}>{children}</TooltipProvider>
- <Toaster position="top-right" richColors />
+ <Toaster position="top-right" richColors closeButton duration={5000} />
</ThemeProvider>
</body>
</html>
diff --git a/notfair-cmo/src/app/onboarding/layout.tsx b/notfair/src/app/onboarding/layout.tsx
similarity index 100%
rename from notfair-cmo/src/app/onboarding/layout.tsx
rename to notfair/src/app/onboarding/layout.tsx
diff --git a/notfair-cmo/src/app/onboarding/page.tsx b/notfair/src/app/onboarding/page.tsx
similarity index 100%
rename from notfair-cmo/src/app/onboarding/page.tsx
rename to notfair/src/app/onboarding/page.tsx
diff --git a/notfair-cmo/src/components/add-mcp-server-card.tsx b/notfair/src/components/add-mcp-server-card.tsx
similarity index 100%
rename from notfair-cmo/src/components/add-mcp-server-card.tsx
rename to notfair/src/components/add-mcp-server-card.tsx
diff --git a/notfair-cmo/src/components/app-sidebar.tsx b/notfair/src/components/app-sidebar.tsx
similarity index 65%
rename from notfair-cmo/src/components/app-sidebar.tsx
rename to notfair/src/components/app-sidebar.tsx
index 8db6206b..4d5d79b2 100644
--- a/notfair-cmo/src/components/app-sidebar.tsx
+++ b/notfair/src/components/app-sidebar.tsx
@@ -13,25 +13,17 @@ import {
SidebarTrigger,
} from "@/components/ui/sidebar";
import { SidebarBrand } from "@/components/sidebar-brand";
-import {
- Home,
- CheckCircle2,
- ListChecks,
- Clock,
- Plug,
- Settings,
- Activity,
- type LucideIcon,
-} from "lucide-react";
+import { BookOpen, Plug, Settings, Target, type LucideIcon } from "lucide-react";
import { listProjects } from "@/server/db/projects";
import { getActiveProject } from "@/server/active-project";
import { listProjectAgents } from "@/server/agent-meta";
-import { TEMPLATES } from "@/server/agent-templates";
+import { getGoalForAgent, getLatestGoalForAgent, type GoalStatus } from "@/server/db/goals";
+import { colorForAgentSlug } from "@/lib/agent-colors";
import { readHarnessUsage } from "@/server/harness-usage";
import { projectHref } from "@/lib/project-href";
+import { cn } from "@/lib/utils";
+import { goalLabel } from "@/lib/goal-label";
import { ProjectSwitcher } from "./project-switcher";
-import { AgentNav } from "./agent-nav";
-import { ApprovalsLiveBadge } from "./live-badge";
import { HarnessFooter } from "./harness-footer";
import { SidebarVersion } from "./sidebar-version";
import { ThemeToggle } from "./theme-toggle";
@@ -40,19 +32,25 @@ type NavItem = {
href: string;
label: string;
icon: LucideIcon;
- badge?: boolean;
};
const NAV: NavItem[] = [
- { href: "", label: "Home", icon: Home },
- { href: "/approvals", label: "Approvals", icon: CheckCircle2, badge: true },
- { href: "/tasks", label: "Tasks", icon: ListChecks },
- { href: "/crons", label: "Crons", icon: Clock },
- { href: "/activity", label: "Activity", icon: Activity },
+ { href: "/context", label: "Shared context", icon: BookOpen },
{ href: "/connections", label: "Connections", icon: Plug },
{ href: "/settings", label: "Settings", icon: Settings },
];
+/** Compact status dot per goal state — the sidebar's only status signal. */
+const GOAL_DOT: Record<GoalStatus, string> = {
+ intake: "ns-dot-warn",
+ proposed: "ns-dot-warn",
+ active: "ns-dot-live",
+ paused: "ns-dot-mute",
+ achieved: "ns-dot-on",
+ failed: "ns-dot-err",
+ killed: "ns-dot-mute",
+};
+
export async function AppSidebar() {
const projects = listProjects();
const active = await getActiveProject();
@@ -91,21 +89,37 @@ export async function AppSidebar() {
<SidebarContent>
{active && (
<SidebarGroup>
- <SidebarGroupLabel>Team</SidebarGroupLabel>
+ <SidebarGroupLabel>Goals</SidebarGroupLabel>
<SidebarGroupContent>
- <AgentNav
- projectSlug={active.slug}
- agents={agentEntries.map((a) => ({
- key: a.agent_id,
- slug: a.slug,
- name: a.name,
- role_label: a.template_key
- ? TEMPLATES.find((t) => t.key === a.template_key)?.display_name
- : undefined,
- description: a.description,
- template_key: a.template_key,
- }))}
- />
+ <SidebarMenu>
+ {agentEntries.map((a) => {
+ const goal = getGoalForAgent(a.agent_id) ?? getLatestGoalForAgent(a.agent_id);
+ const color = colorForAgentSlug(a.slug);
+ return (
+ <SidebarMenuItem key={a.agent_id}>
+ <SidebarMenuButton asChild>
+ <Link href={projectHref(active.slug, `/goals/${a.slug}`)}>
+ <span
+ className={cn("ns-dot", goal ? GOAL_DOT[goal.status] : "ns-dot-mute")}
+ aria-hidden
+ />
+ <span className={cn("truncate", color.label)}>
+ {goal ? goalLabel(goal) : a.name}
+ </span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ );
+ })}
+ <SidebarMenuItem>
+ <SidebarMenuButton asChild>
+ <Link href={projectHref(active.slug, "")}>
+ <Target />
+ <span>New goal…</span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ </SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
)}
@@ -121,7 +135,6 @@ export async function AppSidebar() {
<Link href={projectHref(active.slug, item.href)}>
<item.icon />
<span>{item.label}</span>
- {item.badge && <ApprovalsLiveBadge />}
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
diff --git a/notfair-cmo/src/components/browse-connectors-dialog.tsx b/notfair/src/components/browse-connectors-dialog.tsx
similarity index 100%
rename from notfair-cmo/src/components/browse-connectors-dialog.tsx
rename to notfair/src/components/browse-connectors-dialog.tsx
diff --git a/notfair-cmo/src/components/builtin-mcp-card.tsx b/notfair/src/components/builtin-mcp-card.tsx
similarity index 96%
rename from notfair-cmo/src/components/builtin-mcp-card.tsx
rename to notfair/src/components/builtin-mcp-card.tsx
index 02454c7f..00c26a7e 100644
--- a/notfair-cmo/src/components/builtin-mcp-card.tsx
+++ b/notfair/src/components/builtin-mcp-card.tsx
@@ -7,7 +7,7 @@ import { McpToolsDialog } from "@/components/mcp-tools-dialog";
import type { ToolSummary } from "@/server/mcp-server/tool-summaries";
/**
- * Row for an MCP that ships with notfair-cmo itself — no OAuth, no
+ * Row for an MCP that ships with NotFair itself — no OAuth, no
* connect/disconnect. Settings-row shaped to match McpCard. We drop
* the "Built-in" pill because the section heading and the metadata
* line ("self-hosted · 21 tools · no setup") already convey it; one
diff --git a/notfair-cmo/src/components/client-mount-gate.tsx b/notfair/src/components/client-mount-gate.tsx
similarity index 100%
rename from notfair-cmo/src/components/client-mount-gate.tsx
rename to notfair/src/components/client-mount-gate.tsx
diff --git a/notfair-cmo/src/components/danger-zone.tsx b/notfair/src/components/danger-zone.tsx
similarity index 93%
rename from notfair-cmo/src/components/danger-zone.tsx
rename to notfair/src/components/danger-zone.tsx
index a75d6eb7..b146121c 100644
--- a/notfair-cmo/src/components/danger-zone.tsx
+++ b/notfair/src/components/danger-zone.tsx
@@ -57,16 +57,14 @@ export function DangerZone({ projectSlug, projectName }: Props) {
return;
}
const d = r.data;
- const partial = d.agentsFailed.length + d.cronsFailed;
+ const partial = d.agentsFailed.length;
if (partial > 0) {
+ const detail = d.agentsFailed[0]?.error ?? "";
toast.warning(
- `Deleted with ${partial} issue${partial === 1 ? "" : "s"}. ` +
- `${d.agents.length} agents, ${d.crons} crons removed.`,
+ `Deleted, but ${partial} cleanup step${partial === 1 ? "" : "s"} failed${detail ? `: ${detail}` : "."}`,
);
} else {
- toast.success(
- `Deleted ${projectName}. ${d.agents.length} agents, ${d.crons} crons removed.`,
- );
+ toast.success(`Deleted ${projectName}. ${d.agents.length} goals removed.`);
}
setOpen(false);
router.push("/");
@@ -95,7 +93,7 @@ export function DangerZone({ projectSlug, projectName }: Props) {
Delete this workspace
</h3>
<p className="mt-1 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">
- Removes all agents, every scheduled cron job, and every thread of
+ Removes every goal, its agent, and every thread of
chat history. This cannot be undone.
</p>
</div>
@@ -118,7 +116,7 @@ export function DangerZone({ projectSlug, projectName }: Props) {
Delete &ldquo;{projectName}&rdquo;?
</DialogTitle>
<DialogDescription>
- This will permanently delete the items below from notfair-cmo&apos;s
+ This will permanently delete the items below from NotFair&apos;s
local store. There is no recovery.
</DialogDescription>
</DialogHeader>
@@ -137,7 +135,6 @@ export function DangerZone({ projectSlug, projectName }: Props) {
<div className="grid grid-cols-4 divide-x rounded-xl border border-border bg-card">
<Stat label="Agents" value={summary.totals.agents} />
<Stat label="Threads" value={summary.totals.threads} />
- <Stat label="Crons" value={summary.totals.crons} />
<Stat label="MCPs" value={summary.totals.mcps} />
</div>
{summary.agents.some((a) => a.exists) && (
diff --git a/notfair/src/components/goal-auto-refresh.tsx b/notfair/src/components/goal-auto-refresh.tsx
new file mode 100644
index 00000000..dad6d523
--- /dev/null
+++ b/notfair/src/components/goal-auto-refresh.tsx
@@ -0,0 +1,18 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useEffect } from "react";
+
+/**
+ * Poll-refresh for goal states that change server-side without user input
+ * (intake running, a tick in flight). Server components re-render on
+ * router.refresh(), so the page stays live without a websocket.
+ */
+export function GoalAutoRefresh({ intervalMs = 5000 }: { intervalMs?: number }) {
+ const router = useRouter();
+ useEffect(() => {
+ const t = setInterval(() => router.refresh(), intervalMs);
+ return () => clearInterval(t);
+ }, [router, intervalMs]);
+ return null;
+}
diff --git a/notfair/src/components/goal-checks-strip.tsx b/notfair/src/components/goal-checks-strip.tsx
new file mode 100644
index 00000000..06556070
--- /dev/null
+++ b/notfair/src/components/goal-checks-strip.tsx
@@ -0,0 +1,74 @@
+import { cn } from "@/lib/utils";
+import type { CheckSquare, Streak } from "@/lib/goal-streak";
+
+/**
+ * Maintain-goal hero: the streak headline plus one square per check —
+ * held / intervened / failed. Colors are never alone: each square has a
+ * distinct glyph for the non-held states and a native tooltip, and the
+ * legend spells the mapping out in text.
+ */
+export function GoalChecksStrip({
+ squares,
+ streak,
+}: {
+ squares: CheckSquare[];
+ streak: Streak | null;
+}) {
+ const recent = squares.slice(-28);
+ return (
+ <div>
+ <p className="m-0 mb-2 text-[13px]">
+ {streak === null ? (
+ <span className="text-[hsl(var(--notfair-ink-4))]">No checks yet.</span>
+ ) : !streak.holding ? (
+ <span>
+ <b>Attention needed</b> — the last check drifted or failed.
+ </span>
+ ) : streak.days === 0 ? (
+ <span>
+ <b>Holding at target</b> — since today&rsquo;s check.
+ </span>
+ ) : (
+ <span>
+ Held at target for{" "}
+ <b className="tabular-nums">
+ {streak.days} day{streak.days === 1 ? "" : "s"}
+ </b>
+ </span>
+ )}
+ </p>
+ {recent.length > 0 && (
+ <>
+ <div className="flex flex-wrap gap-1" role="img" aria-label="Check history">
+ {recent.map((sq) => (
+ <span
+ key={sq.tick_number}
+ title={`Check ${sq.tick_number} — ${
+ sq.state === "held"
+ ? "held at target"
+ : sq.state === "acted"
+ ? "agent intervened"
+ : "drifted or failed"
+ } (${new Date(sq.t).toLocaleDateString()})`}
+ className={cn(
+ "flex size-4 items-center justify-center rounded-[3px] text-[9px] font-bold leading-none",
+ sq.state === "held" &&
+ "bg-[hsl(var(--notfair-accent))] text-transparent",
+ sq.state === "acted" &&
+ "bg-[hsl(217_60%_55%)] text-white",
+ sq.state === "failed" && "bg-[hsl(0_72%_51%)] text-white",
+ )}
+ >
+ {sq.state === "acted" ? "▼" : sq.state === "failed" ? "✕" : ""}
+ </span>
+ ))}
+ </div>
+ <p className="m-0 mt-1.5 text-[10.5px] text-[hsl(var(--notfair-ink-4))]">
+ ■ held · <span className="font-bold">▼</span> intervened ·{" "}
+ <span className="font-bold">✕</span> drifted/failed
+ </p>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/notfair/src/components/goal-context-dialog.tsx b/notfair/src/components/goal-context-dialog.tsx
new file mode 100644
index 00000000..9683f973
--- /dev/null
+++ b/notfair/src/components/goal-context-dialog.tsx
@@ -0,0 +1,294 @@
+"use client";
+
+import { useCallback, useMemo, useState } from "react";
+import { ChevronRight, Layers, Loader2 } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ getGoalContextAction,
+ type ContextChunk,
+} from "@/server/actions/context";
+import { cn } from "@/lib/utils";
+import { Markdown } from "@/components/markdown";
+
+/**
+ * /context for a goal: what fills this agent's context window, measured
+ * against the SELECTED MODEL's real window size (read from the harness's
+ * own model metadata — never hardcoded here). Token counts are estimates
+ * (~4 chars/token); clicking a row reveals the chunk's exact content.
+ */
+
+export type ContextModelOption = {
+ value: string;
+ label: string;
+ context_window?: number;
+};
+
+const GROUP_META: Record<
+ ContextChunk["group"],
+ { label: string; swatch: string }
+> = {
+ instructions: { label: "Instructions", swatch: "bg-[hsl(var(--notfair-accent))]" },
+ tools: { label: "Tool definitions", swatch: "bg-[hsl(217_60%_55%)]" },
+ conversation: { label: "Conversation", swatch: "bg-[hsl(38_80%_55%)]" },
+};
+
+const FREE_SWATCH = "bg-[hsl(var(--notfair-ink-4)/0.18)]";
+
+/** 36_308 → "36.3k", 272_000 → "272k", 319 → "319". */
+function fmtK(n: number): string {
+ if (n < 1000) return String(n);
+ const k = n / 1000;
+ return `${k >= 100 ? Math.round(k) : k.toFixed(1).replace(/\.0$/, "")}k`;
+}
+
+type LoadState =
+ | { phase: "idle" }
+ | { phase: "loading" }
+ | { phase: "error"; message: string }
+ | { phase: "ready"; chunks: ContextChunk[]; total: number };
+
+export function GoalContextDialog({
+ projectSlug,
+ agentId,
+ threadId,
+ models,
+}: {
+ projectSlug: string;
+ agentId: string;
+ threadId: string;
+ models: ContextModelOption[];
+}) {
+ const [open, setOpen] = useState(false);
+ const [state, setState] = useState<LoadState>({ phase: "idle" });
+ const [expanded, setExpanded] = useState<string | null>(null);
+ const [model, setModel] = useState(models[0]?.value ?? "");
+
+ const selected = useMemo(
+ () => models.find((m) => m.value === model) ?? models[0],
+ [models, model],
+ );
+ const window = selected?.context_window;
+
+ const load = useCallback(async () => {
+ setState({ phase: "loading" });
+ const r = await getGoalContextAction({
+ project_slug: projectSlug,
+ agent_id: agentId,
+ thread: threadId,
+ });
+ if (r.ok) setState({ phase: "ready", chunks: r.chunks, total: r.total_tokens });
+ else setState({ phase: "error", message: r.error });
+ }, [projectSlug, agentId, threadId]);
+
+ function onOpenChange(next: boolean) {
+ setOpen(next);
+ if (next && state.phase === "idle") void load();
+ if (!next) setExpanded(null);
+ }
+
+ // Denominator: the model's window when known, else the measured total.
+ const denom =
+ state.phase === "ready" ? (window && window > state.total ? window : state.total) : 0;
+ const pct = (tokens: number) => (denom > 0 ? (tokens / denom) * 100 : 0);
+
+ const groupTotals =
+ state.phase === "ready"
+ ? (Object.keys(GROUP_META) as ContextChunk["group"][]).map((g) => ({
+ group: g,
+ tokens: state.chunks
+ .filter((c) => c.group === g)
+ .reduce((a, c) => a + c.tokens, 0),
+ }))
+ : [];
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogTrigger asChild>
+ <button
+ type="button"
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-[hsl(var(--notfair-surface-2))] px-2.5 py-1 text-[12px] text-[hsl(var(--notfair-ink-3))] transition-colors hover:text-[hsl(var(--notfair-ink-1))]"
+ title="What fills this agent's context window"
+ >
+ <Layers className="size-3.5" aria-hidden />
+ Context
+ </button>
+ </DialogTrigger>
+ <DialogContent className="max-h-[82vh] overflow-y-auto sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2 text-[15px]">
+ <Layers className="size-4" aria-hidden />
+ Context window
+ </DialogTitle>
+ <DialogDescription>
+ What this goal&rsquo;s agent works with each turn. Token counts are
+ estimates (~4 characters per token) — click any row for the exact
+ content.
+ </DialogDescription>
+ </DialogHeader>
+
+ {state.phase === "loading" && (
+ <div className="flex items-center gap-2 py-6 text-[13px] text-[hsl(var(--notfair-ink-4))]">
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ Measuring instruction files, tool schemas, and the conversation…
+ </div>
+ )}
+ {state.phase === "error" && (
+ <p className="py-4 text-[13px] text-[hsl(0_72%_51%)]">{state.message}</p>
+ )}
+
+ {state.phase === "ready" && (
+ <>
+ {/* Headline: used-of-window, with the model (and its window)
+ selectable — window sizes come from the harness's own model
+ metadata. */}
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <p className="m-0 text-[20px] font-semibold tabular-nums">
+ ≈{fmtK(state.total)}
+ {window ? (
+ <>
+ <span className="text-[hsl(var(--notfair-ink-4))]"> of </span>
+ {fmtK(window)}
+ <span className="ml-2 text-[13px] font-normal text-[hsl(var(--notfair-ink-3))]">
+ {pct(state.total).toFixed(1)}% used
+ </span>
+ </>
+ ) : (
+ <span className="ml-1 text-[13px] font-normal text-[hsl(var(--notfair-ink-4))]">
+ tokens (window size unknown for this model)
+ </span>
+ )}
+ </p>
+ <label className="flex items-center gap-1.5 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ window of
+ <select
+ value={selected?.value ?? ""}
+ onChange={(e) => setModel(e.target.value)}
+ className="rounded-md bg-[hsl(var(--notfair-surface-2))] px-1.5 py-0.5 text-[12px] text-[hsl(var(--notfair-ink-2))]"
+ >
+ {models.map((m) => (
+ <option key={m.value} value={m.value}>
+ {m.label}
+ {m.context_window ? ` · ${fmtK(m.context_window)}` : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+
+ {/* Stacked bar of the WHOLE window; the muted tail is free space. */}
+ <div
+ className="flex h-4 w-full overflow-hidden rounded-md"
+ role="img"
+ aria-label={
+ window
+ ? `Estimated ${fmtK(state.total)} of ${fmtK(window)} tokens used`
+ : `Estimated ${fmtK(state.total)} tokens`
+ }
+ >
+ {state.chunks.map((c) => (
+ <span
+ key={c.key}
+ className={cn(
+ GROUP_META[c.group].swatch,
+ "border-r border-[hsl(var(--background))] last:border-r-0",
+ )}
+ style={{ width: `${Math.max(0.5, pct(c.tokens))}%` }}
+ title={`${c.label} — ~${fmtK(c.tokens)} tokens`}
+ />
+ ))}
+ {window && window > state.total && (
+ <span
+ className={cn(FREE_SWATCH, "flex-1")}
+ title={`Free — ~${fmtK(window - state.total)} tokens`}
+ />
+ )}
+ </div>
+
+ {/* Group subtotals as the legend — text carries identity. */}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[11.5px] text-[hsl(var(--notfair-ink-3))]">
+ {groupTotals.map(({ group, tokens }) => (
+ <span key={group} className="inline-flex items-center gap-1.5 tabular-nums">
+ <span className={cn("size-2 rounded-[2px]", GROUP_META[group].swatch)} aria-hidden />
+ {GROUP_META[group].label} ~{fmtK(tokens)}
+ </span>
+ ))}
+ {window && window > state.total && (
+ <span className="inline-flex items-center gap-1.5 tabular-nums">
+ <span className={cn("size-2 rounded-[2px]", FREE_SWATCH)} aria-hidden />
+ Free ~{fmtK(window - state.total)}
+ </span>
+ )}
+ </div>
+
+ <ul className="m-0 flex list-none flex-col p-0">
+ {state.chunks.map((c) => {
+ const isOpen = expanded === c.key;
+ const share = pct(c.tokens);
+ return (
+ <li key={c.key}>
+ <button
+ type="button"
+ onClick={() => setExpanded(isOpen ? null : c.key)}
+ className="flex w-full items-center gap-2.5 rounded-md px-1.5 py-2.5 text-left text-[13px] transition-colors hover:bg-[hsl(var(--notfair-surface-2))]"
+ aria-expanded={isOpen}
+ >
+ <ChevronRight
+ className={cn("size-3.5 shrink-0 text-[hsl(var(--notfair-ink-4))] transition-transform", isOpen && "rotate-90")}
+ aria-hidden
+ />
+ <span className={cn("size-2 shrink-0 rounded-[2px]", GROUP_META[c.group].swatch)} aria-hidden />
+ <span className="min-w-0 flex-1 truncate">{c.label}</span>
+ {/* per-row share of the window, as a quiet inline bar */}
+ <span className="hidden h-1.5 w-20 shrink-0 overflow-hidden rounded-full bg-[hsl(var(--notfair-ink-4)/0.12)] sm:block" aria-hidden>
+ <span
+ className={cn("block h-full", GROUP_META[c.group].swatch)}
+ style={{ width: `${Math.min(100, Math.max(1.5, share))}%` }}
+ />
+ </span>
+ <span className="w-16 shrink-0 text-right tabular-nums text-[12px] text-[hsl(var(--notfair-ink-3))]">
+ ~{fmtK(c.tokens)}
+ </span>
+ <span className="w-12 shrink-0 text-right tabular-nums text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ {share < 0.1 ? "<0.1" : share.toFixed(1)}%
+ </span>
+ </button>
+ {isOpen && (
+ <div className="mb-3 ml-6">
+ {c.note && (
+ <p className="m-0 mb-1.5 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ {c.note}
+ </p>
+ )}
+ {c.format === "json" ? (
+ <pre className="m-0 max-h-72 overflow-auto rounded-md bg-[hsl(var(--notfair-ink-1)/0.04)] p-3 text-[11px] leading-relaxed whitespace-pre-wrap break-words text-[hsl(var(--notfair-ink-2))]">
+ {c.content}
+ </pre>
+ ) : (
+ <div className="max-h-72 overflow-auto rounded-md bg-[hsl(var(--notfair-ink-1)/0.04)] p-3">
+ <Markdown className="text-[12px]">{c.content}</Markdown>
+ </div>
+ )}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ <p className="m-0 text-[11px] leading-snug text-[hsl(var(--notfair-ink-4))]">
+ Not shown: the harness&rsquo;s own base prompt and its full
+ tool-output history — those live inside the runtime and
+ aren&rsquo;t visible to NotFair.
+ </p>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/notfair/src/components/goal-controls.tsx b/notfair/src/components/goal-controls.tsx
new file mode 100644
index 00000000..d532a8b3
--- /dev/null
+++ b/notfair/src/components/goal-controls.tsx
@@ -0,0 +1,124 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState, useTransition } from "react";
+import { toast } from "sonner";
+import { Pause, Play, Square, Zap } from "lucide-react";
+import {
+ killGoalAction,
+ pauseGoalAction,
+ resumeGoalAction,
+ runTickNowAction,
+} from "@/server/actions/goals";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+
+/** Pause / resume / run-tick-now / close controls for a live goal. */
+export function GoalControls({
+ goalId,
+ status,
+}: {
+ goalId: string;
+ status: "active" | "paused" | "intake" | "proposed";
+}) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const [killOpen, setKillOpen] = useState(false);
+
+ function run(
+ fn: () => Promise<{ ok: boolean; error?: string }>,
+ successMsg: string,
+ ) {
+ startTransition(async () => {
+ const r = await fn();
+ if (!r.ok) {
+ toast.error(r.error ?? "Action failed.");
+ return;
+ }
+ toast.success(successMsg);
+ router.refresh();
+ });
+ }
+
+ return (
+ <div className="flex items-center gap-2">
+ {status === "active" && (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={pending}
+ onClick={() => run(() => runTickNowAction(goalId), "Tick started — watch the diary.")}
+ >
+ <Zap className="size-3.5" />
+ Run tick now
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={pending}
+ onClick={() => run(() => pauseGoalAction(goalId), "Goal paused.")}
+ >
+ <Pause className="size-3.5" />
+ Pause
+ </Button>
+ </>
+ )}
+ {status === "paused" && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={pending}
+ onClick={() => run(() => resumeGoalAction(goalId), "Goal resumed — heartbeat restarted.")}
+ >
+ <Play className="size-3.5" />
+ Resume
+ </Button>
+ )}
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={pending}
+ onClick={() => setKillOpen(true)}
+ className="text-[hsl(0_72%_51%)]"
+ >
+ <Square className="size-3.5" />
+ Close goal
+ </Button>
+
+ <Dialog open={killOpen} onOpenChange={setKillOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Close this goal?</DialogTitle>
+ <DialogDescription>
+ The loop stops permanently and the goal moves to history. This
+ can&rsquo;t be undone — you&rsquo;d start a fresh goal instead.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setKillOpen(false)} disabled={pending}>
+ Keep it
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={pending}
+ onClick={() => {
+ setKillOpen(false);
+ run(() => killGoalAction(goalId), "Goal closed.");
+ }}
+ >
+ Close goal
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/notfair/src/components/goal-memory-dialog.tsx b/notfair/src/components/goal-memory-dialog.tsx
new file mode 100644
index 00000000..30627f33
--- /dev/null
+++ b/notfair/src/components/goal-memory-dialog.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { useState } from "react";
+import { Brain } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { cn } from "@/lib/utils";
+import { Markdown } from "@/components/markdown";
+
+export type MemoryEntry = {
+ id: string;
+ body: string;
+ confidence: "low" | "medium" | "high";
+ created_at: string;
+};
+
+const CONFIDENCE_STYLE: Record<MemoryEntry["confidence"], string> = {
+ high: "text-[hsl(var(--notfair-accent))]",
+ medium: "text-[hsl(var(--notfair-ink-3))]",
+ low: "text-[hsl(var(--notfair-ink-4))]",
+};
+
+function fmtDate(iso: string): string {
+ return new Date(iso).toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ });
+}
+
+/**
+ * The goal's memory, one click from the header: everything the agent has
+ * learned about this goal (the `log_learning` ledger), newest first, with
+ * confidence and date. Lives in the header so it's reachable without
+ * scrolling the rail, and scales past the handful a rail section could fit.
+ */
+export function GoalMemoryDialog({ entries }: { entries: MemoryEntry[] }) {
+ const [open, setOpen] = useState(false);
+ if (entries.length === 0) return null;
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <button
+ type="button"
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-[hsl(var(--notfair-surface-2))] px-2.5 py-1 text-[12px] text-[hsl(var(--notfair-ink-3))] transition-colors hover:text-[hsl(var(--notfair-ink-1))]"
+ title="What the agent has learned about this goal"
+ >
+ <Brain className="size-3.5" aria-hidden />
+ Memory
+ <span className="tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {entries.length}
+ </span>
+ </button>
+ </DialogTrigger>
+ <DialogContent className="max-h-[70vh] overflow-y-auto sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2 text-[15px]">
+ <Brain className="size-4" aria-hidden />
+ Memory
+ </DialogTitle>
+ <DialogDescription>
+ What the agent has learned working this goal — it reads these
+ before every check.
+ </DialogDescription>
+ </DialogHeader>
+ <ul className="m-0 flex list-none flex-col gap-3 p-0">
+ {entries.map((l) => (
+ <li
+ key={l.id}
+ className="rounded-md bg-[hsl(var(--notfair-surface-2)/0.5)] px-3 py-2.5 text-[13px] leading-snug"
+ >
+ <Markdown className="text-[13px] text-[hsl(var(--notfair-ink-2))]">{l.body}</Markdown>
+ <p className="m-0 mt-1 text-[11px] text-[hsl(var(--notfair-ink-4))]">
+ <span className={cn("font-medium", CONFIDENCE_STYLE[l.confidence])}>
+ {l.confidence} confidence
+ </span>{" "}
+ · {fmtDate(l.created_at)}
+ </p>
+ </li>
+ ))}
+ </ul>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/notfair/src/components/goal-progress-chart.tsx b/notfair/src/components/goal-progress-chart.tsx
new file mode 100644
index 00000000..336d320f
--- /dev/null
+++ b/notfair/src/components/goal-progress-chart.tsx
@@ -0,0 +1,364 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+
+/**
+ * The goal's hero chart: the metric over real time, with the target and
+ * baseline as reference lines, every agent action as a marker on the
+ * moment it happened, and observation windows shaded — cause and effect
+ * on one picture.
+ *
+ * Dataviz rules applied: single series (no legend — the card title names
+ * it), 2px line, ≥8px hit targets with a 2px surface ring, recessive
+ * grid/reference lines in ink tokens, crosshair + tooltip by default,
+ * text in text tokens never series color, and every colored mark carries
+ * a shape + tooltip so nothing is color-alone.
+ */
+
+export type ChartPoint = { t: number; v: number; source: string };
+export type ChartAction = {
+ t: number;
+ kind: string;
+ label: string;
+ expected: string;
+ observed: string | null;
+ reviewUntil: number | null;
+};
+export type ChartFailure = { t: number; error: string };
+
+const W = 340;
+const H = 170;
+const PAD = { top: 10, right: 10, bottom: 20, left: 34 };
+
+function fmtVal(v: number): string {
+ if (Math.abs(v) >= 1000) return `${(v / 1000).toFixed(1)}k`;
+ return Number.isInteger(v) ? String(v) : v.toFixed(2);
+}
+
+function fmtDate(t: number): string {
+ return new Date(t).toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
+export function GoalProgressChart({
+ points,
+ actions,
+ failures,
+ target,
+ baseline,
+ deadline,
+}: {
+ points: ChartPoint[];
+ actions: ChartAction[];
+ failures: ChartFailure[];
+ target: number | null;
+ baseline: number | null;
+ deadline: number | null;
+}) {
+ const wrapRef = useRef<HTMLDivElement>(null);
+ const [hover, setHover] = useState<
+ | { kind: "point"; x: number; y: number; p: ChartPoint }
+ | { kind: "action"; x: number; y: number; a: ChartAction }
+ | { kind: "failure"; x: number; y: number; f: ChartFailure }
+ | null
+ >(null);
+
+ const model = useMemo(() => {
+ if (points.length < 2) return null;
+ const ts = points.map((p) => p.t);
+ const now = Date.now();
+ const tMin = Math.min(...ts, ...actions.map((a) => a.t), now - 1);
+ const tMax = Math.max(...ts, now);
+ const values = [
+ ...points.map((p) => p.v),
+ ...(target !== null ? [target] : []),
+ ...(baseline !== null ? [baseline] : []),
+ ];
+ let vMin = Math.min(...values);
+ let vMax = Math.max(...values);
+ if (vMin === vMax) {
+ vMin -= 1;
+ vMax += 1;
+ }
+ const vPad = (vMax - vMin) * 0.12;
+ vMin -= vPad;
+ vMax += vPad;
+ const x = (t: number) =>
+ PAD.left + ((t - tMin) / (tMax - tMin)) * (W - PAD.left - PAD.right);
+ const y = (v: number) =>
+ PAD.top + (1 - (v - vMin) / (vMax - vMin)) * (H - PAD.top - PAD.bottom);
+ // 3 recessive horizontal gridlines with value labels.
+ const gridVals = [vMin + vPad, (vMin + vMax) / 2, vMax - vPad];
+ // 3 date ticks.
+ const tickTs = [tMin, (tMin + tMax) / 2, tMax];
+ return { tMin, tMax, x, y, gridVals, tickTs };
+ }, [points, actions, target, baseline]);
+
+ if (!model || points.length < 2) {
+ return (
+ <div className="flex h-28 items-center justify-center text-[12px] text-[hsl(var(--notfair-ink-4))]">
+ The chart appears after a couple of readings — history backfills
+ during setup when the source supports it.
+ </div>
+ );
+ }
+
+ const { x, y, gridVals, tickTs, tMax } = model;
+ const path = points
+ .map((p, i) => `${i === 0 ? "M" : "L"}${x(p.t).toFixed(1)},${y(p.v).toFixed(1)}`)
+ .join(" ");
+ const last = points[points.length - 1]!;
+ const deadlineInside = deadline !== null && deadline <= tMax;
+
+ function onMove(e: React.MouseEvent<SVGSVGElement>) {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const mx = ((e.clientX - rect.left) / rect.width) * W;
+ // nearest data point by x
+ let best: ChartPoint | null = null;
+ let bestD = Infinity;
+ for (const p of points) {
+ const d = Math.abs(x(p.t) - mx);
+ if (d < bestD) {
+ bestD = d;
+ best = p;
+ }
+ }
+ if (best && bestD < 24) {
+ setHover({ kind: "point", x: x(best.t), y: y(best.v), p: best });
+ } else {
+ setHover(null);
+ }
+ }
+
+ return (
+ <div ref={wrapRef} className="relative">
+ <svg
+ viewBox={`0 0 ${W} ${H}`}
+ className="w-full"
+ role="img"
+ aria-label={`Metric over time. Latest ${fmtVal(last.v)}${target !== null ? `, target ${fmtVal(target)}` : ""}.`}
+ onMouseMove={onMove}
+ onMouseLeave={() => setHover(null)}
+ >
+ {/* recessive grid + value labels */}
+ {gridVals.map((gv, i) => (
+ <g key={i}>
+ <line
+ x1={PAD.left}
+ x2={W - PAD.right}
+ y1={y(gv)}
+ y2={y(gv)}
+ stroke="hsl(var(--border))"
+ strokeWidth="1"
+ />
+ <text
+ x={PAD.left - 4}
+ y={y(gv) + 3}
+ textAnchor="end"
+ className="fill-[hsl(var(--notfair-ink-4))] text-[8px] tabular-nums"
+ >
+ {fmtVal(gv)}
+ </text>
+ </g>
+ ))}
+ {/* date ticks */}
+ {tickTs.map((tt, i) => (
+ <text
+ key={i}
+ x={x(tt)}
+ y={H - 6}
+ textAnchor={i === 0 ? "start" : i === tickTs.length - 1 ? "end" : "middle"}
+ className="fill-[hsl(var(--notfair-ink-4))] text-[8px]"
+ >
+ {fmtDate(tt)}
+ </text>
+ ))}
+
+ {/* observation windows (shaded) */}
+ {actions
+ .filter((a) => a.reviewUntil !== null)
+ .map((a, i) => (
+ <rect
+ key={`w${i}`}
+ x={x(a.t)}
+ y={PAD.top}
+ width={Math.max(0, x(Math.min(a.reviewUntil!, tMax)) - x(a.t))}
+ height={H - PAD.top - PAD.bottom}
+ fill="hsl(var(--notfair-accent))"
+ opacity="0.07"
+ />
+ ))}
+
+ {/* reference lines: baseline dotted, target dashed + label */}
+ {baseline !== null && (
+ <line
+ x1={PAD.left}
+ x2={W - PAD.right}
+ y1={y(baseline)}
+ y2={y(baseline)}
+ stroke="hsl(var(--notfair-ink-4))"
+ strokeWidth="1"
+ strokeDasharray="1.5 3"
+ />
+ )}
+ {target !== null && (
+ <g>
+ <line
+ x1={PAD.left}
+ x2={W - PAD.right}
+ y1={y(target)}
+ y2={y(target)}
+ stroke="hsl(var(--notfair-ink-3))"
+ strokeWidth="1"
+ strokeDasharray="5 3"
+ />
+ <text
+ x={W - PAD.right}
+ y={y(target) - 3}
+ textAnchor="end"
+ className="fill-[hsl(var(--notfair-ink-3))] text-[8px]"
+ >
+ target {fmtVal(target)}
+ </text>
+ </g>
+ )}
+
+ {/* deadline flag */}
+ {deadlineInside && (
+ <g>
+ <line
+ x1={x(deadline!)}
+ x2={x(deadline!)}
+ y1={PAD.top}
+ y2={H - PAD.bottom}
+ stroke="hsl(var(--notfair-ink-4))"
+ strokeWidth="1"
+ strokeDasharray="2 3"
+ />
+ <text
+ x={x(deadline!) + 3}
+ y={PAD.top + 7}
+ className="fill-[hsl(var(--notfair-ink-4))] text-[8px]"
+ >
+ ⚑ deadline
+ </text>
+ </g>
+ )}
+
+ {/* the metric line */}
+ <path
+ d={path}
+ fill="none"
+ stroke="hsl(var(--notfair-accent))"
+ strokeWidth="2"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ {/* latest point, ringed */}
+ <circle cx={x(last.t)} cy={y(last.v)} r="4" fill="hsl(var(--background))" />
+ <circle cx={x(last.t)} cy={y(last.v)} r="2.5" fill="hsl(var(--notfair-accent))" />
+
+ {/* action markers: ▼ on the time axis of the event */}
+ {actions.map((a, i) => (
+ <g
+ key={`a${i}`}
+ onMouseEnter={() => setHover({ kind: "action", x: x(a.t), y: PAD.top + 8, a })}
+ onMouseLeave={() => setHover(null)}
+ className="cursor-help"
+ >
+ {/* generous invisible hit target */}
+ <rect x={x(a.t) - 8} y={PAD.top} width="16" height="16" fill="transparent" />
+ <path
+ d={`M${x(a.t) - 4.5},${PAD.top + 2} L${x(a.t) + 4.5},${PAD.top + 2} L${x(a.t)},${PAD.top + 9} Z`}
+ fill="hsl(var(--notfair-accent))"
+ stroke="hsl(var(--background))"
+ strokeWidth="1.5"
+ />
+ </g>
+ ))}
+
+ {/* failed checks: ✕ */}
+ {failures.map((f, i) => (
+ <g
+ key={`f${i}`}
+ onMouseEnter={() => setHover({ kind: "failure", x: x(f.t), y: H - PAD.bottom - 8, f })}
+ onMouseLeave={() => setHover(null)}
+ className="cursor-help"
+ >
+ <rect x={x(f.t) - 8} y={H - PAD.bottom - 16} width="16" height="16" fill="transparent" />
+ <text
+ x={x(f.t)}
+ y={H - PAD.bottom - 5}
+ textAnchor="middle"
+ className="fill-[hsl(0_72%_51%)] text-[10px] font-bold"
+ >
+ ✕
+ </text>
+ </g>
+ ))}
+
+ {/* crosshair for hovered data point */}
+ {hover?.kind === "point" && (
+ <g pointerEvents="none">
+ <line
+ x1={hover.x}
+ x2={hover.x}
+ y1={PAD.top}
+ y2={H - PAD.bottom}
+ stroke="hsl(var(--notfair-ink-4))"
+ strokeWidth="1"
+ strokeDasharray="2 2"
+ />
+ <circle cx={hover.x} cy={hover.y} r="4" fill="hsl(var(--background))" />
+ <circle cx={hover.x} cy={hover.y} r="2.5" fill="hsl(var(--notfair-accent))" />
+ </g>
+ )}
+ </svg>
+
+ {/* tooltip */}
+ {hover && (
+ <div
+ className="pointer-events-none absolute z-10 max-w-[240px] rounded-md bg-[hsl(var(--card))] px-2.5 py-1.5 text-[11px] leading-snug shadow-lg"
+ style={{
+ left: `${Math.min(92, Math.max(8, (hover.x / W) * 100))}%`,
+ top: `${(hover.y / H) * 100}%`,
+ transform: `translate(${hover.x > W * 0.6 ? "-100%" : "8px"}, 10px)`,
+ }}
+ >
+ {hover.kind === "point" && (
+ <>
+ <span className="font-medium tabular-nums">{fmtVal(hover.p.v)}</span>{" "}
+ <span className="text-[hsl(var(--notfair-ink-4))]">
+ {fmtDate(hover.p.t)}
+ {hover.p.source === "backfill" ? " · history" : ""}
+ </span>
+ </>
+ )}
+ {hover.kind === "action" && (
+ <>
+ <p className="m-0 font-medium">▼ {hover.a.label}</p>
+ <p className="m-0 text-[hsl(var(--notfair-ink-4))]">
+ expected: {hover.a.expected}
+ </p>
+ {hover.a.observed && (
+ <p className="m-0 text-[hsl(var(--notfair-ink-4))]">
+ observed: {hover.a.observed}
+ </p>
+ )}
+ {!hover.a.observed && hover.a.reviewUntil && (
+ <p className="m-0 text-[hsl(var(--notfair-ink-4))]">
+ measuring until {fmtDate(hover.a.reviewUntil)}
+ </p>
+ )}
+ </>
+ )}
+ {hover.kind === "failure" && (
+ <>
+ <p className="m-0 font-medium text-[hsl(0_72%_51%)]">✕ check failed</p>
+ <p className="m-0 text-[hsl(var(--notfair-ink-4))]">{hover.f.error}</p>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/notfair/src/components/goal-sparkline.tsx b/notfair/src/components/goal-sparkline.tsx
new file mode 100644
index 00000000..9cef76bb
--- /dev/null
+++ b/notfair/src/components/goal-sparkline.tsx
@@ -0,0 +1,74 @@
+/**
+ * Hand-rolled inline-SVG sparkline for the goal metric (no chart dep in
+ * this repo — see cron-calendar for the precedent). Server-renderable:
+ * pure props → markup, no hooks.
+ */
+export function GoalSparkline({
+ values,
+ target,
+ direction,
+ width = 560,
+ height = 96,
+}: {
+ values: number[];
+ target: number | null;
+ direction: "increase" | "decrease" | null;
+ width?: number;
+ height?: number;
+}) {
+ if (values.length < 2) {
+ return (
+ <div className="flex h-24 items-center justify-center text-[12.5px] text-[hsl(var(--notfair-ink-4))]">
+ Not enough readings yet — the sparkline appears after a couple of ticks.
+ </div>
+ );
+ }
+
+ const pad = 6;
+ const all = target !== null ? [...values, target] : values;
+ const min = Math.min(...all);
+ const max = Math.max(...all);
+ const span = max - min || 1;
+
+ const x = (i: number) => pad + (i / (values.length - 1)) * (width - pad * 2);
+ const y = (v: number) => pad + (1 - (v - min) / span) * (height - pad * 2);
+
+ const points = values.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");
+ const last = values[values.length - 1]!;
+ const first = values[0]!;
+ const improving =
+ direction === "decrease" ? last <= first : direction === "increase" ? last >= first : true;
+ const stroke = improving ? "hsl(var(--notfair-accent))" : "hsl(0 72% 51%)";
+
+ return (
+ <svg
+ viewBox={`0 0 ${width} ${height}`}
+ style={{ height: `${height <= 40 ? height : 96}px` }}
+ className="w-full"
+ role="img"
+ aria-label={`Metric trend: ${first} → ${last}${target !== null ? `, target ${target}` : ""}`}
+ preserveAspectRatio="none"
+ >
+ {target !== null && (
+ <line
+ x1={pad}
+ x2={width - pad}
+ y1={y(target)}
+ y2={y(target)}
+ stroke="hsl(var(--notfair-ink-4))"
+ strokeDasharray="4 4"
+ strokeWidth="1"
+ />
+ )}
+ <polyline
+ points={points}
+ fill="none"
+ stroke={stroke}
+ strokeWidth="2"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ <circle cx={x(values.length - 1)} cy={y(last)} r="3" fill={stroke} />
+ </svg>
+ );
+}
diff --git a/notfair/src/components/goal-start-button.tsx b/notfair/src/components/goal-start-button.tsx
new file mode 100644
index 00000000..45da95b2
--- /dev/null
+++ b/notfair/src/components/goal-start-button.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useTransition } from "react";
+import { toast } from "sonner";
+import { Play } from "lucide-react";
+import { startGoalLoopAction } from "@/server/actions/goals";
+import { Button } from "@/components/ui/button";
+
+/**
+ * The consent moment: the loop does not start until the user clicks this.
+ * The click also fires the first tick immediately, so the reward for
+ * consenting is watching the agent work right now.
+ */
+export function GoalStartButton({ goalId }: { goalId: string }) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+
+ function start() {
+ startTransition(async () => {
+ const r = await startGoalLoopAction(goalId);
+ if (!r.ok) {
+ toast.error(r.error ?? "Could not start the loop.");
+ return;
+ }
+ toast.success("Loop started — the first tick is running now.");
+ router.refresh();
+ });
+ }
+
+ return (
+ <Button onClick={start} disabled={pending} size="lg" className="gap-2">
+ <Play className="size-4" />
+ {pending ? "Starting…" : "START the loop"}
+ </Button>
+ );
+}
diff --git a/notfair/src/components/goal-suggestions.tsx b/notfair/src/components/goal-suggestions.tsx
new file mode 100644
index 00000000..113099e0
--- /dev/null
+++ b/notfair/src/components/goal-suggestions.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState, useTransition } from "react";
+import { Sparkles, X } from "lucide-react";
+import { toast } from "sonner";
+import {
+ acceptSuggestionAction,
+ dismissSuggestionAction,
+ refreshSuggestionsAction,
+} from "@/server/actions/suggestions";
+import type { GoalSuggestion } from "@/server/db/suggestions";
+import { projectHref } from "@/lib/project-href";
+import { Button } from "@/components/ui/button";
+
+/**
+ * Suggested-goal cards minted from a mechanical audit of a connected ads
+ * account. Accepting one runs the normal statement-first flow: a goal
+ * agent spins up, verifies the metric, and nothing spends until START.
+ */
+export function GoalSuggestionCard({
+ suggestion,
+ projectSlug,
+}: {
+ suggestion: GoalSuggestion;
+ projectSlug: string;
+}) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const [dismissed, setDismissed] = useState(false);
+
+ function accept() {
+ startTransition(async () => {
+ const r = await acceptSuggestionAction(suggestion.id);
+ if (!r.ok || !r.agent_slug) {
+ toast.error(r.error ?? "Could not create the goal.");
+ return;
+ }
+ toast.success("Goal created — your agent is on it.");
+ router.push(projectHref(projectSlug, `/goals/${r.agent_slug}`));
+ });
+ }
+
+ function dismiss() {
+ setDismissed(true);
+ startTransition(async () => {
+ await dismissSuggestionAction(suggestion.id);
+ router.refresh();
+ });
+ }
+
+ if (dismissed) return null;
+
+ return (
+ <div className="ns-card relative flex flex-col gap-2 p-4">
+ <button
+ type="button"
+ onClick={dismiss}
+ disabled={pending}
+ aria-label="Dismiss suggestion"
+ title="Dismiss — this idea won't come back"
+ className="absolute right-3 top-3 rounded p-1 text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink-2))]"
+ >
+ <X className="size-3.5" />
+ </button>
+ <div className="flex items-center gap-2 pr-8">
+ <Sparkles className="size-3.5 shrink-0 text-[hsl(var(--notfair-accent))]" aria-hidden />
+ <p className="m-0 text-[13.5px] font-medium">{suggestion.title}</p>
+ <span className="ns-tag">
+ {suggestion.mode === "maintain" ? "keep it there" : "reach a target"}
+ </span>
+ </div>
+ <p className="m-0 text-[12.5px] text-[hsl(var(--notfair-ink-3))]">
+ {suggestion.rationale}
+ </p>
+ <div className="mt-1 flex items-center justify-between gap-3">
+ <p className="m-0 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ An agent verifies the numbers first — nothing runs until you press START.
+ </p>
+ <Button size="sm" onClick={accept} disabled={pending}>
+ {pending ? "Creating…" : "Create this goal"}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/** Inline retry for a failed account analysis. */
+export function RetryAnalysisButton({ projectSlug }: { projectSlug: string }) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ return (
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={pending}
+ onClick={() =>
+ startTransition(async () => {
+ await refreshSuggestionsAction(projectSlug);
+ router.refresh();
+ })
+ }
+ >
+ {pending ? "Retrying…" : "Retry"}
+ </Button>
+ );
+}
diff --git a/notfair-cmo/src/components/harness-footer.tsx b/notfair/src/components/harness-footer.tsx
similarity index 99%
rename from notfair-cmo/src/components/harness-footer.tsx
rename to notfair/src/components/harness-footer.tsx
index 3e3547af..cdd91a51 100644
--- a/notfair-cmo/src/components/harness-footer.tsx
+++ b/notfair/src/components/harness-footer.tsx
@@ -17,7 +17,7 @@ const HARNESS_LABEL: Record<Props["adapter"], string> = {
// localStorage key — single bool. Default = expanded (we want users to
// see their usage at a glance on first install; collapsing is a
// per-user preference for once they've internalised the pattern).
-const COLLAPSE_KEY = "notfair-cmo:harness-footer:collapsed";
+const COLLAPSE_KEY = "NotFair:harness-footer:collapsed";
/**
* Sidebar footer summary of the active harness. The header row (dot,
diff --git a/notfair-cmo/src/components/live-transcript.tsx b/notfair/src/components/live-transcript.tsx
similarity index 91%
rename from notfair-cmo/src/components/live-transcript.tsx
rename to notfair/src/components/live-transcript.tsx
index f4c532cb..66e9be49 100644
--- a/notfair-cmo/src/components/live-transcript.tsx
+++ b/notfair/src/components/live-transcript.tsx
@@ -60,7 +60,7 @@ const POLL_INTERVAL_MS = 2_000;
* seenEventIdsRef catches in-channel dups (e.g. polling racing itself);
* this catches dups WHEN the same logical event arrives via different
* channels with different ids — e.g. the shadow transcript stream gave
- * us an assistant turn during the run, and OpenClaw's eventual JSONL
+ * us an assistant turn during the run, and the eventual transcript
* flush gives us the same turn with a fresh UUID at session-end.
*
* Signature keys are intentionally narrow: text body for messages
@@ -96,14 +96,12 @@ type Props = {
projectSlug: string;
agentSlug: string;
agentDisplayName: string;
- /** OpenClaw thread (the URL label half of `agent:<agent>:<label>`). */
+ /** Thread label (the URL half of the (agent, label) session key). */
threadId: string;
- /** Canonical sessionKey for /api/chat sends. */
- sessionKey: string;
/** Server-rendered initial slice of the transcript. */
initialEvents: TranscriptEvent[];
/** Byte offset *after* `initialEvents` — polls start from here. */
- initialByteOffset: number;
+ initialCursor: number;
/**
* When true, disables the composer (e.g., task is running and the user
* shouldn't send mid-run input). Default: composer always enabled.
@@ -117,29 +115,9 @@ type Props = {
blockedReason?: string;
/**
* When set, on each successful poll we call this so the parent can
- * react to JSONL growth (e.g., trigger router.refresh to refetch task
+ * react to transcript growth (e.g., trigger router.refresh to refetch
* statuses). Returning true tells us to stop background polling.
*/
- onPolled?: (info: { newEvents: number; fileSize: number }) => boolean | void;
- /**
- * Auto-kickoff: when true AND the transcript is empty AND we're not
- * already sending, fire a hidden first message so the agent runs
- * without the user typing. Used by the task workspace for tasks still
- * in `proposed` so the user sees gateway events stream in immediately
- * — JSONL polling alone can't (OpenClaw's codex-app-server mode flushes
- * the file once per turn, not incrementally).
- */
- autoKickoff?: boolean;
- /** Override for the auto-kickoff message body. */
- kickoffMessage?: string;
- /**
- * Task this turn belongs to. Forwarded to /api/chat so the server can
- * atomically claim the task (proposed → working) before forwarding to
- * the gateway. Without it, two tabs / a fast reload could race two
- * kickoffs against each other and double-fire the agent. The server
- * returns 409 when the claim fails; we treat that as a benign no-op.
- */
- taskId?: string;
/**
* MCP servers known to this project. The chat uses this to (a) detect
* when a tool call belongs to an MCP server (vs. a shell / built-in
@@ -164,23 +142,15 @@ type Props = {
modelOptions?: Array<{ value: string; label: string }>;
};
-/** Module-level guard so React StrictMode dev double-mounts don't double-fire. */
-const KICKOFF_FIRED = new Set<string>();
-
export function LiveTranscript({
projectSlug,
agentSlug,
agentDisplayName,
threadId,
- sessionKey,
initialEvents,
- initialByteOffset,
+ initialCursor,
composerDisabled = false,
blockedReason,
- onPolled,
- autoKickoff = false,
- kickoffMessage,
- taskId,
mcpCatalog,
leadingContent,
modelOptions = [],
@@ -191,7 +161,7 @@ export function LiveTranscript({
// Composer model override. "" = harness default (no flag). Persisted
// per project+agent in localStorage; loaded after mount so SSR and the
// first client render agree (no hydration mismatch).
- const modelStorageKey = `notfair-cmo:model:${projectSlug}:${agentSlug}`;
+ const modelStorageKey = `NotFair:model:${projectSlug}:${agentSlug}`;
const [model, setModel] = useState("");
useEffect(() => {
const stored = window.localStorage.getItem(modelStorageKey);
@@ -207,7 +177,7 @@ export function LiveTranscript({
if (value) window.localStorage.setItem(modelStorageKey, value);
else window.localStorage.removeItem(modelStorageKey);
}
- const [byteOffset, setByteOffset] = useState(initialByteOffset);
+ const [cursor, setCursor] = useState(initialCursor);
const [input, setInput] = useState("");
const [sendingChat, setSendingChat] = useState(false);
/**
@@ -218,7 +188,6 @@ export function LiveTranscript({
* Cleared once the new user_message lands and rendering catches up.
*/
const [turnStartedAt, setTurnStartedAt] = useState<number | null>(null);
- const [stopPolling, setStopPolling] = useState(false);
const [slashIndex, setSlashIndex] = useState(0);
const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -264,13 +233,13 @@ export function LiveTranscript({
// Optimistic state for the active /api/chat send. Rendered after committed
// events so the user sees their message + the streaming response before
- // polling materializes them from JSONL. Cleared once polling catches up.
+ // polling materializes them from the DB. Cleared once polling catches up.
const [pendingUserMsg, setPendingUserMsg] = useState<string | null>(null);
const [pendingAssistant, setPendingAssistant] = useState("");
const [pendingTools, setPendingTools] = useState<ToolEntry[]>([]);
const [pendingError, setPendingError] = useState<string | null>(null);
/**
- * Most recent OpenClaw lifecycle phase for the in-flight turn (run.start,
+ * Most recent harness lifecycle phase for the in-flight turn (run.start,
* run.warming, etc.). Surfaced in the "thinking…" indicator so a long
* wait before the first model token at least shows forward motion.
* Cleared when the turn ends.
@@ -283,9 +252,9 @@ export function LiveTranscript({
/**
* Ids of every transcript event we've already committed to state. Acts as
* a dedupe set for poll-result merging: two `pollOnce` calls can fire
- * with the same `byteOffset` closure before React commits the next
+ * with the same `cursor` closure before React commits the next
* offset (e.g. the post-stream catch-up poll racing the background
- * polling effect), so both fetches would return the same JSONL slice and
+ * polling effect), so both fetches would return the same event slice and
* we'd end up with duplicate React keys. Lives in a ref so the dedupe
* is synchronous — `setEvents(prev => …)` updater functions don't run
* until React's next commit, so they can't be used to derive the count
@@ -300,7 +269,7 @@ export function LiveTranscript({
* The id-based set above can't catch the case where the SAME logical
* message arrives twice via different paths with different ids — the
* server-side-kickoff path writes a shadow transcript (ids like
- * `shadow-<uuid>`), and OpenClaw later flushes its own copy of the
+ * `shadow-<uuid>`), and the poll later returns the DB copy of the
* session.jsonl at session-end with FRESH UUIDs. Without a content
* key, every assistant turn and tool call would render twice. Keyed by
* the semantic identity: text body for messages, tool_call_id for
@@ -330,17 +299,16 @@ export function LiveTranscript({
// Pass projectSlug explicitly: the API route would otherwise fall back
// to the active-project cookie, which can lag the URL on first paint
// after a project switch or direct deep-link.
- const url = `/api/agents/${agentSlug}/threads/${threadId}/transcript?offset=${byteOffset}&project=${encodeURIComponent(projectSlug)}`;
+ const url = `/api/agents/${agentSlug}/threads/${threadId}/transcript?offset=${cursor}&project=${encodeURIComponent(projectSlug)}`;
const res = await fetch(url, { cache: "no-store" });
if (!res.ok) return { newEvents: 0 };
const data = (await res.json()) as {
events: TranscriptEvent[];
- byteOffset: number;
- file_size: number;
+ cursor: number;
};
// Dedupe against both id (in-channel races) and content signature
- // (cross-channel dups, e.g. shadow stream vs. OpenClaw's eventual
- // JSONL flush). Rationale on the refs' declarations.
+ // (cross-channel dups, e.g. live stream vs. poll). Rationale on the
+ // refs' declarations.
const fresh = data.events.filter((e) => {
if (seenEventIdsRef.current.has(e.id)) return false;
const sig = eventSignature(e);
@@ -353,7 +321,7 @@ export function LiveTranscript({
}
if (fresh.length > 0) {
setEvents((prev) => [...prev, ...fresh]);
- // Clear pending state: JSONL now has the canonical events so the
+ // Clear pending state: the DB now has the canonical events so the
// optimistic placeholders are no longer needed.
setPendingUserMsg(null);
setPendingAssistant("");
@@ -361,17 +329,12 @@ export function LiveTranscript({
setPendingError(null);
setPendingLifecycle(null);
}
- if (data.byteOffset !== byteOffset) setByteOffset(data.byteOffset);
- const shouldStop = onPolled?.({
- newEvents: fresh.length,
- fileSize: data.file_size,
- });
- if (shouldStop) setStopPolling(true);
+ if (data.cursor !== cursor) setCursor(data.cursor);
return { newEvents: fresh.length };
} catch {
return { newEvents: 0 };
}
- }, [agentSlug, byteOffset, onPolled, projectSlug, threadId]);
+ }, [agentSlug, cursor, projectSlug, threadId]);
// Poll faster while the parent says the task is in flight — typical
// first-task experience is "land on workspace, watch the audit run."
@@ -381,7 +344,6 @@ export function LiveTranscript({
// Background polling: runs while mounted, paused during an active send so
// we don't double-render content we're already streaming via SSE.
useEffect(() => {
- if (stopPolling) return;
if (sendingChat) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
@@ -396,19 +358,19 @@ export function LiveTranscript({
cancelled = true;
if (timer) clearTimeout(timer);
};
- }, [pollIntervalMs, pollOnce, sendingChat, stopPolling]);
+ }, [pollIntervalMs, pollOnce, sendingChat]);
// ── Live re-attach: SSE bridge to the shadow-transcript stream. ─────
- // OpenClaw buffers session JSONL until session.ended, so JSONL polling
+ // The DB poll can lag a fast-streaming turn, so polling
// sees nothing mid-turn. Both server-side task kickoffs and /api/chat
- // tee their gateway events to a shadow JSONL — this bridge tails that
+ // tee their gateway events to a live stream — this bridge tails that
// file so a tab switching back to a thread mid-run picks up the stream
// instead of staring at a frozen transcript until the turn flushes.
//
// The bridge runs on every thread mount, not just tasks. The shadow
// file may not exist (idle thread) or exist-but-be-idle (run already
// finished); both cases are no-ops on the server. Same dedup set as
- // polling, so events that later land in OpenClaw's JSONL don't
+ // polling, so events that later land in the DB don't
// double-render.
//
// Skipped during an active /api/chat send — that path already streams
@@ -425,10 +387,6 @@ export function LiveTranscript({
});
return;
}
- if (stopPolling) {
- log("skip: stopPolling=true", { threadId });
- return;
- }
if (typeof EventSource === "undefined") {
log("skip: no EventSource in env (jsdom test)");
return;
@@ -478,7 +436,7 @@ export function LiveTranscript({
log("closing", { threadId });
es.close();
};
- }, [agentSlug, projectSlug, sendingChat, stopPolling, threadId]);
+ }, [agentSlug, projectSlug, sendingChat, threadId]);
// ── Send: optimistic user message + SSE-driven streaming reply. ─────
const send = useCallback(
@@ -497,18 +455,11 @@ export function LiveTranscript({
switch (action.kind) {
case "clear":
setEvents([]);
- setByteOffset(0);
+ setCursor(0);
toast.info(
"Local view cleared. Full transcript is still on disk; the next agent reply will repopulate.",
);
return;
- case "new-session": {
- const newId = crypto.randomUUID();
- router.push(
- projectHref(projectSlug, `/agents/${agentSlug}/chat/${newId}`),
- );
- return;
- }
case "stop":
abortRef.current?.abort();
return;
@@ -564,11 +515,6 @@ export function LiveTranscript({
const ctrl = new AbortController();
abortRef.current = ctrl;
- // Auto-kickoffs forward task_id so the server can atomically claim
- // the task (proposed → working). User-typed messages skip it — the
- // composer is already disabled while the task is in flight, so any
- // message the user can actually send is post-claim.
- const includeTaskId = opts.hidden && taskId;
try {
const res = await fetch("/api/chat", {
method: "POST",
@@ -577,20 +523,11 @@ export function LiveTranscript({
message: text,
agent: agentSlug,
project: projectSlug,
- sessionId: threadId,
- sessionKey,
- ...(includeTaskId ? { task_id: taskId } : {}),
+ thread: threadId,
...(model ? { model } : {}),
}),
signal: ctrl.signal,
});
- if (res.status === 409) {
- // Task was already claimed elsewhere (concurrent tab, reload
- // during a working turn). The agent is running on OpenClaw —
- // JSONL polling will surface the output once the turn flushes.
- // Bail silently; this is not a user-facing error.
- return;
- }
if (!res.ok || !res.body) {
throw new Error((await res.text()) || `HTTP ${res.status}`);
}
@@ -642,16 +579,16 @@ export function LiveTranscript({
});
}
}
- // Stream closed. Give OpenClaw a moment to flush the JSONL, then
+ // Stream closed. Give the writer a moment to flush, then
// pull the committed events. pollOnce clears pending state when it
// returns new events; if it returns nothing yet, the regular
// polling effect picks it up on the next tick.
await new Promise((r) => setTimeout(r, 400));
const { newEvents } = await pollOnce();
if (newEvents === 0) {
- // Re-try once more shortly. Avoids the case where OpenClaw is
+ // Re-try once more shortly. Avoids the case where the writer is
// slow to flush and the user briefly sees pending state with no
- // backing JSONL.
+ // backing rows.
setTimeout(() => {
void pollOnce();
}, 1200);
@@ -673,20 +610,9 @@ export function LiveTranscript({
// eslint-disable-next-line react-hooks/exhaustive-deps -- onPickModel is
// stable in behavior (writes localStorage + state); modelOptions is a
// fresh array from the server component each render.
- [agentSlug, input, model, modelOptions, pollOnce, projectSlug, router, sendingChat, sessionKey, taskId, threadId],
+ [agentSlug, input, model, modelOptions, pollOnce, projectSlug, router, sendingChat, threadId],
);
- // ── Auto-kickoff for FIRST_TURN-style flows. ────────────────────────
- useEffect(() => {
- if (!autoKickoff) return;
- if (KICKOFF_FIRED.has(threadId)) return;
- if (events.length > 0) return;
- if (sendingChat) return;
- KICKOFF_FIRED.add(threadId);
- void send(kickoffMessage ?? "(session start)", { hidden: true });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [autoKickoff, threadId]);
-
const rendered = useMemo(() => collapseEvents(events), [events]);
// Show the working indicator any time the agent is plausibly running —
// the user just sent (sendingChat) OR the parent says the task is in
@@ -695,10 +621,6 @@ export function LiveTranscript({
// so the user sees the same anchor whether the agent is mid-call,
// mid-stream, or waiting on the next model token.
//
- // For `blocked` tasks the composer is enabled (so the user can answer
- // a question or interject) but the agent is still dormant — render
- // the BlockedStatus pill so the chat doesn't read as live.
- //
// (Earlier we hid the indicator once anything pending was rendered.
// That made the chat read as "stuck" the moment streaming started —
// there was no longer any active animation to telegraph "I'm still
@@ -834,10 +756,10 @@ export function LiveTranscript({
disabled={composerDisabled}
placeholder={
composerDisabled
- ? `${agentDisplayName} is on a task — the transcript updates live`
+ ? "The agent is working — the transcript updates live"
: blockedReason
- ? `Reply to ${agentDisplayName} — typing won't resolve the block, but the agent will see your message`
- : `Message ${agentDisplayName}… (type / for commands)`
+ ? "Reply — the agent will see your message"
+ : "Message this goal's agent… (type / for commands)"
}
rows={1}
className="block max-h-52 w-full resize-none bg-transparent px-4 pt-3.5 text-sm placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
@@ -1028,13 +950,13 @@ type ToolEntry = {
};
type RenderedItem =
- | { kind: "user_message"; key: string; body: string }
+ | { kind: "user_message"; key: string; body: string; system?: boolean }
| { kind: "assistant_text"; key: string; body: string }
| { kind: "tool_group"; key: string; tools: ToolEntry[] }
| { kind: "system_unknown"; key: string; raw_type: string };
/**
- * The on-disk JSONL writes `toolCall` and `toolResult` as separate parts,
+ * The transcript stores `toolCall` and `toolResult` as separate parts,
* sometimes interleaved across multiple message rows in one turn. We:
* 1. Pair calls with their later results by tool_call_id so each tool
* renders as one logical entry (spinner → check).
@@ -1095,7 +1017,7 @@ function collapseEvents(events: TranscriptEvent[]): RenderedItem[] {
if (e.kind === "user_message") {
steps.push({
tag: "msg",
- item: { kind: "user_message", key: e.id, body: e.body },
+ item: { kind: "user_message", key: e.id, body: e.body, system: e.system },
});
continue;
}
@@ -1144,16 +1066,23 @@ function RenderItem({
mcpCatalog?: McpCatalogEntryLite[];
}) {
if (item.kind === "user_message") {
- const isKickoff =
- item.body.startsWith("(task assignment)") ||
- item.body.startsWith("(session start)") ||
- item.body.startsWith("TASK_BRIEF") ||
- item.body.startsWith("FIRST_TURN");
- // Kickoff messages duplicate the task header's Brief expandable
- // (and for FIRST_TURN flows, the on-screen onboarding context).
- // Drop them from the transcript so the chat starts with the
- // assistant's reply instead of the raw assignment payload.
- if (isKickoff) return null;
+ // Platform-generated briefs (goal intake kickoff, tick briefs) are
+ // not something the user typed — render a compact system line so the
+ // chat reads as "the agent got to work", not "who wrote this?".
+ if (item.system) {
+ const label = item.body.startsWith("[TICK]")
+ ? "Heartbeat tick — brief delivered to the agent"
+ : item.body.startsWith("[INTAKE]")
+ ? "Goal created — your ambition was handed to the agent"
+ : "Scheduled brief delivered to the agent";
+ return (
+ <div className="flex justify-center">
+ <span className="rounded-full bg-[hsl(var(--notfair-surface-2))] px-3 py-1 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ {label}
+ </span>
+ </div>
+ );
+ }
return <UserBubble body={item.body} />;
}
if (item.kind === "assistant_text") {
@@ -1176,7 +1105,7 @@ function UserBubble({ body }: { body: string }) {
}
function AssistantText({ body }: { body: string }) {
- // Orchestration side effects now go through MCP tool calls, not
+ // Goal side effects now go through MCP tool calls, not
// pseudo-XML blocks. We render the assistant's prose as-is.
if (body.trim() === "") return null;
return (
@@ -1415,7 +1344,7 @@ function BlockedStatus({ reason }: { reason: string }) {
*
* Wraps the presentational WorkingIndicator with the project-specific
* logic: derive headline/subtitle/mood/phases from a mix of SSE-leading
- * pending state and JSONL-trailing committed events, then drive the
+ * pending state and DB-trailing committed events, then drive the
* 1Hz elapsed counter. Kept inside live-transcript so the derivation
* has the full union of TranscriptEvent + ToolEntry types in scope
* without exporting either across the module boundary.
@@ -1492,7 +1421,7 @@ type WorkingView = {
/**
* Build the visible state for the working indicator from the current
- * SSE pending state + committed JSONL events.
+ * SSE pending state + committed transcript events.
*
* Precedence (most-specific first):
* 1. An SSE-pending tool start that hasn't reported a result → that's
@@ -1509,7 +1438,7 @@ type WorkingView = {
* an honest "quiet for Xm" subtitle.
*
* Phases are derived from BOTH sources so the trajectory chips include
- * recent SSE tools the JSONL hasn't seen yet, then dedupe by tool name.
+ * recent SSE tools the DB hasn't seen yet, then dedupe by tool name.
*/
function deriveWorkingView(input: {
agentDisplayName: string;
@@ -1591,7 +1520,7 @@ function deriveWorkingView(input: {
}
// Between-tools window: SSE has seen at least one tool finish this
// turn but the model hasn't started the next thing yet (no in-flight
- // pending tool, no streaming text, no fresh JSONL event because Codex
+ // pending tool, no streaming text, no fresh transcript event because Codex
// buffers the file until end-of-turn). Without this branch we'd fall
// through to "Starting", which is wrong — the agent IS thinking, just
// about its next move. Surface the last tool so the user has context.
@@ -1782,7 +1711,7 @@ function buildPhases(
}
/**
- * Translate an OpenClaw `agent` stream lifecycle phase into a short
+ * Translate a harness stream lifecycle phase into a short
* user-facing label. We don't try to enumerate every possible phase —
* unknown values fall through to a generic "starting up…" so a future
* gateway protocol bump doesn't render a blank status. Used by the
@@ -1812,14 +1741,17 @@ function humanLifecyclePhase(phase: string): string {
*/
function formatToolName(name: string): string {
if (!name) return name;
+ // Codex names can nest both separators (`notfair_<slug>__notfair_goals.propose_target`)
+ // — strip namespaces for BOTH, keeping only the action.
+ let out = name;
for (const sep of ["__", "."]) {
- const idx = name.lastIndexOf(sep);
+ const idx = out.lastIndexOf(sep);
if (idx >= 0) {
- const tail = name.slice(idx + sep.length);
- if (tail) return tail;
+ const tail = out.slice(idx + sep.length);
+ if (tail) out = tail;
}
}
- return name;
+ return out;
}
/**
@@ -1990,7 +1922,7 @@ function humanizeShellCommand(rawCmd: string): ToolIntent {
return { verb: "Copied file" };
case "sed":
case "awk":
- return { verb: "Transformed text" };
+ return { verb: "Edited text", target: extractPathArg(tokens) };
case "which":
case "type":
case "whereis":
@@ -2143,7 +2075,7 @@ function TranscriptEmptyState({
}) {
return (
<div className="py-12 text-center text-sm text-muted-foreground">
- No messages yet. Say hi to {agentDisplayName} below.
+ No messages yet. Tell this goal&rsquo;s agent what you need below.
</div>
);
}
diff --git a/notfair-cmo/src/components/markdown.tsx b/notfair/src/components/markdown.tsx
similarity index 95%
rename from notfair-cmo/src/components/markdown.tsx
rename to notfair/src/components/markdown.tsx
index c28e8aae..fb7171ff 100644
--- a/notfair-cmo/src/components/markdown.tsx
+++ b/notfair/src/components/markdown.tsx
@@ -72,12 +72,12 @@ const COMPONENTS: Components = {
),
th: ({ className, ...props }) => (
<th
- className={cn("border-b px-2 py-1.5 text-left font-medium", className)}
+ className={cn("bg-[hsl(var(--notfair-surface-2))] px-2 py-1.5 text-left font-medium first:rounded-l-md last:rounded-r-md", className)}
{...props}
/>
),
td: ({ className, ...props }) => (
- <td className={cn("border-b border-border/50 px-2 py-1.5 align-top", className)} {...props} />
+ <td className={cn("px-2 py-1.5 align-top", className)} {...props} />
),
code: ({ className, children, ...props }) => {
// react-markdown emits both inline and fenced `code`. Inline gets no
diff --git a/notfair-cmo/src/components/mcp-card.tsx b/notfair/src/components/mcp-card.tsx
similarity index 100%
rename from notfair-cmo/src/components/mcp-card.tsx
rename to notfair/src/components/mcp-card.tsx
diff --git a/notfair-cmo/src/components/mcp-flash-banner.tsx b/notfair/src/components/mcp-flash-banner.tsx
similarity index 58%
rename from notfair-cmo/src/components/mcp-flash-banner.tsx
rename to notfair/src/components/mcp-flash-banner.tsx
index f7fd440d..412f696e 100644
--- a/notfair-cmo/src/components/mcp-flash-banner.tsx
+++ b/notfair/src/components/mcp-flash-banner.tsx
@@ -12,9 +12,15 @@ import { toast } from "sonner";
export function McpFlashBanner({
connected,
error,
+ analyzing,
+ goalsHref,
}: {
connected?: string;
error?: string;
+ /** Set when the connect kicked off an account analysis for goal ideas. */
+ analyzing?: boolean;
+ /** Where the suggestion cards land (the project's goals index). */
+ goalsHref?: string;
}) {
const router = useRouter();
const fired = useRef(false);
@@ -24,13 +30,21 @@ export function McpFlashBanner({
if (!connected && !error) return;
fired.current = true;
if (error) toast.error(error);
- else if (connected) toast.success(`Connected: ${connected}`);
+ else if (connected && analyzing) {
+ toast.success(
+ `Connected: ${connected} — analyzing the account for goal ideas…`,
+ goalsHref
+ ? { action: { label: "See goals", onClick: () => router.push(goalsHref) } }
+ : undefined,
+ );
+ } else if (connected) toast.success(`Connected: ${connected}`);
// Clean the URL so a refresh / back-button doesn't re-fire.
const url = new URL(window.location.href);
url.searchParams.delete("mcp_connected");
url.searchParams.delete("mcp_error");
+ url.searchParams.delete("mcp_analyzing");
router.replace(url.pathname + (url.search ? url.search : ""));
- }, [connected, error, router]);
+ }, [connected, error, analyzing, goalsHref, router]);
return null;
}
diff --git a/notfair-cmo/src/components/mcp-icon.tsx b/notfair/src/components/mcp-icon.tsx
similarity index 100%
rename from notfair-cmo/src/components/mcp-icon.tsx
rename to notfair/src/components/mcp-icon.tsx
diff --git a/notfair-cmo/src/components/mcp-tools-dialog.tsx b/notfair/src/components/mcp-tools-dialog.tsx
similarity index 98%
rename from notfair-cmo/src/components/mcp-tools-dialog.tsx
rename to notfair/src/components/mcp-tools-dialog.tsx
index 2332d4ab..05455f0a 100644
--- a/notfair-cmo/src/components/mcp-tools-dialog.tsx
+++ b/notfair/src/components/mcp-tools-dialog.tsx
@@ -107,7 +107,7 @@ export function McpToolsDialog({
showCloseButton
className="flex max-h-[85vh] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl"
>
- <DialogHeader className="border-b px-6 pt-5 pb-4">
+ <DialogHeader className="px-6 pt-5 pb-4">
<DialogTitle className="flex items-baseline gap-2">
<span>{mcpName}</span>
<span className="text-xs font-normal text-muted-foreground">
@@ -122,7 +122,7 @@ export function McpToolsDialog({
</DialogHeader>
{/* Sticky search row — sits between header and scroll area. */}
- <div className="border-b bg-card px-6 py-2.5">
+ <div className="bg-[hsl(var(--notfair-surface-2)/0.5)] px-6 py-2.5">
<div className="relative">
<Search
aria-hidden
diff --git a/notfair/src/components/new-goal-form.tsx b/notfair/src/components/new-goal-form.tsx
new file mode 100644
index 00000000..2f6965e6
--- /dev/null
+++ b/notfair/src/components/new-goal-form.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState, useTransition } from "react";
+import { toast } from "sonner";
+import { createGoalAgentAction } from "@/server/actions/goals";
+import { projectHref } from "@/lib/project-href";
+import { Button } from "@/components/ui/button";
+
+/**
+ * Statement-first goal creation: the user states the ambition (the only
+ * thing on their mind), the platform auto-names an agent for it, and on
+ * success we drop straight into the agent's chat — where it is already
+ * working out how to measure the goal.
+ */
+export function NewGoalForm({ projectSlug }: { projectSlug: string }) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const [statement, setStatement] = useState("");
+
+ function submit() {
+ startTransition(async () => {
+ const r = await createGoalAgentAction({
+ project_slug: projectSlug,
+ statement,
+ });
+ if (!r.ok || !r.agent_slug) {
+ toast.error(r.error ?? "Could not create the goal.");
+ return;
+ }
+ toast.success("Your agent is on it — watch it work.");
+ router.push(projectHref(projectSlug, `/goals/${r.agent_slug}`));
+ });
+ }
+
+ return (
+ <div className="ns-card flex flex-col gap-3 p-4">
+ <label htmlFor="new-goal-statement" className="text-[13px] font-medium">
+ What do you want to achieve?
+ </label>
+ <textarea
+ id="new-goal-statement"
+ className="min-h-20 w-full resize-y rounded-lg bg-[hsl(var(--notfair-surface-2))] px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent))]"
+ placeholder={'e.g. "Cut our Google Ads CAC to $30" or "Get to 100 signups a month from paid"'}
+ value={statement}
+ onChange={(e) => setStatement(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey && statement.trim() && !pending) {
+ e.preventDefault();
+ submit();
+ }
+ }}
+ disabled={pending}
+ />
+ <div className="flex items-center justify-between gap-3">
+ <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
+ An agent takes it from here: it turns this into a measured metric,
+ shows you the baseline, and nothing runs until you press START.
+ </p>
+ <Button onClick={submit} disabled={pending || !statement.trim()}>
+ {pending ? "Creating…" : "Create goal"}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/notfair-cmo/src/components/onboarding-flow.tsx b/notfair/src/components/onboarding-flow.tsx
similarity index 85%
rename from notfair-cmo/src/components/onboarding-flow.tsx
rename to notfair/src/components/onboarding-flow.tsx
index b26ef068..19de337b 100644
--- a/notfair-cmo/src/components/onboarding-flow.tsx
+++ b/notfair/src/components/onboarding-flow.tsx
@@ -7,6 +7,7 @@ import { AlertCircle, ChevronRight, FolderOpen, Loader2, Plug } from "lucide-rea
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
+import { McpFlashBanner } from "@/components/mcp-flash-banner";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -17,8 +18,6 @@ import { createProjectForOnboardingAction } from "@/server/actions/projects";
import {
listGoogleAdsAccounts,
setOnboardingAccountAction,
- getOnboardingTaskForSkipAction,
- getProvisioningProgressAction,
getConnectStepStateAction,
listMetaAdsAccounts,
setOnboardingMetaAdsAccountAction,
@@ -37,8 +36,7 @@ type Step =
| "connect"
| "account"
| "meta-account"
- | "gsc-property"
- | "setup";
+ | "gsc-property";
export function OnboardingFlow() {
return (
@@ -53,20 +51,21 @@ function OnboardingFlowInner() {
const params = useSearchParams();
const stepParam = params.get("step");
const slug = params.get("slug") ?? null;
+ const mcpConnected = params.get("mcp_connected") ?? undefined;
+ const mcpError = params.get("mcp_error") ?? undefined;
+ const mcpAnalyzing = params.get("mcp_analyzing") === "1";
const step: Step =
stepParam === "connect" ||
stepParam === "account" ||
stepParam === "meta-account" ||
- stepParam === "gsc-property" ||
- stepParam === "setup"
+ stepParam === "gsc-property"
? stepParam
: "name";
// Step → progress-pip state mapping. The pickers (account, meta-account,
// gsc-property) all roll up under "Connect" because they're sub-flows
// launched from the connect step and return to it.
- const phase: "name" | "connect" | "setup" =
- step === "name" ? "name" : step === "setup" ? "setup" : "connect";
+ const phase: "name" | "connect" = step === "name" ? "name" : "connect";
return (
<div className="ns-page">
@@ -84,7 +83,7 @@ function OnboardingFlowInner() {
<img src="/notfair-mark.svg" alt="Notfair" className="dark:hidden" />
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/notfair-mark-dark.svg" alt="Notfair" className="hidden dark:block" />
- <span className="ns-topbar-label">Notfair CMO</span>
+ <span className="ns-topbar-label">NotFair</span>
<div className="ml-auto">
<div className="ns-progress">
<Pip n={1} label="Workspace" state={phase === "name" ? "active" : "done"} />
@@ -92,19 +91,19 @@ function OnboardingFlowInner() {
<Pip
n={2}
label="Connect"
- state={phase === "name" ? "pending" : phase === "connect" ? "active" : "done"}
- />
- <span className="ns-pip-line" />
- <Pip
- n={3}
- label="Setup"
- state={phase === "setup" ? "active" : "pending"}
+ state={phase === "name" ? "pending" : "active"}
/>
</div>
</div>
</div>
<main id="onboarding-main">
+ <McpFlashBanner
+ connected={mcpConnected}
+ error={mcpError}
+ analyzing={mcpAnalyzing}
+ goalsHref={slug ? `/${slug}` : undefined}
+ />
{step === "name" && (
<NameStep
onCreated={(s) =>
@@ -116,12 +115,10 @@ function OnboardingFlowInner() {
{step === "account" && slug && <AccountStep slug={slug} />}
{step === "meta-account" && slug && <MetaAccountStep slug={slug} />}
{step === "gsc-property" && slug && <GscPropertyStep slug={slug} />}
- {step === "setup" && slug && <SetupStep slug={slug} />}
{(step === "connect" ||
step === "account" ||
step === "meta-account" ||
- step === "gsc-property" ||
- step === "setup") &&
+ step === "gsc-property") &&
!slug && <MissingSlug />}
</main>
</div>
@@ -215,6 +212,8 @@ function CodebasePathPicker({ disabled }: { disabled: boolean }) {
// ── Step 1: Name ───────────────────────────────────────────────────
function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
+ const [displayName, setDisplayName] = useState("");
+ const [websiteUrl, setWebsiteUrl] = useState("");
const [state, formAction, isPending] = useActionState<
| { ok: true; data: { slug: string; display_name: string } }
| { ok: false; error: string }
@@ -233,7 +232,7 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
<header>
<h1 className="ns-hero-title">Let&rsquo;s set up your workspace.</h1>
<p className="ns-hero-sub">
- Tell me what this workspace is so I can hit the ground running.
+ Name it, point at your site, and pick which local AI runtime does the work.
</p>
</header>
@@ -247,9 +246,11 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
name="display_name"
required
autoFocus
- placeholder="Notfair"
+ placeholder="Acme Inc"
maxLength={80}
disabled={isPending}
+ value={displayName}
+ onChange={(e) => setDisplayName(e.target.value)}
className="h-9 rounded-lg text-[14px]"
/>
</div>
@@ -265,13 +266,15 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
id="website_url"
name="website_url"
type="url"
- placeholder="https://notfair.co"
+ placeholder="https://acme.com"
maxLength={500}
disabled={isPending}
+ value={websiteUrl}
+ onChange={(e) => setWebsiteUrl(e.target.value)}
className="h-9 rounded-lg text-[14px]"
/>
<p className="text-[11.5px] text-muted-foreground leading-tight">
- The CMO will skim a few pages to learn what you sell.
+ Your agents skim a few pages to learn what you sell.
</p>
</div>
@@ -284,7 +287,7 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
</Label>
<CodebasePathPicker disabled={isPending} />
<p className="text-[11.5px] text-muted-foreground leading-tight">
- Folder the CMO can read locally — README, package.json, top-level
+ Folder your agents can read locally — README, package.json, top-level
files. Skim only.
</p>
</div>
@@ -360,10 +363,10 @@ function HarnessPicker({ disabled }: { disabled: boolean }) {
disabled={disabled}
onClick={() => setValue(opt.id)}
className={cn(
- "flex flex-col items-start gap-1 rounded-md border px-3 py-2 text-left transition-colors",
+ "flex flex-col items-start gap-1 rounded-lg px-3 py-2 text-left transition-colors",
value === opt.id
- ? "border-foreground bg-background"
- : "border-border bg-background/40 hover:bg-background/80",
+ ? "bg-[hsl(var(--notfair-surface-2))] shadow-[var(--notfair-shadow-sm)]"
+ : "bg-background/40 hover:bg-[hsl(var(--notfair-surface-2)/0.6)]",
disabled && "opacity-60",
)}
aria-pressed={value === opt.id}
@@ -388,10 +391,9 @@ function HarnessPicker({ disabled }: { disabled: boolean }) {
/**
* Spec for one of the recommended-MCP tiles in the connect step. The core
- * MCPs (Google Ads, Meta Ads, Google Search Console, X Ads) each get their
- * own first-class tile because connecting them triggers the provisioning of
- * a matching specialist agent. MCPs that power no specialist (Google
- * Analytics) live in the "More tools" browse dialog instead.
+ * ad/search platforms get first-class tiles because they are what goal
+ * agents measure and act on; everything else lives in the "More tools"
+ * browse dialog.
*/
type RecommendedTile = {
mcp_key: string;
@@ -419,7 +421,7 @@ const RECOMMENDED_TILES: RecommendedTile[] = [
mcp_key: "notfair-googleads",
mcp_display_name: "Google Ads MCP",
description:
- "Gives the Google Ads agent the ability to audit campaigns, find wasted spend, and propose bid changes.",
+ "Google Ads campaigns, spend, conversions — the richest ground for CAC and wasted-spend goals.",
resource_url: "https://notfair.co/api/mcp/google_ads",
account_step: "account",
account_action_label: "Select Google Ads account",
@@ -428,7 +430,7 @@ const RECOMMENDED_TILES: RecommendedTile[] = [
mcp_key: "notfair-metaads",
mcp_display_name: "Meta Ads MCP",
description:
- "Gives the Meta Ads agent the ability to audit ad sets, diagnose creative fatigue, and surface ROAS winners.",
+ "Meta (Facebook + Instagram) ad sets, ROAS, creative performance — for paid-social goals.",
resource_url: "https://notfair.co/api/mcp/meta_ads",
account_step: "meta-account",
account_action_label: "Select Meta ad account",
@@ -437,20 +439,18 @@ const RECOMMENDED_TILES: RecommendedTile[] = [
mcp_key: "notfair-googlesearchconsole",
mcp_display_name: "Google Search Console MCP",
// SEO agent owns Search Console — there's no dedicated GSC agent.
- // See SPECIALIST_TEMPLATE_BY_MCP_KEY in agent-templates.ts.
description:
- "Gives the SEO agent the ability to pull organic performance, surface query and page movers, and diagnose indexing.",
+ "Organic search performance — queries, pages, indexing. Lets a goal agent measure and grow organic traffic.",
resource_url: "https://notfair.co/api/mcp/google_search_console",
account_step: "gsc-property",
account_action_label: "Select GSC property",
},
- // Google Analytics deliberately lives under "More tools" — it powers
- // no specialist agent, so it doesn't earn a first-class tile here.
+ // Google Analytics deliberately lives under "More tools".
{
mcp_key: "notfair-xads",
mcp_display_name: "X Ads MCP",
description:
- "Gives the X Ads agent the ability to audit campaigns and line items, and track spend and engagement.",
+ "X (Twitter) Ads campaigns, line items, spend and engagement — measurable ground for a goal agent.",
resource_url: "https://notfair.co/api/mcp/x_ads",
},
];
@@ -517,20 +517,13 @@ function ConnectStep({ slug }: { slug: string }) {
async function onDone() {
setAdvancing(true);
- // The setup step waits for ensureProjectAgents (CMO + any specialists
- // provisioned by the connect-time hooks) and only then routes the user
- // into the CMO task workspace. Going through it instead of the direct
- // task URL means we don't race agent registration with the gateway
- // snapshot on a fresh project.
- router.replace(
- `/onboarding?step=setup&slug=${encodeURIComponent(slug)}&from=connect`,
- );
+ // Straight to the workspace: the user mints their first goal agent
+ // there and defines the goal in its chat. Nothing to provision here.
+ router.replace(projectHref(slug, ""));
}
function onSkip() {
- router.replace(
- `/onboarding?step=setup&slug=${encodeURIComponent(slug)}&from=skip`,
- );
+ router.replace(projectHref(slug, ""));
}
if (view.phase === "loading") {
@@ -576,10 +569,10 @@ function ConnectStep({ slug }: { slug: string }) {
return (
<>
<header>
- <h1 className="ns-hero-title">Connect MCPs to your agents.</h1>
+ <h1 className="ns-hero-title">Connect your data sources.</h1>
<p className="ns-hero-sub">
- Each MCP gives your <b>specialist agent</b> the data and APIs to
- do real work.
+ Every goal agent shares these — they are what your agents
+ measure and act on.
</p>
</header>
@@ -808,158 +801,6 @@ function ExtraConnectorTile({
}
-// ── Step 2.5: Setup (post-skip-or-connect provisioning watcher) ────
-
-type ProgressStep = {
- key: string;
- label: string;
- status: string;
- error?: string;
-};
-
-function statusGlyph(status: string): string {
- if (status === "done") return "✓";
- if (status === "failed") return "✗";
- if (status === "in_progress") return "•";
- return "·";
-}
-
-function SetupStep({ slug }: { slug: string }) {
- const router = useRouter();
- const [steps, setSteps] = useState<ProgressStep[]>([]);
- const [error, setError] = useState<string | null>(null);
- const redirectedRef = useRef(false);
-
- useEffect(() => {
- let cancelled = false;
- let pollTimer: ReturnType<typeof setTimeout> | null = null;
-
- async function poll(): Promise<void> {
- if (cancelled) return;
- try {
- const r = await getProvisioningProgressAction(slug);
- if (cancelled) return;
- if (!r.ok) {
- setError(r.error);
- return;
- }
- setSteps(r.steps);
- if (r.overall === "failed") {
- const failed = r.steps.find((s) => s.status === "failed");
- setError(failed?.error ?? "Provisioning failed.");
- return;
- }
- if (r.overall === "done") {
- // Resolve the CMO + first task slugs and forward to the live
- // task workspace. Guarded so React StrictMode's double-mount
- // doesn't fire two redirects.
- if (redirectedRef.current) return;
- redirectedRef.current = true;
- const dest = await getOnboardingTaskForSkipAction(slug);
- if (cancelled) return;
- if (!dest.ok) {
- setError(dest.error);
- redirectedRef.current = false;
- return;
- }
- router.replace(
- projectHref(
- slug,
- `/agents/${dest.cmo_agent_slug}/tasks?task=${encodeURIComponent(dest.task_display_id)}`,
- ),
- );
- return;
- }
- // Still running — poll again. 500ms keeps the rows feeling
- // alive without hammering the server.
- pollTimer = setTimeout(poll, 500);
- } catch (err) {
- if (cancelled) return;
- setError(err instanceof Error ? err.message : String(err));
- }
- }
-
- void poll();
- return () => {
- cancelled = true;
- if (pollTimer) clearTimeout(pollTimer);
- };
- }, [slug, router]);
-
- return (
- <>
- <header>
- <h1 className="ns-hero-title">Setting up your agents.</h1>
- <p className="ns-hero-sub">
- One moment &mdash; bringing your team online.
- </p>
- </header>
-
- <Card>
- <CardContent className="pt-6">
- <ul className="space-y-2" role="status" aria-live="polite">
- {steps.length === 0 && !error && (
- <li className="flex items-center gap-2 text-sm text-muted-foreground">
- <Loader2 className="size-4 animate-spin" />
- Starting…
- </li>
- )}
- {steps.map((s) => (
- <li
- key={s.key}
- className="flex items-center gap-2 text-sm"
- data-status={s.status}
- >
- <span
- aria-hidden
- className={
- s.status === "done"
- ? "inline-flex size-4 items-center justify-center font-mono text-[hsl(var(--notfair-accent))]"
- : s.status === "failed"
- ? "inline-flex size-4 items-center justify-center font-mono text-destructive"
- : s.status === "in_progress"
- ? "inline-flex size-4 items-center justify-center"
- : "inline-flex size-4 items-center justify-center font-mono text-muted-foreground"
- }
- >
- {s.status === "in_progress" ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- statusGlyph(s.status)
- )}
- </span>
- <span
- className={
- s.status === "done"
- ? "text-foreground"
- : s.status === "failed"
- ? "text-destructive"
- : s.status === "in_progress"
- ? "text-foreground"
- : "text-muted-foreground"
- }
- >
- {s.label}
- </span>
- {s.error && (
- <span className="ml-2 text-xs text-destructive">
- {s.error}
- </span>
- )}
- </li>
- ))}
- </ul>
- {error && (
- <p className="mt-4 text-sm text-destructive" role="alert">
- {error}
- </p>
- )}
- </CardContent>
- </Card>
- </>
- );
-}
-
// ── Step 3: Pick Google Ads account (auto-skipped if only 1) ───────
type AccountListState =
@@ -1014,7 +855,7 @@ function AccountStep({ slug }: { slug: string }) {
return;
}
// Back to the connect step so the user can wire up the rest of
- // their tools. The CMO audit task is minted by
+ // their tools.
// setOnboardingAccountAction and stays blocked behind the
// project-onboarding task until the user clicks "Done — next step".
router.replace(
@@ -1090,7 +931,7 @@ function AccountStep({ slug }: { slug: string }) {
</div>
<p className="text-xs text-muted-foreground">
The connected user has no Google Ads customer accounts. Connect a
- different account or skip and chat with your CMO.
+ different account or skip for now.
</p>
<div className="flex gap-2">
<Button asChild>
diff --git a/notfair-cmo/src/components/project-cookie-sync.tsx b/notfair/src/components/project-cookie-sync.tsx
similarity index 100%
rename from notfair-cmo/src/components/project-cookie-sync.tsx
rename to notfair/src/components/project-cookie-sync.tsx
diff --git a/notfair-cmo/src/components/project-rename-card.tsx b/notfair/src/components/project-rename-card.tsx
similarity index 92%
rename from notfair-cmo/src/components/project-rename-card.tsx
rename to notfair/src/components/project-rename-card.tsx
index b11e10b1..352f4dba 100644
--- a/notfair-cmo/src/components/project-rename-card.tsx
+++ b/notfair/src/components/project-rename-card.tsx
@@ -70,8 +70,8 @@ export function ProjectRenameCard({
Rename this workspace
</h3>
<p className="mt-1 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">
- Changing the slug renames every agent, rewrites cron names, moves
- workspace dirs, and relocates session JSONL files.
+ Changing the slug renames every agent, moves
+ workspace dirs, and relocates sessions.
</p>
</div>
@@ -89,7 +89,7 @@ export function ProjectRenameCard({
onChange={(e) => setName(e.target.value)}
disabled={pending}
className={cn(
- "h-9 w-full rounded-lg border bg-background px-3 text-[13.5px] tracking-tight shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent-border))]",
+ "h-9 w-full rounded-lg bg-[hsl(var(--notfair-surface-2))] px-3 text-[13.5px] tracking-tight focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent-border))]",
slugError && "border-destructive focus-visible:ring-destructive",
pending && "opacity-50",
)}
diff --git a/notfair-cmo/src/components/project-switcher.tsx b/notfair/src/components/project-switcher.tsx
similarity index 100%
rename from notfair-cmo/src/components/project-switcher.tsx
rename to notfair/src/components/project-switcher.tsx
diff --git a/notfair-cmo/src/components/reprovision-button.tsx b/notfair/src/components/reprovision-button.tsx
similarity index 100%
rename from notfair-cmo/src/components/reprovision-button.tsx
rename to notfair/src/components/reprovision-button.tsx
diff --git a/notfair-cmo/src/components/running-dot.tsx b/notfair/src/components/running-dot.tsx
similarity index 100%
rename from notfair-cmo/src/components/running-dot.tsx
rename to notfair/src/components/running-dot.tsx
diff --git a/notfair/src/components/shared-context-editor.tsx b/notfair/src/components/shared-context-editor.tsx
new file mode 100644
index 00000000..9cddffce
--- /dev/null
+++ b/notfair/src/components/shared-context-editor.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState, useTransition } from "react";
+import { Pencil } from "lucide-react";
+import { toast } from "sonner";
+import { saveSharedContextAction } from "@/server/actions/shared-context";
+import { Button } from "@/components/ui/button";
+import { Markdown } from "@/components/markdown";
+
+/**
+ * Shared workspace context (PROJECT.md): rendered markdown at rest, raw
+ * markdown while editing. Saving pushes the new brief into every goal
+ * agent's identity immediately — same path the agents' own
+ * `set_shared_context` tool uses.
+ */
+export function SharedContextEditor({
+ projectSlug,
+ initialContent,
+}: {
+ projectSlug: string;
+ initialContent: string;
+}) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const [saved, setSaved] = useState(initialContent);
+ const [content, setContent] = useState(initialContent);
+ // Nothing written yet → straight into edit mode.
+ const [editing, setEditing] = useState(initialContent.trim() === "");
+ const dirty = content.trim() !== saved.trim();
+
+ function save() {
+ startTransition(async () => {
+ const r = await saveSharedContextAction({
+ project_slug: projectSlug,
+ content,
+ });
+ if (!r.ok) {
+ toast.error(r.error);
+ return;
+ }
+ toast.success(
+ r.synced_agents > 0
+ ? `Saved — synced to ${r.synced_agents} goal agent${r.synced_agents === 1 ? "" : "s"}.`
+ : "Saved.",
+ );
+ setSaved(content);
+ setEditing(false);
+ router.refresh();
+ });
+ }
+
+ if (!editing) {
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-[14px] bg-[hsl(var(--notfair-surface-2)/0.5)] px-5 py-4">
+ <Markdown>{saved}</Markdown>
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
+ Shared with every goal agent — they update it too when they learn
+ something workspace-wide.
+ </p>
+ <Button variant="outline" onClick={() => setEditing(true)}>
+ <Pencil className="size-3.5" aria-hidden />
+ Edit
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ <textarea
+ value={content}
+ onChange={(e) => setContent(e.target.value)}
+ disabled={pending}
+ spellCheck={false}
+ autoFocus
+ className="min-h-[420px] w-full resize-y rounded-[14px] bg-[hsl(var(--notfair-surface-2))] px-4 py-3.5 font-mono text-[12.5px] leading-relaxed outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent))]"
+ placeholder={
+ "# Company\nWhat you sell, to whom, and what matters…\n\nAgents usually write this during their first goal's intake — but you know the business best. Anything here reaches every goal agent."
+ }
+ />
+ <div className="flex items-center justify-between gap-3">
+ <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
+ Raw markdown — rendered once saved. Keep it a curated brief, not a
+ dump.
+ </p>
+ <div className="flex items-center gap-2">
+ {saved.trim() !== "" && (
+ <Button
+ variant="ghost"
+ disabled={pending}
+ onClick={() => {
+ setContent(saved);
+ setEditing(false);
+ }}
+ >
+ Cancel
+ </Button>
+ )}
+ <Button onClick={save} disabled={pending || !dirty}>
+ {pending ? "Saving…" : "Save & sync"}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/notfair-cmo/src/components/sidebar-brand.tsx b/notfair/src/components/sidebar-brand.tsx
similarity index 98%
rename from notfair-cmo/src/components/sidebar-brand.tsx
rename to notfair/src/components/sidebar-brand.tsx
index d26027c1..4f09a389 100644
--- a/notfair-cmo/src/components/sidebar-brand.tsx
+++ b/notfair/src/components/sidebar-brand.tsx
@@ -54,7 +54,7 @@ export function SidebarBrand({ homeHref }: Props) {
return (
<Link
href={homeHref}
- aria-label="Notfair CMO home"
+ aria-label="NotFair home"
className="flex h-8 shrink-0 items-center px-2"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
diff --git a/notfair-cmo/src/components/sidebar-version.tsx b/notfair/src/components/sidebar-version.tsx
similarity index 93%
rename from notfair-cmo/src/components/sidebar-version.tsx
rename to notfair/src/components/sidebar-version.tsx
index 6cc65981..04915359 100644
--- a/notfair-cmo/src/components/sidebar-version.tsx
+++ b/notfair/src/components/sidebar-version.tsx
@@ -14,7 +14,7 @@ type VersionInfo = {
/**
* Sidebar footer: current version + an Upgrade button when npm reports a
- * newer version. Clicking Upgrade runs `npm i -g notfair-cmo@latest` via
+ * newer version. Clicking Upgrade runs `npm i -g notfair@latest` via
* /api/upgrade and tells the user to restart.
*/
export function SidebarVersion() {
@@ -60,7 +60,7 @@ export function SidebarVersion() {
setUpgraded(true);
toast.success(
body.note ??
- "Upgraded. Restart notfair-cmo in your terminal to apply.",
+ "Upgraded. Restart NotFair in your terminal to apply.",
{ duration: 15_000 },
);
} catch (err) {
@@ -73,7 +73,7 @@ export function SidebarVersion() {
if (!info) {
return (
<div className="px-1 text-[11px] font-mono text-[hsl(var(--notfair-ink-5))]">
- notfair-cmo
+ NotFair
</div>
);
}
@@ -81,7 +81,7 @@ export function SidebarVersion() {
return (
<div className="flex items-center justify-between gap-2 px-1 text-[11px]">
<span className="font-mono text-[hsl(var(--notfair-ink-4))]">
- notfair-cmo v{info.current}
+ NotFair v{info.current}
</span>
{info.has_update && !upgraded && (
diff --git a/notfair-cmo/src/components/slash-command-popover.tsx b/notfair/src/components/slash-command-popover.tsx
similarity index 97%
rename from notfair-cmo/src/components/slash-command-popover.tsx
rename to notfair/src/components/slash-command-popover.tsx
index 3c07a573..7654777b 100644
--- a/notfair-cmo/src/components/slash-command-popover.tsx
+++ b/notfair/src/components/slash-command-popover.tsx
@@ -100,7 +100,7 @@ export function SlashCommandPopover({
);
})}
</ul>
- <div className="border-t bg-muted/30 px-3 py-1.5 text-[10px] text-muted-foreground">
+ <div className="bg-muted/40 px-3 py-1.5 text-[10px] text-muted-foreground">
↑↓ navigate · Enter / Tab to select · Enter again to send · Esc to clear
</div>
</div>
diff --git a/notfair-cmo/src/components/theme-provider.tsx b/notfair/src/components/theme-provider.tsx
similarity index 100%
rename from notfair-cmo/src/components/theme-provider.tsx
rename to notfair/src/components/theme-provider.tsx
diff --git a/notfair-cmo/src/components/theme-toggle.tsx b/notfair/src/components/theme-toggle.tsx
similarity index 100%
rename from notfair-cmo/src/components/theme-toggle.tsx
rename to notfair/src/components/theme-toggle.tsx
diff --git a/notfair-cmo/src/components/ui/badge.tsx b/notfair/src/components/ui/badge.tsx
similarity index 93%
rename from notfair-cmo/src/components/ui/badge.tsx
rename to notfair/src/components/ui/badge.tsx
index 6eb2a057..7a6a31a6 100644
--- a/notfair-cmo/src/components/ui/badge.tsx
+++ b/notfair/src/components/ui/badge.tsx
@@ -15,7 +15,7 @@ const badgeVariants = cva(
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
- "border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
+ "bg-[hsl(var(--notfair-surface-2))] text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
diff --git a/notfair-cmo/src/components/ui/button.tsx b/notfair/src/components/ui/button.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/button.tsx
rename to notfair/src/components/ui/button.tsx
diff --git a/notfair-cmo/src/components/ui/card.tsx b/notfair/src/components/ui/card.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/card.tsx
rename to notfair/src/components/ui/card.tsx
diff --git a/notfair-cmo/src/components/ui/dialog.tsx b/notfair/src/components/ui/dialog.tsx
similarity index 93%
rename from notfair-cmo/src/components/ui/dialog.tsx
rename to notfair/src/components/ui/dialog.tsx
index 84bdef4b..606a0492 100644
--- a/notfair-cmo/src/components/ui/dialog.tsx
+++ b/notfair/src/components/ui/dialog.tsx
@@ -61,7 +61,7 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
- "fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
+ "fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-[14px] bg-[hsl(var(--card))] p-6 shadow-[var(--notfair-shadow-lg)] duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className
)}
{...props}
diff --git a/notfair-cmo/src/components/ui/dropdown-menu.tsx b/notfair/src/components/ui/dropdown-menu.tsx
similarity index 89%
rename from notfair-cmo/src/components/ui/dropdown-menu.tsx
rename to notfair/src/components/ui/dropdown-menu.tsx
index ae1fcf62..d6a926f8 100644
--- a/notfair-cmo/src/components/ui/dropdown-menu.tsx
+++ b/notfair/src/components/ui/dropdown-menu.tsx
@@ -42,7 +42,7 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
- "z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
+ "z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
@@ -230,7 +230,7 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
- "z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
+ "z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
diff --git a/notfair-cmo/src/components/ui/input.tsx b/notfair/src/components/ui/input.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/input.tsx
rename to notfair/src/components/ui/input.tsx
diff --git a/notfair-cmo/src/components/ui/label.tsx b/notfair/src/components/ui/label.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/label.tsx
rename to notfair/src/components/ui/label.tsx
diff --git a/notfair-cmo/src/components/ui/separator.tsx b/notfair/src/components/ui/separator.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/separator.tsx
rename to notfair/src/components/ui/separator.tsx
diff --git a/notfair-cmo/src/components/ui/sheet.tsx b/notfair/src/components/ui/sheet.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/sheet.tsx
rename to notfair/src/components/ui/sheet.tsx
diff --git a/notfair-cmo/src/components/ui/sidebar.tsx b/notfair/src/components/ui/sidebar.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/sidebar.tsx
rename to notfair/src/components/ui/sidebar.tsx
diff --git a/notfair-cmo/src/components/ui/skeleton.tsx b/notfair/src/components/ui/skeleton.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/skeleton.tsx
rename to notfair/src/components/ui/skeleton.tsx
diff --git a/notfair-cmo/src/components/ui/sonner.tsx b/notfair/src/components/ui/sonner.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/sonner.tsx
rename to notfair/src/components/ui/sonner.tsx
diff --git a/notfair-cmo/src/components/ui/tooltip.tsx b/notfair/src/components/ui/tooltip.tsx
similarity index 100%
rename from notfair-cmo/src/components/ui/tooltip.tsx
rename to notfair/src/components/ui/tooltip.tsx
diff --git a/notfair-cmo/src/components/working-indicator.tsx b/notfair/src/components/working-indicator.tsx
similarity index 100%
rename from notfair-cmo/src/components/working-indicator.tsx
rename to notfair/src/components/working-indicator.tsx
diff --git a/notfair-cmo/src/components/workspace-browser-card.tsx b/notfair/src/components/workspace-browser-card.tsx
similarity index 100%
rename from notfair-cmo/src/components/workspace-browser-card.tsx
rename to notfair/src/components/workspace-browser-card.tsx
diff --git a/notfair-cmo/src/hooks/use-mobile.ts b/notfair/src/hooks/use-mobile.ts
similarity index 100%
rename from notfair-cmo/src/hooks/use-mobile.ts
rename to notfair/src/hooks/use-mobile.ts
diff --git a/notfair-cmo/src/instrumentation.ts b/notfair/src/instrumentation.ts
similarity index 59%
rename from notfair-cmo/src/instrumentation.ts
rename to notfair/src/instrumentation.ts
index a2b3960a..3e7048aa 100644
--- a/notfair-cmo/src/instrumentation.ts
+++ b/notfair/src/instrumentation.ts
@@ -1,7 +1,6 @@
// Next.js boots this once per server process via the instrumentation hook.
-// We use it to start the cron tick loop — without this call, scheduled jobs
-// fire never, the calendar shows no run history, and the detail dialog has
-// nothing to render in its Result section.
+// We use it to start the goal-tick loop — without that call, goal
+// heartbeats never fire.
export async function register(): Promise<void> {
if (process.env.NEXT_RUNTIME !== "nodejs") return;
const { ensureSchedulerRunning } = await import("@/server/scheduler/tick");
diff --git a/notfair/src/lib/agent-colors.ts b/notfair/src/lib/agent-colors.ts
new file mode 100644
index 00000000..54095c7e
--- /dev/null
+++ b/notfair/src/lib/agent-colors.ts
@@ -0,0 +1,48 @@
+/**
+ * Per-agent color palette used by the cron calendar (and anywhere else a
+ * per-agent swatch helps scanning). Agent = goal: there are no reserved
+ * role hues anymore — every agent gets a stable, vivid color by hashing
+ * its slug. Deliberately vivid: zinc/neutral would read as "disabled"
+ * against the rest of the UI.
+ */
+export type AgentColor = {
+ /** Tailwind classes: chip background + text color. Neutral inset fill —
+ * hue lives in the `dot` / `label` fields only. */
+ chip: string;
+ /** Solid dot/legend swatch. */
+ dot: string;
+ /** Label color when only the label is shown. */
+ label: string;
+};
+
+const CHIP =
+ "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent";
+
+const PALETTE: AgentColor[] = [
+ { chip: CHIP, dot: "bg-blue-500", label: "text-blue-700 dark:text-blue-300" },
+ { chip: CHIP, dot: "bg-violet-500", label: "text-violet-700 dark:text-violet-300" },
+ { chip: CHIP, dot: "bg-emerald-500", label: "text-emerald-700 dark:text-emerald-300" },
+ { chip: CHIP, dot: "bg-amber-500", label: "text-amber-700 dark:text-amber-300" },
+ { chip: CHIP, dot: "bg-rose-500", label: "text-rose-700 dark:text-rose-300" },
+ { chip: CHIP, dot: "bg-cyan-500", label: "text-cyan-700 dark:text-cyan-300" },
+ { chip: CHIP, dot: "bg-fuchsia-500", label: "text-fuchsia-700 dark:text-fuchsia-300" },
+ { chip: CHIP, dot: "bg-teal-500", label: "text-teal-700 dark:text-teal-300" },
+ { chip: CHIP, dot: "bg-orange-500", label: "text-orange-700 dark:text-orange-300" },
+ { chip: CHIP, dot: "bg-indigo-500", label: "text-indigo-700 dark:text-indigo-300" },
+ { chip: CHIP, dot: "bg-pink-500", label: "text-pink-700 dark:text-pink-300" },
+ { chip: CHIP, dot: "bg-lime-500", label: "text-lime-700 dark:text-lime-300" },
+];
+
+/** Fast deterministic hash (djb2) so a slug always maps to the same color. */
+function hashSlug(slug: string): number {
+ let h = 5381;
+ for (let i = 0; i < slug.length; i++) {
+ h = ((h << 5) + h + slug.charCodeAt(i)) | 0;
+ }
+ return Math.abs(h);
+}
+
+/** Stable color for an agent slug (e.g. `goal-alex`). */
+export function colorForAgentSlug(slug: string): AgentColor {
+ return PALETTE[hashSlug(slug) % PALETTE.length]!;
+}
diff --git a/notfair/src/lib/format-metric.ts b/notfair/src/lib/format-metric.ts
new file mode 100644
index 00000000..4f37f7a2
--- /dev/null
+++ b/notfair/src/lib/format-metric.ts
@@ -0,0 +1,11 @@
+/**
+ * Human formatting for metric values everywhere the UI shows one: floats
+ * from averaged measurements come in with full precision
+ * (82065.85714285714) and must never reach the user raw.
+ */
+const FMT = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });
+
+export function formatMetric(v: number | null | undefined): string {
+ if (v === null || v === undefined) return "—";
+ return FMT.format(v);
+}
diff --git a/notfair/src/lib/goal-cadence.ts b/notfair/src/lib/goal-cadence.ts
new file mode 100644
index 00000000..c93ddee7
--- /dev/null
+++ b/notfair/src/lib/goal-cadence.ts
@@ -0,0 +1,20 @@
+/**
+ * Heartbeat cadence presets for the goal loop. UTC cron under the hood
+ * (matching the scheduler); labels speak human. 16:00 UTC ≈ 9am Pacific
+ * (summer) — same convention the goal skill teaches.
+ */
+export type CadenceOption = { value: string; label: string; hint: string };
+
+export const CADENCE_OPTIONS: CadenceOption[] = [
+ { value: "0 16 * * *", label: "Daily", hint: "every day, 9am PT" },
+ { value: "0 16 * * 1-5", label: "Weekdays", hint: "Mon–Fri, 9am PT" },
+ { value: "0 */6 * * *", label: "4× daily", hint: "every 6 hours" },
+ { value: "0 16 * * 1", label: "Weekly", hint: "Mondays, 9am PT" },
+];
+
+export const DEFAULT_CADENCE = CADENCE_OPTIONS[0]!.value;
+
+export function cadenceLabel(cron: string): string {
+ const preset = CADENCE_OPTIONS.find((o) => o.value === cron);
+ return preset ? `${preset.label} (${preset.hint})` : cron;
+}
diff --git a/notfair/src/lib/goal-label.ts b/notfair/src/lib/goal-label.ts
new file mode 100644
index 00000000..06b36146
--- /dev/null
+++ b/notfair/src/lib/goal-label.ts
@@ -0,0 +1,28 @@
+/**
+ * Display identity for a goal. Goals are the only nameable thing in
+ * NotFair (agents are plumbing), so every surface labels rows/pages with
+ * this: the agent-written short_label when it exists, else a trimmed
+ * statement, else a placeholder for goals whose ambition hasn't landed.
+ *
+ * Client-safe: pure string logic, no server imports.
+ */
+
+const MAX_FALLBACK_CHARS = 42;
+
+export function goalLabel(goal: {
+ short_label?: string | null;
+ statement?: string | null;
+}): string {
+ const label = goal.short_label?.trim();
+ if (label) return label;
+ const statement = goal.statement?.trim();
+ if (statement) return trimAtWord(statement, MAX_FALLBACK_CHARS);
+ return "New goal";
+}
+
+function trimAtWord(s: string, max: number): string {
+ if (s.length <= max) return s;
+ const cut = s.slice(0, max);
+ const lastSpace = cut.lastIndexOf(" ");
+ return `${cut.slice(0, lastSpace > max / 2 ? lastSpace : max)}…`;
+}
diff --git a/notfair/src/lib/goal-streak.ts b/notfair/src/lib/goal-streak.ts
new file mode 100644
index 00000000..c14e5e6b
--- /dev/null
+++ b/notfair/src/lib/goal-streak.ts
@@ -0,0 +1,69 @@
+/**
+ * Streak math for MAINTAIN goals: "held at target for N days" is the
+ * right hero stat when holding IS the job. Pure — testable without a DB.
+ */
+
+export type CheckSquare = {
+ tick_number: number;
+ t: number;
+ /** held = measured at/inside target; acted = the agent intervened this
+ * check; failed = the check errored or the metric drifted. */
+ state: "held" | "acted" | "failed";
+};
+
+export type StreakInput = {
+ tick_number: number;
+ started_at: string;
+ metric_value: number | null;
+ status: string;
+ /** true when a mutation action was logged on this check. */
+ acted: boolean;
+};
+
+export function heldAtTarget(
+ value: number | null,
+ target: number | null,
+ direction: "increase" | "decrease" | null,
+): boolean {
+ if (value === null || target === null) return false;
+ return direction === "decrease" ? value <= target : value >= target;
+}
+
+export function buildCheckSquares(
+ checks: StreakInput[],
+ target: number | null,
+ direction: "increase" | "decrease" | null,
+): CheckSquare[] {
+ return checks
+ .slice()
+ .sort((a, b) => a.tick_number - b.tick_number)
+ .map((c) => ({
+ tick_number: c.tick_number,
+ t: Date.parse(c.started_at),
+ state:
+ c.status === "failed" || !heldAtTarget(c.metric_value, target, direction)
+ ? ("failed" as const)
+ : c.acted
+ ? ("acted" as const)
+ : ("held" as const),
+ }));
+}
+
+export type Streak = { holding: boolean; days: number };
+
+/**
+ * The current hold: `holding` is false when the LATEST check drifted or
+ * failed; otherwise days counts from the first check of the unbroken run
+ * (0 = held since today). Null when there are no finished checks yet.
+ */
+export function currentStreak(squares: CheckSquare[], now = Date.now()): Streak | null {
+ if (squares.length === 0) return null;
+ let runStart: number | null = null;
+ for (let i = squares.length - 1; i >= 0; i--) {
+ const sq = squares[i]!;
+ if (sq.state === "failed") break;
+ runStart = sq.t;
+ }
+ if (runStart === null) return { holding: false, days: 0 };
+ return { holding: true, days: Math.max(0, Math.floor((now - runStart) / 86_400_000)) };
+}
diff --git a/notfair-cmo/src/lib/project-href.ts b/notfair/src/lib/project-href.ts
similarity index 85%
rename from notfair-cmo/src/lib/project-href.ts
rename to notfair/src/lib/project-href.ts
index daacc13b..baaffbad 100644
--- a/notfair-cmo/src/lib/project-href.ts
+++ b/notfair/src/lib/project-href.ts
@@ -1,10 +1,10 @@
/**
- * Build a project-scoped URL like `/<slug>/agents/cmo/chat`.
+ * Build a project-scoped URL like `/<slug>/goals/goal-1`.
*
* The router treats every URL under `(app)/[project]/...` as project-scoped,
* so every internal link inside the app shell needs the slug prefix. This
* helper keeps that prefixing consistent and centralizes the leading-slash
- * normalisation so callers can pass either `agents/cmo` or `/agents/cmo`.
+ * normalisation so callers can pass either `goals/goal-1` or `/goals/goal-1`.
*
* Passing an empty `path` returns the project root: `/<slug>`.
*/
@@ -23,7 +23,7 @@ export function projectHref(slug: string, path = ""): string {
* Strip the leading `/<currentSlug>` segment from a pathname and return the
* rest (always with a leading slash, or empty when the pathname is the
* project home). Used by the ProjectSwitcher so picking a different project
- * preserves the user's current view (`/foo/agents/cmo/tasks` → `/agents/cmo/tasks`).
+ * preserves the user's current view (`/foo/connections` → `/connections`).
*
* Returns `""` when the pathname doesn't actually start with `/<currentSlug>` —
* the caller should treat that as "send the user to the new project's home."
diff --git a/notfair-cmo/src/lib/slash-commands.ts b/notfair/src/lib/slash-commands.ts
similarity index 85%
rename from notfair-cmo/src/lib/slash-commands.ts
rename to notfair/src/lib/slash-commands.ts
index d97f7b0e..b25bcccd 100644
--- a/notfair-cmo/src/lib/slash-commands.ts
+++ b/notfair/src/lib/slash-commands.ts
@@ -1,13 +1,9 @@
/**
* Slash command catalog + local executor.
*
- * Every command here is handled CLIENT-SIDE by the chat composer. The
- * catalog used to carry ~17 more entries ported from OpenClaw's web UI
- * (/compact, /status, /elevated, /queue, …) marked "pass through to the
- * agent" — but notfair-cmo no longer runs on OpenClaw, and neither
- * `claude -p` nor `codex exec` interprets slash commands in the prompt,
- * so those rows just sent literal "/compact" text to the agent. The
- * catalog now lists only commands that actually do something.
+ * Every command here is handled CLIENT-SIDE by the chat composer.
+ * Neither `claude -p` nor `codex exec` interprets slash commands in the
+ * prompt, so the catalog lists only commands NotFair itself executes.
*/
export type SlashCommandCategory = "session" | "model" | "status";
@@ -36,13 +32,6 @@ export const SLASH_COMMANDS: SlashCommand[] = [
category: "session",
executeLocal: true,
},
- {
- key: "new",
- name: "new",
- description: "Start a new chat (creates a fresh thread).",
- category: "session",
- executeLocal: true,
- },
{
key: "stop",
name: "stop",
@@ -104,7 +93,6 @@ export function findCommand(name: string): SlashCommand | undefined {
export type LocalSlashAction =
| { kind: "clear" }
- | { kind: "new-session" }
| { kind: "stop" }
| { kind: "set-model"; value: string }
| { kind: "help"; content: string };
@@ -123,8 +111,6 @@ export function executeLocalSlashCommand(
switch (command) {
case "clear":
return { kind: "clear" };
- case "new":
- return { kind: "new-session" };
case "stop":
return { kind: "stop" };
case "model":
diff --git a/notfair-cmo/src/lib/slug.ts b/notfair/src/lib/slug.ts
similarity index 97%
rename from notfair-cmo/src/lib/slug.ts
rename to notfair/src/lib/slug.ts
index b9e6ab4c..0d67692a 100644
--- a/notfair-cmo/src/lib/slug.ts
+++ b/notfair/src/lib/slug.ts
@@ -5,12 +5,10 @@ const RESERVED_SLUGS = new Set([
"admin",
"system",
"settings",
- "cron",
+ "goals",
"agent",
"agents",
- "cmo",
"notfair",
- "openclaw",
]);
const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
diff --git a/notfair-cmo/src/lib/utils.ts b/notfair/src/lib/utils.ts
similarity index 100%
rename from notfair-cmo/src/lib/utils.ts
rename to notfair/src/lib/utils.ts
diff --git a/notfair/src/server/actions/agents.ts b/notfair/src/server/actions/agents.ts
new file mode 100644
index 00000000..8c3e245b
--- /dev/null
+++ b/notfair/src/server/actions/agents.ts
@@ -0,0 +1,51 @@
+"use server";
+
+import { cascadeDeleteAgent, cloneAgent } from "@/server/agents/clone";
+import { writeAgentMeta } from "@/server/agent-meta";
+
+// --- Relocate (used by project rename to move agents to the new slug) ---
+
+export type RelocateAgentInput = {
+ old_agent_id: string;
+ source_project_slug: string;
+ new_project_slug: string;
+ new_slug: string;
+ new_display_name: string;
+ preserve_source_agent_id?: string;
+ preserve_created_at?: string;
+};
+
+export type RelocateAgentResult = {
+ new_agent_id: string;
+ new_slug: string;
+};
+
+export async function relocateAgent(
+ input: RelocateAgentInput,
+): Promise<RelocateAgentResult> {
+ const cloneResult = await cloneAgent({
+ source_agent_id: input.old_agent_id,
+ project_slug: input.new_project_slug,
+ new_slug: input.new_slug,
+ display_name: input.new_display_name,
+ slug_is_canonical: true,
+ });
+
+ await writeAgentMeta({
+ agent_id: cloneResult.new_agent_id,
+ project_slug: input.new_project_slug,
+ slug: cloneResult.new_slug,
+ name: input.new_display_name,
+ ...(input.preserve_source_agent_id
+ ? { source_agent_id: input.preserve_source_agent_id }
+ : {}),
+ created_at: input.preserve_created_at ?? new Date().toISOString(),
+ });
+
+ await cascadeDeleteAgent(input.old_agent_id, input.source_project_slug).catch(() => {});
+
+ return {
+ new_agent_id: cloneResult.new_agent_id,
+ new_slug: cloneResult.new_slug,
+ };
+}
diff --git a/notfair-cmo/src/server/actions/chat-threads.ts b/notfair/src/server/actions/chat-threads.ts
similarity index 100%
rename from notfair-cmo/src/server/actions/chat-threads.ts
rename to notfair/src/server/actions/chat-threads.ts
diff --git a/notfair/src/server/actions/context.ts b/notfair/src/server/actions/context.ts
new file mode 100644
index 00000000..cd012613
--- /dev/null
+++ b/notfair/src/server/actions/context.ts
@@ -0,0 +1,194 @@
+"use server";
+
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { workspaceDirFor } from "@/server/agents/provisioning";
+import { resolveSessionForThread } from "@/server/sessions/transcript-tail";
+import { listTranscriptEvents } from "@/server/sessions/index";
+import { listProjectMcpTokens } from "@/server/mcp/tokens";
+import { mcpRpcAutoRefresh } from "@/server/mcp/rpc";
+import { getOrCreateMcpServerSecret } from "@/server/mcp-server/secret";
+
+/**
+ * Assemble an estimated breakdown of what sits in a goal agent's context
+ * window: workspace instruction files, MCP tool schemas, and the thread's
+ * conversation. Token counts are ESTIMATES (~4 chars/token) — the harness
+ * doesn't expose its real accounting — and the UI says so.
+ */
+
+export type ContextChunk = {
+ key: string;
+ label: string;
+ group: "instructions" | "tools" | "conversation";
+ chars: number;
+ tokens: number;
+ content: string;
+ /** How the UI should display `content`: prose renders as markdown. */
+ format: "markdown" | "json";
+ note?: string;
+};
+
+export type GoalContextResult =
+ | { ok: true; chunks: ContextChunk[]; total_tokens: number }
+ | { ok: false; error: string };
+
+const est = (chars: number) => Math.ceil(chars / 4);
+
+function chunk(
+ key: string,
+ label: string,
+ group: ContextChunk["group"],
+ content: string,
+ note?: string,
+ format: ContextChunk["format"] = "markdown",
+): ContextChunk {
+ return { key, label, group, chars: content.length, tokens: est(content.length), content, format, note };
+}
+
+async function readWorkspaceFile(agent_id: string, name: string): Promise<string | null> {
+ try {
+ return await readFile(join(workspaceDirFor(agent_id), name), "utf8");
+ } catch {
+ return null;
+ }
+}
+
+type ToolsListResult = {
+ tools?: Array<{ name: string; description?: string; inputSchema?: unknown }>;
+};
+
+/** tools/list against one of our internal loopback MCP servers. */
+async function internalToolsList(path: string): Promise<ToolsListResult | null> {
+ const port = process.env.NOTFAIR_PORT?.trim() || "3326";
+ try {
+ const res = await fetch(`http://127.0.0.1:${port}/api/mcp/${path}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Accept: "application/json, text/event-stream",
+ Authorization: `Bearer ${getOrCreateMcpServerSecret()}`,
+ },
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
+ });
+ const text = await res.text();
+ // The route may answer as SSE; take the last data: line in that case.
+ const raw = text.startsWith("event:") || text.includes("\ndata:")
+ ? text.split("\n").filter((l) => l.startsWith("data:")).pop()?.slice(5)
+ : text;
+ if (!raw) return null;
+ const parsed = JSON.parse(raw) as { result?: ToolsListResult };
+ return parsed.result ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function toolsChunk(key: string, label: string, result: ToolsListResult | null): ContextChunk | null {
+ if (!result?.tools || result.tools.length === 0) return null;
+ const content = JSON.stringify(result.tools, null, 2);
+ return chunk(
+ `tools:${key}`,
+ `${label} · ${result.tools.length} tools`,
+ "tools",
+ content,
+ "Tool name + description + input schema, as the harness receives them.",
+ "json",
+ );
+}
+
+export async function getGoalContextAction(input: {
+ project_slug: string;
+ agent_id: string;
+ thread: string;
+}): Promise<GoalContextResult> {
+ const { project_slug, agent_id, thread } = input;
+ try {
+ const chunks: ContextChunk[] = [];
+
+ // ── Instruction files ─────────────────────────────────────────
+ const identity = await readWorkspaceFile(agent_id, "IDENTITY.md");
+ if (identity) {
+ // The shared-context section sits mid-file; carve out exactly that
+ // section (up to the next `## ` heading) and keep the rest together.
+ const marker = "\n## Shared workspace context";
+ const start = identity.indexOf(marker);
+ const end = start >= 0 ? identity.indexOf("\n## ", start + marker.length) : -1;
+ if (start >= 0) {
+ const shared = end >= 0 ? identity.slice(start, end) : identity.slice(start);
+ const rest = end >= 0
+ ? identity.slice(0, start) + identity.slice(end)
+ : identity.slice(0, start);
+ chunks.push(
+ chunk("identity", "Agent instructions (identity + goal protocol)", "instructions", rest.trim(),
+ "Auto-loaded by the harness at every turn (AGENTS.md / CLAUDE.md)."),
+ chunk("shared-context", "Shared workspace context", "instructions", shared.trim(),
+ "The PROJECT.md brief, inlined into the identity. Shared by every goal in this workspace."),
+ );
+ } else {
+ chunks.push(
+ chunk("identity", "Agent instructions (identity + goal protocol)", "instructions", identity,
+ "Auto-loaded by the harness at every turn (AGENTS.md / CLAUDE.md)."),
+ );
+ }
+ }
+ const skill = await readWorkspaceFile(agent_id, "SKILL.md");
+ if (skill) {
+ chunks.push(
+ chunk("skill", "Goal-loop skill (SKILL.md)", "instructions", skill,
+ "Loaded on demand — enters context when the agent reads it during a session."),
+ );
+ }
+
+ // ── MCP tool definitions ──────────────────────────────────────
+ const goalTools = toolsChunk("notfair-goals", "Goal tools (notfair-goals)", await internalToolsList("goals"));
+ if (goalTools) chunks.push(goalTools);
+ const browserTools = toolsChunk("notfair-browser", "Browser tools (notfair-browser)", await internalToolsList("browser"));
+ if (browserTools) chunks.push(browserTools);
+
+ for (const token of listProjectMcpTokens(project_slug)) {
+ const rpc = await mcpRpcAutoRefresh<ToolsListResult>(
+ project_slug, token.server_name, "tools/list", {}, { timeoutMs: 10_000 },
+ );
+ const c = toolsChunk(token.server_name, `Connected tools (${token.server_name})`, rpc.ok ? rpc.result : null);
+ if (c) chunks.push(c);
+ }
+
+ // ── Conversation (this thread) ────────────────────────────────
+ const session = resolveSessionForThread(project_slug, agent_id, thread);
+ if (session) {
+ const events = listTranscriptEvents(session.id, { limit: 10_000 });
+ let briefs = "", userMsgs = "", replies = "", toolActivity = "";
+ for (const e of events) {
+ let payload: Record<string, unknown> = {};
+ try { payload = JSON.parse(e.payload_json) as Record<string, unknown>; } catch { /* skip */ }
+ if (e.kind === "user") {
+ const text = typeof payload.text === "string" ? payload.text : "";
+ const source = typeof payload.source === "string" ? payload.source : "";
+ if (source.startsWith("goal-")) briefs += text + "\n\n";
+ else userMsgs += text + "\n\n";
+ } else if (e.kind === "final") {
+ const text = typeof payload.text === "string" ? payload.text : "";
+ replies += text + "\n\n";
+ } else if (e.kind === "tool") {
+ toolActivity += e.payload_json + "\n";
+ }
+ }
+ if (briefs) {
+ chunks.push(chunk("briefs", "Platform briefs (intake + checks)", "conversation", briefs.trim(),
+ "The [INTAKE] and [TICK] messages the platform sends the agent."));
+ }
+ if (userMsgs) chunks.push(chunk("user", "Your messages", "conversation", userMsgs.trim()));
+ if (replies) chunks.push(chunk("replies", "Agent replies", "conversation", replies.trim()));
+ if (toolActivity) {
+ chunks.push(chunk("tool-activity", "Tool activity (logged)", "conversation", toolActivity.trim(),
+ "NotFair logs tool calls + result summaries. The harness keeps FULL tool outputs in its own context, so the real share is larger.",
+ "json"));
+ }
+ }
+
+ const total_tokens = chunks.reduce((a, c) => a + c.tokens, 0);
+ return { ok: true, chunks, total_tokens };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.ts
new file mode 100644
index 00000000..06ce2ca8
--- /dev/null
+++ b/notfair/src/server/actions/goals.ts
@@ -0,0 +1,168 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import {
+ createGoal,
+ getGoal,
+ getGoalForAgent,
+ setGoalStatus,
+ startGoalLoop,
+} from "@/server/db/goals";
+import { getProject } from "@/server/db/projects";
+import {
+ goalAgentIdFor,
+ goalAgentUrlSlug,
+ provisionGoalAgent,
+} from "@/server/goals/provision";
+import { agentExistsOnDisk, listProjectAgents } from "@/server/agent-meta";
+import { runGoalIntake } from "@/server/goals/intake";
+import { runGoalTick } from "@/server/goals/tick";
+
+export type GoalActionResult = {
+ ok: boolean;
+ error?: string;
+ goal_id?: string;
+ agent_slug?: string;
+};
+
+/** Next free sequential goal number for the project (goal-1, goal-2, …). */
+async function nextGoalNumber(project_slug: string): Promise<number> {
+ const agents = await listProjectAgents(project_slug);
+ let max = 0;
+ for (const a of agents) {
+ const m = a.slug.match(/^goal-(\d+)$/);
+ if (m) max = Math.max(max, Number(m[1]));
+ }
+ let n = max + 1;
+ // Defensive: skip over any orphaned workspace dirs.
+ while (await agentExistsOnDisk(goalAgentIdFor(project_slug, n))) n++;
+ return n;
+}
+
+/**
+ * Mint a new goal from an AMBITION. Goals are the identity — the agent
+ * behind one is anonymous plumbing with a sequential id. The statement
+ * seeds the goal row and an intake turn fires immediately, so the user
+ * lands in a chat where the agent is already working out how to measure
+ * it.
+ */
+export async function createGoalAgentAction(input: {
+ project_slug: string;
+ statement: string;
+}): Promise<GoalActionResult> {
+ const project = getProject(input.project_slug);
+ if (!project) return { ok: false, error: "Project not found." };
+
+ const statement = input.statement.trim();
+ if (!statement) return { ok: false, error: "Say what you want to achieve." };
+
+ const n = await nextGoalNumber(project.slug);
+ const agent_id = goalAgentIdFor(project.slug, n);
+ const urlSlug = goalAgentUrlSlug(n);
+
+ let goal;
+ try {
+ goal = createGoal({ project_slug: project.slug, agent_id, statement });
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+
+ try {
+ await provisionGoalAgent({ goal, urlSlug });
+ } catch (err) {
+ // Roll back so a broken provision doesn't strand a live goal row.
+ setGoalStatus(goal.id, "killed", "provisioning failed");
+ return {
+ ok: false,
+ error: `Agent provisioning failed: ${err instanceof Error ? err.message : String(err)}`,
+ };
+ }
+
+ // The agent starts working immediately; the goal screen's embedded
+ // chat streams it live.
+ void runGoalIntake(goal).catch((err) =>
+ console.error("[goal-intake] kickoff failed:", err),
+ );
+
+ revalidatePath("/", "layout");
+ return {
+ ok: true,
+ goal_id: goal.id,
+ agent_slug: urlSlug,
+ };
+}
+
+/**
+ * The user's START click — the platform-enforced consent that begins the
+ * loop. Fires the first tick immediately so the user watches it work
+ * rather than waiting for tomorrow's heartbeat.
+ */
+export async function startGoalLoopAction(goal_id: string): Promise<GoalActionResult> {
+ const goal = getGoal(goal_id);
+ if (!goal) return { ok: false, error: "Goal not found." };
+ if (goal.status !== "proposed" || goal.target_value === null) {
+ return {
+ ok: false,
+ error: "The goal isn't ready to start — agree a target with the agent in chat first.",
+ };
+ }
+ const started = startGoalLoop(goal_id);
+ if (!started) return { ok: false, error: "Could not start the loop." };
+ void runGoalTick(started, "manual").catch((err) =>
+ console.error("[goal-tick] first tick failed:", err),
+ );
+ revalidatePath("/", "layout");
+ return { ok: true, goal_id: started.id };
+}
+
+export async function pauseGoalAction(goal_id: string): Promise<GoalActionResult> {
+ const goal = setGoalStatus(goal_id, "paused", "paused by user");
+ if (!goal) return { ok: false, error: "Goal not found." };
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+export async function resumeGoalAction(goal_id: string): Promise<GoalActionResult> {
+ const goal = getGoal(goal_id);
+ if (!goal) return { ok: false, error: "Goal not found." };
+ if (goal.status !== "paused") {
+ return { ok: false, error: `Goal is ${goal.status}, not paused.` };
+ }
+ setGoalStatus(goal_id, "active", "resumed by user");
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/**
+ * Close the goal. The agent stays (its chat history and workspace remain
+ * browsable); a closed agent simply never ticks again. Deleting the agent
+ * entirely happens in its Settings danger zone.
+ */
+export async function killGoalAction(
+ goal_id: string,
+ reason?: string,
+): Promise<GoalActionResult> {
+ const goal = setGoalStatus(goal_id, "killed", reason?.trim() || "closed by user");
+ if (!goal) return { ok: false, error: "Goal not found." };
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/** Manual "Run tick now". Fire-and-forget; the diary shows the result. */
+export async function runTickNowAction(goal_id: string): Promise<GoalActionResult> {
+ const goal = getGoal(goal_id);
+ if (!goal) return { ok: false, error: "Goal not found." };
+ if (goal.status !== "active") {
+ return { ok: false, error: `Goal is ${goal.status} — only active goals tick.` };
+ }
+ void runGoalTick(goal, "manual").catch((err) =>
+ console.error("[goal-tick] manual tick failed:", err),
+ );
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/** The live goal for an agent, if any (server helper for pages). */
+export async function getAgentGoalAction(agent_id: string) {
+ return getGoalForAgent(agent_id);
+}
diff --git a/notfair-cmo/src/server/actions/mcp.ts b/notfair/src/server/actions/mcp.ts
similarity index 99%
rename from notfair-cmo/src/server/actions/mcp.ts
rename to notfair/src/server/actions/mcp.ts
index 9b817bdc..acab902a 100644
--- a/notfair-cmo/src/server/actions/mcp.ts
+++ b/notfair/src/server/actions/mcp.ts
@@ -24,7 +24,7 @@ export type StartMcpConnectResult =
* Begin a one-click MCP OAuth flow. Server-side: discovery → DCR →
* PKCE-pair → pending-state stash → caller redirects browser to the
* authorize URL we return. The callback handler in
- * `/api/mcp-oauth/callback` finishes the exchange + writes the openclaw
+ * `/api/mcp-oauth/callback` finishes the exchange + writes the harness
* mcp config.
*/
export async function startMcpConnect(input: {
@@ -571,7 +571,7 @@ async function dynamicRegister(
// grant either ignore the extra entry or reject it; in the latter case
// we'd fall back to the authorization_code-only registration anyway.
const body = {
- client_name: "notfair-cmo",
+ client_name: "NotFair",
redirect_uris: [redirect_uri],
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
diff --git a/notfair-cmo/src/server/actions/projects.ts b/notfair/src/server/actions/projects.ts
similarity index 57%
rename from notfair-cmo/src/server/actions/projects.ts
rename to notfair/src/server/actions/projects.ts
index 10895b60..4715f354 100644
--- a/notfair-cmo/src/server/actions/projects.ts
+++ b/notfair/src/server/actions/projects.ts
@@ -16,21 +16,13 @@ import {
clearActiveProject,
setActiveProject,
} from "@/server/active-project";
-import {
- DEFAULT_ONBOARDING_TEMPLATE_KEYS,
- ensureProjectAgents,
-} from "@/server/agent-templates";
-import { startProvisioning } from "@/server/onboarding/provisioning-state";
import { listProjectAgents, readAgentMeta } from "@/server/agent-meta";
import { relocateAgent } from "@/server/actions/agents";
-import { listCronsForProject, disableCron } from "@/server/scheduler/display";
-import { logAgentAction } from "@/server/db/agent-actions";
import {
cascadeDeleteProjectArtifacts,
getProjectDeletionSummary,
type ProjectDeletionSummary,
} from "@/server/agents/cascade-delete";
-import { clearProvisioning } from "@/server/onboarding/provisioning-state";
export type ActionResult<T = void> =
| { ok: true; data: T }
@@ -46,33 +38,6 @@ export async function createProjectAction(formData: FormData): Promise<void> {
const result = createProject({ display_name });
if (!result.ok) throw new Error(result.reason);
- // Per D6: provision CMO + Google Ads asynchronously so the form returns
- // immediately. The audit step (after OAuth) gates on completion via
- // `awaitProvisioning` from server/onboarding/provisioning-state.
- // Per D4: scope to the default onboarding bundle (SEO is opt-in later).
- // DEFAULT_ONBOARDING_TEMPLATE_KEYS is the single source of truth — also
- // consulted by listProjectAgents to decide which template placeholders
- // appear in the sidebar before disk writes finish.
- const provisionPromise = ensureProjectAgents(
- result.project.slug,
- DEFAULT_ONBOARDING_TEMPLATE_KEYS,
- );
- startProvisioning(result.project.slug, provisionPromise);
- // Log on completion (best-effort, doesn't block form return).
- provisionPromise
- .then((prov) => {
- logAgentAction({
- project_slug: result.project.slug,
- agent_id: "system",
- action_type: "project_created",
- summary: `Project '${result.project.display_name}' created. ${prov.created.length} agents provisioned${prov.failed.length > 0 ? `, ${prov.failed.length} failed` : ""}.`,
- payload: prov,
- });
- })
- .catch((err) => {
- console.error("Agent provisioning failed; project created but no agents:", err);
- });
-
await setActiveProject(result.project.slug);
revalidatePath("/", "layout");
redirect("/");
@@ -82,11 +47,6 @@ 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,
@@ -112,84 +72,6 @@ export async function createProjectForOnboardingAction(
});
if (!result.ok) return { ok: false, error: result.reason };
- // Mint the onboarding task SYNCHRONOUSLY — before provisioning kicks
- // off — so the task row (and its display_id, e.g. `demo3-1`) exists
- // immediately. If the user races through OAuth and lands on
- // setOnboardingAccountAction before provisioning resolves, that flow
- // can still find this task by title and set blocked_by_task_id
- // correctly. Kickoff (which needs the OpenClaw agent to exist) is
- // deferred to the provisionPromise.then() below.
- //
- // Agent personal names are no longer user-configurable at onboarding —
- // we use the template defaults ("Greg" for CMO, "Ana" for Google Ads).
- // Letting users pick once-and-only-once at onboarding was a footgun
- // since agent_ids encode the name and are immutable; if we ever add a
- // proper rename feature (with cascade) it'll live in settings, not
- // here.
- const { agentNameFor, templateForKey } = await import("@/server/agent-templates");
- const cmoName = templateForKey("cmo")?.default_name ?? "Greg";
- const cmoAgentId = agentNameFor(result.project.slug, "cmo", cmoName);
- const { buildProjectOnboardingBrief } = await import(
- "@/server/onboarding/cmo-task-brief"
- );
- const { createTask } = await import("@/server/db/tasks");
- const { title, brief, success_criteria } = buildProjectOnboardingBrief({
- project_slug: result.project.slug,
- project_display_name: result.project.display_name,
- website_url,
- codebase_path,
- });
- const onboardingTask = createTask({
- project_slug: result.project.slug,
- agent_id: cmoAgentId,
- title,
- brief,
- success_criteria,
- assigner_agent_id: null,
- status: "proposed",
- });
-
- // Same async-provisioning policy as createProjectAction (D4 + D6).
- // No `names` override — fall through to each template's default_name.
- const provisionPromise = ensureProjectAgents(
- result.project.slug,
- DEFAULT_ONBOARDING_TEMPLATE_KEYS,
- );
- startProvisioning(result.project.slug, provisionPromise);
- // After provisioning resolves, log + kick off the onboarding task.
- // We chain off provisionPromise (not Promise.all) so a failed provision
- // doesn't try to kickoff against an agent that doesn't exist.
- provisionPromise
- .then(async (prov) => {
- logAgentAction({
- project_slug: result.project.slug,
- agent_id: "system",
- action_type: "project_created",
- 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 cmoOk =
- prov.created.includes(cmoAgentId) || prov.existed.includes(cmoAgentId);
- if (!cmoOk) {
- console.error(
- `[onboarding] CMO agent ${cmoAgentId} not provisioned; skipping onboarding task kickoff`,
- );
- return;
- }
- try {
- const { startTaskIfProposed } = await import(
- "@/server/orchestration/run-task"
- );
- startTaskIfProposed(onboardingTask);
- } 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);
- });
-
await setActiveProject(result.project.slug);
revalidatePath("/", "layout");
return {
@@ -201,22 +83,6 @@ export async function createProjectForOnboardingAction(
};
}
-export async function reprovisionAgentsAction(slug: string): Promise<{ ok: true; created: string[]; existed: string[] } | { ok: false; error: string }> {
- try {
- // Scope to the same set onboarding uses — clicking "Reprovision" should
- // restore the onboarded bundle (cmo + google-ads), not auto-create
- // opt-in templates like SEO that the user never asked for.
- const { DEFAULT_ONBOARDING_TEMPLATE_KEYS } = await import(
- "@/server/agent-templates"
- );
- const result = await ensureProjectAgents(slug, DEFAULT_ONBOARDING_TEMPLATE_KEYS);
- revalidatePath("/", "layout");
- return { ok: true, ...result };
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
- }
-}
-
export async function switchProjectAction(slug: string): Promise<ActionResult> {
await setActiveProject(slug);
revalidatePath("/", "layout");
@@ -225,39 +91,11 @@ export async function switchProjectAction(slug: string): Promise<ActionResult> {
export async function archiveProjectAction(
slug: string,
-): Promise<ActionResult<{ halted_crons: number }>> {
- const updated = archiveProject(slug);
- if (!updated) return { ok: false, error: "Project not found." };
-
- // Cascade: halt all OpenClaw crons matching this project's prefix.
- // Failure to halt is non-fatal; user can clean up manually via the cron tab.
- let halted = 0;
- try {
- const view = await listCronsForProject(slug);
- for (const group of view.groups) {
- for (const cron of group.crons) {
- if (cron.disabled) continue;
- try {
- await disableCron(cron.id);
- halted += 1;
- } catch (err) {
- console.error(`Failed to disable cron ${cron.id} during archive:`, err);
- }
- }
- }
- } catch (err) {
- console.error("Could not list crons during project archive:", err);
- }
-
- logAgentAction({
- project_slug: slug,
- agent_id: "system",
- action_type: "project_archived",
- summary: `Project archived. ${halted} cron${halted === 1 ? "" : "s"} halted.`,
- });
-
+): Promise<ActionResult> {
+ const project = archiveProject(slug);
+ if (!project) return { ok: false, error: "Project not found." };
revalidatePath("/", "layout");
- return { ok: true, data: { halted_crons: halted } };
+ return { ok: true, data: undefined };
}
export async function renameProjectAction(slug: string, display_name: string): Promise<ActionResult> {
@@ -290,7 +128,7 @@ export type RenameProjectFullData = {
* rename), then migrate every DB row keyed off project_slug.
*
* After a full rename: agent_ids change from `<old>-<slug>` to `<new>-<slug>`,
- * cron names rewrite via clone, workspace dirs move, session JSONL files
+ * workspace dirs move, session rows
* relocate, and the active-project cookie repoints at the new slug.
*/
export async function renameProjectFullAction(
@@ -355,7 +193,6 @@ export async function renameProjectFullAction(
new_project_slug: newSlug,
new_slug: a.slug,
new_display_name: a.name,
- preserve_template_key: a.template_key,
preserve_source_agent_id: meta?.source_agent_id,
preserve_created_at: meta?.created_at,
});
@@ -384,9 +221,9 @@ export async function renameProjectFullAction(
// 2.5) Move the canonical PROJECT.md directory from old slug → new slug
// so the brief survives the rename. The per-agent sidecar copies
- // get rewritten on the next ensureProjectAgents pass (or
- // writeIdentityFile call); the canonical file is the source of
- // truth they read from, so moving this is what matters.
+ // get rewritten on the next identity sync; the canonical file is
+ // the source of truth they read from, so moving this is what
+ // matters.
try {
const { renameProjectBriefDir } = await import(
"@/server/onboarding/project-brief"
@@ -435,8 +272,6 @@ export async function getProjectDeletionSummaryAction(
export type DeleteProjectData = {
agents: string[];
agentsFailed: Array<{ agentId: string; error: string }>;
- crons: number;
- cronsFailed: number;
mcps: number;
mcpsFailed: number;
};
@@ -454,19 +289,12 @@ export async function deleteProjectAction(
const projectAgentEntries = await listProjectAgents(slug);
const deletedAgents: string[] = projectAgentEntries.map((a) => a.agent_id);
const agentsFailed: Array<{ agentId: string; error: string }> = [];
-
- // Count crons + MCP tokens upfront so the result shape stays informative.
- let cronsDeleted = 0;
- try {
- const view = await listCronsForProject(slug);
- cronsDeleted = view.groups.reduce((acc, g) => acc + g.crons.length, 0);
- } catch {
- // best-effort
- }
+ // MCP token rows are wiped by the cascade below; count upfront for the
+ // result summary.
const { listProjectMcpTokens } = await import("@/server/mcp/tokens");
const mcpsRevoked = listProjectMcpTokens(slug).length;
const mcpsFailed = 0;
- const cronsFailed = 0;
+
// Single shot — drops every artifact tied to this project: agent workspace
// dirs, scheduled_jobs + runs, sessions + transcripts, mcp_tokens. Adapter
@@ -481,11 +309,7 @@ export async function deleteProjectAction(
});
}
- // Drop the in-memory provisioning Promise so a re-created project with the
- // same slug starts fresh.
- clearProvisioning(slug);
-
- // 5) Canonical PROJECT.md directory at ~/.notfair-cmo/projects/<slug>/.
+ // 5) Canonical PROJECT.md directory at ~/.notfair/projects/<slug>/.
// The per-agent sidecar copies inside each workspace were already wiped
// by cascadeDeleteAgent's `rm -rf` on the workspace dir; this is the
// last surface that holds the project brief on disk. Without this,
@@ -513,10 +337,6 @@ export async function deleteProjectAction(
await clearActiveProject();
}
- // No logAgentAction here — agent_actions has a FK to projects.slug, and
- // deleteProjectRow already purges rows for this slug, so any log entry
- // would either FK-fail or be wiped on the spot.
-
revalidatePath("/", "layout");
return {
@@ -524,8 +344,6 @@ export async function deleteProjectAction(
data: {
agents: deletedAgents,
agentsFailed,
- crons: cronsDeleted,
- cronsFailed,
mcps: mcpsRevoked,
mcpsFailed,
},
diff --git a/notfair/src/server/actions/shared-context.ts b/notfair/src/server/actions/shared-context.ts
new file mode 100644
index 00000000..4ecfb81a
--- /dev/null
+++ b/notfair/src/server/actions/shared-context.ts
@@ -0,0 +1,45 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import { getProject } from "@/server/db/projects";
+import {
+ writeProjectBrief,
+ PROJECT_BRIEF_MAX_BYTES,
+} from "@/server/onboarding/project-brief";
+import { syncProjectAgents } from "@/server/goals/provision";
+
+/**
+ * User-side editing of the shared workspace context (PROJECT.md). Same
+ * write + sync path the agents' `set_shared_context` tool uses, so a save
+ * here lands in every goal agent's identity immediately.
+ */
+export async function saveSharedContextAction(input: {
+ project_slug: string;
+ content: string;
+}): Promise<
+ | { ok: true; synced_agents: number }
+ | { ok: false; error: string }
+> {
+ const project = getProject(input.project_slug);
+ if (!project) return { ok: false, error: "Workspace not found." };
+
+ const content = input.content.trim();
+ if (!content) {
+ return { ok: false, error: "Shared context can't be empty — describe the company instead." };
+ }
+ if (Buffer.byteLength(content, "utf8") > PROJECT_BRIEF_MAX_BYTES) {
+ return {
+ ok: false,
+ error: `Too long — keep it under ${Math.round(PROJECT_BRIEF_MAX_BYTES / 1024)}KB. This is a curated brief, not a dump.`,
+ };
+ }
+
+ try {
+ await writeProjectBrief(input.project_slug, content);
+ const synced_agents = await syncProjectAgents(input.project_slug);
+ revalidatePath("/", "layout");
+ return { ok: true, synced_agents };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
diff --git a/notfair/src/server/actions/suggestions.ts b/notfair/src/server/actions/suggestions.ts
new file mode 100644
index 00000000..f4eff70b
--- /dev/null
+++ b/notfair/src/server/actions/suggestions.ts
@@ -0,0 +1,56 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import {
+ getSuggestion,
+ markSuggestionAccepted,
+ markSuggestionDismissed,
+} from "@/server/db/suggestions";
+import {
+ analyzableSources,
+ generateSuggestionsForSource,
+} from "@/server/suggestions/engine";
+import { createGoalAgentAction, type GoalActionResult } from "@/server/actions/goals";
+
+/**
+ * Accept a suggestion: mint the goal from its statement (the normal
+ * statement-first flow — the agent still verifies the metric and the
+ * user still presses START) and retire the card.
+ */
+export async function acceptSuggestionAction(id: string): Promise<GoalActionResult> {
+ const suggestion = getSuggestion(id);
+ if (!suggestion) return { ok: false, error: "Suggestion not found." };
+ if (suggestion.status !== "open") {
+ return { ok: false, error: "This suggestion was already handled." };
+ }
+
+ const result = await createGoalAgentAction({
+ project_slug: suggestion.project_slug,
+ statement: suggestion.statement,
+ });
+ if (result.ok && result.goal_id) {
+ markSuggestionAccepted(id, result.goal_id);
+ revalidatePath("/", "layout");
+ }
+ return result;
+}
+
+export async function dismissSuggestionAction(id: string): Promise<{ ok: boolean }> {
+ const suggestion = getSuggestion(id);
+ if (!suggestion || suggestion.status !== "open") return { ok: false };
+ markSuggestionDismissed(id);
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/** Re-run analysis across every connected source that supports it. */
+export async function refreshSuggestionsAction(
+ project_slug: string,
+): Promise<{ ok: boolean; sources: number }> {
+ const sources = analyzableSources(project_slug);
+ for (const key of sources) {
+ void generateSuggestionsForSource(project_slug, key);
+ }
+ revalidatePath("/", "layout");
+ return { ok: true, sources: sources.length };
+}
diff --git a/notfair-cmo/src/server/active-project.ts b/notfair/src/server/active-project.ts
similarity index 100%
rename from notfair-cmo/src/server/active-project.ts
rename to notfair/src/server/active-project.ts
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/execute.ts b/notfair/src/server/adapters/claude-code-local/execute.ts
similarity index 97%
rename from notfair-cmo/src/server/adapters/claude-code-local/execute.ts
rename to notfair/src/server/adapters/claude-code-local/execute.ts
index 22acda69..2c55c5f0 100644
--- a/notfair-cmo/src/server/adapters/claude-code-local/execute.ts
+++ b/notfair/src/server/adapters/claude-code-local/execute.ts
@@ -15,7 +15,7 @@ const CLAUDE_BIN = process.env.NOTFAIR_CLAUDE_BIN?.trim() || "claude";
* - The agent's IDENTITY.md is passed as the system prompt via
* `--append-system-prompt`. Claude Code already auto-loads workspace
* CLAUDE.md if present; the IDENTITY.md content takes priority either way.
- * - We resume threads via `--resume <session-id>` when notfair-cmo's threadId
+ * - We resume threads via `--resume <session-id>` when NotFair's threadId
* maps onto an existing Claude session. First turn for a thread is fresh.
* - Each stdout line is a JSON event; we forward as HarnessEvents.
*/
@@ -47,7 +47,7 @@ export async function* executeClaudeCodeLocal(
}
// Resume a Claude session only when we've actually seen one for this
- // thread before. notfair-cmo's `sessions.id` UUID is meaningless to
+ // thread before. NotFair's `sessions.id` UUID is meaningless to
// Claude — passing it to --resume would fail immediately with
// "no session found". The first turn of a thread always runs fresh.
if (ctx.harnessSessionId && isUuid(ctx.harnessSessionId)) {
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/index.ts b/notfair/src/server/adapters/claude-code-local/index.ts
similarity index 94%
rename from notfair-cmo/src/server/adapters/claude-code-local/index.ts
rename to notfair/src/server/adapters/claude-code-local/index.ts
index 95fc322c..a581feda 100644
--- a/notfair-cmo/src/server/adapters/claude-code-local/index.ts
+++ b/notfair/src/server/adapters/claude-code-local/index.ts
@@ -15,7 +15,7 @@ import { testClaudeCodeLocalEnvironment } from "./test";
import { registerClaudeCodeMcp, unregisterClaudeCodeMcp } from "./mcp";
function dataDir(): string {
- return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+ return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
}
function workspaceDirFor(agentId: string): string {
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/mcp.ts b/notfair/src/server/adapters/claude-code-local/mcp.ts
similarity index 97%
rename from notfair-cmo/src/server/adapters/claude-code-local/mcp.ts
rename to notfair/src/server/adapters/claude-code-local/mcp.ts
index e76e6660..32aa1545 100644
--- a/notfair-cmo/src/server/adapters/claude-code-local/mcp.ts
+++ b/notfair/src/server/adapters/claude-code-local/mcp.ts
@@ -8,7 +8,7 @@ import type { McpRegistrationSpec } from "../types";
*
* Claude Code reads MCP server definitions from `<workspace>/.mcp.json`
* (project-scoped) and `~/.claude/mcp_servers.json` (user-scoped). We use
- * the workspace-scoped file because notfair-cmo wants tokens to be
+ * the workspace-scoped file because NotFair wants tokens to be
* project-scoped — one agent's notfair-googleads connection must not bleed
* into another agent's account.
*/
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/models.ts b/notfair/src/server/adapters/claude-code-local/models.ts
similarity index 63%
rename from notfair-cmo/src/server/adapters/claude-code-local/models.ts
rename to notfair/src/server/adapters/claude-code-local/models.ts
index fd636555..4552dc69 100644
--- a/notfair-cmo/src/server/adapters/claude-code-local/models.ts
+++ b/notfair/src/server/adapters/claude-code-local/models.ts
@@ -11,10 +11,12 @@ import type { HarnessModelOption } from "../types";
* point releases. Revisit if the CLI ever ships model enumeration.
*/
const ALIAS_TIERS: HarnessModelOption[] = [
- { value: "fable", label: "Fable" },
- { value: "opus", label: "Opus" },
- { value: "sonnet", label: "Sonnet" },
- { value: "haiku", label: "Haiku" },
+ // context_window: documented tier windows (Anthropic docs); the CLI
+ // exposes no model-metadata surface to read them from.
+ { value: "fable", label: "Fable", context_window: 200_000 },
+ { value: "opus", label: "Opus", context_window: 200_000 },
+ { value: "sonnet", label: "Sonnet", context_window: 200_000 },
+ { value: "haiku", label: "Haiku", context_window: 200_000 },
];
export async function listClaudeCodeModels(): Promise<HarnessModelOption[]> {
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/parse.ts b/notfair/src/server/adapters/claude-code-local/parse.ts
similarity index 100%
rename from notfair-cmo/src/server/adapters/claude-code-local/parse.ts
rename to notfair/src/server/adapters/claude-code-local/parse.ts
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/provision.ts b/notfair/src/server/adapters/claude-code-local/provision.ts
similarity index 89%
rename from notfair-cmo/src/server/adapters/claude-code-local/provision.ts
rename to notfair/src/server/adapters/claude-code-local/provision.ts
index 6f4dfbb7..db6b766e 100644
--- a/notfair-cmo/src/server/adapters/claude-code-local/provision.ts
+++ b/notfair/src/server/adapters/claude-code-local/provision.ts
@@ -6,9 +6,9 @@ import type { AgentProvisionSpec } from "../types";
* Provision a workspace for Claude Code.
*
* Layout under `<workspaceDir>/`:
- * IDENTITY.md — system prompt (notfair-cmo's source of truth)
+ * IDENTITY.md — system prompt (NotFair's source of truth)
* CLAUDE.md — same content (Claude Code auto-loads CLAUDE.md from cwd)
- * SKILL.md — shared orchestration skill text (sidecar for humans)
+ * SKILL.md — shared goal-loop skill text (sidecar for humans)
* PROJECT.md — project brief if available (sidecar for humans)
*
* No subprocess calls. Claude Code discovers the workspace lazily on first
diff --git a/notfair-cmo/src/server/adapters/claude-code-local/test.ts b/notfair/src/server/adapters/claude-code-local/test.ts
similarity index 100%
rename from notfair-cmo/src/server/adapters/claude-code-local/test.ts
rename to notfair/src/server/adapters/claude-code-local/test.ts
diff --git a/notfair-cmo/src/server/adapters/codex-local/execute.ts b/notfair/src/server/adapters/codex-local/execute.ts
similarity index 91%
rename from notfair-cmo/src/server/adapters/codex-local/execute.ts
rename to notfair/src/server/adapters/codex-local/execute.ts
index 636e740e..27e266be 100644
--- a/notfair-cmo/src/server/adapters/codex-local/execute.ts
+++ b/notfair/src/server/adapters/codex-local/execute.ts
@@ -3,7 +3,7 @@ import { readFile } from "node:fs/promises";
import { join } from "node:path";
import type { HarnessEvent, HarnessExecuteContext } from "../types";
import { makeCodexStreamState, parseCodexLine } from "./parse";
-import { bearerEnvVarForServer, CODEX_BEARER_ENV_VAR } from "./mcp";
+import { bearerEnvVarForServer } from "./mcp";
import { getOrCreateMcpServerSecret } from "@/server/mcp-server/secret";
import { listProjectMcpTokens } from "@/server/mcp/tokens";
@@ -25,11 +25,11 @@ const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
export async function* executeCodexLocal(
ctx: HarnessExecuteContext,
): AsyncGenerator<HarnessEvent, void, void> {
- // --dangerously-bypass-approvals-and-sandbox is what makes notfair-cmo
+ // --dangerously-bypass-approvals-and-sandbox is what makes NotFair
// agents useful through Codex. Without it, codex auto-cancels every
- // MCP tool call (so set_project_brief / submit_task_status etc. fail)
- // and sandboxes loopback connections to our orchestration server.
- // notfair-cmo's trust model: the user installed this app, picked
+ // MCP tool call (so set_shared_context / log_goal_action etc. fail)
+ // and sandboxes loopback connections to our local MCP servers.
+ // NotFair's trust model: the user installed this app, picked
// these agents, connected real ad accounts. The product-level
// Approvals flow gates spend / publish / channel changes; the
// OS-level sandbox would also gate things we want the agent to do
@@ -46,7 +46,7 @@ export async function* executeCodexLocal(
}
// Resume only when we have a real codex thread id from a prior turn.
- // notfair-cmo's session UUID is not a codex thread id — passing it would
+ // NotFair's session UUID is not a codex thread id — passing it would
// fail with "thread not found".
if (ctx.harnessSessionId && isUuid(ctx.harnessSessionId)) {
args.push("resume", ctx.harnessSessionId, "-");
@@ -57,9 +57,9 @@ export async function* executeCodexLocal(
// Codex resolves streamable-http MCP bearers via env var. We inject one
// env var per MCP server the project has registered so each server gets
// its OWN bearer:
- // - notfair-orchestration: shared per-machine secret
+ // - notfair-goals: shared per-machine secret
// - notfair-browser: same shared per-machine secret (both are
- // internal notfair-cmo servers on loopback)
+ // internal NotFair servers on loopback)
// - notfair-googleads, gsc, etc.: per-project OAuth token from
// `mcp_tokens`
// Without per-server env vars every MCP would auth with the same
@@ -67,7 +67,7 @@ export async function* executeCodexLocal(
// or pass the wrong token to the wrong server.
const mcpSecret = getOrCreateMcpServerSecret();
const mcpEnv: Record<string, string> = {
- [CODEX_BEARER_ENV_VAR]: mcpSecret,
+ [bearerEnvVarForServer("notfair-goals")]: mcpSecret,
[bearerEnvVarForServer("notfair-browser")]: mcpSecret,
};
for (const token of listProjectMcpTokens(ctx.projectSlug)) {
diff --git a/notfair-cmo/src/server/adapters/codex-local/index.ts b/notfair/src/server/adapters/codex-local/index.ts
similarity index 100%
rename from notfair-cmo/src/server/adapters/codex-local/index.ts
rename to notfair/src/server/adapters/codex-local/index.ts
diff --git a/notfair-cmo/src/server/adapters/codex-local/mcp.ts b/notfair/src/server/adapters/codex-local/mcp.ts
similarity index 66%
rename from notfair-cmo/src/server/adapters/codex-local/mcp.ts
rename to notfair/src/server/adapters/codex-local/mcp.ts
index 463442b3..76cfa068 100644
--- a/notfair-cmo/src/server/adapters/codex-local/mcp.ts
+++ b/notfair/src/server/adapters/codex-local/mcp.ts
@@ -9,7 +9,7 @@ import type { McpRegistrationSpec } from "../types";
*
* Codex reads MCP servers from `~/.codex/config.toml` — a single global file
* shared across every project and agent on the machine. MCP tokens in
- * notfair-cmo are project-scoped (one (project, server) pair → one bearer
+ * NotFair are project-scoped (one (project, server) pair → one bearer
* shared by every agent in the project), so we namespace by project slug:
* `notfair_<projectSlug>__<serverName>`. Every agent in the same project
* sees the same entry; sibling projects don't duplicate.
@@ -70,9 +70,9 @@ function escapeRe(s: string): string {
/**
* Each codex MCP registration gets its OWN env var name carrying its
* bearer. Encodes the server name into the env so different MCPs in the
- * same agent's config (orchestration, Google Ads, GSC, ...) can carry
+ * same agent's config (goals, Google Ads, GSC, ...) can carry
* different bearers. The spawn site (execute.ts) iterates the project's
- * `mcp_tokens` table + the orchestration secret and injects matching
+ * `mcp_tokens` table + the internal-server secret and injects matching
* env vars before invoking codex.
*
* Why env vars and not literal headers: codex 0.132+ marks raw
@@ -81,23 +81,10 @@ function escapeRe(s: string): string {
* path is the documented way.
*/
export function bearerEnvVarForServer(serverName: string): string {
- // Orchestration kept on its dedicated, well-known env var so older
- // configs written before per-server env vars existed keep working.
- if (serverName === "notfair-orchestration") {
- return CODEX_BEARER_ENV_VAR;
- }
const safe = serverName.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase();
return `NOTFAIR_MCP_BEARER__${safe}`;
}
-/**
- * Dedicated env var for the notfair-orchestration MCP. Kept distinct
- * from the generic `NOTFAIR_MCP_BEARER__*` scheme so existing
- * `~/.codex/config.toml` entries written before per-server env vars
- * existed keep authenticating without a forced re-registration.
- */
-export const CODEX_BEARER_ENV_VAR = "NOTFAIR_ORCHESTRATION_BEARER";
-
function renderServer(spec: McpRegistrationSpec): string {
const header = `[mcp_servers.${namespaced(spec.serverName, spec.projectSlug)}]`;
if (spec.transport.type === "stdio") {
@@ -155,48 +142,3 @@ export async function unregisterCodexMcp(
await writeFile(codexConfigPath(), toml.trimStart(), "utf8");
}
-/**
- * Strip `[mcp_servers.notfair_<prefix>__<server>]` sections from the global
- * Codex config when `<prefix>` is not the slug of any currently-known
- * project. Catches two kinds of orphans:
- *
- * 1. Legacy per-agent entries written before per-project namespacing
- * (`notfair_demo1_cmo_greg__notfair_googleads`) — the prefix is an
- * agent id, not a project slug.
- * 2. Entries from projects that have since been deleted without going
- * through cascade-delete (manual db edits, crashes mid-delete).
- *
- * Returns the number of sections removed. Best-effort: leaves the file
- * untouched on parse errors.
- */
-export async function pruneOrphanCodexNamespaces(
- activeProjectSlugs: ReadonlySet<string>,
-): Promise<number> {
- const toml = await readConfig();
- if (!toml) return 0;
- // Project slugs in the namespace use `_` where the slug uses `-`, so
- // normalize both sides for comparison.
- const validPrefixes = new Set(
- Array.from(activeProjectSlugs, (s) => s.replace(/-/g, "_")),
- );
- // Match `[mcp_servers.notfair_<prefix>__<rest>]` and capture the prefix.
- // The prefix is greedy-up-to-the-final-`__` so multi-underscore agent ids
- // (`acme_cmo_greg`) collapse to one capture.
- const headerRe = /\[mcp_servers\.notfair_([A-Za-z0-9_]+?)__[A-Za-z0-9_]+\]/g;
- const orphans = new Set<string>();
- for (const m of toml.matchAll(headerRe)) {
- const prefix = m[1];
- if (!validPrefixes.has(prefix)) {
- // Strip the leading `[mcp_servers.` + trailing `]` to get the section
- // header `stripSection` expects.
- orphans.add(m[0].slice(1, -1));
- }
- }
- if (orphans.size === 0) return 0;
- let next = toml;
- for (const section of orphans) {
- next = stripSection(next, section);
- }
- await writeFile(codexConfigPath(), next.trimStart(), "utf8");
- return orphans.size;
-}
diff --git a/notfair-cmo/src/server/adapters/codex-local/models.ts b/notfair/src/server/adapters/codex-local/models.ts
similarity index 92%
rename from notfair-cmo/src/server/adapters/codex-local/models.ts
rename to notfair/src/server/adapters/codex-local/models.ts
index 6118b4b0..4d3dbbfd 100644
--- a/notfair-cmo/src/server/adapters/codex-local/models.ts
+++ b/notfair/src/server/adapters/codex-local/models.ts
@@ -27,6 +27,7 @@ type CachedModel = {
display_name?: unknown;
visibility?: unknown;
priority?: unknown;
+ context_window?: unknown;
};
const FALLBACK: HarnessModelOption[] = [
@@ -55,6 +56,9 @@ export async function listCodexModels(
.map<HarnessModelOption>((m) => ({
value: m.slug,
label: typeof m.display_name === "string" && m.display_name ? m.display_name : m.slug,
+ ...(typeof m.context_window === "number" && m.context_window > 0
+ ? { context_window: m.context_window }
+ : {}),
}));
return models.length > 0 ? models : FALLBACK;
} catch {
diff --git a/notfair-cmo/src/server/adapters/codex-local/parse.ts b/notfair/src/server/adapters/codex-local/parse.ts
similarity index 100%
rename from notfair-cmo/src/server/adapters/codex-local/parse.ts
rename to notfair/src/server/adapters/codex-local/parse.ts
diff --git a/notfair-cmo/src/server/adapters/codex-local/provision.ts b/notfair/src/server/adapters/codex-local/provision.ts
similarity index 87%
rename from notfair-cmo/src/server/adapters/codex-local/provision.ts
rename to notfair/src/server/adapters/codex-local/provision.ts
index 09dc197e..d62c2d9d 100644
--- a/notfair-cmo/src/server/adapters/codex-local/provision.ts
+++ b/notfair/src/server/adapters/codex-local/provision.ts
@@ -6,9 +6,9 @@ import type { AgentProvisionSpec } from "../types";
* Provision a workspace for Codex CLI.
*
* Layout under `<workspaceDir>/`:
- * IDENTITY.md — notfair-cmo source of truth (also written so humans see it)
+ * IDENTITY.md — NotFair source of truth (also written so humans see it)
* AGENTS.md — same content; codex auto-loads AGENTS.md from cwd
- * SKILL.md — shared orchestration skill text
+ * SKILL.md — the goal-loop skill text
* PROJECT.md — project brief if available
*/
export async function provisionCodexAgent(spec: AgentProvisionSpec): Promise<void> {
diff --git a/notfair-cmo/src/server/adapters/codex-local/test.ts b/notfair/src/server/adapters/codex-local/test.ts
similarity index 100%
rename from notfair-cmo/src/server/adapters/codex-local/test.ts
rename to notfair/src/server/adapters/codex-local/test.ts
diff --git a/notfair-cmo/src/server/adapters/display-registry.ts b/notfair/src/server/adapters/display-registry.ts
similarity index 100%
rename from notfair-cmo/src/server/adapters/display-registry.ts
rename to notfair/src/server/adapters/display-registry.ts
diff --git a/notfair-cmo/src/server/adapters/registry.ts b/notfair/src/server/adapters/registry.ts
similarity index 100%
rename from notfair-cmo/src/server/adapters/registry.ts
rename to notfair/src/server/adapters/registry.ts
diff --git a/notfair-cmo/src/server/adapters/types.ts b/notfair/src/server/adapters/types.ts
similarity index 88%
rename from notfair-cmo/src/server/adapters/types.ts
rename to notfair/src/server/adapters/types.ts
index 6210a1c7..1c345205 100644
--- a/notfair-cmo/src/server/adapters/types.ts
+++ b/notfair/src/server/adapters/types.ts
@@ -1,7 +1,7 @@
/**
- * HarnessAdapter — notfair-cmo's plug-in shape for a local AI coding agent.
+ * HarnessAdapter — NotFair's plug-in shape for a local AI coding agent.
*
- * Inspired by paperclip's ServerAdapterModule but pared down: notfair-cmo runs
+ * Inspired by paperclip's ServerAdapterModule but pared down: NotFair runs
* locally only, so there's no remote execution target, no workspace bridge,
* no skill catalog interop. An adapter only needs to:
*
@@ -11,7 +11,7 @@
* 4. Register / unregister an MCP server for an agent — registerMcp / unregisterMcp
*
* Everything else (cron, MCP token storage, session/transcript persistence,
- * agent metadata) lives in notfair-cmo and is shared across adapters.
+ * agent metadata) lives in NotFair and is shared across adapters.
*/
export type HarnessAdapterId = "claude-code-local" | "codex-local";
@@ -30,17 +30,17 @@ export interface HarnessEnvironmentHealth {
export interface AgentProvisionSpec {
/** Project slug (e.g. "acme"). */
projectSlug: string;
- /** Agent backend id (e.g. "acme-cmo-greg"). */
+ /** Agent backend id (e.g. "acme-goal-1"). */
agentId: string;
/** Personal display name (e.g. "Greg"). */
displayName: string;
- /** Role / template key (e.g. "cmo", "google_ads"). */
+ /** Template key (goal agents use "goal"). */
templateKey: string;
/** Absolute path to the agent's workspace directory. */
workspaceDir: string;
/** The fully-rendered IDENTITY.md the agent should run with. */
identityMd: string;
- /** The shared SKILL.md (orchestration MCP usage etc.). Optional sidecar copy. */
+ /** The shared SKILL.md (goals MCP usage etc.). Optional sidecar copy. */
skillMd?: string;
/** PROJECT.md context, if a project brief exists yet. */
projectMd?: string;
@@ -62,7 +62,7 @@ export interface McpRegistrationSpec {
/**
* Execution context for one chat turn.
*
- * The adapter knows nothing about notfair-cmo SQLite or routes — it gets the
+ * The adapter knows nothing about NotFair SQLite or routes — it gets the
* raw inputs it needs (agent identity, workspace, message), runs the harness,
* and yields HarnessEvents that the caller serializes onto SSE / persists.
*/
@@ -73,7 +73,7 @@ export interface HarnessExecuteContext {
/** The user message for this turn. */
message: string;
/**
- * Stable thread identifier owned by notfair-cmo (the `sessions.id` UUID).
+ * Stable thread identifier owned by NotFair (the `sessions.id` UUID).
* Adapters MUST NOT pass this to their CLI's resume flag — the harness
* doesn't know it. Used only for logging / correlation.
*/
@@ -132,6 +132,11 @@ export interface HarnessModelOption {
value: string;
/** Human label for the dropdown. */
label: string;
+ /**
+ * Input context window in tokens, when the provider exposes it (codex
+ * publishes it in models_cache.json). Absent when unknown.
+ */
+ context_window?: number;
}
export interface HarnessAdapter {
diff --git a/notfair/src/server/agent-meta.ts b/notfair/src/server/agent-meta.ts
new file mode 100644
index 00000000..727b5599
--- /dev/null
+++ b/notfair/src/server/agent-meta.ts
@@ -0,0 +1,144 @@
+import { existsSync, readFileSync } from "node:fs";
+import { mkdir, writeFile, readdir, stat } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+/**
+ * Per-agent meta sidecar (`notfair-meta.json` in the agent's workspace
+ * dir). Agent = goal: every agent is a goal agent, so the sidecar is the
+ * single source of truth for the project's roster — no templates, no
+ * seeded placeholders. Authored at agent-create time, read by the sidebar
+ * and slug resolution.
+ */
+
+export type AgentMeta = {
+ /** Full agent id, e.g. `acme-goal-alex`. */
+ agent_id: string;
+ /** Project slug this agent belongs to. */
+ project_slug: string;
+ /**
+ * Personal name the user assigned (e.g. "Alex"). IMMUTABLE — set once
+ * at agent-create time; the agent_id and URL slug encode it.
+ */
+ name: string;
+ /** URL slug, e.g. `goal-alex`. */
+ slug?: string;
+ /** When cloned, the source agentId. (Legacy field; unused today.) */
+ source_agent_id?: string;
+ created_at: string;
+};
+
+function notfairDataDir(): string {
+ return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
+}
+
+function metaPath(agentId: string): string {
+ return join(notfairDataDir(), "agents", agentId, "notfair-meta.json");
+}
+
+export async function writeAgentMeta(meta: AgentMeta): Promise<void> {
+ const path = metaPath(meta.agent_id);
+ await mkdir(join(path, ".."), { recursive: true });
+ await writeFile(path, JSON.stringify(meta, null, 2), "utf8");
+}
+
+export function readAgentMeta(agentId: string): AgentMeta | null {
+ const path = metaPath(agentId);
+ if (!existsSync(path)) return null;
+ try {
+ return JSON.parse(readFileSync(path, "utf8")) as AgentMeta;
+ } catch {
+ return null;
+ }
+}
+
+/** Has this agent's workspace been provisioned on disk? */
+export async function agentExistsOnDisk(agentId: string): Promise<boolean> {
+ try {
+ const s = await stat(join(notfairDataDir(), "agents", agentId));
+ return s.isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+export type ProjectAgentEntry = {
+ agent_id: string;
+ /** URL slug, e.g. `goal-alex`. */
+ slug: string;
+ /** Personal name (e.g. "Alex"). */
+ name: string;
+ source_agent_id?: string;
+ created_at?: string;
+};
+
+/**
+ * List agents for a project — the meta sidecars whose `project_slug`
+ * field equals the requested slug. The sidecar (not the dir-name prefix)
+ * is authoritative, so projects whose slug is a string prefix of another
+ * ("acme" vs "acme-q4") never cross-leak rosters.
+ */
+export async function listProjectAgents(project_slug: string): Promise<ProjectAgentEntry[]> {
+ const agentsRoot = join(notfairDataDir(), "agents");
+ let entries: string[] = [];
+ try {
+ entries = await readdir(agentsRoot);
+ } catch {
+ return [];
+ }
+ const prefix = `${project_slug}-`;
+ const result: ProjectAgentEntry[] = [];
+ for (const entry of entries) {
+ if (!entry.startsWith(prefix)) continue;
+ const meta = readAgentMeta(entry);
+ if (!meta) continue;
+ if (meta.project_slug !== project_slug) continue;
+ result.push({
+ agent_id: meta.agent_id,
+ slug: meta.slug ?? slugifyForMeta(meta.name),
+ name: meta.name,
+ source_agent_id: meta.source_agent_id,
+ created_at: meta.created_at,
+ });
+ }
+ // Stable order: creation time, oldest first (sidebar reads top-down).
+ return result.sort((a, b) =>
+ (a.created_at ?? "").localeCompare(b.created_at ?? ""),
+ );
+}
+
+/** Workspace dir for an agent. */
+export function workspaceDirFor(agentId: string): string {
+ return join(notfairDataDir(), "agents", agentId);
+}
+
+/** Fallback slug for sidecars written before `slug` was recorded. */
+function slugifyForMeta(s: string): string {
+ return `goal-${s
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 32)}`;
+}
+
+export type ResolvedAgent = {
+ agent_id: string;
+ /** Personal name (e.g. "Alex"). */
+ name: string;
+ slug: string;
+};
+
+/**
+ * Resolve a URL slug to its full agent_id within the current project.
+ * Returns null when no project agent matches the slug.
+ */
+export async function resolveAgentBySlug(
+ project_slug: string,
+ url_slug: string,
+): Promise<ResolvedAgent | null> {
+ const all = await listProjectAgents(project_slug);
+ const hit = all.find((a) => a.slug === url_slug);
+ if (!hit) return null;
+ return { agent_id: hit.agent_id, name: hit.name, slug: hit.slug };
+}
diff --git a/notfair-cmo/src/server/agents/cascade-delete.ts b/notfair/src/server/agents/cascade-delete.ts
similarity index 82%
rename from notfair-cmo/src/server/agents/cascade-delete.ts
rename to notfair/src/server/agents/cascade-delete.ts
index 13f2f2a7..04f11561 100644
--- a/notfair-cmo/src/server/agents/cascade-delete.ts
+++ b/notfair/src/server/agents/cascade-delete.ts
@@ -1,9 +1,7 @@
import { existsSync } from "node:fs";
import { rm } from "node:fs/promises";
-import type { AgentTemplate } from "@/server/agent-templates";
import { listProjectAgents } from "@/server/agent-meta";
import { getMcpCatalog } from "@/server/mcp-catalog";
-import { listCronsForProject } from "@/server/scheduler/display";
import { listProjectMcpTokens, deleteProjectMcpTokens } from "@/server/mcp/tokens";
import { listAgentSessions } from "@/server/sessions";
import { workspaceDirFor } from "./provisioning";
@@ -12,7 +10,6 @@ import { requireAdapter } from "@/server/adapters/registry";
import { getDb } from "@/server/db/db";
export interface ProjectDeletionAgentSummary {
- template?: AgentTemplate["key"];
display_name: string;
agentId: string;
exists: boolean;
@@ -33,7 +30,6 @@ export interface ProjectDeletionSummary {
totals: {
agents: number;
threads: number;
- crons: number;
mcps: number;
};
}
@@ -51,7 +47,6 @@ export async function getProjectDeletionSummary(
const exists = existsSync(dir);
const threadCount = exists ? listAgentSessions(project_slug, e.agent_id).length : 0;
return {
- template: e.template_key,
display_name: e.name,
agentId: e.agent_id,
exists,
@@ -59,14 +54,6 @@ export async function getProjectDeletionSummary(
};
});
- let cronCount = 0;
- try {
- const view = await listCronsForProject(project_slug);
- cronCount = view.groups.reduce((acc, g) => acc + g.crons.length, 0);
- } catch {
- // best-effort
- }
-
// MCP connections live in the mcp_tokens table now. Per-catalog "configured"
// status is derived from whether a token row exists for the (project, server)
// pair.
@@ -88,7 +75,6 @@ export async function getProjectDeletionSummary(
totals: {
agents: agents.filter((a) => a.exists).length,
threads: agents.reduce((acc, a) => acc + a.threadCount, 0),
- crons: cronCount,
mcps: mcps.filter((m) => m.configured).length,
},
};
@@ -96,10 +82,9 @@ export async function getProjectDeletionSummary(
/**
* Hard-delete every artifact tied to a project that lives outside the
- * `projects` row's own FK cascade: agent workspace dirs, the project's
- * scheduled jobs (and their runs), sessions + transcripts, MCP tokens.
- * The caller is expected to then call `deleteProjectRow()` to drop the
- * projects row itself + the FK-cascading children (tasks, approvals, etc).
+ * `projects` row's own FK cascade: agent workspace dirs, sessions +
+ * transcripts, MCP tokens. The caller is expected to then call
+ * `deleteProjectRow()` to drop the projects row itself.
*/
export async function cascadeDeleteProjectArtifacts(project_slug: string): Promise<void> {
const project = getProject(project_slug);
@@ -119,17 +104,17 @@ export async function cascadeDeleteProjectArtifacts(project_slug: string): Promi
// Unregister any MCP servers the adapter wrote into its config (so codex
// global config doesn't leak rows for deleted projects, and claude-code
// workspaces don't reference dead bearers). This must cover the two
- // INTERNAL servers (orchestration + browser) that provisioning registers
+ // INTERNAL servers (goals + browser) that provisioning registers
// for every agent, not just the external catalog — they used to be
// skipped here and leaked [mcp_servers.notfair_<slug>__…] entries into
// ~/.codex/config.toml for every deleted project.
if (adapter) {
- const { ORCHESTRATION_MCP_KEY, BROWSER_MCP_KEY } = await import(
+ const { GOALS_MCP_KEY, BROWSER_MCP_KEY } = await import(
"@/server/mcp-server/registration"
);
const serverNames = [
...getMcpCatalog(project_slug).map((spec) => spec.key),
- ORCHESTRATION_MCP_KEY,
+ GOALS_MCP_KEY,
BROWSER_MCP_KEY,
];
for (const agent of agents) {
@@ -156,11 +141,6 @@ export async function cascadeDeleteProjectArtifacts(project_slug: string): Promi
}
}
- // Drop scheduled jobs (run rows cascade).
- getDb()
- .prepare("DELETE FROM scheduled_jobs WHERE project_slug = ?")
- .run(project_slug);
-
// Drop sessions (transcript_events cascade).
getDb()
.prepare("DELETE FROM sessions WHERE project_slug = ?")
diff --git a/notfair-cmo/src/server/agents/clone.ts b/notfair/src/server/agents/clone.ts
similarity index 75%
rename from notfair-cmo/src/server/agents/clone.ts
rename to notfair/src/server/agents/clone.ts
index eaecd202..c694ac21 100644
--- a/notfair-cmo/src/server/agents/clone.ts
+++ b/notfair/src/server/agents/clone.ts
@@ -3,12 +3,8 @@ import { existsSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { slugify } from "@/lib/slug";
import { workspaceDirFor } from "@/server/agents/provisioning";
-import { writeAgentMeta, readAgentMeta } from "@/server/agent-meta";
+import { writeAgentMeta } from "@/server/agent-meta";
import { getDb } from "@/server/db/db";
-import {
- listAgentScheduledJobs,
- createScheduledJob,
-} from "@/server/scheduler";
export interface CloneAgentInput {
source_agent_id: string;
@@ -19,19 +15,11 @@ export interface CloneAgentInput {
slug_is_canonical?: boolean;
}
-export interface CloneSourceCron {
- id: string;
- name: string;
- disabled: boolean;
-}
-
export interface CloneAgentResult {
new_agent_id: string;
new_slug: string;
files_copied: number;
sessions_copied: number;
- source_crons: CloneSourceCron[];
- new_cron_ids: string[];
}
/**
@@ -70,39 +58,14 @@ export async function cloneAgent(input: CloneAgentInput): Promise<CloneAgentResu
filesCopied = 1; // we don't enumerate; the dir is intact
}
- // Clone scheduled jobs.
- const srcJobs = listAgentScheduledJobs(input.project_slug, input.source_agent_id);
- const sourceCrons: CloneSourceCron[] = srcJobs.map((j) => ({
- id: j.id,
- name: j.name,
- disabled: j.enabled === 0,
- }));
- const newCronIds: string[] = [];
- for (const j of srcJobs) {
- try {
- const cloned = createScheduledJob({
- project_slug: input.project_slug,
- agent_id: newAgentId,
- name: j.name,
- cron_expr: j.cron_expr,
- message: j.message,
- enabled: j.enabled === 1,
- });
- newCronIds.push(cloned.id);
- } catch (err) {
- console.error("[clone] failed to copy cron:", err);
- }
- }
const displayName = (input.display_name ?? input.source_agent_id).trim() || input.source_agent_id;
- const sourceMeta = readAgentMeta(input.source_agent_id);
await writeAgentMeta({
agent_id: newAgentId,
project_slug: input.project_slug,
slug: newSlug,
name: displayName,
source_agent_id: input.source_agent_id,
- template_key: sourceMeta?.template_key,
created_at: new Date().toISOString(),
});
@@ -112,8 +75,6 @@ export async function cloneAgent(input: CloneAgentInput): Promise<CloneAgentResu
files_copied: filesCopied,
// sessions deliberately not copied — new agent starts fresh
sessions_copied: 0,
- source_crons: sourceCrons,
- new_cron_ids: newCronIds,
};
}
diff --git a/notfair-cmo/src/server/agents/files.ts b/notfair/src/server/agents/files.ts
similarity index 92%
rename from notfair-cmo/src/server/agents/files.ts
rename to notfair/src/server/agents/files.ts
index 356c9f1f..2e63a2a8 100644
--- a/notfair-cmo/src/server/agents/files.ts
+++ b/notfair/src/server/agents/files.ts
@@ -4,8 +4,8 @@ import { join } from "node:path";
import { workspaceDirFor } from "./provisioning";
/**
- * Workspace file listing + reading. notfair-cmo owns the agent workspace
- * dir under `~/.notfair-cmo/agents/<id>/`, so file IO is a direct fs read
+ * Workspace file listing + reading. NotFair owns the agent workspace
+ * dir under `~/.notfair/agents/<id>/`, so file IO is a direct fs read
* — no harness subprocess or RPC needed.
*/
export interface AgentFileEntry {
diff --git a/notfair-cmo/src/server/agents/provisioning.ts b/notfair/src/server/agents/provisioning.ts
similarity index 92%
rename from notfair-cmo/src/server/agents/provisioning.ts
rename to notfair/src/server/agents/provisioning.ts
index 9c6b5ba5..0b32e793 100644
--- a/notfair-cmo/src/server/agents/provisioning.ts
+++ b/notfair/src/server/agents/provisioning.ts
@@ -5,11 +5,11 @@ import type { HarnessAdapterId, AgentProvisionSpec } from "@/server/adapters/typ
/**
* Generic agent provisioning. The adapter writes whatever workspace files
- * the harness needs (IDENTITY.md, CLAUDE.md, AGENTS.md, etc.) — notfair-cmo
+ * the harness needs (IDENTITY.md, CLAUDE.md, AGENTS.md, etc.) — NotFair
* supplies the rendered prompt content + workspace path.
*/
export function workspaceDirFor(agentId: string): string {
- const dataDir = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+ const dataDir = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
return join(dataDir, "agents", agentId);
}
diff --git a/notfair-cmo/src/server/browser/actions.ts b/notfair/src/server/browser/actions.ts
similarity index 100%
rename from notfair-cmo/src/server/browser/actions.ts
rename to notfair/src/server/browser/actions.ts
diff --git a/notfair-cmo/src/server/browser/chrome.ts b/notfair/src/server/browser/chrome.ts
similarity index 99%
rename from notfair-cmo/src/server/browser/chrome.ts
rename to notfair/src/server/browser/chrome.ts
index c0195f25..7096269a 100644
--- a/notfair-cmo/src/server/browser/chrome.ts
+++ b/notfair/src/server/browser/chrome.ts
@@ -4,7 +4,7 @@
* Discovers a Chromium-family browser binary, builds launch args for a
* managed instance pointed at a workspace user-data-dir, starts it on a
* known CDP port, waits for the CDP endpoint to come up, and shuts it down
- * cleanly. Borrowed pattern from openclaw's chrome.ts but trimmed to the
+ * cleanly. Standard CDP pattern trimmed to the
* essentials a single-user local app needs.
*/
import { type ChildProcess, spawn } from "node:child_process";
diff --git a/notfair-cmo/src/server/browser/paths.ts b/notfair/src/server/browser/paths.ts
similarity index 84%
rename from notfair-cmo/src/server/browser/paths.ts
rename to notfair/src/server/browser/paths.ts
index 8e06133c..1fdcb6d9 100644
--- a/notfair-cmo/src/server/browser/paths.ts
+++ b/notfair/src/server/browser/paths.ts
@@ -1,14 +1,14 @@
/**
* Per-workspace browser profile path + port resolution.
*
- * Layout under ~/.notfair-cmo/ (override via NOTFAIR_CMO_DATA_DIR):
+ * Layout under ~/.notfair/ (override via NOTFAIR_DATA_DIR):
*
* projects/<slug>/browser/
* user-data/ <- Chrome --user-data-dir (cookies, login state)
* state.json <- last-launched metadata (signed_in_at, etc.)
*
* CDP ports are hashed deterministically from the project slug into the
- * 19000-19099 range. We intentionally avoid openclaw's 18800-18899 range
+ * 19000-19099 range. We intentionally avoid the 18800-18899 range other tools use
* so both can run on the same machine without colliding.
*/
import { createHash } from "node:crypto";
@@ -23,12 +23,12 @@ export const CDP_PORT_RANGE_END = 19099;
const PROJECT_SLUG_REGEX = /^[a-z0-9][a-z0-9-]*$/;
const MAX_SLUG_LENGTH = 64;
-/** Resolve the notfair-cmo data dir (matches db.ts / agent-meta.ts convention). */
+/** Resolve the NotFair data dir (matches db.ts / agent-meta.ts convention). */
export function notfairDataDir(): string {
- return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+ return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
}
-/** True when slug matches the lowercase-alphanum + hyphen format the rest of notfair-cmo uses. */
+/** True when slug matches the lowercase-alphanum + hyphen format the rest of NotFair uses. */
export function isValidProjectSlug(slug: string): boolean {
if (!slug || slug.length > MAX_SLUG_LENGTH) return false;
return PROJECT_SLUG_REGEX.test(slug);
@@ -49,7 +49,7 @@ export function resolveUserDataDir(projectSlug: string): string {
* Deterministic CDP port for a project slug.
*
* Same slug always hashes to the same port across restarts, so a relaunched
- * notfair-cmo process can reattach to a still-running Chrome without
+ * NotFair process can reattach to a still-running Chrome without
* re-discovering ports.
*/
export function allocateCdpPort(projectSlug: string): number {
diff --git a/notfair-cmo/src/server/browser/session.ts b/notfair/src/server/browser/session.ts
similarity index 98%
rename from notfair-cmo/src/server/browser/session.ts
rename to notfair/src/server/browser/session.ts
index ae556001..3d4e93c5 100644
--- a/notfair-cmo/src/server/browser/session.ts
+++ b/notfair/src/server/browser/session.ts
@@ -8,7 +8,7 @@
*
* Shutdown happens four ways:
* 1. User clicks Settings → Workspace browser → Stop (manual).
- * 2. notfair-cmo process exits — SIGINT/SIGTERM/beforeExit handlers
+ * 2. NotFair process exits — SIGINT/SIGTERM/beforeExit handlers
* registered automatically on the first launch.
* 3. User Cmd-Q's the Chrome window — process exit event evicts the
* cached session so the next browser_open relaunches.
@@ -85,7 +85,7 @@ export async function getOrLaunchBrowser(
): Promise<BrowserSession> {
// Every entry point goes through here, so this is also the right place
// to install our process-lifetime maintenance: shutdown hooks (cleanup on
- // notfair-cmo exit) + idle checker (stop unused browsers).
+ // NotFair exit) + idle checker (stop unused browsers).
registerShutdownHooks();
ensureIdleChecker();
@@ -180,7 +180,7 @@ async function launchSession(
async function defaultConnectOverCDP(cdpHttpUrl: string): Promise<Browser> {
// Lazy import keeps playwright-core out of the cold-start path for
- // notfair-cmo features that don't touch the browser.
+ // NotFair features that don't touch the browser.
const { chromium } = await import("playwright-core");
return chromium.connectOverCDP(cdpHttpUrl);
}
diff --git a/notfair-cmo/src/server/browser/tabs.ts b/notfair/src/server/browser/tabs.ts
similarity index 98%
rename from notfair-cmo/src/server/browser/tabs.ts
rename to notfair/src/server/browser/tabs.ts
index 7dec27f1..560cb5bd 100644
--- a/notfair-cmo/src/server/browser/tabs.ts
+++ b/notfair/src/server/browser/tabs.ts
@@ -1,7 +1,7 @@
/**
* Labeled-tab registry for a workspace browser session.
*
- * Each agent gets a stable handle ("greg-cmo", "tina-googleads", or an
+ * Each agent gets a stable handle (its agent id, or an
* auto-generated "t1", "t2", ...) that survives across MCP tool calls.
* Pages added/removed from the underlying BrowserContext are reconciled so
* agent-supplied targetIds keep resolving even when the user opens or
@@ -129,7 +129,7 @@ export interface OpenTabOptions {
/**
* Open a new tab. If `label` is supplied and already exists, reuses the
- * existing tab and (optionally) navigates it — this matches the openclaw
+ * existing tab and (optionally) navigates it — this matches the
* "reuse labeled tab" pattern that avoids duplicates on retries.
*/
export async function openTab(
diff --git a/notfair/src/server/db/db.ts b/notfair/src/server/db/db.ts
new file mode 100644
index 00000000..b99c8e55
--- /dev/null
+++ b/notfair/src/server/db/db.ts
@@ -0,0 +1,32 @@
+import { existsSync, mkdirSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import Database from "better-sqlite3";
+import { SCHEMA } from "./schema";
+
+const DEFAULT_DATA_DIR = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
+const DB_PATH = join(DEFAULT_DATA_DIR, "db.sqlite");
+
+let cached: Database.Database | null = null;
+
+export function getDb(): Database.Database {
+ if (cached) return cached;
+
+ if (!existsSync(DEFAULT_DATA_DIR)) {
+ mkdirSync(DEFAULT_DATA_DIR, { recursive: true, mode: 0o700 });
+ }
+
+ const db = new Database(DB_PATH);
+ db.pragma("journal_mode = WAL");
+ db.pragma("foreign_keys = ON");
+ db.pragma("busy_timeout = 5000");
+
+ db.exec(SCHEMA);
+
+ cached = db;
+ return db;
+}
+
+export function getDbPath(): string {
+ return DB_PATH;
+}
diff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.ts
new file mode 100644
index 00000000..b7e992fa
--- /dev/null
+++ b/notfair/src/server/db/goals.ts
@@ -0,0 +1,816 @@
+import { randomUUID } from "node:crypto";
+import { CronExpressionParser } from "cron-parser";
+import { getDb } from "./db";
+
+/**
+ * Data layer for the goal-driven agent loop.
+ *
+ * The goal row IS the loop's state machine — the agent's context window is
+ * disposable, so everything a tick needs to orient (metric spec, open
+ * actions, learnings, history) lives here. Status flow:
+ *
+ * intake ──▶ proposed ──▶ active ⇄ paused
+ * │
+ * ▼
+ * achieved | failed | killed (terminal)
+ *
+ * intake — goal agent is authoring + testing the metric query
+ * proposed — metric verified server-side, baseline measured; awaiting the
+ * user's confirmation of target/deadline/envelope
+ * active — heartbeat ticks run on cadence_cron
+ */
+
+export type GoalStatus =
+ | "intake"
+ | "proposed"
+ | "active"
+ | "paused"
+ | "achieved"
+ | "failed"
+ | "killed";
+
+export const GOAL_LIVE_STATUSES: GoalStatus[] = [
+ "intake",
+ "proposed",
+ "active",
+ "paused",
+];
+
+export const GOAL_TERMINAL_STATUSES: GoalStatus[] = [
+ "achieved",
+ "failed",
+ "killed",
+];
+
+export type MetricDirection = "increase" | "decrease";
+
+/** achieve = complete when the target is reached. maintain = hold the
+ * number there indefinitely; target met is the steady state. */
+export type GoalMode = "achieve" | "maintain";
+
+export type Goal = {
+ id: string;
+ project_slug: string;
+ agent_id: string;
+ statement: string;
+ /** Compact display label ("Wasted X spend → $0"), written by the agent
+ * during define_goal. Display falls back to a trimmed statement. */
+ short_label: string | null;
+ status: GoalStatus;
+ status_reason: string | null;
+ metric_name: string | null;
+ metric_source_key: string | null;
+ metric_source_tool: string | null;
+ metric_source_args_json: string | null;
+ metric_direction: MetricDirection | null;
+ baseline_value: number | null;
+ current_value: number | null;
+ target_value: number | null;
+ mode: GoalMode;
+ deadline: string | null;
+ spend_envelope_usd: number | null;
+ cadence_cron: string;
+ next_tick_at: string | null;
+ last_tick_at: string | null;
+ tick_count: number;
+ created_at: string;
+ updated_at: string;
+};
+
+export type GoalActionKind = "mutation" | "research" | "decision";
+export type GoalActionStatus = "open" | "reviewed" | "abandoned";
+
+export type GoalAction = {
+ id: string;
+ goal_id: string;
+ tick_number: number | null;
+ kind: GoalActionKind;
+ description: string;
+ resources_touched_json: string;
+ expected_effect: string;
+ review_after: string | null;
+ spend_usd: number | null;
+ status: GoalActionStatus;
+ observed_outcome: string | null;
+ reviewed_at: string | null;
+ created_at: string;
+};
+
+export type GoalMetricSnapshot = {
+ id: string;
+ goal_id: string;
+ value: number;
+ source: "intake" | "tick" | "manual" | "backfill";
+ created_at: string;
+};
+
+export type GoalLearning = {
+ id: string;
+ goal_id: string;
+ body: string;
+ confidence: "low" | "medium" | "high";
+ superseded_by: string | null;
+ created_at: string;
+};
+
+export type GoalTickTrigger = "heartbeat" | "manual" | "approval" | "intake";
+export type GoalTickStatus = "running" | "done" | "failed";
+
+export type GoalTick = {
+ id: string;
+ goal_id: string;
+ tick_number: number;
+ trigger_kind: GoalTickTrigger;
+ session_id: string | null;
+ metric_value: number | null;
+ metric_error: string | null;
+ status: GoalTickStatus;
+ summary: string | null;
+ started_at: string;
+ finished_at: string | null;
+};
+
+function now(): string {
+ return new Date().toISOString();
+}
+
+function computeNextTick(cron_expr: string, from = new Date()): string | null {
+ try {
+ const it = CronExpressionParser.parse(cron_expr, { currentDate: from, tz: "UTC" });
+ return it.next().toISOString();
+ } catch {
+ return null;
+ }
+}
+
+// ── goals ────────────────────────────────────────────────────────────────
+
+export type CreateGoalInput = {
+ project_slug: string;
+ agent_id: string;
+ /** Empty at agent creation — the user articulates it in chat and the
+ * agent records it via the define_goal tool. */
+ statement?: string;
+ deadline?: string | null;
+ spend_envelope_usd?: number | null;
+ cadence_cron?: string;
+};
+
+/**
+ * Insert a new goal in `intake`. Agent = goal: each agent owns exactly one
+ * live goal (partial unique index on agent_id enforces it at the DB level;
+ * we pre-check to control the message).
+ */
+export function createGoal(input: CreateGoalInput): Goal {
+ const db = getDb();
+ if (getGoalForAgent(input.agent_id)) {
+ throw new Error(
+ `Agent '${input.agent_id}' already has a live goal.`,
+ );
+ }
+ const id = randomUUID();
+ const ts = now();
+ db.prepare(
+ `INSERT INTO goals
+ (id, project_slug, agent_id, statement, status, cadence_cron,
+ deadline, spend_envelope_usd, created_at, updated_at)
+ VALUES (?, ?, ?, ?, 'intake', ?, ?, ?, ?, ?)`,
+ ).run(
+ id,
+ input.project_slug,
+ input.agent_id,
+ input.statement ?? "",
+ input.cadence_cron ?? "0 16 * * *",
+ input.deadline ?? null,
+ input.spend_envelope_usd ?? null,
+ ts,
+ ts,
+ );
+ return getGoal(id)!;
+}
+
+export function getGoal(id: string): Goal | null {
+ const row = getDb().prepare("SELECT * FROM goals WHERE id = ?").get(id);
+ return (row as Goal) ?? null;
+}
+
+/** The agent's one live goal (intake/proposed/active/paused), if any. */
+export function getGoalForAgent(agent_id: string): Goal | null {
+ const row = getDb()
+ .prepare(
+ `SELECT * FROM goals
+ WHERE agent_id = ?
+ AND status IN ('intake','proposed','active','paused')
+ LIMIT 1`,
+ )
+ .get(agent_id);
+ return (row as Goal) ?? null;
+}
+
+/** The agent's most recent goal, any status — terminal goals stay visible
+ * on the agent's page as history (the achievement IS the payoff). */
+export function getLatestGoalForAgent(agent_id: string): Goal | null {
+ const row = getDb()
+ .prepare(
+ "SELECT * FROM goals WHERE agent_id = ? ORDER BY created_at DESC, rowid DESC LIMIT 1",
+ )
+ .get(agent_id);
+ return (row as Goal) ?? null;
+}
+
+/** Every live goal in the project — one per agent. */
+export function listLiveGoals(project_slug: string): Goal[] {
+ return getDb()
+ .prepare(
+ `SELECT * FROM goals
+ WHERE project_slug = ?
+ AND status IN ('intake','proposed','active','paused')
+ ORDER BY created_at ASC`,
+ )
+ .all(project_slug) as Goal[];
+}
+
+/**
+ * Chat-intake step 1: record what the user wants (statement) plus any
+ * constraints they stated. Only while the goal is still in intake.
+ */
+export function defineGoal(
+ id: string,
+ input: {
+ statement: string;
+ short_label?: string | null;
+ deadline?: string | null;
+ spend_envelope_usd?: number | null;
+ },
+): Goal | null {
+ const r = getDb()
+ .prepare(
+ `UPDATE goals
+ SET statement = ?, short_label = COALESCE(?, short_label),
+ deadline = COALESCE(?, deadline),
+ spend_envelope_usd = COALESCE(?, spend_envelope_usd), updated_at = ?
+ WHERE id = ? AND status = 'intake'`,
+ )
+ .run(
+ input.statement,
+ input.short_label ?? null,
+ input.deadline ?? null,
+ input.spend_envelope_usd ?? null,
+ now(),
+ id,
+ );
+ if (r.changes === 0) return null;
+ return getGoal(id);
+}
+
+export function listGoals(project_slug: string): Goal[] {
+ return getDb()
+ .prepare("SELECT * FROM goals WHERE project_slug = ? ORDER BY created_at DESC")
+ .all(project_slug) as Goal[];
+}
+
+export type GoalMetricSpec = {
+ metric_name: string;
+ metric_source_key: string;
+ metric_source_tool: string;
+ metric_source_args_json: string;
+ metric_direction: MetricDirection;
+ baseline_value: number;
+};
+
+/**
+ * Intake result: the verified metric definition + measured baseline.
+ * Moves intake → proposed. No-op (returns null) if the goal isn't in
+ * intake — proposing twice or after activation is a bug upstream.
+ */
+export function setGoalMetric(id: string, spec: GoalMetricSpec): Goal | null {
+ const db = getDb();
+ const r = db
+ .prepare(
+ `UPDATE goals
+ SET metric_name = ?, metric_source_key = ?, metric_source_tool = ?,
+ metric_source_args_json = ?, metric_direction = ?,
+ baseline_value = ?, current_value = ?,
+ status = 'proposed', updated_at = ?
+ WHERE id = ? AND status = 'intake'`,
+ )
+ .run(
+ spec.metric_name,
+ spec.metric_source_key,
+ spec.metric_source_tool,
+ spec.metric_source_args_json,
+ spec.metric_direction,
+ spec.baseline_value,
+ spec.baseline_value,
+ now(),
+ id,
+ );
+ if (r.changes === 0) return null;
+ return getGoal(id);
+}
+
+export type ProposeTargetInput = {
+ target_value: number;
+ mode?: GoalMode;
+ deadline?: string | null;
+ spend_envelope_usd?: number | null;
+ cadence_cron?: string;
+};
+
+/**
+ * Agent proposal: record the suggested target/cadence/envelope on a
+ * `proposed` goal. Does NOT start the loop — that consent belongs to the
+ * user, who clicks "Start the loop" (startGoalLoop) on the Goal tab.
+ */
+export function proposeTarget(id: string, input: ProposeTargetInput): Goal | null {
+ const goal = getGoal(id);
+ if (!goal || goal.status !== "proposed") return null;
+ const cadence = input.cadence_cron ?? goal.cadence_cron;
+ if (!computeNextTick(cadence)) {
+ throw new Error(`Invalid cadence cron expression: '${cadence}'`);
+ }
+ getDb()
+ .prepare(
+ `UPDATE goals
+ SET target_value = ?, mode = ?, deadline = ?, spend_envelope_usd = ?,
+ cadence_cron = ?, updated_at = ?
+ WHERE id = ? AND status = 'proposed'`,
+ )
+ .run(
+ input.target_value,
+ input.mode ?? goal.mode ?? "achieve",
+ input.deadline ?? goal.deadline,
+ input.spend_envelope_usd ?? goal.spend_envelope_usd,
+ cadence,
+ now(),
+ id,
+ );
+ return getGoal(id);
+}
+
+/**
+ * The user's click: proposed (with a target on record) → active. Computes
+ * the first heartbeat; the caller fires an immediate first tick.
+ */
+export function startGoalLoop(id: string): Goal | null {
+ const goal = getGoal(id);
+ if (!goal || goal.status !== "proposed" || goal.target_value === null) return null;
+ const nextTick = computeNextTick(goal.cadence_cron);
+ if (!nextTick) throw new Error(`Invalid cadence cron expression: '${goal.cadence_cron}'`);
+ getDb()
+ .prepare(
+ `UPDATE goals SET status = 'active', next_tick_at = ?, updated_at = ?
+ WHERE id = ? AND status = 'proposed'`,
+ )
+ .run(nextTick, now(), id);
+ return getGoal(id);
+}
+
+export type AmendGoalInput = {
+ target_value?: number;
+ deadline?: string | null;
+ spend_envelope_usd?: number | null;
+ cadence_cron?: string;
+};
+
+/**
+ * Adjust a LIVE goal's parameters — "raise my envelope to $3k", "make the
+ * target 25" are normal asks and must not require killing the goal.
+ * Allowed while active or paused; recomputes the heartbeat when the
+ * cadence changes on an active goal.
+ */
+export function amendGoal(id: string, input: AmendGoalInput): Goal | null {
+ const goal = getGoal(id);
+ if (!goal || (goal.status !== "active" && goal.status !== "paused")) return null;
+ const cadence = input.cadence_cron ?? goal.cadence_cron;
+ const cadenceChanged = cadence !== goal.cadence_cron;
+ if (cadenceChanged && !computeNextTick(cadence)) {
+ throw new Error(`Invalid cadence cron expression: '${cadence}'`);
+ }
+ const nextTick =
+ goal.status === "active"
+ ? cadenceChanged
+ ? computeNextTick(cadence)
+ : goal.next_tick_at
+ : null;
+ getDb()
+ .prepare(
+ `UPDATE goals
+ SET target_value = COALESCE(?, target_value),
+ deadline = COALESCE(?, deadline),
+ spend_envelope_usd = COALESCE(?, spend_envelope_usd),
+ cadence_cron = ?, next_tick_at = ?, updated_at = ?
+ WHERE id = ?`,
+ )
+ .run(
+ input.target_value ?? null,
+ input.deadline ?? null,
+ input.spend_envelope_usd ?? null,
+ cadence,
+ nextTick,
+ now(),
+ id,
+ );
+ return getGoal(id);
+}
+
+/** Total incremental spend the agent has logged (non-abandoned actions). */
+export function loggedSpendTotal(goal_id: string): number {
+ const row = getDb()
+ .prepare(
+ `SELECT COALESCE(SUM(spend_usd), 0) AS total FROM goal_actions
+ WHERE goal_id = ? AND status != 'abandoned'`,
+ )
+ .get(goal_id) as { total: number };
+ return row.total;
+}
+
+/**
+ * Open, still-gated actions belonging to OTHER live goals in the same
+ * project. Their resources are just as untouchable — two agents sharing
+ * an ad account must not thrash each other's experiments.
+ */
+export function listGatedActionsForOtherAgents(
+ project_slug: string,
+ goal_id: string,
+ nowIso = now(),
+): Array<GoalAction & { agent_id: string }> {
+ return getDb()
+ .prepare(
+ `SELECT ga.*, g.agent_id FROM goal_actions ga
+ JOIN goals g ON g.id = ga.goal_id
+ WHERE g.project_slug = ? AND g.id != ?
+ AND g.status IN ('active','paused')
+ AND ga.status = 'open'
+ AND ga.review_after IS NOT NULL AND ga.review_after > ?
+ ORDER BY ga.review_after ASC`,
+ )
+ .all(project_slug, goal_id, nowIso) as Array<GoalAction & { agent_id: string }>;
+}
+
+/** Directly set the next heartbeat (smart sleep). Never used to move it earlier. */
+export function setNextTickAt(id: string, iso: string): void {
+ getDb()
+ .prepare("UPDATE goals SET next_tick_at = ?, updated_at = ? WHERE id = ? AND status = 'active'")
+ .run(iso, now(), id);
+}
+
+/**
+ * Status transitions outside the intake→proposed→active happy path:
+ * pause/resume and the three terminal states. Terminal states are
+ * one-way — a closed goal is history, not a resumable draft.
+ */
+export function setGoalStatus(
+ id: string,
+ status: Extract<GoalStatus, "active" | "paused" | "achieved" | "failed" | "killed">,
+ reason?: string | null,
+): Goal | null {
+ const goal = getGoal(id);
+ if (!goal) return null;
+ if (GOAL_TERMINAL_STATUSES.includes(goal.status)) return goal; // no rewrites
+ // Resuming (→ active) restarts the heartbeat; anything else stops it.
+ const nextTick = status === "active" ? computeNextTick(goal.cadence_cron) : null;
+ getDb()
+ .prepare(
+ `UPDATE goals
+ SET status = ?, status_reason = ?, next_tick_at = ?, updated_at = ?
+ WHERE id = ?`,
+ )
+ .run(status, reason ?? null, nextTick, now(), id);
+ return getGoal(id);
+}
+
+/** Active goals whose heartbeat is due. Mirrors scheduler dueJobs(). */
+export function dueGoals(nowIso = now()): Goal[] {
+ return getDb()
+ .prepare(
+ `SELECT * FROM goals
+ WHERE status = 'active'
+ AND next_tick_at IS NOT NULL
+ AND next_tick_at <= ?`,
+ )
+ .all(nowIso) as Goal[];
+}
+
+/**
+ * Advance the heartbeat the moment a tick starts (double-fire guard —
+ * same pattern as scheduler markJobRun) and bump the loop counters.
+ * Returns the tick_number this tick should use.
+ */
+export function markGoalTicked(id: string): number {
+ const db = getDb();
+ const goal = getGoal(id);
+ if (!goal) throw new Error(`goal not found: ${id}`);
+ const ts = now();
+ const nextTick = computeNextTick(goal.cadence_cron);
+ db.prepare(
+ `UPDATE goals
+ SET last_tick_at = ?, next_tick_at = ?, tick_count = tick_count + 1,
+ updated_at = ?
+ WHERE id = ?`,
+ ).run(ts, nextTick, ts, id);
+ return goal.tick_count + 1;
+}
+
+export function updateGoalCurrentValue(id: string, value: number): void {
+ getDb()
+ .prepare("UPDATE goals SET current_value = ?, updated_at = ? WHERE id = ?")
+ .run(value, now(), id);
+}
+
+// ── metric snapshots ─────────────────────────────────────────────────────
+
+export function recordMetricSnapshot(
+ goal_id: string,
+ value: number,
+ source: GoalMetricSnapshot["source"] = "tick",
+): GoalMetricSnapshot {
+ const db = getDb();
+ const id = randomUUID();
+ const ts = now();
+ db.prepare(
+ "INSERT INTO goal_metric_snapshots (id, goal_id, value, source, created_at) VALUES (?, ?, ?, ?, ?)",
+ ).run(id, goal_id, value, source, ts);
+ updateGoalCurrentValue(goal_id, value);
+ return { id, goal_id, value, source, created_at: ts };
+}
+
+/**
+ * Replace the goal's backfilled history with a fresh set of backdated
+ * points (from the agent's date-segmented history query). Never touches
+ * live intake/tick/manual snapshots; does not update current_value.
+ */
+export function replaceBackfillSnapshots(
+ goal_id: string,
+ points: Array<{ value: number; created_at: string }>,
+): number {
+ const db = getDb();
+ const insert = db.prepare(
+ "INSERT INTO goal_metric_snapshots (id, goal_id, value, source, created_at) VALUES (?, ?, ?, 'backfill', ?)",
+ );
+ const tx = db.transaction(() => {
+ db.prepare(
+ "DELETE FROM goal_metric_snapshots WHERE goal_id = ? AND source = 'backfill'",
+ ).run(goal_id);
+ for (const p of points) insert.run(randomUUID(), goal_id, p.value, p.created_at);
+ });
+ tx();
+ return points.length;
+}
+
+export function listMetricSnapshots(goal_id: string, limit = 90): GoalMetricSnapshot[] {
+ // Ascending so the sparkline reads left→right; LIMIT applies to the tail.
+ return getDb()
+ .prepare(
+ `SELECT id, goal_id, value, source, created_at FROM (
+ SELECT *, rowid AS _rid FROM goal_metric_snapshots
+ WHERE goal_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?
+ ) ORDER BY created_at ASC, _rid ASC`,
+ )
+ .all(goal_id, limit) as GoalMetricSnapshot[];
+}
+
+// ── actions ──────────────────────────────────────────────────────────────
+
+export type CreateGoalActionInput = {
+ goal_id: string;
+ tick_number?: number | null;
+ kind: GoalActionKind;
+ description: string;
+ resources_touched?: string[];
+ expected_effect: string;
+ review_after?: string | null;
+ spend_usd?: number | null;
+};
+
+export function createGoalAction(input: CreateGoalActionInput): GoalAction {
+ const db = getDb();
+ const id = randomUUID();
+ const ts = now();
+ db.prepare(
+ `INSERT INTO goal_actions
+ (id, goal_id, tick_number, kind, description, resources_touched_json,
+ expected_effect, review_after, spend_usd, status, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?)`,
+ ).run(
+ id,
+ input.goal_id,
+ input.tick_number ?? null,
+ input.kind,
+ input.description,
+ JSON.stringify(input.resources_touched ?? []),
+ input.expected_effect,
+ input.review_after ?? null,
+ input.spend_usd ?? null,
+ ts,
+ );
+ return getGoalAction(id)!;
+}
+
+export function getGoalAction(id: string): GoalAction | null {
+ const row = getDb().prepare("SELECT * FROM goal_actions WHERE id = ?").get(id);
+ return (row as GoalAction) ?? null;
+}
+
+export function listOpenGoalActions(goal_id: string): GoalAction[] {
+ return getDb()
+ .prepare(
+ "SELECT * FROM goal_actions WHERE goal_id = ? AND status = 'open' ORDER BY created_at ASC, rowid ASC",
+ )
+ .all(goal_id) as GoalAction[];
+}
+
+export function listGoalActions(goal_id: string, limit = 50): GoalAction[] {
+ return getDb()
+ .prepare(
+ "SELECT * FROM goal_actions WHERE goal_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?",
+ )
+ .all(goal_id, limit) as GoalAction[];
+}
+
+/**
+ * Close the measurement loop on an action: record what actually happened
+ * vs. expected_effect. Only open actions can be reviewed.
+ */
+export function reviewGoalAction(
+ id: string,
+ observed_outcome: string,
+ status: Extract<GoalActionStatus, "reviewed" | "abandoned"> = "reviewed",
+): GoalAction | null {
+ const r = getDb()
+ .prepare(
+ `UPDATE goal_actions
+ SET status = ?, observed_outcome = ?, reviewed_at = ?
+ WHERE id = ? AND status = 'open'`,
+ )
+ .run(status, observed_outcome, now(), id);
+ if (r.changes === 0) return null;
+ return getGoalAction(id);
+}
+
+/** Open mutations past their review_after — the "score these first" list. */
+export function listActionsDueForReview(goal_id: string, nowIso = now()): GoalAction[] {
+ return getDb()
+ .prepare(
+ `SELECT * FROM goal_actions
+ WHERE goal_id = ? AND status = 'open'
+ AND review_after IS NOT NULL AND review_after <= ?
+ ORDER BY review_after ASC`,
+ )
+ .all(goal_id, nowIso) as GoalAction[];
+}
+
+/** Open mutations still inside their observation window — the gate. */
+export function listGatedActions(goal_id: string, nowIso = now()): GoalAction[] {
+ return getDb()
+ .prepare(
+ `SELECT * FROM goal_actions
+ WHERE goal_id = ? AND status = 'open'
+ AND review_after IS NOT NULL AND review_after > ?
+ ORDER BY review_after ASC`,
+ )
+ .all(goal_id, nowIso) as GoalAction[];
+}
+
+// ── learnings ────────────────────────────────────────────────────────────
+
+export function addGoalLearning(
+ goal_id: string,
+ body: string,
+ confidence: GoalLearning["confidence"] = "medium",
+ supersedes_id?: string | null,
+): GoalLearning {
+ const db = getDb();
+ const id = randomUUID();
+ const ts = now();
+ db.prepare(
+ "INSERT INTO goal_learnings (id, goal_id, body, confidence, created_at) VALUES (?, ?, ?, ?, ?)",
+ ).run(id, goal_id, body, confidence, ts);
+ if (supersedes_id) {
+ db.prepare("UPDATE goal_learnings SET superseded_by = ? WHERE id = ? AND goal_id = ?").run(
+ id,
+ supersedes_id,
+ goal_id,
+ );
+ }
+ return { id, goal_id, body, confidence, superseded_by: null, created_at: ts };
+}
+
+/** Most recent non-superseded learnings, newest first. */
+export function listGoalLearnings(goal_id: string, limit = 20): GoalLearning[] {
+ return getDb()
+ .prepare(
+ `SELECT * FROM goal_learnings
+ WHERE goal_id = ? AND superseded_by IS NULL
+ ORDER BY created_at DESC, rowid DESC LIMIT ?`,
+ )
+ .all(goal_id, limit) as GoalLearning[];
+}
+
+/** Simple substring search over non-superseded learnings. */
+export function searchGoalLearnings(
+ goal_id: string,
+ query: string,
+ limit = 20,
+): GoalLearning[] {
+ return getDb()
+ .prepare(
+ `SELECT * FROM goal_learnings
+ WHERE goal_id = ? AND superseded_by IS NULL
+ AND body LIKE ? ESCAPE '\\'
+ ORDER BY created_at DESC, rowid DESC LIMIT ?`,
+ )
+ .all(
+ goal_id,
+ `%${query.replace(/[\\%_]/g, (c) => `\\${c}`)}%`,
+ limit,
+ ) as GoalLearning[];
+}
+
+// ── ticks (the diary) ────────────────────────────────────────────────────
+
+export function createGoalTick(input: {
+ goal_id: string;
+ tick_number: number;
+ trigger_kind: GoalTickTrigger;
+ metric_value?: number | null;
+ metric_error?: string | null;
+}): GoalTick {
+ const db = getDb();
+ const id = randomUUID();
+ const ts = now();
+ db.prepare(
+ `INSERT INTO goal_ticks
+ (id, goal_id, tick_number, trigger_kind, metric_value, metric_error,
+ status, started_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'running', ?)`,
+ ).run(
+ id,
+ input.goal_id,
+ input.tick_number,
+ input.trigger_kind,
+ input.metric_value ?? null,
+ input.metric_error ?? null,
+ ts,
+ );
+ return getGoalTick(id)!;
+}
+
+export function getGoalTick(id: string): GoalTick | null {
+ const row = getDb().prepare("SELECT * FROM goal_ticks WHERE id = ?").get(id);
+ return (row as GoalTick) ?? null;
+}
+
+export function attachTickSession(id: string, session_id: string): void {
+ getDb().prepare("UPDATE goal_ticks SET session_id = ? WHERE id = ?").run(session_id, id);
+}
+
+export function finishGoalTick(
+ id: string,
+ status: Extract<GoalTickStatus, "done" | "failed">,
+ summary?: string | null,
+): void {
+ getDb()
+ .prepare(
+ "UPDATE goal_ticks SET status = ?, summary = ?, finished_at = ? WHERE id = ?",
+ )
+ .run(status, summary ?? null, now(), id);
+}
+
+export function listGoalTicks(goal_id: string, limit = 30): GoalTick[] {
+ return getDb()
+ .prepare(
+ "SELECT * FROM goal_ticks WHERE goal_id = ? ORDER BY tick_number DESC LIMIT ?",
+ )
+ .all(goal_id, limit) as GoalTick[];
+}
+
+export function getLastFinishedTick(goal_id: string): GoalTick | null {
+ const row = getDb()
+ .prepare(
+ `SELECT * FROM goal_ticks
+ WHERE goal_id = ? AND status IN ('done','failed')
+ ORDER BY tick_number DESC LIMIT 1`,
+ )
+ .get(goal_id);
+ return (row as GoalTick) ?? null;
+}
+
+// ── derived reads ────────────────────────────────────────────────────────
+
+/**
+ * Direction-aware "has the metric met the target?". Null when the goal
+ * doesn't have both a target and a current reading yet.
+ */
+export function isTargetMet(goal: Goal): boolean | null {
+ if (goal.target_value === null || goal.current_value === null) return null;
+ if (goal.metric_direction === "decrease") {
+ return goal.current_value <= goal.target_value;
+ }
+ return goal.current_value >= goal.target_value;
+}
+
+export function isPastDeadline(goal: Goal, nowIso = now()): boolean {
+ if (!goal.deadline) return false;
+ return nowIso >= goal.deadline;
+}
diff --git a/notfair-cmo/src/server/db/projects.ts b/notfair/src/server/db/projects.ts
similarity index 87%
rename from notfair-cmo/src/server/db/projects.ts
rename to notfair/src/server/db/projects.ts
index 915cac5c..633ceab8 100644
--- a/notfair-cmo/src/server/db/projects.ts
+++ b/notfair/src/server/db/projects.ts
@@ -8,7 +8,7 @@ import type { HarnessAdapterId } from "@/server/adapters/types";
export type CreateProjectInput = {
display_name: string;
slug?: string;
- /** Optional onboarding hints. Free-text — CMO decides how to use them. */
+ /** Optional onboarding hints. Free-text — agents decide how to use them. */
website_url?: string | null;
codebase_path?: string | null;
/** Adapter chosen at onboarding. Defaults to claude-code-local. */
@@ -182,17 +182,13 @@ export function changeProjectSlug(
}
const childTables = [
- "tasks",
- "approvals",
- "approval_policies",
- "questions",
- "cost_events",
- "oauth_tokens",
"mcp_tokens",
- "scheduled_jobs",
+ "user_mcp_servers",
"sessions",
- "agent_actions",
- "sequence_runs",
+ "goal_suggestions",
+ // goal_actions / goal_metric_snapshots / goal_learnings / goal_ticks hang
+ // off goals(id), not project_slug, so only goals needs the slug rewrite.
+ "goals",
];
// Disable FK enforcement for the duration of the rename. Our FKs reference
@@ -248,51 +244,36 @@ export function unarchiveProject(slug: string): Project | null {
/**
* Hard-delete a project row plus any rows in tables that key off
- * project_slug. OpenClaw-side state — agents, sessions, crons — is cleaned
+ * project_slug. On-disk state — agent workspaces — is cleaned
* up by the deleteProject orchestrator, not here.
*
- * MUST match the FK-bearing tables from the migrations (mirrored exactly by
- * the changeProjectSlug helper above). Adding a new migration that FKs to
+ * MUST match the FK-bearing tables in schema.ts (mirrored exactly by the
+ * changeProjectSlug helper above). Adding a new table that FKs to
* projects(slug) requires adding the table name here too — otherwise delete
- * trips a SqliteError FOREIGN KEY constraint failed (the bug we just
- * shipped a regression test for).
+ * trips a SqliteError FOREIGN KEY constraint failed.
*/
export function deleteProjectRow(slug: string): void {
const db = getDb();
const childTables = [
- // tasks must come before scheduled_jobs / sessions because both have
- // optional FK references back to tasks(id) on delete-set-null. Order
- // within the loop otherwise doesn't matter — we just need every
- // child row gone before the parent project row.
- "tasks",
- // approval_comments cascades from approvals.
- "approvals",
- "approval_policies",
- "questions",
- "cost_events",
- "oauth_tokens",
"mcp_tokens",
- // scheduled_job_runs cascades from scheduled_jobs.
- "scheduled_jobs",
// transcript_events cascades from sessions.
"sessions",
- "agent_actions",
- "sequence_runs",
// User-added MCP catalog entries (Browse connectors / custom URLs).
// cascadeDeleteProjectArtifacts also clears these, but this sweep must
// be complete on its own: with foreign_keys=ON, any leftover child row
// makes the final DELETE FROM projects fail and strands the project.
"user_mcp_servers",
+ "goal_suggestions",
+ // goal_actions / goal_metric_snapshots / goal_learnings / goal_ticks
+ // cascade from goals(id) — deleting goals is enough.
+ "goals",
];
- for (const table of childTables) {
- try {
+ db.transaction(() => {
+ for (const table of childTables) {
db.prepare(`DELETE FROM ${table} WHERE project_slug = ?`).run(slug);
- } catch {
- // table missing on this install (e.g., older DB pre-migration).
- // Per-table try/catch so one missing table doesn't block the rest.
}
- }
- db.prepare("DELETE FROM projects WHERE slug = ?").run(slug);
+ db.prepare("DELETE FROM projects WHERE slug = ?").run(slug);
+ })();
}
/**
diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.ts
new file mode 100644
index 00000000..1ceb73cb
--- /dev/null
+++ b/notfair/src/server/db/schema.ts
@@ -0,0 +1,202 @@
+/**
+ * The full NotFair schema, applied idempotently on boot. One file, one
+ * source of truth — no migration history. If the shape needs to change,
+ * change it here (existing dev databases can be recreated; there is no
+ * multi-tenant fleet to migrate).
+ */
+export const SCHEMA = `
+CREATE TABLE IF NOT EXISTS projects (
+ id TEXT PRIMARY KEY,
+ slug TEXT NOT NULL UNIQUE,
+ display_name TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ archived_at TEXT,
+ google_ads_account_id TEXT,
+ meta_ads_account_id TEXT,
+ gsc_property_id TEXT,
+ website_url TEXT,
+ codebase_path TEXT,
+ harness_adapter TEXT NOT NULL DEFAULT 'claude-code-local',
+ hidden_mcp_preset_keys_json TEXT NOT NULL DEFAULT '[]'
+);
+
+CREATE TABLE IF NOT EXISTS sessions (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ label TEXT NOT NULL,
+ harness_adapter TEXT NOT NULL,
+ harness_session_id TEXT,
+ title TEXT,
+ pinned_at TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(project_slug, agent_id, label)
+);
+CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(project_slug, agent_id);
+
+CREATE TABLE IF NOT EXISTS transcript_events (
+ id TEXT PRIMARY KEY,
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ seq INTEGER NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('user','delta','tool','lifecycle','final','error')),
+ payload_json TEXT NOT NULL,
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_transcript_events_session ON transcript_events(session_id, seq);
+
+CREATE TABLE IF NOT EXISTS mcp_tokens (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ server_name TEXT NOT NULL,
+ account_label TEXT NOT NULL DEFAULT '',
+ access_token_enc TEXT NOT NULL,
+ refresh_token_enc TEXT,
+ expires_at TEXT,
+ scope TEXT,
+ metadata_json TEXT,
+ token_endpoint TEXT,
+ client_id TEXT,
+ client_secret TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(project_slug, server_name, account_label)
+);
+CREATE INDEX IF NOT EXISTS idx_mcp_tokens_project ON mcp_tokens(project_slug);
+
+CREATE TABLE IF NOT EXISTS user_mcp_servers (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ key TEXT NOT NULL,
+ display_name TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ resource_url TEXT NOT NULL,
+ discovery_url TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(project_slug, key)
+);
+CREATE INDEX IF NOT EXISTS idx_user_mcp_servers_project ON user_mcp_servers(project_slug);
+
+CREATE TABLE IF NOT EXISTS goals (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ statement TEXT NOT NULL,
+ short_label TEXT,
+ status TEXT NOT NULL DEFAULT 'intake'
+ CHECK (status IN ('intake','proposed','active','paused','achieved','failed','killed')),
+ status_reason TEXT,
+ mode TEXT NOT NULL DEFAULT 'achieve'
+ CHECK (mode IN ('achieve','maintain')),
+ -- Executable metric definition (filled by intake via propose_goal_metric).
+ metric_name TEXT,
+ metric_source_key TEXT,
+ metric_source_tool TEXT,
+ metric_source_args_json TEXT,
+ metric_direction TEXT CHECK (metric_direction IN ('increase','decrease')),
+ baseline_value REAL,
+ current_value REAL,
+ target_value REAL,
+ deadline TEXT,
+ spend_envelope_usd REAL,
+ -- Loop cadence + state. next_tick_at is advanced by the tick runner the
+ -- moment a tick starts, as a double-fire guard.
+ cadence_cron TEXT NOT NULL DEFAULT '0 16 * * *',
+ next_tick_at TEXT,
+ last_tick_at TEXT,
+ tick_count INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_goals_project ON goals(project_slug, status);
+CREATE INDEX IF NOT EXISTS idx_goals_due ON goals(status, next_tick_at);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_goals_one_live_per_agent
+ ON goals(agent_id)
+ WHERE status IN ('intake','proposed','active','paused');
+
+CREATE TABLE IF NOT EXISTS goal_actions (
+ id TEXT PRIMARY KEY,
+ goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
+ tick_number INTEGER,
+ kind TEXT NOT NULL DEFAULT 'mutation'
+ CHECK (kind IN ('mutation','research','decision')),
+ description TEXT NOT NULL,
+ resources_touched_json TEXT NOT NULL DEFAULT '[]',
+ expected_effect TEXT NOT NULL,
+ spend_usd REAL,
+ -- Measurement-maturity gate: the agent may not touch the same resources
+ -- again (and must score this action) once now >= review_after.
+ review_after TEXT,
+ status TEXT NOT NULL DEFAULT 'open'
+ CHECK (status IN ('open','reviewed','abandoned')),
+ observed_outcome TEXT,
+ reviewed_at TEXT,
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_goal_actions_goal ON goal_actions(goal_id, status);
+
+CREATE TABLE IF NOT EXISTS goal_metric_snapshots (
+ id TEXT PRIMARY KEY,
+ goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
+ value REAL NOT NULL,
+ source TEXT NOT NULL DEFAULT 'tick'
+ CHECK (source IN ('intake','tick','manual','backfill')),
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_goal_snapshots_goal
+ ON goal_metric_snapshots(goal_id, created_at);
+
+CREATE TABLE IF NOT EXISTS goal_learnings (
+ id TEXT PRIMARY KEY,
+ goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
+ body TEXT NOT NULL,
+ confidence TEXT NOT NULL DEFAULT 'medium'
+ CHECK (confidence IN ('low','medium','high')),
+ superseded_by TEXT REFERENCES goal_learnings(id) ON DELETE SET NULL,
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_goal_learnings_goal
+ ON goal_learnings(goal_id, created_at);
+
+CREATE TABLE IF NOT EXISTS goal_suggestions (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ source_key TEXT NOT NULL,
+ -- Stable heuristic id (e.g. 'wasted-spend'). One row per kind per
+ -- source: regeneration updates open rows in place, and dismissed or
+ -- accepted kinds keep their status instead of resurfacing.
+ kind TEXT NOT NULL,
+ title TEXT NOT NULL,
+ statement TEXT NOT NULL,
+ mode TEXT NOT NULL DEFAULT 'achieve'
+ CHECK (mode IN ('achieve','maintain')),
+ -- Evidence sentence with the real account numbers that justify it.
+ rationale TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'open'
+ CHECK (status IN ('open','accepted','dismissed')),
+ accepted_goal_id TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(project_slug, source_key, kind)
+);
+CREATE INDEX IF NOT EXISTS idx_goal_suggestions_project
+ ON goal_suggestions(project_slug, status);
+
+CREATE TABLE IF NOT EXISTS goal_ticks (
+ id TEXT PRIMARY KEY,
+ goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
+ tick_number INTEGER NOT NULL,
+ trigger_kind TEXT NOT NULL DEFAULT 'heartbeat'
+ CHECK (trigger_kind IN ('heartbeat','manual','approval','intake')),
+ session_id TEXT,
+ metric_value REAL,
+ metric_error TEXT,
+ status TEXT NOT NULL DEFAULT 'running'
+ CHECK (status IN ('running','done','failed')),
+ summary TEXT,
+ started_at TEXT NOT NULL,
+ finished_at TEXT
+);
+CREATE INDEX IF NOT EXISTS idx_goal_ticks_goal ON goal_ticks(goal_id, tick_number);
+`;
diff --git a/notfair/src/server/db/suggestions.ts b/notfair/src/server/db/suggestions.ts
new file mode 100644
index 00000000..ae640e1f
--- /dev/null
+++ b/notfair/src/server/db/suggestions.ts
@@ -0,0 +1,126 @@
+import { randomUUID } from "node:crypto";
+import { getDb } from "./db";
+
+/**
+ * Goal suggestions: proposals NotFair mints from a mechanical audit of a
+ * freshly connected ads account. One row per (project, source, kind) —
+ * regeneration refreshes open rows in place; accepted and dismissed rows
+ * keep their status so the same idea never resurfaces uninvited.
+ */
+
+export type GoalSuggestion = {
+ id: string;
+ project_slug: string;
+ source_key: string;
+ kind: string;
+ title: string;
+ statement: string;
+ mode: "achieve" | "maintain";
+ rationale: string;
+ status: "open" | "accepted" | "dismissed";
+ accepted_goal_id: string | null;
+ created_at: string;
+ updated_at: string;
+};
+
+export type SuggestionDraft = {
+ kind: string;
+ title: string;
+ statement: string;
+ mode: "achieve" | "maintain";
+ rationale: string;
+};
+
+/**
+ * Write a fresh batch for one source. Open rows for kinds NOT in the new
+ * batch are deleted (the data no longer supports them); accepted and
+ * dismissed rows are never touched.
+ */
+export function replaceOpenSuggestions(
+ project_slug: string,
+ source_key: string,
+ drafts: SuggestionDraft[],
+): void {
+ const db = getDb();
+ const now = new Date().toISOString();
+ const tx = db.transaction(() => {
+ const keep = drafts.map((d) => d.kind);
+ const placeholders = keep.map(() => "?").join(",");
+ db.prepare(
+ `DELETE FROM goal_suggestions
+ WHERE project_slug = ? AND source_key = ? AND status = 'open'
+ ${keep.length > 0 ? `AND kind NOT IN (${placeholders})` : ""}`,
+ ).run(project_slug, source_key, ...keep);
+ for (const d of drafts) {
+ db.prepare(
+ `INSERT INTO goal_suggestions
+ (id, project_slug, source_key, kind, title, statement, mode, rationale, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)
+ ON CONFLICT(project_slug, source_key, kind) DO UPDATE SET
+ title = excluded.title,
+ statement = excluded.statement,
+ mode = excluded.mode,
+ rationale = excluded.rationale,
+ updated_at = excluded.updated_at
+ WHERE goal_suggestions.status = 'open'`,
+ ).run(
+ randomUUID(),
+ project_slug,
+ source_key,
+ d.kind,
+ d.title,
+ d.statement,
+ d.mode,
+ d.rationale,
+ now,
+ now,
+ );
+ }
+ });
+ tx();
+}
+
+export function listOpenSuggestions(project_slug: string): GoalSuggestion[] {
+ return getDb()
+ .prepare(
+ "SELECT * FROM goal_suggestions WHERE project_slug = ? AND status = 'open' ORDER BY created_at ASC, kind ASC",
+ )
+ .all(project_slug) as GoalSuggestion[];
+}
+
+export function getSuggestion(id: string): GoalSuggestion | null {
+ const row = getDb()
+ .prepare("SELECT * FROM goal_suggestions WHERE id = ?")
+ .get(id) as GoalSuggestion | undefined;
+ return row ?? null;
+}
+
+/** True when this source has EVER produced rows for the project. */
+export function hasSuggestionsForSource(
+ project_slug: string,
+ source_key: string,
+): boolean {
+ return (
+ getDb()
+ .prepare(
+ "SELECT 1 FROM goal_suggestions WHERE project_slug = ? AND source_key = ? LIMIT 1",
+ )
+ .get(project_slug, source_key) !== undefined
+ );
+}
+
+export function markSuggestionAccepted(id: string, goal_id: string): void {
+ getDb()
+ .prepare(
+ "UPDATE goal_suggestions SET status = 'accepted', accepted_goal_id = ?, updated_at = ? WHERE id = ?",
+ )
+ .run(goal_id, new Date().toISOString(), id);
+}
+
+export function markSuggestionDismissed(id: string): void {
+ getDb()
+ .prepare(
+ "UPDATE goal_suggestions SET status = 'dismissed', updated_at = ? WHERE id = ?",
+ )
+ .run(new Date().toISOString(), id);
+}
diff --git a/notfair-cmo/src/server/db/user-mcp-servers.ts b/notfair/src/server/db/user-mcp-servers.ts
similarity index 100%
rename from notfair-cmo/src/server/db/user-mcp-servers.ts
rename to notfair/src/server/db/user-mcp-servers.ts
diff --git a/notfair-cmo/src/server/fs/pick-folder.ts b/notfair/src/server/fs/pick-folder.ts
similarity index 98%
rename from notfair-cmo/src/server/fs/pick-folder.ts
rename to notfair/src/server/fs/pick-folder.ts
index 1fe7bdbc..8786b7d0 100644
--- a/notfair-cmo/src/server/fs/pick-folder.ts
+++ b/notfair/src/server/fs/pick-folder.ts
@@ -5,7 +5,7 @@ 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
+ * `npx notfair` 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
diff --git a/notfair/src/server/goals/handlers.ts b/notfair/src/server/goals/handlers.ts
new file mode 100644
index 00000000..d3c43b04
--- /dev/null
+++ b/notfair/src/server/goals/handlers.ts
@@ -0,0 +1,625 @@
+import {
+ addGoalLearning,
+ amendGoal,
+ createGoalAction,
+ defineGoal,
+ getGoal,
+ getGoalAction,
+ listActionsDueForReview,
+ listGatedActions,
+ listGoalLearnings,
+ listGatedActionsForOtherAgents,
+ listGoalTicks,
+ listMetricSnapshots,
+ loggedSpendTotal,
+ proposeTarget,
+ recordMetricSnapshot,
+ replaceBackfillSnapshots,
+ reviewGoalAction,
+ searchGoalLearnings,
+ setGoalMetric,
+ setGoalStatus,
+ isTargetMet,
+ type Goal,
+ type GoalAction,
+ type GoalLearning,
+ type GoalTick,
+ type MetricDirection,
+} from "@/server/db/goals";
+import { getProject } from "@/server/db/projects";
+import { findMcpToken } from "@/server/mcp/tokens";
+import {
+ PROJECT_BRIEF_MAX_BYTES,
+ readProjectBrief,
+ writeProjectBrief,
+} from "@/server/onboarding/project-brief";
+import type { Project } from "@/types";
+import { runHistorySource, runMetricSource } from "./metric";
+
+/**
+ * Handlers for NotFair's MCP tools — the goal agent's coordination
+ * surface. Inputs are schema-validated upstream (zod in
+ * mcp-server/tools.ts); context carries the caller's identity, and
+ * cross-project / wrong-agent calls are rejected here.
+ */
+
+export type HandlerContext = {
+ /** Project the caller is operating in. */
+ project_slug: string;
+ /** Caller's agent_id (the one making the change). */
+ agent_id: string;
+};
+
+export type HandlerResult<T> =
+ | { ok: true; data: T }
+ | { ok: false; error: string };
+
+/** Resolve + authorize a goal for the calling agent. */
+function resolveGoal(
+ goal_id: string,
+ ctx: HandlerContext,
+ opts: { requireOwner?: boolean } = {},
+): HandlerResult<Goal> {
+ const goal = getGoal(goal_id);
+ if (!goal) return { ok: false, error: `Unknown goal_id '${goal_id}'` };
+ if (goal.project_slug !== ctx.project_slug) {
+ return { ok: false, error: `Cross-project goal access rejected on '${goal_id}'` };
+ }
+ if (opts.requireOwner && goal.agent_id !== ctx.agent_id) {
+ return {
+ ok: false,
+ error: `Goal '${goal_id}' is owned by '${goal.agent_id}', not '${ctx.agent_id}'`,
+ };
+ }
+ return { ok: true, data: goal };
+}
+
+// ── get_goal ─────────────────────────────────────────────────────────────
+
+export type GoalStateView = {
+ goal: Goal;
+ target_met: boolean | null;
+ actions_due_for_review: GoalAction[];
+ actions_gated: GoalAction[];
+ recent_learnings: GoalLearning[];
+ recent_ticks: Array<Pick<GoalTick, "tick_number" | "status" | "metric_value" | "summary" | "started_at">>;
+ metric_history: Array<{ value: number; created_at: string }>;
+ /** Sum of spend_usd across your logged (non-abandoned) actions. */
+ logged_spend_usd: number;
+ /** Other agents' still-gated resources in this workspace — equally untouchable. */
+ gated_by_other_agents: Array<{ agent_id: string; description: string; resources: string[]; until: string | null }>;
+ /** Shared workspace context (PROJECT.md) — same for every agent. */
+ shared_context: string | null;
+};
+
+export async function handleGetGoal(
+ input: { goal_id: string },
+ ctx: HandlerContext,
+): Promise<HandlerResult<GoalStateView>> {
+ const r = resolveGoal(input.goal_id, ctx);
+ if (!r.ok) return r;
+ const goal = r.data;
+ const shared_context = await readProjectBrief(ctx.project_slug).catch(() => null);
+ return {
+ ok: true,
+ data: {
+ goal,
+ target_met: isTargetMet(goal),
+ actions_due_for_review: listActionsDueForReview(goal.id),
+ actions_gated: listGatedActions(goal.id),
+ recent_learnings: listGoalLearnings(goal.id, 15),
+ recent_ticks: listGoalTicks(goal.id, 5).map((t) => ({
+ tick_number: t.tick_number,
+ status: t.status,
+ metric_value: t.metric_value,
+ summary: t.summary,
+ started_at: t.started_at,
+ })),
+ metric_history: listMetricSnapshots(goal.id, 30).map((s) => ({
+ value: s.value,
+ created_at: s.created_at,
+ })),
+ logged_spend_usd: loggedSpendTotal(goal.id),
+ gated_by_other_agents: listGatedActionsForOtherAgents(ctx.project_slug, goal.id).map(
+ (a) => ({
+ agent_id: a.agent_id,
+ description: a.description,
+ resources: JSON.parse(a.resources_touched_json || "[]") as string[],
+ until: a.review_after,
+ }),
+ ),
+ shared_context,
+ },
+ };
+}
+
+// ── define_goal (chat intake, step 1) ────────────────────────────────────
+
+export type DefineGoalInput = {
+ goal_id: string;
+ statement: string;
+ short_label: string;
+ deadline?: string;
+ spend_envelope_usd?: number;
+};
+
+/**
+ * Record the ambition the user articulated in chat. Repeatable while the
+ * goal is in intake (the statement sharpens as the conversation does).
+ */
+export function handleDefineGoal(
+ input: DefineGoalInput,
+ ctx: HandlerContext,
+): HandlerResult<{ goal_id: string; statement: string }> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const updated = defineGoal(input.goal_id, {
+ statement: input.statement.trim(),
+ short_label: input.short_label.trim().slice(0, 48),
+ deadline: input.deadline ?? null,
+ spend_envelope_usd: input.spend_envelope_usd ?? null,
+ });
+ if (!updated) {
+ return {
+ ok: false,
+ error: `Goal is '${r.data.status}', not 'intake' — the goal is already defined. Use log_learning to record refinements.`,
+ };
+ }
+ void syncIdentity(updated);
+ return { ok: true, data: { goal_id: updated.id, statement: updated.statement } };
+}
+
+// ── propose_goal_metric (chat intake, step 2) ────────────────────────────
+
+export type ProposeGoalMetricInput = {
+ goal_id: string;
+ metric_name: string;
+ metric_source_key: string;
+ metric_source_tool: string;
+ metric_source_args_json: string;
+ metric_direction: MetricDirection;
+};
+
+/**
+ * Intake's verification gate. The agent submits the metric it authored +
+ * tested; we re-run the exact query server-side. Only a reproducible
+ * number moves the goal to `proposed` — "trust me, the query works"
+ * doesn't.
+ */
+export async function handleProposeGoalMetric(
+ input: ProposeGoalMetricInput,
+ ctx: HandlerContext,
+): Promise<HandlerResult<{ goal_id: string; baseline_value: number; status: string }>> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const goal = r.data;
+ if (goal.status !== "intake") {
+ return {
+ ok: false,
+ error: `Goal is '${goal.status}', not 'intake' — the metric is already set.`,
+ };
+ }
+ if (!goal.statement.trim()) {
+ return {
+ ok: false,
+ error: "Define the goal first (define_goal) — a metric needs an ambition to measure.",
+ };
+ }
+ if (!findMcpToken(ctx.project_slug, input.metric_source_key)) {
+ return {
+ ok: false,
+ error: `No connected MCP '${input.metric_source_key}' for this project. Use a connected data source.`,
+ };
+ }
+
+ const measured = await runMetricSource(ctx.project_slug, {
+ key: input.metric_source_key,
+ tool: input.metric_source_tool,
+ args_json: input.metric_source_args_json,
+ });
+ if (!measured.ok) {
+ return {
+ ok: false,
+ error: `Server-side verification failed — fix the query and propose again. ${measured.error}`,
+ };
+ }
+
+ const updated = setGoalMetric(goal.id, {
+ metric_name: input.metric_name,
+ metric_source_key: input.metric_source_key,
+ metric_source_tool: input.metric_source_tool,
+ metric_source_args_json: input.metric_source_args_json,
+ metric_direction: input.metric_direction,
+ baseline_value: measured.value,
+ });
+ if (!updated) {
+ return { ok: false, error: "Goal left intake while verifying — nothing written." };
+ }
+ recordMetricSnapshot(goal.id, measured.value, "intake");
+ void syncIdentity(updated);
+
+ return {
+ ok: true,
+ data: { goal_id: goal.id, baseline_value: measured.value, status: updated.status },
+ };
+}
+
+// ── backfill_metric_history ──────────────────────────────────────────────
+
+export type BackfillHistoryInput = {
+ goal_id: string;
+ source_key: string;
+ source_tool: string;
+ source_args_json: string;
+};
+
+/**
+ * Reconstruct the metric's past from a date-segmented query so the
+ * progress chart has context from day one. The platform runs the query
+ * itself (same trust rule as the metric), validates the {date, value}
+ * shape, and REPLACES any prior backfill — live snapshots are untouched.
+ */
+export async function handleBackfillHistory(
+ input: BackfillHistoryInput,
+ ctx: HandlerContext,
+): Promise<HandlerResult<{ goal_id: string; points: number; from: string; to: string }>> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const goal = r.data;
+ if (!findMcpToken(ctx.project_slug, input.source_key)) {
+ return { ok: false, error: `No connected MCP '${input.source_key}' for this project.` };
+ }
+ const run = await runHistorySource(ctx.project_slug, {
+ key: input.source_key,
+ tool: input.source_tool,
+ args_json: input.source_args_json,
+ });
+ if (!run.ok) return { ok: false, error: run.error };
+ // Only backdated points make sense — drop anything in the future.
+ const nowIso = new Date().toISOString();
+ const points = run.points.filter((p) => p.date <= nowIso);
+ if (points.length === 0) {
+ return { ok: false, error: "History query returned no past-dated points." };
+ }
+ replaceBackfillSnapshots(
+ goal.id,
+ points.map((p) => ({ value: p.value, created_at: p.date })),
+ );
+ return {
+ ok: true,
+ data: {
+ goal_id: goal.id,
+ points: points.length,
+ from: points[0]!.date.slice(0, 10),
+ to: points[points.length - 1]!.date.slice(0, 10),
+ },
+ };
+}
+
+// ── propose_target (chat intake, step 3) ─────────────────────────────────
+
+function targetDirectionError(
+ goal: Goal,
+ target_value: number,
+ mode: "achieve" | "maintain",
+): string | null {
+ // MAINTAIN targets sit on the ALREADY-MET side by design: "stay above a
+ // 75k floor" when today's number is 82k, or "hold wasted spend at $0".
+ // The direction check only makes sense for ACHIEVE goals, where a target
+ // on the wrong side of the baseline is nonsense (equality allowed).
+ if (mode === "maintain") return null;
+ if (goal.metric_direction === "decrease" && goal.baseline_value !== null && target_value > goal.baseline_value) {
+ return `Direction is 'decrease' but target (${target_value}) is above the baseline (${goal.baseline_value}).`;
+ }
+ if (goal.metric_direction === "increase" && goal.baseline_value !== null && target_value < goal.baseline_value) {
+ return `Direction is 'increase' but target (${target_value}) is below the baseline (${goal.baseline_value}).`;
+ }
+ return null;
+}
+
+export type ProposeTargetToolInput = {
+ goal_id: string;
+ target_value: number;
+ mode?: "achieve" | "maintain";
+ deadline?: string;
+ spend_envelope_usd?: number;
+ cadence_cron?: string;
+};
+
+/**
+ * Record the target/cadence/envelope the user agreed to in chat. Does NOT
+ * start the loop — the user clicks "Start the loop" on the Goal tab.
+ * That click is the platform-enforced consent moment: an agent cannot
+ * start spending cycles (or money) on its own say-so.
+ */
+export function handleProposeTarget(
+ input: ProposeTargetToolInput,
+ ctx: HandlerContext,
+): HandlerResult<{ goal_id: string; status: string }> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const goal = r.data;
+ if (goal.status !== "proposed") {
+ return {
+ ok: false,
+ error: `Goal is '${goal.status}', not 'proposed' — verify a metric first (propose_goal_metric).`,
+ };
+ }
+ const dirErr = targetDirectionError(goal, input.target_value, input.mode ?? goal.mode);
+ if (dirErr) return { ok: false, error: dirErr };
+ let updated: Goal | null;
+ try {
+ updated = proposeTarget(goal.id, {
+ target_value: input.target_value,
+ mode: input.mode,
+ deadline: input.deadline,
+ spend_envelope_usd: input.spend_envelope_usd,
+ cadence_cron: input.cadence_cron,
+ });
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+ if (!updated) return { ok: false, error: "Goal left 'proposed' while recording the target." };
+ void syncIdentity(updated);
+ return { ok: true, data: { goal_id: updated.id, status: updated.status } };
+}
+
+// ── amend_goal (live adjustments) ────────────────────────────────────────
+
+export type AmendGoalToolInput = {
+ goal_id: string;
+ target_value?: number;
+ deadline?: string;
+ spend_envelope_usd?: number;
+ cadence_cron?: string;
+};
+
+/**
+ * Adjust a live goal's parameters when the user asks in chat — "raise my
+ * envelope to $3k", "make the target 25". Active or paused goals only.
+ */
+export function handleAmendGoal(
+ input: AmendGoalToolInput,
+ ctx: HandlerContext,
+): HandlerResult<{ goal_id: string; target_value: number | null; deadline: string | null; spend_envelope_usd: number | null; cadence_cron: string }> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const goal = r.data;
+ if (goal.status !== "active" && goal.status !== "paused") {
+ return {
+ ok: false,
+ error: `Goal is '${goal.status}' — amend applies to active/paused goals. Use the intake tools before the loop starts.`,
+ };
+ }
+ if (
+ input.target_value === undefined &&
+ input.deadline === undefined &&
+ input.spend_envelope_usd === undefined &&
+ input.cadence_cron === undefined
+ ) {
+ return { ok: false, error: "Nothing to amend — pass at least one field." };
+ }
+ if (input.target_value !== undefined) {
+ const dirErr = targetDirectionError(goal, input.target_value, goal.mode);
+ if (dirErr) return { ok: false, error: dirErr };
+ }
+ let updated: Goal | null;
+ try {
+ updated = amendGoal(goal.id, input);
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+ if (!updated) return { ok: false, error: "Goal changed state while amending." };
+ void syncIdentity(updated);
+ return {
+ ok: true,
+ data: {
+ goal_id: updated.id,
+ target_value: updated.target_value,
+ deadline: updated.deadline,
+ spend_envelope_usd: updated.spend_envelope_usd,
+ cadence_cron: updated.cadence_cron,
+ },
+ };
+}
+
+// ── log_goal_action ──────────────────────────────────────────────────────
+
+export type LogGoalActionInput = {
+ goal_id: string;
+ kind: "mutation" | "research" | "decision";
+ description: string;
+ resources_touched?: string[];
+ expected_effect: string;
+ review_after_hours?: number;
+ spend_usd?: number;
+};
+
+export function handleLogGoalAction(
+ input: LogGoalActionInput,
+ ctx: HandlerContext,
+): HandlerResult<{ action_id: string; review_after: string | null }> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const goal = r.data;
+
+ if (input.kind === "mutation" && !input.review_after_hours) {
+ return {
+ ok: false,
+ error:
+ "Mutations require review_after_hours — the observation window is what keeps the loop honest. Pick per the skill guidance (72h+ for waste pauses, 120h+ for bid/budget changes).",
+ };
+ }
+
+ const review_after = input.review_after_hours
+ ? new Date(Date.now() + input.review_after_hours * 3_600_000).toISOString()
+ : null;
+
+ const action = createGoalAction({
+ goal_id: goal.id,
+ tick_number: goal.tick_count || null,
+ kind: input.kind,
+ description: input.description,
+ resources_touched: input.resources_touched ?? [],
+ expected_effect: input.expected_effect,
+ review_after,
+ spend_usd: input.spend_usd ?? null,
+ });
+ return { ok: true, data: { action_id: action.id, review_after: action.review_after } };
+}
+
+// ── review_goal_action ───────────────────────────────────────────────────
+
+export type ReviewGoalActionInput = {
+ goal_id: string;
+ action_id: string;
+ observed_outcome: string;
+ abandoned?: boolean;
+ learning?: string;
+};
+
+export function handleReviewGoalAction(
+ input: ReviewGoalActionInput,
+ ctx: HandlerContext,
+): HandlerResult<{ action_id: string; status: string; learning_id: string | null }> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+
+ const action = getGoalAction(input.action_id);
+ if (!action || action.goal_id !== input.goal_id) {
+ return { ok: false, error: `Unknown action_id '${input.action_id}' on this goal` };
+ }
+ const reviewed = reviewGoalAction(
+ input.action_id,
+ input.observed_outcome,
+ input.abandoned ? "abandoned" : "reviewed",
+ );
+ if (!reviewed) {
+ return { ok: false, error: `Action '${input.action_id}' is not open — already reviewed?` };
+ }
+
+ let learning_id: string | null = null;
+ if (input.learning) {
+ learning_id = addGoalLearning(input.goal_id, input.learning, "medium").id;
+ }
+ return { ok: true, data: { action_id: reviewed.id, status: reviewed.status, learning_id } };
+}
+
+// ── log_learning / search_learnings (per-agent memory) ───────────────────
+
+export function handleLogLearning(
+ input: {
+ goal_id: string;
+ body: string;
+ confidence?: "low" | "medium" | "high";
+ supersedes_id?: string;
+ },
+ ctx: HandlerContext,
+): HandlerResult<{ learning_id: string }> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const learning = addGoalLearning(
+ input.goal_id,
+ input.body,
+ input.confidence ?? "medium",
+ input.supersedes_id ?? null,
+ );
+ return { ok: true, data: { learning_id: learning.id } };
+}
+
+export function handleSearchLearnings(
+ input: { goal_id: string; query?: string; limit?: number },
+ ctx: HandlerContext,
+): HandlerResult<{ learnings: GoalLearning[] }> {
+ const r = resolveGoal(input.goal_id, ctx);
+ if (!r.ok) return r;
+ const limit = Math.min(input.limit ?? 20, 50);
+ const learnings = input.query
+ ? searchGoalLearnings(input.goal_id, input.query, limit)
+ : listGoalLearnings(input.goal_id, limit);
+ return { ok: true, data: { learnings } };
+}
+
+// ── update_goal_status ───────────────────────────────────────────────────
+
+export type UpdateGoalStatusInput = {
+ goal_id: string;
+ status: "achieved" | "failed" | "paused";
+ reason: string;
+};
+
+export function handleUpdateGoalStatus(
+ input: UpdateGoalStatusInput,
+ ctx: HandlerContext,
+): HandlerResult<{ goal_id: string; status: string }> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const goal = r.data;
+
+ if (input.status === "achieved") {
+ if (goal.mode === "maintain") {
+ return {
+ ok: false,
+ error:
+ "This is a MAINTAIN goal — holding the number at target is the job, not the finish line. Keep watching; the user pauses or closes it from the Goal page when they no longer want the watchdog.",
+ };
+ }
+ const met = isTargetMet(goal);
+ if (met === false) {
+ return {
+ ok: false,
+ error: `The measured metric (${goal.current_value}) has not met the target (${goal.target_value}). A goal is achieved when the number says so.`,
+ };
+ }
+ }
+
+ const updated = setGoalStatus(goal.id, input.status, input.reason);
+ if (!updated) return { ok: false, error: `Unknown goal_id '${input.goal_id}'` };
+ if (updated.status !== input.status) {
+ return { ok: false, error: `Goal is terminal ('${updated.status}') — status is final.` };
+ }
+ return { ok: true, data: { goal_id: updated.id, status: updated.status } };
+}
+
+// ── shared workspace context ─────────────────────────────────────────────
+
+export function handleGetProject(
+ _input: Record<string, never>,
+ ctx: HandlerContext,
+): HandlerResult<Project> {
+ const project = getProject(ctx.project_slug);
+ if (!project) return { ok: false, error: `Unknown project '${ctx.project_slug}'` };
+ return { ok: true, data: project };
+}
+
+/**
+ * Rewrite the shared workspace context (PROJECT.md) — visible to EVERY
+ * agent in the project. Re-renders every goal agent's identity so the new
+ * context lands on their next turn.
+ */
+export async function handleSetProjectBrief(
+ input: { content: string },
+ ctx: HandlerContext,
+): Promise<HandlerResult<{ bytes: number; synced_agents: number }>> {
+ const project = getProject(ctx.project_slug);
+ if (!project) return { ok: false, error: `Unknown project '${ctx.project_slug}'` };
+ const content = input.content.trim();
+ if (!content) return { ok: false, error: "Shared context cannot be empty." };
+ if (Buffer.byteLength(content, "utf8") > PROJECT_BRIEF_MAX_BYTES) {
+ return {
+ ok: false,
+ error: `Shared context exceeds ${PROJECT_BRIEF_MAX_BYTES} bytes — keep it a curated brief, not a dump.`,
+ };
+ }
+ await writeProjectBrief(ctx.project_slug, content);
+ const { syncProjectAgents } = await import("./provision");
+ const synced = await syncProjectAgents(ctx.project_slug);
+ return { ok: true, data: { bytes: Buffer.byteLength(content, "utf8"), synced_agents: synced } };
+}
+
+/** Best-effort identity re-render after a goal spec change. */
+function syncIdentity(goal: Goal): Promise<void> {
+ return import("./provision")
+ .then(({ syncGoalIdentity }) => syncGoalIdentity(goal))
+ .catch((err) => console.warn("[goal-handlers] identity sync failed:", err));
+}
diff --git a/notfair/src/server/goals/identity.ts b/notfair/src/server/goals/identity.ts
new file mode 100644
index 00000000..82466a8b
--- /dev/null
+++ b/notfair/src/server/goals/identity.ts
@@ -0,0 +1,253 @@
+import { BROWSER_SKILL } from "@/server/skills/browser-skill";
+import type { Goal } from "@/server/db/goals";
+import type { Project } from "@/types";
+
+/**
+ * Identity + platform skill for a goal agent. Agent = goal: every agent
+ * owns exactly one goal, defined conversationally in its chat, then
+ * pursued via the tick loop.
+ *
+ * Everything volatile (current metric value, open actions, learnings) is
+ * injected per-tick by the tick runner, NOT baked in here — the identity
+ * only carries what's stable across a tick: who the agent is, the goal
+ * spec, and the protocol. Re-rendered (via syncGoalIdentity) whenever the
+ * goal's spec changes (defined, metric verified, target confirmed).
+ *
+ * NOTE: prompt file — per CLAUDE.md, changes here need an eval pass
+ * (tests/evals) before shipping.
+ */
+
+export const GOAL_SKILL = `## Platform skill: the goal loop
+
+You own exactly ONE goal. Your job is not to complete tasks — it is to
+move a number. Every turn is one iteration of an observe → orient →
+act → record loop, and the platform (not you) measures the number you
+are judged on.
+
+You operate autonomously — there is no approval inbox. Your controls
+are the spend envelope, the observation-window discipline below, and
+the user's pause button. That autonomy is borrowed trust: log
+everything, quote real numbers, and stay inside the envelope.
+
+### Context: shared vs. yours
+
+- **Shared workspace context** (PROJECT.md, also in your identity below)
+ is common to every agent in this workspace: what the company sells,
+ who buys, voice, constraints. When you learn something every agent
+ should know (positioning shift, a new product line, a global budget
+ rule), update it via \`set_shared_context\`. Keep it curated — it is
+ a brief, not a log.
+- **Your own memory** is the learnings ledger (\`log_learning\` /
+ \`search_learnings\`) plus your workspace files. Chat context
+ evaporates; these don't. Anything future ticks must know goes here.
+- **MCP data sources are shared** — every agent sees the same connected
+ platforms. Coordinate through the shared context, not by assumption.
+
+### Coordinate through NotFair's MCP tools
+
+State lives in tool calls, never in prose. Every tool requires
+\`project_slug\`, \`agent_id\`, and usually \`goal_id\` — take them from
+"Your runtime identity" above. Never guess.
+
+- \`get_goal\` — full goal state incl. the shared context, your logged
+ spend total, and resources gated by OTHER agents. Call FIRST whenever
+ you've lost context.
+- \`define_goal\` — intake: record the ambition + a compact
+ \`short_label\` ("Wasted X spend → $0") — the label is how the user
+ identifies this goal everywhere in the UI, so make it specific.
+- \`propose_goal_metric\` — intake: submit the metric you authored AND
+ tested; the platform re-runs it server-side and records the baseline.
+- \`backfill_metric_history\` — intake: submit a date-segmented version
+ of the metric (per-day values, ~30 days) so the progress chart has
+ history from day one.
+- \`propose_target\` — intake: record the target/cadence/envelope the
+ user agreed to. The USER starts the loop with the START button on
+ your Goal tab — you cannot start it, and the first tick fires the
+ moment they click.
+- \`amend_goal\` — adjust a live goal when the user asks: new target,
+ deadline, envelope, or cadence. Echo the change back after.
+- \`log_goal_action\` — record a move BEFORE you execute it: kind
+ (mutation / research / decision), description, resources_touched,
+ expected_effect, review_after_hours (required for mutations), and
+ spend_usd when the move commits incremental spend.
+- \`review_goal_action\` — score an action whose review date arrived:
+ what actually happened vs. expected_effect.
+- \`log_learning\` / \`search_learnings\` — your durable memory.
+- \`update_goal_status\` — declare achieved / failed, or pause. Requires
+ a reason grounded in the measured metric.
+- \`set_shared_context\` — rewrite the shared workspace brief (all
+ agents see it).
+
+### Intake: define the goal in conversation
+
+A fresh agent gets the user's ambition in its kickoff. Your first job
+is a short conversation that ends with a measurable goal:
+
+0. **Bootstrap the shared context if it's empty.** When no shared
+ workspace context exists yet, learn what the company is first —
+ skim the website from your workspace facts (browser tools), check
+ \`get_project\` — and write a tight brief via \`set_shared_context\`
+ (what they sell, who buys, positioning). Every later agent inherits
+ it; thirty seconds here pays forever.
+1. **Sharpen.** Acknowledge the ambition in one sentence. If it's vague
+ ("more customers"), ask the one or two questions that make it
+ measurable (which channel? what number? by when? spending what?).
+ Record it via \`define_goal\` with a tight \`short_label\` — refine by
+ calling it again.
+2. **Author the metric.** Explore the connected data sources, write ONE
+ tool call (usually \`runScript\`) that returns a single number — bare
+ number or \`{value: <number>}\`, trailing window (e.g. last 30 days)
+ so every tick measures the same shape. TEST it yourself.
+3. **Verify.** \`propose_goal_metric\`. If the platform can't reproduce
+ a number, fix the query and propose again. Then give the user's chart
+ its history: write the DATE-SEGMENTED version of the same query
+ (per-day values, ~30 days), test it, and submit it via
+ \`backfill_metric_history\`. Skip only if the source truly can't
+ segment by date.
+4. **Agree the target.** Report the measured baseline, suggest a target
+ + cadence + spend envelope, and ask. Choose the mode: \`achieve\`
+ (reach the number, then done) or \`maintain\` ("keep/hold/stay at X"
+ ambitions — the loop watches forever and never self-completes). When
+ the user agrees, record it with \`propose_target\` and tell them to
+ hit START on your Goal tab — the platform requires their click; you
+ cannot start the loop.
+
+If NO connected source can measure the ambition, say so plainly and
+name what to connect (the Connections page). Do not invent a proxy
+metric without flagging it.
+
+### The tick protocol
+
+Tick messages start with \`[TICK]\` and carry the freshly measured
+metric, your open actions (split into "due for review" and "still
+gated"), recent learnings, and stop-condition flags. On each tick, in
+order:
+
+1. **Review first.** For every action due for review, compare its
+ expected_effect against the metric + platform reality, call
+ \`review_goal_action\` with the observed outcome, and \`log_learning\`
+ anything durable. Do this before considering any new move.
+2. **Check stop conditions.** For ACHIEVE goals: target met (confirmed
+ by the measured value)? Deadline passed? Envelope exhausted? →
+ \`update_goal_status\` with the evidence, report, and stop. For
+ MAINTAIN goals: target met just means you're holding — never close
+ as achieved; report drift and act only when the number moves.
+3. **Respect the gate — yours AND your teammates'.** Resources inside
+ an open action's observation window are UNTOUCHABLE, and the tick
+ brief also lists resources gated by OTHER agents in this workspace:
+ treat those exactly the same. No reverts, no double-downs, no "small
+ tweaks". If every promising move is gated, do research (and log it
+ as a research action) or end the tick honestly: "nothing to do until
+ <date>" is a good tick, thrashing a live account is not.
+4. **One meaningful move, maximum.** Log it with \`log_goal_action\`
+ (expected effect + review_after_hours + spend_usd when it commits
+ incremental spend), then execute with your platform tools. One
+ mutation per tick — the ad platform's learning phase and your
+ attribution both break if you change three things at once. The tick
+ brief shows your logged spend total vs. the envelope; if the right
+ move would cross it, don't act — suggest \`amend_goal\` to the user
+ in your summary instead.
+5. **Close the diary.** End with a SHORT summary the user can read in
+ five seconds: the metric read, what you reviewed, what you did, when
+ you'll know if it worked.
+
+### Choosing review_after_hours
+
+Pick the window by what the platform needs to show a real effect:
+- pausing obvious waste (zero-conversion spend): 72–120h
+- bid / budget changes: 120–168h (learning phases reset on edits)
+- new keywords, creative, audiences: 168–336h
+When in doubt, longer. Reading noise as signal is the main way this
+loop fails.
+
+### Chat turns
+
+Messages that don't start with \`[TICK]\` are the user talking to you.
+Answer normally, but the same physics apply: gates hold, one mutation
+per turn, the envelope binds, and anything decided in chat that future
+ticks must know goes into \`log_learning\`.
+
+${BROWSER_SKILL}`;
+
+export function getGoalSkill(): string {
+ return GOAL_SKILL;
+}
+
+/**
+ * Render IDENTITY.md for a goal agent. Pure — provisioning writes it via
+ * the harness adapter (mirrored to CLAUDE.md / AGENTS.md per adapter).
+ */
+export function renderGoalIdentity(input: {
+ goal: Goal;
+ brief: string | null;
+ project?: Project | null;
+}): string {
+ const { goal, brief, project } = input;
+
+ const identityBlock = `## Your runtime identity
+
+When calling NotFair MCP tools, pass these exact values:
+
+- \`project_slug\`: \`${goal.project_slug}\`
+- \`agent_id\`: \`${goal.agent_id}\`
+- \`goal_id\`: \`${goal.id}\`
+
+Do NOT invent other values.`;
+
+ const hasStatement = goal.statement.trim().length > 0;
+ const specLines = [
+ hasStatement
+ ? `- **Statement**: ${goal.statement}`
+ : `- **Statement**: not defined yet — your first job is the intake conversation (see the intake protocol below).`,
+ goal.metric_name ? `- **Metric**: ${goal.metric_name}` : null,
+ goal.metric_direction
+ ? `- **Direction**: ${goal.metric_direction === "decrease" ? "drive it DOWN" : "drive it UP"}`
+ : null,
+ goal.baseline_value !== null ? `- **Baseline**: ${goal.baseline_value}` : null,
+ goal.target_value !== null ? `- **Target**: ${goal.target_value}` : null,
+ goal.deadline ? `- **Deadline**: ${goal.deadline}` : null,
+ goal.spend_envelope_usd !== null
+ ? `- **Spend envelope**: $${goal.spend_envelope_usd} total incremental ad spend — a hard ceiling, since there is no approval step`
+ : null,
+ ].filter(Boolean);
+
+ const factLines = [
+ project?.website_url ? `- Website: ${project.website_url}` : null,
+ project?.google_ads_account_id
+ ? `- Google Ads account: ${project.google_ads_account_id}`
+ : null,
+ project?.meta_ads_account_id
+ ? `- Meta Ads account: ${project.meta_ads_account_id}`
+ : null,
+ project?.gsc_property_id
+ ? `- Search Console property: ${project.gsc_property_id}`
+ : null,
+ ].filter(Boolean);
+ const factsSection =
+ factLines.length > 0
+ ? `\n## Workspace facts\n\n${factLines.join("\n")}\n`
+ : "";
+
+ const projectContextSection = brief
+ ? `\n## Shared workspace context\n\nCommon to every agent in this workspace — treat as the authoritative\ndescription of who the user is and what they sell. Update it via\n\`set_shared_context\` when you learn something all agents should know.\n\n${brief.trim()}\n`
+ : `\n## Shared workspace context\n\nNONE EXISTS YET. During intake, learn what the company is (skim the\nwebsite in your workspace facts, use \`get_project\`) and write the\nfirst brief via \`set_shared_context\` — every agent created after you\ninherits it.\n`;
+
+ return `# This goal's agent
+
+You are the agent for exactly one goal. You have no name and need
+none — the user knows you as "this goal's agent", and the goal's label
+is the identity that matters. You run a disciplined improvement loop
+against it until it is achieved, failed, or the user closes it. Live
+numbers (current metric value, open actions) arrive in each tick
+message — the values below are the spec, not the latest reading.
+
+## Your goal
+
+${specLines.join("\n")}
+
+${identityBlock}
+${factsSection}${projectContextSection}
+---
+
+${GOAL_SKILL}`;
+}
diff --git a/notfair/src/server/goals/intake.ts b/notfair/src/server/goals/intake.ts
new file mode 100644
index 00000000..5de808f1
--- /dev/null
+++ b/notfair/src/server/goals/intake.ts
@@ -0,0 +1,70 @@
+import { getProject } from "@/server/db/projects";
+import { listProjectMcpTokens } from "@/server/mcp/tokens";
+import { readProjectBrief } from "@/server/onboarding/project-brief";
+import type { Goal } from "@/server/db/goals";
+import { streamAgentTurn } from "./tick";
+
+/**
+ * The intake kickoff: fired the moment a goal agent is created, so the
+ * user lands in a chat where the agent is ALREADY working on their
+ * ambition — no dead air, no "say hi to get started". Runs on a fresh
+ * chat session (UUID label) that the chat index picks up as the latest
+ * thread; the user watches it stream live and joins in.
+ */
+
+export function buildIntakeKickoffMessage(input: {
+ goal: Goal;
+ connectedMcpKeys: string[];
+ hasSharedContext: boolean;
+}): string {
+ const { goal, connectedMcpKeys, hasSharedContext } = input;
+ return `[INTAKE] The user just created you for this ambition:
+
+> ${goal.statement}
+
+Connected data sources: ${
+ connectedMcpKeys.length > 0
+ ? connectedMcpKeys.join(", ")
+ : "NONE — nothing is measurable yet; say so plainly and point the user at the Connections page."
+ }
+${hasSharedContext ? "" : "\nNo shared workspace context exists yet — bootstrap it (intake protocol step 0) before or while you author the metric.\n"}
+Follow the intake protocol from your identity. Work NOW, don't just
+greet: acknowledge the ambition in one sentence, ask only what's truly
+blocking (if anything), then explore the data, author + TEST the metric
+query, verify it via propose_goal_metric, and report the measured
+baseline with a suggested target, cadence, and spend envelope. End by
+asking the user to confirm (they'll press START on your Goal tab after
+you record their agreement via propose_target).`;
+}
+
+/** Fire-and-forget from goal creation. The goal screen's embedded chat
+ * streams it live — one conversation per goal, on the "main" session. */
+export async function runGoalIntake(goal: Goal): Promise<void> {
+ const project = getProject(goal.project_slug);
+ if (!project) {
+ console.error(`[goal-intake] project not found: ${goal.project_slug}`);
+ return;
+ }
+ const connectedMcpKeys = listProjectMcpTokens(goal.project_slug).map(
+ (t) => t.server_name,
+ );
+ const brief = await readProjectBrief(goal.project_slug).catch(() => null);
+ const message = buildIntakeKickoffMessage({
+ goal,
+ connectedMcpKeys,
+ hasSharedContext: Boolean(brief?.trim()),
+ });
+ try {
+ await streamAgentTurn({
+ projectSlug: project.slug,
+ harnessAdapter: project.harness_adapter,
+ agentId: goal.agent_id,
+ // One conversation per goal.
+ sessionLabel: "main",
+ message,
+ source: "goal-intake",
+ });
+ } catch (err) {
+ console.error("[goal-intake] intake turn failed:", err);
+ }
+}
diff --git a/notfair/src/server/goals/metric.ts b/notfair/src/server/goals/metric.ts
new file mode 100644
index 00000000..b3b7b0ec
--- /dev/null
+++ b/notfair/src/server/goals/metric.ts
@@ -0,0 +1,240 @@
+import { mcpRpcAutoRefresh } from "@/server/mcp/rpc";
+import type { Goal } from "@/server/db/goals";
+
+/**
+ * Mechanical execution of a goal's stored metric query against a catalog
+ * MCP (e.g. notfair-googleads `runScript`). This is the loop's ground
+ * truth: the tick runner calls it BEFORE the agent wakes, so the agent
+ * never self-reports the number it is being judged on. The same path
+ * verifies the metric during intake (`propose_goal_metric`) — a metric
+ * that can't be measured here is rejected before the goal can activate.
+ */
+
+export type MetricMeasurement =
+ | { ok: true; value: number }
+ | { ok: false; error: string };
+
+const METRIC_TIMEOUT_MS = 60_000;
+
+/** Shape of an MCP tools/call result envelope. */
+type ToolCallResult = {
+ content?: Array<{ type?: string; text?: string }>;
+ isError?: boolean;
+};
+
+export type MetricSource = {
+ /** Catalog MCP key, e.g. "notfair-googleads". */
+ key: string;
+ /** Tool to call on that server, e.g. "runScript". */
+ tool: string;
+ /** JSON-encoded arguments object for the tool call. */
+ args_json: string;
+};
+
+export function metricSourceFromGoal(goal: Goal): MetricSource | null {
+ if (!goal.metric_source_key || !goal.metric_source_tool || !goal.metric_source_args_json) {
+ return null;
+ }
+ return {
+ key: goal.metric_source_key,
+ tool: goal.metric_source_tool,
+ args_json: goal.metric_source_args_json,
+ };
+}
+
+/**
+ * Coerce a metric script's return payload into a single number.
+ *
+ * Convention (taught in the goal agent's identity): the script should
+ * return a bare number or `{ value: <number> }`. We tolerate the obvious
+ * near-misses (numeric strings, a single-element array, a nested `value`)
+ * but refuse anything ambiguous — a metric that needs interpretation is a
+ * metric the loop can't trust.
+ */
+export function parseMetricValue(payload: unknown, depth = 0): number | null {
+ if (depth > 3) return null;
+ if (typeof payload === "number" && Number.isFinite(payload)) return payload;
+ if (typeof payload === "string") {
+ const trimmed = payload.trim();
+ if (trimmed === "") return null;
+ const n = Number(trimmed);
+ return Number.isFinite(n) ? n : null;
+ }
+ if (Array.isArray(payload)) {
+ return payload.length === 1 ? parseMetricValue(payload[0], depth + 1) : null;
+ }
+ if (payload && typeof payload === "object") {
+ // Tolerated wrappers: {value}, and the runScript sandboxes' response
+ // envelope {ok, result} (both Google Ads and X Ads wrap script
+ // returns this way).
+ if ("value" in payload) {
+ return parseMetricValue((payload as { value: unknown }).value, depth + 1);
+ }
+ if ("result" in payload) {
+ return parseMetricValue((payload as { result: unknown }).result, depth + 1);
+ }
+ }
+ return null;
+}
+
+/**
+ * Execute a metric source against its catalog MCP and return the number.
+ * Token lookup, refresh, and SSE/JSON response parsing are handled by
+ * `mcpRpcAutoRefresh` (the same plumbing onboarding uses for account
+ * listing). Every failure mode maps to a human-readable error string that
+ * the tick diary / goal page can surface verbatim.
+ */
+export async function runMetricSource(
+ project_slug: string,
+ source: MetricSource,
+): Promise<MetricMeasurement> {
+ let args: Record<string, unknown>;
+ try {
+ const parsed = JSON.parse(source.args_json);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return { ok: false, error: "metric_source_args_json must encode a JSON object" };
+ }
+ args = parsed as Record<string, unknown>;
+ } catch {
+ return { ok: false, error: "metric_source_args_json is not valid JSON" };
+ }
+
+ const rpc = await mcpRpcAutoRefresh<ToolCallResult>(
+ project_slug,
+ source.key,
+ "tools/call",
+ { name: source.tool, arguments: args },
+ { timeoutMs: METRIC_TIMEOUT_MS },
+ );
+
+ if (!rpc.ok) {
+ const detail = "message" in rpc && rpc.message ? `: ${rpc.message}` : "";
+ return {
+ ok: false,
+ error: `Metric query failed against ${source.key} (${rpc.kind}${detail})`,
+ };
+ }
+
+ const result = rpc.result;
+ const text = result?.content?.find((c) => c.type === "text")?.text ?? "";
+
+ if (result?.isError) {
+ return {
+ ok: false,
+ error: `Metric tool '${source.tool}' errored: ${truncate(text || "(no detail)", 500)}`,
+ };
+ }
+
+ let payload: unknown = text;
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ // Not JSON — fall through; parseMetricValue handles numeric strings.
+ }
+
+ const value = parseMetricValue(payload);
+ if (value === null) {
+ return {
+ ok: false,
+ error: `Metric query returned a non-numeric result. The script must return a single number (or {value: number}). Got: ${truncate(text, 300)}`,
+ };
+ }
+ return { ok: true, value };
+}
+
+/** Measure a goal's metric. Errors if the goal has no metric spec yet. */
+export async function measureGoalMetric(goal: Goal): Promise<MetricMeasurement> {
+ const source = metricSourceFromGoal(goal);
+ if (!source) {
+ return { ok: false, error: "Goal has no metric definition yet (still in intake?)" };
+ }
+ return runMetricSource(goal.project_slug, source);
+}
+
+export type HistoryPoint = { date: string; value: number };
+
+/**
+ * Parse a history query's payload into per-day points. Convention: the
+ * script returns an ARRAY of {date, value} (date = YYYY-MM-DD or ISO).
+ * Tolerates the runScript {ok, result} envelope, {rows: [...]} wrappers,
+ * and `day`/`metric` key aliases — but every row must yield a parseable
+ * date and a finite number, and the whole series is rejected otherwise:
+ * a chart built on guessed data is worse than no chart.
+ */
+export function parseHistoryPoints(payload: unknown, depth = 0): HistoryPoint[] | null {
+ if (depth > 3 || payload === null || payload === undefined) return null;
+ if (Array.isArray(payload)) {
+ if (payload.length === 0 || payload.length > 400) return null;
+ const points: HistoryPoint[] = [];
+ for (const row of payload) {
+ if (!row || typeof row !== "object") return null;
+ const r = row as Record<string, unknown>;
+ const rawDate = r.date ?? r.day ?? r.ts;
+ const rawValue = r.value ?? r.metric ?? r.v;
+ const value = parseMetricValue(rawValue);
+ if (typeof rawDate !== "string" || value === null) return null;
+ const t = Date.parse(rawDate);
+ if (Number.isNaN(t)) return null;
+ points.push({ date: new Date(t).toISOString(), value });
+ }
+ points.sort((a, b) => a.date.localeCompare(b.date));
+ return points;
+ }
+ if (typeof payload === "object") {
+ const o = payload as Record<string, unknown>;
+ if ("result" in o) return parseHistoryPoints(o.result, depth + 1);
+ if ("rows" in o) return parseHistoryPoints(o.rows, depth + 1);
+ if ("value" in o) return parseHistoryPoints(o.value, depth + 1);
+ }
+ return null;
+}
+
+/** Execute a history source and return parsed per-day points. */
+export async function runHistorySource(
+ project_slug: string,
+ source: MetricSource,
+): Promise<{ ok: true; points: HistoryPoint[] } | { ok: false; error: string }> {
+ let args: Record<string, unknown>;
+ try {
+ const parsed = JSON.parse(source.args_json);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return { ok: false, error: "history args_json must encode a JSON object" };
+ }
+ args = parsed as Record<string, unknown>;
+ } catch {
+ return { ok: false, error: "history args_json is not valid JSON" };
+ }
+ const rpc = await mcpRpcAutoRefresh<ToolCallResult>(
+ project_slug,
+ source.key,
+ "tools/call",
+ { name: source.tool, arguments: args },
+ { timeoutMs: METRIC_TIMEOUT_MS },
+ );
+ if (!rpc.ok) {
+ const detail = "message" in rpc && rpc.message ? `: ${rpc.message}` : "";
+ return { ok: false, error: `History query failed against ${source.key} (${rpc.kind}${detail})` };
+ }
+ const text = rpc.result?.content?.find((c) => c.type === "text")?.text ?? "";
+ if (rpc.result?.isError) {
+ return { ok: false, error: `History tool errored: ${truncate(text || "(no detail)", 500)}` };
+ }
+ let payload: unknown = text;
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ // fall through
+ }
+ const points = parseHistoryPoints(payload);
+ if (!points) {
+ return {
+ ok: false,
+ error: `History query must return an array of {date, value} rows (1–400 points). Got: ${truncate(text, 300)}`,
+ };
+ }
+ return { ok: true, points };
+}
+
+function truncate(s: string, max: number): string {
+ return s.length > max ? `${s.slice(0, max)}…` : s;
+}
diff --git a/notfair/src/server/goals/provision.ts b/notfair/src/server/goals/provision.ts
new file mode 100644
index 00000000..ce0b9ca1
--- /dev/null
+++ b/notfair/src/server/goals/provision.ts
@@ -0,0 +1,149 @@
+import { provisionAgent } from "@/server/agents/provisioning";
+import { readAgentMeta, writeAgentMeta } from "@/server/agent-meta";
+import { getProject } from "@/server/db/projects";
+import type { Goal } from "@/server/db/goals";
+import { readProjectBrief } from "@/server/onboarding/project-brief";
+import { DEFAULT_HARNESS_ADAPTER } from "@/server/adapters/registry";
+import {
+ registerBrowserMcpForAgent,
+ registerCatalogMcpForAgent,
+ registerGoalsMcpForAgent,
+} from "@/server/mcp-server/registration";
+import { listProjectMcpTokens } from "@/server/mcp/tokens";
+import { goalLabel } from "@/lib/goal-label";
+import { getGoalSkill, renderGoalIdentity } from "./identity";
+
+/**
+ * Provisioning for goal agents. An agent is a consequence of a goal
+ * existing: created with the goal, identity re-rendered as the goal's spec
+ * evolves (metric authored, target confirmed), garbage-collected with it.
+ */
+
+export const GOAL_TEMPLATE_KEY = "goal";
+
+/**
+ * Agents are anonymous plumbing (goals carry the display identity), so
+ * ids are sequential: url slug `goal-<n>`, agent id
+ * `<project>-goal-<n>`. Stable forever — labels can change, URLs don't.
+ */
+export function goalAgentUrlSlug(n: number): string {
+ return `goal-${n}`;
+}
+
+export function goalAgentIdFor(project_slug: string, n: number): string {
+ return `${project_slug}-${goalAgentUrlSlug(n)}`;
+}
+
+/**
+ * Write the goal agent's workspace (IDENTITY.md + skill + project brief via
+ * the project's harness adapter), its meta sidecar, and wire every MCP the
+ * project has: goals, browser, and all connected catalog servers.
+ * Idempotent — re-running refreshes files in place.
+ */
+export async function provisionGoalAgent(input: {
+ goal: Goal;
+ urlSlug: string;
+}): Promise<void> {
+ const { goal, urlSlug } = input;
+ const project = getProject(goal.project_slug);
+ if (!project) throw new Error(`project not found: ${goal.project_slug}`);
+ const harnessAdapter = project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;
+
+ const brief = await readProjectBrief(goal.project_slug).catch(() => null);
+ const identityMd = renderGoalIdentity({ goal, brief, project });
+ const label = goalLabel(goal);
+
+ await provisionAgent({
+ projectSlug: goal.project_slug,
+ agentId: goal.agent_id,
+ displayName: label,
+ templateKey: GOAL_TEMPLATE_KEY,
+ identityMd,
+ skillMd: getGoalSkill(),
+ projectMd: brief ?? undefined,
+ harnessAdapter,
+ });
+
+ const existing = readAgentMeta(goal.agent_id);
+ await writeAgentMeta({
+ agent_id: goal.agent_id,
+ project_slug: goal.project_slug,
+ // meta.name mirrors the goal label so any surface still reading it
+ // (deletion summaries, etc.) shows the goal, not a persona.
+ name: label,
+ slug: existing?.slug ?? urlSlug,
+ created_at: existing?.created_at ?? new Date().toISOString(),
+ });
+
+ // MCP wiring is best-effort per server — a goal agent without browser
+ // access still has its loop tools. Log and continue on failure.
+ try {
+ await registerGoalsMcpForAgent(goal.project_slug, goal.agent_id);
+ } catch (err) {
+ console.warn(`[goal-provision] goals MCP failed for ${goal.agent_id}:`, err);
+ }
+ try {
+ await registerBrowserMcpForAgent(goal.project_slug, goal.agent_id);
+ } catch (err) {
+ console.warn(`[goal-provision] browser MCP failed for ${goal.agent_id}:`, err);
+ }
+ try {
+ const tokens = listProjectMcpTokens(goal.project_slug);
+ for (const t of tokens) {
+ await registerCatalogMcpForAgent(goal.project_slug, t.server_name, goal.agent_id);
+ }
+ } catch (err) {
+ console.warn(`[goal-provision] catalog MCP wiring failed for ${goal.agent_id}:`, err);
+ }
+}
+
+/**
+ * Re-render IDENTITY.md after a goal spec change (metric proposed, target
+ * confirmed). Keeps the agent's on-disk brain in sync with the DB without
+ * touching MCP wiring. Best-effort — callers treat failure as non-fatal
+ * since the next full provision heals it.
+ */
+/**
+ * Re-render IDENTITY.md for every goal agent in a project — called when
+ * the shared workspace context (PROJECT.md) changes so all agents see it
+ * on their next turn. Returns the number of agents synced.
+ */
+export async function syncProjectAgents(project_slug: string): Promise<number> {
+ const { listProjectAgents } = await import("@/server/agent-meta");
+ const { getGoalForAgent } = await import("@/server/db/goals");
+ const entries = await listProjectAgents(project_slug);
+ let synced = 0;
+ for (const entry of entries) {
+ const goal = getGoalForAgent(entry.agent_id);
+ if (!goal) continue;
+ try {
+ await syncGoalIdentity(goal);
+ synced++;
+ } catch (err) {
+ console.warn(`[goal-provision] brief sync failed for ${entry.agent_id}:`, err);
+ }
+ }
+ return synced;
+}
+
+export async function syncGoalIdentity(goal: Goal): Promise<void> {
+ const meta = readAgentMeta(goal.agent_id);
+ const project = getProject(goal.project_slug);
+ if (!project) return;
+ const brief = await readProjectBrief(goal.project_slug).catch(() => null);
+ const label = goalLabel(goal);
+ await provisionAgent({
+ projectSlug: goal.project_slug,
+ agentId: goal.agent_id,
+ displayName: label,
+ templateKey: GOAL_TEMPLATE_KEY,
+ identityMd: renderGoalIdentity({ goal, brief, project }),
+ skillMd: getGoalSkill(),
+ projectMd: brief ?? undefined,
+ harnessAdapter: project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,
+ });
+ // Keep the meta label in sync so headers/deletion summaries follow the goal.
+ if (meta && meta.name !== label) {
+ await writeAgentMeta({ ...meta, name: label });
+ }
+}
diff --git a/notfair/src/server/goals/tick.ts b/notfair/src/server/goals/tick.ts
new file mode 100644
index 00000000..c05eb01f
--- /dev/null
+++ b/notfair/src/server/goals/tick.ts
@@ -0,0 +1,387 @@
+import { getProject } from "@/server/db/projects";
+import { requireAdapter } from "@/server/adapters/registry";
+import { workspaceDirFor } from "@/server/agents/provisioning";
+import {
+ appendTranscriptEvent,
+ getOrCreateSession,
+ touchSession,
+} from "@/server/sessions";
+import {
+ attachTickSession,
+ createGoalTick,
+ dueGoals,
+ finishGoalTick,
+ getGoal,
+ getLastFinishedTick,
+ isPastDeadline,
+ isTargetMet,
+ listActionsDueForReview,
+ listGatedActions,
+ listGatedActionsForOtherAgents,
+ listGoalLearnings,
+ loggedSpendTotal,
+ markGoalTicked,
+ recordMetricSnapshot,
+ setNextTickAt,
+ type Goal,
+ type GoalAction,
+ type GoalLearning,
+ type GoalTick,
+ type GoalTickTrigger,
+} from "@/server/db/goals";
+import { measureGoalMetric, type MetricMeasurement } from "./metric";
+
+/**
+ * The goal loop's tick runner — one OODA iteration per invocation.
+ *
+ * A tick: measure the metric mechanically (agent never self-reports) →
+ * snapshot → compose the tick brief from DB state → run one adapter turn →
+ * record the diary row. Heartbeats are driven by goals.next_tick_at via
+ * the shared 30s scheduler interval; manual runs and approval wake-ups
+ * call runGoalTick directly.
+ */
+
+const MAX_SUMMARY = 4000;
+
+/** In-process re-entrancy guard: one running tick per goal. */
+const runningTicks = new Set<string>();
+
+export type TickContext = {
+ goal: Goal;
+ tickNumber: number;
+ nowIso: string;
+ measurement: MetricMeasurement;
+ targetMet: boolean | null;
+ pastDeadline: boolean;
+ actionsDueForReview: GoalAction[];
+ gatedActions: GoalAction[];
+ gatedByOthers: Array<GoalAction & { agent_id: string }>;
+ loggedSpendUsd: number;
+ recentLearnings: GoalLearning[];
+ lastTick: GoalTick | null;
+ /** Extra leading section, e.g. an approval decision on wake-up. */
+ extraContext?: string;
+};
+
+function fmtValue(v: number | null): string {
+ return v === null ? "—" : String(v);
+}
+
+function daysUntil(deadline: string, nowIso: string): number {
+ return Math.ceil(
+ (new Date(deadline).getTime() - new Date(nowIso).getTime()) / 86_400_000,
+ );
+}
+
+/**
+ * Compose the tick brief. Pure — everything volatile the agent needs is
+ * injected here so the turn is self-sufficient even after the agent's
+ * context has rotated. Kept scannable: the agent's protocol lives in its
+ * identity; this message carries only the live state.
+ */
+export function buildTickMessage(ctx: TickContext): string {
+ const { goal } = ctx;
+ const lines: string[] = [];
+
+ lines.push(`[TICK] Goal heartbeat #${ctx.tickNumber} — ${ctx.nowIso}`);
+ lines.push("");
+
+ if (ctx.extraContext) {
+ lines.push(ctx.extraContext.trim());
+ lines.push("");
+ }
+
+ lines.push("## Metric (measured by the platform just now)");
+ if (ctx.measurement.ok) {
+ lines.push(`- ${goal.metric_name ?? "metric"}: **${ctx.measurement.value}**`);
+ } else {
+ lines.push(`- MEASUREMENT FAILED: ${ctx.measurement.error}`);
+ lines.push(
+ "- Diagnose before anything else. If the query is broken, fix your approach; if the connection/token is broken, call update_goal_status with status=paused and a reason quoting this error so the user can reconnect.",
+ );
+ }
+ lines.push(
+ `- Baseline: ${fmtValue(goal.baseline_value)} | Target: ${fmtValue(goal.target_value)} (${goal.metric_direction ?? "?"})`,
+ );
+ lines.push("");
+
+ lines.push("## Stop-condition flags");
+ if (goal.mode === "maintain") {
+ lines.push(
+ `- holding_at_target: ${ctx.targetMet === null ? "unknown" : ctx.targetMet} — MAINTAIN goal: target met is the steady state, NOT a reason to close. Watch for drift; act only when the number leaves target.`,
+ );
+ } else {
+ lines.push(`- target_met: ${ctx.targetMet === null ? "unknown" : ctx.targetMet}`);
+ }
+ if (goal.deadline) {
+ const d = daysUntil(goal.deadline, ctx.nowIso);
+ lines.push(
+ `- deadline: ${goal.deadline} (${ctx.pastDeadline ? "PASSED" : `${d} day${d === 1 ? "" : "s"} left`})`,
+ );
+ } else {
+ lines.push("- deadline: none");
+ }
+ lines.push(
+ goal.spend_envelope_usd !== null
+ ? `- spend: $${ctx.loggedSpendUsd} logged of $${goal.spend_envelope_usd} envelope — a hard ceiling. Log spend_usd on every spend-committing action; if the right move would cross the ceiling, don't act — suggest amend_goal to the user in your summary.`
+ : "- spend envelope: none set — treat any NEW incremental spend as out of bounds until the user sets one (they can, via amend_goal in chat).",
+ );
+ if ((ctx.targetMet && goal.mode !== "maintain") || ctx.pastDeadline) {
+ lines.push(
+ "- A stop condition looks met. Verify against the measured metric and close the goal with update_goal_status before doing anything else.",
+ );
+ }
+ lines.push("");
+
+ lines.push("## Actions due for review (score these FIRST via review_goal_action)");
+ if (ctx.actionsDueForReview.length === 0) {
+ lines.push("- none");
+ } else {
+ for (const a of ctx.actionsDueForReview.slice(0, 10)) {
+ lines.push(
+ `- [${a.id}] ${a.description} — expected: ${a.expected_effect} (review was due ${a.review_after})`,
+ );
+ }
+ }
+ lines.push("");
+
+ lines.push("## Actions still gated (their resources are UNTOUCHABLE)");
+ if (ctx.gatedActions.length === 0) {
+ lines.push("- none");
+ } else {
+ for (const a of ctx.gatedActions.slice(0, 10)) {
+ const resources = JSON.parse(a.resources_touched_json || "[]") as string[];
+ lines.push(
+ `- [${a.id}] ${a.description} — resources: ${resources.join(", ") || "(unspecified)"} — until ${a.review_after}`,
+ );
+ }
+ }
+ lines.push("");
+
+ if (ctx.gatedByOthers.length > 0) {
+ lines.push(
+ "## Gated by OTHER agents in this workspace (equally untouchable)",
+ );
+ for (const a of ctx.gatedByOthers.slice(0, 10)) {
+ const resources = JSON.parse(a.resources_touched_json || "[]") as string[];
+ lines.push(
+ `- (${a.agent_id}) ${a.description} — resources: ${resources.join(", ") || "(unspecified)"} — until ${a.review_after}`,
+ );
+ }
+ lines.push("");
+ }
+
+ lines.push("## Recent learnings");
+ if (ctx.recentLearnings.length === 0) {
+ lines.push("- none yet — use search_learnings for older ones once they exist");
+ } else {
+ for (const l of ctx.recentLearnings.slice(0, 8)) {
+ lines.push(`- (${l.confidence}) ${l.body}`);
+ }
+ }
+ lines.push("");
+
+ if (ctx.lastTick) {
+ lines.push(
+ `## Last tick\n#${ctx.lastTick.tick_number} (${ctx.lastTick.status}): ${ctx.lastTick.summary ?? "(no summary)"}`,
+ );
+ lines.push("");
+ }
+
+ lines.push(
+ "Follow the tick protocol from your identity: review first → check stop conditions → respect the gate → at most ONE meaningful move (log it before executing) → end with a short diary line.",
+ );
+
+ return lines.join("\n");
+}
+
+/**
+ * Run one tick for a goal. Fire-and-forget safe: never throws; every
+ * failure lands on the goal_ticks row so the diary shows it.
+ */
+export async function runGoalTick(
+ goalRef: Goal | string,
+ trigger: GoalTickTrigger,
+ opts: { extraContext?: string } = {},
+): Promise<void> {
+ const goalId = typeof goalRef === "string" ? goalRef : goalRef.id;
+ // Re-read: the caller's snapshot may be stale (paused/killed since).
+ const goal = getGoal(goalId);
+ if (!goal || goal.status !== "active") return;
+ if (runningTicks.has(goal.id)) {
+ console.warn(`[goal-tick] tick already running for goal ${goal.id}; skipping`);
+ return;
+ }
+ runningTicks.add(goal.id);
+ try {
+ await runGoalTickInner(goal, trigger, opts);
+ } catch (err) {
+ console.error(`[goal-tick] tick failed for goal ${goal.id}:`, err);
+ } finally {
+ runningTicks.delete(goal.id);
+ }
+}
+
+async function runGoalTickInner(
+ goal: Goal,
+ trigger: GoalTickTrigger,
+ opts: { extraContext?: string },
+): Promise<void> {
+ const project = getProject(goal.project_slug);
+ if (!project) {
+ console.error(`[goal-tick] project not found: ${goal.project_slug}`);
+ return;
+ }
+
+ // Advance the heartbeat immediately (double-fire guard) and claim the
+ // tick number.
+ const tickNumber = markGoalTicked(goal.id);
+ const nowIso = new Date().toISOString();
+
+ // Ground truth first: the platform measures, not the agent.
+ const measurement = await measureGoalMetric(goal);
+ if (measurement.ok) {
+ recordMetricSnapshot(goal.id, measurement.value, "tick");
+ }
+ const freshGoal = getGoal(goal.id)!;
+
+ const tick = createGoalTick({
+ goal_id: goal.id,
+ tick_number: tickNumber,
+ trigger_kind: trigger,
+ metric_value: measurement.ok ? measurement.value : null,
+ metric_error: measurement.ok ? null : measurement.error,
+ });
+
+ const message = buildTickMessage({
+ goal: freshGoal,
+ tickNumber,
+ nowIso,
+ measurement,
+ targetMet: isTargetMet(freshGoal),
+ pastDeadline: isPastDeadline(freshGoal, nowIso),
+ actionsDueForReview: listActionsDueForReview(goal.id, nowIso),
+ gatedActions: listGatedActions(goal.id, nowIso),
+ gatedByOthers: listGatedActionsForOtherAgents(goal.project_slug, goal.id, nowIso),
+ loggedSpendUsd: loggedSpendTotal(goal.id),
+ recentLearnings: listGoalLearnings(goal.id, 8),
+ lastTick: getLastFinishedTick(goal.id),
+ extraContext: opts.extraContext,
+ });
+
+ try {
+ const { sessionId, summary } = await streamAgentTurn({
+ projectSlug: project.slug,
+ harnessAdapter: project.harness_adapter,
+ agentId: goal.agent_id,
+ sessionLabel: `tick-${tickNumber}`,
+ message,
+ source: "goal-tick",
+ });
+ attachTickSession(tick.id, sessionId);
+ finishGoalTick(tick.id, "done", summary);
+ smartSleep(goal.id);
+ } catch (err) {
+ const messageText = err instanceof Error ? err.message : String(err);
+ finishGoalTick(tick.id, "failed", messageText);
+ }
+}
+
+/**
+ * Smart sleep: when the tick ends with no reviews pending and every open
+ * mutation still inside its observation window, the next heartbeat is
+ * pushed to the earliest review date — waking an LLM daily to conclude
+ * "nothing to do until Jul 16" burns tokens for nothing. Never moves the
+ * heartbeat earlier than the cron already scheduled, never past the
+ * deadline, and the user's "Run tick now" always works regardless.
+ */
+function smartSleep(goalId: string): void {
+ const goal = getGoal(goalId);
+ if (!goal || goal.status !== "active" || !goal.next_tick_at) return;
+ const nowIso = new Date().toISOString();
+ if (listActionsDueForReview(goal.id, nowIso).length > 0) return;
+ const gated = listGatedActions(goal.id, nowIso);
+ if (gated.length === 0) return;
+ const earliestReview = gated
+ .map((a) => a.review_after!)
+ .sort()[0]!;
+ if (earliestReview <= goal.next_tick_at) return;
+ const capped =
+ goal.deadline && goal.deadline < earliestReview ? goal.deadline : earliestReview;
+ setNextTickAt(goal.id, capped);
+}
+
+/**
+ * Heartbeat sweep — called from the shared scheduler interval. Ticks run
+ * sequentially (there's only ever one live goal per project today, and
+ * sequential keeps SQLite + subprocess pressure sane).
+ */
+export async function runDueGoalTicks(): Promise<void> {
+ const due = dueGoals();
+ for (const goal of due) {
+ await runGoalTick(goal, "heartbeat");
+ }
+}
+
+/**
+ * Run one full agent turn server-side and persist the transcript — the
+ * same inline pattern as scheduler dispatchJob / task kickoff. Returns the
+ * session id (for the tick diary link) and a truncated summary.
+ */
+export async function streamAgentTurn(input: {
+ projectSlug: string;
+ harnessAdapter: "claude-code-local" | "codex-local";
+ agentId: string;
+ sessionLabel: string;
+ message: string;
+ source: string;
+}): Promise<{ sessionId: string; summary: string | null }> {
+ const adapter = requireAdapter(input.harnessAdapter);
+ const session = getOrCreateSession({
+ project_slug: input.projectSlug,
+ agent_id: input.agentId,
+ label: input.sessionLabel,
+ harness_adapter: input.harnessAdapter,
+ });
+ appendTranscriptEvent(session.id, "user", { text: input.message, source: input.source });
+
+ let finalText: string | null = null;
+ let deltaBuffer = "";
+ const errors: { message: string; transient: boolean }[] = [];
+
+ for await (const evt of adapter.execute({
+ projectSlug: input.projectSlug,
+ agentId: input.agentId,
+ workspaceDir: workspaceDirFor(input.agentId),
+ message: input.message,
+ threadId: session.id,
+ harnessSessionId: session.harness_session_id,
+ })) {
+ if (evt.kind === "session") {
+ touchSession(session.id, evt.harnessSessionId);
+ continue;
+ }
+ appendTranscriptEvent(session.id, evt.kind, evt);
+ if (evt.kind === "final") {
+ finalText = evt.text;
+ } else if (evt.kind === "delta" && deltaBuffer.length < MAX_SUMMARY) {
+ deltaBuffer += evt.text;
+ } else if (evt.kind === "error") {
+ errors.push({ message: evt.message, transient: evt.transient ?? false });
+ }
+ }
+ touchSession(session.id);
+
+ if (finalText === null && errors.length > 0) {
+ const terminal = [...errors].reverse().find((e) => !e.transient);
+ throw new Error((terminal ?? errors[errors.length - 1]!).message);
+ }
+
+ const raw = (finalText ?? deltaBuffer).trim();
+ const summary = raw
+ ? raw.length > MAX_SUMMARY
+ ? `${raw.slice(0, MAX_SUMMARY)}…`
+ : raw
+ : null;
+ return { sessionId: session.id, summary };
+}
diff --git a/notfair-cmo/src/server/harness-usage.ts b/notfair/src/server/harness-usage.ts
similarity index 100%
rename from notfair-cmo/src/server/harness-usage.ts
rename to notfair/src/server/harness-usage.ts
diff --git a/notfair-cmo/src/server/live-events/emitter.ts b/notfair/src/server/live-events/emitter.ts
similarity index 96%
rename from notfair-cmo/src/server/live-events/emitter.ts
rename to notfair/src/server/live-events/emitter.ts
index 40cad9d8..229f4087 100644
--- a/notfair-cmo/src/server/live-events/emitter.ts
+++ b/notfair/src/server/live-events/emitter.ts
@@ -10,7 +10,7 @@ import type { TranscriptEvent } from "@/server/sessions";
* live turn receive the event in milliseconds instead of waiting for the
* next 500ms DB poll.
*
- * Single-process only (notfair-cmo is a local Next.js app). If we ever
+ * Single-process only (NotFair is a local Next.js app). If we ever
* cluster, swap this for a Redis pub/sub or move events through the DB
* with NOTIFY/LISTEN — same subscriber API at the call site.
*/
diff --git a/notfair-cmo/src/server/mcp-catalog.ts b/notfair/src/server/mcp-catalog.ts
similarity index 98%
rename from notfair-cmo/src/server/mcp-catalog.ts
rename to notfair/src/server/mcp-catalog.ts
index 6398d9d7..e03bb614 100644
--- a/notfair-cmo/src/server/mcp-catalog.ts
+++ b/notfair/src/server/mcp-catalog.ts
@@ -1,5 +1,5 @@
/**
- * Project-scoped catalog of MCP servers the notfair-cmo UI knows about.
+ * Project-scoped catalog of MCP servers the NotFair UI knows about.
*
* Two sources merge into one list:
*
diff --git a/notfair-cmo/src/server/mcp-pending.ts b/notfair/src/server/mcp-pending.ts
similarity index 98%
rename from notfair-cmo/src/server/mcp-pending.ts
rename to notfair/src/server/mcp-pending.ts
index 4e4aca98..92d5805c 100644
--- a/notfair-cmo/src/server/mcp-pending.ts
+++ b/notfair/src/server/mcp-pending.ts
@@ -41,7 +41,7 @@ export type PendingMcpFlow = {
// in-flight flow. Pinning to `globalThis` survives hot reloads because the
// global is not recreated. The single-process invariant still holds (the
// CLI launches one local Next.js server), so we don't need a real KV.
-const GLOBAL_KEY = "__notfair_cmo_mcp_pending__";
+const GLOBAL_KEY = "__notfair_mcp_pending__";
type GlobalSlot = { store?: Map<string, PendingMcpFlow> };
const slot = globalThis as unknown as GlobalSlot;
const STORE: Map<string, PendingMcpFlow> = slot.store ?? (slot.store = new Map());
diff --git a/notfair-cmo/src/server/mcp-server/browser-tools.ts b/notfair/src/server/mcp-server/browser-tools.ts
similarity index 98%
rename from notfair-cmo/src/server/mcp-server/browser-tools.ts
rename to notfair/src/server/mcp-server/browser-tools.ts
index 7bfc8cde..07880752 100644
--- a/notfair-cmo/src/server/mcp-server/browser-tools.ts
+++ b/notfair/src/server/mcp-server/browser-tools.ts
@@ -377,14 +377,14 @@ function isToolResult(x: unknown): x is ToolResult {
// Following Hermes' convention (tools/browser_tool.py:1473), every browser
// tool description does explicit traffic control: when to use it, when
// something else is better, and (importantly) what NOT to fall back to.
-// This matters because notfair-cmo runs agents under Codex CLI / Claude
+// This matters because NotFair runs agents under Codex CLI / Claude
// Code, both of which may ship bundled "browser" plugins that compete
// for the same intent. Strong descriptions outcompete generic plugins by
// making the right tool obviously the right choice.
const ROUTING_PREAMBLE =
- "This is the ONLY browser tool that drives the notfair-cmo workspace browser " +
- "(persistent profile at ~/.notfair-cmo/projects/<slug>/browser/, shared by " +
+ "This is the ONLY browser tool that drives the NotFair workspace browser " +
+ "(persistent profile at ~/.notfair/projects/<slug>/browser/, shared by " +
"every agent in the project, where the user has signed into Google/Meta/etc.). " +
"Do NOT use any other 'browser-use' plugin, `open -a 'Google Chrome'` shell " +
"commands, AppleScript, or similar — those launch a different Chrome with the " +
diff --git a/notfair-cmo/src/server/mcp-server/jsonrpc.ts b/notfair/src/server/mcp-server/jsonrpc.ts
similarity index 95%
rename from notfair-cmo/src/server/mcp-server/jsonrpc.ts
rename to notfair/src/server/mcp-server/jsonrpc.ts
index 156ab1ec..a8318e1d 100644
--- a/notfair-cmo/src/server/mcp-server/jsonrpc.ts
+++ b/notfair/src/server/mcp-server/jsonrpc.ts
@@ -1,9 +1,9 @@
import { describeTool, type ToolDefinition } from "./tools";
/**
- * JSON-RPC 2.0 dispatcher for notfair-cmo's outbound MCP servers.
+ * JSON-RPC 2.0 dispatcher for NotFair's outbound MCP servers.
*
- * Each MCP server endpoint (e.g. /api/mcp/orchestration, /api/mcp/browser)
+ * Each MCP server endpoint (e.g. /api/mcp/goals, /api/mcp/browser)
* passes its own tool registry to `handleJsonRpc`. Splitting the surface
* into multiple servers keeps related tools grouped, lets users
* enable/disable per-MCP, and makes "what is this MCP for?" obvious from
@@ -43,7 +43,7 @@ export type JsonRpcResponse =
const PROTOCOL_VERSION = "2025-06-18";
export interface McpServerInfo {
- /** Server name reported in `initialize`. Should match the MCP registration key (e.g. "notfair-orchestration"). */
+ /** Server name reported in `initialize`. Should match the MCP registration key (e.g. "notfair-goals"). */
name: string;
/** Server version string. Bump when wire-visible behavior changes. */
version: string;
diff --git a/notfair-cmo/src/server/mcp-server/registration.ts b/notfair/src/server/mcp-server/registration.ts
similarity index 59%
rename from notfair-cmo/src/server/mcp-server/registration.ts
rename to notfair/src/server/mcp-server/registration.ts
index 3eda0dcd..c66404ce 100644
--- a/notfair-cmo/src/server/mcp-server/registration.ts
+++ b/notfair/src/server/mcp-server/registration.ts
@@ -1,97 +1,62 @@
import { requireAdapter } from "@/server/adapters/registry";
-import { getProject, listProjects } from "@/server/db/projects";
+import { getProject } from "@/server/db/projects";
import { listProjectAgents } from "@/server/agent-meta";
import { mcpSpecByKey } from "@/server/mcp-catalog";
import { findMcpToken } from "@/server/mcp/tokens";
import { getOrCreateMcpServerSecret } from "./secret";
-import type { HarnessAdapterId } from "@/server/adapters/types";
/**
- * Register notfair-cmo's outbound MCP server (`notfair-orchestration`) with
+ * Register NotFair's outbound MCP server (`notfair-goals`) with
* the project's harness adapter for a specific agent.
*
- * In v0.1.0 we registered once globally with OpenClaw's mcp config. The
- * harness-adapter model writes MCP wiring into whichever config file the
- * chosen harness expects (Claude Code's `.mcp.json`, Codex's
- * `~/.codex/config.toml`), so registration is per-agent now.
+ * The harness-adapter model writes MCP wiring into whichever config file
+ * the chosen harness expects (Claude Code's `.mcp.json`, Codex's
+ * `~/.codex/config.toml`); registration is per-agent.
*
- * URL: `NOTFAIR_CMO_MCP_URL` if set, else
- * `http://127.0.0.1:${NOTFAIR_CMO_PORT||3326}/api/mcp/orchestration`.
+ * URL: `NOTFAIR_MCP_URL` if set, else
+ * `http://127.0.0.1:${NOTFAIR_PORT||3326}/api/mcp/goals`.
*/
-export const ORCHESTRATION_MCP_KEY = "notfair-orchestration";
+export const GOALS_MCP_KEY = "notfair-goals";
export const BROWSER_MCP_KEY = "notfair-browser";
function notfairOriginPort(): string {
- return process.env.NOTFAIR_CMO_PORT?.trim() || "3326";
+ return process.env.NOTFAIR_PORT?.trim() || "3326";
}
function defaultMcpUrl(): string {
- if (process.env.NOTFAIR_CMO_MCP_URL?.trim()) {
- return process.env.NOTFAIR_CMO_MCP_URL.trim();
+ if (process.env.NOTFAIR_MCP_URL?.trim()) {
+ return process.env.NOTFAIR_MCP_URL.trim();
}
- return `http://127.0.0.1:${notfairOriginPort()}/api/mcp/orchestration`;
+ return `http://127.0.0.1:${notfairOriginPort()}/api/mcp/goals`;
}
function defaultBrowserMcpUrl(): string {
- if (process.env.NOTFAIR_CMO_BROWSER_MCP_URL?.trim()) {
- return process.env.NOTFAIR_CMO_BROWSER_MCP_URL.trim();
+ if (process.env.NOTFAIR_BROWSER_MCP_URL?.trim()) {
+ return process.env.NOTFAIR_BROWSER_MCP_URL.trim();
}
return `http://127.0.0.1:${notfairOriginPort()}/api/mcp/browser`;
}
-/**
- * One-shot per-process cleanup of legacy per-agent + dead-project rows in
- * `~/.codex/config.toml`. Per-project namespacing landed in 0.4.x; older
- * installs still have `[mcp_servers.notfair_<agentId>__...]` headers from
- * before the switch, which keep showing up when an agent introspects its
- * tools. Strip them once on the first registration we run after start.
- *
- * Claude Code's per-workspace `.mcp.json` doesn't have this problem, so
- * the prune is no-op for that adapter.
- */
-let codexPruneRan = false;
-async function maybePruneCodexOrphans(adapterId: HarnessAdapterId): Promise<void> {
- if (adapterId !== "codex-local" || codexPruneRan) return;
- codexPruneRan = true;
- try {
- const { pruneOrphanCodexNamespaces } = await import(
- "@/server/adapters/codex-local/mcp"
- );
- const slugs = new Set(
- listProjects({ includeArchived: true }).map((p) => p.slug),
- );
- const removed = await pruneOrphanCodexNamespaces(slugs);
- if (removed > 0) {
- console.info(
- `[mcp] pruned ${removed} orphan notfair_* section(s) from ~/.codex/config.toml`,
- );
- }
- } catch (err) {
- // Best-effort. A broken prune must not block actual registration.
- console.warn("[mcp] codex orphan prune failed:", err);
- }
-}
-
export type InstallResult =
| { ok: true; key: string; url: string }
| { ok: false; key: string; url: string; error: string };
-export async function registerOrchestrationForAgent(
+export async function registerGoalsMcpForAgent(
project_slug: string,
agent_id: string,
): Promise<InstallResult> {
return registerInternalMcpForAgent({
project_slug,
agent_id,
- key: ORCHESTRATION_MCP_KEY,
+ key: GOALS_MCP_KEY,
url: defaultMcpUrl(),
});
}
/**
* Register the standalone browser MCP (notfair-browser) for an agent.
- * Same shared-secret auth + same harness adapter glue as orchestration;
+ * Same shared-secret auth + same harness adapter glue as the goals server;
* separate URL + server name so agents see the surface as its own thing.
*/
export async function registerBrowserMcpForAgent(
@@ -119,7 +84,6 @@ async function registerInternalMcpForAgent(args: {
}
try {
const adapter = requireAdapter(project.harness_adapter);
- await maybePruneCodexOrphans(adapter.id);
await adapter.registerMcp({
serverName: key,
agentId: agent_id,
@@ -184,7 +148,6 @@ export async function registerCatalogMcpForAgent(
}
try {
const adapter = requireAdapter(project.harness_adapter);
- await maybePruneCodexOrphans(adapter.id);
await adapter.registerMcp({
serverName: catalog_key,
agentId: agent_id,
@@ -226,19 +189,3 @@ export async function registerCatalogMcpForProject(
return results;
}
-/**
- * No-op shim. The v0.1.0 cleanup removed leaked per-project rows from
- * OpenClaw's global mcp config; the new model has no such global registry.
- */
-export async function cleanupLegacyOrchestrationRows(_slugs: string[]): Promise<void> {
- // intentionally empty
-}
-
-/**
- * Legacy global install. Kept as a no-op so older callers (CLI reinstall
- * command) don't break — orchestration MCP wiring is now per-agent and
- * happens at provision time via `registerOrchestrationForAgent`.
- */
-export async function ensureOrchestrationMcpInstalled(): Promise<InstallResult> {
- return { ok: true, key: ORCHESTRATION_MCP_KEY, url: defaultMcpUrl() };
-}
diff --git a/notfair-cmo/src/server/mcp-server/secret.ts b/notfair/src/server/mcp-server/secret.ts
similarity index 82%
rename from notfair-cmo/src/server/mcp-server/secret.ts
rename to notfair/src/server/mcp-server/secret.ts
index ac966843..15f99b23 100644
--- a/notfair-cmo/src/server/mcp-server/secret.ts
+++ b/notfair/src/server/mcp-server/secret.ts
@@ -4,18 +4,18 @@ import { join } from "node:path";
import { randomBytes, timingSafeEqual } from "node:crypto";
/**
- * Shared secret used to authenticate calls from OpenClaw-side agents into our
+ * Shared secret used to authenticate calls from harness-side agents into our
* outbound-facing MCP server. Lives in a file with 0600 perms inside the
- * notfair-cmo data dir (NOT the project SQLite DB — keeping it in a small
+ * NotFair data dir (NOT the project SQLite DB — keeping it in a small
* dedicated file lets the file's own mode bits enforce single-user access
- * and lets the OpenClaw registration step read it with a one-liner).
+ * and lets registration read it with a one-liner).
*
* Single-user local CLI: we mint one secret per install and reuse it across
* every project + every agent. No rotation in V1 — easy to add later by
- * deleting the file and re-running `notfair-cmo mcp register`.
+ * deleting the file and re-running `NotFair mcp register`.
*/
-const DATA_DIR = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");
+const DATA_DIR = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
const SECRET_PATH = join(DATA_DIR, "mcp-server-secret");
/** Read the secret, minting + persisting one the first time. */
diff --git a/notfair-cmo/src/server/mcp-server/tool-summaries.ts b/notfair/src/server/mcp-server/tool-summaries.ts
similarity index 97%
rename from notfair-cmo/src/server/mcp-server/tool-summaries.ts
rename to notfair/src/server/mcp-server/tool-summaries.ts
index b563893a..36aa3c69 100644
--- a/notfair-cmo/src/server/mcp-server/tool-summaries.ts
+++ b/notfair/src/server/mcp-server/tool-summaries.ts
@@ -6,7 +6,7 @@ import { TOOLS, describeTool } from "./tools";
* Schema trees) across the server/client boundary — the modal cares
* about name + description + arg list, not validation.
*
- * Same shape for built-in (notfair-orchestration) tools we own + for
+ * Same shape for built-in (notfair-goals) tools we own + for
* external (Google Ads etc.) tools we learn about via tools/list. The
* modal renders both identically.
*/
diff --git a/notfair/src/server/mcp-server/tools.ts b/notfair/src/server/mcp-server/tools.ts
new file mode 100644
index 00000000..17db3ab2
--- /dev/null
+++ b/notfair/src/server/mcp-server/tools.ts
@@ -0,0 +1,592 @@
+import { z } from "zod";
+import { CronExpressionParser } from "cron-parser";
+
+import {
+ handleAmendGoal,
+ handleBackfillHistory,
+ handleDefineGoal,
+ handleGetGoal,
+ handleGetProject,
+ handleLogGoalAction,
+ handleLogLearning,
+ handleProposeGoalMetric,
+ handleProposeTarget,
+ handleReviewGoalAction,
+ handleSearchLearnings,
+ handleSetProjectBrief,
+ handleUpdateGoalStatus,
+} from "@/server/goals/handlers";
+
+/**
+ * Tool definitions exposed by NotFair's MCP server to goal agents. The
+ * server is globally shared (one bearer for every project), so every tool
+ * takes required `project_slug` + `agent_id` args the caller fills from
+ * its IDENTITY.md — we never derive identity from the bearer.
+ *
+ * The surface is deliberately small: the goal lifecycle
+ * (define → propose metric → propose target → user clicks START), the loop's bookkeeping
+ * (actions, reviews, learnings, status), the shared workspace context,
+ * and auxiliary scheduling. There is no task board, no approvals, no
+ * delegation — one agent, one goal, one loop.
+ */
+
+// ── Shared scaffolding ─────────────────────────────────────────────────
+
+export type ToolHandlerContext = {
+ /** Reserved for future per-agent bearer scoping. Unused today. */
+ agentId?: string;
+};
+
+export type ToolResult =
+ | { ok: true; content: { type: "text"; text: string }[] }
+ | { ok: false; error: string };
+
+export type ToolDefinition = {
+ name: string;
+ description: string;
+ inputSchema: z.ZodObject<z.ZodRawShape>;
+ handler: (input: unknown, ctx: ToolHandlerContext) => Promise<ToolResult>;
+};
+
+function invalid(err: z.ZodError): ToolResult {
+ return {
+ ok: false,
+ error: `Invalid arguments: ${err.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`,
+ };
+}
+
+function txt(text: string): ToolResult {
+ return { ok: true, content: [{ type: "text", text }] };
+}
+
+const callerFields = {
+ project_slug: z.string().min(1).describe("From IDENTITY.md."),
+ agent_id: z.string().min(1).describe("Your own agent_id, from IDENTITY.md."),
+};
+
+const goalIdFields = {
+ ...callerFields,
+ goal_id: z.string().min(1).describe("Your goal_id, from IDENTITY.md."),
+};
+
+// ── get_goal ───────────────────────────────────────────────────────────
+
+const getGoalInput = z.object({ ...goalIdFields });
+
+async function handleGetGoalTool(input: unknown): Promise<ToolResult> {
+ const parsed = getGoalInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, goal_id } = parsed.data;
+ const r = await handleGetGoal({ goal_id }, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify(r.data, null, 2));
+}
+
+// ── define_goal ────────────────────────────────────────────────────────
+
+const defineGoalInput = z.object({
+ ...goalIdFields,
+ statement: z
+ .string()
+ .min(1)
+ .describe(
+ "The ambition, concrete enough to measure — e.g. 'Cut Google Ads CAC to ~$30 within 60 days'. Refine by calling again while still in intake.",
+ ),
+ short_label: z
+ .string()
+ .min(1)
+ .max(48)
+ .describe(
+ "Compact display label for the sidebar/dashboard, ≤ 5 words with the number — e.g. 'Wasted X spend → $0', 'CAC → $30'. This is how the user identifies the goal everywhere.",
+ ),
+ deadline: z
+ .string()
+ .optional()
+ .describe("ISO date the user stated, if any (e.g. 2026-09-01)."),
+ spend_envelope_usd: z
+ .number()
+ .optional()
+ .describe("Total incremental ad spend the user authorized, if stated."),
+});
+
+async function handleDefineGoalTool(input: unknown): Promise<ToolResult> {
+ const parsed = defineGoalInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = handleDefineGoal(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(`goal defined: "${r.data.statement}". Next: author + test the metric, then propose_goal_metric.`);
+}
+
+// ── propose_goal_metric ────────────────────────────────────────────────
+
+const proposeGoalMetricInput = z.object({
+ ...goalIdFields,
+ metric_name: z
+ .string()
+ .min(1)
+ .describe("Human label incl. unit + window, e.g. 'CAC (USD, trailing 30d)'."),
+ metric_source_key: z
+ .string()
+ .min(1)
+ .describe("Connected catalog MCP key, e.g. 'notfair-googleads'."),
+ metric_source_tool: z
+ .string()
+ .min(1)
+ .describe("Tool to call on that server, usually 'runScript'."),
+ metric_source_args_json: z
+ .string()
+ .min(1)
+ .describe(
+ "JSON-encoded arguments object for the tool call. The call must return a single number (or {value: number}). You must have TESTED this exact call yourself first.",
+ ),
+ metric_direction: z
+ .enum(["increase", "decrease"])
+ .describe("Which way is progress: 'increase' (signups, ROAS) or 'decrease' (CAC, wasted spend)."),
+});
+
+async function handleProposeGoalMetricTool(input: unknown): Promise<ToolResult> {
+ const parsed = proposeGoalMetricInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = await handleProposeGoalMetric(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `Metric verified server-side. Baseline measured: ${r.data.baseline_value}. Report this to the user, suggest a target + cadence + spend envelope, and record it with propose_target once they agree. They start the loop with the START button on your Goal tab.`,
+ );
+}
+
+// ── backfill_metric_history ────────────────────────────────────────────
+
+const backfillHistoryInput = z.object({
+ ...goalIdFields,
+ source_key: z
+ .string()
+ .min(1)
+ .describe("Connected catalog MCP key (usually the same as the metric's)."),
+ source_tool: z.string().min(1).describe("Tool to call, usually 'runScript'."),
+ source_args_json: z
+ .string()
+ .min(1)
+ .describe(
+ "JSON-encoded arguments for a DATE-SEGMENTED query returning an array of {date: 'YYYY-MM-DD', value: number} — one point per day, ~30 days, same definition as the goal metric. TEST it yourself first.",
+ ),
+});
+
+async function handleBackfillHistoryTool(input: unknown): Promise<ToolResult> {
+ const parsed = backfillHistoryInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = await handleBackfillHistory(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `History backfilled: ${r.data.points} daily points from ${r.data.from} to ${r.data.to}. The progress chart now has context.`,
+ );
+}
+
+// ── propose_target / amend_goal ────────────────────────────────────────
+
+const proposeTargetInput = z.object({
+ ...goalIdFields,
+ target_value: z
+ .number()
+ .describe("The number you and the user landed on in chat."),
+ mode: z
+ .enum(["achieve", "maintain"])
+ .optional()
+ .describe(
+ "achieve (default) = the goal completes when the target is reached. maintain = HOLD the number there indefinitely (\"keep waste at $0\") — the loop keeps watching and never self-completes.",
+ ),
+ deadline: z.string().optional().describe("ISO date, if agreed."),
+ spend_envelope_usd: z
+ .number()
+ .optional()
+ .describe("Total incremental spend ceiling, if agreed."),
+ cadence_cron: z
+ .string()
+ .optional()
+ .describe(
+ "5-field UTC cron for the heartbeat. Common: '0 16 * * *' daily 9am PT, '0 16 * * 1-5' weekdays, '0 16 * * 1' weekly Monday. Defaults to daily.",
+ ),
+});
+
+async function handleProposeTargetTool(input: unknown): Promise<ToolResult> {
+ const parsed = proposeTargetInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ if (rest.cadence_cron) {
+ try {
+ CronExpressionParser.parse(rest.cadence_cron, { tz: "UTC" });
+ } catch {
+ return { ok: false, error: `Invalid cadence_cron '${rest.cadence_cron}' — must be a 5-field cron expression.` };
+ }
+ }
+ const r = handleProposeTarget(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ "Target recorded. Tell the user everything is set and point them at the START button on your Goal tab — the loop begins the moment they click it (the first tick runs immediately). You cannot start it yourself.",
+ );
+}
+
+const amendGoalInput = z.object({
+ ...goalIdFields,
+ target_value: z.number().optional().describe("New target, if the user changed it."),
+ deadline: z.string().optional().describe("New ISO deadline."),
+ spend_envelope_usd: z.number().optional().describe("New total spend ceiling."),
+ cadence_cron: z.string().optional().describe("New 5-field UTC heartbeat cron."),
+});
+
+async function handleAmendGoalTool(input: unknown): Promise<ToolResult> {
+ const parsed = amendGoalInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ if (rest.cadence_cron) {
+ try {
+ CronExpressionParser.parse(rest.cadence_cron, { tz: "UTC" });
+ } catch {
+ return { ok: false, error: `Invalid cadence_cron '${rest.cadence_cron}' — must be a 5-field cron expression.` };
+ }
+ }
+ const r = handleAmendGoal(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ const d = r.data;
+ return txt(
+ `Goal amended: target=${d.target_value ?? "—"}, deadline=${d.deadline ?? "none"}, envelope=${d.spend_envelope_usd !== null ? `$${d.spend_envelope_usd}` : "none"}, cadence=${d.cadence_cron}. Confirm the change back to the user.`,
+ );
+}
+
+// ── log_goal_action ────────────────────────────────────────────────────
+
+const logGoalActionInput = z.object({
+ ...goalIdFields,
+ kind: z
+ .enum(["mutation", "research", "decision"])
+ .describe(
+ "mutation = a platform write (bid, budget, pause, creative). research = read-only investigation. decision = a strategic choice worth recording.",
+ ),
+ description: z
+ .string()
+ .min(1)
+ .describe("What you did / are about to do. Be specific — quote IDs and dollar amounts."),
+ resources_touched: z
+ .string()
+ .optional()
+ .describe(
+ "Comma-separated resource keys the action touches, e.g. 'campaign:123,adgroup:456'. Required for mutations.",
+ ),
+ expected_effect: z
+ .string()
+ .min(1)
+ .describe("The falsifiable prediction, e.g. 'CPA -$3 within 7 days'. You will be scored against this at review time."),
+ review_after_hours: z
+ .number()
+ .optional()
+ .describe(
+ "Observation window in hours before this action may be scored and its resources touched again. REQUIRED for mutations (72h+ waste pauses, 120h+ bid/budget, 168h+ creative/keywords).",
+ ),
+ spend_usd: z
+ .number()
+ .optional()
+ .describe(
+ "Estimated INCREMENTAL spend this action commits (e.g. a budget raise's expected extra cost until review). The platform sums these against the envelope and shows the total in every tick brief. Omit for spend-neutral actions.",
+ ),
+});
+
+async function handleLogGoalActionTool(input: unknown): Promise<ToolResult> {
+ const parsed = logGoalActionInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, resources_touched, ...rest } = parsed.data;
+ const r = handleLogGoalAction(
+ {
+ ...rest,
+ resources_touched: resources_touched
+ ? resources_touched.split(",").map((s) => s.trim()).filter(Boolean)
+ : [],
+ },
+ { project_slug, agent_id },
+ );
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `action ${r.data.action_id} logged.${r.data.review_after ? ` Review due ${r.data.review_after}. Its resources are gated until then.` : ""}`,
+ );
+}
+
+// ── review_goal_action ─────────────────────────────────────────────────
+
+const reviewGoalActionInput = z.object({
+ ...goalIdFields,
+ action_id: z.string().min(1).describe("The open action you're scoring."),
+ observed_outcome: z
+ .string()
+ .min(1)
+ .describe("What actually happened vs. expected_effect, with the numbers."),
+ abandoned: z
+ .boolean()
+ .optional()
+ .describe("true when the action was reverted/obsoleted rather than measured."),
+ learning: z
+ .string()
+ .optional()
+ .describe("Optional durable learning to record alongside the review."),
+});
+
+async function handleReviewGoalActionTool(input: unknown): Promise<ToolResult> {
+ const parsed = reviewGoalActionInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = handleReviewGoalAction(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `action ${r.data.action_id} ${r.data.status}.${r.data.learning_id ? ` Learning ${r.data.learning_id} recorded.` : ""}`,
+ );
+}
+
+// ── log_learning / search_learnings ────────────────────────────────────
+
+const logLearningInput = z.object({
+ ...goalIdFields,
+ body: z
+ .string()
+ .min(1)
+ .describe("The durable fact, specific enough to act on later. Quote numbers."),
+ confidence: z.enum(["low", "medium", "high"]).optional().describe("Default medium."),
+ supersedes_id: z
+ .string()
+ .optional()
+ .describe("Learning this replaces — supersede stale facts instead of contradicting them."),
+});
+
+async function handleLogLearningTool(input: unknown): Promise<ToolResult> {
+ const parsed = logLearningInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = handleLogLearning(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(`learning ${r.data.learning_id} recorded.`);
+}
+
+const searchLearningsInput = z.object({
+ ...goalIdFields,
+ query: z
+ .string()
+ .optional()
+ .describe("Substring to search for. Omit to list the most recent learnings."),
+ limit: z.number().optional().describe("Max results (default 20, cap 50)."),
+});
+
+async function handleSearchLearningsTool(input: unknown): Promise<ToolResult> {
+ const parsed = searchLearningsInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = handleSearchLearnings(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify(r.data.learnings, null, 2));
+}
+
+// ── update_goal_status ─────────────────────────────────────────────────
+
+const updateGoalStatusInput = z.object({
+ ...goalIdFields,
+ status: z
+ .enum(["achieved", "failed", "paused"])
+ .describe(
+ "achieved = target met (verified against the measured metric). failed = can't be met (deadline/envelope/blocked). paused = needs the user before the loop can continue.",
+ ),
+ reason: z
+ .string()
+ .min(1)
+ .describe("Evidence-based reason, quoting the measured metric."),
+});
+
+async function handleUpdateGoalStatusTool(input: unknown): Promise<ToolResult> {
+ const parsed = updateGoalStatusInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = handleUpdateGoalStatus(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(`goal ${r.data.goal_id} is now '${r.data.status}'.`);
+}
+
+// ── get_project / set_shared_context ───────────────────────────────────
+
+const getProjectInput = z.object({ ...callerFields });
+
+async function handleGetProjectTool(input: unknown): Promise<ToolResult> {
+ const parsed = getProjectInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id } = parsed.data;
+ const r = handleGetProject({}, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(JSON.stringify(r.data, null, 2));
+}
+
+const setSharedContextInput = z.object({
+ ...callerFields,
+ content: z
+ .string()
+ .min(1)
+ .describe(
+ "The FULL new shared context (markdown). This replaces the previous version — read the current one first (get_goal returns it) and edit, don't blindly overwrite.",
+ ),
+});
+
+async function handleSetSharedContextTool(input: unknown): Promise<ToolResult> {
+ const parsed = setSharedContextInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, content } = parsed.data;
+ const r = await handleSetProjectBrief({ content }, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `shared context updated (${r.data.bytes} bytes); ${r.data.synced_agents} agent identit${r.data.synced_agents === 1 ? "y" : "ies"} re-rendered.`,
+ );
+}
+
+// ── Registry ───────────────────────────────────────────────────────────
+
+export const TOOLS: ToolDefinition[] = [
+ {
+ name: "get_goal",
+ description:
+ "Fetch your goal's full state: spec, metric history, open actions (due-for-review vs still-gated), recent learnings and ticks, plus the shared workspace context. Call FIRST whenever you've lost context — this is the re-anchor tool.",
+ inputSchema: getGoalInput,
+ handler: handleGetGoalTool,
+ },
+ {
+ name: "define_goal",
+ description:
+ "Intake step 1: record the ambition the user articulated in chat (statement + any stated deadline/spend envelope). Repeatable while the goal is in intake — refine as the conversation sharpens.",
+ inputSchema: defineGoalInput,
+ handler: handleDefineGoalTool,
+ },
+ {
+ name: "propose_goal_metric",
+ description:
+ "Intake step 2: submit the metric definition you authored AND tested. The platform re-runs the exact tool call server-side; only a reproducible single number moves the goal to 'proposed' and records the baseline. Fails with the error if the query can't be verified — fix and propose again.",
+ inputSchema: proposeGoalMetricInput,
+ handler: handleProposeGoalMetricTool,
+ },
+ {
+ name: "backfill_metric_history",
+ description:
+ "Reconstruct the metric's past: run a date-segmented version of the metric query (per-day values, ~30 days) so the user's progress chart has history from day one. Platform-verified like the metric; replaces any earlier backfill. Call during intake right after propose_goal_metric.",
+ inputSchema: backfillHistoryInput,
+ handler: handleBackfillHistoryTool,
+ },
+ {
+ name: "propose_target",
+ description:
+ "Intake step 3: record the target/cadence/spend envelope the user agreed to in chat. This does NOT start the loop — the user clicks START on your Goal tab (platform-enforced consent), which also fires the first tick immediately. Rejects targets on the wrong side of the baseline.",
+ inputSchema: proposeTargetInput,
+ handler: handleProposeTargetTool,
+ },
+ {
+ name: "amend_goal",
+ description:
+ "Adjust a LIVE goal when the user asks: new target, deadline, spend envelope, or heartbeat cadence. Active/paused goals only; echo the change back to the user after. Never amend without the user having asked.",
+ inputSchema: amendGoalInput,
+ handler: handleAmendGoalTool,
+ },
+ {
+ name: "log_goal_action",
+ description:
+ "Record a move BEFORE executing it: what, which resources, the falsifiable expected effect, and the observation window (review_after_hours, required for mutations). Gated resources are untouchable until their review date. Unlogged mutations are invisible to future ticks — always log first.",
+ inputSchema: logGoalActionInput,
+ handler: handleLogGoalActionTool,
+ },
+ {
+ name: "review_goal_action",
+ description:
+ "Score an open action whose review date arrived: observed outcome vs. expected_effect, with numbers. Closes the measurement loop and (optionally) records a learning. Do this at the START of a tick, before any new move.",
+ inputSchema: reviewGoalActionInput,
+ handler: handleReviewGoalActionTool,
+ },
+ {
+ name: "log_learning",
+ description:
+ "Write a durable fact to your own memory (survives context rotation). Use for anything future ticks must know: platform quirks, what worked, decisions made in chat. Supersede stale learnings instead of contradicting them.",
+ inputSchema: logLearningInput,
+ handler: handleLogLearningTool,
+ },
+ {
+ name: "search_learnings",
+ description:
+ "Query your own memory. Call while orienting, before acting — check what you already know about a campaign/keyword/tactic before touching it.",
+ inputSchema: searchLearningsInput,
+ handler: handleSearchLearningsTool,
+ },
+ {
+ name: "update_goal_status",
+ description:
+ "Declare your goal achieved / failed, or pause it. Requires an evidence-based reason; 'achieved' is rejected unless the measured metric actually meets the target. Resume and close belong to the user in the UI.",
+ inputSchema: updateGoalStatusInput,
+ handler: handleUpdateGoalStatusTool,
+ },
+ {
+ name: "get_project",
+ description:
+ "Fetch project metadata: connected account ids (Google Ads / Meta / GSC), website, harness. Cheap re-anchor for platform facts.",
+ inputSchema: getProjectInput,
+ handler: handleGetProjectTool,
+ },
+ {
+ name: "set_shared_context",
+ description:
+ "Rewrite the shared workspace context (PROJECT.md) — the brief EVERY agent in this workspace sees in its identity: what the company sells, who buys, positioning, voice, global constraints. Update it when you learn something all agents should know. Full replacement: read the current version first (get_goal returns it) and edit.",
+ inputSchema: setSharedContextInput,
+ handler: handleSetSharedContextTool,
+ },
+];
+
+// Browser MCP tools live in their own server (notfair-browser) so this
+// surface stays focused. See ./browser-tools.ts and the /api/mcp/browser
+// route.
+
+export function describeTool(tool: ToolDefinition): {
+ name: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+} {
+ return {
+ name: tool.name,
+ description: tool.description,
+ inputSchema: zodObjectToJsonSchema(tool.inputSchema),
+ };
+}
+
+export function findTool(name: string): ToolDefinition | undefined {
+ return TOOLS.find((t) => t.name === name);
+}
+
+/**
+ * Minimal zod→JSON-schema conversion covering the shapes we use
+ * (string / number / boolean / enum, optional, describe). Anything more
+ * exotic falls back to `{type:"string"}` — the handler's safeParse is the
+ * real validation.
+ */
+function zodObjectToJsonSchema(schema: z.ZodObject<z.ZodRawShape>): Record<string, unknown> {
+ const properties: Record<string, unknown> = {};
+ const required: string[] = [];
+ for (const [key, raw] of Object.entries(schema.shape)) {
+ let field = raw as z.ZodTypeAny;
+ let isOptional = false;
+ while (field instanceof z.ZodOptional || field instanceof z.ZodDefault) {
+ isOptional = true;
+ field = field._def.innerType as z.ZodTypeAny;
+ }
+ const description = (field as { description?: string }).description ?? (raw as { description?: string }).description;
+ let prop: Record<string, unknown>;
+ if (field instanceof z.ZodEnum) {
+ prop = { type: "string", enum: field.options };
+ } else if (field instanceof z.ZodNumber) {
+ prop = { type: "number" };
+ } else if (field instanceof z.ZodBoolean) {
+ prop = { type: "boolean" };
+ } else {
+ prop = { type: "string" };
+ }
+ if (description) prop.description = description;
+ properties[key] = prop;
+ if (!isOptional) required.push(key);
+ }
+ return { type: "object", properties, required, additionalProperties: false };
+}
diff --git a/notfair-cmo/src/server/mcp/discovery-url.ts b/notfair/src/server/mcp/discovery-url.ts
similarity index 100%
rename from notfair-cmo/src/server/mcp/discovery-url.ts
rename to notfair/src/server/mcp/discovery-url.ts
diff --git a/notfair-cmo/src/server/mcp/probe-cache.ts b/notfair/src/server/mcp/probe-cache.ts
similarity index 98%
rename from notfair-cmo/src/server/mcp/probe-cache.ts
rename to notfair/src/server/mcp/probe-cache.ts
index 09c99e34..e77d7b70 100644
--- a/notfair-cmo/src/server/mcp/probe-cache.ts
+++ b/notfair/src/server/mcp/probe-cache.ts
@@ -22,7 +22,7 @@ import type { McpRuntimeStatus } from "./state";
type CacheEntry = { result: McpRuntimeStatus; expiresAt: number };
-const GLOBAL_KEY = "__notfair_cmo_probe_cache__";
+const GLOBAL_KEY = "__notfair_probe_cache__";
type GlobalSlot = { [GLOBAL_KEY]?: Map<string, CacheEntry> };
const slot = globalThis as unknown as GlobalSlot;
const STORE: Map<string, CacheEntry> =
diff --git a/notfair-cmo/src/server/mcp/refresh.ts b/notfair/src/server/mcp/refresh.ts
similarity index 98%
rename from notfair-cmo/src/server/mcp/refresh.ts
rename to notfair/src/server/mcp/refresh.ts
index ef01e113..f2711135 100644
--- a/notfair-cmo/src/server/mcp/refresh.ts
+++ b/notfair/src/server/mcp/refresh.ts
@@ -6,7 +6,7 @@ import { updateMcpTokenSecrets, type McpToken } from "./tokens";
*
* Returns `null` (and leaves the row alone) when:
* - the row has no refresh_token / token_endpoint / client_id stored
- * (legacy rows from before migration 013 + callback fix), OR
+ * (rows written before refresh support), OR
* - the token endpoint rejects the refresh (revoked, expired, scope drift).
*
* Callers should treat `null` as "the user must reconnect" and surface the
diff --git a/notfair-cmo/src/server/mcp/rpc.ts b/notfair/src/server/mcp/rpc.ts
similarity index 98%
rename from notfair-cmo/src/server/mcp/rpc.ts
rename to notfair/src/server/mcp/rpc.ts
index bbd21fdc..5ccfbc3e 100644
--- a/notfair-cmo/src/server/mcp/rpc.ts
+++ b/notfair/src/server/mcp/rpc.ts
@@ -7,7 +7,7 @@ import { refreshMcpToken, isExpiringSoon } from "./refresh";
* - `mcp/state.ts:probe()` (liveness check via tools/list)
* - `onboarding/audit.ts` (real audit via tools/call runScript)
*
- * Single source of truth for: token lookup (from notfair-cmo SQLite), bearer
+ * Single source of truth for: token lookup (from NotFair SQLite), bearer
* extraction, JSON-RPC envelope construction, SSE-vs-JSON response parsing,
* error shapes.
*
@@ -37,7 +37,7 @@ export type RpcResult<T> =
/**
* Look up an MCP config row by (project_slug, catalog_key). Returns null when
* no token is stored or the catalog entry is unknown. Replaces the legacy
- * `openclaw mcp show` subprocess that backed the same surface.
+ * subprocess call that backed the same surface.
*/
export function readMcpConfigRow(
project_slug: string,
diff --git a/notfair-cmo/src/server/mcp/state.ts b/notfair/src/server/mcp/state.ts
similarity index 98%
rename from notfair-cmo/src/server/mcp/state.ts
rename to notfair/src/server/mcp/state.ts
index 3d34d99b..d4ae10ff 100644
--- a/notfair-cmo/src/server/mcp/state.ts
+++ b/notfair/src/server/mcp/state.ts
@@ -89,7 +89,7 @@ async function probe(
{
protocolVersion: "2025-06-18",
capabilities: {},
- clientInfo: { name: "notfair-cmo", version: "0.3.1" },
+ clientInfo: { name: "NotFair", version: "0.3.1" },
},
{ timeoutMs: 6000 },
);
diff --git a/notfair-cmo/src/server/mcp/tokens.ts b/notfair/src/server/mcp/tokens.ts
similarity index 96%
rename from notfair-cmo/src/server/mcp/tokens.ts
rename to notfair/src/server/mcp/tokens.ts
index 1f04ede2..ff1bac50 100644
--- a/notfair-cmo/src/server/mcp/tokens.ts
+++ b/notfair/src/server/mcp/tokens.ts
@@ -2,9 +2,9 @@ import { randomUUID } from "node:crypto";
import { getDb } from "@/server/db/db";
/**
- * MCP token storage for notfair-cmo.
+ * MCP token storage for NotFair.
*
- * Replaces OpenClaw's config-file storage (`openclaw mcp set/unset`). Tokens
+ * Tokens
* are project-scoped — one project's notfair-googleads connection never bleeds
* into another's.
*
@@ -12,7 +12,7 @@ import { getDb } from "@/server/db/db";
* placeholders today (we store the raw JSON envelope from the OAuth callback)
* but the schema is ready for a keytar-backed encryption pass.
*
- * `token_endpoint`, `client_id`, `client_secret` were added in migration 013
+ * `token_endpoint`, `client_id`, `client_secret` support refresh
* so the refresh helper (`mcp/refresh.ts`) can rotate access tokens without
* sending the user back through consent. They are nullable: pre-013 rows
* have them as NULL and stay on the legacy reconnect-on-401 path.
diff --git a/notfair-cmo/src/server/onboarding/accounts.ts b/notfair/src/server/onboarding/accounts.ts
similarity index 61%
rename from notfair-cmo/src/server/onboarding/accounts.ts
rename to notfair/src/server/onboarding/accounts.ts
index 6252cc14..ec4c7af6 100644
--- a/notfair-cmo/src/server/onboarding/accounts.ts
+++ b/notfair/src/server/onboarding/accounts.ts
@@ -125,30 +125,13 @@ function parseAccountsPayload(
}
export type SetAccountResult =
- | {
- ok: true;
- project: Project;
- task_display_id: string;
- /** URL slug for the CMO so the client can navigate to its tasks
- * page without recomputing `<role>-<name>` itself. */
- cmo_agent_slug: string;
- }
+ | { ok: true; project: Project }
| { ok: false; error: string };
/**
- * 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 in `proposed`
- * state. The task workspace the user lands on auto-fires the
- * kickoff via /api/chat, so the user sees streaming gateway events
- * live — JSONL polling alone can't (OpenClaw's codex-app-server
- * mode flushes the file once per turn, not incrementally).
- *
- * The caller redirects to /agents/cmo/tasks?task=<display_id> so the user
- * watches the live audit stream the moment the page mounts.
+ * Persist the chosen Google Ads account on the project row. Validates the
+ * account_id against the MCP's reachable list (anti-tamper for the form
+ * submit). Goal agents pick this up via get_project / their identity.
*/
export async function setOnboardingAccountAction(
project_slug: string,
@@ -180,299 +163,10 @@ export async function setOnboardingAccountAction(
const updated = setProjectGoogleAdsAccount(project_slug, match.id);
if (!updated) return { ok: false, error: "Project not found." };
- // 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 { listTasks } = await import("@/server/db/tasks");
- const { listProjectAgents } = await import("@/server/agent-meta");
- // Resolve the CMO agent by template_key — agent_ids now encode the
- // personal name, so we can't synthesize one from project_slug alone.
- const projectAgents = await listProjectAgents(project_slug);
- const cmo = projectAgents.find((a) => a.template_key === "cmo");
- if (!cmo) {
- return { ok: false, error: "CMO agent has not been provisioned yet." };
- }
- const cmoAgentId = cmo.agent_id;
- const audit = await ensureAuditTask({
- project_slug,
- project_display_name: updated.display_name,
- google_ads_account_id: match.id,
- cmoAgentId,
- });
- const onboardingTask = listTasks(project_slug).find(
- (t) =>
- t.agent_id === cmoAgentId &&
- t.title === "Learn the project and write PROJECT.md",
- );
-
- // Pick the task to surface in the redirect:
- // - Prefer the onboarding task while it's still non-terminal — that's
- // what's actually executing; the audit sits blocked behind it.
- // - Fall back to the audit when onboarding is already done (or never
- // existed) so the user lands on the running task either way.
- const TERMINAL = new Set(["done", "failed", "cancelled"]);
- const surfaceTask =
- onboardingTask && !TERMINAL.has(onboardingTask.status)
- ? onboardingTask
- : (audit ?? onboardingTask);
- if (!surfaceTask) {
- return { ok: false, error: "Onboarding task not found." };
- }
-
revalidatePath("/", "layout");
- return {
- ok: true,
- project: updated,
- task_display_id: surfaceTask.display_id,
- cmo_agent_slug: cmo.slug,
- };
-}
-
-/** Ads platforms whose connection makes the CMO audit meaningful. */
-const ADS_PLATFORM_KEYS = [
- "notfair-googleads",
- "notfair-metaads",
- "notfair-xads",
-] as const;
-
-/**
- * Mint the CMO's multi-platform audit task — shared by the Google Ads
- * account-pick path and the setup step (which covers X-Ads-only /
- * Meta-Ads-only connects that never pass through an account picker;
- * without the setup-step hook those projects got NO audit at all and
- * their specialists sat idle forever).
- *
- * Callers are responsible for only invoking this when at least one ads
- * platform is connected (the account-pick path just validated Google
- * Ads; the setup path checks the token table). Dedupes by title prefix
- * so back-navigation / both paths firing can't create two audits. Gated
- * on the PROJECT.md onboarding task while that's in flight; createTask
- * drops the blocker automatically when it's already terminal.
- */
-async function ensureAuditTask(input: {
- project_slug: string;
- project_display_name: string;
- google_ads_account_id: string | null;
- cmoAgentId: string;
-}): Promise<import("@/types").Task | null> {
- const { listTasks, createTask } = await import("@/server/db/tasks");
- const allTasks = listTasks(input.project_slug);
- const existing = allTasks.find(
- (t) => t.agent_id === input.cmoAgentId && t.title?.startsWith("Audit the"),
- );
- if (existing) return existing;
-
- const onboardingTask = allTasks.find(
- (t) =>
- t.agent_id === input.cmoAgentId &&
- t.title === "Learn the project and write PROJECT.md",
- );
- const { buildOnboardingBrief } = await import("./cmo-task-brief");
- const { title, brief, success_criteria } = buildOnboardingBrief({
- project_slug: input.project_slug,
- project_display_name: input.project_display_name,
- google_ads_account_id: input.google_ads_account_id,
- });
- return createTask({
- project_slug: input.project_slug,
- agent_id: input.cmoAgentId,
- title,
- brief,
- success_criteria,
- assigner_agent_id: null,
- status: "proposed",
- blocked_by_task_id: onboardingTask?.id ?? null,
- });
-}
-
-export type ProvisioningProgressResult =
- | { ok: true; steps: { key: string; label: string; status: string; error?: string }[]; overall: "running" | "done" | "failed" }
- | { ok: false; error: string };
-
-/**
- * Poll endpoint for the onboarding "Setting up your agents…" screen.
- * Returns the live per-template provisioning checklist published by
- * `ensureProjectAgents`. The client polls this every ~500ms while the
- * user watches each row flip from pending → in_progress → done.
- *
- * Falls back to a synthesized "done" view when the in-memory progress
- * map is empty AND the agents already exist on disk (cold-start path
- * for users who navigate back to the setup URL after provisioning
- * completed in a prior request).
- */
-export async function getProvisioningProgressAction(
- project_slug: string,
-): Promise<ProvisioningProgressResult> {
- if (!project_slug.trim()) {
- return { ok: false, error: "Missing project slug." };
- }
- const project = getProject(project_slug);
- if (!project) return { ok: false, error: "Project not found." };
-
- const { getProgress } = await import("./provisioning-progress");
- const progress = getProgress(project_slug);
- if (progress) {
- return { ok: true, steps: progress.steps, overall: progress.overall };
- }
- // Cold-start: no progress record (process restart between provisioning
- // and the user hitting this screen). Treat as done so the screen
- // proceeds to redirect instead of hanging.
- return {
- ok: true,
- steps: [
- { key: "cmo", label: "Setting up CMO", status: "done" },
- { key: "google_ads", label: "Setting up Google Ads Specialist", status: "done" },
- { key: "gateway", label: "Connecting agents to gateway", status: "done" },
- ],
- overall: "done",
- };
-}
-
-export type OnboardingReadyResult =
- | { ok: true }
- | { ok: false; error: string };
-
-/**
- * Block until the project's agents are fully provisioned AND the gateway's
- * runtime snapshot has surfaced them. Called by the onboarding "connect or
- * skip" screen so the user never sees a Connect/Skip button before the
- * agent is ready to receive its first chat.send — without this, clicking
- * Skip immediately after creating a project races the
- * `openclaw agents add` config write and the kickoff fails with
- * INVALID_REQUEST "Agent '<id>' no longer exists in configuration".
- *
- * 30-second ceiling matches the worst-case provisioning + gateway-wait
- * we've observed in dev. Returns ok=false on timeout so the UI can show
- * a retry-friendly error instead of hanging forever.
- */
-export async function awaitOnboardingReadyAction(
- project_slug: string,
-): Promise<OnboardingReadyResult> {
- if (!project_slug.trim()) {
- return { ok: false, error: "Missing project slug." };
- }
- const project = getProject(project_slug);
- if (!project) return { ok: false, error: "Project not found." };
-
- const { awaitProvisioning } = await import("./provisioning-state");
- const ready = await awaitProvisioning(project_slug, 30_000);
- if (ready.kind === "timeout") {
- return {
- ok: false,
- error: "Setting up your agents is taking longer than expected. Refresh to retry.",
- };
- }
- if (ready.kind === "no-agents") {
- return {
- ok: false,
- error: "Agent provisioning hasn't started for this project.",
- };
- }
- return { ok: true };
-}
-
-export type SkipAccountResult =
- | { ok: true; task_display_id: string; cmo_agent_slug: string }
- | { ok: false; error: string };
-
-/**
- * Resolve where the setup step lands the user (both the connect and the
- * skip paths route through here). Resolves the CMO agent + its
- * "Learn the project and write PROJECT.md" task, and — when at least one
- * ads platform is connected — ensures the multi-platform audit task
- * exists. This is what covers X-Ads-only / Meta-Ads-only connects: they
- * never pass through the Google Ads account picker, which used to be the
- * only place the audit was minted. With nothing connected (true skip) no
- * audit is created — the user can connect later from /connections.
- *
- * Blocks until provisioning has fully resolved — `ensureProjectAgents`
- * itself waits for the gateway's runtime config to surface the new agent
- * ids — so by the time the redirect fires, the agent is registered AND
- * the gateway sees it. Without this, the kickoff (server-side via
- * startTaskIfProposed OR client-side via /api/chat) can outrun the
- * `openclaw agents add` config rewrite and fail with INVALID_REQUEST
- * "Agent '<id>' no longer exists in configuration".
- */
-export async function getOnboardingTaskForSkipAction(
- project_slug: string,
-): Promise<SkipAccountResult> {
- if (!project_slug.trim()) {
- return { ok: false, error: "Missing project slug." };
- }
- const project = getProject(project_slug);
- if (!project) return { ok: false, error: "Project not found." };
-
- const { awaitProvisioning } = await import("./provisioning-state");
- const ready = await awaitProvisioning(project_slug, 30_000);
- if (ready.kind === "timeout") {
- return {
- ok: false,
- error: "Setting up your agents is taking longer than expected. Try again in a moment.",
- };
- }
- if (ready.kind === "no-agents") {
- return {
- ok: false,
- error: "Agent provisioning hasn't started for this project.",
- };
- }
-
- const { listTasks } = await import("@/server/db/tasks");
- const { listProjectAgents } = await import("@/server/agent-meta");
- const projectAgents = await listProjectAgents(project_slug);
- const cmo = projectAgents.find((a) => a.template_key === "cmo");
- if (!cmo) {
- return { ok: false, error: "CMO agent has not been provisioned yet." };
- }
- const onboardingTask = listTasks(project_slug).find(
- (t) =>
- t.agent_id === cmo.agent_id &&
- t.title === "Learn the project and write PROJECT.md",
- );
- // Only mint the audit when an ads platform is actually connected — a
- // true skip (nothing connected) lands on the PROJECT.md task alone.
- const { listProjectMcpTokens } = await import("@/server/mcp/tokens");
- const connected = new Set(
- listProjectMcpTokens(project_slug).map((t) => t.server_name),
- );
- const audit = ADS_PLATFORM_KEYS.some((k) => connected.has(k))
- ? await ensureAuditTask({
- project_slug,
- project_display_name: project.display_name,
- google_ads_account_id: project.google_ads_account_id,
- cmoAgentId: cmo.agent_id,
- })
- : null;
- // Land on whatever is actually executing: the onboarding task while
- // it's in flight, else the audit (which auto-kicks off on page open),
- // else the onboarding task as the terminal-state fallback.
- const TERMINAL = new Set(["done", "failed", "cancelled"]);
- const surfaceTask =
- onboardingTask && !TERMINAL.has(onboardingTask.status)
- ? onboardingTask
- : (audit ?? onboardingTask);
- if (!surfaceTask) {
- return { ok: false, error: "Onboarding task not found." };
- }
- return {
- ok: true,
- task_display_id: surfaceTask.display_id,
- cmo_agent_slug: cmo.slug,
- };
+ return { ok: true, project: updated };
}
-// ── Meta Ads account picker ────────────────────────────────────────
-//
-// Mirrors the Google Ads pattern. The notfair-metaads MCP exposes a
-// `listAdAccounts` tool that returns the ad accounts the current bearer
-// can reach. Onboarding asks the user to pick one and we persist it on
-// `projects.meta_ads_account_id`.
-
const META_ADS_MCP_KEY = "notfair-metaads";
const META_ADS_LIST_TOOL = "listAdAccounts";
diff --git a/notfair-cmo/src/server/onboarding/project-brief.ts b/notfair/src/server/onboarding/project-brief.ts
similarity index 85%
rename from notfair-cmo/src/server/onboarding/project-brief.ts
rename to notfair/src/server/onboarding/project-brief.ts
index 73fa2891..28d0885b 100644
--- a/notfair-cmo/src/server/onboarding/project-brief.ts
+++ b/notfair/src/server/onboarding/project-brief.ts
@@ -3,27 +3,27 @@ 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.
+ * PROJECT.md — the shared workspace context: "what is this project / who
+ * is the company". Any goal agent can update it via the
+ * `set_shared_context` tool; it propagates into every agent's IDENTITY.md
+ * so all goals share the same picture.
*
- * Path layout (relative to the data dir, default ~/.notfair-cmo):
+ * Path layout (relative to the data dir, default ~/.notfair):
*
- * projects/<slug>/PROJECT.md — canonical, edited by the CMO
+ * projects/<slug>/PROJECT.md — canonical shared copy
*
* 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.
+ * regardless of which files the harness 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");
+ return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
}
export function projectBriefDir(project_slug: string): string {
diff --git a/notfair/src/server/scheduler/tick.ts b/notfair/src/server/scheduler/tick.ts
new file mode 100644
index 00000000..2e58e819
--- /dev/null
+++ b/notfair/src/server/scheduler/tick.ts
@@ -0,0 +1,33 @@
+import { runDueGoalTicks } from "@/server/goals/tick";
+
+/**
+ * The heartbeat loop. Started once on boot (src/instrumentation.ts); a
+ * 30s interval sweeps active goals whose next_tick_at has passed and
+ * runs their ticks. This is the ONLY scheduler in the product — goals
+ * are the one thing that recurs.
+ */
+let started = false;
+let timer: NodeJS.Timeout | null = null;
+const TICK_INTERVAL_MS = 30_000;
+
+export function ensureSchedulerRunning(): void {
+ if (started) return;
+ started = true;
+ timer = setInterval(() => {
+ runDueGoalTicks().catch((err) =>
+ console.error("[scheduler] goal tick sweep failed:", err),
+ );
+ }, TICK_INTERVAL_MS);
+ // First sweep on the next event-loop turn so callers return immediately.
+ setImmediate(() =>
+ runDueGoalTicks().catch((err) =>
+ console.error("[scheduler] goal tick sweep failed:", err),
+ ),
+ );
+}
+
+export function stopScheduler(): void {
+ if (timer) clearInterval(timer);
+ timer = null;
+ started = false;
+}
diff --git a/notfair-cmo/src/server/secrets/cipher.ts b/notfair/src/server/secrets/cipher.ts
similarity index 100%
rename from notfair-cmo/src/server/secrets/cipher.ts
rename to notfair/src/server/secrets/cipher.ts
diff --git a/notfair-cmo/src/server/secrets/master-key.ts b/notfair/src/server/secrets/master-key.ts
similarity index 97%
rename from notfair-cmo/src/server/secrets/master-key.ts
rename to notfair/src/server/secrets/master-key.ts
index c8190a57..54032e10 100644
--- a/notfair-cmo/src/server/secrets/master-key.ts
+++ b/notfair/src/server/secrets/master-key.ts
@@ -1,6 +1,6 @@
import { randomBytes } from "node:crypto";
-const KEYTAR_SERVICE = "notfair-cmo";
+const KEYTAR_SERVICE = "NotFair";
const KEYTAR_ACCOUNT = "master-key";
type Keytar = {
diff --git a/notfair-cmo/src/server/sessions/index.ts b/notfair/src/server/sessions/index.ts
similarity index 85%
rename from notfair-cmo/src/server/sessions/index.ts
rename to notfair/src/server/sessions/index.ts
index d0a3b19b..08ea7bbd 100644
--- a/notfair-cmo/src/server/sessions/index.ts
+++ b/notfair/src/server/sessions/index.ts
@@ -7,10 +7,8 @@ import type { HarnessAdapterId } from "@/server/adapters/types";
*
* A "session" is one chat thread between the user and an agent. Each agent
* can have many sessions (named "main", "Q4 audit", etc.). The session id
- * is a stable notfair-cmo UUID; we also store the adapter's own session id
+ * is a stable NotFair UUID; we also store the adapter's own session id
* (e.g. Claude Code's session UUID for resumption) when known.
- *
- * Replaces OpenClaw's session-key namespace + JSONL transcript files.
*/
export interface Session {
id: string;
@@ -19,7 +17,6 @@ export interface Session {
label: string;
harness_adapter: HarnessAdapterId;
harness_session_id: string | null;
- task_id: string | null;
/** User-set display title (thread rename). Null = derive from content. */
title: string | null;
/** Set when the user pins the thread; doubles as pin-order tiebreaker. */
@@ -44,7 +41,6 @@ interface SessionRow {
label: string;
harness_adapter: string;
harness_session_id: string | null;
- task_id: string | null;
title: string | null;
pinned_at: string | null;
created_at: string;
@@ -60,7 +56,6 @@ export function getOrCreateSession(input: {
agent_id: string;
label: string;
harness_adapter: HarnessAdapterId;
- task_id?: string | null;
}): Session {
const db = getDb();
const existing = db
@@ -77,7 +72,6 @@ export function getOrCreateSession(input: {
label: input.label,
harness_adapter: input.harness_adapter,
harness_session_id: null,
- task_id: input.task_id ?? null,
title: null,
pinned_at: null,
created_at: new Date().toISOString(),
@@ -85,14 +79,13 @@ export function getOrCreateSession(input: {
};
db.prepare(
- "INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, harness_session_id, task_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)",
+ "INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, harness_session_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?)",
).run(
session.id,
session.project_slug,
session.agent_id,
session.label,
session.harness_adapter,
- session.task_id,
session.created_at,
session.updated_at,
);
@@ -168,20 +161,24 @@ export function appendTranscriptEvent(
db.prepare(
"INSERT INTO transcript_events (id, session_id, seq, kind, payload_json, created_at) VALUES (?, ?, ?, ?, ?, ?)",
).run(id, session_id, seq, kind, payload_json, created_at);
- // Push to live subscribers AFTER the INSERT commits. Inline import to
- // keep this module free of the live-events dependency at module load —
- // matters for the migration tests that don't want EventEmitter eagerness.
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { publishSessionEvent } =
- require("@/server/live-events/emitter") as typeof import("@/server/live-events/emitter");
- publishSessionEvent(session_id, {
- id,
- session_id,
- seq,
- kind,
- payload_json,
- created_at,
- });
+ // Push to live subscribers AFTER the INSERT commits. Best-effort: the
+ // row is already persisted, so a publish failure must not throw into
+ // the caller's adapter-event loop.
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { publishSessionEvent } =
+ require("@/server/live-events/emitter") as typeof import("@/server/live-events/emitter");
+ publishSessionEvent(session_id, {
+ id,
+ session_id,
+ seq,
+ kind,
+ payload_json,
+ created_at,
+ });
+ } catch {
+ // Live subscribers miss this event; the poll fallback still sees it.
+ }
}
export function listTranscriptEvents(
diff --git a/notfair-cmo/src/server/sessions/transcript-tail.ts b/notfair/src/server/sessions/transcript-tail.ts
similarity index 74%
rename from notfair-cmo/src/server/sessions/transcript-tail.ts
rename to notfair/src/server/sessions/transcript-tail.ts
index c821aace..dc9e12d3 100644
--- a/notfair-cmo/src/server/sessions/transcript-tail.ts
+++ b/notfair/src/server/sessions/transcript-tail.ts
@@ -2,12 +2,12 @@ import { getDb } from "@/server/db/db";
import type { TranscriptEvent as RawEvent, Session } from "./index";
/**
- * UI-facing transcript event shape preserved from the previous OpenClaw-backed
- * JSONL reader. The chat polling endpoint returns a flat array of these so the
- * live-transcript component can replay events on re-attach.
+ * UI-facing transcript event shape. The chat polling endpoint returns a
+ * flat array of these so the live-transcript component can replay events
+ * on re-attach.
*/
export type TranscriptEvent =
- | { kind: "user_message"; id: string; ts: number; body: string }
+ | { kind: "user_message"; id: string; ts: number; body: string; system?: boolean }
| { kind: "assistant_text"; id: string; ts: number; body: string }
| {
kind: "tool_call";
@@ -30,7 +30,7 @@ export type TranscriptEvent =
| { kind: "unknown"; id: string; ts: number; raw_type: string };
/**
- * Resolve a URL thread id to a notfair-cmo `sessions` row by label.
+ * Resolve a URL thread id to a NotFair `sessions` row by label.
* Returns null when no session has been created yet (e.g., the user just
* clicked New and hasn't sent a turn).
*/
@@ -52,7 +52,7 @@ export function resolveSessionForThread(
/**
* Read transcript events for a thread after `cursor`. We expose the same
- * shape the JSONL tail used (an `byteOffset` integer the client carries
+ * cursor shape across polls (a `cursor` integer the client carries
* across polls) — only here it indexes the monotonically-increasing `seq`
* column on `transcript_events`. Callers don't care what backs the cursor;
* they just hand back what they received.
@@ -62,9 +62,9 @@ export function readTranscriptTail(
agent_id: string,
thread: string,
cursor: number,
-): { events: TranscriptEvent[]; byteOffset: number; fileSize: number } {
+): { events: TranscriptEvent[]; cursor: number } {
const session = resolveSessionForThread(project_slug, agent_id, thread);
- if (!session) return { events: [], byteOffset: cursor, fileSize: 0 };
+ if (!session) return { events: [], cursor };
const rows = getDb()
.prepare(
@@ -81,7 +81,12 @@ export function readTranscriptTail(
const id = row.id;
if (row.kind === "user") {
const text = typeof payload.text === "string" ? payload.text : "";
- events.push({ kind: "user_message", id, ts, body: text });
+ // Platform-generated turns (goal intake kickoff, tick briefs) are
+ // not something the user typed — the UI renders them as a compact
+ // system line instead of a user bubble.
+ const source = typeof payload.source === "string" ? payload.source : "";
+ const system = source.startsWith("goal-");
+ events.push({ kind: "user_message", id, ts, body: text, system });
} else if (row.kind === "delta") {
const text = typeof payload.text === "string" ? payload.text : "";
events.push({ kind: "assistant_text", id, ts, body: text });
@@ -126,10 +131,7 @@ export function readTranscriptTail(
}
}
- // fileSize legacy field — for the JSONL reader this was the source file
- // size in bytes. The UI uses it only to decide whether more data may exist;
- // we substitute the highest seq seen so far.
- return { events, byteOffset: last, fileSize: last };
+ return { events, cursor: last };
}
function safeParse(json: string): Record<string, unknown> {
@@ -140,13 +142,3 @@ function safeParse(json: string): Record<string, unknown> {
return {};
}
}
-
-/** Coerce a raw payload value into the UI's TranscriptEvent flat-text body. */
-export function rawEntryToEvents(_raw: unknown): TranscriptEvent[] {
- // Compat shim. The previous JSONL reader exposed a row-level parser so the
- // shadow tee in `chat/route.ts` could echo entries to the SSE bridge. The new
- // chat route persists structured events directly into `transcript_events`,
- // so this helper is unused — kept as an empty array to avoid breaking
- // existing imports while the live SSE bridge is rewritten on the new model.
- return [];
-}
diff --git a/notfair-cmo/src/server/sessions/view.ts b/notfair/src/server/sessions/view.ts
similarity index 50%
rename from notfair-cmo/src/server/sessions/view.ts
rename to notfair/src/server/sessions/view.ts
index 5279dd5d..5378a737 100644
--- a/notfair-cmo/src/server/sessions/view.ts
+++ b/notfair/src/server/sessions/view.ts
@@ -1,24 +1,17 @@
-import { cookies } from "next/headers";
import { randomUUID } from "node:crypto";
import { getDb } from "@/server/db/db";
import { getProject } from "@/server/db/projects";
import { DEFAULT_HARNESS_ADAPTER } from "@/server/adapters/registry";
-import { listTasksByAgent } from "@/server/db/tasks";
-import { listCronsForProject } from "@/server/scheduler/display";
import type { Session } from "./index";
import { getOrCreateSession, listAgentSessions } from "./index";
-/**
- * UI-facing session shape preserved from the previous OpenClaw-backed module.
- * The chat thread dropdown rendered against this in v0.1.0; keeping the field
- * names lets the existing component continue to work.
- */
+/** UI-facing session shape for the goal page's thread views. */
export interface SessionView {
- /** Stable thread label used in URLs (`/chat/<label>`). */
+ /** Stable thread label used in URLs. */
sessionId: string;
- /** Short label shown in the dropdown. */
+ /** Short label shown in thread lists. */
label: string;
- /** Compatibility — earlier code carried a backend session-key string. */
+ /** The sessions row's DB primary key. */
sessionKey: string;
/** Last interaction (ms epoch). 0 when freshly minted. */
lastInteractionAt: number;
@@ -30,10 +23,6 @@ export interface SessionView {
pinned: boolean;
}
-function cookieName(project_slug: string, agent_template_key: string): string {
- return `notfair_active_session_${project_slug}_${agent_template_key}`;
-}
-
function sessionRowToView(s: Session): SessionView {
return {
sessionId: s.label,
@@ -54,10 +43,6 @@ export function listSessionsForAgent(
return rows.map(sessionRowToView);
}
-export function buildPendingSessionKey(_agent_id: string, label: string): string {
- return label;
-}
-
export function newSessionId(): string {
return randomUUID();
}
@@ -79,75 +64,6 @@ export function findSessionBySessionId(
return row ? sessionRowToView(row) : null;
}
-/**
- * Build the chat dropdown view: the currently-active thread plus the full
- * list of threads. If the cookie points at a label not yet in the table
- * (user clicked New, hasn't sent a message), it appears at the top as
- * pending.
- */
-export async function getSessionsView(
- project_slug: string,
- agent_template_key: string,
- agent_full_id: string,
-): Promise<{ active: SessionView; all: SessionView[] }> {
- const existing = listSessionsForAgent(project_slug, agent_full_id);
- const c = await cookies();
- const cookieLabel = c.get(cookieName(project_slug, agent_template_key))?.value;
-
- let active: SessionView | undefined;
- if (cookieLabel) {
- active = existing.find((s) => s.label === cookieLabel);
- if (!active) {
- active = {
- sessionId: cookieLabel,
- label: cookieLabel.slice(0, 8),
- sessionKey: cookieLabel,
- lastInteractionAt: 0,
- pending: true,
- title: null,
- pinned: false,
- };
- }
- }
-
- if (!active) {
- if (existing.length > 0) {
- active = existing[0]!;
- } else {
- const newLabel = "main";
- active = {
- sessionId: newLabel,
- label: newLabel,
- sessionKey: newLabel,
- lastInteractionAt: 0,
- pending: true,
- title: null,
- pinned: false,
- };
- }
- }
-
- const all = active.pending && !existing.find((s) => s.label === active!.label)
- ? [active, ...existing]
- : existing;
-
- return { active, all };
-}
-
-export async function setActiveSession(
- project_slug: string,
- agent_template_key: string,
- label: string,
-): Promise<void> {
- const c = await cookies();
- c.set(cookieName(project_slug, agent_template_key), label, {
- httpOnly: true,
- sameSite: "lax",
- path: "/",
- maxAge: 60 * 60 * 24 * 365,
- });
-}
-
/**
* Materialize a session row immediately (used when the first chat turn is
* about to fire and the caller wants the session UUID to exist). Falls back
@@ -157,7 +73,6 @@ export function materializeSession(input: {
project_slug: string;
agent_id: string;
label: string;
- task_id?: string | null;
}): Session {
const project = getProject(input.project_slug);
const harness = project?.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;
@@ -166,31 +81,26 @@ export function materializeSession(input: {
agent_id: input.agent_id,
label: input.label,
harness_adapter: harness,
- task_id: input.task_id ?? null,
});
}
// ── Thread origins ──────────────────────────────────────────────────
export type SessionOrigin =
- | { kind: "task"; display_id: string; title: string | null }
- | { kind: "cron"; cron_name: string }
+ | { kind: "tick"; tick_number: number }
| { kind: "chat"; preview: string };
-const CRON_LABEL_PREFIX = "cron:";
+const TICK_LABEL_RE = /^tick-(\d+)$/;
-export function isTaskOrCronSession(
- label: string,
- taskThreadIds: ReadonlySet<string>,
-): boolean {
- return label.startsWith(CRON_LABEL_PREFIX) || taskThreadIds.has(label);
+/** Tick-originated sessions (not user-initiated chats). */
+export function isSystemSession(label: string): boolean {
+ return TICK_LABEL_RE.test(label);
}
export function pickLatestChatSession<S extends { label: string }>(
sessions: readonly S[],
- taskThreadIds: ReadonlySet<string>,
): S | undefined {
- return sessions.find((s) => !isTaskOrCronSession(s.label, taskThreadIds));
+ return sessions.find((s) => !isSystemSession(s.label));
}
// Generous cap: the rail shows ~40 chars at rest and reveals the rest by
@@ -199,10 +109,9 @@ export function pickLatestChatSession<S extends { label: string }>(
const PREVIEW_MAX_CHARS = 140;
/**
- * Classify each session by origin so the dropdown can show meaningful labels.
- * Tasks come from the project DB (`tasks.thread_id === session.label`); crons
- * are identified by a `cron:<name>` label prefix; free chats fall back to a
- * preview of the first user message stored in `transcript_events`.
+ * Classify each session by origin so the thread rail can show meaningful
+ * labels. Goal-loop ticks use a `tick-<n>` label; free chats fall back to
+ * a preview of the first user message.
*/
export async function classifySessions(
agent_id: string,
@@ -212,48 +121,19 @@ export async function classifySessions(
const out = new Map<string, SessionOrigin>();
if (sessions.length === 0) return out;
- const taskByThread = new Map<string, { display_id: string; title: string | null }>();
- const tasks = listTasksByAgent(agent_id);
- for (const t of tasks) {
- if (t.thread_id) {
- taskByThread.set(t.thread_id, { display_id: t.display_id, title: t.title });
- }
- }
-
- const cronNames = new Map<string, string>();
- try {
- const view = await listCronsForProject(project_slug);
- for (const g of view.groups) {
- for (const c of g.crons) {
- cronNames.set(c.short_name, c.short_name);
- }
- }
- } catch {
- // best-effort
- }
-
for (const s of sessions) {
if (s.pending) continue;
- if (s.label.startsWith(CRON_LABEL_PREFIX)) {
- const name = s.label.slice(CRON_LABEL_PREFIX.length);
- out.set(s.label, {
- kind: "cron",
- cron_name: cronNames.get(name) ?? name,
- });
- continue;
- }
- const task = taskByThread.get(s.label);
- if (task) {
- out.set(s.label, {
- kind: "task",
- display_id: task.display_id,
- title: task.title,
- });
+ const tickMatch = s.label.match(TICK_LABEL_RE);
+ if (tickMatch) {
+ out.set(s.label, { kind: "tick", tick_number: Number(tickMatch[1]) });
continue;
}
+ const preview = readFirstUserMessagePreview(project_slug, agent_id, s.label);
out.set(s.label, {
kind: "chat",
- preview: readFirstUserMessagePreview(project_slug, agent_id, s.label),
+ // The intake kickoff is platform-generated — label the thread by
+ // what it is rather than the raw brief text.
+ preview: preview.startsWith("[INTAKE]") ? "Goal kickoff" : preview,
});
}
return out;
diff --git a/notfair/src/server/skills/browser-skill.ts b/notfair/src/server/skills/browser-skill.ts
new file mode 100644
index 00000000..c4b6a720
--- /dev/null
+++ b/notfair/src/server/skills/browser-skill.ts
@@ -0,0 +1,111 @@
+/**
+ * Workspace-browser guidance included in every goal agent's skill (see
+ * src/server/goals/identity.ts). The workspace has ONE shared Chrome with
+ * persistent cookies, so the rules here — labeled tabs, snapshot → act →
+ * snapshot, honest blocker reporting — are what keep multiple agents from
+ * stepping on each other.
+ */
+export const BROWSER_SKILL = `## Workspace browser tools
+
+The workspace has a single shared Chrome instance with persistent cookies.
+The user has signed in there during onboarding — so login state for Google,
+Meta, Search Console, etc. is already available to you. Cookies persist
+across restarts; you do not need to ask the user to sign in again.
+
+### CRITICAL: which "browser" tool to use
+
+The notfair-browser MCP exposes \`browser_open\`, \`browser_snapshot\`,
+\`browser_click\`, etc. **These are the ONLY tools that touch the workspace
+browser.** When the user says "launch the browser", "open a page", "go to
+<URL>", "snapshot the page", or anything in that family, the answer is
+ALWAYS one of the \`browser_*\` MCP tools below.
+
+Do **not**:
+- Use any bundled or third-party "browser-use" plugin your host runtime
+ might ship (e.g. OpenAI's bundled \`browser-use\` plugin in Codex CLI).
+ Those open a different Chrome with a different profile — your work
+ won't persist for other agents in this project.
+- Shell out to \`open -a "Google Chrome"\`, \`open <url>\`, AppleScript
+ \`tell application "Google Chrome"\`, \`xdg-open\`, \`start chrome\`,
+ or similar. Same problem: wrong profile, no shared cookies.
+- "Initialize" or "launch" the browser as a separate step. \`browser_open\`
+ starts the workspace Chrome on its first call automatically.
+
+If you're unsure whether the workspace browser is running, call
+\`browser_status\` first — it's cheap and tells you everything.
+
+### One labeled tab per agent
+
+Every agent shares the same Chrome, so coordinate via tab labels.
+**Always pass \`label\` equal to your \`agent_id\` when calling
+\`browser_open\`.** That reserves a stable tab for your work and prevents
+you (or a retry) from racing other agents.
+
+\`\`\`
+browser_open({ project_slug, label: "<your agent_id>", url: "..." })
+\`\`\`
+
+If a labeled tab already exists, \`browser_open\` reuses it (navigates
+that tab instead of duplicating). Subsequent calls target it as
+\`target_id: "<your agent_id>"\`.
+
+Before opening, call \`browser_tabs\` if you suspect a prior turn left
+state you can reuse — it lists every tab in the workspace with handle,
+URL, and title.
+
+### Snapshot → act → snapshot
+
+Refs in a snapshot (\`e1\`, \`e2\`, ...) are valid ONLY until the DOM
+changes. Discipline:
+
+1. \`browser_snapshot\` to learn what's on the page (returns elements
+ with stable refs + a text excerpt).
+2. \`browser_click\`/\`browser_type\`/\`browser_press\` using a ref from
+ that snapshot.
+3. After any navigation, form submit, or modal change, snapshot AGAIN
+ before the next action. Stale refs fail loudly — recover with a
+ fresh snapshot, never a blind retry.
+
+\`browser_navigate\` triggers a navigation; \`browser_scroll\` does not
+invalidate refs but may reveal new ones (re-snapshot if you need them).
+
+### Reporting blockers honestly
+
+If the page surfaces a login wall, captcha, 2FA prompt, permission
+dialog, or any state that needs the human, STOP. Do not loop. Use
+\`submit_task_status\` with \`status: "blocked"\` and a summary that
+quotes the exact UI ("Google asks for SMS verification on
++1•••••5309"). Do not claim "not logged in" just because the current
+page shows an onboarding splash — snapshot first and read the visible
+UI.
+
+Do not try to bypass interstitials by reloading or clicking around. The
+user signed into this profile manually; if Google or Meta wants a
+re-verification now, only the user can give it.
+
+### Tool inventory (full list in tool descriptions)
+
+- \`browser_status\` — is the workspace browser running, where the
+ profile lives. Cheap; safe to call first.
+- \`browser_tabs\` — list every tab with handle, URL, title.
+- \`browser_open\` — open / reuse a tab. ALWAYS pass \`label\`.
+- \`browser_close\` — close a tab by handle.
+- \`browser_navigate\` — point an existing tab at a new URL.
+- \`browser_snapshot\` — get refs + text. Snapshot before every action.
+- \`browser_click\` — click ref. Supports right/middle/double + modifiers.
+- \`browser_type\` — type into ref. \`submit: true\` presses Enter after.
+- \`browser_press\` — single key / chord (Tab, Escape, Control+a, ...).
+- \`browser_scroll\` — viewport scroll up/down/left/right.
+- \`browser_back\` — history back.
+
+You CANNOT stop the workspace browser. Browser lifecycle belongs to the
+user (Settings → Workspace browser → Stop). This is deliberate: every
+agent in this workspace shares one Chrome, so stopping it would interrupt
+your teammates mid-task.
+
+`;
+
+/** Back-compat alias used by tests. */
+export function getBrowserSkill(): string {
+ return BROWSER_SKILL;
+}
diff --git a/notfair/src/server/suggestions/engine.ts b/notfair/src/server/suggestions/engine.ts
new file mode 100644
index 00000000..abe6b557
--- /dev/null
+++ b/notfair/src/server/suggestions/engine.ts
@@ -0,0 +1,131 @@
+import {
+ hasSuggestionsForSource,
+ replaceOpenSuggestions,
+ type SuggestionDraft,
+} from "@/server/db/suggestions";
+import { listLiveGoals } from "@/server/db/goals";
+import { listProjectMcpTokens } from "@/server/mcp/tokens";
+import {
+ auditXadsAccount,
+ xadsSuggestionsFromSnapshot,
+ XADS_SOURCE_KEY,
+} from "./xads";
+
+/**
+ * Suggestion generation: after a user connects an ads account, NotFair
+ * audits it mechanically and proposes goals. One analyzer per platform;
+ * X Ads is the first. Generation is idempotent per (project, source) —
+ * open rows refresh, accepted/dismissed rows are left alone.
+ */
+
+type Analyzer = (
+ project_slug: string,
+ liveGoalStatements: string[],
+) => Promise<SuggestionDraft[]>;
+
+const ANALYZERS: Record<string, { label: string; run: Analyzer }> = {
+ [XADS_SOURCE_KEY]: {
+ label: "X Ads",
+ run: async (project_slug, liveGoals) => {
+ const snapshot = await auditXadsAccount(project_slug);
+ return xadsSuggestionsFromSnapshot(snapshot, liveGoals);
+ },
+ },
+};
+
+export function suggestionSourceLabel(source_key: string): string | null {
+ return ANALYZERS[source_key]?.label ?? null;
+}
+
+export type SuggestionRun = {
+ source_key: string;
+ label: string;
+ status: "running" | "done" | "failed";
+ error?: string;
+ finished_at?: number;
+};
+
+// Per-project run state. In-memory is enough for a single-user local
+// process: the UI polls it while a run is live, and a lost run after a
+// restart just means the user re-triggers from the index page.
+const runs = new Map<string, Map<string, SuggestionRun>>();
+
+function projectRuns(project_slug: string): Map<string, SuggestionRun> {
+ let m = runs.get(project_slug);
+ if (!m) {
+ m = new Map();
+ runs.set(project_slug, m);
+ }
+ return m;
+}
+
+export function listSuggestionRuns(project_slug: string): SuggestionRun[] {
+ return Array.from(projectRuns(project_slug).values());
+}
+
+export function anySuggestionRunActive(project_slug: string): boolean {
+ return listSuggestionRuns(project_slug).some((r) => r.status === "running");
+}
+
+/**
+ * Analyze one connected source and refresh its open suggestions.
+ * No-ops when the source has no analyzer or a run is already live.
+ */
+export async function generateSuggestionsForSource(
+ project_slug: string,
+ source_key: string,
+): Promise<void> {
+ const analyzer = ANALYZERS[source_key];
+ if (!analyzer) return;
+ const state = projectRuns(project_slug);
+ if (state.get(source_key)?.status === "running") return;
+
+ state.set(source_key, {
+ source_key,
+ label: analyzer.label,
+ status: "running",
+ });
+ try {
+ const liveStatements = listLiveGoals(project_slug).map((g) => g.statement);
+ const drafts = await analyzer.run(project_slug, liveStatements);
+ replaceOpenSuggestions(project_slug, source_key, drafts);
+ state.set(source_key, {
+ source_key,
+ label: analyzer.label,
+ status: "done",
+ finished_at: Date.now(),
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error(`[suggestions] ${source_key} analysis failed:`, message);
+ state.set(source_key, {
+ source_key,
+ label: analyzer.label,
+ status: "failed",
+ error: message,
+ finished_at: Date.now(),
+ });
+ }
+}
+
+/** Every connected source that has an analyzer. */
+export function analyzableSources(project_slug: string): string[] {
+ return listProjectMcpTokens(project_slug)
+ .map((t) => t.server_name)
+ .filter((key) => key in ANALYZERS);
+}
+
+/**
+ * First-visit hook for the goals index: kick off analysis for any
+ * connected source that has never produced suggestions (covers accounts
+ * connected before this feature existed, and dropped runs after a
+ * restart). Fire-and-forget; failures land in the run state.
+ */
+export function maybeAutoGenerate(project_slug: string): void {
+ for (const key of analyzableSources(project_slug)) {
+ const run = projectRuns(project_slug).get(key);
+ if (run) continue; // already attempted this process lifetime
+ if (hasSuggestionsForSource(project_slug, key)) continue;
+ void generateSuggestionsForSource(project_slug, key);
+ }
+}
diff --git a/notfair/src/server/suggestions/xads.ts b/notfair/src/server/suggestions/xads.ts
new file mode 100644
index 00000000..c64425d6
--- /dev/null
+++ b/notfair/src/server/suggestions/xads.ts
@@ -0,0 +1,245 @@
+import { mcpRpcAutoRefresh } from "@/server/mcp/rpc";
+import type { SuggestionDraft } from "@/server/db/suggestions";
+
+/**
+ * Mechanical X Ads account audit → grounded goal suggestions.
+ *
+ * Same trust model as goal metrics: the platform runs the queries itself
+ * (no agent self-reporting), so every number in a suggestion's rationale
+ * is real account data. The audit is one `runScript` call against the
+ * notfair-xads MCP; the heuristics below turn its snapshot into at most
+ * three proposals. The goal agent re-verifies everything at intake, so
+ * suggestions only need to be directionally right.
+ */
+
+export const XADS_SOURCE_KEY = "notfair-xads";
+
+type ToolCallResult = {
+ content?: Array<{ type?: string; text?: string }>;
+ isError?: boolean;
+};
+
+export type XadsSnapshot = {
+ account: { name: string; currency: string };
+ counts: {
+ campaigns: number;
+ activeCampaigns: number;
+ lineItems: number;
+ activeLineItems: number;
+ };
+ activeDailyBudget: number;
+ /** Trailing-30-day totals across all line items. */
+ last30d: {
+ spend: number;
+ impressions: number;
+ engagements: number;
+ linkClicks: number;
+ conversions: number;
+ /** Spend on line items that took budget but produced zero engagement. */
+ wastedSpend: number;
+ };
+ /** Trailing-7-day totals (the most recent stats chunk). */
+ last7d: { spend: number; impressions: number };
+ topSpenders: Array<{ name: string; spend: number; conversions: number }>;
+};
+
+/**
+ * The audit script. X Ads sync stats allow at most 7 days + 1 hour per
+ * request, so the 30-day window runs as five sequential chunks; line
+ * items batch 20 ids per stats call (API limit).
+ */
+const AUDIT_SCRIPT = `
+const r = await ads.getParallel([
+ { name: 'account', path: 'accounts/{accountId}' },
+ { name: 'campaigns', path: 'accounts/{accountId}/campaigns', paged: true },
+ { name: 'lineItems', path: 'accounts/{accountId}/line_items', paged: true },
+]);
+for (const k of ['account', 'campaigns', 'lineItems']) {
+ if (!r[k] || !r[k].ok) throw new Error('X Ads audit: ' + k + ' fetch failed: ' + JSON.stringify(r[k] && r[k].error));
+}
+// Unpaged gets keep the raw response envelope; the entity is one level down.
+const account = (r.account.data && r.account.data.data) || r.account.data || {};
+const campaigns = r.campaigns.data || [];
+const lineItems = r.lineItems.data || [];
+const activeLineItems = lineItems.filter(li => li.entity_status === 'ACTIVE');
+
+const ENGAGEMENT_KEYS = ['follows','app_clicks','retweets','likes','engagements','clicks','card_engagements','replies','link_clicks','billed_engagements','carousel_swipes'];
+const CONVERSION_KEYS = ['conversion_purchases','conversion_sign_ups','conversion_site_visits','conversion_downloads','conversion_custom'];
+// Metric values vary by group: ENGAGEMENT/BILLING come back as plain
+// arrays ([574452]), WEB_CONVERSION as {metric: [...]} objects. Read both.
+const sum = (m, k) => {
+ const v = m[k];
+ const arr = Array.isArray(v) ? v : (v && Array.isArray(v.metric) ? v.metric : []);
+ return arr.reduce((a, b) => a + Number(b || 0), 0);
+};
+
+// Per-line-item accumulators over 30 days.
+const acc = {};
+for (const li of lineItems) acc[li.id] = { spendMicros: 0, impressions: 0, engagements: 0, linkClicks: 0, conversions: 0 };
+
+const end = new Date(); end.setUTCMinutes(0, 0, 0);
+// 30 days as hour-aligned chunks inside the 7d+1h API limit: the first
+// chunk is exactly the trailing 7 days (168h), the rest split the
+// remaining 23 days into 138h slices. 168 + 4*138 = 720h = 30 days.
+const HOUR = 3600000;
+const bounds = [0, 168, 306, 444, 582, 720];
+let spend7dMicros = 0, impressions7d = 0;
+for (let chunk = 0; chunk < bounds.length - 1; chunk++) {
+ const chunkEnd = new Date(end.getTime() - bounds[chunk] * HOUR);
+ const chunkStart = new Date(end.getTime() - bounds[chunk + 1] * HOUR);
+ const win = { start_time: ads.helpers.formatHourIso(chunkStart), end_time: ads.helpers.formatHourIso(chunkEnd) };
+ for (let i = 0; i < lineItems.length; i += 20) {
+ const ids = lineItems.slice(i, i + 20).map(li => li.id);
+ const stats = await ads.stats({
+ entity: 'LINE_ITEM', entity_ids: ids,
+ metric_groups: ['BILLING', 'ENGAGEMENT', 'WEB_CONVERSION'],
+ granularity: 'TOTAL', ...win,
+ });
+ for (const row of (stats.data || [])) {
+ const m = (row.id_data && row.id_data[0] && row.id_data[0].metrics) || {};
+ const a = acc[row.id]; if (!a) continue;
+ const spendMicros = sum(m, 'billed_charge_local_micro');
+ a.spendMicros += spendMicros;
+ a.impressions += sum(m, 'impressions');
+ a.engagements += ENGAGEMENT_KEYS.reduce((t, k) => t + sum(m, k), 0);
+ a.linkClicks += sum(m, 'link_clicks');
+ a.conversions += CONVERSION_KEYS.reduce((t, k) => t + sum(m, k), 0);
+ if (chunk === 0) { spend7dMicros += spendMicros; impressions7d += sum(m, 'impressions'); }
+ }
+ }
+}
+
+const usd = micros => Number(ads.helpers.microsToMajor(micros).toFixed(2));
+let spendMicros = 0, impressions = 0, engagements = 0, linkClicks = 0, conversions = 0, wastedMicros = 0;
+const spenders = [];
+for (const li of lineItems) {
+ const a = acc[li.id];
+ spendMicros += a.spendMicros; impressions += a.impressions;
+ engagements += a.engagements; linkClicks += a.linkClicks; conversions += a.conversions;
+ if (a.spendMicros > 0 && a.engagements === 0) wastedMicros += a.spendMicros;
+ if (a.spendMicros > 0) spenders.push({ name: li.name, spend: usd(a.spendMicros), conversions: a.conversions });
+}
+spenders.sort((a, b) => b.spend - a.spend);
+
+return {
+ account: { name: account.name || 'your X Ads account', currency: 'USD' },
+ counts: {
+ campaigns: campaigns.length,
+ activeCampaigns: campaigns.filter(c => c.entity_status === 'ACTIVE').length,
+ lineItems: lineItems.length,
+ activeLineItems: activeLineItems.length,
+ },
+ activeDailyBudget: usd(activeLineItems.reduce((t, li) => t + (li.daily_budget_amount_local_micro || 0), 0)),
+ last30d: {
+ spend: usd(spendMicros), impressions, engagements, linkClicks, conversions,
+ wastedSpend: usd(wastedMicros),
+ },
+ last7d: { spend: usd(spend7dMicros), impressions: impressions7d },
+ topSpenders: spenders.slice(0, 3),
+};
+`;
+
+export async function auditXadsAccount(project_slug: string): Promise<XadsSnapshot> {
+ const rpc = await mcpRpcAutoRefresh<ToolCallResult>(
+ project_slug,
+ XADS_SOURCE_KEY,
+ "tools/call",
+ { name: "runScript", arguments: { timeoutMs: 45_000, code: AUDIT_SCRIPT } },
+ { timeoutMs: 60_000 },
+ );
+ if (!rpc.ok) {
+ const detail = "message" in rpc && rpc.message ? `: ${rpc.message}` : "";
+ throw new Error(`X Ads audit failed (${rpc.kind}${detail})`);
+ }
+ const text = rpc.result?.content?.find((c) => c.type === "text")?.text ?? "";
+ if (rpc.result?.isError) {
+ throw new Error(`X Ads audit script errored: ${text.slice(0, 400)}`);
+ }
+ const envelope = JSON.parse(text) as { ok?: boolean; result?: XadsSnapshot; error?: { message?: string } };
+ if (!envelope.ok || !envelope.result) {
+ throw new Error(`X Ads audit script failed: ${envelope.error?.message ?? text.slice(0, 400)}`);
+ }
+ return envelope.result;
+}
+
+const money = (n: number) => `$${n % 1 === 0 ? n : n.toFixed(2)}`;
+
+/**
+ * Snapshot → at most three proposals, priority-ordered. `liveGoalStatements`
+ * lets each heuristic skip territory an existing goal already owns (the
+ * user may have stated it by hand — don't pitch them their own goal).
+ */
+export function xadsSuggestionsFromSnapshot(
+ s: XadsSnapshot,
+ liveGoalStatements: string[],
+): SuggestionDraft[] {
+ const overlaps = (re: RegExp) => liveGoalStatements.some((st) => re.test(st));
+ const out: SuggestionDraft[] = [];
+ const d = s.last30d;
+
+ // Nothing in the account yet → one bootstrap proposal and stop.
+ if (s.counts.lineItems === 0) {
+ if (!overlaps(/launch|first campaign/i)) {
+ out.push({
+ kind: "xads-bootstrap",
+ title: "Launch your first X Ads campaign",
+ statement:
+ "Launch our first X Ads campaign and get it delivering — reaching real impressions within a week.",
+ mode: "achieve",
+ rationale: `The connected X Ads account (${s.account.name}) has no campaigns or ad groups yet.`,
+ });
+ }
+ return out;
+ }
+
+ // Spending but some of it buys zero engagement → cut the waste.
+ if (d.wastedSpend > 0 && !overlaps(/wast\w* spend|no.engagement/i)) {
+ out.push({
+ kind: "xads-wasted-spend",
+ title: "Cut wasted X Ads spend to $0",
+ statement: `Cut X Ads wasted spend to $0 and keep it there — pause line items that spend without producing a single engagement.`,
+ mode: "maintain",
+ rationale: `${money(d.wastedSpend)} of the last 30 days' ${money(d.spend)} X Ads spend went to line items with zero engagements.`,
+ });
+ }
+
+ // Active entities but the account isn't actually delivering.
+ if (
+ s.counts.activeLineItems > 0 &&
+ s.last7d.impressions === 0 &&
+ !overlaps(/deliver|impression|reviv/i)
+ ) {
+ out.push({
+ kind: "xads-dormant",
+ title: "Get X Ads delivering again",
+ statement: `Revive the X Ads account: get the active campaigns actually serving, with steady daily impressions.`,
+ mode: "achieve",
+ rationale: `${s.counts.activeLineItems} of ${s.counts.lineItems} line items are ACTIVE with ${money(s.activeDailyBudget)}/day of budget, but the account served 0 impressions in the last 7 days.`,
+ });
+ }
+
+ // Converting → push cost per conversion down.
+ if (d.conversions > 0 && d.spend > 0 && !overlaps(/cost per|cpa|per conversion/i)) {
+ const cpa = d.spend / d.conversions;
+ out.push({
+ kind: "xads-cpa",
+ title: "Lower X Ads cost per conversion",
+ statement: `Lower our X Ads cost per conversion below ${money(Math.floor(cpa * 0.8))} (currently ${money(Number(cpa.toFixed(2)))}).`,
+ mode: "achieve",
+ rationale: `Last 30 days: ${money(d.spend)} spend for ${d.conversions} conversions = ${money(Number(cpa.toFixed(2)))} per conversion.`,
+ });
+ }
+
+ // Spending and getting clicks but conversions never report → tracking gap.
+ if (d.spend > 0 && d.linkClicks > 0 && d.conversions === 0 && !overlaps(/conversion|tracking/i)) {
+ out.push({
+ kind: "xads-no-conversions",
+ title: "Get X Ads conversions reporting",
+ statement: `Get X Ads conversion tracking working end to end — the account should report at least one conversion from paid traffic.`,
+ mode: "achieve",
+ rationale: `${money(d.spend)} spend and ${d.linkClicks} link clicks in 30 days, but 0 conversions recorded — either tracking is broken or the funnel is.`,
+ });
+ }
+
+ return out.slice(0, 3);
+}
diff --git a/notfair-cmo/src/server/trusted-connectors.ts b/notfair/src/server/trusted-connectors.ts
similarity index 100%
rename from notfair-cmo/src/server/trusted-connectors.ts
rename to notfair/src/server/trusted-connectors.ts
diff --git a/notfair-cmo/src/server/version.ts b/notfair/src/server/version.ts
similarity index 97%
rename from notfair-cmo/src/server/version.ts
rename to notfair/src/server/version.ts
index c21e0064..31a30868 100644
--- a/notfair-cmo/src/server/version.ts
+++ b/notfair/src/server/version.ts
@@ -1,5 +1,5 @@
/**
- * Notfair-cmo version helpers.
+ * NotFair version helpers.
*
* Reads the current version from package.json (JSON import is statically
* resolved by Next.js so it works in dev, prod standalone, and tests).
@@ -8,7 +8,7 @@
*/
import pkg from "../../package.json";
-const PACKAGE_NAME = "notfair-cmo";
+const PACKAGE_NAME = "NotFair";
const NPM_REGISTRY_LATEST = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
const NPM_FETCH_TIMEOUT_MS = 5_000;
const LATEST_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
diff --git a/notfair/src/types/index.ts b/notfair/src/types/index.ts
new file mode 100644
index 00000000..118b90af
--- /dev/null
+++ b/notfair/src/types/index.ts
@@ -0,0 +1,58 @@
+// Shared types. Imported by both server (Next.js API + MCP) and client (React).
+
+export type Project = {
+ id: string;
+ slug: string;
+ display_name: string;
+ created_at: string;
+ archived_at: string | null;
+ /**
+ * Selected Google Ads customer ID for this project. Bearers from
+ * notfair.co/api/mcp/google_ads can grant access to multiple customer
+ * accounts; the onboarding flow asks the user to pick one and persists
+ * it here so the audit + later automation target the right account.
+ * Null until the user picks (or until /onboarding gets re-run).
+ */
+ google_ads_account_id: string | null;
+ /**
+ * Selected Meta Ads ad-account id (e.g. "act_123456"). Same pattern as
+ * google_ads_account_id: the notfair-metaads bearer may grant access
+ * to multiple ad accounts, and onboarding asks the user to pick the
+ * one this project should target. Null until picked.
+ */
+ meta_ads_account_id: string | null;
+ /**
+ * Selected Google Search Console property id (e.g. "sc-domain:example.com"
+ * or "https://example.com/"). Same idea as the ad-account fields: the
+ * notfair-googlesearchconsole bearer may cover multiple verified
+ * properties, and we persist the chosen one. Null until picked.
+ */
+ gsc_property_id: string | null;
+ /**
+ * Optional inputs the user provided at onboarding — starting points
+ * for agents exploring what the project is. Both are free-text.
+ */
+ website_url: string | null;
+ codebase_path: string | null;
+ /**
+ * Which harness adapter runs this project's agents. Picked at
+ * onboarding. "codex-local" is the recommended default; "claude-code-local"
+ * runs through Anthropic's Claude Code CLI instead.
+ */
+ harness_adapter: "claude-code-local" | "codex-local";
+};
+
+export type ToolErrorEnvelope = {
+ ok: false;
+ error_code: string;
+ message: string;
+ retryable: boolean;
+ user_message: string;
+};
+
+export type ToolSuccessEnvelope<T> = {
+ ok: true;
+ data: T;
+};
+
+export type ToolResult<T> = ToolSuccessEnvelope<T> | ToolErrorEnvelope;
diff --git a/notfair-cmo/tsconfig.json b/notfair/tsconfig.json
similarity index 100%
rename from notfair-cmo/tsconfig.json
rename to notfair/tsconfig.json